Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Saturday, June 25, 2011

Old School VS .net 2005 MFC Threading and Timers

I come from a background of multithreading with Java. I also did some threading with pthreads.

CWinThreads don't seem to have the same level of control that java has.

To create a CWinThread, use this :

AfxBeginThread(ProcName, NULL, THREAD_PRIORITY_NORMAL, 0, 0, NULL);

Using AfxBeginThread allows you to access MFC objects.

Make sure you create global function:


UINT ProcName(LPVOID param)

{

for(int i=0; i<100000000; i++)

{
if (i % 10000000 == 0){

TRACE("thread 2 id = %d, %d \n",AfxGetThread()->m_nThreadID,i);
}

}

return 0;
}


You probably noticed the AfxGetThread() function which gives you access to the current thread. Very helpful function.

It looks like CWinThread uses preemptive multitasking but it's kind of slow, doing like context switches every second or so.

I also played with the MFC timer. This doesn't create a new thread whenever the timer function executes. It uses the same thread as is used in the GUI (I was using a dialog project). This is also much too slow. You can set the timer to every millisec. Would be nice to have it down to microsec.

Monday, April 5, 2010

Flash Card to Moodle xml

#example flashcard questions:
Which switch would you use with the echo command to enable the "backslash" options? ------ -e
Which switch would you use with the find utility to cause another command to run without prompting you? ------ -exec



#shell script
#!/bin/sh
converted="converted.xml"
sep="------"

if [[ $# -ne 1 ]]
then
echo "$0 file_to_convert"
exit 1
fi

echo "starting conversion to moodle xml"

if [[ -f $converted ]]
then
echo "$converted already exists"
rm $converted
fi

echo '<?xml version="1.0" ?>' > $converted
echo "<quiz>" >> $converted

i=1

cat $1 | while read line
do

q=`echo $line | awk -F"$sep" '{ print $1 }'`
a=`echo $line | awk -F"$sep" '{ print $2 }'`
echo '<question type="shortanswer">' >> $converted
echo '<name>' >> $converted
echo "<text>Question $i</text>" >> $converted
echo '</name>' >> $converted
echo '<questiontext format="html">' >> $converted
echo "<text>$q</text>" >> $converted
echo '</questiontext>' >> $converted
echo '<answer fraction = "100">' >> $converted
echo "<text>$a</text>" >> $converted
echo '<feedback><text>Correct!</text></feedback>' >>$converted
echo '</answer>' >> $converted
echo '</question>' >> $converted

((i=i+1))

done
echo '</quiz>' >> $converted

Wednesday, March 17, 2010

gcc, gdb and make commands

Macro definition
gcc -D DUMMY_DEF -c test_str.c

Makefile arguments
test:
./program $(PROG_ARGS)

make test PROG_ARGS='testfile1.txt'

gdb commands
run args - runs program
frame - examines current frame
up - examines previous frame

Sunday, January 24, 2010

Mortgage calculator - bash script

This simply outputs the monthly mortgage payment.

Takes five arguments : principle years interest points fees

For instance,

bash mortgage.sh 100000 5 .075 0 0

Outputs

Principle + fees = 100000 , Years = 5 , Months = 60 , interest .006250000000
Points = 0 , 0
2003.794859563881




#!/bin/sh

if [[ $# -ne 5 ]]
then
echo "enter 5 args : principle years interest points fees"
exit
fi

prin=$1
((mon=$2 * 12 ))
inter=`echo "scale=12;$3/12" | bc`
pts=`echo "scale=12; $prin * $4" | bc`
fee=$5
prin=`echo "scale=12;$prin + $fee" | bc`


echo "Principle + fees = $prin , Years = $2 , Months = $mon , interest $inter"
echo "Points = $4 , $pts"

prin=`echo "scale=12; $prin - $pts" | bc`


echo `echo "scale=12;($prin*$inter)*((1+$inter)^$mon)/(((1+$inter)^$mon)-1)"|bc`
echo "the monthly payment : $new_prin"



Monday, January 11, 2010

Bash - Gaussian Elimination Op count example



#!/bin/sh

if [[ $# -ne 2 ]]
then
exit
fi

echo " m $1 by n $2 matrix"

n=$2
m=$1
mult=0
add=0
c=0

for ((i=1;i < m;i++))
do
echo "row = i = $i"
for ((j=i;j < m;j++))
do
((mult=mult + (n-i+1)))
((add=add + (n-i+1)))
done
((c=c+(m-i)*(n-i+1)))
done
echo "additions = $add"
echo "mults = $mult"
echo "summation = $c"



Matlab - simple newton's method ex



function r = doNewton(f,x0,x,err)

while abs(x0 - x) > err

x0, (x0 - x)

x0 = x0 - (polyval(f,x0))/polyval(polyder(f),x0);


end



r = x0;
end

Saturday, November 7, 2009

Jacobi Method example

I wrote this code a while back. Apparently, this post is getting a few hits. I refined it a bit. Also wanted to make sure it was looked right.

What is the Jacobi method? It's an iterative way of solving a system of equations. Ax = b. This is learned in Numerical Analysis classes.

Generally, you decompose a matrix into its diagonal and lower and upper triangles. Such that,

A = D + L + U

x0 is the initial guess.

Now you want to solve for x. x_approx = inverse of D * (b - (L+U)x0)

Get x_approx from this formula, then plug it into x0 and do it all over again until you reach the desired error.



% Code is for matlab / octave
format long e;
A = [ 2 -1; -1 2];
b = [ 2; 1];
k = 20;
xi = [0;0]; % initial guess

%we want
%x' = Dinv(b - (L+U)x)

% just take the diagonal of A
D=[A(1,1) 0;0 A(2,2)];

Di=inv(D);

%lower and upper triangles of A
L=[0 0; -A(2,1) 0];
U=[0 -A(1, 2); 0 0];

% this part doesn't change, so calc now
C=Di*b;
% this is the main term of the algo
M=Di*(L+U);

x = [5/3; 4/3]; % solution

abs_err = [ 100 ; 100];
abs_err = abs_err - x;
i=0;

%stop until error is <= 1e-6
while abs_err(1) >= 1e-6 && abs_err(2) >= 1e-6
xi=M*xi+C
abs_err = abs(xi - x);
fprintf('i = %f abs-err = %f %f \n',i,abs_err(1),abs_err(2));
i=i+1;
end


Friday, November 6, 2009

matlab : polynomial fitting



octave-3.2.3:4> for i = 1 : 51
> x(i) = .2*(i - 1);
> end


octave-3.2.3:6> for i = 1: 51
> y(i) = 1 - x(i);
> end

octave-3.2.3:8> polyfit(x,y,4)
ans =

1.1249e-17 -2.3654e-16 1.7285e-15 -1.0000e+00 1.0000e+00

Wednesday, November 4, 2009

Java : sample applet






import java.applet.*;
import java.awt.*;

public class A extends Applet
{
private int w, h;
public void init( )
{
w = 45;
h = 50;
}

public void paint(Graphics g)
{
g.drawRect(w, h, 20, 80);
}
}


Friday, October 30, 2009

Matlab polynomial basics: roots, derivative of polynomial, evaluate polynomial



%Get roots of function

octave-3.2.3:13> A = [1 -3 3 -1]
A =

1 -3 3 -1

octave-3.2.3:14> roots(A)
ans =

1.00001 + 0.00000i
1.00000 + 0.00001i
1.00000 - 0.00001i

%get derivative of polynomial

octave-3.2.3:18> A
A =

1 -2 1

octave-3.2.3:19> polyder(A)
ans =

2 -2


%evaluate polynomial using matrix notation

polyval(A,1)
ans = 0
octave-3.2.3:21> polyval(A,2)
ans = 1

Saturday, October 3, 2009

matlab basics : scripts, functions, precision

running scripts
===============

matlab -r myscript


creating and using a function
=============================

g = inline('9*(s.^6) + 6*(s.^5) - 11*(s.^4) - 4*(s.^3) - 5*(s.^2) + 12*s - 4')

g(1)

precision display
=================

format long e %15 digits with exponent

Thursday, September 3, 2009

Cut out unwanted pieces of a lastname with vbscript



lastname = "DE' CA-R LO III"

'separate lastname by spaces into an array
a = split(lastname," ")
new_lastname = a(0)

for i = 0 to ubound(a) -1 ' add each chunk of the last name to the final string
'the last piece of the last name is not added if it is less than 4 characters (such as III, II, I, etc)
if i + 1 = ubound(a) and len(a(i+1)) > 3 then
new_lastname = new_lastname + a(i+1)
elseif i + 1< ubound(a) then
new_lastname = new_lastname + a(i+1)
end if
next

new_lastname = Replace(new_lastname,"-","") 'take out hyphens
new_lastname = Replace(new_lastname,"'","") 'take out punctuations

wscript.echo new_lastname

Tuesday, June 16, 2009

Php basics : error handling, tests, array functs, classes, and scope

Checking if a file exists

if (file_exists($some_file)){
...
}

Basic Error Handling

function($var) or exit("some error");


Printing an array


print_r();


Creating a class

class SomeClass{

private some_var;

public function SomeClass(){}

public function new_fun($r){
print_r($r);
echo $this->some_var;

}

}


Defining an array

$my_array = array('elem1','elem2');

Adding an array element

array_push($array,$elem)


Checking if a key exists

array_key_exists("some_name",$r)


Using a global var in a function

global $global_var;

JQuery basics : working with divs and text boxes, and checking for null elements

Adding text to a div's innerHTML

$("div#some_div").append(s);


Getting text from a div

var text = $("div#some_div" ).html();


Getting/Setting value from text box

var text = $("#some_textbox").val();
$("#some_textbox").val("bla");


Checking if document element is null

if (!$("#some_elem").length){
...

}

Monday, June 15, 2009

Get the distance between two latitude/longitude points in km (example)

Here is a python script to convert lat/lng point to meters. It expects the points to be entered in as decimal degrees. It outputs the distance in km.

For example:

python distlatlng.py 36.12 -86.67 33.94 -118.40
the distance in km is 2887.25995061



#uses the haversine formula
# based on code from http://www.movable-type.co.uk/scripts/latlong.html
import math, sys

def main(*args):
if len(args) < 5:
print args[0]," lng1 lat1 lng2 lat2 (finds distance between two lat/lng pairs)"
return
lat1 = float(args[1])
lng1 = float(args[2])
lat2 = float(args[3])
lng2 = float(args[4])
radius = 6372.8 # earth's mean radium in km
dlat = math.radians(lat2-lat1)
dlng = math.radians(lng2-lng1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng/2)*math.sin(dlng/2)
c = 2*math.atan2(math.sqrt(a),math.sqrt(1-a))
dist = radius*c
print "the distance in km is " , dist


if __name__ == "__main__":
main(*sys.argv)


Python basics : math functions, main funct

Math functions
#Unfortunately, you need to import math, but python has a nice library of math functions



import math
math.pow(2,3)
math.cos(math.pi/2) #<-- radians!
math.pi
math.sqrt(4)



Main function

#Making a main function in Python is a little tricky. Here is an example:



def main(*args):
if len(args) < 4:
return

print "main : args[0] ", args[0], " args[1]", args[1]
print "(main) : args[1] ", args[2]
print "(main) : args[3] ", args[3]

if __name__ == "__main__":


Thursday, June 11, 2009

Checking versions if Office 2004 is at 11.5.5 and Acrobat is at 9.1.2

This is a trick to check version of some software on a group of computers


Here we're checking that Office 2004 11.5.5 update is installed


for ((i=1;i < 21;i++)); do if [[ $i -lt 10 ]]; then echo "station $i" ; ssh station-0${i}.local " ls -l /Applications/Microsoft\ Office\ 2004/Updater\ Logs/11.5.5\ Update\ Log.txt "; else ssh station-${i}.local " ls -l /Applications/Microsoft\ Office\ 2004/Updater\ Logs/11.5.5\ Update\ Log.txt "; fi; done

Here we're checking that Acrobat reader and acrobat are at 9.1.2


for ((i=1;i < 21;i++)); do if [[ $i -lt 10 ]]; then echo "station $i" ; ssh station-0${i}.local "system_profiler SPSoftwareDataType SPApplicationsDataType | grep '9.1.2' "; else ssh station-${i}.local " system_profiler SPSoftwareDataType SPApplicationsDataType | grep '9.1.2' "; fi; done

Wednesday, June 10, 2009

How to set up Jogre for the web

Set up jdk, apache tomcat, and hsqldb
==============================

apt-get install sun-java6-jdk
apt-get install tomcat5.5 tomcat5.5-wepapps tomcat5.5-admin
apt-get install hsqldb-server

Set up jogre
=========

wget http://voxel.dl.sourceforge.net/sourceforge/jogre/jogre_beta_0.3_bin.zip
cd /opt
unzip ~/jogre_beta_0.3.bin.zip
adduser jogre
chown -R jogre:jogre jogre
su jogre
cd
echo "export CLASSPATH=$CLASSPATH:/usr/share/java/hsqldb.jar:." >> .profile
source .profile
java org.hsqldb.Server &
cd /opt/jogre/server
chmod a+x *.sh


Configuration
==========

./server.sh &

#I prefer the gui; it's easier to just change the db settings with this tool
./administrator.sh &
#Login with admin, admin
#Change the database from xml to hsqldb
#The path to the db is jdbc:hsqldb:hsql://localhost/jogre_hsqldb

#restart the jogre server
killall server.sh
./server.sh &


#With apache tomcat admin (http://localhost:8180/admin), add jogreweb.war

Sunday, June 7, 2009

Java - convert byte array to String



int len = (int)c.getLength();

if (len > 0) {
int actual = 0;
int bytesread = 0 ;
byte[] data = new byte[len];
while ((bytesread != len) && (actual != -1)) {
actual = is.read(data, bytesread, len - bytesread);
bytesread += actual;

}

//assuming utf-8 encoding
String test = new String(data,0,data.length,"UTF8");
System.out.println(test);


Java - how to make an anonymous thread

Creating an anonymous thread is pretty easy. If you want to make a thread that performs a simple operation anonymous threads can be convenient.

Java threads perform their task in the run() function, which is initiated with the start method.

Here is an example:



Thread t = new Thread( new Runnable(){
public void run(){
System.out.println(" do some work");


}
});

t.start();