Archive

Posts Tagged ‘c’

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 , , , , , , ,

OSCON Sessions, Day 2

July 25th, 2008

Oh man, what a day.

I attended quite a few talks, grabbed a lot of swag, and entered a few contests. I ended up buying the Arduino Starter Kit from MAKE so I can do some awesome embedded Ruby like I saw at FOSCON. It looks really fun – I can’t wait to try it out.

The talks I attended were half-way decent, but I learned a lot more on the first day.

Hadoop and EC2

A good overview of how one can use Amazon’s S3 and EC2 services to cheaply process and store data on a pretty large scale. The New York Times digitized hundreds of years of articles in a single day using these services and some awesome C++ code.

Open standards in cloud computing

This ended up being a marketing talk. I don’t know what it had to do with cloud computing, and I didn’t stick around to find out.

Ruby 1.9: What to Expect

An awesome overview of all the new stuff in Ruby 1.9 given by Sam Ruby. I had no idea they were changing so much, and this was a good dive with code examples into that. There was some discussion among everyone in the middle on whether for loops should work like .each blocks with regards to scope. I happen to disagree with what ended up being the popular thought on this subject. Most were advocating that a for loop constitutes a block, and that scope variables and iterators should be localized inside of it. This is contrary to almost every language, which I brought up using the example of C. Yet, when you iterate with .each, you immediately define a block and a scoped iterator, which, if it has a conflicting name with the outside world, it doesn’t matter since that’s out of scope. The only thing this changes is the value of a variable outside after the loop finishes. I think leaving the ability to modify a variable external to the loop is very convenient – in summary, leave it how you’ve done it in Ruby 1.9 already.

Ubuntu on the Go: Subnotebook and MID technologies

This was an interesting session on where Canonical is taking mobile technology, and what the community can do to help. They seem to have a pretty neat subnotebook coming out soon.

Python, C++, and SWIG

This could have been one of the best talks, but the speed at which it was given and the lack of enthusiasm in the presentation left most of us either bored or unfulfilled at the end of the talk. He spent the first half explaining what Python and C++ were, then he got to what SWIG is. The end was a quick dive into an extremely complicated bunch of files that didn’t help very much. In the future, it would be helpful to go to a SWIG talk that details how to make a simple Python extension with SWIG. I may have to throw that one together myself…

I also attended the tail end of Designing Political Web Apps for MoveOn.org, but I didn’t take any notes.

We ended up going to dinner at Widmer Brothers, which was pretty awesome. I had the Pork Schnitzel, a very tender piece of meat if I do say so myself, along with 2 Full Nelson IPAs. Afterwards, we caught the bus from the convention center to BeerForge and the SourceForge Community Choice Awards party. Beerforge was a blast. I ended up talking to Jean-Baptiste Kempf, one of the developers of VLC, for hours – a truly great guy. I learned a lot about France and the French people, but also about VLC. Apparently, you can use VLC from the command line much like mplayer, which I did not know. Yet, he explained that they removed Directshow support from VLC in Linux in favor of open source alternatives, which in part I can understand. Yet, the only codec available that is able to smoothly play 1080p h264 video is closed source (CoreAVC), and until the ffmpeg avc codec catches up, I’ll have to continue using mplayer. When I can play everything back smoothly with VLC, I may consider switching.

The beer at BeerForge was pretty good – I had the IPA. SourceForge had some sort of mixed drink which wasn’t too great. All in all, a good day, but now I’m dehydrated…


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 , , , ,

Compiling Stepmania in Ubuntu Feisty

September 9th, 2007

OK – so I love DDR. I was trying to compile Stepmania this morning, and found that it has some issues. I found the answer to the first issue in this post, and found the answer to the second in this one. Apparently, there are some patches that have gone into 4.0 CVS that haven’t been put into the old source.

Procedure

Get the Stepmania Source and extract it somewhere. Now we need to get stuff to compile it:


sudo apt-get install gcc-3.4 g++-3.4 build-essential liblualib50-dev
CC=gcc-3.4 CXX=g++-3.4 ./configure

Now we should have a nice Makefile and such. If you get dependency problems, you can figure that out on your own. You’ll need SDL and a few other things too, but I already had those.

First, I got this:


rch/InputHandler/InputHandler_SDL.cpp:126: error: `int SDL_EventMask' redeclared as different kind of symbol
/usr/include/SDL/SDL_events.h:108: error: previous declaration of `typedef enum SDL_EventMasks SDL_EventMask'
arch/InputHandler/InputHandler_SDL.cpp:126: error: declaration of `int SDL_EventMask'/usr/include/SDL/SDL_events.h:108: error: conflicts with previous declaration `typedef enum SDL_EventMasks SDL_EventMask'
arch/InputHandler/InputHandler_SDL.cpp: In constructor `InputHandler_SDL::InputHandler_SDL()':
arch/InputHandler/InputHandler_SDL.cpp:176: error: expected unqualified-id before '|=' token
arch/InputHandler/InputHandler_SDL.cpp: In member function `virtual void InputHandler_SDL::Update(float)':
arch/InputHandler/InputHandler_SDL.cpp:195: error: expected primary-expression before ')' token
make[2]: *** [InputHandler_SDL.o] Error 1
make[2]: Leaving directory `/usr/local/src/StepMania-3.9-src/src'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/usr/local/src/StepMania-3.9-src/src'
make: *** [all-recursive] Error 1

Then, after I fixed that, I got this:


if g++ -DHAVE_CONFIG_H -I. -I. -I. -I/usr/include/lua50 -I/usr/include/SDL -D_GNU_SOURCE=1 -D_REENTRANT   -finline-limit=300   -Wall -W -Wno-unused -Wno-switch -O3 -MT LinuxThreadHelpers.o -MD -MP -MF ".deps/LinuxThreadHelpers.Tpo" \
          -c -o LinuxThreadHelpers.o `test -f 'archutils/Unix/LinuxThreadHelpers.cpp' || echo './'`archutils/Unix/LinuxThreadHelpers.cpp; \
        then mv -f ".deps/LinuxThreadHelpers.Tpo" ".deps/LinuxThreadHelpers.Po"; \
        else rm -f ".deps/LinuxThreadHelpers.Tpo"; exit 1; \
        fi
archutils/Unix/LinuxThreadHelpers.cpp:32: error: ‘gettid’ has not been declared
archutils/Unix/LinuxThreadHelpers.cpp:39: error: expected initializer before ‘CStdStringA’
archutils/Unix/LinuxThreadHelpers.cpp: In function ‘uint64_t GetCurrentThreadIdInternal()’:
archutils/Unix/LinuxThreadHelpers.cpp:136: error: ‘gettid’ was not declared in this scope
make[2]: *** [LinuxThreadHelpers.o] Error 1
make[2]: Leaving directory `/home/jon/Desktop/StepMania-3.9-src/src'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/jon/Desktop/StepMania-3.9-src/src'
make: *** [all-recursive] Error 1

Time to patch:


cd StepMania-3.9-src/
wget -O - http://ralree.info/assets/2007/9/9/stepmania-3.9-glibc.patch | patch -p1
wget -O - http://ralree.info/assets/2007/9/9/sdl.patch | patch -p0

This should fix most of it. I’m still having trouble with this though:


if g++-3.4 -DHAVE_CONFIG_H -I. -I. -I. -I/usr/include/lua50 -I/usr/include/SDL -D_GNU_SOURCE=1 -D_REENTRANT   -finline-limit=300   -Wall -W -Wno-unused -Wno-switch -O3 -MT CryptHelpers.o -MD -MP -MF ".deps/CryptHelpers.Tpo" \
          -c -o CryptHelpers.o `test -f 'CryptHelpers.cpp' || echo './'`CryptHelpers.cpp; \
        then mv -f ".deps/CryptHelpers.Tpo" ".deps/CryptHelpers.Po"; \
        else rm -f ".deps/CryptHelpers.Tpo"; exit 1; \
        fi
crypto51/misc.h: In function `std::string CryptoPP::IntToString(T, unsigned int) [with T = unsigned int]':
crypto51/simple.h:25:   instantiated from here
crypto51/misc.h:176: warning: comparison of unsigned expression < 0 is always false
g++-3.4 -finline-limit=300   -Wall -W -Wno-unused -Wno-switch -O3  -rdynamic -o stepmania  Screen.o ScreenAttract.o ScreenBookkeeping.o ScreenBranch.o ScreenCaution.o
################### ...........
################### ...........
pubkey.o queue.o randpool.o rsa.o sha.o strciphr.o CryptHelpers.o -lvorbisfile -lvorbis -logg -lmad /usr/lib/liblualib50.a /usr/lib/liblua50.a -L/usr/lib -lSDL -lXtst -lGL -lGLU ./libresample/libresample.a -ldl  -lpng -lz -lm -ljpeg -lz -lpthread
`.gnu.linkonce.t._Z23CourseEntryTypeToString15CourseEntryType' referenced in section `.rodata' of EditCoursesMenu.o: defined in discarded section `.gnu.linkonce.t._Z23CourseEntryTypeToString15CourseEntryType' of EditCoursesMenu.o
collect2: ld returned 1 exit status
make[2]: *** [stepmania] Error 1
make[2]: Leaving directory `/nexus/rofl/hank/tmp/StepMania-3.9-src/src'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/nexus/rofl/hank/tmp/StepMania-3.9-src/src'
make: *** [all-recursive] Error 1

Leave a comment if you know the answer.

Update


00:59:55 < hardwarehank> the stable is - massively unstable
01:00:02 < hardwarehank> needed 2 patches and it still didnt work
01:00:13 < hardwarehank> has a linker error in the final compile :(
01:00:19 < DevastatorIIC> worked immediately after untarring here
01:00:30 < hardwarehank> you got the binary :)
01:00:38 < DevastatorIIC> yeah, and it worked ;)
01:00:41 < hardwarehank> maybe i should do that
01:02:52 < hardwarehank> woohoo
01:02:55 < hardwarehank> DevastatorIIC++

Lesson: Don’t overcomplicate things.

Uncategorized , , , ,

PL/Ruby on CentOS 5

August 1st, 2007

I had some trouble compiling PL/Ruby for PostgreSQL today on Modzer0. I solved it with some clever extconf.rb switches:


ruby extconf.rb --with-pgsql-include=/usr/include/pgsql/ --with-pgsql-version=81

Now I avoid the problems I was having before:


[root@modzer0 plruby-0.5.1]# make
make[1]: Entering directory
#...
In function ‘perm_fmgr_info’:plruby.c:116: error: ‘TopMemoryContext’ undeclared (first use in this function)
plruby.c:116: error: (Each undeclared identifier is reported only once
plruby.c:116: error: for each function it appears in.)
plruby.c: In function ‘plruby_call_handler’:
plruby.c:706: warning: unused variable ‘result’
plruby.c: In function ‘pl_compile’:
plruby.c:875: error: subscripted value is neither array nor pointer
plruby.c:876: error: subscripted value is neither array nor pointer
plruby.c:879: error: subscripted value is neither array nor pointer
plruby.c:889: error: subscripted value is neither array nor pointer
plruby.c:937: error: ‘TopMemoryContext’ undeclared (first use in this function)
make[1]: *** [plruby.o] Error 1

Now I just have to create the language in Postgres. I’m making it trusted since I don’t want anyone doing anything nasty. I might build the untrusted version later like Robby did here.


CREATE FUNCTION plruby_call_handler() RETURNS language_handler
  AS '/usr/lib/ruby/site_ruby/1.8/i386-linux/plruby.so'
  LANGUAGE C;

CREATE TRUSTED LANGUAGE 'plruby'
  HANDLER plruby_call_handler
  LANCOMPILER 'PL/Ruby';

Voila!


Procedural Languages
  Name  | Trusted?
--------+----------
 plperl | yes
 plruby | yes

OH OH

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 , , , ,