Archive

Posts Tagged ‘my code’

My GitHub account

October 26th, 2009 No comments

I’ve recently added the link to my GitHub profile. I signed up some time ago, but now I’ve started to use git for my university projects and push them to GitHub.

Categories: Uncategorized Tags: ,

Matrix chain multiplication: parallel and sequential

June 25th, 2009 No comments

Yep, that’s the project that uses threads. Nothing more is worth to add — the problem is well-known, as well as the algorithm.

Source: http://www.srednikpe.org/src/matrix/

boost::thread and std::list

June 22nd, 2009 4 comments

I had to create many threads in C++. Of course I didn’t want to use pthread, because it’s ugly C. I chose boost::thread instead. Then I needed some container to keep all these threads. Arrays were out of the question for the same reason as pthread. I could use boost:array but stl::list was easier.

The problem was—how to keep this thread objects? I couldn’t use std::list<boost::thread> nor std::list<boost::thread &> because threads cannot be copied. I had to dynamically create the object in order to prevent the destruction after the scope. But for some reason I got compiler error while trying std::list< std::auto_ptr<boost::thread> > in the line where I pushed_back newly created threads.

The cause of the error was that the argument of std::list::push_back() was a constant reference. And while assinging one auto_ptr to another, the first one is getting call release() method, but it can’t since the reference is constant and release() change the state of the object.

To solve this problem one can use boost::shared_ptr.

Example:

#include <iostream>
#include <list>
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
#include <boost/smart_ptr.hpp>
 
using std::list;
using std::cout;
using std::endl;
 
struct foo
{
	void operator() (int id)
	{
		cout << "starting thread " << id << '\n';
		boost::this_thread::sleep(boost::posix_time::seconds(3));
		cout << "ending thread " << id << '\n';
	}
};
 
int main()
{
	typedef boost::shared_ptr<boost::thread> thread_ptr;
	list<thread_ptr> thread;
 
	cout << "creating threads\n";
 
	for (int i = 0; i < 10; ++i)
	{
		thread.push_back(boost::shared_ptr<boost::thread>(new boost::thread(foo(), i)));
	}
 
	cout << "after creation, now joining them\n";
 
	for (list<thread_ptr>::iterator it = thread.begin(); it != thread.end(); ++it)
	{
		(*it)->join();
	}
 
	cout << "ending program" << endl;
 
	return 0;
}

And the result:

tomek@notlob:~% g++ -o threads threads.cpp -O2 -Wall -lboost_thread-mt
tomek@notlob:~% ./threads
creating threads
starting thread 1
starting thread 0
starting thread 2
starting thread 3
starting thread starting thread 4
5
starting thread 6
starting thread 7
starting thread 8
starting thread 9
after creation, now joining them
ending thread 1
ending thread 3
ending thread 5
ending thread 4
ending thread 0
ending thread 2
ending thread 6
ending thread 8
ending thread 7
ending thread 9
ending program

Program verification conditions

December 22nd, 2008 No comments

Yay, another parser in Haskell! That was a Haskell week, but I’m glad I had an opportunity to recall this beautiful full-of-math language.

This program reads an annotated program — a program with assertions. Assertions are just logic formulas. We use them to describe the program state between instructions, ie. variable x is equal to variable y squared. But assertions cannot be random, they must be derived from Hoare’s logic axioms and rules (which base on the formal semantic of the language). How do we know if there is an derivation of a program?

Here verification condicitions come. They are logic formulas too, but generated from annotated program. If all of them are true, then the program is derivable. More information here: http://www.macs.hw.ac.uk/~air/hic-hisd/ and http://www.daimi.au.dk/~bra8130/Wiley_book/wiley.html. The whole point is about formal verification of programs. Nowadays compiler can tell only whether given program has a syntax or type error. It doesn’t know anything about how this program should work and can’t say something like: “This program certainly does not multiply matrices.”. Assertions are some way to tell the programmer’s intentions to the compiler: “This is my piece of code and it should multiply two matrices”, and thus, by generating verification conditions and using automated theorem proving it could say: “It does.”.

So after a boring digression… this program reads an annotated program in a simple imperative language and generates verification conditions. That’s all.

All files are here: http://srednikpe.org/src/vc/

Reverse Polish notation calculator in Haskell

December 22nd, 2008 6 comments

Just a few lines of code, written when I was slightly bored.

module Main where
 
data Token = Plus | Minus | Divide | Times | Num Integer
 
rpnEval :: [Token] -> Integer
rpnEval = rpnEval' [] where
		rpnEval' (i:s) [] = i
		rpnEval' s ((Num i):t) = rpnEval' (i:s) t
		rpnEval' (a:b:s) (op:t) = rpnEval' ((evalOp op a b):s) t
 
		evalOp Plus = (+)
		evalOp Minus = (-)
		evalOp Times = (*)
		evalOp Divide = div
 
toToken :: String -> Token
toToken "+" = Plus
toToken "-" = Minus
toToken "*" = Times
toToken "/" = Divide
toToken s = Num (read s)
 
main = do
	l <- getContents
	mapM print $ map (rpnEval . (map toToken) . words) (lines l)

Update: See comments for better solution.

Kości

August 30th, 2008 3 comments

Nie mieliśmy kości na sesję, to trzeba było coś napisać. NWOD-owy rzucacz kośćmi w Pythonie:

#!/usr/bin/python
 
import time
import random
import sys
 
# argumenty: 
ile_scian = int(sys.argv[1])    # ilusciennymi koscmi rzucamy
sukces = int(sys.argv[2])       # od ilu oczek jest sukces
ile_rzutow = int(sys.argv[3])   # ile razy rzucamy
 
def kostka(sciany):
    rzut = random.randint(1, sciany)
    print rzut
    return rzut
 
print '------------------------------'
 
random.seed()
 
sukcesy = 0
 
for i in range(0, ile_rzutow):
    rzut = kostka(ile_scian)
 
    if rzut >= sukces:
        sukcesy += 1
 
    while rzut == ile_scian:
        print 'Przerzut!'
 
        rzut = kostka(ile_scian)
 
        if rzut >= sukces:
            sukcesy += 1
 
print
print "Sukcesy: ", sukcesy

Just another wget clone

June 10th, 2008 No comments

While nothing interesting is happening in my life I post my recent program. Simply wget clone, with -m option it downloads all images and some stylesheets from the page and changes them to local adresses. Sorry for Polish comments and names in source file.

Source

LOLCode Compiler (my own!)

April 23rd, 2008 No comments

Hah! My dream have come through! I wrote my first compiler with my own lexer and parser. It compiles LOLCode (slightly modified version, see in specification [in polish, but only output language]) to stack machine language. My project contains also stack machine which interprets output files and prints them in human readable assembler and three examples of LOLCode programs. It’s all GPL so you can learn how it works. It’s written in C and I didn’t have much time to write pretty dynamic arrays and If someone will fix it, I would be verry happy. If you’ve got question about how it works, go ahead, write me and ask.

Source: http://www.srednikpe.org/src/lcc/

pyhttpd – a tiny HTTP deamon written in Python

February 11th, 2008 No comments

It’s for my Python Course. It provides only very basic HTTP, but yet can be used for simple WWW hosting. Source.

Features:

  • GET and POST methods
  • New thread for new connection
  • Directory listing
  • Error pages
  • Document index
  • Deafult type and charset
  • Python scripts ;)
  • Configuration file
  • … and my own modules to handle these

TODOs:

  • Logging
  • Much more stability (exceptions handling, etc.)
  • Sending gzipped or chunked data (if accepted)
  • Range headers
  • … and many, many other

To run just edit pyhttpd.conf and change Port and Document root. Then type “python pyhttpd.py” and it should be now listening for connections.

How to run a python script and its output send to client? Pyhttpd checks if the requesting file is a python one. If so then it opens a python interpreter by a pipe, sends _GET and _POST dictionaries and file contents. And finally, sends interpreter outputs to client.

_GET and_POST are just dictionaries with variable names as keys. So if there is a foobar.py?i=500 request then _GET will be { ‘i’ : ‘500′ } (note that this is always a string value).

It’s GPL if someone asked.

JZW Interpreter source and examples

September 9th, 2007 1 comment

All right. I said I’ll show my jzwi source and here it is: http://www.srednikpe.org/src/jzwi/

It is almost ended. It doesn’t only check local variable if they have unique names. I’m too lazy to do that. But after all it works fine and quite fast (compared to other interpreters written by my colleagues).

To run jzwi program just run “jzwi program.jzw argument1 argument2 …”.

It’s all licensed on GPL (any version). There is no guarantee that it’ll work. ;)