Blog

The importance of Coding Small

What does “Coding Small” mean?

Simple. It means code small. A small bit of code is easier to debug then a large program.

Take for instance my current Perl coding project. I’m writing a script that will reside on my server and download a comic, and news headlines and then print it out at about 5 in the morning so everybody can have a bit of happiness, and find out what hell has broken loose in the world today.

The comic I want to use is Sheldon. Sometimes, however the creator doesn’t keep strictly to posting the link on his RSS feed. So, I have to make sure that I grab that, or I will get a perl error later on. How you ask?

Until tonight, this comic meant absoloutely nothing to me . . . .

Stand Back!

Yes indeed.

use warnings; use strict;
my @file_contents;

open FILE, "text.txt" or die "$!"; #open with write rights
@file_contents = <FILE>;
close FILE;
foreach my $text (@file_contents){
 chomp $text;
 if ($text =~ m/^Strip for /){
 print $text;
 } else {
 print "No goodness here (Text:$text) n"
 }
}

Pretty much what this snippet does is takes and loads the contents of the file into an array, with each line being an item in the array.  It then stores one value of the array, chomps the newline character off of the end, and check if it starts with “Strip for”, case sensitively via a regular expression.  If the value starts as wanted, then I’m good and it prints that line from the file.  If  the line does not start with “Strip for”, then it prints “No Goodness here” and what the line actually was.

This can then be turned into a subroutine to use with perl.

use warnings; use strict;
my @file_contents;

open FILE, "text.txt" or die "$!"; #open with write rights
@file_contents = <FILE>;
close FILE;

&reg_ex(@file_contents);

sub reg_ex{
 foreach my $text (@file_contents){
 chomp $text;
 if ($text =~ m/^Strip for /){
 print $text;
 } else {
 print "No goodness here (Text:$text) n"
 }
 }
}

Now, no matter how many different types of data I wanna shove at the array, I just call &reg_ex(array of data), and it parse and prints.

Why is this nice?  Let say that I have a more complicated program.  Now that I know that section of code works, I can paste that subroutine in, call when needed, and know that it works and is not affecting other parts of my program.  Then I can work on debugging the rest of my crappy code.

Lemme know what you think in the comments, and hopefully I’ll be posting more of this stuff as I go on . . . .


Linux Update!

Well, I never properly ended off my category about my laptop and linux.  As I said somewhere in the previous post, it has to do with the BIOS, or more accurately the lack there of.

I gave up on getting linux onto my laptop and working for a number of reasons.  The biggest one was I didn’t have enough time to get the damn thing done.  The other was  it was to big of a fight with my parents who seem to think that they can consume all of my free time.  The end result of that was it was literally causing my mind to crash and burn.

So, about a week ago I booted up a distro called Back Track 4, just for grins and giggles.  Or because I really want linux.  Guess what?  The Ubuntu (or rather Kubuntu) based distro worked.  I figured what the heck, with a server that runs all the time I’ll download the live disc and have a gander at Kubuntu, and it seems to be working properly.  The fan runs at least, which is something I didn’t have with the other versions.  I”m going to try to get Kubuntu installed within the month.  Maybe I can have my birthday off to do whatever the hell I want (its a Sunday after all).

I don’t normally like Ubuntu.  I personally think it more of a “kiddie” OS, though there are those that would disagree with me.  Perhaps their thoughts on the subject are well founded.  Again, debating linux distros is worse then debating Apple and Redmond.  (I only debate whether the x86 and x86_64 is better then Apple’s platform, which x86 is surely better for a number of reasons). Update: Apple sucks, plain and simple.  I can stand people that can use both windows and macs and make a LOGICAL and fair argument for why they PREFER one or the other.  Debating the flavors of linux is redundant to.  However, at least you are comparing kiwi to kiwi, and not kiwis to oranges to crap (mac).  Now, back to the main content: I also dislike its (Ubuntu’s) overwhelming popularity.  I tend to avoid anything like that.  Popularity really makes me wary of things.  But in this case, it seems to be working in its favor.  People have the shitty insydeh20 bios that Toshiba used for the laptop, and Canonical seems to have listened.  Its great.

But first I think I need to reinstall Windows 7.  Yes, the OS that I installed back somewhere in January.  I seem to be having a driver issue that I think is related to update I received, since the mouse works perfectly within Linux.

Another Update: Since I threatened the OS with a re-install, its been behaving.  A update must have screwed the system up, which is what I figured.

Does that might mean that there’s going to be yet ANOTHER guide on Dual Booting a computer?  Probably, we’ll see how lazy I’m feeling.

Until I next post, goodnight.


Deep Water Horizon Oil Spill

I thought of something today.  The Deepwater Horizon basically burned down, fell over and then sank into the swamp, I mean the ocean.

Wait, what?


Email Updates on Server IP Change

Here’s a script I wrote in perl (yes perl) that checks your ip and will email you if the ip changes. Because I’m using private IP’s, I need to check via an external server. What I want to know is if my IP changes, because if it does, I probably need to restart my IRC Bot. Because of the private IP mess, I need to use an external to get my external IP. I use a simple PHP script on my server from Fivebean to tell me the IP.
The PHP is:

<?php
echo $_SERVER['REMOTE_ADDR'];
?>

Stick that somewhere that’s not on your local LAN.
Now, make a batch file with this
perl ip_checker.pl location_of_previous_php_script file_to_write_some_info_to

Coincidentally, I think it would be best if I maybe removed those option and just put them in the configuration section of the perl script . . .

Copy this and save this within the same place as that bat file, using the name ip_checker.pl. Make sure you have Net::SMTP::SSL installed in your perl modules.

use LWP::Simple;
use Net::SMTP::SSL;

use warnings; use strict;
sub text;

#texting information
#configure whether to send alerts.  Email based
################################
######Script configuration######
################################
################################
#####Options Confiugration######
################################
my $send_alert = 'true'; #set true to allow messages to be sent informing you of changes to the local IP
################################
#####Email send information#####
################################

my $email_from = '';
my $email_password = '';
my $send_to= '';
my $email_host ='smtp.gmail.com'; #something link that anyway

################################
##End of Configuration Section##
################################

if (@ARGV ne 2){
    die 'Usage: perl ipchecker.pl (URL To Retrieve External IP From) (File to ReadWrite LastCurrent IP From)n';
}

my $ip_bouncer = shift;
my $read_file_location = shift;
my $current_ip = get($ip_bouncer); die "Couldn't get it!" unless $current_ip;
my $old_ip; my $new_ip;

my $read_file; my $print_file;

open OLD_IP, "$read_file_location" or die "$!"; #open with write rights
$old_ip = <OLD_IP>;
close OLD_IP;
open OLD_IP, ">$read_file_location" or die "$!"; #open with write rights

print "Current IP Address: $current_ip n";
print "Last IP Address: $old_ip n";
print OLD_IP $current_ip;
close OLD_IP;

if ($current_ip ne $old_ip){  #ne is a string comparison of equal or not == is numeric comparison
    #/&text ($host, $from, $password, $message );
    print "Alert!  IP address has changedn";
    if ($send_alert eq 'true'){
    print "Sending Alert!n";
    my $desired_message = "IP Change $current_ip";
    &text ( $send_to, $email_host, $email_from, $email_password, $desired_message);
    print "Alert Sentn";
    }
} else {
    print "All is welln";
    }

sub text { # ($to, $host, $from, $password, $message )
    #mostly from http://robertmaldon.blogspot.com/2006/10/sending-email-through-google-smtp-from.html
    #modified to suit my needs

    my $to = shift;
    my $host = shift;
    my $from = shift;
    my $password = shift;
    my $message = shift;

    my $smtp;
    if (not $smtp = Net::SMTP::SSL->new($host,
                    Port=> 465,
                    Debug => 1,
                  ) ) { die "Couldn't connect" };
    $smtp->auth($from, $password) || die "Authentication failed!n";

    $smtp->mail($from."n" );     # use the sender's address here
    $smtp->to($to."n" );        # recipient's address
    $smtp->data();                      # Start the mail

    # Send the header.
    $smtp->datasend("To: $to n" );
    $smtp->datasend("From: $from n" );
    $smtp->datasend("Subject: Server Alertn");
    $smtp->datasend('Content-Type: text/plain; charset=ISO-8859-1;' . "nn");
    # Send the body.
    $smtp->datasend("Automated Server Message n", $message, "n");
    $smtp->dataend();                   # Finish sending the mail
    $smtp->quit;                        # Close the SMTP connection
}

Schedule every 6 hours or so. I did it with the scheduled jobs thingy in windows server 2003.

Sorry for the poor write up, hit me up in the comments if you need help setting this up or if you have other general questions. Right now, I have to go mess with a wordpress theme in need of fixin . . . .

use warnings; use strict;
sub text;

#texting information
#configure whether to send alerts.  Email based
################################
######Script configuration######
################################
################################
#####Options Confiugration######
################################
my $send_alert = ‘true’; #set true to allow messages to be sent informing you of changes to the local IP
################################
#####Email send information#####
################################

my $email_from = ”;
my $email_password = ”;
my $send_to= ”;
my $email_host =’smtp.gmail.com’; #something link that anyway

################################
##End of Configuration Section##
################################

if (@ARGV ne 2){
die ‘Usage: perl ipchecker.pl (URL To Retrieve External IP From) (File to ReadWrite LastCurrent IP From)n’;
}

my $ip_bouncer = shift;
my $read_file_location = shift;
my $current_ip = get($ip_bouncer); die “Couldn’t get it!” unless $current_ip;
my $old_ip; my $new_ip;

my $read_file; my $print_file;

open OLD_IP, “$read_file_location” or die “$!”; #open with write rights
$old_ip = <OLD_IP>;
close OLD_IP;
open OLD_IP, “>$read_file_location” or die “$!”; #open with write rights

print “Current IP Address: $current_ip n”;
print “Last IP Address: $old_ip n”;
print OLD_IP $current_ip;
close OLD_IP;

if ($current_ip ne $old_ip){  #ne is a string comparison of equal or not == is numeric comparison
#/&text ($host, $from, $password, $message );
print “Alert!  IP address has changedn”;
if ($send_alert eq ‘true’){
print “Sending Alert!n”;
my $desired_message = “IP Change $current_ip”;
&text ( $send_to, $email_host, $email_from, $email_password, $desired_message);
print “Alert Sentn”;
}
} else {
print “All is welln”;
}

sub text { # ($to, $host, $from, $password, $message )
#mostly from http://robertmaldon.blogspot.com/2006/10/sending-email-through-google-smtp-from.html
#modified to suit my needs

my $to = shift;
my $host = shift;
my $from = shift;
my $password = shift;
my $message = shift;

my $smtp;
if (not $smtp = Net::SMTP::SSL->new($host,
Port=> 465,
Debug => 1,
) ) { die “Couldn’t connect” };
$smtp->auth($from, $password) || die “Authentication failed!n”;

$smtp->mail($from.”n” );     # use the sender’s address here
$smtp->to($to.”n” );        # recipient’s address
$smtp->data();                      # Start the mail

# Send the header.
$smtp->datasend(“To: $to n” );
$smtp->datasend(“From: $from n” );
$smtp->datasend(“Subject: Server Alertn”);
$smtp->datasend(‘Content-Type: text/plain; charset=ISO-8859-1;’ . “nn”);
# Send the body.
$smtp->datasend(“Automated Server Message n”, $message, “n”);
$smtp->dataend();                   # Finish sending the mail
$smtp->quit;                        # Close the SMTP connection


Twitter Feed on HomePage Code

On my homepage, you may notice that I have a bit of code to get my latest tweet for this website’s twitter account. Usually this is blog updates, but it may show other things.

I originally found this code on http://www.phoenixheart.net/2009/05/code-snippet-1-get-latest-tweet/. Since twitter has been having issues lately, I realized a need for a fall back value if the code couldn’t get anything. I also removed a variable declaration and then copied the returned value from the function to another variable, to hopefully optimize the code and make it work better and faster.

<?php

 // the function
 /**
 * @desc Get latest tweet from a Twitter account
 * @param string The account's username
 * @return string The tweet
 * http://www.phoenixheart.net/2009/05/code-snippet-1-get-latest-tweet/
 *
 */
 function get_latest_tweet($username) {
 $url = "http://search.twitter.com/search.atom?q=from:$username&rpp=1";
 $content = file_get_contents($url);
 $content = explode('<content type="html">', $content);
 $content = explode('</content>', $content[1]);
 return html_entity_decode($content[0]);
 }
 $my_tweet = get_latest_tweet('TWITTERLOGIN');
 if ($my_tweet == NULL)
 {
echo "Twitter is having issues again . . . .";
 }
 else {
 echo "$my_tweet";
 }

 ?>

Just paste this in a php file and change your twitter name so it gets the right feeds!


SSH Window Forwarding

Recently, I put out a call on freecycle for an old computer (I’d like a laptop to, as well, but . . .) and I got one Sunday. Why did I do this?

SSH Window Forwarding finally got the better of me. What is window forwarding? Well, its a simple enough concept, if you know what you are doing. The concept is that you enable X11 Forwarding and then whenever you open an application with an window interface, like Xterm or Geany, it is opened on your local computer.

This means that if have a remote server with X11 Forwarding and you open Firefox on the commandline, you will be browsing with firefox window forwarded from that computer! You can set this up, then check it out be visting perhaps ipchicken. It will show the ip of the remote computer.

Enough concept, let’s get our fingers dirty!

The first thing you need is a computer. You could also use a Virtual Machine in VBox to do this, but I don’t really have any computers powerful enough to run virtual machines. That was why I requested a old computer. Boy, was it old. Its a HP XE743. Designed for Windows 98. Computer stats: 600 mhz Intel Celeron, and 64 megs of RAM. I was really, really lucky and had a extra stick of RAM that fit the computer (no reason). Now I have 128 megs of RAM.

I mention this for two reasons: 1)to show the power of linux. This is a computer that should be in the graveyard by window’s standards, and yet it is alive and very well by running a slightly outdated copy of Ubuntu Server. 2) Windows forwarding doesn’t take that much power. Running it over my local LAN, my experiences are that even with the low power, it still acts pretty snappily.

The second thing is Linux. I’m sure that there are ways to do this with windows, but linux works. Its also free. My choice was Ubuntu Server 8.10. Yes, I need to update but this was the disc I had handy. I wasn’t expecting to have to do a whole lot with it, though that might change.

Install Ubuntu Server on the machine. Something you really need to be aware of with this machine is that you need to change a few settings in the BIOS. First of all, turn off the quick boot and such. Make it do the full tests to insure everything is correct. Then set the disk access to other, so it knows its using linux. Otherwise, it will act like a turd and not boot at all. Install everything, and when it asks for services, install the sshd. If you forget it, you can install it later. I would recommend using a static ip for all servers. It can be a pain when your server’s ip address changes constantly and you have to find it in the DHCP loan list.

Now, you need to install Xorg. I remember install Xorg, then installing a window manager. It should be sufficient to run something like sudo apt-get install fluxbox. That should pull all dependencies, including xorg for fluxbox. Fluxbox isn’t the best, but it gets the job done, which is what I am concerned about. It also isn’t a resource hog. On this machine, there isn’t a whole lot to hog!

You’ll need to configure Xorg. Run xorg -configure, then copy the config file to the proper location: sudo mv /etc/X11/xorg.conf /etc/X11/xorg.conf.old
cp /home/user/xorg.conf.new /etc/X11/xorg.conf

Edit the sshd conf file to allow window forwarding, and the ssh to try to do window forwarding. These should be in /etc/ssh/sshd_config and /etc/ssh/ssh_config respectively. Run startx and again, then pull up xterm and do ssh localhost. This will ssh to yourself. Run Xterm on the commandline, and you should have a new xterm window popup. You may need to install Xterm first, however. Close out the ssh windows.

Now, head over to your windows machine (cause this is where it gets really cool). Install Xming and start it up. Then start putty. I’m also starting to use Kitty now, which is a port of putty with more features, with some really nice features that make me like it more then putty.

For putty, enter the ip address of the server (I chose 192.168.1.5, and yes that’s a local ip). Go to Connection, then SSH, then X11. Check the box to enable forwarding. Then click connect. Enter login and password. Then, type xterm. If you’ve done everything right on the windows side, Xterm will run and you will have a graphical shell.

*UPDATE*

I installed Ubuntu 10.4, which seems to be a bit friendlier on the resources side of things.  Anyway, I didn’t install or configure xorg.  I simply did <code>sudo apt-get install xterm</code>.  After running Xming on my windows machine and connection, everything ran fine.  So, you’ll need the dependencies (one of which I believe was X11 common) but you don’t have to setup Xorg if you don’t want to.


Random Quotes on Page

I’ve converted my homepage to php. This has the benefit of maintaining standard HTML interaction, while allowing me to script certain things into my page. I wrote this because I hate java and java script with a passion. I blame it on my college’s use of blackboard. Its enough to make any one think twice.


The Guerilla Guide to Portable Apps

Some of you may know of my involvement with PortableApps.com. One of the things that I did there was to create a “manual” as it were for developing a portable app. Not how to code it, but the way to start working on it. Awhile ago I asked John if I could turn it into a full HTML page. He never said I could, though I probably could get away without him knowing about it.

I’ve started work upgrading the Guerrilla Guide here on my website. You can find the link here If it moves, I’ll try to remember to either update the link, or post a redirect. Its currently a work in progress just porting it to how I want it to look, and updating it with all the new information. I will hopefully add more content later.

That’s this short update.


Gradients in Text via GIMP

No words, because its late, I’m lazy, and pictures are worth one thousand of them


I guess I didn’t get a image of me using the gradient tool.  But at this point, you would just use the gradient tool like you would to fill a square or circle or what have you.


Geany Portable, Nightly Edition

So, around January, I started playing with batch scripting (I’m terrible at it still).  Anyway, I had installed MingW so that I could compile geany nightlies from source on my server.  The ones hosted at geany.org are cross compiled, unlike mine.

Anyway, I created a script that would download the svn posted on the server, extract it, compile, and then copy it into a folder and then compress it so I would have a portable version of the geany nightly, natively compiled.

The trick was to get it up to a server.  Windows (my server is Windows Server 2003), has a built-in ftp client, that can be called from the command line.  It can even be scripted.  The problem is that it didn’t work for my.  So I was stuck trying to get it to the outside world until I figured out how to ftp it to another site.

The answer is WinSCP.  WinSCP allows scripting, in a variety of forms.  I had stumbled across this at some point, it wasn’t until I created a backup script for my mother’s computer (more to come on that one) that I rehashed the script I had been using to add upload abilities.

The script itself is far from complete but I thought that by posting this, I might help someone else in a similar situation.  I’ve tried to comment it pretty well, since it sucks when someone posts something and there is no comments.

REM This script requires you to have wget either in the script folder or in your %PATH%
REM It also requires a copy of the 7Zip command line tools
REM You also need the winscp binaries

cd ........
REM Change directory to root of drive
cd nightly
REM change to nightly folder
wget http://files.uvena.de/geany/geany_svn.tar.gz
REM download the nightly tar ball generated by Geany Project from server
7za e geany_svn.tar.gz
7za x geany_svn.tar
REM extract geany via 7zip command line
MakeBuilder.exe
REM this is a custom program that changes a single line within the geany make file so that it is compatible with a stock mingw install
cd geany_svn
mingw32-make -f makefile.win32
REM go the the geany svn folder and build the binary
cd ..
REM get out of the geany_svn folder
erase C:nightlyGeanyPortableAppGeanybingeany.exe
erase geany_svn.tar
erase geany_svn.tar.gz
REM clear out unneeded stuff
copy geany_svngeany.exe C:nightlyGeanyPortableAppGeanybin
REM copy the binary over to the bin folder in Geany Portable
rmdir /s /q C:nightlyGeanyPortableDatasettings
REM delete the datasettings folder so that any of my settings are not copied to you
7za a -sfx7z.sfx GeanyPortable%date:~4,2%-%date:~-7,2%-%date:~-4,4%.exe GeanyPortable
REM create a self extracting 7-zip package with a month-data-year ending name
winscp /console /command "option batch on" "open login:password@host" "put GeanyPortable%date:~4,2%-%date:~-7,2%-%date:~-4,4%.exe /downloads/Geany/nightlies/" "exit" "close"
REM upload the file to the intellilaunch server via winscp binary
erase GeanyPortable%date:~4,2%-%date:~-7,2%-%date:~-4,4%.exe
REM erase the file from the "local" location
rmdir /s /q geany_svn
REM delete the geany_svn folder so that the directory can be extracted without needing to overwrite anything

If you are wondering where to get those Geany nightlies I mentioned, they are right over here.