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