Export Oracle users to text file

This is achieved by using the sys.dba_users table, which means these queries must be done using an account with proper privileges. Beyond creation of users, the second SQL statement in the example below also generates account-locking commands for those users that are currently marked as locked. Finally, note the output file has the extension .sql, which suggests that it can be run directly from SQL*Plus as part of an automated script, if necessary.

set linesize 256;
spool c:oracleUsers.sql;

select 'create user '||username||' identified by values '||''''||password||''''||' 
default tablespace '||default_tablespace||' 
temporary tablespace '||temporary_tablespace||' 
quota unlimited on '||default_tablespace||' 
quota unlimited on '||temporary_tablespace||';' as "-- create_users"
from sys.dba_users 
where default_tablespace not in('SYSAUX','SYSTEM')
order by username;

select concat(concat('alter user ',du.username),' account lock;') as "--lock_users"
from sys.dba_users du
where du.account_status<>'OPEN'
and du.default_tablespace not in('SYSAUX','SYSTEM')
order by du.username;

spool off;

Manually deleting an Oracle 11g database

The following steps outlines how to manually delete a database within Oracle 11g, running in an Linux environment. I am currently running Oracle’s Enterprise Linux release 5 update 2.

  • Use SQL*Plus or your favorite SQL command line tool to log in to the target database; log in as sysdba
  • Issue the following commands to get the path to various files
    select name from v$datafile;
    select member from v$logfile;
    select name from v$controlfile;
    select name from v$tempfile;
    
  • Shut down the database within SQL*Plus, and then exit out of SQL*Plus
    shutdown immediate;
    quit;
    
  • Stop the listener service by issuing the following command in the terminal prompt:
    lsnrctl stop
  • Recall the file paths found earlier; use them as a check list as you delete each one of those files. Reminder: did you back up your database yet? When ready, go ahead delete your data files, redo log files, control files, and temp files.
  • Go to the $ORACLE_HOME/network/admin directory and delete the tnsnames.ora and listener.ora files
  • Go to the $ORACLE_HOME/dbs directory and delete the init[db_name].ora, orapw[db_name], and spfile[db_name].ora files
  • Go to the $ORACLE_HOME/admin/[db_name]/pfile directory and delete the init[db_name].ora file
  • Go to the $ORACLE_HOME/admin/[db_name]/adump directory and delete all files in that directory
  • Edit the file /etc/oratab by removing the line that starts with your database name

Get dates corresponding to calendar week days in Oracle

To do so, we will make use of Oracle’s next_day() function. The sample code is as follows:

select next_day(sysdate-14,'SUNDAY') as week_start, next_day(sysdate-7,'SATURDAY') as week_end from dual;

Assuming the current date is 20 Aug 2008, the above code will return 10 Aug 2008 and 16 Aug 2008, reflecting that the previous calendar week is between Sunday the 10th and Saturday the 16th. Thus, your query to get records inserted in the previous calendar week may look something like the following.

select record_id, record_stuff, entry_date
from bunch_of_records
where entry_date between 
	next_day(sysdate-14,'SUNDAY') and 
	next_day(sysdate-7,'SATURDAY');

Lorem ipsum automatic text generator in Javascript

First, create a Javascript file that we will call “lorem.js”. Copy/paste the following code into that file.


// Lorem ipsum generator
// @author C. Peter Chen of http://dev-notes.com
// @date 20080812
function loremIpsum(elem) {
	var loremIpsumWordBank = new Array("lorem","ipsum","dolor","sit","amet,","consectetur","adipisicing","elit,","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua.","enim","ad","minim","veniam,","quis","nostrud","exercitation","ullamco","laboris","nisi","ut","aliquip","ex","ea","commodo","consequat.","duis","aute","irure","dolor","in","reprehenderit","in","voluptate","velit","esse","cillum","dolore","eu","fugiat","nulla","pariatur.","excepteur","sint","occaecat","cupidatat","non","proident,","sunt","in","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum.","sed","ut","perspiciatis,","unde","omnis","iste","natus","error","sit","voluptatem","accusantium","doloremque","laudantium,","totam","rem","aperiam","eaque","ipsa,","quae","ab","illo","inventore","veritatis","et","quasi","architecto","beatae","vitae","dicta","sunt,","explicabo.","nemo","enim","ipsam","voluptatem,","quia","voluptas","sit,","aspernatur","aut","odit","aut","fugit,","sed","quia","consequuntur","magni","dolores","eos,","qui","ratione","voluptatem","sequi","nesciunt,","neque","porro","quisquam","est,","qui","dolorem","ipsum,","quia","dolor","sit,","amet,","consectetur,","adipisci","velit,","sed","quia","non","numquam","eius","modi","tempora","incidunt,","ut","labore","et","dolore","magnam","aliquam","quaerat","voluptatem.","ut","enim","ad","minima","veniam,","quis","nostrum","exercitationem","ullam","corporis","suscipit","laboriosam,","nisi","ut","aliquid","ex","ea","commodi","consequatur?","quis","autem","vel","eum","iure","reprehenderit,","qui","in","ea","voluptate","velit","esse,","quam","nihil","molestiae","consequatur,","vel","illum,","qui","dolorem","eum","fugiat,","quo","voluptas","nulla","pariatur?","at","vero","eos","et","accusamus","et","iusto","odio","dignissimos","ducimus,","qui","blanditiis","praesentium","voluptatum","deleniti","atque","corrupti,","quos","dolores","et","quas","molestias","excepturi","sint,","obcaecati","cupiditate","non","provident,","similique","sunt","in","culpa,","qui","officia","deserunt","mollitia","animi,","id","est","laborum","et","dolorum","fuga.","harum","quidem","rerum","facilis","est","et","expedita","distinctio.","Nam","libero","tempore,","cum","soluta","nobis","est","eligendi","optio,","cumque","nihil","impedit,","quo","minus","id,","quod","maxime","placeat,","facere","possimus,","omnis","voluptas","assumenda","est,","omnis","dolor","repellendus.","temporibus","autem","quibusdam","aut","officiis","debitis","aut","rerum","necessitatibus","saepe","eveniet,","ut","et","voluptates","repudiandae","sint","molestiae","non","recusandae.","itaque","earum","rerum","hic","tenetur","a","sapiente","delectus,","aut","reiciendis","voluptatibus","maiores","alias","consequatur","aut","perferendis","doloribus","asperiores","repellat");
	var minWordCount = 15;
	var maxWordCount = 100;

	var randy = Math.floor(Math.random()*(maxWordCount - minWordCount)) + minWordCount;
	var ret = "";
	for(i = 0; i < randy; i++) {
		var newTxt = loremIpsumWordBank[Math.floor(Math.random() * (loremIpsumWordBank.length - 1))];
		if (ret.substring(ret.length-1,ret.length) == "." || ret.substring(ret.length-1,ret.length) == "?") {
			newTxt = newTxt.substring(0,1).toUpperCase() + newTxt.substring(1, newTxt.length);
		}
		ret += " " + newTxt;
	}
	document.getElementById(elem).innerHTML = document.getElementById(elem).innerHTML + "<p>Lorem ipsum " + ret.substring(0,ret.length-1) + ".</p>";
}

Next, in your HTML page, include the Javascript file as follows.


<script type="text/javascript" src="lorem.js"></script>

To populate some random text, call the Javascript function “loremIpsum(‘elementName’)”, where “elementName” is the ID of an element you wish to populate the text to. The following code illustrate how we can use this function to populate automatic lorem ipsum text into a DIV.


<html>
<head>
<script type="text/javascript" src="lorem.js"></script>
</head>
<body>

<p><b>Lorem Ipsum generator</b><br />
Written by C. Peter Chen of <a href="http://dev-notes.com">dev-notes.com</a></p>

<div id="div1">
</div>

<input type="button" onclick="loremIpsum('div1');" value="Add Text">

</body>
</html>

Finally, the following section is a live demo of how the code should behave.

Sending emails using VBScript

To do so, follow the sample code shown below. To use the code as-is, just alter the configuration parameters by providing the from address, to address, subject, body, and SMTP server information. Optionally, you may also provide a path to a file that you want to attach to the email. Usually SMTP port number is 25; if you are unsure, leave this parameter untouched and it will probably work at the default value of 25.

option explicit

dim fromAddress, toAddress, subj, body, smtp, attach, smtpPort

'''''''''''''''''
' Configuration '
'''''''''''''''''

' Required parameters
fromAddress = "my@email.address"      ' The from email address
toAddress = "recepient@email.address" ' The to email address
subj = "Email Subject"                ' The subject of the email
body = "Put a message here!"          ' The body message of the email
smtp = "mail.server.com"              ' Name of the SMTP server you wish to use

' Optional parameters
attach = "c:filename.txt"            ' Optional file you may wish to attach to the email
smtpPort = 25                         ' SMTP port used by your server, usually 25; if not provided, the script will default to 25

'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''


if fromAddress = "" then
	msgbox("Error: From email address not defined")
elseif toAddress = "" then
	msgbox("Error: To email address not defined")
elseif subj = "" then
	msgbox("Error: Subject not defined")
elseif body = "" then
	msgbox("Error: Body not defined")
elseif smtp = "" then
	msgbox("Error: SMTP server not defined")
else
	dim objMessage
	Set objMessage = CreateObject("CDO.Message")
	objMessage.Subject = subj
	objMessage.From = fromAddress
	objMessage.To = toAddress
	objMessage.TextBody = body
	if attach <> "" then
		objMessage.AddAttachment attach
	end if
	
	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
	if smtpPort <> "" then
		objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort
	else
		objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
	end if
	objMessage.Configuration.Fields.Update
	
	objMessage.Send
	
	msgbox("Email sent successfully")
end if

Installing fonts on a MacOS X desktop

Fonts for the Mac usually come in .otf and .ttf files, which are OpenType and TrueType files, respectively. After you download a new font, make sure you have at least one of these two files.

Next, you should decide who will get to use the new font, particularly if you have more than one user on the computer. The answer to that question will determine whether you should copy the .otf/.ttf files to one or the other of the two folder locations below. Wether you have system administrator access also plays a role.

  • /Users/[username]/Library/Fonts/
  • /Library/Fonts/

If you only want one particular user to have access to the new font, or if you only have access to install fonts for yourself, place the font files in the first folder. If you have administrator access and would like to install his font for everyone who uses the computer, put the files in the second folder.

Creating a PRE text area with scroll bar

I actually had this issue on Dev-Notes.com for a little while. To get around it, I changed the style class for code so it looks like the following:

pre.code {
	overflow: auto; 
	overflow-y: visible;
}

With this, when encountered with a long line of code, a horizontal scroll bar will appear to allow the user to scroll left and right instead of breaking the width and sometimes positioning of the parent DIV. Below is a demo of this CSS style.

BufferedWriter out = new BufferedWriter(new FileWriter("/folder/anotherFolder/thirdFolder/anotherFolderToMakeThisLineLong/file.txt"));

Get current mouse cursor position with Javascript

The Javascript code below provides a sample of how the user’s mouse cursor position, displayed as X- and Y-coordinates in relation to the top left corner of the page. In this example, I put the X- and Y-coordinate values in an input box, but you can tweak that to fit your needs.


<html>

<script type="text/javascript">
window.onload = init;
function init() {
	if (window.Event) {
	document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = getCursorXY;
}

function getCursorXY(e) {
	document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
</script>

<body>

<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor

</body>
</html>

Below is a demo of the code listed above:

X-position of the mouse cursor

Y-position of the mouse cursor

Custom split() function in Oracle

The following function will take in a list, let’s say “AAA,BBB”, split them up to “AAA” and “BBB”, and allow the user to specify which one to return.

create or replace function split(input_list varchar2, ret_this_one number, delimiter varchar2)
return varchar2
is
	v_list varchar2(32767) := delimiter || input_list;
	start_position number;
	end_position number;
begin
	start_position := instr(v_list, delimiter, 1, ret_this_one);
	if start_position > 0 then
		end_position := instr( v_list, delimiter, 1, ret_this_one + 1);
		if end_position = 0 then
			end_position := length(v_list) + 1; 
		end if;
		return(substr(v_list, start_position + 1, end_position - start_position - 1));
	else
		return NULL;
	end if;
end split;
/
show errors;

In the previous listed example, we would run this function as follows.

select split('AAA,BBB',1,','); -- Returns AAA
select split('AAA,BBB',2,','); -- Returns BBB

Please note that the first index is 1, not 0.

This function is inspired and based on work done by Simon Baird and Francois Degrelle. Thanks Simon and Francois!

Drop columns in an Oracle table

The following example demonstrates how it could be done.

alter table schema1.my_table drop column unused_field;

There is also an alternative syntax that could be used to drop multiple fields at once.

alter table schema1.my_table drop (unused_field); -- Dropping one field only
alter table schema1.my_table drop (unused_field1, unused_field2); -- Dropping two fields

In the second example, if you need to drop more than two fields, just keep adding them within the parenthesis, separated by commas.