Quote of the Day and Something Cool

Posted in Code, Guns on September 10th, 2009 by bemasher

So I was sitting in my discrete structures analysis class today when a student asked a question about the homework. It went a little like this:

Student: How should we format pseudo-code in the homework?
Professor: Ah see pseudo-code is in that grey area. It’s somewhere in between code and english.
Professor: You see me do it one way in class, the book does it another way and the homework assignment does it an even different way.
Professor: Think of it this way, pseudo-code is a lot like pornography: you’ll know it when you see it.
Professor: So I’m not very worried about how you do your pseudo-code as long as I understand it.

The other cool thing that happened today was that I found out the owner of my favorite coffee shop is a pro-gun person. Apparently some of his relatives own a gun shop and he’s done some shooting competitions. All very cool. It definitely explains why none of the employees ever freak out about me carrying my 1911 which looks giant on my hip compared to others. I’m a tall skinny guy if you didn’t already know.

Tags: , , , , , , , , ,

Second More Useless Plugin

Posted in Code on July 8th, 2009 by bemasher

Bored again which seems to be the usual for the summer I sat down with one purpose in mind: To write another plugin. Didn’t really matter to me if it was useful or not I just wanted to write another one. I decided to ask my friend Pete who snarkily replied “Write one that randomly inserts horse pr0n1 in your blog.” to which I immediately replied “not horse pr0n, ASCII pr0n!” which probably made him choke on his drink and immediately remember rule 34. But this made me think to myself: Why not a random plugin?

So I did just that, I wrote a random plugin. One so useless that I don’t think I’m even going to activate it on my blog save for days like April Fools Day. The plugin chooses at random a word from each post using the the_content hook and censors it out with <censored>. Funny huh? This will ignore html tags so it won’t break links and things like that. The code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?
    /*
        Plugin Name: Random Censor
        Plugin URI: http://www.bemasher.net/
        Description: Picks a common word at random from posts at display
            and replaces with &lt;censor&gt;. Ignores urls and other
            semi-important things.
        Version: 0.01
        Author: BeMasher
        Author URI: http://www.bemasher.net/
    */


    function random_censor($content) {
        $oldcontent = $content;
       
        $content = preg_replace("/<[^<]+?>/", "", $content);
        preg_match_all("/\b\w+\b/", $content, $words);
        $word = $words[0][rand(0, sizeof($words[0]))];
       
        $oldcontent = preg_replace("/\b$word\b/i", " &lt;censored&gt; ", $oldcontent);
       
        return $oldcontent;
    }
   
    add_filter("the_content", "random_censor");
?>
  1. Mind you this is a joke, relating to the fact that horse pr0n happens to rank pretty high on the list of strange things on the internet. []
Tags: , , , , ,

My First Wordpress Plugin

Posted in Code on July 6th, 2009 by bemasher

I’ve been meaning to do this for a while, I’m writing a plugin for wordpress to automatically capitalize the right letter in the words I’m generally lazy about typing. Things like I, I’m, I’ve and the like1.

Took me a little while but I did finally find some documentation on all the different hooks wordpress has for filters. I found one in particular that does what I want called content_save_pre which applies a particular filter to the content of a post any time I save or edit it. So for things like drafts and actual posting and updating posts it would fire the function I registered as a filter.

The first problem I ran into is that for some strange reason it didn’t seem to want to replace contractions with the single quote character. I later found out that when displaying the single-quote it converts it to the html entity &#8217; which shows up as an apostrophe. So I tried working around that but that dIdn’t seem to work either. Eventually I just setup a small test post and modified the function to email me the plain-text contents of the post that the filter would receIve, I noticed that it escaped single quotes probably through the use of the php function mysql_escape_string2. So anything with an single-quote would show up with a backslash just before the single-quote. This of course broke the regular expression I was using and I couldn’t seem to figure out how to get it to check for that character so I gave up and just used the negated word-character class \W.

Anyway after fiddling around with it a little more and adding a few new cases to the regex I arrived at this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
    /*
        Plugin Name: Lazy Errors
        Plugin URI: http://www.bemasher.net/
        Description: Replaces errors from lazy typing, things like:
            I, I'd, I've, I'm will be replaced with proper case.
        Version: 0.02
        Author: BeMasher
        Author URI: http://www.bemasher.net/
    */

   
    function lazy_errors($content) {
        return preg_replace("/I(?(?=\W')(\W')(ve|m|d|)|(\b))/", "I$1$2$3", $content);
    }
   
    add_filter("content_save_pre", "lazy_errors");
?>

The regular expression reads like so: If there’s an I followed by any non-word character and a single-quote then make sure it’s got a proper contraction following the single-quote. Else make sure there’s a space, period, comma, colon or semI-colon following the I. Then replace with capitalized I and the matching group from the conditional.

I should probably work out some code to make it ignore sections of text I don’t want it to filter. A prime example of this would be in the comments of the plugin and especially in any code as code examples copied from my site would then be broken if the regex I wrote matched anything in the code.

  1. Notice they look normal to you because I’ve gotten my script working. []
  2. http://www.php.net/manual/en/function.mysql-escape-string.php []
Tags: , , , , ,

Installing MikTeX on Windows 7

Posted in Code, Computers on June 23rd, 2009 by bemasher

One of the only things that kept me from installing Windows 7 permanently during the school year was that the few times I tried, I had never gotten MikTeX1 to work. This of course was a major problem since nearly all of my assignments are done with MikTeX now. When installing MikTeX I always ran into a BSOD that I ignored because I figured that it was only because Windows 7 was only an RC2.

I’ve had Windows 7 on my desktop now for about 2 weeks and up until this point I’ve been making due with the MikTeX Portable Edition which is pretty buggy to say the least. More than half of the time it would hang on compiling a document to pdf at something due to it not thinking initexmf.exe was an operable program. And of course upon googling this problem, nothing of use could be found.

Well tonight I decided I’d give the install another go to see if either Windows 7 had been patched to fix this issue, or if MikTeX had fixed the problem. On my first try, it did exactly as it had always done before BSOD’d. Since I had never set windows to not automatically restart upon catastrophic system failure3 it would just instantly restart without giving me enough time to read the type of error. I fixed this and ran the installer once more. The BSOD was a PAGE_FAULT_IN_NON_PAGED_AREA error, which was pretty vague as usual but I figured it had to do with system paging, so I disabled the Virtual Memory restarted and ran the installer once more. This time it worked exactly as it should.

On another interesting note, I discovered that pdflatex is significantly faster than texify. I found this out when I was trying different methods of compiling my TeX documents into pdf’s using the MikTeX Portable Edition which was giving me fits with my old method.

I used to use the following in NotePad++’s NppExec plugin to compile a pdf and view in Adobe Reader:

1
2
C:\Program Files\MiKTeX 2.7\miktex\bin\texify.exe -c -p "$(FULL_CURRENT_PATH)" "$(NAME_PART).pdf"
C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe "$(CURRENT_DIRECTORY)\$(NAME_PART).pdf"

Now I use pdflatex:

1
2
C:\Program Files\MiKTeX 2.7\miktex\bin\pdflatex.exe "$(FULL_CURRENT_PATH)"
C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe "$(CURRENT_DIRECTORY)\$(NAME_PART).pdf"
  1. MiKTeX (pronounced mick-tech) is an up-to-date implementation of TeX and related programs for Windows (all current variants). []
  2. Release Candidate []
  3. Read: Blue Screen Of Death []
Tags: , , , , ,

GitHub Repositories Feed

Posted in Code on May 4th, 2009 by bemasher

I noticed at the bottom of the page on GitHub that there was an API link. I took a look at it and found it to be pretty interesting, it’s actually really simple to use. You can export in xml, json and yaml. I thought to myself: “Hey it’d be great if I could put a repositories feed in the sidebar of my blog here!”.

So I took a look at the JSON output since it’s small and really easy to deserialize in php, so I wrote up a quick little php script on the server I’m hosting my blog at that will spit out an RSS feed of the repositories I’ve created on GitHub. The code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?="<?xml version=\"1.0\"?>"?>
<rss version="2.0">
  <channel>
    <title>BeMasher's GitHub Repositories</title>
    <link>http://github.com/bemasher</link>
    <description>BeMasher's GitHub Repositories</description>
    <language>en-us</language>
    <pubDate><?=date("D, d M Y G:i:s e")?></pubDate>
    <lastBuildDate><?=date("D, d M Y G:i:s e")?></lastBuildDate>
    <webMaster>bemasher@bemasher.net</webMaster>
    <ttl>5</ttl>

<?php
    $data = file_get_contents("http://github.com/api/v2/json/repos/show/bemasher");
    $data = json_decode($data, true);
   
    $today = date("D, d M Y G:i:s e");
   
    foreach($data["repositories"] as $repository) {
echo <<<ITEM
    <item>
        <title>{$repository["name"]}</title>
        <link>{$repository["url"]}</link>
        <description>{$repository["description"]}</description>
        <pubDate>$today</pubDate>
        <guid>{$repository["url"]}</guid>
    </item>

ITEM
;
    }
?>
    </channel>
</rss>

And if you look to the right you can see the RSS Widget in action displaying the output of the script. Cool huh?

Tags: , , , ,

GitHub Won

Posted in Code, Computers on May 2nd, 2009 by bemasher

In lieu of my Git vs. Mercurial post I’ve pretty much decided to stick with GitHub due to it’s extreme ease of migrating subversion repositories to it. While I’m sure it’s going to take me a little while to get used to the GUI for MSysGit (or find a better client) I’ve decided to move all of my current version control to GitHub.

You can find all my repositories here: http://github.com/bemasher/. Feel free to follow me on there, I’m always looking to meet other tech-friendly people.

Tags: , ,

Free Hosting for Git vs. Mercurial

Posted in Code, Computers on May 1st, 2009 by bemasher

A co-worker and I were talking about version control software and he made an interesting comparison: Git is like MacGuyver and Mercurial is like James Bond. He then proceeded to point me in the direction of GitHub and Bitbucket.

From first impression both seem to have the same basic set of tools and features. Both have built in simple wiki’s and issue trackers. Both allow unlimited public repositories limited only by disk space, 150MB for Mercurial and 300MB for GitHub. Mercurial allows one private repository while GitHub allows no private repositories without a paid plan.

Both of them have fatal flaws for Windows users. First off, GitHub is the most enticing because they offer an integrated subversion repository importing, just give it the URL to a SVN repository and you can import all the authors and history of it. Bitbucket however doesn’t seem to have this feature, I’ll continue looking for a simple way to do this but right now that’s a major flaw in Bitbucket because all of my repositories until this point have been on xp-dev a free SVN hosting service I talked about in my Free Subversion Hosting post.

The major fatal flaw in GitHub for Windows users is that there’s not really any solid Git clients to use with it at the moment. There’s MSysGit which provides a very basic GUI and command line tools which is great but not very integrated or simple to pick up and use. There’s a project for porting TortoiseSVN to TortoiseGit, though at the moment it heavily relies on MSysGit except it uses it’s own ssh client plink instead of the OpenSSH library that MSysGit uses which means running pageant to manage your keys and importing and creaking a ppk of your private keys for use with GitHub.

Mercurial seems to have a major fix for the main problem with Git’s poor selection of Windows clients is a major issue for usefulness in Windows. Mercurial wins this particular aspect of the competition. Mercurial has TortoiseHg which is pretty stable so far.

When it’s all said and done Bitbucket and GitHub are more or less equivalent services built on top of two different version control projects.

Tags: , , , , , , ,

Compiling Python (w/Jython)

Posted in Code, Computers, Technology on April 16th, 2009 by bemasher

If you’re interested in the cross-platform-y-ness of python, you’ll probably find this interesting. Initially i’ve written a few programs for work in python. They needed to be more or less cross-platform and simple to use since it’s going to be distributed to users who have pretty much no idea how to do anything in the command line or anything of that nature.

My first experience with packaging python such that it could run on Windows desktops without installing the python interpreter before hand involved using a program called py2exe. Which does just what it says, it compiles all the dependencies and libraries of a particular python program into a single zip file along with a few basic things and generates an executable file for Windows based systems. The only drawback to this is that it only seems to work with Python 2.5 right now, it also has several extra files that must be distributed with the program and are really good at confusing users.

As for running python on Linux and OS X based systems it was a breeze, I had written a few very basic interfaces using Tkinter which is installed by default with python. The scripts by themselves run great on Linux and OS X systems since both come with them by default (RedHat Desktop is the Linux distro in question).

I still wanted an easier // more fool-proof way to distribute the scripts between computers with different flavors of OS’s without having to have a different version for each OS. A co-worker suggested I look at Jython which to my surprise happens to be awesome. Jython is a full implementation of python on the Java VM. This is great for me because ALL of the systems I’m writing this stuff for have Java. You’re probably wondering why I’m not just writing this stuff in Java to begin with and my answer to that is, these are really simple tasks that take way too much code//time to implement in Java when they took a few hours and about a 4th of the amount of code to perform the same task in python.

I discovered much to my surprise that it ended up being as simple as switching from Tkinter to Swing for the GUI’s and then fixing a few random things like OS detection for configuring default paths of certain system files before the code all ran flawlessly in Jython. Now onto the really fun part. I discovered that I could compile the code including all dependencies and libraries for the Jython interpreter into a single Jar file usually about 1MB total. All the user has to do is double-click on the jar and everything fires up and does it’s thing.

The first problem I ran into though was that OS X distributes their own version of the Java VM, 1.5.0_16 instead of the latest 1.6.0_13. I eventually discovered that it was as simple as adding the -target option to the java compiler and telling it to compile for the target version. Once all that was said and done I had a single jar file that contained all the necessary files to run the program by itself without any external dependencies.

If you’re interested in knowing what command I use to compile to jar it is as follows:

1
C:\Program Files\Jython221\jythonc.bat -J "-target 1.5" --jar "$(NAME_PART).jar" --all --core "$(FULL_CURRENT_PATH)"

Mind you that I run this in Notepad++ on the current open file. $(NAME_PART) is the name portion of the filename excluding the extension. $(FULL_CURRENT_PATH) is you guessed it: the full current path including the filename and extension.

Tags: , , , , , , , ,

Podcast Downloading on FreeNAS (Followup)

Posted in Code, Computers on March 30th, 2009 by bemasher

I’ve been following the referrals to my blog lately and I noticed the FreeNAS Podcast Downloader post was getting a lot of traffic but that the post wasn’t descriptive enough in it’s actual use. So I’ve got some instructions how to actually USE the project.

First off this will involve installing a package that isn’t default for FreeNAS, if this worries you then skip down a step or two to the link to download all the project files manually. All this involves is installing subversion for checking out the code and all necessary files for the project to run. SSH into your FreeNAS server and execute this command:

1
pkg_add -r subversion

This will take a while to run so don’t worry if it looks like it froze. You should reboot your server after this is finished for all the new settings to take effect. This is just so you can download the latest copy of the project.

Next step is to check out the project which can be done using the package you just installed. Choose a folder on your data partition for this to go because in an embedded install any other location would be overwritten on reboot. I made a directory in /mnt/Main/Content/.db/ (This is where I’ve chosen for all the databases for UPnP and DAAP to be stored along with the scripts for my server that I’ve written):

1
svn checkout http://svn.xp-dev.com/svn/bemasher-FreeNASPodder/ FreeNASPodder

This will check out the latest copy of the code to a new folder FreeNASPodder in /mnt/Main/Content/.db/

If you’re uncomfortable with installing new packages to your server and just want a copy of the project you can simply browse to http://svn.xp-dev.com/svn/bemasher-FreeNASPodder and download each individual file manually. The benefit of using subversion is that getting the latest version of the file requires only browsing to the folder it resides in and executing:

1
svn update

Once this is all done you’ve checked out a working copy of the code. There are a few minor things you’ll need to change in the script and in the configuration file. First in bashpodder.sh you’ll need to change podcast_dir to the directory that you’d like your podcasts to be downloaded to, do the same in select_podcasts.sh. Make sure this folder exists as the script won’t create it for you, it will only create folders for individual podcast feeds inside this folder. Be sure to escape spaces with a backslash.

The next change you’ll need to make is in feeds.list. This will have a list of the url to each podcast feed you’d like to download episodes from. Be sure to keep one blank line at the very end of the file it will skip the last feed if you don’t.

If you don’t want to download all the current episodes all at once run select_podcasts.sh from the shell using:

1
sh select_podcasts.sh

This will create the basic folder structure that all of your podcasts will go into and compile episode.txt files for each podcast feed in their respective folders wherever you specified podcast_dir to be. To download a particular episode just remove the url for the episode you’d like to download from the episode.txt of the cooresponding podcast. Then simply run:

1
sh bashpodder.sh

If you’d like to execute this using cron in the web interface go to: System -> Advanced -> Cron. Click the add button and use the following command to check for and download new scripts however often you’d like:

1
sh /path/to/FreeNASPodder/bashpodder.sh

Followup:
Good news! I’ve moved all of my subversion repositories over to GitHub, the latest code for FreeNASPodder can be found at http://github.com/bemasher/FreeNASPodder/tree. And even better news: you no longer have to install svn or download each final manually, GitHub has the option to download an archive in tgz or zip format of the latest source files.

Tags: , , , , ,

Power Set Generator

Posted in Code, Computers, Math on March 13th, 2009 by bemasher

Recently I had a bout of programming withdrawal so I set out to write a power-set generator.

So a little background on the power set. The power set of a given set A is the set containing all subsets of A. Suppose that we have a set:

A = \{x,y,z\}

The power set of A would be:

\mathcal{P}(A) = \left\{\emptyset, \{x\}, \{y\}, \{z\}, \{x, y\}, \{x, z\}, \{y, z\}, \{x, y, z\}\right\}\,\!.

Now looking more carefully at the power set of A you’ll notice that it contains 2 to the power of the cardinality of A subsets, always containing the empty set.

2^{|A|} = 8

The code I came up with for this is short and more or less simple:

1
2
3
4
5
6
7
8
9
10
def PowerSet(base):
    power_set = []
    b = len(base)
    map(lambda g: power_set.append(map(lambda x: base[x],
        filter(lambda x: g[x], range(0, b)))),
        map(lambda value: map(lambda x: (value >> x) & 1, range(b - 1, -1, -1)),
        map(lambda value: value ^ (value / 2), range(0, 2**b))))
    return power_set

print PowerSet([1,2,3])

I figured out shortly after I wrote this that I had the right general idea but in this particular case, since I’m not actually using set types… the graycode I’m generating is useless for this sort of thing.

The point of generating graycode for this is that graycode is used for binary counting such that only one digit is changed from one consecutive value to the next. It was originally designed so that mechanical switches in early computers wouldn’t cause a race condition while counting fast enough.

In this particular solution using graycode is useful for only having to add one new element to a set at a time which if I were actually using sets, would be faster, but since I’m not, it isn’t. I’ll probably rewrite it later to make it play nicer with graycode.

The basic procedure here is that given a set A we’re going to count from 0 to 2^|A| – 1 and in binary graycode, the 1’s determine the elements of the base set that will be added as a new set to the power set and 0’s indicate that that element of the base set will be ignored in the current subset.

Tags: , , , , , ,