<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-3911524026180358554</atom:id><lastBuildDate>Mon, 16 Sep 2024 21:46:13 +0000</lastBuildDate><category>c</category><category>grep</category><category>math</category><category>perl</category><category>python</category><category>bash</category><category>find</category><category>php</category><category>awk</category><category>diff</category><category>fftw</category><category>haskell</category><category>java</category><category>mysql</category><category>regex</category><category>ruby</category><category>vim</category><title>XOR Logic</title><description>Coding Hacks and Horrors from a Computer Science Grad Student</description><link>http://xorlogic.blogspot.com/</link><managingEditor>noreply@blogger.com (J)</managingEditor><generator>Blogger</generator><openSearch:totalResults>16</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-7529200076598150684</guid><pubDate>Fri, 29 Aug 2008 14:19:00 +0000</pubDate><atom:updated>2008-08-29T07:20:05.883-07:00</atom:updated><title>Yo.</title><description>Still there?</description><link>http://xorlogic.blogspot.com/2008/08/yo.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-8807050554338831290</guid><pubDate>Wed, 05 Dec 2007 16:35:00 +0000</pubDate><atom:updated>2007-12-05T12:07:49.485-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">perl</category><category domain="http://www.blogger.com/atom/ns#">python</category><title>Perl&#39;s Diamond Operator in Python</title><description>&lt;p&gt;I&#39;m been a full Python convert for over a year now. Perl is just too cumbersome at times. I think the artist who draws XKCD &lt;a href=&quot;http://xkcd.com/353/&quot;&gt;has made the same choice&lt;/a&gt;. The one thing that still takes me back to Perl is the ultra-handy &lt;&gt; &quot;diamond operator&quot;. You can&#39;t deny Perl&#39;s dominance when it comes to string processing. Look at this elegance:&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;&gt;&lt;pre&gt;
#!/usr/bin/perl

while (&lt;&gt;) {
    print
}
&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;Every time I encounter a string processing problem where I have to work with multiple files, I go back to Perl. I didn&#39;t think Python could do this. Python should have the same ability as Perl&#39;s diamond:&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;&gt;&lt;pre&gt;
def diamond():
    &quot;&quot;&quot;
    diamond()
    Pre: Nothing.
    This is my attempt to recreate the very handy diamond operator found in
    Perl, which is my only reason for still using that language.

    To use the code:
    for line in diamond():
        process(line)
    &quot;&quot;&quot;
    import sys
    if len(sys.argv[1:]) &gt; 0:
        for file in sys.argv[1:]:
            if file == &#39;-&#39;:
                for line in sys.stdin:
                    yield line
            else:
                f = open(file, &#39;r&#39;)
                for line in f:
                    yield line
                f.close()
    else:
        for line in sys.stdin:
            yield line&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;What does this do? It checks the &lt;span style=&quot;font-weight:bold;&quot;&gt;sys.argv&lt;/span&gt; variable for file names on the command line and iterates through each line of each file. If it can&#39;t find a file, it defaults to standard input.&lt;/p&gt;

&lt;p&gt;Of course, before I start to write code, I should always use Google first. There exist a module called &quot;&lt;a href=&quot;http://www.python.org/doc/lib/module-fileinput.html&quot;&gt;fileinput&lt;/a&gt;&quot; which does the same thing.&lt;/p&gt;

&lt;p&gt;D&#39;oh! Hey... it&#39;s practice.&lt;/p&gt;</description><link>http://xorlogic.blogspot.com/2007/12/perls-diamond-operator-in-python.html</link><author>noreply@blogger.com (J)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-6400987620784308075</guid><pubDate>Mon, 03 Dec 2007 05:50:00 +0000</pubDate><atom:updated>2007-12-02T21:52:23.737-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">python</category><title>A Losing Strategy</title><description>Today I ran across a year 2000 article in the New York Times titled &lt;a href=&quot;http://query.nytimes.com/gst/fullpage.html?res=9500E3D71F3DF936A15752C0A9669C8B63&quot;&gt;&quot;Paradox in Game Theory: Losing Strategy That Wins.&quot;&lt;/a&gt; Given two games which lose most of the time, a strategy can be devised so that we can win most of the time.

The article has a (fairly) detailed description of two example games:

&lt;blockquote&gt;
&lt;p&gt;The paradox is illustrated by two games played with coins weighted on one side so that they will not fall by chance to heads or tails.&lt;/p&gt;

&lt;p&gt;In game A, a player tosses a single loaded coin and bets on each throw. The probability of winning is less than half.&lt;/p&gt;

&lt;p&gt;In game B, there are two coins and the rules are more complicated. The player tosses either Coin 1, loaded to lose almost all the time or Coin 2 loaded to win more than half the time. He plays Coin 1 if his money is a multiple of a particular whole number, like three.&lt;/p&gt;

&lt;p&gt;If his money cannot be divided evenly by that number, he plays Coin 2. In this setup, the second coin will be played more often than the first.&lt;/p&gt;
&lt;/blockquote&gt;

After reading this story, &lt;a href=&quot;http://pastebin.org/10265&quot;&gt;I wrote a quick Python script to demonstrate this game&lt;/a&gt;. The problem description isn&#39;t definitive on things like the exact probabilities of the coin flips, so we have to make a few assumptions. I set the probability of the coin flip in Game A to p1=0.33, and in Game B, the probability of coin1 to p=0.1 and coin2 to p=0.66. These probabilities are pulled from the air, but they do meet the requirement set forth in the problem description, so they should work.

So the two games alternating should outperform both Game A and Game B when run indivdually. Let&#39;s run the program a few times to see if a combination of Games A and B are better than Game A or Game B.

&lt;code&gt;&lt;pre&gt;

[jcchurch@mcart python]$ python badgames.py 
Game A, 1000 runs:
  Before: 1000 MONEY
  After:  674 MONEY

Game B, 1000 runs:
  Before: 1000 MONEY
  After:  978 MONEY

Alternating: 1000 runs:
  Before: 1000 MONEY
  After:  850 MONEY

[jcchurch@mcart python]$ python badgames.py 
Game A, 1000 runs:
  Before: 1000 MONEY
  After:  734 MONEY

Game B, 1000 runs:
  Before: 1000 MONEY
  After:  890 MONEY

Alternating: 1000 runs:
  Before: 1000 MONEY
  After:  870 MONEY

[jcchurch@mcart python]$ python badgames.py 
Game A, 1000 runs:
  Before: 1000 MONEY
  After:  636 MONEY

Game B, 1000 runs:
  Before: 1000 MONEY
  After:  932 MONEY

Alternating: 1000 runs:
  Before: 1000 MONEY
  After:  820 MONEY

[jcchurch@mcart python]$ python badgames.py 
Game A, 1000 runs:
  Before: 1000 MONEY
  After:  604 MONEY

Game B, 1000 runs:
  Before: 1000 MONEY
  After:  918 MONEY

Alternating: 1000 runs:
  Before: 1000 MONEY
  After:  846 MONEY
&lt;/pre&gt;&lt;/code&gt;

I just ran the problem described in the New York Times 4 times and got 4 negative results. Game B always outperforms Game A and the combined Games A and B. This article looked very interesting and very improbable. If it&#39;s too good to be true, check for yourself.</description><link>http://xorlogic.blogspot.com/2007/12/losing-strategy.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-5097242194800210926</guid><pubDate>Sat, 08 Sep 2007 22:43:00 +0000</pubDate><atom:updated>2007-09-08T16:07:57.881-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">math</category><category domain="http://www.blogger.com/atom/ns#">python</category><title>Three Parts of Division</title><description>I was going to update this blog at some point.&lt;br&gt;
&lt;br&gt;
I&#39;m back to solving problems on &lt;a href=&quot;http://projecteuler.net&quot;&gt;Project Euler&lt;/a&gt;. I&#39;ve solved the easy ones, and now I&#39;m getting around to the medium difficulty problems. I like #26.&lt;br&gt;
&lt;br&gt;
&lt;a href=&quot;http://projecteuler.net/index.php?section=view&amp;id=26&quot;&gt;Problem 26&lt;/a&gt;: Find the value of d &lt; 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.&lt;br&gt;
&lt;br&gt;
That&#39;s kinda interesting. Every time you divide two numbers, there are three parts: The integer part, the non-repeating decimal part, and the repeating decimal part.&lt;br&gt;
&lt;br&gt;
I wrote up this little piece of Python to compute the three parts. It is a forced base-10 long division calculator, and it makes good use of Python&#39;s stings doubling as list, which is a feature that I always thought was nice about Python.&lt;br&gt;
&lt;br&gt;
&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;
def division(num, den):
    ipart = str(num / den);
    fpart = &quot;&quot;
    rpart = &quot;&quot;
    seen  = [ num%den ]
    while num % den != 0:
        num        = (num%den) * 10
        multiple   = num / den
        fpart     += str(multiple)
        num        = num - (den * multiple)
        c = 0
        quit = False
        for i in seen:
            if num == i: # This number has been seen before.
                rpart = fpart[c:] # Make characters from c to end of list part of repeating part
                fpart = fpart[:c] # Truncate fpart
                quit = True
                break
            c = c + 1
        if quit:
            break
        seen += [num]
    return [ipart, fpart, rpart]&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;br&gt;
This method accepts two arguments: An integer numerator and an integer denominator. The return is a list with three items: The whole number part, the non-repeating decimal part, and the repeating decimal part. Each part is a string data type (because sometimes these parts can be excessively long for python&#39;s Integer type.)

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;&gt;&gt;&gt; division(1,4)
[&#39;0&#39;, &#39;25&#39;, &#39;&#39;]
&gt;&gt;&gt; division(1,6)
[&#39;0&#39;, &#39;1&#39;, &#39;6&#39;]
&gt;&gt;&gt; division(1,7)
[&#39;0&#39;, &#39;&#39;, &#39;142857&#39;]&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;</description><link>http://xorlogic.blogspot.com/2007/09/three-parts-of-division.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-3340489209685070429</guid><pubDate>Thu, 26 Apr 2007 05:39:00 +0000</pubDate><atom:updated>2007-04-25T22:55:03.116-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">php</category><title>Converting ISBN13 to ISBN10 in PHP</title><description>&lt;p&gt;I&#39;ve been writing a textbook buyback system for a buddy of mine. He runs a service that purchases textbooks from students at the end of a school semester. He wanted me to write a program to query Amazon.com and estimate the best value to offer a student for his or her book.&lt;/p&gt;

&lt;p&gt;As of January 1, 2007, the agency that controls ISBN codes for all books printed in the world has changed their code format from 10 digits (regular expression /[0-9Xx]{10}/) to 13 digits (regular expression /[0-9]{13}/). Amazon has not updated their Web E-Commerce API to accommodate this change in standard. Thus, any time I get an 13-digits ISBN, I must convert it to the older 10-digits standard.&lt;/p&gt;

&lt;p&gt;When &quot;Googling&quot; for solutions to this problem, I found several, but I decided to write this one myself.&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;
// Converts ISBN-13 to ISBN-10
// Leaves ISBN-10 numbers (or anything else not matching 13 consecutive numbers) alone
function ISBN13toISBN10($isbn) {
    if (preg_match(&#39;/^\d{3}(\d{9})\d$/&#39;, $isbn, $m)) {
        $sequence = $m[1];
        $sum = 0;
        $mul = 10;
        for ($i = 0; $i &lt; 9; $i++) {
            $sum = $sum + ($mul * (int) $sequence{$i});
            $mul--;
        }
        $mod = 11 - ($sum%11);
        if ($mod == 10) {
            $mod = &quot;X&quot;;
        }
        else if ($mod == 11) {
            $mod = 0;
        }
        $isbn = $sequence.$mod;
    }
    return $isbn;
}
&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;</description><link>http://xorlogic.blogspot.com/2007/04/converting-isbn13-to-isbn10-in-php.html</link><author>noreply@blogger.com (J)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-2012910323845233531</guid><pubDate>Fri, 23 Mar 2007 04:13:00 +0000</pubDate><atom:updated>2007-03-22T22:16:16.306-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">mysql</category><category domain="http://www.blogger.com/atom/ns#">php</category><title>Handling Multiple MySQL Queries - &quot;AS&quot; labels</title><description>&lt;p&gt;I&#39;m working on a project for the School of Pharmacy on campus. They wanted me to write a program that pulls numbers from a database on Marijuana into a nicely formatted report that they could print off and send to government agencies that are interested in the data. One of the reports requires me to pull hundreds of individually calculated items from a MySQL database. A single MySQL query isn&#39;t able to do the job. When this report is completed, there will probably 75 to 100 queries. To think that this quarterly report has been done manually for almost 2 decades overwhelms me as I try to write this report software. I&#39;m trying to reduce several weeks of work to prepare this report to a few seconds.&lt;/p&gt;

&lt;p&gt;The entire project is done in PHP and MySQL. PHP and MySQL go hand-in-hand, but every time I write a query, I can&#39;t help but wonder how this could be made easier. Pulling one value out of a query looks like spaghetti code. Pulling 300 values from 100 different queries is an explosion of crappy code. MySQL queries required for this report look like this:&lt;/p&gt;

&lt;pre&gt;SELECT THC FROM samples HAVING MAX(THC);&lt;/pre&gt;

&lt;p&gt;This is just one query that will find the one sample in the database with the highest THC composition and report what that composition value is. There are hundreds more queries in the report similar to this one. Typically, when you run a MySQL query from PHP, here are the steps you have to take:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Format the query command.
&lt;li&gt;Execute the query command.
&lt;li&gt;Retrieve the first row of results from the successful execution (usually in the form of an associative array).
&lt;li&gt;Transfer those values from the array to variables that actually mean something to the nature of the program (like $max_thc_composition).
&lt;/ol&gt;

&lt;p&gt;If I have 100 queries, and I have to perform the same 4 steps for each query, that&#39;s 400 lines of code. Obviously, as any freshmen computer science instructor will tell you (because I am one), this needs to be regulated to a function. But how do you specify a query (which can return more than one value) and the variables associated with those results in a concise manner? If the function doesn&#39;t know the variables names going into the function, it can&#39;t assign those values coming out of the function.&lt;/p&gt;

&lt;pre&gt;SELECT THC AS max_thc_composition FROM samples HAVING MAX(THC);&lt;/pre&gt;

&lt;p&gt;The &quot;AS&quot; expression in MySQL will rename a column into something else. It can also be used to uniquely label a query. This may not seem useful in a single call, but when you have a few 100 calls to make, it&#39;s a real time saver.&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;    //runQueries: Runs multiple queries.
    // Pre: An array of MySQL single-result queries where
    // each result has a unique &quot;AS&quot; expression.
    // Post: An associative array populated with all of those values.
    function runQueries($sqls) {
        $report = array();
        //Execute each SQL query and drop the result in the report array
        foreach ($sqls as $query) {
            $result = mysql_query($query) or die(&quot;Query Failed: $query Reason: &quot;.mysql_error());
            $row    = mysql_fetch_assoc($result);

            // Essentially, for each &quot;AS&quot; expression in the query,
            // look for that result in row returned and pull that value out if it exist.
            // If it does not exist, just give it a value of 0.
            preg_match_all(&quot;/ AS (\w+)/&quot;, $query, $keys);
            foreach ($keys[1] as $key)
                if (isset($row[$key]))
                    $report[$key] = $row[$key];
                else
                    $report[$key] = 0;
        }
        return $report;
    }&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;This function takes an array of MySQL single-result query strings, where each result has an &quot;AS&quot; label identifying what this result means. This method executes each query and drops the result into a associative array where the &quot;AS&quot; labels double as the array keys. And of course, it uses a regular expression.&lt;/p&gt;

&lt;p&gt;I&#39;m suppose to be teaching a class on Python programming in the fall. Have you noticed that I haven&#39;t featured a Python script in this blog series yet? That bothers me.&lt;/p&gt;</description><link>http://xorlogic.blogspot.com/2007/03/handling-multiple-mysql-queries-as.html</link><author>noreply@blogger.com (J)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-9166447889968746280</guid><pubDate>Thu, 22 Feb 2007 20:09:00 +0000</pubDate><atom:updated>2007-02-22T12:17:00.724-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">bash</category><category domain="http://www.blogger.com/atom/ns#">find</category><category domain="http://www.blogger.com/atom/ns#">grep</category><title>Finding lost files</title><description>&lt;p&gt;So a student e-mails me today saying that he doesn&#39;t have a grade recorded for one of his programming assignments. I check his folder of turned-in assignments and I can&#39;t find it.&lt;/p&gt;

&lt;p&gt;Who knows? Maybe I just dropped his homework in a different folder by mistake. Checking through everyone&#39;s folders for his will take me a while. I make all of my students put their e-mail address in the comments of their code, so I just run a search on all the *.java files on my computer that have a certain e-mail address with this handy line:&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;for i in $(find . -name *.java); do grep -H &#39;emailName&#39; $i; done&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

(Replace &#39;emailName&#39; with the descriptive feature of the file you are looking for.)

&lt;p&gt;I still can&#39;t find his homework.&lt;/p&gt;</description><link>http://xorlogic.blogspot.com/2007/02/finding-lost-files.html</link><author>noreply@blogger.com (J)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-600135068438098395</guid><pubDate>Thu, 25 Jan 2007 06:18:00 +0000</pubDate><atom:updated>2007-01-24T22:52:34.535-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">awk</category><category domain="http://www.blogger.com/atom/ns#">grep</category><category domain="http://www.blogger.com/atom/ns#">perl</category><category domain="http://www.blogger.com/atom/ns#">regex</category><title>Regular Expression Speeds</title><description>&lt;p&gt;I read a paper today titled &lt;a href=&quot;http://swtch.com/~rsc/regexp/regexp1.html&quot;&gt;&quot;Regular Expression Matching Can Be Simple And Fast&quot;&lt;/a&gt;. I thought his results were interesting enough to compare to my own regular expression engine. (Yes, I&#39;m dorky enough to have my own engine.) I call my program &quot;chrep&quot;, which is short for &quot;Church&#39;s Regular Expression Parser&quot;.&lt;/p&gt;

&lt;p&gt;Below, I&#39;ve tested four engines with the string &quot;aaaaaaaaaaaaaaaaaaaa&quot; against the expression &quot;a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaa&quot; (which should always return a successful match). (Note: Sorry if you aren&#39;t able to read the entire command. My CSS-foo sucks and you probably have to read the source code.)&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:Courier,Ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;jcchurch@linux:~&gt; time echo &quot;aaaaaaaaaaaaaaaaaaaa&quot; | chrep &#39;a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaa&#39;
[aaaaaaaaaaaaaaaaaaaa] in : aaaaaaaaaaaaaaaaaaaa

real    0m5.137s
user    0m2.964s
sys     0m0.012s&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

5 seconds. Not bad, but not really all that good. The next program tested was egrep:

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;jcchurch@linux:~&gt; time echo &quot;aaaaaaaaaaaaaaaaaaaa&quot; | egrep &#39;a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaa&#39;
aaaaaaaaaaaaaaaaaaaa

real    0m0.055s
user    0m0.008s
sys     0m0.008s&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

0.055 seconds. Roughly 100 times faster than my parser. The speed benchmark has been set pretty high. The next test is the old, reliable AWK:

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;jcchurch@linux:~&gt; time echo &quot;aaaaaaaaaaaaaaaaaaaa&quot; | awk &#39;/a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaa/{print}&#39;
aaaaaaaaaaaaaaaaaaaa

real    0m0.049s
user    0m0.004s
sys     0m0.004s&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

0.049 seconds. Still making my program look bad. Finally, I wanted to test Perl:

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;jcchurch@linux:~&gt; time echo &quot;aaaaaaaaaaaaaaaaaaaa&quot; | perl -ne&#39;print if /a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaa/&#39;
aaaaaaaaaaaaaaaaaaaa

real    0m0.393s
user    0m0.328s
sys     0m0.008s&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;Perl takes almost a half second. That&#39;s horribly slow compared to grep and awk, but still 13 times faster than my parser.&lt;/p&gt;

&lt;p&gt;My parser (&#39;cause I know you are wondering) is a simple interpretative, recursive decent parser. There is no compiling of the expression, which I know would speed things up. I&#39;m glad to see that I&#39;m not too far behind the competition, and this will encourage me to make those benchmarks.&lt;p&gt;</description><link>http://xorlogic.blogspot.com/2007/01/regular-expression-speeds.html</link><author>noreply@blogger.com (J)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-5893374913989703253</guid><pubDate>Wed, 10 Jan 2007 04:15:00 +0000</pubDate><atom:updated>2007-09-08T16:06:28.569-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">c</category><category domain="http://www.blogger.com/atom/ns#">math</category><title>XOR Logic</title><description>&lt;p&gt;It&#39;s winter break, so I have had less &quot;essential&quot; programming to do. I have been wasting time on &lt;a href=&quot;http://www.projecteuler.net&quot;&gt;projecteuler.net&lt;/a&gt;. This site is an on-line competition devoted to solving very difficult math problems of the type that require programs to solve. I&#39;ve been on the site for about two weeks and I&#39;ve solved a third of the problems.&lt;/p&gt;

&lt;p&gt;The problem that has interested me the most is &lt;a href=&quot;http://www.projecteuler.net/index.php?section=view&amp;id=59&quot;&gt;problem #59: Brute force decryption using XOR Logic&lt;/a&gt;. I can&#39;t talk about the solution here, because that would only help people who are trying to win the competition by Googling answers, but I can talk about XOR Logic.&lt;/p&gt;

&lt;p&gt;XOR Logic is the comparison between two items where the results is true if one is true and the other isn&#39;t. If both are false or if both are true, the result is false. In programming terms, we think of it like this:&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;unsigned char a, b, c;
scanf(&quot;%c&quot;,&amp;a);
scanf(&quot;%c&quot;,&amp;b);
c = (~a&amp;b)|(a&amp;~b); // XOR Logic Here!
printf(&quot;%c(%d) -&gt; %c(%d) -&gt; %c(%d)\n&quot;, a,a, b,b, c,c);
&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;In this example, we have two terms: a and b. We wish to XOR these two items to make a result c. Using C&#39;s bitwise and &quot;&amp;&quot;, bitwise or &quot;|&quot;, and bitwise negate &quot;~&quot;, we can create the XOR gate. We have two inputs, and one has to be true and the other must be false for the result to be true. It doesn&#39;t matter the order. Output c is true if input a is true and input b is false or if a is false and b is true. In fact, that sentence is pretty much how I programmed it.&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;English:
Output c is true if input a is true and input b is false
or if a is false and b is true.

English and C:
Output c is true [c = ] if [(] input a is true [a] and(&amp;)
input b is false[~b] [)] or[|] if[(] a is false[~a] and[&amp;]
b is true[b] [)].[;]

C:
c = (~a&amp;b)|(a&amp;~b);&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;So how is this useful? Cryptography is based on the practice of taking a message, &lt;span style=&quot;font-style:italic;&quot;&gt;encrypting&lt;/span&gt; it, then taking the encrypted message and &lt;span style=&quot;font-style:italic;&quot;&gt;decrypting&lt;/span&gt; it. The great thing about XOR logic is that it is used for both encrypting and decrypting text.&lt;p&gt;

&lt;p&gt;Let&#39;s say that your secret message consist of one character: &quot;L&quot;. &quot;L&quot; on the ASCII table is decimal 76 or binary &quot;01001100&quot;. You need a secret password to encrypt the letter &quot;L&quot;. For that, we&#39;ll use &quot;!&quot; which is decimal 33 or binary &quot;00100001&quot;.&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;01001100 L (76)
00100001 ! (33)
-------- XOR
01101101 m (109)&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&quot;L&quot; has now been encrypted. The encrypted text is now &quot;m&quot;. Using our password &quot;!&quot;, we can now decrypt the text:

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1em;&quot;  &gt;&lt;pre&gt;01101101 m (109)
00100001 ! (33)
-------- XOR
01001100 L (76)&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

We just decrypted our message &quot;m&quot; using the same XOR method and password &quot;!&quot; that we used to encrypt the message. XOR Logic is pretty useful because it provides the method to both encrypt and decrypt messages quickly.&lt;span style=&quot;font-style:italic;&quot;&gt;&lt;/span&gt;</description><link>http://xorlogic.blogspot.com/2007/01/xor-logic.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-2464850943846619019</guid><pubDate>Wed, 13 Dec 2006 09:46:00 +0000</pubDate><atom:updated>2007-09-08T16:06:49.402-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">c</category><category domain="http://www.blogger.com/atom/ns#">haskell</category><category domain="http://www.blogger.com/atom/ns#">math</category><title>Matrix Fun in Haskell</title><description>&lt;p&gt;I have always thought that the snobbiest of programmers are those that use Haskell, which is a language so academic that I&#39;m not sure if it&#39;s been used outside academia. Haskell is known for what it doesn&#39;t have. Haskell doesn&#39;t have the same loop structure. It doesn&#39;t have variables. It doesn&#39;t have the imperative design like most languages. I like Haskell. Any time I need to jump on a math program, I usually solve it in Haskell first, then the language I need second.&lt;/p&gt;

&lt;p&gt;A friend of mine is a physics Ph.D. student who is trying to learn C. He wanted to write a program to find all of the 2-by-2 determinants found in a 4-by-4 matrix. There are 36 total. He had his own ideas on how to solve this, but I still think the quickest way is to brute force all of the possibilities.&lt;/p&gt;

&lt;p&gt;The following patches of Haskell and C are almost identical. They use the exact same variables  (&quot;labels&quot; for the Haskell code) to accomplish the same task. The Haskell code returns an array of floats, where the C code prints each of the 36 determinants.&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1.25em;&quot;  &gt;&lt;pre&gt;twoByTwo :: [[Float]] -&gt; [Float]
twoByTwo m = concat (map(\i-&gt;
                 concat (map(\j-&gt;
                     concat (map(\p-&gt;
                         map(\q-&gt;
                             (m!!i!!j)*(m!!p!!q)-(m!!i!!q)*(m!!p!!j)
                         )[(j+1)..(n-1)]
                     )[(i+1)..(n-1)])
                 )[0..(n-2)])
             )[0..(n-2)])
             where
                 n = length m&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

Yes, Haskell fans, there is a quadruple-nested lambda expression there, which does seem a little confusing. It&#39;s short and elegant, which is why Haskell reminds me of Python.

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:1.25em;&quot;  &gt;&lt;pre&gt;void twoByTwo(float *m, int n) {
    int i, j, p, q;
    for (i = 0; i &lt; n-1; i++)
        for (j = 0; j &lt; n-1; j++)
            for (p = i+1; p &lt; n; p++)
                for (q = j+1; q &lt; n; q++)
                    printf(&quot;%3.1f\n&quot;, m[i*n+j]*m[p*n+q] - m[i*n+q]*m[p*n+j]);
}&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

No one ever said C was pretty. I also wrote a recursive Matrix determinant algorithm in Haskell, but I may save that for another time.</description><link>http://xorlogic.blogspot.com/2006/12/matrix-fun-in-haskell.html</link><author>noreply@blogger.com (J)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-5649767792595432363</guid><pubDate>Wed, 22 Nov 2006 06:02:00 +0000</pubDate><atom:updated>2006-11-23T19:27:47.213-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby</category><title>A Review of MySpace Passwords using Ruby</title><description>&lt;p&gt;Over on the site &lt;a href=&quot;http://reddit.com&quot;&gt;Reddit&lt;/a&gt;, someone posted a link to some 50,000+ MySpace user e-mails and passwords from a phishing site. I&#39;m not going to post the link to those passwords. You&#39;ll have to find it yourself.&lt;/p&gt;

&lt;p&gt;I wrote a quick Ruby script to pour through the text. Normally I would have done this in Perl, but Ruby seems to be the language du jour.&lt;/p&gt;

&lt;p&gt;Here&#39;s a breakdown of things I noticed about people&#39;s passwords. I tallied the number of passwords that had a lowercase letter, uppercase letter, a number, or a symbol in the password itself. I also checked for usernames that were the same as their passwords, and passwords that followed the pattern of &quot;word-then-number&quot;.&lt;/p&gt;

&lt;p&gt;total: 52692&lt;br/&gt;
lowercase: 50818 (96.44%)&lt;br/&gt;
numbers: 42570 (80.79%)&lt;br/&gt;
symbols: 2959 (5.62%)&lt;br/&gt;
uppercase: 2330 (4.21%)&lt;br/&gt;
Same as username: 197 (0.37%)&lt;br/&gt;
Word-Number pattern: 35800 (67.94%)&lt;/p&gt;

&lt;p&gt;Almost everyone is using lowercase letters in their password. 4 out of every 5 users are using numbers. Less than 6% of all users are using symbols or uppercase letters in their passwords. Almost 1/3rd of a percent of MySpace&#39;s users are dumb enough to use their e-mail&#39;s user name as their password. Two-thirds of users use a &quot;word followed by a number&quot; pattern for their password. If I were to write a password cracker, I would first try to hack accounts that followed this very common pattern. (I must admit: most of my own passwords follow this pattern.)&lt;/p&gt;

&lt;p&gt;I went on to check for the most common word usage. This was done by stripping out any non-letter characters and dumping the results in a hash table.&lt;/p&gt;

&lt;p&gt;password  334&lt;br/&gt;
a  299 (The single letter &#39;a&#39; is commonly used with a sequence of numbers.)&lt;br/&gt;
soccer  285&lt;br/&gt;
iloveyou  273&lt;br/&gt;
fuckyou  173&lt;br/&gt;
love  139&lt;br/&gt;
abc  137&lt;br/&gt;
football  135&lt;br/&gt;
baseball  125&lt;br/&gt;
myspace  122&lt;/p&gt;

&lt;p&gt;There are a few surprises in this list. Why on earth would anyone make their password &quot;password&quot;? For that matter, if you are on MySpace, why make your password &quot;myspace&quot;. There seem to be a lot of sports fans on MySpace. &quot;soccer&quot;,&quot;baseball&quot;, and &quot;football&quot; all appear in the top ten most common words. There is also a love/hate drama going on between many users. &quot;love&quot;, &quot;iloveyou&quot; and &quot;fuckyou&quot; are common choices for passwords.&lt;/p&gt;

&lt;p&gt;So where&#39;s the code?!?&lt;/p&gt;

&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;pre&gt;#!/usr/bin/ruby

file = ARGV[0]

total     = 0
wordnum   = 0
numbers   = 0
lowercase = 0
uppercase = 0
symbol    = 0
samename  = 0

words = Hash.new

IO.foreach(file) do |line|

    line.strip!

    (user,password) = line.split /:/
    next if password == nil

    (name,domain)   = user.split /@/
    total = total + 1

    if password =~ /^[a-zA-Z]+[0-9]+$/
        wordnum = wordnum + 1
    end

    if password =~ /[0-9]/
        numbers = numbers + 1
    end

    if password =~ /[a-z]/
        lowercase = lowercase + 1
    end

    if password =~ /[A-Z]/
        uppercase = uppercase + 1
    end

    if password =~ /[`~!@#\$%^&amp;*()_\+\-\\=]/
        symbol = symbol + 1
    end

    if password == name
        samename = samename + 1
    end

    lettersonly = password.gsub(/[^a-zA-Z]/, &#39;&#39;)

    next if lettersonly =~ /^$/

    if false == words.key?(lettersonly)
        words[lettersonly] = 1
    else
        words[lettersonly] = words[lettersonly] + 1
    end

end

puts &quot;total:               #{total}&quot;
puts &quot;numbers:             #{numbers}&quot;
puts &quot;lowercase:           #{lowercase}&quot;
puts &quot;uppercase:           #{uppercase}&quot;
puts &quot;symbols:             #{symbol}&quot;
puts &quot;Same as username:    #{samename}&quot;
puts &quot;Word-Number pattern: #{wordnum}&quot;

words_ary = words.sort {|a,b| b[1]&lt;=&gt;a[1]}

10.times do |i|
    puts &quot;#{words_ary[i][0]}  #{words_ary[i][1]}&quot;
end&lt;/pre&gt;&lt;/div&gt;</description><link>http://xorlogic.blogspot.com/2006/11/review-of-myspace-passwords-using-ruby.html</link><author>noreply@blogger.com (J)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-7707378167022571034</guid><pubDate>Tue, 14 Nov 2006 06:34:00 +0000</pubDate><atom:updated>2006-11-14T10:33:31.076-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">java</category><title>Bits of Java</title><description>&lt;p&gt;Note: Today&#39;s coding gem is one that probably most Java programmers have experienced at least once.&lt;/p&gt;

&lt;p&gt;A student of mine came to me with a problem from a different class she was taking. She had to write a program to generate truth tables for certain electrical gates. Because she&#39;s in my Java class, Java was her choice to complete the assignment. While I teach Java, I&#39;m very unfamiliar with many of its low level aspects. This was a unique challenge for me.&lt;/p&gt;

&lt;p&gt;These particular electrical gates required 4 binary inputs. How could I quickly generate all 16 possible binary combinations of 1&#39;s and 0&#39;s without resorting to spaghetti code? My first thought was to write a simple &#39;for&#39; loop to generate the binary bits.&lt;/p&gt;

&lt;p&gt;Solution #1:
&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;pre&gt;    for (int i = 0; i &lt; 16; i++) { // Combination Number
        for (int j = 0; j &lt; 4; j++) { // Nth bit in combination
            int bit = (int) Math.pow(2,j);
            System.out.print( (i&amp;bit)/bit );
        } // End For
        System.out.println(&quot;&quot;);
    } // End For&lt;/pre&gt;&lt;/div&gt;&lt;/p&gt;

&lt;p&gt;It just looks ugly, but it&#39;s mathematically correct (or at least plausible). We call &quot;Math.pow&quot;, convert double to integer, there seems to be division taking place (but it&#39;s anyone&#39;s guess as to why), and we still have to perform the logical &quot;and&quot; (&lt;span style=&quot;font-weight:bold;&quot;&gt;&amp;&lt;/span&gt;). Bleh! How is anyone suppose to understand what&#39;s going on?&lt;/p&gt;

&lt;p&gt;Solution #2:
&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;pre&gt;    for (int i = 0; i &lt; 16; i++) { // Combination Number
        for (int j = 0; j &lt; 4; j++) { // Nth bit in combination
            System.out.print( (i&gt;&gt;&gt;j)&amp;1 );
        } // End For
        System.out.println(&quot;&quot;);
    } // End For&lt;/pre&gt;&lt;/div&gt;&lt;/p&gt;

&lt;p&gt;It&#39;s a little cleaner. There&#39;s a unsigned shift which is then compared and-wise to the number 1. It&#39;s only two operations, both of which happen at the binary level. Works for me. Too bad I figured this out after she came up with her own solution using large, ugly 2D-arrays.&lt;/p&gt;</description><link>http://xorlogic.blogspot.com/2006/11/bits-of-java.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-6107328065939197475</guid><pubDate>Fri, 03 Nov 2006 03:34:00 +0000</pubDate><atom:updated>2006-11-02T19:54:42.900-08:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">c</category><category domain="http://www.blogger.com/atom/ns#">fftw</category><title>The Impossible FFTW Bug</title><description>Ever had a computer bug that you spent weeks working on it? You might try every trick you know to solve it: debugging messages, profilers, Google, professors, coworkers, fellow students. You might try to explain the code to someone who doesn&#39;t even program just so you have to describe the logic in simple terms. Nothing seems to fix the problem.

&lt;p&gt;I had this bug in my code for about two weeks. I had to write a program to compute the 2 dimensional FFT of an image. That&#39;s it. I&#39;ll just use FFTW, the most popular open source library for computing FFTs.

&lt;p&gt;The Wrong Solution for computing FFTs with FFTW:

&lt;div style=&quot;width:100%; background: rgb(255, 180, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:100%;&quot;  &gt;&lt;pre&gt;int j;
fftw_plan myplan;
fftw_complex in[x*y], out[x*y];

for (j = 0; j &lt; x*y; j++) {
    in[j][0] = r[j];
    in[j][1] = i[j];
} // End For

myplan = (dir == 1)? fftw_plan_dft_2d(x, y, in, out, FFTW_FORWARD,  FFTW_MEASURE) :
                     fftw_plan_dft_2d(x, y, in, out, FFTW_BACKWARD, FFTW_MEASURE) ;

fftw_execute(myplan);&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;In these few lines of code lies a problem that I&#39;ve spent weeks trying to find. There are no syntax errors, nor are there logic errors. Every time I ran this code, the result would be all zeros. If I ran it multiple times, I got the correct results for every execution after the first. I dropped the data into a prepared array, made a plan (as defined by the FFTW C library), then executed that library. Should work, right? Wrong.

&lt;p&gt;The Correct Solution for computing FFTs with FFTW:
&lt;div style=&quot;width:100%; background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:100%;&quot;  &gt;&lt;pre&gt;int j;
fftw_plan myplan;
fftw_complex in[x*y], out[x*y];

myplan = (dir == 1)? fftw_plan_dft_2d(x, y, in, out, FFTW_FORWARD,  FFTW_MEASURE) :
                     fftw_plan_dft_2d(x, y, in, out, FFTW_BACKWARD, FFTW_MEASURE) ;

for (j = 0; j &lt; x*y; j++) {
    in[j][0] = r[j];
    in[j][1] = i[j];
} // End For

fftw_execute(myplan);&lt;/pre&gt;&lt;/span&gt;&lt;/div&gt;

&lt;p&gt;I found buried in the &lt;a href=&quot;http://www.fftw.org/faq/section3.html#allzero&quot;&gt;FFTW FAQ&lt;/a&gt; that I&#39;m suppose to make a plan before giving it the data. I switched two sets of lines around and everything magically works for reasons I fail to understand. Let this be a lesson to anyone having to use FFTW.</description><link>http://xorlogic.blogspot.com/2006/11/impossible-fftw-bug.html</link><author>noreply@blogger.com (J)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-7648684831024882560</guid><pubDate>Tue, 24 Oct 2006 20:24:00 +0000</pubDate><atom:updated>2006-10-24T13:36:21.155-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">perl</category><category domain="http://www.blogger.com/atom/ns#">vim</category><title>vi Number Sequence Trick</title><description>I&#39;m a vim user.

Often times in my editing, I want to number some of the lines in a file from 1 to some ending number. It might be only a few lines, or it might be thousands. To save myself some carpal tunnel, I wrote one line of perl to do the job. This program will pass a block of lines in whatever file you are editing to a one line perl script which will number the lines starting with 1 and drop that text back into the editor:

&lt;table style=&quot;width: 100%;&quot;&gt;&lt;tbody&gt;&lt;tr&gt;
&lt;td style=&quot;background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:100%;&quot;  &gt;&lt;pre&gt;:x,y!perl -ne&#39;print &quot;$.  $_&quot;;&#39;&lt;/pre&gt;&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;

In this example, x is the starting line number and y is the ending line number. That&#39;s it!</description><link>http://xorlogic.blogspot.com/2006/10/vi-number-sequence-trick.html</link><author>noreply@blogger.com (J)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-5852129474886903548</guid><pubDate>Sun, 15 Oct 2006 08:33:00 +0000</pubDate><atom:updated>2006-10-24T13:42:10.549-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">c</category><title>File Character Frequency</title><description>In my machine learning course, our first project was to write a program to sort e-mail into nine class labels A through I. In my implementation after every e-mail was classified, I would write a single character to the screen. There were several thousand of e-mails that needed sorting, so I needed a program that displayed a final tally of the results.

&lt;p&gt;
I could have easily built something into the program I was writing, but I thought something more general purpose would be useful. I quickly wrote the following code. It takes a tally of each character in a file and then uses a quick sort to sort the data and then prints the results. I even added a switch to ignore whitespace characters.

&lt;p&gt;
&lt;table style=&quot;width: 100%;&quot;&gt;&lt;tbody&gt;&lt;tr&gt;
&lt;td style=&quot;background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:85%;&quot;  &gt;&lt;pre&gt;#include &amp;#60;stdio.h&amp;#62;

/* Author:      James Church
 * Date:        09/11/06
 * Program:     charfreq
 * Version:     0.3
 * Description: Takes a single file from the command line as input and
 *              reports the character frequence of each character in order
 *              from most common to least common.
 *
 * Copyright © 2006 Free Software Foundation, Inc.
 *
 * Copying and distribution of this file, with or without modification,
 * are permitted in any medium without royalty provided the copyright
 * notice and this notice are preserved.
 */

#define CHARRANGE 256

typedef struct _charcount {
    unsigned char c;
    long          count;
} CharCount;

void quicksort (CharCount *a, int i, int j);
int  partition (CharCount *a, int i, int j);

int main(int argc, char **argv) {
    int            i;
    unsigned char  c;
    CharCount      freq[CHARRANGE];
    FILE          *file;
    int           ignore_whitespace = 0;
    int           argparse = 1;

    if (argc == 1) {
        printf(&quot;\nUsage: %s [-s] [filename] - Reports character frequence of file.\n&quot;, argv[0]);
        printf(&quot; -s  Ignores whitespace (optional)\n&quot;);
        return 0;
    } // End If

    if (strcmp(&quot;-s&quot;, argv[argparse]) == 0) {
        ignore_whitespace = 1;
        argparse++;
    } // End If

    if ((file = fopen(argv[argparse], &quot;r&quot;)) == NULL) {
        printf(&quot;Error: Cannot open %s\n&quot;, argv[1]);
        return 0;
    } // End If
    argparse++;

    for (i = 0; i &lt; CHARRANGE; i++) {
        freq[i].c     = (unsigned char) i;
        freq[i].count = 0;
    } // End For

    while (1) {
        fread (&amp;c, sizeof(unsigned char), 1, file);
        if (feof(file)) break;

        if (ignore_whitespace &amp;&amp; (c == &#39; &#39; || c == &#39;\t&#39; || c == &#39;\r&#39; || c == &#39;\n&#39;))
            continue;

        freq[c].count++;
    } // End While

    quicksort(freq, 0, CHARRANGE-1);

    for (i = CHARRANGE-1; i &gt;= 0; i--) {
        if (freq[i].count == 0) break;

        printf(&quot;%c[%3d]: %d\n&quot;, freq[i].c, freq[i].c, freq[i].count);
    } // End For

    fclose(file);
    return 0;
} // End Main

void quicksort (CharCount *a, int i, int j) {
    int p;

    if (i &lt; j) {
        p = partition (a, i, j);
        quicksort (a, i, p-1);
        quicksort (a, p+1, j);
    } /* End If */
} /* End mergesort */

int partition (CharCount *a, int i, int j) {
    int val = a[i].count;
    int h   = i;
    int k;
    CharCount temp;

    for (k = i+1; k &lt;= j; k++)
        if (a[k].count &lt; val) {
            h++;
            temp = a[h];
            a[h] = a[k];
            a[k] = temp;
        } /* End If */

    temp = a[i];
    a[i] = a[h];
    a[h] = temp;
    return h;
} /* End partition */&lt;/pre&gt;&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;
Enjoy!</description><link>http://xorlogic.blogspot.com/2006/10/file-character-frequency.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-3911524026180358554.post-5333639877948757288</guid><pubDate>Thu, 12 Oct 2006 08:00:00 +0000</pubDate><atom:updated>2006-10-15T01:05:28.440-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">bash</category><category domain="http://www.blogger.com/atom/ns#">diff</category><category domain="http://www.blogger.com/atom/ns#">find</category><category domain="http://www.blogger.com/atom/ns#">grep</category><title>Finding Identical Files using bash and find</title><description>I wanted to start a blog of all the little bits of code featuring tricks that I&#39;ve learned over the years. I don&#39;t know how often I&#39;ll update this blog, but any time I use a bit of code to complete a complicated task, I&#39;ll describe the task and show the code used to solve it.

My first example will be a identical file finder. In my class on Java programming that I teach, I suspected two students of turning in the exact same work. As I was grading, I had seen some identical code elsewhere, but I couldn&#39;t remember. I keep all the students work in different directories on my office computer just in case I need to look at their old homework solutions. Rather than look at every solution manually for an identical file, I wrote this little bash script to do the work for me:

&lt;table style=&quot;width: 100%;&quot;&gt;&lt;tbody&gt;&lt;tr&gt;
&lt;td style=&quot;background: rgb(255, 255, 180) none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;&quot;&gt;&lt;span style=&quot;color: rgb(0, 0, 0);font-family:courier,ariel;font-size:85%;&quot;  &gt;&lt;pre&gt;#!/bin/bash

if [ $# -eq 2 ]
then
    for i in $(find . -name $1); do diff -s $i $2 | grep -v differ; done
else
    echo &quot;USAGE: findIdent [SOME FILE EXPRESSION] [SOME FILE]&quot;
fi&lt;/pre&gt;&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
This script &quot;findIdent&quot; takes two arguments: a file pattern (say... &quot;*.mp3&quot;) and the file that you want to see if duplicates exist.

So did I find any duplicates of students&#39; work? No. Turns out I just found some very similar code and it was nothing to worry about. But I kept this script in case I ever need it again.</description><link>http://xorlogic.blogspot.com/2006/10/finding-identical-files-using-bash-and.html</link><author>noreply@blogger.com (J)</author><thr:total>0</thr:total></item></channel></rss>