Re: Another Little MySQL Problem

2010-05-27 Thread Tim Golden

On 26/05/2010 23:24, Christian Heimes wrote:

 Actually, no.  The names of tables are not quoted in SQL.
One writes

SELECT ID FROM mytable;

not

SELECT ID FROM "mytable";


nit picking mode:

Some RDBMS support case sensitive table names. You have to quote the
table name if you using the feature. Yeah I know, it's pretty bad idea
but it's possible.


Also -- at least in MSSQL -- if the table name contains spaces
(and probably certain other characters which I can't be bothered to
research at this moment).

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


Re: confusing error with nntplib

2010-05-27 Thread Alf P. Steinbach

* Eduardo Alvarez, on 27.05.2010 03:01:

When trying to use nntplib to connect to the news server nntp.aioe.org,
a bizarre sequence of events occurs:

1) I import the module, and create an instance, as follows:

s = nntplib.NNTP('nntp.aioe.org')

I get no errors, which leads me to believe all went well. The I try
fetching info on a newsgroup (in this case, comp.lang.python):

s.group('comp.lang.python')

I then get the following error:

Traceback (most recent call last):
   File "", line 1, in
   File "/usr/lib/python2.6/nntplib.py", line 345, in group
 resp = self.shortcmd('GROUP ' + name)
   File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd
 return self.getresp()
   File "/usr/lib/python2.6/nntplib.py", line 214, in getresp
 resp = self.getline()
   File "/usr/lib/python2.6/nntplib.py", line 206, in getline
 if not line: raise EOFError
EOFError


This sounds like a time-out.



Running this a *second* time, gives me the following, different error:

Traceback (most recent call last):
   File "", line 1, in
   File "/usr/lib/python2.6/nntplib.py", line 345, in group
 resp = self.shortcmd('GROUP ' + name)
   File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd
 self.putcmd(line)
   File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd
 self.putline(line)
   File "/usr/lib/python2.6/nntplib.py", line 193, in putline
 self.sock.sendall(line)
   File "", line 1, in sendall
socket.error: [Errno 32] Broken pipe


When you say "running this", do you mean running a Python program a second time, 
or issuing the same command in the interpreter a second time?


For the latter the result would be more or less expected.

After all, you've had an End of File on the connection.



As this is a broken pipe, I reconnect to the server, the same way as
before. When I *then* retrieving the newsgroup's info, I get no errors.

I'm pretty baffled by this. It might be an issue with the server itself,
but still, any input would be very appreciated.


Check if there's any way to specify time-outs.

Check if there's any way to trace the actual commands and responses.


Cheers & hth.,

- Alf


--
blog at http://alfps.wordpress.com>
--
http://mail.python.org/mailman/listinfo/python-list


type error raise

2010-05-27 Thread timo verbeek
what is the problem with this code?

_base={"repeat":False,"string":"Progres has failed","works":True}
print _base
class dictreturn(_base):pass

this error
Traceback (most recent call last):
  File "", line 244, in run_nodebug
  File "C:\Documents and Settings\Owner\Desktop\Python\assistent new
\user\dictreturn.py", line 4, in 
class dictreturn(_base):pass
TypeError: Error when calling the metaclass bases
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type error raise

2010-05-27 Thread Chris Rebert
On Thu, May 27, 2010 at 4:16 AM, timo verbeek  wrote:
> what is the problem with this code?
>
> _base={"repeat":False,"string":"Progres has failed","works":True}
> print _base
> class dictreturn(_base):pass

You can't subclass a dictionary object, you can only subclass other
classes. What on earth are you trying to do?

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


Re: confusing error with nntplib

2010-05-27 Thread Martin P. Hellwig

On 05/27/10 02:01, Eduardo Alvarez wrote:

When trying to use nntplib to connect to the news server nntp.aioe.org,
a bizarre sequence of events occurs:

1) I import the module, and create an instance, as follows:

s = nntplib.NNTP('nntp.aioe.org')

I get no errors, which leads me to believe all went well. The I try
fetching info on a newsgroup (in this case, comp.lang.python):

s.group('comp.lang.python')

I then get the following error:

Traceback (most recent call last):
   File "", line 1, in
   File "/usr/lib/python2.6/nntplib.py", line 345, in group
 resp = self.shortcmd('GROUP ' + name)
   File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd
 return self.getresp()
   File "/usr/lib/python2.6/nntplib.py", line 214, in getresp
 resp = self.getline()
   File "/usr/lib/python2.6/nntplib.py", line 206, in getline
 if not line: raise EOFError
EOFError

Running this a *second* time, gives me the following, different error:

Traceback (most recent call last):
   File "", line 1, in
   File "/usr/lib/python2.6/nntplib.py", line 345, in group
 resp = self.shortcmd('GROUP ' + name)
   File "/usr/lib/python2.6/nntplib.py", line 258, in shortcmd
 self.putcmd(line)
   File "/usr/lib/python2.6/nntplib.py", line 198, in putcmd
 self.putline(line)
   File "/usr/lib/python2.6/nntplib.py", line 193, in putline
 self.sock.sendall(line)
   File "", line 1, in sendall
socket.error: [Errno 32] Broken pipe

As this is a broken pipe, I reconnect to the server, the same way as
before. When I *then* retrieving the newsgroup's info, I get no errors.

I'm pretty baffled by this. It might be an issue with the server itself,
but still, any input would be very appreciated.

yours,



Here is how I approached it:

# Lets see first if the server is available
[mar...@aspire8930 /usr/home/martin]$ telnet nntp.aioe.org nntp
Trying 94.75.214.90...
Connected to nntp.aioe.org.
Escape character is '^]'.
200 nntp.aioe.org InterNetNews NNRP server INN 2.5.1 ready (posting ok)
^]
telnet> quit
Connection closed.
# Okidoki seems fine

# lets fire up python
[mar...@aspire8930 /usr/home/martin]$ python
Python 2.6.4 (r264:75706, Apr  9 2010, 12:45:45)
[GCC 4.2.1 20070719  [FreeBSD]] on freebsd8
Type "help", "copyright", "credits" or "license" for more information.
>>> import nntplib
>>> s = nntplib.NNTP('nntp.aioe.org')
>>> s.group('comp.lang.python')
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.6/nntplib.py", line 345, in group
resp = self.shortcmd('GROUP ' + name)
  File "/usr/local/lib/python2.6/nntplib.py", line 259, in shortcmd
return self.getresp()
  File "/usr/local/lib/python2.6/nntplib.py", line 214, in getresp
resp = self.getline()
  File "/usr/local/lib/python2.6/nntplib.py", line 206, in getline
if not line: raise EOFError
EOFError
# Ah yes the same error, good at least the same problem.

# Lets see what the docs has to say about it.
>>> help(nntplib.NNTP)
Help on class NNTP in module nntplib:

class NNTP
 |  # The class itself
 |
 |  Methods defined here:
 |
 |  __init__(self, host, port=119, user=None, password=None, 
readermode=None, usenetrc=True)

 |  Initialize an instance.  Arguments:
 |  - host: hostname to connect to
 |  - port: port to connect to (default the standard NNTP port)
 |  - user: username to authenticate with
 |  - password: password to use with username
 |  - readermode: if true, send 'mode reader' command after
 |connecting.
 |
 |  readermode is sometimes necessary if you are connecting to an
 |  NNTP server on the local machine and intend to call
 |  reader-specific comamnds, such as `group'.  If you get
 |  unexpected NNTPPermanentErrors, you might need to set
 |  readermode.
 |
# readermode seems to be worth a shot:
>>> s = nntplib.NNTP('nntp.aioe.org', readermode=True)
>>> s.group('comp.lang.python')
('211 2444 50405 52862 comp.lang.python', '2444', '50405', '52862', 
'comp.lang.python')

>>>
# okidoki got something, but I have no idea why, perhaps need to have
# a look at the source to see what that mode actually does.
# But then again I think it would be better if you would do
# that and if you are feeling generous might contribute back
# to this thread what your findings where.

--
mph



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


Re: confusing error with nntplib

2010-05-27 Thread Peter Otten
Eduardo Alvarez wrote:

> When trying to use nntplib to connect to the news server nntp.aioe.org,
> a bizarre sequence of events occurs:
> 
> 1) I import the module, and create an instance, as follows:
> 
> s = nntplib.NNTP('nntp.aioe.org')
> 
> I get no errors, which leads me to believe all went well. The I try
> fetching info on a newsgroup (in this case, comp.lang.python):
> 
> s.group('comp.lang.python')
> 
> I then get the following error:
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.6/nntplib.py", line 345, in group
> resp = self.shortcmd('GROUP ' + name)
>   File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd
> return self.getresp()
>   File "/usr/lib/python2.6/nntplib.py", line 214, in getresp
> resp = self.getline()
>   File "/usr/lib/python2.6/nntplib.py", line 206, in getline
> if not line: raise EOFError
> EOFError

> I'm pretty baffled by this. It might be an issue with the server itself,
> but still, any input would be very appreciated.

I tried your example and got the EOFError, too.

>>> import nntplib
>>> s = nntplib.NNTP("nntp.aioe.org")
>>> s.group("comp.lang.python")
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.6/nntplib.py", line 345, in group
resp = self.shortcmd('GROUP ' + name)
  File "/usr/lib/python2.6/nntplib.py", line 259, in shortcmd
return self.getresp()
  File "/usr/lib/python2.6/nntplib.py", line 214, in getresp
resp = self.getline()
  File "/usr/lib/python2.6/nntplib.py", line 206, in getline
if not line: raise EOFError
EOFError
>>> s = nntplib.NNTP("nntp.aioe.org", readermode=True)
>>> s.group("comp.lang.python")
('211 2445 50405 52863 comp.lang.python', '2445', '50405', '52863', 
'comp.lang.python')

nntplib.NNTP(host, readermode=True) seems to fix the problem (if it wasn't 
sheer luck).

Peter

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


if, continuation and indentation

2010-05-27 Thread HH
I have a question about best practices when it comes to line wrapping/
continuation and indentation, specifically in the case of an if
statement.

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

if (width == 0 and
height == 0 and
color == 'red' and
emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")

The problem should be obvious -- it's not easy to see where the
conditional ends and the statement begins since they have the same
indentation.  Part of the problem, I suppose, is that Emacs indents
'height' and the other lines in the conditional to 4 spaces (because
of the parenthesis).  How do people deal with this situation?

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


Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
Hi;
I have this code:

sql = "insert into %s (%s) values ('%%s');" % (personalDataTable,
string.join(cols[1:], ', '))
#cursor.execute(sql, string.join(vals[1:], "', '"))
cursor.execute('insert into %s (%s) values ("%s");' %
(personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '",
"')))

Now, if I uncomment the 2nd line and comment the third, the command fails
because, apparently, that "');" at the tail end of sql (1st line) gets
chopped off. Why??
TIA,
beno

(Note to self: enterPeople3.py)
-- 
http://mail.python.org/mailman/listinfo/python-list


Minor annoyances with properties

2010-05-27 Thread eb303
Hello all,

I've been using Python properties quite a lot lately and I've found a
few things that are a bit annoying about them in some cases. I
wondered if I missed something or if anybody else has this kind of
problems too, and if there are better solutions than the ones I'm
using ATM.

The first annoyance is when I want to specialize a property in a
subclass. This happens quite often actually, and it is even sometimes
the reason why a plain attribute is turned into a property: a subclass
needs to do more things than the superclass when the property is
updated for example. So, of course, my first try was:

class A(object):
  def __init__(self):
self._p = None
  def _get_p(self):
return self._p
  def _set_p(self, p):
self._p = p
  p = property(_get_p, _set_p)
class B(A):
  def _set_p(self, p):
## Additional things here…
super(B, self)._set_p(p)

And of course, it doesn't work: the property has been bound to
A._set_p in A, so any new definition of _set_p in any subclass does
not replace the set method for the property. So I always have to add a
line:
p = property(A._get_p, _set_p)
in the subclass too. This is a bit awkward to me, since I have to
specify the superclass's name (super(…) can't be used, since it should
take B as an argument, and B isn't defined yet…). Do I miss something?
Is this the way to do it, or is there a better one?


The second annoyance is when I have a property that is a list of
something. I often have to do something when the contents of the list
is modified. So basically, I often end up doing the following:
def C(object):
  def __init__(self):
self._l = []
  def _get_l(self):
return list(self._l)
  def _set_l(self, l):
self._l = list(l)
  l = property(_get_l, _set_l)
But then, I have to do:
o = C()
l = o.l
l.append(42)
o.l = l
instead of just doing:
o.l.append(42)
which would seem much more natural IMHO.

Is there any not too complicated way to have o.l.append(…) call
something in C? And the same for o.l.remove(…), o.l[i] = …, and
everything else updating the list contents?

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


Re: if, continuation and indentation

2010-05-27 Thread Xavier Ho
On 27 May 2010 22:22, HH  wrote:

>if (width == 0 and
>height == 0 and
>color == 'red' and
>emphasis == 'strong' or
>highlight > 100):
>raise ValueError("sorry, you lose")
>

I've gotta say - I've bumped into this problem before, and I'm sure many
other have - this is a valid question. It just hasn't bothered me enough to
ask...

Correct me if I'm wrong, but I think the following is equivalent, and looks
better. Although this won't fix all ugly cases in that problem.

if (width, height, color, emphasis) == (0, 0, 'red', 'strong') or highlight
> 100:
raise ValueError("sorry, you lose")

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


Re: if, continuation and indentation

2010-05-27 Thread Martin P. Hellwig

On 05/27/10 13:22, HH wrote:

I have a question about best practices when it comes to line wrapping/
continuation and indentation, specifically in the case of an if
statement.

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

 if (width == 0 and
 height == 0 and
 color == 'red' and
 emphasis == 'strong' or
 highlight>  100):
 raise ValueError("sorry, you lose")

The problem should be obvious -- it's not easy to see where the
conditional ends and the statement begins since they have the same
indentation.  Part of the problem, I suppose, is that Emacs indents
'height' and the other lines in the conditional to 4 spaces (because
of the parenthesis).  How do people deal with this situation?

Thanks,
Henrik


Well style guide aside (if pylint is happy with it, so am I) it depends 
on what I want to emphasize.


For example if it is really one long line with every item in it being 
equally important I do this:
if width == 0 and height == 0 and color == 'red' and emphasis == 
'strong' \
 or 
highlight > 100:

raise ValueError("sorry, you lose")

In case it doesn't display correctly, I break up the line to nearest 
80th character and align the remaining part on the next line to the 
right to the 80th character.


If I want to emphasize visually a certain part I would do something like 
this:


if width == 0 and height == 0 and color == 'red' \
   and emphasis == 'strong' or highlight > 100:
raise ValueError("sorry, you lose")

But these are my preference, and since it is most likely that I have to
read again what I have written I write it in a way that it is most 
readable to me within the constraints of pylint.


--
mph

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


Re: if, continuation and indentation

2010-05-27 Thread Jean-Michel Pichavant

HH wrote:

I have a question about best practices when it comes to line wrapping/
continuation and indentation, specifically in the case of an if
statement.

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

if (width == 0 and
height == 0 and
color == 'red' and
emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")

The problem should be obvious -- it's not easy to see where the
conditional ends and the statement begins since they have the same
indentation.  Part of the problem, I suppose, is that Emacs indents
'height' and the other lines in the conditional to 4 spaces (because
of the parenthesis).  How do people deal with this situation?

Thanks,
Henrik
  

One possible solution

   if (
   width == 0 and
   height == 0 and
   color == 'red' and
   emphasis == 'strong' or
   highlight > 100
  ):
   raise ValueError("sorry, you lose")


JM  
--

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


Re: Minor annoyances with properties

2010-05-27 Thread Neil Cerutti
On 2010-05-27, eb303  wrote:
> I've been using Python properties quite a lot lately and I've
> found a few things that are a bit annoying about them in some
> cases. I wondered if I missed something or if anybody else has
> this kind of problems too, and if there are better solutions
> than the ones I'm using ATM.

> The first annoyance is when I want to specialize a property in a
> subclass. 

See:

URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20property.xhtml

-- 
Neil Cerutti
*** You found a dead moose-rat. You sell the hide for $200. ***
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if, continuation and indentation

2010-05-27 Thread Xavier Ho
On 27 May 2010 22:57, Jean-Michel Pichavant  wrote:

> One possible solution
>
>   if (
>   width == 0 and
>   height == 0 and
>   color == 'red' and
>   emphasis == 'strong' or
>   highlight > 100
>  ):
>   raise ValueError("sorry, you lose")
>
> But... but you have a sad face in one line! :(

Good trick.

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


Re: Minor annoyances with properties

2010-05-27 Thread Christian Heimes

 Do I miss something?
Is this the way to do it, or is there a better one?


A better way was introduced in Python 2.6. See 
http://docs.python.org/library/functions.html?highlight=property#property

I have a Python only version around if you are still using Python 2.5.

Christian

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


Re: if, continuation and indentation

2010-05-27 Thread Xavier Ho
On 27 May 2010 22:57, Jean-Michel Pichavant  wrote:

>  One possible solution
>>
>>   if (
>>   width == 0 and
>>   height == 0 and
>>   color == 'red' and
>>   emphasis == 'strong' or
>>   highlight > 100
>>  ):
>>   raise ValueError("sorry, you lose")
>>
>
Oh, one minor optimisation. You can put the last condition first:

  if (
  highlight > 100 or
  width == 0 and
  height == 0 and
  color == 'red' and
  emphasis == 'strong'
 ):
  raise ValueError("sorry, you lose")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 8:34 AM, Victor Subervi wrote:

> Hi;
> I have this code:
>
> sql = "insert into %s (%s) values ('%%s');" % (personalDataTable,
> string.join(cols[1:], ', '))
> #cursor.execute(sql, string.join(vals[1:], "', '"))
> cursor.execute('insert into %s (%s) values ("%s");' %
> (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '",
> "')))
>
> Now, if I uncomment the 2nd line and comment the third, the command fails
> because, apparently, that "');" at the tail end of sql (1st line) gets
> chopped off. Why??
>
> (Note to self: enterPeople3.py)
>

...and here's another one:

print 'insert into categories (Store, Category, Parent) values("%s",
"%s", Null)'% (store, cat)
#cursor.execute('insert into categories (Store, Category, Parent)
values("%s", "%s", Null)', (store, cat))

If I print out and manually insert, all goes well. If I uncomment the 2nd
line, it inserts store and cat with single quote marks and screws everything
up!

mysql> select * from categories;
+++++
| ID | Store  | Category   | Parent |
+++++
|  1 | 'products' | 'prodCat1' | NULL   |
|  2 | 'products' | 'prodCat2' | NULL   |
+++++

as opposed to

mysql> select * from categories;
+++++
| ID | Store  | Category   | Parent |
+++++
|  1 | products | prodCat1 | NULL   |
|  2 | products | prodCat2 | NULL   |
+++++

TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if, continuation and indentation

2010-05-27 Thread Xavier Ho
On 27 May 2010 23:26, Xavier Ho  wrote:

> Oh, one minor optimisation. You can put the last condition first
>

I take that back. You really can't, without using more parans or ifs.
Apologies.

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


Re: if, continuation and indentation

2010-05-27 Thread Tim Chase

On 05/27/2010 07:22 AM, HH wrote:

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

 if (width == 0 and
 height == 0 and
 color == 'red' and
 emphasis == 'strong' or
 highlight>  100):
 raise ValueError("sorry, you lose")


While it's not PEP material, I tend to use the coding standards I 
learned working for Computer Sciences Corporation (10 yrs ago, so 
things may have changed) that mandated 2 levels of indentation 
for continued lines, turning the above into


  if (width == 0 and
  height == 0 and
  color == 'red' and
  emphasis == 'strong' or
  highlight>  100):
  # or the closing "):" on this line,
  # aligned with the previous line
  raise ValueError("sorry, you lose")

which is fairly close to Jean-Michel's proposal.

-tkc



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


Re: Yet Another MySQL Problem

2010-05-27 Thread Kushal Kumaran
On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote:
> Hi;
> I have this code:
> 
> sql = "insert into %s (%s) values ('%%s');" % (personalDataTable,
> string.join(cols[1:], ', '))
> #cursor.execute(sql, string.join(vals[1:], "', '"))
> cursor.execute('insert into %s (%s) values ("%s");' %
> (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:],
> '", "')))
> 
> Now, if I uncomment the 2nd line and comment the third, the command
> fails because, apparently, that "');" at the tail end of sql (1st
> line) gets chopped off. Why??

That's not why it is failing.

The second argument to cursor.execute must be a tuple of values that
will be escaped and interpolated into the query.  You are passing in a
string instead.

Also, you'll need as many %s in the values clause as the number of
columns you have.  Basically, the query needs to be something like:

insert into tablename (col1, col2, col3) values (%s, %s, %s)

and the tuple argument to cursor.execute will have to have three values.

Also, lose the single quotes around the %s.

-- 
regards,
kushal


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


Re: Yet Another MySQL Problem

2010-05-27 Thread Kushal Kumaran
On Thu, 2010-05-27 at 09:34 -0400, Victor Subervi wrote:
> On Thu, May 27, 2010 at 8:34 AM, Victor Subervi
>  wrote:
> Hi;
> I have this code:
> 
> sql = "insert into %s (%s) values ('%%s');" %
> (personalDataTable, string.join(cols[1:], ', '))
> #cursor.execute(sql, string.join(vals[1:], "', '"))
> cursor.execute('insert into %s (%s) values ("%s");' %
> (personalDataTable, string.join(cols[1:], ', '),
> string.join(vals[1:], '", "')))
> 
> Now, if I uncomment the 2nd line and comment the third, the
> command fails because, apparently, that "');" at the tail end
> of sql (1st line) gets chopped off. Why??
> 
> (Note to self: enterPeople3.py)
> 
> ...and here's another one:
> 
> print 'insert into categories (Store, Category, Parent)
> values("%s", "%s", Null)'% (store, cat)
> #cursor.execute('insert into categories (Store, Category,
> Parent) values("%s", "%s", Null)', (store, cat))
> 

Lose the quotes around the %s.  I'm pretty sure somebody mentioned this
in the previous MySQL problem thread.

-- 
regards,
kushal



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


Re: if, continuation and indentation

2010-05-27 Thread MRAB

HH wrote:

I have a question about best practices when it comes to line wrapping/
continuation and indentation, specifically in the case of an if
statement.

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

if (width == 0 and
height == 0 and
color == 'red' and
emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")

The problem should be obvious -- it's not easy to see where the
conditional ends and the statement begins since they have the same
indentation.  Part of the problem, I suppose, is that Emacs indents
'height' and the other lines in the conditional to 4 spaces (because
of the parenthesis).  How do people deal with this situation?


I would probably use half-indentation:

if (width == 0 and
  height == 0 and
  color == 'red' and
  emphasis == 'strong' or
  highlight > 100):
raise ValueError("sorry, you lose")

Try doing that with tabs! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran
wrote:

> On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote:
> > Hi;
> > I have this code:
> >
> > sql = "insert into %s (%s) values ('%%s');" % (personalDataTable,
> > string.join(cols[1:], ', '))
> > #cursor.execute(sql, string.join(vals[1:], "', '"))
> > cursor.execute('insert into %s (%s) values ("%s");' %
> > (personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:],
> > '", "')))
> >
> > Now, if I uncomment the 2nd line and comment the third, the command
> > fails because, apparently, that "');" at the tail end of sql (1st
> > line) gets chopped off. Why??
>
> That's not why it is failing.
>
> The second argument to cursor.execute must be a tuple of values that
> will be escaped and interpolated into the query.  You are passing in a
> string instead.
>

So I tried this:

sql = "insert into %s (%s) values (%%s);" % (personalDataTable,
string.join(cols[1:], ', '))
cursor.execute(sql, vals[1:])

and got this:

A problem occurred in a Python script. Here is the sequence of function
calls leading up to the error, in the order they occurred.
 /var/www/html/angrynates.com/cart/enterPeople3.py
   85   print "Enter more
personal data?" % personalDataTable
   86   print "Enter products?"
   87   print '\n'
   88
   89 enterPeople3()
enterPeople3 = 
 /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3()
   42 # We will not include the ID column
   43 sql = "insert into %s (%s) values (%%s);" % (personalDataTable,
string.join(cols[1:], ', '))
   44 cursor.execute(sql, vals[1:])
   45 #cursor.execute(sql, string.join(vals[1:], "', '"))
   46 #cursor.execute('insert into %s (%s) values ("%s");' %
(personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '",
"')))
cursor = , cursor.execute = >, sql = 'insert into
doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState)
values (%s);', vals = ['Null', 'prescriptions', 'Beno', 'Candelon', '123',
'456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
'00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR']
 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=, query='insert into
doctorsPersonalData (Store, FirstNam...OB, Email, PW, State, ShippingState)
values (%s);', args=['prescriptions', 'Beno', 'Candelon', '123', '456',
'789', '11 here', '', 'csted', '00820', '22 there', '', 'csted', '00820',
'2000-01-01', 'benoismyname', '12345', 'CA', 'AR'])
  146 query = query.encode(charset)
  147 if args is not None:
  148 query = query % db.literal(args)
  149 try:
  150 r = self._query(query)
query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email, PW,
State, ShippingState) values (%s);', db = , db.literal = >, args =
['prescriptions', 'Beno', 'Candelon', '123', '456', '789', '11 here', '',
'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01',
'benoismyname', '12345', 'CA', 'AR']

TypeError: not all arguments converted during string formatting
  args = ('not all arguments converted during string formatting',)

You sure about not converting to string??


Also, lose the single quotes around the %s.
>

Well, sure, if not converting to string. Otherwise it's needed. Dennis
advised not using quotes, but what he meant was not using double quotes.
Single quotes, I have found by experimentation, do work.
TIA
beno

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


Re: Yet Another MySQL Problem

2010-05-27 Thread Kushal Kumaran
On Thu, 2010-05-27 at 10:30 -0400, Victor Subervi wrote:
> On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran
>  wrote:
> 
> On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote:
> > Hi;
> > I have this code:
> >
> > sql = "insert into %s (%s) values ('%%s');" %
> (personalDataTable,
> > string.join(cols[1:], ', '))
> > #cursor.execute(sql, string.join(vals[1:], "', '"))
> > cursor.execute('insert into %s (%s) values ("%s");' %
> > (personalDataTable, string.join(cols[1:], ', '),
> string.join(vals[1:],
> > '", "')))
> >
> > Now, if I uncomment the 2nd line and comment the third, the
> command
> > fails because, apparently, that "');" at the tail end of sql
> (1st
> > line) gets chopped off. Why??
> 
> 
> That's not why it is failing.
> 
> The second argument to cursor.execute must be a tuple of
> values that
> will be escaped and interpolated into the query.  You are
> passing in a
> string instead.
> 
> So I tried this:
> 
> sql = "insert into %s (%s) values (%%s);" % (personalDataTable,
> string.join(cols[1:], ', '))
> cursor.execute(sql, vals[1:])
> 
> and got this:
> 

> 

> query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email,
> PW, State, ShippingState) values (%s);', db =  0x2b4c17e707e0 to Connection>, db.literal =  Connection.literal of <_mysql.connection open to 'localhost' at
> e6b08c0>>, args = ['prescriptions', 'Beno', 'Candelon', '123', '456',
> '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
> '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR']
> 
> TypeError: not all arguments converted during string formatting
>   args = ('not all arguments converted during string
> formatting',)  
> 
> 
> You sure about not converting to string??
> 

Yep, pretty sure.  You still need to have as many %s in the query string
as the number of values.  Since you seem to be passing in 19 values (by
a rough count), the query string must be like this:

insert into doctorsPersonalData (Store, FirstNam.) values
(%s, %s, %s, ...19 of these)

not

insert into doctorsPersonalData (Store, FirstNam.) values
(%s)

The exception with the "not all arguments converted" message says you
have too few %s.

> 
> 
> Also, lose the single quotes around the %s.
> 
> Well, sure, if not converting to string. Otherwise it's needed. Dennis
> advised not using quotes, but what he meant was not using double
> quotes. Single quotes, I have found by experimentation, do work.

You seem to have a strange definition of "work".

-- 
regards,
kushal



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


Re: if, continuation and indentation

2010-05-27 Thread Harald Luessen
On Thu, 27 May 2010 HH wrote:

>I have a question about best practices when it comes to line wrapping/
>continuation and indentation, specifically in the case of an if
>statement.
>
>if (width == 0 and
>height == 0 and
>color == 'red' and
>emphasis == 'strong' or
>highlight > 100):
>raise ValueError("sorry, you lose")

My solution would probably look like this:

if (   width == 0
   and height == 0
   and color == 'red'
   and emphasis == 'strong'
or highlight > 100
   ):
raise ValueError("sorry, you lose")

Harald

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


Re: if, continuation and indentation

2010-05-27 Thread Alain Ketterlin
HH  writes:

> if (width == 0 and
> height == 0 and
> color == 'red' and
> emphasis == 'strong' or
> highlight > 100):
> raise ValueError("sorry, you lose")

I prefer to see the "and" at the beginning of continuation lines, and
usually group related items. I never mix operators without putting
explicit parentheses. Something like:

 if  (  width == 0 and height == 0
and color == 'red'
and ( emphasis == 'strong' or highlight > 100 ) ):
 raise ValueError("sorry, you lose")

Anyway, choose your style and stick to it.

> The problem should be obvious -- it's not easy to see where the
> conditional ends and the statement begins since they have the same
> indentation.  Part of the problem, I suppose, is that Emacs indents
> 'height' and the other lines in the conditional to 4 spaces (because
> of the parenthesis).

Emacs aligns "height" with "width", not with the parenthesis. You can
put as many spaces as you want before "(" or between "(" and "width",
and the following lines will follow. At least that's what happens with
my stock emacs-snapshot on ubuntu, with python.el.

If you use a backslashes at the end of line, emacs will double-indent
the following lines, but I think you said you prefer paretheses...

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


Re: multiprocessing and accessing server's stdout

2010-05-27 Thread Tim Arnold
On May 26, 4:52 pm, Adam Tauno Williams 
wrote:
> On Wed, 2010-05-26 at 11:47 -0700, Tim Arnold wrote:
> > Hi,
> > I'm using multiprocessing's BaseManager to create a server on one
> > machine and a client on another. The client fires a request and the
> > server does some work, the result of which ends up on a shared file
> > system that both the client and server can see.
> > However, I need the client machine to see the stdout of the process
> > running on the server. Not sure this is doable--I've been unable to
> > google anything useful on this one.
>
> Nope, it isn't.  Don't use stdout, use an IPC mechanism to communicate
> between the client and the server if you need feedback.
> --
> Adam Tauno Williams  LPIC-1, Novell CLA
> 
> OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

Thanks for that info, it saves me some time. This is a new area for me
though: do you redirect stdout on the server to a socket and have the
client listen and somehow pipe the sockets contents to the client
stdout?

Interestingly, the RPYc package manages it--that is, the client gets
the stdout of the server process, so I'll dig into that code to get an
idea. In the meantime, are there any recipes or other docs that would
be helpful? I've been googling but without much luck.

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


Re: if, continuation and indentation

2010-05-27 Thread Jean-Michel Pichavant

MRAB wrote:

HH wrote:

I have a question about best practices when it comes to line wrapping/
continuation and indentation, specifically in the case of an if
statement.

When I write an if statement with many conditions, I prefer to use a
parenthesis around the whole block and get the implicit continuation,
rather than ending each line with an escape character.  Thus, using
the example from the style guide (http://www.python.org/dev/peps/
pep-0008/) I would write:

if (width == 0 and
height == 0 and
color == 'red' and
emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")

The problem should be obvious -- it's not easy to see where the
conditional ends and the statement begins since they have the same
indentation.  Part of the problem, I suppose, is that Emacs indents
'height' and the other lines in the conditional to 4 spaces (because
of the parenthesis).  How do people deal with this situation?


I would probably use half-indentation:

if (width == 0 and
  height == 0 and
  color == 'red' and
  emphasis == 'strong' or
  highlight > 100):
raise ValueError("sorry, you lose")

Try doing that with tabs! :-)


   if (width ==0 and
' \\  // ' and height == 0 and
'  \\//  ' and color == 'red' and
'   /OO\ ' and emphasis == 'strong' and
'   \> 100):
   raise ValueError("sorry, you lose")

Try doing this with spaces !! :p

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


Re: Yet Another MySQL Problem

2010-05-27 Thread Kushal Kumaran
On Thu, 2010-05-27 at 20:47 +0530, Kushal Kumaran wrote:
> On Thu, 2010-05-27 at 10:30 -0400, Victor Subervi wrote:
> > On Thu, May 27, 2010 at 10:17 AM, Kushal Kumaran
> >  wrote:
> > 
> > On Thu, 2010-05-27 at 08:34 -0400, Victor Subervi wrote:
> > > Hi;
> > > I have this code:
> > >
> > > sql = "insert into %s (%s) values ('%%s');" %
> > (personalDataTable,
> > > string.join(cols[1:], ', '))
> > > #cursor.execute(sql, string.join(vals[1:], "', '"))
> > > cursor.execute('insert into %s (%s) values ("%s");' %
> > > (personalDataTable, string.join(cols[1:], ', '),
> > string.join(vals[1:],
> > > '", "')))
> > >
> > > Now, if I uncomment the 2nd line and comment the third, the
> > command
> > > fails because, apparently, that "');" at the tail end of sql
> > (1st
> > > line) gets chopped off. Why??
> > 
> > 
> > That's not why it is failing.
> > 
> > The second argument to cursor.execute must be a tuple of
> > values that
> > will be escaped and interpolated into the query.  You are
> > passing in a
> > string instead.
> > 
> > So I tried this:
> > 
> > sql = "insert into %s (%s) values (%%s);" % (personalDataTable,
> > string.join(cols[1:], ', '))
> > cursor.execute(sql, vals[1:])
> > 
> > and got this:
> > 
> 
> > 
> 
> > query = 'insert into doctorsPersonalData (Store, FirstNam...OB, Email,
> > PW, State, ShippingState) values (%s);', db =  > 0x2b4c17e707e0 to Connection>, db.literal =  > Connection.literal of <_mysql.connection open to 'localhost' at
> > e6b08c0>>, args = ['prescriptions', 'Beno', 'Candelon', '123', '456',
> > '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
> > '00820', '2000-01-01', 'benoismyname', '12345', 'CA', 'AR']
> > 
> > TypeError: not all arguments converted during string formatting
> >   args = ('not all arguments converted during string
> > formatting',)  
> > 
> > 
> > You sure about not converting to string??
> > 
> 
> Yep, pretty sure.  You still need to have as many %s in the query string
> as the number of values.  Since you seem to be passing in 19 values (by
> a rough count), the query string must be like this:
> 
> insert into doctorsPersonalData (Store, FirstNam.) values
> (%s, %s, %s, ...19 of these)
> 
> not
> 
> insert into doctorsPersonalData (Store, FirstNam.) values
> (%s)
> 
> The exception with the "not all arguments converted" message says you
> have too few %s.
> 
> > 
> > 
> > Also, lose the single quotes around the %s.
> > 
> > Well, sure, if not converting to string. Otherwise it's needed. Dennis
> > advised not using quotes, but what he meant was not using double
> > quotes. Single quotes, I have found by experimentation, do work.
> 
> You seem to have a strange definition of "work".
> 

Since I'm in a good mood today, here's a little present:

def insert(cursor, table, columns, values):
"""Insert a row into a table.  columns must be a list of column
names.  values must be a list of values for the new row.  The
columns and values must correspond."""
assert len(columns) == len(values)

stmt = """
insert into %s (%s) values (%s)
""" % (table,
   ', '.join(columns),
   ', '.join('%s' * len(values)))
logging.debug('stmt: %s, values: %s' % (stmt, values))

cursor.execute(stmt, values)

Hope it helps.

-- 
regards,
kushal


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


matplotlib: show xticks only for discrete times

2010-05-27 Thread speedy66

I am plotting data that depends on time and height using pcolor.  The data is
collected every 30 minutes, so there will be data at 1PM and again at 1:30PM
for instance.  

My question deals with how to get xticks to show up only for time values
that actually exist in the dataset.  As an example, ticks will currently
appear at a time that corresponds to 1:24PM which is not a time where data
exists.  These values change as I zoom in also.  I'm using
matplotlib.pyplot.

I've tried searching around for the answer, but have not been successful.

Thanks in advance.


-- 
View this message in context: 
http://old.nabble.com/matplotlib%3A-show-xticks-only-for-discrete-times-tp28696606p28696606.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 12:11 PM, Kushal Kumaran
wrote:

> Since I'm in a good mood today, here's a little present:
>
> def insert(cursor, table, columns, values):
>"""Insert a row into a table.  columns must be a list of column
>names.  values must be a list of values for the new row.  The
>columns and values must correspond."""
>assert len(columns) == len(values)
>
>stmt = """
> insert into %s (%s) values (%s)
> """ % (table,
>   ', '.join(columns),
>   ', '.join('%s' * len(values)))
>logging.debug('stmt: %s, values: %s' % (stmt, values))
>
>cursor.execute(stmt, values)
>
> Glad you're in a good mood :)
First, I got an error because logging isn't defined. What should I import?
I commented out that line. Here's my original code, which is now commented
out:

##cursor.execute('insert into %s (%s) values ("%s");' %
(personalDataTable, string.join(cols[1:], ', '), string.join(vals[1:], '",
"')))

I ran this with your code:

insert(cursor, personalDataTable, cols[1:], vals[1:])

and got this error:

 /var/www/html/angrynates.com/cart/enterPeople3.py
   97   print "Enter more
personal data?" % personalDataTable
   98   print "Enter products?"
   99   print '\n'
  100
  101 enterPeople3()
enterPeople3 = 
 /var/www/html/angrynates.com/cart/enterPeople3.py in enterPeople3()
   51   if whatDo == 'insert':
   52 # We will not include the ID column
   53 insert(cursor, personalDataTable, cols[1:], vals[1:])
   54 #sql = "insert into %s (%s) values (%%s);" % (personalDataTable,
string.join(cols[1:], ', '))
   55 #cursor.execute(sql, vals[1:])
global insert = , cursor = ,
personalDataTable = 'doctorsPersonalData', cols = ['ID', 'Store',
'FirstName', 'LastName', 'Phone', 'Cell', 'Fax', 'Address1', 'Address2',
'City', 'Zip', 'ShippingAddress1', 'ShippingAddress2', 'ShippingCity',
'ShippingZip', 'DOB', 'Email', 'PW', 'State', 'ShippingState'], vals =
['Null', 'prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11
here', '', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01',
'victorsubervi', '12345', 'DC', 'AK']
 /var/www/html/angrynates.com/cart/enterPeople3.py in
insert(cursor=, table='doctorsPersonalData',
columns=['Store', 'FirstName', 'LastName', 'Phone', 'Cell', 'Fax',
'Address1', 'Address2', 'City', 'Zip', 'ShippingAddress1',
'ShippingAddress2', 'ShippingCity', 'ShippingZip', 'DOB', 'Email', 'PW',
'State', 'ShippingState'], values=['prescriptions', 'jane', 'shmo',
'321-654-9870', '456', '789', '11 here', '', 'csted', '00820', '22 there',
'', 'csted', '00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'])
   19   ', '.join('%s' * len(values)))
   20 #   logging.debug('stmt: %s, values: %s' % (stmt, values))
   21cursor.execute(stmt, values)
   22
   23 def enterPeople3():
cursor = , cursor.execute = >, stmt = '\ninsert into
doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s,
%, s, %, s)\n', values = ['prescriptions', 'jane', 'shmo', '321-654-9870',
'456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
'00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK']
 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=, query='\ninsert into
doctorsPersonalData (Store, FirstNa... %, s, %, s, %, s, %, s, %, s, %, s,
%, s, %, s)\n', args=['prescriptions', 'jane', 'shmo', '321-654-9870',
'456', '789', '11 here', '', 'csted', '00820', '22 there', '', 'csted',
'00820', '2000-01-01', 'victorsubervi', '12345', 'DC', 'AK'])
  146 query = query.encode(charset)
  147 if args is not None:
  148 query = query % db.literal(args)
  149 try:
  150 r = self._query(query)
query = '\ninsert into doctorsPersonalData (Store, FirstNa... %, s, %, s, %,
s, %, s, %, s, %, s, %, s, %, s)\n', db = , db.literal = >, args =
['prescriptions', 'jane', 'shmo', '321-654-9870', '456', '789', '11 here',
'', 'csted', '00820', '22 there', '', 'csted', '00820', '2000-01-01',
'victorsubervi', '12345', 'DC', 'AK']

ValueError: unsupported format character ',' (0x2c) at index 221
  args = ("unsupported format character ',' (0x2c) at index 221",)

It appears to be separating the '%' from the 's' in your assert of '%s', but
since I don't know anything about asserts, I'm hoping you can help me here.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if, continuation and indentation

2010-05-27 Thread HH
On May 27, 11:37 am, Alain Ketterlin 
wrote:
> HH  writes:
> >     if (width == 0 and
> >         height == 0 and
> >         color == 'red' and
> >         emphasis == 'strong' or
> >         highlight > 100):
> >         raise ValueError("sorry, you lose")
>
> I prefer to see the "and" at the beginning of continuation lines, and
> usually group related items. I never mix operators without putting
> explicit parentheses. Something like:
>
>      if  (  width == 0 and height == 0
>             and color == 'red'
>             and ( emphasis == 'strong' or highlight > 100 ) ):
>          raise ValueError("sorry, you lose")

Thanks for all suggestions!  I like this solution a lot.

I agree with your statement about mixed operators and explicit
parentheses -- expecially since the eye/brain parser often does it
wrong, and I believe you demonstrated that above...

In [29]: print(False and (False or True))
False
In [30]: print(False and False or True)
True

> If you use a backslashes at the end of line, emacs will double-indent
> the following lines, but I think you said you prefer paretheses...

Yes, I much prefer the parentheses -- partly because PEP-8 suggests it
but mostly because the escapes get lost too easily.


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


Re: Yet Another MySQL Problem

2010-05-27 Thread MRAB

Kushal Kumaran wrote:
[snip]

Since I'm in a good mood today, here's a little present:

def insert(cursor, table, columns, values):
"""Insert a row into a table.  columns must be a list of column
names.  values must be a list of values for the new row.  The
columns and values must correspond."""
assert len(columns) == len(values)

stmt = """
insert into %s (%s) values (%s)
""" % (table,
   ', '.join(columns),
   ', '.join('%s' * len(values)))


That should be:

   ', '.join(['%s'] * len(values)))


logging.debug('stmt: %s, values: %s' % (stmt, values))

cursor.execute(stmt, values)

Hope it helps.



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


Re: Yet Another MySQL Problem

2010-05-27 Thread Kushal Kumaran
On Thu, 2010-05-27 at 17:56 +0100, MRAB wrote:
> Kushal Kumaran wrote:
> [snip]
> > Since I'm in a good mood today, here's a little present:
> > 
> > def insert(cursor, table, columns, values):
> > """Insert a row into a table.  columns must be a list of column
> > names.  values must be a list of values for the new row.  The
> > columns and values must correspond."""
> > assert len(columns) == len(values)
> > 
> > stmt = """
> > insert into %s (%s) values (%s)
> > """ % (table,
> >', '.join(columns),
> >', '.join('%s' * len(values)))
> 
> That should be:
> 
> ', '.join(['%s'] * len(values)))

My bad.  Tested with sqlite using '?' as the placeholder, then simply
replaced with '%s'.

-- 
regards,
kushal


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


Re: Minor annoyances with properties

2010-05-27 Thread John Posner

On 5/27/2010 9:14 AM, Neil Cerutti wrote:

On 2010-05-27, eb303  wrote:

I've been using Python properties quite a lot lately and I've
found a few things that are a bit annoying about them in some
cases. I wondered if I missed something or if anybody else has
this kind of problems too, and if there are better solutions
than the ones I'm using ATM.



The first annoyance is when I want to specialize a property in a
subclass.


See:

URI:http://infinitesque.net/articles/2005/enhancing%20Python%27s%20property.xhtml



Very nice idea, but I think this solution works too hard and not quite 
correctly. In Python 2.6.5, checking the name of the OProperty object's 
"fget" method:


if self.fget.__name__ == '' or not self.fget.__name__:

... doesn't distinguish between the original class's get-the-value 
method and the derived class's. (Did something change between 2005-11-02 
and now?)


Moreover, you don't *need* to perform this check -- just let *getattr* 
do the work of finding the right method. These method defs work fine for me:


def __get__(self, obj, objtype):
if self.fget:
return getattr(obj, self.fget.__name__)()
else:
raise AttributeError, "unreadable attribute"

def __set__(self, obj, value):
if self.fset:
getattr(obj, self.fset.__name__)(value)
else:
raise AttributeError, "can't set attribute"

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


Re: A Quick MySQL Question

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 1:37 PM, Dennis Lee Bieber wrote:

> On Wed, 26 May 2010 08:29:21 -0400, Victor Subervi
>  declaimed the following in
> gmane.comp.python.general:
>
> > valueList = ("%value1", "%value2", "%value3")
>
>If I'd coded it correctly, there should have been a % on both sides
> (I didn't actually test the statement, was coding from memory -- might
> have needed to double up the % to escape them)
>
> > cur.execute("select * from table where name1 like %s and name2 like %s
> and
> > name3 like %s", ("%value1", "%value2", "%value3"))
> >
> > Why do the values have that extra "%"?
>
> Wild card -- match zero or more characters
>
>%value1% will match "value1" /anywhere/ in the field name1; useful
> if doing keyword searches on text fields.
>
>To use my card catalog example:
>
> BOOK(title, author)
> "Witch World", "Andre Norton"
> "A Mankind Witch", "Dave Freer"
> "Three Against the Witch World", "Andre Norton"
> "The Jargoon Pard", "Andre Norton"
>
> names = ["author", "title"]
> values = ["Norton", "Witch"]
>
>The final SQL statement should become
>
> select * from BOOK
> where author like "%Norton%"
>and title like "%Witch%"
>
> and that statement will find the first and third book listed.
>

Ok. Now I understand. Thank you!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 12:56 PM, MRAB  wrote:

> Kushal Kumaran wrote:
> [snip]
>
>  Since I'm in a good mood today, here's a little present:
>>
>> def insert(cursor, table, columns, values):
>>"""Insert a row into a table.  columns must be a list of column
>>names.  values must be a list of values for the new row.  The
>>columns and values must correspond."""
>>assert len(columns) == len(values)
>>
>>stmt = """
>> insert into %s (%s) values (%s)
>> """ % (table,
>>   ', '.join(columns),
>>   ', '.join('%s' * len(values)))
>>
>
> That should be:
>
>
>   ', '.join(['%s'] * len(values)))
>
> logging.debug('stmt: %s, values: %s' % (stmt, values))
>>
>>cursor.execute(stmt, values)
>>
>> Hope it helps.
>>
>> Yes it did. Thanks. Also figured out the "import logging" :-}
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: matplotlib: show xticks only for discrete times

2010-05-27 Thread Mark Lawrence

On 27/05/2010 17:27, speedy66 wrote:


I am plotting data that depends on time and height using pcolor.  The data is
collected every 30 minutes, so there will be data at 1PM and again at 1:30PM
for instance.

My question deals with how to get xticks to show up only for time values
that actually exist in the dataset.  As an example, ticks will currently
appear at a time that corresponds to 1:24PM which is not a time where data
exists.  These values change as I zoom in also.  I'm using
matplotlib.pyplot.

I've tried searching around for the answer, but have not been successful.

Thanks in advance.


See 
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks


matplotlib also has it's own mailing list.

HTH

Mark Lawrence

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


Some More MySQL

2010-05-27 Thread Victor Subervi
Hi;
But what about this?

  sql = "select pic%d from %s where ID='%%s';" % (pic, store)
  cursor.execute(sql % id)

If I try and rewrite the last line like this:

  cursor.execute(sql, id)

it doesn't work. What do?

How about this one:

cursor.execute("insert into categories (Store, Category, Parent)
values('%s', '%s', Null)", (store, cat))

For some reason it puts single quotes around my variables! This doesn't
happen if I change that comma for a percent sign! What do?

How about this one:

  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
opTable[1:])
#  cursor.execute(sql, id)
  cursor.execute('select * from options%s where ID=%s' %
(opTable[0].upper() + opTable[1:], id))

The last one works, but if I comment it out and uncomment the middle line,
it doesn't. Same here:

sql = "update options%s set PriceDiff='%%s' where Field='%%s' and
ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:])
#cursor.execute(sql, (value, opName, id, store))
cursor.execute('update options%s set PriceDiff="%s" where Field="%s"
and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:], value,
opName, id, store))

Please help.
TIA,
beno

TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


First script. Need some help

2010-05-27 Thread ledpepper
#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is > but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.

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


Re: Some More MySQL

2010-05-27 Thread MRAB

Victor Subervi wrote:

Hi;
But what about this?

  sql = "select pic%d from %s where ID='%%s';" % (pic, store)
  cursor.execute(sql % id)

If I try and rewrite the last line like this:

  cursor.execute(sql, id)

it doesn't work. What do?

How about this one:

cursor.execute("insert into categories (Store, Category, Parent) 
values('%s', '%s', Null)", (store, cat))


For some reason it puts single quotes around my variables! This doesn't 
happen if I change that comma for a percent sign! What do?


How about this one:

  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() 
+ opTable[1:])

#  cursor.execute(sql, id)
  cursor.execute('select * from options%s where ID=%s' % 
(opTable[0].upper() + opTable[1:], id))


The last one works, but if I comment it out and uncomment the middle 
line, it doesn't. Same here:


sql = "update options%s set PriceDiff='%%s' where Field='%%s' 
and ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:])

#cursor.execute(sql, (value, opName, id, store))
cursor.execute('update options%s set PriceDiff="%s" where 
Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + 
opTable[1:], value, opName, id, store))



As has already been explained, when working with SQL in Python there are
2 forms of placeholder:

1. Python's %s placeholder, replaced by Python's % operator.

2. SQL's %s placeholder, replaced by the .execute method.

SQL might not let you use its %s placeholder for table or column names,
but they are normally hidden from the user and fixed by the application.

For user-supplied values there's the risk of SQL-injection attacks.
There are 2 ways of approaching that:

1. The hard way: check the values and add any necessary quoting or
escaping before using Python's % operator, then pass the fully-formed
SQL statement to result to .execute.

2. The easy way: pass the SQL statement to .execute with a %s for each
value and let the method substitute the values itself (it'll add
whatever quoting or escaping is necessary).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Minor annoyances with properties

2010-05-27 Thread Francesco Bochicchio
On 27 Mag, 14:37, eb303  wrote:
> Hello all,
>
> I've been using Python properties quite a lot lately and I've found a
> few things that are a bit annoying about them in some cases. I
> wondered if I missed something or if anybody else has this kind of
> problems too, and if there are better solutions than the ones I'm
> using ATM.
>
> The first annoyance is when I want to specialize a property in a
> subclass. This happens quite often actually, and it is even sometimes
> the reason why a plain attribute is turned into a property: a subclass
> needs to do more things than the superclass when the property is
> updated for example. So, of course, my first try was:
>
> class A(object):
>   def __init__(self):
>     self._p = None
>   def _get_p(self):
>     return self._p
>   def _set_p(self, p):
>     self._p = p
>   p = property(_get_p, _set_p)
> class B(A):
>   def _set_p(self, p):
>     ## Additional things here…
>     super(B, self)._set_p(p)
>
> And of course, it doesn't work: the property has been bound to
> A._set_p in A, so any new definition of _set_p in any subclass does
> not replace the set method for the property. So I always have to add a
> line:
> p = property(A._get_p, _set_p)
> in the subclass too. This is a bit awkward to me, since I have to
> specify the superclass's name (super(…) can't be used, since it should
> take B as an argument, and B isn't defined yet…). Do I miss something?
> Is this the way to do it, or is there a better one?
>

Don't know if is better, but you could add a level of indirection to
solve it

 class A(object):
   def __init__(self):
 self._p = None
   def _get_p(self):
 return self._p
   def _set_p(self, p):
 self._p = p
   def _virtual_get_p (self): _get_p(self)
   def _virtual_set_p (self,v): _set_p(self, v)
   p = property(_virtual_get_p, _virtual_set_p)

At this point, the subclasses of A can reimplement _get_p and _set_p
as they like (I think)

Ciao
-
FB


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


Re: Some More MySQL

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 2:54 PM, MRAB  wrote:

> Victor Subervi wrote:
>
>> Hi;
>> But what about this?
>>
>>  sql = "select pic%d from %s where ID='%%s';" % (pic, store)
>>  cursor.execute(sql % id)
>>
>> If I try and rewrite the last line like this:
>>
>>  cursor.execute(sql, id)
>>
>> it doesn't work. What do?
>>
>> How about this one:
>>
>>cursor.execute("insert into categories (Store, Category, Parent)
>> values('%s', '%s', Null)", (store, cat))
>>
>> For some reason it puts single quotes around my variables! This doesn't
>> happen if I change that comma for a percent sign! What do?
>>
>> How about this one:
>>
>>  sql = 'select * from options%s where ID=%%s', (opTable[0].upper() +
>> opTable[1:])
>> #  cursor.execute(sql, id)
>>  cursor.execute('select * from options%s where ID=%s' %
>> (opTable[0].upper() + opTable[1:], id))
>>
>> The last one works, but if I comment it out and uncomment the middle line,
>> it doesn't. Same here:
>>
>>sql = "update options%s set PriceDiff='%%s' where Field='%%s' and
>> ID=%%s and Store='%%s'" % (opTable[0].upper() + opTable[1:])
>> #cursor.execute(sql, (value, opName, id, store))
>>cursor.execute('update options%s set PriceDiff="%s" where
>> Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() + opTable[1:],
>> value, opName, id, store))
>>
>>  As has already been explained, when working with SQL in Python there are
> 2 forms of placeholder:
>
> 1. Python's %s placeholder, replaced by Python's % operator.
>
> 2. SQL's %s placeholder, replaced by the .execute method.
>
> SQL might not let you use its %s placeholder for table or column names,
> but they are normally hidden from the user and fixed by the application.
>
> For user-supplied values there's the risk of SQL-injection attacks.
> There are 2 ways of approaching that:
>
> 1. The hard way: check the values and add any necessary quoting or
> escaping before using Python's % operator, then pass the fully-formed
> SQL statement to result to .execute.
>
> 2. The easy way: pass the SQL statement to .execute with a %s for each
> value and let the method substitute the values itself (it'll add
> whatever quoting or escaping is necessary).
>
>
> Ok, so you're telling me I'm trying to do it the hard way. That's because I
still don't have my head wrapped around the easy way. I was able to follow
what Kushal Kumaran supplied; however I must still be lost on how that
applies to the above examples. Could you illustrate with the first and let
me try and figure out the rest?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


dbf files and indexes

2010-05-27 Thread Ethan Furman

Let's say I have two tables:

CatLoversDogLovers
---  ---
| name  | age |  | name  | age |
|-|  |-|
| Allen |  42 |  | Alexis|   7 |
| Jerod |  29 |  | Michael   |  21 |
| Samuel|  17 |  | Samuel|  17 |
| Nickalaus |  55 |  | Lawrence  |  63 |
| Frederick |  34 |  | Frederick |  34 |
---  ---

NumberOfPets
---
| name  | cats | dogs |
---
| Allen |   2  |   0  |
| Alexis|   0  |   3  |
| Michael   |   0  |   1  |
| Samuel|   1  |   2  |
| Jerod |   3  |   0  |
| Nickalaus |   5  |   0  |
| Lawrence  |   0  |   1  |
| Frederick |   3  |   2  |
---

(I know, I know -- coming up with examples has never been my strong 
point. ;)


catlovers = dbf.Table('CatLovers')
doglovers = dbf.Table('DogLovers')
petcount  = dbf.Table('NumberOfPets')

For the sake of this highly contrived example, let's say I'm printing a 
report that I would like in alphabetical order of those who love both 
cats and dogs...


def names(record):
return record.name

c_idx = catlovers.create_index(key=names)
d_idx = doglovers.create_index(key=names)
p_idx = petcount.create_index(key=names)

# method 1
for record in c_idx:
if record in d_idx:
print record.name, record.age, \
  p_idx[record].cats, p_idx[record].dogs

*or*

# method 2
for record in c_idx:
if d_idx.key(record) in d_idx:  # or if names(record) in d_idx:
print record.name, record.age \
  p_idx[record].cats, p_idx[record].dogs

Which is better (referring to the _in_ statement)?  Part of the issue 
revolves around the question of is _any_ record in the CatLovers table 
really in the DogLovers index?  Obviously no -- so if you are asking the 
question in code you are really asking if a record from CatLovers has a 
matching key value in DogLovers, which means either the __contains__ 
code can apply the key function to the record (implicit, as in method 1 
above) or the calling code can do it (explicit, as in method 2 above).


I'm leaning towards method 1, even though the key function is then 
called behind the scenes, because I think it makes the calling code cleaner.


Opinions?

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


Re: First script. Need some help

2010-05-27 Thread MRAB

ledpepper wrote:

#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is > but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.


You need to download and install the Windows-specific extensions:

http://sourceforge.net/projects/pywin32/

I'm assuming you're using Python 2.6 on Windows.
--
http://mail.python.org/mailman/listinfo/python-list


Re: First script. Need some help

2010-05-27 Thread Mark Lawrence

On 27/05/2010 19:41, ledpepper wrote:

#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is>  but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.

Thanks


Have you installed the Win32 extensions?

From http://www.devx.com/opensource/Article/37233/0/page/3

"Author's Note: the win32clipboard module is not part of the standard 
Python distribution on Windows. You can get it (along with lots of other 
comprehensive Python bindings to Win32 APIs) as part of the Win32 
extensions project on SourceForge. Alternatively, the module is also 
bundled with the ActivePython distribution for Windows."


HTH.

Mark Lawrence

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


On the installation of external Python modules

2010-05-27 Thread Wim R. Cardoen
Hello,

In the past I installed different versions of python (using gcc) e.g. 2.5.4,
2.6.4
at the following places:

/wim/pkg/python/2.5.4
/wim/pkg/python/2.6.4

I installed the numpy, scipy, matplotlib, dadi modules
using the command:
/wim/pkg/python/2.5.4/bin/python setup.py install
--prefix=/wim/pkg/python/2.5.4
As a result the working modules got installed under:
/wim/pkg/python/.5.4/lib/python2.5/site-packages/dadi
/wim/pkg/python/.5.4/lib/python2.5/site-packages/numpy
/wim/pkg/python/.5.4/lib/python2.5/site-packages/scipy
/wim/pkg/python/.5.4/lib/python2.5/site-packages/matplotlib

Question 1: Is it correct when I state that the above scipy, numpy,
modules can only be used by the python2.5.4 executable or
can I also use in python2.6.4 if I modify the PYTHONHOME and PYTHONPATH
variables?
Does one have to recompile all its external libraries for use with an
updated python version?
(assuming that the glibc is identical)


I also tried to install the external libraries (e.g. numpy) in different
directories than the main
python directories by specifying e.g. --prefix=/wim/pkg/pylib/   (in the
case of using python2.6.5)*
*I noticed that the suffix was still of the form
"lib/pythonx.y/site-packages/numpy"
Therefore, I wonder:

a. How can one (elegantly) force numpy to be installed under (using python
2.6.2 and python2.6.5):
/wim/pkg/pylib/lib/python2.6.4/.
/wim/pkg/pylib/lib/python2.6.5
b. How can one (elegantly) install different versions of the same package
using the same python binary (2.6.4) as e.g:
 /wim/pkg/pylib/lib/python2.6/site-packages/numpy0.70
/wim/pkg/pylib/lib/python2.6/site-packages/numpy0.71

or is this the wrong approach?



Thanks,

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


Re: dbf files and indexes

2010-05-27 Thread D'Arcy J.M. Cain
On Thu, 27 May 2010 12:45:58 -0700
Ethan Furman  wrote:
> Let's say I have two tables:
> 
> CatLoversDogLovers
> ---  ---
> | name  | age |  | name  | age |
> |-|  |-|
[...]
> 
> NumberOfPets
> ---
> | name  | cats | dogs |
> ---
[...]

First problem is learning to count.  :-)

Second (first real) problem is that you database is not normalized.  If
all of the cat lovers and dog lovers are in NumberOfPets then move the
age into that.  Probably should rename it as well.

Finally, are these SQL databases?  The best way of getting information
is with SQL.

SELECT * FROM NumberOfPets
WHERE name IN (SELECT name FROM CatLovers) OR
  name IN (SELECT name FROM DogLovers)
ORDER BY name;

> catlovers = dbf.Table('CatLovers')
> doglovers = dbf.Table('DogLovers')
> petcount  = dbf.Table('NumberOfPets')

I guess you should tell us what dbf is.  It doesn't seem to be a
standard module and it doesn't look like DB-API.  It's hard to answer
your question without knowing what these functions do.

-- 
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: First script. Need some help

2010-05-27 Thread Dave Angel

ledpepper wrote:

#Enter in firstname.lastname (bob.smith)
#Count the amount of letters(x) and vowels(y)
#Then work out if bob is > but not equal to 6 letters
#If firstname is less than 6 print firstnamesurnamexy
#If firstname is equal to or greater than 6 print firstnamexy
#Copy result to clipboard

http://codepad.org/Emzpix3H

I think you can see what i'm trying to do here. I will definitely
elaborate if anyone needs me to.

Thanks

  
Why bother using codepad for this?  The problem occurs parsing the 3rd 
line, so you only needed that and the traceback.


Have you installed the Win32 extensions?  If you think you have, can you 
find the file ?


C:\ProgFiles\Python26\Lib\site-packages\win32\win32clipboard.pyd

Naturally, your install directory may be different.  But it should be in 
the site-packages directory, which is where add-ons are installed.


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


Re: dbf files and indexes

2010-05-27 Thread Ethan Furman

Ethan Furman wrote:

Let's say I have two tables:


Okay, let's say I have three tables instead.  ;p
--
http://mail.python.org/mailman/listinfo/python-list


Re: Yet Another MySQL Problem

2010-05-27 Thread Tim Chase

On 05/27/2010 11:56 AM, MRAB wrote:

Kushal Kumaran wrote:

', '.join('%s' * len(values)))


That should be:

 ', '.join(['%s'] * len(values)))


Or as I've done in the past:

  ', '.join('%s' for _ in values)

-tkc



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


Re: dbf files and indexes

2010-05-27 Thread Ethan Furman

D'Arcy J.M. Cain wrote:

On Thu, 27 May 2010 12:45:58 -0700
Ethan Furman  wrote:

Let's say I have two tables:

CatLoversDogLovers
---  ---
| name  | age |  | name  | age |
|-|  |-|

[...]

NumberOfPets
---
| name  | cats | dogs |
---

[...]

First problem is learning to count.  :-)


Heh -- like I said, I'm terrible at making examples.  Originally it was 
two tables, then I threw in a third so I could show using an index as a 
dictionary.


> Second (first real) problem is that you database is not normalized.
> If all of the cat lovers and dog lovers are in NumberOfPets then move
> the age into that.  Probably should rename it as well.

The actual tables that I would be using are different versions of 
mailing tables, with one table not having as many records as the other, 
and wanting to do something with the records that are in common between 
the two.


> Finally, are these SQL databases?  The best way of getting information
> is with SQL.

The format of these tables is either dBase III or Visual FoxPro 6, and 
dbf is a module I have coded (still working on SQL support for it... 
getting closer!).  A slightly out-of-date version of it is available on 
PyPI.


My question centers around the __contains__ method of the Index object 
that I am writing, and whether it should call the key function of the 
index when passed a record, or if I should make the calling code do that.


Hope this helps.

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


Re: dbf files and indexes

2010-05-27 Thread Christian Heimes

Finally, are these SQL databases?  The best way of getting information
is with SQL.

SELECT * FROM NumberOfPets
WHERE name IN (SELECT name FROM CatLovers) OR
   name IN (SELECT name FROM DogLovers)
ORDER BY name;


A good way is to use SQL with JOINs instead of horrible nested selects. 
Although SQL is declarative, you shouldn't make the work of the query 
optimizer so hard.


Christian

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


Re: Yet Another MySQL Problem

2010-05-27 Thread Victor Subervi
On Thu, May 27, 2010 at 1:15 PM, Tim Chase  wrote:

> On 05/27/2010 11:56 AM, MRAB wrote:
>
>> Kushal Kumaran wrote:
>>
>>>', '.join('%s' * len(values)))
>>>
>>
>> That should be:
>>
>> ', '.join(['%s'] * len(values)))
>>
>
> Or as I've done in the past:
>
>  ', '.join('%s' for _ in values)
>

Huh? Can you describe that underscore to me? Fascinating!
beno

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


Tryton 1.6 series is out

2010-05-27 Thread ced
Tryton is a three-tiers high-level general purpose application
platform under the license GPL-3 written in Python and using
PostgreSQL as main database engine.
It is the core base of a complete business solution providing
modularity, scalability and security.

This new release comes with the support of MySQL and various
improvements and polishing of the framework. As always database
migration is ensured from any previous version. This release also
marks the end of support for the 1.0 series.

The most noteworthy new features are:

- The add of MySQL support as DBMS
- Some new modules:
  - Calendar Scheduling
  - Dashboard
  - Project Plan
- The Russian translation
- The security enforcement with fingerprint and CA checks for SSL
- The introduction of PYSON[1] for dynamic domain
- The add of JSON-RPC protocol
- The lazy load of fields in Export/Import windows
- The usage of python-dateutil instead of egenix-mx-base
- A versioned configuration directory for the client
- A bundle of Neso (standalone version of Tryton) for MacOSX
- The digits validation on numeric fields[2]
- The usage of singleton model[3] for various sequences configuration
- Some speed improvements of the report engine

A more complete list of the new features on: 
http://www.tryton.org/news.html#d2010-05-17

:Homepage: http://www.tryton.org/
:Downloads: http://www.tryton.org/downloads.html
:Screenshots: http://www.tryton.org/screenshots.html
:Demo: http://www.tryton.org/demo.html

[1] http://doc.tryton.org/1.6/trytond/doc/topics/pyson.html
[2] http://doc.tryton.org/1.6/trytond/doc/ref/models/fields.html#numeric
[3] 
http://doc.tryton.org/1.6/trytond/doc/ref/models/models.html#trytond.model.ModelSingleton]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Python Function

2010-05-27 Thread joy99
On May 25, 12:18 pm, Peter Otten <__pete...@web.de> wrote:
> Kushal Kumaran wrote:
> > On Tue, May 25, 2010 at 3:38 AM,joy99 wrote:
> >> 
>
> >> Dear Vlastimir,
>
> >> As pointed out by Alister, I can print the values of function1 and
> >> function2 with the help of another function3, but my target is to call
> >> the "add" value of function1 and "mult" value of function2 in a third
> >> function or the values and parameters of the third function in fourth
> >> function. While calling, I am looking not only to print, but to use
> >> them or manipulate them.
>
> >> I hope I am bit clear now.
>
> > If you need to use the values in another function, you need a way to
> > let that function get its hands on the values.  Your function1 and
> > function2 should return the values they compute instead of printing
> > them out.
>
> For example:
>
>  >>> def add(x, y):
> ...     return x + y
> ...>>> def mul(x, y):
>
> ...     return x * y
> ...>>> def sum_of_squares(x, y):
>
> ...     return add(mul(x, x), mul(y, y))
> ...>>> sum_of_squares(3, 4)
>
> 25
>
> OP: If that addresses your question I suggest that you work through some
> introductory text about python. The python wiki has a few suggestions, see
>
> http://wiki.python.org/moin/BeginnersGuide
>
> Peter

Hi Peter and Other Kind Contributors of the Group,

I got lot of insights from the discussion in the group. Though I did
not get the exact answer but from Peter's link I could work them out.
Thank you, Peter, for kindly referring me the link. I like to thank
others of the group also for kindly spending their valuable time. I
wanted to define one function and call the value of that function to
be used by another function. If I misquoted the problem, I am sorry.

Wishing You all a Great Day Ahead,
Best Regards,
Subhabrata.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQt4 QThread - passing arguments to thread methods

2010-05-27 Thread nganon tj
Hi,
I am trying to figure out how to implement a  QThread class that
will handle GUI event while keeping the GUI responsive.

I want to call thread's methods by their names and start() the
thread from inside that method.
My problem is with passing methods their arguments since
start() wont take any argument.

So I thought I could keep a global variable self.invoker which
holds the name of currently called method and start the thread
accordingly as follows:

class Counter(QThread):
def __init__(self, parent=None):
super(Counter, self).__init__(parent)
self.reset()

def __del__(self):
self.exiting = True
self.wait()
try:
self.reset()
# is not instantiated
except TypeError:
return

def stop(self):
self.__del__()

def reset(self):
self.exiting = False

def countup(self, till):
if not self.isRunning():
self.invoker = [self.countup, till]
self.start()

else:
n = 0
while not self.exiting and n < till:
n += 1
self.emit(SIGNAL("ticktock(int)", n))

def run(self):
self.invoker[0](self.invoker[1], self.invoker[2])


But I cant always know the number of arguments the invoker has, can I?
So can you please suggest me a better way of doing this please?

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


re ElemenTree producing and reading examples needed :

2010-05-27 Thread robert somerville
does anybody have some working code that they can point me to so i could see
ElemenTtree in action (especially writing XML files) ???

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


Re: Yet Another MySQL Problem

2010-05-27 Thread Tim Chase

On 05/27/2010 03:32 PM, Victor Subervi wrote:

On Thu, May 27, 2010 at 1:15 PM, Tim Chase wrote:

That should be:

 ', '.join(['%s'] * len(values)))


Or as I've done in the past:

  ', '.join('%s' for _ in values)


Huh? Can you describe that underscore to me? Fascinating!


The underscore is a valid variable-name, idiomatically used for 
"I don't care about this", often seen in places like tuple 
assignment:


  a,_,_,d = some_4_element_tuple

So in my above case, it could also have been written as

  ', '.join('%s' for value in values)
  ', '.join('%s' for dont_care_about_the_value in values)

but the "_" idiom means "I'm iterating over 'values' but I'm not 
actually using the values I get from it"


-tkc




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


Re: Some More MySQL

2010-05-27 Thread MRAB

Victor Subervi wrote:
On Thu, May 27, 2010 at 2:54 PM, MRAB > wrote:


Victor Subervi wrote:

Hi;
But what about this?

 sql = "select pic%d from %s where ID='%%s';" % (pic, store)
 cursor.execute(sql % id)

If I try and rewrite the last line like this:

 cursor.execute(sql, id)

it doesn't work. What do?

How about this one:

   cursor.execute("insert into categories (Store, Category,
Parent) values('%s', '%s', Null)", (store, cat))

For some reason it puts single quotes around my variables! This
doesn't happen if I change that comma for a percent sign! What do?

How about this one:

 sql = 'select * from options%s where ID=%%s',
(opTable[0].upper() + opTable[1:])
#  cursor.execute(sql, id)
 cursor.execute('select * from options%s where ID=%s' %
(opTable[0].upper() + opTable[1:], id))

The last one works, but if I comment it out and uncomment the
middle line, it doesn't. Same here:

   sql = "update options%s set PriceDiff='%%s' where
Field='%%s' and ID=%%s and Store='%%s'" % (opTable[0].upper() +
opTable[1:])
#cursor.execute(sql, (value, opName, id, store))
   cursor.execute('update options%s set PriceDiff="%s" where
Field="%s" and ID=%s and Store="%s"' % (opTable[0].upper() +
opTable[1:], value, opName, id, store))

As has already been explained, when working with SQL in Python there are
2 forms of placeholder:

1. Python's %s placeholder, replaced by Python's % operator.

2. SQL's %s placeholder, replaced by the .execute method.

SQL might not let you use its %s placeholder for table or column names,
but they are normally hidden from the user and fixed by the application.

For user-supplied values there's the risk of SQL-injection attacks.
There are 2 ways of approaching that:

1. The hard way: check the values and add any necessary quoting or
escaping before using Python's % operator, then pass the fully-formed
SQL statement to result to .execute.

2. The easy way: pass the SQL statement to .execute with a %s for each
value and let the method substitute the values itself (it'll add
whatever quoting or escaping is necessary).


Ok, so you're telling me I'm trying to do it the hard way. That's 
because I still don't have my head wrapped around the easy way. I was 
able to follow what Kushal Kumaran supplied; however I must still be 
lost on how that applies to the above examples. Could you illustrate 
with the first and let me try and figure out the rest?



First build the SQL statement with placeholder(s) for the values:

sql = "select pic%d from %s where ID=%%s;" % (pic, store)

Then execute the SQL statement, passing the value(s) so that .execute
performs the substitution itself:

cursor.execute(sql, id)

Placeholders which are handled by .execute shouldn't be wrapped in
quotes, even is the value is a string, because .execute will handle that
(and any other details) itself.
--
http://mail.python.org/mailman/listinfo/python-list


ElementTree write creates large one line XML file ....

2010-05-27 Thread robert somerville
Hi I am using Ubuntu 9.10 and Python 2.6.4 ..

when I create an ElementTree object and the write it out using:

 xml.etree.ElementTree.write() , I get one single long single line files,
instead of something that looks reasonable , what gives ??? (and is it
important ??)

eg: I get :

OneTwo

instead of :


One
Two



i found this example at: ( Listing 4 )
http://www.learningpython.com/2008/05/07/elegant-xml-parsing-using-the-elementtree-module/#Listing1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree write creates large one line XML file ....

2010-05-27 Thread Robert Kern

On 5/27/10 7:52 PM, robert somerville wrote:

Hi I am using Ubuntu 9.10 and Python 2.6.4 ..

when I create an ElementTree object and the write it out using:

  xml.etree.ElementTree.write() , I get one single long single line
files, instead of something that looks reasonable , what gives ??? (and
is it important ??)


ElementTree writes exactly what you tell it to. In XML, whitespace is 
significant. If you want newlines and/or indentation to make it pretty-looking, 
then you need to add those to your elements.


Fredrik provides an example function for doing this:

  http://effbot.org/zone/element-lib.htm#prettyprint

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: MySQLDB - server has gone on blob insertion...

2010-05-27 Thread John Nagle

Dennis Lee Bieber wrote:

On Wed, 26 May 2010 11:30:41 +0200, Durumdara 
declaimed the following in gmane.comp.python.general:


cursor.execute('delete from blobs;')


Since that statement will delete EVERY record from the table
"blobs", I believe it is common practice to replace it with

drop table blobs
create table blobs (whatever definition it had originally)


   No, it's not "common practice".  Actually, the proper way
to clear a table is "TRUNCATE TABLE tablename;"

   Note that deleting a table referenced by other tables using FOREIGN KEY
can be rejected by the database.

John Nagle
 

When I tried to start this, I got error:

_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

I read that server have some parameter, that limit the Query length.

Then I decreased the blob size to 1M, and then it is working.


What is the table definition? In MySQL 4 (and likely not changed in
v5 -- I've got the old brown tree book handy, hence the mention of v4)
field type BLOB is limited to a length of 2^16 (64kB), MEDIUMBLOB is
2^24, and LONGBLOB is 2^32 (if the system is using unsigned integers
internally, that should support 4GB... But do you have enough memory to
pass such an argument? ).

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


Tkinter error

2010-05-27 Thread ipatrol6010
I run a program (important parts at http://paste.pocoo.org/show/219148/) and 
all I get is this error: warning: callback failed in WindowList  : invalid command name ".45328424.windows"

Why?

P.S.: Please CC all replies to me, I don't watch the list



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


pythonMagick question

2010-05-27 Thread jyoung79
Hello,

I'm wanting to try out pythonMagick, but am pretty lost with this whole thing.  
What I'm wanting to do is view EPS and PDF files with Python and be able to 
zoom into the images to see smaller detail.

I downloaded PythonMagick-0.9.1.tar and have been looking through that 
folder.  The README file says:

-
Requists for installation is:
boost
boost-python
python 2.5
Magick++ (>= 6.2)

and for building:
pkg-config
libtool
make

and for generation build scripts is defined in autogen.pl

Building:
./configure
make
make install
-

What's this 'boost' stuff and Magick++?  Do I need to install 
more things to make this work?  I was going to run '.configure', 
then 'make' and then 'make install' from the command-line, 
but want to make sure I know what I'm doing before installing 
something (especially if it won't work).  Can anyone give me 
more info about pythonMagick or send me a link to a site(s) 
that has more info?

Thanks!

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


Re: ElementTree write creates large one line XML file ....

2010-05-27 Thread Sebastian Bassi
On Thu, May 27, 2010 at 9:13 PM, Robert Kern  wrote:
> ElementTree writes exactly what you tell it to. In XML, whitespace is
> significant. If you want newlines and/or indentation to make it
> pretty-looking, then you need to add those to your elements.

This is not always true. Let me quote an XML tutorial (by Oracle):


"What is XML Whitespace?
XML considers four characters to be whitespace: the carriage return
(\r or ch(13)), the linefeed (\n or ch(10)), the tab(\t), and the
spacebar (' '). In XML documents, there are two types of whitespace:

Significant whitespace is part of the document content and should be preserved.
Insignificant whitespace is used when editing XML documents for
readability. These whitespaces are typically not intended for
inclusion in the delivery of the document.

Usually without DTD or XML schema definition, all whitespaces are
significant whitespaces and should be preserved. However, with DTD or
XML schema definitions, only the whitespaces in the content are
significant as follows:


   --
   John Smith
   Product Manager
   Example.com
   

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


Re: pythonMagick question

2010-05-27 Thread Chris Rebert
On Thu, May 27, 2010 at 7:00 PM,   wrote:
> Hello,
>
> I'm wanting to try out pythonMagick, but am pretty lost with this whole thing.
> What I'm wanting to do is view EPS and PDF files with Python and be able to
> zoom into the images to see smaller detail.
>
> I downloaded PythonMagick-0.9.1.tar and have been looking through that
> folder.  The README file says:
>
> -
> Requists for installation is:
> boost
> boost-python
> python 2.5
> Magick++ (>= 6.2)
>
> and for building:
> pkg-config
> libtool
> make
>
> and for generation build scripts is defined in autogen.pl
>
> Building:
> ./configure
> make
> make install
> -
>
> What's this 'boost' stuff and Magick++?  Do I need to install
> more things to make this work?

Yes:
http://www.imagemagick.org/Magick++/
http://www.boost.org/

For what `make` et. al do:
http://www.tuxfiles.org/linuxhelp/softinstall.html

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


Free chapter about Python and databases (MySQL and SQLite)

2010-05-27 Thread Sebastian Bassi
Hello, I want to announce that the publisher of "Python for
Bioinformatis" (CRC Press) allowed me to publish a chapter from my
book.
I decided to publish the chapter about "Python and databases". I think
it may be useful for somebody.
The official announcement and download link is here:
http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/
For more information about the book: www.tinyurl.com/biopython
Best,
SB.


-- 
Sebastián Bassi. Lic. en Biotecnologia.
Curso de Python en un día: http://bit.ly/cursopython

Non standard disclaimer: READ CAREFULLY. By reading this email,
you agree, on behalf of your employer, to release me from all
obligations and waivers arising from any and all NON-NEGOTIATED
agreements, licenses, terms-of-service, shrinkwrap, clickwrap,
browsewrap, confidentiality, non-disclosure, non-compete and
acceptable use policies ("BOGUS AGREEMENTS") that I have
entered into with your employer, its partners, licensors, agents and
assigns, in perpetuity, without prejudice to my ongoing rights and
privileges. You further represent that you have the authority to release
me from any BOGUS AGREEMENTS on behalf of your employer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Free chapter about Python and databases (MySQL and SQLite)

2010-05-27 Thread John Bokma
Sebastian Bassi  writes:

> Hello, I want to announce that the publisher of "Python for
> Bioinformatis" (CRC Press) allowed me to publish a chapter from my
> book.
> I decided to publish the chapter about "Python and databases". I think
> it may be useful for somebody.
> The official announcement and download link is here:
> http://py4bio.com/2010/05/28/python_databases_mysql_sqlite/
> For more information about the book: www.tinyurl.com/biopython

I feel more than uncomfortable with example code that uses: user="root"
(e.g. p291). I never get why people write a short (IMO) /bad/ intro to
databases while there are books out there that do a way better
job. To me such chapters are just a way to get more pages :-(. (=make
the book more expensive = less money to buy a /good/ book on databases)

I would love to see more technical books that start at page 1 with the
topic, not with an introduction to the language (170+ pages) and some
other stuff that IMO shouldn't be there (MySQL introduction, XML, etc.). What
I would expect, based on the title is:

p 175-222
p 315-456
p 539-552

This would probably make the book a bit cheaper, so one can buy a good
book on MySQL, a good book on XML, and a good book on Python. (Or maybe
one already has those, like me).

IMO, YMMV

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Free chapter about Python and databases (MySQL and SQLite)

2010-05-27 Thread Sebastian Bassi
On Fri, May 28, 2010 at 12:37 AM, John Bokma  wrote:
> I feel more than uncomfortable with example code that uses: user="root"

What's wrong with this? It is just an example of connection string.
The reader will use his/her user/pass/dbname according to their own
settings.

> (e.g. p291). I never get why people write a short (IMO) /bad/ intro to
> databases while there are books out there that do a way better

The intended audience of this book are biologist who may be not
familiarized with relational databases. Most of my colleagues (at
least from the bio camp) don't even know that behind most dynamic web
pages there are databases and I think that most of them will find the
intro section useful. You can always skip what you know and go to the
point you want.

> job. To me such chapters are just a way to get more pages :-(. (=make
> the book more expensive = less money to buy a /good/ book on databases)

I am not sure that price in this kind of book are tied to the number
of pages. There must be some relation, but this is not the main factor
affecting price.

> I would love to see more technical books that start at page 1 with the
> topic, not with an introduction to the language (170+ pages) and some
...

I see where you go, it seems you are not the target audience for this
book. Anyway I appreciate your feedback.

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


Re: First script. Need some help

2010-05-27 Thread ledpepper
Thanks Everyone. I followed your instructions and my script is
successfully copying the result to the clipboard. Now for the fun. To
work out the rest of the script :)

I use the IDLE IDE and not codepad.org. I just thought that was the
standard for pasting scripts here in this group.

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