Re: Tkinter question

2010-04-23 Thread eb303
On Apr 22, 5:55 pm, Rotwang  wrote:
> James Mills wrote:
> > On Wed, Apr 21, 2010 at 8:45 PM, Rotwang  wrote:
>
> >> [...]
>
> >>From reading the documentation myself (pydoc)...
>
> > It would seem your only option is to make a thread
> > out of this (not my preferred way - I was hoping it was
> > possible to poll the Tk event system...).
>
> Thanks, I don't know anything about threading at the moment but I'll
> look into it.

>From my experience, mixing Tkinter with threads is a bad idea. As most
GUI toolkits, it really doesn't like to be manipulated from different
threads, so you might end up getting weird problems or even crashes.

By the way, did you try to remove the line out.mainloop() from your
'draw' function? This is the line that blocks the IDLE GUI, since it
initiates a secondary event loop that will only exit when you do a
out.quit(), so that might be a solution.

> BTW, another problem: whenever I call a widget.quit() method, the widget
> in question crashes. IDLE carries on working but the widget window stays
> there, not responding, and if I tell my OS to kill it then IDLE
> restarts. Is this a bug? I'm using Windows 7 and Python 2.6.4.

The 'quit' method just exits the mainloop. It doesn't destroy the
widget. So if your application doesn't actually exit, the widget will
just stay there. If you want to destroy the it too, you have to call
explicitely widget.destroy().

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


Re: question about an exciting gotcha for unittests (and elsewhere) ...

2010-04-23 Thread Cameron Simpson
On 23Apr2010 16:15, I wrote:
| On 23Apr2010 15:37, I wrote:
| |   class Backend(object):
| | def serialise(self, value):
| |   ''' Convert a value for external string storage.
| |   '''
| |   if isinstance(value, Node): [...]
| | return ":%s:%s" % (value.type, value.name)
| |   t = type(value)
| |   assert t in (str,int), repr(t)+" "+repr(value)+" "+repr(Node)
| |   [...]
| [...]
| |   AssertionError:  HOST:foo:{} 
| | 
| | Experienced users will see at once what's happened: I've made a Node
| | myself in the test using the local class, and the Node class is thus
| | __main__.Node. However, my sql Backend class has independently imported
| | the "Node" and "Backend" classes from "cs.nodedb.node". So when _it_
| | calls serialise(), "Node" is "cs.nodedb.node.Node".
| [...]
| 
| A walk around the block and I'm thinking the olny sane way to do this is
| to use relative imports, to always get the sqla.py module from the same
| place as the node.py where the test lives, and likewise in sqla.py
| to relatively import node.py to get its matching file.
| 
| And then to explicitly import from "node" etc in the test to get the
| right names.
| 
| However, that means the unit test knows its own filename/module-name.

Further down this path I've done the following:

  node.py's unittest now doesn't use the sqla module at all, and passes its
self tests with a no-op Backend

  sqla.py's unittest subclasses node.py's unittest and replaces the setUp()
with one that uses a Backend_SQLAlchemy object

  the imports at the top of sqla.py now read:
from . import NodeDB, Backend
from .node import TestAll as NodeTestAll
  to remove special knowledge of the package name

  I was invoking the self test like this:
DEBUG=1 dev python2.6 ./lib/cs/nodedb/sqla.py
  which breaks relative imports. Now I do this:
DEBUG=1 dev python2.6 -m cs.nodedb.sqla
  and it is all good. ("dev" is a wrapper to set PYTHONPATH
  to use my work area, etc).

Since I've convinced myself that my previous practices were inherently
instantiating node.py twice with different names, I guess I can say my
problem is solved, for some definition of the term:-)

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

Every program has at least one bug and can be shortened by at least one
instruction -- from which, by induction, it is evident that every
program can be reduced to one instruction that does not work.
- Ken Arnold
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux servers, network and file names

2010-04-23 Thread Rebelo

Infinity77 wrote:

Hi All,

I apologize in advance if this sounds like a stupid question but I am
really no expert at all in network things, and I may be looking in the
wrong direction altogether.

At work we have a bunch of Linux servers, and we can connect to them
with our Windows PCs over a network. Now, let's assume we only have
one Linux server, let's call it SERVER. Everyone of us, on our Windows
PC, can map this server as a network drive choosing whatever Windows
"drive letter" he wants. For example, I could map SERVER to be "Y:/",
my colleague might call it "Z:/" and so on.

The problem arises in one of my little applications, which allows the
user to choose a file living in SERVER and do some calculations with
it; then, this file name gets saved in a common database (common in
the sense that it is shared between Windows users, ourselves). Now, I
choose this file myself, the FileDialog (a window representing a file
selector dialog) will return something like this (let's ignore the
back/forward slashes, this is not an issue):

Y:/Folder/FileName.txt

If my colleague does it, he will get:

Z:/Folder/FileName.txt

Even if I am able to work out the server name using the Windows drive
letter (and I was able to do it, now I don't remember anymore how to
do it), what I get is:

For me:  //SERVER/gavana/Folder/FileName.txt
Colleague: //SERVER/Colleague/Folder/FileName.txt

So, no matter what I do, the file name stored in the database is user-
dependent and not universal and common to all of us.

Am I missing something fundamental? I appreciate any suggestion, even
a Windows-only solution (i.e., based on PyWin32) would be perfect.

Thank you in advance for your help.

Andrea.



why don't you store servers path to file in a database?
example:
//SERVER/Public/file.txt

this way you can use python to list files in share without the need for 
mapping drives, if permissions are set correctly.


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


Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

2010-04-23 Thread Bryan
Steven D'Aprano wrote:
> John Nagle wrote:
> >    Is "nlargest" smart enough to decide when it's cheaper to track the
> > N largest entries on a linear pass through the list than to sort?

It *always* does a linear pass through the list (linear, that is in
the length of the entire list). It tracks the n largest elements seen
so far in a heap.

> Doesn't appear to do so. From Python 3.1:

I think you're mis-reading it.

> def nlargest(n, iterable):
>     """Find the n largest elements in a dataset.
>
>     Equivalent to:  sorted(iterable, reverse=True)[:n]
>     """
>     it = iter(iterable)
>     result = list(islice(it, n))
>     if not result:
>         return result
>     heapify(result)
>     _heappushpop = heappushpop
>     for elem in it:
>         _heappushpop(result, elem)
>     result.sort(reverse=True)
>     return result

That doesn't sort, or even heapify, the whole list. It keeps the
largest n elements seen so far in the 'result' heap, smallest on top.

Note the doc for heappushpop: "Push item on the heap, then pop and
return the smallest item from the heap." Thus the 'result' heap stays
of size n.

The final result.sort() is just so the returned list is sorted, and
assuming that's a requirement, I think the algorithm is asymptotically
the best a comparison-based method can do, regardless of whether the
length of the entire sequence dominates n. I figure the worst-case run
time is Theta(s lg(n)) where s in the length of the sequence.

> Interestingly, nsmallest does use two different algorithms,
> depending on how many items you ask for. See the source code.

That is interesting. The above algorithm for nlargest is better, but
to use it for nsmallest requires a largest-on-top heap, which the
module does not bother to implement.


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


question about an exciting gotcha for unittests (and elsewhere) ...

2010-04-23 Thread Cameron Simpson
I've run into a problem unittesting something I'm writing.

I have a little node tracking class I'm using to track items and
attributes.  An item is a "Node" object, and the collection is a
"NodeDB".

So I'm writing some unittests, thus:

  class Node(dict): [...]
  class NodeDB(dic): [...]
  class Backend(object):
def serialise(self, value):
  ''' Convert a value for external string storage.
  '''
  if isinstance(value, Node): [...]
return ":%s:%s" % (value.type, value.name)
  t = type(value)
  assert t in (str,int), repr(t)+" "+repr(value)+" "+repr(Node)
  [...]

  class TestAll(unittest.TestCase):
def setUp(self):
  from cs.nodedb.sqla import Backend_SQLAlchemy
  self.backend=Backend_SQLAlchemy('sqlite:///:memory:')
  self.db=NodeDB(backend=self.backend)
def test01serialise(self):
  H = self.db.newNode('HOST', 'foo')
  for value in 1, 'str1', ':str2', '::', H:
s = self.backend.serialise(value)
assert type(s) is str
self.assert_(value == self.backend.deserialise(s))
[...]

  if __name__ == '__main__':
import sqlalchemy
print 'SQLAlchemy version =', sqlalchemy.__version__
unittest.main()

and it's failing. I've traced the failure cause, ending up with this
assertion message from the end of serialise() above:

  AssertionError:  HOST:foo:{} 

Experienced users will see at once what's happened: I've made a Node
myself in the test using the local class, and the Node class is thus
__main__.Node. However, my sql Backend class has independently imported
the "Node" and "Backend" classes from "cs.nodedb.node". So when _it_
calls serialise(), "Node" is "cs.nodedb.node.Node".

And lo, the:

  if isinstance(value, Node):

test at the top of serialise() fails.

What's a sensible way of doing this correctly?

I _don't_ want to duck-type the Node and merely test for "type" and "name"
values, because I want to be rather picky about what gets into the backend
database - the wrong types indicate bad app code, and should not be allowed
to introduce corrupt database values.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

That particular mistake will not be repeated.  There are plenty of mistakes
left that have not yet been used. - Andy Tanenbaum 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux servers, network and file names

2010-04-23 Thread Martin P. Hellwig

On 04/22/10 15:13, Infinity77 wrote:



For me:  //SERVER/gavana/Folder/FileName.txt
Colleague: //SERVER/Colleague/Folder/FileName.txt

So, no matter what I do, the file name stored in the database is user-
dependent and not universal and common to all of us.

If that user dependent part happens to be equal to the login name, then 
what you could do is replace is with the username variable (I believe 
%USERNAME% on windows) instead.


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


Smtpd module

2010-04-23 Thread Johny
I would like to use smtpd module to write very simple smtp server but
this server must:

1. accept several connections at the same time( like a forking server)
2. have basic authentication  that is it must understand AUTH command.

Does anyone know if the smtpd module have both?
Thanks

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


Re: Calling multiple programs with subprocess

2010-04-23 Thread Bryan
amit asked:
> How does one go about calling multiple programs using subprocess?
>
> This is the program flow:
>
> C:\> wrenv.exe
> C:\> make clean
> ..
>
> The 'wrenv.exe' is necessary since it sets up the proper environment
> for building. How do I use subprocess to execute 'wrenv.exe' and then
> the 'make clean' command.
>
> Any help is appreciated.

In this case I don't see that you need to call multiple programs
simultaneously. You call 'wrenv.exe', then when and if it completes
successfully you call 'make clean'. Calling multiple programs
sequentially should be straightforward. What, specifically, is going
wrong?

Python's subprocess module rocks on Unix, and provides some useful
corresponding features that are easily available on MS Windows. If
your job is to rock on Windows, don't commit to modules devoted to
rockin' on Unix. Python has multiple ways to run "wrenv.exe", then
"make clean". In particular, check out os.system.


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


Making special method names, work with __getattr__

2010-04-23 Thread Antoon Pardon
The following is a proof of concept. The idea is to have variables that
represent symbolic names/expressions, you can work with like ordinary
values, but that can be evaluated later.

This is the code:



import operator
from functools import partial

class Expression (object) :
  def __add__(self, term):
return Binary(self, operator.__add__, term)

  def __getattr__(self, name):
op = getattr(operator, name)
return partial(Binary, self, op)

class Binary (Expression) :
  def __init__(self, left, op, right):
self.left = left
self.operator = op
if not isinstance(right, Expression):
  right = Value(right)
self.right = right

  def eval(self, dct):
left = self.left.eval(dct)
right = self.right.eval(dct)
return self.operator(left, right)


class Symbol (Expression):
  def __init__(self, name):
self.name = name

  def eval(self, dct={}):
return dct[self.name]


class Value (Expression):
  def __init__(self, val):
self.value = val

  def eval(self, dct={}):
return self.value

def test():
  dct = {"var1" : 5, "var2" : 7}
  val1 = Symbol("var1")
  val2 = Symbol("var2")
  print val1.eval(dct)
  sum = val1 + 3
  print sum.eval(dct)
  sum = sum + val2
  print sum.eval(dct)
  product = val1 * 7
  print product.eval(dct)

test()

--

The result I get is:

5
8
15
Traceback (most recent call last):
  File "Symbolics", line 54, in 
test()
  File "Symbolics", line 51, in test
product = val1 * 7
TypeError: unsupported operand type(s) for *: 'Symbol' and 'int'

What I had hoped for was, that the line:
  
  product = val1 * 7

would be translated into something like

  product = val1.__mul__(7)

which would then be treated by the __getattr__ of the Expression superclass.

That doesn't seem to happen.


Does anyone have another idea, so I can get this to work without having
to manually add all numeric special methods to the Expression class.

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


Re: when should I explicitly close a file?

2010-04-23 Thread Adam Tauno Williams
On Fri, 2010-04-23 at 16:29 +1200, Lawrence D'Oliveiro wrote:
> In message , Chris 
> Rebert wrote:
> > On Wed, Apr 21, 2010 at 5:53 PM, Lawrence D'Oliveiro wrote:
> >> In message <4bc9aad...@dnews.tpgi.com.au>, Lie Ryan wrote:
> >>> Since in python nothing is guaranteed about implicit file close ...
> >> It is guaranteed that objects with a reference count of zero will be
> >> disposed.
> >> In my experiments, this happens immediately.
> > Experiment with an implementation other than CPython and prepare to be
> > surprised.
> Any implementation that doesn’t do reference-counting is brain-damaged.

Why?  There are much better ways to do memory management / garbage
collection;  especially when dealing with large applications.

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


FW: help req debugging

2010-04-23 Thread sanam singh









hi,
i am using wingware to debug python.however i also want to debug my c modules 
which have been called in my python script simultaneously. so i have followed 
instructions given on 
http://www.wingware.com/doc/howtos/debugging-extension-modules-on-linux .
as a result i launch my python script in wingide and successfully attach it to 
gdb.when i debug my python code i get following in gdb :
[New Thread 0xa62eab90 (LWP 3957)]
[New Thread 0xa5ae9b90 (LWP 3958)]
[New Thread 0xa52e8b90 (LWP 3959)]
[New Thread 0xa4ae7b90 (LWP 3960)]
[New Thread 0xa42e6b90 (LWP 3961)]
[New Thread 0xa3ae5b90 (LWP 3962)]
[New Thread 0xa32e4b90 (LWP 3963)]

but the problem is that when in wingide the c module is called gdb doesnt take 
me into the respective c module.
i am new to gdb please help me where am i going wrong?
Thanks in advance.

Regards,
Sanam
  
Hotmail: Trusted email with Microsoft’s powerful SPAM protection. Sign up now.  
  
_
Hotmail: Free, trusted and rich email service.
https://signup.live.com/signup.aspx?id=60969-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when should I explicitly close a file?

2010-04-23 Thread Alf P. Steinbach

* Adam Tauno Williams:

On Fri, 2010-04-23 at 16:29 +1200, Lawrence D'Oliveiro wrote:
In message , Chris 
Rebert wrote:

On Wed, Apr 21, 2010 at 5:53 PM, Lawrence D'Oliveiro wrote:

In message <4bc9aad...@dnews.tpgi.com.au>, Lie Ryan wrote:

Since in python nothing is guaranteed about implicit file close ...

It is guaranteed that objects with a reference count of zero will be
disposed.
In my experiments, this happens immediately.

Experiment with an implementation other than CPython and prepare to be
surprised.

Any implementation that doesn’t do reference-counting is brain-damaged.


Why?


Depends on what the statement was meant to mean.

But for a literal context-free interpretation e.g. the 'sys.getrefcount' 
function is not documented as CPython only and thus an implementation that 
didn't do reference counting would not be a conforming Python implementation.


Whether it uses reference counting to destroy objects at earliest opportunity is 
another matter.




 There are much better ways to do memory management / garbage
collection;  especially when dealing with large applications.


Depends on whether you're talking about Python implementations or as a matter of 
general principle, and depends on how you define "better", "large" and so on.


On its own it's a pretty meaningless statement.

But although a small flame war erupted the last time I mentioned this, I think a 
case can be made that Python is not designed for programming-in-the-large. And 
that the current CPython scheme is eminently suitable for small scripts. But it 
has its drawbacks, especially considering the various ways that stack frames can 
be retained, and considering the documentation of 'gc.garbage', ...


  "Objects that have __del__() methods and are part of a reference cycle cause
  the entire reference cycle to be uncollectable, including objects not
  necessarily in the cycle but reachable only from it."

... which means that a programming style assuming current CPython semantics and 
employing RAII can be detrimental in a sufficiently large system.



Cheers & hth.,

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


Re: question about an exciting gotcha for unittests (and elsewhere) ...

2010-04-23 Thread Peter Otten
Cameron Simpson wrote:

> and it's failing. I've traced the failure cause, ending up with this
> assertion message from the end of serialise() above:
> 
>   AssertionError:  HOST:foo:{}'cs.nodedb.node.Node'>
> 
> Experienced users will see at once what's happened: I've made a Node
> myself in the test using the local class, and the Node class is thus
> __main__.Node. However, my sql Backend class has independently imported
> the "Node" and "Backend" classes from "cs.nodedb.node". So when _it_
> calls serialise(), "Node" is "cs.nodedb.node.Node".
> 
> And lo, the:
> 
>   if isinstance(value, Node):
> 
> test at the top of serialise() fails.
> 
> What's a sensible way of doing this correctly?

Move the unit tests into a separate script and have that import the module 
cs.nodedb.node. 

In general, avoid importing a module and at the same time using it as the 
main script. When persistent objects are involved "the same time" can even 
spread over distinct runs of separate scripts accessing the same data.

Obvious? But you asked for a /sensible/ way.

Peter

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


Re: Windows debugging symbols for python 2.5.4 and pywin32 214

2010-04-23 Thread Alexandre Fayolle
On Friday 23 April 2010 08:36:01 Mark Hammond wrote:
> On 22/04/2010 7:23 AM, Alexandre Fayolle wrote:
> > Hi everyone,
> >
> > I have a production server running a Windows Service written in Python,
> > which uses python 2.5.4 (yes I know it is old, but I am somewhat stuck
> > with this for now) and pywin32 214.
> >
> > Given a set of manipulations, I get a stack overflow in the service, and
> > a bad crash. The same operation when running without
> > win32serviceutil.ServiceFramework does not trigger the bug. I'm looking
> > for some debugging tools (debug build of the interpreter and the pywin32
> > libraries) that some good soul could have kept from a previous debugging
> > session to try to get a C stack trace and understand what causes this.
> 
> I expect the problem might be that pythonservice.exe isn't linked with a
> large enough stack - python itself builds with a larger than default
> stack.  That difference could cause a recursive function to hard-crash
> before Python itself detected the recursion as being too deep.
> 
> You could test this by playing with the sys.setrecursionlimit function -
> at some limit I expect you would find the hard-crash would be replaced
> with a max recursion exception.  Let me know if that is the case and
> I'll be sure to adjust the stack size for the next pywin32 build.
> 
> > Any hint towards what could cause that stack overflow would be welcome
> > too. The application is multithreaded (and uses pyro and twisted). I can
> > provide more information for the curious.
> 
> Some parts of twisted are written such that server responses are
> processed recursively, and very large input can cause the recursion
> limit to be hit.  I'm still occasionally bitten by this in the IMAP
> client code...

Thank you for this very helpful information. I've found on my side that 
upgrading to python2.6 will prevent the crash from happening in the reported 
conditions, and used this as a fix (currently running extensive tests to be on 
the safe side). 

Runnning 2.6 will among other things enable me to use a recent VS compiler to 
rebuild stuff if required. 

I'm very interested in a pywin32 build with a larger stack for 
pythonservice.exe, as this would seriously increase my confidence level and 
improve my sleep quality :-) 

-- 
Alexandre Fayolle  LOGILAB, Paris (France)
Formations Python, CubicWeb, Debian :  http://www.logilab.fr/formations
Développement logiciel sur mesure :  http://www.logilab.fr/services
Informatique scientifique:   http://www.logilab.fr/science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter question

2010-04-23 Thread Rotwang

eb303 wrote:

On Apr 22, 5:55 pm, Rotwang  wrote:


[...]



From my experience, mixing Tkinter with threads is a bad idea. As most
GUI toolkits, it really doesn't like to be manipulated from different
threads, so you might end up getting weird problems or even crashes.

By the way, did you try to remove the line out.mainloop() from your
'draw' function?


I didn't. How do I get Python to display the draw window, other than by 
using mainloop()?




This is the line that blocks the IDLE GUI, since it
initiates a secondary event loop that will only exit when you do a
out.quit(), so that might be a solution.


BTW, another problem: whenever I call a widget.quit() method, the widget
in question crashes. IDLE carries on working but the widget window stays
there, not responding, and if I tell my OS to kill it then IDLE
restarts. Is this a bug? I'm using Windows 7 and Python 2.6.4.


The 'quit' method just exits the mainloop. It doesn't destroy the
widget. So if your application doesn't actually exit, the widget will
just stay there. If you want to destroy the it too, you have to call
explicitely widget.destroy().


That worked like a charm, thanks!

Here's another problem I've run into today: I've just added a bit of 
code so that it's possible to resize the draw window and the contents 
will be resized automatically. The method now looks something like this:


out = Tkinter.Tk()
slave = Tkinter.Canvas(out, width = wh[0], height = wh[1])
slave.grid()
# I put the canvas widget inside a tk widget instead of just
# using the former because I want keypresses to do things, and
# it doesn't seem to be possible to bind keyboard events to a
# canvas
# draw something
slave.pack()

def resize(b):
wh[:] = [b.width, b.height]
slave.config(width = wh[0], height = wh[1])
# resize the contents of slave

out.bind('', resize)
out.mainloop()


The trouble is, when I call the method the window it spawns slowly grows 
larger, until I move or resize it myself by grabbing one of the edges; 
after this everything works as intended. If I add the line "print wh" 
after "wh[:] = [b.width, b.height]", the output looks like this (the 
default value of wh is [640,480]:


[644, 484]
[648, 488]
[648, 488]
[648, 488]
[652, 492]
[652, 492]
[652, 492]
[656, 496]
[656, 496]
[656, 496]
[660, 500]
etc.

My only guess as to why this is happening is that Tkinter is resizing 
out to be 4 pixels wider and taller than slave, and the line 
"slave.config(...)" consequently leads to resize being called again. But 
this doesn't explain why it stops happening when I resize the window 
intentionally, nor why the window apparently only gets larger every 
third time resize is called. The problem goes away if I replace "wh[:] = 
[b.width, b.height]" with


wh[:] = [b.width - 4, b.height - 4]

but this seems like a rather ad-hoc and ugly solution, and I'd rather 
understand what's going on. Can anyone help?

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


Re: question about an exciting gotcha for unittests (and elsewhere) ...

2010-04-23 Thread Cameron Simpson
On 23Apr2010 13:25, Peter Otten <__pete...@web.de> wrote:
| Cameron Simpson wrote:
| > and it's failing. I've traced the failure cause, ending up with this
| > assertion message from the end of serialise() above:
| > 
| >   AssertionError:  HOST:foo:{}'cs.nodedb.node.Node'>
| > 
| > Experienced users will see at once what's happened: I've made a Node
| > myself in the test using the local class, and the Node class is thus
| > __main__.Node. However, my sql Backend class has independently imported
| > the "Node" and "Backend" classes from "cs.nodedb.node". So when _it_
| > calls serialise(), "Node" is "cs.nodedb.node.Node".
| >
| > And lo, the:
| >   if isinstance(value, Node):
| > test at the top of serialise() fails.
| > 
| > What's a sensible way of doing this correctly?
| 
| Move the unit tests into a separate script and have that import the module 
| cs.nodedb.node. 

Hmm. I have been very attracted by the idea of having the unittest in
the module itself, and run if I "run" the module alone (instead of
importing it).

Conversely, I've also got a few modules that are standalone programs
and running _then_ runs the app, not a bunch of tests.

Having the tests elsewhere would solve the problem as you say; an import
of the module is what "real" code will be doing and, as my misadventure
above demonstrates, that's a different thing as far as namespaces go.

| In general, avoid importing a module and at the same time using it as the 
| main script.

Fsir enough - that's a succinct description of what I did wrong.

| When persistent objects are involved "the same time" can even 
| spread over distinct runs of separate scripts accessing the same data.

Good point; this is another thing to add to my reluctance to use
persistent objects. Persistent _data_, sure, and my little nodedb
package is exactly such an animal, but not persistent objects.

| Obvious? But you asked for a /sensible/ way.

Indeed. Thanks for the suggestion. I'll try to pursue it; the rest of my
thread shows I've worked around some of the problem but the workaround
still depends somewhat on the package internal dependencies and going
your way with a separate test script that does a proper import will
avoid that weakness.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

Thought: Why does man kill?  He kills for food.  And not only for
food: frequently there must be a beverage.  - Woody Allen
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: eGenix mxODBC Zope Database Adapter 2.0.1

2010-04-23 Thread eGenix Team: M.-A. Lemburg

ANNOUNCEMENT

 mxODBC Zope Database Adapter

Version 2.0.1

 for Zope and the Plone CMS

Available for Zope 2.12 and later on
Windows, Linux, Mac OS X, FreeBSD and other platforms

This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mxODBC-Zope-DA-2.0.1-GA.html


INTRODUCTION

The eGenix mxODBC Zope Database Adapter allows you to easily connect
your Zope or Plone installation to just about any database backend on
the market today, giving you the reliability of the commercially
supported eGenix product mxODBC and the flexibility of the ODBC
standard as middle-tier architecture.

The mxODBC Zope Database Adapter is highly portable, just like Zope
itself and provides a high performance interface to all your ODBC data
sources, using a single well-supported interface on Windows, Linux,
Mac OS X, FreeBSD and other platforms.

This makes it ideal for deployment in ZEO Clusters and Zope hosting
environments where stability and high performance are a top priority,
establishing an excellent basis and scalable solution for your Plone
CMS.


NEWS

We are pleased to announce a new version 2.0.1 of our mxODBC Zope DA
product.

With the patch level 2.0.1 release we have backported the mxODBC Zope DA
product to also run on Zope 2.10, 2.11 as well as Python 2.4. This was
done to meet popular demand, since Plone 3 still uses these Zope and
Python versions.

The mxODBC Zope DA is now fully compatible with all recent Plone
versions, including the upcoming Plone 4.0 release. Please see the
mxODBC Zope DA documentation for details on how to install the
product for use in Plone.

Compared to the previous 1.0 version of the mxODBC Zope DA, the 2.0
version includes these enhancements:

 * Includes mxODBC 3.1 with updated support for many current ODBC
   drivers, giving you more portability and features for a wider
   range of database backends.

 * Mac OS X 10.6 (Snow Leopard) support.

 * Python 2.4, 2.5 and 2.6 support.

 * Zope 2.10, 2.11 and 2.12 support.

 * Zero maintenance support to automatically reconnect the
   Zope connection after a network or database problem.

 * More flexible Unicode support with options to work with
   pure Unicode, plain strings or mixed setups - even for
   databases that don't support Unicode

 * Automatic and transparent text encoding and decoding

 * More flexible date/time support including options to work
   with Python datetime objects, mxDateTime, strings or tuples

 * New decimal support to have the Zope DA return decimal
   column values using Python's decimal objects.

 * Fully eggified to simplify easy_install and zc.buildout based
   installation


UPGRADING

Licenses purchased for version 2.0.0 of the mxODBC Zope DA will continue
to work with the 2.0.1 patch level release.

If you have already bought mxODBC Zope DA 1.0.x licenses, we offer you
a time limited upgrade option:

 * If you have purchased the licenses between 2009-06-01 and 2009-12-31
   you can get a 20% discount on the full price of version 2.0.

 * If you have purchased the licenses after 2010-01-01
   you can get a 40% discount on the full price of version 2.0.

This offer is time limited until 2010-09-30.

Please write to sa...@egenix.com for details on how to get the
needed discount coupons.


MORE INFORMATION

For more information on the mxODBC Zope Database Adapter, licensing
and download instructions, please visit our web-site:

http://www.egenix.com/products/zope/mxODBCZopeDA/

You can buy mxODBC Zope DA licenses online from the eGenix.com shop at:

http://shop.egenix.com/



Thank you,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Apr 23 2010)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


py3 tkinter Text accepts what bytes?

2010-04-23 Thread Matthias Kievernagel
Hello,

I stumbled upon this one while porting some of my programs
to Python 3.1. The program receives messages from a socket
and displays them in a tkinter Text. Works fine in Python 2
and Python 3.1. The problems arrived when I wanted to know
the details...

First surprise: Text.insert accepts not only str
but also bytes.

So I looked into the sources to see how it is done.
I found no magic in 'tkinter.__init__.py'. All python
objects seem to go unchanged to _tkinter.c.
There they are turned into Tcl objects using Tcl_NewUnicodeObj
(for str) and Tcl_NewStringObj (for bytes).
The man page for Tcl_NewStringObj says that it creates
a tcl string from utf-8 encoded bytes.
So I continued to test...

Second surprise: Text.insert also works for latin-1 encoded bytes.
It even works with mixed utf-8 and latin-1 encoded bytes.
At least it works for me.

Anyone can enlighten me, where this magic is done?
Is it tcl magic or did I miss something in the python sources?
Is this somewhere documented?

Thanks for any hints,
Matthias Kievernagel

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


Re: Linux servers, network and file names

2010-04-23 Thread Infinity77
Hi Martin & All,

On Apr 23, 9:50 am, "Martin P. Hellwig" wrote:
> On 04/22/10 15:13, Infinity77 wrote:
> 
>
> > For me:  //SERVER/gavana/Folder/FileName.txt
> > Colleague: //SERVER/Colleague/Folder/FileName.txt
>
> > So, no matter what I do, the file name stored in the database is user-
> > dependent and not universal and common to all of us.
>
> If that user dependent part happens to be equal to the login name, then
> what you could do is replace is with the username variable (I believe
> %USERNAME% on windows) instead.

The funny thing is that the user dependent part *is* the login name,
but not the Windows one, it is the *Linux SERVER* one, and no mapping
has been done between Windows logins and Linux usernames. IT...

Anyway, it seems like Tim's suggestion is working (for the moment), so
I'll stick with it as this network/filenames issue has already taken
me a ridiculous amount of time to fix :-)

Thank you guys for your help!

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


Re: how does a queue stop the thread?

2010-04-23 Thread Steve
On Apr 21, 6:08 pm, kaiix  wrote:
> A simple thread pool example. My question is, since *MyThread.run*
> will loop endless, how does the thread know the time to quit? how does
> the *queue* notify the thread? is there any shared variables, like a
> *lock*?
>
> When I set daemon false, it stays in the loop, not quit any more.
> what's the role does the daemon state plays?
>
> code:
> --- 
> -
> import Queue
> import threading
>
> def do_some_thing(x):
>     print int(x)
>
> class MyThread(threading.Thread):
>     def __init__(self, queue):
>         threading.Thread.__init__(self)
>         self.queue = queue
>
>     def run(self):
>         while True:
>             params = self.queue.get()
>             do_some_thing(params)
>             self.queue.task_done()
>
> q = Queue.Queue()
>
> for i in range(1, 5):
>     t = MyThread(q)
>     t.setDaemon(True)
>     t.start()
>
> for x in range(10):
>     q.put(x)
>
> q.join()

Here's a slightly different example that demonstrates more clearly how
to end each thread.

http://effbot.org/librarybook/queue.htm

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


Re: Tkinter question

2010-04-23 Thread eb303
On Apr 23, 1:58 pm, Rotwang  wrote:
> eb303 wrote:
> > On Apr 22, 5:55 pm, Rotwang  wrote:
>
> >> [...]
>
> > From my experience, mixing Tkinter with threads is a bad idea. As most
> > GUI toolkits, it really doesn't like to be manipulated from different
> > threads, so you might end up getting weird problems or even crashes.
>
> > By the way, did you try to remove the line out.mainloop() from your
> > 'draw' function?
>
> I didn't. How do I get Python to display the draw window, other than by
> using mainloop()?

Well, mainloop doesn't actually display anything. It's just the event
loop for tk. So since you run your program within IDLE, there is
already one running. What does it do if you delete the mainloop()
line? Doesn't your window appear at all?

> > This is the line that blocks the IDLE GUI, since it
> > initiates a secondary event loop that will only exit when you do a
> > out.quit(), so that might be a solution.
>
> >> BTW, another problem: whenever I call a widget.quit() method, the widget
> >> in question crashes. IDLE carries on working but the widget window stays
> >> there, not responding, and if I tell my OS to kill it then IDLE
> >> restarts. Is this a bug? I'm using Windows 7 and Python 2.6.4.
>
> > The 'quit' method just exits the mainloop. It doesn't destroy the
> > widget. So if your application doesn't actually exit, the widget will
> > just stay there. If you want to destroy the it too, you have to call
> > explicitely widget.destroy().
>
> That worked like a charm, thanks!
>
> Here's another problem I've run into today: I've just added a bit of
> code so that it's possible to resize the draw window and the contents
> will be resized automatically. The method now looks something like this:
>
> out = Tkinter.Tk()
> slave = Tkinter.Canvas(out, width = wh[0], height = wh[1])
> slave.grid()
>         # I put the canvas widget inside a tk widget instead of just
>         # using the former because I want keypresses to do things, and
>         # it doesn't seem to be possible to bind keyboard events to a
>         # canvas
> # draw something
> slave.pack()

(Hope this line is a mistake: gridding *and* packing slave will
probably result in tk thinking for ages how it should display it in
its parent…)

>
> def resize(b):
>         wh[:] = [b.width, b.height]
>         slave.config(width = wh[0], height = wh[1])
>         # resize the contents of slave
>

You don't need at all to resize the slave explicitely. You should do
the following:
- Tell 'out' that its first row and first column should resize
themselves when the window is resized by doing:
out.grid_rowconfigure(1, weight=1)
out.grid_columnconfigure(1, weight=1)
- Make sure slave is actually put in the cell in first row and column,
and that all its sides will stick to the cell borders:
slave.grid(row=1, column=1, sticky='nswe')

If you do that, the slave.config in the resize function shouldn't be
needed anymore.

> out.bind('', resize)

If using the grid options, better do a slave.bind(…) here, which will
call the binding when the canvas is resized, which is obvioulsy when
you want to update its contents.

> out.mainloop()
>
> The trouble is, when I call the method the window it spawns slowly grows
> larger, until I move or resize it myself by grabbing one of the edges;
> after this everything works as intended. If I add the line "print wh"
> after "wh[:] = [b.width, b.height]", the output looks like this (the
> default value of wh is [640,480]:
>
> [644, 484]
> [648, 488]
> [648, 488]
> [648, 488]
> [652, 492]
> [652, 492]
> [652, 492]
> [656, 496]
> [656, 496]
> [656, 496]
> [660, 500]
> etc.
>
> My only guess as to why this is happening is that Tkinter is resizing
> out to be 4 pixels wider and taller than slave, and the line
> "slave.config(...)" consequently leads to resize being called again. But
> this doesn't explain why it stops happening when I resize the window
> intentionally, nor why the window apparently only gets larger every
> third time resize is called. The problem goes away if I replace "wh[:] =
> [b.width, b.height]" with
>
>         wh[:] = [b.width - 4, b.height - 4]
>
> but this seems like a rather ad-hoc and ugly solution, and I'd rather
> understand what's going on. Can anyone help?

You get the size for the outer window and apply it to the canvas
inside it. Since the canvas has a border which is 2 pixels wide by
default, this resizes the window containing it to take this border
into account. So your binding is called again, and so on… But using
the options to grid described above, there should never be any need to
resize the canvas explicitely.

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


Re: py3 tkinter Text accepts what bytes?

2010-04-23 Thread eb303
On Apr 23, 2:00 pm, Matthias Kievernagel 
wrote:
> Hello,
>
> I stumbled upon this one while porting some of my programs
> to Python 3.1. The program receives messages from a socket
> and displays them in a tkinter Text. Works fine in Python 2
> and Python 3.1. The problems arrived when I wanted to know
> the details...
>
> First surprise: Text.insert accepts not only str
> but also bytes.
>
> So I looked into the sources to see how it is done.
> I found no magic in 'tkinter.__init__.py'. All python
> objects seem to go unchanged to _tkinter.c.
> There they are turned into Tcl objects using Tcl_NewUnicodeObj
> (for str) and Tcl_NewStringObj (for bytes).
> The man page for Tcl_NewStringObj says that it creates
> a tcl string from utf-8 encoded bytes.
> So I continued to test...
>
> Second surprise: Text.insert also works for latin-1 encoded bytes.
> It even works with mixed utf-8 and latin-1 encoded bytes.
> At least it works for me.
>
> Anyone can enlighten me, where this magic is done?
> Is it tcl magic or did I miss something in the python sources?
> Is this somewhere documented?
>
> Thanks for any hints,
> Matthias Kievernagel

Let me guess: you're on Windows? ;-)

There is nothing in the Python sources that can help you here.
Everything is handled by the underlying tcl/tk interpreter. The
default encoding for strings in tcl happens to be UTF-8. So putting
bytestrings with a UTF-8 encoding in a Text widget will just work. For
latin-1 strings, there is some magic going on, but apparently, this
magic happens only on Windows (hence my guess above…), which seems to
recognize its default encoding by some means. My advice is: don't
count on it. It won't work on any other platform, and it might even
stop working on Windows one day.

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


"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS"

2010-04-23 Thread Naeem
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on
http://hollywood6y.blogspot.com/"SEXY CAMRON" "SEXY PRETTY
CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT HOLLYWWOD  CELEBERITIES"
"SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS" "SEXY CHINESE GIRLS" "SEXY
PAKISTANI GIRLS" "SEXY INDIAN GIRLS" on http://hollywood6y.blogspot.com/
"SEXY CAMRON" "SEXY PRETTY CAMERON" "SEXY HOT HOLLYWOOD STARS" "HOT
HOLLYWWOD  CELEBERITIES" "SEXY HOLLYWOOD GIRLS" "SEXY BIKINI GIRLS"
"SEXY CHINESE GIRLS" "SEXY PAKIST

Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

2010-04-23 Thread Grant Edwards
On 2010-04-22, D'Arcy J.M. Cain  wrote:
> On Thu, 22 Apr 2010 15:04:01 +0100
> Tim Golden  wrote:
>> > So please tell me if there is one or not. I really need this soon.
>> > Appreciate a lot.
>> 
>> Assuming top-k doesn't mean something obscurely statistical:
>
> You really shouldn't do people's homework for them.  It doesn't do
> them any favours.

Doing people's homework for them is a survival mechanism -- it reduces
the competence of potential new rivals.  :)

OTOH, if you do end up working with one of those a new grads with a
diploma but not a clue, you end up worse off because now you have to
teach them the problem solving skills they didn't learn in school.

-- 
Grant Edwards   grant.b.edwardsYow! I just had a NOSE
  at   JOB!!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Difficulty w/json keys

2010-04-23 Thread Red
My apologies for what is probably a simple question to most on this
group. However, I am new to python and very new to json.

I am trying to read in a json file from a twitter download. There are,
generally, two types of lines: those lines with "text" and the other
lines.  I am only interested in the lines with "text".  I am also only
interested in lines with "lang":"en", but I haven't gotten far enough
to implement that condition in the code snippets below.

I have gotten Option 2 below to sort of work.  It works fine for
'text', but doesn't work for 'lang'.

FWIW I am using Python 2.6.4

Can someone tell me what I'm doing wrong with the following code
snippets and/or point me toward an example of an implementation?

Many thanks for your patience.

-

import sys
import json

f = open(sys.argv[1])

#option 1

for line in f:
j = json.loads(line)
try:
'text' in j
print "TEXT:  ", j
except:
print "EXCEPTION:   ", j
continue
else:
text=j['text']
snip 




#option 2   does basically the same thing as option 1 , but also looks
for 'lang'

for line in f:
j = json.loads(line)
if 'text' in j:
if 'lang' in j:
lang = j['lang']
print "language", lang
text = j['text']
snip 

-- Two Sample Twitter lines -

{"text":"tech managers what size for your teams? better to have 10-20
ppl per manager or 2-5 and have the managers be more hands
on?","in_reply_to_user_id":null,"coordinates":null,"geo":null,"created_at":"Thu
Apr 22 17:35:42 + 2010","contributors":null,"source":"http://twitterfeed.com\"; rel=\"nofollow\">twitterfeed","in_reply_to_status_id":null,"place":null,"truncated":false,"in_reply_to_screen_name":null,"user":
{"favourites_count":
0,"profile_text_color":"00","time_zone":"Eastern Time (US &
Canada)","created_at":"Tue Oct 27 19:50:51 +
2009","statuses_count":
286,"notifications":null,"profile_link_color":"ff","description":"I
write code and talk to people.
","lang":"en","profile_background_image_url":"http://s.twimg.com/a/
1271891196/images/themes/theme1/bg.png","profile_image_url":"http://
s.twimg.com/a/1271891196/images/
default_profile_0_normal.png","location":"Near the
water.","contributors_enabled":false,"following":null,"geo_enabled":false,"profile_sidebar_fill_color":"e0ff92","profile_background_tile":false,"screen_name":"sstatik","profile_sidebar_border_color":"87bc44","followers_count":
40,"protected":false,"verified":false,"url":"http://
elliotmurphy.com/","name":"statik","friends_count":18,"id":
85646316,"utc_offset":-18000,"profile_background_color":"9ae4e8"},"id":
12651537502,"favorited":false}
{"delete":{"status":{"id":12650137902,"user_id":128090723}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


font change

2010-04-23 Thread Vikram Moule
Q1. I want to change the font of the menu . I want to write the menu items
like "File" in my native language.I was successful writing the text in the
window in my font. But I am not able to write the menu items in same font.
In fact I am not able to find how to change the font of the menu.
I am using wx module of wxPython.
Q2. A white window is seen when i execute the program it says
wxPython:stdout/stderr what is that ? and how to get rid of it ?
Thanks in advance.

-- 
Regrads ,
Vikram Moule
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py3 tkinter Text accepts what bytes?

2010-04-23 Thread Matthias Kievernagel
eb303  wrote:
> On Apr 23, 2:00 pm, Matthias Kievernagel 
> wrote:
>> Hello,
>>
>> I stumbled upon this one while porting some of my programs
>> to Python 3.1. The program receives messages from a socket
>> and displays them in a tkinter Text. Works fine in Python 2
>> and Python 3.1. The problems arrived when I wanted to know
>> the details...
>>
>> First surprise: Text.insert accepts not only str
>> but also bytes.
>>
>> So I looked into the sources to see how it is done.
>> I found no magic in 'tkinter.__init__.py'. All python
>> objects seem to go unchanged to _tkinter.c.
>> There they are turned into Tcl objects using Tcl_NewUnicodeObj
>> (for str) and Tcl_NewStringObj (for bytes).
>> The man page for Tcl_NewStringObj says that it creates
>> a tcl string from utf-8 encoded bytes.
>> So I continued to test...
>>
>> Second surprise: Text.insert also works for latin-1 encoded bytes.
>> It even works with mixed utf-8 and latin-1 encoded bytes.
>> At least it works for me.
>>
>> Anyone can enlighten me, where this magic is done?
>> Is it tcl magic or did I miss something in the python sources?
>> Is this somewhere documented?
>>
>> Thanks for any hints,
>> Matthias Kievernagel
> 
> Let me guess: you're on Windows? ;-)
> 
> There is nothing in the Python sources that can help you here.
> Everything is handled by the underlying tcl/tk interpreter. The
> default encoding for strings in tcl happens to be UTF-8. So putting
> bytestrings with a UTF-8 encoding in a Text widget will just work. For
> latin-1 strings, there is some magic going on, but apparently, this
> magic happens only on Windows (hence my guess above???), which seems to
> recognize its default encoding by some means. My advice is: don't
> count on it. It won't work on any other platform, and it might even
> stop working on Windows one day.
> 
> HTH
> - Eric -

Thanks for the info, Eric.
Funny it's working for me, because I'm on Linux.
So I'll take a look at the tcl/tk sources (8.4 btw.)
I don't like this magic at all, run-time errors waiting for you
at the most inconvenient moment.

Best regards,
Matthias Kievernagel.

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


Re: Difficulty w/json keys

2010-04-23 Thread Jim Byrnes

Red wrote:

My apologies for what is probably a simple question to most on this
group. However, I am new to python and very new to json.

I am trying to read in a json file from a twitter download. There are,
generally, two types of lines: those lines with "text" and the other
lines.  I am only interested in the lines with "text".  I am also only
interested in lines with "lang":"en", but I haven't gotten far enough
to implement that condition in the code snippets below.

I have gotten Option 2 below to sort of work.  It works fine for
'text', but doesn't work for 'lang'.

FWIW I am using Python 2.6.4

Can someone tell me what I'm doing wrong with the following code
snippets and/or point me toward an example of an implementation?

Many thanks for your patience.

-

import sys
import json

f = open(sys.argv[1])

#option 1

for line in f:
j = json.loads(line)
try:
'text' in j
print "TEXT:  ", j
except:
print "EXCEPTION:   ", j
continue
else:
text=j['text']
snip 




#option 2   does basically the same thing as option 1 , but also looks
for 'lang'

for line in f:
j = json.loads(line)
if 'text' in j:
if 'lang' in j:
lang = j['lang']
print "language", lang
text = j['text']
snip 

-- Two Sample Twitter lines -

{"text":"tech managers what size for your teams? better to have 10-20
ppl per manager or 2-5 and have the managers be more hands
on?","in_reply_to_user_id":null,"coordinates":null,"geo":null,"created_at":"Thu
Apr 22 17:35:42 + 2010","contributors":null,"source":"http://twitterfeed.com\"; rel=\"nofollow\">twitterfeed","in_reply_to_status_id":null,"place":null,"truncated":false,"in_reply_to_screen_name":null,"user":
{"favourites_count":
0,"profile_text_color":"00","time_zone":"Eastern Time (US&
Canada)","created_at":"Tue Oct 27 19:50:51 +
2009","statuses_count":
286,"notifications":null,"profile_link_color":"ff","description":"I
write code and talk to people.
","lang":"en","profile_background_image_url":"http://s.twimg.com/a/
1271891196/images/themes/theme1/bg.png","profile_image_url":"http://
s.twimg.com/a/1271891196/images/
default_profile_0_normal.png","location":"Near the
water.","contributors_enabled":false,"following":null,"geo_enabled":false,"profile_sidebar_fill_color":"e0ff92","profile_background_tile":false,"screen_name":"sstatik","profile_sidebar_border_color":"87bc44","followers_count":
40,"protected":false,"verified":false,"url":"http://
elliotmurphy.com/","name":"statik","friends_count":18,"id":
85646316,"utc_offset":-18000,"profile_background_color":"9ae4e8"},"id":
12651537502,"favorited":false}
{"delete":{"status":{"id":12650137902,"user_id":128090723}}}


I can't help you directly with your problem but have you seen this:

http://arstechnica.com/open-source/guides/2010/04/tutorial-use-twitters-new-real-time-stream-api-in-python.ars

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


Re: python 2.6 py2exe wx app fails

2010-04-23 Thread Robin Becker

On 22/04/2010 13:56, Robin Becker wrote:

I'm trying to move a wxPython application forward to 2.6, but although
the app runs fine in 2.6 when run directly when I build the app into an
exe using py2exe

I get this popup message

"application failed to initialize properly (0xc142)"

when I try to run the built exe.

The same application seems to build and run fine with python 2.5 py2exe.

I've tried various googled "solutions", but none seem to work. I do
notice that the standard py2exe samples/advanced test_wx.exe also fails
when built in this way.

I'm guessing this may be due to some obscure exe requirement with
manifests or something which varies depending on the base msvc library.
Any help much appreciated.


After much faffing about I managed to make this work, it seems that the 
instructions here


http://www.py2exe.org/index.cgi/Tutorial#Step52

aren't complete; for python 2.6 in addition to changing the runtime dll setup so 
that we copy MSVCR90.dll & Microsoft.VC90.CRT.manifest to a toplevel folder 
Microsoft.VC90.CRT, we also need to modify the embedded manifest to include an 
additional dependency


ie







that seems to make the exe workable again. I did actually see this in a google, 
but it was for a different version of the dll so did not work when I first tried it.

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


Re: Difficulty w/json keys

2010-04-23 Thread Rolando Espinoza La Fuente
On Fri, Apr 23, 2010 at 10:20 AM, Red  wrote:
[...]
> for line in f:
>        j = json.loads(line)
>        if 'text' in j:
>                if 'lang' in j:
>                        lang = j['lang']
>                        print "language", lang
>                text = j['text']

"lang" key is in "user" dict

>>> tweet['text']
'tech managers what size for your teams? better to have 10-20 ppl per
manager or 2-5 and have the managers be more hands on?'

>>> tweet['lang']
[...]
KeyError: 'lang'

>>> tweet['user']['lang']
'en'

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


Re: Difficulty w/json keys

2010-04-23 Thread J. Cliff Dyer

You need to know what your input data actually looks like, and the best
thing for that is a little bit of formatting.  I bet you can figure out
the problem yourself, once you see the structure of your data more
clearly.  I've reformatted the JSON for you to help out.


On Fri, 2010-04-23 at 07:20 -0700, Red wrote:
> -- Two Sample Twitter lines -
{
  "text":"tech managers what size for your teams? better to have 10-20
ppl per manager or 2-5 and have the managers be more hands
on?",
  "in_reply_to_user_id":null,
  "coordinates":null,
  "geo":null,
  "created_at":"Thu Apr 22 17:35:42 + 2010",
  "contributors":null,
  "source":"http://twitterfeed.com\"; rel=\"nofollow
\">twitterfeed",
  "in_reply_to_status_id":null,
  "place":null,
  "truncated":false,
  "in_reply_to_screen_name":null,
  "user": {
"favourites_count":0,
"profile_text_color":"00",
"time_zone":"Eastern Time (US & Canada)",
"created_at":"Tue Oct 27 19:50:51 + 2009",
"statuses_count": 286,
"notifications":null,
"profile_link_color":"ff",
"description":"I write code and talk to people.",
"lang":"en",
"profile_background_image_url":"http://s.twimg.com/a/
1271891196/images/themes/theme1/bg.png",
"profile_image_url":"http://s.twimg.com/a/1271891196/images/
default_profile_0_normal.png",
"location":"Near the water.",
"contributors_enabled":false,
"following":null,
"geo_enabled":false,
"profile_sidebar_fill_color":"e0ff92",
"profile_background_tile":false,
"screen_name":"sstatik",
"profile_sidebar_border_color":"87bc44",
"followers_count": 40,
"protected":false,
"verified":false,
"url":"http://elliotmurphy.com/";,
"name":"statik",
"friends_count":18,
"id":85646316,
"utc_offset":-18000,
"profile_background_color":"9ae4e8"
  },
  "id": 12651537502,
  "favorited":false
}
{
  "delete": {
"status":{
  "id":12650137902,
  "user_id":128090723
}
  }
}


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


[Python3] Reading a binary file and wrtiting the bytes verbatim in an utf-8 file

2010-04-23 Thread fab
Hello.

I have to read the contents of a binary file (a PNG file exactly), and
dump it into an RTF file.

The RTF-file has been opened with codecs.open in utf-8 mode.

As I expected, the utf-8 decoder chokes on some combinations of bits;
how can I tell python to dump the bytes as they are, without
interpreting them?

Thanks.

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


Re: Making special method names, work with __getattr__

2010-04-23 Thread Chris Rebert
On Fri, Apr 23, 2010 at 2:41 AM, Antoon Pardon  wrote:
> The following is a proof of concept. The idea is to have variables that
> represent symbolic names/expressions, you can work with like ordinary
> values, but that can be evaluated later.
>
> This is the code:
>
> 
>
> import operator
> from functools import partial
>
> class Expression (object) :
>  def __add__(self, term):
>    return Binary(self, operator.__add__, term)
>
>  def __getattr__(self, name):
>    op = getattr(operator, name)
>    return partial(Binary, self, op)
>
> class Binary (Expression) :
>  def __init__(self, left, op, right):
>    self.left = left
>    self.operator = op
>    if not isinstance(right, Expression):
>      right = Value(right)
>    self.right = right
>
>  def eval(self, dct):
>    left = self.left.eval(dct)
>    right = self.right.eval(dct)
>    return self.operator(left, right)
>
>
> class Symbol (Expression):
>  def __init__(self, name):
>    self.name = name
>
>  def eval(self, dct={}):
>    return dct[self.name]
>
>
> class Value (Expression):
>  def __init__(self, val):
>    self.value = val
>
>  def eval(self, dct={}):
>    return self.value
>
> def test():
>  dct = {"var1" : 5, "var2" : 7}
>  val1 = Symbol("var1")
>  val2 = Symbol("var2")
>  print val1.eval(dct)
>  sum = val1 + 3
>  print sum.eval(dct)
>  sum = sum + val2
>  print sum.eval(dct)
>  product = val1 * 7
>  print product.eval(dct)
>
> test()
>
> --
>
> The result I get is:
>
> 5
> 8
> 15
> Traceback (most recent call last):
>  File "Symbolics", line 54, in 
>    test()
>  File "Symbolics", line 51, in test
>    product = val1 * 7
> TypeError: unsupported operand type(s) for *: 'Symbol' and 'int'
>
> What I had hoped for was, that the line:
>
>  product = val1 * 7
>
> would be translated into something like
>
>  product = val1.__mul__(7)

That's basically correct.

> which would then be treated by the __getattr__ of the Expression superclass.
>
> That doesn't seem to happen.

Indeed it doesn't. The lookup of fouble-underscore special methods
bypasses __getattribute__() and friends. For details, see
http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes

> Does anyone have another idea, so I can get this to work without having
> to manually add all numeric special methods to the Expression class.

You could write a decorator to make it a bit less painful/repetitive,
but no, you're gonna have to define all the methods individually.

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


Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

2010-04-23 Thread Steven Howe

Really! Learn to use google better. I just used "python sort list"

Look at: http://wiki.python.org/moin/HowTo/Sorting

Read about list.sort. Try, at a command prompt (assuming you have a unix 
shell), "pydoc list"

search for sort; read it. It mentions 'reverse'.

then slice the list to your desired set and return.

sph


On 04/23/2010 07:02 AM, Grant Edwards wrote:

On 2010-04-22, D'Arcy J.M. Cain  wrote:
   

On Thu, 22 Apr 2010 15:04:01 +0100
Tim Golden  wrote:
 

So please tell me if there is one or not. I really need this soon.
Appreciate a lot.
 

Assuming top-k doesn't mean something obscurely statistical:
   

You really shouldn't do people's homework for them.  It doesn't do
them any favours.
 

Doing people's homework for them is a survival mechanism -- it reduces
the competence of potential new rivals.  :)

OTOH, if you do end up working with one of those a new grads with a
diploma but not a clue, you end up worse off because now you have to
teach them the problem solving skills they didn't learn in school.

   


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


Re: [Python3] Reading a binary file and wrtiting the bytes verbatim in an utf-8 file

2010-04-23 Thread Chris Rebert
On Fri, Apr 23, 2010 at 9:22 AM,   wrote:
> I have to read the contents of a binary file (a PNG file exactly), and
> dump it into an RTF file.
>
> The RTF-file has been opened with codecs.open in utf-8 mode.
>
> As I expected, the utf-8 decoder

You mean encoder.

> chokes on some combinations of bits;

Well yeah, it's supposed to be getting *characters*, not bytes.

> how can I tell python to dump the bytes as they are, without
> interpreting them?

Go around the encoder and write bytes directly to the file:

# Disclaimer: Completely untested

import codecs

raw_rtf = open("path/to/rtf.rtf", 'w')
png = open("path/to/png.png", 'r')
writer_factory = codecs.getwriter('utf-8')

encoded_rtf = writer_factory(raw_rtf)
encoded_rtf.write(u"whatever text we want") # use unicode
# ...write more text...

# flush buffers
encoded_rtf.reset()
raw_rtf.flush()

raw_rtf.write(png.read()) # write from bytes to bytes

raw_rtf.close()
#END code

I have no idea how you'd go about reading the contents of such a file
in a sensible way.

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


DLLs loading in interpreter but not with direct run on Windows

2010-04-23 Thread JTimoty
Hi,

I've got a weird problem, apparently related to the way python
searches for DLLs on Windows.

I compiled PyQt4 (no errors) but scripts that use it fail with "DLL
load failed: Invalid access to memory location."
If I play with loading the modules inside the interpreter, I see no
errors.

Even more, if I use IDLE, running scripts fails. However, if I _first_
type "from PyQt4 import QtGui" in the python shell, the script
executes without problems.

What is the difference between these two cases? How is loading dlls
different in ( $> python script.py ) and just ( $> python )?

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


Re: [Python3] Reading a binary file and wrtiting the bytes verbatim in an utf-8 file

2010-04-23 Thread Chris Rebert
On Fri, Apr 23, 2010 at 9:48 AM, Chris Rebert  wrote:
> On Fri, Apr 23, 2010 at 9:22 AM,   wrote:
>> I have to read the contents of a binary file (a PNG file exactly), and
>> dump it into an RTF file.

>> how can I tell python to dump the bytes as they are, without
>> interpreting them?
>
> Go around the encoder and write bytes directly to the file:
>
> # Disclaimer: Completely untested

> encoded_rtf.write(u"whatever text we want") # use unicode

Erm, sorry, since you're apparently using Python 3.x, that line should
have been just:

encoded_rtf.write("whatever text we want") # use unicode

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


Re: [Python3] Reading a binary file and wrtiting the bytes verbatim ?in an utf-8 file

2010-04-23 Thread fab
Thanks, I'll try this.

> I have no idea how you'd go about reading the contents of such a file
> in a sensible way.

The purpose is to embed PNG pictures in an RTF file that will be read
by OpenOffice. It seems that OpenOffice reads RTF in 8-bit, so it
should be ok.

The RTF is produced from a TeX source file encoded in UTF-8, that's
why I mix unicode and 8-bit.

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


Re: Pydev 1.5.6 Released (Django Integration)

2010-04-23 Thread Fabio Zadrozny
>> Pydev 1.5.6 has been released
>>
>> Details on Pydev: http://pydev.org
>> Details on its development: http://pydev.blogspot.com
>
> Question,
> Does it have a feature to evaluate the current edit buffer and continue
> with an interactive prompt?
>

Yes. See: http://pydev.org/manual_adv_interactive_console.html

Cheers,

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


Re: question about an exciting gotcha for unittests (and elsewhere) ...

2010-04-23 Thread Terry Reedy

On 4/23/2010 8:03 AM, Cameron Simpson wrote:

On 23Apr2010 13:25, Peter Otten<__pete...@web.de>  wrote:



| Move the unit tests into a separate script and have that import the module
| cs.nodedb.node.

Hmm. I have been very attracted by the idea of having the unittest in
the module itself, and run if I "run" the module alone (instead of
importing it).


I do this too. edit, run (F5 in IDLE), (click back to edit window) edit, 
run, ... several times in an hour. Very nice.


But... I have simpler modules (function, not class definitions) and no 
circular imports. So I was thinking the same thing Peter said for your case.



Conversely, I've also got a few modules that are standalone programs
and running _then_ runs the app, not a bunch of tests.

Having the tests elsewhere would solve the problem as you say; an import
of the module is what "real" code will be doing and, as my misadventure
above demonstrates, that's a different thing as far as namespaces go.

| In general, avoid importing a module and at the same time using it as the
| main script.

Fsir enough - that's a succinct description of what I did wrong.


Several people have posted problems that amount to this. An 'exciting 
gotcha' indeed ;-).


Terry Jan Reedy



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


Re: Difficulty w/json keys

2010-04-23 Thread Terry Reedy

On 4/23/2010 10:20 AM, Red wrote:

My apologies for what is probably a simple question to most on this
group. However, I am new to python and very new to json.

I am trying to read in a json file from a twitter download. There are,
generally, two types of lines: those lines with "text" and the other
lines.  I am only interested in the lines with "text".  I am also only
interested in lines with "lang":"en", but I haven't gotten far enough
to implement that condition in the code snippets below.

I have gotten Option 2 below to sort of work.  It works fine for
'text', but doesn't work for 'lang'.


You do not define 'work', 'sort of work', and "doesn't work".


FWIW I am using Python 2.6.4

Can someone tell me what I'm doing wrong with the following code
snippets and/or point me toward an example of an implementation?

Many thanks for your patience.

-

import sys
import json

f = open(sys.argv[1])

#option 1

for line in f:
j = json.loads(line)
try:
'text' in j


This does not raise an exception when false


print "TEXT:  ", j


so this should always print.
Forget this option.



except:
print "EXCEPTION:   ", j
continue
else:
text=j['text']
snip 




#option 2   does basically the same thing as option 1 ,


Not at all when 'text' in not in j.


 but also looks

for 'lang'

for line in f:
j = json.loads(line)
if 'text' in j:
if 'lang' in j:
lang = j['lang']
print "language", lang
text = j['text']
snip 


tjr

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


Re: Difficulty w/json keys

2010-04-23 Thread Terry Reedy

On 4/23/2010 10:51 AM, Jim Byrnes wrote:


I can't help you directly with your problem but have you seen this:

http://arstechnica.com/open-source/guides/2010/04/tutorial-use-twitters-new-real-time-stream-api-in-python.ars


Yes. Ignore the part about push versus pull (you are already doing the 
latter) and just look at the processing examples.


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


Re: question about an exciting gotcha for unittests (and elsewhere) ...

2010-04-23 Thread Gabriel Genellina
En Fri, 23 Apr 2010 03:15:16 -0300, Cameron Simpson   
escribió:

On 23Apr2010 15:37, I wrote:



| Experienced users will see at once what's happened: I've made a Node
| myself in the test using the local class, and the Node class is thus
| __main__.Node. However, my sql Backend class has independently imported
| the "Node" and "Backend" classes from "cs.nodedb.node". So when _it_
| calls serialise(), "Node" is "cs.nodedb.node.Node".
[...]

A walk around the block and I'm thinking the olny sane way to do this is
to use relative imports, to always get the sqla.py module from the same
place as the node.py where the test lives, and likewise in sqla.py
to relatively import node.py to get its matching file.


Another way is to split the test code and move it into its own module.  
This way, the testing code will import the node module the same way the  
real application would do.


--
Gabriel Genellina

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


Re: Tkinter question

2010-04-23 Thread Rotwang

eb303 wrote:

On Apr 23, 1:58 pm, Rotwang  wrote:


[...]

I didn't. How do I get Python to display the draw window, other than by
using mainloop()?


Well, mainloop doesn't actually display anything. It's just the event
loop for tk. So since you run your program within IDLE, there is
already one running. What does it do if you delete the mainloop()
line? Doesn't your window appear at all?


No.



[...]

Here's another problem I've run into today: I've just added a bit of
code so that it's possible to resize the draw window and the contents
will be resized automatically. The method now looks something like this:

out = Tkinter.Tk()
slave = Tkinter.Canvas(out, width = wh[0], height = wh[1])
slave.grid()
# I put the canvas widget inside a tk widget instead of just
# using the former because I want keypresses to do things, and
# it doesn't seem to be possible to bind keyboard events to a
# canvas
# draw something
slave.pack()


(Hope this line is a mistake: gridding *and* packing slave will
probably result in tk thinking for ages how it should display it in
its parent…)


Not a mistake so much as a symptom of my inept, cargo-cult approach to 
programming. Needless to say you're correct that it shouldn't be there, 
though taking it out doesn't give a noticeable improvement in 
performance (perhaps because the canvas is the only thing there so 
there's no conflict).




def resize(b):
wh[:] = [b.width, b.height]
slave.config(width = wh[0], height = wh[1])
# resize the contents of slave



You don't need at all to resize the slave explicitely. You should do
the following:
- Tell 'out' that its first row and first column should resize
themselves when the window is resized by doing:
out.grid_rowconfigure(1, weight=1)
out.grid_columnconfigure(1, weight=1)
- Make sure slave is actually put in the cell in first row and column,
and that all its sides will stick to the cell borders:
slave.grid(row=1, column=1, sticky='nswe')

If you do that, the slave.config in the resize function shouldn't be
needed anymore.


Indeed! That works great.



out.bind('', resize)


If using the grid options, better do a slave.bind(…) here, which will
call the binding when the canvas is resized, which is obvioulsy when
you want to update its contents.


Right, though before you suggested making the sides of the canvas 
sticky, resizing the window didn't reconfigure slave.



[...] 


You get the size for the outer window and apply it to the canvas
inside it. Since the canvas has a border which is 2 pixels wide by
default, this resizes the window containing it to take this border
into account. So your binding is called again, and so on… But using
the options to grid described above, there should never be any need to
resize the canvas explicitely.


Thanks very much for your help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Smtpd module

2010-04-23 Thread Gabriel Genellina

En Fri, 23 Apr 2010 06:30:42 -0300, Johny  escribió:


I would like to use smtpd module to write very simple smtp server but
this server must:

1. accept several connections at the same time( like a forking server)


I think asyncore takes care of that.


2. have basic authentication  that is it must understand AUTH command.


I think there was a recipe doing AUTH in code.activestate.com

--
Gabriel Genellina

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


Re: Calling multiple programs with subprocess

2010-04-23 Thread Amit Uttamchandani
On Thu, Apr 22, 2010 at 10:12:47PM -0400, Dave Angel wrote:
> amit wrote:
> >How does one go about calling multiple programs using subprocess?
> >
> >This is the program flow:
> >
> >C:\> wrenv.exe
> >C:\> make clean
> >..
> >..
> >
> >The 'wrenv.exe' is necessary since it sets up the proper environment
> >for building. How do I use subprocess to execute 'wrenv.exe' and then
> >the 'make clean' command.
> >
> >Any help is appreciated.
> >
> >Thanks,
> >Amit
> >
> One way is to write a batch file (since you're on Windows), and
> execute that with shell=True.
> 
> It's not the only way, or the most efficient.  But it's most likely
> to work, without knowing anything more about those two programs.
> 
> DaveA
> 

Thanks Dave.

That's actually a good idea and in this case probably the only way that
this would work. I can auto-generate the batch file from the python
script with the parameters that I need and just execute that with the
subprocess.

I wish there was a cleaner was as well.

But thanks for tip!

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


Re: On Class namespaces, calling methods

2010-04-23 Thread Aahz
In article <4bc120bd$0$8850$c3e8...@news.astraweb.com>,
Steven D'Aprano   wrote:
>
>I can only think of two circumstances where old-style classes are 
>*wrong*: if you use multiple inheritance with a diamond diagram ("...now 
>you have THREE problems" *wink*), if you intend using descriptors such as 
>properties, or if you need __slots__. That's three circumstances: 
>multiple inheritance with a diamond diagram, descriptors, __slots__, and 
>__getattribute__. Four circumstances.
>
>Any other time, they're merely discouraged, and gone in Python 3.x.

Discouraged by some people.  I certainly encourage the use of old-style
classes unless there's a specific reason to use new-style classes.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv.py sucks for Decimal

2010-04-23 Thread Phlip
On Apr 22, 5:03 pm, MRAB  wrote:

> It might be a stupid question, but have you tried passing in the
> Decimal() object itself?

Yep. Nope. Might as well (we ain't working today).

But sorry, as usual, for my tone, and thanks all for playing!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv.py sucks for Decimal

2010-04-23 Thread Phlip
On Apr 22, 6:15 pm, Jerry Hill  wrote:

> 10,10.0,10.00,"10"
>
> That's an int, a float, a Decimal and a string, all of which appear to
> be formatted as I would expect.

When you point your finger 'cause your plan fell thru
you got three more fingers, pointing back at you! --Dire Straights
-- 
http://mail.python.org/mailman/listinfo/python-list


"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES JOBS IN SWEDEN" ON http://jobsinsweden-net.blogspot.com/

2010-04-23 Thread saima81
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN SWEDEN" "ADMIN JOBS IN SWEDEN" "SALES
JOBS IN SWEDEN" ON  http://jobsinsweden-net.blogspot.com/
"JOBS IN SWEDEN" " SWEDEN JOBS" "MEDICAL JOBS IN SWEDEN" "FINANCE JOBS
IN SWEDEN" "ACCOUNTS JOBS IN

problem when running .py file

2010-04-23 Thread Tingting HAN
Dear Officer,

I first apologize that I am totally new for python. I have downloaded a code
packet “triMC3D” from online, and within it there is a file
“configuration.py”.I downloaded and installed python and some related
packages, tried very hard, but there is still the following error:



the  Traceback (most recent call last):
  File "E:\TingTing\triMC3D-1.0.0\python\configuration.py", line 8, in ?
from tables import *
  File "C:\Python23\Lib\site-packages\tables\__init__.py", line 31, in ?
from tables.utilsExtension import getPyTablesVersion, getHDF5Version
ImportError: DLL load failed: The specified procedure could not be
found. The first attached



The system of my computer is Windows XP.

The first attached file is the README file for triMC3D code. It says they
used python 2.3 so I used the version python-2.3.5.

The second attached is the file “configuration.py” I want to run. I
sincerely hope that you could try to run it, see what is the problem and
give me some tips.


-- 
Best regards,
Sofia

ETSI de Telecomunicación - office C-203-1
Dpto. Ingeniería Electrónica
Ciudad Universitaria s/n
Madrid 28040,  Spain
TEL: +34 65 232 4340
triMC3D
-- 

Monte Carlo simulation environment for heterogeneous turbid media. The
geometry is described by a triangle mesh, which allows for computation
of reflection/refraction effects at different tissue layers.

Features:
* Arbitrary geometries importable from STL format.
* Easy generation of analytical shapes using python
* Calculation of light fluence/absorbance whithin the medium. 
* Calculation and storage of photon paths with time-resolved 
information.
* HDF5 format for neat data input and output.
TODO:
* Optimize the spatial organisation of triangles.
* Hardware acceleration of ray-triangle intersection functions.
* Introduction of new phase functions.
* Addition of more source functions.
* Incorporation of polarisation handling

Compilation
---
triMC3D depends on several libraries in order to be built:

* libhdf5 and libhdf5_hl
* libgsl
* an MPI implementation, like mpich2, in order to compile the
parallel version

Furthermore, python 2.3 and packets pytables, scipy, VTK and numarray/numpy are
extensively used for model preparation and post-processing of simulation data.

Usage
-
There are several options in order to deal with input and output files
for triMC3D (HDF5 data format). Among the programs and libraries that
can be used to this end, the following are probably most useful:

* Python + PyTables
* Matlab + HDF5 access library
* IDL + HDF library
* HDFview
* HDF tools from NCSA   
* Paraview for fast data visualisation

#!/usr/bin/python
"""Add a configuration entry to the parameters"""
import sys
import array
import struct
import math
import numarray
from tables import *

from local_modules import hdf5


def create_config(file_id):
try:
table = file_id.root.Configuration
except Exception:
table = file_id.createTable(file_id.root, 'Configuration',
hdf5.Configuration, "Simulation Parameters")
c1 = table.row

c1["idnumber"]   = 1
c1["num_phots"]  = 1000
c1["descr"]  = "Background Illumination"
c1["bin_size"]   = 2e-4
c1["out_file"]   = "outtest.h5"
c1["src_type"]   = "gaussian"
c1["src_dir"]= (0, 0, 1)
c1["src_pos"]= (0, 0,-2.1e-3 )
c1["sim_type"]   = hdf5.sim_types["Incoherent"]
c1["extra_params"] = 0

c1.append()
table.flush()

def create_extra(file_id):
try:
table = file_id.root.EXTRAParams
except Exception:
table = file_id.createTable(file_id.root, 'EXTRAParams',
hdf5.EXTRAParam, "EXTRA Parameters")
p1 = table.row
p1["idnumber"]   = 0
p1["mode"]   = hdf5.extra_modes["Limited"]
p1["Li_limit"]   = 5
p1.append()
table.flush()

def main():
if len(sys.argv) <> 2:
print( "Usage: " + sys.argv[0] + "H5file.h5")
sys.exit(1)

file_id = openFile(sys.argv[1],mode = "r+")


create_config(file_id)
create_extra(file_id)

if __name__ == "__main__":
main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when should I explicitly close a file?

2010-04-23 Thread Steven D'Aprano
On Fri, 23 Apr 2010 13:19:41 +0200, Alf P. Steinbach wrote:

> But for a literal context-free interpretation e.g. the 'sys.getrefcount'
> function is not documented as CPython only and thus an implementation
> that didn't do reference counting would not be a conforming Python
> implementation.

Since Jython and IronPython are conforming Python implementations, and 
Guido has started making policy decisions specifically to support these 
other implementations (e.g. the language feature moratorium, PEP 3003), I 
think we can assume that this is a documentation bug.

However, a Python implementation that always returned 0 for 
sys.getrefcount would technically satisfy the word of the documentation, 
if not the spirit.



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


Re: Difficulty w/json keys

2010-04-23 Thread Red
Thanks to Cliff and Rolando who saw where my real problem was.
Terry,Jim: I had not seen the tutorial before, so I'll have to dig
into that as well.  So little time.

Cheers


On Apr 23, 10:06 am, "J. Cliff Dyer"  wrote:
> You need to know what your input data actually looks like, and the best
> thing for that is a little bit of formatting.  I bet you can figure out
> the problem yourself, once you see the structure of your data more
> clearly.  I've reformatted the JSON for you to help out.
>
> On Fri, 2010-04-23 at 07:20 -0700, Red wrote:
> > -- Two Sample Twitter lines -
>
> {
>   "text":"tech managers what size for your teams? better to have 10-20
> ppl per manager or 2-5 and have the managers be more hands
> on?",
>   "in_reply_to_user_id":null,
>   "coordinates":null,
>   "geo":null,
>   "created_at":"Thu Apr 22 17:35:42 + 2010",
>   "contributors":null,
>   "source":"http://twitterfeed.com\"; rel=\"nofollow
> \">twitterfeed",
>   "in_reply_to_status_id":null,
>   "place":null,
>   "truncated":false,
>   "in_reply_to_screen_name":null,
>   "user": {
>     "favourites_count":0,
>     "profile_text_color":"00",
>     "time_zone":"Eastern Time (US & Canada)",
>     "created_at":"Tue Oct 27 19:50:51 + 2009",
>     "statuses_count": 286,
>     "notifications":null,
>     "profile_link_color":"ff",
>     "description":"I write code and talk to people.",
>     "lang":"en",
>     "profile_background_image_url":"http://s.twimg.com/a/
> 1271891196/images/themes/theme1/bg.png",
>     "profile_image_url":"http://s.twimg.com/a/1271891196/images/
> default_profile_0_normal.png",
>     "location":"Near the water.",
>     "contributors_enabled":false,
>     "following":null,
>     "geo_enabled":false,
>     "profile_sidebar_fill_color":"e0ff92",
>     "profile_background_tile":false,
>     "screen_name":"sstatik",
>     "profile_sidebar_border_color":"87bc44",
>     "followers_count": 40,
>     "protected":false,
>     "verified":false,
>     "url":"http://elliotmurphy.com/";,
>     "name":"statik",
>     "friends_count":18,
>     "id":85646316,
>     "utc_offset":-18000,
>     "profile_background_color":"9ae4e8"
>   },
>   "id": 12651537502,
>   "favorited":false}
>
> {
>   "delete": {
>     "status":{
>       "id":12650137902,
>       "user_id":128090723
>     }
>   }
>
> }
>
>

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


Re: Difficulty w/json keys

2010-04-23 Thread Red
On Apr 23, 1:17 pm, Terry Reedy  wrote:
> On 4/23/2010 10:20 AM, Red wrote:
>
> > My apologies for what is probably a simple question to most on this
> > group. However, I am new to python and very new to json.
>
> > I am trying to read in a json file from a twitter download. There are,
> > generally, two types of lines: those lines with "text" and the other
> > lines.  I am only interested in the lines with "text".  I am also only
> > interested in lines with "lang":"en", but I haven't gotten far enough
> > to implement that condition in the code snippets below.
>
> > I have gotten Option 2 below to sort of work.  It works fine for
> > 'text', but doesn't work for 'lang'.
>
> You do not define 'work', 'sort of work', and "doesn't work".
>
>
>
> > FWIW I am using Python 2.6.4
>
> > Can someone tell me what I'm doing wrong with the following code
> > snippets and/or point me toward an example of an implementation?
>
> > Many thanks for your patience.
>
> > -
>
> > import sys
> > import json
>
> > f = open(sys.argv[1])
>
> > #option 1
>
> > for line in f:
> >    j = json.loads(line)
> >    try:
> >            'text' in j
>
> This does not raise an exception when false
>
> >            print "TEXT:  ", j
>
> so this should always print.
> Forget this option.
>
> >    except:
> >            print "EXCEPTION:   ", j
> >            continue
> >    else:
> >            text=j['text']
> > snip 
>
> > #option 2  does basically the same thing as option 1 ,
>
> Not at all when 'text' in not in j.
>
>   but also looks
>
> > for 'lang'
>
> > for line in f:
> >    j = json.loads(line)
> >    if 'text' in j:
> >            if 'lang' in j:
> >                    lang = j['lang']
> >                    print "language", lang
> >            text = j['text']
> > snip 
>
> tjr

I need to think about the logic here again and see what I'm missing
beyond my original question.  Thanks for taking the time to explain.

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


Re: Smtpd module

2010-04-23 Thread Miki
Hello,

> I would like to use smtpd module to write very simple smtp server but
> this server must:
>
> 1. accept several connections at the same time( like a forking server)
> 2. have basic authentication  that is it must understand AUTH command.
>
> Does anyone know if the smtpd module have both?
http://twistedmatrix.com/documents/current/mail/tutorial/smtpclient/smtpclient.html

HTH,
--
Miki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get live streaming of friends tweets??

2010-04-23 Thread Florian Diesch



has some explanations about how to use real-time stream API 

>"eka (Esteban)"  writes:
>
> IMO the real time update is your work to do.
>
> You can poll, to say, each 1 minute or less and then you will have
> your real time tweets update.
>
>
> On Apr 14, 9:08 am, Harshad Joshi  wrote:
>> import twython.core as twython, pprint
>> import codecs
>>
>> # Authenticate using Basic (HTTP) Authentication
>> twitter = twython.setup(username='yourname', password='yourpassword')
>> friends_timeline = twitter.getFriendsTimeline(count="60", page="2")
>>
>> a=codecs.open('twython_log.txt','a','utf-8')
>> for tweet in friends_timeline:
>>         print "\n"+tweet["user"]["screen_name"]+">>"+ tweet["text"]
>>         d="\n"+tweet["user"]["screen_name"]+">>"+ tweet["text"]
>>         a.write(d)
>>
>> a.close()
>>
>> This is the code I wrote but I doubt if its a live stream i am
>> receiving.
>>
>> I wanted some real time updates from my friends. The above code
>> fetches data from the 'latest' friends tweet and continues till 60th
>> tweet. It doesent do anything about the new tweet that might come from
>> someone.
>>
>> On Apr 11, 9:34 pm, Atul Kulkarni  wrote:
>>
>> > Hi Harshad,
>>
>> > It depends on what you want those updates for? If it is a client then you
>> > will have to stick with the methods you have described but if you are
>> > writing and server end application then you can think of using streaming 
>> > api
>> > with follow predicate. This will feed in to your application live updates
>> > from the people you are following. But do not use streaming api if you
>> > thinking of a client, as streaming API could be overwhelming for the client
>> > side application.
>>
>> > Tweepy has code examples, which should help you with the sample code. Just
>> > my 2 cents.
>>
>> > Regards,
>> > Atul.
>>
>> > On Sat, Apr 10, 2010 at 12:34 AM, Harshad Joshi 
>> > wrote:
>>
>> > > In the original twitter api, there was a method like
>>
>> > > a=twitter.Api('user','password')
>>
>> > > b=a.GetFriendsTimeline()
>>
>> > > where we could get the friends time line after authentication. It used
>> > > to show maximum 20 tweets at a time.
>>
>> > > Is there any similar method available in tweepy which will show live
>> > > updates? If yes, then what is the maximim number of tweets being
>> > > shown?
>>
>> > > I would like to see a code snippet of the above method.
>>
>> > > --
>> > > To unsubscribe, reply using "remove me" as the subject.
>>
>> > --
>> > Regards,
>> > Atul Kulkarni


   Florian
-- 
Simple dict-like Python API for GConf:
 

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


Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

2010-04-23 Thread Raymond Hettinger
On Apr 22, 10:49 am, John Nagle  wrote:
> Chris Rebert wrote:
> > 2010/4/22 Jo Chan :
> >> Hi,friends.
> >>  I wanna ask if there is a function which is able to take a list as 
> >> argument
> >> and then return its top-k maximums?
> >> I only know about max which is poorly a top-1 maximum function, now I want
> >> more yet I am lazy enough that don't want to write one by myself.
>
> >http://docs.python.org/library/heapq.html#heapq.nlargest
>
> > Cheers,
> > Chris
> > --
> >http://blog.rebertia.com
>
>    Is "nlargest" smart enough to decide when it's cheaper to track the
> N largest entries on a linear pass through the list than to sort?

nlargest() has gotten smarter over time.  So, the answer depends on
which version you're using.

Here's a snippet from 
http://svn.python.org/view/python/branches/py3k/Lib/heapq.py?revision=70695&view=markup

def nlargest(n, iterable, key=None):
"""Find the n largest elements in a dataset.

Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
"""

# Short-cut for n==1 is to use max() when len(iterable)>0
if n == 1:
it = iter(iterable)
head = list(islice(it, 1))
if not head:
return []
if key is None:
return [max(chain(head, it))]
return [max(chain(head, it), key=key)]

# When n>=size, it's faster to use sort()
try:
size = len(iterable)
except (TypeError, AttributeError):
pass
else:
if n >= size:
return sorted(iterable, key=key, reverse=True)[:n]

# When key is none, use simpler decoration
if key is None:
it = zip(iterable, count(0,-1)) # decorate
result = _nlargest(n, it)
return [r[0] for r in result]   #
undecorate

# General case, slowest method
in1, in2 = tee(iterable)
it = zip(map(key, in1), count(0,-1), in2)   # decorate
result = _nlargest(n, it)
return [r[2] for r in result]   #
undecorate
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

2010-04-23 Thread Raymond Hettinger
On Apr 23, 1:24 am, Bryan  wrote:
> That is interesting. The above algorithm for nlargest is better, but
> to use it for nsmallest requires a largest-on-top heap, which the
> module does not bother to implement.

FWIW, the pure python versions differ because they are both
implemented in terms of the basic minheap functions, but the
underlying C code uses the same algorithm for both (using an
underlying maxheap when necessary):

http://svn.python.org/view/python/branches/py3k/Modules/_heapqmodule.c?revision=64351&view=markup


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


Re: problem when running .py file

2010-04-23 Thread Gabriel Genellina
En Fri, 23 Apr 2010 18:43:41 -0300, Tingting HAN   
escribió:


I first apologize that I am totally new for python. I have downloaded a  
code

packet “triMC3D” from online, and within it there is a file
“configuration.py”.I downloaded and installed python and some related
packages, tried very hard, but there is still the following error:



the  Traceback (most recent call last):
  File "E:\TingTing\triMC3D-1.0.0\python\configuration.py", line 8, in ?
from tables import *
  File "C:\Python23\Lib\site-packages\tables\__init__.py", line 31, in ?
from tables.utilsExtension import getPyTablesVersion, getHDF5Version
ImportError: DLL load failed: The specified procedure could not be
found.


Looks like some dependecies are incomplete. triMC3D home page at  
http://trimc3d.et.tudelft.nl/index.php?n=Main.Installation says:


"triMC3D depends on several libraries in order to be built:

  libhdf5 and libhdf5_hl
  libgsl
  an MPI implementation, like mpich2, in order to compile the parallel  
version


Furthermore, python 2.x and packages pytables, scipy, VTK and  
numarray/numpy are extensively used for model preparation and  
post-processing of simulation data."


Did you install all of them?

triMC3D doesn't appear to be widely used, so better ask the author for  
further advice.


--
Gabriel Genellina

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


Re: Calling multiple programs with subprocess

2010-04-23 Thread Kushal Kumaran
On Sat, Apr 24, 2010 at 1:21 AM, Amit Uttamchandani
 wrote:
> On Thu, Apr 22, 2010 at 10:12:47PM -0400, Dave Angel wrote:
>> amit wrote:
>> >How does one go about calling multiple programs using subprocess?
>> >
>> >This is the program flow:
>> >
>> >C:\> wrenv.exe
>> >C:\> make clean
>> >..
>> >..
>> >
>> >The 'wrenv.exe' is necessary since it sets up the proper environment
>> >for building. How do I use subprocess to execute 'wrenv.exe' and then
>> >the 'make clean' command.
>> >
>> >Any help is appreciated.
>> >
>> >Thanks,
>> >Amit
>> >
>> One way is to write a batch file (since you're on Windows), and
>> execute that with shell=True.
>>
>> It's not the only way, or the most efficient.  But it's most likely
>> to work, without knowing anything more about those two programs.
>>
>> DaveA
>>
>
> Thanks Dave.
>
> That's actually a good idea and in this case probably the only way that
> this would work. I can auto-generate the batch file from the python
> script with the parameters that I need and just execute that with the
> subprocess.
>
> I wish there was a cleaner was as well.
>

Run a shell (cmd.exe, I think) using subprocess and send it the
commands you want to run using the communicate() method.

-- 
regards,
kushal
-- 
http://mail.python.org/mailman/listinfo/python-list


NotImplemented used in Decimal

2010-04-23 Thread Steven D'Aprano
I'm reading the source code for decimal.Decimal, and I see that the 
arithmetic operations (__add__, __sub__, etc.) start with code like this:

if other is NotImplemented:
return other


I don't understand the purpose of this. I presume that it is *not* for 
the use-case of:

d = Decimal('123.456')
result = d + NotImplemented

which not only doesn't make sense to me, but when I try it, it raises 
TypeError. So I find myself confused why the arithmetic methods do this.



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


Re: NotImplemented used in Decimal

2010-04-23 Thread Kushal Kumaran
On Sat, Apr 24, 2010 at 8:54 AM, Steven D'Aprano
 wrote:
> I'm reading the source code for decimal.Decimal, and I see that the
> arithmetic operations (__add__, __sub__, etc.) start with code like this:
>
>        if other is NotImplemented:
>            return other
>
>
> I don't understand the purpose of this. I presume that it is *not* for
> the use-case of:
>
> d = Decimal('123.456')
> result = d + NotImplemented
>
> which not only doesn't make sense to me, but when I try it, it raises
> TypeError. So I find myself confused why the arithmetic methods do this.
>

There's a _convert_other method which is called before the test that
can return NotImplemented.

-- 
regards,
kushal
-- 
http://mail.python.org/mailman/listinfo/python-list


"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" O

2010-04-23 Thread Naeem
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUDI GIRLS" "HOT WIFE" ON
http://hollywood6y.blogspot.com/ "SAUDI ARABIAN GIRLS"
"MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT GIRLS" "SEXY ARABIAN
GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID GIRLS" "HOT ARABIAN GIRLS"
"SEXY DATING SAUDI GIRLS" "HOT WIFE" ON http://hollywood6y.blogspot.com/
"SAUDI ARABIAN GIRLS" "MUSLIM SEXY GIRLS""SEXU SAUDI GIRLS" "SEXY HOT
GIRLS" "SEXY ARABIAN GIRLS" "SEXY ARABIAN LADIES" "SEXY HOT SAID
GIRLS" "HOT ARABIAN GIRLS" "SEXY DATING SAUD

Re: NotImplemented used in Decimal

2010-04-23 Thread Steven D'Aprano
On Sat, 24 Apr 2010 09:05:14 +0530, Kushal Kumaran wrote:

> On Sat, Apr 24, 2010 at 8:54 AM, Steven D'Aprano
>  wrote:
>> I'm reading the source code for decimal.Decimal, and I see that the
>> arithmetic operations (__add__, __sub__, etc.) start with code like
>> this:
>>
>>        if other is NotImplemented:
>>            return other
>>
>>
>> I don't understand the purpose of this. I presume that it is *not* for
>> the use-case of:
>>
>> d = Decimal('123.456')
>> result = d + NotImplemented
>>
>> which not only doesn't make sense to me, but when I try it, it raises
>> TypeError. So I find myself confused why the arithmetic methods do
>> this.
>>
>>
> There's a _convert_other method which is called before the test that can
> return NotImplemented.


Yes, I can see that, but why?



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


Re: NotImplemented used in Decimal

2010-04-23 Thread Chris Rebert
On Fri, Apr 23, 2010 at 11:25 PM, Steven D'Aprano
 wrote:
> On Sat, 24 Apr 2010 09:05:14 +0530, Kushal Kumaran wrote:
>> On Sat, Apr 24, 2010 at 8:54 AM, Steven D'Aprano
>>  wrote:
>>> I'm reading the source code for decimal.Decimal, and I see that the
>>> arithmetic operations (__add__, __sub__, etc.) start with code like
>>> this:
>>>
>>>        if other is NotImplemented:
>>>            return other
>>>
>>>
>>> I don't understand the purpose of this. I presume that it is *not* for
>>> the use-case of:
>>>
>>> d = Decimal('123.456')
>>> result = d + NotImplemented
>>>
>>> which not only doesn't make sense to me, but when I try it, it raises
>>> TypeError. So I find myself confused why the arithmetic methods do
>>> this.
>>>
>> There's a _convert_other method which is called before the test that can
>> return NotImplemented.
>
> Yes, I can see that, but why?

If the conversion to Decimal in  _convert_other() fails, the operator
method returns NotImplemented to signal to the interpreter that
Decimal doesn't know how to do the requested operation with an operand
of the given type; the interpreter will fall back by calling the
reflected method of the other operand. And if that also fails, the
interpreter raises TypeError:
>>> Decimal(4)+'g'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'Decimal' and 'str'

Note how the traceback doesn't mention decimal.py

See also NotImplemented's entry in the docs:
http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy

Now, they could have had _convert_other() return some other sentinel
value (or raise an exception) to indicate that the conversion failed,
but they didn't; it probably made the code marginally simpler.

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