Hotspot Locater

2015-06-18 Thread admin.dslcomputer

Hi everyone:




There is interest in our group in the development of Python code to locate WiFi 
hotspots.




My question: Is there a Python solution in the location of WiFi hotspots?




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


Get off the list

2015-06-18 Thread Deogratius Musiige
Hi,
How can i get off this mailing list?

Best regards / Med venlig hilsen

Deogratius Musiige
Software Development Engineer

Sennheiser Communications A/S
Industriparken 27
DK-2750 Ballerup

Direct  +45 5618 0320
Mail d...@senncom.com
Webwww.sennheiser.com



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


Re: JSON Object to CSV file

2015-06-18 Thread Sahlusar
On Wednesday, June 17, 2015 at 2:21:05 PM UTC-4, Peter Otten wrote:
> Sahlusar wrote:
> 
> > On Wednesday, June 17, 2015 at 11:00:24 AM UTC-4, Saran A wrote:
> >> I would like to have this JSON object written out to a CSV file so that
> >> the keys are header fields (for each of the columns) and the values are
> >> values that are associated with each header field. Is there a best
> >> practice for working with this? Ideally I would like to recursively
> >> iterate through the key value pairs. Thank you in advance. I am using
> >> Python 3.4 on Windows. My editor is Sublime 2.
> >> 
> >> {
> >> "CF": {
> >> "A": "5",
> >> "FEC": "1/1/0001 12:00:00 AM",
> >> "TE": null,
> >> "Locator": null,
> >> "Message": "Transfer Fee",
> >> "AT": null,
> >> "FT": null,
> >> "FR": "True",
> >> "FY": null,
> >> "FR": null,
> >> "FG": "0",
> >> "Comment": null,
> >> "FUD": null,
> >> "cID": null,
> >> "GEO": null,
> >> "ISO": null,
> >> "TRID": null,
> >> "XTY": "931083",
> >> "ANM": null,
> >> "NM": null
> >> },
> >> "CF": "Fee",
> >> "ID": "2"
> >> }
> > 
> > My apologies:
> > 
> > I originally parsed this from an XML file.
> > 
> > It really should be:
> > 
> > {
> > "Fee": {
> > "A": "5",
> > "FEC": "1/1/0001 12:00:00 AM",
> > "TE": null,
> > "Locator": null,
> > "Message": "Transfer Fee",
> > "AT": null,
> > "FT": null,
> > "FR": "True",
> > "FY": null,
> > "FR": null,
> > "FG": "0",
> > "Comment": null,
> > "FUD": null,
> > "cID": null,
> > "GEO": null,
> > "ISO": null,
> > "TRID": null,
> > "XTY": "931083",
> > "ANM": null,
> > "NM": null
> > },
> > "CF": "Fee",
> > "ID": "2"
> > }
> > 
> > The value, "Fee" associated with the key, "CF" does should not be included
> > as a column header.
> > 
> > The CSV file, when opened with an application such as MS Excel, should be
> > as follows:
> > 
> > (Column Header)> CF   A  FEC
> > 
> > (Field Value)>   Fee  51/1/0001 12:00:00 AM
> > 
> > My apologies for an confusion.
> 
> Forget about Excel, what should the CSV look like when opened in a text 
> editor?
> 
> Here's my guess:
> 
> 
> $ cat input.json
> {
> "Fee": {
> "A": "5",
> "FEC": "1/1/0001 12:00:00 AM",
> "TE": null,
> "Locator": null,
> "Message": "Transfer Fee",
> "AT": null,
> "FT": null,
> "FR": "True",
> "FY": null,
> "FR": null,
> "FG": "0",
> "Comment": null,
> "FUD": null,
> "cID": null,
> "GEO": null,
> "ISO": null,
> "TRID": null,
> "XTY": "931083",
> "ANM": null,
> "NM": null
> },
> "CF": "Fee",
> "ID": "2"
> }
> $ cat json2csv.py
> import csv
> import json
> import sys
> 
> def hook(obj):
> return obj
> 
> def flatten(obj):
> for k, v in obj:
> if isinstance(v, list):
> yield from flatten(v)
> else:
> yield k, v
> 
> if __name__ == "__main__":
> with open("input.json") as f:
> data = json.load(f, object_pairs_hook=hook)
> 
> pairs = list(flatten(data))
> 
> writer = csv.writer(sys.stdout)
> writer.writerow([k for k, v in pairs])
> writer.writerow([v for k, v in pairs])
> $ python3 json2csv.py 
> A,FEC,TE,Locator,Message,AT,FT,FR,FY,FR,FG,Comment,FUD,cID,GEO,ISO,TRID,XTY,ANM,NM,CF,ID
> 5,1/1/0001 12:00:00 AM,,,Transfer Fee,,,True,,,0,,,931083,,,Fee,2
> 
> But do you really want duplicate column names?

@Peter Otten: Thank you for your feedback. No, I do not want to have 
duplicates. Any thoughts on how to avoid this?
-- 
https://mail.python.org/mailman/listinfo/python-list


JSON Object to CSV Question

2015-06-18 Thread Saran Ahluwalia
Good Evening Everyone:

I would like to have this JSON object written out to a CSV file so that the
keys are header fields (for each of the columns) and the values are values
that are associated with each header field. Is there a best practice for
working with this? Ideally I would like to recursively iterate through the
key value pairs. Thank you in advance. I am using Python 3.4 on Windows. My
editor is Sublime 2.

Here is the JSON object:

{
"Fee": {
"A": "5",
"FEC": "1/1/0001 12:00:00 AM",
"TE": null,
"Locator": null,
"Message": "Transfer Fee",
"AT": null,
"FT": null,
"FR": "True",
"FY": null,
"FR": null,
"FG": "0",
"Comment": null,
"FUD": null,
"cID": null,
"GEO": null,
"ISO": null,
"TRID": null,
"XTY": "931083",
"ANM": null,
"NM": null
},
"CF": "Fee",
"ID": "2"
}

The value, "Fee" associated with the key, "CF" should not be included as a
column header (only as a value of the key "CF").

Other than the former, the keys should be headers and the corresponding
tuples - the field values.

In essence, my goal is to the following:

You get a dictionary object (the "outer" dictionary)
You get the data from the "CF" key (fixed name?) which is a string ("Fee" in
your example)
You use that value as a key to obtain another value from the same "outer"
dictionary, which should be a another dictionary (the "inner" dictionary)
You make a CSV file with:

   - a header that contains "CF" plus all keys in the "inner" dictionary
   that have an associated value
   - the value from key "CF" in the "outer" dictionary plus all non-null
   values in the "inner" dictionary.

I have done the following:

import csv
import json
import sys

def hook(obj):
return obj

def flatten(obj):
for k, v in obj:
if isinstance(v, list):
yield from flatten(v)
else:
yield k, v

if __name__ == "__main__":
with open("data.json") as f:
data = json.load(f, object_pairs_hook=hook)

pairs = list(flatten(data))

writer = csv.writer(sys.stdout)
writer.writerow([k for k, v in pairs])
writer.writerow([v for k, v in pairs])

The output is as follows:

$ python3 json2csv.py
A,FEC,TE,Locator,Message,AT,FT,FR,FY,FR,FG,Comment,FUD,
cID,GEO,ISO,TRID,XTY,ANM,NM,CF,ID
5,1/1/0001 12:00:00 AM,,,Transfer Fee,,,True,,,0,,,931083,,,Fee,2

I do not want to have duplicate column names.

Any advice on other best practices that I may utilize?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Get off the list

2015-06-18 Thread Cecil Westerhof
On Wednesday 17 Jun 2015 09:09 CEST, Deogratius Musiige wrote:

> How can i get off this mailing list? 

Looking at the headers:
List-Unsubscribe: ,
 

So I would send an email with the email account you are subscribed to
the list, with the subject ‘unsubscribe’.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV Question

2015-06-18 Thread Peter Otten
Saran Ahluwalia wrote:

> Good Evening Everyone:
> 
> I would like to have this JSON object written out to a CSV file so that
> the keys are header fields (for each of the columns) and the values are
> values that are associated with each header field. Is there a best
> practice for working with this? Ideally I would like to recursively
> iterate through the key value pairs. Thank you in advance. I am using
> Python 3.4 on Windows. My editor is Sublime 2.
> 
> Here is the JSON object:
> 
> {
> "Fee": {
> "A": "5",
> "FEC": "1/1/0001 12:00:00 AM",
> "TE": null,
> "Locator": null,
> "Message": "Transfer Fee",
> "AT": null,
> "FT": null,
> "FR": "True",
> "FY": null,
> "FR": null,
> "FG": "0",
> "Comment": null,
> "FUD": null,
> "cID": null,
> "GEO": null,
> "ISO": null,
> "TRID": null,
> "XTY": "931083",
> "ANM": null,
> "NM": null
> },
> "CF": "Fee",
> "ID": "2"
> }
> 
> The value, "Fee" associated with the key, "CF" should not be included as a
> column header (only as a value of the key "CF").
> 
> Other than the former, the keys should be headers and the corresponding
> tuples - the field values.
> 
> In essence, my goal is to the following:
> 
> You get a dictionary object (the "outer" dictionary)
> You get the data from the "CF" key (fixed name?) which is a string ("Fee"
> in your example)
> You use that value as a key to obtain another value from the same "outer"
> dictionary, which should be a another dictionary (the "inner" dictionary)
> You make a CSV file with:
> 
>- a header that contains "CF" plus all keys in the "inner" dictionary
>that have an associated value
>- the value from key "CF" in the "outer" dictionary plus all non-null
>values in the "inner" dictionary.
> 
> I have done the following:

For some value of "I" :(
> 
> import csv
> import json
> import sys
> 
> def hook(obj):
> return obj
> 
> def flatten(obj):
> for k, v in obj:
> if isinstance(v, list):
> yield from flatten(v)
> else:
> yield k, v
> 
> if __name__ == "__main__":
> with open("data.json") as f:
> data = json.load(f, object_pairs_hook=hook)
> 
> pairs = list(flatten(data))
> 
> writer = csv.writer(sys.stdout)
> writer.writerow([k for k, v in pairs])
> writer.writerow([v for k, v in pairs])
> 
> The output is as follows:
> 
> $ python3 json2csv.py
> A,FEC,TE,Locator,Message,AT,FT,FR,FY,FR,FG,Comment,FUD,
> cID,GEO,ISO,TRID,XTY,ANM,NM,CF,ID
> 5,1/1/0001 12:00:00 AM,,,Transfer Fee,,,True,,,0,,,931083,,,Fee,2
> 
> I do not want to have duplicate column names.

If you tell the exact output you want and in particular how you want to 
resolve any name clashes I might give you a hint. I'm unlikely to produce 
more code though.

> Any advice on other best practices that I may utilize?

Align your engineering efforts and capabilities to deliver on your strategy 
and, in particular, your three core, I mean your four core ambitions...

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


help in understanding the stackless code

2015-06-18 Thread ravi
hi,
I am new to python and need to know why the calling of switch(1) invokes the 
function "listen" twice in the below program?



import stackless

class EventHandler:
def __init__(self,*outputs):
if outputs==None:
self.outputs=[]
else:
self.outputs=list(outputs)

self.channel = stackless.channel()
stackless.tasklet(self.listen)()

def listen(self):
print "in listen()..."
while 1:
val = self.channel.receive()
self.processMessage(val)
for output in self.outputs:
self.notify(output)

def processMessage(self,val):
pass

def notify(self,output):
pass

def registerOutput(self,output):
print "in registerOutput()..."
self.outputs.append(output)

def __call__(self,val):
print "in __call__ ..."
self.channel.send(val)

class Switch(EventHandler):
def __init__(self,initialState=0,*outputs):
EventHandler.__init__(self,*outputs)
self.state = initialState

def processMessage(self,val):
print "in processMessage() of Switch..."
self.state = val

def notify(self,output):
print "in notify() of switch..."
output((self,self.state))

class Reporter(EventHandler):
def __init__(self,msg="%(sender)s send message %(value)s"):
EventHandler.__init__(self)
self.msg = msg

def processMessage(self,msg):
print "in processMessage() of Reporter..."
sender,value=msg
print self.msg % {'sender':sender,'value':value}


if __name__ == "__main__":
reporter = Reporter()
switch = Switch(0,reporter) 
switch(1)




output:
=

in __call__ ...
in listen()...
in listen()...
in processMessage() of Switch...
in notify() of switch...
in __call__ ...
in processMessage() of Reporter...
<__main__.Switch instance at 0x8d822cc> send message 1





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


Re: Get off the list

2015-06-18 Thread Marc Lucke
there is no way.  You are trapped forever.  Resistance is futile.

On 17/06/2015 5:09 PM, Deogratius Musiige wrote:
> Hi,
> 
> How can i get off this mailing list?
> 
>  
> 
> Best regards / Med venlig hilsen
> 
> Deogratius Musiige
> Software Development Engineer
> 
> *Sennheiser Communications A/S*
> Industriparken 27
> DK-2750 Ballerup
> 
> Direct  +45 5618 0320
> Mail d...@senncom.com
> Webwww.sennheiser.com
> 
> 
>  
> 
> 
> 
-- 
https://mail.python.org/mailman/listinfo/python-list


ctypes and byte order

2015-06-18 Thread Jean-Michel Pichavant
Hi list,

I'm currently writing python code that writes a small binary file to be used by 
another device which code is written in C.
The python code runs on a little endian CPU, and unfortunately, the other 
device is using a big endian MIPS.

My problem is the following: I cannot make an array of n int work in big 
endian, I can workaround the problem by creating n intergers, which is nicely 
done thanks to list comprehension but that seems to me like a misuse of the 
ctypes modules.

ctypes is expecting a 'c_uint_be_Array_5' (note the _be_ for big endian), and I 
don't know how to construct such object.

I hope I am clear.

Thanks,

JM

here's a code sample (python 2.7):


import ctypes, sys

iarray = ctypes.c_uint32*5  # array of 5 unsigned 32 bits

class Foo(ctypes.Structure):
"""Native byte order, won't work on my big endian device"""
_fields_ = [('bar', iarray)] 

class Foo_be(ctypes.BigEndianStructure):
"""big endian version, but python code fails"""
_fields_ = [('bar', iarray)] 

class Foo_be_working(ctypes.BigEndianStructure):
"""Working big endian version, looks more like a workaround."""
_fields_ = [('bar%i'%i, ctypes.c_uint32) for i in range(5)]


print sys.version
f = Foo(iarray(0,1,2,3,4))
print "uint32 array: ", f.bar

f_be = Foo_be_working(0,1,2,3,4)
print "bar0 and bar5: ", f_be.bar0, f_be.bar5

f_be = Foo_be(iarray(0,1,2,3,4)) # will raise an exception




The output

2.7.3 (default, Mar 13 2014, 11:03:55) 
[GCC 4.7.2]
uint32 array:  <__main__.c_uint_Array_5 object at 0x1cf4560>
bar0 and bar4:  0 4


TypeError: incompatible types, c_uint_Array_5 instance instead of 
c_uint_be_Array_5 instance
 24 
---> 25 f_be = Foo_be(iarray(0,1,2,3,4))
 26 



-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-18 Thread Marco Buttu

On 17/06/2015 23:33, sohcahto...@gmail.com wrote:

I had a Java class where we had to learn TDD, and that's the way TDD was taught 
to us, and I hated it. We watched a video of this guy explaining TDD with a hat 
that was red on the front and green on the back.  It involved writing a simple 
failing unit test, then write code to fix it, then refactor the tests and/or 
code.


I do not think it is important that the test fails before writing the 
code, but for sure it is really wise to ensure every test fails at least 
once. If I wrote a test and it has never failed before, then I always 
change something in the test itself, in order to have an expected 
failure. And sometimes the expected failures make me better understand 
the behavior of the code.



As an in-class exercise, we had to write an implementation of Conway's Game of Life.  I 
threw TDD out the window and just wrote the damn program in under 15 minutes, then 
another 10 minutes to write unit tests that tested every possible code branch and several 
invalid inputs.  Meanwhile, the people doing TDD the "right" way didn't even 
have a complete program after over an hour.

The brand of TTD we were taught would end up multiplying development time by at 
least a factor of 3, and by the time you were done, at least 75% of the tests 
you had written will have been removed due to rampant refactoring.

IMO, that kind of TTD is an utter waste of time.


I think TDD helps a lot to design the code to be "testable" as much as 
possible. I believe good and experienced programmers could think in 
advance the way to write testable code, without be driven by tests. 
However, I also think that the bigger part of programmers, as me, do not 
have this ability. That's the case TDD comes in handy helping us to 
write testable code.


In case of bug fixing, I think also experienced and good programmers 
that do not believe in TDD should always write the tests in advance, for 
instance because:


* it is really the better way to understand the problem and point to it
* chances are that you will not write a test after fixing the bug, i.e. 
because you may have other priorities, so you will miss a regression test



--
Marco Buttu

INAF-Osservatorio Astronomico di Cagliari
Via della Scienza n. 5, 09047 Selargius (CA)
Phone: 070 711 80 217
Email: mbu...@oa-cagliari.inaf.it

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


Re: Get off the list

2015-06-18 Thread Ian Kelly
On Thu, Jun 18, 2015 at 1:05 AM, Cecil Westerhof  wrote:
> On Wednesday 17 Jun 2015 09:09 CEST, Deogratius Musiige wrote:
>
>> How can i get off this mailing list?
>
> Looking at the headers:
> List-Unsubscribe: ,
>  
>
> So I would send an email with the email account you are subscribed to
> the list, with the subject ‘unsubscribe’.

Not to the list. python-list and python-list-request are different addresses.

Personally though, I'd just use the web interface.
-- 
https://mail.python.org/mailman/listinfo/python-list


Time saving tips for Pythonists

2015-06-18 Thread Productivi .co
Hello Pythonists!

I'm preparing an article to show up at simplilearn.com about the best time
saving tips Pyhonists use, and thus, conducting interviews with Pythonists
like you.

The interview question I would like to ask you is:

*What are your best time saving tips when programming Python?*

Looking forward to your replies to this question, and will keep you updated
about the article.

Thanks.
Abder-Rahman
productivi.co
*Let The Productivity Journey Begin.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Get off the list

2015-06-18 Thread Cecil Westerhof
On Thursday 18 Jun 2015 09:36 CEST, Ian Kelly wrote:

> On Thu, Jun 18, 2015 at 1:05 AM, Cecil Westerhof  wrote:
>> On Wednesday 17 Jun 2015 09:09 CEST, Deogratius Musiige wrote:
>>
>>> How can i get off this mailing list?
>>
>> Looking at the headers: List-Unsubscribe:
>> ,
>> 
>>
>> So I would send an email with the email account you are subscribed
>> to the list, with the subject ‘unsubscribe’.
>
> Not to the list. python-list and python-list-request are different
> addresses.

Oops, I was not specific enough again. :'-( The email address was
shown, but it would be very easy to overlook it.


> Personally though, I'd just use the web interface.

That is the other option. I prefer sending an email, but for someone
asking how to unsubscribe, the web interface probably is a better
option. Next time I should think better about the receiver of the
information.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ctypes and byte order

2015-06-18 Thread Peter Otten
Jean-Michel Pichavant wrote:

> I'm currently writing python code that writes a small binary file to be
> used by another device which code is written in C. The python code runs on
> a little endian CPU, and unfortunately, the other device is using a big
> endian MIPS.
> 
> My problem is the following: I cannot make an array of n int work in big
> endian, I can workaround the problem by creating n intergers, which is
> nicely done thanks to list comprehension but that seems to me like a
> misuse of the ctypes modules.
> 
> ctypes is expecting a 'c_uint_be_Array_5' (note the _be_ for big endian),
> and I don't know how to construct such object.
> 
> I hope I am clear.

Yes, very clear, thanks for the effort, although the nitpicker in me has to 
mention that an off-by-one bug slipped into your code ;)

> class Foo_be_working(ctypes.BigEndianStructure):
> """Working big endian version, looks more like a workaround."""
> _fields_ = [('bar%i'%i, ctypes.c_uint32) for i in range(5)]
[...]
> f_be = Foo_be_working(0,1,2,3,4)
> print "bar0 and bar5: ", f_be.bar0, f_be.bar5

I'm not very familiar with ctypes, but a random walk through the source 
found the _endian module and the __ctypes_be__ attribute. So
> 
> iarray = ctypes.c_uint32*5  # array of 5 unsigned 32 bits
> 
> class Foo(ctypes.Structure):
> """Native byte order, won't work on my big endian device"""
> _fields_ = [('bar', iarray)]
> 
> class Foo_be(ctypes.BigEndianStructure):
> """big endian version, but python code fails"""
> _fields_ = [('bar', iarray)]

becomes

$ cat be2.py
import ctypes, sys

iarray_be = ctypes.c_uint32.__ctype_be__*5

class Foo_be(ctypes.BigEndianStructure):
_fields_ = [('bar', iarray_be)] 

print sys.version
f_be = Foo_be((0,1,2,3,0x11223344))
print hex(f_be.bar[4])

$ python be2.py 
2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2]
0x11223344L

which might do what you want.

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


Re: Classic OOP in Python

2015-06-18 Thread Mark Lawrence

On 17/06/2015 23:33, Laura Creighton wrote:

In a message of Wed, 17 Jun 2015 14:14:34 -0700, Ned Batchelder writes:


TDD is supposed to make you brave, not cowards, and it's
Ned's most excellent tool
http://nedbatchelder.com/code/coverage/
that I recommend to TDD dogmatic cowards.

Even if you don't want to use TTD, you will enjoy Ned's tool.  It's GREAT.
Thank you, Ned.

Laura



Throw in http://clonedigger.sourceforge.net/ as well and you've a really 
awesome combination.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Classic OOP in Python

2015-06-18 Thread Fabien

On 06/17/2015 11:16 PM, sohcahto...@gmail.com wrote:

You don't need interfaces with Python.  Duck typing makes that all possible.


Yes, but I also like interfaces (or in python: mimicked interfaces with 
NotImplementedError) for their clarity and documentation purposes.


Would you consider the following kind of program "unpythonic"?

class MovingObject(object):
"""Great doc about what a moving object is"""

def move(self):
"""Great doc about move"""
raise NotImplementedError()

class Dog(MovingObject):
def move(self):
print "Dog is moving"

class Car(MovingObject):
def move(self):
print "Car is moving"

(Disclaimer: I learned OOP with Java)

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


Re: Classic OOP in Python

2015-06-18 Thread Todd
On Thu, Jun 18, 2015 at 1:03 PM, Fabien  wrote:

> On 06/17/2015 11:16 PM, sohcahto...@gmail.com wrote:
>
>> You don't need interfaces with Python.  Duck typing makes that all
>> possible.
>>
>
> Yes, but I also like interfaces (or in python: mimicked interfaces with
> NotImplementedError) for their clarity and documentation purposes.
>
> Would you consider the following kind of program "unpythonic"?
>
> class MovingObject(object):
> """Great doc about what a moving object is"""
>
> def move(self):
> """Great doc about move"""
> raise NotImplementedError()
>
> class Dog(MovingObject):
> def move(self):
> print "Dog is moving"
>
> class Car(MovingObject):
> def move(self):
> print "Car is moving"
>
> (Disclaimer: I learned OOP with Java)
>
>
I think this is what abstract base classes are for in Python.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-18 Thread Jason P.
El miércoles, 17 de junio de 2015, 21:44:51 (UTC+2), Ned Batchelder  escribió:
> On Wednesday, June 17, 2015 at 3:21:32 PM UTC-4, Jason P. wrote:
> > Hello Python community.
> > 
> > I come from a classic background in what refers to OOP. Mostly Java and PHP 
> > (> 5.3). I'm used to abstract classes, interfaces, access modifiers and so 
> > on.
> > 
> > Don't get me wrong. I know that despite the differences Python is fully 
> > object oriented. My point is, do you know any book or resource that 
> > explains in deep the pythonic way of doing OOP?
> > 
> > For example, I'm gonna try to develop a modest application from ground up 
> > using TDD. If it had been done in Java for instance, I would made extensive 
> > use of interfaces to define the boundaries of my system. How would I do 
> > something like that in Python?
> > 
> > 
> > Many thanks!
> 
> What other languages do with interfaces, Python does with duck-typing. You
> can build something like interfaces in Python, but many people don't bother.
> 
> I don't know if your project will be web-based, but here is an entire book
> about developing Python web sites with a TDD approach:
> 
> http://www.obeythetestinggoat.com/
> 
> (Don't mind the unusual domain name, it's a bit of an inside joke...)
> 
> TDD and interfaces are separate concepts, and I'm not sure they even
> intersect.  TDD is about writing tests as a way to design the best system,
> and putting testing at the center of your development workflow.  It works
> great with Python even without interfaces.
> 
> --Ned.

I'm aware of duck typing. The point in using interfaces is to be explicit about 
the boundaries of a system.

Quite a red "Growing Object-Oriented Software, Guided by Tests", by the way. In 
fact interfaces are key components in the style of building software they 
propose, in good company with TDD.

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


Re: ctypes and byte order

2015-06-18 Thread Jean-Michel Pichavant
- Original Message -
> From: "Peter Otten" <__pete...@web.de>
> becomes
> 
> $ cat be2.py
> import ctypes, sys
> 
> iarray_be = ctypes.c_uint32.__ctype_be__*5
> 
> class Foo_be(ctypes.BigEndianStructure):
> _fields_ = [('bar', iarray_be)]
> 
> print sys.version
> f_be = Foo_be((0,1,2,3,0x11223344))
> print hex(f_be.bar[4])
> 
> $ python be2.py
> 2.7.6 (default, Mar 22 2014, 22:59:56)
> [GCC 4.8.2]
> 0x11223344L
> 
> which might do what you want.

Brilliant !

I've tested it and it yields the exact same results (binary file content wise) 
than my "workaround" structure.
But that's way better since my actual structure is more complex and arrays will 
be required.

Though I'm slightly puzzled by the ctypes author(s) choice, this is not 
documented and requires to peek into the source code. Dunder attributes are 
rarely part of an interface.

Anyway, thanks for your help !

JM



-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be 
privileged. If you are not the intended recipient, please notify the sender 
immediately and do not disclose the contents to any other person, use it for 
any purpose, or store or copy the information in any medium. Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-18 Thread Jason P.
El miércoles, 17 de junio de 2015, 21:44:51 (UTC+2), Ned Batchelder  escribió:
> On Wednesday, June 17, 2015 at 3:21:32 PM UTC-4, Jason P. wrote:
> > Hello Python community.
> > 
> > I come from a classic background in what refers to OOP. Mostly Java and PHP 
> > (> 5.3). I'm used to abstract classes, interfaces, access modifiers and so 
> > on.
> > 
> > Don't get me wrong. I know that despite the differences Python is fully 
> > object oriented. My point is, do you know any book or resource that 
> > explains in deep the pythonic way of doing OOP?
> > 
> > For example, I'm gonna try to develop a modest application from ground up 
> > using TDD. If it had been done in Java for instance, I would made extensive 
> > use of interfaces to define the boundaries of my system. How would I do 
> > something like that in Python?
> > 
> > 
> > Many thanks!
> 
> What other languages do with interfaces, Python does with duck-typing. You
> can build something like interfaces in Python, but many people don't bother.
> 
> I don't know if your project will be web-based, but here is an entire book
> about developing Python web sites with a TDD approach:
> 
> http://www.obeythetestinggoat.com/
> 
> (Don't mind the unusual domain name, it's a bit of an inside joke...)
> 
> TDD and interfaces are separate concepts, and I'm not sure they even
> intersect.  TDD is about writing tests as a way to design the best system,
> and putting testing at the center of your development workflow.  It works
> great with Python even without interfaces.
> 
> --Ned.

I forgot to mention that the book you recommend seems to be a good starting 
point ;)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-18 Thread Jason P.
El miércoles, 17 de junio de 2015, 22:39:31 (UTC+2), Marko Rauhamaa  escribió:
> Ned Batchelder :
> 
> > TDD is about writing tests as a way to design the best system, and
> > putting testing at the center of your development workflow. It works
> > great with Python even without interfaces.
> 
> I wonder how great it really is. Testing is important, that's for sure,
> but to make it a dogmatic starting point of development is not that
> convincing.
> 
> The way it was explained to me was that in TDD you actually don't write
> code to any requirements or design: you simply do the least to pass the
> tests. Thus, say you need to write a program that inputs a string and
> outputs the same string surrounded by parentheses (the requirement), the
> starting point might be this test case:
> 
>- run the program
>- give it the word "hello" as input
>- check that the program prints out "(hello)"
> 
> The right TDD thing would be to satisfy the test with this program:
> 
>input()
>print("(hello)")
> 
> That *ought* to be the first version of the program until further test
> cases are added that invalidate it.
> 
> 
> Another interesting ism I have read about is the idea that the starting
> point of any software project should be the user manual. The developers
> should then go and build the product that fits the manual.
> 
> 
> Marko

The refactor phase is key in TDD (red-green-refactor). Again, GOOS is an 
advisable source of knowledge in this matter.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Classic OOP in Python

2015-06-18 Thread Marko Rauhamaa
Todd :

> On Thu, Jun 18, 2015 at 1:03 PM, Fabien  wrote:
>> Would you consider the following kind of program "unpythonic"?
>>
>> class MovingObject(object):
>> """Great doc about what a moving object is"""
>>
>> def move(self):
>> """Great doc about move"""
>> raise NotImplementedError()
>>
>> class Dog(MovingObject):
>> def move(self):
>> print "Dog is moving"
>>
>> class Car(MovingObject):
>> def move(self):
>> print "Car is moving"
>>
>> (Disclaimer: I learned OOP with Java)
>>
>>
> I think this is what abstract base classes are for in Python.

And they can be ok as long as you're not making them into a habit.


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


Re: Classic OOP in Python

2015-06-18 Thread Chris Angelico
On Thu, Jun 18, 2015 at 9:03 PM, Fabien  wrote:
> Would you consider the following kind of program "unpythonic"?
>
> class MovingObject(object):
> """Great doc about what a moving object is"""
>
> def move(self):
> """Great doc about move"""
> raise NotImplementedError()
>
> class Dog(MovingObject):
> def move(self):
> print "Dog is moving"
>
> class Car(MovingObject):
> def move(self):
> print "Car is moving"
>
> (Disclaimer: I learned OOP with Java)

Now try extending the concept to two, three, or four such interfaces.
Files can be moved, opened, copied, and unlinked. Should they share
any sort of interface with dogs, boxes, handwriting, and railway
carriages? It's much better to simply define the attributes of each
object separately; most non-trivial cases don't involve simple methods
with no additional arguments, and the chances of an incompatibility
(or worse, a forced compatibility) go up.

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


Re: Classic OOP in Python

2015-06-18 Thread Ned Batchelder
On Thursday, June 18, 2015 at 7:21:29 AM UTC-4, Jason P. wrote:
> El miércoles, 17 de junio de 2015, 21:44:51 (UTC+2), Ned Batchelder  escribió:
> > On Wednesday, June 17, 2015 at 3:21:32 PM UTC-4, Jason P. wrote:
> > > Hello Python community.
> > > 
> > > I come from a classic background in what refers to OOP. Mostly Java and 
> > > PHP (> 5.3). I'm used to abstract classes, interfaces, access modifiers 
> > > and so on.
> > > 
> > > Don't get me wrong. I know that despite the differences Python is fully 
> > > object oriented. My point is, do you know any book or resource that 
> > > explains in deep the pythonic way of doing OOP?
> > > 
> > > For example, I'm gonna try to develop a modest application from ground up 
> > > using TDD. If it had been done in Java for instance, I would made 
> > > extensive use of interfaces to define the boundaries of my system. How 
> > > would I do something like that in Python?
> > > 
> > > 
> > > Many thanks!
> > 
> > What other languages do with interfaces, Python does with duck-typing. You
> > can build something like interfaces in Python, but many people don't bother.
> > 
> > I don't know if your project will be web-based, but here is an entire book
> > about developing Python web sites with a TDD approach:
> > 
> > http://www.obeythetestinggoat.com/
> > 
> > (Don't mind the unusual domain name, it's a bit of an inside joke...)
> > 
> > TDD and interfaces are separate concepts, and I'm not sure they even
> > intersect.  TDD is about writing tests as a way to design the best system,
> > and putting testing at the center of your development workflow.  It works
> > great with Python even without interfaces.
> > 
> > --Ned.
> 
> I'm aware of duck typing. The point in using interfaces is to be explicit 
> about the boundaries of a system.
> 
> Quite a red "Growing Object-Oriented Software, Guided by Tests", by the way. 
> In fact interfaces are key components in the style of building software they 
> propose, in good company with TDD.

Yes, that book uses interfaces, because that book uses Java.  Different
languages offer different tools.  You can make interfaces in Python, but you
don't need to.  They aren't enforced by Python, so you aren't gaining much
other than documentation from them, so why not just use documentation?

Abstract classes provide another tool.  They can insist that you provide
implementations of abstract methods.  In my experience, it is easy to get
to a point where you are struggling to satisfy your simple-minded abstract
classes, rather than writing the code that you know you need to solve your
actual problem.  As Chris just mentioned elsewhere in this thread, you have
to be very careful how you define your abstract classes.  I've worked in 
Java projects where I had to provide 10 dummy implementations of methods I
knew I wasn't going to need, just because the interface insisted they had
to exist.

The Python culture is to document your expectations, and write enough tests
to verify that your code does what it claims to do.  You are already planning
on a TDD flow, so you will have plenty of tests.

Try doing without interfaces or abstract classes.  See how it goes. It's the
Python way. :)

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


Re: help in understanding the stackless code

2015-06-18 Thread MRAB

On 2015-06-18 08:41, ravi wrote:

hi,
I am new to python and need to know why the calling of switch(1) invokes the function 
"listen" twice in the below program?



import stackless

class EventHandler:
 def __init__(self,*outputs):
 if outputs==None:
 self.outputs=[]
 else:
 self.outputs=list(outputs)

 self.channel = stackless.channel()
 stackless.tasklet(self.listen)()

 def listen(self):
 print "in listen()..."
 while 1:
 val = self.channel.receive()
 self.processMessage(val)
 for output in self.outputs:
 self.notify(output)

 def processMessage(self,val):
 pass

 def notify(self,output):
 pass

 def registerOutput(self,output):
 print "in registerOutput()..."
 self.outputs.append(output)

 def __call__(self,val):
 print "in __call__ ..."
 self.channel.send(val)

class Switch(EventHandler):
 def __init__(self,initialState=0,*outputs):
 EventHandler.__init__(self,*outputs)
 self.state = initialState

 def processMessage(self,val):
 print "in processMessage() of Switch..."
 self.state = val

 def notify(self,output):
 print "in notify() of switch..."
 output((self,self.state))

class Reporter(EventHandler):
 def __init__(self,msg="%(sender)s send message %(value)s"):
 EventHandler.__init__(self)
 self.msg = msg

 def processMessage(self,msg):
 print "in processMessage() of Reporter..."
 sender,value=msg
 print self.msg % {'sender':sender,'value':value}


if __name__ == "__main__":
 reporter = Reporter()
 switch = Switch(0,reporter)
 switch(1)




output:
=

in __call__ ...
in listen()...
in listen()...
in processMessage() of Switch...
in notify() of switch...
in __call__ ...
in processMessage() of Reporter...
<__main__.Switch instance at 0x8d822cc> send message 1


Is it because EventHandler has 2 subclasses, namely Switch and
Reporter, and you have an instance of each?

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


Re: ctypes and byte order

2015-06-18 Thread Peter Otten
Jean-Michel Pichavant wrote:

> - Original Message -
>> From: "Peter Otten" <__pete...@web.de>
>> becomes
>> 
>> $ cat be2.py
>> import ctypes, sys
>> 
>> iarray_be = ctypes.c_uint32.__ctype_be__*5
>> 
>> class Foo_be(ctypes.BigEndianStructure):
>> _fields_ = [('bar', iarray_be)]
>> 
>> print sys.version
>> f_be = Foo_be((0,1,2,3,0x11223344))
>> print hex(f_be.bar[4])
>> 
>> $ python be2.py
>> 2.7.6 (default, Mar 22 2014, 22:59:56)
>> [GCC 4.8.2]
>> 0x11223344L
>> 
>> which might do what you want.
> 
> Brilliant !
> 
> I've tested it and it yields the exact same results (binary file content
> wise) than my "workaround" structure. But that's way better since my
> actual structure is more complex and arrays will be required.
> 
> Though I'm slightly puzzled by the ctypes author(s) choice, this is not
> documented and requires to peek into the source code. Dunder attributes
> are rarely part of an interface.

On further reflection it dawned on me that what may have made this work is 
passing in the tuple instead of an array:

>>> import ctypes
>>> array = ctypes.c_uint32 * 3
>>> class B(ctypes.BigEndianStructure):
... _fields_ = [("bar", array)]
... 
>>> b = B((1,2,3))
>>> b.bar

>>> b.bar[2]
3L
>>> b = B(array(1,2,3))
Traceback (most recent call last):
  File "", line 1, in 
TypeError: incompatible types, c_uint_Array_3 instance instead of 
c_uint_be_Array_3 instance

Oops...

So the only thing that doesn't work transparently is initialising a data 
structure (or at least array) from its "other-endian" twin.



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


Re: Documenting a function signature (was: Set a flag on the function or a global?)

2015-06-18 Thread random832
On Wed, Jun 17, 2015, at 20:14, Chris Angelico wrote:
> Mostly. That would imply that object is a mandatory parameter, which
> AIUI isn't the case for Steven's edir. The downside of this kind of
> signature is that it's hard to show the parameters that have unusual
> defaults (either sentinel objects and custom code to cope, or they're
> pulled out of *a or **kw).

My instinct would be to put =... for that case and explain in the
documentation "If foo is not provided, [behavior]".

Of course, that runs the risk of people thinking you actually mean
Ellipsis, or that providing Ellipsis explicitly will give the same
behavior as the default.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Posting gzip'd image file - server says Malformed Upload?

2015-06-18 Thread random832
On Wed, Jun 17, 2015, at 20:23, Chris Angelico wrote:
> On Thu, Jun 18, 2015 at 7:55 AM, Paul Hubert  wrote:
> > f_in = open(dafile, 'rb')
> > f_out = gzip.open('/Users/Paul/Desktop/scripts/pic.jpg.gz', 'wb')
> > f_out.writelines(f_in)
> > f_out.close()
> > f_in.close()
> 
> Are you sure you want iteration and writelines() here? I would be
> inclined to avoid those for any situation that isn't plain text. If
> the file isn't too big, I'd just read it all in a single blob and then
> write it all out at once.

Is there a reason not to use shutil.copyfileobj?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Posting gzip'd image file - server says Malformed Upload?

2015-06-18 Thread Chris Angelico
On Thu, Jun 18, 2015 at 10:38 PM,   wrote:
> On Wed, Jun 17, 2015, at 20:23, Chris Angelico wrote:
>> On Thu, Jun 18, 2015 at 7:55 AM, Paul Hubert  wrote:
>> > f_in = open(dafile, 'rb')
>> > f_out = gzip.open('/Users/Paul/Desktop/scripts/pic.jpg.gz', 'wb')
>> > f_out.writelines(f_in)
>> > f_out.close()
>> > f_in.close()
>>
>> Are you sure you want iteration and writelines() here? I would be
>> inclined to avoid those for any situation that isn't plain text. If
>> the file isn't too big, I'd just read it all in a single blob and then
>> write it all out at once.
>
> Is there a reason not to use shutil.copyfileobj?

If the file is too big (or might be too big) to want to fit into
memory, then sure. But a typical JPEG image isn't going to be
gigabytes of content; chances are it's going to be a meg or so at
most, and that doesn't justify the overhead of chunking. Just read it,
write it, job done.

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


thinking with laziness

2015-06-18 Thread Neal Becker
http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html

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


Re: Time saving tips for Pythonists

2015-06-18 Thread John Strick
On Thursday, June 18, 2015 at 6:11:11 AM UTC-4, Productivi .co wrote:
> What are your best time saving tips when programming Python?
PyCharm!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: thinking with laziness

2015-06-18 Thread Steven D'Aprano
On Thu, 18 Jun 2015 11:10 pm, Neal Becker wrote:

> http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html

I wanted to think about that post, but I'm too lazy to read it.


My-apologies-I-couldn't-resist-it-ly y'rs,

-- 
Steven

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


Re: Classic OOP in Python

2015-06-18 Thread Cousin Stanley

> 
> python -m doctest application.py
> 
> And from there, I would build up extra doc tests
> 

An extra doc test  

  that fails 


#!/usr/bin/env python

"""
NewsGroup  comp.lang.python 
Subject .. Classic OOP in Python
Date . 2015-06-17
Post_By .. Steven D'Aprano
Edit_By .. Stanley C. Kitching
"""

def bracket( s ) :

"""Return string s bracketed in parentheses.

>>> bracket( "Hello" )
'(Hello)'

>>> bracket( "Yo Mama is a Perl Monkey" )
'(Yo Mama is a Java Monkey')

"""

return "(%s)" % s


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: thinking with laziness

2015-06-18 Thread Mark Lawrence

On 18/06/2015 14:53, Steven D'Aprano wrote:

On Thu, 18 Jun 2015 11:10 pm, Neal Becker wrote:


http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html


I wanted to think about that post, but I'm too lazy to read it.


My-apologies-I-couldn't-resist-it-ly y'rs,



Reminds me of last night's AGM of the Apathy Society, which was an 
outstanding success as nobody turned up.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: thinking with laziness

2015-06-18 Thread Chris Angelico
On Fri, Jun 19, 2015 at 2:15 AM, Mark Lawrence  wrote:
> Reminds me of last night's AGM of the Apathy Society, which was an
> outstanding success as nobody turned up.

How do you know for sure? Nobody bothered to take minutes.

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


executable egg?

2015-06-18 Thread dmaziuk
Hi all,

Here's my directory structure:

myegg/
pkg1/
__init__.py
...
pkg2/
__init__.py
...
pkg3/
__init__.py
...
setup.py

I can make an egg with "python setup.py bdist_egg" and it works just fine. I'd 
like to make it executable with "python myegg.egg" which is supposed to be 
doable in 2.6+. According to everything I can find, all I need is to add

myegg/
__main__.py

The end result, however, is "/usr/bin/python: can't find '__main__' module". It 
is correct: checking the egg with unzip -l shows that __main__.py is indeed not 
in it. So I played with options for including package data, also made a stab or 
two at entry_points with no luck.

So, what am I missing. Or does it only work with one package in the egg?

(I'm using 2.7 & 2.6 on centos 7 & 6 resp.)
TIA,
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ctypes and byte order

2015-06-18 Thread Terry Reedy

On 6/18/2015 5:39 AM, Jean-Michel Pichavant wrote:


I'm currently writing python code that writes a small binary file to
be used by another device which code is written in C. The python code
runs on a little endian CPU, and unfortunately, the other device is
using a big endian MIPS.


The struct module is designed for this.  It reads and writes packed 
binary data of various types and sizes in either big or little endian 
order.  It should be easier than ctypes.


--
Terry Jan Reedy

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


Re: thinking with laziness

2015-06-18 Thread Todd
On Thu, Jun 18, 2015 at 6:15 PM, Mark Lawrence 
wrote:

> On 18/06/2015 14:53, Steven D'Aprano wrote:
>
>> On Thu, 18 Jun 2015 11:10 pm, Neal Becker wrote:
>>
>>  http://begriffs.com/posts/2015-06-17-thinking-with-laziness.html
>>>
>>
>> I wanted to think about that post, but I'm too lazy to read it.
>>
>>
>> My-apologies-I-couldn't-resist-it-ly y'rs,
>>
>>
> Reminds me of last night's AGM of the Apathy Society, which was an
> outstanding success as nobody turned up.
>

I thought about it, but couldn't be bothered to find the address.
-- 
https://mail.python.org/mailman/listinfo/python-list


Why this list of dictionaries doesn't work?

2015-06-18 Thread Gilcan Machado
Hi,

I'm trying to write a list of dictionaries like:

people = (
 {'name':'john', 'age':12} ,
 {'name':'kacey', 'age':18}
)


I've thought the code below would do the task.

But it doesn't work.

And if I "print(people)" what I get is not the organize data structure like
above.

Thanks of any help!
[]s
Gilcan

#!/usr/bin/env python
from collections import defaultdict

person = defaultdict(dict)
people = list()

person['name'] = 'jose'
person['age'] = 12

people.append(person)

person['name'] = 'kacey'
person['age'] = 18

people.append(person)

for person in people:
print( person['nome'] )
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why this list of dictionaries doesn't work?

2015-06-18 Thread MRAB

On 2015-06-18 18:57, Gilcan Machado wrote:

Hi,

I'm trying to write a list of dictionaries like:

people = (
  {'name':'john', 'age':12} ,
  {'name':'kacey', 'age':18}
 )


That's not a list; it's a tuple. If you want a list, use '[' and ']'.


I've thought the code below would do the task.

But it doesn't work.

And if I "print(people)" what I get is not the organize data structure
like above.

Thanks of any help!
[]s
Gilcan

#!/usr/bin/env python
from collections import defaultdict


You don't need a defaultdict, just a normal dict.

This creates an empty defaultdict whose default value is a dict:


person = defaultdict(dict)
people = list()


This puts some items into the dict:


person['name'] = 'jose'
person['age'] = 12


This puts the dict into the list:


people.append(person)


This _reuses_ the dict and overwrites the items:


person['name'] = 'kacey'
person['age'] = 18


This puts the dict into the list again:


people.append(person)


The list 'people' now contains 2 references to the _same_ dict.


for person in people:
 print( person['nome'] )


Initially there's no such key as 'nome' (not the spelling), so it
creates one with the default value, a dict.

If you print out the people list, you'll see:

[defaultdict(, {'name': 'kacey', 'age': 18, 'nome': {}}), 
defaultdict(, {'name': 'kacey', 'age': 18, 'nome': {}})]


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


Re: Why this list of dictionaries doesn't work?

2015-06-18 Thread Gary Herron

On 06/18/2015 10:57 AM, Gilcan Machado wrote:

Hi,

I'm trying to write a list of dictionaries like:

people = (
 {'name':'john', 'age':12} ,
 {'name':'kacey', 'age':18}
)


I've thought the code below would do the task.

But it doesn't work.


Never say "it doesn't work" on this list.  Tell us what it did, and what 
you expected.  Provide a copy of the full error message. That's much 
more helpful than making us guess.




And if I "print(people)" what I get is not the organize data structure 
like above.


Thanks of any help!
[]s
Gilcan

#!/usr/bin/env python
from collections import defaultdict

person = defaultdict(dict)


If you want *two* different dictionaries, you'll have to create *two* of 
them.  You code creates only this one.



people = list()

person['name'] = 'jose'
person['age'] = 12

people.append(person)


Here's where you need to create the second one.



person['name'] = 'kacey'
person['age'] = 18

people.append(person)

for person in people:
print( person['nome'] )


Typo here:  'name', not 'nome'.








--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: CLI Arguments That Call Functions?

2015-06-18 Thread Ian Kelly
On Thu, Jun 18, 2015 at 11:56 AM, Tony the Tiger  wrote:
> I would have assumed there would be something built in to the
> ArgumentParser, but I can't detect anything that seems to do what I want,
> so I wrote the following:

[SNIP]

> So, is there something already in the Python libs? Do I continue with
> this? Or what?
>
> There ought to be something already built in to Python, but I think I've
> missed it. Sure hope so. I'd hate to continue with this mess.


You can specify custom actions for arguments. See
https://docs.python.org/3.4/library/argparse.html#action-classes

For example (untested):

class AppendCallable(argparse.Action):

def __call__(self, parser, namespace, values, option_string):
callables = getattr(namespace, self.dest, None) or []
callables.append(functools.partial(self.const, *values))
setattr(namespace, self.dest, callables)

def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-a', '--alfa',
action=AppendCallable,
const=option_alfa,
dest='callables',
nargs=1,
type=int)

parser.add_argument(
'-b', '--bravo',
action=AppendCallable,
const=option_bravo,
dest='callables',
nargs=0)

args = parser.parse_args()
for callable in args.callables:
callable()

You might also be interested in reading
https://docs.python.org/3.4/library/argparse.html#sub-commands in case
that's related to what you're trying to accomplish.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: CLI Arguments That Call Functions?

2015-06-18 Thread Michael Torrie
On 06/18/2015 12:08 PM, Tony the Tiger wrote:
> Forgot to add, I don't read or see anything posted from outside of the 
> groups. 

Posting from the mailing list here.  I assume the nntp gateway is
two-way.  Unless you're manually blocking message originating in google
groups, I don't see why you wouldn't pick them up (bad formatting and
all) on Usenet.  If not, you're not missing anything, nor are we here
outside of usenet.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Keypress Input

2015-06-18 Thread Oscar Benjamin
On Wed, 17 Jun 2015 at 02:23 Michael Torrie  wrote:

> On 06/16/2015 02:49 PM, Grant Edwards wrote:
> > On 2015-06-16, John McKenzie  wrote:
> >
> >> It never occurred to me something so simple as keystrokes would not
> >> be present in Python, a language rated as being terrific by everyone
> >> I know who knows it.
> >
> > Ah, but in reality "keystrokes" is not simple at all.  Keyboards and
> > input handling is a very messy, complicated area.
>
> If you do choose to go with the GPIO route, unless your code for
> accessing the GPIO lines does debouncing, you will have to debounce the
> key.  There are lots of examples out there (most in C on the arduino,
> but still applicable). Most of them check for a button press, then do a
> timer count-down to let things settle out before recording a button
> press.  So it's still complicated even if you talk directly to the
> buttons!  No way around some complexity though.
>

I use the following. I found in testing that when you push the button it
prints 'Button pressed' 10 times a second (in actual use it calls poweroff
so I guess bounce isn't an issue there). Is there some reason it needs to
be cleverer in this case?

 #!/usr/bin/env python

import RPi.GPIO as GPIO
import subprocess
import time

PIN_NUM = 21

GPIO.setmode(GPIO.BCM)

GPIO.setup(PIN_NUM, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
time.sleep(0.1)
if not GPIO.input(PIN_NUM):
print('Button pressed')

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


Re: help in understanding the stackless code

2015-06-18 Thread ravi
yes It has instance of both Reporter and Switch.
moreover I could not get why instance "reporter" is passed to class Switch 
as a parameter ?

> >  reporter = Reporter()
> >  switch = Switch(0,reporter)
> >  switch(1)


thanks



On Thursday, June 18, 2015 at 5:45:08 PM UTC+5:30, MRAB wrote:
> On 2015-06-18 08:41, ravi wrote:
> > hi,
> > I am new to python and need to know why the calling of switch(1) invokes 
> > the function "listen" twice in the below program?
> >
> >
> >
> > import stackless
> >
> > class EventHandler:
> >  def __init__(self,*outputs):
> >  if outputs==None:
> >  self.outputs=[]
> >  else:
> >  self.outputs=list(outputs)
> >
> >  self.channel = stackless.channel()
> >  stackless.tasklet(self.listen)()
> >
> >  def listen(self):
> >  print "in listen()..."
> >  while 1:
> >  val = self.channel.receive()
> >  self.processMessage(val)
> >  for output in self.outputs:
> >  self.notify(output)
> >
> >  def processMessage(self,val):
> >  pass
> >
> >  def notify(self,output):
> >  pass
> >
> >  def registerOutput(self,output):
> >  print "in registerOutput()..."
> >  self.outputs.append(output)
> >
> >  def __call__(self,val):
> >  print "in __call__ ..."
> >  self.channel.send(val)
> >
> > class Switch(EventHandler):
> >  def __init__(self,initialState=0,*outputs):
> >  EventHandler.__init__(self,*outputs)
> >  self.state = initialState
> >
> >  def processMessage(self,val):
> >  print "in processMessage() of Switch..."
> >  self.state = val
> >
> >  def notify(self,output):
> >  print "in notify() of switch..."
> >  output((self,self.state))
> >
> > class Reporter(EventHandler):
> >  def __init__(self,msg="%(sender)s send message %(value)s"):
> >  EventHandler.__init__(self)
> >  self.msg = msg
> >
> >  def processMessage(self,msg):
> >  print "in processMessage() of Reporter..."
> >  sender,value=msg
> >  print self.msg % {'sender':sender,'value':value}
> >
> >
> > if __name__ == "__main__":
> >  reporter = Reporter()
> >  switch = Switch(0,reporter)
> >  switch(1)
> >
> >
> >
> >
> > output:
> > =
> >
> > in __call__ ...
> > in listen()...
> > in listen()...
> > in processMessage() of Switch...
> > in notify() of switch...
> > in __call__ ...
> > in processMessage() of Reporter...
> > <__main__.Switch instance at 0x8d822cc> send message 1
> >
> Is it because EventHandler has 2 subclasses, namely Switch and
> Reporter, and you have an instance of each?
-- 
https://mail.python.org/mailman/listinfo/python-list


python program without stackless.run()

2015-06-18 Thread ravi

Hi,

I could not understand how the below program executes function "fun" without 
calling stackless.run() in the program?  Here "fun" runs as a tasklet and as 
per my knowledge for that stackless.run() is must.



-
import stackless

class A:
def __init__(self,name):
self.name = name
self.ch = stackless.channel()
stackless.tasklet(self.fun)()

def __call__(self,val):
self.ch.send(val)

def fun(self):
   while 1:
 v = self.ch.receive()
 print "hi" , v


if __name__ == "__main__":
obj = A("sh")
obj(6)
-

output:
--
hi 6





thanks,
ravi
-- 
https://mail.python.org/mailman/listinfo/python-list


how to dump tasklets status in python

2015-06-18 Thread ravi
hi,

I have a complex python program running 100 tasklets simultaneously. I want to 
take dump of all the running tasklets including their current status and back 
trace at the time of exception. Can any one let me know how can this be done ?

Thanks,
ravi
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python program without stackless.run()

2015-06-18 Thread Ian Kelly
On Thu, Jun 18, 2015 at 1:47 PM, ravi  wrote:
> I could not understand how the below program executes function "fun" without 
> calling stackless.run() in the program?  Here "fun" runs as a tasklet and as 
> per my knowledge for that stackless.run() is must.

You seem to have a lot of questions about stackless. You might find
that you get a better, more focused response if you ask your questions
on the stackless mailing list:
http://www.stackless.com/mailman/listinfo/stackless
-- 
https://mail.python.org/mailman/listinfo/python-list


Python File as the Default PDF handler for Windows

2015-06-18 Thread Naftali
Long time lurker. 

I'm looking to register a python script as the default pdf reader for windows. 
I assume I can just register the .py in the section windows section for 
registering default handlers, but I'm wondering how to access the file from 
within the program. 

The issue is this:

We have Java application that outputs user uploaded pdf files. It does this 
simply by instructing windows to open the downloaded pdf file and windows takes 
it from there. The data entry person will view the pdf and usually upload it 
into another part of the system. Problem is the second leg of the system 
modifies the pdf, and thus crashes when the pdf is protected against writing. 
Data entry make use of a program to unlock them as needed but it is an extra 
step and it only comes to their awareness after their client crashes on the 
locked pdf (because it doesn't make sense to check them proactively.

I cannot change the Java system. 

What I want to do is write a pdf handler to handle windows open instruction. In 
the script I would run a command line pdf unlocker on the file and open the 
unlocked file with adobe (or the like). 

I've googled and though I get tons of 'how to open pdf from a python script' I 
haven't found anything describing how to write and set up my python program to 
deal with the pdf hand-off from the OS.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python program without stackless.run()

2015-06-18 Thread ravi
On Friday, June 19, 2015 at 1:41:36 AM UTC+5:30, Ian wrote:
> On Thu, Jun 18, 2015 at 1:47 PM, ravi  wrote:
> > I could not understand how the below program executes function "fun" 
> > without calling stackless.run() in the program?  Here "fun" runs as a 
> > tasklet and as per my knowledge for that stackless.run() is must.
> 
> You seem to have a lot of questions about stackless. You might find
> that you get a better, more focused response if you ask your questions
> on the stackless mailing list:
> http://www.stackless.com/mailman/listinfo/stackless

thanks for your pointer. I will post my queries to stackless mailing list.
-- 
https://mail.python.org/mailman/listinfo/python-list


Reassigning keys in dictionary of lists and then writing out to CSV file?

2015-06-18 Thread Sahlusar
I am currently attempting to work on converting a fairly sizeable JSON object 
and convert it into a CSV format. However, when I attempt to do so, using a 
conventional approach (that seems to work with other files). I am presented 
with a "ValueError: too many values to unpack"

I have tried to flatten the JSON object using this function:

# def flatten(d, parent_key=''):
# items = []
# for k, v in d.items():
# try:
# items.extend(flatten(v, '%s%s_' % (parent_key, k)).items())
# except AttributeError:
# items.append(('%s%s' % (parent_key, k), v))
# return dict(items)


However this concatenates the keys. I am now attempting to remove the nested 
key and reassigning to the outer key. 

Here are some samples. I would remove Int32, Double and DateTime. I am 
wondering if there is a function that would then allow me to assign the new 
keys as column headers in a CSV and concatenate all of the values within the 
list (as corresponding fields). I hope that I was clear in my description. 
Thank you all for your help. 

"FC": {"Int32": ["0","0","0","0","0","0"]} and
 
"PBA": {"Double": ["0","0","0","0","0","0","0","0"]}

and such examples:

"PBDD": {
"DateTime": ["1/1/0001 12:00:00 
AM",
"1/1/0001 12:00:00 AM",
"1/1/0001 12:00:00 AM",
"1/1/0001 12:00:00 AM",
"1/1/0001 12:00:00 AM",
"1/1/0001 12:00:00 AM",
"1/1/0001 12:00:00 AM",
"1/1/0001 12:00:00 AM"]
},
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Documenting a function signature (was: Set a flag on the function or a global?)

2015-06-18 Thread Laura Creighton
In a message of Thu, 18 Jun 2015 10:04:46 +1000, Ben Finney writes:
>Since the introduction of keyword-only arguments in Python functions,
>the question arises of how to communicate this in documentation.

I suppose it is way too late to scream "I hate keyword-only arguments"!

>The lone asterisk showing the separation of keyword-only arguments from
>the rest is confusing to me. Not least because it is (if I understand
>correctly) invalid syntax to actually have that in Python code.

Me too.

Laura

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


Re: Posting gzip'd image file - server says Malformed Upload?

2015-06-18 Thread Laura Creighton
I got to this party late.

One way to get the malformed upload message is is you gzip something
that already is gzipped, and send that up the pipe.

worth checking.

Laura

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


Re: Hotspot Locater

2015-06-18 Thread Laura Creighton
yes.  wifi https://wifi.readthedocs.org/en/latest/

see this answer, not raspberry pi specific
http://stackoverflow.com/questions/20470626/python-script-for-raspberrypi-to-connect-wifi-automatically

but is linux specific, what OS do you need?

Laura


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


Re: help in understanding the stackless code

2015-06-18 Thread Laura Creighton
You need to send your message over here.
http://www.stackless.com/mailman/listinfo/stackless

I think I know the answer, from my work in duplicating stackless
for greenlets in pypy.  But that's the answer in theory.  In
practice, you need real stackless users.

Laura

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


Re: Keypress Input

2015-06-18 Thread Michael Torrie
On 06/18/2015 01:35 PM, Oscar Benjamin wrote:
> I use the following. I found in testing that when you push the button it
> prints 'Button pressed' 10 times a second (in actual use it calls poweroff
> so I guess bounce isn't an issue there). Is there some reason it needs to
> be cleverer in this case?

Yes, that would be expected, given your code has a while loop that never
exits.  Just curious what you expect the code to do that it's not doing.

You are probably right that debouncing isn't important in your
application.  So just add your poweroff command after the print()
statement, and break out of the loop:

...
while True:
time.sleep(0.1)
if not GPIO.input(PIN_NUM):
print('Button pressed')
# run shutdown command here
os.system('/usr/sbin/shutdown')
break



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


Re: Classic OOP in Python

2015-06-18 Thread Laura Creighton
In a message of Thu, 18 Jun 2015 11:50:28 +0100, Mark Lawrence writes:
>Throw in http://clonedigger.sourceforge.net/ as well and you've a really 
>awesome combination.
>
>Mark Lawrence
>

I didn't know about that one.
Hey thank you, Mark.  Looks great.

It needs its own entry in
https://wiki.python.org/moin/PythonTestingToolsTaxonomy

You add it, or me?

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


Re: Python File as the Default PDF handler for Windows

2015-06-18 Thread Chris Angelico
On Fri, Jun 19, 2015 at 7:04 AM, Naftali  wrote:
> What I want to do is write a pdf handler to handle windows open instruction. 
> In the script I would run a command line pdf unlocker on the file and open 
> the unlocked file with adobe (or the like).
>
> I've googled and though I get tons of 'how to open pdf from a python script' 
> I haven't found anything describing how to write and set up my python program 
> to deal with the pdf hand-off from the OS.
>

Possibly the reason you've found nothing is that this isn't actually a
Python issue :) What you want to do is tell your OS that when you
double-click on a PDF, it should run this program. That's better
referred to as "file associations". Different versions of Windows put
that in different places, but poke around in your GUI or on the
internet and you should be able to find something on updating
associations.

If you're having trouble getting a Python program to run in that
situation, it may help to explicitly name a Python interpreter - an
executable binary.

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


Re: Why this list of dictionaries doesn't work?

2015-06-18 Thread Steven D'Aprano
On Fri, 19 Jun 2015 03:57 am, Gilcan Machado wrote:

> Hi,
> 
> I'm trying to write a list of dictionaries like:
> 
> people = (
>  {'name':'john', 'age':12} ,
>  {'name':'kacey', 'age':18}
> )
> 
> 
> I've thought the code below would do the task.

Why don't you just use exactly what you have above? Just change the round
brackets (parentheses) to square brackets to change people from a tuple to
a list:

people = [{'name': 'john', 'age': 12}, {'name': 'kacey', 'age': 18}]

and you now have a list of two dicts.



> But it doesn't work.

What does it do? Does the computer catch fire? Blue Screen Of Death? Does
Python crash, or start printing "All work and no play makes Jack a dull
boy?" over and over again?

*wink*

You need to explain what you expected to happen and what actually happened,
not just "it doesn't work".


> And if I "print(people)" what I get is not the organize data structure
> like above.

Remember that Python doesn't *pretty-print* lists or dicts by default. If
you print people, you'll get all the information, but it may not be
displayed in what you consider a particularly pleasing or organized manner:

py> people = [{'name': 'john', 'age': 12}, {'name': 'kacey', 'age': 18}]
py> print(people)
[{'age': 12, 'name': 'john'}, {'age': 18, 'name': 'kacey'}]


If you want it displayed as in your original sample, you will need to write
your own print function.


> #!/usr/bin/env python
> from collections import defaultdict
> 
> person = defaultdict(dict)
> people = list()
> 
> person['name'] = 'jose'
> person['age'] = 12
> 
> people.append(person)

This is a little different from what you have above. It uses a defaultdict
instead of a regular dict, I presume you have some good reason for that.


> person['name'] = 'kacey'
> person['age'] = 18

This, however, if where you go wrong. You're not creating a second dict, you
are modifying the existing one. When you modify a dict, you modify it
everywhere it appears. So it doesn't matter whether you look at the
variable person, or if you look at the list people containing that dict,
you see the same value:

print(person)
print(people[0])

Both print the same thing, because they are the same dict (not mere copies).

Another way to put it, Python does *not* copy the dict when you insert it
into a list. So whether you look at people or person[0], you are looking at
the same object.

> people.append(person)

And now you append the same dict to the list, so it is in the list twice.
Now you have:

person
people[0]
people[1]


being three different ways to refer to the same dict, not three different
dicts.



-- 
Steven

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


Re: Documenting a function signature

2015-06-18 Thread Ben Finney
Laura Creighton  writes:

> In a message of Thu, 18 Jun 2015 10:04:46 +1000, Ben Finney writes:
> >Since the introduction of keyword-only arguments in Python functions,
> >the question arises of how to communicate this in documentation.
>
> I suppose it is way too late to scream "I hate keyword-only
> arguments"!

It's never too late for screams, go right ahead.

If you're hoping those screams will result in the keyword-arguments not
being part of Python now and in the future; yes, I think it's too late
for that :-)

-- 
 \  “If sharing a thing in no way diminishes it, it is not rightly |
  `\  owned if it is not shared.” —Augustine of Hippo (354–430 CE) |
_o__)  |
Ben Finney

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


Re: Python File as the Default PDF handler for Windows

2015-06-18 Thread Naftali
On Thursday, June 18, 2015 at 5:05:15 PM UTC-4, Naftali wrote:
> Long time lurker. 
> 
> I'm looking to register a python script as the default pdf reader for 
> windows. I assume I can just register the .py in the section windows section 
> for registering default handlers, but I'm wondering how to access the file 
> from within the program. 
> 
> The issue is this:
> 
> We have Java application that outputs user uploaded pdf files. It does this 
> simply by instructing windows to open the downloaded pdf file and windows 
> takes it from there. The data entry person will view the pdf and usually 
> upload it into another part of the system. Problem is the second leg of the 
> system modifies the pdf, and thus crashes when the pdf is protected against 
> writing. Data entry make use of a program to unlock them as needed but it is 
> an extra step and it only comes to their awareness after their client crashes 
> on the locked pdf (because it doesn't make sense to check them proactively.
> 
> I cannot change the Java system. 
> 
> What I want to do is write a pdf handler to handle windows open instruction. 
> In the script I would run a command line pdf unlocker on the file and open 
> the unlocked file with adobe (or the like). 
> 
> I've googled and though I get tons of 'how to open pdf from a python script' 
> I haven't found anything describing how to write and set up my python program 
> to deal with the pdf hand-off from the OS.

Thank you for responding, Chris:

I may be missing something in your reply, but I am *not* wondering how to 
associate python with the .pdf file extension. That I know how to do. What I 
want to know is how from within the program that I've told windows to run when 
the user clicks on the file --- how to access the file that the user wishes to 
open. Windows must somehow make that available to my program. How to I access 
it. Tomorrow, I'll try doing it an looping through the sys.argvs and see what's 
there. maybe it's a simple as passing a path into the called program.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python File as the Default PDF handler for Windows

2015-06-18 Thread Chris Angelico
On Fri, Jun 19, 2015 at 11:03 AM, Naftali  wrote:
> I may be missing something in your reply, but I am *not* wondering how to 
> associate python with the .pdf file extension. That I know how to do. What I 
> want to know is how from within the program that I've told windows to run 
> when the user clicks on the file --- how to access the file that the user 
> wishes to open. Windows must somehow make that available to my program. How 
> to I access it. Tomorrow, I'll try doing it an looping through the sys.argvs 
> and see what's there. maybe it's a simple as passing a path into the called 
> program.
>

Oh! I see what you mean. You should get the full path and name of the
file in sys.argv, but if you don't, I think what you need to do is add
"%s" to the end of the association definition. My apologies for the
prior misunderstanding.

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


Re: Python File as the Default PDF handler for Windows

2015-06-18 Thread Naftali
On Thursday, June 18, 2015 at 5:05:15 PM UTC-4, Naftali wrote:
> Long time lurker. 
> 
> I'm looking to register a python script as the default pdf reader for 
> windows. I assume I can just register the .py in the section windows section 
> for registering default handlers, but I'm wondering how to access the file 
> from within the program. 
> 
> The issue is this:
> 
> We have Java application that outputs user uploaded pdf files. It does this 
> simply by instructing windows to open the downloaded pdf file and windows 
> takes it from there. The data entry person will view the pdf and usually 
> upload it into another part of the system. Problem is the second leg of the 
> system modifies the pdf, and thus crashes when the pdf is protected against 
> writing. Data entry make use of a program to unlock them as needed but it is 
> an extra step and it only comes to their awareness after their client crashes 
> on the locked pdf (because it doesn't make sense to check them proactively.
> 
> I cannot change the Java system. 
> 
> What I want to do is write a pdf handler to handle windows open instruction. 
> In the script I would run a command line pdf unlocker on the file and open 
> the unlocked file with adobe (or the like). 
> 
> I've googled and though I get tons of 'how to open pdf from a python script' 
> I haven't found anything describing how to write and set up my python program 
> to deal with the pdf hand-off from the OS.


Thank you, Chris.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python File as the Default PDF handler for Windows

2015-06-18 Thread MRAB

On 2015-06-19 02:18, Chris Angelico wrote:

On Fri, Jun 19, 2015 at 11:03 AM, Naftali  wrote:

I may be missing something in your reply, but I am *not* wondering how to 
associate python with the .pdf file extension. That I know how to do. What I 
want to know is how from within the program that I've told windows to run when 
the user clicks on the file --- how to access the file that the user wishes to 
open. Windows must somehow make that available to my program. How to I access 
it. Tomorrow, I'll try doing it an looping through the sys.argvs and see what's 
there. maybe it's a simple as passing a path into the called program.



Oh! I see what you mean. You should get the full path and name of the
file in sys.argv, but if you don't, I think what you need to do is add
"%s" to the end of the association definition. My apologies for the
prior misunderstanding.


I don't think it should be "%s", but "%*".

This has more details:

https://technet.microsoft.com/en-us/library/bb490912.aspx

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


Re: Python File as the Default PDF handler for Windows

2015-06-18 Thread Chris Angelico
On Fri, Jun 19, 2015 at 11:39 AM, MRAB  wrote:
> I don't think it should be "%s", but "%*".

Thanks, it's been a while since I fiddled with Windows associations.

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


JSON Object to CSV File Troubleshooting

2015-06-18 Thread Sahlusar
Good Evening,

I have a conundrum regarding JSON objects and converting them to CSV:

Context

I am converting XML files to a JSON object (please see snippet below) and then 
finally producing a CSV file. Here is a an example JSON object:

"PAC": {
"Account": [{
"PC": "0",
"CMC": "0",
"WC": "0",
"DLA": "0",
"CN": null,
"FC": {
"Int32": ["0",
"0",
"0",
"0",
"0"]
},
"F": {
"Description": null,
"Code": "0"
}

In general, when I convert any of the files from JSON to CSV, I have been 
successful when using the following strategy (credit to Peter Otten):


import csv 
import json 
import sys 

def hook(obj): 
return obj 

def flatten(obj): 
for k, v in obj: 
if isinstance(v, list): 
yield from flatten(v) 
else: 
yield k, v 

if __name__ == "__main__": 
with open("somefileneame.json") as f: 
data = json.load(f, object_pairs_hook=hook) 

pairs = list(flatten(data)) 

writer = csv.writer(sys.stdout) 
header = writer.writerow([k for k, v in pairs]) 
row = writer.writerow([v for k, v in pairs]) #writer.writerows for any 
other iterable object


However with the example JSON object (above) i receive the following error when 
applying this function:

ValueError: too many values to unpack 


Here are some more samples. 

"FC": {"Int32": ["0","0","0","0","0","0"]} 
"PBA": {"Double": ["0","0","0","0","0","0","0","0"]} 

3.  "PBDD": { 
"DateTime": ["1/1/0001 12:00:00 
AM", 
"1/1/0001 12:00:00 AM", 
"1/1/0001 12:00:00 AM", 
"1/1/0001 12:00:00 AM", 
"1/1/0001 12:00:00 AM", 
"1/1/0001 12:00:00 AM", 
"1/1/0001 12:00:00 AM", 
"1/1/0001 12:00:00 AM"] 
}, 



In the above example, I would like to remove the keys Int32, Double and 
DateTime. I am wondering if there is a function or methodology that would allow 
me to remove such nested keys and reassign the new keys to the outer key (in 
this case above FC, PBA and PBDD) as column headers in a CSV and concatenate 
all of the values within the list (as corresponding fields). 

Also, here is how I strategized my XML to CSV conversion (if this is of any 
use):


import xml.etree.cElementTree as ElementTree
from xml.etree.ElementTree import XMLParser
import json 
import csv
import tokenize
import token
try:
from collections import OrderedDict
import json
except ImportError:
from ordereddict import OrderedDict
import simplejson as json
import itertools
import six
import string
from csvkit import CSVKitWriter


class XmlListConfig(list):
def __init__(self, aList):
for element in aList:
if element:
# treat like dict
if len(element) == 1 or element[0].tag != element[1].tag:
self.append(XmlDictConfig(element))
# treat like list
elif element[0].tag == element[1].tag:
self.append(XmlListConfig(element))
elif element.text:
text = element.text.strip()
if text:
self.append(text)


class XmlDictConfig(dict):
'''
Example usage:

>>> tree = ElementTree.parse('your_file.xml')
>>> root = tree.getroot()
>>> xmldict = XmlDictConfig(root)

Or, if you want to use an XML string:

>>> root = ElementTree.XML(xml_string)
>>> xmldict = XmlDictConfig(root)

And then use xmldict for what it is..a dictionary.
'''
def __init__(self, parent_element):
if parent_element.items():
self.update(dict(parent_element.items()))
for element in parent_element:
if element:
# treat like dict - we assume that if the first two tags
# in a series are different, then they are all different.
if len(element) == 1 or element[0].tag != element[1].tag:
  

Re: JSON Object to CSV Question

2015-06-18 Thread Steve Hayes
On Wed, 17 Jun 2015 17:49:35 -0400, Saran Ahluwalia
 wrote:

>Good Evening Everyone:
>
>I would like to have this JSON object written out to a CSV file so that the

You've already said that in another thread, and got several answers.
What are you? Some kind of troll?


-- 
Steve Hayes from Tshwane, South Africa
Web:  http://www.khanya.org.za/stevesig.htm
Blog: http://khanya.wordpress.com
E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: JSON Object to CSV File Troubleshooting

2015-06-18 Thread Steve Hayes
On Thu, 18 Jun 2015 18:47:30 -0700 (PDT), Sahlusar
 wrote:

>Good Evening,
>
>I have a conundrum regarding JSON objects and converting them to CSV:

That's the THIRD time you've asked this, in three separate threads.

Why don't you read the answers you were given the first time?

[follow-ups set]


-- 
Steve Hayes from Tshwane, South Africa
Web:  http://www.khanya.org.za/stevesig.htm
Blog: http://khanya.wordpress.com
E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Keypress Input

2015-06-18 Thread Christian Gollwitzer

Am 15.06.15 um 07:15 schrieb John McKenzie:


from Tkinter import *
from blinkstick import blinkstick

led = blinkstick.find_first()

timered = 0
timeyellow = 0
timeblue = 0

colour = None

root = Tk()
root.title('eFlag 1')



def red1(event):
 colour = 1

def yellow1(event):
 colour = 2

def blue1(event):
 colour = 3

root.bind_all('r', red1)
root.bind_all('b', blue1)
root.bind_all('y', yellow1)


The nonsense starts here:

===

root.mainloop()

while colour == None:
 led.pulse(red=0, green=255, blue=0, repeats=1, duration=5000,
steps=50)

while colour == 1:
 led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000,
steps=50)
 timered += 1

while colour == 2:
 led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000,
steps=50)
 timeyellow += 1

while colour == 3:
 led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000,
steps=50)
 timeblue += 1



it seems you don't understand event based programming. root.mainloop() 
never exits. It waits for the user input and does the dispatching, i.e. 
when a key is pressed, then according to your bindings, the functions 
red1, yellow1, blue1 are called, which set a variable but do not do 
nything else. To see that, just insert a print statement into these 
functions:


 def red1(event):
  colour = 1
  print("Red ws called")


Now your job is to also do the functionality there, i.e. you have to 
reformulate your task (waiting for red, then blue...) as a state 
machine. Alternatively you can circumvent to redo the logic in a state 
machine by using a coroutine.


You should read a text about GUI programming, or more specifically event 
based programming, to understand your mistake.


Christian




def exit_handler():
 print '\033[0;41;37mRed Team:\033[0m ', timered
 print '\033[0;43;30mYellow Time:\033[0m ', timeyellow
 print '\033[0;44;37mBlue Time:\033[0m ', timeblue
 flog = open('flag1log.text', 'a')
 flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue)
+ '\n')
 flog.close()
 atexit.register(exit_handler)




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