Re: global variable not working inside function. Increment

2013-05-13 Thread Andreas Perstinger
"feather.duster.kung.fu"  wrote:
>I'm just learning Python and NONE of the tutorials I read said
>anything about that . In fact they all say a global can be called from
>inside a Function. If possible please contact the ppl that write these
>things.

Well, we don't know which tutorials you read.
So why don't you tell them yourself?

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


Re: Illegal seek error with seek() and os.lseek()

2013-05-14 Thread Andreas Perstinger

On 14.05.2013 21:00, krishna2pra...@gmail.com wrote:

  # first, open the file as a plain binary
  try:
  self.file = open(/dev/relpcfpga, "r+b", buffering=0)


Aren't you missing the quotes for "/dev/relpcfpga"?


The method seek() complains "OSError: [Errno 29] Illegal seek"
The device relpcfpga is a char device.


Are you sure that your device is seekable?
Try

f = open("/dev/relpcfpga", "r+b", buffering=0)
print(f.seekable())

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


Re: PEP 378: Format Specifier for Thousands Separator

2013-05-24 Thread Andreas Perstinger

On 24.05.2013 17:25, Carlos Nepomuceno wrote:



Date: Thu, 23 May 2013 19:29:14 -0700
Subject: Re: PEP 378: Format Specifier for Thousands Separator
From: dihedral88...@gmail.com
[some typical dihedral stuff]


I'm sorry but I don't understand your question.


Don't worry. I guess most people on this list don't understand it either.

It looks like dihedral is a bot although nobody knows for sure. Search 
for some other posts from him/her/it in the archive and form your own 
opinion.


IMHO you can simply ignore him/her/it.

Bye, Andreas

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


Re: netcdF4 variables

2013-06-01 Thread Andreas Perstinger

On 01.06.2013 05:30, Sudheer Joseph wrote:

some hing like a list
xx=nc,variables[:]
should get me all variable names with out other surrounding stuff??

In [4]: ncf.variables
Out[4]: OrderedDict([(u'LON', ),

[SNIP]

It looks like "variables" is an OrderedDict. Thus

>>> ncf.variables.keys()

should return a view (or list, depending on your python version) of all 
keys, i.e. all variable names.


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


Re: Source code as text/plain

2013-06-04 Thread Andreas Perstinger

On 04.06.2013 00:34, Carlos Nepomuceno wrote:



Date: Mon, 3 Jun 2013 09:06:46 +1000
From: c...@zip.com.au
To: c...@rebertia.com

[...]

http://hg.python.org/cpython/raw-file/tip/Lib/string.py


What's the 'tip' tag?   


http://hg.python.org/cpython/help/tip

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


Re: Changing filenames from Greeklish => Greek (subprocess complain)

2013-06-09 Thread Andreas Perstinger

On 09.06.2013 11:38, Νικόλαος Κούρας wrote:

s = 'α'
s = s.encode('iso-8859-7').decode('utf-8')
print( s )

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 0: 
unexpected end of data

Why this error? because 'a' ordinal value > 127 ?


>>> s = 'α'
>>> s.encode('iso-8859-7')
b'\xe1'
>>> bin(0xe1)
'0b1111'

Now look at the table on https://en.wikipedia.org/wiki/UTF-8#Description 
to find out how many bytes a UTF-8 decoder expects when it reads that value.


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


Re: Changing filenames from Greeklish => Greek (subprocess complain)

2013-06-10 Thread Andreas Perstinger

On 10.06.2013 09:10, nagia.rets...@gmail.com wrote:

Τη Κυριακή, 9 Ιουνίου 2013 3:31:44 μ.μ. UTC+3, ο χρήστης Steven D'Aprano έγραψε:


py> c = 'α'
py> ord(c)
945


The number 945 is the characters 'α' ordinal value in the unicode charset 
correct?


Yes, the unicode character set is just a big list of characters. The 
946th character in that list (starting from 0) happens to be 'α'.



The command in the python interactive session to show me how many bytes
this character will take upon encoding to utf-8 is:


s = 'α'
s.encode('utf-8')

b'\xce\xb1'

I see that the encoding of this char takes 2 bytes. But why two exactly?


That's how the encoding is designed. Haven't you read the wikipedia 
article which was already mentioned several times?



How do i calculate how many bits are needed to store this char into bytes?


You need to understand how UTF-8 works. Read the wikipedia article.


Trying to to the same here but it gave me no bytes back.


s = 'a'
s.encode('utf-8')

b'a'


The encode method returns a byte object. It's length will tell you how 
many bytes there are:


>>> len(b'a')
1
>>> len(b'\xce\xb1')
2

The python interpreter will represent all values below 256 as ASCII 
characters if they are printable:


>>> ord(b'a')
97
>>> hex(97)
'0x61'
>>> b'\x61' == b'a'
True

The Python designers have decided to use b'a' instead of b'\x61'.


py> c.encode('utf-8')
b'\xce\xb1'


2 bytes here. why 2?


Same as your first question.


py> c.encode('utf-16be')
b'\x03\xb1'


2 byets here also. but why 3 different bytes? the ordinal value of
char 'a' is the same in unicode. the encodign system just takes the
ordinal value end encode, but sinc eit uses 2 bytes should these 2 bytes
be the same?


'utf-16be' is a different encoding scheme, thus it uses other rules to 
determine how each character is translated into a byte sequence.



py> c.encode('iso-8859-7')
b'\xe1'


And also does '\x' means that the value is being respresented in hex way?
and when i bin(6) i see '0b101'

I should expect to see 8 bits of 1s and 0's. what the 'b' is tryign to say?

'\x' is an escape sequence and means that the following two characters 
should be interpreted as a number in hexadecimal notation (see also the 
table of allowed escape sequences: 
http://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals 
).


'0b' tells you that the number is printed in binary notation.
Leading zeros are usually discarded when a number is printed:
>>> bin(70)
'0b1000110'
>>> 0b100110 == 0b00100110
True
>>> 0b100110 == 0b00100110
True

It's the same with decimal notation. You wouldn't say 00123 is different 
from 123, would you?


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


Re: Changing filenames from Greeklish => Greek (subprocess complain)

2013-06-10 Thread Andreas Perstinger

On 10.06.2013 11:59, Νικόλαος Κούρας wrote:

 s = 'α'
 s.encode('utf-8')
> b'\xce\xb1'


'b' stands for binary right?


No, here it stands for bytes:
http://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals


  b'\xce\xb1' = we are looking at a byte in a hexadecimal format?


No, b'\xce\xb1' represents a byte object containing 2 bytes.
Yes, each byte is represented in hexadecimal format.


if yes how could we see it in binary and decimal represenation?


>>> s = b'\xce\xb1'
>>> s[0]
206
>>> bin(s[0])
'0b11001110'
>>> s[1]
177
>>> bin(s[1])
'0b10110001'

A byte object is a sequence of bytes (= integer values) and support 
indexing.

http://docs.python.org/3/library/stdtypes.html#bytes


Since 2^8 = 256, utf-8 should store the first 256 chars of unicode
charset using 1 byte.

Also Since 2^16 = 65535, utf-8 should store the first 65535 chars of
unicode charset using 2 bytes and so on.

But i know that this is not the case. But i dont understand why.


Because your method doesn't work.
If you use all possible 256 bit-combinations to represent a valid 
character, how do you decide where to stop in a sequence of bytes?



 s = 'a'
 s.encode('utf-8')
> b'a'
utf-8 takes ASCII as it is, as 1 byte. They are the same


EBCDIC and ASCII and Unicode are charactet sets, correct?

iso-8859-1, iso-8859-7, utf-8, utf-16, utf-32 and so on are encoding methods, 
right?



Look at http://www.unicode.org/glossary/ for an explanation of all the 
terms.


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


OT: e-mail reply to old/archived message (was Re: Encoding questions (continuation))

2013-06-11 Thread Andreas Perstinger

On 10.06.2013 15:56, Νικόλαος Κούρας wrote:

Τη Δευτέρα, 10 Ιουνίου 2013 2:41:07 μ.μ. UTC+3, ο χρήστης Steven
D'Aprano έγραψε:

On Mon, 10 Jun 2013 14:13:00 +0300, Νικόλαος Κούρας wrote:

ps. i tried to post a reply to the thread i opend via thunderbird
mail client, but not as a reply to somne other reply but as  new
mail send to python list. because of that a new thread will be
opened. How can i tell thunderbird to reply to the original
thread and not start a new one?

By replying to an email in that thread.


Yes thats obvious. What is not obvious is how you reply back to a
thread by giving extra info when you are not replying to a mail formt
tha thread or when you ahve deleted the reply for a member

sending the mail to python-list@python.org will just open anew
subject intead of replyign to an opened thread.


You would need to find out the Message-Id of the post you want to reply 
to and then add manually the In-Reply-To and References headers to your 
e-mail using that Id.


It's probably easier to just use the web interface at Gmane.

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


Re: Receing a form variable as a list instead of as a string

2013-06-11 Thread Andreas Perstinger

On 11.06.2013 12:38, Νικόλαος Κούρας wrote:

but page is a form variable coming from a previous sumbitted form
why the error says 'page' is a list?


RTFM:
"If the submitted form data contains more than one field with the same 
name, the object retrieved by form[key] is not a FieldStorage or 
MiniFieldStorage instance but a list of such instances. Similarly, in 
this situation, form.getvalue(key) would return a list of strings."

http://docs.python.org/3.3/library/cgi.html#using-the-cgi-module

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


Re: OT: e-mail reply to old/archived message

2013-06-11 Thread Andreas Perstinger

On 11.06.2013 22:14, Νικόλαος Κούρας wrote:

Τη Τρίτη, 11 Ιουνίου 2013 2:21:50 μ.μ. UTC+3, ο χρήστης Andreas Perstinger 
έγραψε:

> sending the mail to python-list@python.org will just open anew
> subject intead of replyign to an opened thread.



You would need to find out the Message-Id of the post you want to reply
to and then add manually the In-Reply-To and References headers to your
e-mail using that Id.


You mean by viewing for example your post as 'view original source', finding
In-Reply-To: <71d585e6-bb98-47b7-9a45-7cde1ba0c...@googlegroups.com>


No, the In-Reply-To header in *my* post is the post *I* have replied to, 
i.e. that's the Message-ID of *your* earlier post.




and then compose a new mail as:

to: Andreas Perstinger 
cc: In-Reply-To: <71d585e6-bb98-47b7-9a45-7cde1ba0c...@googlegroups.com>

is this the way Andrea?


No, the headers would be:
To: python-list@python.org
In-Reply-To: <51b7084e.9040...@gmail.com>
References:  
<51b5bb53$0$29997$c3e8da3$54964...@news.astraweb.com> 
<71d585e6-bb98-47b7-9a45-7cde1ba0c...@googlegroups.com> 
<51b7084e.9040...@gmail.com>


Basically, you should follow RFC 2822 and RFC 1036 if you don't mess up 
with message threading.


You also need to know that you can't add these headers manually in 
Thunderbird out of the box. You would need to edit the configuration.


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


Re: A certainl part of an if() structure never gets executed.

2013-06-12 Thread Andreas Perstinger

[Please trim your replies to the relevant parts.]

On 12.06.2013 10:54, Νικόλαος Κούρας wrote:

But when it comes to select '==' from month instead of
'==' to be submitted a zero gets submitted and i think the
problem is the way i'm filling up months into the drop down menu which is:


for i, month in enumerate(months):
  print(' %s ' % (i, month) )


the if case does not execute because of the way it checks for None entry
which is: elif '=' not in year:

but if enumerate yields 0 instead of '==' then elif '=' not in
year of course fails.


How often do we need to tell you that you should reread your posts 
before sending them?
You start with telling us you have problems with "month" and then show 
us code regarding "year"



So, i must tell:

for i, month in enumerate(months):
  print(' %s ' % (i, month) )

to somehow return '==' instead of 0 but don't know how.


As with most of your problems you are barking up the wrong tree.
Why not use the actual value you get from the form to check whether you 
have a valid month?

Do you understand why "0" is submitted instead of "=="?

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


Re: Problem creating a regular expression to parse open-iscsi, iscsiadm output (help?)

2013-06-13 Thread Andreas Perstinger

On 13.06.2013 02:59, rice.cr...@gmail.com wrote:

I am parsing the output of an open-iscsi command that contains
severalblocks of data for each data set. Each block has the format:

[SNIP]

I tried using \s* to swallow the whitespace between the to iSCSI
lines. No joy... However [\s\S]*? allows the regex to succeed. But that
seems to me to be overkill (I am not trying to skip lines of text here.)
Also note that I am using \ + to catch spaces between the words. On the
two problem lines, using \s+ between the label words fails.


Changing

 # Connection state
 iSCSI\ +Connection\ +State:\s+(?P\w+\s*\w*)
 [\s\S]*?<< without this the regex fails
 # Session state
 iSCSI\ +Session\ +State:\s+(?P\w+)


to
# Connection state
iSCSI\s+Connection\s+State:\s+(?P\w+\s*\w*)\s*
# Session state
iSCSI\s+Session\s+State:\s+(?P\w+)

gives me

>>> # 'test' is the example string
>>> myDetails = [ m.groupdict() for m in regex.finditer(test)]
>>> print myDetails
[{'initiatorIP': '221.128.52.214', 'connState': 'LOGGED IN', 'SID': 
'154', 'ipaddr': '221.128.52.224', 'initiatorName': 
'iqn.1996-04.de.suse:01:7c9741b545b5', 'sessionState': 'LOGGED_IN', 
'iqn': 'iqn.1992-04.com.emc:vplex-8460319f-0007', 
'tag': '7', 'port': '3260'}]


for your example (same for the original regex).
It looks like it works (Python 2.7.3) and there is something else 
breaking the regex.


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


Re: Wrong website loaded when other requested

2013-06-13 Thread Andreas Perstinger

On 13.06.2013 16:23, Νικόλαος Κούρας wrote:

Please suggest something of why this happnes.


That's not a Python problem.

BTW both scripts at
http://superhost.gr/~dauwin/metrites.py
and at
http://superhost.gr/~dauwin/cgi-bin/metrites.py
show the world the passwords to your databases in plain text.

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


Re: Wrong website loaded when other requested

2013-06-13 Thread Andreas Perstinger

On 13.06.2013 20:10, Nick the Gr33k wrote:
[nothing new]

Could you please stop spamming the whole internet with your problems.
Not only that you've posted two similar offtopic messages within only 6 
minutes to this list, you've also crossposted to alt.os.linux (where it 
is offtopic too) and to the forum at devshed.com (at least you've found 
the right subforum there).


Thank you very much!

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


Re: Having a hard time to 'get' bing api search results

2013-06-13 Thread Andreas Perstinger

On 14.06.2013 03:00, Yves S. Garret wrote:

Thanks again Kevin.  I'm deviating from the original thread,
but I've got another issue.  When I try to load the json file
and then parse it, this is the error that I get:
http://bin.cakephp.org/view/1329549559


1) Please don't top post. Put your answer after the parts you are 
replying to.


2) Is Kevin sending his e-mails only to you? I don't get them and they 
aren't in the mailing list archive either.


3) Please copy the traceback you get into your message. Otherwise you 
will reduce the amount of people who are willing to help you because not 
everyone likes to go to an external website just to read them.

So here's it:

>>> import json
>>> import pprint
>>> json_data = open('temp.json')
>>> data = json.load(json_data)
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/json/__init__.py", line 290, in load
**kw)
  File "/usr/local/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
  File "/usr/local/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 2 column 1 (char 2)

4) The error message tells you that json.load() can't parse your file 
due to an error at the beginning of line 2. So can you please post the 
first lines of your file?


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


Re: Having a hard time to 'get' bing api search results

2013-06-14 Thread Andreas Perstinger

On 14.06.2013 20:19, Yves S. Garret wrote:

This is the error that I'm getting right now.

import json
from pprint import pprint
path = '/home/azureuser/temp.json'
with open(path) as data_file:

...   data = json.load(data_file)
...
Traceback (most recent call last):
   File "", line 2, in 
   File "/usr/local/lib/python2.7/json/__init__.py", line 290, in load
 **kw)
   File "/usr/local/lib/python2.7/json/__init__.py", line 338, in loads
 return _default_decoder.decode(s)
   File "/usr/local/lib/python2.7/json/decoder.py", line 365, in decode
 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
   File "/usr/local/lib/python2.7/json/decoder.py", line 381, in raw_decode
 obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 2 column 1 (char 2)

Thanks for your inputs Andreas.

Also, this is my JSON file, I'll post again.  Since it's going to be
messy, I'll include a link as well (users can decide what they prefer
to read).
http://bin.cakephp.org/view/1050217914


Ok, I've just copied the text from the site into a file and there is no 
problem loading the file.


You could try the same.

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


Re: Pattern Search Regular Expression

2013-06-15 Thread Andreas Perstinger
subhabangal...@gmail.com wrote:
>I know this solution but I want to have Regular Expression option.
>Just learning.

http://mattgemmell.com/2008/12/08/what-have-you-tried/

Just spell out what you want:
A word at the beginning, followed by any text, followed by a word at
the end.
Now look up the basic regex metacharacters and try to come up with a
solution (Hint: you will need groups)

http://docs.python.org/3/howto/regex.html#regex-howto
http://docs.python.org/3/library/re.html#regular-expression-syntax

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


Re: Don't feed the troll...

2013-06-15 Thread Andreas Perstinger
Nick the Gr33k  wrote:
>You are spamming my thread.

Well, you don't own this thread. In fact nobody owns it. This is a
public forum and thus anybody can answer to any post as he likes.

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


OT: C vs Python terminology (was: A certainl part of an if() structure never gets executed)

2013-06-16 Thread Andreas Perstinger

On 16.06.2013 08:32, Denis McMahon wrote:

C:

int a, b;
b = 6;
a = b;

In C, this places the numeric value 6 into the memory location identified
by the variable "b",


so far so good.


then copies the value from the location pointed to by "b" into the
location pointed to by "a".


Wrong. Neither "a" nor "b" are pointers, thus they don't point to a 
memory location.

This part should be written as
"then copies the value at the location identified by "b" to the location 
identified by "a".



b is a pointer to a memory location containing the value 6

> a is a pointer to another memory location also containing the value 6

Again, neither "a" nor "b" are pointers.
"b" is the name of a memory location containing the integer value 6.
"a" is the name of another memory location containing the integer value 6.


Python:

b = 6
a = b

In Python, this first puts the value 6 in in a memory location and points
"b" at that memory location, then makes "a" point to the same memory
location as "b" points to.

b is a pointer to a memory location containing the value 6
a is a pointer to the same memory location


I wouldn't use the term "pointer" in context with Python. Using the 
terms from the language reference I would write that as
"In Python, this first creates an integer object with value 6 and then 
binds the name "b" to it. Then it binds the name "a" to the same object.
Thus both "a" and "b" reference the same object, i.e. they are different 
names for the same object."


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


Re: OT: C vs Python terminology

2013-06-16 Thread Andreas Perstinger

On 16.06.2013 14:55, Dave Angel wrote:

On 06/16/2013 07:22 AM, Andreas Perstinger wrote:

On 16.06.2013 08:32, Denis McMahon wrote:

C:

^



int a, b;
b = 6;
a = b;

In C, this places the numeric value 6 into the memory location identified

^


by the variable "b",


so far so good.


then copies the value from the location pointed to by "b" into the
location pointed to by "a".


Wrong. Neither "a" nor "b" are pointers, thus they don't point to a
memory location.
This part should be written as
"then copies the value at the location identified by "b" to the location
identified by "a".


But it doesn't.  It binds b to the same object to which a is currently
bound.


Are you aware that Denis was talking about the behaviour of C in the 
above quote?



b is a pointer to a memory location containing the value 6

 > a is a pointer to another memory location also containing the value 6

Again, neither "a" nor "b" are pointers.
"b" is the name of a memory location containing the integer value 6.
"a" is the name of another memory location containing the integer value 6.



Not even close.  If you don't like the terms "bound" or "points", the
perhaps you'd be happy with "b" is the name that currently knows how to
find an int object containing 6.  That object has no name, and never
will.  And it can exist for a long time with no names directly bound to it.


Again, Denis was talking about C.

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


Re: Help me with the script? How to find items in csv file A and not in file B and vice versa

2013-06-18 Thread Andreas Perstinger
alonn...@gmail.com wrote:
>and when I run it I get an invalid syntex error and (as a true newbie
>I used a GUI)in_a_not_b is highlighted in the with open("inAnotB.csv",
>"wb") as f: 
>writer = csv.writer(f) 
>writer.writerows([item] for item in_a_not_b)
 

The syntax for the for-clause in a comprehension is

for x in something

thus you are missing the "in" keyword:

writer.writerows([item] for item in in_a_not_b)

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


Re: A few questiosn about encoding

2013-06-20 Thread Andreas Perstinger
Rick Johnson  wrote:
>
> Since we're on the subject of Unicode:
>
>One the most humorous aspects of Unicode is that it has
>encodings for Braille characters. Hmm, this presents a
>conundrum of sorts. RIDDLE ME THIS?!
>
>Since Braille is a type of "reading" for the blind by
>utilizing the sense of touch (therefore DEMANDING 3
>dimensions) and glyphs derived from Unicode are
>restrictively two dimensional, because let's face it people,
>Unicode exists in your computer, and computer screens are
>two dimensional... but you already knew that -- i think?,
>then what is the purpose of a Unicode Braille character set?
>
>That should haunt your nightmares for some time.

>From http://www.unicode.org/versions/Unicode6.2.0/ch15.pdf
"The intent of encoding the 256 Braille patterns in the Unicode
Standard is to allow input and output devices to be implemented that
can interchange Braille data without having to go through a
context-dependent conversion from semantic values to patterns, or vice
versa. In this manner, final-form documents can be exchanged and
faithfully rendered."

http://files.pef-format.org/specifications/pef-2008-1/pef-specification.html#Unicode

I wish you a pleasant sleep tonight.

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


Re: Question about mailing list rules

2013-07-12 Thread Andreas Perstinger

On 12.07.2013 01:59, Devyn Collier Johnson wrote:

Am I allowed to ask questions like "Here is my code. How can I optimize
it?" on this mailing list?


If it's written in Python, why not?

But that doesn't mean you are guaranteed to get an answer :-).

And please read http://sscce.org/ before posting your latest 10,000 line 
program :-)


Bye, Andreas

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


Re: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator

2012-07-11 Thread Andreas Perstinger
On Thu, 12 Jul 2012 10:41:52 +1000 
Simon Cropper  wrote:

> That said... with more than a passing interest in software and
> content licensing I looked at how the work was licensed. A
> none-standard license like this makes most people stop and think
> "will this be a problem if I use this in my work?" How compatible is
> your license with the main software licenses currently available?

Do you mean this license?:
http://packages.python.org/PollyReports/license.html

It's the standard license for NetBSD projects and approved by OSI:
http://www.opensource.org/licenses/bsd-license.php

and GPL-compatible:
http://www.gnu.org/licenses/license-list.html#FreeBSD

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


Re: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator

2012-07-12 Thread Andreas Perstinger
On Thu, 12 Jul 2012 16:59:06 +1000 
Chris Angelico  wrote:

> On Thu, Jul 12, 2012 at 3:35 PM, Andreas Perstinger
>  wrote:
> > Do you mean this license?:
> > http://packages.python.org/PollyReports/license.html
> >
> > It's the standard license for NetBSD projects and approved by OSI:
> > http://www.opensource.org/licenses/bsd-license.php
> >
> > and GPL-compatible:
> > http://www.gnu.org/licenses/license-list.html#FreeBSD
> 
> Can you state that on the page, perhaps? It'd mean that anyone who's
> familiar with the license can read one keyword and know what the terms
> are, rather than dig through the full text to see if it's really the
> same or not.

I'm not responsible for any of the tree pages I've mentioned.

I've just looked at the "PollyReports"-license page because I was
curious which "strange" license the original author uses. Then I noticed
it's just one of the BSD-licenses, used Wikipedia to confirm it and
searched for the two other pages to show that it isn't problematic at
all.

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


Re: Beautiful Soup Table Parsing

2012-08-09 Thread Andreas Perstinger

On 09.08.2012 01:58, Tom Russell wrote:

For instance this code below:

soup = 
BeautifulSoup(urlopen('http://online.wsj.com/mdc/public/page/2_3021-tradingdiary2.html?mod=mdc_pastcalendar'))

table = soup.find("table",{"class": "mdcTable"})
for row in table.findAll("tr"):
 for cell in row.findAll("td"):
 print cell.findAll(text=True)

brings in a list that looks like this:


[snip]


What I want to do is only be getting the data for NYSE and nothing
else so I do not know if that's possible or not. Also I want to do
something like:

If cell.contents[0] == "Advances":
 Advances = next cell or whatever??---> this part I am not sure how to do.

Can someone help point me in the right direction to get the first data
point for the Advances row? I have others I will get as well but
figure once I understand how to do this I can do the rest.


To get the header row you could do something like:

header_row = table.find(lambda tag: tag.td.string == "NYSE")

From there you can look for the next row you are interested in:

advances_row = header_row.findNextSibling(lambda tag: tag.td.string == 
"Advances")


You could also iterate through all next siblings of the header_row:

for row in header_row.findNextSiblings("tr"):
 # do something

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


Re: help me debug my "word capitalizer" script

2012-08-22 Thread Andreas Perstinger

On 22.08.2012 08:21, Santosh Kumar wrote:

with open(givenfile) as file:
 # List to store the capitalised lines.
 lines = []
 for line in file:
 # Split words by spaces.
 words = line.split(' ')


The last element in your "words" list will still have a newline 
character appended to it.

You could probably use line.split().
See also the docs:
http://docs.python.org/py3k/library/stdtypes.html#str.split


 for i, word in enumerate(words):
 if len(word.strip(punctuation)) > 3:
 # Capitalise and replace words longer than 3 (without
punctuation)
 words[i] = word.capitalize()
 # Join the capitalised words with spaces.
 lines.append(' '.join(words))


This rebuilds the line including a newline character at the end.


 # Join the capitalised lines by the line separator
 capitalised = linesep.join(lines)


Because you haven't removed the newline character from each line, 
joining them with "linesep" introduces a second newline character after 
each line.


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


Re: Python list archives double-gzipped?

2012-08-27 Thread Andreas Perstinger

On 27.08.2012 03:40, Tim Chase wrote:

So it looks like some python-list@ archiving process is double
gzip'ing the archives.  Can anybody else confirm this and get the
info the right people?


In January, "random joe" noticed the same problem[1].
I think, Anssi Saari[2] was right in saying that there is something 
wrong in the browser or server setup, because I notice the same 
behaviour with Firefox, Chromium, wget and curl.


$ ll *July*
-rw-rw-r-- 1 andreas andreas 747850 Aug 27 13:48 chromium_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 748041 Aug 27 13:41 curl_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 747850 Aug 27 13:48 firefox_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 748041 Aug  2 03:27 wget_2012-July.txt.gz

The browsers get a double gzipped file (size 747850) whereas the 
download utilities get a normal gzipped file (size 748041).


After looking at the HTTP request and response headers I've noticed that 
the browsers accept compressed data ("Accept-Encoding: gzip, deflate") 
whereas wget/curl by default don't. After adding that header to 
wget/curl they get the same double gzipped file as the browsers do:


$ ll *July*
-rw-rw-r-- 1 andreas andreas 747850 Aug 27 13:48 chromium_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 748041 Aug 27 13:41 curl_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 747850 Aug 27 13:40 
curl_encoding_2012-July.txt.gz

-rw-rw-r-- 1 andreas andreas 747850 Aug 27 13:48 firefox_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 748041 Aug  2 03:27 wget_2012-July.txt.gz
-rw-rw-r-- 1 andreas andreas 747850 Aug  2 03:27 
wget_encoding_2012-July.txt.gz


I think the following is happening:
If you send the "Accept-Encoding: gzip, deflate"-header, the server will 
gzip the file a second time (which is arguably unnecessary) and responds 
with "Content-Encoding: gzip" and "Content-Type: application/x-gzip" 
(which is IMHO correct according to RFC2616/14.11 and 14.17[3]).
But because many servers apparently don't set correct headers, the 
default behaviour of most browsers nowadays is to ignore the 
content-encoding for gzip files (application/x-gzip - see bug report for 
firefox[4] and chromium[5]) and don't uncompress the outer layer, 
leading to a double gzipped file in this case.


Bye, Andreas

[1] http://mail.python.org/pipermail/python-list/2012-January/617983.html

[2] http://mail.python.org/pipermail/python-list/2012-January/618211.html

[3] http://www.ietf.org/rfc/rfc2616

[4] https://bugzilla.mozilla.org/show_bug.cgi?id=610679#c5

[5] http://code.google.com/p/chromium/issues/detail?id=47951#c9
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cut out XML subtree

2012-08-29 Thread Andreas Perstinger
On Wed, 29 Aug 2012 18:17:18 +0200 
Florian Lindner  wrote:
> I want to cut out an XML subtree like that:
[snip] 
> Is there a way I can do that using etree or DOM? The first is
> prefered...

Python 3.2.2 (default, Sep  5 2011, 22:09:30) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as etree
>>> test = """
... 
... 
... Element A.1
... Element A.2
... 
... 
... Element B.1
... Element B.2
... 
... """
>>> tree = etree.fromstring(test)
>>> subA = tree.find("subA")
>>> tree.remove(subA)
>>> new = etree.tostring(tree, encoding="unicode")
>>> print(new)


Element B.1
Element B.2



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


Re: focus on jtextfield

2012-09-04 Thread Andreas Perstinger

On 04.09.2012 11:34, Paolo wrote:

how do I know if a JTextField has the focus?
thank to all


Look there:
http://www.catb.org/esr/faqs/smart-questions.html#forum

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


Re: How to tell people to ask questions the smart way

2012-09-05 Thread Andreas Perstinger

On 05.09.2012 01:05, Ben Finney wrote:

Andreas Perstinger  writes:


On 04.09.2012 11:34, Paolo wrote:
> how do I know if a JTextField has the focus?
> thank to all

Look there:
http://www.catb.org/esr/faqs/smart-questions.html#forum


That is an unhelpful response.


So we have to agree to disagree.

EOD.

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


Re: Question regarding 2 modules installed via 'pip'

2013-11-16 Thread Andreas Perstinger

On 16.11.2013 16:13, Ferrous Cranus wrote:

Τη Σάββατο, 16 Νοεμβρίου 2013 5:01:15 μ.μ. UTC+2, ο χρήστης Robert
Kern έγραψε:

The kind people at http://serverfault.com/ can help you with your
system administration problems. I'm afraid that we cannot.


Robert i have followed your advise and akse there the other time for
why yum cannot detect python and pip and what i should do.

i received no reply 2-3 days now.

> I will nto ask there again.

The only question I've found from you on serverfault

http://serverfault.com/questions/555054/python-pip-installation-under-centos-6-4

was answered within one hour (you asked at 2013-11-14 17:27:33Z,
"yoonix" answered at 2013-11-14 18:19:54Z). But since he didn't spoonfed
you, no wonder that you ignore that answer.

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: using ffmpeg command line with python's subprocess module

2013-12-04 Thread Andreas Perstinger
iMath  wrote:
>I use the following code to do the test ,but error occurred ,it
>prompts system cannot find specified files ,but the files are indeed
>exists there ,any help ?
>
>with tempfile.TemporaryFile() as fp:
>fp.write(("file '"+'a1.mp3'+"'\n").encode('utf-8'))
>fp.write(("file '"+'a2.mp3'+"'\n").encode('utf-8'))
>
>subprocess.call(['ffmpeg/ffmpeg', '-f', 'concat','-i',fp, '-c',
> 'copy', 'a3.mp3'])

Basic rule: Always copy'n'paste the exact traceback you get.

I don't think you are running the code you have posted because your
subprocess call doesn't work:

>>> import tempfile, subprocess
>>> with tempfile.TemporaryFile() as fp:
...   subprocess.call(["foo", "bar", fp, "baz"])
... 
Traceback (most recent call last):
  File "", line 2, in 
  File "/usr/lib/python3.3/subprocess.py", line 520, in call
with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.3/subprocess.py", line 820, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.3/subprocess.py", line 1380, in _execute_child
restore_signals, start_new_session, preexec_fn)
TypeError: Can't convert '_io.BufferedRandom' object to str implicitly

"fp" is a file object, but subprocess expects a list of strings as
its first argument.

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: using ffmpeg command line with python's subprocess module

2013-12-10 Thread Andreas Perstinger
iMath  wrote:
>we don't have permission to use the temporary file while it has not
>been closed,but when the file is closed , it will be destroyed by
>default(delete=True),but once we set delete=False,then we couldn't
>depend on the convenience of letting the temporary file automatically
>delete itself after it has been used(then we have to delete it later
>by os.remove()) ,thus there is nearly no convenience in creating a
>temporary file or a persistent one when using NamedTemporaryFile.

In your OP you asked for a platform independent solution thus I don't
think it's possible to do what you want if the OS doesn't support
opening a file another time while it's still open.

Otherwise, on my Linux system this works:

>>> import tempfile, subprocess
>>> with tempfile.NamedTemporaryFile() as fp:   
...   fp.write(b"foo\nbar\nbaz\n")
...   fp.flush()
...   subprocess.call(["cat", fp.name])
... 
12
foo
bar
baz
0

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem with graph of python(show)

2013-12-10 Thread Andreas Perstinger

On 10.12.2013 18:03, Asemaneh Allame wrote:

my mean is obvios
i cont get any graph of vpython
it shows me a maseage in this form:
" pythonw.exe has stopped working"
i m sure that have a good & perfect install and i dont khnow what s problem
is that enouph??


No, that's not enough. You need to be more specific.

How do you run your program? From the command line or some IDE? Or are 
you using the python shell?


What code are you trying to run?

How do you know that you have a "good & perfect install"?

Have you tried the example from the official site?
http://www.vpython.org/contents/bounce_example.html

There is also a forum for VPython:
https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: Need Help with the BeautifulSoup problem, please

2013-12-16 Thread Andreas Perstinger

On 16.12.2013 07:41, seasp...@gmail.com wrote:

I need to replace all tag  with  after ■. But the result
frombelow is '■ D / '
Can you explain what I did wrong, please.

 s = '■A B C D / '
 soup = BeautifulSoup(s)
 for i in soup.find_all(text='■'):
 tag = soup.new_tag('span')
 tag['style'] = 'REPLACE'
 for ii in i.find_next_siblings():
 if ii.name=='font' or str(ii).lstrip('')[0:1]=='/':
 break
 else:
 if ii.name=='b':
 tag.string=ii.string
 print(ii.replace_with(tag))
 print(soup)



You are only creating one new tag but as I understand your problem you 
want to replace each b-element with a new tag. Simply move the tag 
creating part:


for i in soup.find_all(text='■'):
for ii in i.find_next_siblings():
if ii.name=='font' or str(ii).lstrip('')[0:1]=='/':
break
else:
if ii.name=='b':
tag = soup.new_tag('span')
tag['style'] = 'REPLACE'
tag.string=ii.string
print(ii.replace_with(tag))

And please read
https://wiki.python.org/moin/GoogleGroupsPython
if you want to continue using Google Groups for accessing this list.

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: PDFMiner install question

2013-12-20 Thread Andreas Perstinger
Jason Mellone  wrote:
>I get the following error:
>PS C:\USERS\Python27> .\python.exe .\MyTest.py
>Traceback (most recent call last):
>  File ".\MyTest.py", line 4, in 
>from pdfminer.pdfpage import PDFTextExtractionNotAllowed
>ImportError: cannot import name PDFTextExtractionNotAllowed
>
>
>If I run commenting out the import of "PDFTextExtractionNotAllowed" it
>runs without a problem. Quite odd.

According to the latest version on Github,
"PDFTextExtractionNotAllowed" was moved into the "PDFPage" class, but
the sample code in the docs was obviously not updated.

https://github.com/euske/pdfminer/blob/master/pdfminer/pdfpage.py

So just leave out that line and if you need that exception use
"PDFPage.PDFTextExtractionNotAllowed" instead of
"PDFTextExtractionNotAllowed".

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Datetime string reformatting

2013-12-22 Thread Andreas Perstinger

On 22.12.2013 11:58, Igor Korot wrote:

My script receives a data from the csv file. In this csv file there is
a datetime field.
This datetime field is formatted as follows: %m/%d/%Y
%H:%M:%S.{milliseconds}. I'm reading this field into the string with
this format.

The trouble comes from the fact that I need to insert this value into
mySQL. Doing it directly gives me an error: "Incorrect formatting".
After a bit of googling and trial I found out that mySQL is looking
for the format of '%Y/%m/%d %H:%M:%S.{milliseconds}.

There is a mySQL function which transfers the data into the proper
format: STR_TO_DATE(), but I can't obviously call it since it is not
known to Python.


You don't want to call "STR_TO_DATE()" from Python but use it inside the 
SQL statement.


So instead of doing the conversion in Python as Mark suggested, you 
could do something like


sql_stmt = """INSERT ...
  VALUES (..., STR_TO_DATE(%s, "%m/%d/%Y %H:%M:%S.{%f}"),
  ...)"""
cursor.execute(sql_stmt, (..., mydate_from_csv, ...))

(BTW: Do you mean microseconds instead of milliseconds? And are the 
"milliseconds" really inside curly braces?)


Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to check the date validity?

2013-12-23 Thread Andreas Perstinger
Jason Friedman  wrote:
>Would this not work?
>import re
>if re.search(r"\d{1,2}:\d{2}:\d{2}(.\d{1,3})?", "12:55:55.705"):
># It's a time

No, because this regexp also matches stuff like "99:99:99.999".
Checking for the number of digits is not enough, because not all
combinations of two digits are valid hours, minutes or seconds.

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print function and unwanted trailing space

2013-08-31 Thread Andreas Perstinger

On 31.08.2013 10:17, candide wrote:


What is the equivalent in Python 3 to the following Python 2 code:

# -
for i in range(5):
  print i,
# -

?


How about

>>> print(" ".join(str(i) for i in range(5)))
0 1 2 3 4

Bye, Andreas



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


Re: Weird bahaviour from shlex - line no

2013-09-28 Thread Andreas Perstinger

On 28.09.2013 08:26, Daniel Stojanov wrote:

Can somebody explain this. The line number reported by shlex depends
on the previous token. I want to be able to tell if I have just popped
the last token on a line.


[SNIP]


second = shlex.shlex("word1 word2,\nword3")


Punctuation characters like the comma are not considered as word 
characters by default and thus are seen as different tokens (consisting 
of only a single character):


>>> lexer = shlex.shlex("foo, bar, ...")
>>> token = lexer.get_token()
>>> while token != lexer.eof:
...   print token
...   token = lexer.get_token()
...
foo
,
bar
,
.
.
.

If you want to treat them as "word" characters you need to add them to 
the string "wordchars" (a public attribute of the "shlex" instance):


>>> lexer = shlex.shlex("foo.bar, baz")
>>> lexer.wordchar += '.,'
>>> print lexer.get_token()
foo.bar,
>>> print lexer.get_token()
baz

There is also a "debug" attribute (with three different levels: 1, 2, 3; 
default value 0 means no debug output):


>>> lexer = shlex.shlex("foo, bar, ...")
>>> lexer.debug = 1
>>> print lexer.get_token()
shlex: token='foo'
foo
>>> print lexer.get_token()
shlex: popping token ','
,

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: Handling 3 operands in an expression without raising an exception

2013-09-28 Thread Andreas Perstinger
Νίκος  wrote:

>Στις 28/9/2013 1:19 μμ, ο/η Chris Angelico έγραψε:
>> [ROLL] Rosuav rolls his eyes: 1, 1, totalling 2.
>>
>> Then split your try blocks! You've already been told this.
>>
>No we didn't have said this. if you are referring to this:

At least Denis told you about 24 hours ago:
https://mail.python.org/pipermail/python-list/2013-September/656318.html

So either do it like that (which is the reasonable way) or look for
another programming language.

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Select fails when cookie tried to get a numeric value

2013-10-05 Thread Andreas Perstinger

On 05.10.2013 17:31, Νίκος Αλεξόπουλος wrote:

Now i have it like this:

# connect to database
con = pymysql.connect( db = 'nikos_metrites', user = 'nikos_root',
passwd = 't1abhp2r!', charset = 'utf8', host = 'localhost' )


Just to be sure: That's not your real password, is it?

Bye, Andreas

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


Re: Select fails when cookie tried to get a numeric value

2013-10-05 Thread Andreas Perstinger

On 05.10.2013 16:24, Νίκος Αλεξόπουλος wrote:

# initialize cookie
cookie = cookies.SimpleCookie( os.environ.get('HTTP_COOKIE') )
cookie.load( cookie )


Watch:

>>> cookie1 = cookies.SimpleCookie('ID=42')
>>> cookie1.load(cookie1)
>>> print(cookie1)
Set-Cookie: ID="Set-Cookie: ID=42"
>>> cookie1.get('ID').value
'Set-Cookie: ID=42'

And now watch this:

>>> cookie2 = cookies.SimpleCookie('ID=42')
>>> print(cookie2)
Set-Cookie: ID=42
>>> cookie2.get('ID').value
'42'

Explanation:

http://docs.python.org/3/library/http.cookies.html#http.cookies.BaseCookie.load

>>> c = cookies.SimpleCookie('ID=42')
>>> isinstance(c, dict)
True
>>> c.items()
dict_items([('ID', )])

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to streamingly read text file and display whenever updated text

2013-10-07 Thread Andreas Perstinger

On 07.10.2013 03:54, galeom...@gmail.com wrote:

https://docs.google.com/file/d/0B2D69u2pweEvelh1T25ra19oZEU/edit?usp=sharing



For the readers who don't bother clicking on the link above: It's a 
short video where the OP demonstrates how her/his usage of tail doesn't 
work.



no matter call tail directly in python or using the script of tail
all failed
it seems it can not read next line


In your video you use gedit to write some file and "tail -f " to 
follow it. But "tail -f" will follow the file descriptor. Usually, 
editors like gedit won't save your changes to the original file but 
create a new temporary file and rename it later to the original file 
name after deleting the original one. Thus tail will follow an already 
deleted file.

See also this blog post:
http://tech.shantanugoel.com/2009/12/23/continuous-monitor-tail-fails.html

For your example you will have to use "tail -F " which will follow 
the file name.


Alternatively you could write a simple script to simulate a continously 
growing file like


import time
for i in range(1000):
with open("test.txt", "a") as f:
f.write(str(i) + '\n')
time.sleep(1)

which should work with "tail -f".

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re for Apache log file format

2013-10-08 Thread Andreas Perstinger

On 08.10.2013 08:33, Sam Giraffe wrote:

#this is a single line
string = '192.168.122.3 - - [29/Sep/2013:03:52:33 -0700] "GET / HTTP/1.0"
302 276 "-" "check_http/v1.4.16 (nagios-plugins 1.4.16)"'

#trying to break up the pattern match for easy to read code
pattern = re.compile(r'(?P\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+'
  r'(?P\-)\s+'
  r'(?P\-)\s+'
  r'(?P\[(.*?)\])\s+'
  r'(?P\"(.*?)\")\s+'
  r'(?P\d{3})\s+'
  r'(?P\d+)\s+'
  r'(?P\"\")\s+'
  r'(?P\((.*?)\))')


[SNIP]


The python interpreter is skipping to the 'math = re.search' and then the
'if' statement right after it looks at the , instead of moving onto
 and so on.


I'm not sure if I understand your problem, but your regex pattern only 
matches up to the size. When you look for the referrer, the pattern 
expects two quotes but in your string you have "-" (quote, dash, quote). 
Thus there is no match (i.e. "match" is None) and the if-statement will 
print "not found".


Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: parsing email from stdin

2013-10-08 Thread Andreas Perstinger

On 08.10.2013 14:20, Antoon Pardon wrote:

As I don't know what encoding these messages will be in, I thought it
would be prudent to read stdin as binary data.

Using python 3.3 on a debian box I have the following code.

#!/usr/bin/python3

import sys
from email import message_from_file

sys.stdin = sys.stdin.detach()
msg = message_from_file(sys.stdin)


Looking at the docs, I've found there is also "message_from_binary_file" 
which works for me with your code.


http://docs.python.org/3/library/email.parser.html#email.message_from_binary_file

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: parsing email from stdin

2013-10-08 Thread Andreas Perstinger

On 08.10.2013 17:25, Antoon Pardon wrote:

Op 08-10-13 16:24, Andreas Perstinger schreef:

Looking at the docs, I've found there is also "message_from_binary_file"
which works for me with your code.

http://docs.python.org/3/library/email.parser.html#email.message_from_binary_file



I can't try that out right now, but I had a look at the code and the
ByteParser that is mentioned their looks like this:

class BytesFeedParser(FeedParser):
  """Like FeedParser, but feed accepts bytes."""

  def feed(self, data):
  super().feed(data.decode('ascii', 'surrogateescape'))


Somehow I doubt that trying to decode my utf-8 stream as if it was
ascii will work.


Actually it does work:

$ cat testmail.txt
From: "someone" 
To: "me" 
Subject: something
Content-Type: text/plain; charset="UTF-8";
Content-Transfer-Encoding: 8bit

foo bar AÄÖÜĎӅ baz

$ file testmail.txt
testmail.txt: news or mail, UTF-8 Unicode text

$ cat foo.py
#!/usr/bin/python3

import sys
from email import message_from_binary_file

sys.stdin = sys.stdin.detach()
msg = message_from_binary_file(sys.stdin)

print("from: ", msg['From'])
print("to: ", msg['To'])
print("subject: ", msg['Subject'])
print("body: ", msg.get_payload())

$ ./foo.py < testmail.txt
from:  "someone" 
to:  "me" 
subject:  something
body:  foo bar AÄÖÜĎӅ baz

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to get final URL after redirection

2013-10-31 Thread Andreas Perstinger
nishant bhakta  wrote:

>I have a link that will redirect to any-other link and i have to work
>with that final link. For example if i have a link "www.bit.ly/2V6CFi"
>that will redirect to "www.google.com". Here i want that i take
>"www.bit.ly/2V6CFi" and find the final redirect link and append
>"#q=python" to that link and produce an output that is
>"www.google.com/#q=python".

For bitly links you need to use their API:
http://dev.bitly.com/links.html#v3_expand

There is a python module for interacting with it:
https://github.com/bitly/bitly-api-python

Bye, Andreas
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to add a current string into an already existing list

2013-11-02 Thread Andreas Perstinger

On 02.11.2013 12:58, Nick the Gr33k wrote:

Trying to add the current filename into the existent 'downloads' column
Somehow i don't think i just use the plus sign into an existing column.
We don't try to add numbers here but add an extra string to an already
existing array of strings(list).


[SNIP]


# update specific visitor's download record
cur.execute('''UPDATE visitors SET downloads = downloads + %s WHERE host
= %s''', (filename, host) )
==


Well, when do you understand that your MySQL problems have nothing to do 
with Python?


Everything inside the triple quotes is MySQL specific, so it's a MySQL 
problem whether you can use + to "add an extra string to an already 
existing array of strings(list)".


This list is not a MySQL support forum.

Bye, Andreas
--
https://mail.python.org/mailman/listinfo/python-list


Re: Invoke a superclass method from a subclass constructor

2011-09-11 Thread Andreas Perstinger

On 2011-09-11 13:17, Kayode Odeyemi wrote:

On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans  wrote:

 It is working:

 >>>  class A(object):
 ... def log (self, module):
 ... return str ('logged')
 ...
 >>>  class B(A):
 ... def __init__(self, module):
 ... self.module = A().log(module)
 ...
 >>>  c = B('system')
 >>>  c.module
 'logged'


Why do you have to do c.module? I'm expecting an output just by creating an
instance of B.


Why do you expect an output? In B.__init__ you are just assigning the 
return value from A.log() to the attribute "module" and in A.log() there 
is no output either.


Bye, Andreas

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


Re: file processing question

2011-10-12 Thread Andreas Perstinger

On 2011-10-12 13:15, selahattin ay wrote:


hi all, I wrote these codes but the program must write the prints to a text 
file...
  code = [100, 200, 300, 400, 500]


list= []
a = 0
while a<  9:
 a+=1
 list.append(a)
last_list = [[int(str(i) + str(k)) for i in code] for k in list]
list2= []
b = 0
while b<  9:
 b+=1
 list2.append(b)


Others have already told you yesterday that you don't need while-loops:
list = range(1, 10)
list2 = list[:]
(you probably don't need "list2" at all)


the thing that I want to do is, I want to create text files from 1 to 9 as in 
list2
1.txt, 2.txt 9.txt like thatsample of a text file is :

X:CA
VERSION:2.5
P:(here will be the first value of list2 )
L;C: (here will be the first value of last_list )


the first sample
X:CA
VERSION:2.5
P: 1 
L;C: 1001

the first sample

X:CA
VERSION:2.5
P: 8 
L;C: 1008


You want to write 9 files but last_list has 45 elements. What will 
happen with the rest of them?


BTW: Your last_list is a list of 9 lists, each containing 5 elements 
([[1001, 2001, ...], [1002, 2002, ...], ...]). Don't you really want a 
list of 5 lists, each containing 9 elements ([[1001, 1002, ...], [2001, 
2002, ...], ...])? At least I get this impression from your samples.


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


Re: Python gp.ListFeatureClasses return only one file

2011-10-13 Thread Andreas Perstinger

On 2011-10-13 14:00, yo wrote:

Hi All,
I m using the gp.ListFeatureClasses to make a list of file in my
directory (containing several hundreds of file)
however when I print the variable in which the List is supposed to be
stored, the print just return one file name
does any one have an idea


Depending on the version you are using, "ListFeatureClasses()" returns 
either a list or an enumeration object:

http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=ListFeatureClasses_method

You are just printing the first item. To print all, something like the 
following should work (assuming you are using version 9.2):


shpList = gp.ListFeatureClasses("*.shp")
shp = shpList.Next()
while shp:
print shp
shp = shpList.Next()

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


Re: Python lesson please

2011-11-07 Thread Andreas Perstinger

On 2011-11-07 12:22, gene heskett wrote:

On Monday, November 07, 2011 05:35:15 AM Peter Otten did opine:

 Are you talking about this one?

 https://github.com/halsten/Duqu-detectors/blob/master/DuquDriverPatterns
 .py


Yes.  My save as renamed it, still has about 30k of tabs in it.  But I
pulled it again, using the 'raw' link, saved it, no extra tabs.

But it still doesn't work for linux.  My python is 2.6.6


Go to the directory where you've downloaded the file and type:

python DuquDriverPatterns.py .

What output do you get?

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


Re: Trying to write beautifulsoup result to a file and get error message

2011-11-14 Thread Andreas Perstinger

On 2011-11-13 23:37, goldtech wrote:

If I try:
...
soup = BeautifulSoup(ft3)
f = open(r'c:\NewFolder\clean4.html', "w")
f.write(soup)
f.close()

I get error message:

Traceback (most recent call last):
   File "C:\Documents and Settings\user01\Desktop\py\tb1a.py", line
203, in
 f.write(soup)
TypeError: expected a character buffer object

I want to write beautiful soup's result to a file, I am doing
something wrong. Help appreciated.


BeautifulSoup takes a html document in the form of a string or file-like 
oject and creates an internal data-structure after parsing it:


Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from BeautifulSoup import BeautifulSoup
>>> html = "Demo"
>>> soup = BeautifulSoup(html)
>>> type(soup)


To write the modified document into a file, you have to convert this 
structur back into a string:


>>> new_html = str(soup)
>>> type(new_html)

>>> new_html
'\n \n  Demo\n \n'

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


Re: sick of distribute, setup, and all the rest...

2011-11-28 Thread Andreas Perstinger

On 2011-11-28 14:14, rusi wrote:

On Nov 28, 4:42 pm, Steven D'Aprano  wrote:

 We don't chase people down on the street and lecture them about the
 problems we think they are having, we answer questions about ACTUAL
 problems that they have experienced and asking about.



 ... ever question gets an answer, and we're discussing
 things about as much as we ought to.


How about applying these claims to the OP?



OP asked only one question (the rest was just ranting) and Steven 
answered it (IMHO in the right manner).


OP never mentioned specific problems or what's wrong with any of the 
distribution systems. So what answers are you expecting from such a post?


Bye, Andreas


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


Re: Learning Python 2.4

2011-12-21 Thread Andreas Perstinger

On 2011-12-20 19:31, kimma wrote:

I am about to learn python with "how to think like a computer
scientist". This book is just available for python 2.4. Does it matter
for programming?


There is also a online-version for Python 3 but there are some differences:
http://openbookproject.net/thinkcs/python/english3e/preface3-rle.html

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


Re: Checking for valid date input and convert appropriately

2013-02-22 Thread Andreas Perstinger
Lele Gaifax  wrote:
>Ferrous Cranus  writes:
>
>> Let me ask it like this:
>> How can i avoid using try: except: for checkign the date but instead
>> check it with an if statement:
>
>Let me answer this way: you can't, without resorting to the simple
>helper functions I wrote in my previous message. 
>
>Why do you dislike that solution?

Ferrous Cranus has proven in previous discussions (search the archives)
that he doesn't like common-sense solutions and insists on doing it his
own way (although his methods are either wrong or impossible).

Don't waste your time.

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


Re: Simple Plot in Python

2013-03-16 Thread Andreas Perstinger
subhabangal...@gmail.com wrote:
>I was trying to draw in Matplotlib but did not find much help.

Have you looked already at the homepape for "maptlotlib"?:
http://matplotlib.org/index.html

There you'll find a tutorial:
http://matplotlib.org/users/pyplot_tutorial.html

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


Re: Error in "Import gv " module

2013-04-22 Thread Andreas Perstinger

On 22.04.2013 12:13, Megha Agrawal wrote:

https://code.google.com/p/python-graph/wiki/Example

When I am trying to run the code to draw a graph, given on above link, I am
getting following error:

ImportError: No module named gv

What can be the reasons?


Which OS?

It looks like you are missing "graphviz" or you need to adapt your paths:
https://code.google.com/p/python-graph/issues/detail?id=15

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


Re: Error in "Import gv " module

2013-04-22 Thread Andreas Perstinger

Please avoid top posting and answer to the list.

On 22.04.2013 12:38, Megha Agrawal wrote:

Widows 7, and i have pygraphviz library in python27-> lib->
site-package folder.


Sorry don't know much about Windows.

Have you read through all the issues involving "import gv" errors?:
https://code.google.com/p/python-graph/issues/list?can=1&q=import+gv&colspec=ID+Type+Status+Priority+Milestone+Owner+Summary&cells=tiles

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


Re: Error in "Import gv " module

2013-04-22 Thread Andreas Perstinger

You are still top posting.

On 22.04.2013 14:43, Megha Agrawal wrote:

yes, I did. They said, gv module doesn't exist for windows.


Then I'm afraid you are out of luck.

Two possible alternatives:

1) Save your graph to a file and use the command line tools:
http://stackoverflow.com/a/12698636

2) Try some other Graphviz bindings. A quick search on PyPi gave me:
https://pypi.python.org/pypi/pygraphviz/1.1
https://pypi.python.org/pypi/pydot/1.0.28
https://pypi.python.org/pypi/yapgvb/1.2.0

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