Archive

Posts Tagged ‘programming’

1,000,000th Fibonacci Number One-Liner in C

September 9th, 2009

This is possibly the best one-liner I’ve ever written:

gcc -x c -o /tmp/out - -lgmp <<< '#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <gmp.h>
void omg_i_love_leonardo_of_pisa(uint32_t num, mpz_t * result) { mpz_t retval, last, tmp; mpz_init(retval);
 mpz_init(last); mpz_init(tmp); uint32_t i = 1; if(num == 0) return; mpz_set_ui(retval, 1U);
mpz_set_ui(last, 0U); for(; i < num; i++) { mpz_set(tmp, retval); mpz_add(retval, retval, last);
mpz_set(last, tmp); } mpz_set(*result, retval); } int main() { uint32_t num; mpz_t fibo; mpz_init(fibo);
omg_i_love_leonardo_of_pisa(1000001, &fibo); mpz_out_str(stdout, 10, fibo); printf("\n"); return 1; }
' && time /tmp/out

It compiles a C program given from STDIN, puts it in /tmp/out, and runs it with time to find the time it takes to run. It generates the 1,000,000th Fibonacci number. Try it!


Uncategorized , , , , , , ,

GitHub Widget for Wordpress

February 28th, 2009

For all you coders out there wanting to show off all those forked repositories, the github-widget is for you.

There are a few ways to install.

  1. Download from here.  The most recent stable release will be available.  As of this writing, it’s REL-1.3.
  2. Clone the git repository: git clone git://github.com/hank/github-widget.git
  3. Get it through Wordpress (Work in Progress)

If you use one of the first 2 methods, just drop the resultant directory into wp-content/plugins/.

Using any of the three methods, after you have it installed, go to the Admin panel, Plugins -> Installed.  Then, activate the plugin.  Then, go to Appearance -> Widgets.  Put it into a sidebar, and go look at the results.

Please report any errors or problems as a comment to this post.

UPDATE: I just found out that my minimal searching for ‘Github’ in the plugins area, which found no results when I tried it, was insufficient.  I should have used Google.  Oh, well – at least I know how a widget works now!


Uncategorized , , , , , ,

My favorite program

April 26th, 2008

    \  |  /
     /```\               \/ \/
  _ |     | _                           /\
  _ |     | _                          //\\
     \___/                             //\\
    /  |  \                             ||
                                        ||
                                       /||\
+++++++                           +++[>+++++++>+++                +++++
+>+++>+\>                       +++++++++++>++++++++            ++++<<<
<<<-]>+++.>>     @__         ++.<<+++.>>>>+.>--.<-----        -----.<<.
<-.>>>>-------   /  \     .++++++.<<<.<<-.>>>>.>---------    .+++++++.<
.>++++++.<<.<<--.>>>++++.+++..<<.<++.>>>+++.>----.<<<.<<++.>>>>--------
------.>---..+++++++.<<<.<<.>>>>++++.<<<<--------------.?>>>.__________

Hint: It’s code, and the language it’s in has a dirty word in the name


Uncategorized

Finding bad JPEGs with Xorg hacks in Ubuntu

November 25th, 2007

So, I have all these JPEGs, and I want to know which ones are corrupt (specifically, ones that end prematurely). qiv will spit out the following to STDERR when it finds one:


Premature end of JPEG file

So, this is nice, except it’s entirely unscriptable. The solution I found was using the following script to the display the images in sequence:


perl -e 'for(glob("*.png *.jpg")){$output = `qiv "$_" 2>&1;`; if($output =~ /Premature/){print $_, "\n";}}'

All this does is mix STDERR with STDOUT for a qiv of the file, and check the output for the word “Premature”. If it finds the word, it prints the filename. Simple.

The only problem is that qiv doesnt have a way to just check whether a JPEG file is corrupt (and if there is a command line utility that does, please let me know). To make it go thru the list, I wrote this little gem:


while(true); do xte "key q"; done

All this does is send the q key to the Xserver infinitely. All I have to do is put focus on the first qiv window to make it and all subsequent qiv windows receive q’s. So, just run it, and click on the window. Then there are lots of flashes, and eventually that perl script will print out the names of the bad files. It’s totally ghetto, but it’s the best I’ve got right now. The point of this post is to hopefully find new ways to do this more programmatically.

Uncategorized , , , , , , , ,

Random Fun with NASM

November 22nd, 2007

I was on IRC tonight and someone was having trouble with their NASM homework. I decided to help them by learning NASM and coding up their homework problem for fun. It was pretty cool.

Read more…

Uncategorized , , , ,

HAI WURLD! LOL

October 7th, 2007

So, today I was stumbling around and I found an implementation of 99 bottles in LOLCODE! Wow, time to get the interpreter. I really need to make a deb for this, but that can wait. Anyway, first I tried some simple hello world sort of stuff:


BTW OMFG A LOLCODE!!oen!111
BTW THIS IS WROTE BY ERIK GREGG 10/07/07
BTW LOL FROM HTTP://WWW.RALREE.INFO
HAI
  VISIBLE "HAI WURLD! LOL"
KTHXBYE

Then I moved on to something even more awesome…

Read more…

Uncategorized ,

KLone – C on Rails!

June 10th, 2007

Well, I was over at Debian Package of the Day when I noticed an article on KLone. It’s a little application framework that allows you to do XHTML templating in C! Then, you can compile it and send it off to any Linux machine (with a few dependencies of course) to run it. I got it, and it didn’t work for me at first. Then, for some reason, it started working. Here’s what I think did it:

In Ubuntu, I did this:


sudo apt-get install build-essential libssl-dev quilt klone klone-package

Then, I made a new test project:


make-klone-project create -p myhello

This creates a new project directory. Now, go into it and make it your new home:


cd myhello-0.1/
cd userdata/
mkdir www etc
vim etc/kloned.conf

I’m just going to assume you’re using vim because, well, you should be. Make the config file look something like this:


server_list my_http
allow_root yes

my_http
{
    type      http
    addr.type IPv4
    addr.port 8880
    dir_root  /www
}

Now lets give it something to work with (note we’re still in userdata):


vim www/index.klone
<html>
<head><title>Hello Lady!</title></head>
<body>
  <%  io_printf(out, "Hey, Lady!  You call him Dr. Jones!");  %>
</body>
</html>

Now add your precious files to the sauce:


cd ../../site/
klone -c import ../userdata/
# 2 dirs and 2 files imported
cd ..

Now, compile and run it:


kloned-build -o myapp userdata
./myapp -F  # This runs it in non-daemonized mode

If you don’t get any errors, congratulations. That means I did something right.

Now, just hop over to here or wherever you specified it to run, and it will magically appear.

Now you can do this:


<html>
<head><title>Hello World</title></head>
<body>
<%
int i;
for(i=0; i < 10; ++i) {
    io_printf(out, "Hello Lady! %d<br />", i);
}
%>
</body>
</html>

Then run this to rebuild and re-run the server:


kloned-build -o myapp userdata && ./myapp -F

Update

So, I ran some tests, and I have to say, the speed increase from C might be really awesome every now and again. Here’s the code:


   clock_t curtime = clock();
   #define SEED 35791246
   int niter=10000000;
   double x,y;
   int count=0; /* # of points in the 1st quadrant of unit circle */
   double z;
   double pi;

   /* initialize random numbers */
   srand(SEED);
   count=0;
   for ( i=0; i<niter; i++) {
      x = (double)rand()/RAND_MAX;
      y = (double)rand()/RAND_MAX;
      z = x*x+y*y;
      if (z<=1) count++;
      }
   pi=(double)count/niter*4;
   io_printf(out, "# of trials= %d , estimate of pi is %g \n",niter,pi);
   io_printf(out, "%f", (double)(clock() - curtime)/(double)CLOCKS_PER_SEC);

All this is is a Monte Carlo method of calculating pi that I stole from here. It takes 0.56 seconds of CPU time on my Core 2 Duo @ 3.3Ghz. Now for the Ruby on Rails test:


# Controller
    @start = Time.now
    srand(35791246)
    iter = 10000000
    count = 0
    0.upto(iter) do |i|
      x = rand().to_f
      y = rand().to_f
      z = x*x+y*y
      count += 1 if z <= 1
    end
    @pi = count.to_f / iter * 4
    @end = Time.now

This finishes in 20.75 seconds (about 40x slower). C is great for things like this. I hope to use KLone in the future for these kinds of tasks.

Uncategorized , , , ,

Using seq to zero-pad strings in a series

May 19th, 2007

I thought this was pretty cool:


for i in `seq -f "%03g" 1 100`; do wget http://www.gozerog.com/images/Hawking_$i.jpg; done

We were trying to do this the other night using bash, but to no avail since the square brackets only work for local file path expansion. I should have remembered seq. Also, this example shows how to 0-pad a series using seq and bash, noted by the *-f* option. Three cheers for seq!

Uncategorized , ,

SVN Log Made Easier

May 3rd, 2007

So, I got tired of typing in the dates to find a range of log messages. Here’s my solution:


# In ~/.bashrc
svn-log() {
  case $1 in
    yesterday | yes | y) svn log -r {`date -d yesterday +"%Y-%m-%d"`}:{`date +"%Y-%m-%d"`};;
    *) echo "Invalid Option: $1";;
  esac
}

I plan to add more to this later.

Uncategorized , ,

Precaching Images with Javascript

April 17th, 2007

Today, Will told me about some awesome image caching. I used it.


//Do some image caching
cached_image = Array(new Image(), new Image(), new Image(), new Image());
cached_image[0].src="image1.jpg";
cached_image[1].src="image2.jpg";

It’s amazing.

Uncategorized , , , ,