Re: How to write fast into a file in python?

2013-05-19 Thread Tim Roberts
Carlos Nepomuceno  wrote:

>Python really writes '\n\r' on Windows. Just check the files.

It actually writes \r\n, but it's not Python that's doing it.  It's the C
runtime library.

And, of course, you can eliminate all of that by opening the file in binary
mode open(name,'wb').
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scope of a class..help???

2013-05-23 Thread Tim Roberts
lokeshkopp...@gmail.com wrote:
>
>ok Peter Otten,
>but how to make a Class global??

Your class IS global.  I still don't think you understand what you did
wrong.  You've tripped into a strange little quirk of scoping.  Here is
your code with some unimportant lines removes.

class Node:
def __init__(self, value=None):
self.value = value
self.next = None

## OK, at this point, you have a global called "Node", which is a class.

def number_to_LinkedList(numbers):
  pass
  list_numbers = list(numbers)
  head_node = Node()
  # ... 
  current_node.next = None
  while Node:
print Node.data

Python actually does a first scan through your function before it starts to
compile it.  When it does the scan, it sees you use the name "Node" as a
local variable.  At that point, it remembers that "in this function scope,
'Node' is a local name".  Now, it codes to compile the class.  When it
encounters Node() for the first time, it sees that "Node" is not defined
locally, even though it was supposed to be a local name.

You are assuming that the first Node() in that function will automatically
refer to the global class.  It won't.  The only way to solve this dilemma
is to change the name you use in the "while" loop.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encodign issue in Python 3.3.1 (once again)

2013-05-26 Thread Tim Roberts
? ???33?  wrote:
>
>This is the code that although correct becaus it works with englisg(standARD 
>ASCII letters) it wont with Greek:
>...
>if( log ):
>   name = log
>   # print specific client header info
>   cur.execute('''SELECT hits, money FROM clients WHERE name = %s''', 
> (name,) )
>   data = cur.fetchone()
>===
>
>The following is the live output of: tail -F /usr/local/apache/logs/error_log &
>...
>   File "/opt/python3/lib/python3.3/site-packages/pymysql/cursors.py", line 
> 108, in execute, referer: http://superhost.gr/cgi-bin/pelatologio.py
> query = query.encode(charset), referer: 
> http://superhost.gr/cgi-bin/pelatologio.py
> UnicodeEncodeError: 'latin-1' codec can't encode characters in position 
> 46-52: ordinal not in range(256), referer: 
> http://superhost.gr/cgi-bin/pelatologio.py
>
>I can udnerstand that this is an encoding issue but i dont knwo how to fix 
>this.
>please help.

While the other responders have a good laugh at your expense, let me
actually point you toward a solution.

The traceback line I left above is the key.  It shows that the pymysql
module is trying to encode your Unicode string into an 8-bit character set
in order to send it to the MySQL server.  It is THAT conversion that
failed; this has nothing to do with the server (yet).

So, why did it choose 'latin-1'?  Because that's the default character set
for pymysql.  You could have learned this yourself -- you have the full
source code for pymysql on your machine.

You can override the default character set:

    con = pymysql.connect( db = 'metrites', host = 'localhost', user =
'me', passwd = 'somepass', charset='utf-8', init_command='SET NAMES UTF8' )
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an integer from a sequence of bytes

2013-06-04 Thread Tim Roberts
Grant Edwards  wrote:

>On 2013-06-03, Dan Stromberg  wrote:
>>
>> When I was a Freshman in college, I used a CDC Cyber a lot; it had 6 bit
>> bytes and 60 bit words.  This was in 1985.
>
>But you couldn't address individual 6-bit "hextets" in memory could
>you?  My recollection is that incrementing a memory address got you
>the next 60-bit chunk -- that means that by the older terminology a
>"byte" was 60 bits.  A "character" was 6 bits, and a single register
>or memory location could hold 6 characters.

A single machine word was 60 bits, so a single register read got you 10
characters.  There were three sets of registers -- the X registers were 60
bits, the A and B registers were 18 bits, which was the size of the largest
possible address.

CDC didn't actually use the term "byte".  That was IBM's domain.

When ASCII became unavoidable, most programs changed to using 5x 12-bit
"bytes" per word.

Ah, memories.  I spent 10 years working for Control Data.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-11 Thread Tim Roberts
 ??  wrote:
>
>[code]
>   if not re.search( '=', name ) and not re.search( '=', month ) 
> and not re.search( '=', year ):
>   cur.execute( '''SELECT * FROM works WHERE clientsID = 
> (SELECT id FROM clients WHERE name = %s) and MONTH(lastvisit) = %s and 
> YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', (name, month, year) )
>   elif not re.search( '=', month ) and not re.search( '=', year ):
>   cur.execute( '''SELECT * FROM works WHERE 
> MONTH(lastvisit) = %s and YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', 
> (month, year) )
>   elif not re.search( '=', year ):
>   cur.execute( '''SELECT * FROM works WHERE 
> YEAR(lastvisit) = %s ORDER BY lastvisit ASC''', year )

There is so much you didn't tell us here, including which database you are
using.

With most Python database adapters, the second parameter of the "execute"
method must be a tuple.  "year" is not a tuple.  My guess is that this will
work fine:
cur.execute( 
"SELECT * FROM works WHERE YEAR(lastvisit)=%s ORDER BY lastvisit",
(year,) )

It seems silly to fire up a regular expression compiler to look for a
single character.  
if name.find('=') < 0 and month.find('=') < 0 and year.find('=') < 0:
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an integer from a sequence of bytes

2013-06-13 Thread Tim Roberts
Fábio Santos  wrote:

>On 5 Jun 2013 06:23, "Tim Roberts"  wrote:
>> A single machine word was 60 bits, so a single register read got you 10
>> characters.
>
>10 characters! Now that sounds like it's enough to actually store a word.
>However long words can inadverten be cropped.

Well, Cybers weren't often used for heavy text processing.  Most of the
time, a "word" was limited to 7 characters, so you could fit an 18-bit
address in the bottom of the register.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-15 Thread Tim Roberts
Nick the Gr33k  wrote:
>
>but i'm doing this all day long i just dont comprehend why it works this 
>way.
>it doesn't make any sense to me.

It's just a rule you'll have to learn.  The "and" and "or" operators in
Python simply do not return a boolean value.  The expression "a or b" is
evaluated as:
if a is true then return a otherwise return b

It's true that in many languages, "or" returns a Boolean value, so the
result is:
if a is true then return True otherwise return bool(b)

Because Python lets you use arbitrary values in a Boolean context, the net
result is exactly the same.  However, the Python is a lot more flexible,
because it lets you simulate the C ternary ?: operator.

Similarly, "a and b" is evaluated as:
if a is false then return a otherwise return b

In a long series separated by "or", the expression is true as soon as one
of the subexpressions is true.  So, as a short-circuit, Python simply
returns the first one that has a "true" value.  So, for example, these all
return 'abcd':

'abcd' or 'defg' or 'hjkl'   ==> 'abcd'
0 or 'abcd' or 'defg' or 'hjkl'  ==> 'abcd'
0 or None or 'abcd' or 'defg' or 'hjkl'  ==> 'abcd'

Similarly, "and" returns the first "false" value, or if they're all true,
the last value.  Why?  Because it can't know whether the whole expression
is true unless it looks at every value.  So:

0 and 1 and 'what'   ==>  0
1 and 0 and 'what'   ==>  0
1 and None and 0 ==>  None
1 and 1 and 'what'   ==> 'what'
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A certainl part of an if() structure never gets executed.

2013-06-18 Thread Tim Roberts
Nick the Gr33k  wrote:
>
>On 16/6/2013 4:55 ??, Tim Roberts wrote:
>
>> Nick the Gr33k  wrote:
>> Because Python lets you use arbitrary values in a Boolean context, the net
>> result is exactly the same.
>
>What is an arbitrary value? don even knwo what arbitrary means literally 
>in English.

Basically, it means "any".  In Python, you can use ANY value where a
Boolean is expected.  All types have a Boolean meaning.  For integers, 0 is
false, anything else is true.  For strings, an empty string "" is false,
anything else is true.  For lists, an empty list [] is false, anything else
is true.  For tuples, an empty tuple () is false, anything else is true.
For dicts, an empty dict {} is false, anything else is true.

>The argument being returned in an "and" or "or" expression is the one 
>that *determined' the evaluation of the expression.

That's not exactly how I'd put it, but the statement is correct.  The last
thing it had to evaulate is the result of the expression.

>And actually what's being returned is not the argument itself but the 
>argument's value.

But this is no different than any other programming language.  Expressions
always use the value of their operands, and they always return a value.

The name vs value thing is critical to understanding Python, in my opinion,
and it can be a stumbling block when you're coming from another language.
Here's how I think about it.

Python had two distinct spaces: there is a space for names, and there is a
space for objects (which are values).  Objects live in a nameless, faceless
object cloud.

A name is always bound to some object (which might be the "None" object). A
name always knows its object, but an object never knows what names it is
bound to.

The only things that can be used in expressions and function arguments are
objects.  Names are merely the way we specify which objects to be used.

a = [3]

That creates a nameless list containing a single integer object with the
value 3.  It then binds the name "a" to that list.  Note that the list has
no clue that it is bound to any names.

b = a

That binds "b" to the same list.  "b" and "a" are not related in any way,
except that they happen to be bound to the same object.  Note that there is
still only one list.

a.append(4)

That modifies the list so that it now contains [3,4].  b is bound to the
same list, so if you 
print(b)
you'll see [3,4]

Now, let's say I do this:

a = [5]

Here's where people get tripped up.  This does not change our original
list.  Instead, it creates a new nameless list containing 5, and binds the
name a to that list.  a and b are no longer bound to the same object.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell Script to use pythonw.exe ?

2013-07-02 Thread Tim Roberts
goldtech  wrote:
>
>I just changed the file extension of the script file from .py to .pyw
>and it uses pythonw.exe. I didn't read it anywhere, just intuited it
>and tried it. Python has some very smart people working the language...

While your statement is true, that's not what happened here.

Windows has long had the ability to associate a file extension with a
handler.  If you start a command shell, the "assoc" command tells you the
program type associated with an extension, and the "ftype" command tells
you the command line that will be executed for that program type.  On my
box:

C:\tmp>assoc .py
.py=Python

C:\tmp>ftype Python
Python="C:\Apps\Python27\Python.exe" "%1" %*

C:\tmp>assoc .pyw
.pyw=Python.NoConFile

C:\tmp>ftype Python.NoConFile
Python.NoConFile="C:\Apps\Python27\Pythonw.exe" "%1" %*

You can create your own, if you want.  If you want files with a .script
extension to run PythonW, you can type:

assoc .script=Python.NoConFile
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Geo Location extracted from visitors ip address

2013-07-05 Thread Tim Roberts
? Gr33k  wrote:
>
>Is there a way to extract out of some environmental variable the Geo 
>location of the user being the city the user visits out website from?
>
>Perhaps by utilizing his originated ip address?

It is possible to look up the geographic region associated with a block of
IP addresses.  That does not necessarily bear any resemblence to the actual
location of the user.  It tells you the location of the Internet provider
that registered the IP addresses.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hex dump w/ or w/out utf-8 chars

2013-07-12 Thread Tim Roberts
Joshua Landau  wrote:
>
>Isn't a superscript "c" the symbol for radians?

That's very rarely used.  More common is "rad".  The problem with a
superscript "c" is that it looks too much like a degree symbol.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get the OS System Font Directory(Cross-Platform) in python?

2013-07-12 Thread Tim Roberts
Metallicow  wrote:
>
>If the OS doesn't *have* a dedicated system fonts dir that is accessable 
>by the user, then I am not that much interested in dealing with it. 

Really?  Because Windows is the ONLY one of the major operating systems
that actually has a dedicated system fonts directory.  Linux doesn't even
have a dedicated windowing system.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: must be dicts in tuple

2013-07-29 Thread Tim Roberts
Tanaya D  wrote:
>
>I am using Python with Bots(EDI translator)
>
>But i am getting the following error:
>MappingFormatError: must be dicts in tuple: get((({'BOTSID': 'HEADER'},),))
>
>Can anyone pls help me with it.

Possible hint: the error says you're supposed to have dicts in a tuple.
What you have is a dict in a tuple in a tuple.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when "normal" parallel computations in CPython will be implemented at last?

2012-07-04 Thread Tim Roberts
John Nagle  wrote:
>
>It would be "un-Pythonic" to have real concurrency in Python.
>You wouldn't be able to patch code running in one thread from
>another thread.  Some of the dynamic features of Python
>would break.   If you want fine-grained concurrency, you need
>controlled isolation between concurrent tasks, so they interact
>only at well-defined points.  That's un-Pythonic.

I disagree.  The situation in Python is no different than the situation in
other programming languages.  If you have shared state, you protect it with
some kind of lock.  After all, you don't patch code on a byte-by-byte basis
-- you just change function bindings.  That can be done atomically.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I disable module of tkinter when compiling Python 2.5 on redhat9 ?

2012-07-09 Thread Tim Roberts
cheetah  wrote:
>
>I don't need it.

It's not worth worrying about.  You're talking about way less than a
megabyte of disk space, and there is no performance penalty unless you're
using it.

In general, the parts of the Python standard library are not individually
selectable.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Search and replace text in XML file?

2012-07-28 Thread Tim Roberts
todd.tab...@gmail.com wrote:
>
>I basically need to replace every occurrence C:\Program Files with
>C:\Program Files (x86), regardless of location. For example, that 
>text appears within: 
>C:\Program Files\\Map Data\Road_Centerlines.shp
>and also within: 
>C:\Program 
>Files\Templates\RoadNetwork.rtx
>...among others.
>I've tried some non-python methods and they all ruined the XML structure. 

I don't see how that's possible.  XML doesn't have any character counts,
and it doesn't care about extra white space.  A rock-stupid editor
substitution should have been able to do this in two seconds.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when an iterable object is exhausted or not

2012-08-04 Thread Tim Roberts
Franck Ditter  wrote:
>
>Two similar iterable objects but with a different behavior :
>
>$$$ i = range(2,5)
>$$$ for x in i : print(x,end=' ')
>
>2 3 4 
>$$$ for x in i : print(x,end=' ')# i is not exhausted   
>
>2 3 4 
>
>- Compare with :
>
>$$$ i = filter(lambda c : c.isdigit(), 'a1b2c3')
>$$$ for x in i : print(x,end=' ')
>
>1 2 3 
>$$$ for x in i : print(x,end=' ')# i is exhausted
>
>$$$ 
>
>IMHO, this should not happen in Py3k.

It's interesting that it DOESN'T happen in Python 2.  The first "i" is of
type list, the second "i" is of type string, and both are restartable.

What's the type of "i" in the second case in Python 3?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On-topic: alternate Python implementations

2012-08-04 Thread Tim Roberts
Steven D'Aprano  wrote:
>
>Most people are aware, if only vaguely, of the big Four Python 
>implementations:
>
>CPython, or just Python, the reference implementation written in C.
>IronPython, written in .NET.

Technicality:  .NET is not a language, it is a run-time framework.
IronPython is written in C#.  It generates code that runs in the .NET
Framework.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling loaded DLL function expecting POINT * argument

2012-08-26 Thread Tim Roberts
Tim Williams  wrote:

>Hello all,
>
>I'm trying to use the ctypes module to call functions in a DLL. I've
>figured out how to modify my path so the library is found, and I can 
>call LoadLibrary on it, but one of the functions expects an array of
> POINTS. Here is the prototype from the .h file:
>
>
>TRACKER_API HRESULT InitializeMask(HANDLE pHandle, int nWidth, int nHeight, 
>POINT* ptMasks, int nNumPoints);

How is TRACKER_API defined?  You're using ctypes.oledll, which uses the
__stdcall calling convention.  It's possible your DLL is defined as
__cdecl.  Try cdll.LoadLibrary instead of oledll.LoadLibrary.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending USB commands with Python

2012-08-28 Thread Tim Roberts
"Adam W."  wrote:
>
>So I'm trying to get as low level as I can with my Dymo label printer, 
>and this method described the PDF 
>http://sites.dymo.com/Documents/LW450_Series_Technical_Reference.pdf 
>seems to be it.
>
>I'm unfamiliar with dealing with the USB interface and would greatly
>appreciate it if someone could tell me how to send and receive these
>commands with Python.  Perhaps if you were feeling generous and 
>wanted to write a bit of sample code, sending the "Get Printer 
>Status" command and receiving the response (page 17 of the PDF) 
>would be perfect to get me on my way.

Well, it's more than "a bit of sample code".  You would essentially be
writing a device driver.

Which operating system are you using?  If you are on Windows, then the
operating system has already loaded a printer driver for this device.  You
can't talk to the USB pipes without uninstalling that driver.  It would be
just about as easy for you to learn to use GDI to write to the printer like
a normal application, and that way the code would work on the NEXT
generation of printer, too.

The libusb or libusbx libraries can be used to talk to USB devices.  There
is a Python binding.  On Windows, you still need to have a driver, but the
libusbx instructions can help you find an install one.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending USB commands with Python

2012-08-30 Thread Tim Roberts
"Adam W."  wrote:
>
>You are correct about the 2 being the number of bytes written.  However when I 
>issue a read command I get:
>
>>>> ep.write('\x1BA')
>4
>>>> ep.read(1)
>usb.core.USBError: [Errno None] b'libusb0-dll:err [_usb_setup_async] invalid 
>endpoint 0x02\n'

USB endponts only go in one direction.  There will be one endpoint for
outoging data, and one endpoint for incoming data.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Tim Roberts
David Smith  wrote:
>
>I'm converting windows bat files little by little to Python 3 as I find 
>time and learn Python.
>The most efficient method for some lines is to call Python like:
>python -c "import sys; sys.exit(3)"
>
>How do I "indent" if I have something like:
>if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else 
>sys.exit(3)
>
>My sole result in many attempts is "Syntax Error."

The other responses asking "why" are excellent, but this will do that
specific job:

sys.exit( {'Cope':1,'Perform':2}.get(sR,3) )

The best way to convert a batch file to Python is to convert the whole file
to a Python script.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing arguments to & executing, a python script on a remote machine from a python script on local machine (using ssh ?)

2012-09-19 Thread Tim Roberts
ashish  wrote:
>
>Here is my situation
>
>1. I have two machines. Lets call them 'local' & 'remote'.
>Both run ubuntu & both have python installed
>
>2. I have a python script, local.py, running on 'local' which needs to pass
>arguments ( 3/4 string arguments, containing whitespaces like spaces, etc )
>to a python script, remote.py running on 'remote' (the remote machine).

You haven't provided very many details, so it's possible ssh is the
low-impact solution, but don't discard the possibility of using a TCP
socket for this.  It's easy in Python.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to limit CPU usage in Python

2012-09-22 Thread Tim Roberts
Rolando Cañer Roblejo  wrote:
>
>Is it possible for me to put a limit in the amount of processor usage (% 
>CPU) that my current python script is using?

Why?  That's an odd request.  It's natural to want to reduce your priority
if you want other processes handled first, but an idle CPU is a wasted
resource.  You want it to be busy all of the time.

>Some people recommend to use nice and cpulimit unix 
>tools, but those are external to python and I prefer a python solution. 

Scheduling and CPU priority are, by their very nature, operating system
concepts.  You will not find generic mechanisms wrapping them.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exact integer-valued floats

2012-09-22 Thread Tim Roberts
Dennis Lee Bieber  wrote:
>
>On 22 Sep 2012 01:36:59 GMT, Steven D'Aprano wrote:
>> 
>> For non IEEE 754 floating point systems, there is no telling how bad the 
>> implementation could be :(
>
>   Let's see what can be found...
>
>   IBM 360: Same as Sigma-6 (no surprise; hearsay is the Sigma was
>designed by renegade IBM folk; even down to using EBCDIC internally --
>but with a much different interrupt system [224 individual interrupt
>vectors as I recall, vs the IBM's 7 vectors and polling to find what
>device]).

The Control Data 6000/Cyber series had sign bit and 11-bit exponent, with
either a 48-bit mantissa or a 96-bit mantissa, packed into one or two
60-bit words.  Values were not automatically normalized, so there was no
assumed 1 bit, as in IEEE-754.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exact integer-valued floats

2012-09-22 Thread Tim Roberts
True.  Seymour wanted all of the integer instructions to be combinatorial 
logic, rather than iterative.  Fortunately, since the floating point binary 
point was to the right, it was trivial to pack integers to float, do a floating 
computation, then unpack back to integer.

Apologize in advance for top-posting.  My Xoom makes bottom-posting awkward.
--
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.

Dave Angel  wrote:


On 09/22/2012 05:05 PM, Tim Roberts wrote:
> Dennis Lee Bieber  wrote:
>> On 22 Sep 2012 01:36:59 GMT, Steven D'Aprano wrote:
>>> For non IEEE 754 floating point systems, there is no telling how bad the
>>> implementation could be :(
>>  Let's see what can be found...
>>
>>  IBM 360: Same as Sigma-6 (no surprise; hearsay is the Sigma was
>> designed by renegade IBM folk; even down to using EBCDIC internally --
>> but with a much different interrupt system [224 individual interrupt
>> vectors as I recall, vs the IBM's 7 vectors and polling to find what
>> device]).
> The Control Data 6000/Cyber series had sign bit and 11-bit exponent, with
> either a 48-bit mantissa or a 96-bit mantissa, packed into one or two
> 60-bit words.  Values were not automatically normalized, so there was no
> assumed 1 bit, as in IEEE-754.

And it's been a long time (about 39 years), but as I recall the CDC 6400
(at least) had no integer multiply or divide.  You had to convert to
float first.  The other oddity about the CDC series is it's the last
machine I've encountered that used ones-complement for ints, with two
values for zero.


--

DaveA

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


Re: How to limit CPU usage in Python

2012-09-24 Thread Tim Roberts
Paul Rubin  wrote:
>
>Tim Roberts: reasons to want to do this might involve a shared host
>where excessive cpu usage affects other users;

That's what priorities are for.

>...or a computer with
>limited power consumption, where prolonged high cpu activity causes
>thermal or other problems.

OK, I grant that.  However, statistically speaking, it is much more likely
that the OP merely has a misunderstanding.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who's laughing at my responses, and who's not?

2012-09-24 Thread Tim Roberts
Dwight Hutto  wrote:
>
>Been getting slammed by a few for some insignificant things, so who's
>laughing at me, and who takes me seriously. I don't claim to be the
>best, just trying to help.
>
>So who doesn't want me around?

Who cares?  There are probably hundreds of thousands of people reading this
forum.  A few of those people probably don't like you.  So what?

Illegitemi non carborondum -- don't let the bastards wear you down.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Experimental Python-based shell

2012-10-02 Thread Tim Roberts
Jonathan Hayward  wrote:
>
>I've made an experimental Python-based Unix/Linux shell at:
>
>http://JonathansCorner.com/cjsh/
>
>An experimental Unix/Linux command line shell, implemented in Python 3,
>that takes advantage of some more recent concepts in terms of usability
>and searching above pinpointing files in heirarchies.
>
>I invite you to try it.

Without intending to detract from your work in any way, are you familiar
with the IPython project?

http://ipython.org/

You may find some interesting synergy with them.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating C++ code

2012-10-10 Thread Tim Roberts
Jean-Michel Pichavant  wrote:
>
>I'm trying to generate C++ code from an XML file. I'd like to use a template 
>engine, which imo produce something readable and maintainable.
>My google search about this subject has been quite unsuccessful, I've been 
>redirected to template engine specific to html mostly.
>
>Does anybody knows a python template engine for generating C++ code ?

I'm a big fan of Cheetah.  It's simple but flexible enough to be useful.
Besides the many web projects I've done with it, I also I use it in one
project to generate PHP code (it generates data access objects from a live
database schema).
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding http proxies

2012-10-14 Thread Tim Roberts
Olive  wrote:
>
>it seems when I read the code above that the proxy acts mostly as an
>orinary server with respect to the client except that it is supposed to
>receive the full URL instead of just the path. Am I right? Is there any
>documentation on what an http proxy is supposed to implement.

Consider the ways HTTP could have been implemented.  Say we have a request
to get http://www.bigsite.com/pictures/index.html .

One way HTTP could have been implemented is by sending this request to the
server at www.bigsite.com:

GET /pictures/index.html HTTP/1.0

If that were how HTTP were done, you could not implement a proxy, because
there isn't enough information for any intermediates to know where the
request had to end up.

Instead, http looks like this:

GET /pictures/index.html HTTP/1.1
Host: www.bigsite.com

Now, even if this is sent to someone who is not "www.bigsite.com", that
receipient can tell exactly who is supposed to get the message.

So, a web proxy receives requests intended for other sites, and forwards
them on, possibly after restricting or modifying them.  That's it.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pls help me with this prog

2012-10-20 Thread Tim Roberts
inshu chauhan  wrote:
>
>but i want to calculate it for every 3 points not the whole data, but
>instead of giving me centre for every 3 data the prog is printing the
>centre 3 times...
>
>def main (data):
>j = 0
>for  i in data[:3]:
>while j != 3:
> centre = CalcCentre(data)
> j += 1
> print centre

This loop doesn't do what you think it does.  Think about the problem you
have to solve.  You have a set of data.  You want to operate on the whole
set, 3 points at a time.  What this loop does is grab the first three
points (only), then calculates the center on the entire list three times.

You want something like:

# As long as there is data in the list:
while data:
# Split the list into two parts: first 3 and the rest.
first3, data = data[3:],data[3:]
# Operate on the first three.
print CalcCenter( first3 )

To make it a little more resilient, you might make sure that len(data) is a
multiple of 3, or at least stop when it is shorter than 3.

To be more clever, you can write a function that returns 3 at a time:

def N_at_a_time( iter, n ):
while len(iter) >= n:
yield iter[:n]
iter = iter[n:]

Now you can do this:

def main(data):
for first3 in N_at_a_time(data, 3):
print CalcCenter(first3)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Listen for changes in variable (alsaaudio.Mixer(x, x).getvolume(x)

2012-10-24 Thread Tim Roberts
Muffinman  wrote:
>
>I'm new to Python (running 2.6.6 but if necessary 3.x should also be
>fine). I have a little idea I hope to accomplish with Python. I want to
>listen for changes in Alsa sound volume level and base some actions on
>that. With the few lines below I can check the current volume level. 
...
>
>volumes = mixer.getvolume(1)

Now, do you understand that this is just fetching the current setting of
the volume control for the microphone?  It's not telling you anything about
the actual level of the sounds being captured.

The fact that you're talking about real-time response makes me think you
might be misunderstanding this.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: awk like usage in python

2012-11-09 Thread Tim Roberts
Rudra Banerjee  wrote:
>
>Friends,
>I am in process learning python.
>I basically use shell scripts for text formatting and trying my hand on
>python.
>where I am fighting is awk's functionality in python. 
>Say, one of my real tiny code looks like:
>#!/bin/bash
>TMP=store
>for i in $1/MnBi_EOS_*
>do
>#  echo $i
>  grep -A 15 "T(est)" $i/out-Dy-eos2 >$TMP
>  var_T=`awk '/T\(est\)/{printf $2}' $TMP`
>  var_s1=`awk '/s1,torque/{print $6;exit}' $TMP`
>  var_t=`awk '/s1,torque/{print $7;exit}' $TMP`
>  echo  $var_T  $var_s1  $var_t >>tfl
>#  echo ""
>#  echo ""
>done
>sort -n tfl >$2
>rm -i $TMP tfl

Well, describe your program in words.  Then, you can convert it to Python.

For every directory in the given directory whose name starts with
MnBi_EOS_:
extract the 15 lines starting with T(est) from the file out-Dy-eos2 to
a temporary file
extract the 2nd field from the line with T(est) in it
extract the 6th field from the first line with "s1,torque"
extract the 7th field from the first line with "s1,torque"
print those three fields to a file
sort that file
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subprocess puzzle and two questions

2012-11-13 Thread Tim Roberts
w...@mac.com wrote:
>...
>However, if I try the same operation in the python interpreter using 
>subprocess.Popen like so:
>
>>>> import subprocess
>>>> result = subprocess.Popen(['time', 'nslookup', 'www.es.net', '8.8.4.4'], 
>>>> shell = False, stdout = subprocess.PIPE, stderr = 
>>>> subprocess.PIPE).communicate()
>>>> print result
>('Server:\t\t8.8.4.4\nAddress:\t8.8.4.4#53\n\nNon-authoritative 
>answer:\nwww.es.net\tcanonical name = 
>www3.es.net.\nName:\twww3.es.net\nAddress: 128.55.22.201\n\n', '0.06 
>real 0.00 user 0.00 sys\n')
>
>And the timing information I'm after has been truncated to two digits after 
>the decimal.  It appears that Popen is applying a default format. 

No, that's silly.  A few minutes thought should have told you that.  In
your standalone test, you are getting the "time" command that is built in
to bash.  In the subprocess example, you've specified "shell = False", so
you are using the external "time" command (/usr/bin/time in my system), and
that command has a different output format.  The csh "time" command is
different yet again.

>1) how can I recover that third digit from the subprocess?

Do you actually believe that the third decimal place has any meaning at
all?  It doesn't.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing process name

2012-11-19 Thread Tim Roberts
andrea crotti  wrote:

>I have very long processes to spawn which I want to lauch as separate
>processes (and communicate with ZeroMQ), but now the problem is that the
>forked process appears in "ps" with the same name as the launcher
>process.

http://code.google.com/p/py-setproctitle/
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.popen and the subprocess module

2012-11-28 Thread Tim Roberts
Andrew  wrote:
>
>I'm working on a script that will run an executable obtaine the output  
> from the executable
>and do some analysis on the output. Essentially the script runs the  
>executable analyses
>the data.
>I'm looking into os.popen and the subprocess module, implementing os.popen  
>is easy but i hear
>it is depreciating  however I'm finding the implemantation of subprocess  
>daunting can anyone help

One of my favorite things about the subprocess module is that the
introductory comments have examples of how to use subprocess to replace
almost every use case for os.system and os.popen.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why does dead code costs time?

2012-12-05 Thread Tim Roberts
Bruno Dupuis  wrote:

>On Wed, Dec 05, 2012 at 05:40:51PM +0100, Bruno Dupuis wrote:
> 
>> Good point! I didn't even noticed that. It's weird... Maybe the
>> difference comes from a peehole optim on f which is not possible on g as
>> g is to complex.
>
>Neil, you were right, thanks. I patched peehole.c to remove this optim, and
>now the figures are the same. I investigate to find out why the latter
>function is not optimized the same way (and if it can be, I'll propose a
>patch for that)

At the risk of being labeled a prude, please be careful about spelling (and
pronouncing) the whole word "peephole".  The word as you have spelled it
here (twice) is a vulgarity.

Now, I'm all in favor of the occasional vulgarity, but if this is a
misunderstanding, you could find yourself as the butt of some awkward jokes
at some future optimization conference...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python USB control on Windows 7?

2012-12-22 Thread Tim Roberts
Duncan Booth  wrote:
>
>In this year's Christmas Raffle at work I won a 'party-in-a-box' including 
>USB fairy lights.
>
>They sit boringly on all the time, so does anyone know if I can toggle the 
>power easily from a script? My work PC is running Win7.

Not easily, no.  It's not really a USB device -- I'm betting it doesn't
even enumerate.  It's just sucking power from the USB wires.  There's
nothing to control.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-26 Thread Tim Roberts
Abhas Bhattacharya  wrote:
>
>While I am defining a function, how can I access the name (separately as
>string as well as object) of the function without explicitly naming 
>it(hard-coding the name)?
>For eg. I am writing like:
>def abc():
>#how do i access the function abc here without hard-coding the name?

Why?  Of what value would that be?

Note that I'm not merely being obstructionist here.  What you're asking
here is not something that a Python programmer would normally ask.  The
compiled code in a function, for example, exists as an object without a
name.  That unnamed object can be bound to one or more function names, but
the code doesn't know that.  Example:

def one():
print( "Here's one" )

two = one

That creates one function object, bound to two names.  What name would you
expect to grab inside the function?

Even more obscure:

two = lamba : "one"
one = two

Which one of these is the "name" of the function?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am facing an issue while decoding json string using json.loads

2012-12-26 Thread Tim Roberts
sajuptpm  wrote:
>
>I am facing an issue while decoding json string using json.loads(jstring).
>Its working, if i do json.dumps(eval(jstring)) before json.loads(jstring).
>I could not figure out the issue. I want to avoide use of "eval" here.

The problem is that your string contains two instances of an escaped right
bracket  \]  .  That's not one of the characters you're allowed to escape
in JSON.  The rules are very strict.  There are only 8 allowed escape
codes, plus the \u construct.

Note that you cannot just replace \] with ], because your string also
contains one instance of \\] .

Who is doing the JSON encoding?  It appears to be doing it incorrectly.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the name of a function while defining it

2012-12-28 Thread Tim Roberts
Abhas Bhattacharya  wrote:
>
>Now, for your questions:
>If i call one() and two() respectively, i would like to see "one" and "two".
>I dont have much knowledge of lambda functions, neither am i going to use
>them, so that's something I cant answer.

My point is not that these are special cases to consider, but rather that
all of these are the GENERAL case.  A function, now matter how it was
created, is an anonymous object that lives out in object space.  Like all
objects, a function object can be bound to many different names.  An object
doesn't know just one name, and when a function object is invoked, it has
NO IDEA what name was used to invoke it.  The information is simply not
available.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle module doens't work

2012-12-28 Thread Tim Roberts
Omer Korat  wrote:
>
>So it means pickle doesn't ever save the object's values, only how it was 
>created? 

You say that as though there were a difference between the two.  There
isn't.  An object is just a dictionary of values.  If you set an object
member to a string, then that object's dictionary for that member name
contains a string.  It doesn't contain some alternative packed binary
representation of a string.

>Say I have a large object that requires a lot of time to train on data. It
>means pickle doesn't save its values, so you have to train it every time
>anew? Is there no way to save its trained values?

When you say "train on data", what do you mean?  If your training creates
computed data in other members, those members and their values should also
be saved in the pickle.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle module doens't work

2013-01-01 Thread Tim Roberts
Omer Korat  wrote:
>
>I am using the nltk.classify.MaxEntClassifier. This object has a set of 
>labels, and a set of probabilities: P(label | features). It modifies 
>this probability given data. SO for example, if you tell this object 
>that the label L appears 60% of the time with the feature F, then 
>P(L | F) = 0.6. 
>
>The point is, there is no way to access the probabilities directly. 
>The object's 'classify' method uses these probabilities, but you can't
>call them as an object property. 

Well, you have the source code, so you can certainly go look at the
implementation and see what the data is based on.

>In order to adjust probabilities, you have to call the object's 'train' 
>method, and feed classified data in.

The "train" method is not actually an object method, it's a class method.
It doesn't use any existing probabilities -- it returns a NEW
MaxEntClassifier based entirely on the training set.

>So is there any way to save a MaxEntClassifier object, with its 
>classification probabilities, without having to call the 'train' method?

If you haven't called the "train" method, there IS no MaxEntClassifier
object.  Once you have called "train", you should be able to pickle the new
MaxEntClassifier and fetch it back with its state intact.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the class problem

2013-01-01 Thread Tim Roberts
contro opinion  wrote:
>
>here is my haha  class
>class  haha(object):
>  def  theprint(self):
>print "i am here"
>
>>>> haha().theprint()
>i am here
>>>> haha(object).theprint()
>Traceback (most recent call last):
>  File "", line 1, in 
>TypeError: object.__new__() takes no parameters
>
>why   haha(object).theprint()  get wrong output?

It doesn't -- that's the right output.  What did you expect it to do?

The line "class haha(object)" says that "haha" is a class that happens to
derive from the "object" base class.  The class is still simply called
"haha", and to create an instance of the class "haha", you write "haha()".
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: got stuck in equation

2013-01-01 Thread Tim Roberts
usamazo...@gmail.com wrote:
> 
>i know very litle about programing. still learning from tutorials. u can call 
>me a beginner.
>now i need to solve this equation so that i can put this in python but the 
>formula of design is very complex 
> 
>Formula is :
> 
>log(W18) = (Z)(S)+9.36log(SN+1) 
>-2.0+(log(dpsi/(4.5-1.5))(/(.40+1094/(SN+1)^2.5)+2.32log(Mr-)-8.07
> 
>every thing is constant except this SN. . i want to seperate SN like SN= 
>rest of the stuff. how can i seprate it because manualy its impossible to
>take SN out.

Right.  Algebraically, it isn't practical to solve this for SN.  That
probably means you're going to need a iterative solution.  That is, you
start with a guess, see how far off you are, and refine the guess until you
narrow in on a solution.  That means you'll have to figure out whether
raising SN gets you closer or farther away from a solution.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: how to download internet files by python ?

2013-01-09 Thread Tim Roberts
iMath  wrote:
>
>There is also a httplib2 module 
>https://code.google.com/p/httplib2/
>
>which one is more pythonic and powerful ?

Both are Pythonic, and power is irrelevant for this.  Your code is going to
spend 90% of its time waiting for the network.  Just solve the problem.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Tim Roberts
Dave Angel  wrote:
>
>As Adnan has pointed out, Python is case insensitive. 

That's not really what you meant to say...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-21 Thread Tim Roberts
Ferrous Cranus  wrote:
>
>No, it is difficult but not impossible.
>It just cannot be done by tagging the file by:
>
>1. filename
>2. filepath
>3. hash (math algorithm producing a string based on the file's contents)
>
>We need another way to identify the file WITHOUT using the above attributes.

Think about it this way.  Say that YOU, as a human being, were inserted
into the web server.  You are handed the path and the contents of a page
about to be served.  How would YOU solve this problem?

If you can't describe in words how YOU would recognize these altered files,
then there is absolutely no way to teach a computer how to do it.  It IS
impossible.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-21 Thread Tim Roberts
Ferrous Cranus  wrote:
>
>Renames and  moves are performed, either by shell access or either by cPanel 
>access by website owners.
>
>That being said i have no control on HOW and WHEN users alter their html pages.

Right, and that makes it impossible to solve this problem.

Think about some scenarios.  Let's say I have a web site with two pages:
~/web/page1.html
~/web/page2.html

Now let's say I use some editor to make a copy of page1 called page1a.html.
~/web/page1.html
~/web/page1a.html
~/web/page2.html

Should page1a.html be considered the same page as page1.html?  What if I
subsequently delete page1.html?  What if I don't?  How long will you wait
before deciding they are the same?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing sys.path

2012-02-02 Thread Tim Roberts
Andrea Crotti  wrote:
>
>So suppose I want to modify the sys.path on the fly before running some code
>which imports from one of the modules added.
>
>at run time I do
>sys.path.extend(paths_to_add)
>
>but it still doesn't work and I get an import error.

Are you actually adding multiple paths?  One possible cause for error would
be this:
sys.path.extend( '/usr/local/lib' )

That succeeds, but it doesn't do what you meant.  It adds "/" as a path,
then "u", then "s", then "r", and so on.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem sending an email in html with mime image

2012-02-02 Thread Tim Roberts
Ariel  wrote:
>
>Hi everybody I have a question, here is my problem I want to send an
>email with content in html with an image embed so I converted the
>image binary in mime text and then I put the mime code inside the src
>attribute of the html like this:
>
>/>

Do email readers actually implement the data: scheme in  tags?

>The problem is that if I don't put the image mime code inside the src
>the email is sent but when I put the code then the email is not send
>and I don't get any error message.

There must be something else going on.  The content of the message is
irrelevant to the sending process, unless it makes your message way too
big.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs. C++11

2012-02-14 Thread Tim Roberts
sturlamolden  wrote:
>
>There are bigsimilarities between Python and the new C++ standard. Now
>we can actually use our experience as Python programmers to write
>fantastic C++ :-)

This is more true than you might think.  For quite a few years now, I've
been able to do an almost line-for-line translation of my Python programs
to C++ programs.  (Microsoft has had a "for each" extension for a while
that made this easier.)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerical Linear Algebra in arbitrary precision

2012-02-16 Thread Tim Roberts
Ken  wrote:
>
>Brand new Python user and a bit overwhelmed with the variety of
>packages available.  Any recommendation for performing numerical
>linear algebra (specifically least squares and generalized least
>squares using QR or SVD) in arbitrary precision?  I've been looking at
>mpmath but can't seem to find much info on built in functions except
>for LU decomposition/solve.

It is been my experience that numpy is the best place to start with
requests like this, although I don't know whether it will actually solve
your specific tasks:

http://docs.scipy.org/doc/numpy/reference/routines.linalg.html
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyusb and microchip mcp2210 interface

2012-02-29 Thread Tim Roberts
jobattle  wrote:
>
>Has anybody out there had any experience in using the PYUSB library with
>the new Microchip MCP2210 USB to SPI chip?

It appears to the system as a HID device.  You don't need to use PyUSB --
it already has a driver.

Check libhid -- it has a Python binding.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: are int, float, long, double, side-effects of computer engineering?

2012-03-05 Thread Tim Roberts
Xah Lee  wrote:
>
>some additional info i thought is relevant.
>
>are int, float, long, double, side-effects of computer engineering?

Of course they are.  Such concepts violate the purity of a computer
language's abstraction of the underlying hardware.  We accept that
violation because of performance reasons.  There are, as you point out,
languages that do maintain the purity of the abstraction, but that purity
is ALWAYS at the expense of performance.

I would also point out pre-emptively that there is nothing inherently wrong
with asking us to accept an impure abstraction in exchange for performance.
It is a performance choice that we choose to make.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Biologist new to cgi in python

2012-03-07 Thread Tim Roberts
Shane Neeley  wrote:
>
>Here is the function I am using to insert the variable file text inside the
>url. Is it even possible to include the upload command in the url? 

No.  You are trying to simulate a "GET" request, but files can only be
uploaded via a "POST" request of type multiport/form-data.  There is a
module called "poster" that can do the appropriate encoding for you:

http://stackoverflow.com/questions/680305/using-multipartposthandler-to-post-form-data-with-python
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyUSB available for current versions of Windows?

2012-03-09 Thread Tim Roberts
John Nagle  wrote:

>I want to enumerate the available USB devices.  All I really
>need is the serial number of the USB devices available to PySerial.
>...
>(When you plug in a USB device on Windows, it's assigned the next
>available COM port number.  On a reboot, the numbers are reassigned.
>So if you have multiple USB serial ports, there's a problem.)

You can use the SetupDi APIs to enumerate the list of USB devices, but that
won't tell you what COM port they were assigned to.

You can look at the source code for USBView, which is available in the
Windows driver kit.  It can enumerate the hubs and ports and even fetch
their descriptors (by talking to the USB hub and host controller drivers),
but again it won't tell you what COM port was assigned.

>PyUSB can supposedly do this, but the documentation is misleading.
>It makes a big point of being "100% Python", but that's because it's
>just glue code to a platform-specific "back end" provided by someone
>else.

Of course it is.  You can't access devices in Windows without a kernel
driver.

>There's an old Windows back-end at 
>"http://www.craftedge.com/products/libusb.html";, but it was written for 
>Windows XP, and can supposedly be run in "compatibility mode" on Windows 
>Vista. Current versions of Windows, who knows? It's not open source, and 
>it comes from someone who sells paper-cutting machines for crafters.

It IS open source.  They are shipping libusb-win32 -- exactly the same
library you reference below.  Until Microsoft released WinUSB, libusb-win32
was the ONLY generic USB driver available on Windows.  It runs just fine on
Windows 7.

>There's another Windows back end at
>   https://sourceforge.net/apps/trac/libusb-win32/wiki
>but it involves installing a low-level driver in Windows.

It's the same backend.  A driver is required in order to access devices on
Windows.  It's required on Linux as well, but Linux happens to include a
generic USB driver in the kernel.

A more modern generic USB driver and library is available at
http://www.libusb.org.  There is a Python binding for it.

>I especially like the instruction "Close all applications which use USB 
>devices before installing."  Does this include the keyboard and mouse?

No, that's just being overly cautious.  Libusb-Win32 can act as a filter
driver, inserting itself into an existing USB stack, but to do so the
device stack you are filtering must be idle.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Will MySQL ever be supported for Python 3.x?

2012-03-31 Thread Tim Roberts
John Nagle  wrote:

>On 3/30/2012 2:32 PM, Irmen de Jong wrote:
>> Try Oursql instead  http://packages.python.org/oursql/
>> "oursql is a new set of MySQL bindings for python 2.4+, including python 3.x"
>
>Not even close to being compatible with existing code.   Every SQL
>statement has to be rewritten, with the parameters expressed
>differently.  It's a good approach, but very incompatible.

Those changes can be automated, given an adequate editor.  "Oursql" is a
far better product than the primitive MySQLdb wrapper.  It is worth the
trouble.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Gotcha's?

2012-04-07 Thread Tim Roberts
Roy Smith  wrote:
>
>There's absolutely no reason why JSON should follow Python syntax rules. 

No, but there certainly is a justification for expecting JAVASCRIPT Object
Notation (which is, after all, what JSON stands for) to follow Javascript's
syntax rules.  And Javascript happens to follow the same quoting rules as
Python.

Now, I fully understand that it is the way it is.  I'm merely pointing out
that his was not an unreasonable expectation.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f python?

2012-04-11 Thread Tim Roberts
"WJ"  wrote:
>
>Slashes can work under windows, up to a point:

ALL Windows APIs accept forward slashes.  The only place they are not
accepted is command line commands that take options which can begin with
forward slash.

>Also, most languages I use under windows allow you to use
>slashes in paths:

All of them should do so.  They're just string being passed to CreateFile,
and CreateFile accepts forward slashes just fine.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: functions which take functions

2012-04-11 Thread Tim Roberts
Kiuhnm  wrote:
>
>That won't do. A good example is when you pass a function to re.sub, for 
>instance.

This is an odd request.

I often pass functions to functions in order to simulate a C switch
statement, such as in a language translator:

  commands = {
'add': doAdd,
'subtract' : doSubtract,
'multiply' : doMultiply,
'divide' : doDivide
  }

  nextCommand = parseCommandLine( line )
  invokeCommand( commands[NextCommand] )
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv: No fields, or one field?

2012-04-25 Thread Tim Roberts
Neil Cerutti  wrote:

>Is there an explanation or previous dicussion somewhere for the
>following behavior? I haven't yet trolled the csv mailing list
>archive, though that would probably be a good place to check.
>
>Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
>(Intel)] on win 32
>Type "help", "copyright", "credits" or "license" for more information.
>>>> import csv
>>>> next(csv.reader(['""\r\n']))
>['']
>>>> next(csv.reader(['\r\n']))
>[]
>
>I hoped or assumed that the 2nd invocation should have the same
>result as the first.

Really?  That's not at all what I would have expected.  The first line
contains one field.  The second line contains 0 fields.  It's consistent,
and syntactically valid.

>I admit a blank, one-field csv record just isn't very
>insteresting, but isn't this a special case that ought to be
>documented? 

But that's what you have in the first line, and the reader has returned to
you a list containing one (empty) string.

I just don't see your interpretation.  The results are exactly what I would
have expected.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTML Code - Line Number

2012-04-27 Thread Tim Roberts
smac2...@comcast.net wrote:
>
>For scrapping purposes, I am having a bit of trouble writing a block
>of code to define, and find, the relative position (line number) of a
>string of HTML code. I can pull out one string that I want, and then
>there is always a line of code, directly beneath the one I can pull
>out, that begins with the following:
>
>
>However, because this string of HTML code above is not unique to just
>the information I need (which I cannot currently pull out), I was
>hoping there is a way to effectively say "if you find the html string
>_ in the line of HTML code above, and the string valign="top" class="body_cols_middle"> in the line immediately
>following, then pull everything that follows this second string.

Regular expression-based screen scraping is extremely delicate.  All it
takes is one tweak to the HTML, and your scraping fails although the page
continues to look the same.

A much better plan is to use sgmllib to write yourself a mini HTML parser.
You can handle "td" tags with the attributes you want, and count down until
you get to the "td" tag you want.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: %d not working in re at Python 2.7?

2012-05-15 Thread Tim Roberts
vacu  wrote:
>
>I am frustrated to see %d not working in my Python 2.7 re.search, like
>this example:
>
>>>> (re.search('%d', "asdfdsf78asdfdf")).group(0)
>Traceback (most recent call last):
>  File "", line 1, in 
>AttributeError: 'NoneType' object has no attribute 'group'
>
>\d works fine:
>
>>>> (re.search('\d+', "asdfdsf78asdfdf")).group(0)
>'78'
>
>And google search ignores % in their search, so I failed to find
>answer from Python mailing list or web,
>Do you have any idea what's problem here?

Yes.  %d has never worked.  \d+ is the right answer.  It's just that
simple.  Where did you read that %d should work?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function declarations ?

2011-06-12 Thread Tim Roberts
Andre Majorel  wrote:
>
>Anyway, it seems the Python way to declare a function is
>
>  def f ():
>pass

No, that DEFINES a function.  There is no way to declare a function in
Python.  It isn't done, because it isn't necessary.

That code doesn't do what you think it does.  Example:

def f():
pass

g = f

def f():
return 3

print g()

That prints "none".  That module has two definitions of f, not one.  The
meaning of the name "f" changes partway through the module.

Python is not C.  You need to use Python habits, not C habits.  What
construct led you to think you need to declare a function like that?  This
code, for example, works fine:

def g():
return f()
def f():
return 3
print g()

The name "f" does not have to be defined until the function "g" is actually
executed.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keyboard Layout: Dvorak vs Colemak: is it Worthwhile to Improve the Dvorak Layout?

2011-06-12 Thread Tim Roberts
Xah Lee  wrote:
>
>(a lil weekend distraction from comp lang!)
>
>in recent years, there came this Colemak layout. The guy who created
>it, Colemak, has a site, and aggressively market his layout. It's in
>linuxes distro by default, and has become somewhat popular.
>...
>If your typing doesn't come anywhere close to a data-entry clerk, then
>any layout “more efficient” than Dvorak is practically meaningless.

More than that, any layout "more efficient" than QWERTY is practically
meaningless.  The whole "intentional inefficiency" thing in the design of
the QWERTY layout is an urban legend.  Once your fingers have the mapping
memorized, the actual order is irrelevent.  Studies have shown that even a
strictly alphabetical layout works perfectly well, once the typist is
acclimated.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keyboard Layout: Dvorak vs Colemak: is it Worthwhile to Improve the Dvorak Layout?

2011-06-15 Thread Tim Roberts
Dennis Lee Bieber  wrote:
>
>On Sun, 12 Jun 2011 21:30:43 -0700, Tim Roberts 
>declaimed the following in gmane.comp.python.general:
>
>> More than that, any layout "more efficient" than QWERTY is practically
>> meaningless.  The whole "intentional inefficiency" thing in the design of
>> the QWERTY layout is an urban legend.
>
>   Oh, there was an "inefficiency" in QWERTY -- but it only applies to
>fully manual typewriters, in which some of the more common letters were
>placed under the weakest fingers -- to slow down key strokes enough to
>reduce jamming multiple type blocks 

That's what I was referring to.  That's a very common belief, but it's
nonsense.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run Python script from JS

2011-06-16 Thread Tim Roberts
Gnarlodious  wrote:
>
>Is there any way to call a Py script from Javascript in a webpage?

It is POSSIBLE to install Python as an active language, so that Internet
Explorer lets you write 

Re: Run Python script from JS

2011-06-17 Thread Tim Roberts
Hansmeet Singh wrote:
> for xhtml wouldnt the syntax be 

Re: Strategy to Verify Python Program is POST'ing to a web server.

2011-06-18 Thread Tim Roberts
"mzagu...@gmail.com"  wrote:
>
>For example, if I create a website that tracks some sort of
>statistical information and don't ensure that my program is the one
>that is uploading it, the statistics can be thrown off by people
>entering false POST data onto the data upload page.  Any remedy?

The amount of protection you need to take depends on what the cost of
interference will be, and how likely it is to be spoofed.  How will people
find out about your interface?  If they found out about it, what would they
gain by spoofing it?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parse date string having "EDT"

2011-06-20 Thread Tim Roberts
Junaid P V  wrote:
>
>I was trying to parse a date string containing "EDT" time zone
>
>eg: 'Mon Jun 20 14:00:57 EDT 2011'
>
>I tried:
>
>datetime.strptime('Mon Jun 20 14:00:57 EDT 2011', '%a %b %d %H:%M:%S %Z %Y')
>
>But I get error

Right, because strptime doesn't support %Z.  You'll have to handle that
yourself and remove it before conversion.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parse date string having "EDT"

2011-06-22 Thread Tim Roberts
Ben Finney  wrote:

>Tim Roberts  writes:
>
>> Right, because strptime doesn't support %Z.
>
>Au contraire:
>
>Support for the %Z directive is based on the values contained in
>tzname and whether daylight is true. Because of this, it is
>platform-specific except for recognizing UTC and GMT which are
>always known (and are considered to be non-daylight savings timezones).

I do keep forgetting that Python's strptime does not just pass through to
the C library.  C's strptime does not support %Z.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I speed up a script that iterates over a large range (600 billion)?

2011-06-22 Thread Tim Roberts
Mel  wrote:
>
>It certainly can be done faster.  I ran it against the factor finder that I 
>wrote, and it popped up the answer
>
>mwilson@tecumseth:~$ bin/factors.py 600851475143
>71 839 1471 ...
>
>before I could glance at my watch.  factors.py works, as does yours, by 
>testing for small factors first, but it divides them out as it goes, so it 
>tends to do its work on smallish numbers.  And since the smallest factors 
>are taken out as soon as possible, they have to be the prime ones.

That's a great hint, and I'm not sure it would have occurred to me on my
own.  Using your hint, I was able to write a 16-line script that also
produced a result instantaneously.  Very satisfying.

I'm going to save that one...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: poll of filesystem

2011-07-02 Thread Tim Roberts
Belisko Marek  wrote:
>
>just want to use poll method to get data from /proc file system. Use
>simple code for it. Problem is it seems poll return POLLIN flag but
>when I try to read data it's always empty. Could be a problem changes
>are so fast that print can't print it?

Poll doesn't make sense here.  The data in /proc/loadavg data is not text
data that gets updated periodically.  There is no file on disk somewhere
called /proc/loadavg.  Instead, reading /proc/loadavg causes a call into a
kernel driver, and reads data directly from variables stored in the kernel.
The data is ALWAYS available.

If you want the data once a second, just do it the easy way:

import time
while True:
print open('/proc/loadavg').read()
time.sleep(1)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Serial & reset of the device

2011-07-08 Thread Tim Roberts
yorick  wrote:
>
>I'm trying to access a hardware board of my company through a serial
>connection using a Python script and the pyserial module.
>
>I use Python 2.7.1 with Ubuntu 11.04 (pyserial is the package python-
>serial with version 2.5.2, http://pyserial.sourceforge.net/pyserial_api.html).
>
>The board to which I'm trying to connect works correctly with serial
>as some other guys did some TCL scripts to manage it.
>My problem is that every time I open a new connection, the device is
>reset. I'd like to not have the device reset.

I'm not sure what that means.  The RS-232 standard does not have the
concept of "reset".  What is it that triggers a device reset?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes: point to buffer in structure

2011-07-10 Thread Tim Roberts
Jesse R  wrote:
>
>Hey I've been trying to convert this to run through ctypes and i'm
>having a hard time
>
>typedef struct _SYSTEM_PROCESS_ID_INFORMATION
>{
>HANDLE ProcessId;
>UNICODE_STRING ImageName;
>} SYSTEM_PROCESS_IMAGE_NAME_INFORMATION,
>*PSYSTEM_PROCESS_IMAGE_NAME_INFORMATION;
>
>to
>
>class SYSTEM_PROCESS_ID_INFORMATION(ctypes.Structure):
>_fields_ = [('pid', ctypes.c_ulong),
>('imageName', ctypes.c_wchar_p)]
>...
>does anyone know how to get this working?

UNICODE_STRING is not just a pointer to wide characters.  It is itself a
structure:

typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR  Buffer;
} UNICODE_STRING;

So, I think you want fields of ctypes.c_ulong, ctypes.c_ushort,
ctypes.c_ushort, and ctypes.c_wchar_p.  MaximumLength gives the allocated
size of the buffer.  Length gives the length of the string currently held
in the buffer.  It can be less than the maximum length, and the buffer does
NOT necessarily contain a zero-terminator.

UNICODE_STRING and ANSI_STRING are used in kernel programming to avoid the
potential ambiguities of counted strings.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-16 Thread Tim Roberts
rantingrick  wrote:
>
>As we all know python allows us to use either tabs or spaces but NEVER
>both in the same source file.

That's not true.  Python allows tabs and spaces to be used in the same
source file, and even in the same source line.

I'm not saying it's wise, but it certainly allowed.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-18 Thread Tim Roberts
Andrew Berg  wrote:
>
>> I'm not saying it's wise
>
>Why not?

It just makes it more difficult to follow the pattern when you add new
code.  If you have an editor mnaging that for you, then you might as well
have the editor go all tabs or all spaces to avoid trouble.

Vi and friends with ts=8 and sw=4 will use 4 spaces, then tab, then tab
plus 4 spaces, then two tabs, etc.  That's recognizable, but I still
convert such a file to all spaces when I find one.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am fed up with Python GUI toolkits...

2011-07-22 Thread Tim Roberts
Gregory Ewing  wrote:

>sturlamolden wrote:
>
>> Or should modern deskop apps be written with something completely
>> different, such as HTML5?
>
>I hope not! HTML is great for web pages, but not
>everything should be a web page.

I don't think your glibness is justified.  There is a legitimate appeal to
this notion.  The fact is that MANY APIs can be completely and adequately
described by HTML.  It provides a very natural separation of presentation
and behavior.  Without style sheets, you can describe simple APIs very
compactly and let the renderer do positioning.  With style sheets, you can
get very complete control over the look and feel.

This is very similar to what Microsoft has done with Windows Presentation
Foundation, except that they are using a more sophisticated XML DTD.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am fed up with Python GUI toolkits...

2011-07-24 Thread Tim Roberts
Gregory Ewing  wrote:

>Tim Roberts wrote:
>> 
>> I don't think your glibness is justified.  There is a legitimate appeal to
>> this notion.  The fact is that MANY APIs can be completely and adequately
>> described by HTML.
>
>My brain raises a TypeError on that statement. According to
>my understanding of the world, describing APIs is not something
>that HTML does. (Or did you mean GUI rather than API?)

Yes, you are correct.  Brain fart on my part.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to separate a list into two lists?

2011-08-06 Thread Tim Roberts
smith jack  wrote:
>
>if a list L is composed with tuple consists of two elements, that is
>L = [(a1, b1), (a2, b2) ... (an, bn)]
>
>is there any simple way to divide this list into two separate lists , such that
>L1 = [a1, a2... an]
>L2=[b1,b2 ... bn]
>
>i do not want to use loop, any methods to make this done?

There will always be a loop.  It might not be written with a "for"
statement, but there will always be a loop.

  L1 = [k[0] for k in L]
  L2 = [k[1] for k in L]

I did momentarily consider the following slimy solution:
  L1 = dict(L).keys()
  L2 = dict(L).values()
but that reorders the tuples.  They still correspond, but in a different
order.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing timing issue

2011-08-10 Thread Tim Roberts
Tim Arnold  wrote:
>
>The task:
>I have a bunch of chapters that I want to gather data on individually 
>and then update a report database with the results.
>I'm using multiprocessing to do the data-gathering simultaneously.
>
>Each chapter report gets put on a Queue in their separate processes. 
>Then each report gets picked off the queue and the report database is 
>updated with the results.
>
>My problem is that sometimes the Queue is empty and I guess it's
>because the get_data() method takes a lot of time.
>
>I've used multiprocessing before, but never with a Queue like this.
>Any notes or suggestions are very welcome.

The obvious implication is that your timeout is simply not long enough for
your common cases.  If you know how many chapters to expect, why have a
timeout at all?  Why not just wait forever?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-14 Thread Tim Roberts
Steven D'Aprano  wrote:
>
>The only exception I can think of is *very* early Fortran, and that rightly
>is considered a mistake. Fortran 77 used to treat whitespace as always
>optional, so that in Python terms this:
>
>forxinrange(42)
>
>would be parsed as this:
>
>for x in range(42)

Absolutely true, and that led to one of the more famous computing screw-ups
in the early space program.  The author intended to write this:
  DO 10 I=1,8
which, in Fortran, begins a loop that will run 8 times ending at the
statement labeled "10".  In this case, the author mistakenly typed a period
instead of a comma:
  DO 10 I=1.8

That, unfortunately, is a perfectly valid statement that assigns the value
"1.8" to the floating point variable "DO10I", supposedly resulting in the
loss of an unmanned launch vehicle...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-16 Thread Tim Roberts
John Doe  wrote:

>def wait_for_keystroke():
>  char=0
>  while not (char==chr(27) or char==chr(110)):
>char=msvcrt.getch()
>if char==0:
>  return
>
>That freezes the process.

That exact code works perfectly for me.  The function returns as soon as I
press the escape key.  You are running this from a console process, and not
a GUI process, right?

>That means char=msvcrt.getch() is getting something?

Did you ever think about inserting a debug statement to help you?
    print hex(ord(char))
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string to unicode

2011-08-16 Thread Tim Roberts
Artie Ziff  wrote:
>
>if I am using the standard csv library to read contents of a csv file 
>which contains Unicode strings (short example: 
>'\xe8\x9f\x92\xe8\x9b\x87'),

You need to be rather precise when talking about this.  That's not a
"Unicode string" in Python terms.  It's an 8-bit string.  It might be UTF-8
encoding.  If so, it maps to two Unicode code points, U+87D2 and U+86C7,
which are both CJK ideograms.  Is that what you expected?

  C:\Dev\videology\sw\viewer>python
  Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit
(Intel)] on win32
  Type "help", "copyright", "credits" or "license" for more information.
  >>> x = '\xe8\x9f\x92\xe8\x9b\x87'
  >>> x.decode('utf8')
  u'\u87d2\u86c7'
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idea for pure-python templates using AST.

2011-08-16 Thread Tim Roberts
"Paul Wray"  wrote:
>
>Ive had what I think is a great idea for pure-python templates (I can almost 
>hear the groans, bear with me...)
>...
>The idea:
>Python syntax allows a statement to be a bare literal or identifier. These 
>have no effect on the program.
>...
>So is this (within the appropriate class context of course):
>
>def body(self, r):
>''; self.heading; ''
>''
>for itm in self.items:
>''; itm; ''
>''

This is essentially how the original CherryPy version 1 web framework
worked.In the end, I think it was decided that this represented too
much of a mix of processing and presentation, and CherryPy 2 and 3 use a
different scheme.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why i cannot import djang?

2011-08-16 Thread Tim Roberts
smith jack  wrote:
>
>this package is already in the site-packages directory, but i cannot
>import it , it's really confusing ...

The package is called "django".  The name you put in the subject line is
wrong.  Does your code use the right spelling?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wait for a keypress before continuing?

2011-08-21 Thread Tim Roberts
John Doe  wrote:
>
>Tim Roberts  wrote: 
>
>> That exact code works perfectly for me.  The function returns as
>> soon as I press the escape key.  You are running this from a
>> console process, and not a GUI process, right? 
>
>No. I am running this from within Windows, all sorts of Windows. 
>
>So... Does that mean I will need something complex like a keyboard
>hook? Or what? 

I see that this conversation took a nasty turn while I was on vacation.

msvcrt.getch works with consoles.  If you have an application where stdin
and stdout are connected to a real, live console window (which looks just
like a command line window), then msvcrt.getch will work.  If not, then you
have to use the Windows APIs.  GetKeyboardState and GetKeyState can tell
you if a specific key is currently being pressed.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why PyImport_ExecCodeModule takes char*?

2011-08-28 Thread Tim Roberts
Mateusz Loskot  wrote:
>
>I'm wondering, why PyImport_ExecCodeModule function takes char*
>instead of const char*?

My guess is "history".
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help parsing a text file

2011-08-30 Thread Tim Roberts
William Gill  wrote:
>
>My initial passes into Python have been very unfocused (a scatter gun of 
>too many possible directions, yielding very messy results), so I'm 
>asking for some suggestions, or algorithms (possibly even examples)that 
>may help me focus.
>
>I'm not asking anyone to write my code, just to nudge me toward a more 
>disciplined approach to a common task, and I promise to put in the 
>effort to understand the underlying fundamentals.

Python includes "sgmllib", which was designed to parse SGML-based files,
including both neat XML and slimy HTML, and "htmllib", which derives from
it.  I have used "htmllib" to parse HTML files where the tags were not
properly closed.  Perhaps you could start from "htmllib" and modify it to
handle the quirks in your particular format.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to print a module?

2011-09-05 Thread Tim Roberts
Martin De Kauwe  wrote:
>
>If I wanted to print an entire module, skipping the attributes
>starting with "__" is there an *optimal* way? 

Your question is somewhat ambiguous.  When I read "print an entire module",
I assumed you were asking for a way to print the source code, perhaps with
syntax coloring.

Surely there is no reason to have an "optimal" method of doing this -- this
is never going to be in an inner loop.  If you have a method that works,
there is little justification to optimize...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython SQLite and Reportlab demo

2011-02-24 Thread Tim Roberts
Beppe  wrote:
>
>I would recommend this my little work on sourceforge.
>
> http://sourceforge.net/projects/pyggybank/
>
>you can download an exe (pyggy_w32.7z)  make with py2exe
>and the source  (pyggy_source.7z)
>the project is named Pyggy Bank.

Nowhere, in either this announcement or your sourceforge.net page, do you
say a single word about what this application actually is. 

Just a few sentences describing what the application does would go a long
way toward stirring up interest in this app.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestion Reqd for Designing a Website in Python

2011-02-24 Thread Tim Roberts
joy99  wrote:
>
>Dear Group,
>I have developed one big Machine Learning software a Machine
>Translation system in Python.
>Now, I am thinking to make a User Interface of it and upload it in a
>web site.

Do you mean you want people to download this from a web site as an
executable, and then run it locally on their computers?  Or do you mean you
want people to use this as a web site, using their web browsers?  The
answers are very different.

>My questions are:
>(i) For Designing an interface I am choosing Tkinter. Is it fine?
>(ii) How to connect this interface with my Tkinter based interface -
>should I have to recode the whole system?
>(iii) After designing I want to upload now how to do the server side
>scripting?

Question (i) implies that you want the first option (download an executable
and run it).  Question (iii) implies the second (that you want your app to
run on a web server so people use it through your browser).  Please
clarify.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dijkstra Algorithm Help

2011-03-09 Thread Tim Roberts
yoro  wrote:
>
>Thanks for replying, maybe i'm misunderstanding your comment -

Yes, it was not clear at first glance that you are calling
populateNodeTable twice.  You call it once and throw away the result, then
you call it again and pass the result to tentativeDistance.  That's
probably not what you meant to do.

But look at the code within populateNodeTable.  You read the list from your
file, chop it into pieces at the commas, convert them to integers, and then
store them into a variable that you never use.  You never use the contents
of your file in this code.

>nodeTable is used to store the distances from source of each node
>within a text file, the file having the format :
>
>1,2,3,4,5,6,7,8,9
>1,2,3,4,5,6,7,8,9
>
>Each of these nodes will have the same settings as set out in Class
>Node, i.e. all having no previous nodes. I am then trying to pass this
>parameter to the next function so that the distance from the start
>node can be calculated

How do those numbers say anything about the distances between nodes?
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How should I handle socket receiving?

2011-03-12 Thread Tim Roberts
Hans  wrote:
>
>I'm thinking to write a code which to:
>1. establish tons of udp/tcp connections to a server

What does "tons" mean?  Tens?  Hundreds?

>my question is how should I handle receiving traffic from each
>connection respectively? 

You're really going to want to use "select".  You can store the objects in
a dictionary where the key is the socket number.  That way, you can use the
result of the select and get your network object directly.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python script to find Installed programs in Uninstall folder in registry

2011-03-14 Thread Tim Roberts
KishoreRP  wrote:
>
>I am working on creating a python script to find Installed programs in
>Uninstall folder in registry, the script works perfectly fine on 32
>bit machines but errors out with a wmi error on 64 bit machines. Am
>not able to get hold of a wmi module for python on 64 bit machines.

There shouldn't be any difference.  What error do you get, exactly?

Also, let me point out that you can access the registry in a couple of
ways, without invoking the overhead of WMI.  I grant you that they are a
bit wordier, but it might get you around this issue.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call php function from python

2011-04-01 Thread Tim Roberts
CrabbyPete  wrote:
>
>I have a python script that automatically loads wordpress, up to the
>point that it asks for the admin password.
>that is a php function call
>
>function wp_install( $blog_title, $user_name, $user_email, $public,
>$deprecated = '', $user_password = '' )
>
>Is there a way to call this function from python?

Are you running this script on the web server, or are you invoking this
over a socket using something like urllib?

If you are running remotely, then PHP does not exist.  All you have are
HTTP requests.  You need to make yourself look exactly like a human being
at a browser.  Fortunately, that's not too hard.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List comprehension vs filter()

2011-04-20 Thread Tim Roberts
Chris Angelico  wrote:

>On Wed, Apr 20, 2011 at 1:45 PM, Chris Rebert  wrote:
>> Built-ins aren't quite the same as globals, but essentially yes:
>
>Sure. That might explain some of the weirdness, but it doesn't explain
>why things were still weird with the variable named posttype. 

It's because, unlike some other languages (like Pascal), Python doesn't
have infinitely recursive nested namespaces.  Glossing over details, there
is a global namespace, and there is a local namespace.  A new function gets
a new local namespace.  "posttype" is part of the local namespace of the
outer function, but it's not part of the local namespace of the lambda.

You can solve this through the common lamba idiom of a closure:

lst=filter(lambda x,posttype=posttype: x["type"].lower()==posttype,lst)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-04 Thread Tim Roberts
harrismh777  wrote:
>
>If I call a function in C, and pass-by-value, the data's 'value' is 
>placed on the stack in a stack-frame, as a 'value' parm... its a copy of 
>the actual data in memory.
>
>If I call a function in C, and pass-by-reference, the data's 'address' 
>is placed on the stack in a stack-frame, as a 'reference' parm... no 
>data is copied and the function must de-reference the pointer to get to 
>the data   this is by definition.

This is not correct.  Consider an example.

  int BumpMe( int * a )
  {
  return *a+3;
  }

  int Other()
  {
  int x = 9;
  return BumpMe( &x );
  }

That is not an instance of passing an "int" by reference.  That is an
instance of passing an "int *" by value.  The fact that the parameter "a"
in BumpMe happens to be an address is completely irrelevent to the
definition of the parameter passing mechanism.

C has pass-by-value, exclusively.  End of story.

>There may be some language somewhere that does pass-by-reference which 
>is not implemented under the hood as pointers, but I can't think of 
>any... 

Fortran had genuine pass-by-reference.  In Fortran, you could write a
program like this:

   SUBROUTINE CONFUSION(IVALUE)
   INTEGER IVALUE
   IVALUE = IVALUE + 1
   END

   PROGRAM MAIN
   CONFUSION(4)
   END

That program would actually modify the value of the constant 4.  Such an
abomination is simply not possible in C.  Is that implemented
under-the-hood with pointers/addresses?  Of course it is.  However, that
does not change the parameter passing model as defined by the language
specification.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >