simple rsa from javascript to python

2012-04-02 Thread Astan Chee
Hi,
I've got a simple javascript that looks like this:

var public_key_mod =
B99808B881F3D8A620F043D70B89674C0A120417FBD3690B3472589C641AD5D422502D0B26CADF97E2CB618DDDBD06CA0619EBBFB328A2FA31BD0F272FE3791810546E04BF42F05DB620FC7B4D0A2EAA17C18FF30C84D93341205C1D6EAD6ACBF2F08E334049DEBF31555CF164AD5CCE437B1AB5EFFEE1FF38552B63EDEF74861E665D90D5AB76D85F5242F42BA29F20EC64553D08020C1E37909341A25F339F802A83EE65E1559AC1CDFE0837160759770D27A058CED0C3771356BCAC8739A0FEF8F344CF64833CDDECC41BBE76BB2F1F8229EB04C72FABA91E4798A3DDFD9100A5171490B30F30EAADF6FDA7677F63CD77D1E6E88F79A6CED5A4966DD6459F;
var public_key_exp = 010001;
var my_text = this is a text.,);
var public_key = RSA.getPublicKey( public_key_mod, public_key_exp );
var encrypted_text = RSA.encrypt( my_text, public_key );

and I'm trying to convert this into python and I'm rather stuck with
pycrypto as there is no example on how to make the public key with a
mod and exponent (or I've probably missed it).
Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: turn monitor off and on

2011-05-19 Thread Astan Chee
On Mon, May 16, 2011 at 7:29 PM, Gabriel Genellina
gagsl-...@yahoo.com.arwrote:


 Your script worked fine for me, 2.6 and XP also. Perhaps your monitor
 device driver is buggy or does not implement the required functionality.
 Mine is from Philips.


I'm actually using windows 7. Maybe its the difference in OS? Anyway, yes,
the monitor turns back on if the keys are pressed.
I've gone with a pygame/autoit hack which doesn't turn the monitor off (just
black) and then removes the black screen (no offence).
Thanks again for the helps
-- 
http://mail.python.org/mailman/listinfo/python-list


starting a separate thread in maya

2011-05-19 Thread Astan Chee
Hi,
I'm using python2.5 in maya 2009 x64 (in linux). I have a script running and
somewhere in the script, I want to start another python script that might
not return and i don't want the main maya python script to wait for it to
finish, even more, after the second script started, I'd like the main script
to continue processing. I've tried using threading and
maya.utils.executeInMainThread and os.popen and os.spawn, none seem to work
this way. Is it not possible to do this in python2.5?
Thanks again for any help.
Cheers
-- 
http://mail.python.org/mailman/listinfo/python-list


turn monitor off and on

2011-05-14 Thread Astan Chee
Hi,
I'm trying to turn off my monitor, pause and then turn it on again.
I'm doing this in python 2.6 and windows xp. Here is my script so far
(that doesn't work):

import time
import win32gui
import win32con
import win32api

def turnOffMonitor():
  SC_MONITORPOWER = 0xF170
  win32gui.SendMessage(win32con.HWND_BROADCAST,
win32con.WM_SYSCOMMAND, SC_MONITORPOWER, 2)

def turnOnMonitor():
  SC_MONITORPOWER = 0xF170
  win32gui.SendMessage(win32con.HWND_BROADCAST,
win32con.WM_SYSCOMMAND, SC_MONITORPOWER, -1)

if __name__ == __main__:
  turnOffMonitor()
  time.sleep(5)
  turnOnMonitor()

For some reason, the script doesn't turn the monitor back on. What am
I doing wrong here or are there any other alternative?
-- 
http://mail.python.org/mailman/listinfo/python-list


Running and killing a process in python

2011-05-03 Thread Astan Chee
Hi,
I'm trying to make a python script (in windows 7 x64 using python 2.5) to
start a process, and kill it after x minutes/seconds and kill all the
descendants of it.
Whats the best way of doing this in python? which module is best suited to
do this? subprocess?
thanks for any help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fitting polynomial curve

2011-03-17 Thread Astan Chee
On Thu, Mar 17, 2011 at 5:09 PM, Terry Reedy tjre...@udel.edu wrote:

 Look at scipy.

 --


Thanks for the info. I realized I made some mistakes. Anyway, what I'm
trying to do is in maya (python), fit selected vertices on a curve. Here is
what I have so far:

import maya.cmds as cmds
import numpy

def run_main():
verts = cmds.ls(sl=True,fl=True)
if len(verts) = 2:
degree = 5
x = []
y = []
for vert in verts:
vert_x,vert_y,vert_z = cmds.pointPosition(vert,w=True)
x.append(vert_x)
y.append(vert_z)
print x , x
print y , y
x_numpy = numpy.array(x)
y_numpy = numpy.array(y)
funct = numpy.polyfit(x_numpy,y_numpy,degree)
print funct #p : ndarray, shape (M,) or (M, K)
#Polynomial coefficients, highest power first. If y was 2-D,
the coefficients for k-th data set are in p[:,k].
#make an outline curve
curvs = []
for i in range(len(verts)):
vert_x,vert_y,vert_z = cmds.pointPosition(verts[i],w=True)
pos_x = 0
pos_y = 0
for j in range(degree):
pos_x += (funct[j] *(vert_x**(degree-j)))
pos_y += (funct[j] *(vert_y**(degree-j)))
centerPos = (pos_x,pos_y,vert_z)
curvs.append(centerPos)
if curvs:
print cirv , curvs
crv = cmds.curve(p=curvs)
cmds.select(cl=True)
for v in verts:
cmds.select(v,tgl=True)

else:
print please select more than 2 verts

But this only works for 2D (x,z-axis). Is it possible to make it work at 3
by combining them or doing (x,y) and (x,z) and somehow colate (average?) the
results? Is there a formula for combining the results?
Thanks again for any help or suggestions
-- 
http://mail.python.org/mailman/listinfo/python-list


Fitting polynomial curve

2011-03-16 Thread Astan Chee
Hi,
I have 2 points in 3D space and a bunch of points in-between them. I'm
trying to fit a polynomial curve on it. Currently I'm looking through numpy
but I don't think the function exists to fit a function like this:
y = ax**4 + bx**3 + cx**2 + dx + e
(I'm not sure what thats called but one degree up from a cubic curve)
Also, I'm sure it'll take alot of time to brute force it like this but I'm
sure I'm missing something for this.
Thanks for any advice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run a function in another processor in python

2010-12-10 Thread Astan Chee
Thanks for that. I'll try and see if it makes any difference but I'm using
python 2.6 not 3
Are the multiprocessing modules different? That code (or whatever is using
the multiprocessing module) seems to cause infinite python processes on my
machine and eventually kills it.
I'm running python 2.6 on windows 7 x64 is it the ammount of memory/cpu
speed/number of cpu that is the issue?
Thanks for any clarification



On Fri, Dec 10, 2010 at 4:16 AM, geremy condra debat...@gmail.com wrote:

  On Thu, Dec 9, 2010 at 5:03 AM, Astan Chee astan.c...@gmail.com wrote:
  Thanks but I'm having trouble with that module too. Currently what I
  have is something like this:
 
  import sys
  import os
  import multiprocessing
 
  import time
 
  def functionTester(num):
 return ((num+2)/(num-2))**2
 
  num_args = [61,62,33,7,12,16,19,35,36,37,38,55,56,57,63]
 
  max_result = 0
 
  start = time.time()
 
  num_processes = multiprocessing.cpu_count()
 
  threads = []
  len_stas = len(num_args)
 
  for list_item in num_args:
 if len(threads)  num_processes:
 p =
 multiprocessing.Process(target=functionTester,args=[list_item])
 p.start()
 print p, p.is_alive()
 threads.append(p)
 else:
 for thread in threads:
 if not thread.is_alive():
 threads.remove(thread)
 
  print Result  + str(max_result)
  end = time.time()
  elapsed= end - start
  print Took, elapsed, seconds to execute
 
  But it doesn't give me any return data. It also spawns an infinite
  number of (sub)processes that crashes my machine. What am I doing
  wrong here?
 
  On 12/9/10, Jean-Michel Pichavant jeanmic...@sequans.com wrote:
  Astan Chee wrote:
  Hi,
  I've got a python script that calls a function many times with various
  arguments and returns a result. What I'm trying to do is run this
  function each on different processors and compile the result at the
  end based on the function result. The script looks something like
  this:
 
 
  import time
 
  def functionTester(num):
  return ((num+2)/(num-2))**2
 
  num_args = [1,2,3,7,12,16,19,35,36,37,38,55,56,57,63,44,71,81,91]
 
  max_result = 0
 
  start = time.time()
 
  for n in num_args:
  result = functionTester(n)
  if result  max_result:
  max_result = result
 
  print Result  + str(max_result)
  end = time.time()
  elapsed= end - start
  print Took, elapsed, seconds to execute
 
 
  What I'm trying to do is run each function on a processor and when its
  done, move on to the next function-argument specifically on windows 7
  x64 using python 2.6. How do I do this?
  Thanks for any help
 
  If I'm not wrong, CPU management is handled by your system, meaning
  there's no way to 'force' anything to run on a specific CPU. However,
  you may try to execute your fonction in a subprocess, so that the system
  will use different CPUs (hopefully). You then just need to limit the
  number of subprocess alive at the same time.
 
  Have a look here
  http://docs.python.org/library/multiprocessing.html
 
  JM
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 

 Here's a way of doing what I think you mean to do. I assume that
 max_result should be the maximum value returned by a run of
 functionTester.

 Also, just a note, usually function names like this are spelled
 function_tester rather than functionTester in python.

 If you need to de-python3ify it just change the line at the top and
 cast your nums to floats, otherwise you'll get integer division (which
 I again assume you don't want).

 #! /usr/bin/env python3

 import time
 import multiprocessing


 def functionTester(num):
   return ((num+2)/(num-2))**2

 num_args = [61,62,33,7,12,16,19,35,36,37,38,55,56,57,63]

 num_processes = multiprocessing.cpu_count()
 pool = multiprocessing.Pool(num_processes)

 start = time.time()
 results = pool.map(functionTester, num_args)
 end = time.time()

 # is this what you meant to do with the results?
 max_result = max(results)
 print(Result  + str(max_result))

 elapsed = end - start
 print(Took, elapsed, seconds to execute)

 Geremy Condra

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run a function in another processor in python

2010-12-10 Thread Astan Chee
I just saw this:
http://bugs.python.org/issue8094
which seem to be similar to what I'm having. Does anyone know if there is a
fix for it?
Thanks again

On Fri, Dec 10, 2010 at 11:02 PM, Astan Chee astan.c...@gmail.com wrote:

 Thanks for that. I'll try and see if it makes any difference but I'm using
 python 2.6 not 3
 Are the multiprocessing modules different? That code (or whatever is using
 the multiprocessing module) seems to cause infinite python processes on my
 machine and eventually kills it.
 I'm running python 2.6 on windows 7 x64 is it the ammount of memory/cpu
 speed/number of cpu that is the issue?
 Thanks for any clarification



 On Fri, Dec 10, 2010 at 4:16 AM, geremy condra debat...@gmail.com wrote:

  On Thu, Dec 9, 2010 at 5:03 AM, Astan Chee astan.c...@gmail.com wrote:
  Thanks but I'm having trouble with that module too. Currently what I
  have is something like this:
 
  import sys
  import os
  import multiprocessing
 
  import time
 
  def functionTester(num):
 return ((num+2)/(num-2))**2
 
  num_args = [61,62,33,7,12,16,19,35,36,37,38,55,56,57,63]
 
  max_result = 0
 
  start = time.time()
 
  num_processes = multiprocessing.cpu_count()
 
  threads = []
  len_stas = len(num_args)
 
  for list_item in num_args:
 if len(threads)  num_processes:
 p =
 multiprocessing.Process(target=functionTester,args=[list_item])
 p.start()
 print p, p.is_alive()
 threads.append(p)
 else:
 for thread in threads:
 if not thread.is_alive():
 threads.remove(thread)
 
  print Result  + str(max_result)
  end = time.time()
  elapsed= end - start
  print Took, elapsed, seconds to execute
 
  But it doesn't give me any return data. It also spawns an infinite
  number of (sub)processes that crashes my machine. What am I doing
  wrong here?
 
  On 12/9/10, Jean-Michel Pichavant jeanmic...@sequans.com wrote:
  Astan Chee wrote:
  Hi,
  I've got a python script that calls a function many times with various
  arguments and returns a result. What I'm trying to do is run this
  function each on different processors and compile the result at the
  end based on the function result. The script looks something like
  this:
 
 
  import time
 
  def functionTester(num):
  return ((num+2)/(num-2))**2
 
  num_args = [1,2,3,7,12,16,19,35,36,37,38,55,56,57,63,44,71,81,91]
 
  max_result = 0
 
  start = time.time()
 
  for n in num_args:
  result = functionTester(n)
  if result  max_result:
  max_result = result
 
  print Result  + str(max_result)
  end = time.time()
  elapsed= end - start
  print Took, elapsed, seconds to execute
 
 
  What I'm trying to do is run each function on a processor and when its
  done, move on to the next function-argument specifically on windows 7
  x64 using python 2.6. How do I do this?
  Thanks for any help
 
  If I'm not wrong, CPU management is handled by your system, meaning
  there's no way to 'force' anything to run on a specific CPU. However,
  you may try to execute your fonction in a subprocess, so that the
 system
  will use different CPUs (hopefully). You then just need to limit the
  number of subprocess alive at the same time.
 
  Have a look here
  http://docs.python.org/library/multiprocessing.html
 
  JM
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 

 Here's a way of doing what I think you mean to do. I assume that
 max_result should be the maximum value returned by a run of
 functionTester.

 Also, just a note, usually function names like this are spelled
 function_tester rather than functionTester in python.

 If you need to de-python3ify it just change the line at the top and
 cast your nums to floats, otherwise you'll get integer division (which
 I again assume you don't want).

 #! /usr/bin/env python3

 import time
 import multiprocessing


 def functionTester(num):
   return ((num+2)/(num-2))**2

 num_args = [61,62,33,7,12,16,19,35,36,37,38,55,56,57,63]

 num_processes = multiprocessing.cpu_count()
 pool = multiprocessing.Pool(num_processes)

 start = time.time()
 results = pool.map(functionTester, num_args)
 end = time.time()

 # is this what you meant to do with the results?
 max_result = max(results)
 print(Result  + str(max_result))

 elapsed = end - start
 print(Took, elapsed, seconds to execute)

 Geremy Condra



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run a function in another processor in python

2010-12-10 Thread Astan Chee
On Fri, Dec 10, 2010 at 1:37 AM, Peter Otten __pete...@web.de wrote:

 I can't replicate the crash. However, your problem looks like there is a
 ready-to-use solution:

 http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers

 --
 http://mail.python.org/mailman/listinfo/python-list


Pool.map doesn't seem to be able to support multiple argument functions
which is what I'm trying to do here. Any other suggestions?
Thanks again
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run a function in another processor in python

2010-12-10 Thread Astan Chee
Sorry about that, here is a summary of my complete code. I haven't cleaned
it up much or anything, but this is what it does:

import time
import multiprocessing

test_constx =0
test_consty =0

def functionTester(x):
  global test_constx
  global test_consty
  print constx  + str(test_constx)
  print consty  + str(test_consty)
  return (test_constx*x[0]-x[1]+test_consty*x[0]+x[2])

def functionTesterMain(constx,consty):
  global test_constx
  global test_consty
  test_constx = constx
  test_consty = consty
  num_args =
[(61,12,1),(61,12,2),(61,12,3),(61,11,4),(61,12,4),(62,33,4),(7,12,4),(16,19,4),(35,36,4),(37,38,3),(55,56,3),(57,63,3)]
  num_processes = multiprocessing.cpu_count()
  pool = multiprocessing.Pool(num_processes)
  rs = []
  start = time.time()
  rs = pool.map(functionTester,num_args)
  end = time.time()
  elapsed= end - start
  min = elapsed/60
  print Took, elapsed, seconds to run, which is the same as, min,
minutes
  pos = 0
  high = 0
  n = None
  for r in rs:
if r  high:
  n = num_args[pos]
  high = r
pos+=1
  print high  + str(high)
  print n  + str(n)

  return high,n

if __name__ == '__main__':
  for i in range(1,4):
a,b = functionTesterMain(i,7)
print ---
print a  + str(a)
print b  + str(a)


  Which doesn't seem to work because the functionTester() needs to be
simpler and not use global variables.
I'm using global variables because I'm also trying to pass a few other
variables and I tried using a class but that just gave me a unpickleable
error. I tried using zip but I'm confused with how I can get to pass the
data.
I know I can probably combine the data into tuples but that means that there
is alot of data duplication, especially if the constx and consty are large
dictionaries (or even custom objects), which might happen later.
So it seems that map doesn't quite like functions like these. Anyway, I'll
try and see if threads or something can substitute. I'd appriciate any help.
Thanks



On Sat, Dec 11, 2010 at 9:04 AM, geremy condra debat...@gmail.com wrote:

  On Fri, Dec 10, 2010 at 4:42 AM, Astan Chee astan.c...@gmail.com wrote:
  On Fri, Dec 10, 2010 at 1:37 AM, Peter Otten __pete...@web.de wrote:
 
  I can't replicate the crash. However, your problem looks like there is a
  ready-to-use solution:
 
 
 
 http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers
 
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 
  Pool.map doesn't seem to be able to support multiple argument functions
  which is what I'm trying to do here. Any other suggestions?
  Thanks again

 1. Post the real code you're using, and
 2. Put the arguments you want in a tuple and pass that. As an example,
 let's say I have the following function:

 def my_func(x, y, z):
return x + y * z

 you could rewrite this as:

 def my_func(*args):
return args[0] + args[1] * args[2]


 Here's a worked-out example:

 #! /usr/bin/env python3

 import multiprocessing

 def my_func(x, y, z):
return x + y * z

 def my_func_wrapper(t):
return my_func(*t)

 # assume we can get an iterable over each argument
 xs = [1, 2, 3, 4]
 ys = [5, 6, 7, 8]
 zs = [9, 1, 2, 3]

 # set up the pool to match the number of CPUs
 num_processes = multiprocessing.cpu_count()
 pool = multiprocessing.Pool(num_processes)

 #will call my_func(1, 5, 9), my_func(2, 6, 1), etc.
 results = pool.map(my_func_wrapper, zip(xs, ys, zs))
 print(results)


 Interesting factoid: you can't seem to use lambda or a decorator to do
 this, which would have been my first instinct. Pickle apparently
 chokes, although marshall wouldn't.

 Geremy Condra

-- 
http://mail.python.org/mailman/listinfo/python-list


run a function in another processor in python

2010-12-09 Thread Astan Chee
Hi,
I've got a python script that calls a function many times with various
arguments and returns a result. What I'm trying to do is run this
function each on different processors and compile the result at the
end based on the function result. The script looks something like
this:


import time

def functionTester(num):
return ((num+2)/(num-2))**2

num_args = [1,2,3,7,12,16,19,35,36,37,38,55,56,57,63,44,71,81,91]

max_result = 0

start = time.time()

for n in num_args:
result = functionTester(n)
if result  max_result:
max_result = result

print Result  + str(max_result)
end = time.time()
elapsed= end - start
print Took, elapsed, seconds to execute


What I'm trying to do is run each function on a processor and when its
done, move on to the next function-argument specifically on windows 7
x64 using python 2.6. How do I do this?
Thanks for any help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run a function in another processor in python

2010-12-09 Thread Astan Chee
Thanks but I'm having trouble with that module too. Currently what I
have is something like this:

import sys
import os
import multiprocessing

import time

def functionTester(num):
return ((num+2)/(num-2))**2

num_args = [61,62,33,7,12,16,19,35,36,37,38,55,56,57,63]

max_result = 0

start = time.time()

num_processes = multiprocessing.cpu_count()

threads = []
len_stas = len(num_args)

for list_item in num_args:
if len(threads)  num_processes:
p = multiprocessing.Process(target=functionTester,args=[list_item])
p.start()
print p, p.is_alive()
threads.append(p)
else:
for thread in threads:
if not thread.is_alive():
threads.remove(thread)

print Result  + str(max_result)
end = time.time()
elapsed= end - start
print Took, elapsed, seconds to execute

But it doesn't give me any return data. It also spawns an infinite
number of (sub)processes that crashes my machine. What am I doing
wrong here?

On 12/9/10, Jean-Michel Pichavant jeanmic...@sequans.com wrote:
 Astan Chee wrote:
 Hi,
 I've got a python script that calls a function many times with various
 arguments and returns a result. What I'm trying to do is run this
 function each on different processors and compile the result at the
 end based on the function result. The script looks something like
 this:


 import time

 def functionTester(num):
 return ((num+2)/(num-2))**2

 num_args = [1,2,3,7,12,16,19,35,36,37,38,55,56,57,63,44,71,81,91]

 max_result = 0

 start = time.time()

 for n in num_args:
 result = functionTester(n)
 if result  max_result:
 max_result = result

 print Result  + str(max_result)
 end = time.time()
 elapsed= end - start
 print Took, elapsed, seconds to execute


 What I'm trying to do is run each function on a processor and when its
 done, move on to the next function-argument specifically on windows 7
 x64 using python 2.6. How do I do this?
 Thanks for any help

 If I'm not wrong, CPU management is handled by your system, meaning
 there's no way to 'force' anything to run on a specific CPU. However,
 you may try to execute your fonction in a subprocess, so that the system
 will use different CPUs (hopefully). You then just need to limit the
 number of subprocess alive at the same time.

 Have a look here
 http://docs.python.org/library/multiprocessing.html

 JM

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RCX using python serial help

2010-12-08 Thread Astan Chee
Thanks for that help. I really appriciate it.
My next question is how do I code or what is the checksum? The sum of
opcode and arguments in hex and then mod 256? Does it include the
compliment opcode and arguments as well? Is the checksum compliment
equal to the sum of the opcode (and arguments) compliment?
Thanks again for the clarification

On 12/8/10, MRAB pyt...@mrabarnett.plus.com wrote:
 On 06/12/2010 15:37, Astan Chee wrote:
 Hi,
 I've got a lego mindstorm RCX 1.0 (but firmware is 2.0) that uses one of
 those old serial IR towers to control the microcontroller. I've had a
 look around at python's serial documentation as well as the RCX's
 documentation and I'm trying to write something to control the RCX
 directly using python. Several examples from of doing this in python
 include using lnp (i think) and that doesn't quite run well in windows.
 I've had a look at the C++ code and some protocol documentation here:
 http://www.generation5.org/content/2001/rob08.asp and converted it to
 python. I've attached it at the end of the email. So now I've figured
 out how to check for the battery level and it seems to work (I've tested
 it on my RCX) but I'm confused with the other documentation (e.g.
 http://graphics.stanford.edu/~kekoa/rcx/ ) about how to do this in
 python or what this all means. I was wondering if anyone can help me
 complete these? or maybe help me do it step-by-step?
 Thanks for any help.
 [snip]
 Here's a brief summary of the protocol:

 A command or request to the microcontroller is a packet consisting of a
 header, an opcode, arguments, and a checksum.

   The header used in the documentation is 0x55, 0xFF, 0x00.

   The opcode is 1 byte, followed by its one's complement.

   The argument is 0 or more bytes, each followed by its one's complement.

   The checksum is the sum of the opcode and the arguments, modulo 256,
 followed by its one's complement.

 A reply from the microcontroller is also a packet consisting of a
 header, an opcode, arguments, and a checksum.

   The header is the same as the original command or request.

   The opcode is the one's complement of the original opcode, followed by
 its one's complement (ie, the original opcode).

   The argument is 0 or more bytes, each followed by its one's complement.

   The checksum is the sum of the opcode and the arguments, modulo 256,
 followed by its one's complement.

 The microcontroller will ignore a packet whose opcode is the same as the
 previous one; this is to prevent unintended duplicates due to
 communication errors.

 Each opcode has 2 alternatives, one with bit 3 clear and the other with
 bit 3 set (bitwise-ored with 0x08), so if you do want to send a command
 or request with the same opcode as the previous packet you can just use
 the alternative form.
 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


RCX using python serial help

2010-12-06 Thread Astan Chee
Hi,
I've got a lego mindstorm RCX 1.0 (but firmware is 2.0) that uses one of
those old serial IR towers to control the microcontroller. I've had a look
around at python's serial documentation as well as the RCX's documentation
and I'm trying to write something to control the RCX directly using python.
Several examples from of doing this in python include using lnp (i think)
and that doesn't quite run well in windows. I've had a look at the C++ code
and some protocol documentation here:
http://www.generation5.org/content/2001/rob08.asp and converted it to
python. I've attached it at the end of the email. So now I've figured out
how to check for the battery level and it seems to work (I've tested it on
my RCX) but I'm confused with the other documentation (e.g.
http://graphics.stanford.edu/~kekoa/rcx/ ) about how to do this in python or
what this all means. I was wondering if anyone can help me complete these?
or maybe help me do it step-by-step?
Thanks for any help.

Below is the python code I've been working on:

import time
import serial
import struct
import binascii

def tcbin(x, y=8):

This function returns the padded, two's complement representation of x,
in y-bits.
It is conventional for y to be 8, 16, 32 or 64, though y can have any
non-zero positive value.

if x = 0:
binstr = bin(x)
# pad with leading zeros
while len(binstr)  y + 2:
binstr = 0b0 + binstr[2:]
return binstr
return bin((2**y) + x) # x is negative

def bitcompliment(hex_code):
return hex(int(tcbin(~(ord(hex_code))),2))

def processOutput(raw_data,output):
outputStatus = True
pos = 0
for i in range(3):
if raw_data[i] != output[i]:
outputStatus = False
pos+=1
if outputStatus:
print output OK
else:
print problem with output
outputCompliment = True
while outputCompliment:
if hex(ord(output[pos])) == bitcompliment(output[pos+1]):
print output compliment OK
else:
print problem with output compliment
pos+=2
if hex(ord(output[pos])) == '0x55' and hex(ord(output[pos+1])) ==
'0xff' and hex(ord(output[pos+2])) == '0x0':
pos+=3
outputCompliment = False
if hex(ord(output[pos])) == '0xcf' or hex(ord(output[pos])) == '0xc7':
#battery checker
pos+=2
if hex(ord(output[pos])) == bitcompliment(output[pos+1]) and
hex(ord(output[pos+2])) == bitcompliment(output[pos+3]):
s = ((ord(output[pos+2]) * 256) + ord(output[pos])) / 1000.0
print Battery is at  + str(s) +  Volts
else:
for i in range(len(output[pos:]),len(output),2):
print hex(ord(output[i]))
if i+1  len(output):
if hex(ord(output[i])) == bitcompliment(output[i+1]):
print message OK. contents:  +
hex(ord(output[i]))

# configure the serial connections (the parameters differs on the device you
are connecting to)
ser = serial.Serial(
 port='COM1',
 baudrate=2400,
 parity=serial.PARITY_ODD,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.EIGHTBITS
)
raw_data = '\x55\xff\x00\x38\xc7\x38\xc7'
result = ser.write(raw_data)
out = ''
time.sleep(1) #pause for a second
while ser.inWaiting()  0:
out+=ser.read(1)
processOutput(raw_data,out)
-- 
http://mail.python.org/mailman/listinfo/python-list


webcam in gtalk/xmpp

2010-09-14 Thread Astan Chee

Hi,
I was wondering if there is an implementation in any of the xmpp python 
API (e.g. xmpppy, etc) that implements broadcasting webcam (as well as 
audio-chat). The documentation on xmpppy doesn't show me how this can be 
done. Is this even possible?

Thanks
Astan
--
http://mail.python.org/mailman/listinfo/python-list


killing all subprocess childrens

2010-09-01 Thread Astan Chee

Hi,
I have a piece of code that looks like this:

import subprocess
retcode = subprocess.call([java,test,string])
print Exited with retcode  + str(retcode)

What I'm trying to do (and wondering if its possible) is to make sure 
that any children (and any descendants) of this process is killed when 
the main java process is killed (or dies).

How do I do this in windows, linux and OSX?
Thanks
Astan

--
http://mail.python.org/mailman/listinfo/python-list


Re: killing all subprocess childrens

2010-09-01 Thread Astan Chee

Chris Rebert wrote:

import os
import psutil # http://code.google.com/p/psutil/

# your piece of code goes here

myself = os.getpid()
for proc in psutil.process_iter():
  
Is there a way to do this without psutil or installing any external 
modules or doing it from python2.5?

Just wondering.
Thanks again

if proc.ppid == myself:
proc.kill()

Cheers,
Chris
--
http://blog.rebertia.com
  

--
http://mail.python.org/mailman/listinfo/python-list


equivalent of source file in python?

2010-08-24 Thread Astan Chee

Hi,
I'm trying to convert my tcsh script to python and am stuck at one part, 
particularly the part of the script that looks like this:


#!/bin/tcsh
setenv LSFLOG /var/tmp/lsf_log
source /etc/setup
unalias cp
umask 0
env  ${AFLOG}

What is the equivalent of doing this in python2.5?
Thanks again
--
http://mail.python.org/mailman/listinfo/python-list


Re: equivalent of source file in python?

2010-08-24 Thread Astan Chee
Thanks for all the help. I think Chris's answer is the one I can use. I 
know its probably better to convert the /etc/setup file into python but 
it'll do for now.
Also, the entire tsch script is just setting up env vars and such; 
various mvs and cps. Not really executing anything.

Thanks again for the help.


Chris Rebert wrote:

On Tue, Aug 24, 2010 at 12:18 PM, Astan Chee astan.c...@al.com.au wrote:
  

Hi,
I'm trying to convert my tcsh script to python and am stuck at one part,
particularly the part of the script that looks like this:

#!/bin/tcsh
setenv LSFLOG /var/tmp/lsf_log
source /etc/setup
unalias cp
umask 0
env  ${AFLOG}

What is the equivalent of doing this in python2.5?



I agree with Stefan, but anyway, here's an approximate untested
literal translation:

import os
import subprocess

os.environ['LSFLOG'] = '/var/tmp/lsf_log'
subprocess.check_call(['tcsh', '/etc/setup'])
os.umask(0)
out = open(os.environ['AFLOG'], 'a')
subprocess.check_call(['env'], stdout=out)
out.close()

Cheers,
Chris
--
http://blog.rebertia.com
  
-- 
http://mail.python.org/mailman/listinfo/python-list


executing python scripts within wx frames

2010-07-13 Thread Astan Chee

Hi,
I'm trying to make one of those frames thats similar to the wx python 
demo where a folder is filled with demo wx python scripts and there is 
one main script that opens the other ones in as different items in a 
tree/notebook.
I've gotten most of it figured out except the part where the scripts are 
executed in a wx frame. The difference between what I'm trying to do and 
the wx python demo one is that mine are generic scripts that output the 
results to std out/error (or whatever gets displayed in IDLE). Does 
anyone know how I can do this? Simulate a IDLE or python shell in one of 
the frames thats basically the output of whatever script has been 
selected to run?

It would be better if the solution was platform independent too.
Thanks for any suggestions
--
http://mail.python.org/mailman/listinfo/python-list


sound effects in python

2010-05-18 Thread Astan Chee

Hi,
I have a sound file (e.g. .wav; .mp3, etc) in python that I'd like to 
modify (e.g. change tempo, pitch, add echo, amplify, etc).
Any recommendation on how I can achieve this in python independent of 
platform?

Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: calculating a string equation

2010-02-20 Thread Astan Chee

Arnaud Delobelle wrote:

Astan Chee astan.c...@al.com.au writes:

  

Hi,
I have some variables in my script that looks like this:
vars = {'var_a':'10','var_b':'4'}
eqat = (var_a/2.0) = var_b
result = (var_a+var_b)/7
What I'm trying to do is to plug in var_a and var_b's values from vars
into eqat and see if eqat returns true or false as well as getting the
value of result if these variables were plugged in. How do I do
this?
I'm also expecting eqat and result to contain various python
mathematical operators like **, and compounded ()'s.
I'm not sure how to convert the equation; if I have to make a bunch of
if-statements or if there is a python function that already does
something like this.



Yes: eval()

  

vars = {'var_a':10 ,'var_b':4}
eqat = (var_a/2.0) = var_b
result = (var_a+var_b)/7
eval(eqat, vars)


False

Hi,
I now have a slight problem with this. This doesnt seem to work:
 vars = {'var a':10 ,'var b':4}
 eqat = (var a/2.0) = var b
 eval(eqat, vars)

Traceback (most recent call last):
 File pyshell#11, line 1, in module
   eval(eqat, vars)
 File string, line 1
   (var a/2.0) = var b
^
SyntaxError: invalid syntax

So eval can't take spaces? is there a way to go around this?
Thanks again for any suggestions
Cheers
Astan

-- 
http://mail.python.org/mailman/listinfo/python-list


calculating a string equation

2010-02-11 Thread Astan Chee

Hi,
I have some variables in my script that looks like this:
vars = {'var_a':'10','var_b':'4'}
eqat = (var_a/2.0) = var_b
result = (var_a+var_b)/7
What I'm trying to do is to plug in var_a and var_b's values from vars 
into eqat and see if eqat returns true or false as well as getting the 
value of result if these variables were plugged in. How do I do this?
I'm also expecting eqat and result to contain various python 
mathematical operators like **, and compounded ()'s.
I'm not sure how to convert the equation; if I have to make a bunch of 
if-statements or if there is a python function that already does 
something like this.

Thanks for any help.
Cheers
Astan

--
http://mail.python.org/mailman/listinfo/python-list


Re: converting XML to hash/dict/CustomTreeCtrl

2010-02-03 Thread Astan Chee

Nobody wrote:

The code you're using expects the XML to follow a particular format, and
yours doesn't.

You might want to start with a fairly direct translation, e.g.:

def xmldict(e):
d = {}
d['tag'] = e.tag
d.update(e.attrib)
children = map(xmldict, e)
if children:
d['children'] = children
text = e.text.strip()
if text:
d['text'] = text
return d

tree = ElementTree.parse('test.xml')
root = tree.getroot()
d = xmldict(root)
pprint.pprint(d)

then refine this as needed.
  

Thanks, that is simple enough for me to understand. I think I got it now.
Thanks again
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting XML to hash/dict/CustomTreeCtrl

2010-02-02 Thread Astan Chee

Hi,
Sorry for being vague but here my question about converting an xml into 
a dict. I found some examples online but none gives the dict/result I 
want. The xml looks like this:

doc
   stats name=position1 description=Calculation statistics
kind=position
   stats name=time description=Timing summary kind=section
   string name=timersNote description=Note:This is the note
on calculation times/string
   stats name=timers kind=timers

   timer name=totaltime description=Total time
   elapsed609.081574/elapsed
   user2531.972081/user
   system65.119100/system
   /timer
   timer name=partialTimer description=Gravitational Displacement
   elapsed1772.011230/elapsed
   /timer
   stats name=subTimers description=All non-phased time 
kind=timers

   timer name=subATimer description=Phase time A
   elapsed72.418861/elapsed
   /timer

   timer name=subBTimer description=Phase time B
   elapsed28.285192/elapsed
   /timer
   timer name=spaceMem description=Space memory
   elapsed0.000/elapsed
   /timer
   /stats
   timer name=endTime description=End
   elapsed607.432373/elapsed
   /timer
   /stats
   /stats
   stats name=space description=Space usage summary kind=section
   stats name=systemSpace description=System Space
   memory name=heapSpace description=Total Space
   peak483328/peak

   current483328/current
   /memory
   memory name=spaceResidentSize description=Space resident size
   peak4182777856/peak
   current4182777856/current
   /memory
   int name=pageMem1/int

   int name=memReclaims1943498/int
   int name=memSwaps0/int
   /stats
   stats name=subsystems kind=memstats
   memory name=geoSpace description=Geo-Space
   peak1640100156/peak
   current411307840/current
   /memory
   memory name=gridSpace description=Grid-Space
   peak709596712/peak
   current1406752/current
   /memory
   memory name=spaceMem description=Space memory
   peak737720720/peak
   current0/current
   /memory
   memory name=endTime description=End
   peak607.432373/peak
   /memory
   /stats
   memory name=subsystemSpace description=Subsystem space
total
   peak5164184694/peak
   current2054715622/current
   /memory
  
   /stats

   /stats
/doc

using this script (taken from http://code.activestate.com/recipes/410469/):
from xml.etree import cElementTree as ElementTree

class XmlListConfig(list):
   def __init__(self, aList):
   for element in aList:
   if element:
   # treat like dict
   if len(element) == 1 or element[0].tag != element[1].tag:
   self.append(XmlDictConfig(element))
   # treat like list
   elif element[0].tag == element[1].tag:
   self.append(XmlListConfig(element))
   elif element.text:
   text = element.text.strip()
   if text:
   self.append(text)


class XmlDictConfig(dict):
   '''
   Example usage:

tree = ElementTree.parse('your_file.xml')
root = tree.getroot()
xmldict = XmlDictConfig(root)

   Or, if you want to use an XML string:

root = ElementTree.XML(xml_string)
xmldict = XmlDictConfig(root)

   And then use xmldict for what it is... a dict.
   '''
   def __init__(self, parent_element):
   if parent_element.items():
   self.update(dict(parent_element.items()))
   for element in parent_element:
   if element:
   # treat like dict - we assume that if the first two tags
   # in a series are different, then they are all different.
   if len(element) == 1 or element[0].tag != element[1].tag:
   aDict = XmlDictConfig(element)
   # treat like list - we assume that if the first two tags
   # in a series are the same, then the rest are the same.
   else:
   # here, we put the list in dictionary; the key is the
   # tag name the list elements all share in common, and
   # the value is the list itself
   aDict = {element[0].tag: XmlListConfig(element)}
   # if the tag has attributes, add those to the dict
   if element.items():
   aDict.update(dict(element.items()))
   self.update({element.tag: aDict})
   # this assumes that if you've got an attribute in a tag,
   # you won't be having any text. This may or may not be a
   # good idea -- time will tell. It works for the way we are
   # currently doing XML configuration files...
   elif element.items():
   self.update({element.tag: dict(element.items())})
   # finally, if 

converting XML to hash/dict/CustomTreeCtrl

2010-02-01 Thread Astan Chee

Hi,
I have xml files that I want to convert to a hash/dict and then further 
placed in a wx CustomTreeCtrl based on the structure. The problem I am 
having now is that the XML file is very unusual and there aren't any 
unique identifiers to be put in a dict and because there are no unique 
variables, finding the value of it from a CustromTreeCtrl is abit tricky.

I would appreciate any help or links to projects similar to this.
Thanks

The XML file looks something like this:
doc
rm:statsDoc xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance;
   stats name=position1 description=Calculation statistics 
kind=position

   stats name=time description=Timing summary kind=section
   string name=timersNote description=Note:This is the note 
on calculation times/string

   stats name=timers kind=timers

   timer name=totaltime description=Total time
   elapsed609.081574/elapsed
   user2531.972081/user
   system65.119100/system
   /timer
   timer name=partialTimer description=Gravitational Displacement
   elapsed1772.011230/elapsed
   /timer
   stats name=subTimers description=All non-phased time 
kind=timers

   timer name=subATimer description=Phase time A
   elapsed72.418861/elapsed
   /timer

   timer name=subBTimer description=Phase time B
   elapsed28.285192/elapsed
   /timer
   timer name=spaceMem description=Space memory
   elapsed0.000/elapsed
   /timer
   /stats
   timer name=endTime description=End
   elapsed607.432373/elapsed
   /timer
   /stats
   /stats
   stats name=space description=Space usage summary kind=section
   stats name=systemSpace description=System Space
   memory name=heapSpace description=Total Space
   peak483328/peak

   current483328/current
   /memory
   memory name=spaceResidentSize description=Space resident size
   peak4182777856/peak
   current4182777856/current
   /memory
   int name=pageMem1/int

   int name=memReclaims1943498/int
   int name=memSwaps0/int
   /stats
   stats name=subsystems kind=memstats
   memory name=geoSpace description=Geo-Space
   peak1640100156/peak
   current411307840/current
   /memory
   memory name=gridSpace description=Grid-Space
   peak709596712/peak
   current1406752/current
   /memory
   memory name=spaceMem description=Space memory
   peak737720720/peak
   current0/current
   /memory
   memory name=endTime description=End
   peak607.432373/peak
   /memory
   /stats
   memory name=subsystemSpace description=Subsystem space 
total

   peak5164184694/peak
   current2054715622/current
   /memory

   /stats
   /stats
/rm:statsDoc
/doc

--
http://mail.python.org/mailman/listinfo/python-list


Help with invoking standard mail app in windows

2009-12-18 Thread Astan Chee

Hi,
I'm trying to launch standard mail app in windows and after looking 
around most look like this:


import urllib, webbrowser, win32api
def mailto_url(to=None,subject=None,body=None,cc=None):
   
   encodes the content as a mailto link as described on
   http://www.faqs.org/rfcs/rfc2368.html
   
   url = mailto:  + urllib.quote(to.strip(),@,)
   sep = ?
   if cc:
   url+= sep + cc= + urllib.quote(cc,@,)
   sep = 
   if subject:
   url+= sep + subject= + urllib.quote(subject,)
   sep = 
   if body:
   # Also note that line breaks in the body of a message MUST be
   # encoded with %0D%0A. (RFC 2368)
   body=\r\n.join(body.splitlines())
   url+= sep + body= + urllib.quote(body,)
   sep = 
   return url

url = mailto_url(txtTo,txtSubject,body,txtCC)
# win32api.ShellExecute(0,'open',url,None,None,0)
webbrowser.open(url,new=1)
# os.startfile(url)

all of these are having WindowsError : [Error 5] Access is denied 
errors. I'm using windows xp and python 2.5. I have outlook 2007 
installed as a default mail client. Clicking on any mailto links in html 
brings up the normal write mail from the mail client. Any ideas why this 
is happening or how do I debug what access is being denied?

Thanks for any help
Astan
--
http://mail.python.org/mailman/listinfo/python-list


Help with invoking standard mail app in windows

2009-12-18 Thread Astan Chee

Hi,
I don't know if my last mail made it or not but here it is again.
I'm trying to launch standard mail app in windows and after looking 
around most look like this:


import urllib, webbrowser, win32api
def mailto_url(to=None,subject=None,body=None,cc=None):
   
   encodes the content as a mailto link as described on
   http://www.faqs.org/rfcs/rfc2368.html
   
   url = mailto:  + urllib.quote(to.strip(),@,)
   sep = ?
   if cc:
   url+= sep + cc= + urllib.quote(cc,@,)
   sep = 
   if subject:
   url+= sep + subject= + urllib.quote(subject,)
   sep = 
   if body:
   # Also note that line breaks in the body of a message MUST be
   # encoded with %0D%0A. (RFC 2368)
   body=\r\n.join(body.splitlines())
   url+= sep + body= + urllib.quote(body,)
   sep = 
   return url

url = mailto_url(txtTo,txtSubject,body,txtCC)
# win32api.ShellExecute(0,'open',url,None,None,0)
webbrowser.open(url,new=1)
# os.startfile(url)

all of these are having WindowsError : [Error 5] Access is denied 
errors. I'm using windows xp and python 2.5. I have outlook 2007 
installed as a default mail client. Clicking on any mailto links in html 
brings up the normal write mail from the mail client. Any ideas why this 
is happening or how do I debug what access is being denied?

Thanks for any help
Astan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with invoking standard mail app in windows

2009-12-18 Thread Astan Chee

Kev Dwyer wrote:

Hello Astan,

Your code executes without error for me on Win98 (!) with Python 2.5 or 
XP with Python 2.6.  

It would help people to help you if you could provide the *exact* console 
output from when you try to execute the code, *including* the traceback.  
That way we can work out which line of code is hitting the exception.


Cheers,

Kev

  

Hi,
My mistake. The length of body is over 1400 characters. Here is my 
updated code and result:


import urllib, webbrowser, win32api
def mailto_url(to=None,subject=None,body=None,cc=None):
   
   encodes the content as a mailto link as described on
   http://www.faqs.org/rfcs/rfc2368.html 
   url = mailto:  + urllib.quote(to.strip(),@,)
   sep = ?
   if cc:
   url+= sep + cc= + urllib.quote(cc,@,)
   sep = 
   if subject:
   url+= sep + subject= + urllib.quote(subject,)
   sep = 
   if body:
   # Also note that line breaks in the body of a message MUST be
   # encoded with %0D%0A. (RFC 2368)
   body=\r\n.join(body.splitlines())
   url+= sep + body= + urllib.quote(body,)
   sep = 
   return url

txtTo = t...@com.com
txtSubject = Test Subject
body = Test body
for t in range(278):
   body+=test 
txtCC = cc_t...@com.com

url = mailto_url(txtTo,txtSubject,body,txtCC)
#win32api.ShellExecute(0,'open',url,None,None,0)
webbrowser.open(url,new=1)
# os.startfile(url)

result:

Traceback (most recent call last):
 File C:/stanc_home/python/mail_test.py, line 32, in module
   webbrowser.open(url,new=1)
 File C:\Python25\lib\webbrowser.py, line 61, in open
   if browser.open(url, new, autoraise):
 File C:\Python25\lib\webbrowser.py, line 518, in open
   os.startfile(url)
WindowsError: [Error 5] Access is denied: 'mailto: 
t...@com.com?cc=cc_test@com.comsubject=Test%20Subjectbody=Test%20bodytest%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20te

st%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test
%20test%20test%20test%20test%20test%20'

Is there some sort of limitation here? If I shorten the string, it works 
fine. You're right, but I'm wondering if there is a way to go around 
this limitation.

Thanks again
Cheers
Astan

--
http://mail.python.org/mailman/listinfo/python-list


Re: ignore special characters in python regex

2009-07-21 Thread Astan Chee

I think the re.escape did the trick.
to answer your questions:
By ignore i meant instead of using non-alphanumeric characters that 
have special significance in regular expression (e.g. [|\]) and treat 
them as normal strings (i.e preceded by \), but since I don't know all 
the characters in regular expression that have special significance, I 
don't know which ones to add a '\' infront of.

Thanks anyway

John Machin wrote:

On Jul 21, 3:02 pm, Astan Chee astan.c...@al.com.au wrote:
  

Hi,
I'm reading text from a file (per line) and I want to do a regex using
these lines but I want the regex to ignore any special characters and
treat them like normal strings.
Is there a regex function that can do this?



It would help if you were to say

(1) what ignore ... characters means -- pretend they don't exist?
(2) what are special chararacters -- non-alphanumeric?
(3) what treat them like normal strings means
(4) how you expect these special characters to be (a) ignored and (b)
treated like normal strings /at the same time/.

Cheers,
John
  
-- 
http://mail.python.org/mailman/listinfo/python-list


ignore special characters in python regex

2009-07-20 Thread Astan Chee

Hi,
I'm reading text from a file (per line) and I want to do a regex using 
these lines but I want the regex to ignore any special characters and 
treat them like normal strings.

Is there a regex function that can do this?
Here is what I have so far:
fp = open('file.txt','r')
notes = fp.readlines()
fp.close()
strin = this is what I want
for note in notes:
if re.search(r+ str(note) + ,strin):
  print Found  + str(note) +  in  + strin

Thanks for any help
--
http://mail.python.org/mailman/listinfo/python-list


Re: copytree with timeout in windows

2009-07-07 Thread Astan Chee

Tim Golden wrote:

Astan Chee wrote:
  

Hi,
I'm trying to modify the copytree function in shutil so that any file 
being copied does not take more than 5 minutes (if it does, skip to the 
next one). 



One suggestion is to use the CopyFileEx API
exposed in the win32file module from pywin32. That
allows for a callback function which can abort
the copy (or issue a progress meter, etc.).
  
Thanks, but looking in the documentation there is no callback function. 
Did you mean */the Progress Routine?

Thanks again
/*

Obviously, you'd have to roll your own copytree, but
that's not beyond the wit of man.

TJG
  
-- 
http://mail.python.org/mailman/listinfo/python-list


copytree with timeout in windows

2009-07-06 Thread Astan Chee

Hi,
I'm trying to modify the copytree function in shutil so that any file 
being copied does not take more than 5 minutes (if it does, skip to the 
next one). This is what I have so far:


import shutil
import signal, os

def handler(signum, frame):
   print 'Signal handler called with signal', signum
   raise IOError, Couldn't open device!

signal.signal(signal.SIGALRM, handler)

def copytree(src, dst):
   names = os.listdir(src)
   os.makedirs(dst)
   signal.alarm(0)
   for name in names:
   if name in ignored_names:
   continue
   srcname = os.path.join(src, name)
   dstname = os.path.join(dst, name)
   try:
   if os.path.isdir(srcname):
   copytree(srcname, dstname, symlinks, ignore)
   else:
   signal.alarm(300)
   shutil.copy2(srcname, dstname)
   except (IOError, os.error), why:
   print str(why)
   # catch the Error from the recursive copytree so that we can
   # continue with other files
   except Error, err:
   print str(err.args[0])

source = c:\\testwa\\
destination = d:\\testwa\\

copytree(source,destination)

Then I re-read the documentation which said that signal.SIGALRM is 
unix/linux only. How do I go about doing this in windows?

Thanks for any help.
Cheers
Astan


--
http://mail.python.org/mailman/listinfo/python-list


square box graph (?) API in python

2009-06-22 Thread Astan Chee

Hi,
I'm trying to graph something that looks like the bottom half of this 
http://windirstat.info/images/windirstat.jpg
I was wondering if there is any API in python or wxPython specifically 
to do this?
I know it is possible to do calculation manually and use floatcanvas or 
something similar but I was wondering if something like this has already 
been done.

Cheers
Astan
--
http://mail.python.org/mailman/listinfo/python-list


square box graph (?) API in python

2009-06-22 Thread Astan Chee

Hi,
I'm trying to graph something that looks like the bottom half of this 
http://windirstat.info/images/windirstat.jpg
I was wondering if there is any API in python or wxPython specifically 
to do this?
I know it is possible to do calculation manually and use floatcanvas or 
something similar but I was wondering if something like this has already 
been done.

Cheers
Astan

--
http://mail.python.org/mailman/listinfo/python-list


factoring wx.Image

2009-02-26 Thread Astan Chee

Hi,
I want to factor (red, green and blue at the same time) an image using 
wx but without any GUI display or windows but it keeps crashing and if I 
set the checks to ignore it, it doesn't produce the images at all.

It looks like this:

import wx
img = wx.Image(star.jpg,wx.BITMAP_TYPE_BMP)
factor = 1
for i in range(1,30):
   image = img.AdjustChannels(factor, factor, factor, 1)
   fname = star. + str(factor) + .jpg
   img.SaveFile(fname,wx.BITMAP_TYPE_JPEG)
   factor+=1

What am I missing here? What am I doing wrong? Can this even be done 
with only wx?

Thanks for any help.
Cheers
Astan

--
http://mail.python.org/mailman/listinfo/python-list


get most common number in a list with tolerance

2009-02-20 Thread Astan Chee

Hi,
I have a list that has a bunch of numbers in it and I want to get the 
most common number that appears in the list. This is trivial because i 
can do a max on each unique number. What I want to do is to have a 
tolerance to say that each number is not quite unique and if the 
difference from other numbers is small, than it can be counted together. 
This is what I have to get the common number (taken from the internet 
somewhere):


l = [10,30,20,20,11,12]
d = {}
tolerance = 5
for elm in l:
   d[elm] = d.get(elm, 0) + 1
counts = [(j,i) for i,j in d.items()]



This of course returns a list where each of them is unique

[(1, 12), (1, 10), (1, 11), (2, 20), (1, 30)]

but I am expecting a list that looks like this:

[(3, 10), (2, 20), (1, 30)]

What do I need to add?
Thanks for any help.
Cheers
Astan
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-26 Thread Astan Chee


Brian Allen Vanderburg II wrote:

This is the FT245 chip which is basically USB-to-Parallel.

Chips: http://www.ftdichip.com/Products/FT245R.htm
Kit/Board: http://www.ftdichip.com/Products/EvaluationKits/UM245R.htm

The spec sheet for the board seems quite simple.  It's pin out is 
similar to that of a parallel port in that you have your data lines 
DB0-DB7, etc.  It can also be connected in bus-powered configuration 
(~100mA) or self-powered configuration.  The kit is more expensive than 
the chip itself, but probably easier especially if you don't have any 
experience with surface mount.


  
That is a good idea. The main factor (aside from complexity) that I 
forgot to mention is the cost. I live very far away from the US and 
sometimes it is cheaper to buy a microcontroller here than have bits n 
pieces shipped from the US.
Anyway, I'll see if I can find these parts here and maybe use that. 
Thanks for all the ideas!

Cheers
Astan
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-25 Thread Astan Chee

Tim Roberts wrote:

Sorry, but you have NOT created a USB device, and I sincerely hope you do
not try to plug it in to a real USB port.
  
Sorry, by USB device, I meant a device that is powered/activated by a 
bunch of wires that I want to control using a computer and since I had a 
spare USB jack lying around, I used that instead. But so far I haven't 
tried it, nor will try it if it wont work properly. Yes, it is not a 
proper USB device, because I didnt build it to specifically interface 
with the USB port; but I had to start somewhere. Also, the device 
requires more power than the standard parallel port can give.

Anyway, it looks like the easiest solution for my case is a microcontroller
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-22 Thread Astan Chee

Diez B. Roggisch wrote:

Astan Chee wrote:

  

Hi,
Im trying to write a program for my USB device and I'm thinking of using
python to do this. The USB device is of my own making and it is
activated when one of the two data pins of the USB is given about 5V (or
similar to whatever the power pin is getting). Now I'm confused to if
the software to activate this can actually be written and how do I do
it? Any examples? I've seen pyUSB but it doesn't give me control over
the hardware and how much power is going through the data pins.


Unless I'm not getting something here.


  

Hi,
Thanks for all the responses but I forgot to mention that I have very 
little hardware understanding (at least in english) and the device 
itself it very simple and only needs about 5V power to be active. The 
problem here is that I want to control when the device is active using a 
computer so I thought USB might be a good choice since its simple (but 
didn't turn out to be). I'm open to any other suggestions on how I might 
achieve this hardware and software-wise (as in what interface should I 
use, etc). Also I'm trying to stay away from (complex) micro controllers.

Any ideas?
Thanks again
Astan
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-22 Thread Astan Chee

Diez B. Roggisch wrote:
Others suggested the parallel port. It is the natural choice for such 
things, with two caveats:


  - it is legacy, and thus often not available on modern hardware, 
especially on mobile ones. So if you want it be prepared to additionally 
buy a usb2parallel-adapter.


  - it's electrical specs aren't as robust I fear. USB allos up to 500mA 
to be drawn, and shouldn't break if you try more  fail (albeit, that 
might be something that isn't true all the time). So you can draw quite 
a bit of current from it (the stupid USB-cup-warmers are an example of 
that). I have often had broken parallel-ports, and I think the reason is 
that they *ARE NOT* specified to drive anything - they only provide 
low-current control-lines. So whatever you design, you need a second 
power-source then.


All in all, using a USB-controller is IMHO the best solution. The 
AT90USBKey is a low-cost evaluation-board. ATMEL provides quite a bit of 
example-code, and there is other FOSS available.


I have to admit though that the whole USB-topic isn't the easiest thing.

  
Yeah, I forgot to mention that the device is requires about 70-80mA and 
the parallel port (according to the spec) only provides 1mA. Thats why I 
was looking into the USB solution.
Thanks for the suggestion though. Also, yes, the device is rather mobile 
and that is why it is powered by the computer/laptop but legacy isn't 
really an issue for me I guess.

Cheers
Astan
--
http://mail.python.org/mailman/listinfo/python-list


Re: USB in python

2009-01-22 Thread Astan Chee


Diez B. Roggisch wrote:



If all you need is on-off - why can't you just use a switch?


  
Because I want to control the on-off the device using a computer and 
write software for it (which I am confident I can do if I had references 
to how the wrappers to said interface).

Cheers
Astan.

--
http://mail.python.org/mailman/listinfo/python-list


USB in python

2009-01-21 Thread Astan Chee

Hi,
Im trying to write a program for my USB device and I'm thinking of using 
python to do this. The USB device is of my own making and it is 
activated when one of the two data pins of the USB is given about 5V (or 
similar to whatever the power pin is getting). Now I'm confused to if 
the software to activate this can actually be written and how do I do 
it? Any examples? I've seen pyUSB but it doesn't give me control over 
the hardware and how much power is going through the data pins.

Thanks for any help.
Cheers
Astan
--
http://mail.python.org/mailman/listinfo/python-list


defining class functions

2009-01-19 Thread Astan Chee

Hi,
I have two classes in python that are in two different files/python 
scripts. Class A uses Class B like this:

class B(object):
   def function1(self,something):
   pass
   def function2(self,something):
   print hello one
   print something

class A(object):
   def __init__(self):
 instance = B()
 instance.function2(hello two)
 self.function3()
   def function3(self):
 print hello three

What I want to do here is to (re)define function1 from function3. Is 
that possible? Is there any way of redefining a function of another 
class without inheriting it? Does this make sense?

Thanks
Astan
--
http://mail.python.org/mailman/listinfo/python-list


Re: defining class functions

2009-01-19 Thread Astan Chee
Actually, yes, I just realized a better way of doing this without state 
change based on the requirement.

Thanks for the info anyway

Nehemiah Dacres wrote:
wouldn't you use a state change? Use a variable to indicate which 
function you want the first class to do


On Mon, Jan 19, 2009 at 6:31 PM, James Mills 
prolo...@shortcircuit.net.au mailto:prolo...@shortcircuit.net.au 
wrote:


On Tue, Jan 20, 2009 at 10:08 AM, Astan Chee astan.c...@al.com.au
mailto:astan.c...@al.com.au wrote:
 Hi,
 I have two classes in python that are in two different
files/python scripts.
 Class A uses Class B like this:
 class B(object):
   def function1(self,something):
   pass
   def function2(self,something):
   print hello one
   print something

 class A(object):
   def __init__(self):
 instance = B()
 instance.function2(hello two)
 self.function3()
   def function3(self):
 print hello three

def function3(self):
  print hello three
  self.instance.function1 = lambda x; x

But you must bind instnace to self in B

Modify your __init__ as follows:

class A(object):
  def __init__(self):
 self.instance = B()
 self.instance.function2(hello two)
 self.function3()

What's the use-case anyway ?
There might be a better way to solve your problem :)

cheers
James
--
http://mail.python.org/mailman/listinfo/python-list




--

lalalalala! it's not broken because I can use it

http://linux.slashdot.org/comments.pl?sid=194281threshold=1commentsort=0mode=threadcid=15927703 
http://linux.slashdot.org/comments.pl?sid=194281threshold=1commentsort=0mode=threadcid=15927703
--
http://mail.python.org/mailman/listinfo/python-list


Re: equivalent of py2exe in other os

2008-10-13 Thread Astan Chee

Hi,
Thanks for all the links and information. It seems that I can't make 
linux binaries in windows of my python code. What I mean is that I am 
using windows to develop my python code, but I want it to run in linux 
and mac. So far py2exe,gui2exe,pyinstaller,freeze,etc seems to all 
create .exe in because I am in windows. Is what I am after not possible 
so far?

Thanks again for all the help.
Cheers
Astan
PS: I already did some google and tried out all the suggestions everyone 
gave but still nothing.



Benjamin Kaplan wrote:



On Tue, Oct 7, 2008 at 10:58 AM, Joe Strout [EMAIL PROTECTED] 
mailto:[EMAIL PROTECTED] wrote:


On Oct 7, 2008, at 8:43 AM, Benjamin Kaplan wrote:

I believe that all (or nearly all) Unix variants come with
Python preinstalled. Ubuntu, at least, has a lot of system
programs written in Python. Even Mac OS X requires Python.


Yes, but with significant differences between different Python
distributions, you might be safer bundling whatever version of
Python your app requires with the app itself.  Otherwise, you risk
your app failing (and probably puking up runtime exceptions all
over the poor user's lap) on some distros or versions.

(My Mac OS X machine comes with Python 2.5.1, for example, which
is hardly the latest.)


1) 2.6 doesn't break backwards-compatibility, just don't use anything 
added in 2.6 and you're fine.


2)wx hasn't been compiled for 2.6 yet, so the OP is probably still 
using 2.5 and there are no api changes between 2.5.1 and 2.5.2



Best,
- Joe


--
http://mail.python.org/mailman/listinfo/python-list




--
http://mail.python.org/mailman/listinfo/python-list
  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. 
-David Morgan-Mar




Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

--
http://mail.python.org/mailman/listinfo/python-list


Re: equivalent of py2exe in other os

2008-10-07 Thread Astan Chee

Hi,
Thanks for the replies. I forgot to add that I am developing my python 
scripts in windows, but would like to make executables/binaries for win, 
linux and osx without the os themselves.
Does this make sense? Also, it seems that freeze requires some sort of 
python installed on the linux box, what I'm looking for is a stand-alone 
binary/executable.

Thanks again for the suggestions
Astan

Lars Stavholm wrote:

Almar Klein wrote:
  

Hi,
I was going to say try google, but it seems quite hard to find indeed.
Use freeze for linux and py2app for osx.



http://python.net/crew/atuining/cx_Freeze
/L

  

I know of a program called gui2exe which is a gui which uses the three
to compile executables of your os of choise (but I think only py2exe was
implemented thus far).

Almar

2008/10/7 Astan Chee [EMAIL PROTECTED] mailto:[EMAIL PROTECTED]

Hi,
I was just wondering if there is a equivalent of py2exe on linux
(centOS) and mac (OS X). I have a python script that uses wx and I
dont want to install wx on linux/mac machines. What are my choices?
Thanks
Astan

-- 
Formulations of number theory: Complete, Consistent, Non-trivial.

Choose two. -David Morgan-Mar



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or
privileged. If you are not the intended recipient of this email, you
must not disclose or use the information contained in it. Please
notify the sender immediately and delete this document if you have
received it in error. We do not guarantee this email is error or
virus free.



--
http://mail.python.org/mailman/listinfo/python-list





--
http://mail.python.org/mailman/listinfo/python-list





  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. 
-David Morgan-Mar




Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

--
http://mail.python.org/mailman/listinfo/python-list


equivalent of py2exe in other os

2008-10-07 Thread Astan Chee

Hi,
I was just wondering if there is a equivalent of py2exe on linux 
(centOS) and mac (OS X). I have a python script that uses wx and I dont 
want to install wx on linux/mac machines. What are my choices?

Thanks
Astan

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. 
-David Morgan-Mar



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


VNC capture in python

2008-07-06 Thread Astan Chee

Hi,
I was wondering if I can do a capture of a VNC screen in python. Kinda 
like this http://search.cpan.org/~lbrocard/Net-VNC-0.35/lib/Net/VNC.pm

but without opening a VNC window or doing a screen capture.
Thanks for any suggestions

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


parsing .pcap files

2008-06-06 Thread Astan Chee

Hi,
Im using pyflag to parse .pcap files. Pyflag displays the data part of 
the .pcap file in binary and I was wondering what this means. How do I 
decode the 'data' part of the packet without using external libraries? 
What does these non-alpha numerical information mean? Is there a 
(python) dictionary/documentation somewhere that I can use to parse this 
data?

Thanks again.
Cheers
Astan
PS: I've attached the .pcap file that Im using to test and the python 
file as well.


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

# **
# Michael Cohen [EMAIL PROTECTED]
#
# **
#  Version: FLAG $Version: 0.86RC1 Date: Thu Jan 31 01:21:19 EST 2008$
# **
#
# * This program is free software; you can redistribute it and/or
# * modify it under the terms of the GNU General Public License
# * as published by the Free Software Foundation; either version 2
# * of the License, or (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# **
 A library for reading PCAP files.

PCAP format is really simple so this is a nobrainer. Good example of
using the file format library though. This shows how we can handle the
endianess issue simply.

import struct,time,cStringIO
import sys

## This is the default size that will be read when not specified
DEFAULT_SIZE=600*1024*1024

class Buffer:
 This class looks very much like a string, but in fact uses a file object.

The advantage here is that when we do string slicing, we are not duplicating strings all over the place (better performace). Also it is always possible to tell where a particular piece of data came from.

def __init__(self,fd,offset=0,size=None):
 We can either specify a string, or a fd as the first arg 
self.offset=offset
self.fd=fd
if size!=None:
self.size=size
else:
self.fd=fd
if size!=None:
self.size=size
else:
## Try to calculate the size by seeking the fd to the end
offset = fd.tell()
try:
fd.seek(0,2)
except Exception,e:
print %s: %r % (e,fd)
self.size=fd.tell()
fd.seek(offset)

#if self.size0:
#raise IOError(Unable to set negative size (%s) for buffer (offset was %s) % (self.size,self.offset))

def clone(self):
return self.__class__(fd=self.fd, offset=self.offset, size=self.size)

def __len__(self):
return self.size

def set_offset(self,offset):
 This sets the absolute offset.

It is useful in files which specify an absolute offset into the file within some of the data structures.

return self.__class__(fd=self.fd,offset=offset)

def __getitem__(self,offset):
 Return a single char from the string 
self.fd.seek(offset+self.offset)
return self.fd.read(1)


## FIXME: Python slicing will only pass uint_32 using the syntax
def __getslice__(self,a=0,b=None):
 Returns another Buffer object which may be manipulated completely independently from this one.

Note that the new buffer object references the same fd that we are based on.

if b:
if bself.size:
b=self.size
return self.__class__(fd=self.fd,offset=self.offset+a,size=b-a)
else:
return self.__class__(fd=self.fd,offset=self.offset+a)

def __str__(self):
self.fd.seek(self.offset)
if self.size=0:
data=self.fd.read(self.size)
else:
data=self.fd.read(DEFAULT_SIZE)

#if len(data)  self.size:
#raise IOError(Unable to read %s bytes from %s %(self.size,self.offset))

return data

def __nonzero__(self):
return 1

def search(self, bytes):
 

threads problem in python

2008-05-13 Thread Astan Chee

Hi,
I have 2 classes in python, the first one runs first and and then the 
first one calls the second class. I want it to run the second class as a 
separate thread but I want the first one to wait until the second class 
is dead.
Im having problem in both killing the second class when its done and 
making the first class wait for it to finish.

Im very confused on doing threads in python.
Thanks for any help.
Astan

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


Re: threads problem in python

2008-05-13 Thread Astan Chee
Sorry, I mean functions not classes. Well, actually, one is a class and 
another is a function. So when the script (its a free game btw) runs, it 
instantiates the first class and somewhere in the middle of processing 
the first class, I need to call a function as a separate thread, I also 
want to wait for the function to complete and I was wondering how python 
handles the thread of this function? Does it die when the function 
completes? Anyway, I know it sounds silly to have 2 threads when I can 
do it with one, but Im using wx to render opengl objects using pygame. 
So it has to be a separate thread, otherwise wx wont play nice. Is there 
a simple example of how I can do this?
And as for finance, the source for the game is free, but it isnt free to 
play on my server. How does that sound?

Thanks
Astan

[EMAIL PROTECTED] wrote:

On May 13, 5:38 am, Gabriel Genellina [EMAIL PROTECTED]
wrote:
  

En Tue, 13 May 2008 06:42:13 -0300, Astan Chee [EMAIL PROTECTED] escribió:
I'm confused trying to understand your requirements too. run a class?
Threads execute code, it's easier to think of them as *functions* that are  
executed at the same time (or almost).
So you have a function A that runs first, and creates a second thread that  
will execute function B. Then A will wait for B to finish. What do you  
want to do in A while it's waiting? Nothing? Then why to use a second  
thread? Or is it a graphical interfase? GUI libraries like wxPython, Qt  
and others have specific ways to execute backgroung tasks while keeping  
the user interface responsive - you should tell us which one you're using  
in that case.


--
Gabriel Genellina



I don't mean to be impertinent, but are you making any cents with the
assignment?  Both free-ers and workers come in here.  I am a free-er
who has reason to doubt that money-driven programs get stuck at that
kind of ambiguity.  I hold that money keeps you out of that mess.

However, there are a number of things we can do to help, but as I, per
se, am only one person, I may not give you the best advice to start
with.  How do you find the 'threading.py' docs?
--
http://mail.python.org/mailman/listinfo/python-list

  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

--
http://mail.python.org/mailman/listinfo/python-list

get number that is raised to the power of

2008-05-02 Thread Astan Chee

Hi,
Im not sure if this is more of a math question or a python question. I 
have a variable in python:

 v = 10.0**n
is there a way to find the value of n if i know only v aside from 
str(v).split('+')[1] ? that seems like too much of a hack and I was 
wondering if there was a faster way of doing it?

Thanks for any pointers
Astan

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


Re: get number that is raised to the power of

2008-05-02 Thread Astan Chee



Python.Arno wrote:

the reverse of a power to is logarithm
so v = 10**n  =  math.log(v,10) = n

Arno


Im so ashamed of myself for not thinking in logs.
I must be dreaming again.
Thanks for the help.

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


tool to calculate color combination

2008-04-30 Thread Astan Chee

Hi,
I was just wondering if there is a tool/script in python that allows me 
to do color calculations; specifically, when I add them.
Also I was thinking that for this to work other than a simple way, some 
form of measure is included. e.g 50% red(1,0,0) + 50% yellow(1,1,0) =  
100% orange(1,0.7,0)

Is there such a tool in python?
Thanks for any information
Astan

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


Re: tool to calculate color combination

2008-04-30 Thread Astan Chee

Dont worry about this. I've figured it out. Rather simple :
red = sum of for each red (50/100) * 1
green = sum of for each green (50/100) * 0
blue = sum of for each blue(50/100) * 0

Astan Chee wrote:

Hi,
I was just wondering if there is a tool/script in python that allows 
me to do color calculations; specifically, when I add them.
Also I was thinking that for this to work other than a simple way, 
some form of measure is included. e.g 50% red(1,0,0) + 50% 
yellow(1,1,0) =  100% orange(1,0.7,0)

Is there such a tool in python?
Thanks for any information
Astan



--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


simple chemistry in python

2008-04-29 Thread Astan Chee

Hi,
Im looking for a python module to do simple chemistry things. Things 
like, finding the name of elements given the atomic number (and vice 
versa); what state the given matter is in depending on certain 
parameters; maybe even color of certain elements or even calculating the 
result of combining certain elements.
I was looking for something simple, but everything I see seems to be a 
full blown chemistry set.
I know I can probably spend a day doing this one element at a time, but 
I was wondering if there is already something like this done in a small 
scale?

Thanks for any information
Astan

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list


Re: simple chemistry in python

2008-04-29 Thread Astan Chee

Wow, that is the jackpot.
Is that color node supposed to be the actual color of the element? or 
just representation?

Thanks again
Astan

baoilleach wrote:

If you are familiar with parsing XML, much of the data you need is
stored in the following file:
http://bodr.svn.sourceforge.net/viewvc/*checkout*/bodr/trunk/bodr/elements/elements.xml?revision=34content-type=text%2Fplain

This file is part of the Blue Obelisk Data Repository, an effort by
several chemistry software developers to share common information. If
you have any further questions, please email blueobelisk-
[EMAIL PROTECTED]

Noel

On Apr 29, 8:48 am, Astan Chee [EMAIL PROTECTED] wrote:
  

Hi,
Im looking for a python module to do simple chemistry things. Things
like, finding the name of elements given the atomic number (and vice
versa); what state the given matter is in depending on certain
parameters; maybe even color of certain elements or even calculating the
result of combining certain elements.
I was looking for something simple, but everything I see seems to be a
full blown chemistry set.
I know I can probably spend a day doing this one element at a time, but
I was wondering if there is already something like this done in a small
scale?
Thanks for any information
Astan

--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.

Animal Logichttp://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



--
http://mail.python.org/mailman/listinfo/python-list

  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

--
http://mail.python.org/mailman/listinfo/python-list

testing client-server sockets

2008-04-18 Thread Astan Chee
Hi,
I have a client-server socket script in python. Something like this 
http://ubuntuforums.org/showthread.php?t=208962
Now the problem I have is that I want to try to connect the client to 
the server on the same machine, but it gives me a 'port already in use' 
error. I just want the client to connect to the server for testing 
purposes. Any suggestions on how I should do this?
Thanks
Astan

-- 
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: testing client-server sockets

2008-04-18 Thread Astan Chee

Server code:

import os, sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 5602
s.bind((host,port))
try:
   s.listen(1)
   while 1:
   conn, addr = s.accept()
   print 'client is at', addr
   data = conn.recv(100)
   data = data * 10
   z = raw_input()
   conn.send(data)
   conn.close()
except Exception:
   s.close()

Client code:

import sys, os, socket

   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   host = 'hostIP'
   port = 5602
   s.connect((host,port))
   s.send(dlg.user.GetValue())
   i =0
   while True:
   data = s.recv(100)
   i+=1
   if (i5):
   print data
   if not data:
   break
   print 'received', len(data), 'bytes'
   s.close()


David Harrison wrote:

On 18/04/2008, Astan Chee [EMAIL PROTECTED] wrote:
  

Hi,
 I have a client-server socket script in python. Something like this
 http://ubuntuforums.org/showthread.php?t=208962
 Now the problem I have is that I want to try to connect the client to
 the server on the same machine, but it gives me a 'port already in use'
 error. I just want the client to connect to the server for testing
 purposes. Any suggestions on how I should do this?
 Thanks
 Astan



Can you post the client / server code for us ?  It sounds like it's
likely to be a minor bug.

  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: testing client-server sockets

2008-04-18 Thread Astan Chee

Wierd. It works now. I must've changed something. Oh well, thanks anyway.

David Harrison wrote:

On 18/04/2008, Astan Chee [EMAIL PROTECTED] wrote:
  

 Server code:

 import os, sys, socket
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 host = ''
 port = 5602
 s.bind((host,port))
 try:
 s.listen(1)
 while 1:
 conn, addr = s.accept()
 print 'client is at', addr
 data = conn.recv(100)
 data = data * 10
 z = raw_input()
 conn.send(data)
 conn.close()
 except Exception:
 s.close()

 Client code:

 import sys, os, socket

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 host = 'hostIP'
 port = 5602
 s.connect((host,port))
 s.send(dlg.user.GetValue())
 i =0
 while True:
 data = s.recv(100)
 i+=1
 if (i5):
 print data
 if not data:
 break
 print 'received', len(data), 'bytes'
 s.close()



I just ran the code (albeit with a tiny change to send a small string
instead so I could see what was going on), and it seems to work fine
... anything else that might be different ?

  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

-- 
http://mail.python.org/mailman/listinfo/python-list

sine in python

2008-04-03 Thread Astan Chee
Hi,
I have a math function that looks like this
sin (Theta) = 5/6
How do I find Theta (in degrees) in python? I am aware of the math.sin 
function, but is there a reverse? maybe a sine table in python?
Thanks
Astan

-- 
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copy file over LAN

2008-03-27 Thread Astan Chee

Well, the solution seems to be something like (windows only)
import os
import os.path
import shutil
import sys
import win32wnet

def wnet_connect(host, username, password):
   unc = ''.join(['', host])
   try:
   win32wnet.WNetAddConnection2(0, None, unc, None, username, password)
   except Exception, err:
   if isinstance(err, win32wnet.error):
   # Disconnect previous connections if detected, and reconnect.
   if err[0] == 1219:
   win32wnet.WNetCancelConnection2(unc, 0, 0)
   return wnet_connect(host, username, password)
   raise err

if __name__ == '__main__':

   node = hostname
   dst = r'C:\temp\destination__'
   dst += node + r'.txt'
   wnet_connect(node,username,password)
   shutil.copyfile(r'\\' + node + r'\c$\temp\\al_lsf_log',dst)


Gabriel Genellina wrote:

En Thu, 27 Mar 2008 00:34:20 -0300, Astan Chee [EMAIL PROTECTED] escribió:

  

I have a file on another machine on the local network (my machine and
local machines are on windows) and I want to copy it locally. Now the
machine requires authentication and when I try to do a
import shutil
shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt')
and it gives me a IOError: [Errno 13] Permission denied: error, which I
expect. How do I provide authentication to copy this file?



Probably there are other ways, but the net use command looks easy  
enough. Execute net help use | more in a console to see the right syntax.

Use the subprocess module to run the command from inside Python.

  


--
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

-- 
http://mail.python.org/mailman/listinfo/python-list

copy file over LAN

2008-03-26 Thread Astan Chee
Hi,
I have a file on another machine on the local network (my machine and 
local machines are on windows) and I want to copy it locally. Now the 
machine requires authentication and when I try to do a
import shutil
shutil.copy(r'\\remotemachine\c$\temp\filename',r'C:\folder\test.txt')
and it gives me a IOError: [Errno 13] Permission denied: error, which I 
expect. How do I provide authentication to copy this file?
Thanks for the help.
Cheers
Astan

-- 
Formulations of number theory: Complete, Consistent, Non-trivial. Choose two.


Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



-- 
http://mail.python.org/mailman/listinfo/python-list


Help with jabber client in wx

2008-02-10 Thread Astan Chee
Hi,
A project Im working on is a jabber client working with wx to interface 
with uTorrent's webUI using a python API for it. My project can be found 
here:
http://code.google.com/p/gtalktorrent/
A quick note, the project started as a google talk client, but it seems 
that xmpppy is flexible enough to support various other/similar XMPP 
servers, but I mainly use with/in google talk
It is open source and I've included the windows executable as an 
optional download.
The current problem Im having is that whenever the jabber client 
disconnects or whenever a network error occurs (ISP goes down,etc), the 
client does not reconnect. I've added some code to help this, but it 
still doesnt reconnect properly; or rather, it doesnt detect the 
disconnection properly. What am I doing wrong in the xmpppy classes/methods?
I also ask people in the wx community since Im not sure how to overwrite 
or handle the wx MainLoop method and maybe I'm doing something wrong in 
there. Maybe a deadlocked event?
Anyway, does anyone have any ideas?
Cheers
Astan

Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxEVT_SCROLL_ENDSCROLL

2008-01-31 Thread Astan Chee
try wx.EVT_SCROLL_ENDSCROLL ?


Jack Holt wrote:
 Hello,

 I got the following error:

 Traceback (most recent call last):
   File vplayer.py, line 15, in ?
   File config.pyo, line 3, in ?
   File wx\__init__.pyo, line 44, in ?
   File wx\_core.pyo, line 3592, in ?
 AttributeError: 'module' object has no attribute
 'wxEVT_SCROLL_ENDSCROLL'


 I never had that error before... until I messed up
 with the python package
 (I had to reinstall Active Python + py2exe +
 wxpython). I can run my app
 from the SVN with no problem. I get the error from the
 compiled version -
 made with py2exe.

 Line 3 in config.py points to: Import wx



 Help!!

 Thanks, 
  -Dan



   
 
 Looking for last minute shopping deals?  
 Find them fast with Yahoo! Search.  
 http://tools.search.yahoo.com/newsearch/category.php?category=shopping
   

Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



-- 
http://mail.python.org/mailman/listinfo/python-list


small problem with re.sub

2008-01-30 Thread Astan Chee
Hi,
I have a html text stored as a string. Now I want to go through this 
string and find all 6 digit numbers and make links from them.
Im using re.sub and for some reason its not picking up the previously 
matched condition. Am I doing something wrong? This is what my code 
looks like:
htmlStr = re.sub('(?Pid\d{6})','a 
href=\http://linky.com/(?P=id).html\(?P=id)/a',htmlStr)
It seems that it replaces it alright, but it replaces it literally. Am I 
not escaping certain characters?
Thanks again for the help.
Cheers

Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.



-- 
http://mail.python.org/mailman/listinfo/python-list


Bittorent client with google talk interface

2008-01-20 Thread Astan Chee

Hi,
I dont know where to send this but I'll try here. I recently took the 
newest version of ABCTorrent and its code and added some features to it 
that I find very useful. Basically it is like a webUI except it connect 
to google's google talk and you can issue commands from it. Kinda like a 
command line bittorrent client. So when you start up the client, you can 
enter your google talk account information and using another google talk 
account (from somewhere else) send commands (system and torrent 
related). I've also added some proxy support for it since Im constantly 
behind proxies (but not at work or school). I use windows XP and 
wxPython 2.6.3.3 http://2.6.3.3 and python 2.5 so I dont know how it 
will behave in newer versions of things. There are also new modules that 
it requires (win32api) for file operations that you might need before 
compiling this. The main script to run this all is the abc.py script. 
Also I havent done much brushing up with the GUI so it wont look like 
the fastest ship around. Any suggestions or changes for further improvement?
Also for anyone who is developing or has used this before and tinkered 
with it Im pretty sure Im doing something wrong calling the interface 
from the code because it (wx) sporadically crashes; Im not sure what to 
do since I dont know how to call it properly. Does anyone have any idea?


Cheers
Astan

The file can be downloaded here:
http://gtalktorrent.googlecode.com/files/3.1.0.zip
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [python] How to detect a remote webpage is accessible? (in HTTP)

2008-01-17 Thread Astan Chee
How about:

import socket, urllib2

timeout = 10
socket.setdefaulttimeout(timeout)
try:
auth_handler = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(auth_handler) #this used if we need 
authentication
urllib2.install_opener(opener)
req = urllib2.Request('http://website.com')
f = urllib2.urlopen(req)
notes= f.readlines()
f.close()
print Everything is ok
except IOError, r:
p = str(r)
if re.search(r'urlopen error timed out',p):
print Web page timed out

You'll need to set up the timeout to whatever duration your website 
takes to load.
Cheers
Astan

?? wrote:
 Howdy, all,
  I want to use python to detect the accessibility of website.
 Currently, I use urllib
 to obtain the remote webpage, and see whether it fails. But the problem is 
 that
 the webpage may be very large; it takes too long time. Certainly, it
 is no need to download
 the entire page. Could you give me a good and fast solution?
 Thank you.
 --
 ShenLei
   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restart crashing modules in windows

2008-01-15 Thread Astan Chee

Mike Driscoll wrote:

On Jan 14, 9:02 pm, Astan Chee [EMAIL PROTECTED] wrote:
  

Hi,
I have a python module that keeps on crashing with various windows
errors (not BSOD but the less lethal windows XP popup ones). Now these
are intentional and rather sporadic so I cant really solve it by
attempting to fix the crash; rather what Im trying to do is make another
module outside it that restarts this module every time it crashes. Is
this possible? 



If you're not going to catch the error that is causing the crash, then
I think your only option is to restart your application with an
external program. 
  
My understanding of using an external application to do this is to first 
create my module as an executable using py2exe. Then I have another 
python script that runs this module like this


while (1):
   os.popen(program_module.exe)

and make this other python script into another executable and execute 
this one. If Im not mistaken, when the python program crashes, the 
thread is killed. is this correct or how should I do it?

Thanks again.
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list

Restart crashing modules in windows

2008-01-14 Thread Astan Chee
Hi,
I have a python module that keeps on crashing with various windows 
errors (not BSOD but the less lethal windows XP popup ones). Now these 
are intentional and rather sporadic so I cant really solve it by 
attempting to fix the crash; rather what Im trying to do is make another 
module outside it that restarts this module every time it crashes. Is 
this possible? How do I do this? Or does one windows crash in one python 
module crash python entirely and I have to resort in an external program 
to restart python everytime it crashes?
Thanks again for all the help.
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


(bit)torrent source code help

2008-01-13 Thread Astan Chee
Hi,
Im using windows XP and I was wondering if anyone had any experience in 
compiling (using py2exe) the official bittorrent client ( 
http://download.bittorrent.com/dl/BitTorrent-5.2.0.tar.gz ) or any 
bittorrent client open source and written in python. I ask since I am 
trying to make several of my own modification to the protocol but the 
official open source client keeps on giving me missing modules (I have 
all the required modules and components and it keeps on failing due to 
platform-based errors) when I try to create an executable of it using 
py2exe.
Can anyone either suggest another source code for a torrent client or 
any torrent client in python that compiles nicely with py2exe in windows?
Thanks
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sending commands in body of HTTP with urllib2

2008-01-03 Thread Astan Chee
Astan Chee wrote:
 Hi,
 Im trying to implement the logic from 
 http://www.hypothetic.org/docs/msn/general/http_connections.php to a 
 simple python code using urllib2 and some parts of urllib. Im behind a 
 http proxy that requires authentication that is why Im using urllib2. Im 
 asking for help on how to send commands in a body of a HTTP before 
 requesting for response. What am I doing wrong? I only get the response 
 from the server but my commands never seem to be acknowledged or 
 properly handled. 
   
I've tried a httplib implementation for it, and now it keeps giving me 
an Error 400 (bad request) / Invalid header name as a response. What am 
I doing wrong? is the server depreciated? or not working like the 
document describes it? Thanks again for any help. Below is my code


import httplib
import base64
import urllib

USER='user'
PASS='pass'
url = 
'http://gateway.messenger.hotmail.com/gateway/gateway.dll?Action=openServer=NSIP=messenger.hotmail.com'

values = 'VER 5 MSNP8 CVR0\r\n'
user_pass = base64.encodestring('%s:%s' % 
(urllib.unquote(USER),urllib.unquote(PASS)))
authheader =  Basic %s % user_pass
proxy_authorization='Proxy-authorization: Basic '+user_pass+'\r\n'

conn = httplib.HTTPConnection(proxy.com.au, 8080)
conn.connect()
conn.putrequest(POST, url)
conn.putheader('Accept','*/*')
conn.putheader('Accept-Language','en-us')
conn.putheader('Accept-Encoding','gzip, deflate')
conn.putheader('User-agent','MSMSGS')
conn.putheader('Host','gateway.messenger.hotmail.com')
conn.putheader('Proxy-Connection','Keep-Alive')
conn.putheader('Pragma','no-cache')
conn.putheader('Content-Type','application/x-msn-messenger')
conn.putheader('content-length',str(len(values)))
conn.putheader('Proxy-authorization',authheader)
conn.endheaders()
conn.send(values)
r = conn.getresponse()
print r.status, r.reason
print r.msg
print r.read()
   

-- 
http://mail.python.org/mailman/listinfo/python-list


sending commands in body of HTTP with urllib2

2008-01-02 Thread Astan Chee
Hi,
Im trying to implement the logic from 
http://www.hypothetic.org/docs/msn/general/http_connections.php to a 
simple python code using urllib2 and some parts of urllib. Im behind a 
http proxy that requires authentication that is why Im using urllib2. Im 
asking for help on how to send commands in a body of a HTTP before 
requesting for response. What am I doing wrong? I only get the response 
from the server but my commands never seem to be acknowledged or 
properly handled. Below is my code:

import urllib2
import base64
import urllib

USER='user'
PASS='pass'

proxy_info  = {'host' : proxy.com.au,'port' : 8080}

# build a new opener that uses a proxy requiring authorization
proxy_support = urllib2.ProxyHandler({http : \
http://%(host)s:%(port)d % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)

user_pass = base64.encodestring('%s:%s' % 
(urllib.unquote(USER),urllib.unquote(PASS)))
authheader =  Basic %s % user_pass

opener.addheaders = [('Accept-Language','en-us'),
 ('Accept-Encoding','gzip, deflate'),
 ('Host','gateway.messenger.hotmail.com'),
 ('Proxy-Connection','Keep-Alive'),
 ('Connection','Keep-Alive'),
 ('Pragma','no-cache'),
 ('Content-Type','application/x-msn-messenger'),
 ('User-agent','MSMSGS'),
 ('Accept','*/*'),
 ('Proxy-authorization',authheader)]

# install it
urllib2.install_opener(opener)

# use it
url = 
'http://gateway.messenger.hotmail.com/gateway/gateway.dll?Action=openServer=NSIP=messenger.hotmail.com'
values = 'VER 5 MSNP8 CVR0'

f = urllib2.urlopen(url,values)
print f.headers
print f.read()

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


socket in python with proxies

2007-12-20 Thread Astan Chee
Hi, I have a proxy server that requires authentication on a non-standard 
port and Im trying to connect to it via socket.connect()
I tried doing this:
import socket
server = (username:[EMAIL PROTECTED],1234)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server)

I keep getting the

Traceback (most recent call last):
  File pyshell#6, line 1, in module
s.connect(server)
  File string, line 1, in connect
gaierror: (11001, 'getaddrinfo failed')

What does this mean? and can I actually use username/password to connect 
using a socket in python?
Thanks
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


python sounds-like module

2007-12-12 Thread Astan Chee
Hi,
Thanks for all the help from the previous problem. Turns out I didnt 
have to use wxSizers, just change the size of my wxWidgets everytime a 
EVT_SIZE is called.
Anyway, Im trying to find a python module (im not sure if it exists) 
that takes two words and compares if they sound the same. So 'right' and 
'write' sounds the same or 'u' and 'you' . Also I know this takes into 
account the use of language and accent but is there any out there before 
I start making my own?
Thanks
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python sounds-like module

2007-12-12 Thread Astan Chee
John Machin wrote:
 Someone is sure to trot out the hoary old soundex ... believe me, it's
 teh suxxor.

   
plus febrl has soundex (and modified versions of it) within it. But 
thanks again! Looks like this is what I'm looking for.
Thanks alot guys!
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python sounds-like module

2007-12-12 Thread Astan Chee
John Machin wrote:
 Someone is sure to trot out the hoary old soundex ... believe me, it's
 teh suxxor.

   
Plus febrl has soundex in it (as well as several modified versions of 
it) among other things. Looks like this is what Im looking for.
Thanks!
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python sounds-like module

2007-12-12 Thread Astan Chee
John Machin wrote:
 Someone is sure to trot out the hoary old soundex ... believe me, it's
 teh suxxor.

   
Plus febrl has soundex in it (as well as several modified versions of 
it) among other things. Looks like this is what Im looking for.
Thanks!
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


sizers in wxpanels/notebooks

2007-12-07 Thread Astan Chee
Hi,
I have a wxNoteBook with a bunch of wxPanels attached to it as pages. 
Every page has its own GUI items.
What Im trying to do is on a certain page, a certain GUI (wxTextCtrl) to 
be resized every time the notebook or panel is resized. But everything 
else stays the same.
Now I know I can use sizers to solve this, but I have each GUI item's 
position hard-coded and they shouldnt move around or change size. I was 
thinking of putting this wxTextCtrl in a child wxPanel of these 
wxPanel/pages. So the hierarchy is wxNoteBook - wxPanel - wxPanel - 
wxSizer.Add( wxTextCtrl)
is this possible? how do i get it working? are there other alternatives 
to what Im trying to do? because simply putting a wxPanel in a wxPanel 
and adding a sizer in a normal manner doesnt work for me.
below is a snippet of what Im doing (i dont want the button to change 
position or change size or be in any sizers, but I do want the textctrl 
to do so).

self.tab12 = wxPanel(self.notebook,-1)
self.s_test = wxButton(self.tab12,-1,Clear,(20,20))
self.tab12_child = wxPanel(self.tab12,-1,(0,0),self.tab12.GetSize())
self.c_test =  
wxTextCtrl(self.tab12_child,-1,,(130,270),wxSize(800,350),style=wxTE_MULTILINE|wxHSCROLL|wxTE_RICH2|wxTE_RICH)
self.globalSizer = wx.BoxSizer(wxHORIZONTAL)
self.globalSizer.Add(self.c_test)
self.tab12.SetSizer(self.globalSizer)
self.globalSizer.SetSizeHints(self)
   
self.notebook.AddPage(self.tab12,Test Sizers)


Thanks!
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


reading raw variables from file

2007-11-29 Thread Astan Chee
Hi,
I have a file that might contain literal python variable statements at 
every line. For example the file info.dat looks like this:
users = [Bob, Jane]
status = {1:ok,2:users[0]}
the problem is I want to read this file and load whatever variables 
written in it as normal python variable statements so that when i read 
the file, my users var will be [Bob,Jane] and my status var will be 
{1:ok,2:users[0]} . Is there an easy way of doing this instead of 
parsing the files and checking said types?
Thanks
Cheers
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading raw variables from file

2007-11-29 Thread Astan Chee

Paddy wrote:

On Nov 30, 4:57 am, Astan Chee [EMAIL PROTECTED] wrote:
  

Hi,
I have a file that might contain literal python variable statements at
every line. For example the file info.dat looks like this:
users = [Bob, Jane]
status = {1:ok,2:users[0]}
the problem is I want to read this file and load whatever variables
written in it as normal python variable statements so that when i read
the file, my users var will be [Bob,Jane] and my status var will be
{1:ok,2:users[0]} . Is there an easy way of doing this instead of
parsing the files and checking said types?
Thanks
Cheers
Astan



Think SECURITY. If is someone likely to put malicious code in the file
to crap all over your machine?
  

Well, its only for variables, but yeah, security isnt an issue with my code.


If not then import the file as a module.
  

This works.
Thanks!


- Paddy.
  
-- 
http://mail.python.org/mailman/listinfo/python-list

check if var is dict

2007-08-13 Thread Astan Chee
Hi,
I have a variable, I want to check if it is a dictionary or a string.
Is there any better way to do this than I've done. How I did it is by 
doing a .items() and catching a AttributeError that it raises if its not 
a dictionary.
How do i properly do it?
Thanks
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


get position is scrolled wxScrolledWindow

2007-08-06 Thread Astan Chee
Hi,
I have a wxScrolledWindow, and some things drawn on it. I've hooked the 
left click event to a certain function I've got. Anyway, everytime I do 
a event.GetPosition() on the position of the mouse on the 
wxScrolledWindow, it returns the physical location or position of the 
mouse. Does anyone have any examples or advice on how to get the real or 
position of the window including where it has been scrolled?
Thanks
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


removing redundant elements in a dictionary

2007-07-31 Thread Astan Chee

Hi,
I have a dictionary which looks something like this:

elem = 
{co:[1,2,3],cp:[3,2,1],pp:[5,6,7],cl:[1,2,3],qw:[6,7,8],qa:[8,7,6]}


what Im trying to do is find all keys in the list that have the same 
value and delete those (except one); thereby removing all redundant keys 
so that the above dict will look like this:


elem = {co:[1,2,3],pp:[5,6,7],qa:[8,7,6]}

my code so far looks like this:

for out1 in elem.keys():
   for out2 in elem.keys():
   if out1 != out2:
   elem[out1].sort()
   elem[out2].sort()
   if elem[out1] == elem[out2]:
   del elem[out1]

This returns in a KeyError exception when sorting. What am I missing here?
Thanks
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ok

2007-04-05 Thread Astan Chee

How much does it pay?
[EMAIL PROTECTED] wrote:
 hi looking for someone to bult my web site for me

   
-- 
http://mail.python.org/mailman/listinfo/python-list


upgrading python (and other modules)

2007-03-28 Thread Astan Chee
Hi,
I was once using python 2.4 in win2k with wxPython 2.4.2.4 (if im not 
mistaken) with it.
Now i've upgraded to winXP and am using python 2.5 with wxPython 2.8.1.1.
The problem Im currently having is that in my code:

from wxPython.wx import *
from wxPython.grid import *
from wxPython.html import *

no longer works. An error/warning appears:

Warning (from warnings module):
  File C:\stanc_home\WHIP\whip.py, line 7
from wxPython.wx import *
DeprecationWarning: The wxPython compatibility package is no longer 
automatically generated or activly maintained.  Please switch to the wx 
package as soon as possible.

Traceback (most recent call last):
  File C:\stanc_home\WHIP\whip.py, line 10, in module
from wxPython.html import *
  File C:\Python25\lib\site-packages\wx-2.8-msw-ansi\wxPython\html.py, 
line 151, in module
wxHtmlWindowEvent = wx.html.HtmlWindowEvent
AttributeError: 'module' object has no attribute 'HtmlWindowEvent'

How should I be importing in the new wx?
Thanks!
Astan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: upgrading python (and other modules)

2007-03-28 Thread Astan Chee
Forget I asked this question.
I've solved it using wxPython 2.6.3.3
Cheers

Astan Chee wrote:
 Hi,
 I was once using python 2.4 in win2k with wxPython 2.4.2.4 (if im not 
 mistaken) with it.
 Now i've upgraded to winXP and am using python 2.5 with wxPython 2.8.1.1.
 The problem Im currently having is that in my code:

 from wxPython.wx import *
 from wxPython.grid import *
 from wxPython.html import *

 no longer works. An error/warning appears:

 Warning (from warnings module):
   File C:\stanc_home\WHIP\whip.py, line 7
 from wxPython.wx import *
 DeprecationWarning: The wxPython compatibility package is no longer 
 automatically generated or activly maintained.  Please switch to the wx 
 package as soon as possible.

 Traceback (most recent call last):
   File C:\stanc_home\WHIP\whip.py, line 10, in module
 from wxPython.html import *
   File C:\Python25\lib\site-packages\wx-2.8-msw-ansi\wxPython\html.py, 
 line 151, in module
 wxHtmlWindowEvent = wx.html.HtmlWindowEvent
 AttributeError: 'module' object has no attribute 'HtmlWindowEvent'

 How should I be importing in the new wx?
 Thanks!
 Astan

   
-- 
http://mail.python.org/mailman/listinfo/python-list


getting local system information with python

2007-03-15 Thread Astan Chee
Hi,
I have a python script and I want to check what operating system it is 
on and what the current local machine name is.
How do I do it with python?
Thanks!
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


converting epoch time to string (and vice versa)

2007-03-12 Thread Astan Chee
Hi,
I have a string in this format DD/MM/YYY for example:
tdate = 18/01/1990
and Im trying to convert this to epoch time, can anyone help?
Im also trying to convert that epoch time to the string format 
previously. Can anyone help this one too?
Thanks!
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


eval('000052') = 42?

2007-02-20 Thread Astan Chee
Hi,
I just tried to do
eval('00052') and it returned 42.
Is this a known bug in the eval function? Or have I missed the way eval 
function works?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen(1-4) as a seperate process

2006-11-17 Thread Astan Chee


Dennis Lee Bieber wrote:
 On Fri, 17 Nov 2006 18:53:41 +1100, Astan Chee [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:


   
 What would be a good method to do this? I've tried your 
 os.system(command) and the spawned process is still the child of the 
 current running process (which is not what I want to happen).
 Thanks again and sorry for the confusion.
 

   The  trailer is UNIX/LINUX specific for detaching a process. There
 may be other commands needed for Windows. Especially as, I think, the 
 syntax can create processes that remain running even if the user logs
 off... Something Windows doesn't really support.

   Windows os.startfile(...) MIGHT do what you want
   
Yes I know  works in unix/linux; I thought it worked in windows also.
But thanks, os.startfile() worked perfectly.
Cheers
-- 
http://mail.python.org/mailman/listinfo/python-list


popen(1-4) as a seperate process

2006-11-16 Thread Astan Chee
Hi,
Im trying to popen (or more specifically os.popen4() ) from wxPython. 
I've read the documentation on popen and it says I can do a popen as a 
seperate process or popen not as a child process but it doesnt say how.
Can anyone help?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen(1-4) as a seperate process

2006-11-16 Thread Astan Chee

Fredrik Lundh wrote:

Astan Chee wrote:

  
Im trying to popen (or more specifically os.popen4() ) from wxPython. 
I've read the documentation on popen and it says I can do a popen as a 
seperate process or popen not as a child process



where does it say that?  afaik, the whole point of the popen API is to 
run an external process and use pipes to communicate with it.


/F

  
Yes, that is true. But everytime I run a os.popen() it executes as a 
child process of the current running one. How do I launch as a seperate 
process?
Note that I dont care about whatever happens to the seperate process 
itself.

Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: popen(1-4) as a seperate process

2006-11-16 Thread Astan Chee
Fredrik Lundh wrote:
 Astan Chee wrote:

   
 Yes, that is true. But everytime I run a os.popen() it executes as a 
 child process of the current running one. How do I launch as a seperate 
 process?
 

 what's your definition of separate process, and how is that different 
 from a child process?  (all processes created by a process start out as 
 child processes).

   
 Note that I dont care about whatever happens to the seperate process 
 itself.
 

 so why are you using os.popen() if you're not interested in talking to 
 it?  maybe os.system(command) would be more appropriate ?

 /F

   
My appologies,
What I meant by seperate process is that the spawned process is not the 
child of the current running process or the spawned process does not 
have a parent (if that is possible).
popen not a good idea? Im not sure myself frankyl.
What would be a good method to do this? I've tried your 
os.system(command) and the spawned process is still the child of the 
current running process (which is not what I want to happen).
Thanks again and sorry for the confusion.

-- 
http://mail.python.org/mailman/listinfo/python-list


web-based SSH

2006-10-25 Thread Astan Chee
Hi,
I was looking for a web-based SSH client (something like
www.port42.com..but for some reason it doesnt work..can anyone verify
this)..does anyone know any other alternative to other websites that offer
this? If you're gonna scream 'security!security!' well, its for testing
purposes and the box im ssh-ing into is expandable and disposeable
Cheers


-- 
http://mail.python.org/mailman/listinfo/python-list


a bug in list.remove?

2006-08-18 Thread Astan Chee
Hi all,
I have 2 lists. What Im doing is check the first list and remove all 
occurances of the elements in the second list from the first list, like so:
  ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
  qs = [6,7,8,9,10,11,12,1,2]
  for p in ps:
if p in qs:
ps.remove(p)

The problem Im having is that when I do
  print ps
 it gives me
[2, 3, 4, 5, 7, 9, 11, 13, 14, 15]
which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a 
bug in .remove? or is my algorithm somewhat flawed?
Thanks for your help!
Cheers
Astan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a bug in list.remove?

2006-08-18 Thread Astan Chee


Tim Chase wrote:

 I have 2 lists. What Im doing is check the first list and remove all 
 occurances of the elements in the second list from the first list, 
 like so:
   ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
   qs = [6,7,8,9,10,11,12,1,2]
   for p in ps:
 if p in qs:
 ps.remove(p)

 The problem Im having is that when I do
   print ps
  it gives me
 [2, 3, 4, 5, 7, 9, 11, 13, 14, 15]
 which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a 
 bug in .remove? or is my algorithm somewhat flawed?



 I'd go with the somewhat flawed answer.

 I'd just use

 ps = [x for x in ps if x not in qs]

 which will remove *all* instances of x from ps if it exists in qs.  
 There's a subtle difference from the remove() method, which will only 
 remove the first instance:

  help([].remove)
 Help on built-in function remove:

 remove(...)
 L.remove(value) -- remove first occurrence of value



 If qs is large, you'll get improved performance by converting it to a 
 set first:

  s = set(qs)
  ps = [x for x in ps if x not in s]


 As for your algorithm, you're modifying the list over which you're 
 iterating--at best, often considered bad form...at worst, I've had 
 Python throw exceptions at me for attempting it.

 -tkc

Thanks for that. Really helpful!
Cheers
Astan
-- 
http://mail.python.org/mailman/listinfo/python-list


urllib2, proxies and https

2006-08-18 Thread Astan Chee
Hi again,
According to
https://demo.launchpad.net/products/python/+bug/56872
or more specifically, the example of its working code:
http://librarian.demo.launchpad.net/3507227/urllib2_proxy_auth.py
I can use urllib2 via proxy to access a https site(specifically hooking 
it up to libgmail).
The problem is that the proxy that is accessible to me is http/port8080 
only. Is it possible to use urllib2 with this proxy to access a https 
site? (im guessing no, but im sure there are ways around it).
I've tried modifying the code to point to a https site 
(https://mail.google.com/mail/) without changing the http proxy and it 
produces a HTTP timeout error.
Despite this, if I manually use a web browser to access these sites it 
prompts me with the proxy login and lets me through. So im also puzzled 
here why my browser lets this happen but urllib2 doesnt.
Thanks again for all your help.
Cheers
Astan



-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >