Friday, January 23, 2009

Saturday, January 10, 2009

How to mount an iso in linux

How to mount an iso in linux

1. make some folder
mkdir /mnt/iso1


2. as root...mount it
mount -o loop abc.iso /mnt/iso1

Friday, January 09, 2009

A8V-VM SE sound on linux

How to configure the onaboard ALC861 sound on the A8V-VM SE motherboard in opensuse:


in opensuse 11.1 set 'model' option to 3stack in yast2

Tuesday, December 16, 2008

to extract any rpm:

to extract any rpm:

rpm2cpio some.rpm | cpio -id

Sunday, December 14, 2008

replace notepad with notepad2

notepad2

replacenotepad2.bat
copy notepad2.exe C:\WINDOWS\notepad.exe
copy notepad2.exe C:\WINDOWS\system32\notepad.exe
copy notepad2.exe C:\WINDOWS\ServicePackFiles\i386\notepad.exe
copy notepad2.exe C:\WINDOWS\system32\dllcache\notepad.exe

Windows XP - how to turn off compressed folders

regsvr32 /u zipfldr.dll

Friday, December 05, 2008

mount a samba fileshare in linux

how to mount a linux samba fileshare back into another linux box

edit /etc/fstab, add the line:
//host/shared/ /home/shar/ cifs username=u,password=p,_netdev,uid=root,gid=users 0 0

replace host with [host]
/shared/ with the folder shared
/home/shar/ with where you want to mount it
u with the samba username
p with the samba password

(when complete, 'mount -a' should apply the fstab changes).

Thursday, November 27, 2008

MySQL: Load CSV into db

DROP TABLE IF EXISTS `digitalsignage`.`tmp_directory`;
CREATE TABLE `digitalsignage`.`tmp_directory` (
`f1` varchar(255) NULL,
`f2` varchar(255) NULL,
`f3` varchar(255) NULL,
`f4` varchar(255) NULL,
`f5` varchar(255) NULL,
`f6` varchar(255) NULL,
`f7` varchar(255) NULL,
`f8` varchar(255) NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

LOAD DATA INFILE 'Book2.csv'
INTO TABLE `tmp_table`
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Thursday, November 20, 2008

pgsql rename table

ALTER TABLE products RENAME TO items;

Wednesday, November 19, 2008

linux disk usage

du -B MB --max-depth=1 |sort -nr

Wednesday, November 12, 2008

linux sort

sort a tab delimited file: on column 2 (where you have column 1,2,3...)

sort -t$'\t' +1 -2 export_1612.txt>sorted.txt

Friday, November 07, 2008

BASH - Time Your Bash Script

#!/bin/bash
time_start=`date +%s`
sleep 63
time_end=`date +%s`
time_elapsed=$((time_end - time_start))
echo $(( time_elapsed / 60 ))m $(( time_elapsed % 60 ))s

Tuesday, November 04, 2008

VMWare on supporting 64 bit guest OSes

I wanted to play with a 64 bit OS once, so I installed VMWare to experiment with it. My box had a 64 bit AMD CPU, and was running a 32 bit linux OS on it. I didn't think I would be able to install a 64 bit VMWare guest OS on it, but it worked fine.

Later I tried this all again but on an intel 32 bit box, and it didn't work.

I just found a link that describes under exactly what conditions 64 bit guest OSes will and won't work:[kb.vmware.com].

Tuesday, October 28, 2008

PgSQL: random notes


postgres, allow localhost with no password
/var/lib/pgsql/pg_hba.conf
on line: with host all all 127.0.0.1/32 md5
change md5 to trust

postgres, set new password
[user@server ~]psql -U postgres -h localhost -d postgres
ALTER USER postgres WITH PASSWORD 'newpass';

#where postgres is the dbname
pgsql -U postgres -d dbname

# (at pgsql prompt) this will give the schema of the table
dbname=# \d tablename

# (at pgsql prompt) view autoincrement expression for field
dbname=# \d tablename

# (at pgsql prompt) how to view next autoincrement number
dbname=# select nextval('tablename_fieldname_seq');

# (at pgsql prompt) how to set autoincrement number
dbname=# select setval('tablename_fieldname_seq', 50);






source(s): http://www.source.com

Thursday, October 16, 2008

Linux - New set of Notes

I just installed Fedora, and I'll be making some notes about setting up and configuring Fedora 8 in this post.

this is a system startup script kind of like the old autoexec.bat
/etc/rc.local

this is a bash startup script for that user, also an .sh
/home/username/.bash_profile

defaults for new users
/etc/skel/.bash_profile

CTRL-ALT-D
show desktop

FC8:
System > Preferences > Personal > Keyboard Shortcuts
CTRL-ALT <arrow> (l,r,u,d) to navigate between desktops





Monday, September 22, 2008

Skype: Belkin Skype Phone

One of the nice things about skype is that you can download it for Mac, Linux or Windows, so you aren't particularly tied down.

Skype is a DIY voip service. They offer a skype out unlimited subscription for canada and the usa (unlimited outgoing calling from your computer to landlines and cellphones) for $30. If you choose you can also get a phone number in whatever USA area code you want for another $30. I am sad that there still are no numbers available in canada. Because skype online numbers are available in over 20 countries at the time of this writing, i wouldn't be surprised if canada has extra red tape, which is preventing this.

So for the cost of $5 computer speakers, $5 computer microphone, an internet connection and $60/year ($5/month) you can scrap your $30/month landline. Don't forget to read the fine print, skype wants you to know that you can't use it for 911 calling, because the 911 operators have no idea where you are calling from. You could be online in europe and still take skype calls at your 801 usa area code through your internet connection. So... it is important to keep an old cell phone around. Even deactivated/non-sim card cell phones are required by law to be able to call 911.

My wife doesn't like using the computer for calling much, plus we don't want to leave it on 24/7 to take calls so we were thinking of getting the belkin skype desktop phone. This phone is a no computer required phone. It seems a little pricey considering it is just a phone... but understood what the skype phone really is, its pretty much an $80 computer with built-in microphone and speakers.

There are a lot of items for sale which replace your microphone and speakers... some usb phones, some cordless phones (comp req'd), other cordless phones (comp not req'd), and even wifi phones. Wifi is great... if you get a wifi hotspot anywhere you can make or take calls. I have heard the battery life on them isn't great yet... because it just like a minilaptop- but you can't turn the wifi network card off for power saving mode!

Thursday, September 11, 2008

C++ : How to Launch a Background in Windows Program

In linux it is easy to launch a background process at the command line with ampersand.

./app_to_launch &

In windows there is no easy command line suffix which will launch your program in the background. However it is relatively easy to code one up. If you install Visual C++ Express 2005, and the Microsoft Platform SDK (see configuration below) just compile this application as BKLAUNCH.exe and you will soon be able launch apps in the background from batch files.

I created an empty win32 project named BKLAUNCH, no precompiled header, and compiled the following code.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <windows.h>
#include <shellapi.h>
#include <tchar.h>

int _tmain(int argc, _TCHAR* argv[])
{
if (argc!=2)
{
printf("Usage:\n");
printf(" BKLAUNCH.EXE [apptolaunch]\n");
printf(" BKLAUNCH.EXE notepad.exe\n");
exit(0);
}
ShellExecute(NULL, TEXT("open"), argv[1], NULL, NULL, SW_SHOW);
return 0;
}


Once BKLAUNCH has successfully compiled, place it in a folder that is in the PATH. Now, go to Start > Run > cmd.exe [OK], and enter the following:
BKLAUNCH notepad.exe

You will notice notepad.exe is launched in the background, perfect for batch files.

Troubleshooting
If you are like me and use default settings, look under
Project > Project Properties > Linker > Input > Additional Dependencies
it will will have only kernel32.lib. When you compile there will be linker errors.

Because of the #include <windows.h> and #include <shellapi.h>
you need to add the following to your Additional Dependencies
kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib in order to resolve the linker errors.

Microsoft Platform SDK Config
In order to use the MS Platform SDK in Visual C++ Express 2005, you have make the platform SDK visible to the compiler.

Go to
Tools > Options > Projects and Solutions > VC++ Directories > Platform=Win32 > Show Directories for=include files
Add to the list,
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Include
(or wherever you installed the MS Platform SDK\Include)

Now, go to
Tools > Options > Projects and Solutions > VC++ Directories > Platform=Win32 > Show Directories for=library files
Add to the list,
C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Lib
(or wherever you installed the MS Platform SDK\Lib)

Tuesday, September 09, 2008

BASH: bad interpreter: No such file or directory

-bash: ./execute.sh: /usr/bash^M: bad interpreter: No such file or directory


Dos text files use \r\n (0xD 0xA) as their end of line characters. Unix text files use \n (0xA) as their end of line character. What happened here is I had a file in dos text format, and tried to execute it in bash. the ^M you see above is saying "It wasn't expecting the \r character".

Solution:

use dos2unix
[user@linux1 ~] dos2unix execute.sh
dos2unix: converting files execute.sh to UNIX format...

Monday, September 08, 2008

C++: Simple Makefile Example

I have always been looking for a nice makefile template, that will allow me to have separate include, src, and obj directories. Today I stumbled on addprefix a directive that allows me to add only the filename of each src file I add to my project.

Assuming you have the files
./Makefile
./include/file1.h
./include/file2.h
./include/file3.h
./src/file1.cpp
./src/file2.cpp
./src/file3.cpp
and all obj files go in ./obj/
and your target executable is ./execfile


Makefile
CC        =g++
CFLAGS =-c -Wall
LDFLAGS =
INCLUDE =-I./include
OBJDIR =obj/
OBJLIST = file1.o file2.o file3.o
OBJECTS = $(addprefix $(OBJDIR), $(OBJLIST) )

all:execfile

execfile: $(OBJECTS)
[TAB]$(CC) $(LDFLAGS) $(OBJECTS) -o $@

$(OBJECTS): obj/%.o: src/%.cpp
[TAB]$(CC) $(CFLAGS) $? -o $@ $(INCLUDE)

clean:
[TAB]rm -rf obj/*.o
obviously, replace [TAB] with the actual tab character(\t).

Thursday, June 19, 2008

PHP: Web Bug Script

Somebody wanted hits on their website... so they linked web bug[wikipedia] web bug tracker article to their web bug script[pineapple.vg].

The problem with their web bug script is it requires the php-gd2 extension, it results in 95 byte output, and uses php gd code allocating memory... deallocating memory when its not necessary. This script when scaled up 100,000x has too large a footprint. It can be optimized into 3 lines as follows (with a 43 byte output):

<?php
//saves ip address and timestamp
file_put_contents("ip_list.txt", date("Y-m-d H:i:s") . ": ". $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND);

header("content-type: image/gif");

//43byte 1x1 transparent pixel gif
echo base64_decode("R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
?>

Thursday, January 31, 2008

PHP: Calculate PHP Page Load Time

//put this at the start of your php script.
$s_mt = explode(" ",microtime());

//put this at the end of your php script
$e_mt = explode(" ",microtime());
$s = (($e_mt[1] + $e_mt[0]) - ($s_mt[1] + $s_mt[0]));
echo "Page created in ".$s." seconds";

Monday, January 21, 2008

Javascript: Error, Internet Explorer cannot open the internet site

I have built a website that used a lot of javascript code to generate a floating overlay div, appends it to the body, and got this crazy Internet Explorer error in IE 6 AND IE 7.

Internet Explorer cannot open the internet site http://blah.blah.com/

Operation Aborted.


At which point I got redirected to a "The page cannot be displayed" IE error.

I trimmed everything out of the webpage which had nothing to do with the error and I was left with a tiny page which still produced the error:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
<
head>
<
meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<
title>pagetitle</title>
<
script language="JavaScript" type="text/JavaScript">
<!--
function creatediv()
{
try
{
document.body.appendChild( document.createElement("<div>") );//IE
}
catch (e)
{
document.body.appendChild( document.createElement("div") );
}
}
//-->
<
/script>
<
/head>
<
body>

<
div>
<
script language="JavaScript" type="text/JavaScript">
<!--
creatediv();
//-->
<
/script>
<
/div>

<
/body>
<
/html>


If you copy and paste the above, and then save it as html, and open the page in IE you will see the error. Then I googled around and played with my page, and realized that if I moved the creatediv() function outside the >div< (or any other html container), that I would no longer get this error. Basically, the problem is that IE 6 and 7 do not create the document.body part of the DOM until after the page has finished loading. In my javascript code I call document.body.appendChild and IE has a hissy fit. Something about calling the javascript from within a div or table makes also contributes to this error.

Workarounds and Solutions:
- moving my javascript function out of the div (see below)
- using <body onload='creatediv()' > instead of calling it within the page
- if using an event handler class like in http://www.dustindiaz.com/rock-solid-addevent/
use: addEvent(window,'load',creatediv);

Code that doesn't produce the error:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
<
head>
<
meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<
title>pagetitle</title>
<
script language="JavaScript" type="text/JavaScript">
<!--
function creatediv()
{
try
{
document.body.appendChild( document.createElement("<div>") );//IE
}
catch (e)
{
document.body.appendChild( document.createElement("div") );
}
}
//-->
<
/script>
<
/head>
<
body>

<
div>
<
/div>

<
script language="JavaScript" type="text/JavaScript">
<!--
creatediv();
//-->
<
/script>


<
/body>
<
/html>


source(s): http://tinyurl.com/hvfsw

Sunday, January 20, 2008

FLASH: Mp3 player swf plays chipmunk sounds

Most mp3s are encoded at 128 and 192 kbps, but I was working on a project that used speech recordings, and speech is usually encoded at a lower bitrate than 128. I found every time I played the recording in a flash based mp3 player it played it too fast, making it sound like alvin and the chipmunks.

I went through and made a whole bunch of mp3s at different bitrates using the lame 3.96 encoder to see which were supported and which bitrates were not.
fixed bitrates:
:( 16 kbps
:( 24 kbps
:( 32 kbps
:( 40 kbps
:) 48 kbps
:( 56 kbps
:( 64 kbps
:( 80 kbps
:) 96 kbps
:) 112 kbps
:) 128 kbps
:) 160 kbps
:) 192 kbps
:) 224 kbps
:) 320 kbps

variable bitrates (with lame; 0 is high quality, 9 is low):
:) V0-6
:( V7-9


So the basic synopsis is mp3s encoded as 48kbps work and anything greater or equal to 96kbps also works. Everything else is not supported (is support, but sounds like chipmunks).
[EDITED]
see
http://www.summitsolutions.co.uk/blog/how-to-correct-the-chipmunk-effect-in-the-podpress-flash-player
for another possible explanation of the chipmunk sounds.

Friday, December 14, 2007

C++: Borland C++ Builder Linker Errors

I kept getting these linker errors for a wrapper class I was writing.

[Linker Error] Unresolved external 'Curlit::errorBuffer' referenced from C:\PROJECTS\LIBCURL\CURLIT.OBJ
[Linker Error] Unresolved external 'Curlit::buffer' referenced from C:\PROJECTS\LIBCURL\CURLIT.OBJ

Now I thought I was just getting random linker errors. But only after I played with things a bit did I realize it was because errorBuffer and buffer were declared static.

class Curlit
{
protected:
static char errorBuffer[CURL_ERROR_SIZE];
static string buffer;
static int writer(char *data, size_t size, size_t nmemb, string *buffer);
static string easycurl(string &url, bool post, string &pstring);

public:
Curlit();
~
Curlit();
static string post(string &url, std::map<string, string> &querystr);
static string get(string &url);
static string escape(string &param);
};

Once I realized it was because they were static, I was able to put the right words into google. I soon learned that static class members, must be redeclared outside the class definition as shown below. Once I added two lines of code, the linker errors went away.

class Curlit
{
protected:
static char errorBuffer[CURL_ERROR_SIZE];
static string buffer;
static int writer(char *data, size_t size, size_t nmemb, string *buffer);
static string easycurl(string &url, bool post, string &pstring);

public:
Curlit();
~
Curlit();
static string post(string &url, std::map<string, string> &querystr);
static string get(string &url);
static string escape(string &param);
};

char Curlit::errorBuffer[CURL_ERROR_SIZE];
string Curlit::buffer;

source(s): programmersheaven.com/mb/CandCPP/67811/67811/ReadMessage.aspx

Monday, December 10, 2007

Scientists Discover How to Make Robots Bounce on Water

Scientists have discovered how water striders are able to not just walk but also bounce on water

Just check out this picture, its awesome.



source(s): http://www.environmentalgraffiti.com/?p=592

Wednesday, December 05, 2007

JS: Are you sure you want to navigate away from this page?

I've been using blogger for a while, and not because I don't know how to build my own blog or website. I've build dozens of them, but I use blogger because its easy, and I don't have to worry about the details of the code. Heck I could build a site like blogger if I wanted, it would just take time. Occasionally on blogger I bump into a feature that I don't know how to replicate, and this is one of them.

I've always wondered how blogger uses javascript to ask "Are you sure you want to navigate away from this page? You have unsaved changes."

I was browsing around in some MSDN DOM documentation and found a window event called onbeforeunload. I've actually explored this issue once before and only got as far as onunload. Having the right keyword to put into google makes a real difference.

Add this javascript code to a page and then try to close the page.
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "Are you sure you want to leave this page?";
}


source(s): http://msdn2.microsoft.com/en-us/library/ms536907.aspx, http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

Monday, October 15, 2007

10 great javascript functions

I haven't found time to go back and discuss these functions, but here they are.

//this function is case insensitive
String.prototype.beginsWith = function(t) {
return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
}
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}



function isInt (str)
{
var i = parseInt (str);
if (isNaN (i))
return false;
if (i.toString() != str)
return false;
return true;
}



function alert_obj(obj)
{
var str2='';
for(s in obj)
str2+= "obj["+s+"]"+obj[s]+"\n";
alert(str2);
}



function xml_text_node(elem,nam)
{
try{
return elem.getElementsByTagName(nam)[0].firstChild.nodeValue;
}
catch(e){
return "";
}
}


function count_children(myElement)
{
if (!myElement)
return 0;
var count=0;
var child = myElement.firstChild;
while (child!=null)
{
count++;
child = child.nextSibling;
}
return count;
}




function removeChildren(list)
{
if (list==null) return;
var child = list.firstChild;
while(child!=null)
{
list.removeChild(child);
child = list.firstChild;
}
}


function DOMelement(txt)
{
var o = new Object();
o.elementname = txt;
o.attributes = new Object();
o.innerHTML = '';
o.innerText = '';
o.createElement = function()
{
var attribute_str = '';
for(attrib_name in o.attributes)
attribute_str+= attrib_name+"='"+escape(o.attributes[attrib_name])+"'";

var element;
try
{//IE
element = document.createElement("<"+o.elementname+" "+attribute_str);
}
catch (e)
{
element = document.createElement( o.elementname );
for(attrib_name in o.attributes)
element.setAttribute( attrib_name , o.attributes[attrib_name] );
}
if (o.innerHTML.length>0)
element.innerHTML = o.innerHTML;
else if (o.innerText.length>0)
element.appendChild( document.createTextNode(o.innerText) );
return element;
}

o.setAttribute = function(attribute,attribute_value)
{
o.attributes[attribute] = attribute_value;
}
return o;
}


usage:
var e = DOMelement('div');
e.setAttribute('asdfs','asdfs');
e.setAttribute('asdfs','asdfs');
e.setAttribute('asdfs','asdfs');
var element = e.createElement();

This is the ultimate, because it works in IE as well as compliant browsers.

Monday, August 13, 2007

PHP: Force a page to https

Here is some php code which forces a page to redirect to the same page for https at port 443.

<?php
function die_force_page_to_https()
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='off')
{
$u='https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
$t='';
$t.='<html>';
$t.= '<head>';
$t.= '<meta http-equiv="Refresh" content="0;url='.$u.'>';
$t.= '</meta>';
$t.= '</head>';
$t.= '<body>';
$t.= '</body>';
$t.='</html>';
die($t);
}
}
?>

Monday, August 06, 2007

APACHE: Problem with mod_rewrite setup

One way to see if mod_rewrite is installed is to create a file called info.php with the following contents

 <?php echo phpinfo(); ?> 


Put the file in your server root and view it at http://localhost/info.php. Go to the apache section and look at Loaded Modules. If you see mod_rewrite listed there, you can start using the mod_rewrite commands. If not, you have to play with the apache config file: http.conf, add the following (a website told me to do this):

LoadModule rewrite_module modules/mod_rewrite.so
AddModule mod_rewrite.c


... and make sure the mod_rewrite.so file is in the right place. Then restart your web server. (suse linux: "rcapache2 restart", or windows: Control Panel->Administrative Tools->Services, right click on Apache and select restart)

PROBLEM:
Apache fails to restart.

In windows you can discover the reason using the Event Viewer (Control Panel->Administrative Tools->Services->Event Viewer). It gives the error for Apache:
Invalid command 'AddModule', perhaps mis-spelled or defined by a module not included in the server configuration

REASON:
AddModule for mod_rewrite is for apache 1.2 to 1.3x, but not apache2. I was running Apache2, so instead, the following worked for me in the apache config file:

LoadModule rewrite_module modules/mod_rewrite.so


Now restart apache, and check your http://localhost/info.php file and Voila! mod_rewrite is there, listed as a Loaded Module.

Now as for how to actually use mod_rewrite there are a lot of examples out there,
thats what google is for, right?

http://hypermail.linklord.com/new-httpd.old/2001/Jul/0863.html

Friday, August 03, 2007

CSS: Irritating IE FORM tags act like BR tag

One of the irritating things about IE is that the form start tag is automatically treated like a line-break tag.

Add this to your stylesheet to solve the problem:
form {margin: 0px 0px 0px 0px; }


source(s): http://weblogs.macromedia.com/cantrell/archives/2003/05/
git_rid_of_anno.cfm

Wednesday, August 01, 2007

C++: Set Registry Key Values

This piece of example code writes a key to the windows registry.

#include <windows.h>

int SetRegValue(char *key_name,char *key_word,char *b,int dwType,int s)
{
int j=0;

DWORD lpdwDisposition;
HKEY hKey;

j=RegCreateKeyEx(
HKEY_CURRENT_USER,
key_name,
0, /* reserved */
NULL, /* address of class string */
REG_OPTION_NON_VOLATILE, /* special options flag */
KEY_WRITE, /* desired security access */
NULL, /* address of key security structure */
&
hKey, /* address of buffer for opened handle */
&
lpdwDisposition /* address of disposition value buffer */
);

if (j==ERROR_SUCCESS)
{
RegSetValueEx(hKey, key_word, 0, dwType, (unsigned char *)b, s);
RegCloseKey(hKey);
}
return(j);
}

int main(int argc, char* argv[])
{
char val[100]="myusername";
SetRegValue("Software\\MySoft\\Settings","Username", val, REG_SZ, 100);
return 0;
}



source(s): http://msdn2.microsoft.com/en-us/library/ms724923.aspx
http://msdn2.microsoft.com/en-us/library/ms724875.aspx

Wednesday, July 25, 2007

C++: Check a valid date

C++ has no checkdate, like php does. so i wrote this to filter out bad dates and feb29ths.

bool isValidDate(int m, int d, int y)
{
//
checks Gregorian date
if
(! (1582<= y ) )
return false;
if (! (1<= m && m<=12) )
return false;
if (! (1<= d && d<=31) )
return false;
if ( (d==31) && (m==2 || m==4 || m==6 || m==9 || m==11) )
return false;
if ( (d==30) && (m==2) )
return false;
if ( (m==2) && (d==29) && (y%4!=0) )
return false;
if ( (m==2) && (d==29) && (y%400==0) )
return true;
if ( (m==2) && (d==29) && (y%100==0) )
return false;
if ( (m==2) && (d==29) && (y%4==0) )
return true;

return true;
}


source(s): http://en.wikipedia.org/wiki/Leap_year

Monday, July 23, 2007

C++: Hide an Application from the Taskbar

(This solution is specific to Borland C++ Builder)

Use this code as your project source to prevent the window from showing up in your windows taskbar.

WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(TForm1), &Form1);
SetWindowLong(Application->Handle,
GWL_EXSTYLE,
GetWindowLong(Application->Handle, GWL_EXSTYLE)
|
WS_EX_TOOLWINDOW) ;
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}


source(s): http://delphi.about.com/od/adptips1999/qt/hidefromtaskbar.htm

Friday, July 20, 2007

C++: Redirect command-line output

I've always wondered how to capture output from a command line program in windows, and the record it into a file.

while you can always just the greater-than-sign to output text into a file at the windows command prompt, sometimes it just isn't good enough.
"echo abc>hi.txt"

I ran into this once with mysqldump.exe.

Well I finally found the code that works. In this example I call 'dir'.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
char psBuffer[128];
FILE *iopipe;

if( (iopipe = _popen( "dir", "rt" )) == NULL )
exit( 1 );

while( !feof( iopipe ) )
{
if( fgets( psBuffer, 128, iopipe ) != NULL )
printf( psBuffer );
}

printf( "\nProcess returned %d\n", _pclose( iopipe ) );

return 0;
}





source(s): www.daniweb.com/forums/thread5755.html

Thursday, July 05, 2007

SVN: Command-line SVN

Just a couple examples.

Use svn checkout help or svn update help for more details.
//you do the initial checkout like this:
svn checkout [svn path] [destination path]
//svn path: svn://192.168.0.93/srv/svn/src/trunk/proj
//dest path: /srv/www/htdocs/dest_path
//user note: it may prompt for a username and password

//this will update to the most recent revision
svn update [destination path]

//for more details call
svn checkout help
// or
svn update help

Thursday, May 10, 2007

Recruiting: High-tech companies go virtual

I am about to graduate from BYU with a bachelor's degree in CS, and have began my job search. I signed up for an erecruiting account where my school has an account with Experience Inc. The system is set up so that interested companies can view my resume and send me job opportunities while I finish up my last segment of schooling.

I received this email this morning.

Dear Students:

Representatives from Hewlett Packard have released the following opportunity.

HP will be interviewing in the virtual world for real-world jobs! This is a first for HP and encourage BYU students to try it out, especially if they are already Second Life players. Those interested can go to the following web address:

http://www.networkinworld.jobs/hp_profile.aspx

Good Luck!
Career Placement Services


Second life is virtual world where "Residents can explore, meet other Residents, socialize, participate in individual and group activities, create and trade items (virtual property) and services from one another." [wikipedia.org]

Most companies have an multiple-contact interview process. Its kind of like tryouts on a high school sports team with multiple cuts. After each interview you sit around waiting to know "Did I make the cut?". For technical positions the first interview is usually with a non-technical person who weeds out their stack of candidates. If you made the cut, you reach the second interview with a more technical person, sometimes as a phone interview depending on your location. After 4-6 contacts they have weeded their candidate pool down to the point they often invite you to their facilities and make you an offer.



Human Resource managers who are involved in the hiring process try to make the best decisions they can based on how you will fit into the company culture, your goals, your passions, and your technical abilities. But how they are trying to measure this using Second Life I just don't know. I mean they may as well have an HP LiveChat operator waiting to assist you and you can sign up for an interview.

For my job I've had to interview before, and I don't understand how an interviewer could adequately determine how someone could work in the real world at HP with a virtual interview. In an interview you are trying to make use of every piece of information available to you to learn about the individual and make the best decision you can.



I guess it makes sense though, if you're being interviewed for a satellite job or a job like HP Second Life Advertising, where you'll never talk to you boss face to face in real life anyway.

While I do respect HP as a company, do they really think they make good decision using Second Life? Or are they just using this as a marketing tactic to lure people into their potential candidate pool who would otherwise not be included? Are they just doing this for the first interview? Or are they trying to use Second Life for every interview?

Thursday, April 19, 2007

Windows: Nightly Defrag

It isn't that hard to set up a nightly defragmentation routine.

In Windows XP, go to Start Menu > Settings > Control Panel > Scheduled Tasks go through the wizard, selecting C:\Windows\System32\defrag.exe to run. At the end, in the advanced options make it run
C:\Windows\System32\defrag.exe c: -f
or D: or whatever your drive name is.

Microsoft provides documentation on the command line defrag:
defrag volume [-a] [-f][-v] [-?]
volume: The drive letter or a mount point of the volume to be defragmented
-a: Analyze only
-f: Forces defragmentation of the volume regardless of whether it needs to be defragmented or even if free space is low
-v: Verbose output
-?: Display the help text


source(s): http://support.microsoft.com/kb/283080

Wednesday, April 18, 2007

PHP: PHP 5 Deployment Error

I've written some code for PHP5, and deployed it to a production server and I saw an error that I'd never seen before.

PHP 5 Code:
<?php

class form
{
    public $name;
    public $fields;
}
?>


Error:
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in C:\x\y\page.php on line z


The problem is that PHP 4 has a different syntax for classes. The code above is PHP 5 valid, but not PHP 4. A valid version of its PHP 4 equivalent is this:

PHP 4 Code:
<?php

class form
{
    var $name;
    var $fields;
}
?>

Tuesday, April 10, 2007

WINDOWS: Skip 'Open With Web Service' Window

When you try to open a file and you haven't set a handler for a file extension, a window pops up in XP saying:

"Windows cannot open this file:"
To open this file, Windows needs to know what program created it. Windows can go online to look it up automatically, or you can manually select from a list of programs on your computer.
What do you want to do?
- Use the Web service to find the appropriate program
- Select the program from a list


This is really irritating because no one would ever want to use 'the Web Service' anyway. BTW Microsoft, look up Web Service at wikipedia.

To skip that step, make a file with the following contents, and open it and the registry setting will be automatically imported into your system.

skipOpenWithWebService.reg
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer]
"InternetOpenWith"=dword:00000000


source(s): http://www.pctools.com/guides/registry/detail/1314/

Monday, April 09, 2007

C++: Associative Arrays

#include <map>
#include <string>


using namespace std;

int main()
{
std::map<std::string, std::string> m;
m["ENG"] = "English";
m["FRA"] = "France";
m["CAN"] = "Canada";
m["AUS"] = "Australia";

//does print empty string
cout<<m["Germany"]<<endl;

//iterate through all elements of array
std::map<string, string>::iterator curr,end;
for( curr = m.begin(), end = m.end(); curr != end; curr++ )
cout << curr->first + " = " + curr->second << endl;
return 0;
}


C++ maps or associative arrays are implemented as self-balancing binary search tree. This means that when you iterate through your map it will not be in the order you added them like in PHP but instead will be in sorted order.

source(s):
http://www.webmasterworld.com/html/3249762.htm

Sunday, April 08, 2007

HTML: Website blank in IE, fine in Firefox

I coded up a website in firefox but it wouldn't show in IE. I was trying to make it xHTML-ish, and had the script tag looking like this:

<script language='JavaScript' type='text/JavaScript' 
src='script.js'/>


For some idiot reason, IE chokes on the whole page, unless it looks like this:

<script language='JavaScript' type='text/JavaScript' 
src='script.js'></script>


source:
http://www.webmasterworld.com/html/3249762.htm

Tuesday, April 03, 2007

LINUX : C++ Hello World Compile Errors

A simple hello world using cout and string yields this.

main.cpp
#include <string>
#include <iostream>

using namespace std;

int main ( int argc, int argv[] )
{
cout << "running....\n";

cout<<"finished"<<endl;
return 0;
}


compile.sh
#compile
CFG=/usr/bin/mysql_config
sh -c "gcc -o mysqltest `$CFG --cflags` main.cpp `$CFG --libs`"


errors
abc@localhost:~/Projects/mysqltest> ./compile.sh
/tmp/ccpF755X.o: In function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0x23): undefined reference to `std::ios_base::Init::Init()'
/tmp/ccpF755X.o: In function `__tcf_0':
main.cpp:(.text+0x66): undefined reference to `std::ios_base::Init::~Init()'
/tmp/ccpF755X.o: In function `main':
main.cpp:(.text+0x81): undefined reference to `std::cout'
main.cpp:(.text+0x86): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
main.cpp:(.text+0x90): undefined reference to `std::cout'
main.cpp:(.text+0x95): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
main.cpp:(.text+0x9d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
main.cpp:(.text+0xa2): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
/tmp/ccpF755X.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'


The problem is that I was compiling with gcc instead of g++

Monday, April 02, 2007

LINUX: Weird characters when you compile

Why are there weird characters when I compile:

test.cpp: In function âint main()â:
test.cpp:7: error: âcoutâ was not declared in this scope
test.cpp:7: error: âendlâ was not declared in this scope


It's normal if you don't set the environment variable e.g.
export LANG=C


source(s):
http://gcc.gnu.org/ml/gcc-help/2006-08/msg00179.html