print range in python3.3

2014-01-04 Thread luofeiyu
>>> range(1,10)
range(1, 10)
>>> print(range(1,10))
range(1, 10)

how can i get 1,2,3,4,5,6,7,8,9 in python3.3 ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: more simple to split the string?

2014-08-08 Thread luofeiyu
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 
bit (AM

D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> str='(\\HasNoChildren \\Junk) "/" "[Gmail]/&V4NXPpCuTvY-"'
>>> str.split(" ")
['(\\HasNoChildren', '\\Junk)', '"/"', '"[Gmail]/&V4NXPpCuTvY-"']
>>>

it can be split into four parts,you can see.


On 8/8/2014 1:43 AM, Mark Lawrence wrote:

On 08/08/2014 01:23, elearn wrote:

str='(\\HasNoChildren \\Junk) "/" "[Gmail]/&V4NXPpCuTvY-"'


First up it's not usually a good idea to override the builtin name str.


x=str.split(' "')
[i.replace('"','') for i in x]
['(\\HasNoChildren \\Junk)', '/', '[Gmail]/&V4NXPpCuTvY-']

x.strip(" ") will create four parts.


I assume you meant x=str.split(" ") ?  Even so I don't see how you can 
get four parts so please explain.




is there more simple to do that ?


No loop needed that I can see.

>>> oldstr='(\\HasNoChildren \\Junk) "/" "[Gmail]/&V4NXPpCuTvY-"';oldstr
'(\\HasNoChildren \\Junk) "/" "[Gmail]/&V4NXPpCuTvY-"'
>>> newstr=oldstr.replace('"', '');newstr
'(\\HasNoChildren \\Junk) / [Gmail]/&V4NXPpCuTvY-'
>>> substrings=newstr.split();substrings
['(\\HasNoChildren', '\\Junk)', '/', '[Gmail]/&V4NXPpCuTvY-']



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


how to get the ordinal number in list

2014-08-08 Thread luofeiyu

>>> x=["x1","x3","x7","x5"]
>>> y="x3"

 how can i get the ordinal number by some codes?

for id ,value in enumerate(x):
if y==value : print(id)

Is more simple way to do that?
--
https://mail.python.org/mailman/listinfo/python-list


how to print with given font and size?

2014-08-08 Thread luofeiyu

print("hallo") is so simple.

how can  print word "hallo"  in console with courier New font  16 pound?
--
https://mail.python.org/mailman/listinfo/python-list


Re: how to get the ordinal number in list

2014-08-08 Thread luofeiyu

>>> x=["x1","x3","x7","x5","x3"]
>>> x.index("x3")
1
if i want the result of 1 and 4 ?

On 8/8/2014 7:25 PM, Larry Martell wrote:

On Sat, Aug 9, 2014 at 1:22 PM, luofeiyu  wrote:

x=["x1","x3","x7","x5"]
y="x3"

  how can i get the ordinal number by some codes?

for id ,value in enumerate(x):
 if y==value : print(id)

Is more simple way to do that?

print x.index(y)


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


how to write file into my android phone?

2014-08-08 Thread luofeiyu
When i input usb line with my android phone into the pc , there are two 
disks j: and k: (type :removable disk)  displayed in win7.


i can get my android phone bluetooth mac address .

import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names = True)
for addr, phoneName in nearby_devices:
print(addr)


it is  6C:8B:2F:CE:5B:59

Now how can i write a file into the disk  j:  of my android 
phone(bluetooth mac is 6C:8B:2F:CE:5B:59 )?


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


attendance system in pybluez

2014-08-09 Thread luofeiyu

I want to write a program to help my teacher to take attendence.

There are 300 students in a big room,everyone has android phone.
I have matched them with my pc in win7 .
when all of them seated on the classroom,

import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names = True)
print("found %d devices" % len(nearby_devices))


The function can discover all of them ? 300 bluetooth mac address?

can i search for a given bluetooth mac?

blue_mac=[]  (i can write it in a list in advance,it is not blank,full 
of strings)


for add in blue_mac:
 print(bluetooth.seacrh_given_mac) #result is true or false

Is there a function to run?



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


Re: attendance system in pybluez

2014-08-09 Thread luofeiyu

in the http://homepages.ius.edu/rwisman/C490/html/PythonandBluetooth.htm

*Discovery*

   The address and name of enabled devices within range can be
   discovered by other Bluetooth devices. Discovery can take some time
   to complete, given that radio communications is unreliable. The
   following displays address and name of all enabled devices nearby.

   from bluetooth import *

   print "performing inquiry..."

   *nearby_devices = discover_devices(lookup_names = True)*

   print "found %d devices" % len(nearby_devices)

   for name, addr in nearby_devices:
 print " %s - %s" % (addr, name)

   performing inquiry...
   found 2 devices
   Ray's Nokia - 00:12:D2:5A:BD:E4
   Ray's MacBook - 00:1E:C2:93:DA:6F



On 8/9/2014 4:53 AM, Steven D'Aprano wrote:

luofeiyu wrote:


I want to write a program to help my teacher to take attendence.

There are 300 students in a big room,everyone has android phone.

If your students allow strange devices to connect to their android phones,
then they won't remain their android phones for very long. They will belong
to whatever hacker takes control of them first.

http://blog.kaspersky.com/bluetooth-security/



I have matched them with my pc in win7 .
when all of them seated on the classroom,

import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names = True)
print("found %d devices" % len(nearby_devices))


The function can discover all of them ? 300 bluetooth mac address?

You will have to ask the author of the bluetooth module. Where did you find
it? Does it come with documentation? Did you read it?





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


how to get the subject of email?

2014-08-09 Thread luofeiyu

I am in python3.4

typ, data = x.con.fetch(b'1', '(RFC822)')   #get  the first email
text = data[0][1]
message = email.message_from_string(text).get('subject')

Traceback (most recent call last):
  File "", line 1, in 
  File "D:\Python34\lib\email\__init__.py", line 40, in message_from_string
return Parser(*args, **kws).parsestr(s)
  File "D:\Python34\lib\email\parser.py", line 70, in parsestr
return self.parse(StringIO(text), headersonly=headersonly)
TypeError: initial_value must be str or None, not bytes

message = email.message_from_string(str(text)).get('subject')
message  # nothing displayed
--
https://mail.python.org/mailman/listinfo/python-list


Re: how to get the subject of email?

2014-08-09 Thread luofeiyu

message = email.message_from_bytes(text)

I get it ,
print(message['Subject'])  #can get the subject

But how can i get the body content of message?

no , message['Body']  or message['Content']

On 8/9/2014 7:01 PM, John Gordon wrote:

In  luofeiyu 
 writes:


message = email.message_from_string(str(text)).get('subject')
message  # nothing displayed

Try using email.message_from_bytes() instead.

Also have a look at
http://stackoverflow.com/questions/19508393/python-email-parsing-issue
for a question very similar to yours.  Perhaps something in the code
will help.



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


Re: how to get the subject of email?

2014-08-09 Thread luofeiyu

think you ,i get it .
message = email.message_from_bytes(text)
print(message['Subject'])  #can get the subject

But how can i get the body content of message?

 message['Body']  or message['Content'] can get none.


On 8/9/2014 7:01 PM, John Gordon wrote:

In  luofeiyu 
 writes:


message = email.message_from_string(str(text)).get('subject')
message  # nothing displayed

Try using email.message_from_bytes() instead.

Also have a look at
http://stackoverflow.com/questions/19508393/python-email-parsing-issue
for a question very similar to yours.  Perhaps something in the code
will help.



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


get the min date from a list

2014-08-10 Thread luofeiyu

>>> date
['Sat, 09 Aug 2014 07:36:46 -0700', 'Fri, 8 Aug 2014 22:25:40 -0400', 
'Sat, 9 Au
g 2014 12:46:43 +1000', 'Sat, 9 Aug 2014 12:50:52 +1000', 'Sat, 9 Aug 
2014 02:51
:01 + (UTC)', 'Sat, 9 Aug 2014 13:03:24 +1000', 'Sat, 09 Aug 2014 
13:06:28 +
1000', 'Fri, 8 Aug 2014 20:48:44 -0700 (PDT)', 'Fri, 8 Aug 2014 23:52:09 
-0700 (
PDT)', 'Sat, 09 Aug 2014 09:15:50 +0200', 'Sat, 9 Aug 2014 01:49:54 
-0600', 'Sat
, 9 Aug 2014 01:57:18 -0600', 'Sat, 9 Aug 2014 17:54:23 +0800 (CST)', 
'Sat, 9 Au
g 2014 12:49:08 +0200', 'Sat, 9 Aug 2014 07:31:09 -0400', 'Sat, 9 Aug 
2014 07:34
:16 -0400', 'Sat, 09 Aug 2014 11:39:16 +', 'Sat, 9 Aug 2014 07:40:41 
-0400',
 'Sat, 9 Aug 2014 11:46:54 +', 'Sat, 09 Aug 2014 13:48:17 +0200', 
'Sat, 09 A
ug 2014 21:53:11 +1000', 'Sat, 09 Aug 2014 14:13:13 +0200', 'Sat, 09 Aug 
2014 08
:16:08 -0400', 'Sat, 09 Aug 2014 22:17:25 +1000', 'Sat, 09 Aug 2014 
14:33:54 +02
00', 'Sat, 9 Aug 2014 14:46:01 +0200', 'Sat, 09 Aug 2014 10:34:58 
-0300', 'Sat,
09 Aug 2014 11:34:22 -0400', 'Sat, 09 Aug 2014 12:16:56 -0400', 'Sat, 09 
Aug 201
4 12:26:38 -0400', 'Sat, 09 Aug 2014 13:29:59 -0400', 'Sat, 09 Aug 2014 
13:43:33
 -0400', 'Sat, 9 Aug 2014 11:30:35 -0300', 'Sat, 09 Aug 2014 20:14:20 
+0200', 'S
un, 10 Aug 2014 08:18:34 +1000', 'Sat, 9 Aug 2014 18:23:08 -0400 (EDT)', 
'Sat, 0
9 Aug 2014 18:30:17 -0400', 'Sat, 09 Aug 2014 18:31:38 -0400', 'Sun, 10 
Aug 2014
 09:43:44 +1000', 'Sat, 9 Aug 2014 18:27:15 -0700 (PDT)', 'Sun, 10 Aug 
2014 03:4
4:56 +0200', 'Sun, 10 Aug 2014 01:55:24 + (UTC)', 'Sun, 10 Aug 2014 
02:01:06
 + (UTC)', 'Sat, 9 Aug 2014 19:41:08 -0700 (PDT)', 'Sat, 9 Aug 2014 
22:51:29
 -0400 (EDT)', 'Sun, 10 Aug 2014 07:34:44 +0200', 'Tue, 5 Aug 2014 
01:55:24 +000

0 (UTC)']
>>> min(date)
'Fri, 8 Aug 2014 20:48:44 -0700 (PDT)'

The result is wrong,the min date should be 'Tue, 5 Aug 2014 01:55:24 +000
0 (UTC)' ,how can i get it ?
--
https://mail.python.org/mailman/listinfo/python-list


why i can't copy mail with imaplib?

2014-08-10 Thread luofeiyu

Help on method copy in module imaplib:

copy(message_set, new_mailbox) method of imaplib.IMAP4_SSL instance
Copy 'message_set' messages onto end of 'new_mailbox'.

(typ, [data]) = .copy(message_set, new_mailbox)


self is an instance in my code."[Gmail]/&kc2JgQ-]" is the important mailbox.


self.con.select("inbox")
self.con.copy(b"1","[Gmail]/&kc2JgQ-]")

why i can not copy the first email into my  important mailbox?
--
https://mail.python.org/mailman/listinfo/python-list


Re: why i can't copy mail with imaplib?

2014-08-10 Thread luofeiyu

>>> x.con.list()
('OK', [b'(\\HasNoChildren) "/" "INBOX"', b'(\\Noselect \\HasChildren) 
"/" "[Gma
il]"', b'(\\HasNoChildren \\Junk) "/" "[Gmail]/&V4NXPpCuTvY-"', 
b'(\\HasNoChildr
en \\Trash) "/" "[Gmail]/&XfJSIJZkkK5O9g-"', b'(\\HasNoChildren 
\\Flagged) "/" "
[Gmail]/&XfJSoGYfaAc-"', b'(\\HasNoChildren \\Sent) "/" 
"[Gmail]/&XfJT0ZCuTvY-"'
, b'(\\HasNoChildren \\All) "/" "[Gmail]/&YkBnCZCuTvY-"', 
b'(\\HasNoChildren \\D
rafts) "/" "[Gmail]/&g0l6Pw-"', b'(\\HasNoChildren \\Important) "/" 
"[Gmail]/&kc

2JgQ-"'])
>>> x.con.select("inbox")
('OK', [b'40'])
>>> x.con.copy(b"1","[Gmail]/&kc2JgQ-]")
('NO', [b'[TRYCREATE] No folder [Gmail]/\xe9\x87\x8d\xe8\xa6\x81] 
(Failure)'])

>>> x.con.copy(b"1","[Gmail]/Important")
('NO', [b'[TRYCREATE] No folder [Gmail]/Important (Failure)'])
On 8/10/2014 4:07 PM, John Gordon wrote:

In  luofeiyu 
 writes:


self.con.select("inbox")
self.con.copy(b"1","[Gmail]/&kc2JgQ-]")
why i can not copy the first email into my  important mailbox?

What happens when you run the above code?  Do you get an error?



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


how to change the time string into number?

2014-08-13 Thread luofeiyu

s="Aug"

how can i change it into 8 with some python time module?
--
https://mail.python.org/mailman/listinfo/python-list


what is the "/" mean in __init__(self, /, *args, **kwargs) ?

2014-08-13 Thread luofeiyu

>>> help(int.__init__)
Help on wrapper_descriptor:

__init__(self, /, *args, **kwargs)
Initialize self.  See help(type(self)) for accurate signature.

what is the "/" mean in __init__(self, /, *args, **kwargs) ?

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


a python console in bluestacks

2014-08-13 Thread luofeiyu
I have installed bluestacks(an android phone emulator) on my pc,and SL4A 
on it.Now i can run python thish way :
1.edit an file ending with |.py|, save it in 
/sdcard/sl4a/scripts/yourname.py.

2.open sl4a ,and click the file to make it run.

Is there a python console to type python command to run python directly 
such as in pc ?


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


Re: how to change the time string into number?

2014-08-13 Thread luofeiyu

in the manual  https://docs.python.org/3.4/library/time.html

%z 	Time zone offset indicating a positive or negative time difference 
from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour 
digits and M represents decimal minute digits [-23:59, +23:59]. 	

%Z  Time zone name (no characters if no time zone exists).


t1='Sat, 09 Aug 2014  07:36:46  '
time.strptime(t1,"%a, %d %b %Y %H:%M:%S ")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36, tm_sec

=46, tm_wday=5, tm_yday=221, tm_isdst=-1)

>>> t2='Sat, 09 Aug 2014  07:36:46  -0700'
>>> time.strptime(t2,"%a, %d %b %Y %H:%M:%S %z")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36, tm_sec

=46, tm_wday=5, tm_yday=221, tm_isdst=-1)

t1 and t2 is different time ,the timezone in t2 is -0700 ,why we get the 
same result?


>>> t3='Sat, 09 Aug 2014  07:36:46  +0400'
>>> time.strptime(t3,"%a, %d %b %Y %H:%M:%S %z")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36, tm_sec

=46, tm_wday=5, tm_yday=221, tm_isdst=-1)


The Directive   %z  has no any effect here,what is the matter?

On 8/14/2014 10:01 AM, Ben Finney wrote:

luofeiyu  writes:


s="Aug"

how can i change it into 8 with some python time module?

What is your purpose here? If you want to parse a text value into a
structured time object, don't do it piece by piece. Use the
‘time.strptime’ function.

 >>> import time
 >>> input_time_text = "14 Aug 2014"
 >>> input_time = time.strptime(input_text, "%d %b %Y")
 >>> input_time.tm_mon
 8



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


Re: what is the "/" mean in __init__(self, /, *args, **kwargs) ?

2014-08-14 Thread luofeiyu

python3.4



On 8/14/2014 10:12 AM, Tim Chase wrote:

On 2014-08-14 10:01, luofeiyu wrote:

  >>> help(int.__init__)
Help on wrapper_descriptor:

__init__(self, /, *args, **kwargs)
  Initialize self.  See help(type(self)) for accurate signature.

what is the "/" mean in __init__(self, /, *args, **kwargs) ?

Where are you seeing this?



Python 2.7.3 (default, Mar 13 2014, 11:03:55)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

help(int.__init__)

Help on wrapper_descriptor:

__init__(...)
 x.__init__(...) initializes x; see help(type(x)) for signature

^D


Python 3.2.3 (default, Feb 20 2013, 14:44:27)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

help(int.__init__)

Help on wrapper_descriptor:

__init__(...)
 x.__init__(...) initializes x; see help(type(x)) for signature



-tkc




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


Re: a python console in bluestacks

2014-08-14 Thread luofeiyu
i want to run python on my android phone ,to install python on 
bluestacks is to emulate it .



On 8/14/2014 2:56 PM, Cameron Simpson wrote:
On 14Aug2014 08:25, Chris =?utf-8?B?4oCcS3dwb2xza2HigJ0=?= Warrick 
 wrote:

On Aug 14, 2014 4:30 AM, "luofeiyu"  wrote:
I have installed bluestacks(an android phone emulator) on my pc,and 
SL4A on

it.Now i can run python thish way :

1.edit an file ending with .py, save it in /sdcard/sl4a/scripts/

yourname.py.

2.open sl4a ,and click the file to make it run.

Is there a python console to type python command to run python directly

such as in pc ?

Why are you using an Android emulator to run Python, a PC-first 
software?!

Just install the Windows version from http://python.org/ and use that.


Maybe he wants Python to run on the emulator? Just an idea...

Cheers,
Cameron Simpson 

The wonderous pulp and fibre of the brain had been substituted by 
brass and

iron; he had taught wheelwork to think. - Harry Wilmot Buxton 1832,
referring to Charles Babbage and his difference engine.


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


Re: how to change the time string into number?

2014-08-14 Thread luofeiyu

>>> import sys
>>> sys.version
'3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit 
(AMD64)]'


>>> import time
>>> time.tzname
('China Standard Time', 'China Daylight Time')


On 8/14/2014 3:25 PM, Cameron Simpson wrote:

On 14Aug2014 14:52, luofeiyu  wrote:

in the manual https://docs.python.org/3.4/library/time.html

┌──┬──┬─┐ 

│  │Time zone offset indicating a positive or negative time 
difference│ │
│%z│from UTC/GMT of the form +HHMM or -HHMM, where H represents 
decimal   │ │
│  │hour digits and M represents decimal minute digits [-23:59, 
+23:59].  │ │
├──┼──┼─┤ 

│%Z│Time zone name (no characters if no time zone 
exists).│ │
└──┴──┴─┘ 



t1='Sat, 09 Aug 2014  07:36:46  '
time.strptime(t1,"%a, %d %b %Y %H:%M:%S ")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36,

tm_sec
=46, tm_wday=5, tm_yday=221, tm_isdst=-1)


t2='Sat, 09 Aug 2014  07:36:46 -0700'
time.strptime(t2,"%a, %d %b %Y %H:%M:%S %z")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36,

tm_sec
=46, tm_wday=5, tm_yday=221, tm_isdst=-1)

t1 and t2 is different time ,the timezone in t2 is -0700 ,why we get 
the same

result?


What you get back a struct_time, which is little more than the numeric 
values extracted from a time string. And as far as the text you have 
supplied in your example, those values are the same.


Regarding the difference, string in t2 has a time zone offset.

My Python 3.4 doco says (about struct_time):

  Changed in version 3.3: tm_gmtoff and tm_zone attributes are 
available on   platforms with C library supporting the corresponding 
fields in struct tm.


Judging by your output, your C library does not support the tm_gmtoff 
and tm_zone fields in its C library "struct tm".


Please:

  tell us what specific version of Python you are using

  tell us what OS you're running on

Then look up the localtime() or gmtime() functions for you C library 
and see what that documentation says about "struct tm", which is what 
they and the C library strptime() return.



t3='Sat, 09 Aug 2014  07:36:46 +0400'
time.strptime(t3,"%a, %d %b %Y %H:%M:%S %z")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36,

tm_sec
=46, tm_wday=5, tm_yday=221, tm_isdst=-1)

The Directive   %z  has no any effect here,what is the matter?


The directive allows the strptime parser to keep recognising text. 
Imagine, for example, that the timezone were embedded in the middle of 
the string for some reason.


It looks like you platform does not support storing the time zone 
information in the C library "struct tm", and therefore it does not 
get exposed to the Python interpreter.


Cheers,
Cameron Simpson 

What I want is Facts. Teach these boys and girls nothing but Facts.  
Facts
alone are wanted in life. Plant nothing else, and root out everything 
else.

- Charles DickensJohn Huffam   1812-1870  Hard Times [1854]


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


how to write a function to make operation as a argument in the function

2014-08-14 Thread luofeiyu

I want to write a function to make operation as a argument in the function.

|def   fun(op,x,y):
return(x op y)|

it is my target for the funciton:

if op ="+" fun(op,3,9) =12
if op ="*" fun(op,3,9) =27

How to write it?

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


Re: get the min date from a list

2014-08-14 Thread luofeiyu

I finished it ,but how to make it into more pythonic way such as
min (dates, key = converter)


here is my code

times=['Sat, 09 Aug 2014 07:36:46 -0700',
'Fri, 8 Aug 2014 22:25:40 -0400',
'Sat, 9 Aug 2014 12:46:43 +1000',
'Sat, 9 Aug 2014 12:50:52 +1000',
'Sat, 9 Aug 2014 02:51:01 + (UTC)',
'Sat, 9 Aug 2014 13:03:24 +1000',
'Sat, 09 Aug 2014 13:06:28 +1000',
'Fri, 8 Aug 2014 20:48:44 -0700 (PDT)',
'Fri, 8 Aug 2014 23:52:09 -0700 (PDT)',
'Sat, 09 Aug 2014 09:15:50 +0200',
'Sat, 9 Aug 2014 01:49:54 -0600',
'Sat, 9 Aug 2014 01:57:18 -0600',
'Sat, 9 Aug 2014 17:54:23 +0800 (CST)',
'Sat, 9 Aug 2014 12:49:08 +0200',
'Sat, 9 Aug 2014 07:31:09 -0400',
'Sat, 9 Aug 2014 07:34:16 -0400',
'Sat, 09 Aug 2014 11:39:16 +',
'Sat, 9 Aug 2014 07:40:41 -0400',
'Sat, 9 Aug 2014 11:46:54 +',
'Sat, 09 Aug 2014 13:48:17 +0200',
'Sat, 09 Aug 2014 21:53:11 +1000',
'Sat, 09 Aug 2014 14:13:13 +0200',
'Sat, 09 Aug 2014 08:16:08 -0400',
'Sat, 09 Aug 2014 22:17:25 +1000',
'Sat, 09 Aug 2014 14:33:54 +0200',
'Sat, 9 Aug 2014 14:46:01 +0200',
'Sat, 09 Aug 2014 10:34:58 -0300',
'Sat, 09 Aug 2014 11:34:22 -0400',
'Sat, 09 Aug 2014 12:16:56 -0400',
'Sat, 09 Aug 2014 12:26:38 -0400',
'Sat, 09 Aug 2014 13:29:59 -0400',
'Sat, 09 Aug 2014 13:43:33  -0400',
'Sat, 9 Aug 2014 11:30:35 -0300',
'Sat, 09 Aug 2014 20:14:20 +0200',
'Sun, 10 Aug 2014 08:18:34 +1000',
'Sat, 9 Aug 2014 18:23:08 -0400 (EDT)',
'Sat, 09 Aug 2014 18:30:17 -0400',
'Sat, 09 Aug 2014 18:31:38 -0400',
'Sun, 10 Aug 2014  09:43:44 +1000',
'Sat, 9 Aug 2014 18:27:15 -0700 (PDT)',
'Sun, 10 Aug 2014 03:44:56 +0200',
'Sun, 10 Aug 2014 01:55:24 + (UTC)',
'Sun, 10 Aug 2014 02:01:06  + (UTC)',
'Sat, 9 Aug 2014 19:41:08 -0700 (PDT)',
'Sat, 9 Aug 2014 22:51:29  -0400 (EDT)',
'Sun, 10 Aug 2014 07:34:44 +0200',
'Tue, 5 Aug 2014 01:55:24 + (UTC)']


def  changeToUnix(times):
import time,calendar,re
time_list=[]
for time1 in times:
pat='(.+?)([-|+]\d{4})(\(?.*\)?)'
x=re.search(pat,time1)
time_part=x.groups()[0].strip()
tz_part=x.groups()[1]
tz_acc=x.groups()[2].strip().replace('(','').replace(')','')
num=int(tz_part[1:3])
if tz_acc in ["","UTC","CST","GMT","EST","CST","PST"]:   num=num
if tz_acc in ["EDT"]:   num=num+2
if tz_acc in ["CDT"]:   num=num+1
if tz_acc in ["PDT"]:   num=num-1
op=tz_part[0]
y=time.strptime(time_part,"%a, %d %b %Y %H:%M:%S")
if op=="-":hour=int(y.tm_hour)-num
if op=="+":hour=int(y.tm_hour)+num
time2=(y.tm_year,y.tm_mon,y.tm_mday,hour,y.tm_min,y.tm_sec)
time_list.append(calendar.timegm(time2))
return(time_list)


y=changeToUnix(times)
times[y.index(min(y))]

'Tue, 5 Aug 2014 01:55:24 + (UTC)'



You neglected to specify your Python version,  but I'll assume at
 least 2.5.

The min function did exactly as it's documented to do, found the
 minimum string, by alphabetical ordering. Since 'F' is less than
 'T' it didn't need to look at the rest.  If you had been sorting
 a list of datetime objects, it would have found the least of
 those.

Your simplest answer is probably to write a function that converts
 a string like you have into a datetime object, say call it
 converter (). Then after testing it, you call

min (dates, key = converter)

Note I did NOT use parens on converter.

I also used the name dates for the list,  since it's a collection
 of dates. But that assumes you rename it in your code that
 gathered them.

--
DaveA


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


Re: get the min date from a list

2014-08-14 Thread luofeiyu
I am glad to hear that it is no necessary to create a complicated my 
function to change the time string.

But in my computer the timezone offset  do not work for me.
I am in win7+python34.

>>> import sys
>>> sys.version
'3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit 
(AMD64)]'


>>> import time
>>> time.tzname
('China Standard Time', 'China Daylight Time')
>>> time.strptime(t1,"%a, %d %b %Y %H:%M:%S %z")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36, tm_sec

=46, tm_wday=5, tm_yday=221, tm_isdst=-1)
>>> time.strptime(t2,"%a, %d %b %Y %H:%M:%S %z")
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7, 
tm_min=36, tm_sec

=46, tm_wday=5, tm_yday=221, tm_isdst=-1)
>>>

The %z does not work for me, how to adjust it my computer?


On 8/15/2014 1:24 AM, Ian Kelly wrote:

On Thu, Aug 14, 2014 at 8:10 AM, luofeiyu  wrote:

I finished it ,but how to make it into more pythonic way such as

min (dates, key = converter)

The converter will be your changeToUnix function, but you'll need to
rework it to convert a single, rather than the whole list.


def  changeToUnix(times):
 import time,calendar,re
 time_list=[]
 for time1 in times:
 pat='(.+?)([-|+]\d{4})(\(?.*\)?)'
 x=re.search(pat,time1)
 time_part=x.groups()[0].strip()
 tz_part=x.groups()[1]
 tz_acc=x.groups()[2].strip().replace('(','').replace(')','')
 num=int(tz_part[1:3])
 if tz_acc in ["","UTC","CST","GMT","EST","CST","PST"]:   num=num
 if tz_acc in ["EDT"]:   num=num+2
 if tz_acc in ["CDT"]:   num=num+1
 if tz_acc in ["PDT"]:   num=num-1
 op=tz_part[0]
 y=time.strptime(time_part,"%a, %d %b %Y %H:%M:%S")
 if op=="-":hour=int(y.tm_hour)-num
 if op=="+":hour=int(y.tm_hour)+num
 time2=(y.tm_year,y.tm_mon,y.tm_mday,hour,y.tm_min,y.tm_sec)
 time_list.append(calendar.timegm(time2))
 return(time_list)

This looks way overly complicated. Why are you trying to mess with the
time zone offset? strptime has a %z format code for parsing that
(although I would recommend using datetime.datetime.strptime since I'm
not sure how well time.strptime supports it). By adding the offset to
the hour like that, you could end up with an hour that falls outside
the accepted range. And I think you have your addition and subtraction
switched around anyway -- in effect you're doubling the time zone
offset, not converting to UTC. Also you would be losing the minutes
part of the time zone offset if you were to get something like +0545.
I also don't understand why you're special-casing and modifying three
of the time zones.

All you need to do is strip the parenthesized timezone off the string
if it's present, and pass the result to datetime.datetime.strptime.


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


problem on top-post

2014-08-14 Thread luofeiyu

when i search what top-post mean:


*top-post*: n., v.
[common] To put the newly-added portion of an email or Usenet response 
before the quoted part, as opposed to the more logical sequence of 
quoted portion first with original following.
*bottom-post*: v.In a news or mail reply, to put the response to a news 
or email message after the quoted content from the parent message. This 
is correct form, and until around 2000 was so universal on the Internet 
that neither the term ‘bottom-post’ nor its antonym /top-post/ 
 existed. 
Hackers consider that the best practice is actually to excerpt only the 
relevent portions of the parent message, then intersperse the poster's 
response in such a way that each section of response appears directly 
after the excerpt it applies to. This reduces message bulk, keeps thread 
content in a logical order, and facilitates reading.



the best way is to excerpt only the relevent portions of the parent 
message ,not top-post nor bottom-post , right?
-- 
https://mail.python.org/mailman/listinfo/python-list


timedelta problem

2014-08-14 Thread luofeiyu

In the python doc , https://docs.python.org/3.4/library/datetime.html

A timedelta 
 
object represents a duration, the difference between two dates or times.


/class /datetime.timedelta(/days=0/, /seconds=0/, /microseconds=0/, 
/milliseconds=0/, /minutes=0/, /hours=0/, /weeks=0/)


   All arguments are optional and default to 0. Arguments may be
   integers or floats, and may be positive or negative.

   Only /days/, /seconds/ and /microseconds/ are stored internally.

import datetime
t1='Sat, 09 Aug 2014 07:36:46 -0700'
t2='Sat, 09 Aug 2014 07:36:46 +0700'
>>> datetime.datetime.strptime(t1,"%a, %d %b %Y %H:%M:%S %z")
datetime.datetime(2014, 8, 9, 7, 36, 46, 
tzinfo=datetime.timezone(datetime.timed

elta(-1, 61200)))
>>> datetime.datetime.strptime(t2,"%a, %d %b %Y %H:%M:%S %z")
datetime.datetime(2014, 8, 9, 7, 36, 46, 
tzinfo=datetime.timezone(datetime.timed

elta(0, 25200)))


problem :

t1 is GMT time   2014  00:36:46
t2 is GMT time   2014  14:36:46

datetime.datetime.strptime  do not give me the right answer.


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


timezone argument %z and %Z

2014-08-15 Thread luofeiyu
I feel it is necessary to start a new post to go on the discussion about 
timezone.


In my system : win7+ python3.4 .
related  official material.
https://docs.python.org/3.4/library/datetime.html#strftime-and-strptime
%z 	UTC offset in the form +HHMM or -HHMM (empty string if the the 
object is naive). 	(empty), +, -0400, +1030 	(6)
%Z 	Time zone name (empty string if the object is naive). 	(empty), UTC, 
EST, CST 	



1.%z  (lowercase)

import datetime
t1='Sat, 09 Aug 2014 07:36:46 -0700' # - is after  backword
t2='Sat, 09 Aug 2014 07:36:46 +0700'#+ is before   foreward
dt1=datetime.datetime.strptime(t1,"%a, %d %b %Y %H:%M:%S %z")
dt2=datetime.datetime.strptime(t2,"%a, %d %b %Y %H:%M:%S %z")
dt1.astimezone(datetime.timezone.utc)
datetime.datetime(2014, 8, 9, 14, 36, 46, tzinfo=datetime.timezone.utc)
 dt2.astimezone(datetime.timezone.utc)
datetime.datetime(2014, 8, 9, 0, 36, 46, tzinfo=datetime.timezone.utc)

%z is sovled by our community.

2.%Z  (uppercase)   Time zone name

problem 1:
There are 24 time zone in the world, does any time zone has the time 
zone name  such as EST,CST ?
Are there 24  time zone  abbreviations in python  ?what are other 22 
except for  EST ,CST ?


problem 2:
t3='Sat, 09 Aug 2014 07:36:46 EST'
dt3=datetime.datetime.strptime(t3,"%a, %d %b %Y %H:%M:%S %Z")
Traceback (most recent call last):
  File "", line 1, in 
  File "D:\Python34\lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
  File "D:\Python34\lib\_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data 'Sat, 09 Aug 2014 07:36:46 EST' does not match 
format '%a,

 %d %b %Y %H:%M:%S %Z'

does %Z  remain problem?is it a bug in python datetime module?







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


How can I get the timezone time of a location?

2014-08-17 Thread luofeiyu
The land area of China is 60-degree longitude from west to east. 
According to the demarcation of the world time zoning standard,
the land area of China lies between the eastern fifth to ninth time 
zones, there are 5 time zones in china in fact.
Currently, all the places in China have adopted the eastern eighth time 
zone for the sake of convenience. It is the so-called “/Beijing Time/”.


I knew there is a difference between localtime and timezone time.
Localtime: The official time in a local region (adjusted for location 
around the Earth); established by law or custom.
Timezone: Any of the 24 regions of the globe (loosely divided by 
longitude) throughout which the same standard time is used.
Timezone time : If location A is belong to timezone X, the time of 
timezone X is the location A 's timezone time.


For Urumqi,localtime is the time of east 8 timezone, but timezone time 
is the time of east 6 timezone.

How can I get the timezone time of urumqi with python code?

|from datetime import datetime, timedelta
from pytz import timezone
import pytz
tz = pytz.timezone('Asia/Urumqi')
dt= tz.localize(datetime(2002, 10, 27, 6, 0, 0))
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
print(dt.strftime(fmt))
2002-10-27 06:00:00 CST+0800
|

It is a wrong answer,the timezone time is 2002-10-27 04:00:00 +0600 
.|2002-10-27 06:00:00 CST+0800| is the localtime for Urumiq(by law in 
china).


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


Re: How to look up historical time zones by date and location

2014-08-17 Thread luofeiyu

http://www.thefreedictionary.com/time+zone

time zone Any of the 24 divisions of the Earth's surface used to 
determine the local time for any given locality.
Each zone is roughly 15° of longitude in width, with local variations 
for economic and political convenience.
Local time is one hour ahead for each time zone as one travels east and 
one hour behind for each time zone as one travels west.


Urumqi  's localtime is beijin time ,it is decided  by law .
Urumqi  's timezone is east 6 ,it is decided by geography.

There is only one localtime in all over the chian,beijin time,but there 
are 5  timezone time in china .


you are totally wrong ,not me .



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


Re: How to look up historical time zones by date and location

2014-08-18 Thread luofeiyu

|I found that it is a concept LMT local mean time can express my meaning.

import pytz,datetime
tz1 = pytz.timezone('Asia/Shanghai')
tz1


str(tz1)

'Asia/Shanghai'
|
||tz2 = pytz.timezone('Asia/Urumqi')|
tz2


the time difference between shanghai and Urumqi is about 2 hours in the form of 
LMT.

now ,how can i get the output of|`|LMT+8:06:00|` in||

str(tz1) or str(tz2) can not do that.

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


Re: How to look up historical time zones by date and location

2014-08-18 Thread luofeiyu
My dear  friends here, all i want is get   ` |LMT+8:06:00` from the 
output of tz1  `||`|


Shall we get back to the main point?

If you are interested in it ,please say yes or no ,and how to do that ?

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


Re: How to look up historical time zones by date and location

2014-08-18 Thread luofeiyu
My dear  friends here, all i want is get   ` LMT+8:06:00`  from the 
output of tz1  ``


Shall we get back to the main point?

If you are interested in it ,please say yes or no ,and how to do that ?


import pytz,datetime
tz1 = pytz.timezone('Asia/Shanghai')
tz1

>>> str(tz1)
'Asia/Shanghai'

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


Re: How to look up historical time zones by date and location

2014-08-19 Thread luofeiyu

>>> tz1

>>> repr(tz1)
""
>>> x=repr(tz1)
>>> x
""
>>> import re
>>> re.search("LMT.+\s",x).group()
'LMT+8:06:00 '


i got it ,thinks to all my friends .
--
https://mail.python.org/mailman/listinfo/python-list


why i can't get the sourcecode with inspect module?

2014-08-19 Thread luofeiyu

>>> import inspect
>>> def changer(x,y):
... return(x+y)
...
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__
 'changer', 'inspect']
>>> inspect.getsource(changer)
Traceback (most recent call last):
  File "", line 1, in 
  File "D:\Python34\lib\inspect.py", line 830, in getsource
lines, lnum = getsourcelines(object)
  File "D:\Python34\lib\inspect.py", line 819, in getsourcelines
lines, lnum = findsource(object)
  File "D:\Python34\lib\inspect.py", line 667, in findsource
raise OSError('could not get source code')
OSError: could not get source code
>>>
--
https://mail.python.org/mailman/listinfo/python-list


Re: How can I get the timezone time of a location?

2014-08-19 Thread luofeiyu


would you mind sending the video to my mailbox?
There is no video in the web when i open it in my firefox.

think you in advance.
 


Even with perfect knowledge, you can't always do that. There are
points on the globe which use two timezones. :)

http://pyvideo.org/video/1765/blame-it-on-caesar-what-you-need-to-know-about-d

ChrisA


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


what is the difference between name and _name?

2014-08-20 Thread luofeiyu

When i learn property in python , i was confused by somename and _somename,what 
is the difference between them?

class Person(object):
def __init__(self, name):
self._name = name
def getName(self):
print('fetch')
return self._name
def setName(self, value):
print('change...')
self._name = value
def delName(self):
print('remove')
del self._name
name = property(getName, setName, delName, "name property docs")



bob._name

'Bob'

pt=Person("peter")
pt.name

fetch
'peter'

pt._name

'peter'

pt.name="tom"

change...

pt._name="tom"
pt._name

'tom'

pt.name

fetch
'tom'

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


why no 2to3 in my python?

2014-08-20 Thread luofeiyu

why no 2to3 in my python34,how can i change python 2 into python3?
>dir d:\Python34\Scripts
 Volume in drive D is soft
 Volume Serial Number is 6F34-9A10

 Directory of d:\Python34\Scripts

08/18/2014  09:06 AM  .
08/18/2014  09:06 AM  ..
07/09/2014  09:01 AM95,064 actdiag.exe
07/09/2014  09:00 AM95,066 blockdiag.exe
06/14/2014  05:25 PM   333 easy_install-3.4-script.py
06/14/2014  05:25 PM74,752 easy_install-3.4.exe
06/14/2014  05:25 PM   325 easy_install-script.py
06/14/2014  05:25 PM74,752 easy_install.exe
05/24/2014  07:06 AM   709 f2py.py
08/04/2014  10:58 AM10,119 google.py
07/09/2014  09:02 AM95,063 nwdiag.exe
07/09/2014  09:02 AM95,067 packetdiag.exe
07/09/2014  09:00 AM 2,337 pilconvert.py
07/09/2014  09:00 AM15,604 pildriver.py
07/09/2014  09:00 AM 2,582 pilfile.py
07/09/2014  09:00 AM 1,028 pilfont.py
07/09/2014  09:00 AM 2,383 pilprint.py
08/04/2014  04:04 PM 0 pip
05/17/2014  04:01 AM   286 pip-script.py
05/17/2014  04:01 AM74,752 pip.exe
05/17/2014  04:01 AM   288 pip3-script.py
05/17/2014  04:01 AM   292 pip3.4-script.py
05/17/2014  04:01 AM74,752 pip3.4.exe
05/17/2014  04:01 AM74,752 pip3.exe
07/08/2014  03:51 PM   321 pygmentize-script.py
07/08/2014  03:51 PM74,752 pygmentize.exe
03/17/2014  10:22 AM78,848 python3.dll
07/09/2014  09:02 AM95,065 rackdiag.exe
07/08/2014  03:52 PM   600 rst2html.py
07/08/2014  03:52 PM   797 rst2latex.py
07/08/2014  03:52 PM   606 rst2man.py
07/08/2014  03:52 PM   770 rst2odt.py
07/08/2014  03:52 PM 1,704 rst2odt_prepstyles.py
07/08/2014  03:52 PM   607 rst2pseudoxml.py
07/08/2014  03:52 PM   643 rst2s5.py
07/08/2014  03:52 PM   792 rst2xetex.py
07/08/2014  03:52 PM   608 rst2xml.py
07/08/2014  03:52 PM   676 rstpep2html.py
07/09/2014  09:01 AM95,064 seqdiag.exe
07/08/2014  03:51 PM95,062 sphinx-apidoc.exe
07/08/2014  03:51 PM95,080 sphinx-autogen.exe
07/08/2014  03:51 PM95,055 sphinx-build.exe
07/08/2014  03:51 PM95,066 sphinx-quickstart.exe
07/09/2014  10:05 PM95,059 virtualenv-2.7.exe
05/17/2014  04:03 AM   332 virtualenv-3.4-script.py
05/17/2014  04:03 AM74,752 virtualenv-3.4.exe
05/17/2014  04:03 AM   324 virtualenv-script.py
05/17/2014  04:03 AM74,752 virtualenv.exe
08/18/2014  09:06 AM  __pycache__
  46 File(s)  1,767,641 bytes
   3 Dir(s)   5,010,251,776 bytes free

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


Re: what is the difference between name and _name?

2014-08-20 Thread luofeiyu

So in this example:

class Person(object):
  def __init__(self, name):
  self._name = name

[...]

  name = property(getName, setName, delName, "name property docs")



(3) name is the public attribute that other classes or functions are
permitted to use.


problem 1:  there is no self.name =  something in the defination ,why i can get 
bob.name?



class Person(object):
def __init__(self, name):
self._name = name
def getName(self):
print('fetch')
return self._name
def setName(self, value):
print('change...')
self._name = value
def delName(self):
print('remove')
del self._name
name = property(getName, setName, delName, "name property docs")

>>> bob=Person("dear bob")
>>> bob._name  # there is a defination in class Person ,self._name = 
name ,when we initial it ,we can get bob._name

'dear bob'
>>> bob.name  #there is no defination in class Person ,self.name=name 
,why we can get the value of bob.name?

fetch
'dear bob'


problem 2: what is the meaning of

name = property(getName, setName, delName, "name property docs")?

why i can not write  _name = property(getName, setName, delName, "name property 
docs") ?


 class Person(object):

def __init__(self, name):

self._name = name

def getName(self):

print('fetch')

return self._name

def setName(self, value):

print('change...')

self._name = value

def delName(self):

print('remove')

del self._name

_name = property(getName, setName, delName, "name property docs")

bob=Person("dear bob")

I got error from the codes:

  File "", line 9, in setName
  File "", line 8, in setName
RuntimeError: maximum recursion depth exceeded while calling a Python object

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


how to copy emails into local directory?

2014-08-20 Thread luofeiyu

import imaplib,email
user=""
password=""
con=imaplib.IMAP4_SSL('imap.gmail.com')
con.login(user,password)
con.list()
('OK', [b'(\\HasNoChildren) "/" "INBOX"', b'(\\Noselect \\HasChildren) 
"/" "[Gma
il]"', b'(\\HasNoChildren \\Junk) "/" "[Gmail]/&V4NXPpCuTvY-"', 
b'(\\HasNoChildr
en \\Trash) "/" "[Gmail]/&XfJSIJZkkK5O9g-"', b'(\\HasNoChildren 
\\Flagged) "/" "
[Gmail]/&XfJSoGYfaAc-"', b'(\\HasNoChildren \\Sent) "/" 
"[Gmail]/&XfJT0ZCuTvY-"'
, b'(\\HasNoChildren \\All) "/" "[Gmail]/&YkBnCZCuTvY-"', 
b'(\\HasNoChildren \\D
rafts) "/" "[Gmail]/&g0l6Pw-"', b'(\\HasNoChildren \\Important) "/" 
"[Gmail]/&kc

2JgQ-"'])

Now, i want to  copy all the emails in the gmailbox of
"[Gmail]/&kc2JgQ-"  (the important mailbox in my gmail"
into local directory  "g:\emails",how can i do that in python code?
--
https://mail.python.org/mailman/listinfo/python-list


Re: How can I get the timezone time of a location?

2014-08-20 Thread luofeiyu
it is so sorry to tell you that youtube was banned by chinese government 
for about 6 years , everyone in china can not open


https://www.youtube.com  .


https://www.youtube.com/watch?v=GBKqRhn0ekM


The page describing the video also has a link to the hosted site of the
video, see the “Video origin” field to the right side of that page.



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


Re: what is the difference between name and _name?

2014-08-20 Thread luofeiyu

one more question,how can i get the doc info?

class Person(object):
def __init__(self, name):
self._name = name
def getName(self):
print('fetch')
return self._name
def setName(self, value):
print('change...')
self._name = value
def delName(self):
print('remove')
del self._name
name = property(getName, setName, delName, "name property docs")

Person("bob").name.doc
Person("bob").name.__doc__
Person("bob")._name.doc
Person("bob")._name.__doc__

all the expressions can not get the info "name property docs" ?how can i 
get it?


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


Distinguishing attribute name from varible name to make codes clear and definite

2014-08-21 Thread luofeiyu

I feel that self.x and x will be confused in the following codes.

class MyDescriptor(object):
 def __init__(self, x):
 self.x = x
 def __get__(self, instance, owner):
 print('get from descriptor')
 return self.x
 def __set__(self, instance, value):
 print('set from descriptor')
 self.x = value
 def __delete__(self, instance):
 print('del from descriptor, the val is', self.x)

exam=MyDescriptor("hallo")


when class MyDescriptor  initiate , the `hallo` was passed into x in 
__init__(self, x);
Literally  self.x maybe understood to be self.hallo ,assign a attribute 
named 'hallo' to instance exam.

It is a better way to replace self.x to self.y .

class MyDescriptor(object):
 def __init__(self, x):
 self.y = x
 def __get__(self, instance, owner):
 print('get from descriptor')
 return self.y
 def __set__(self, instance, value):
 print('set from descriptor')
 self.y = value
 def __delete__(self, instance):
 print('del from descriptor, the val is', self.y)
exam=MyDescriptor("hallo")


There is a attribute y  in instance exam , the `hallo` was passed into x 
in __init__(self, x).No any relation between x and y ,`hallo` and y.

My view is correct or not ?
--
https://mail.python.org/mailman/listinfo/python-list


Re: what do you get with 1 divide by 998001, interesting results

2014-08-21 Thread luofeiyu
This man is  crazy , he go on to send rubbish to waste our time ,i 
strongly strongly advise that python maillist administrator kick him off 
here.



On 8/21/2014 9:25 PM, Everything You Need To Know wrote:

On Thursday, 21 August 2014 01:06:37 UTC+9:30, Everything You Need To Know  
wrote:

These exercises were all linked together to make a 'python' board game, Thought 
it was really neat myself. This is something that would not interest this Forum 
I am to presume?

Thank you

Adam A


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


the output in reference of descriptor.

2014-08-21 Thread luofeiyu

 class C(object):
a = 'abc'
def __getattribute__(self, *args, **kwargs):
print("__getattribute__() is called")
return object.__getattribute__(self, *args, **kwargs)
def __getattr__(self, name):
print("__getattr__() is called ")
return name + " from getattr"
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self
def foo(self, x):
print(x)


class C2(object):
d = C()


>>> c2.d
__get__() is called <__main__.C2 object at 0x0297BE10> '__main__.

C2'>
<__main__.C object at 0x0297BBA8>

I understant the result ,c2.d trigger the __get__ method in class C.
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self

It print "__get__() is called", instance, owner and return self 
`<__main__.C object at 0x0297BBA8>`



>>> c2.d.a
__get__() is called <__main__.C2 object at 0x0297BE10> '__main__.

C2'>
__getattribute__() is called
'abc'

Why the result of c2.d.a  is not :

__get__() is called <__main__.C2 object at 0x0297BE10> '__main__.

C2'>
__getattribute__() is called
'abc'

Why the` return self` in the __get__ method in class C  does not work?

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


Re: what is the difference between name and _name?

2014-08-21 Thread luofeiyu

I fix a mistake in Steven D'Aprano interpretation.

class Person(object):
 def __init__(self, name):
 self._name = name
 def getName(self):
 print('fetch')
 return self._name
 def setName(self, value):
 print('change...')
 self._name = value
 def delName(self):
 print('remove')
 del self._name
 _name = property(getName, setName, delName, "name property docs")


x=Person("peter")

It can not initinalize.
  File "", line 9, in setName
  File "", line 8, in setName
RuntimeError: maximum recursion depth exceeded while calling a Python 
object.


Steven D'Aprano interpretation:

10 Python finds the property _name
20 Python retrieves the getter, getName
30 Python runs the getName() method
40 which looks up self._name
50 go to 10

the right interpretation according to the error message:


10 python call __init__ method. self._name = name
20 python call setName method,
 print('change...')
 self._name = value
30 from self._name = value ,python call call setName method again

then we get a recursion error.

why i can not write  _name = property(getName, setName, delName, "name
property docs") ?

Because you will have infinite recursion.

When you look up instance._name:

10 Python finds the property _name
20 Python retrieves the getter, getName
30 Python runs the getName() method
40 which looks up self._name
50 go to 10

and you get a recursion error.





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


when the method __get__ will be called?

2014-08-22 Thread luofeiyu

class C(object):
a = 'abc'
def __getattribute__(self, *args, **kwargs):
print("__getattribute__() is called")
return object.__getattribute__(self, *args, **kwargs)
def __getattr__(self, name):
print("__getattr__() is called ")
return name + " from getattr"
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self
def foo(self, x):
print(x)


>>> x=C()
>>> x.a
__getattribute__() is called
'abc'
>>> x.b
__getattribute__() is called
__getattr__() is called
'b from getattr'




If call an attribute which does exist ,__getattribute__() is called
If call an attribute which does not  exist ,__getattribute__() is called
and then __getattr__() is called ?

when the __get__ method will be called?no chance for my example?
--
https://mail.python.org/mailman/listinfo/python-list


Why can not initialize the class?

2014-08-22 Thread luofeiyu

System:win7+python34.

class Contact(object):
def __init__(self, first_name=None, last_name=None,
 display_name=None, email=None):
self.first_name = first_name
self.last_name = last_name
self.display_name = display_name
self.email = email
def print_info(self):
print(self.display_name, "<" + self.email + ">"  )
def set_email(self, value):
if '@' not in value:
raise Exception("This doesn't look like an email address.")
self._email = value
def get_email(self):
return self._email
email = property(get_email, set_email)

contact = Contact()

The error message is :
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 7, in __init__
  File "", line 11, in set_email
TypeError: argument of type 'NoneType' is not iterable

What is wrong with the code?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Why can not initialize the class?

2014-08-22 Thread luofeiyu

how to fix the code then?
On 8/22/2014 10:36 PM, Larry Martell wrote:
The 'in' operator requires an iterable. When you do 'self.email = 
email' set_email gets called and value is None. 


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


Re: Why can not initialize the class?

2014-08-22 Thread luofeiyu

>>> class Contact(object):
... def __init__(self, first_name=None, last_name=None,
...  display_name=None, email="haha@haha"):
... self.first_name = first_name
... self.last_name = last_name
... self.display_name = display_name
... self.email = email
... def print_info(self):
... print(self.display_name, "<" + self.email + ">"  )
... def set_email(self, value):
... print(value)
... self._email = value
... def get_email(self):
... return self._email
... email = property(get_email, set_email)
...
>>>
>>> contact = Contact()
haha@haha

why the value in `def set_email(self, value): `  is  haha@haha?
how haha@haha  is called to  value in `def set_email(self, value): `?
would you mind telling me the process?






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


Re: Why can not initialize the class?

2014-08-22 Thread luofeiyu

One final version:

class Contact(object):
def __init__(self, email="haha@haha"):
self.email = email
def _get_email(self):
return self._the_secret_private_email
def _set_email(self, value):
self.self._the_secret_private_email = value
email = property(_get_email, _set_email)

contact = Contact()
print(contact.email)

There is a little mistake here. It is

self._the_secret_private_email = value

not

self.self._the_secret_private_email = value

think for your demo .The value in `def _set_email(self, value):` is the value 
of self.email .


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


Re: Why can not initialize the class?

2014-08-23 Thread luofeiyu
I edit it in the vim in well formatted form,when copied into email ,the 
format changed ,i don't know why.

My email editor is thunderbird, you can try it as i say.

I didn't mean to .


By posting code with an extra indent, you make it imposible to run by 
just cutting and pasting. You should already know that.




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


Re: Why can not initialize the class?

2014-08-23 Thread luofeiyu



You can copy it into vim,and input  :%<  ,the codes  will be changed 
into well formatted.
-- 
https://mail.python.org/mailman/listinfo/python-list


why the attribute be deleted still in dir(man)?

2014-08-23 Thread luofeiyu

class Person(object):
   def addProperty(self, attribute):
  getter = lambda self: self._getProperty(attribute)
  setter = lambda self, value: self._setProperty(attribute, 
value)

  deletter = lambda self:self.delProperty(attribute)
  setattr(self.__class__, attribute, 
property(fget=getter,fset=setter,fdel=deletter,doc="Auto-generated method"))

   def _setProperty(self, attribute, value):
 setattr(self, '_' + attribute, value.title())
  def _getProperty(self, attribute):
return getattr(self, '_' + attribute)
  def delProperty(self,attribute):
delattr(self,'_' + attribute)

>>> man=Person()
>>> dir(man)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__form
at__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__le__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__
repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref_

_', '_getProperty', '_setProperty', 'addProperty', 'delProperty']
>>> man.addProperty("name")
>>> man.name="john"
>>> dir(man)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__form
at__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__le__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__
repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref_
_', '_getProperty', '_name', '_setProperty', 'addProperty', 
'delProperty', 'name

']
>>> man.name
'John'
>>> man.delProperty("name")
>>> man.name
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in 
  File "", line 12, in _getProperty
AttributeError: 'Person' object has no attribute '_name'
>>> dir(man)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__form
at__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__le__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__
repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref_

_', '_getProperty', '_setProperty', 'addProperty', 'delProperty', 'name']


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


Re: why the attribute be deleted still in dir(man)?

2014-08-23 Thread luofeiyu
dear ChrisA ,dynamic is python feature, it is to create descriptor in 
run time ,

that is the meaning in the codes,and maybe it is a bug:

the attribute  can be displayed  in dir(man)  after be deleted.




On 8/24/2014 6:56 AM, Chris Angelico wrote:

On Sun, Aug 24, 2014 at 8:49 AM, luofeiyu  wrote:

class Person(object):
def addProperty(self, attribute):
   getter = lambda self: self._getProperty(attribute)
   setter = lambda self, value: self._setProperty(attribute,
value)
   deletter = lambda self:self.delProperty(attribute)
   setattr(self.__class__, attribute,
property(fget=getter,fset=setter,fdel=deletter,doc="Auto-generated method"))
def _setProperty(self, attribute, value):
  setattr(self, '_' + attribute, value.title())
   def _getProperty(self, attribute):
 return getattr(self, '_' + attribute)
   def delProperty(self,attribute):
 delattr(self,'_' + attribute)

Look. Forget properties. Python is not Java or C++, and you almost
never need this kind of thing. Read up a tutorial on doing classes
Python's way, and you'll find that all this sort of thing just doesn't
matter. You've come here with a significant number of questions about
properties, and it looks as if you're trying to do everything through
them - which is utterly and completely useless, especially when you
use properties to be as dynamic as you're doing. Just don't do it.

ChrisA


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


Re: why the attribute be deleted still in dir(man)?

2014-08-23 Thread luofeiyu
Think for your  remark " You didn't delete the name property, which is 
part of the class, not the instance."

I fix my codes to get the target done.

class Person(object):
   def addProperty(self, attribute):
  getter = lambda self: self._getProperty(attribute)
  setter = lambda self, value: self._setProperty(attribute, 
value)

  deletter = lambda self:self.delProperty(attribute)
  setattr(self.__class__, attribute, 
property(fget=getter,fset=setter,fdel=deletter,doc="Auto-generated method"))

def _setProperty(self, attribute, value):
  setattr(self, '_' + attribute, value.title())
def _getProperty(self, attribute):
   return getattr(self, '_' + attribute)
def delProperty(self,attribute):
   delattr(self,'_' + attribute)
   delattr(self.__class__, attribute)

I am so happy .



> >>> man.delProperty("name")
> >>> man.name 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 4, in 
>   File "", line 12, in _getProperty
> AttributeError: 'Person' object has no attribute '_name'
> >>> dir(man)
> ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', 
'__eq__', '__form
> at__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__le__',
>  '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__
> repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref_
> _', '_getProperty', '_setProperty', 'addProperty', 'delProperty', 
'name']


You deleted the _name attribute where you're storing the value of the 
name property. You didn't delete the name property, which is part of 
the class, not the instance.





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


Re: the output in reference of descriptor.

2014-08-23 Thread luofeiyu

let me paste it again to make my question more clear:

>>>c2.d
__get__() is called <__main__.C2 object at 0x0297BE10> 


<__main__.C object at 0x0297BBA8>

>>> c2.d.a
__get__() is called <__main__.C2 object at 0x0297BE10> 


__getattribute__() is called
'abc'

Why the result of c2.d.a  is not :

__get__() is called <__main__.C2 object at 0x0297BE10> 


<__main__.C object at 0x0297BBA8>
__getattribute__() is called
'abc'

Why the` return self` in the __get__ method in class C  does not work? 
Why there is no <__main__.C object at 0x0297BBA8>  in the output?



and the source code are:


|class C(object):
a = 'abc'
def __getattribute__(self, *args, **kwargs):
print("__getattribute__() is called")
return object.__getattribute__(self, *args, **kwargs)
def __getattr__(self, name):
print("__getattr__() is called ")
return name + " from getattr"
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self
def foo(self, x):
print(x)


class C2(object):
d = C()


|


On 8/23/2014 12:10 PM, Ian Kelly wrote:
On Thu, Aug 21, 2014 at 7:25 PM, luofeiyu <mailto:[email protected]>> wrote:

> >>> c2.d.a
> __get__() is called <__main__.C2 object at 0x0297BE10> 

> C2'>
> __getattribute__() is called
> 'abc'
>
> Why the result of c2.d.a  is not :
>
> __get__() is called <__main__.C2 object at 0x0297BE10> 

> C2'>
> __getattribute__() is called
> 'abc'

As far as I can tell you pasted the same output twice, so I don't 
understand what it is that you're asking.







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


sqlite3.OperationalError: near ".": syntax error

2014-09-19 Thread luofeiyu

C:\Users\pengsir>sqlite3 F:\\workspace\\china\\data\\china.sqlite
SQLite version 3.8.5 2014-06-04 14:06:34
Enter ".help" for usage hints.
sqlite> .tables
balance   cash  fi_di ipo   profile   quote
capital   dividend  fund  majority  profit
sqlite>

import slqite3
con = sqlite3.connect('F:\\workspace\\china\\data\\china.sqlite')
cur = con.cursor()
cur.execute('.tables')


Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near ".": syntax error


why  can't get the  right tables  in  "  cur.execute('.tables')"  ?
--
https://mail.python.org/mailman/listinfo/python-list


sqlite3.OperationalError: near ".": syntax error

2014-09-19 Thread luofeiyu

C:\Users\pengsir>d:\\sqlite3 F:\\workspace\\china\\data\\china.sqlite
SQLite version 3.8.5 2014-06-04 14:06:34
Enter ".help" for usage hints.
sqlite> .tables
balance   cash  fi_di ipo   profile   quote
capital   dividend  fund  majority  profit
sqlite>

import slqite3
con = sqlite3.connect('F:\\workspace\\china\\data\\china.sqlite')
cur = con.cursor()
cur.execute('.tables')


Traceback (most recent call last):
  File "", line 1, in 
sqlite3.OperationalError: near ".": syntax error


why " cur.execute('.tables')  "  can't  get output?
--
https://mail.python.org/mailman/listinfo/python-list


how to write a html to automatically display the dictionary?

2014-09-23 Thread luofeiyu

x={'f1':1,'f2':2,'f3':3}
how can i create the following html file automatically with python to 
display x ?





f1


f2


f3



1


2


3




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


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread luofeiyu

how can i  create the proper html file with /Jinjia/2 or other temple?

Joel Goldstick wrote:
Generally, you would use a framework like django or others.

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


how to display the result in table with jinkoa2 temple?

2014-09-24 Thread luofeiyu

import sqlite3
db=r'F:\workspace\china\data\china.sqlite'
con=sqlite3.connect(db)
cur=con.cursor()
res=cur.execute('select 代码,所属行业,注册资本,雇员人数,管理人员人数 
from profile limit 20').fetchall()


the result is a list.

>>> for row in res:
... print(row)
...
('60', '银行', '187亿', 39340.0, 30.0)
('64', '民航机场', '11.5亿', 4499.0, 23.0)
('65', '钢铁行业', '101亿', 38857.0, 24.0)
('66', '汽车行业', '20.0亿', 10290.0, 20.0)
('67', '房地产', '10.1亿', 2332.0, 19.0)
('68', '公用事业', '22.0亿', 6515.0, 20.0)
('69', '民航机场', '19.3亿', 5472.0, 18.0)
('600010', '钢铁行业', '80.0亿', 31389.0, 19.0)
('600011', '电力行业', '141亿', 37729.0, 29.0)
('600012', '高速公路', '16.6亿', 2106.0, 14.0)
('600015', '银行', '89.0亿', 25200.0, 34.0)
('600016', '银行', '340亿', 54927.0, 32.0)
('600017', '港口水运', '30.8亿', 5340.0, 21.0)
('600018', '港口水运', '228亿', 19842.0, 20.0)
('600019', '钢铁行业', '165亿', 37487.0, 23.0)
('600020', '高速公路', '22.5亿', 2959.0, 32.0)
('600021', '电力行业', '21.4亿', 6673.0, 22.0)
('600022', '钢铁行业', '64.4亿', 31738.0, 20.0)
('600023', '电力行业', '118亿', 10142.0, 14.0)
('600026', '港口水运', '34.0亿', 7536.0, 21.0)
>>>

i want to display it in html table .

html_str=''
for row in res:
html_str=html_str+''
for col in row:
html_str=html_str+''+str(col).replace('\s','')
html_str=html_str+''
html_str=html_str+''

html_str=html_str+''
myhtml=open('f:\\test.html','w')
myhtml.write(html_str)
myhtml.close()

when i open 'f:\\test.html'  in chrome ,



how can i change my code more elegantly with temple jinjia2 to do the 
same display ?





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


why can't open the file with browser?

2014-09-24 Thread luofeiyu

|
import webbrowser
webbrowser.open('f:\\test.html')

why the file f:\\test.html is opened by notepad ,not by my firefox or chrome?


|

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


how to make return(self.res) not to output the content of list ?

2014-09-24 Thread luofeiyu

There is a file named analyse.py in the D:\Python34\Lib\site-packages.


import sqlite3,os,jinja2
db = r'F:\workspace\china\data\china.sqlite'
con = sqlite3.connect(db)
cur = con.cursor()

class status():
def grow(self):
self.res=cur.execute('select 代码,所属行业,注册资本,雇员人数,管 
理人员人数 from profile limit 10').fetchall()


def display(self):
template = jinja2.Template('''

{% for row in res %}

{% for col in row -%}
{{ col}}
{% endfor %}

{% endfor %}

''')
with open('f:\\test.html', 'w') as f:
 f.write(template.render(res=self.res))
import webbrowser
webbrowser.open('f:\\test.html')


when i open python3.4  console to input  the code:
import analyse
x=analyse.status()
x.grow()
x.display()

i get


when i add  return(self.res) in grow method to make analyse.py into the 
following:


import sqlite3,os,jinja2
db = r'F:\workspace\china\data\china.sqlite'
con = sqlite3.connect(db)
cur = con.cursor()

class status():
def grow(self):
self.res=cur.execute('select 代码,所属行业,注册资本,雇员人数,管 
理人员人数 from profile limit 10').fetchall()

return(self.res)
def display(self):
template = jinja2.Template('''

{% for row in res %}

{% for col in row -%}
{{ col}}
{% endfor %}

{% endfor %}

''')
with open('f:\\test.html', 'w') as f:
 f.write(template.render(res=self.res))
import webbrowser
webbrowser.open('f:\\test.html')


now again input the code:
import analyse
x=analyse.status()
x.grow()
the x.grow() will output

[('60', '银行', '187亿', 39340.0, 30.0),
('64', '民航机场', '11.5亿', 4499.0, 23.0),
 ('65', '钢铁行业', '101亿', 38857.0, 24.0),
('66', '汽车行业', '20.0亿', 10290.0, 20.0),
('67', '房地产', '10.1亿', 2332.0, 19.0),
 ('68', '公用事业', '22.0亿', 6515.0, 20.0),
('69', '民航机场', '19.3亿', 5472.0, 18.0),
('600010', '钢铁行业', '80.0亿', 31389.0, 19.0),
('600011', '电力行业', '141亿', 37729.0, 29.0),
('600012', '高速公路', '16.6亿', 2106.0, 14.0)]

now what i want to do is :
1.keep  return(self.res)  in grow method.
2.it is my target that when run  the code:

import analyse
x=analyse.status()
x.grow()

there is nothing output in my console ,  to make return(self.res) not to 
output the content of list ,

how can i do ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to make return(self.res) not to output the content of list ?

2014-09-24 Thread luofeiyu

`sys.displayhook = lambda obj: None ` will block everything to be displayed on 
the interactive python console .

i rewrite my code as the following :

import sqlite3,os,jinja2
db = r'data.sqlite'
con = sqlite3.connect(db)
cur = con.cursor()

class status():
 def __init__():
 import sys
 sys.displayhook=mydisplay
 
 def mydisplay(x):

 if (x is not the result of an method grow of class status ) : x  #how 
to do in python code?
 else : pass
 
 def grow(self):

 self.res=  a data ananlyse process
 return(self.res)

 def display(self):

 #to display it in the html table



how to fulfill the mydisplay function in python code to make x.grow() in the 
following not to output the list of self.res??


import analyse
x=analyse.status()
x.grow()


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


Re: how to make return(self.res) not to output the content of list ?

2014-09-24 Thread luofeiyu


You could write a separate method that just calls self.grow() and does 
not return the result, and call that method instead from the interactive 
interpreter.


how can i change your meaning into python code?

There is my code structure.

class status():
 def grow(self):
 self.res=  a data ananlyse process
 return(self.res)

def display(self):
 #to display it in the html table

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