problem with money datatype based calculations in python

2009-05-02 Thread Krishnakant
hello all,
I am using postgresql as a database server for my db application.

The database is related to accounts and point of sales and many
calculations involve money datatype.

The application logic is totally done in python.  Now the problem is
that there is a situation where we calculate tax on % of the total
amount on the invoice.  The  percentage is in terms of float but the
eventual amount has to be in a money datatype.

The product cost comes in money datatype from postgresql and the tax %
comes in float.  So I would like to know if python supports some thing
similar to money datatype so that I can cast my total amount (in money )
divided by tax% (in float ) so money divided by float should be the
result and that result should be in money datatype.
For example a product x has the cost Rs. 100 which is stored in the
tabel as money type.  and in the tax table for that product the VAT is
5% and this 5% is stored in float datatype.  So after using both these
values the resulting total 105Rs. should be in money type and not float.
I awaite some reply,
Thanks in advice.
happy hacking.
Krishnakant.

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


interesting float to money conversion problem

2009-05-02 Thread Krishnakant
hello all,
> > I am using postgresql as a database server for my db application.
> > 
> > The database is related to accounts and point of sales and many
> > calculations involve money datatype.
> > 
> > The application logic is totally done in python.  Now the problem is
> > that there is a situation where we calculate tax on % of the total
> > amount on the invoice.  The  percentage is in terms of float but the
> > eventual amount has to be in a money datatype.
> > 
> > The product cost comes in money datatype from postgresql and the tax %
> > comes in float.  So I would like to know if python supports some thing
> > similar to money datatype so that I can cast my total amount (in money )
> > divided by tax% (in float ) so money divided by float should be the
> > result and that result should be in money datatype.
> > For example a product x has the cost Rs. 100 which is stored in the
> > tabel as money type.  and in the tax table for that product the VAT is
> > 5% and this 5% is stored in float datatype.  So after using both these
> > values the resulting total 105Rs. should be in money type and not float.
> > I awaite some reply,
> > Thanks in advice.
> > happy hacking.
> > Krishnakant.
> > 
> > --
> > http://mail.python.org/mailman/listinfo/python-list

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


Re: Why bool( object )?

2009-05-02 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Fri, 01 May 2009 15:03:30 -0700, Aaron Brady wrote:
>
>> On May 1, 4:30 am, Steven D'Aprano > cybersource.com.au> wrote:
>>> On Fri, 01 May 2009 16:30:19 +1200, Lawrence D'Oliveiro wrote:
>>> > I have never written anything so unbelievable in my life. And I hope
>>> > I never will.
>>>
>>> I didn't say you did. If anyone thought I was quoting Lawrence's code,
>>> I'd be surprised. It was not my intention to put words into your mouth.
>>>
>>> But seeing as you have replied, perhaps you could tell us something.
>>> Given so much you despise using non-bools in truth contexts, how would
>>> you re-write my example to avoid "a or b or c"?
>>>
>>> for x in a or b or c:
>>>     do_something_with(x)
>
> [...]
>> I don't think it would be very common to write Steven's construction for
>> arbitrary values of 'a', 'b', and 'c'.
>
> I don't care about "arbitrary values" for a, b and c. I don't expect a 
> solution that works for (say) a=None, b=5, c=[]. I'm happy to restrict 
> the arguments to all be arbitrary sequence-like objects.
>
> I'm even happy for somebody to give a solution with further restrictions, 
> like "if I know before hand that all three are lists, then I do blah...". 
> But state your restrictions up front.

If a, b, c are names or literals, then I guess you could do this:

for seq in a, b, c:
if seq: break
for x in seq:
do_something_with(x)

I have never been in a situation where I needed something like this,
though.
-- 
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list


Re: eval(WsgiApplication)

2009-05-02 Thread Arnaud Delobelle
gert  writes:

> I would like to read the following from a text file
>
> from json import loads
> from gert.db import Db
> def application(environ, response):
> v = loads(environ['wsgi.input'].read(int(environ
> ['CONTENT_LENGTH'])).decode('utf-8'))
> db = Db()
> db.execute('UPDATE votes SET count=count+1 WHERE vid=?',(v
> ['vid'],))
> db.execute('SELECT * FROM votes')
> j = '{"rec":'+db.json()+',\n'
> j+= ' "des":'+db.jdes()+'}'
> j = j.encode('utf-8')
> response('200 OK', [('Content-type', 'text/
> javascript;charset=utf-8'), ('Content-Length', str(len(j)))])
> return [j]
>
> execute it, and wrap a new function name around it for example
>
> def wrapper(environ, response):
>  exec(file)
>  return application(environ, response)
>
> How do I do this in python3?

What's wrong with importing it?

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


File handling problem.

2009-05-02 Thread subhakolkata1234
Dear Group,

I am using Python2.6 and has created a file where I like to write some
statistical values I am generating. The statistical values are
generating in a nice way, but as I am going to write it, it is not
taking it, the file is opening or closing properly but the values are
not getting stored. It is picking up arbitrary values from the
generated set of values and storing it. Is there any solution for it?

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


Re: File handling problem.

2009-05-02 Thread Pascal Chambon

subhakolkata1...@gmail.com a écrit :

Dear Group,

I am using Python2.6 and has created a file where I like to write some
statistical values I am generating. The statistical values are
generating in a nice way, but as I am going to write it, it is not
taking it, the file is opening or closing properly but the values are
not getting stored. It is picking up arbitrary values from the
generated set of values and storing it. Is there any solution for it?

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


  

Hello

Could you post excerpt of your file-handling code ?
It might be a buffering problem (although when the file closes, I think 
buffers get flushed), else it's really weird...


Regards,
pascal

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


Re: eval(WsgiApplication)

2009-05-02 Thread paul

gert schrieb:

I would like to read the following from a text file

Hi gert,

I'm puzzled, what is wrong with using wsgi as advertised? Just import 
your code and insert it in the wsgi chain no?


cheers
 Paul



from json import loads
from gert.db import Db
def application(environ, response):
v = loads(environ['wsgi.input'].read(int(environ
['CONTENT_LENGTH'])).decode('utf-8'))
db = Db()
db.execute('UPDATE votes SET count=count+1 WHERE vid=?',(v
['vid'],))
db.execute('SELECT * FROM votes')
j = '{"rec":'+db.json()+',\n'
j+= ' "des":'+db.jdes()+'}'
j = j.encode('utf-8')
response('200 OK', [('Content-type', 'text/
javascript;charset=utf-8'), ('Content-Length', str(len(j)))])
return [j]

execute it, and wrap a new function name around it for example

def wrapper(environ, response):
 exec(file)
 return application(environ, response)

How do I do this in python3?
--
http://mail.python.org/mailman/listinfo/python-list



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


Re: eval(WsgiApplication)

2009-05-02 Thread gert
On May 2, 10:25 am, Arnaud Delobelle  wrote:
> gert  writes:
> > I would like to read the following from a text file
>
> > from json import loads
> > from gert.db import Db
> > def application(environ, response):
> >     v = loads(environ['wsgi.input'].read(int(environ
> > ['CONTENT_LENGTH'])).decode('utf-8'))
> >     db = Db()
> >     db.execute('UPDATE votes SET count=count+1 WHERE vid=?',(v
> > ['vid'],))
> >     db.execute('SELECT * FROM votes')
> >     j = '{"rec":'+db.json()+',\n'
> >     j+= ' "des":'+db.jdes()+'}'
> >     j = j.encode('utf-8')
> >     response('200 OK', [('Content-type', 'text/
> > javascript;charset=utf-8'), ('Content-Length', str(len(j)))])
> >     return [j]
>
> > execute it, and wrap a new function name around it for example
>
> > def wrapper(environ, response):
> >      exec(file)
> >      return application(environ, response)
>
> > How do I do this in python3?
>
> What's wrong with importing it?

The problem is that my wsgi files have a wsgi extention for mod_wsgi
use

package
- __init__.py
- session.py
- db.py
- sqlite
- - sql.db
- www
- - test.htm
- - test.css
- - test.js
- - test.wsgi

i would like to make this package work both in mod_wsgi and cherrypy
server
mod_wsgi has a .wsgi handler because it is recommended to rename the
wsgi file with wsgi extensions to avoid double imports
cherrypy server has a dispatcher class

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


Re: Warning of missing side effects

2009-05-02 Thread Pascal Chambon

Tobias Weber a écrit :

Hi,
being new to Python I find remarkable that I don't see any side effects. 
That's especially true for binding. First, it is a statement, so this 
won't work:


   if x = q.pop():
  print x # output only true values

Second, methods in the standard library either return a value OR modify 
the reciever, so even if assignment was an expression the above wouldn't 
work.


Only it still wouldn't, because IF is a statement as well. So no ternary:

   x = if True: 5 else: 7;

However there is one bit of magic, functions implicitly return None. So 
while the following will both run without error, only one actually works:


   x = 'foo'.upper()
   y = ['f', 'b'].reverse()

Now I mentioned that the mutable types don't have functions that mutate 
and return something, so I only have to remember that...


But I'm used to exploiting side effect, and sometimes forget this rule 
in my own classes. IS THERE A WAY to have the following produce a 
runtime error?


   def f():
  x = 5
  # no return

   y = f()

Maybe use strict ;)

  

Hello

Just to note that if "['f', 'b'].reverse()" doesn't return the new 
value, there is a corersponding function : "reversed(mylist)" which does 
it (idem, sorted(list) <-> list.sort())  B-)


Concerning your question on warnings, well I guess that after a little 
time in python, you won't make mistakes on "side effects" anymore ;


But if you want to add checks to your methods, you should see towards 
decorators or metaclasses : they allow you to wrap your methods inside 
other methods, of which the only point couldbe, for example, to check 
what your methods returtn and raise a warning if it returns "None". But 
the problem is, sometimes you WANT them to return None


If you want to detect methods that don't have explicit "return" 
statements, then you'll have to play with abstract syntax trees it 
seems... much trouble for not much gain.

I guess you'll quickly get the pythonic habits without needing all that ^^

Regards,
pascal

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


Re: web access through vpn client

2009-05-02 Thread Martin P. Hellwig

mark.sea...@gmail.com wrote:

On May 1, 5:57 pm, "Martin P. Hellwig" 
wrote:

mark.sea...@gmail.com wrote:

Hi;
I am trying to retrieve financial data off website for stock market
analysis.  Just hobby not for pay.  I actually am impressed that
urllib2 and BeautifulSoup work pretty well to do what I want, and the
first little routine actually gets the data from the web page...
except if my VPN client is turned on.
I've looked around for a solution but can't find... perhaps I'm not
entering the right search words.  I don't even know where to start.
Can anyone suggest some good reading, or basic idea how to approach?
Thanks,
Mark

When the VPN client is on, can you actually still browse the 'classical'
way to the website in question?
I ask this because many cooperate VPN clients have a way of shutting
down all other access besides to the VPN server (which is very annoying
but I can see the logic behind it).

If that is the case your VPN network might have a webproxy which needs
to be configured to continue browsing when connected to the VPN. For
python you can automate this by checking for access to the proxy and use
it if it is there.

--
MPHhttp://blog.dcuktec.com


Yes when Cisco AnyConnect VPN client is connected, I can browse w/
IE.  I think the packets get encrypted and possibly go to my company's
server and out from there, because then also Outlook connects to my
company, Communicator works, etc.  With VPN off I can browse and
Python can get URL, but no connection through my company's server & no
encryption.

Where can I find out more about how to configure the webproxy, if the
info is handy?  Thanks!

Mark


Most likely your IE gets automatically configured for using a proxy when 
the VPN is made, just check your IE settings ounce you are connected to 
the VPN particular the Connection / LAN-connection settings.

Or query what is set in the registry at :
'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
Settings'

And use the content (if set) as the proxy address in the urllib module.

You might find this module useful for that:
http://docs.python.org/library/_winreg.html

--
MPH
http://blog.dcuktec.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Warning of missing side effects

2009-05-02 Thread Martin v. Löwis
> But I'm used to exploiting side effect, and sometimes forget this rule 
> in my own classes. IS THERE A WAY to have the following produce a 
> runtime error?
> 
>def f():
>   x = 5
>   # no return
> 
>y = f()

Typically, this will produce a runtime error fairly quickly,
namely when you *use* the (presumed) return value of f().
You would normally try to perform some computation with y,
or invoke methods on it - and then you see that it is None.

So while it is not possible to get an exception on the
assignment, you will usually get a runtime error sooner
or later (most of the time, sooner).

FWIW, pylint -e reports on your code

E:  5: Assigning to function call which doesn't return

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


Re: Multiprocessing.Queue - I want to end.

2009-05-02 Thread Hendrik van Rooyen
: "Roel Schroeven"  wrote:


> Hendrik van Rooyen schreef:
> > I have always wondered why people do the one queue many getters thing.
> 
> Because IMO it's the simplest and most elegant solution.

That is fair enough...

> > 
> > Given that the stuff you pass is homogenous in that it will require a
> > similar amount of effort to process, is there not a case to be made
> > to have as many queues as consumers, and to round robin the work?
> 
> Could work if the processing time for each work unit is exactly the same
> (otherwise one or more consumers will be idle part of the time), but in
> most cases that is not guaranteed. A simple example is fetching data
> over the network: even if the data size is always the same, there will
> be differences because of network load variations.
> 
> If you use one queue, each consumer fetches a new work unit as soon it
> has consumed the previous one. All consumers will be working as long as
> there is work to do, without having to write any code to do the load
> balancing.
> 
> With one queue for each consumer, you either have to assume that the
> average processing time is the same (otherwise some consumers will be
> idle at the end, while others are still busy processing work units), or
> you need some clever code in the producer(s) or the driving code to
> balance the loads. That's extra complexity for little or no benefit.
> 
> I like the simplicity of having one queue: the producer(s) put work
> units on the queue with no concern which consumer will process them or
> how many consumers there even are; likewise the consumer(s) don't know
> and don't need to know where their work units come from. And the work
> gets automatically distributed to whichever consumer has first finished
> its previous work unit.

This is all true in the case of a job that starts, runs and finishes.
I am not so sure it applies to something that has a long life.

> 
> > And if the stuff you pass around needs disparate effort to consume,
> > it seems to me that you can more easily balance the load by having
> > specialised consumers, instead of instances of one humungous 
> > "I can eat anything" consumer.
> 
> If there is a semantic difference, maybe yes; but I think it makes no
> sense to differentiate purely on the expected execution times.

The idea is basically that you have the code that classifies in one
place only, instead of running in all the instances of the consumer.
Feels better to me, somehow.

> 
> > I also think that having a queue per consumer thread makes it easier
> > to replace the threads with processes and the queues with pipes or
> > sockets if you need to do serious scaling later.
> 
> Perhaps, but isn't that a case of YAGNI and/or premature optimization?

Yes and no:

Yes - You Are Gonna Need It.
and 
No it is never premature to use a decent structure.

:-)

- Hendrik


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


Re: Question about the wording in the python documents.

2009-05-02 Thread Sebastian Wiesner

> I don't understand your objection. Is it that the documentation calls it
> Request instead of urllib2.Request? Or that it calls it an object instead
> of an instance?
I guess the latter ...

> In either case, I think you're picking a nit so small that it isn't
> actually there. All objects are instances (in Python), and all instances
> are objects.
Exactly, so strictly seen, "Request object" could possibly refer to the 
urllib2.Request class itself.  I guess, the OP would prefer the term 
"Request instance", emphasizing, that an instance of the request class has 
to be passed, not he class itself.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)

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


Re: Question about the wording in the python documents.

2009-05-02 Thread Lawrence D'Oliveiro
In message , grocery_stocker wrote:

> req is clearly an instance of urllib2.Request and not a Request object.

"Object" is a term commonly used to mean "instance of a class". In Python, 
classes are also objects, but if classes were meant rather than instances, I 
imagine it would say so.

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


Re: stuck with PyOBEX

2009-05-02 Thread alejandro
I am having problems with connect() it says that it doesn't have sendall 
atribute.

Error:

Traceback (most recent call last):
  File "novi_pokusaj.py", line 25, in 
client.connect()
  File "C:\Python25\lib\PyOBEX\client.py", line 356, in connect
return Client.connect(self, header_list = [headers.Target(uuid)])
  File "C:\Python25\lib\PyOBEX\client.py", line 127, in connect
response = self._send_headers(request, header_list, max_length)
  File "C:\Python25\lib\PyOBEX\client.py", line 81, in _send_headers
self.socket.sendall(request.encode())
AttributeError: BluetoothSocket instance has no attribute 'sendall'>>> Exit 
Code: 1


Did you manage to run it under windows? 


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


Re: File handling problem.

2009-05-02 Thread Steven D'Aprano
On Sat, 02 May 2009 01:26:14 -0700, subhakolkata1234 wrote:

> Dear Group,
> 
> I am using Python2.6 and has created a file where I like to write some
> statistical values I am generating. The statistical values are
> generating in a nice way, but as I am going to write it, it is not
> taking it, the file is opening or closing properly but the values are
> not getting stored. It is picking up arbitrary values from the generated
> set of values and storing it. Is there any solution for it?

Yes. Find the bug in your program and fix it.

If you'd like some help finding the bug, you'll need to give us a little 
bit more information. This website might help you:

http://www.catb.org/~esr/faqs/smart-questions.html



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


Re: object query assigned variable name?

2009-05-02 Thread David Stanek
On Fri, May 1, 2009 at 12:48 PM, Steven D'Aprano
 wrote:
> On Fri, 01 May 2009 09:24:10 -0700, warpcat wrote:
>
>> I'd like it to print, when instanced, something like this:
>>
> s = Spam()
>> I’m assigned to s!
>>
>> But it seems prohibitively hard (based on my web and forum searches) for
>> an object to know what variable name is has been assigned to when
>> created.
>
> Can't be done. Objects don't know what names they are bound to.
>

While objects don't know what they are assigned to, they can be made
to find out. Unless you have a good use case I don't think that you
really want to be doing it.

DecoratorTools allows you to do this. I have code that allows you to
use a a function like:

class C:
attr = inject(Customer)

The inject function does know that it is being assigned to attr. There
is tracing/frame introspection black magic involved. So much so that I
have been debating removing that feature.

The code is on Bitbucket[1]. It has a little extra complication
because inject can also be used as a decorator. The key is the
decorate_assignment call in the inject function.

Again I don't think you really want to do this.

[1] http://bitbucket.org/dstanek/snake-guice/src/tip/snakeguice/decorators.py

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
--
http://mail.python.org/mailman/listinfo/python-list


Re: Warning of missing side effects

2009-05-02 Thread Dave Angel

Tobias Weber wrote:

Hi,
being new to Python I find remarkable that I don't see any side effects. 
That's especially true for binding. First, it is a statement, so this 
won't work:


   if x = q.pop():
  print x # output only true values

Second, methods in the standard library either return a value OR modify 
the reciever, so even if assignment was an expression the above wouldn't 
work.


Only it still wouldn't, because IF is a statement as well. So no ternary:

   x = if True: 5 else: 7;

However there is one bit of magic, functions implicitly return None. So 
while the following will both run without error, only one actually works:


   x = 'foo'.upper()
   y = ['f', 'b'].reverse()

Now I mentioned that the mutable types don't have functions that mutate 
and return something, so I only have to remember that...


But I'm used to exploiting side effect, and sometimes forget this rule 
in my own classes. IS THERE A WAY to have the following produce a 
runtime error?


   def f():
  x = 5
  # no return

   y = f()

Maybe use strict ;)

  

There's a ternary operator.  Check out the following sequence:

a = 42
b = 12 if a == 42 else 9
print a, b


Then try it again with a different value of a.

As for using = in an ordinary expression, I don't really miss it.  
Python allows multiple assignments in the same statement, but they're 
all to the same object.  For the kinds of things where I would have done 
an assignment inside an if or while (in C++), I usually can use a list 
comprehension or somesuch.



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


Re: problem with money datatype based calculations in python

2009-05-02 Thread Günther Dietrich
Krishnakant  wrote:

['money datatype' for database stored values]

What ist the real problem? Do you have problems converting results of 
float calculations to the 'money datatype' before storing them in the 
database, or do you want to avoid the precision issues which come with 
the conversion od non-integer values between binary and decimal?
In the latter case use the Decimal data type from module decimal (comes 
with the python distribution -- it is mentioned in the tutorial).



Regards,

Günther
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with money datatype based calculations in python

2009-05-02 Thread anusha k
Do calculations in postgresql and then call that calculated value from the
python.So no need to calculate in python at all


Njoy the share of Freedom,
Anusha Kadambala
On Sat, May 2, 2009 at 1:15 PM, Krishnakant  wrote:

> hello all,
> I am using postgresql as a database server for my db application.
>
> The database is related to accounts and point of sales and many
> calculations involve money datatype.
>
> The application logic is totally done in python.  Now the problem is
> that there is a situation where we calculate tax on % of the total
> amount on the invoice.  The  percentage is in terms of float but the
> eventual amount has to be in a money datatype.
>
> The product cost comes in money datatype from postgresql and the tax %
> comes in float.  So I would like to know if python supports some thing
> similar to money datatype so that I can cast my total amount (in money )
> divided by tax% (in float ) so money divided by float should be the
> result and that result should be in money datatype.
> For example a product x has the cost Rs. 100 which is stored in the
> tabel as money type.  and in the tax table for that product the VAT is
> 5% and this 5% is stored in float datatype.  So after using both these
> values the resulting total 105Rs. should be in money type and not float.
> I awaite some reply,
> Thanks in advice.
> happy hacking.
> Krishnakant.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Warning of missing side effects

2009-05-02 Thread Arnaud Delobelle
Dave Angel  writes:

> Python allows multiple assignments in the same statement, but they're
> all to the same object.

Unless they are to different objects:

a, b = 1, 2

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


Re: problem with money datatype based calculations in python

2009-05-02 Thread Dave Angel

Krishnakant wrote:

hello all,
I am using postgresql as a database server for my db application.

The database is related to accounts and point of sales and many
calculations involve money datatype.

The application logic is totally done in python.  Now the problem is
that there is a situation where we calculate tax on % of the total
amount on the invoice.  The  percentage is in terms of float but the
eventual amount has to be in a money datatype.

The product cost comes in money datatype from postgresql and the tax %
comes in float.  So I would like to know if python supports some thing
similar to money datatype so that I can cast my total amount (in money )
divided by tax% (in float ) so money divided by float should be the
result and that result should be in money datatype.
For example a product x has the cost Rs. 100 which is stored in the
tabel as money type.  and in the tax table for that product the VAT is
5% and this 5% is stored in float datatype.  So after using both these
values the resulting total 105Rs. should be in money type and not float.
I awaite some reply,
Thanks in advice.
happy hacking.
Krishnakant.


  
Tax rate isn't divided, it's multiplied.  But probably that's just a 
typo in your message.


Short answer is use your money class to convert the float into money.  
And then test, to see that's really what you wanted.  Be sure and check 
the edge cases, because float is a binary system, and you can get both 
quantization and rounding problems converting between them.


Is the money you're dealing with decimal-based?  So maybe money values 
are integers plus two more digits of fractional precision?


It's going to be tough for somebody with no access to that "money type" 
to guess what your problem is.  What operations does it currently 
support?  If it supports multiply, then just change the tax rate to be a 
money type.  Unless of course you might have a tax rate of 5.221%   Does 
your money class support accurate conversion to class decimal?  In that 
case, convert to decimal, multiply, then convert back.


Or if money is really a fixed-point class, with assumed two digits, 
multiply the cost by 100 and convert to int.  Multiply by the tax, and 
convert back.


You also need to specify the government rules for the multiply.  Is 
rounding permitted, or must all fractions of a penny (assumption there) 
be rounded up?


Or switch everything to "class decimal" in the standard python library,  
You still have most of the questions to answer, but at least you'd be 
asking on the right forum.



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


Re: debian apt somehow created python hell! - help

2009-05-02 Thread Paulo Repreza
Hi,

Try this.
# aptitude update
# aptitude update
# aptitude upgrade you can also use # aptitude safe-upgrade

Hope it helps.

Paulo Repreza

On May 1, 2009 7:20 PM, "watermod"  wrote:

I was doing one of those auto apt-get gui things with update manager in
Debian and not watching the error log so I don't know where it started.

It involves only Python stuff.  I don't know Python but apps use it.


The current apt state is that python apps are failing install in:
/usr/sbin/update-python-modules

typical error list looks like:

dpkg: warning - old pre-removal script returned error exit status 1
dpkg - trying script from the new package instead ...
WARNING: python-gtk2-doc.private does not exist.
Some bytecompiled files may be left behind.
Traceback (most recent call last):
 File "/usr/sbin/update-python-modules", line 437, in 
   public_packages[package].install(need_postinstall)
 File "/usr/sbin/update-python-modules", line 232, in __getitem__
   self[name] = SharedFileList (path)
 File "/usr/sbin/update-python-modules", line 146, in __init__
   for line in file(path):
IOError: [Errno 21] Is a directory
dpkg: error processing /var/cache/apt/archives/python-gtk2-
doc_2.14.1-2_all.deb (--unpack):
 subprocess new pre-removal script returned error exit status 1
Traceback (most recent call last):
 File "/usr/sbin/update-python-modules", line 437, in 
   public_packages[package].install(need_postinstall)
 File "/usr/sbin/update-python-modules", line 232, in __getitem__
   self[name] = SharedFileList (path)
 File "/usr/sbin/update-python-modules", line 146, in __init__
   for line in file(path):
IOError: [Errno 21] Is a directory
dpkg: error while cleaning up:

on and on and on
The following:

 dpkg -C

gives:
The following packages are in a mess due to serious problems during
installation.  They must be reinstalled for them (and any packages
that depend on them) to function properly:
 python-reportbug Python modules for interacting with bug tracking
systems
 lsb-release  Linux Standard Base version reporting utility
 python-ogg   Python interface to the Ogg library
 system-config-lvmA utility for graphically configuring Logical
Volumes
 bitpim   utility to communicate with many CDMA phones
 bitpim-lib   architecture-dependent helper files for BitPim
 python-glade2GTK+ bindings: Glade support
 python-gtk2  Python bindings for the GTK+ widget set
 python-feedparserUniversal Feed Parser for Python
 python-gtk2-doc  Python bindings for the GTK+ widget set -
documentation
 k3d  3D modeling and animation system

The following packages have been unpacked but not yet configured.
They must be configured using dpkg --configure or the configure
menu option in dselect for them to work:
 acroread-plugins Plugins for Adobe Acrobat(R) Reader
 python-roman module for generating/analyzing Roman numerals
 python-soappySOAP Support for Python
 python-glpk  Python bindings to the GNU Linear Programming Kit
 python-dialogPython module for making simple Text/Console-mode
user in
 python-biggles   Scientific plotting package for Python
 python-gdPython module wrapper for libgd
 python-clutter   Open GL based interactive canvas library - Python
binding
 python-decoratortools version-agnostic decorators support for Python
 python-fpconst   Utilities for handling IEEE 754 floating point
special va
 acroread-datadata files for acroread
 python-galago-gtkGTK+ widgets for the Galago presence library
(Python inte
 python-utmp  python module for working with utmp
 python-debianbts Python interface to Debian's Bug Tracking System
 python-gobject-dev   Development headers for the GObject Python bindings
 acroread-escript Adobe EScript Plug-In
 python-dhm   collection of Python utilities / helper
 python-unit  unit test framework for Python
 acpidUtilities for using ACPI power management
 python-sqlalchemySQL toolkit and Object Relational Mapper for Python
 python-gnutlsPython wrapper for the GNUTLS library
 python-xlib  Interface for Python to the X11 Protocol
 acroread Adobe Acrobat Reader: Portable Document Format file
viewe
 python-pyinotify simple Linux inotify Python bindings
 python-facebook  Python wrappers for the Facebook API
 reportbugreports bugs in the Debian distribution
 python-ll-core   Python modules for colors, make, cron, daemons,
URLs, tem
 python-beakerSimple WSGI middleware that uses the Myghty
Container API
 python-xcbgenX C Binding - protocol binding generator
 libroot-dev  Header files for ROOT
 python-dcop  DCOP bindings for Python
 python-docutils  utilities for the documentation of Python modules
 libroot-python-dev   Python extension for ROOT - development files
 python-extractor extracts meta-data from files 

Re: stuck with PyOBEX

2009-05-02 Thread David Boddie
On Saturday 02 May 2009 14:25, alejandro wrote:

> I am having problems with connect() it says that it doesn't have sendall
> atribute.
> 
> Error:
> 
> Traceback (most recent call last):
>   File "novi_pokusaj.py", line 25, in 
> client.connect()
>   File "C:\Python25\lib\PyOBEX\client.py", line 356, in connect
> return Client.connect(self, header_list = [headers.Target(uuid)])
>   File "C:\Python25\lib\PyOBEX\client.py", line 127, in connect
> response = self._send_headers(request, header_list, max_length)
>   File "C:\Python25\lib\PyOBEX\client.py", line 81, in _send_headers
> self.socket.sendall(request.encode())
> AttributeError: BluetoothSocket instance has no attribute 'sendall'>>>
> Exit Code: 1
> 
> Did you manage to run it under windows?

I haven't tried to run it under Windows. I just assumed that BluetoothSocket
would have the same API on both Linux and Windows.

Looking around, it seems that this is something we can work around:

http://svn.navi.cx/misc/trunk/laserprop/client/BluetoothConduit.py

I'll send you an updated version to try if you would like to test it.

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


for with decimal values?

2009-05-02 Thread Esmail

Hello all,

Is there a Python construct to allow me to do something like
this:

   for i in range(-10.5, 10.5, 0.1):
 ...

If there is such a thing already available, I'd like
to use it, otherwise I can write a function to mimic this,
but I thought I'd check (my search yielded nothing).

Thanks,
Esmail

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


Re: Profiling gives very different predictions of best algorithm

2009-05-02 Thread Rick
On May 1, 7:38 pm, Terry Reedy  wrote:

> I presume in your overall time text, you ran the two versions of the
> algorith 'naked'.  But, for some reason, you are profiling them embedded
> inside a test suite and runner.  It does not seem that this should
> affect relative timing, but I have seen some pretty strange behaviors.
> At best, it will add noise.
>
> Let me expand my question: what did you do differently between the two
> profile runs?

When I compute the electron repulsion integrals, the two different
methods are:

if packed:
ijkl = intindex(i,j,k,l)
Ints[ijkl] = coulomb(bfs[i],bfs[j],bfs
[k],bfs[l])
else:
val = coulomb(bfs[i],bfs[j],bfs[k],bfs[l])
Ints[i,j,k,l] = val
Ints[j,i,k,l] = val
Ints[i,j,l,k] = val
Ints[j,i,l,k] = val
Ints[k,l,i,j] = val
Ints[k,l,j,i] = val
Ints[l,k,i,j] = val
Ints[l,k,j,i] = val

and when I access the integrals the differences are:

if packed:
index = intindex(i,j,k,l)
temp[kl] = Ints[index]
else:
temp[kl] = Ints[i,j,k,l]

If you look at the profiling, I'm making something like 11M calls to
intindex, which is a routine I've written in C. I thought that by
storing all N**4 integrals (rather than the N**4/8 that packed stores)
would remove the need for the intindex calls and speed things up, but
it's 50% slower. I can't really figure out why it's slower, though,
since profiling makes it look like the slower version is faster.
Something like 30% of the time for the full PyQuante test suite is
taken up with calls to intindex, and I'd like to remove this if
possible.

I also wrote a version of the code where I stored all of the intindex
values in a Python dictionary rather than calling a C function. That
version appeared to be roughly the same speed when I profiled the
code, although I didn't test it without profiling (stupidly) because
at that point I didn't recognize the magnitude of the discrepancy
between the profiling/nonprofiling timings.

I was posting to the list mostly because I would like to know whether
I can do something different when I profile my code so that it give
results that correspond more closely to those that the nonprofiling
results give.

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


Re: for with decimal values?

2009-05-02 Thread Aahz
In article ,
Esmail   wrote:
>
>Is there a Python construct to allow me to do something like this:
>
>for i in range(-10.5, 10.5, 0.1):
>  ...
>
>If there is such a thing already available, I'd like
>to use it, otherwise I can write a function to mimic this,
>but I thought I'd check (my search yielded nothing).

Write a function
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Typing is cheap.  Thinking is expensive."  --Roy Smith
--
http://mail.python.org/mailman/listinfo/python-list


Re: Warning of missing side effects

2009-05-02 Thread Dave Angel

Arnaud Delobelle wrote:

Dave Angel  writes:

  

Python allows multiple assignments in the same statement, but they're
all to the same object.



Unless they are to different objects:

a, b = 1, 2

  
You're right, of course.  I was referring to the multiple '=' form, and 
my statement was too general to be correct.


a = b = 42   is legal
a = (b=42) + 1  is not

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


Re: Question about the wording in the python documents.

2009-05-02 Thread grocery_stocker
On May 2, 4:14 am, Sebastian Wiesner  wrote:
> > I don't understand your objection. Is it that the 
> documentation calls it
> > Request instead of urllib2.Request? Or that it calls it an object instead
> > of an instance?
>
> I guess the latter ...
>
> > In either case, I think you're picking a nit so small that it isn't
> > actually there. All objects are instances (in Python), and all instances
> > are objects.
>
> Exactly, so strictly seen, "Request object" could possibly refer to the
> urllib2.Request class itself.  I guess, the OP would prefer the term
> "Request instance", emphasizing, that an instance of the request class has
> to be passed, not he class itself.
>

Yes, I personally think that the term "Request instance" would have
made it much clearer to us people that have never taken a computer
science class in our lives.
--
http://mail.python.org/mailman/listinfo/python-list


Re: for with decimal values?

2009-05-02 Thread Pascal Chambon

Aahz a écrit :

In article ,
Esmail   wrote:
  

Is there a Python construct to allow me to do something like this:

   for i in range(-10.5, 10.5, 0.1):
 ...

If there is such a thing already available, I'd like
to use it, otherwise I can write a function to mimic this,
but I thought I'd check (my search yielded nothing).



Write a function
  
Else you can work on integers - for i in range (-105, 105) - and divide 
by ten just below... but concerning performances I don't know if it's a 
good idea ^^


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


Re: problem with money datatype based calculations in python

2009-05-02 Thread D'Arcy J.M. Cain
On Sat, 02 May 2009 15:43:23 +0200
"Günther Dietrich"  wrote:
> Krishnakant  wrote:
> 
> ['money datatype' for database stored values]
> 
> What ist the real problem? Do you have problems converting results of 
> float calculations to the 'money datatype' before storing them in the 
> database, or do you want to avoid the precision issues which come with 
> the conversion od non-integer values between binary and decimal?
> In the latter case use the Decimal data type from module decimal (comes 
> with the python distribution -- it is mentioned in the tutorial).

And if you use PyGreSQL (http://www.PyGreSQL.org/) to connect to
the database then the money type is already converted to Decimal.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with money datatype based calculations in python

2009-05-02 Thread Peter Pearson
On Sat, 02 May 2009 13:15:22 +0530, Krishnakant  wrote:
> hello all,
> I am using postgresql as a database server for my db application.
>
> The database is related to accounts and point of sales and many
> calculations involve money datatype.
[snip]

As far as I can tell, Python has no type "money".  Is money
a class defined by some postgresql module you're using?  A
very small amount of specific information (e.g., a five-line
sample program that demonstrates the problem) would greatly
improve your chances of getting useful help.

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


Accessing files in a directory which is a shortcut link (Windows)

2009-05-02 Thread jorma kala
Hi,
I'd like to process files in a directory which is in fact a short cut link
to another directory (under windows XP).
If the path to the directory is for instance called c:\test. I have tried
both following code snipets for printing all names of files in the
directory:

++ snippet 1++

 for filename in glob.glob( os.path.join(r'c:\test', '*') ):
 print filename

++ snippet 2++

 for filename in glob.glob( os.path.join(r'c:\test.lnk', '*') ):
 print filename

Neither solution works.
Thanks very much for any help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Daemonic processes in multiprocessing - solved

2009-05-02 Thread Pascal Chambon

Pascal Chambon a écrit :


Hello everyone


I've just read the doc of the (awesome) "multiprocessing" module, and 
there are some little things I don't understand, concerning daemon 
processes (see quotes below).


When a python process exits, the page says it attempts to join all its 
children. Is this just a design choice, or are there constraints 
behind this ? Because normally, when a parent process exits, its child 
gets adopted by init, and that can be useful for creating daemons, 
can't it ?


Concerning daemons processes, precisely, the manual states that they 
are all terminated when their parent process exits. But isn't it 
contrary to the concept of dameons, which are supposed to have become 
independent from their parent ?


And I don't understand how "the initial value (of the "daemonic" 
attribute) is inherited from the creating process", since "daemonic 
processes are not allowed to create child processes". Isn't it the 
same to say that "daemonic" is always false by default, then ?
And finally, why can't daemonic processes have children ? If these 
children get "orphaned" when the daemonic process gets terminated (by 
its parent), they'll simply get adpoted by init, won't they ?


Thanks a lot for helping me get rid of my confusion,
regards,
Pascal


=QUOTES==
daemon¶ 



The process's daemon flag, a Boolean value. This must be set
before start()


is called.

The initial value is inherited from the creating process.

When a process exits, it attempts to terminate all of its daemonic
child processes.

Note that a daemonic process is not allowed to create child
processes. Otherwise a daemonic process would leave its children
orphaned if it gets terminated when its parent process exits.

--

Similarly, if the child process is non-daemonic then the parent
process may hang on exit when it tries to join all its non-daemonic children.
--
Remember also that non-daemonic
processes will be automatically be joined.

  



--
http://mail.python.org/mailman/listinfo/python-list
  
Allright, I guess I hadn't understand much about "daemonic processes" in 
python's multiprocessing module.


So, for those interested, here is a clarification of the concepts, as 
far as I've understood - please poke me if I'm wrong somewhere.


Usually, in Unix, daemon processes are processes which got disconnected from
their parent process and from terminals, and work in the background, often 
under a
different user identity.
The python multiprocessing module has the concept of "daemon" too, but this
time in reference to the "threading" module, in which dameons are just
threads that wont prevent the application termination, even if they are
still running. Thus, daemonic processes launched through multiprocessing
API are normal processes that will be terminated (and not joined) if 
non-dameonic processes are all over.


Thus, not much in common between "traditionnal" *nix daemon processes, and 
python multiprocessing daemon processes.

Regards, 
pascal



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


Re: Accessing files in a directory which is a shortcut link (Windows)

2009-05-02 Thread Tim Golden

jorma kala wrote:

Hi,
I'd like to process files in a directory which is in fact a short cut link
to another directory (under windows XP).
If the path to the directory is for instance called c:\test. I have tried
both following code snipets for printing all names of files in the
directory:

++ snippet 1++

 for filename in glob.glob( os.path.join(r'c:\test', '*') ):
 print filename

++ snippet 2++

 for filename in glob.glob( os.path.join(r'c:\test.lnk', '*') ):
 print filename



Windows shortcuts are Shell (ie GUI Desktop) objects rather
than filesystem objects. The filesystem doesn't treat them
specially; just returns the .lnk file (or whatever it's
called). You need to invoke the Shell functionality specifically.


import os, sys
import glob
import pythoncom
from win32com.shell import shell, shellcon

def shortcut_target (filename):
 shell_link = pythoncom.CoCreateInstance (
   shell.CLSID_ShellLink, 
   None,
   pythoncom.CLSCTX_INPROC_SERVER, 
   shell.IID_IShellLink

 )
 ipersist = shell_link.QueryInterface (pythoncom.IID_IPersistFile)
 ipersist.Load (filename)
 name, _ = shell_link.GetPath (1)
 return name

def shell_glob (pattern):
 for filename in glob.glob (pattern):
   if filename.endswith (".lnk"):
 yield "%s => %s" % (filename, shortcut_target (filename))
   else:
 yield filename

for filename in shell_glob ("c:/temp/*"):
 print filename



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


Re: for with decimal values?

2009-05-02 Thread Arnaud Delobelle
Esmail  writes:

> Hello all,
>
> Is there a Python construct to allow me to do something like
> this:
>
>for i in range(-10.5, 10.5, 0.1):
>  ...
>
> If there is such a thing already available, I'd like
> to use it, otherwise I can write a function to mimic this,
> but I thought I'd check (my search yielded nothing).
>
> Thanks,
> Esmail

In this particular example, you could do this:

for i in range(-105, 105):
i = 0.1*i
...
In general, you'd have to write your own (generator) function.

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


Re: Accessing files in a directory which is a shortcut link (Windows)

2009-05-02 Thread Tim Golden

Tim Golden wrote:

Windows shortcuts are Shell (ie GUI Desktop) objects rather
than filesystem objects. The filesystem doesn't treat them
specially; just returns the .lnk file (or whatever it's
called). 


As a caveat: they don't actually *have* to be called .lnk
(altho' they almost universally are). That said, I don't know
any straightforward way of otherwise distinguishing shortcut
from non-shortcut files. I think you'd just have to call
.Load on the IPersist instance and catch the E_FAIL
exception.

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


Re: for with decimal values?

2009-05-02 Thread Mark Dickinson
On May 2, 4:12 pm, Esmail  wrote:
> Is there a Python construct to allow me to do something like
> this:
>
>     for i in range(-10.5, 10.5, 0.1):
>       ...

I'd recommend using integer arithmetic:

for ten_times_i in range(-105, 106):
i = ten_times_i / 10.0
...

This has the advantage that it's clear that
you want to include the endpoint 10.5. (*Did*
you want to include the endpoint?)

Presumably you'd want the float version
to be interpreted as:

i = -10.5
while i < 10.5:
...
i += 0.1

(which isn't *quite* right, because the
value of i that you end up with *after* the
while loop has run to completion is 0.1
more than the last value used within the
loop).

The big problem with this is that 0.1
is not exactly representable as a float, and
so the successive additions in the
assignment i += 0.1 are subject to
(small) rounding errors.  As a result, it's
not clear whether the value of i for the last
loop is going to be 10.4+small_error or
10.5-small_error.

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


Re: for with decimal values?

2009-05-02 Thread Esmail

Thanks all, I appreciate the various suggestions and
caveats. Just wanted to make sure I'm not re-inventing
the wheel as Python seems to have already so much.

Cheers,
Esmail

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


Re: Is there any way this queue read can possibly block?

2009-05-02 Thread John Nagle

   That wasn't the problem.  An incoherent bug report from a user
was the problem.

John Nagle

Carl Banks wrote:

On Apr 30, 11:48 am, John Nagle  wrote:

def draininput(self) :  # consume any queued input
 try:
 while True :
 ch = self.inqueue.get_nowait() # get input, if any
 except Queue.Empty:# if empty
 return # done

"self.inqueue" is a Queue object.  The intent here is to drain the
queue, then return.  Is there any way this can possibly block or hang?


Yes, but it'll be waiting to acquire the semaphore which Queues
normally don't hold onto for long.


Carl Banks


I wouldn't think so.  Another thread is doing "put" operations,
but slowly, never more than 5 per second.

(It's working for me, but a user of a program of mine is having a problem.)

John Nagle



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


Re: Question about the wording in the python documents.

2009-05-02 Thread Sebastian Wiesner


> On May 2, 4:14 am, Sebastian Wiesner  wrote:
>> >
>> > In either case, I think you're picking a nit so small that it isn't
>> > actually there. All objects are instances (in Python), and all
>> > instances are objects.
>>
>> Exactly, so strictly seen, "Request object" could possibly refer to the
>> urllib2.Request class itself.  I guess, the OP would prefer the term
>> "Request instance", emphasizing, that an instance of the request class
>> has to be passed, not he class itself.
> 
> Yes, I personally think that the term "Request instance" would have
> made it much clearer to us people that have never taken a computer
> science class in our lives.

Btw, I should have said, that I don't share your objection:  Imho you don't 
need computer science lessons, but only common sense to understand, that 
passing the class object itself doesn't really make sense in this context ;)

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)

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


Convert variable directly into a string (no ASCII)

2009-05-02 Thread Justin Rajewski
Hello,

I need to print variables out over serial, however I need them to not be
in ASCII, ie if the variable is 5 then print 5 not "5".

The function that writes to the serial port requires a string and I can
send non-variables out with the string "/x05" for 5.

Is this even possible?

Thanks,
Justin

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


Re: for with decimal values?

2009-05-02 Thread bearophileHUGS
Esmail:
> Is there a Python construct to allow me to do something like
> this:
>     for i in range(-10.5, 10.5, 0.1):

Sometimes I use an improved version of this:
http://code.activestate.com/recipes/66472/

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: for with decimal values?

2009-05-02 Thread Esmail

bearophileh...@lycos.com wrote:

Esmail:

Is there a Python construct to allow me to do something like
this:
for i in range(-10.5, 10.5, 0.1):


Sometimes I use an improved version of this:
http://code.activestate.com/recipes/66472/


neat .. lots of code to study there. Thanks,
Esmail

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


Re: Multiprocessing.Queue - I want to end.

2009-05-02 Thread Roel Schroeven
Hendrik van Rooyen schreef:
> : "Roel Schroeven"  wrote:

>> ...

> This is all true in the case of a job that starts, runs and finishes.
> I am not so sure it applies to something that has a long life.

It's true that I'm talking about work units with relatively short
lifetimes, mostly a few seconds but perhaps maximum about ten minutes. I
assumed that queues are mostly used for that kind of stuff. I've never
really thought about cases where that assumption doesn't hold, so it's
very well possible that all I've said is invalid in other cases.

>>> And if the stuff you pass around needs disparate effort to consume,
>>> it seems to me that you can more easily balance the load by having
>>> specialised consumers, instead of instances of one humungous 
>>> "I can eat anything" consumer.
>> If there is a semantic difference, maybe yes; but I think it makes no
>> sense to differentiate purely on the expected execution times.
> 
> The idea is basically that you have the code that classifies in one
> place only, instead of running in all the instances of the consumer.
> Feels better to me, somehow.

I most cases that I can imagine (and certainly in all cases I've used),
no classification whatsoever is even needed.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

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


Re: Convert variable directly into a string (no ASCII)

2009-05-02 Thread Stephen Hansen
> I need to print variables out over serial, however I need them to not be
> in ASCII, ie if the variable is 5 then print 5 not "5".
>
> The function that writes to the serial port requires a string and I can
> send non-variables out with the string "/x05" for 5.
>
> Is this even possible?
>

Check out the struct module.

>>> a = 5
>>> struct.pack("b", a)
'\x05'

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


Re: problem with money datatype based calculations in python

2009-05-02 Thread Krishnakant
On Sat, 2009-05-02 at 11:57 -0400, D'Arcy J.M. Cain wrote:
> And if you use PyGreSQL (http://www.PyGreSQL.org/) to connect to
> the database then the money type is already converted to Decimal.
> d'arcy, I visited the home page for pygresql and discovered that you wrote 
> the library.
I am happy that you also included a non-dbapi (postgresql classic
interface ) along with the standard DBAPI module.

I would like to know if it has been tested with postgresql 8.3 and are
there any known bottlenecks while using this driver module on large
scale database opperations?
Is this actively maintained?
Perhaps this might be off topic but may I ask, how is pypgsql, 
>  
Has any one used pgsql for any postgresql based software?
and between pygresql and pypgsql which one is more maintained?

the system I am developing is a mission critical financial application
and I must be pritty sure about any module I am using.

happy hacking.
Krishnakant.



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


Re: Convert variable directly into a string (no ASCII)

2009-05-02 Thread Martin v. Löwis
> I need to print variables out over serial, however I need them to not be
> in ASCII, ie if the variable is 5 then print 5 not "5".
> 
> The function that writes to the serial port requires a string and I can
> send non-variables out with the string "/x05" for 5.
> 
> Is this even possible?

So you have a number N given, between 0 and 255, and you want to send
the byte whose ordinal is N. Right? Send chr(N).

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


Re: Convert variable directly into a string (no ASCII)

2009-05-02 Thread Ulrich Eckhardt
Justin Rajewski wrote:
> I need to print variables out over serial, however I need them to not be
> in ASCII, ie if the variable is 5 then print 5 not "5".
> 
> The function that writes to the serial port requires a string and I can
> send non-variables out with the string "/x05" for 5.

Take a look at the chr() function. For completeness, the complementary one
is ord(). However, also take a look at the 'struct' module, which is the
tool of choice if you want to do other formatting operations.

I seem to remember there was a third tool that can be used for similar
tasks, but I forgot which it was...

Uli

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


Re: Convert variable directly into a string (no ASCII)

2009-05-02 Thread Günther Dietrich
Justin Rajewski  wrote:

>I need to print variables out over serial, however I need them to not be
>in ASCII, ie if the variable is 5 then print 5 not "5".
>
>The function that writes to the serial port requires a string and I can
>send non-variables out with the string "/x05" for 5.

See module struct:

>>> struct.pack('b', 5)
'\x05'
>>> struct.pack('', 5, 150, 3, 224)
'\x05\x96\x03\xe0'



Regards,

Günther
--
http://mail.python.org/mailman/listinfo/python-list


writing consecutive data to subprocess command 'more'

2009-05-02 Thread SanPy
I have this method that prints a given text via a subprocess command
'more' . It is like this:

def print_by_page(text):
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
viewer = 'more -EMR'
proc = subprocess.Popen([viewer], shell=True,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
stdout, stderr = proc.communicate(text)
except OSError:
pass
else:
if stderr: # probably no 'more' available on this system
sys.stdout.write(text)
return
sys.stdout.write(text)

It works fine, but what I really want to do is first print a header
through the 'more' command, then fetch some data from the web, and
show it through the same 'more' command/process. And even more data,
another header, other data from the web, all through the same 'more'
command/process.
Can somebody help me out on this?

Regards,

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


Re: Convert variable directly into a string (no ASCII)

2009-05-02 Thread Tim Roberts
Justin Rajewski  wrote:
>
>I need to print variables out over serial, however I need them to not be
>in ASCII, ie if the variable is 5 then print 5 not "5".
>
>The function that writes to the serial port requires a string and I can
>send non-variables out with the string "/x05" for 5.
>
>Is this even possible?

Of course.  The struct and array modules can help you with this.  Note that
you have to know how big each variable should be.

For example, if you want to sent 1, 2, and 3 out as bytes, you can do:

  a = 1
  b = 2
  c = 3
  serial = struct.pack( 'BBB', a, b, c )

If you need them as 16-bit ints, you can use H instead of B.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to measure the memory cost in Python?

2009-05-02 Thread CTO
> > PS) The asizeof(obj) function from this recipe  > code.activestate.com/recipes/546530> does size the object plus its
> > references, recursively.
>
> Correction, the last sentence should be: The asizeof(obj) ... plus its
> referents, recursively.

I will admit, I have *no idea* what that code is doing, but in looking
through the gc module documentation, I'm seeing the gc.get_objects
function. Would it be equivalent to what the OP is asking to track the
size of every element returned by that?

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


Re: Help! Can't get program to run.

2009-05-02 Thread seanm . py
On May 1, 6:10 pm, Ned Deily  wrote:
> In article <7618rjf1a3t8...@mid.uni-berlin.de>,
>  "Diez B. Roggisch"  wrote:
>
>
>
> > seanm...@gmail.com schrieb:
> > > I think this is maybe the most basic problem possible, but I can't get
> > > even the most basic Python to run on OS X using Terminal or IDLE. I
> > > used the IDLE editor to create a file with one line of code
>
> > > print 'text string'
>
> > > and I saved the file as module1.py. When using terminal I entered
> > > "python" to load the interpreter or whatever and then tried
>
> > > python module1.py
>
> > > but I got an error message. I've tried using the file path instead of
> > > module1.py and that didn't work either. I've tried moving the file to
> > > different places, my desktop, hard drive, etc., and none of that
> > > worked either. In IDLE I tried similar things and only got error
> > > messages there too.
>
> > > Needless to say this is a frustrating start to learning this langauge.
> > > I'd really appreciate any help getting this to work, so I can move on
> > > the actual language. Thanks so much.
>
> > It would have helped if you had given us the *actual* error-message.
> >  From what little information you give, it appears as if you do
> > something very basic wrong - instead of doing
> > $ python
> >  >>> python mymodule.py
> > (where $ is the shell/terminal and >>> the python-prompt)
> > you either do
> > $ python
> >  >>> print "hello"
> > or
> > $ python mymodule.py
> > to execute mymodule directly.
>
> And from within OS X IDLE itself, if you create or open the file
> mymodule.py, it will be in a separate window and, as long as that window
> is selected, you can run the file directly within IDLE by selecting "Run
> Module" from the "Run" menu.   So, no need to use the Terminal if you
> don't want to.
>
> --
>  Ned Deily,
>  n...@acm.org

Thank you for both for the help. I still cannot get the program to run
though. Below I've copied my commands and the error messages for you
(in IDLE then Terminal):

IDLE 2.6.2
>>> python module1.py
SyntaxError: invalid syntax

and

sean-marimpietris-computer:~ seanmarimpietri$ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> python module1.py
  File "", line 1
python module1.py
 ^
SyntaxError: invalid syntax



Again, any help would be appreciated. Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help! Can't get program to run.

2009-05-02 Thread Arnaud Delobelle
seanm...@gmail.com writes:

> sean-marimpietris-computer:~ seanmarimpietri$ python
> Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
 python module1.py
>   File "", line 1
> python module1.py
>  ^
> SyntaxError: invalid syntax
>
>
>
> Again, any help would be appreciated. Thanks.

>From Terminal.app, this should work:

sean-marimpietris-computer:~ seanmarimpietri$ python module1.py

Assuming that your module1.py file is in /Users/seanmarimpietri/

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


Re: writing consecutive data to subprocess command 'more'

2009-05-02 Thread Gabriel Genellina

En Sat, 02 May 2009 15:53:17 -0300, SanPy  escribió:


I have this method that prints a given text via a subprocess command
'more' . It is like this:

def print_by_page(text):
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
viewer = 'more -EMR'
proc = subprocess.Popen([viewer], shell=True,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
stdout, stderr = proc.communicate(text)
except OSError:
pass
else:
if stderr: # probably no 'more' available on this system
sys.stdout.write(text)
return
sys.stdout.write(text)

It works fine, but what I really want to do is first print a header
through the 'more' command, then fetch some data from the web, and
show it through the same 'more' command/process. And even more data,
another header, other data from the web, all through the same 'more'
command/process.
Can somebody help me out on this?


communicate writes to the child's stdin and waits for it to finish. If you  
want to keep writing, don't use communicate. And you'll need to keep state  
from one call to another, so use a class. Based on the code above, create  
a class Pager with __init__, write and close methods:


class Pager:
 def __init__(self):
  # copy the logic above
  self.proc = subprocess.Popen(...)
  self.file = self.proc.stdin
  # if something goes wrong, set self.proc=None and self.file=sys.stdout

 def write(self, text):
  self.file.write(text)

 def close(self):
  if self.proc:
   self.file.close()
   self.proc.wait()

Also, take a look at the pager function in the pydoc module (see the  
source) - it handles several cases.


--
Gabriel Genellina

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


Most Basic Question Ever - please help

2009-05-02 Thread seanm . py
I am going to try posting here again with more detail to see if I can
finally get my first program to work.

I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
in IDLE to create a file. The file had only one line of code and was
saved as module1.py. I saved it to Macintosh HD. The one line of code
in the file is copied below:

print 'Hello module world!'

I closed the file and tried to run it in IDLE and Terminal, but I have
had no success. I'll paste my commands and the error messages below
(for IDLE, then Terminal). Any help would be very much appreciated. I
feel like the marathon just started and I've fallen flat on my face.
Thanks.

IDLE 2.6.2
>>> python module1.py
SyntaxError: invalid syntax


sean-m-computer:~ seanm$ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> python module1.py
  File "", line 1
python module1.py
 ^
SyntaxError: invalid syntax




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


Re: writing consecutive data to subprocess command 'more'

2009-05-02 Thread Piet van Oostrum
> SanPy  (S) wrote:

>S> I have this method that prints a given text via a subprocess command
>S> 'more' . It is like this:

>S> def print_by_page(text):
>S> if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
>S> viewer = 'more -EMR'
>S> proc = subprocess.Popen([viewer], shell=True,
>S> stdin=subprocess.PIPE,
>S> stderr=subprocess.PIPE)
>S> try:
>S> stdout, stderr = proc.communicate(text)
>S> except OSError:
>S> pass
>S> else:
>S> if stderr: # probably no 'more' available on this system
>S> sys.stdout.write(text)
>S> return
>S> sys.stdout.write(text)

>S> It works fine, but what I really want to do is first print a header
>S> through the 'more' command, then fetch some data from the web, and
>S> show it through the same 'more' command/process. And even more data,
>S> another header, other data from the web, all through the same 'more'
>S> command/process.
>S> Can somebody help me out on this?

You have to split this. Do the startup (creating the subprocess) once,
and then for each piece of text that you want to pass through 'more' do
stdout, stderr = proc.communicate(text)

By the way, in this last line, stdout should come out empty because the
output of more doesn't come back to the parent process, but goes to the
original stdout of the calling script.

Also I would use the following:
viewer = ['more', '-EMR']
proc = subprocess.Popen(viewer, stdin=subprocess.PIPE, 
stderr=subprocess.PIPE)
No reason to use a shell.

And if there is no 'more' available you get an exception on the Popen
already. You don't have to wait until the communicate call.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


eric not working on ubuntu 9.04

2009-05-02 Thread bvidinli
any idea ?
here is output:

bvidi...@bvidinli-yenihdd:~$ eric
Warning: translation file 'qt_tr_TR'could not be loaded.
Using default.
Warning: translation file 'qscintilla_tr_TR'could not be loaded.
Using default.
Exception RuntimeError: 'maximum recursion depth exceeded while
calling a Python object' in  ignored
Exception RuntimeError: 'maximum recursion depth exceeded in
__subclasscheck__' in  ignored
An unhandled exception occurred. Please report the problem
using the error reporting dialog or via email to .
A log has been written to "/home/bvidinli/.eric4/eric4_error.log".

Error information:

2009-05-02, 23:42:05

:
cannot import name walk

  File "/usr/share/eric/modules/eric4.py", line 250, in 
main()
  File "/usr/share/eric/modules/eric4.py", line 229, in main
from UI.UserInterface import UserInterface
  File "/usr/share/eric/modules/UI/UserInterface.py", line 66, in 
from EmailDialog import EmailDialog
  File "/usr/share/eric/modules/UI/EmailDialog.py", line 28, in 
from email.MIMEBase import MIMEBase
  File "/usr/lib/python2.6/email/__init__.py", line 79, in __getattr__
__import__(self.__name__)
  File "/usr/lib/python2.6/email/mime/base.py", line 9, in 
from email import message
  File "/usr/lib/python2.6/email/message.py", line 90, in 
class Message:
  File "/usr/lib/python2.6/email/message.py", line 790, in Message
from email.Iterators import walk


Version Numbers:
  Python 2.6.2
  KDE 4.2.2
  PyKDE 4.0.2
  Qt 4.5.0
  PyQt4 4.4.4
  sip sip version not available
  QScintilla 2.3.2
  eric4 4.3.0 (r2852)

Platform: linux2
2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3]

Distribution Info:
  /etc/lsb-release
  DISTRIB_ID=Ubuntu
  DISTRIB_RELEASE=9.04
  DISTRIB_CODENAME=jaunty
  DISTRIB_DESCRIPTION="Ubuntu 9.04"
bvidi...@bvidinli-yenihdd:~$
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help! Can't get program to run.

2009-05-02 Thread seanm . py
On May 2, 4:30 pm, Arnaud Delobelle  wrote:
> seanm...@gmail.com writes:
> > sean-marimpietris-computer:~ seanmarimpietri$ python
> > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.
>  python module1.py
> >   File "", line 1
> >     python module1.py
> >                  ^
> > SyntaxError: invalid syntax
>
> > Again, any help would be appreciated. Thanks.
>
> From Terminal.app, this should work:
>
> sean-marimpietris-computer:~ seanmarimpietri$ python module1.py
>
> Assuming that your module1.py file is in /Users/seanmarimpietri/
>
> --
> Arnaud

Awesome. Thank you, Arnaud. I moved the file to that folder, and I got
it to work in Terminal. However, I still can't get it to run using
IDLE. Any idea why that might be? Thanks again. -Sean
--
http://mail.python.org/mailman/listinfo/python-list


return functions

2009-05-02 Thread gert
Aldo i like the cerrypy wsgi server very much, i do not like the tools
that go with it
so i am stuck with a configuration file that looks like this

http://pastebin.com/m4d8184bc

After 152 line I finally arrived to a point where i was thinkig "thats
it, this is like going to work on a uni cycle and is just plain
ridicules"

So how can i generate some functions something like

def generate(url,type): # where type could be htm js css or wsgi
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing.Queue - I want to end.

2009-05-02 Thread Dave Angel

Hendrik van Rooyen wrote:

: "Roel Schroeven"  wrote:


 

Hendrik van Rooyen schreef:
   

I have always wondered why people do the one queue many getters thing.
  

Because IMO it's the simplest and most elegant solution.



That is fair enough...

 

Given that the stuff you pass is homogenous in that it will require a
similar amount of effort to process, is there not a case to be made
to have as many queues as consumers, and to round robin the work?
  

Could work if the processing time for each work unit is exactly the same
(otherwise one or more consumers will be idle part of the time), but in
most cases that is not guaranteed. A simple example is fetching data
over the network: even if the data size is always the same, there will
be differences because of network load variations.

If you use one queue, each consumer fetches a new work unit as soon it
has consumed the previous one. All consumers will be working as long as
there is work to do, without having to write any code to do the load
balancing.

With one queue for each consumer, you either have to assume that the
average processing time is the same (otherwise some consumers will be
idle at the end, while others are still busy processing work units), or
you need some clever code in the producer(s) or the driving code to
balance the loads. That's extra complexity for little or no benefit.

I like the simplicity of having one queue: the producer(s) put work
units on the queue with no concern which consumer will process them or
how many consumers there even are; likewise the consumer(s) don't know
and don't need to know where their work units come from. And the work
gets automatically distributed to whichever consumer has first finished
its previous work unit.



This is all true in the case of a job that starts, runs and finishes.
I am not so sure it applies to something that has a long life.

 

And if the stuff you pass around needs disparate effort to consume,
it seems to me that you can more easily balance the load by having
specialised consumers, instead of instances of one humungous "I can 
eat anything" consumer.
  

If there is a semantic difference, maybe yes; but I think it makes no
sense to differentiate purely on the expected execution times.



The idea is basically that you have the code that classifies in one
place only, instead of running in all the instances of the consumer.
Feels better to me, somehow.
  
If the classifying you're doing is just based on expected time to 
consume the item, then I think your plan to use separate queues is 
misguided.


If the consumers are interchangeable in their abilities, then feeding 
them from a single queue is more efficient, both on average wait time, 
worst-case wait time, and on consumer utilization, in nearly all 
non-pathological scenarios.  Think the line at the bank.  There's a good 
reason they now have a single line for multiple tellers.  If you have 
five tellers, and one of your transactions is really slow, the rest of 
the line is only slowed down by 20%, rather than a few people being 
slowed down by a substantial amount because they happen to be behind the 
slowpoke.  30 years ago, they'd have individual lines, and I tried in 
vain to explain queuing theory to the bank manager.


Having said that, notice that sometimes the consumers in a computer are 
not independent.  If you're running 20 threads with this model, on a 
processor with only two cores, and if the tasks are CPU bound, you're 
wasting lots of thread-management time without gaining anything.  
Similarly, if there are other shared resources that all the threads trip 
over, it may not pay to do as many of them in parallel.  But for 
homogeneous consumers, do them with a single queue, and do benchmarks to 
determine the optimum number of consumers to start.


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


Re: return functions

2009-05-02 Thread gert
On May 2, 10:44 pm, gert  wrote:
> Aldo i like the cerrypy wsgi server very much, i do not like the tools
> that go with it
> so i am stuck with a configuration file that looks like this
>
> http://pastebin.com/m4d8184bc
>
> After 152 line I finally arrived to a point where i was thinkig "thats
> it, this is like going to work on a uni cycle and is just plain
> ridicules"
>
> So how can i generate some functions something like
>
> def generate(url,type): # where type could be htm js css or wsgi

I was thinking something like this ?

def static(url, mime):
def application(environ, response):
f=open(os.path.join(os.path.dirname(__file__), url),'rb')
l=os.fstat(f.fileno()).st_size
response('200 OK', [('Content-type', mime+';charset=utf-8'),
('Content-Length', str(l))])
return FileWrapper(f, 8192)
return application
--
http://mail.python.org/mailman/listinfo/python-list


Re: writing consecutive data to subprocess command 'more'

2009-05-02 Thread SanPy
Thanks, that works beautifully!

Regards,
Sander

On 2 mei, 22:35, "Gabriel Genellina"  wrote:
> En Sat, 02 May 2009 15:53:17 -0300, SanPy  escribió:
>
>
>
>
>
> > I have this method that prints a given text via a subprocess command
> > 'more' . It is like this:
>
> > def print_by_page(text):
> >     if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
> >         viewer = 'more -EMR'
> >         proc = subprocess.Popen([viewer], shell=True,
> > stdin=subprocess.PIPE,
> >             stderr=subprocess.PIPE)
> >         try:
> >             stdout, stderr = proc.communicate(text)
> >         except OSError:
> >             pass
> >         else:
> >             if stderr: # probably no 'more' available on this system
> >                 sys.stdout.write(text)
> >             return
> >     sys.stdout.write(text)
>
> > It works fine, but what I really want to do is first print a header
> > through the 'more' command, then fetch some data from the web, and
> > show it through the same 'more' command/process. And even more data,
> > another header, other data from the web, all through the same 'more'
> > command/process.
> > Can somebody help me out on this?
>
> communicate writes to the child's stdin and waits for it to finish. If you  
> want to keep writing, don't use communicate. And you'll need to keep state  
>  from one call to another, so use a class. Based on the code above, create  
> a class Pager with __init__, write and close methods:
>
> class Pager:
>   def __init__(self):
>    # copy the logic above
>    self.proc = subprocess.Popen(...)
>    self.file = self.proc.stdin
>    # if something goes wrong, set self.proc=None and self.file=sys.stdout
>
>   def write(self, text):
>    self.file.write(text)
>
>   def close(self):
>    if self.proc:
>     self.file.close()
>     self.proc.wait()
>
> Also, take a look at the pager function in the pydoc module (see the  
> source) - it handles several cases.
>
> --
> Gabriel Genellina

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


Re: Help! Can't get program to run.

2009-05-02 Thread Rhodri James

On Sat, 02 May 2009 21:42:03 +0100,  wrote:


Awesome. Thank you, Arnaud. I moved the file to that folder, and I got
it to work in Terminal. However, I still can't get it to run using
IDLE. Any idea why that might be? Thanks again. -Sean


To repeat what you were told earlier, IDLE is an interactive Python
shell, not a command line.  It executes Python commands directly, like


print "Hello, world"


"python mymodule.py" is *not* a Python command.

To run your script from within IDLE, you have two choices: either
open the script to edit with IDLE (menu File->Open or Ctrl-O) and
use menu Run->Run Module or F5 to run it; or (assuming mymodule.py
is in your home directory) type


import mymodule


The former has a few gotchas that you probably won't hit, and the
latter has several that you almost certainly will hit.  Personally
I'd stick with the command line that you've already succeeded with!

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help! Can't get program to run.

2009-05-02 Thread Ned Deily
In article 
<8f6634a2-c977-430a-b9f2-90ef9356d...@x6g2000vbg.googlegroups.com>,
 seanm...@gmail.com wrote:
> Thank you for both for the help. I still cannot get the program to run
> though. Below I've copied my commands and the error messages for you
> (in IDLE then Terminal):
> 
> IDLE 2.6.2
> >>> python module1.py
> SyntaxError: invalid syntax

The default IDLE window is a python shell window.  That is, you are 
already "inside" the python interpreter, the same as if you typed just 
"python", with no file name, in the Terminal window.  You can use that 
to execute python statements and introspect objects, among other things.  
Try it.

But, back in IDLE, ignore that window for the moment and use the Open 
command in the File Menu to select and open your file module1.py from 
whatever directory it is in.  A new window should open with the contents 
of that file.  With that window selected (click on it, if necessary), 
there should be a "Run" option in the Menu bar and under it will be a 
"Run Script" option that will cause the script to run and the output to 
appear in the shell window.  You can then explore the other options 
available in IDLE for debugging, etc.

-- 
 Ned Deily,
 n...@acm.org

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


Need Help with str.replace & tuples

2009-05-02 Thread mikefromvt
Hello.

I am very very unfamiliar with Python and need to update a Python
script.  What I need to do is to replace three variables (already
defined in the script) within a string.  The present script correctly
replaces two of the three variables.  I am unable to add a third
variable.  Specifically, I would like to add

"panoble",panoble

to the following code:

idxItemStr+=string.replace(string.replace
(idxItemTplStr,"stylenumber",stylenumber),"formalname",formalname)

and, specifically as regards

idxItemTplStr

Is this possible?

Thanks

Mike


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


Re: Most Basic Question Ever - please help

2009-05-02 Thread Stephen Hansen
>
> IDLE 2.6.2
> >>> python module1.py
> SyntaxError: invalid syntax
>

The ">>>" prompt is Python's interactive interpreter. Once you are here, you
already are in python-- so typing "python" again is redundant and invalid.
>From this prompt you type in python code.

I have never used IDLE so can't comment on how to get it to run modules and
collect output-- but I suspect when your file is open in IDLE there's a menu
option that says something about Run.

But


> sean-m-computer:~ seanm$ python
> Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> python module1.py
>  File "", line 1
>python module1.py
> ^
> SyntaxError: invalid syntax
>

Same thing. You're starting python: then doing 'python module1.py' within
Python, which doesn't make sense. If you want Python to run the module, just
do "python module1.py" instead of "python" from your command prompt.

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


Re: Most Basic Question Ever - please help

2009-05-02 Thread Dave Angel

seanm...@gmail.com wrote:

I am going to try posting here again with more detail to see if I can
finally get my first program to work.

I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
in IDLE to create a file. The file had only one line of code and was
saved as module1.py. I saved it to Macintosh HD. The one line of code
in the file is copied below:

print 'Hello module world!'

I closed the file and tried to run it in IDLE and Terminal, but I have
had no success. I'll paste my commands and the error messages below
(for IDLE, then Terminal). Any help would be very much appreciated. I
feel like the marathon just started and I've fallen flat on my face.
Thanks.

IDLE 2.6.2
  

python module1.py


SyntaxError: invalid syntax


sean-m-computer:~ seanm$ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
  

python module1.py


  File "", line 1
python module1.py
 ^
SyntaxError: invalid syntax


  
In both cases, you're already running python.  Why would you expect to 
have to run python inside python?


Once you're at a python prompt (in either of your cases), you use the 
command "import" to load a module.  And you do not put the ".py" 
extension on the parameter.  Specifically, it should look like this, and 
very similar for IDLE.


M:\Programming\Python\sources\temp>c:\ProgFiles\Python26\python.exe
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit 
(Intel)] on

win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import module1
Hello module world!
>>>



  

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


Re: Dictionary, integer compression

2009-05-02 Thread bearophileHUGS
dineshv:
> Thanks for that about Python3.  My integers range from 0 to 9,999,999
> and I have loads of them.  Do you think Python3 will help?

Nope.
Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: return functions

2009-05-02 Thread gert
On May 2, 10:58 pm, gert  wrote:
> On May 2, 10:44 pm, gert  wrote:
>
> > Aldo i like the cerrypy wsgi server very much, i do not like the tools
> > that go with it
> > so i am stuck with a configuration file that looks like this
>
> >http://pastebin.com/m4d8184bc
>
> > After 152 line I finally arrived to a point where i was thinkig "thats
> > it, this is like going to work on a uni cycle and is just plain
> > ridicules"
>
> > So how can i generate some functions something like
>
> > def generate(url,type): # where type could be htm js css or wsgi
>
> I was thinking something like this ?
>
> def static(url, mime):
>     def application(environ, response):
>         f=open(os.path.join(os.path.dirname(__file__), url),'rb')
>         l=os.fstat(f.fileno()).st_size
>         response('200 OK', [('Content-type', mime+';charset=utf-8'),
> ('Content-Length', str(l))])
>         return FileWrapper(f, 8192)
>     return application

it works, i reduced it to this :-)

http://code.google.com/p/appwsgi/source/browse/trunk/server.py

any other suggestions to make it smaller and more automatic ?

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


Re: Need Help with str.replace & tuples

2009-05-02 Thread bearophileHUGS
mikefromvt:
> I am very very unfamiliar with Python and need to update a Python
> script.  What I need to do is to replace three variables (already
> defined in the script) within a string.  The present script correctly
> replaces two of the three variables.  I am unable to add a third
> variable.  Specifically, I would like to add
>
> "panoble",panoble
> to the following code:
> idxItemStr+=string.replace(string.replace
(idxItemTplStr,"stylenumber",stylenumber),"formalname",formalname)

This isn't going to win some contest of coding style quality, but you
may try this (for other people: I have not added any new variable name
on purpose):

idxItemStr += idxItemTplStr.replace("stylenumber",
  stylenumber).replace("formalname",
  formalname).replace("panoble", panoble)

Note that in Python names are usually written like this:
idx_item_tpl
Instead of:
idxItemTplStr

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most Basic Question Ever - please help

2009-05-02 Thread John Machin
On May 3, 7:46 am, Dave Angel  wrote:
> seanm...@gmail.com wrote:
> > I am going to try posting here again with more detail to see if I can
> > finally get my first program to work.
>
> > I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
> > in IDLE to create a file. The file had only one line of code and was
> > saved as module1.py. I saved it to Macintosh HD. The one line of code
> > in the file is copied below:
>
> > print 'Hello module world!'
>
> > I closed the file and tried to run it in IDLE and Terminal, but I have
> > had no success. I'll paste my commands and the error messages below
> > (for IDLE, then Terminal). Any help would be very much appreciated. I
> > feel like the marathon just started and I've fallen flat on my face.
> > Thanks.
>
> > IDLE 2.6.2
>
>  python module1.py
>
> > SyntaxError: invalid syntax
>
> > sean-m-computer:~ seanm$ python
> > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.
>
>  python module1.py
>
> >   File "", line 1
> >     python module1.py
> >                  ^
> > SyntaxError: invalid syntax
>
> In both cases, you're already running python.  Why would you expect to
> have to run python inside python?
>
> Once you're at a python prompt (in either of your cases), you use the
> command "import" to load a module.  And you do not put the ".py"
> extension on the parameter.  Specifically, it should look like this, and
> very similar for IDLE.
>
> M:\Programming\Python\sources\temp>c:\ProgFiles\Python26\python.exe
> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import module1
> Hello module world!
>  >>>

Dave, importing modules which have side effects like printing is NOT a
good habit to which a beginner should be introduced. He needs to know
how to run a script.

Sean, in Terminal, instead of typing
python
type
python module1.py

and I suggest that you give your script (not module) a more meaningful
name.

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


Re: problem with money datatype based calculations in python

2009-05-02 Thread John Machin
On May 3, 12:09 am, Dave Angel  wrote:
> Krishnakant wrote:
> > hello all,
> > I am using postgresql as a database server for my db application.
>
> > The database is related to accounts and point of sales and many
> > calculations involve money datatype.
>
> > The application logic is totally done in python.  Now the problem is
> > that there is a situation where we calculate tax on % of the total
> > amount on the invoice.  The  percentage is in terms of float but the
> > eventual amount has to be in a money datatype.
>
> > The product cost comes in money datatype from postgresql and the tax %
> > comes in float.  So I would like to know if python supports some thing
> > similar to money datatype so that I can cast my total amount (in money )
> > divided by tax% (in float ) so money divided by float should be the
> > result and that result should be in money datatype.
> > For example a product x has the cost Rs. 100 which is stored in the
> > tabel as money type.  and in the tax table for that product the VAT is
> > 5% and this 5% is stored in float datatype.  So after using both these
> > values the resulting total 105Rs. should be in money type and not float.
> > I awaite some reply,
> > Thanks in advice.
> > happy hacking.
> > Krishnakant.
>
> Tax rate isn't divided, it's multiplied.  But probably that's just a
> typo in your message.
>
> Short answer is use your money class to convert the float into money.  
> And then test, to see that's really what you wanted.  Be sure and check
> the edge cases, because float is a binary system, and you can get both
> quantization and rounding problems converting between them.
>
> Is the money you're dealing with decimal-based?  So maybe money values
> are integers plus two more digits of fractional precision?
>
> It's going to be tough for somebody with no access to that "money type"
> to guess what your problem is.  What operations does it currently
> support?  If it supports multiply, then just change the tax rate to be a
> money type.

Aarrgghh!! If the "money type" supports multiplying money by money,
the author should be put in the stocks and pelted with rotten
vegetables.

(IMHO)

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


Re: for with decimal values?

2009-05-02 Thread Ben Finney
Esmail  writes:

> Hello all,
> 
> Is there a Python construct to allow me to do something like
> this:
> 
>for i in range(-10.5, 10.5, 0.1):
>  ...

Note that those values are of type ‘float’, which is a distinct type
from ‘Decimal’ with very different behaviour.

> If there is such a thing already available, I'd like to use it,
> otherwise I can write a function to mimic this, but I thought I'd
> check (my search yielded nothing).

You can write a function to do it.

Alternatively, this case seems simple enough that you can write a
generator expression. Assuming you want ‘Decimal’ values:

>>> from decimal import Decimal
>>> amounts = (Decimal(mantissa)/10 for mantissa in range(-105, 105))
>>> for amount in amounts:
... print amount
...
-10.5
-10.4
-10.3
-10.2
-10.1
-10
-9.9
…
9.6
9.7
9.8
9.9
10
10.1
10.2
10.3
10.4

-- 
 \  “I have a large seashell collection, which I keep scattered on |
  `\the beaches all over the world. Maybe you've seen it.” —Steven |
_o__)   Wright |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help! Can't get program to run.

2009-05-02 Thread seanm . py
On May 2, 5:30 pm, Ned Deily  wrote:
> In article
> <8f6634a2-c977-430a-b9f2-90ef9356d...@x6g2000vbg.googlegroups.com>,
>
>  seanm...@gmail.com wrote:
> > Thank you for both for the help. I still cannot get the program to run
> > though. Below I've copied my commands and the error messages for you
> > (in IDLE then Terminal):
>
> > IDLE 2.6.2
> > >>> python module1.py
> > SyntaxError: invalid syntax
>
> The default IDLE window is a python shell window.  That is, you are
> already "inside" the python interpreter, the same as if you typed just
> "python", with no file name, in the Terminal window.  You can use that
> to execute python statements and introspect objects, among other things.  
> Try it.
>
> But, back in IDLE, ignore that window for the moment and use the Open
> command in the File Menu to select and open your file module1.py from
> whatever directory it is in.  A new window should open with the contents
> of that file.  With that window selected (click on it, if necessary),
> there should be a "Run" option in the Menu bar and under it will be a
> "Run Script" option that will cause the script to run and the output to
> appear in the shell window.  You can then explore the other options
> available in IDLE for debugging, etc.
>
> --
>  Ned Deily,
>  n...@acm.org

Awesome. I think that clears it up (at least enough for now). Thank
you both very much.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most Basic Question Ever - please help

2009-05-02 Thread seanm . py
On May 2, 6:25 pm, John Machin  wrote:
> On May 3, 7:46 am, Dave Angel  wrote:
>
>
>
> > seanm...@gmail.com wrote:
> > > I am going to try posting here again with more detail to see if I can
> > > finally get my first program to work.
>
> > > I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
> > > in IDLE to create a file. The file had only one line of code and was
> > > saved as module1.py. I saved it to Macintosh HD. The one line of code
> > > in the file is copied below:
>
> > > print 'Hello module world!'
>
> > > I closed the file and tried to run it in IDLE and Terminal, but I have
> > > had no success. I'll paste my commands and the error messages below
> > > (for IDLE, then Terminal). Any help would be very much appreciated. I
> > > feel like the marathon just started and I've fallen flat on my face.
> > > Thanks.
>
> > > IDLE 2.6.2
>
> >  python module1.py
>
> > > SyntaxError: invalid syntax
>
> > > sean-m-computer:~ seanm$ python
> > > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> > > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> > > Type "help", "copyright", "credits" or "license" for more information.
>
> >  python module1.py
>
> > >   File "", line 1
> > >     python module1.py
> > >                  ^
> > > SyntaxError: invalid syntax
>
> > In both cases, you're already running python.  Why would you expect to
> > have to run python inside python?
>
> > Once you're at a python prompt (in either of your cases), you use the
> > command "import" to load a module.  And you do not put the ".py"
> > extension on the parameter.  Specifically, it should look like this, and
> > very similar for IDLE.
>
> > M:\Programming\Python\sources\temp>c:\ProgFiles\Python26\python.exe
> > Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> > (Intel)] on
> > win32
> > Type "help", "copyright", "credits" or "license" for more information.
> >  >>> import module1
> > Hello module world!
> >  >>>
>
> Dave, importing modules which have side effects like printing is NOT a
> good habit to which a beginner should be introduced. He needs to know
> how to run a script.
>
> Sean, in Terminal, instead of typing
>     python
> type
>     python module1.py
>
> and I suggest that you give your script (not module) a more meaningful
> name.
>
> HTH,
> John

Great. Thank you both very much. I appreciate the help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: web access through vpn client

2009-05-02 Thread mark . seagoe
On May 2, 3:01 am, "Martin P. Hellwig" 
wrote:
> mark.sea...@gmail.com wrote:
> > On May 1, 5:57 pm, "Martin P. Hellwig" 
> > wrote:
> >> mark.sea...@gmail.com wrote:
> >>> Hi;
> >>> I am trying to retrieve financial data off website for stock market
> >>> analysis.  Just hobby not for pay.  I actually am impressed that
> >>> urllib2 and BeautifulSoup work pretty well to do what I want, and the
> >>> first little routine actually gets the data from the web page...
> >>> except if my VPN client is turned on.
> >>> I've looked around for a solution but can't find... perhaps I'm not
> >>> entering the right search words.  I don't even know where to start.
> >>> Can anyone suggest some good reading, or basic idea how to approach?
> >>> Thanks,
> >>> Mark
> >> When the VPN client is on, can you actually still browse the 'classical'
> >> way to the website in question?
> >> I ask this because many cooperate VPN clients have a way of shutting
> >> down all other access besides to the VPN server (which is very annoying
> >> but I can see the logic behind it).
>
> >> If that is the case your VPN network might have a webproxy which needs
> >> to be configured to continue browsing when connected to the VPN. For
> >> python you can automate this by checking for access to the proxy and use
> >> it if it is there.
>
> >> --
> >> MPHhttp://blog.dcuktec.com
>
> > Yes when Cisco AnyConnect VPN client is connected, I can browse w/
> > IE.  I think the packets get encrypted and possibly go to my company's
> > server and out from there, because then also Outlook connects to my
> > company, Communicator works, etc.  With VPN off I can browse and
> > Python can get URL, but no connection through my company's server & no
> > encryption.
>
> > Where can I find out more about how to configure the webproxy, if the
> > info is handy?  Thanks!
>
> > Mark
>
> Most likely your IE gets automatically configured for using a proxy when
> the VPN is made, just check your IE settings ounce you are connected to
> the VPN particular the Connection / LAN-connection settings.
> Or query what is set in the registry at :
> 'HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet
> Settings'
>
> And use the content (if set) as the proxy address in the urllib module.
>
> You might find this module useful for 
> that:http://docs.python.org/library/_winreg.html
>
> --
> MPHhttp://blog.dcuktec.com- Hide quoted text -
>
> - Show quoted text -

Thanks! I'll check it out.
--
http://mail.python.org/mailman/listinfo/python-list


Re: for with decimal values?

2009-05-02 Thread Esmail

Ben Finney wrote:


Note that those values are of type ‘float’, which is a distinct type
from ‘Decimal’ with very different behaviour.


If there is such a thing already available, I'd like to use it,
otherwise I can write a function to mimic this, but I thought I'd
check (my search yielded nothing).


You can write a function to do it.

Alternatively, this case seems simple enough that you can write a
generator expression. Assuming you want ‘Decimal’ values:

>>> from decimal import Decimal
>>> amounts = (Decimal(mantissa)/10 for mantissa in range(-105, 105))
>>> for amount in amounts:
... print amount
...



Another nice solution stored away for use!

Thanks,
Esmail

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


Can someone please explain to me this code?

2009-05-02 Thread Soumen banerjee
Hello,
I was trying to find a method to make global hotkeys with python in
linux. I found this one which uses a library called python-xlib. The
point is that since i dont have much experience with this, i cant
understand some of the code. Can someone please explain to me how this
code works?  According to the author, it is meant to reduce and
increase volume. Im not interested in that specifically. All i want is
to be ale to bind a hotkey to a function in my python program.

from Xlib.display import Display
from Xlib import X
import oss

# custom keys from my dell D400 Laptop
vol_plus  = 176
vol_moins = 174

keys = [vol_plus,vol_moins]

def changeVolume(aValue):
mixer = oss.open_mixer()
symbol = oss.SOUND_DEVICE_LABELS.index('Vol  ')
left,right  = mixer.read_channel(symbol)

avg = (left + right) / 2
if (avg + aValue) >= 0:
mixer.write_channel(symbol,(left + aValue,right + aValue))
mixer.close()

def handle_event(aEvent):
keycode = aEvent.detail
if aEvent.type == X.KeyPress:
if keycode == vol_moins:
changeVolume(-2)
elif keycode == vol_plus:
changeVolume(+2)

def main():
# current display
disp = Display()
root = disp.screen().root

# we tell the X server we want to catch keyPress event
root.change_attributes(event_mask = X.KeyPressMask)

for keycode in keys:
root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync)

while 1:
event = root.display.next_event()
handle_event(event)

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


Re: eval(WsgiApplication)

2009-05-02 Thread Дамјан Георгиевски
>> > How do I do this in python3?
>>
>> What's wrong with importing it?
> 
> The problem is that my wsgi files have a wsgi extention for mod_wsgi
> use
..
> mod_wsgi has a .wsgi handler because it is recommended to rename the
> wsgi file with wsgi extensions to avoid double imports
> cherrypy server has a dispatcher class


You can either use .py extension for the wsgi files OR use a custom 
importer that can import your .wsgi files
http://docs.python.org/library/modules.html



-- 
дамјан ( http://softver.org.mk/damjan/ )

Scarlett Johansson: You always see the glass half-empty.
Woody Allen: No. I see the glass half-full, but of poison.

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


Re: eval(WsgiApplication)

2009-05-02 Thread gert
On May 2, 2:15 pm, Дамјан Георгиевски  wrote:
> >> > How do I do this in python3?
>
> >> What's wrong with importing it?
>
> > The problem is that my wsgi files have a wsgi extention for mod_wsgi
> > use
> ..
> > mod_wsgi has a .wsgi handler because it is recommended to rename the
> > wsgi file with wsgi extensions to avoid double imports
> > cherrypy server has a dispatcher class
>
> You can either use .py extension for the wsgi files OR use a custom
> importer that can import your .wsgi 
> fileshttp://docs.python.org/library/modules.html
>
> --
> дамјан (http://softver.org.mk/damjan/)
>
> Scarlett Johansson: You always see the glass half-empty.
> Woody Allen: No. I see the glass half-full, but of poison.

I stick with the .py files thank you :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: return functions

2009-05-02 Thread gert
On May 3, 12:17 am, gert  wrote:
> On May 2, 10:58 pm, gert  wrote:
>
>
>
> > On May 2, 10:44 pm, gert  wrote:
>
> > > Aldo i like the cerrypy wsgi server very much, i do not like the tools
> > > that go with it
> > > so i am stuck with a configuration file that looks like this
>
> > >http://pastebin.com/m4d8184bc
>
> > > After 152 line I finally arrived to a point where i was thinkig "thats
> > > it, this is like going to work on a uni cycle and is just plain
> > > ridicules"
>
> > > So how can i generate some functions something like
>
> > > def generate(url,type): # where type could be htm js css or wsgi
>
> > I was thinking something like this ?
>
> > def static(url, mime):
> >     def application(environ, response):
> >         f=open(os.path.join(os.path.dirname(__file__), url),'rb')
> >         l=os.fstat(f.fileno()).st_size
> >         response('200 OK', [('Content-type', mime+';charset=utf-8'),
> > ('Content-Length', str(l))])
> >         return FileWrapper(f, 8192)
> >     return application
>
> it works, i reduced it to this :-)
>
> http://code.google.com/p/appwsgi/source/browse/trunk/server.py
>
> any other suggestions to make it smaller and more automatic ?

Wait a minute why am i not using this ?

http://docs.python.org/3.0/library/wsgiref.html#wsgiref.util.request_uri

And just make my own server ?
--
http://mail.python.org/mailman/listinfo/python-list


yet another list comprehension question

2009-05-02 Thread Ross
I'm trying to set up a simple filter using a list comprehension. If I
have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)]
and I wanted to filter out all tuples containing None, I would like to
get the new list b = [(1,2), (3,4),(6,7)].

I tried b = [i for i in a if t for t in i is not None]   but I get the
error that "t is not defined". What am I doing wrong?
--
http://mail.python.org/mailman/listinfo/python-list


Re: yet another list comprehension question

2009-05-02 Thread Chris Rebert
On Sat, May 2, 2009 at 7:13 PM, Ross  wrote:
> I'm trying to set up a simple filter using a list comprehension. If I
> have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)]
> and I wanted to filter out all tuples containing None, I would like to
> get the new list b = [(1,2), (3,4),(6,7)].

b = [tup for tup in a if None not in tup]

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


Re: yet another list comprehension question

2009-05-02 Thread Ross
On May 2, 7:21 pm, Chris Rebert  wrote:
> On Sat, May 2, 2009 at 7:13 PM, Ross  wrote:
> > I'm trying to set up a simple filter using a list comprehension. If I
> > have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)]
> > and I wanted to filter out all tuples containing None, I would like to
> > get the new list b = [(1,2), (3,4),(6,7)].
>
> b = [tup for tup in a if None not in tup]
>
> Cheers,
> Chris
> --http://blog.rebertia.com

Thanks I feel retarded sometimes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: yet another list comprehension question

2009-05-02 Thread CTO
On May 2, 10:13 pm, Ross  wrote:
> I'm trying to set up a simple filter using a list comprehension. If I
> have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)]
> and I wanted to filter out all tuples containing None, I would like to
> get the new list b = [(1,2), (3,4),(6,7)].

try this:

b = [i for i in a if None not in i]

> I tried b = [i for i in a if t for t in i is not None]   but I get the
> error that "t is not defined". What am I doing wrong?

You've got a "for" and an "if" backwards. t isn't defined when the if
tries to evaluate it.



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


Re: Can someone please explain to me this code?

2009-05-02 Thread CTO
On Sat, May 2, 2009 at 9:41 PM, Soumen banerjee 
wrote:

Hello,
I was trying to find a method to make global hotkeys with python
in
linux. I found this one which uses a library called python-xlib.
The
point is that since i dont have much experience with this, i cant
understand some of the code. Can someone please explain to me how
this
code works?  According to the author, it is meant to reduce and
increase volume. Im not interested in that specifically. All i
want is
to be ale to bind a hotkey to a function in my python program.


It's not so hard. Just a little confusing at first. The thing is that
X is a
client-server protocol, so it doesn't call a function or anything to
let
you know that the user has pressed a key- it just sends all the events
you've asked for to your application, and lets it handle them how it
will. To get a better idea about how that happens, fire up xev (the
X Event Viewer) on your console.

from Xlib.display import Display
from Xlib import X


You still need these


def handle_event(aEvent):
 keycode = aEvent.detail
 if aEvent.type == X.KeyPress:
 if keycode == vol_moins:
 changeVolume(-2)
 elif keycode == vol_plus:
 changeVolume(+2)


(Spacing mine)
You don't really care about this, but the important thing is how
it's structured. It takes an event, then gets its detail attribute,
which is where the key that is pressed will go if it is a keypress,
then sees if its type is KeyPress, then performs the appropriate
action based on that keycode. Your app will do pretty much the
same thing, just with different actions.


def main():
 # current display
 disp = Display()
 root = disp.screen().root

 # we tell the X server we want to catch keyPress event
 root.change_attributes(event_mask = X.KeyPressMask)

 for keycode in keys:
 root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync,
X.GrabModeAsync)

 while 1:
 event = root.display.next_event()
 handle_event(event)

if __name__ == '__main__':
main()


(spacing mine)
While I'd do things a little differently, this is pretty much
boilerplate.
You can use this as a template for what you want to do, assuming
that you've appropriately defined your keycodes and handle_event
function.

Geremy Condra

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


Multiprocessing + Frozen bug?

2009-05-02 Thread Stephen Hansen
In the multiprocessing.forking module, there's:
def get_command_line():
...

if getattr(sys, 'frozen', False):
return [sys.executable, '--multiprocessing-fork']
else:
prog = 'from multiprocessing.forking import main; main()'
return [_python_exe, '-c', prog, '--multiprocessing-fork']

I think that the test there should be "if not getattr(sys, 'frozen',
False):", because if its not frozen then you want to use the sys.executable
-- but if it is, you want to use the one which has been explicitly set. I
think, at least. I'm not quite sure if I want to report it as a bug yet
because I'm very new to multiprocessing and am doing something very
complicated (a windows service using multiprocessing to start various
processes, each of which start arbitrary thirdparty-non-python subprocesses
themselves) so maybe my understanding is wrong.

Or iiis it not?

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


Re: problem with money datatype based calculations in python

2009-05-02 Thread D'Arcy J.M. Cain
On Sun, 03 May 2009 00:07:17 +0530
Krishnakant  wrote:
> On Sat, 2009-05-02 at 11:57 -0400, D'Arcy J.M. Cain wrote:
> > And if you use PyGreSQL (http://www.PyGreSQL.org/) to connect to
> > the database then the money type is already converted to Decimal.
> > d'arcy, I visited the home page for pygresql and discovered that you wrote 
> > the library.

Sorry, I should have mentioned my bias.  :-)

> I am happy that you also included a non-dbapi (postgresql classic
> interface ) along with the standard DBAPI module.

That interface existed before there was a DB-API spec.  We added the
DB-API interface later and decided to support both.

> I would like to know if it has been tested with postgresql 8.3 and are

The current version of PyGreSQL has been tested with Python 2.5 and
PostGreSQL 8.3. Older version should work as well, but you will need
at least Python 2.3 and PostgreSQL 7.4.

> there any known bottlenecks while using this driver module on large
> scale database opperations?

None that I know of.  It is used on some pretty big databases that I
know of.

> Is this actively maintained?

Yes.

I'll leave the rest of the questions for someone less biased.  :-)

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone please explain to me this code?

2009-05-02 Thread Soumen banerjee
Hello,
I'd like a little more help with the following lines:

root.change_attributes(event_mask = X.KeyPressMask)

for keycode in keys:
root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync,
X.GrabModeAsync)

what exactly do they do?
regards
Soumen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most Basic Question Ever - please help

2009-05-02 Thread CM
On May 2, 4:36 pm, seanm...@gmail.com wrote:
> I am going to try posting here again with more detail to see if I can
> finally get my first program to work.
>
> I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
> in IDLE to create a file. The file had only one line of code and was
> saved as module1.py. I saved it to Macintosh HD. The one line of code
> in the file is copied below:
>
> print 'Hello module world!'
>
> I closed the file and tried to run it in IDLE and Terminal, but I have
> had no success. I'll paste my commands and the error messages below
> (for IDLE, then Terminal). Any help would be very much appreciated. I
> feel like the marathon just started and I've fallen flat on my face.
> Thanks.
>
> IDLE 2.6.2>>> python module1.py
>
> SyntaxError: invalid syntax
>
> sean-m-computer:~ seanm$ python
> Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> python module1.py
>
>   File "", line 1
>     python module1.py
>                  ^
> SyntaxError: invalid syntax

Sean, also, keep in mind you can use IDLE to run
your scripts.  After you have saved a script/program,
there is an option for Run in the menu, and then under
that, Run Module.  The output of the script will be
sent to IDLE window indicated as the Python shell.
You can also just test code directly from within
that shell, though for multi-line programs, it is
easier within the composing window.

I suggest you sign up for the Python tutor list:
http://mail.python.org/mailman/listinfo/tutor

And you can search through their big archive of
questions and answers here:
http://www.nabble.com/Python---tutor-f2981.html

The tutors there are great and super-helpful, and
will field any level of question but are particularly
good for absolute beginners.

Here is a tutorial on using IDLE:
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html

And here is a very good general programming tutorial online
book, focusing on Python:
http://www.freenetpages.co.uk/hp/alan.gauld/

Good luck!
Che
--
http://mail.python.org/mailman/listinfo/python-list


Doc strings in descriptors

2009-05-02 Thread Kevin D . Smith

I have a simple descriptor to create a cached property as shown below.

class cproperty(object):
   """ Property whose value is only calculated once and cached """
   def __init__(self, func):
   self._func = func
   self.__doc__ = func.__doc__
   def __get__(self, obj, type=None):
   if obj is None:
   return self
   try:
   return getattr(obj, '@%s' % self._func.func_name)
   except AttributeError:
   result = self._func(obj)
   setattr(obj, '@%s' % self._func.func_name, result)
   return result

The problem is that when I use the help() function on them, I don't get 
the doc string from the function that is being wrapped.  Instead, I get 
the following:


   hasEmployees = 

What do I need to do to get the doc string of the wrapped function to 
apper when using help()?


--
Kevin D. Smith

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


Re: eval(WsgiApplication)

2009-05-02 Thread Graham Dumpleton
On May 2, 10:15 pm, Дамјан Георгиевски  wrote:
> >> > How do I do this in python3?
>
> >> What's wrong with importing it?
>
> > The problem is that my wsgi files have a wsgi extention for mod_wsgi
> > use
> ..
> > mod_wsgi has a .wsgi handler because it is recommended to rename the
> > wsgi file with wsgi extensions to avoid double imports
> > cherrypy server has a dispatcher class
>
> You can either use .py extension for the wsgi files OR use a custom
> importer that can import your .wsgi 
> fileshttp://docs.python.org/library/modules.html

You don't have to go to such an extreme if it is only for one file to
be used as root WSGI application. Can use something like:

  def load_script(filename, label='__wsgi__'):
module = imp.new_module(label)
module.__file__ = filename
execfile(filename, module.__dict__)
return module

  module = load_script('/some/path/file.wsgi')

  application = module.application

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


Re: return functions

2009-05-02 Thread Graham Dumpleton
On May 3, 6:44 am, gert  wrote:
> Aldo i like the cerrypywsgiserver very much, i do not like the tools
> that go with it
> so i am stuck with a configuration file that looks like this
>
> http://pastebin.com/m4d8184bc
>
> After 152 line I finally arrived to a point where i was thinkig "thats
> it, this is like going to work on a uni cycle and is just plain
> ridicules"
>
> So how can i generate some functions something like
>
> def generate(url,type): # where type could be htm js css orwsgi

You seem to have finally discovered that when using Apache/mod_wsgi,
Apache does a level of URL matching to filesystem based resources.
This isn't automatic in normal WSGI servers unless you use a WSGI
middleware that does the mapping for you. :-)

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


Re: eric not working on ubuntu 9.04

2009-05-02 Thread Stefan Behnel
bvidinli wrote:
> An unhandled exception occurred. Please report the problem
> using the error reporting dialog or via email to 
> .
> A log has been written to "/home/bvidinli/.eric4/eric4_error.log".

Did you try that?

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