Flatten an email Message with a non-ASCII body using 8bit CTE

2013-01-24 Thread W. Trevor King
Hello list!

I'm trying to figure out how to flatten a MIMEText message to bytes
using an 8bit Content-Transfer-Encoding in Python 3.3.  Here's what
I've tried so far:

  # -*- encoding: utf-8 -*-
  import email.encoders
  from email.charset import Charset
  from email.generator import BytesGenerator
  from email.mime.text import MIMEText
  import sys

  body = 'Ζεύς'
  encoding = 'utf-8'
  charset = Charset(encoding)
  charset.body_encoding = email.encoders.encode_7or8bit

  message = MIMEText(body, 'plain', encoding)
  del message['Content-Transfer-Encoding']
  message.set_payload(body, charset)
  try:
  BytesGenerator(sys.stdout.buffer).flatten(message)
  except UnicodeEncodeError as e:
  print('error with string input:')
  print(e)

  message = MIMEText(body, 'plain', encoding)
  del message['Content-Transfer-Encoding']
  message.set_payload(body.encode(encoding), charset)
  try:
  BytesGenerator(sys.stdout.buffer).flatten(message)
  except TypeError as e:
  print('error with byte input:')
  print(e)

The `del m[…]; m.set_payload()` bits work around #16324 [1] and should
be orthogonal to the encoding issues.  It's possible that #12553 is
trying to address this issue [2,3], but that issue's comments are a
bit vague, so I'm not sure.

The problem with the string payload is that
email.generator.BytesGenerator.write is getting the Unicode string
payload unencoded and trying to encode it as ASCII.  It may be
possible to work around this by encoding the payload so that anything
that doesn't encode (using the body charset) to a 7bit value is
replaced with a surrogate escape, but I'm not sure how to do that.

The problem with the byte payload is that _has_surrogates (used in
email.generator.Generator._handle_text and
BytesGenerator._handle_text) chokes on byte input:

  TypeError: can't use a string pattern on a bytes-like object

For UTF-8, you can get away with:

  message.as_string().encode(message.get_charset().get_output_charset())

because the headers are encoded into 7 bits, so re-encoding them with
UTF-8 is a no-op.  However, if the body charset is UTF-16-LE or any
other encoding that remaps 7bit characters, this hack breaks down.

Thoughts?
Trevor

[1]: http://bugs.python.org/issue16324
[2]: http://bugs.python.org/issue12553
[3]: http://bugs.python.org/issue12552#msg140294

-- 
This email may be signed or encrypted with GnuPG (http://www.gnupg.org).
For more information, see http://en.wikipedia.org/wiki/Pretty_Good_Privacy


signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any algorithm to preserve whitespaces?

2013-01-24 Thread Santosh Kumar
On 1/24/13, Peter Otten <[email protected]> wrote:
> Santosh Kumar wrote:
>
>> Yes, Peter got it right.
>>
>> Now, how can I replace:
>>
>> script, givenfile = argv
>>
>> with something better that takes argv[1] as input file as well as
>> reads input from stdin.
>>
>> By input from stdin, I mean that currently when I do `cat foo.txt |
>> capitalizr` it throws a ValueError error:
>>
>> Traceback (most recent call last):
>>   File "/home/santosh/bin/capitalizr", line 16, in 
>> script, givenfile = argv
>> ValueError: need more than 1 value to unpack
>>
>> I want both input methods.
>
> You can use argparse and its FileType:
>
> import argparse
> import sys
>
> parser = argparse.ArgumentParser()
> parser.add_argument("infile", type=argparse.FileType("r"), nargs="?",
> default=sys.stdin)
> args = parser.parse_args()
>
> for line in args.infile:
> print line.strip().title() # replace with your code
>

This works file when I do `script.py inputfile.txt`; capitalizes as
expected. But it work unexpected if I do `cat inputfile.txt |
script.py`; leaves the first word of each line and then capitalizes
remaining.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any algorithm to preserve whitespaces?

2013-01-24 Thread Peter Otten
Santosh Kumar wrote:

> On 1/24/13, Peter Otten <[email protected]> wrote:
>> Santosh Kumar wrote:
>>
>>> Yes, Peter got it right.
>>>
>>> Now, how can I replace:
>>>
>>> script, givenfile = argv
>>>
>>> with something better that takes argv[1] as input file as well as
>>> reads input from stdin.
>>>
>>> By input from stdin, I mean that currently when I do `cat foo.txt |
>>> capitalizr` it throws a ValueError error:
>>>
>>> Traceback (most recent call last):
>>>   File "/home/santosh/bin/capitalizr", line 16, in 
>>> script, givenfile = argv
>>> ValueError: need more than 1 value to unpack
>>>
>>> I want both input methods.
>>
>> You can use argparse and its FileType:
>>
>> import argparse
>> import sys
>>
>> parser = argparse.ArgumentParser()
>> parser.add_argument("infile", type=argparse.FileType("r"), nargs="?",
>> default=sys.stdin)
>> args = parser.parse_args()
>>
>> for line in args.infile:
>> print line.strip().title() # replace with your code
>>
> 
> This works file when I do `script.py inputfile.txt`; capitalizes as
> expected. But it work unexpected if I do `cat inputfile.txt |
> script.py`; leaves the first word of each line and then capitalizes
> remaining.

I cannot reproduce that:

$ cat title.py 
#!/usr/bin/env python
import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument("infile", type=argparse.FileType("r"), nargs="?",
default=sys.stdin)
args = parser.parse_args()

for line in args.infile:
print line.strip().title() # replace with your code
$ cat inputfile.txt 
alpha beta
gamma delta epsilon
zeta
$ cat inputfile.txt | ./title.py 
Alpha Beta
Gamma Delta Epsilon
Zeta
$ ./title.py inputfile.txt 
Alpha Beta
Gamma Delta Epsilon
Zeta


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


The best, friendly and easy use Python Editor.

2013-01-24 Thread Hazard Seventyfour
Hello,

I new in this python and decided to learn more about it, so i can make an own 
script :),

for all senior can you suggest me the best, friendly and easy use with nice GUI 
editor for me, and have many a good features such as auto complete/auto correct.

any recommend? Thanks ^_^
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving the full command line

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 04:49, Steven D'Aprano
 wrote:
[SNIP]
>
> Contrariwise, I don't believe that there is currently *any* way to
> distinguish between running a script with or without -m. That should be
> fixed.

As I said earlier in the thread, the __package__ module global
distinguishes the two cases:

~$ mkdir pkg
~$ touch pkg/__init__.py
~$ vim pkg/__main__.py
~$ cat pkg/__main__.py
import sys
if __package__ is None:
cmdline = [sys.executable] + sys.argv
else:
cmdline = [sys.executable, '-m', __package__] + sys.argv[1:]
print(cmdline)
~$ python pkg/__main__.py arg1 arg2
['q:\\tools\\Python27\\python.exe', 'pkg/__main__.py', 'arg1', 'arg2']
~$ python -m pkg arg1 arg2
['q:\\tools\\Python27\\python.exe', '-m', 'pkg', 'arg1', 'arg2']


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


Re: Any algorithm to preserve whitespaces?

2013-01-24 Thread Santosh Kumar
But I can; see: http://pastebin.com/ZGGeZ71r

On 1/24/13, Peter Otten <[email protected]> wrote:
> Santosh Kumar wrote:
>
>> On 1/24/13, Peter Otten <[email protected]> wrote:
>>> Santosh Kumar wrote:
>>>
 Yes, Peter got it right.

 Now, how can I replace:

 script, givenfile = argv

 with something better that takes argv[1] as input file as well as
 reads input from stdin.

 By input from stdin, I mean that currently when I do `cat foo.txt |
 capitalizr` it throws a ValueError error:

 Traceback (most recent call last):
   File "/home/santosh/bin/capitalizr", line 16, in 
 script, givenfile = argv
 ValueError: need more than 1 value to unpack

 I want both input methods.
>>>
>>> You can use argparse and its FileType:
>>>
>>> import argparse
>>> import sys
>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("infile", type=argparse.FileType("r"), nargs="?",
>>> default=sys.stdin)
>>> args = parser.parse_args()
>>>
>>> for line in args.infile:
>>> print line.strip().title() # replace with your code
>>>
>>
>> This works file when I do `script.py inputfile.txt`; capitalizes as
>> expected. But it work unexpected if I do `cat inputfile.txt |
>> script.py`; leaves the first word of each line and then capitalizes
>> remaining.
>
> I cannot reproduce that:
>
> $ cat title.py
> #!/usr/bin/env python
> import argparse
> import sys
>
> parser = argparse.ArgumentParser()
> parser.add_argument("infile", type=argparse.FileType("r"), nargs="?",
> default=sys.stdin)
> args = parser.parse_args()
>
> for line in args.infile:
> print line.strip().title() # replace with your code
> $ cat inputfile.txt
> alpha beta
> gamma delta epsilon
> zeta
> $ cat inputfile.txt | ./title.py
> Alpha Beta
> Gamma Delta Epsilon
> Zeta
> $ ./title.py inputfile.txt
> Alpha Beta
> Gamma Delta Epsilon
> Zeta
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory error with quadratic interpolation

2013-01-24 Thread Oscar Benjamin
On 23 January 2013 17:33, Isaac Won  wrote:
> On Wednesday, January 23, 2013 10:51:43 AM UTC-6, Oscar Benjamin wrote:
>> On 23 January 2013 14:57, Isaac Won  wrote:
>>
>> > On Wednesday, January 23, 2013 8:40:54 AM UTC-6, Oscar Benjamin wrote:
>>
>> Unless I've misunderstood how this function is supposed to be used, it
>> just doesn't really seem to work for arrays of much more than a few
>> hundred elements.
>>

The solution is to use UnivariateSpline. I don't know what the
difference is but it works where the other fails:

import numpy as np
from scipy.interpolate import UnivariateSpline
x = np.array(1 * [0.0], float)
indices = np.arange(len(x))
interp = UnivariateSpline(indices, x, k=2)
print(interp(1.5))


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


Python to send Midi commands to iPad via USB

2013-01-24 Thread mikprog
Dear all,

I am asking for a design/strategy suggestion.

What I have to do is to write a Python application that will send MIDI commands 
to an iPad application.
All I know is that the iPad application can be connected to an external Midi 
deck through a usb cable and be controlled.
So I think I would connect the iPad via USB to my computer and... try to send 
midi commands.
I think the limitation is that the iPad will allow signaling/connection only to 
Midi devices, so I have to make so that my Python script pretends that my 
computer is a Midi device.
So far I have tried PyUSB library and I can see the iPad, but I can't send 
anything to it (probably because I am not pretending to be a Midi device well 
enough).

I am keen to try PyUSB + pygame for the Midi stuff.

Any suggestion / recommendation / hint / whatever to tell me?
I appreciate every idea at this stage!

Thanks for reading,
Mik
-- 
http://mail.python.org/mailman/listinfo/python-list


using split for a string : error

2013-01-24 Thread inshu chauhan
Here I have a code which basically reads a csv file, tries to compare the
last 2 items in each line of the file.

f = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
for l in f:
sp = l.split(",")
if len(sp) != 11:
print >> of, l,

else:
#print sp[9], sp[10]
if sp[9] == sp[10]:
print " Same class"
else :
print "Different class"

f.close()

For me I think the programme is logically correct, but its giving me
results which are strange.
It is  Printing " Different Class"  even when sp[9] is equal to sp[10] and
"Same class" when sp[9] is not equal to sp[10].  and sp[9] and sp[10] are
simple integers like 3, 3, 4 ,4.

I have a little understanding why the programme is behaving like this ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread mikprog
On Thursday, January 24, 2013 9:43:31 AM UTC, Hazard Seventyfour wrote:
> Hello,
> 
> 
> 
> I new in this python and decided to learn more about it, so i can make an own 
> script :),
> 
> 
> 
> for all senior can you suggest me the best, friendly and easy use with nice 
> GUI editor for me, and have many a good features such as auto complete/auto 
> correct.
> 
> 
> 
> any recommend? Thanks ^_^

Hi,
an editor is pretty much a matter of personal preferences.
I personally like Eclipse as I use it for most of my projects (not only Python) 
so I use Eclipse + PyDev plug-in for Python.

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


Re: Python to send Midi commands to iPad via USB

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 9:31 PM,   wrote:
> What I have to do is to write a Python application that will send MIDI 
> commands to an iPad application.
> All I know is that the iPad application can be connected to an external Midi 
> deck through a usb cable and be controlled.
> So I think I would connect the iPad via USB to my computer and... try to send 
> midi commands.

Are you able to hook into ALSA? I've had reasonable success driving a
USB-MIDI cable using ALSA. See if you can do it with the inbuilt
'pmidi' app first:

$ pmidi -p 128:0 No.19.mid

(that uses port 128:0 which is a TiMidity-provided one)

If that works, you can then look for Python ALSA bindings, which I
believe are available on PyPI.

My example is from Linux, so you may need to tweak things on other OSes.

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


Re: Any algorithm to preserve whitespaces?

2013-01-24 Thread Peter Otten
Santosh Kumar wrote:

> But I can; see: http://pastebin.com/ZGGeZ71r

You have messed with your cat command -- it adds line numbers.
Therefore the output of

cat somefile | ./argpa.py

differs from

./argpa.py somefile

Try

./argpa.py < somefile

to confirm my analysis. As to why your capitalisation algorithm fails on 
those augmented lines: the number is separated from the rest of the line by 
a TAB -- therefore the first word is "1\tthis" and the only candidate to be 
capitalised is the "1". To fix this you could use regular expressions (which 
I wanted to avoid initially):

>>> parts = re.compile("(\s+)").split(" 1\tthis is it")
>>> parts
['', ' ', '1', '\t', 'this', ' ', 'is', ' ', 'it']

Process every other part as you wish and then join all parts:

>>> parts[::2] = [s.upper() for s in parts[::2]]
>>> parts
['', ' ', '1', '\t', 'THIS', ' ', 'IS', ' ', 'IT']
>>> print "".join(parts)
 1  THIS IS IT


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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Hi,

do a "print sp" after the split and you might see that the strings don't 
look as you expected. There might be leading or trailing whitespaces in 
the splitted strings and in sp[10] there probably is a line break "\n" 
at the end.

To remove those unwanted characters you could use the strip() function.

So your code could be:

if sp[9].strip() == sp[10].strip():
print "Same class"
else:
print "Different class"

At least this works for me when I tried it...

Am 24.01.2013 11:37, schrieb inshu chauhan:
Here I have a code which basically reads a csv file, tries to compare 
the last 2 items in each line of the file.


f = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
for l in f:
sp = l.split(",")
if len(sp) != 11:
print >> of, l,

else:
#print sp[9], sp[10]
if sp[9] == sp[10]:
print " Same class"
else :
print "Different class"

f.close()

For me I think the programme is logically correct, but its giving me 
results which are strange.
It is  Printing " Different Class"  even when sp[9] is equal to sp[10] 
and "Same class" when sp[9] is not equal to sp[10]. and sp[9] and 
sp[10] are simple integers like 3, 3, 4 ,4.


I have a little understanding why the programme is behaving like this ?




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


Re: Retrieving the full command line

2013-01-24 Thread Tim Golden
On 24/01/2013 10:06, Oscar Benjamin wrote:
> On 24 January 2013 04:49, Steven D'Aprano
>  wrote:
> [SNIP]
>>
>> Contrariwise, I don't believe that there is currently *any* way to
>> distinguish between running a script with or without -m. That should be
>> fixed.
> 
> As I said earlier in the thread, the __package__ module global
> distinguishes the two cases:
> 
> ~$ mkdir pkg
> ~$ touch pkg/__init__.py
> ~$ vim pkg/__main__.py
> ~$ cat pkg/__main__.py
> import sys
> if __package__ is None:
> cmdline = [sys.executable] + sys.argv
> else:
> cmdline = [sys.executable, '-m', __package__] + sys.argv[1:]
> print(cmdline)
> ~$ python pkg/__main__.py arg1 arg2
> ['q:\\tools\\Python27\\python.exe', 'pkg/__main__.py', 'arg1', 'arg2']
> ~$ python -m pkg arg1 arg2
> ['q:\\tools\\Python27\\python.exe', '-m', 'pkg', 'arg1', 'arg2']

Reasonable (and thanks for the clear example), but it doesn't work
if the package which is reconstructing the command line the package
which was the target of the original command line. In my case,
I'm making use of the cherrypy reloader, whose __package__ is
cherrypy.process. But the command which invoked the program was
python -m myapp.

ie I'm issuing "python -m myapp". In myapp.__main__ I'm importing
cherrypy, itself a package, and somewhere in cherrypy.whatever there is
code which attempts to reconstruct the command line.

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


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 9:37 PM, inshu chauhan  wrote:
> For me I think the programme is logically correct, but its giving me results
> which are strange.
> It is  Printing " Different Class"  even when sp[9] is equal to sp[10] and
> "Same class" when sp[9] is not equal to sp[10].  and sp[9] and sp[10] are
> simple integers like 3, 3, 4 ,4.
>
> I have a little understanding why the programme is behaving like this ?

Without your data file I can't advise, but here's a couple of things
to try. I see you've tried displaying the values:

#print sp[9], sp[10]

Try this version:

print repr(sp[9]), repr(sp[10])

That'll make it obvious if, for instance, there are leading/trailing spaces.

The other thing you may want to consider, if the values are supposed
to be integers, is to convert them to Python integers before
comparing. Currently, you're working with strings. Replace this:

if sp[9] == sp[10]:

with this:

if int(sp[9]) == int(sp[10]):

That will consider "1" and "1 " to be the same, since they'll both be
parsed as the integer 1. Alternatively, consider what Tobias said and
explicitly strip spaces. Either way, displaying repr() of the strings
(or printing the whole of sp, as Tobias suggests) will show you what's
needed.

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


mysql solution

2013-01-24 Thread Ferrous Cranus
# insert new page record in table counters or update it if already exists
try:
cursor.execute( '''INSERT INTO counters(page, hits) VALUES(%s, 
%s) 
ON DUPLICATE 
KEY UPDATE hits = hits + 1''', (htmlpage, 1) )
except MySQLdb.Error, e:
print ( "Query Error: ", sys.exc_info()[1].excepinfo()[2] )

# update existing visitor record if same pin and same host found
try:
cursor.execute( '''UPDATE visitors SET hits = hits + 1, useros 
= %s, browser = %s, date = %s WHERE pin = %s AND host = %s''', (useros, 
browser, date, pin, host))
except MySQLdb.Error, e:
print ( "Error %d: %s" % (e.args[0], e.args[1]) )

# insert new visitor record if above update did not affect a row
if cursor.rowcount == 0:
cursor.execute( '''INSERT INTO visitors(hits, host, useros, 
browser, date) VALUES(%s, %s, %s, %s, %s)''', (1, host, useros, browser, date) )

==

I;am now convinced the hash solution isn't reversible and also isn't unique.
I'am trying the database oriented solution.

pin column = 5-digit integer Primary Key.

When i'am inserting a new record to table counters, a sequenced number is 
crated as pin. Thats works ok.


But when i try to Update or Insert into the visitors table the 'pin' comunn is 
needed to to identify the rrecord for which iam trying to update like here:


cursor.execute( '''UPDATE visitors SET hits = hits + 1, useros = %s, browser = 
%s, date = %s WHERE pin = %s AND host = %s''', (useros, browser, date, pin, 
host))


how is the mysql statement is going to find the 'pin' to update the specific 
record.
And also in here:


if cursor.rowcount == 0:
cursor.execute( '''INSERT INTO visitors(pin, hits, host, 
useros, browser, date) VALUES(%s, %s, %s, %s, %s, %s)''', (pin, 1, host, 
useros, browser, date) )


'pin' column's value is also need to make insert


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


Re: using split for a string : error

2013-01-24 Thread inshu chauhan
On Thu, Jan 24, 2013 at 11:55 AM, Tobias M.  wrote:

>  Hi,
>
> do a "print sp" after the split and you might see that the strings don't
> look as you expected. There might be leading or trailing whitespaces in the
> splitted strings and in sp[10] there probably is a line break "\n" at the
> end.
> To remove those unwanted characters you could use the strip() function.
>
> So your code could be:
>
> if sp[9].strip() == sp[10].strip():
>
> print "Same class"
> else:
> print "Different class"
>
> At least this works for me when I tried it...
>
> Am 24.01.2013 11:37, schrieb inshu chauhan:
>
>   Here I have a code which basically reads a csv file, tries to compare
> the last 2 items in each line of the file.
>
> f = open(r"Z:\modules\Feature_Vectors_300_Pclass.arff")
> for l in f:
> sp = l.split(",")
> if len(sp) != 11:
> print >> of, l,
>
> else:
> #print sp[9], sp[10]
> if sp[9] == sp[10]:
> print " Same class"
> else :
> print "Different class"
>
> f.close()
>
>  For me I think the programme is logically correct, but its giving me
> results which are strange.
>  It is  Printing " Different Class"  even when sp[9] is equal to sp[10]
> and "Same class" when sp[9] is not equal to sp[10].  and sp[9] and sp[10]
> are simple integers like 3, 3, 4 ,4.
>
>  I have a little understanding why the programme is behaving like this ?
>
>
>  Yeah I tried printing, there were trailing white spaces, so i used
> strip() and IT Worked !!! :)
>

Thank you

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


Re: mysql solution

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 10:04 PM, Ferrous Cranus  wrote:
> I;am now convinced the hash solution isn't reversible and also isn't unique.
> I'am trying the database oriented solution.

Glad you've listened to at least some of what you've been told. But if
you want to be taken seriously on this list, I recommend going back to
your previous name of Νικόλαος Κούρας (which Google Translate tells me
transliterates as Nicholas Kouri), apologizing for trolling, and being
VERY careful to be respectful. I suspect a number of the list's best
posters have already killfiled you.

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


Re: Retrieving the full command line

2013-01-24 Thread Tim Golden
On 24/01/2013 10:56, Tim Golden wrote:
> if the package which is reconstructing the command line the package
> which was the target of the original command line.


Sorry:

  if the package which is reconstructing the command line *is not*
  the package which was the target of the original command line.

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 8:43 PM, Hazard Seventyfour
 wrote:
> Hello,
>
> I new in this python and decided to learn more about it, so i can make an own 
> script :),
>
> for all senior can you suggest me the best, friendly and easy use with nice 
> GUI editor for me, and have many a good features such as auto complete/auto 
> correct.
>
> any recommend? Thanks ^_^

Here we go, it's holy war time again! :)

You'll get a HUGE lot of responses. Many use emacs or vim, and you'll
get a few recommendations for IDLE. After that, it's a huge field of
options. I personally use SciTE; it's a good editor, but I don't
particularly like the way the project is run (nothing strong, but I
didn't like the tone on its mailing list). Eclipse has its fans, too.

A Python IDE is not nearly as beneficial as, say, a Java IDE. A good
Python editor just needs to do the basics like indentation, syntax
highlighting, and such; I like IDLE's method info when I'm working
interactively, but it's not a big deal when I'm writing a program. In
fact, all you really need out of an IDE can probably be supplied by
just a good editor, maybe a makefile, and alt-tabbing to IDLE.
However, if you want an IDE, they do exist.

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


Re: mysql solution

2013-01-24 Thread Lele Gaifax
Ferrous Cranus  writes:

> I;am now convinced the hash solution isn't reversible and also isn't
> unique.

Great!

> how is the mysql statement is going to find the 'pin' to update the
> specific record.

The simplest way is to execute a SELECT just after the insertion, doing
a

  SELECT pin FROM counters WHERE page = %s

I don't use MySQL, so I can't say if it supports "INSERT ... RETURNING ..."
SQL syntax: should it, then you could insert the data and fetch
the pin in one shot, with something like

  INSERT INTO counters (page, hits) VALUES (%s, %s) RETURNING (pin)

ciao, lele.
--
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected]  | -- Fortunato Depero, 1929.

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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Chris Angelico wrote:



The other thing you may want to consider, if the values are supposed
to be integers, is to convert them to Python integers before
comparing. Currently, you're working with strings. Replace this:

if sp[9] == sp[10]:

with this:

if int(sp[9]) == int(sp[10]):
I thought of this too and I wonder if there are any major differences 
regarding performance compared to using the strip() method when parsing 
large files.


In addition I guess one should catch the ValueError that might be raised 
by the cast if there is something else than a number in the file.

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


Re: mysql solution

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 10:25 PM, Lele Gaifax  wrote:
> The simplest way is to execute a SELECT just after the insertion, doing
> a
>
>   SELECT pin FROM counters WHERE page = %s
>
> I don't use MySQL, so I can't say if it supports "INSERT ... RETURNING ..."
> SQL syntax: should it, then you could insert the data and fetch
> the pin in one shot, with something like
>
>   INSERT INTO counters (page, hits) VALUES (%s, %s) RETURNING (pin)

AFAIK it doesn't, but if pin is an AUTO_INCREMENT primary key, you can
retrieve the ID of the newly inserted record. It's not nearly as
flexible as INSERT... RETURNING, but it covers the most common use
case.

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


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 10:01 PM, inshu chauhan  wrote:
> Yeah I tried printing, there were trailing white spaces, so i used strip()
> and IT Worked !!! :)

Awesome! Keep repr() in mind, it's a great way to check what's really there.

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


Re: Retrieving the full command line

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 10:56, Tim Golden  wrote:
> On 24/01/2013 10:06, Oscar Benjamin wrote:
>> On 24 January 2013 04:49, Steven D'Aprano
>>  wrote:
>> [SNIP]
>>>
>>> Contrariwise, I don't believe that there is currently *any* way to
>>> distinguish between running a script with or without -m. That should be
>>> fixed.
>>
>> As I said earlier in the thread, the __package__ module global
>> distinguishes the two cases:
>>
>> ~$ mkdir pkg
>> ~$ touch pkg/__init__.py
>> ~$ vim pkg/__main__.py
>> ~$ cat pkg/__main__.py
>> import sys
>> if __package__ is None:
>> cmdline = [sys.executable] + sys.argv
>> else:
>> cmdline = [sys.executable, '-m', __package__] + sys.argv[1:]
>> print(cmdline)
>> ~$ python pkg/__main__.py arg1 arg2
>> ['q:\\tools\\Python27\\python.exe', 'pkg/__main__.py', 'arg1', 'arg2']
>> ~$ python -m pkg arg1 arg2
>> ['q:\\tools\\Python27\\python.exe', '-m', 'pkg', 'arg1', 'arg2']
>
> Reasonable (and thanks for the clear example), but it doesn't work
> if the package which is reconstructing the command line the package
> which was the target of the original command line. In my case,
> I'm making use of the cherrypy reloader, whose __package__ is
> cherrypy.process. But the command which invoked the program was
> python -m myapp.
>
> ie I'm issuing "python -m myapp". In myapp.__main__ I'm importing
> cherrypy, itself a package, and somewhere in cherrypy.whatever there is
> code which attempts to reconstruct the command line.

Easy enough:

~$ mkdir pkg
~$ touch pkg/__init__.py
~$ vim pkg/__main__.py
~$ cat pkg/__main__.py
import pkg.whatever
~$ vim pkg/whatever.py
~$ cat pkg/whatever.py
import sys
import pkg.__main__ as main
cmdline = [sys.executable, '-m', main.__package__] + sys.argv[1:]
print(cmdline)
~$ python -m pkg
['q:\\tools\\Python27\\python.exe', '-m', 'pkg']
~$ python -m pkg arg1 arg32
['q:\\tools\\Python27\\python.exe', '-m', 'pkg', 'arg1', 'arg32']

I don't really understand what your spec is. Why do you need to
inspect this information from sys.argv? Can you not just always use
'python -m pkg' as your entry point?


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


XML validation / exception.

2013-01-24 Thread Andrew Robinson

A quick question:

On xml.etree,
When I scan in a handwritten XML file, and there are mismatched tags -- 
it will throw an exception.
and the exception will contain a line number of the closing tag which 
does not have a mate of the same kind.


Is there a way to get the line number of the earlier tag which caused 
the XML parser to know the closing tag was mismatched, so I can narrow 
down the location of the mismatches for a manual repair? (I don't want 
auto-repair like beautiful soup. but google is worthless for finding a 
solution...)


And secondly, for times where I want to throw a software/content 
specific error on valid XML files;
I don't see which attribute of an element, or method, allows me to find 
out the line number and column number that an element I am examining is 
found at.


? How do I get it ?

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


Re: How do functions get access to builtins?

2013-01-24 Thread Steven D'Aprano
Rouslan Korneychuk wrote:

> I found the answer in Python's source code. When you execute a code
> object, PyFrame_New is called which gets 'bultins' from 'globals', but
> inside PyFrame_New (defined on line 596 of Objects/frameobject.c) is the
> following (line 613):
> 
>builtins = PyDict_GetItem(globals, builtin_object);
> 
> Unlike PyObject_GetItem, PyDict_GetItem is specialized for dict objects.
> Your ChainedDict class uses ChainMaps's storage and leaves dict's
> storage empty, so PyDict_GetItem doesn't find anything.
[...]
> Interestingly: it looks like it could be fixed easily enough. Unless
> there are other places where globals is assumed to be a dict object, it
> would just be a matter of doing the same check and fallback in
> PyFrame_New that is done in LOAD_GLOBAL (technically, you could just use
> PyObject_GetItem; obviously, this is an optimization).


Thanks for the reply Rouslan.

Perhaps I should report this as a bug.




-- 
Steven

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


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 10:16 PM, Tobias M.  wrote:
> Chris Angelico wrote:
>> The other thing you may want to consider, if the values are supposed
>> to be integers, is to convert them to Python integers before
>> comparing.
>
> I thought of this too and I wonder if there are any major differences
> regarding performance compared to using the strip() method when parsing
> large files.
>
> In addition I guess one should catch the ValueError that might be raised by
> the cast if there is something else than a number in the file.

I'd not consider the performance, but the correctness. If you're
expecting them to be integers, just cast them, and specifically
_don't_ catch ValueError. Any non-integer value will then noisily
abort the script. (It may be worth checking for blank first, though,
depending on the data origin.)

It's usually fine to have int() complain about any non-numerics in the
string, but I must confess, I do sometimes yearn for atoi() semantics:
atoi("123asd") == 123, and atoi("qqq") == 0. I've not seen a
convenient Python function for doing that. Usually it involves
manually getting the digits off the front. All I want is to suppress
the error on finding a non-digit. Oh well.

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


Re: Python to send Midi commands to iPad via USB

2013-01-24 Thread mikprog
On Thursday, January 24, 2013 10:44:47 AM UTC, Chris Angelico wrote:
[..]
> 
> Are you able to hook into ALSA? I've had reasonable success driving a
> 
> USB-MIDI cable using ALSA. See if you can do it with the inbuilt
> 
> 'pmidi' app first:
> 
> 
> 
> $ pmidi -p 128:0 No.19.mid
> 
> 
> 
> (that uses port 128:0 which is a TiMidity-provided one)
> 
> 
> 
> If that works, you can then look for Python ALSA bindings, which I
> 
> believe are available on PyPI.
> 

Thanks for your help Chris!
forgive my ignorance, but I am not sure what you mean.
I've installed pmidi and what I get is:

~$ pmidi -p 128:0 No.19.mid
Could not open file No.19.mid

Doesn't that mean that the iPad is not seen?

where:
~$ lsusb 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 002: ID 0a5c:4500 Broadcom Corp. BCM2046B1 USB 2.0 Hub (part of 
BCM2046 Bluetooth)
Bus 005 Device 002: ID 0a5c:5800 Broadcom Corp. BCM5880 Secure Applications 
Processor
Bus 003 Device 003: ID 413c:8157 Dell Computer Corp. Integrated Keyboard
Bus 003 Device 004: ID 413c:8158 Dell Computer Corp. Integrated Touchpad / 
Trackstick
Bus 006 Device 002: ID 192f:0416 Avago Technologies, Pte. 
Bus 002 Device 003: ID 05ac:12a4 Apple, Inc. 


Essentially the reason to use the iPad is because we have to make a demo where 
with our hardware we send midi commands and the iPad has a very good DJ 
application that can be used with a USB midi controller.
So I wish to connect our hardware to a Raspberry Pi (or similar) via BLE and 
then the board (Raspberry Pi) to the iPad through USB cable.

I think the weak point is communication from the Raspberry Pi (or PC) to the 
iPad via USB. I could actually remove that if I find a decent Linux/Python 
application that acts as a DJ deck.

I am having a look at pygame.midi as well, but I am not sure how to link that 
with a USB cable.

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


Re: Python to send Midi commands to iPad via USB

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 10:48 PM,   wrote:
> Thanks for your help Chris!
> forgive my ignorance, but I am not sure what you mean.
> I've installed pmidi and what I get is:
>
> ~$ pmidi -p 128:0 No.19.mid
> Could not open file No.19.mid
>
> Doesn't that mean that the iPad is not seen?

Heya! That was just an example; I used track number 19 from the opera
"Iolanthe" as my test file. Pick any other MIDI file you have handy.
Though, I may have my commands mixed up; aplaymidi may be more what
you want.

In any case, the key is the port number. Try this to enumerate ports:

$ aplaymidi -l

That's lower-case l for list. If that tells you about something that
looks like your iPad, you're in luck, ALSA has already done most of
the work! And you should be able to play any file with:

$ aplaymidi -p X:Y some-file.mid

where X:Y is from the first column of aplaymidi -l output.

On my system currently, I have 128:0 through 128:3 from TiMidity, and
14:0 "Midi Through". When my USB device is connected, I get a couple
more ports from it.

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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Chris Angelico wrote:

I'd not consider the performance, but the correctness. If you're
expecting them to be integers, just cast them, and specifically
_don't_ catch ValueError. Any non-integer value will then noisily
abort the script. (It may be worth checking for blank first, though,
depending on the data origin.)
Well, when I said you should catch the ValueError I didn't imply you 
should ignore the error and supress any error messages. Of course this 
depents on the use case. Maybe you want to raise another exception with 
a more user friendly error message or you might want to skip the line 
and just print a warning. :)


What I'm trying to say: When I give a script/program to a user who is 
not a python programmer I don't want him to see an error message like 
"ValueError: invalid literal for int() with base 10: 'abc'" as this 
would help him in no way.

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


Re: mysql solution

2013-01-24 Thread Ferrous Cranus
Τη Πέμπτη, 24 Ιανουαρίου 2013 1:25:20 μ.μ. UTC+2, ο χρήστης Lele Gaifax έγραψε:
> Ferrous Cranus  writes:
> 
> 
> 
> > I;am now convinced the hash solution isn't reversible and also isn't
> 
> > unique.
> 
> 
> 
> Great!
> 
> 
> 
> > how is the mysql statement is going to find the 'pin' to update the
> 
> > specific record.
> 
> 
> 
> The simplest way is to execute a SELECT just after the insertion, doing
> 
> a
> 
> 
> 
>   SELECT pin FROM counters WHERE page = %s
> 
> 
> 
> I don't use MySQL, so I can't say if it supports "INSERT ... RETURNING ..."
> 
> SQL syntax: should it, then you could insert the data and fetch
> 
> the pin in one shot, with something like
> 
> 
> 
>   INSERT INTO counters (page, hits) VALUES (%s, %s) RETURNING (pin)
> 
> 
> 
> ciao, lele.
> 
> --
> 
> nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
> 
> real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
> 
> [email protected]  | -- Fortunato Depero, 1929.

I just tried this statement:

==
cursor.execute( '''INSERT INTO counters(page, hits) VALUES(%s, %s) RETURNING 
(pin) 
ON DUPLICATE 
KEY UPDATE hits = hits + 1''', (htmlpage, 1) )
except MySQLdb.Error, e:
print ( "Query Error: ", sys.exc_info()[1].excepinfo()[2] )
==

and the error python tells me is:

: 'ProgrammingError' object has no attribute 
'excepinfo' 
  args = ("'ProgrammingError' object has no attribute 'excepinfo'",) 
  message = "'ProgrammingError' object has no attribute 'excepinfo'"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 10:58 PM, Tobias M.  wrote:
> Chris Angelico wrote:
>>
>> I'd not consider the performance, but the correctness. If you're
>> expecting them to be integers, just cast them, and specifically
>> _don't_ catch ValueError. Any non-integer value will then noisily
>> abort the script. (It may be worth checking for blank first, though,
>> depending on the data origin.)
>
> Well, when I said you should catch the ValueError I didn't imply you should
> ignore the error and supress any error messages. Of course this depents on
> the use case. Maybe you want to raise another exception with a more user
> friendly error message or you might want to skip the line and just print a
> warning. :)
>
> What I'm trying to say: When I give a script/program to a user who is not a
> python programmer I don't want him to see an error message like "ValueError:
> invalid literal for int() with base 10: 'abc'" as this would help him in no
> way.

Sure. Definitely. But for a proglet where the programmer IS the user
(which I think is one of Python's best use-cases), that exception
landing on the console is better than having to think ahead of time
about what might go wrong.

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


Re: using split for a string : error

2013-01-24 Thread Tobias M.

Am 24.01.2013 13:02, schrieb Chris Angelico:

On Thu, Jan 24, 2013 at 10:58 PM, Tobias M.  wrote:

Chris Angelico wrote:

I'd not consider the performance, but the correctness. If you're
expecting them to be integers, just cast them, and specifically
_don't_ catch ValueError. Any non-integer value will then noisily
abort the script. (It may be worth checking for blank first, though,
depending on the data origin.)

Well, when I said you should catch the ValueError I didn't imply you should
ignore the error and supress any error messages. Of course this depents on
the use case. Maybe you want to raise another exception with a more user
friendly error message or you might want to skip the line and just print a
warning. :)

What I'm trying to say: When I give a script/program to a user who is not a
python programmer I don't want him to see an error message like "ValueError:
invalid literal for int() with base 10: 'abc'" as this would help him in no
way.

Sure. Definitely. But for a proglet where the programmer IS the user
(which I think is one of Python's best use-cases), that exception
landing on the console is better than having to think ahead of time
about what might go wrong.

ChrisA

Okay, I absolutely agree with that :)

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


Re: mysql solution

2013-01-24 Thread Lele Gaifax
Ferrous Cranus  writes:

> Τη Πέμπτη, 24 Ιανουαρίου 2013 1:25:20 μ.μ. UTC+2, ο χρήστης Lele Gaifax 
> έγραψε:

Please, trim your response messages, cutting away useless details.

>
> I just tried this statement:
>
> ==
> cursor.execute( '''INSERT INTO counters(page, hits) VALUES(%s, %s) RETURNING 
> (pin) 
>   ON DUPLICATE 
> KEY UPDATE hits = hits + 1''', (htmlpage, 1) )
>   except MySQLdb.Error, e:
>   print ( "Query Error: ", sys.exc_info()[1].excepinfo()[2] )
> ==
>
> and the error python tells me is:
>
> : 'ProgrammingError' object has no 
> attribute 'excepinfo' 
>   args = ("'ProgrammingError' object has no attribute 'excepinfo'",) 
>   message = "'ProgrammingError' object has no attribute 'excepinfo'"

As the error message says, you have a typo in your exception handler.

I suggest using the logging[1] module to print out such information, as it
expose a bunch of handy methods that make it easier to print the
exception, for example:

  ...
  except MySQLdb.Error:
logging.error('Query Error!', exc_info=True)

or even

  ...
  except MySQLdb.Error:
logging.exception('Query Error!')

ciao, lele.

[1] http://docs.python.org/2.7/library/logging.html#module-logging
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected]  | -- Fortunato Depero, 1929.

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


Re: using split for a string : error

2013-01-24 Thread inshu chauhan
Thanks a lot people.. :).. :)



On Thu, Jan 24, 2013 at 1:10 PM, Tobias M.  wrote:

> Am 24.01.2013 13:02, schrieb Chris Angelico:
>
>  On Thu, Jan 24, 2013 at 10:58 PM, Tobias M.  wrote:
>>
>>> Chris Angelico wrote:
>>>
 I'd not consider the performance, but the correctness. If you're
 expecting them to be integers, just cast them, and specifically
 _don't_ catch ValueError. Any non-integer value will then noisily
 abort the script. (It may be worth checking for blank first, though,
 depending on the data origin.)

>>> Well, when I said you should catch the ValueError I didn't imply you
>>> should
>>> ignore the error and supress any error messages. Of course this depents
>>> on
>>> the use case. Maybe you want to raise another exception with a more user
>>> friendly error message or you might want to skip the line and just print
>>> a
>>> warning. :)
>>>
>>> What I'm trying to say: When I give a script/program to a user who is
>>> not a
>>> python programmer I don't want him to see an error message like
>>> "ValueError:
>>> invalid literal for int() with base 10: 'abc'" as this would help him in
>>> no
>>> way.
>>>
>> Sure. Definitely. But for a proglet where the programmer IS the user
>> (which I think is one of Python's best use-cases), that exception
>> landing on the console is better than having to think ahead of time
>> about what might go wrong.
>>
>> ChrisA
>>
> Okay, I absolutely agree with that :)
>
> Tobias
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to send Midi commands to iPad via USB

2013-01-24 Thread mikprog
[..]

> 
> > ~$ pmidi -p 128:0 No.19.mid
> 
> > Could not open file No.19.mid
> 
> >
> 
> > Doesn't that mean that the iPad is not seen?
> 
> 
> Heya! That was just an example; I used track number 19 from the opera
> 
> "Iolanthe" as my test file. Pick any other MIDI file you have handy.


This is exactly the point where I feel dumb :-)

 
[..] 
> $ aplaymidi -l
> 

I think I am not lucky :-(

$ aplaymidi -l
 PortClient name  Port name
 14:0Midi Through Midi Through Port-0

I get the same either the iPad is connected or not.
So I guess is not recognized.
Shame.

I'll keep on investigating, hopefully without loosing any of my neurons.

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


Re: Python to send Midi commands to iPad via USB

2013-01-24 Thread Chris Angelico
On Thu, Jan 24, 2013 at 11:25 PM,   wrote:
> I think I am not lucky :-(
>
> $ aplaymidi -l
>  PortClient name  Port name
>  14:0Midi Through Midi Through Port-0
>
> I get the same either the iPad is connected or not.
> So I guess is not recognized.
> Shame.
>
> I'll keep on investigating, hopefully without loosing any of my neurons.

Yeah, this is the bit where you have to poke around with iPad stuff.
They say "there's an app for that"; maybe there's a way to turn an
iPad into a USB MIDI device. I did a quick Google search for 'ipad usb
midi' and there seem to be some decent hits, so your luck mightn't
have completely run out yet.

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


Re: mysql solution

2013-01-24 Thread Ferrous Cranus
column 'pin' is an 5-digit integer auto_increment primary key.

What i want is to insert a new record or update the existing one, if 'pin' 
column's value exist. The following statement fails.

[code]
cursor.execute( '''INSERT INTO counters(page, hits) VALUES(%s, %s) RETURNING 
(pin) 
ON DUPLICATE KEY UPDATE hits = hits + 1''', (htmlpage, 
1) )
[/code] 

Also except from the inserting/updating job, i also need 'pin' colum's value to 
be extracted from the above statement so to be used to subsequent statement 
like the following. This is not happening, hence the following statement have 
no way to find 'pin' column's value which is to be used as a parameter to it.

[code]
cursor.execute( '''UPDATE visitors SET hits = hits + 1, useros = %s, browser = 
%s, date = %s WHERE pin = %s AND host = %s''', (useros, browser, date, pin, 
host)) 
[/code]

Can someone correct this please and explain?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysql solution

2013-01-24 Thread Ferrous Cranus
Τη Πέμπτη, 24 Ιανουαρίου 2013 1:16:51 μ.μ. UTC+2, ο χρήστης Chris Angelico 
έγραψε:
> On Thu, Jan 24, 2013 at 10:04 PM, Ferrous Cranus  
> wrote:
> 
> > I;am now convinced the hash solution isn't reversible and also isn't unique.
> 
> > I'am trying the database oriented solution.
> 
> 
> 
> Glad you've listened to at least some of what you've been told. But if
> 
> you want to be taken seriously on this list, I recommend going back to
> 
> your previous name of Νικόλαος Κούρας (which Google Translate tells me
> 
> transliterates as Nicholas Kouri), apologizing for trolling, and being
> 
> VERY careful to be respectful. I suspect a number of the list's best
> 
> posters have already killfiled you.

First of all i'am not trolling, it looks like i'am trolling because i persist 
"on my way" of handling a problem.

Secondly, why go back to that handle?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysql solution

2013-01-24 Thread Lele Gaifax
Ferrous Cranus  writes:

> The following statement fails.
>
> [code]
> cursor.execute( '''INSERT INTO counters(page, hits) VALUES(%s, %s) RETURNING 
> (pin) 
> ON DUPLICATE KEY UPDATE hits = hits + 1''', 
> (htmlpage, 1) )
> [/code] 

How? What's the error message/traceback?

If, as Chris said, MySQL does not support the “RETURNING” syntax, you
cannot use that. I gave two different solutions in my previous message,
did you try the “simplest” one?

ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected]  | -- Fortunato Depero, 1929.

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


Re: Retrieving the full command line

2013-01-24 Thread Tim Golden
On 24/01/2013 11:30, Oscar Benjamin wrote:
> I don't really understand what your spec is. Why do you need to
> inspect this information from sys.argv? Can you not just always use
> 'python -m pkg' as your entry point?

Sorry about the confusion. I think my original point was simply one
of surprise that sys.argv wouldn't essentially mirror the elements
of the command line which I used to get there.
The specifics of my use-case weren't really too important.

For completeness, I'm talking about the cherrypy Autoreloader which
attempts to restart (via execv) whatever process was responsible for
loading it in the first place, via an identical or equivalent command
line. The current (cherrypy) code simply joins sys.executable and
sys.argv but this fails in the face of python -m as we have seen.

The cherrypy package has no especial knowledge of the structure of the
application which imported it and so must piece together the command
line somehow. Clearly, I can take various approaches of the sort
which you've outlined, or subclass the reloader, or fetch the original
command line from the OS, etc. It's not that this is a showstopper,
merely slightly surprising. (To me).

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


anyone can make a Python bindings of VLC-Qt ?

2013-01-24 Thread iMath

anyone can make a Python bindings of VLC-Qt  ?
https://github.com/ntadej/vlc-qt
accurately, can anyone make a  PyQt bindings of VLC-Qt  ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysql solution

2013-01-24 Thread Ferrous Cranus
Τη Πέμπτη, 24 Ιανουαρίου 2013 3:37:24 μ.μ. UTC+2, ο χρήστης Lele Gaifax έγραψε:

> How? What's the error message/traceback?

REURNING is not a correct mysql syntax thats why it produces errors.

> If, as Chris said, MySQL does not support the “RETURNING” syntax, you
> 
> cannot use that. I gave two different solutions in my previous message,
> 
> did you try the “simplest” one?

SELECT pin FROM counters WHERE page = %s 

I can do that but then i have to use that pin column's value in my next 
statement.

cursor.execute( '''UPDATE visitors SET hits = hits + 1, useros = %s, browser = 
%s, date = %s WHERE pin = %s AND host = %s''', (useros, browser, date, pin, 
host)) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysql solution

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 12:31 AM, Ferrous Cranus  wrote:
> Τη Πέμπτη, 24 Ιανουαρίου 2013 1:16:51 μ.μ. UTC+2, ο χρήστης Chris Angelico 
> έγραψε:
>> Glad you've listened to at least some of what you've been told. But if
>> you want to be taken seriously on this list, I recommend going back to
>> your previous name of Νικόλαος Κούρας (which Google Translate tells me
>> transliterates as Nicholas Kouri), apologizing for trolling, and being
>> VERY careful to be respectful. I suspect a number of the list's best
>> posters have already killfiled you.
>
> First of all i'am not trolling, it looks like i'am trolling because i persist 
> "on my way" of handling a problem.

Then why do you use, as your name, something which everyone who tries
a quick web search will see is the name of a category of troll? And,
what's more, a category which clearly includes you?

Python believes in "duck typing". Instead of writing a function that
expects a File object, Python tends toward writing functions that
expect an object that can be given data to write() out. Or, instead of
looking for an integer, Python code will look for "something that can
be added to 5". In the same way, we on this list do not ask "are you a
troll". We ask "does your behaviour match that of a troll". You are
treated as a troll because you act like one.

> Secondly, why go back to that handle?

That said, though, carrying the name of a troll doesn't help. Using
your real name is the best way to get started. If you want to win
respect, you want to win it for yourself, not for some strange title.
(There are exceptions to that principle. Some people on the list don't
use their names, and I'm on another list where one of the regular
posters freely admits that the name "John Spartan" isn't actually his.
But in general, you should use your real name.)

Among geeks (and this list/newsgroup is full of them), respect is
everything. You earn it, you give it. The best ways to earn respect
are to give respect and to contribute to the community. Contributing
is fairly obvious; answering questions, helping out, submitting
patches, triaging bugs, reviewing and confirming bug reports. Stuff
that takes time and benefits other people. The "top dogs" in a geeky
community are usually the ones who give the most time. I've no idea
how many hours Guido puts into Python, but it'll be rather a lot.

Giving respect is a little harder to define, but just as important.
The main thing to remember is that we, here, helping you, are
volunteers. Nobody is paying us to solve your problems, especially not
you yourself. Demanding that we solve your problems is NOT respectful.
Offering us interesting problems (which we enjoy), following up
courteously, helping to maintain the community's standards (even in
supposedly-trivial matters like bottom-posting), and doing your own
work before asking for help, ARE. I recently dropped someone a private
note thanking him for the way he phrased his question, because it made
for a very interesting little puzzle, and he'd clearly put work into
it. It was a pleasure to help him, cliche though that sound. He was
respectful of the time people would put in, and afterward of the time
they had put in, and thus he won respect.

Ferrous/Nicholas, you are currently looking like that very worst thing
on a mailing list: an open-ended time sink. You are looking like
you'll cost huge numbers of smart-person-hours (that's like man-hours
but not gender specific, or like programmer-hours but less mythical)
with little or no benefit to the community. Continue down this path
and you will find yourself with nobody to talk to, as everyone will
decide that the best use of time is to delete your posts unread.

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


Re: anyone can make a Python bindings of VLC-Qt ?

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 1:25 AM, iMath  wrote:
>
> anyone can make a Python bindings of VLC-Qt  ?
> https://github.com/ntadej/vlc-qt
> accurately, can anyone make a  PyQt bindings of VLC-Qt  ?

Yes, someone can. Ideally, someone who knows C++, Python, VLC, and Qt,
and has the time to port the code you just linked to. It'll probably
be a fairly big job, but relatively straight-forward for someone who
knows. That someone isn't me, though (I don't know Qt, and I'm not
familiar with VLC's internals - my knowledge of VLC is just as a
user); maybe it's you?

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread John Gordon
In  Hazard Seventyfour 
 writes:

> Hello,

> I new in this python and decided to learn more about it, so i can make
> an own script :),

> for all senior can you suggest me the best, friendly and easy use with
> nice GUI editor for me, and have many a good features such as auto
> complete/auto correct.

Try PyScripter.

http://code.google.com/p/pyscripter/

-- 
John Gordon   A is for Amy, who fell down the stairs
[email protected]  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: mysql solution

2013-01-24 Thread Duncan Booth
Ferrous Cranus  wrote:

> I can do that but then i have to use that pin column's value in my
> next statement. 
> 
> cursor.execute( '''UPDATE visitors SET hits = hits + 1, useros = %s,
> browser = %s, date = %s WHERE pin = %s AND host = %s''', (useros,
> browser, date, pin, host)) 

I'm not MySQL expert, but something like this might work:

cursor.execute('''UPDATE visitors,counter 
SET visitors.hits=visitors.hits+1, visitors.useros=%s,
visitors.browser =%s, visitors.date=%s
WHERE visitors.pin=counter.pin AND counter.page = %s 
AND visitors.host=%s''',
   (useros, browser, date, page, host))

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysql solution

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 2:19 AM, Duncan Booth
 wrote:
> Ferrous Cranus  wrote:
>
>> I can do that but then i have to use that pin column's value in my
>> next statement.
>>
>> cursor.execute( '''UPDATE visitors SET hits = hits + 1, useros = %s,
>> browser = %s, date = %s WHERE pin = %s AND host = %s''', (useros,
>> browser, date, pin, host))
>
> I'm not MySQL expert, but something like this might work:
>
> cursor.execute('''UPDATE visitors,counter
> SET visitors.hits=visitors.hits+1, visitors.useros=%s,
> visitors.browser =%s, visitors.date=%s
> WHERE visitors.pin=counter.pin AND counter.page = %s
> AND visitors.host=%s''',
>(useros, browser, date, page, host))

Not sure that that works. This should, though:

UPDATE visitors SET hits=hits+1,blah,blah WHERE visitors.pin=(SELECT
pin FROM counter WHERE page=%s)

I prefer not to mention a table for updating if it's not actually being updated.

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


Re: Retrieving the full command line

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 13:45, Tim Golden  wrote:
> On 24/01/2013 11:30, Oscar Benjamin wrote:
>> I don't really understand what your spec is. Why do you need to
>> inspect this information from sys.argv? Can you not just always use
>> 'python -m pkg' as your entry point?
>
[SNIP]
>
> For completeness, I'm talking about the cherrypy Autoreloader which
> attempts to restart (via execv) whatever process was responsible for
> loading it in the first place, via an identical or equivalent command
> line. The current (cherrypy) code simply joins sys.executable and
> sys.argv but this fails in the face of python -m as we have seen.
>
> The cherrypy package has no especial knowledge of the structure of the
> application which imported it and so must piece together the command
> line somehow. Clearly, I can take various approaches of the sort
> which you've outlined, or subclass the reloader, or fetch the original
> command line from the OS, etc. It's not that this is a showstopper,
> merely slightly surprising. (To me).

Ok I understand. Then I guess you want:

import __main__
pkg = __main__.__package__


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Sharwan Joram
On Thursday, January 24, 2013 8:42:19 PM UTC+5:30, John Gordon wrote:
> In  Hazard Seventyfour 
>  writes:
> 
> 
> 
> > Hello,
> 
> 
> 
> > I new in this python and decided to learn more about it, so i can make
> 
> > an own script :),
> 
> 
> 
> > for all senior can you suggest me the best, friendly and easy use with
> 
> > nice GUI editor for me, and have many a good features such as auto
> 
> > complete/auto correct.
> 
> 
> 
> Try PyScripter.
> 
> 
> 
> http://code.google.com/p/pyscripter/
> 
> 
> 
> -- 
> 
> John Gordon   A is for Amy, who fell down the stairs
> 
> [email protected]  B is for Basil, assaulted by bears
> 
> -- Edward Gorey, "The Gashlycrumb Tinies"

use vim.

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


Re: mysql solution

2013-01-24 Thread Lele Gaifax
Duncan Booth  writes:

> I'm not MySQL expert, but something like this might work:
>
> cursor.execute('''UPDATE visitors,counter 
> SET visitors.hits=visitors.hits+1, visitors.useros=%s,
> visitors.browser =%s, visitors.date=%s
> WHERE visitors.pin=counter.pin AND counter.page = %s 
> AND visitors.host=%s''',
>(useros, browser, date, page, host))

I stopped surprising at MySQL syntax eons ago, so if that works... great!

Otherwise I would write the equivalent statement with a more "standard
syntax" (for whatever meaning of "standard" in the SQL world :-) as:

UPDATE visitors
   SET visitors.hits=visitors.hits+1, 
   visitors.useros=%s,
   visitors.browser=%s, 
   visitors.date=%s
WHERE visitors.pin=(SELECT counters.pin
FROM counters
WHERE counters.page=%s)
  AND visitors.host=%s

But I wonder about the "logic" here: why are you storing the "useros",
"browser" and "date" in a table where the primary key seems to be
("pin", "host")? I mean, what happens if a user visits the same page
twice, first with Firefox and then with Chrome?

hope this helps,
ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected]  | -- Fortunato Depero, 1929.

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


Re: Retrieving the full command line

2013-01-24 Thread Tim Golden
On 24/01/2013 15:28, Oscar Benjamin wrote:
> On 24 January 2013 13:45, Tim Golden  wrote:
>> On 24/01/2013 11:30, Oscar Benjamin wrote:
>>> I don't really understand what your spec is. Why do you need to
>>> inspect this information from sys.argv? Can you not just always use
>>> 'python -m pkg' as your entry point?
>>
> [SNIP]
>>
>> For completeness, I'm talking about the cherrypy Autoreloader which
>> attempts to restart (via execv) whatever process was responsible for
>> loading it in the first place, via an identical or equivalent command
>> line. The current (cherrypy) code simply joins sys.executable and
>> sys.argv but this fails in the face of python -m as we have seen.
>>
>> The cherrypy package has no especial knowledge of the structure of the
>> application which imported it and so must piece together the command
>> line somehow. Clearly, I can take various approaches of the sort
>> which you've outlined, or subclass the reloader, or fetch the original
>> command line from the OS, etc. It's not that this is a showstopper,
>> merely slightly surprising. (To me).
> 
> Ok I understand. Then I guess you want:
> 
> import __main__
> pkg = __main__.__package__

Brilliant. Never thought of importing __main__. Thanks.

For the benefit of anyone still watching, the code (which has to be
compatible back to 2.3) looks something like this:


import __main__

# [.. .snip ...]

try:
is_package = bool(__main__.__package__)
except NameError:
is_package = False
if is_package:
args = [sys.executable, '-m', __main__.__package__] + sys.argv[1:]
else:
args = [sys.executable] + sys.argv

os.chdir(_startup_cwd) # avoids relative/absolute issues
os.execv(args[0], args)



I don't pretend it's foolproot, but it certainly works for my particular
case. Nor have I considered it against all the cases identified in PEP
432: http://www.python.org/dev/peps/pep-0432/#configuring-sys-argv

TJG

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread rusi
On Jan 24, 2:43 pm, Hazard Seventyfour  wrote:
> Hello,
>
> I new in this python and decided to learn more about it, so i can make an own 
> script :),
>
> for all senior can you suggest me the best, friendly and easy use with nice 
> GUI editor for me, and have many a good features such as auto complete/auto 
> correct.
>
> any recommend? Thanks ^_^

What editor you use does not matter. What matters is that you learn to
use the interpreter.

That is learn to use things like
- history
- last expression with _ (underscore)
- Using introspection to find out about odd stuff (ie use dir and
help)
- Loading a python file
- And after things kind-of work, copy pasting into your editor

Here's a test to check whether youve got the idea: Do you think that
to write a program you need to write a 'main?' If yes then no!

[I personally use emacs. It would be sadistic to make that into a
recommendation]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 2:54 AM, rusi  wrote:
> - last expression with _ (underscore)

Small terminology quibble: That's not last expression, but last non-None result.

>>> 1+2
3
>>> _
3
>>> _,None
(3, None)
>>> _
(3, None)
>>> _[1]
>>> _
(3, None)

Otherwise, agree totally. Get to know the interactive interpreter, and
keep it handy.

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread John Gordon
In  Sharwan Joram 
 writes:

> use vim.

He said he wanted autocomplete.  Does Vim have that?

-- 
John Gordon   A is for Amy, who fell down the stairs
[email protected]  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Retrieving the full command line

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 15:51, Tim Golden  wrote:
> On 24/01/2013 15:28, Oscar Benjamin wrote:
>> On 24 January 2013 13:45, Tim Golden  wrote:
>>> On 24/01/2013 11:30, Oscar Benjamin wrote:
 I don't really understand what your spec is. Why do you need to
 inspect this information from sys.argv? Can you not just always use
 'python -m pkg' as your entry point?
>>>
>> [SNIP]
>>>
>>> For completeness, I'm talking about the cherrypy Autoreloader which
>>> attempts to restart (via execv) whatever process was responsible for
>>> loading it in the first place, via an identical or equivalent command
>>> line. The current (cherrypy) code simply joins sys.executable and
>>> sys.argv but this fails in the face of python -m as we have seen.
>>>
>>> The cherrypy package has no especial knowledge of the structure of the
>>> application which imported it and so must piece together the command
>>> line somehow. Clearly, I can take various approaches of the sort
>>> which you've outlined, or subclass the reloader, or fetch the original
>>> command line from the OS, etc. It's not that this is a showstopper,
>>> merely slightly surprising. (To me).
>>
>> Ok I understand. Then I guess you want:
>>
>> import __main__
>> pkg = __main__.__package__
>
> Brilliant. Never thought of importing __main__. Thanks.
>
> For the benefit of anyone still watching, the code (which has to be
> compatible back to 2.3) looks something like this:
>
> 
> import __main__
>
> # [.. .snip ...]
>
> try:
> is_package = bool(__main__.__package__)
> except NameError:
> is_package = False
> if is_package:
> args = [sys.executable, '-m', __main__.__package__] + sys.argv[1:]
> else:
> args = [sys.executable] + sys.argv
>
> os.chdir(_startup_cwd) # avoids relative/absolute issues
> os.execv(args[0], args)
>
> 
>
> I don't pretend it's foolproot, but it certainly works for my particular
> case. Nor have I considered it against all the cases identified in PEP
> 432: http://www.python.org/dev/peps/pep-0432/#configuring-sys-argv

Does it work if you use the -m option to run a module rather than a script?


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Thomas Heller

Am 24.01.2013 16:54, schrieb rusi:

[I personally use emacs. It would be sadistic to make that into a
recommendation]


It would be truly sadistic to force a long-time emacs user to any
other editor.

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


Re: Retrieving the full command line

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 16:08, Oscar Benjamin  wrote:
> On 24 January 2013 15:51, Tim Golden  wrote:
>> On 24/01/2013 15:28, Oscar Benjamin wrote:
>>> On 24 January 2013 13:45, Tim Golden  wrote:
 On 24/01/2013 11:30, Oscar Benjamin wrote:
> I don't really understand what your spec is. Why do you need to
> inspect this information from sys.argv? Can you not just always use
> 'python -m pkg' as your entry point?

>>> [SNIP]

 For completeness, I'm talking about the cherrypy Autoreloader which
 attempts to restart (via execv) whatever process was responsible for
 loading it in the first place, via an identical or equivalent command
 line. The current (cherrypy) code simply joins sys.executable and
 sys.argv but this fails in the face of python -m as we have seen.

 The cherrypy package has no especial knowledge of the structure of the
 application which imported it and so must piece together the command
 line somehow. Clearly, I can take various approaches of the sort
 which you've outlined, or subclass the reloader, or fetch the original
 command line from the OS, etc. It's not that this is a showstopper,
 merely slightly surprising. (To me).
>>>
>>> Ok I understand. Then I guess you want:
>>>
>>> import __main__
>>> pkg = __main__.__package__
>>
>> Brilliant. Never thought of importing __main__. Thanks.
>>
>> For the benefit of anyone still watching, the code (which has to be
>> compatible back to 2.3) looks something like this:
>>
>> 
>> import __main__
>>
>> # [.. .snip ...]
>>
>> try:
>> is_package = bool(__main__.__package__)
>> except NameError:
>> is_package = False
>> if is_package:
>> args = [sys.executable, '-m', __main__.__package__] + sys.argv[1:]
>> else:
>> args = [sys.executable] + sys.argv
>>
>> os.chdir(_startup_cwd) # avoids relative/absolute issues
>> os.execv(args[0], args)
>>
>> 
>>
>> I don't pretend it's foolproot, but it certainly works for my particular
>> case. Nor have I considered it against all the cases identified in PEP
>> 432: http://www.python.org/dev/peps/pep-0432/#configuring-sys-argv
>
> Does it work if you use the -m option to run a module rather than a script?

Sorry that was written incorrectly. I meant to say: does it work when
a module is directly on sys.path rather than as a submodule of a
package? In this case __package__ is set to the empty string if run
with -m or None if run with a direct path. So the check needs to be
"__package__ is not None" rather than "bool(__package__)".


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Tim Chase

On 01/24/13 10:23, Thomas Heller wrote:

Am 24.01.2013 16:54, schrieb rusi:

[I personally use emacs. It would be sadistic to make that into a
recommendation]


It would be truly sadistic to force a long-time emacs user to any
other editor.


I saw the recommendation for Vim elsewhere on the thread and comment 
the same as this sub-thread: "I personally use vim. It would be 
sadistic to make that into a recommendation"  And likewise, it's 
"truly sadistic to force a long-time vim user to any other editor." :-)


Not that Vim isn't great for programming Python (which I do 
daily)...it *is*!  It's just not where I'd throw somebody who 
doesn't already have an existing editor preference *and* doesn't 
know Python.


-tkc





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


monolithic apps

2013-01-24 Thread tamnt54
Any suggestions for study?..:
 Is is possible to take a large executable with GUI and real time data and 
images, to extract modules, and it can run as if it looks like a monolithic 
application (windows over main windows, or images over other images) but is 
various python script driven modules calling each other as separate apps?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving the full command line

2013-01-24 Thread Tim Golden
On 24/01/2013 16:53, Oscar Benjamin wrote:
>> Does it work if you use the -m option to run a module rather than a script?
> 
> Sorry that was written incorrectly. I meant to say: does it work when
> a module is directly on sys.path rather than as a submodule of a
> package? In this case __package__ is set to the empty string if run
> with -m or None if run with a direct path. So the check needs to be
> "__package__ is not None" rather than "bool(__package__)".

The answer is: it depends. Given the code I outlined earlier:

A package-based module run via -m (python -m package.module) works
as described (including the implicit __main__ module, my
primary use-case).

A module run from the filesystem (python c:\path\to\module.py) works
by dropping through through to the not is_package logic branch.

A module run via -m (python -m module) actually works by accident,
because it too drops through to the not is_package branch and is
rerun with its full filesystem path. This doesn't have the same
problems as running a package from the filesystem because relative
imports aren't an issue. I don't know if there are any other differences
between python -mmodule and python c:\path\to\module.py.

As you say, a more refined check could determine a blank __package__
as opposed to a None __package__. But this code (cherrypy) must also
cope with version of Python before 2.6 which didn't even have a
__package__ attribute, muddying the waters that little bit further.

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Andrew Gudovich
I think PyCharm is ideal for you.

http://www.jetbrains.com/pycharm/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: monolithic apps

2013-01-24 Thread Dave Angel

On 01/24/2013 12:06 PM, [email protected] wrote:

Any suggestions for study?..:
  Is is possible to take a large executable with GUI and real time data and 
images, to extract modules, and it can run as if it looks like a monolithic 
application (windows over main windows, or images over other images) but is 
various python script driven modules calling each other as separate apps?



I can see at least 4 things you might mean.  Perhaps you'd better spell 
it out.


1) glom all the scripts & binary modules into one big file, so the user 
thinks it's one huge app


2) Manipulate multiple gui apps while having the same UI as though there 
was just one main window, and other windows all belong to it.  Multiple 
GUI processes, but some central control to change the user experience 
into resembling a single GUI app.


3) Have one gui app "main" that other apps can somehow call to 
manipulate the windows of "main."  Multiple processes, only one of them 
with a GUI.


4) From a GUI app, use other apps as loadable modules, and reuse their 
class definitions and functions by calling them from the GUI app.  One 
process.



You say this a topic for study, but there's a lot of other things you 
may need to specify before you get to implementing.  What OS, what 
version of Python, what GUI, are these apps modifiable, or are you just 
allowed to write glue, ...


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


Changing the font size of anOptionMenu widget

2013-01-24 Thread Angel
I am changing the font of an OptionMenu widget:

w = OptionMenu(master, variable, "one", "two", "three")

with 

w.configure()

That changes the font of the widget but how can I change also the font (size) 
of the menu that appears when the mouse clicks it?

Thanks in advandce,

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


Re: monolithic apps

2013-01-24 Thread Ulrich Eckhardt

Am 24.01.2013 18:06, schrieb [email protected]:

Any suggestions for study?..: Is is possible to take a large
executable with GUI and real time data and images, to extract
modules, and it can run as if it looks like a monolithic application
(windows over main windows, or images over other images) but is
various python script driven modules calling each other as separate
apps?



http://www.gnu.org/software/hurd/

Uli


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


Re: mysql solution

2013-01-24 Thread Ferrous Cranus
Τη Πέμπτη, 24 Ιανουαρίου 2013 5:39:54 μ.μ. UTC+2, ο χρήστης Lele Gaifax έγραψε:

> UPDATE visitors
> 
>SET visitors.hits=visitors.hits+1, 
> 
>visitors.useros=%s,
> 
>visitors.browser=%s, 
> 
>visitors.date=%s
> 
> WHERE visitors.pin=(SELECT counters.pin
> 
> FROM counters
> 
> WHERE counters.page=%s)
> 
>   AND visitors.host=%s
> 
> 
> 
> But I wonder about the "logic" here: why are you storing the "useros",
> 
> "browser" and "date" in a table where the primary key seems to be
> 
> ("pin", "host")? I mean, what happens if a user visits the same page
> 
> twice, first with Firefox and then with Chrome?


it doesn't work, it creates new entries on every webpage visit instead of 
updating.

this is what i have up until now:

[code]
# insert new page record in table counters or update it if already 
exists
try:
cursor.execute( '''INSERT INTO counters(page, hits) VALUES(%s, 
%s)
ON DUPLICATE 
KEY UPDATE hits = hits + 1''', (htmlpage, 1) )
except MySQLdb.Error, e:
print ( "Error %d: %s" % (e.args[0], e.args[1]) )

# update existing visitor record if same pin and same host found
try:
cursor.execute('''UPDATE visitors SET hits=hits+1, useros=%s, 
browser=%s, date=%s 
  WHERE id=(SELECT id FROM 
counters WHERE page=%s) AND host=%s''',

(useros, browser, date, htmlpage, host))
except MySQLdb.Error, e:
print ( "Error %d: %s" % (e.args[0], e.args[1]) )

# insert new visitor record if above update did not affect a row
if cursor.rowcount == 0:
cursor.execute( '''INSERT INTO visitors(hits, host, useros, 
browser, date) VALUES(%s, %s, %s, %s, %s)''', (1, host, useros, browser, date) )
[/code]

Something is definately wrong here, its logic is not correct.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Increase value in hash table

2013-01-24 Thread Vito De Tullio
moonhkt wrote:

> Data file
> V1
> V2
> V3
> V4
> V4
> V3
> 
> How to using count number of data ?
> 
> Output
> V1 = 1
> V2 = 1
> V3 =2
> V4 = 2

import collections

with open(data_file) as f:
print(collections.Counter(f.readlines()))


it's a start

-- 
ZeD

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


Search Engine optimization technique

2013-01-24 Thread Marlen Coner
jilltoler.com is a web blog where you can find WHAT IS Search Engine
optimization, what is SEO Analytics, and how to you SEO tools and
Importance of SEO Rankings.

For more information please visit : http://www.jilltoler.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Walter Hurry
On Thu, 24 Jan 2013 22:10:21 +1100, Chris Angelico wrote:

> On Thu, Jan 24, 2013 at 8:43 PM, Hazard Seventyfour
>  wrote:
>> Hello,
>>
>> I new in this python and decided to learn more about it, so i can make
>> an own script :),
>>
>> for all senior can you suggest me the best, friendly and easy use with
>> nice GUI editor for me, and have many a good features such as auto
>> complete/auto correct.
>>
>> any recommend? Thanks ^_^
> 
> Here we go, it's holy war time again! :)
> 
> You'll get a HUGE lot of responses. Many use emacs or vim, and you'll
> get a few recommendations for IDLE. After that, it's a huge field of
> options. I personally use SciTE; it's a good editor, but I don't
> particularly like the way the project is run (nothing strong, but I
> didn't like the tone on its mailing list). Eclipse has its fans, too.
> 
> A Python IDE is not nearly as beneficial as, say, a Java IDE. A good
> Python editor just needs to do the basics like indentation, syntax
> highlighting, and such; I like IDLE's method info when I'm working
> interactively, but it's not a big deal when I'm writing a program. In
> fact, all you really need out of an IDE can probably be supplied by just
> a good editor, maybe a makefile, and alt-tabbing to IDLE. However, if
> you want an IDE, they do exist.

All true (especially the holy wars bit!). OP didn't (as far as I can see) 
even say which OS he is using. Anyway, my suggestion is generally that 
people use the editor with which they are already comfortable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to send Midi commands to iPad via USB

2013-01-24 Thread rusi
On Jan 24, 3:31 pm, [email protected] wrote:
> Dear all,
>
> I am asking for a design/strategy suggestion.
>
> What I have to do is to write a Python application that will send MIDI 
> commands to an iPad application.
> All I know is that the iPad application can be connected to an external Midi 
> deck through a usb cable and be controlled.
> So I think I would connect the iPad via USB to my computer and... try to send 
> midi commands.
> I think the limitation is that the iPad will allow signaling/connection only 
> to Midi devices, so I have to make so that my Python script pretends that my 
> computer is a Midi device.
> So far I have tried PyUSB library and I can see the iPad, but I can't send 
> anything to it (probably because I am not pretending to be a Midi device well 
> enough).
>
> I am keen to try PyUSB + pygame for the Midi stuff.
>
> Any suggestion / recommendation / hint / whatever to tell me?
> I appreciate every idea at this stage!
>
> Thanks for reading,
> Mik

Some suggestions:
1. The linux audio list will serve you better than the python list for
this line of questions
2. Before worrying about python get your 'plumbing' right with
dedicated midi s/w like rosegarden, qtractor etc
3. [I dont understand much midi but…] look at aconnect, aseqnet in
addition to pmidi, aplaymidi
4. On some recent linuxes, (notably ubuntu) timidity is broken thanks
to pulseaudio. In particular, timidity as a normal program works does
not imply that timidity as a server works
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: The best, friendly and easy use Python Editor.

2013-01-24 Thread Leonard, Arah
> All true (especially the holy wars bit!). OP didn't (as far as I can see) 
> even say which OS he is using. Anyway, my suggestion is generally that people 
> use the editor with which they are already comfortable.
> 

Sound advice.  Most of the time I still use Visual Studio for editing Python 
because I also use it for C++, so it's just what I'm used to.  No big deal, 
really.  Whatever works is what works.  It's just a text file after all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving the full command line

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 17:13, Tim Golden  wrote:
> On 24/01/2013 16:53, Oscar Benjamin wrote:
>>> Does it work if you use the -m option to run a module rather than a script?
>>
>> Sorry that was written incorrectly. I meant to say: does it work when
>> a module is directly on sys.path rather than as a submodule of a
>> package? In this case __package__ is set to the empty string if run
>> with -m or None if run with a direct path. So the check needs to be
>> "__package__ is not None" rather than "bool(__package__)".
>
> The answer is: it depends. Given the code I outlined earlier:
>
> A package-based module run via -m (python -m package.module) works
> as described (including the implicit __main__ module, my
> primary use-case).

Does it work in the "python -m package.module" case? It looks to me as
if the code below will run "python -m package" instead. I think you
need to split the module name out of sys.argv[0] and put that into the
command line as well.

> import __main__
>
> # [.. .snip ...]
>
> try:
> is_package = bool(__main__.__package__)
> except NameError:
> is_package = False
> if is_package:
> args = [sys.executable, '-m', __main__.__package__] + sys.argv[1:]
> else:
> args = [sys.executable] + sys.argv
>
> os.chdir(_startup_cwd) # avoids relative/absolute issues
> os.execv(args[0], args)

I believe "python -m package" and "python -m package.__main__" are
equivalent so it doesn't matter in that case.

>
> A module run from the filesystem (python c:\path\to\module.py) works
> by dropping through through to the not is_package logic branch.
>
> A module run via -m (python -m module) actually works by accident,
> because it too drops through to the not is_package branch and is
> rerun with its full filesystem path. This doesn't have the same
> problems as running a package from the filesystem because relative
> imports aren't an issue. I don't know if there are any other differences
> between python -mmodule and python c:\path\to\module.py.

There is a (probably pathological) case in which running the script
via a file path and running it via -m are not equivalent. "python
dir/script.py" places "dir" at the top of sys.path. "python -m script"
only works if "dir" is in sys.path but it needn't be at the top. This
means that the order of sys.path is changed and import conflicts may
be resolved differently in the two cases:

~$ cat ~/.local/lib/python2.7/site-packages/script.py
print("Running script.py")
import optparse
~$ cat ~/.local/lib/python2.7/site-packages/optparse.py
raise ImportError('Wrong optparse!')
~$ python ~/.local/lib/python2.7/site-packages/script.py
Running script.py
Traceback (most recent call last):
  File "/home/oscar/.local/lib/python2.7/site-packages/script.py",
line 2, in 
import optparse
  File "/home/oscar/.local/lib/python2.7/site-packages/optparse.py",
line 1, in 
raise ImportError('Wrong optparse!')
ImportError: Wrong optparse!
~$ python -m script
Running script.py
~$ python ~/.local/lib/python2.7/site-packages/script.py
Running script.py
Traceback (most recent call last):
  File "/home/oscar/.local/lib/python2.7/site-packages/script.py",
line 2, in 
import optparse
  File "/home/oscar/.local/lib/python2.7/site-packages/optparse.py",
line 1, in 
raise ImportError('Wrong optparse!')
ImportError: Wrong optparse!
~$ python -m script
Running script.py

>
> As you say, a more refined check could determine a blank __package__
> as opposed to a None __package__. But this code (cherrypy) must also
> cope with version of Python before 2.6 which didn't even have a
> __package__ attribute, muddying the waters that little bit further.

Then you won't be able to use this method to get the -m switch to work
on Python < 2.6. If it's ok to just never try the -m switch on those
versions then it's as simple as doing:
pkg = getattr(__main__, '__package__', None)


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Dave Hirschfeld
Leonard, Arah  bruker-axs.com> writes:

> 
> > All true (especially the holy wars bit!). OP didn't (as far as I can see) 
> >even say which OS he is using.
> Anyway, my suggestion is generally that people use the editor with which 
> > they are already comfortable.
> > 
> 
> Sound advice.  Most of the time I still use Visual Studio for editing Python 
> because I also use it for C++, so
> it's just what I'm used to.  No big deal, really.  Whatever works is what 
> works. It's just a text file after all.
> 

I assume you're using PyTools (http://pytools.codeplex.com/)?

-Dave

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Neil Cerutti
On 2013-01-24, John Gordon  wrote:
> In  Sharwan Joram 
>  writes:
>
>> use vim.
>
> He said he wanted autocomplete.  Does Vim have that?

Yes, you use its ctags support to get it working, I believe.

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Neil Cerutti
On 2013-01-24, Tim Chase  wrote:
> On 01/24/13 10:23, Thomas Heller wrote:
>> Am 24.01.2013 16:54, schrieb rusi:
>>> [I personally use emacs. It would be sadistic to make that into a
>>> recommendation]
>>>
>> It would be truly sadistic to force a long-time emacs user to any
>> other editor.
>
> I saw the recommendation for Vim elsewhere on the thread and comment 
> the same as this sub-thread: "I personally use vim. It would be 
> sadistic to make that into a recommendation"  And likewise, it's 
> "truly sadistic to force a long-time vim user to any other editor." :-)
>
> Not that Vim isn't great for programming Python (which I do 
> daily)...it *is*!  It's just not where I'd throw somebody who 
> doesn't already have an existing editor preference *and* doesn't 
> know Python.

I agree.

Vim is great, Emacs is great. I'm glad I know one of them. But
learning one of them is as project unto itself. So selecting
either just for Python is skipping too many decisions and maybe
biting off too big a piece of the snake.

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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Tim Chase

On 01/24/13 13:34, Leonard, Arah wrote:

All true (especially the holy wars bit!). OP didn't (as far as
I can see) even say which OS he is using. Anyway, my suggestion
is generally that people use the editor with which they are
already comfortable.


Sound advice.  [snip] Whatever works is what works. It's just a
text file after all.


So even "ed" or "edlin" or even "cat" would do ;-)
?
-tkc
?
wq




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


RE: The best, friendly and easy use Python Editor.

2013-01-24 Thread Leonard, Arah
>> Sound advice.  Most of the time I still use Visual Studio for editing 
>> Python because I also use it for C++, so it's just what I'm used to.  
>> No big deal, really.  Whatever works is what works. It's just a text 
>> file after all.
>> 
> 
> I assume you're using PyTools (http://pytools.codeplex.com/)?
> 

Would that I could!  To my knowledge they still haven't backported PyTools to 
VS2008, which I'm presently stuck on because Python 2.7 still doesn't compile 
on VS2010.  :(

Kind of makes you think...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Retrieving the full command line

2013-01-24 Thread Tim Golden

On 24/01/2013 20:01, Oscar Benjamin wrote:

On 24 January 2013 17:13, Tim Golden  wrote:

A package-based module run via -m (python -m package.module) works
as described (including the implicit __main__ module, my
primary use-case).


Does it work in the "python -m package.module" case? It looks to me as
if the code below will run "python -m package" instead. I think you
need to split the module name out of sys.argv[0] and put that into the
command line as well.


Good catch. Unless I am, once again, mistaken, I can't see any way
of recreating a dotted module path which is running as a main module
without the somewhat fragile expedient of walking back up the
filepath and hoping that nothing strange has happened to the imports
on the way down? (pywin32: I'm looking at you!)

And we haven't even touched on zipped archives or other invented
loaders (pulling modules from a database or direct from the internet).

I think, though, that the point which with I started this thread is
still valid: that to reconstruct the command line with which Python
was started, you need an increasingly awkward set of conditions and
checks. As opposed to asking the interpreter: please give me the command
line which started you.

How common that particular requirement actually is, I couldn't say.
But the two cases which clearly could use it are: the reloader
setup we've been discussing here; and the apply-new-version-and-restart
which I'm hoping to use in another setup at work.

Thanks for all the help and input on this, Oscar

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


Dict comp help

2013-01-24 Thread Joseph L. Casale
Hi,
Slightly different take on an old problem, I have a list of dicts, I need to 
build one dict
from this based on two values from each dict in the list. Each of the dicts in 
the list have
similar key names, but values of course differ.


[{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 'ff'}]


{ 'xx': 'zz', 'dd': 'ff'}


Anyone have insight on how to pull this off?


Thanks!
jlc



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


Re: Dict comp help

2013-01-24 Thread Dave Angel

On 01/24/2013 03:58 PM, Joseph L. Casale wrote:

Hi,
Slightly different take on an old problem, I have a list of dicts, I need to 
build one dict
from this based on two values from each dict in the list. Each of the dicts in 
the list have
similar key names, but values of course differ.


[{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 'ff'}]


{ 'xx': 'zz', 'dd': 'ff'}


Anyone have insight on how to pull this off?



Not till you tell us what the pattern is supposed to be.  I can see how 
you might want xx:dd, yy:ee, zz:ffbut have no idea what the intended 
connection is between the source dicts and the result.




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


Re: Dict comp help

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 20:58, Joseph L. Casale  wrote:
> Hi,
> Slightly different take on an old problem, I have a list of dicts, I need to 
> build one dict
> from this based on two values from each dict in the list. Each of the dicts 
> in the list have
> similar key names, but values of course differ.
>
>
> [{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
>
>
> { 'xx': 'zz', 'dd': 'ff'}
>
>
> Anyone have insight on how to pull this off?
>

Your specification is not exactly clear about how to handle all of the
different cases or what you really want but how about:

>>> l = [{'a': 'xx', 'b': 'yy', 'c': 'zz'}, {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
>>> dict(d.values()[:2] for d in l)
{'xx': 'zz', 'dd': 'ff'}


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread llanitedave
On Thursday, January 24, 2013 7:54:55 AM UTC-8, rusi wrote:

> 
> [I personally use emacs. It would be sadistic to make that into a
> 
> recommendation]

Lol!  That's just too true.  It's also true for Eclipse, which I use very 
comfortably on Windows 7, but has proven to be a nightmare to set up on Ubuntu.

On Linux, I've tried several, but always keep coming back to Geany.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Tetsuya

On 01/24/2013 04:51 PM, John Gordon wrote:

In  Sharwan Joram 
 writes:


use vim.


He said he wanted autocomplete.  Does Vim have that?



Vim has everything, you just need a bunch of plugins.
I code mainly in python and django, and I use these plugins (among others):

powerline (status bar indicating git branch, etc..)
syntastic (support for pep8, flake8, pyflakes, etc..)
ctrlp (fuzzy search for filenames)
jedi (*awesome* python smart autocompletion)
tagbar (support for ctags, tags in a side window, jump around, etc)
fugitive (git with vim commands, very useful)
nerdcommenter (smart comment management)
nerdtree (filesystem management, tree of files, etc)
snipmate (snippets and autoexpanding of boilerplates)
gundo (undo management - vim has a smarter-than-others undo system)
supertab (autocomplete everything with TAB, smartly depending on 
language and context).


Is this enough? :-)
I can continue, but I think that, just to start, is enough. Vim wins.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dict comp help

2013-01-24 Thread Peter Otten
Joseph L. Casale wrote:

> Slightly different take on an old problem, I have a list of dicts, I need
> to build one dict from this based on two values from each dict in the
> list. Each of the dicts in the list have similar key names, but values of
> course differ.
> 
> 
> [{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
> 
> 
> { 'xx': 'zz', 'dd': 'ff'}
> 
> 
> Anyone have insight on how to pull this off?

>>> data = [{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 
'ff'}]
>>> {d["a"]: d["c"] for d in data}
{'xx': 'zz', 'dd': 'ff'}


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Kayode Odeyemi
Simply use Netbeans

On Thu, Jan 24, 2013 at 10:09 PM, llanitedave wrote:

> On Thursday, January 24, 2013 7:54:55 AM UTC-8, rusi wrote:
>
> >
> > [I personally use emacs. It would be sadistic to make that into a
> >
> > recommendation]
>
> Lol!  That's just too true.  It's also true for Eclipse, which I use very
> comfortably on Windows 7, but has proven to be a nightmare to set up on
> Ubuntu.
>
> On Linux, I've tried several, but always keep coming back to Geany.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Odeyemi 'Kayode O.
http://ng.linkedin.com/in/kayodeodeyemi. t: @charyorde blog:
http://sinati.com/tree/java-cheat-sheet
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dict comp help

2013-01-24 Thread Leonard, Arah
> Hi,
> Slightly different take on an old problem, I have a list of dicts, I need to 
> build one dict from this based on two values from each dict in the list. Each 
> of the dicts in the list have similar key names, but values of course differ.
> 
> 
> [{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
> 
> 
> { 'xx': 'zz', 'dd': 'ff'}
> 
> 
> Anyone have insight on how to pull this off?
> 
> 
> Thanks!
> jlc
> 

listy = [{'a':'xx', 'b':'yy', 'c':'zz'}, {'a':'dd', 'b':'ee','c':'ff'}]
kryten = {}
keys = []
for l in listy:
for key in l.keys():
if key not in keys: keys.append(key)
for key in keys:
kryten[key] = ''
for l in listy:
kryten[key] += l.has_key(key) and l[key] or ''
print kryten
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dict comp help

2013-01-24 Thread Rob Day
On 24 January 2013 21:11, Oscar Benjamin  wrote:
 l = [{'a': 'xx', 'b': 'yy', 'c': 'zz'}, {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
 dict(d.values()[:2] for d in l)
> {'xx': 'zz', 'dd': 'ff'}

Python doesn't guarantee any ordering of items in a dictionary; {'a':
'xx', 'b': 'yy', 'c': 'zz'}.values()[:2] may not return ['xx', 'zz']
in different Python implementations or future versions (though it
seems to work consistently in CPython 2.7). See
http://docs.python.org/2/library/stdtypes.html#dict.items.

--
Robert K. Day
[email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Dict comp help

2013-01-24 Thread Joseph L. Casale
> >>> data = [{'a': 'xx', 'b': 'yy', 'c': 'zz'},  {'a': 'dd', 'b': 'ee', 'c': 
> >>> 'ff'}] 
> >>> {d["a"]: d["c"] for d in data}
> {'xx': 'zz', 'dd': 'ff'}


Priceless,
That is exactly what I needed, for which I certainly over complicated!


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


Re: The best, friendly and easy use Python Editor.

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 7:25 AM, Tim Chase
 wrote:
> On 01/24/13 13:34, Leonard, Arah wrote:
>>>
>>> All true (especially the holy wars bit!). OP didn't (as far as
>>> I can see) even say which OS he is using. Anyway, my suggestion
>>> is generally that people use the editor with which they are
>>> already comfortable.
>>
>>
>> Sound advice.  [snip] Whatever works is what works. It's just a
>> text file after all.
>
>
> So even "ed" or "edlin" or even "cat" would do ;-)

Definitely. Especially if your edlin syntax highlights Python.

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


Re: using split for a string : error

2013-01-24 Thread Oscar Benjamin
On 24 January 2013 11:35, Chris Angelico  wrote:
>
> It's usually fine to have int() complain about any non-numerics in the
> string, but I must confess, I do sometimes yearn for atoi() semantics:
> atoi("123asd") == 123, and atoi("qqq") == 0. I've not seen a
> convenient Python function for doing that. Usually it involves
> manually getting the digits off the front. All I want is to suppress
> the error on finding a non-digit. Oh well.
>

I'm interested to know what the situations are where you want the
behaviour of atoi().

Personally, I consider the int() function too permissive because of
its behaviour in truncating non-integer numeric types. But then that's
because I'm always paranoid that the values of my precious numbers are
being changed without my knowledge. From my vantage point I really
can't see why the ambiguous behaviour of atoi() would actually be
desired by anyone (unless they were stuck using a language that made
string manipulation generally a bit awkward).


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


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 11:20 AM, Steven D'Aprano
 wrote:
> Chris Angelico wrote:
>
>> It's usually fine to have int() complain about any non-numerics in the
>> string, but I must confess, I do sometimes yearn for atoi() semantics:
>> atoi("123asd") == 123, and atoi("qqq") == 0. I've not seen a
>> convenient Python function for doing that. Usually it involves
>> manually getting the digits off the front. All I want is to suppress
>> the error on finding a non-digit. Oh well.
>
> It's easy enough to write your own. All you need do is decide what you
> mean by "suppress the error on finding a non-digit".
>
> Should atoi("123xyz456") return 123 or 123456?
>
> Should atoi("xyz123") return 0 or 123?
>
> And here's a good one:
>
> Should atoi("1OOl") return 1, 100, or 1001?

123, 0, and 1. That's standard atoi semantics.

> That last is a serious suggestion by the way. There are still many people
> who do not distinguish between 1 and l or 0 and O.

Sure. But I'm not trying to cater to people who get it wrong; that's a
job for a DWIM.

> def atoi(s):
> from unicodedata import digit
> i = 0
> for c in s:
> i *= 10
> i += digit(c, 0)
> return i
>
> Variations that stop on the first non-digit, instead of treating them as
> zero, are not much more difficult.

And yes, I'm fully aware that I can roll my own. Here's a shorter
version (ASCII digits only, feel free to expand to Unicode), not
necessarily better:

def atoi(s):
return int("0"+s[:-len(s.lstrip("0123456789"))])

It just seems silly that this should have to be done separately, when
it's really just a tweak to the usual string-to-int conversion: when
you come to a non-digit, take one of three options (throw error, skip,
or terminate).

Anyway, not a big deal.

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


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 12:03 PM, Oscar Benjamin
 wrote:
> On 24 January 2013 11:35, Chris Angelico  wrote:
>>
>> It's usually fine to have int() complain about any non-numerics in the
>> string, but I must confess, I do sometimes yearn for atoi() semantics:
>> atoi("123asd") == 123, and atoi("qqq") == 0. I've not seen a
>> convenient Python function for doing that. Usually it involves
>> manually getting the digits off the front. All I want is to suppress
>> the error on finding a non-digit. Oh well.
>>
>
> I'm interested to know what the situations are where you want the
> behaviour of atoi().

It simplifies operations on strings that contain numbers. For
instance, here's a problem from yesterday. I have a set of files (MIDI
files of The Rose of Persia) which have been sloppily numbered:

Rose_1.mid
Rose_10.mid
Rose_11.mid
Rose_12.mid
Rose_13.mid
Rose_14.mid
Rose_15.mid
Rose_16.mid
Rose_17.mid
Rose_18.mid
Rose_19.mid
Rose_2.mid
Rose_20.mid
Rose_21.mid
Rose_22.mid
Rose_23.mid
Rose_24.mid
Rose_3.mid
Rose_4.mid
Rose_5.mid
Rose_6.mid
Rose_7.mid
Rose_8.mid
Rose_9.mid
Rose_Int.mid

They're not in order. The one marked "Int" is the Introduction and
should be first; then Rose_1 ... Rose_9, then Rose_10 ... Rose_24. In
fact, the correct sort order is exactly:

atoi(filename[5:])

Most of the time, it makes no difference. Python's int() will do
exactly what atoi() does. It's only in the unusual case where they
even differ.

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


Re: using split for a string : error

2013-01-24 Thread Oscar Benjamin
On 25 January 2013 01:11, Chris Angelico  wrote:
> On Fri, Jan 25, 2013 at 12:03 PM, Oscar Benjamin
>  wrote:
>> On 24 January 2013 11:35, Chris Angelico  wrote:
>>>
>>> It's usually fine to have int() complain about any non-numerics in the
>>> string, but I must confess, I do sometimes yearn for atoi() semantics:
>>> atoi("123asd") == 123, and atoi("qqq") == 0. I've not seen a
>>> convenient Python function for doing that. Usually it involves
>>> manually getting the digits off the front. All I want is to suppress
>>> the error on finding a non-digit. Oh well.
>>>
>>
>> I'm interested to know what the situations are where you want the
>> behaviour of atoi().
>
> It simplifies operations on strings that contain numbers. For
> instance, here's a problem from yesterday. I have a set of files (MIDI
> files of The Rose of Persia) which have been sloppily numbered:
>
> Rose_1.mid
> Rose_10.mid
> Rose_11.mid
> Rose_12.mid
> Rose_13.mid
> Rose_14.mid
> Rose_15.mid
> Rose_16.mid
> Rose_17.mid
> Rose_18.mid
> Rose_19.mid
> Rose_2.mid
> Rose_20.mid
> Rose_21.mid
> Rose_22.mid
> Rose_23.mid
> Rose_24.mid
> Rose_3.mid
> Rose_4.mid
> Rose_5.mid
> Rose_6.mid
> Rose_7.mid
> Rose_8.mid
> Rose_9.mid
> Rose_Int.mid
>
> They're not in order. The one marked "Int" is the Introduction and
> should be first; then Rose_1 ... Rose_9, then Rose_10 ... Rose_24. In
> fact, the correct sort order is exactly:
>
> atoi(filename[5:])

I have solved similar situations with
sorted(filenames, key=lambda s: (len(s), s))
which is better than lexicographical ordering for sorting integer
strings. It gets the _Int file wrong in this case (but I consider it
luck that atoi does what you want for that file).


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


Need Pattern For Logging Into A Website

2013-01-24 Thread Tim Daneliuk

I need to write a Python script to do the following:

  - Connect to a URL and accept any certificate - self-signed or authoritative
  - Provide login name/password credentials
  - Fill in some presented fields
  - Hit a "Submit" button

Why?  Because I don't want to have to start a browser and do this
interactively every time I authenticate with a particular server.
I want to do this at the command line with no interactive intervention.

I know Python pretty well.  I don't quite know how to do this and
was hoping someone had a simple pattern they could share for
doing this.

TIA,
--

Tim Daneliuk [email protected]
PGP Key: http://www.tundraware.com/PGP/

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


Re: using split for a string : error

2013-01-24 Thread Chris Angelico
On Fri, Jan 25, 2013 at 12:33 PM, Oscar Benjamin
 wrote:
> I have solved similar situations with
> sorted(filenames, key=lambda s: (len(s), s))
> which is better than lexicographical ordering for sorting integer
> strings. It gets the _Int file wrong in this case (but I consider it
> luck that atoi does what you want for that file).

Yep. Now give me an easy way to rename them all so that the glob *.mid
will produce them in the right order. BTW, there's no guarantee that
the files have no gaps; some other directories have things like
Iol_08_11.mid being followed by Iol_12.mid - I'd rather not renumber
them based on their indices in the final list.

But like I said, it's an unusual case.

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


Inherent asyncore.dispatcher_with_send exception

2013-01-24 Thread nobody
Hi,

I have a class ClientHandler(asyncore.dispatcher_with_send), it was running 
fine without calling any of my own classes. But it got following exception when 
I called my own class GetMyResponse inside the def handle_read(self). Not sure 
why it causes disturbance to asyncore.dispatcher_with_send __init__ when 
calling an extra class? Appreciate any clues and tips.

class GetMyResponse:
   def __init__(self, message):
  

class ClientHandler(asyncore.dispatcher_with_send):
def handle_read(self):
  
   handleResponse = GetMyResponse(data)
   self.send(handleResponse.getResponse())


error: uncaptured python exception, closing channel <__main__.ClientHandler 
connected 127.0.0.1:42383 at 0x7f3b638b6758> (:__init__() takes exactly 4 arguments (3 given) 
[/usr/lib64/python2.6/asyncore.py|read|78] 
[/usr/lib64/python2.6/asyncore.py|handle_read_event|428]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the font size of anOptionMenu widget

2013-01-24 Thread Rick Johnson

Ignoring the fact that the Tkinter.Optionmenu is by far the worst widget in the 
toolkit, not to mention that the whole idea of "Tkinter X_Variables" was a poor 
attempt to reuse code at the expense destroying the simple and  intuitive 
interface of "get" and "set"; here is your answer:

## START CODE ##
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
optMenu = OptionMenu(master, variable, "one", "two", "three")
optMenu.pack()
# Get the menu
menu = optMenu.nametowidget(optMenu.menuname)
menu.configure(font=('Impact', 30))
mainloop()
## END CODE ##

PS: You could have probably intuited the answer yourself if you used the dir() 
function on "w". Of course you probably would have expected the Optionmenu to 
have a reference to the submenu. It does, however not a direct reference. 

PPS: Or, if you prefer information overload you could have called "help(w)".


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


MySQL - "create table" creates malfunctioning tables

2013-01-24 Thread F.R.
The other day, for unfathomable reasons, I lost control over tables 
which I create. There was no concurrent change of anything on the 
machine, such as an update. So I have no suspect. Does the following 
action log suggest any recommendation to experienced SQL programmers?



1. A table:

mysql> select * from  expenses;
+++---+--++-+---+
| id | date   | place | stuff| amount | category| flags |
+++---+--++-+---+
| 38 | 2013-01-15 | ATT   | Sim card |  25.00 | Visa credit |   |
+++---+--++-+---+
1 row in set (0.00 sec)

2. I want to delete everything:

mysql> delete from expenses;

3. Nothing happens for about one minute. Then this:

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
mysql>

4. I want to delete the table:

mysql> drop table expenses;

5. Nothing happens indefinitely. I have to hit Ctrl-C

^CCtrl-C -- sending "KILL QUERY 167" to server ...
Ctrl-C -- query aborted.
ERROR 1317 (70100): Query execution was interrupted
mysql>

6. I expect to find "expenses.frm", "expenses.MYD" and "expenses.MYI".

I find only the format file:

root@hatchbox-one:/home/fr# find / -name 'expenses.*' -ls
1055950   12 -rw-rw   1 mysqlmysql8783 Jan 25 01:51 
/var/lib/mysql/fr/expenses.frm

root@hatchbox-one:/home/fr#

7. All the tables I regularly work with have a "frm", a "MYD" and a 
"MYI" file in the directory "/var/lib/mysql/fr/".


8. I'd like to drop the table "expenses", plus a number of other tables 
I created, hoping to hit it right by chance. I didn't and now I have a 
bunch of unusable tables which I can't drop and I don't know where their 
files are hiding. If I did, I could remove them.




Grateful for any hint, comment, suggestion

Frederic



Dell E6500
Ubuntu 10.04 LTS
Python 2.7.3 (default, Aug  1 2012, 05:16:07) \n[GCC 4.6.3
MySQL (Can't find a version number)
Server version: 5.5.28-0ubuntu0.12.04.3 (Ubuntu)

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


Re: MySQL - "create table" creates malfunctioning tables

2013-01-24 Thread Walter Hurry
On Fri, 25 Jan 2013 07:55:06 +0100, F.R. wrote:

> The other day, for unfathomable reasons, I lost control over tables
> which I create. There was no concurrent change of anything on the
> machine, such as an update. So I have no suspect. Does the following
> action log suggest any recommendation to experienced SQL programmers?
> 
This is a Python list.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >