Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Chris Angelico
On Tue, Dec 11, 2012 at 4:34 PM, Michael Torrie  wrote:
> I use a module I got from pypi called dateutil.  It has a nice submodule
> called parser that can handle a variety of date formats with good
> accuracy.  Not sure how it works, but it handles all the common American
> date formats I've thrown at it.

That sort of statement will get you either amusement or ire, depending
on the respondent. From me, amusement, because there are enough
"common American date formats" for you to feel you've done a thorough
test.

There are a LOT more date formats than those used in the USA. The most
obvious trio is American MDY, European DMY, Japanese YMD, but there
are plenty more to deal with. Have fun.

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Steven D'Aprano
On Mon, 10 Dec 2012 22:48:50 -0500, Dave Cinege wrote:

> Thesaurus: A different way to call a dictionary.

Is this intended as a ready-for-production class?


> Thesaurus is a new a dictionary subclass which allows calling keys as if
> they are class attributes and will search through nested objects
> recursively when __getitem__ is called.


If only that were true...

py> d = Thesaurus()
py> d['spam'] = {}
py> d['spam']['ham'] = 'cheese'  # key access works
py> d.spam.ham  # but attribute access doesn't
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'dict' object has no attribute 'ham'



> You will notice that the code is disgusting simple. However I have found
> that this has completely changed the way I program in python.

By making it less robust and more prone to errors?


py> d = Thesaurus()
py> d.copy = "some value"
py> assert d.copy == "some value"
Traceback (most recent call last):
  File "", line 1, in 
AssertionError


Operations which silently fail or do the wrong thing are not a good 
thing. Scarily, this isn't even consistent:

py> "%(copy)s" % d
'some access'
py> d.copy




Some further comments about your code:


> class Thesaurus (dict):
>   [...]
>   def __getitem__(self, key):
>   if '.' not in key:
>   return dict.__getitem__(self, key)
>   l = key.split('.')
>   if isinstance(l[0], (dict, Thesaurus)):
>   a = self.data

Testing for isinstance (dict, Thesaurus) is redundant, since Thesaurus is 
a subclass of dict.

More importantly, there are no circumstances where l[0] will be a dict. 
Since l is created by splitting a string, l[0] must be a string and this 
clause is dead code.

Which is good, because self.data is not defined anywhere, so if you ever 
did reach this branch, your code would fail.


>   else:
>   a = self
>   for i in range(len(l)): # Walk keys recursivly


This is usually better written as:

for subkey in l:
# look up subkey
# or if all else fails
raise KeyError(subkey)


KeyError('spam.ham.cheese [1]') is misleading, since it implies to me 
that looking up spam.ham.cheese succeeded, and the failed lookup was on 
1. I would expect either of these:

KeyError('spam.ham')
KeyErroor('ham')

with a slight preference for the first.

Further issues with your code:

>   try:
>   a = a[l[i]] # Attempt key
>   except:


Bare excepts like this are not good. At best they are lazy and sloppy, 
good only for throw-away code. At worst, they are hide bugs. In this 
case, they can hide bugs:


py> class X(object):
... @property
... def test(self):
... return 1/0  # oops a bug
... 
py> d = Thesaurus(a=X())
py> d.a.test  # Gives the correct exception for the error.
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in test
ZeroDivisionError: float division
py>
py> "%(a.test)s" % d  # Lies about the problem.
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 29, in __getitem__
KeyError: 'a.test [1]'



One more comment:


> # I like to create a master global object called 'g'.
> # No more 'global' statements for me.
> g = thes()

This is not a good thing. Encouraging the use of globals is a bad thing.



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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Michael Torrie
On 12/11/2012 01:08 AM, Chris Angelico wrote:
> There are a LOT more date formats than those used in the USA. The most
> obvious trio is American MDY, European DMY, Japanese YMD, but there
> are plenty more to deal with. Have fun.

For the record I didn't write the module, so I don't care whether or not
I have fun or not.  The module is simply there, and I've found it quite
useful for parsing free-form dates as arguments passed to my program.
While what you say is correct--and the parser can be given hints about
what order to expect numeric dates--if you read the OP's question, he
really is mainly looking for a flexible date parser that can handle /
instead of - as a separator.  And going by his example, the order is the
same, so if he can parse one he can parse the other.  This is exactly
the kind of thing the dateutil.parser module works for.  That's why I
suggested it.  Sure he needs to always be aware of the order, but I have
to assume that since his strptime had a specific order, he has a reason
for assuming that order.  If he wasn't he is now, of course.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Michael Torrie
On 12/11/2012 01:08 AM, Chris Angelico wrote:
> That sort of statement will get you either amusement or ire, depending
> on the respondent. From me, amusement, because there are enough
> "common American date formats" for you to feel you've done a thorough
> test.

Also what I meant was common "english language" formats.  Such as:

1 Apr 2013
April 1, 2013
Apr 1
Apr 2013
1st of April, 2013
April of 2013
5pm on August 3

http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c

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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Chris Angelico
n Tue, Dec 11, 2012 at 7:25 PM, Michael Torrie  wrote:
> On 12/11/2012 01:08 AM, Chris Angelico wrote:
>> That sort of statement will get you either amusement or ire, depending
>> on the respondent. From me, amusement, because there are enough
>> "common American date formats" for you to feel you've done a thorough
>> test.
>
> Also what I meant was common "english language" formats.  Such as:
>
> 1 Apr 2013
> April 1, 2013
> Apr 1
> Apr 2013
> 1st of April, 2013
> April of 2013
> 5pm on August 3

Ah! Okay. So, more general than just "different delimiters and such
that you'd find in the USA". Still, it did come across as rather
amusing, worded the way you had it.

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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Greg Donald
On Mon, Dec 10, 2012 at 10:34:31PM -0700, Michael Torrie wrote:
> I use a module I got from pypi called dateutil.  It has a nice submodule
> called parser that can handle a variety of date formats with good
> accuracy.  Not sure how it works, but it handles all the common American
> date formats I've thrown at it.

from dateutil.parser import parse
dt = parse( whatever )

I've throw all kind of date and timestamps at it.. have yet to see anything it 
won't parse.


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


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-11 Thread Paul Kölle

Hi,

Am 10.12.2012 20:13, schrieb bitbucket:

I have an existing Windows application which provides an OLE
Automation (IDispatch) interface.  I'm not able to change that
interface.  I'd like to call it from a scripting language.  I figure
this would provide a nice quick way to invoke on the app.

I initially tried this with Windows Powershell but ran into the
following problem.  I was able to create the object and invoke simple
methods on it.  However the interface for this app has methods which
take out params.  i.e. you pass in a reference to a variable and the
server fills in the value.  I couldn't get that to work.  I finally
gave up and decided it was just a limitation of Powershell, not being
able to work with those out params.


[snipp]
Before switching technologies I'd check if this solves your problem 
http://geekswithblogs.net/Lance/archive/2009/01/14/pass-by-reference-parameters-in-powershell.aspx 



TL;DR IMHO "out" parameters are basically pointers (pass by reference) 
and need to be passed like GetSettingValue("name", [ref]$value)...


cheers
 Paul

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


Re: MySQLdb insert HTML code error

2012-12-11 Thread Chris Angelico
On Tue, Dec 11, 2012 at 11:46 AM, Anatoli Hristov  wrote:
>> Brilliant, I think your problem is in line 97 of the code that you *HAVEN'T
>> QUOTED*.  Please go here, read and inwardly digest before you say anything
>> else http://www.sscce.org/
>
> :) I thought it was clear. the "spec" is the description and when the
> str"spec" contains the html code I'm getting an error, if you don't
> want to help then just don't become an..

SSCCE starts with "Short". The HTML you unloaded into that email
hardly qualifies.

When you're trying to figure out a problem that appears to happen only
when you have X and not when you have Y, see what the smallest example
data for X and Y are that continue to exhibit the difference. It's way
easier, especially on those of us who might have been interested in
helping, had it been possible to paste your failing code into IDLE.
Plus, in cutting it down you might discover what the real cause of the
problem is.

Of course, sometimes you fail to cut something down as expected. In
this example, HTML didn't turn out to be the problem, so cutting it
down to "" wouldn't have worked. But do at least _try_,
and then mention what worked and didn't work in your question.

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Jean-Michel Pichavant


- Original Message -
> Thesaurus: A different way to call a dictionary.
> 
> Thesaurus is a new a dictionary subclass which allows calling keys as
> if they are class attributes and will search through nested objects
> recursively when __getitem__ is called.
> 
> You will notice that the code is disgusting simple. However I have
> found that
> this has completely changed the way I program in python. I've
> re-written some
> exiting programs using Thesaurus, and often realized 15-30% code
> reduction.
> Additionally I find the new code much easier to read.
> 
> If you find yourself programing with nested dictionaries often,
> fighting to
> generate output or command lines for external programs, or wish you
> had
> a dictionary that could act (sort of) like a class, Thesaurus may be
> for you.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

did you know you can write

class TestClass:
no = 'Class'
way = 'this'


tc = TestClass()

print "Something you find clean, and I'm not sure why, this is way %(way)s and 
this is no %(no)s" % vars(tc).


JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: open URL in the current tab

2012-12-11 Thread Jabba Laci
Dear All,

If someone is interested, I've made a module out of it. Available here:

https://github.com/jabbalaci/jabbapylib/blob/master/jabbapylib/browser/firefox.py

It seems you can program your Firefox instance from your script as you
want through this add-on. I will explore the possibilities in the
future.

Best,

Laszlo

On Tue, Dec 11, 2012 at 1:16 AM, Chris Angelico  wrote:
> On Tue, Dec 11, 2012 at 11:05 AM, Jabba Laci  wrote:
>> Hi,
>>
>>> If this is for use on somebody else's system, *please don't*. My
>>
>> This is for me. I have a simple GUI that produces some URL that I want
>> to open in the current tab. Since I want to verify several URLs, I
>> don't want to open dozens of new tabs.
>>
>> Here is my working solution. It requires the MozRepl Firefox add-on
>> that I mentioned in the previous message.
>
> Looks good! Since it's your own single system, the add-on requirement
> isn't too onerous (but even if it's an all-mine system, I'd hesitate
> to deploy an add-on to more than a handful of computers).
>
> Specific problem, specific solution. I like it.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb insert HTML code error

2012-12-11 Thread Anatoli Hristov
> SSCCE starts with "Short". The HTML you unloaded into that email
> hardly qualifies.
>
> When you're trying to figure out a problem that appears to happen only
> when you have X and not when you have Y, see what the smallest example
> data for X and Y are that continue to exhibit the difference. It's way
> easier, especially on those of us who might have been interested in
> helping, had it been possible to paste your failing code into IDLE.
> Plus, in cutting it down you might discover what the real cause of the
> problem is.
>
> Of course, sometimes you fail to cut something down as expected. In
> this example, HTML didn't turn out to be the problem, so cutting it
> down to "" wouldn't have worked. But do at least _try_,
> and then mention what worked and didn't work in your question.

This is the reason  I posted in the beginning only the part with the
problem function.
-after I posted the all string (the HTML) as there was some miss
understandings:
-I will try to follow the (sscce) next time, excuse me as I'm a
beginner in coding at all.

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


Re: forking and avoiding zombies!

2012-12-11 Thread andrea crotti
Yes I wanted to avoid to do something too complex, anyway I'll just
comment it well and add a link to the original code..

But this is now failing to me:

def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)

# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid()

# Perform second fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)

# The process is now daemonized, redirect standard file descriptors.
sys.stdout.flush()
sys.stderr.flush()

si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == '__main__':
daemonize(stdout='sample_file', stderr='sample')
print("hello world, now should be the child!")


[andrea@andreacrotti experiments]$ python2 daemon.py
Traceback (most recent call last):
  File "daemon.py", line 49, in 
daemonize(stdout='sample_file', stderr='sample')
  File "daemon.py", line 41, in daemonize
so = file(stdout, 'a+')
IOError: [Errno 13] Permission denied: 'sample_file'

The parent process can write to that file easily, but the child can't,
why is it working for you and not for me though?
(Running this on Linux with a non-root user)
-- 
http://mail.python.org/mailman/listinfo/python-list


m2crypto load from memory to ctx.set_tmp_dh()

2012-12-11 Thread makeit . tsxtsx
o far I have not been able to load the diffie-hellman params on to 
ctx.set_tmp_dh(), the BIO class should help do that, but "my way" dont works, 
maybe I need to specify the smime ?

here's what I tried:

1)

dh_params="""
-BEGIN DH PARAMETERS-
MIGHAoGBAJyoxPGR3wxcp8Nf5C3w0Jh9tFk/4eRMuimJN8+d9myW/JMuZTHdRslE
b+wBIpMoEC2g9GLnWCgX+Xzu01kDABFO5JAdypVbdscXKyE0423/rxWic8LKy+EG
LGbc716lIxflajBn0uNy0xRDK7xcn9RECRamf7jPPGqMVYBtV+njAgEC
-END DH PARAMETERS-
"""
...

dhbio = M2Crypto.BIO.MemoryBuffer(dh_params)
ctx.set_tmp_dh(dhbio)
...
with dhbio = M2Crypto.BIO.MemoryBuffer(str(dh_params)) gives the same result:

Traceback (most recent call last):
  File "bconn.py", line 121, in 
main()
  File "bconn.py", line 88, in main
ctx.set_tmp_dh(dhbio)
  File "/usr/local/lib/python2.6/dist-packages/M2Crypto/SSL/Context.py", line 
190, in set_tmp_dh
f = BIO.openfile(dhpfile)
  File "/usr/local/lib/python2.6/dist-packages/M2Crypto/BIO.py", line 186, in 
openfile
return File(open(filename, mode))
TypeError: coercing to Unicode: need string or buffer, instance found

thx you ! (:
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread peter

On 12/11/2012 08:47 AM, andrea crotti wrote:

Yes I wanted to avoid to do something too complex, anyway I'll just
comment it well and add a link to the original code..

But this is now failing to me:

def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
 # Perform first fork.
 try:
 pid = os.fork()
 if pid > 0:
 sys.exit(0) # Exit first parent.
 except OSError as e:
 sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
 sys.exit(1)

 # Decouple from parent environment.
 os.chdir("/")
 os.umask(0)
 os.setsid()

 # Perform second fork.
 try:
 pid = os.fork()
 if pid > 0:
 sys.exit(0) # Exit second parent.
 except OSError, e:
 sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
 sys.exit(1)

 # The process is now daemonized, redirect standard file descriptors.
 sys.stdout.flush()
 sys.stderr.flush()

 si = file(stdin, 'r')
 so = file(stdout, 'a+')
 se = file(stderr, 'a+', 0)
 os.dup2(si.fileno(), sys.stdin.fileno())
 os.dup2(so.fileno(), sys.stdout.fileno())
 os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == '__main__':
 daemonize(stdout='sample_file', stderr='sample')
 print("hello world, now should be the child!")


[andrea@andreacrotti experiments]$ python2 daemon.py
Traceback (most recent call last):
   File "daemon.py", line 49, in 
 daemonize(stdout='sample_file', stderr='sample')
   File "daemon.py", line 41, in daemonize
 so = file(stdout, 'a+')
IOError: [Errno 13] Permission denied: 'sample_file'

The parent process can write to that file easily, but the child can't,
why is it working for you and not for me though?
(Running this on Linux with a non-root user)
In the time when you fork the proccess you can't use relative path, is 
dangerous. You need to use absolute path's like this.


import os, sys

def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)

# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid()

# Perform second fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)

# The process is now daemonized, redirect standard file descriptors.
sys.stdout.flush()
sys.stderr.flush()

si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == '__main__':
daemonize(stdout='/tmp/sample_file.log', stderr='/tmp/sample.log')
print("hello world, now should be the child!")
--
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread andrea crotti
Ah sure that makes sense!

But actually why do I need to move away from the current directory of
the parent process?
In my case it's actually useful to be in the same directory, so maybe
I can skip that part,
or otherwise I need another chdir after..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread peter

On 12/11/2012 10:25 AM, andrea crotti wrote:

Ah sure that makes sense!

But actually why do I need to move away from the current directory of
the parent process?
In my case it's actually useful to be in the same directory, so maybe
I can skip that part,
or otherwise I need another chdir after..
You don't need to move away from the current directory. You cant use os 
to get the current work directory


stderrfile = '%s/error.log' % os.getcwd()
stdoutfile = '%s/out.log' % os.getcwd()

then call the daemon function like this.

daemonize(stdout=stdoutfile, stderr=stderrfile)
--
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread andrea crotti
2012/12/11 peter :
> On 12/11/2012 10:25 AM, andrea crotti wrote:
>>
>> Ah sure that makes sense!
>>
>> But actually why do I need to move away from the current directory of
>> the parent process?
>> In my case it's actually useful to be in the same directory, so maybe
>> I can skip that part,
>> or otherwise I need another chdir after..
>
> You don't need to move away from the current directory. You cant use os to
> get the current work directory
>
> stderrfile = '%s/error.log' % os.getcwd()
> stdoutfile = '%s/out.log' % os.getcwd()
>
> then call the daemon function like this.
>
> daemonize(stdout=stdoutfile, stderr=stderrfile)


But the nice thing now is that all the forked processes log also on
stdout/stderr, so if I launch the parent in the shell I get

DEBUG -> csim_flow.worker[18447]: Moving the log file
/user/sim/tests/batch_pdump_records/running/2012_12_11_13_4_10.log to
/user/sim/tests/batch_pdump_records/processed/2012_12_11_13_4_10.log

DEBUG -> csim_flow.area_manager[19410]: No new logs found in
/user/sim/tests/batch_pdump_records

where in [] I have the PID of the process.
In this suggested way I should use some other files as standard output
and error, but for that I already have the logging module that logs
in the right place..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread Jean-Michel Pichavant
- Original Message -
> So I implemented a simple decorator to run a function in a forked
> process, as below.
> 
> It works well but the problem is that the childs end up as zombies on
> one machine, while strangely
> I can't reproduce the same on mine..
> 
> I know that this is not the perfect method to spawn a daemon, but I
> also wanted to keep the code
> as simple as possible since other people will maintain it..
> 
> What is the easiest solution to avoid the creation of zombies and
> maintain this functionality?
> thanks
> 
> 
> def on_forked_process(func):
> from os import fork
> """Decorator that forks the process, runs the function and gives
> back control to the main process
> """
> def _on_forked_process(*args, **kwargs):
> pid = fork()
> if pid == 0:
> func(*args, **kwargs)
> _exit(0)
> else:
> return pid
> 
> return _on_forked_process
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Ever though about using the 'multiprocessing' module? It's a slightly higher 
API and I don't have issues with zombie processes.
You can combine this with a multiprocess log listener so that all logs are sent 
to the main process.

See Vinay Sajip's code about multiprocessing and logging, 
http://plumberjack.blogspot.fr/2010/09/using-logging-with-multiprocessing.html

I still had to write some cleanup code before leaving the main process, but 
once terminate is called on all remaining subprocesses, I'm not left with 
zombie processes.
Here's the cleaning:

for proc in multiprocessing.active_children():
proc.terminate()

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with usbtmc-communication

2012-12-11 Thread wrw
On Dec 11, 2012, at 1:58 AM, Jean Dubois  wrote:

> On 10 dec, 16:34, w...@mac.com wrote:
>> On Dec 10, 2012, at 8:31 AM, Jean Dubois  wrote:
>> 
>> [byte]

>>> As you can see this approach suffers from the same "buffer problem" as
>>> the approach with readline did. One now good argue as a workaround:
>>> get rid of the first data pair and add an extra measure command for
>>> the missing data pair, however this still does not explain why this
>>> problem is there in Python and not in Octave and I also fear I'll get
>>> more trouble when sending combined commands e.g. such as that to
>>> create a staircase current
>>> So my question is, how to modify the Python-code such that the first
>>> data pair is indeed the first data pair
>> 
>>> thanks,
>>> jean
>> 
>>> Here follows the new code:
>>> #!/usr/bin/python
>>> import time
>>> import os
>>> import sys
>>> measurementcurr=''
>>> measurementvolt=''
>>> timesleepdefault=5
>>> print "Enter a numofchar (11 =>> numofchar = int(raw_input())
>>> filename ='mydata.txt'
>>> usbkeith = open('/dev/usbtmc1','r+')
>>> usbkeith.flush()
>>> usbkeith.write("*IDN?\n")
>> 
>> It seems like a real leap of faith to be opening /dev/usbtmc1 as though it 
>> were a file-oriented device.  I've never heard of ANY instrument interface 
>> implemented this way.
>> Where did you see example code that did that.
> I found examples in the usbtmc kernel driver documentation (the
> examples there are given in C):
> http://www.home.agilent.com/upload/cmc_upload/All/usbtmc.htm?&cc=BE&lc=dut
> 

OK - I see where the examples came from, and I notice -

int my_inst;
my_inst=open(“/dev/usbtmc1”,O_RDWR);
write(my_inst,”*RST\n”,5);
close(my_inst);

and similarly in another place -

retval=write(myfile,"*IDN?\n",6);

Note that both write commands contain a byte count of the number of characters 
to be written (\n counts as one character).
Again, the read commands contain byte counts.  I'm very suspicious that a write 
command with no byte count writes nothing, but does move a buffer pointer.

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


Re: forking and avoiding zombies!

2012-12-11 Thread andrea crotti
2012/12/11 Jean-Michel Pichavant :
> - Original Message -
>> So I implemented a simple decorator to run a function in a forked
>> process, as below.
>>
>> It works well but the problem is that the childs end up as zombies on
>> one machine, while strangely
>> I can't reproduce the same on mine..
>>
>> I know that this is not the perfect method to spawn a daemon, but I
>> also wanted to keep the code
>> as simple as possible since other people will maintain it..
>>
>> What is the easiest solution to avoid the creation of zombies and
>> maintain this functionality?
>> thanks
>>
>>
>> def on_forked_process(func):
>> from os import fork
>> """Decorator that forks the process, runs the function and gives
>> back control to the main process
>> """
>> def _on_forked_process(*args, **kwargs):
>> pid = fork()
>> if pid == 0:
>> func(*args, **kwargs)
>> _exit(0)
>> else:
>> return pid
>>
>> return _on_forked_process
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
> Ever though about using the 'multiprocessing' module? It's a slightly higher 
> API and I don't have issues with zombie processes.
> You can combine this with a multiprocess log listener so that all logs are 
> sent to the main process.
>
> See Vinay Sajip's code about multiprocessing and logging, 
> http://plumberjack.blogspot.fr/2010/09/using-logging-with-multiprocessing.html
>
> I still had to write some cleanup code before leaving the main process, but 
> once terminate is called on all remaining subprocesses, I'm not left with 
> zombie processes.
> Here's the cleaning:
>
> for proc in multiprocessing.active_children():
> proc.terminate()
>
> JM
>
>
> -- IMPORTANT NOTICE:
>
> The contents of this email and any attachments are confidential and may also 
> be privileged. If you are not the intended recipient, please notify the 
> sender immediately and do not disclose the contents to any other person, use 
> it for any purpose, or store or copy the information in any medium. Thank you.


Yes I thought about that but I want to be able to kill the parent
without killing the childs, because they can run for a long time..

Anyway I got something working now with this

def daemonize(func):

def _daemonize(*args, **kwargs):
# Perform first fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno,
e.strerror))
sys.exit(1)

# Decouple from parent environment.
# check if decoupling here makes sense in our case
# os.chdir("/")
# os.umask(0)
# os.setsid()

# Perform second fork.
try:
pid = os.fork()
if pid > 0:
return pid

except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno,
e.strerror))
sys.exit(1)

# The process is now daemonized, redirect standard file descriptors.
sys.stdout.flush()
sys.stderr.flush()
func(*args, **kwargs)

return _daemonize


@daemonize
def long_smarter_process():
while True:
sleep(2)
print("Hello how are you?")


And it works exactly as before, but more correctly..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread noydb
On Tuesday, December 11, 2012 3:35:29 AM UTC-5, Greg Donald wrote:
> On Mon, Dec 10, 2012 at 10:34:31PM -0700, Michael Torrie wrote:
> 
> > I use a module I got from pypi called dateutil.  It has a nice submodule
> 
> > called parser that can handle a variety of date formats with good
> 
> > accuracy.  Not sure how it works, but it handles all the common American
> 
> > date formats I've thrown at it.
> 
> 
> 
> from dateutil.parser import parse
> 
> dt = parse( whatever )
> 
> 
> 
> I've throw all kind of date and timestamps at it.. have yet to see anything 
> it won't parse.
> 
> 
> 
> 
> 
> --
> 
> Greg Donald


Thanks - I tried this (dateutil.parser import parsed...), and it works.  I'm 
skeptical of it working for any crazy date string thrown at it, but for my 
purposes it should suffice -- and my purposes for now was purely just 
curiousity on how to handle if it became necessary.

I tried figuring out Steve D'Aprano's solution above on my system (windows 7, 
python 2.7) - no luck.  Sorry, I am a newbie, so I'm a bit lost on this --- my 
locale module doesnt offer a nl_langinfo function -- why would this be?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread peter

On 12/11/2012 10:57 AM, andrea crotti wrote:

where in [] I have the PID of the process.
In this suggested way I should use some other files as standard output
and error, but for that I already have the logging module that logs
in the right place..
It's not realy neccesary do use the stderr and stdout parameters, in 
fact the default value for those parameters are null ('/dev/null').

The functionality is like this.
All you print to stdout going to be in the stdout parameter of the 
daemon function, and the same thing for stderr.


Now my suggestion for you, is you already have initialize a "logging 
file", just use the logging module  to redirect informacion  what's is 
doing your forked  function, and use the stderr paramater of the daemon 
function to DEBUG errors in the forked function.

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


Re: forking and avoiding zombies!

2012-12-11 Thread Thomas Rachel

Am 11.12.2012 14:34 schrieb peter:

On 12/11/2012 10:25 AM, andrea crotti wrote:

Ah sure that makes sense!

But actually why do I need to move away from the current directory of
the parent process?
In my case it's actually useful to be in the same directory, so maybe
I can skip that part,
or otherwise I need another chdir after..

You don't need to move away from the current directory. You cant use os
to get the current work directory

stderrfile = '%s/error.log' % os.getcwd()
stdoutfile = '%s/out.log' % os.getcwd()


ITYM

os.path.join(os.getcwd(), 'error.log')

resp.

os.path.join(os.getcwd(), 'out.log')


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


JSON logging ?

2012-12-11 Thread Bart Thate
Is it possible to change hooks or something to let the logging SocketServer
stuff handle JSON instead of pickle ?

I am thinking of sending my JSON dict data through the logging system to
remote.

A default standard way to send stuff back and forth would be welcome here.

pickle uses eval still ? or is is considered safe now ? i was told not to
use eval() stuff on data.

Strange thing i never thought of using the logging plugin to send stuff
remote.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-11 Thread bitbucket
On Tuesday, December 11, 2012 3:42:35 AM UTC-5, Paul Kölle wrote:
> Before switching technologies I'd check if this solves your problem 
> 
> http://geekswithblogs.net/Lance/archive/2009/01/14/pass-by-reference-parameters-in-powershell.aspx
>  
> 
> TL;DR IMHO "out" parameters are basically pointers (pass by reference) 
> 
> and need to be passed like GetSettingValue("name", [ref]$value)...
> 

Thanks for the suggestion.  I believe the [ref] syntax was one of the things I 
tried, but it didn't work in the context of OLE Automation (IDispatch) calls.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-11 Thread bitbucket
On Monday, December 10, 2012 8:16:43 PM UTC-5, Mark Hammond wrote:
> "out" params are best supported if the object supplied a typelib - then 
> Python knows the params are out and does the right thing automagically. 
>   If out params are detected, the result of the function will be a tuple 
> of (real_result, out_param1, ...)
> 
> Even if no typelib is supported, you can access them with a little pain 
> via the win32com.client.Dispatch() object.  You might like to follow up 
> to the python-wi...@python.org mailing list where many people will be 
> able to help.
> 
> HTH,
> 
> Mark

Mark, thanks for the reply.  In this case, I have a type library and attempted 
to use MakePy but it doesn't seem to be working as expected.

I was reading through CH12 of your Python Programming on Win32 book 
(http://oreilly.com/catalog/pythonwin32/chapter/ch12.html).  I was hopeful 
given your description of MakePy that I could get this to work.  It appears 
that you're saying MakePy will convert "byref" args in a function over to 
return values.

For example, the IDL in the server includes the following 3 functions.

[id(1)] void ShowMessage(BSTR msg);
[id(2)] void GetSettingValue(BSTR settingName, BSTR* 
settingValue);
[id(3)] void SetSettingValue(BSTR settingName, BSTR 
settingValue);

The thorny one is the GetSettingValue since it takes the out param.  When I run 
MakePy, it generates the below.

def ShowMessage(self, msg=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(1, LCID, 1, (24, 0), ((8, 
0),),msg
)

def GetSettingValue(self, settingName=defaultNamedNotOptArg, 
settingValue=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(2, LCID, 1, (24, 0), ((8, 0), 
(16392, 0)),settingName
, settingValue)

def SetSettingValue(self, settingName=defaultNamedNotOptArg, 
settingValue=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(3, LCID, 1, (24, 0), ((8, 0), 
(8, 0)),settingName
, settingValue)

I noticed that the argument type is different for the out param (16392 instead 
of 8).  However, it doesn't appear to me that its generating return values 
instead of args (though I'm not very experienced in python).

I tried invoking these in python.  The ShowMessage and SetSettingValue work 
great.  I can't get the GetSettingValue to work though.  Perhaps there's a 
different syntax I need when using the MakePy generated code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-11 Thread bitbucket
On Tuesday, December 11, 2012 10:48:53 AM UTC-5, bitbucket wrote:
>
> I noticed that the argument type is different for the out param (16392 
> instead of 8).  However, it doesn't appear to me that its generating return 
> values instead of args (though I'm not very experienced in python).
>

I see that the value 16392 is really VT_BYREF | VT_BSTR and 8 is just VT_BSTR.  
So in that case it appears MakePy is taking noticed at least of the VT_BYREF 
and including that in the generated code (since it uses 16392).

So maybe there's a special way I need to call the generated wrapper?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String manipulation in python..NEED HELP!!!!

2012-12-11 Thread duncan smith

On 10/12/12 22:38, qbai...@ihets.org wrote:

I need help with a program i am doing. it is a cryptography program. i am given 
a regular alphabet and a key. i need to use the user input and use the regular 
alphabet and use the corresponding letter in the key and that becomes the new 
letter. i have the basic code but need help with how to mainpulate the string 
to do the encryption/decryption. please help

here is my code so far:


""" crypto.py
 Implements a simple substitution cypher
"""

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key =   "XPMGTDHLYONZBWEARKJUFSCIQV"

def main():
   keepGoing = True
   while keepGoing:
 response = menu()
 if response == "1":
   plain = raw_input("text to be encoded: ")
   print encode(plain)
 elif response == "2":
   coded = raw_input("code to be decyphered: ")
   print decode(coded)
 elif response == "0":
   print "Thanks for doing secret spy stuff with me."
   keepGoing = False
 else:
   print "I don't know what you want to do..."




i really need help on how to encrypt it im not sure how to go about doing that 
please help.



>>> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
>>> key = "XPMGTDHLYONZBWEARKJUFSCIQV"
>>> mapping = {}
>>> for i, ch in enumerate(alpha):
mapping[ch] = key[i]


>>> ''.join(mapping[ch] for ch in "ACE")
'XMT'
>>> ''.join(mapping[ch] for ch in "WORD")
'CEKG'
>>>


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


Create xml with elementtree ET and xml escaping

2012-12-11 Thread nenad . cikic
Hello, I have posted the same in XML group but it seems pretty dead there so I 
will repost here.

I am new to xml processing in python.
I am looking to create XML. Xml is not too difficult so I thought to create it 
manually using ElementTree.
First I noted that ET.toString does escape <>& but not " and '
Is that normal?

Since I have also the need to sign the XML I need the ability to create xml but 
without xml escaping (unescaped data are signed).
If i do ET.toString(root,'utf8',text') i do not get the xml tags and if I do 
ET.toString(root,'utf8') I get escaped chars.
For example:
a=ET.Element('a')
b=ET.SubElement(a,'b')
b.text=u"šđ<>&"

ET.tostring(a,'utf8')
outputs to
"\n\xc5\xa1\xc4\x91<>&"

ET.tostring(a,'utf8',method='text')
outputs to
"\xc5\xa1\xc4\x91<>&"

and I need before singing
\xc5\xa1\xc4\x91<>&
and after signing
\xc5\xa1\xc4\x91<>&

Is there some way other than string replace?
Thanks
Nenad
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] DjangoCon Europe 2013 call for papers

2012-12-11 Thread D.M. Procida
DjangoCon Europe  will be held in Warsaw from
the 15th-19th May 2013 (three days of talks followed by two of sprints
and workshops).

The organisers are very pleased to invite members of the Django
community to submit their talk proposals for the event.

We're looking for Django and Python enthusiasts, pioneers, adventurers
and anyone else who would like to share their Django achievements and
experiments with the rest of the community.

We are particularly keen to invite submissions from potential speakers
who have not previously considered speaking at an event like this - so
if you haven't, please consider it now!

We really look forward to hearing from you all, and seeing you in Warsaw
next May. 

For more information, see
. 

This call for papers closes on January 8th 2013.

Powodzenia!


Daniele, on behalf of the DjangoCon Europe organising committee.
-- 
http://mail.python.org/mailman/listinfo/python-list


Establishing Https connection

2012-12-11 Thread nenad . cikic
Hello,
Once I get my xml populated I have to send it to web service.
Should I use httplib?
I am reading the docs and I have managed to open the connection with 
httplib.HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout[, 
source_address]])
After that i intend to use
HTTPConnection.request('POST', url[, body[, headers]])

During opening it asks me for the password. I see that the urllib class has 
prompt_user_passwd() that can be overriden for the password supply, so that no 
console action is necessary, but with httplib how is done?
My questions are:
-am I using the right class?
-i intend to store certificate and private key in database, but how can I use 
them without saving back to file?

I have already developed applications for http/https but not in python, so I 
need some hint to point me in the right direction.

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


Re: String manipulation in python..NEED HELP!!!!

2012-12-11 Thread Terry Reedy

On 12/10/2012 5:59 PM, John Gordon wrote:


def encode(plain):
'''Return a substituted version of the plain text.'''
encoded = ''
for ch in plain:
   encoded += key[alpha.index(ch)]
return encoded


The turns an O(n) problem into a slow O(n*n) solution. Much better to 
build a list of chars and then join them.


--
Terry Jan Reedy

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


Re: Establishing Https connection

2012-12-11 Thread Kwpolska
On Tue, Dec 11, 2012 at 7:26 PM,   wrote:
> Hello,
> Once I get my xml populated I have to send it to web service.
> Should I use httplib?
> I am reading the docs and I have managed to open the connection with
> httplib.HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, 
> timeout[, source_address]])
> After that i intend to use
> HTTPConnection.request('POST', url[, body[, headers]])
>
> During opening it asks me for the password. I see that the urllib class has 
> prompt_user_passwd() that can be overriden for the password supply, so that 
> no console action is necessary, but with httplib how is done?
> My questions are:
> -am I using the right class?
> -i intend to store certificate and private key in database, but how can I use 
> them without saving back to file?
>
> I have already developed applications for http/https but not in python, so I 
> need some hint to point me in the right direction.
>
> Thanks
> Nenad
>
> --
> http://mail.python.org/mailman/listinfo/python-list

I, for one, suggest  for your sanity.  I
guess it would be something along the lines of:

import requests
xml = """ ..."""
files = {'file-field-as-requested-by-the-service': xml}
requests.post(url, files=files, auth=HTTPDigestAuth('user', 'pass'))


Plus 
http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification
and other stuff from there.

Httplib may not be wrong, but I’m doing this for your sanity.
-- 
Kwpolska 
stop html mail  | always bottom-post
www.asciiribbon.org | www.netmeister.org/news/learn2quote.html
GPG KEY: 5EAAEA16
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create xml with elementtree ET and xml escaping

2012-12-11 Thread MRAB

On 2012-12-11 17:47, nenad.ci...@gmail.com wrote:

Hello, I have posted the same in XML group but it seems pretty dead there so I 
will repost here.

I am new to xml processing in python.
I am looking to create XML. Xml is not too difficult so I thought to create it 
manually using ElementTree.
First I noted that ET.toString does escape <>& but not " and '
Is that normal?


" needs to be encoded when it's in an attribute's value:



because it's also being used as a delimiter in that case, but elsewhere
it has no special meaning.


Since I have also the need to sign the XML I need the ability to create xml but 
without xml escaping (unescaped data are signed).


XML with the escaping isn't valid XML.


If i do ET.toString(root,'utf8',text') i do not get the xml tags and if I do 
ET.toString(root,'utf8') I get escaped chars.
For example:
a=ET.Element('a')
b=ET.SubElement(a,'b')
b.text=u"šđ<>&"

ET.tostring(a,'utf8')
outputs to
"\n\xc5\xa1\xc4\x91<>&"

ET.tostring(a,'utf8',method='text')
outputs to
"\xc5\xa1\xc4\x91<>&"

and I need before singing
\xc5\xa1\xc4\x91<>&
and after signing
\xc5\xa1\xc4\x91<>&

Is there some way other than string replace?



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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Marc Christiansen
Greg Donald  wrote:
> On Mon, Dec 10, 2012 at 10:34:31PM -0700, Michael Torrie wrote:
>> I use a module I got from pypi called dateutil.  It has a nice submodule
>> called parser that can handle a variety of date formats with good
>> accuracy.  Not sure how it works, but it handles all the common American
>> date formats I've thrown at it.
> 
> from dateutil.parser import parse
> dt = parse( whatever )
> 
> I've throw all kind of date and timestamps at it.. have yet to see
> anything it won't parse.

Interesting. First thing I tried gave an error:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'LC_CTYPE=de_DE.utf8;LC_NUMERIC=de_DE.utf8;LC_TIME=de_DE.utf8;LC_COLLATE=C;LC_MONETARY=de_DE.utf8;LC_MESSAGES=C;LC_PAPER=de_DE.utf8;LC_NAME=de_DE.utf8;LC_ADDRESS=de_DE.utf8;LC_TELEPHONE=de_DE.utf8;LC_MEASUREMENT=de_DE.utf8;LC_IDENTIFICATION=de_DE.utf8'
>>> from dateutil.parser import parse
>>> parse('1. Januar 2013')
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib64/python3.3/site-packages/dateutil/parser.py", line 720, in 
parse
return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/usr/lib64/python3.3/site-packages/dateutil/parser.py", line 310, in 
parse
raise ValueError("unknown string format")
ValueError: unknown string format
>>> parse('1.2.2013') # ambiguous, I know
datetime.datetime(2013, 1, 2, 0, 0) # should be datetime.datetime(2013, 2, 1, 
0, 0)

so it doesn't like long german dates and it misparses the numerical
form. And I even was so nice to set the locale :) (not that it succeeds
without…)
I admit I didn't read any documentation on it apart from help(parse)
which mentions a parserinfo argument, so one could probably give it a
hand at parsing.

The only thing this shows is that parsing dates is difficult.

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


Re: problem with usbtmc-communication

2012-12-11 Thread Jean Dubois
On 11 dec, 15:34, w...@mac.com wrote:
> On Dec 11, 2012, at 1:58 AM, Jean Dubois  wrote:
>
>
>
>
>
>
>
>
>
> > On 10 dec, 16:34, w...@mac.com wrote:
> >> On Dec 10, 2012, at 8:31 AM, Jean Dubois  wrote:
>
> >> [byte]
> >>> As you can see this approach suffers from the same "buffer problem" as
> >>> the approach with readline did. One now good argue as a workaround:
> >>> get rid of the first data pair and add an extra measure command for
> >>> the missing data pair, however this still does not explain why this
> >>> problem is there in Python and not in Octave and I also fear I'll get
> >>> more trouble when sending combined commands e.g. such as that to
> >>> create a staircase current
> >>> So my question is, how to modify the Python-code such that the first
> >>> data pair is indeed the first data pair
>
> >>> thanks,
> >>> jean
>
> >>> Here follows the new code:
> >>> #!/usr/bin/python
> >>> import time
> >>> import os
> >>> import sys
> >>> measurementcurr=''
> >>> measurementvolt=''
> >>> timesleepdefault=5
> >>> print "Enter a numofchar (11 = >>> numofchar = int(raw_input())
> >>> filename ='mydata.txt'
> >>> usbkeith = open('/dev/usbtmc1','r+')
> >>> usbkeith.flush()
> >>> usbkeith.write("*IDN?\n")
>
> >> It seems like a real leap of faith to be opening /dev/usbtmc1 as though it 
> >> were a file-oriented device.  I've never heard of ANY instrument interface 
> >> implemented this way.
> >> Where did you see example code that did that.
> > I found examples in theusbtmckernel driver documentation (the
> > examples there are given in C):
> >http://www.home.agilent.com/upload/cmc_upload/All/usbtmc.htm?&cc=BE&l...
>
> OK - I see where the examples came from, and I notice -
>
>         int my_inst;
>         my_inst=open(“/dev/usbtmc1”,O_RDWR);
>         write(my_inst,”*RST\n”,5);
>         close(my_inst);
>
> and similarly in another place -
>
>         retval=write(myfile,"*IDN?\n",6);
>
> Note that both write commands contain a byte count of the number of 
> characters to be written (\n counts as one character).
> Again, the read commands contain byte counts.  I'm very suspicious that a 
> write command with no byte count writes nothing, but does move a buffer 
> pointer.
>
> -Bill

Does Python support/implement simular commands? Can I use
usbkeith.write("*IDN?\n",6) and  something simular for the reading
commands?

thanks,
jean
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Dave Cinege
On Tuesday 11 December 2012 01:41:38 Ian Kelly wrote:

> running into bugs like this:
> >>> thes = Thesaurus()
> >>> thes.update = 'now'
> >>> thes.update
> 
> 

I've noticed this but it's mostly pointless, as meaningful code does work.
(Also you stepped on the existing 'update()' dictionary method.)

>>> import thesaurus
>>> t = thesaurus.Thesaurus()
>>> t.s = 'now'
>>> t.s + ' this'
>'now this'

Works perfect. However I'll take a look at __getattribute__  as from what you 
say it's more proper.

> Second, in __getitem__ you start a loop with "for i in
> range(len(l)):", and then you use i as an index into l several times.
> It would be cleaner and more Pythonic to do "for i, part in
> enumerate(l):", and then you can replace every occurrence of "l[i]"

My python is still 'old school' due to being stuck on old versions for in 
production embedded system python applications.

> It's not clear to me what the isinstance call here is meant to be
> testing for.

It's used to determine if it's the root instance of the recursive string 
because self.data, not self must be used to access that. Can you offer a better 
way?

> The prior statements require key to be a string.  If key
> is a string, then by construction l[0] is also a string.  So it seems
> to me that the isinstance check here will always be False.

OK, try and remove it and then get back to me. :-)

> In any case, the key splitting here seems to be done primarily to
> support the use of formatting placeholders like "%(L.l.1)s" in the
> examples.  I want to point out that this use case is already well
> supported (I might even say "better" supported since it cleanly
> distinguishes index elements from attributes with syntax) by the

Thesaurus recursion works with modules like Template, in addition to allowing 
easy hierarchical organization of (global) data. It's not about string 
formatting. It's about organizing data and recursive retrieval of that data.

> Lastly, you have several bare "except" clauses in the code.  Bare

Not going to get into religion. There is no 'correct' way to do this code at 
all because it's not established normal python. I left it simple and it suits 
my needs. I've converted several production commercial utilities and 
applications to use Thesaurus, and have seen nothing but benefit.

If anyone needs more to this, have at it, I'm busy

Dave

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


MySQLdb compare lower

2012-12-11 Thread Anatoli Hristov
Hello guys,

Excuse me for the noob question, but is there a way to compare a field
in mysql as lower() somehow?

I have a situation where I compare the SKU in my DB and there are some
SKU that are with lowercase and some with uppercase, how can I solve
this in your opinion ?

def Update_SQL(price, sku):

db = MySQLdb.connect("localhost","getit","opencart",
use_unicode=True, charset="utf8")
cursor = db.cursor()
sql = "UPDATE product SET price=%s WHERE sku=%s"
cursor.execute(sql, (price, sku))
db.commit()
db.close()


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


Re: String manipulation in python..NEED HELP!!!!

2012-12-11 Thread Ross Ridge
John Gordon wrote:
> def encode(plain):
> '''Return a substituted version of the plain text.'''
> encoded = ''
> for ch in plain:
>encoded += key[alpha.index(ch)]
> return encoded

Terry Reedy   wrote:
>The turns an O(n) problem into a slow O(n*n) solution. Much better to 
>build a list of chars and then join them.

There have been much better suggestions in this thread, but John Gordon's
code above is faster than the equivilent list and join implementation
with Python 2.6 and Python 3.1 (the newest versions I have handy).
CPython optimized this case of string concatenation into O(n) back in
Python 2.4.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Zen of Zope, by Alex Clark

2012-12-11 Thread Gregory Ewing

Steven D'Aprano wrote:

On Sun, 09 Dec 2012 20:13:43 -0500, Alex Clark wrote:

>

The Zen of Zope, by Alex Clark


I expect that I would find that hilarious if I knew anything about Zope :)


It's probably a good thing I don't know much about Zope,
because I'm already finding it hilarious. If I knew more,
the hilarity level might become physically dangerous.

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Dave Cinege
On Tuesday 11 December 2012 03:12:19 Steven D'Aprano wrote:

> Is this intended as a ready-for-production class?

For me, yes. In production code.

> py> d = Thesaurus()
> py> d['spam'] = {}

Maybe because spam is type dict instead of type thes???

>>> import thesaurus
>>> thes = thesaurus.Thesaurus
>>> t = thes()
>>> t.spam = thes()
>>> t.spam.ham = 'cheese'
>>> print t.spam.ham
>cheese
>>> print t['spam'].ham
>cheese
>>> print t['spam']['ham']
>cheese
>>> '%(spam.ham)s' % t
>'cheese'

Works for me!

Remainder of your post, not productive, not worth my time.

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


Re: The Zen of Zope, by Alex Clark

2012-12-11 Thread Alex Clark

On 2012-12-11 21:01:03 +, Gregory Ewing said:


Steven D'Aprano wrote:

On Sun, 09 Dec 2012 20:13:43 -0500, Alex Clark wrote:

 >

The Zen of Zope, by Alex Clark


I expect that I would find that hilarious if I knew anything about Zope :)


It's probably a good thing I don't know much about Zope,
because I'm already finding it hilarious. If I knew more,
the hilarity level might become physically dangerous.



Well, the point is two-fold:


- Provide comic relief for those who have encountered unexpected 
complexity in Zope.

- Showcase Zope's strengths for those who may be unfamiliar with it.


TL;DR: Zope has a lot to offer, and there are times when you may need 
its libraries to perform complex tasks.




--
Alex Clark · https://www.gittip.com/aclark4life/


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


Re: String manipulation in python..NEED HELP!!!!

2012-12-11 Thread Tim Delaney
On 12 December 2012 07:52, Ross Ridge  wrote:

> John Gordon wrote:
> > def encode(plain):
> > '''Return a substituted version of the plain text.'''
> > encoded = ''
> > for ch in plain:
> >encoded += key[alpha.index(ch)]
> > return encoded
>
> Terry Reedy   wrote:
> >The turns an O(n) problem into a slow O(n*n) solution. Much better to
> >build a list of chars and then join them.
>
> There have been much better suggestions in this thread, but John Gordon's
> code above is faster than the equivilent list and join implementation
> with Python 2.6 and Python 3.1 (the newest versions I have handy).
> CPython optimized this case of string concatenation into O(n) back in
> Python 2.4.
>

>From "What's New in Python 2.4":
http://docs.python.org/release/2.4.4/whatsnew/node12.html#SECTION000121

String concatenations in statements of the form s = s + "abc" and s +=
"abc" are now performed more efficiently *in certain circumstances*. This
optimization *won't be present in other Python implementations such as
Jython*, so you shouldn't rely on it; using the join() method of strings is
still recommended when you want to efficiently glue a large number of
strings together.

Emphasis mine.

The optimisation was added to improve the situation for programs that were
already using the anti-pattern of string concatenation, not to encourage
people to use it.

As a real-world case, a bug was recently found in Mercurial where an
operation on Windows was taking orders of magnitudes longer than on
Linux due to use of string concatenation rather than the join idiom (from
~12 seconds spent on string concatenation to effectively zero).

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Ian Kelly
On Tue, Dec 11, 2012 at 1:57 PM, Dave Cinege  wrote:
> On Tuesday 11 December 2012 01:41:38 Ian Kelly wrote:
>> Second, in __getitem__ you start a loop with "for i in
>> range(len(l)):", and then you use i as an index into l several times.
>> It would be cleaner and more Pythonic to do "for i, part in
>> enumerate(l):", and then you can replace every occurrence of "l[i]"
>
> My python is still 'old school' due to being stuck on old versions for in
> production embedded system python applications.

Just out of curiosity, how old are we talking?  enumerate was added in
Python 2.3, which is nearly 10 years old.  Prior to 2.2 I don't think
it was even possible to subclass dict, which would make your Thesaurus
implementation unusable, so are these systems running Python 2.2?

>> It's not clear to me what the isinstance call here is meant to be
>> testing for.
>
> It's used to determine if it's the root instance of the recursive string
> because self.data, not self must be used to access that. Can you offer a 
> better
> way?
>
>> The prior statements require key to be a string.  If key
>> is a string, then by construction l[0] is also a string.  So it seems
>> to me that the isinstance check here will always be False.
>
> OK, try and remove it and then get back to me. :-)

Okay.  I replaced this code:

if isinstance(l[0], (dict, Thesaurus)):
a = self.data
else:
a = self

with:

a = self

and then I ran the examples, and the output was unchanged.  As Steven
pointed out, I don't see how that first branch could succeed anyway,
since self.data is never defined.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing an OLE Automation (IDispatch) server from python which requires the use of "out params"

2012-12-11 Thread Mark Hammond

On 12/12/2012 2:48 AM, bitbucket wrote:

On Monday, December 10, 2012 8:16:43 PM UTC-5, Mark Hammond wrote:

"out" params are best supported if the object supplied a typelib -
then Python knows the params are out and does the right thing
automagically. If out params are detected, the result of the
function will be a tuple of (real_result, out_param1, ...)

Even if no typelib is supported, you can access them with a little
pain via the win32com.client.Dispatch() object.  You might like to
follow up to the python-wi...@python.org mailing list where many
people will be able to help.

HTH,

Mark


Mark, thanks for the reply.  In this case, I have a type library and
attempted to use MakePy but it doesn't seem to be working as
expected.

I was reading through CH12 of your Python Programming on Win32 book
(http://oreilly.com/catalog/pythonwin32/chapter/ch12.html).  I was
hopeful given your description of MakePy that I could get this to
work.  It appears that you're saying MakePy will convert "byref" args
in a function over to return values.

For example, the IDL in the server includes the following 3
functions.

[id(1)] void ShowMessage(BSTR msg); [id(2)] void GetSettingValue(BSTR
settingName, BSTR* settingValue); [id(3)] void SetSettingValue(BSTR
settingName, BSTR settingValue);

The thorny one is the GetSettingValue since it takes the out param.
When I run MakePy, it generates the below.

def ShowMessage(self, msg=defaultNamedNotOptArg): return
self._oleobj_.InvokeTypes(1, LCID, 1, (24, 0), ((8, 0),),msg )

def GetSettingValue(self, settingName=defaultNamedNotOptArg,
settingValue=defaultNamedNotOptArg): return
self._oleobj_.InvokeTypes(2, LCID, 1, (24, 0), ((8, 0), (16392,
0)),settingName , settingValue)

def SetSettingValue(self, settingName=defaultNamedNotOptArg,
settingValue=defaultNamedNotOptArg): return
self._oleobj_.InvokeTypes(3, LCID, 1, (24, 0), ((8, 0), (8,
0)),settingName , settingValue)

I noticed that the argument type is different for the out param
(16392 instead of 8).  However, it doesn't appear to me that its
generating return values instead of args (though I'm not very
experienced in python).

I tried invoking these in python.  The ShowMessage and
SetSettingValue work great.  I can't get the GetSettingValue to work
though.  Perhaps there's a different syntax I need when using the
MakePy generated code?


Seeing the "real" return value is void, it should just be a matter of:

settingValue = ob.GetSettingValue("settingName")

Mark




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


Re: MySQLdb compare lower

2012-12-11 Thread John Gordon
In  Anatoli Hristov 
 writes:

> I have a situation where I compare the SKU in my DB and there are some
> SKU that are with lowercase and some with uppercase, how can I solve
> this in your opinion ?

> def Update_SQL(price, sku):

> db = MySQLdb.connect("localhost","getit","opencart",
> use_unicode=True, charset="utf8")
> cursor = db.cursor()
> sql = "UPDATE product SET price=%s WHERE sku=%s"
> cursor.execute(sql, (price, sku))
> db.commit()
> db.close()

I think this will work:

sql = 'UPDATE product SET price=%s WHERE LOWER(sku)=%s'
cursor.execute(sql, (price, sku.lower())

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Ian Kelly
On Tue, Dec 11, 2012 at 2:53 PM, Ian Kelly  wrote:
> and then I ran the examples, and the output was unchanged.  As Steven
> pointed out, I don't see how that first branch could succeed anyway,
> since self.data is never defined.

It occurs to me that the UserDict class does have a data attribute.
Perhaps there was another version of Thesaurus that inherited from
UserDict instead of dict, and so the access to .data is a holdover
from legacy code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String manipulation in python..NEED HELP!!!!

2012-12-11 Thread Peter Pearson
On Tue, 11 Dec 2012 16:39:27 +, duncan smith wrote:
[snip]
> >>> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
> >>> key = "XPMGTDHLYONZBWEARKJUFSCIQV"
> >>> mapping = {}
> >>> for i, ch in enumerate(alpha):
>   mapping[ch] = key[i]

mapping = dict(zip(alpha, key))

-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with print and output to screen

2012-12-11 Thread Mike
Hello, I am learning python and i have the next problem and i not understand 
how fix.
The script is very simple, shows in the terminal the command but, the row is 
divided in two:
Example:
 

/opt/zimbra/bin/zmprov ga u...@example.com
|egrep "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" 
/opt/zimbra/bin/zmprov ga us...@example.com
|egrep "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"

And the correct is: 
/opt/zimbra/bin/zmprov ga u...@example.com |egrep 
"(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"


The script is:

#!/usr/bin/python
import os

for user in open ("email"):
print '/opt/zimbra/bin/zmprov ga ' + user + '|egrep 
"(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" '



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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Dave Cinege
On Tuesday 11 December 2012 16:53:12 Ian Kelly wrote:

> Just out of curiosity, how old are we talking?  enumerate was added in
> Python 2.3, which is nearly 10 years old.  Prior to 2.2 I don't think
> it was even possible to subclass dict, which would make your Thesaurus
> implementation unusable, so are these systems running Python 2.2?

I'm finally beyond 2.2 and getting rid of 2.4 soon. Just started using 2.6 5 
months ago.

Thesaurus initially came about from me doing this:
class Global:
pass
g = Global()

As a way to organize/consolidate global vars and eliminate the global 
statement.

After a brain fart one day I expanded this to some simple recursion and felt I 
was onto something as my entire life changed with how easy it now was to build 
output strings.

As you noted it was not possible to subclass dict, so I first tried with a 
class, and you run into recursion hell with __setatrib__ to which i think 
there is no fix.

I then made a UserDict version. Then when I moved mostly to 2.6 I could do a 
proper dict subclass. 

So I believe you're actually correct here 

 if isinstance(l[0], (dict, Thesaurus)):
a = self.data

Looks like an artifact from my UserDict version and was needed.  :-(

class UserDict:
def __init__(self, dict=None, **kwargs):
self.data = {}

Thanks for this. You'll see from the version number I wrote this 3 months ago 
so it's not 100% fresh in my mind. I'm releasing it now because a python coder 
I contracted to pick up some slack for me saw this and went ape at how much he 
liked it...and that prompted me to finally get it out into the wild.

As for in depth discussion and enhancement to this, I lack the time.

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Cameron Simpson
On 11Dec2012 15:57, Dave Cinege  wrote:
| On Tuesday 11 December 2012 01:41:38 Ian Kelly wrote:
| > running into bugs like this:
| > >>> thes = Thesaurus()
| > >>> thes.update = 'now'
| > >>> thes.update
| > 
| > 
| 
| I've noticed this but it's mostly pointless, as meaningful code does work.
| (Also you stepped on the existing 'update()' dictionary method.)

I think that was a deliberate choice of name by Ian.

I've got a class like Thesaurus that subclasses dict and maps attributes
to dictionary elements (with a few special purpose tweaks I could go into
if anyone cares). I made a deliberate decision to only map UPPERCASE
attributes to dict keys to avoid exactly the kind of conflict above,
because:

  thes.update = 'now'

must either trash the dict.update method _or_ fail to present .update as
'now'. Both have their downsides. So at the cost of shoutier but still
effective code I accepted only .UPPERCASE attribute names as mapping to
keys.

This compromise also makes subclassing much easier, because the
subclasser is free to use conventional lowercase attribute names.

Cheers,
-- 
Cameron Simpson 

Thousands at his bidding speed,
And post o'er land and ocean without rest   - Milton
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb compare lower

2012-12-11 Thread Anatoli Hristov
> I think this will work:
>
> sql = 'UPDATE product SET price=%s WHERE LOWER(sku)=%s'
> cursor.execute(sql, (price, sku.lower())
>
Thanks John, this works, I was about to make double check with lower
and upper, but this saves me :)

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


Re: MySQLdb compare lower

2012-12-11 Thread Cameron Simpson
On 11Dec2012 22:01, Anatoli Hristov  wrote:
| Excuse me for the noob question, but is there a way to compare a field
| in mysql as lower() somehow?
| 
| I have a situation where I compare the SKU in my DB and there are some
| SKU that are with lowercase and some with uppercase, how can I solve
| this in your opinion ?
| 
| def Update_SQL(price, sku):
| 
| db = MySQLdb.connect("localhost","getit","opencart",
| use_unicode=True, charset="utf8")
| cursor = db.cursor()
| sql = "UPDATE product SET price=%s WHERE sku=%s"
| cursor.execute(sql, (price, sku))
| db.commit()
| db.close()

Let the db do the work. Untested example:

  sql = "UPDATE product SET price=%s WHERE LOWER(sku)=LOWER(%s)"

See:

  http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

However I would point out that this form of the SQL requires a scan of
the whole db table per update. The plain test against "sku" instead of
"LOWER(sku)" lets the db use an index on "sku" to access the relevant
row directly; MUCH more efficient (if you've got an index on "sku",
of course).

You can only run with the first, efficient, form if the sku values in
the db are normalised. For example, all upper case or all lower case.

Supposing that your sku has been normalised to all lower case (i.e. the
data entry phase converts skus to lowercase when inserting data into the
db), then you can write:

  sql = "UPDATE product SET price=%s WHERE sku=LOWER(%s)"

which can use the index on "sku" - efficient. Here's you're normalising
the test value (the %s part) to match the db content, which should
alreay be lowercase.

_If_ you know SKUs can always be normalised to lower case (or upper
case, your call provided it is consistent), you can normalise the values
in the db if they've been put in unnormalised. And then get on with your
life as above.

Cheers,
-- 
Cameron Simpson 

Hal, open the file
Hal, open the damn file, Hal
open the, please Hal
- Haiku Error Messages 
http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with print and output to screen

2012-12-11 Thread Dave Angel
On 12/11/2012 05:31 PM, Mike wrote:
> Hello, I am learning python and i have the next problem and i not understand 
> how fix.
> The script is very simple, shows in the terminal the command but, the row is 
> divided in two:
> Example:
>  
>
> /opt/zimbra/bin/zmprov ga u...@example.com
> |egrep "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" 
> /opt/zimbra/bin/zmprov ga us...@example.com
> |egrep "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"
>
> And the correct is: 
> /opt/zimbra/bin/zmprov ga u...@example.com |egrep 
> "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"
>
>
> The script is:
>
> #!/usr/bin/python
> import os
>
> for user in open ("email"):
> print '/opt/zimbra/bin/zmprov ga ' + user + '|egrep 
> "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" '
>
>
>

I'll assume that 'email' is a file in the current working directory.  So
when  you open it and iterate through it, each line will be stored in
'user', including its trailing newline.

When you print 'user', you're seeing the newline.

To see for yourself, you could/should have used (just before your print
statement)

   print repr(user)

which will show such things as escape sequences.

Anyway, the easiest way to fix it would be to use rstrip() on the line.

for user in open("email"):
user = user.rstrip()
print '/opt/...

That's assuming there's no trailing whitespace that you DO want to preserve.



-- 

DaveA

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


Re: Problem with print and output to screen

2012-12-11 Thread Joel Goldstick
When you read the file line by line the end of line character is included
in the result

try user[:-1] instead to strip the return from your printed text


On Tue, Dec 11, 2012 at 5:31 PM, Mike  wrote:

> Hello, I am learning python and i have the next problem and i not
> understand how fix.
> The script is very simple, shows in the terminal the command but, the row
> is divided in two:
> Example:
>
>
> /opt/zimbra/bin/zmprov ga u...@example.com
> |egrep
> "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"
> /opt/zimbra/bin/zmprov ga us...@example.com
> |egrep
> "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"
>
> And the correct is:
> /opt/zimbra/bin/zmprov ga u...@example.com |egrep
> "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)"
>
>
> The script is:
>
> #!/usr/bin/python
> import os
>
> for user in open ("email"):
> print '/opt/zimbra/bin/zmprov ga ' + user + '|egrep
> "(zimbraPrefMailForwardingAddress:|zimbraPrefMailForwardingAddress:)" '
>
>
>
> Thanks
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: Problem with print and output to screen

2012-12-11 Thread Dave Angel
On 12/11/2012 05:53 PM, Joel Goldstick wrote:
> When you read the file line by line the end of line character is included
> in the result
>
> try user[:-1] instead to strip the return from your printed text
>

The catch to that is the last line in the file might not have a
newline.  In that case, we'd be ignoring the last character of the line.

The .rstrip() method is easy, and for most purposes equivalent.  Few
text files have trailing whitespace, but many are missing the final
linefeed.



-- 

DaveA

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


Re: Problem with print and output to screen

2012-12-11 Thread Joel Goldstick
On Tue, Dec 11, 2012 at 6:00 PM, Dave Angel  wrote:

> On 12/11/2012 05:53 PM, Joel Goldstick wrote:
> > When you read the file line by line the end of line character is included
> > in the result
> >
> > try user[:-1] instead to strip the return from your printed text
> >
>
> The catch to that is the last line in the file might not have a
> newline.  In that case, we'd be ignoring the last character of the line.
>
> The .rstrip() method is easy, and for most purposes equivalent.  Few
> text files have trailing whitespace, but many are missing the final
> linefeed.
>
> Point taken.  Brain freeze.  I forgot about .rstrip.  That is the way to go
>
> --
>
> DaveA
>
>


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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Dave Cinege
On Tuesday 11 December 2012 17:39:12 Dave Cinege wrote:

My memory is getting jogged more why did some things:

raise KeyError(key + ' [%s]' % i)

I did this to specificly give you the indice that failed recursion but provide 
the entire key name as it was provided to __getitem__

So if:
g.cfg.host.cpu
fails recursion on 'host' you will see:  g.cfg.host.cpu [2]
I know my code sent g.cfg.host.cpu. I know host failed. if It was 
g.cfg.host.host, I'd know which host failed.

Makes sense to me. Works for me. Sure there are other ways to do it.

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


Re: forking and avoiding zombies!

2012-12-11 Thread andrea crotti
2012/12/11 Dennis Lee Bieber :
> On Tue, 11 Dec 2012 10:34:23 -0300, peter  declaimed
> the following in gmane.comp.python.general:
>
>>
>> stderrfile = '%s/error.log' % os.getcwd()
>> stdoutfile = '%s/out.log' % os.getcwd()
>>
> Ouch...
>
> stdoutfile = os.path.join(os.getcwd(), "out.log")
>
> minimizes any OS specific quirks in path naming...
> --
> Wulfraed Dennis Lee Bieber AF6VN
> wlfr...@ix.netcom.comHTTP://wlfraed.home.netcom.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list


Good point yes, but in this case fork doesn't work on Windows anyway
so it's not really an issue..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Zen of Zope, by Alex Clark

2012-12-11 Thread alex23
On Dec 12, 7:23 am, Alex Clark  wrote:
> TL;DR: Zope has a lot to offer, and there are times when you may need
> its libraries to perform complex tasks.

I always avoided Zope as I kept hearing "there's the Python way and
then there's the Zope way", however, all that did is lead me to avoid
a framework representing almost 15 years worth of experience. Having
now been exposed to it through Plone, I'm finding a lot there to like,
like zope.interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with print and output to screen

2012-12-11 Thread Mike
El martes, 11 de diciembre de 2012 20:07:09 UTC-3, Joel Goldstick  escribió:
> On Tue, Dec 11, 2012 at 6:00 PM, Dave Angel  wrote:
> 
> 
> On 12/11/2012 05:53 PM, Joel Goldstick wrote:
> 
> > When you read the file line by line the end of line character is included
> 
> > in the result
> 
> >
> 
> > try user[:-1] instead to strip the return from your printed text
> 
> >
> 
> 
> 
> The catch to that is the last line in the file might not have a
> 
> newline.  In that case, we'd be ignoring the last character of the line.
> 
> 
> 
> The .rstrip() method is easy, and for most purposes equivalent.  Few
> 
> text files have trailing whitespace, but many are missing the final
> 
> linefeed.
> 
> 
> 
> Point taken.  Brain freeze.  I forgot about .rstrip.  That is the way to go
> 
> 
> 
> --
> 
> 
> 
> DaveA
> 
> 
> 
> 
> 
> 
> -- 
> Joel Goldstick

Thank you very much, i used  "user.rstrip" and the output is correct . 

Best Regards!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Mitya Sirenef

On 12/11/2012 05:39 PM, Dave Cinege wrote:

On Tuesday 11 December 2012  16:53:12 Ian Kelly wrote:

>
>> Just out of curiosity, how old are we talking? enumerate was added in
>> Python 2.3, which is nearly 10 years old. Prior to 2.2 I don't think
>> it was even possible to subclass dict, which would make your Thesaurus
>> implementation unusable, so are these systems running Python 2.2?
>
> I'm finally beyond 2.2 and getting rid of 2.4 soon. Just started 
using 2.6 5

> months ago.
>
> Thesaurus initially came about from me doing this:
> class Global:
> pass
> g = Global()
>
> As a way to organize/consolidate global vars and eliminate the global
> statement.


I think that's the key issue here. I find that when code is well
structured, you pretty much never have a need for global statements,
anyway.

By the way, the Thesaurus class reminds me of using the old recipe
called 'Bunch':

http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/

like this:

b = Bunch(x=1) b.stuff = Bunch(y=2)

b.stuff.y 2

I've also seen an answer on StackOverflow that uses automatic recursive
'Bunching':

http://stackoverflow.com/questions/1123000/does-python-have-anonymous-classes

I've seen another variation of recursive bunching, I think it was by
Alex Martelli on StackOverflow, but I can't find it now, I believe it
used defaultdict as part of it..

This approach can be handy sometimes but has drawbacks, as others have
pointed out.

I think the issue is that it's not a "solution for avoiding globals",
which is not a problem in need of solution, but this can be a quick and
dirty way to organize a few levels of dicts/Bunches and usually people
come up with a custom variation on these recipes that suit their
program.


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Mitya Sirenef

On 12/11/2012 07:53 PM, Mitya Sirenef wrote:

By the way, the Thesaurus class reminds me of using the old recipe
called 'Bunch':

http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/ 



like this:

b = Bunch(x=1) b.stuff = Bunch(y=2)

b.stuff.y 2 


Sorry, this was meant to be:

b = Bunch(x=1)
b.stuff = Bunch(y=2)

b.stuff.y
 2

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


Re: The Zen of Zope, by Alex Clark

2012-12-11 Thread Alex Clark

On 2012-12-12 00:36:29 +, alex23 said:


On Dec 12, 7:23 am, Alex Clark  wrote:

TL;DR: Zope has a lot to offer, and there are times when you may need
its libraries to perform complex tasks.


I always avoided Zope as I kept hearing "there's the Python way and
then there's the Zope way", however, all that did is lead me to avoid
a framework representing almost 15 years worth of experience. Having
now been exposed to it through Plone, I'm finding a lot there to like,
like zope.interface.



Indeed, and getting folks to discuss Zope (especially in a positive 
way) is part of my goal.



--
Alex Clark · https://www.gittip.com/aclark4life/


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


Re: Create xml with elementtree ET and xml escaping

2012-12-11 Thread nenad . cikic
Il giorno martedì 11 dicembre 2012 20:59:54 UTC+1, MRAB ha scritto:
> > Hello, I have posted the same in XML group but it seems pretty dead there 
> > so I will repost here.
> 
> >
> 
> > I am new to xml processing in python.
> 
> > I am looking to create XML. Xml is not too difficult so I thought to create 
> > it manually using ElementTree.
> 
> > First I noted that ET.toString does escape <>& but not " and '
> 
> > Is that normal?
> 
> >
> 
> " needs to be encoded when it's in an attribute's value:
> 
> 
> 
>  


OK I understood.
 
> 
> 
> because it's also being used as a delimiter in that case, but elsewhere
> 
> it has no special meaning.
> 
> 
> 
> > Since I have also the need to sign the XML I need the ability to create xml 
> > but without xml escaping (unescaped data are signed).
> 
> 
> 
> XML with the escaping isn't valid XML.
> 

Of course I know it is not valid without escaping. But I need it only for 
signing. I will recheck this if really the web service wants the data to be 
signed as non escaped.
 
Thanks
Nenad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with usbtmc-communication

2012-12-11 Thread wrw
On Dec 11, 2012, at 3:48 PM, Jean Dubois  wrote:

[byte]

>> 
>> OK - I see where the examples came from, and I notice -
>> 
>> int my_inst;
>> my_inst=open(“/dev/usbtmc1”,O_RDWR);
>> write(my_inst,”*RST\n”,5);
>> close(my_inst);
>> 
>> and similarly in another place -
>> 
>> retval=write(myfile,"*IDN?\n",6);
>> 
>> Note that both write commands contain a byte count of the number of 
>> characters to be written (\n counts as one character).
>> Again, the read commands contain byte counts.  I'm very suspicious that a 
>> write command with no byte count writes nothing, but does move a buffer 
>> pointer.
>> 
>> -Bill
> 
> Does Python support/implement simular commands? Can I use
> usbkeith.write("*IDN?\n",6) and  something simular for the reading
> commands?
> 
> thanks,
> jean
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Yes of course.  BUT, that isn't really a python question, it depends on how the 
device driver implements the function call.

-Bill

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


Re: Establishing Https connection

2012-12-11 Thread nenad . cikic
Many thanks, I will check it.

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


Re: Matplotlib/Pylab Error

2012-12-11 Thread Oscar Benjamin
On 10 December 2012 20:40,   wrote:
> Dear Group,
>
> I am trying to enumerate few interesting errors on pylab/matplotlib.
> If any of the learned members can kindly let me know how should I address 
> them.
>
> I am trying to enumerate them as follows.
>
> i) >>> import numpy
 import pylab
 t = numpy.arange(0.0, 1.0+0.01, 0.01)
 s = numpy.cos(2*2*numpy.pi*t)
 pylab.plot(t, s)
> []
 pylab.show()
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
> return self.func(*args)
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
> line 236, in resize
> self.show()
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
> line 239, in draw
> FigureCanvasAgg.draw(self)
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", 
> line 421, in draw
> self.figure.draw(self.renderer)
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> draw(artist, renderer, *args, **kwargs)
>   File "C:\Python26\Lib\site-packages\matplotlib\figure.py", line 898, in draw
> func(*args)
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> draw(artist, renderer, *args, **kwargs)
>   File "C:\Python26\Lib\site-packages\matplotlib\axes.py", line 1997, in draw
> a.draw(renderer)
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> draw(artist, renderer, *args, **kwargs)
>   File "C:\Python26\Lib\site-packages\matplotlib\axis.py", line 1045, in draw
> tick.draw(renderer)
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> draw(artist, renderer, *args, **kwargs)
>   File "C:\Python26\Lib\site-packages\matplotlib\axis.py", line 239, in draw
> self.label1.draw(renderer)
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> draw(artist, renderer, *args, **kwargs)
>   File "C:\Python26\Lib\site-packages\matplotlib\text.py", line 591, in draw
> ismath=ismath)
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", 
> line 167, in draw_text
> font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
> TypeError: draw_glyphs_to_bitmap() takes no keyword arguments
>
> ii) Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit 
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
>

The example above works for me just fine (in ipython):
In [1]: import pylab

In [2]: import numpy

In [3]: t = numpy.arange(0.0, 1.0+0.01, 0.01)

In [4]: s = numpy.cos(2*2*numpy.pi*t)

In [5]: pylab.plot(t, s)
Out[5]: []

In [6]: pylab.show()  # At this point a plot of cos(t) appears as expected


Have you customised your matplotlibrc file? I have no problems with the above,

>
> IDLE 2.6.1
 import networkx as nx

Sorry, I don't have this module installed.


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


Re: Matplotlib/Pylab Error

2012-12-11 Thread subhabangalore
On Tuesday, December 11, 2012 2:10:07 AM UTC+5:30, subhaba...@gmail.com wrote:
> Dear Group,
> 
> 
> 
> I am trying to enumerate few interesting errors on pylab/matplotlib. 
> 
> If any of the learned members can kindly let me know how should I address 
> them.
> 
> 
> 
> I am trying to enumerate them as follows.
> 
> 
> 
> i) >>> import numpy
> 
> >>> import pylab
> 
> >>> t = numpy.arange(0.0, 1.0+0.01, 0.01)
> 
> >>> s = numpy.cos(2*2*numpy.pi*t)
> 
> >>> pylab.plot(t, s)
> 
> []
> 
> >>> pylab.show()
> 
> Exception in Tkinter callback
> 
> Traceback (most recent call last):
> 
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
> 
> return self.func(*args)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
> line 236, in resize
> 
> self.show()
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
> line 239, in draw
> 
> FigureCanvasAgg.draw(self)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", 
> line 421, in draw
> 
> self.figure.draw(self.renderer)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\figure.py", line 898, in draw
> 
> func(*args)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\axes.py", line 1997, in draw
> 
> a.draw(renderer)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\axis.py", line 1045, in draw
> 
> tick.draw(renderer)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\axis.py", line 239, in draw
> 
> self.label1.draw(renderer)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\text.py", line 591, in draw
> 
> ismath=ismath)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", 
> line 167, in draw_text
> 
> font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
> 
> TypeError: draw_glyphs_to_bitmap() takes no keyword arguments
> 
> 
> 
> ii) Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit 
> (Intel)] on win32
> 
> Type "copyright", "credits" or "license()" for more information.
> 
> 
> 
> 
> 
> Personal firewall software may warn about the connection IDLE
> 
> makes to its subprocess using this computer's internal loopback
> 
> interface.  This connection is not visible on any external
> 
> interface and no data is sent to or received from the Internet.
> 
> 
> 
> 
> 
> IDLE 2.6.1  
> 
> >>> import networkx as nx
> 
> >>> G=nx.Graph()
> 
> >>> G.add_node(1)
> 
> >>> G.add_nodes_from([2,3])
> 
> >>> H=nx.path_graph(10)
> 
> >>> G.add_nodes_from(H)
> 
> >>> G.add_node(H)
> 
> >>> G.add_edge(1,2)
> 
> >>> G.draw()
> 
> 
> 
> Traceback (most recent call last):
> 
>   File "", line 1, in 
> 
> G.draw()
> 
> AttributeError: 'Graph' object has no attribute 'draw'
> 
> >>> import matplotlib.pyplot as plt
> 
> >>> plt.show()
> 
> >>> nx.draw(G)
> 
> >>> plt.show()
> 
> Exception in Tkinter callback
> 
> Traceback (most recent call last):
> 
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
> 
> return self.func(*args)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
> line 236, in resize
> 
> self.show()
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_tkagg.py", 
> line 239, in draw
> 
> FigureCanvasAgg.draw(self)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\backends\backend_agg.py", 
> line 421, in draw
> 
> self.figure.draw(self.renderer)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\figure.py", line 898, in draw
> 
> func(*args)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\axes.py", line 1997, in draw
> 
> a.draw(renderer)
> 
>   File "C:\Python26\Lib\site-packages\matplotlib\artist.py", line 55, in 
> draw_wrapper
> 
> draw(artist, renderer, *args, **kwargs)
> 
>   File "C:\Python26\

Re: Matplotlib/Pylab Error

2012-12-11 Thread Mark Lawrence

On 10/12/2012 20:40, subhabangal...@gmail.com wrote:

Dear Group,

I am trying to enumerate few interesting errors on pylab/matplotlib.
If any of the learned members can kindly let me know how should I address them.



I think you'd get more responses if you post your questions on the 
matplotlib users mailing list.


--
Cheers.

Mark Lawrence.

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


PyParsing contextual suggestions?

2012-12-11 Thread Tim Chase
I've just started tinkering around with PyParsing and have unable to
come up with an answer to the following without deep diving into the
code.  Is there a way to do a partial parsing and then get the list
of possible things that could appear at the terminus of the parsing?
 My hope is to implement context-aware suggestions in a
readline.py/cmd.py application.  So I might have a grammar that
knows about filenames, and could then appropriately suggest
file-names at the given point in a parsing of the command.

Any hints on where I should read up?

Thanks,

-tkc


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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Steven D'Aprano
On Tue, 11 Dec 2012 02:35:29 -0600, Greg Donald wrote:

> On Mon, Dec 10, 2012 at 10:34:31PM -0700, Michael Torrie wrote:
>> I use a module I got from pypi called dateutil.  It has a nice
>> submodule called parser that can handle a variety of date formats with
>> good accuracy.  Not sure how it works, but it handles all the common
>> American date formats I've thrown at it.
> 
> from dateutil.parser import parse
> dt = parse( whatever )
> 
> I've throw all kind of date and timestamps at it.. have yet to see
> anything it won't parse.

The question is not "will it parse", but will it parse CORRECTLY?

What will it parse 11/12/10 as, and how do you know that is the intended 
date?


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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Greg Donald
On Tue, Dec 11, 2012 at 2:18 PM, Marc Christiansen
 wrote:
 parse('1. Januar 2013')
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib64/python3.3/site-packages/dateutil/parser.py", line 720, in 
> parse
> return DEFAULTPARSER.parse(timestr, **kwargs)
>   File "/usr/lib64/python3.3/site-packages/dateutil/parser.py", line 310, in 
> parse
> raise ValueError("unknown string format")
> ValueError: unknown string format

A parserinfo class can be passed to parse() for unknown locale strings.

 parse('1.2.2013') # ambiguous, I know
> datetime.datetime(2013, 1, 2, 0, 0) # should be datetime.datetime(2013, 2, 1, 
> 0, 0)

In [2]: parse('1.2.2013', dayfirst=True)
Out[2]: datetime.datetime(2013, 2, 1, 0, 0)



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


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread Greg Donald
On Tue, Dec 11, 2012 at 11:05 PM, Steven D'Aprano
 wrote:
> The question is not "will it parse", but will it parse CORRECTLY?
>
> What will it parse 11/12/10 as, and how do you know that is the intended
> date?

If it were me I'd look at more of the source dates I was tasked with
parsing and dial it in using the appropriate dayfirst, yearfirst, etc.
options.



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


Re: problem with usbtmc-communication

2012-12-11 Thread Jerry Hill
On Tue, Dec 11, 2012 at 1:58 AM, Jean Dubois  wrote:
>
> I found examples in the usbtmc kernel driver documentation (the
> examples there are given in C):
> http://www.home.agilent.com/upload/cmc_upload/All/usbtmc.htm?&cc=BE&lc=dut

Thanks for that link.  I think it explains how the driver works pretty
well.  I haven't done any work with devices like this, but I see a few
things in those docs that might help.

In their example code, they open the device with: open(“/dev/usbtmc1”,O_RDWR);

That's not exactly the same as what you've been doing.  I would try
opening the file this way in python:
usb_device = open('/dev/usbtmc1', 'w+', buffering=0)

That truncates the file after it opening it, and disables any
buffering that might be going on.

Then, I would try writing to the device with usb_device.write() and
usb_device.read().  read() attempts to read to end-of-file, and based
on the docs, the driver will work okay that way.  Doing that, along
with turning off buffering when you open the file, should eliminate
any issues with the driver failing to emit newlines someplace.

Personally, I would probably try playing with the device from python's
interactive interpreter.  I think that could shed a lot of light on
the behavior you're seeing.

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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Steven D'Aprano
On Tue, 11 Dec 2012 16:08:34 -0500, Dave Cinege wrote:

> On Tuesday 11 December 2012 03:12:19 Steven D'Aprano wrote:
> 
>> Is this intended as a ready-for-production class?
> 
> For me, yes. In production code.
> 
>> py> d = Thesaurus()
>> py> d['spam'] = {}
> 
> Maybe because spam is type dict instead of type thes???

Well duh. By the way, it's a dirty trick to cut out all context to try to 
make me seem like an idiot.

In context, you stated that Thesaurus "will search through nested objects
recursively when __getitem__ is called", but in fact that is not true. It 
does not do what you state it does.


> Remainder of your post, not productive, not worth my time.

Oh well I'm just hurt now. *sobs*

So, let's see now... I identified that your Thesaurus code:

* will fail silently;
* contains dead code that is never used;
* contains redundant code that is pointless;
* hides errors in the caller's code;

and you consider this "not productive, not worth my time". Code review 
with you must be *all* sorts of fun.



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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Steven D'Aprano
On Tue, 11 Dec 2012 16:08:34 -0500, Dave Cinege wrote:

> On Tuesday 11 December 2012 03:12:19 Steven D'Aprano wrote:
> 
>> Is this intended as a ready-for-production class?
> 
> For me, yes. In production code.
> 
>> py> d = Thesaurus()
>> py> d['spam'] = {}
> 
> Maybe because spam is type dict instead of type thes???

Well duh. By the way, it's a dirty trick to cut out all context to try to 
make me seem like an idiot.

In context, you stated that Thesaurus "will search through nested objects
recursively when __getitem__ is called", but in fact that is not true. It 
does not do what you state it does.


> Remainder of your post, not productive, not worth my time.

Oh well I'm just hurt now. *sobs*

So, let's see now... I identified that your Thesaurus code:

* will fail silently;
* contains dead code that is never used;
* contains redundant code that is pointless;
* hides errors in the caller's code;

and you consider this "not productive, not worth my time". Code review 
with you must be *all* sorts of fun.



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


Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

2012-12-11 Thread Chris Angelico
On Wed, Dec 12, 2012 at 5:34 PM, Steven D'Aprano
 wrote:
> So, let's see now... I identified that your Thesaurus code:
>
> * will fail silently;
> * contains dead code that is never used;
> * contains redundant code that is pointless;
> * hides errors in the caller's code;
>
> and you consider this "not productive, not worth my time". Code review
> with you must be *all* sorts of fun.

He never asked for code review :)

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