Re: Pythonic way to count sequences

2013-04-24 Thread Steven D'Aprano
On Wed, 24 Apr 2013 22:05:52 -0700, CM wrote:

> I have to count the number of various two-digit sequences in a list such
> as this:
> 
> mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4) sequence
> appears 2 times.)
> 
> and tally up the results, assigning each to a variable.  The inelegant
> first pass at this was something like...
> 
> # Create names and set them all to 0
> alpha = 0
> beta = 0
> delta = 0
> gamma = 0
> # etc...

Do they absolutely have to be global variables like that? Seems like a 
bad design, especially if you don't know in advance exactly how many 
there are.


> # loop over all the tuple sequences and increment appropriately for
> sequence_tuple in list_of_tuples:
> if sequence_tuple == (1,2):
> alpha += 1
> if sequence_tuple == (2,4):
> beta += 1
> if sequence_tuple == (2,5):
> delta +=1
> # etc... But I actually have more than 10 sequence types.

counts = {}
for t in list_of_tuples:
counts[t] = counts.get(t, 0) + 1


Or, use collections.Counter:

from collections import Counter
counts = Counter(list_of_tuples)


> # Finally, I need a list created like this: result_list = [alpha, beta,
> delta, gamma] #etc...in that order

Dicts are unordered, so getting the results in a specific order will be a 
bit tricky. You could do this:

results = sorted(counts.items(), key=lambda t: t[0])
results = [t[1] for t in results]

if you are lucky enough to have the desired order match the natural order 
of the tuples. Otherwise:

desired_order = [(2, 3), (3, 1), (1, 2), ...]
results = [counts.get(t, 0) for t in desired_order]



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


Re: how to: multiplayer game connecting to central server effectively?

2013-04-24 Thread webmaster
The idea is a risk game application and data collected and controlled by a 
gameserver, which happens to be a webserver too.
But for learning the principles, i want to start with tic-tac-toe multiplayer.


Thanks for your answers, I will read all your advices first now. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison Style

2013-04-24 Thread Chris Angelico
On Thu, Apr 25, 2013 at 3:49 PM, llanitedave  wrote:
> Given that
>
> s = some static value
> i = a value incremented during a loop
>
> I'm used to comparing them as
>
> if i == s:
> # some code
>
> But for some unknown reason I did a switch
>
> if s == i:
> # same code
>
> It didn't seem to make any difference at first glance, so I just got to 
> wondering --

It won't make any difference in any sort of sane code. If there's any
situation in which == is not reflexive, something seriously nasty is
going on.

> Is there a standard for comparison order?  Is there any kind of performance 
> difference?  Is there even a tradition for one or the other?  Are there any 
> gotchas?

It's conventional to compare variables to constants, not constants to
variables (even in C where there's the possibility of mucking up the
operator, most people still compare variables to constants). I'd
normally use "i == s" there, treating s as a constant for the purpose
of the loop. Unless you're deliberately being poetical, language such
as "Three is the number thou shalt count" is distinctly abnormal, so
saying "if (5 == i)" is equally awkward. It's nothing major; mostly
it's like the algebraic convention of putting the more-known elements
earlier in a term (eg 2πix - 2 is known, 3.14159 is mostly known,
i is imaginary but at least it's constant, and x is unknown).

> Do I need to get a hobby?

I thought programming WAS a hobby?

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


Comparison Style

2013-04-24 Thread llanitedave
Given that 

s = some static value
i = a value incremented during a loop

I'm used to comparing them as

if i == s:
# some code

But for some unknown reason I did a switch

if s == i:
# same code

It didn't seem to make any difference at first glance, so I just got to 
wondering --

Is there a standard for comparison order?  Is there any kind of performance 
difference?  Is there even a tradition for one or the other?  Are there any 
gotchas?

Do I need to get a hobby?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to count sequences

2013-04-24 Thread Chris Angelico
On Thu, Apr 25, 2013 at 3:05 PM, CM  wrote:
> I have to count the number of various two-digit sequences in a list
> such as this:
>
> mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4)
> sequence appears 2 times.)
>
> and tally up the results, assigning each to a variable.

You can use a tuple as a dictionary key, just like you would a string.
So you can count them up directly with a dictionary:

count = {}
for sequence_tuple in list_of_tuples:
count[sequence_tuple] = count.get(sequence_tuple,0) + 1

Also, since this is such a common thing to do, there's a standard
library way of doing it:

import collections
count = collections.Counter(list_of_tuples)

This doesn't depend on knowing ahead of time what your elements will
be. At the end of it, you can simply iterate over 'count' and get all
your counts:

for sequence,number in count.items():
print("%d of %r" % (number,sequence))

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


Pythonic way to count sequences

2013-04-24 Thread CM
I have to count the number of various two-digit sequences in a list
such as this:

mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4)
sequence appears 2 times.)

and tally up the results, assigning each to a variable.  The inelegant
first pass at this was something like...

# Create names and set them all to 0
alpha = 0
beta = 0
delta = 0
gamma = 0
# etc...

# loop over all the tuple sequences and increment appropriately
for sequence_tuple in list_of_tuples:
if sequence_tuple == (1,2):
alpha += 1
if sequence_tuple == (2,4):
beta += 1
if sequence_tuple == (2,5):
delta +=1
# etc... But I actually have more than 10 sequence types.

# Finally, I need a list created like this:
result_list = [alpha, beta, delta, gamma] #etc...in that order

I can sense there is very likely an elegant/Pythonic way to do this,
and probably with a dict, or possibly with some Python structure I
don't typically use.  Suggestions sought.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IPython in Emacs

2013-04-24 Thread rusi
On Apr 25, 8:35 am, Seb  wrote:
> Hi,
>
> Please excuse the slightly off-topic query.  I'm learning Python, using
> the IPython (0.13) shell, and wanted to run it from Emacs 24.  AFAICT,
> python.el is the most actively developed library, and is included in
> Emacs.  How do experienced Python programmers set up their python.el to
> make the best of it?  I've done it following the recommendations given
> in the library¹:
>
> (setq
>  python-shell-interpreter "ipython"
>  python-shell-interpreter-args ""
>  python-shell-prompt-regexp "In \\[[0-9]+\\]: "
>  python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
>  python-shell-completion-setup-code
>  "from IPython.core.completerlib import module_completion"
>  python-shell-completion-module-string-code
>  "';'.join(module_completion('''%s'''))\n"
>  python-shell-completion-string-code
>  "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
>
> but this may be a little outdated as it refers to IPython 0.11.
>
> Thanks,
> Seb
>
> +--- Footnotes ---+
> ¹ Ignored recommended setting for `python-shell-interpreter-args'

There were some ipython+emacs+windows bugs:
https://bugs.launchpad.net/ipython/+bug/290228

Last I tried nearly 2 years, they were still there
http://groups.google.com/group/comp.lang.python/browse_thread/thread/36e757567f28368e

[Since you did not say whether you are on windows or *nix, just saying]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: epiphany

2013-04-24 Thread Steven D'Aprano
On Wed, 24 Apr 2013 19:25:37 -0700, Ethan Furman wrote:

> On 04/24/2013 06:35 PM, Steven D'Aprano wrote:
>> Objects are supposed to return NotImplemented from special dunder
>> methods like __add__, __lt__, etc. to say "I don't know how to
>> implement this method for the given argument". Python will then try
>> calling the other object's special method. If both objects return
>> NotImplemented, Python falls back on whatever default behaviour is
>> appropriate.
>>
>> So, knowing nothing of your application, I fear that this is an abuse
>> of NotImplemented's semantics. If a rule returns NotImplemented, I
>> would expect your application to fall back on a different rule. If
>> that's not the case, you're using it in a non-standard way that will
>> cause confusion for those with expectations of what NotImplemented
>> means.
> 
> Why would you assume some random application is going to deal with
> NotImplemented the same way the python interpreter does?


Why would you assume that some random application is going to treat x==y 
the same way the Python interpreter does?

Just because you can design your objects to do anything you want doesn't 
mean you should. Breaking conventions carries costs by the mere fact that 
you're breaking conventions. There are established semantics that an 
experienced Python developer will expect for NotImplemented, and doing 
something else risks causing confusion and mistakes.

Or worse, bugs. If there is any chance that a rule might be called in a 
context where the Python interpreter gets to interpret the return result 
before you see it, then returning NotImplemented could lead to difficult 
to debug problems.



> And even the
> interpreter isn't consistent -- sometimes it will return false (__eq__)
> and sometimes it will raise an Exception (__add__).

As I said:

"If both objects return NotImplemented, Python falls back on whatever 
default behaviour is appropriate."

If neither object knows how to compare the other for equality, the 
appropriate behaviour is to treat them as unequal. If neither object 
knows how to add itself to the other, the appropriate behaviour is to 
raise an exception.


> I hardly think it an abuse of NotImplemented to signal something is not
> implemented when NotImplemented means, um, not implemented.

It doesn't just mean "not implemented in general", it has a specific 
meaning: "I don't know what to do here, let the other object handle it".

As I have repeatedly said, I don't know the context of the application, 
but from what little has been described, this part of it doesn't feel to 
me like a good, clean design. I might be wrong, but from the outside it 
feels like the API should be that rules return a three-state logic 
instance:

True, False, Unknown

where Unknown can be trivially created with 

Unknown = object()

The semantics of NotImplementedError is that it is an *error*, and that 
doesn't sound appropriate given the example shown. Why would a rule that 
raises an *error* exception be treated as if it had passed? That's just 
wrong.

The semantics of NotImplemented is that it is a signal for one object to 
say "I don't know how to do this, let somebody else try". That also 
doesn't seem appropriate. There's no sign that Roy's application does the 
equivalent to this:

result = rule()
if result is NotImplemented:
result = another_rule()
if result is NotImplemented:
result = some_default


Since rules apparently take no arguments, either:

1) they rely on global state, which is a nasty design; or

2) rules actually have a fixed return result, in which case why make them 
functions in the first place?


Since both possibilities seem stupid, and I do not believe that Roy 
actually is stupid, I suspect that his example over-simplifies the 
situation. But I can't comment on the infinite number of things that his 
code might do, I can only comment on the examples as actually given, and 
as given, I don't think that either NotImplementedError or NotImplemented 
is a clean solution to the problem.


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


IPython in Emacs

2013-04-24 Thread Seb
Hi,

Please excuse the slightly off-topic query.  I'm learning Python, using
the IPython (0.13) shell, and wanted to run it from Emacs 24.  AFAICT,
python.el is the most actively developed library, and is included in
Emacs.  How do experienced Python programmers set up their python.el to
make the best of it?  I've done it following the recommendations given
in the library¹:

(setq
 python-shell-interpreter "ipython"
 python-shell-interpreter-args ""
 python-shell-prompt-regexp "In \\[[0-9]+\\]: "
 python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
 python-shell-completion-setup-code
 "from IPython.core.completerlib import module_completion"
 python-shell-completion-module-string-code
 "';'.join(module_completion('''%s'''))\n"
 python-shell-completion-string-code
 "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")

but this may be a little outdated as it refers to IPython 0.11.

Thanks,
Seb

+--- Footnotes ---+
¹ Ignored recommended setting for `python-shell-interpreter-args'

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


Re: My gui

2013-04-24 Thread Chris Angelico
On Thu, Apr 25, 2013 at 3:08 AM, Daniel Kersgaard
 wrote:
> import tkinter
> import tkinter.messagebox
>
> class MyGui:
> def _init_(self):
> ... all code here
>
> poop = MyGui()

As already mentioned, changing that to __init__ makes everything work
(I just tested in Python 3.3 on Windows). But since Python is not
Java, there's no reason to bury all this code in a class; just move
all that code flush left and abandon the explicit instantiation. The
constructor doesn't return until the window's been closed, so there's
really no point in returning an object. (Maybe if you remove the
mainloop() call, you could possibly make use of two of these sorts of
windows, but YAGNI - don't bother with the complexity required to
handle multiple simultaneous windows until you have a use-case.)

So here's a direct translation to top-level code:

import tkinter
import tkinter.messagebox

def convert():
kilo = float(kilo_entry.get())
miles = kilo * 0.6214
tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is
equal to ' + str(miles) + 'miles.')

main_window = tkinter.Tk()

top_frame = tkinter.Frame(main_window)
bottom_frame = tkinter.Frame(main_window)

prompt_label = tkinter.Label(top_frame, text = 'Enter a distance in
Kilometers: ')
kilo_entry = tkinter.Entry(top_frame, width = 10)

prompt_label.pack(side = 'left')
kilo_entry.pack(side = 'left')

calc_button = tkinter.Button(bottom_frame, text = 'Convert', command = convert)

quit_button = tkinter.Button(bottom_frame, text = 'Quit', command =
main_window.destroy)

calc_button.pack(side = 'left')
quit_button.pack(side = 'left')

top_frame.pack()
bottom_frame.pack()

tkinter.mainloop()


-- cut --

(You may want to bury the code inside a main(), but that's optional too.)

And here's a slightly modified version:

import tkinter
import tkinter.messagebox

main_window = tkinter.Tk()
top_frame = tkinter.Frame(main_window)
bottom_frame = tkinter.Frame(main_window)

tkinter.Label(top_frame, text = 'Enter a distance in Kilometers:
').pack(side = 'left')
km_entry = tkinter.Entry(top_frame, width = 10); km_entry.pack(side = 'left')

def convert():
km = float(km_entry.get())
miles = km * 0.6214
tkinter.messagebox.showinfo('Result', '%.2f kilometers is equal to
%.2f miles.' % (km, miles) )

tkinter.Button(bottom_frame, text = 'Convert', command =
convert).pack(side = 'left')
tkinter.Button(bottom_frame, text = 'Quit', command =
main_window.destroy).pack(side = 'left')

top_frame.pack()
bottom_frame.pack()

tkinter.mainloop()

-- cut --

I've removed some redundant variables (you don't need to hang onto
references to your labels,just pack 'em in and be done), and reordered
the code a bit to put the Convert button's function right near where
the Convert button is created (take your pick - do you prefer that, or
to have all the other functions up top? Both are viable); I also
changed your message box to use percent-formatting with fixed decimals
rather than str(), to tidy up the display a bit. Oh, and renamed
"kilo" to "km", because to me "kilo" means "kilogram". :)

This version of the code isn't necessarily better in every way, but
it's different. Like the Oracle in The Matrix, I want you to make up
your own mind as to what you ought to do; maybe you'll like some of my
changes, maybe you won't, but either way you're making an intelligent
decision about code style :)

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


Re: how to: multiplayer game connecting to central server effectively?

2013-04-24 Thread Chris Angelico
On Thu, Apr 25, 2013 at 6:59 AM,   wrote:
> hi,
> I struggle for some days about a "model" for a multiplayer game application.
> I read so much from my enemy Google, i got lost by all that info and dont 
> know which path i should chose.
>
> a multiplayer game application, sending/receiving  instantly every change in 
> the game to a central webserver, http://www.x.com, probably via socket 
> connection?
>
> which system/module should i use for this contineous connection and where can 
> i find a good tutorial, which a beginner like me can understand a bit? (i 
> have read too many too complicated/technical artickles, but no nice 
> tutorials).
>
> i have tried and accompished an urllib connection, with get and post 
> variabels, but that will be polling, with all the http-overhead for every 
> poll. I think this is also to slow and no "real" updating of the game status.
>
> Thanks in advance for any hint/tutorial i get:)

The easiest way to start would be a MUD or chat server. Establish a
TCP socket, then whenever anything happens, report the change to all
connected sockets. In its simplest form:

* Accept connection
* Wait for login (or, for a simple test, just "Enter your name: " would do)
* Add connection to pool
* Whenever a line of text is received, prepend the name and send it to
every connection in the pool.

That's a basic chat server. A MUD adds only a small bit of
complication: you need some form of command parser, and not everything
will announce to all connected clients. I can walk you through a lot
of this, but I haven't done most of it in Python; there's another
language, very similar in semantics, which is better suited to MUD
building: Pike. But it's all similar enough that you'll be able to do
it in either.

The project you're looking at sounds to me like it'd be well
implemented as a MUD-style connection with a fancy client in front of
it. Debug your system using the MUD connection, and make sure you
don't have any security holes that can be exploited by someone
switching out your client for a custom one; because, believe you me,
someone will figure out how to do it. (If you're concerned about
privacy, you can easily switch in SSL/TLS, while not fundamentally
changing any of your code.) Start with something as simple as you
possibly can, and then add complication only as you find you need it.

Here's the module you'll be wanting:
http://docs.python.org/3.3/library/socket.html

(By the way, you won't be connecting to a *web* server. Your central
server will be quite separate from that system. It might happen to be
the same computer, but there's no real connection.)

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


Re: epiphany

2013-04-24 Thread Ethan Furman

On 04/24/2013 07:20 PM, Chris Angelico wrote:

On Thu, Apr 25, 2013 at 11:41 AM, Roy Smith  wrote:

In article <5178884b$0$29977$c3e8da3$54964...@news.astraweb.com>,
  Steven D'Aprano  wrote:


I don't see why you would need anything like that. Reading further on, I
see that you are counting unimplemented rules as true, for some reason
which I don't understand.


The top-level logic we need to enforce is "this configuration doesn't
violate any rules".


Then have your unimplemented rules simply return True. Easy!


And less clear.

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


Re: My gui

2013-04-24 Thread Terry Jan Reedy

On 4/24/2013 1:53 PM, Chris “Kwpolska” Warrick wrote:


Please try fixing it and running it _outside of IDLE_, which is also
built in Tk


The default mode of Idle runs user code in a separate process. Editing 
tkinter code with Idle and running it (in the separate process) should 
be no problem.




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


Re: epiphany

2013-04-24 Thread Ethan Furman

On 04/24/2013 06:35 PM, Steven D'Aprano wrote:

Objects are supposed to return NotImplemented from special dunder methods
like __add__, __lt__, etc. to say "I don't know how to implement this
method for the given argument". Python will then try calling the other
object's special method. If both objects return NotImplemented, Python
falls back on whatever default behaviour is appropriate.

So, knowing nothing of your application, I fear that this is an abuse of
NotImplemented's semantics. If a rule returns NotImplemented, I would
expect your application to fall back on a different rule. If that's not
the case, you're using it in a non-standard way that will cause confusion
for those with expectations of what NotImplemented means.


Why would you assume some random application is going to deal with NotImplemented the same way the python interpreter 
does?  And even the interpreter isn't consistent -- sometimes it will return false (__eq__) and sometimes it will raise 
an Exception (__add__).


I hardly think it an abuse of NotImplemented to signal something is not implemented when NotImplemented means, um, not 
implemented.


possibly-not-implemented-ly yours,

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


Re: epiphany

2013-04-24 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> On Thu, Apr 25, 2013 at 11:41 AM, Roy Smith  wrote:
> > In article <5178884b$0$29977$c3e8da3$54964...@news.astraweb.com>,
> >  Steven D'Aprano  wrote:
> >
> >> I don't see why you would need anything like that. Reading further on, I
> >> see that you are counting unimplemented rules as true, for some reason
> >> which I don't understand.
> >
> > The top-level logic we need to enforce is "this configuration doesn't
> > violate any rules".
> 
> Then have your unimplemented rules simply return True. Easy!
> 
> ChrisA

It's nice to have tri-state logic:

* This rule passes

* This rule fails

* This rule was not evaluated

What I've got now expresses that perfectly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: epiphany

2013-04-24 Thread Chris Angelico
On Thu, Apr 25, 2013 at 11:41 AM, Roy Smith  wrote:
> In article <5178884b$0$29977$c3e8da3$54964...@news.astraweb.com>,
>  Steven D'Aprano  wrote:
>
>> I don't see why you would need anything like that. Reading further on, I
>> see that you are counting unimplemented rules as true, for some reason
>> which I don't understand.
>
> The top-level logic we need to enforce is "this configuration doesn't
> violate any rules".

Then have your unimplemented rules simply return True. Easy!

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


Re: epiphany

2013-04-24 Thread Roy Smith
In article <5178884b$0$29977$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> I don't see why you would need anything like that. Reading further on, I 
> see that you are counting unimplemented rules as true, for some reason 
> which I don't understand.

The top-level logic we need to enforce is "this configuration doesn't 
violate any rules".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: epiphany

2013-04-24 Thread Steven D'Aprano
On Wed, 24 Apr 2013 19:50:33 -0400, Roy Smith wrote:

> I discovered something really neat today.
> 
> We've got a system with a bunch of rules.  Each rule is a method which
> returns True or False.  At some point, we need to know if all the rules
> are True.  Complicating things, not all the rules are implemented. Those
> that are not implemented raise NotImplementedError.


NotImplementedError is intended to be raised by abstract base classes to 
indicate a method that must be overridden. I also use it as a place-
holder for functions or methods I haven't actually written yet. I'm not 
sure what semantics you're giving NotImplementedError in your code, but I 
wonder whether a neater solution might be to just use rule = None for 
unimplemented rules, rather than:

def unimplemented():
raise NotImplementedError

rule = unimplemented

Then your logic for seeing if all rules return true would become:

all(r() for r in rules if r is not None)

and for seeing if all rules return true or are unimplemented:

all(r is None or r() for r in rules)



> We used to have some ugly logic which kept track of which rules were
> active and only evaluated those.

I don't see why you would need anything like that. Reading further on, I 
see that you are counting unimplemented rules as true, for some reason 
which I don't understand. (Knowing nothing of your use-case, I would have 
expected intuitively that unimplemented rules count as not true.) A 
simple helper function will do the job:


def eval(rule):
try:
return rule()
except NotImplementedError:
return True

everything_is_true = all(eval(r) for r in rules)



No need for complicated ugly logic keeping track of what rules are 
implemented. But if you're worried about the cost of catching those 
exceptions (you've profiled your code, right?) then that's easy with a 
decorator:


def not_implemented(func):
@functools.wraps(func)
def inner(*args, **kw):
raise NotImplementedError
inner.ni = True
return inner


# Decorate only the rules you want to be unimplemented.

@not_implemented
def my_rule():
pass


everything_is_true = all(r() for r in rules if not hasattr(r, 'ni'))



Note that if you could reverse the logic so that unimplemented rules 
count as not true, this will also work:

try:
everything_is_true = all(r() for r in rules)
except NotImplementedError:
everything_is_true = False



> So, here's the neat thing.  It turns out that bool(NotImplemented)
> returns True.  By changing the unimplemented rules from raising
> NotImplementedError to returning NotImplemented, the whole thing
> becomes:
> 
> return all(r() for r in rules)

Objects are supposed to return NotImplemented from special dunder methods 
like __add__, __lt__, etc. to say "I don't know how to implement this 
method for the given argument". Python will then try calling the other 
object's special method. If both objects return NotImplemented, Python 
falls back on whatever default behaviour is appropriate.

So, knowing nothing of your application, I fear that this is an abuse of 
NotImplemented's semantics. If a rule returns NotImplemented, I would 
expect your application to fall back on a different rule. If that's not 
the case, you're using it in a non-standard way that will cause confusion 
for those with expectations of what NotImplemented means.



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


Re: Scan CSV file and saving it into an array

2013-04-24 Thread Oscar Benjamin
On 25 April 2013 00:01, Ana Dionísio  wrote:
> Hello!
>
> I have this script that scans a csv file and if the value in the first column 
> == 200 it saves that row into an array.
>
> The problem is, I need to save that row and the next 10 rows in that same 
> array. What can I add to the script so it does that? I tried to do for row in 
> len(10): but I get an error.
>
>
> p = csv.reader(open('file.csv'), delimiter=';')
> a=[0]*2881
> a = numpy.array(a, dtype=dict)

You shouldn't be using a numpy array for this; use a list instead. I
suggest that you have a go at the Python tutorial and avoid using
numpy until you are more confident with the basics of Python itself.

The tutorial (for Python 2) is here:
http://docs.python.org/2/tutorial/


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


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread Dave Angel

On 04/24/2013 08:00 PM, Oscar Benjamin wrote:

On 25 April 2013 00:26, Dave Angel  wrote:

On 04/24/2013 05:09 PM, William Ray Wing wrote:



   



My question is why bother with multithreading?  Why not just do these as
separate processes?  You said "they in no way interact with each other" and
that's a clear clue that separate processes would be cleaner.


It's using multiprocessing rather than threads: they are separate processes.



You're right;  I was completely off base.  brain-freeze.






It's state that is passed to it by the subprocess and should only be
accessed by the top-level process after the subprocess completes (I
think!).



Separate processes will find it much more difficult to interact, which is a
good thing most of the time.  Further, they seem to be scheduled more
efficiently because of the GIL, though that may not make that much
difference when you're time-limited by network data.


They are separate processes and do not share the GIL (unless I'm very
much mistaken).


No, you're not mistaken.  Somehow I interpreted the original as saying 
multi-thread, and everything else was wrong as a result.  Now it sounds 
like a bug in, or misuse of, the Pool class.




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


Re: Scan CSV file and saving it into an array

2013-04-24 Thread Dave Angel

On 04/24/2013 07:01 PM, Ana Dionísio wrote:

Hello!

I have this script that scans a csv file and if the value in the first column 
== 200 it saves that row into an array.


No it doesn't. It creates a list, then overwrites it with a numpy array, 
then overwrites that with a list of strings representing one row.


If you want to really use a Python array, then read here:

   http://docs.python.org/2/library/array.html

It'd probably be best to start with a precise problem statement, 
presumably copied from your textbook or assignment sheet.  What python 
version is this for?  And what OS?  (that affects whether you need a 
file mode)  Exactly what data structure are you trying to build?  What 
type of a csv file are you trying to use?  Is there a standard header 
line?  How big might the file be?  What behavior do you want if there's 
no line that begins with the field "200"?  Or if there's more than one 
such line?  Or if there are less than 10 lines following it in the file? 
 What about a field of "0200"?




The problem is, I need to save that row and the next 10 rows in that same 
array. What can I add to the script so it does that? I tried to do for row in 
len(10): but I get an error.



When you say "get an error" it could be one of many things.  In this 
case, it's obvious, since len() doesn't make sense with an integer 
parameter.  But in general you want to say either:


1) it gave me the wrong result.  I expected  and got 
2) it did nothing at all.
3) it gave an exception, and here's the full traceback.




p = csv.reader(open('file.csv'), delimiter=';')
a=[0]*2881
a = numpy.array(a, dtype=dict)


These two lines do nothing useful, and they confuse the reader of the 
code, since they imply that the list will end up of size 2881, and/or as 
a numpy array.



for row in p:
if row[0]=="200":
   a=row
   break


missing else clause. How do you detect that there was no match?


print a




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


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread Oscar Benjamin
On 25 April 2013 00:26, Dave Angel  wrote:
> On 04/24/2013 05:09 PM, William Ray Wing wrote:
>>
>> On Apr 24, 2013, at 4:31 PM, Neil Cerutti  wrote:
>>
>>> On 2013-04-24, William Ray Wing  wrote:

 When I look at the pool module, the error is occurring in
 get(self, timeout=None) on the line after the final else:

 def get(self, timeout=None):
 self.wait(timeout)
 if not self._ready:
 raise TimeoutError
 if self._success:
 return self._value
 else:
 raise self._value
>>>
>>>
>>> The code that's failing is in self.wait. Somewhere in there you
>>> must be masking an exception and storing it in self._value
>>> instead of letting it propogate and crash your program. This is
>>> hiding the actual context.
>>>
>>> --
>>> Neil Cerutti
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>> I'm sorry, I'm not following you.  The "get" routine (and thus self.wait)
>> is part of the "pool" module in the Python multiprocessing library.
>> None of my code has a class or function named "get".
>>
>> -Bill
>>
>
> My question is why bother with multithreading?  Why not just do these as
> separate processes?  You said "they in no way interact with each other" and
> that's a clear clue that separate processes would be cleaner.

It's using multiprocessing rather than threads: they are separate processes.

>
> Without knowing anything about those libraries, I'd guess that somewhere
> they do store state in a global attribute or equivalent, and when that is
> accessed by both threads, it can crash.

It's state that is passed to it by the subprocess and should only be
accessed by the top-level process after the subprocess completes (I
think!).

>
> Separate processes will find it much more difficult to interact, which is a
> good thing most of the time.  Further, they seem to be scheduled more
> efficiently because of the GIL, though that may not make that much
> difference when you're time-limited by network data.

They are separate processes and do not share the GIL (unless I'm very
much mistaken). Also I think the underlying program is limited by the
call to sleep for 15 seconds.


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


epiphany

2013-04-24 Thread Roy Smith
I discovered something really neat today.

We've got a system with a bunch of rules.  Each rule is a method which 
returns True or False.  At some point, we need to know if all the rules 
are True.  Complicating things, not all the rules are implemented.  
Those that are not implemented raise NotImplementedError.

We used to have some ugly logic which kept track of which rules were 
active and only evaluated those.

So, here's the neat thing.  It turns out that bool(NotImplemented) 
returns True.  By changing the unimplemented rules from raising 
NotImplementedError to returning NotImplemented, the whole thing becomes:

return all(r() for r in rules)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scan CSV file and saving it into an array

2013-04-24 Thread Dave Angel

On 04/24/2013 07:21 PM, Rhodri James wrote:

On Thu, 25 Apr 2013 00:01:01 +0100, Ana Dionísio
 wrote:



  

Odd that this subject should have come up so many times in various
guises in the last week or two.



Not that odd.  In a larger classroom I'd expect several of the students 
to have enough internet savvy to find a forum like this.


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


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread Dave Angel

On 04/24/2013 05:09 PM, William Ray Wing wrote:

On Apr 24, 2013, at 4:31 PM, Neil Cerutti  wrote:


On 2013-04-24, William Ray Wing  wrote:

When I look at the pool module, the error is occurring in
get(self, timeout=None) on the line after the final else:

def get(self, timeout=None):
self.wait(timeout)
if not self._ready:
raise TimeoutError
if self._success:
return self._value
else:
raise self._value


The code that's failing is in self.wait. Somewhere in there you
must be masking an exception and storing it in self._value
instead of letting it propogate and crash your program. This is
hiding the actual context.

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


I'm sorry, I'm not following you.  The "get" routine (and thus self.wait) is part of the 
"pool" module in the Python multiprocessing library.
None of my code has a class or function named "get".

-Bill



My question is why bother with multithreading?  Why not just do these as 
separate processes?  You said "they in no way interact with each other" 
and that's a clear clue that separate processes would be cleaner.


Without knowing anything about those libraries, I'd guess that somewhere 
they do store state in a global attribute or equivalent, and when that 
is accessed by both threads, it can crash.


Separate processes will find it much more difficult to interact, which 
is a good thing most of the time.  Further, they seem to be scheduled 
more efficiently because of the GIL, though that may not make that much 
difference when you're time-limited by network data.


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


Re: Scan CSV file and saving it into an array

2013-04-24 Thread Rhodri James
On Thu, 25 Apr 2013 00:01:01 +0100, Ana Dionísio  
 wrote:



I tried to do for row in len(10): but I get an error.


Please remember to tell us what error, with the traceback, so that we can  
make fun of you for not reading it :-)  In this case it's pretty obvious;  
Python will complain that you can't call len() on an integer (because it's  
not a container type, so the whole idea of "length" is meaningless).  You  
probably meant to use "range(10)" instead of "len(10)", but then "row"  
would be the integers from 0 to 9 inclusive, which isn't what you want  
either.


What you actually want to do is "row = p.next()" (in Python 2.x) or "row =  
next(p)" (in Python 3.x) to get the next row from the CSV file, add it to  
the array and repeat until you have ten more lines.  Another for-loop will  
make this less tedious to write.


Odd that this subject should have come up so many times in various guises  
in the last week or two.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Scan CSV file and saving it into an array

2013-04-24 Thread Ana Dionísio
Hello!

I have this script that scans a csv file and if the value in the first column 
== 200 it saves that row into an array.

The problem is, I need to save that row and the next 10 rows in that same 
array. What can I add to the script so it does that? I tried to do for row in 
len(10): but I get an error.


p = csv.reader(open('file.csv'), delimiter=';')
a=[0]*2881
a = numpy.array(a, dtype=dict)
for row in p:
   if row[0]=="200":
  a=row
  break
print a
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread MRAB

On 24/04/2013 20:25, William Ray Wing wrote:

I run a bit of python code that monitors my connection to the greater Internet. 
 It checks connectivity to the requested target IP addresses, logging both 
successes and failures, once every 15 seconds.  I see failures quite regularly, 
predictably on Sunday nights after midnight when various networks are 
undergoing maintenance.  I'm trying to use python's multiprocessing library to 
run multiple copies in parallel to check connectivity to different parts of the 
country (they in no way interact with each other).

On rare occasions (maybe once every couple of months) I get the following 
exception and traceback:

Traceback (most recent call last):
   File "./CM_Harness.py", line 12, in 
 Foo = pool.map(monitor, targets)# and hands off two targets
   File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py",
 line 227, in map
 return self.map_async(func, iterable, chunksize).get()
   File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py",
 line 528, in get
 raise self._value
IndexError: list index out of range

The code where the traceback occurs is:

#!/usr/bin/env python

""" Harness to call multiple parallel copies
 of the basic monitor program
"""

from multiprocessing import Pool
from Connection_Monitor import monitor

targets = ["8.8.8.8", "www.ncsa.edu"]
pool = Pool(processes=2)# start 2 worker processes
Foo = pool.map(monitor, targets)# and hands off two targets


Line 12, in my code is simply the line that launches the underlying monitor 
code.  I'm assuming that the real error is occurring in the monitor program 
that is being launched, but I'm at a loss as to what to do to get a better 
handle on what's going wrong. Since, as I said, I see failures quite regularly, 
typically on Sunday nights after midnight when various networks are undergoing 
maintenance, I don't _think_ the exception is being triggered by that sort of 
failure.


[snip]
If the exception is being raised by 'monitor', you could try catching
the exception within that (or write a simple wrapper function which
calls it), write the traceback to a logfile, and then re-raise.

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


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread Oscar Benjamin
On 24 April 2013 20:25, William Ray Wing  wrote:
> I run a bit of python code that monitors my connection to the greater 
> Internet.  It checks connectivity to the requested target IP addresses, 
> logging both successes and failures, once every 15 seconds.  I see failures 
> quite regularly, predictably on Sunday nights after midnight when various 
> networks are undergoing maintenance.  I'm trying to use python's 
> multiprocessing library to run multiple copies in parallel to check 
> connectivity to different parts of the country (they in no way interact with 
> each other).
>
> On rare occasions (maybe once every couple of months) I get the following 
> exception and traceback:
>
> Traceback (most recent call last):
>   File "./CM_Harness.py", line 12, in 
> Foo = pool.map(monitor, targets)# and hands off two targets
>   File 
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py",
>  line 227, in map
> return self.map_async(func, iterable, chunksize).get()
>   File 
> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py",
>  line 528, in get
> raise self._value
> IndexError: list index out of range
>
> The code where the traceback occurs is:
>
> #!/usr/bin/env python
>
> """ Harness to call multiple parallel copies
> of the basic monitor program
> """
>
> from multiprocessing import Pool
> from Connection_Monitor import monitor
>
> targets = ["8.8.8.8", "www.ncsa.edu"]
> pool = Pool(processes=2)# start 2 worker processes
> Foo = pool.map(monitor, targets)# and hands off two targets
>
>
> Line 12, in my code is simply the line that launches the underlying monitor 
> code.  I'm assuming that the real error is occurring in the monitor program 
> that is being launched, but I'm at a loss as to what to do to get a better 
> handle on what's going wrong. Since, as I said, I see failures quite 
> regularly, typically on Sunday nights after midnight when various networks 
> are undergoing maintenance, I don't _think_ the exception is being triggered 
> by that sort of failure.
>
> When I look at the pool module, the error is occurring in get(self, 
> timeout=None) on the line after the final else:
>
> def get(self, timeout=None):
> self.wait(timeout)
> if not self._ready:
> raise TimeoutError
> if self._success:
> return self._value
> else:
> raise self._value
>
>
> Python v 2.7.3, from Python.org, running on Mac OS-X 10.8.3

This looks to me like a bug in multiprocessing but I'm not very
experienced with it. Perhaps it would be good to open an issue on the
tracker. It might not be solvable without an easier way of reproducing
it though.


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


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread William Ray Wing
On Apr 24, 2013, at 4:31 PM, Neil Cerutti  wrote:

> On 2013-04-24, William Ray Wing  wrote:
>> When I look at the pool module, the error is occurring in
>> get(self, timeout=None) on the line after the final else:
>> 
>>def get(self, timeout=None):
>>self.wait(timeout)
>>if not self._ready:
>>raise TimeoutError
>>if self._success:
>>return self._value
>>else:
>>raise self._value
> 
> The code that's failing is in self.wait. Somewhere in there you
> must be masking an exception and storing it in self._value
> instead of letting it propogate and crash your program. This is
> hiding the actual context.
> 
> -- 
> Neil Cerutti
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I'm sorry, I'm not following you.  The "get" routine (and thus self.wait) is 
part of the "pool" module in the Python multiprocessing library.
None of my code has a class or function named "get".

-Bill

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


Re: how to: multiplayer game connecting to central server effectively?

2013-04-24 Thread Fábio Santos
This series of articles is flash-based, and the examples apparently
don't run, but it is a great read on all the problems you face when
coding several kinds of multiplayer games, and the variety of things
you can do to fix it:

http://playerio.com/documentation/tutorials/building-flash-multiplayer-games-tutorial/

Did you know that Age of Empires was actually internally turn-based,
in order to avoid syncing problems?


On Wed, Apr 24, 2013 at 10:48 PM, John Gordon  wrote:
> In  
> webmas...@terradon.nl writes:
>
>> i have tried and accompished an urllib connection, with get and post
>> variabels, but that will be polling, with all the http-overhead for every
>> poll. I think this is also to slow and no "real" updating of the game status.
>
> Http can still work, depending on what kind of game it is.  For example
> a game where only the current player can make decisions and the other
> players just sit and watch (like Risk), or a game where each player submits
> a move and the server applies the game rules to resolve the outcome (like
> Rock-Scissors-Paper).
>
> But a truly interactive game would probably require something more, like
> an active socket connection.
>
> --
> John Gordon   A is for Amy, who fell down the stairs
> gor...@panix.com  B is for Basil, assaulted by bears
> -- Edward Gorey, "The Gashlycrumb Tinies"
>
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Fábio Santos
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to: multiplayer game connecting to central server effectively?

2013-04-24 Thread John Gordon
In  
webmas...@terradon.nl writes:

> i have tried and accompished an urllib connection, with get and post
> variabels, but that will be polling, with all the http-overhead for every
> poll. I think this is also to slow and no "real" updating of the game status.

Http can still work, depending on what kind of game it is.  For example
a game where only the current player can make decisions and the other
players just sit and watch (like Risk), or a game where each player submits
a move and the server applies the game rules to resolve the outcome (like
Rock-Scissors-Paper).

But a truly interactive game would probably require something more, like
an active socket connection.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


how to: multiplayer game connecting to central server effectively?

2013-04-24 Thread webmaster
hi,
I struggle for some days about a "model" for a multiplayer game application.
I read so much from my enemy Google, i got lost by all that info and dont know 
which path i should chose.

a multiplayer game application, sending/receiving  instantly every change in 
the game to a central webserver, http://www.x.com, probably via socket 
connection?

which system/module should i use for this contineous connection and where can i 
find a good tutorial, which a beginner like me can understand a bit? (i have 
read too many too complicated/technical artickles, but no nice tutorials).

i have tried and accompished an urllib connection, with get and post variabels, 
but that will be polling, with all the http-overhead for every poll. I think 
this is also to slow and no "real" updating of the game status.

Thanks in advance for any hint/tutorial i get:)

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


Re: Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread Neil Cerutti
On 2013-04-24, William Ray Wing  wrote:
> When I look at the pool module, the error is occurring in
> get(self, timeout=None) on the line after the final else:
>
> def get(self, timeout=None):
> self.wait(timeout)
> if not self._ready:
> raise TimeoutError
> if self._success:
> return self._value
> else:
> raise self._value

The code that's failing is in self.wait. Somewhere in there you
must be masking an exception and storing it in self._value
instead of letting it propogate and crash your program. This is
hiding the actual context.

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


Re: My gui

2013-04-24 Thread Neil Cerutti
On 2013-04-24, Arnaud Delobelle  wrote:
> His class is not a frame, it's just a container for the tkinter
> code. It's a bit unusual but it looks correct to me (apart from
> the single underscores in __init__() as spotted by Ned
> Batchelder).

I dunno if it makes any difference, but it's usual to call
mainloop of the root window, rather than tkinter.mainloop.

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


Finding the source of an exception in a python multiprocessing program

2013-04-24 Thread William Ray Wing
I run a bit of python code that monitors my connection to the greater Internet. 
 It checks connectivity to the requested target IP addresses, logging both 
successes and failures, once every 15 seconds.  I see failures quite regularly, 
predictably on Sunday nights after midnight when various networks are 
undergoing maintenance.  I'm trying to use python's multiprocessing library to 
run multiple copies in parallel to check connectivity to different parts of the 
country (they in no way interact with each other).

On rare occasions (maybe once every couple of months) I get the following 
exception and traceback:

Traceback (most recent call last):
  File "./CM_Harness.py", line 12, in 
Foo = pool.map(monitor, targets)# and hands off two targets
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py",
 line 227, in map
return self.map_async(func, iterable, chunksize).get()
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py",
 line 528, in get
raise self._value
IndexError: list index out of range

The code where the traceback occurs is:

#!/usr/bin/env python

""" Harness to call multiple parallel copies
of the basic monitor program
"""

from multiprocessing import Pool
from Connection_Monitor import monitor

targets = ["8.8.8.8", "www.ncsa.edu"]
pool = Pool(processes=2)# start 2 worker processes
Foo = pool.map(monitor, targets)# and hands off two targets


Line 12, in my code is simply the line that launches the underlying monitor 
code.  I'm assuming that the real error is occurring in the monitor program 
that is being launched, but I'm at a loss as to what to do to get a better 
handle on what's going wrong. Since, as I said, I see failures quite regularly, 
typically on Sunday nights after midnight when various networks are undergoing 
maintenance, I don't _think_ the exception is being triggered by that sort of 
failure.

When I look at the pool module, the error is occurring in get(self, 
timeout=None) on the line after the final else:

def get(self, timeout=None):
self.wait(timeout)
if not self._ready:
raise TimeoutError
if self._success:
return self._value
else:
raise self._value


Python v 2.7.3, from Python.org, running on Mac OS-X 10.8.3

Thanks for any suggestions,
Bill
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My gui

2013-04-24 Thread Arnaud Delobelle
On 24 April 2013 18:53, Chris “Kwpolska” Warrick  wrote:
> On Wed, Apr 24, 2013 at 7:08 PM, Daniel Kersgaard
>  wrote:
>> Today, being the last day of lectures at school, my instructor ran briefly 
>> through Tkninter and GUIs. I'd been looking forward to this particular 
>> lesson all semester, but when I got home and copied a sample program from my 
>> textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here  
>> is the code from my program. I'm not sure if this is appropriate, but 
>> suggestions are helpful.
>>
>> import tkinter
>> import tkinter.messagebox
>>
>> class MyGui:
>> def _init_(self):
>> self.main_window = tkinter.Tk()
>>
>> self.top_frame = tkinter.Frame(self.main_window)
>> self.bottom_frame = tkinter.Frame(self.main_window)
>>
>> self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a 
>> distance in Kilometers: ')
>> self.kilo_entry = tkinter.Entry(self.top_frame, width = 10)
>>
>> self.prompt_label.pack(side = 'left')
>> self.kilo_entry.pack(side = 'left')
>>
>> self.calc_button = tkinter.Button(self.bottom_frame, text = 
>> 'Convert', command = self.convert)
>>
>> self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', 
>> command = self.main_window.destroy)
>>
>> self.calc_button.pack(side = 'left')
>> self.quit_button.pack(side = 'left')
>>
>> self.top_frame.pack()
>> self.bottom_frame.pack()
>>
>> tkinter.mainloop()
>>
>> def convert(self):
>> kilo = float(self.kilo_entry.get())
>>
>> miles = kilo * 0.6214
>>
>> tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is 
>> equal to ' + str(miles) + 'miles.')
>>
>> poop = MyGui()
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
> poop?  Seriously?  You aren’t serious about that copying, right?
>
> Your code seems to be missing a lot of important stuff.  You don’t
> inherit from tkinter.Frame.  Compare your program to the sample “Hello
> world!” program:

His class is not a frame, it's just a container for the tkinter code.
It's a bit unusual but it looks correct to me (apart from the single
underscores in __init__() as spotted by Ned Batchelder).

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


Re: Weird python behavior

2013-04-24 Thread Forafo San
On Wednesday, April 24, 2013 3:08:27 PM UTC-4, Neil Cerutti wrote:
> On 2013-04-24, Forafo San  wrote:
> 
> > Hello All,
> 
> > I'm running Python version 2.7.3_6 on a FreeBSD system. The following 
> > session in a Python interpreter throws a mysterious TypeError:
> 
> >
> 
> > --
> 
> > [ppvora@snowfall ~/xbrl]$ python 
> 
> > Python 2.7.3 (default, Apr 22 2013, 18:42:18) 
> 
> > [GCC 4.2.1 20070719  [FreeBSD]] on freebsd8
> 
> > Type "help", "copyright", "credits" or "license" for more information.
> 
>  import glob
> 
> > Traceback (most recent call last):
> 
> >   File "", line 1, in 
> 
> >   File "glob.py", line 14, in 
> 
> > myl = glob.glob('data/*.xml')
> 
> > TypeError: 'module' object is not callable
> 
> > --
> 
> > The file glob.py that the error refers to was run under another
> 
> > screen session. It's a mystery why even that program threw an
> 
> > error. Regardless, why should that session throw an import
> 
> > error in this session? Weird. Any help is appreciated. Thanks,
> 
> 
> 
> 'Cause Python's import statement looks in the current directory
> 
> first for files to import. So you're importing your own
> 
> error-riddled and mortal glob.py, rather than Python's pristine
> 
> and Olympian glob.py.
> 
> 
> 
> -- 
> 
> Neil Cerutti
> 
>   "This room is an illusion and is a trap devisut by Satan.  Go
> 
> ahead and dauntlessly!  Make rapid progres!"
> 
>   --Ghosts 'n Goblins

OK, lesson learned: Take care not to have module names that conflict with 
python's built ins. Sorry for being so obtuse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Grant Edwards
On 2013-04-24, Roozbeh  wrote:

> I want to use spline interpolation function from SciPy in an
> application and at the same time, I don't want the end user to have
> to install SciPy separately. Is there a way around this problem?

You could bundle you app along with python and SciPy and whatever
other libraries are required using py2exe, py2app, cx_Freeze, Freeze,
etc.

-- 
Grant Edwards   grant.b.edwardsYow! JAPAN is a WONDERFUL
  at   planet -- I wonder if we'll
  gmail.comever reach their level of
   COMPARATIVE SHOPPING ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Weird python behavior

2013-04-24 Thread Forafo San
Hello All,
I'm running Python version 2.7.3_6 on a FreeBSD system. The following session 
in a Python interpreter throws a mysterious TypeError:

--
[ppvora@snowfall ~/xbrl]$ python 
Python 2.7.3 (default, Apr 22 2013, 18:42:18) 
[GCC 4.2.1 20070719  [FreeBSD]] on freebsd8
Type "help", "copyright", "credits" or "license" for more information.
>>> import glob
Traceback (most recent call last):
  File "", line 1, in 
  File "glob.py", line 14, in 
myl = glob.glob('data/*.xml')
TypeError: 'module' object is not callable
--
The file glob.py that the error refers to was run under another screen session. 
It's a mystery why even that program threw an error. Regardless, why should 
that session throw an import error in this session? Weird. Any help is 
appreciated. Thanks,
-Premal 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Weird python behavior

2013-04-24 Thread Neil Cerutti
On 2013-04-24, Forafo San  wrote:
> Hello All,
> I'm running Python version 2.7.3_6 on a FreeBSD system. The following session 
> in a Python interpreter throws a mysterious TypeError:
>
> --
> [ppvora@snowfall ~/xbrl]$ python 
> Python 2.7.3 (default, Apr 22 2013, 18:42:18) 
> [GCC 4.2.1 20070719  [FreeBSD]] on freebsd8
> Type "help", "copyright", "credits" or "license" for more information.
 import glob
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "glob.py", line 14, in 
> myl = glob.glob('data/*.xml')
> TypeError: 'module' object is not callable
> --
> The file glob.py that the error refers to was run under another
> screen session. It's a mystery why even that program threw an
> error. Regardless, why should that session throw an import
> error in this session? Weird. Any help is appreciated. Thanks,

'Cause Python's import statement looks in the current directory
first for files to import. So you're importing your own
error-riddled and mortal glob.py, rather than Python's pristine
and Olympian glob.py.

-- 
Neil Cerutti
  "This room is an illusion and is a trap devisut by Satan.  Go
ahead and dauntlessly!  Make rapid progres!"
  --Ghosts 'n Goblins
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: QTableWidget updating columns in a single row

2013-04-24 Thread Vincent Vande Vyvre

Le 24/04/2013 19:12, Sara Lochtie a écrit :

On Tuesday, April 23, 2013 11:22:29 PM UTC-7, Sara Lochtie wrote:

I have written a GUI that gets data sent to it in real time and this data is 
displayed in a table. Every time data is sent in it is displayed in the table 
in a new row. My problem is that I would like to have the data just replace the 
old in the first row.



The table has 6 columns (A, B, C, D, E, F) I want the new data to continue 
replacing the old data in the same row unless the data that goes under column A 
changes, at which point a new row would be added.



Does anyone have tips on how to approach this? I can post a portion of my code 
to get a better idea of what I have done.

So that is where I am stuck. I don't how to compare them and I am trying to 
avoiding saving the data to a file.

This is the code that I have:





if msg.arg2() != ERROR:
entry = (A, B, C, D, E, F)  
self.data.append(entry)

 data = self.data
 
 # Display how many runs occurred

 self.statusBar().showMessage('Data read. %s Run(s) Occurred.' % 
self.runCount)
 
 # Populates table by adding only new entries to the end of the table

 lastRow = self.table.rowCount()
 self.table.setRowCount(len(data))
 for entryPos in range(lastRow, len(data)):
 for fieldPos in range(6):
 item = QtGui.QTableWidgetItem(str(data[entryPos][fieldPos]))
 self.table.setItem(entryPos, fieldPos, item)
 self.table.resizeColumnsToContents()
 self.table.horizontalHeader().setStretchLastSection(True)  
 self.currentRunLabel.setText('Current Run: ' + str(self.runCount))
 self.currentLineLabel.setText('Number of lines: ' + 
str(len(self.data)))
print('End of %s. run:%s. entries found' % (self.runCount, 
len(self.data)))
As sayed by Chris "Kwpolska", you can compare the new data with the data 
of the first row.


Something like that:

 # Get the content of row 0, column A
first = str(self.table.item(0, 0).text())

for entryPos in range(lastRow, len(data)):
if str(data[entryPos][0]) == first:
self.update_first_row(data[entryPos])

else:
self.add_new_row(data[entryPos])
--
Vincent V.V.
Oqapy  . Qarte 
 . PaQager 

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


Re: My gui

2013-04-24 Thread Ned Batchelder


On 4/24/2013 1:08 PM, Daniel Kersgaard wrote:

Today, being the last day of lectures at school, my instructor ran briefly 
through Tkninter and GUIs. I'd been looking forward to this particular lesson 
all semester, but when I got home and copied a sample program from my textbook 
verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here  is the code 
from my program. I'm not sure if this is appropriate, but suggestions are 
helpful.

import tkinter
import tkinter.messagebox

class MyGui:
 def_init_(self):


You need to define __init__, not _init_.  Python special methods are 
named with double underscore leading and trailing, and __x__ is 
pronounced "dunder-x".


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


Re: QTableWidget updating columns in a single row

2013-04-24 Thread Chris “Kwpolska” Warrick
On Wed, Apr 24, 2013 at 7:12 PM, Sara Lochtie  wrote:
> So that is where I am stuck. I don't how to compare them and I am trying to 
> avoiding saving the data to a file.

To a file?  Just store it in a class attribute and you will be fine.
You have it in self.data already.  Unless that structure doesn’t work,
then “mirror” your table in a Python array.  (alternatively, you could
query QTableWidgetItem.text() for every existing item, but that’s
crazy.)

--
Kwpolska  | GPG KEY: 5EAAEA16
stop html mail| always bottom-post
http://asciiribbon.org| http://caliburn.nl/topposting.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My gui

2013-04-24 Thread Chris “Kwpolska” Warrick
On Wed, Apr 24, 2013 at 7:08 PM, Daniel Kersgaard
 wrote:
> Today, being the last day of lectures at school, my instructor ran briefly 
> through Tkninter and GUIs. I'd been looking forward to this particular lesson 
> all semester, but when I got home and copied a sample program from my 
> textbook verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here  
> is the code from my program. I'm not sure if this is appropriate, but 
> suggestions are helpful.
>
> import tkinter
> import tkinter.messagebox
>
> class MyGui:
> def _init_(self):
> self.main_window = tkinter.Tk()
>
> self.top_frame = tkinter.Frame(self.main_window)
> self.bottom_frame = tkinter.Frame(self.main_window)
>
> self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a 
> distance in Kilometers: ')
> self.kilo_entry = tkinter.Entry(self.top_frame, width = 10)
>
> self.prompt_label.pack(side = 'left')
> self.kilo_entry.pack(side = 'left')
>
> self.calc_button = tkinter.Button(self.bottom_frame, text = 
> 'Convert', command = self.convert)
>
> self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', 
> command = self.main_window.destroy)
>
> self.calc_button.pack(side = 'left')
> self.quit_button.pack(side = 'left')
>
> self.top_frame.pack()
> self.bottom_frame.pack()
>
> tkinter.mainloop()
>
> def convert(self):
> kilo = float(self.kilo_entry.get())
>
> miles = kilo * 0.6214
>
> tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is 
> equal to ' + str(miles) + 'miles.')
>
> poop = MyGui()
>
> --
> http://mail.python.org/mailman/listinfo/python-list

poop?  Seriously?  You aren’t serious about that copying, right?

Your code seems to be missing a lot of important stuff.  You don’t
inherit from tkinter.Frame.  Compare your program to the sample “Hello
world!” program:
http://docs.python.org/2/library/tkinter.html#a-simple-hello-world-program
— unfortunately, I am not a fan and I am not knowledgeable about
tkinter, but I can see a lot of stuff is missing.

Please try fixing it and running it _outside of IDLE_, which is also
built in Tk.  This may cause problems (but don’t worry, the code you
pasted doesn’t work anyways.)

--
Kwpolska  | GPG KEY: 5EAAEA16
stop html mail| always bottom-post
http://asciiribbon.org| http://caliburn.nl/topposting.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: improvements sought re. logging across modules

2013-04-24 Thread Dave Angel

On 04/24/2013 12:54 PM, The Night Tripper wrote:

Hi all
I have a small suite of python modules, say

A.py
B.py
C.py

which can be invoked in a variety of ways. eg.

1) A.py is invoked directly; this imports and uses B.py and C.py

2) B.py is invoked; this imports and uses A.py and C.py



Right there you have a potential problem.  Unless you make those imports 
conditional, you have an import loop, which can be a minor problem, or a 
big one.


Whenever you find loops in the import call tree, please break them.  The 
best way is to move the interdependencies into yet another module, and 
let both A and B import that one.




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


Re: My gui

2013-04-24 Thread Dave Angel

On 04/24/2013 01:08 PM, Daniel Kersgaard wrote:

Today, being the last day of lectures at school, my instructor ran briefly 
through Tkninter and GUIs. I'd been looking forward to this particular lesson 
all semester, but when I got home and copied a sample program from my textbook 
verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here  is the code 
from my program. I'm not sure if this is appropriate, but suggestions are 
helpful.

import tkinter
import tkinter.messagebox

class MyGui:
 def _init_(self):
 self.main_window = tkinter.Tk()

 self.top_frame = tkinter.Frame(self.main_window)
 self.bottom_frame = tkinter.Frame(self.main_window)

 self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a 
distance in Kilometers: ')
 self.kilo_entry = tkinter.Entry(self.top_frame, width = 10)

 self.prompt_label.pack(side = 'left')
 self.kilo_entry.pack(side = 'left')

 self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', 
command = self.convert)

 self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', 
command = self.main_window.destroy)

 self.calc_button.pack(side = 'left')
 self.quit_button.pack(side = 'left')

 self.top_frame.pack()
 self.bottom_frame.pack()

 tkinter.mainloop()

 def convert(self):
 kilo = float(self.kilo_entry.get())

 miles = kilo * 0.6214

 tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is 
equal to ' + str(miles) + 'miles.')

poop = MyGui()



I'm not an IDLE user, but I wouldn't be surprised if IDLE interferes 
with some GUI apps.   I'd run your code from the bash prompt.




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


A Healthy Alternative to Takeaway Regret

2013-04-24 Thread 23alagmy
A Healthy Alternative to Takeaway Regret

http://natigtas7ab.blogspot.com/2013/03/a-healthy-alternative-to-takeaway-regret.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: improvements sought re. logging across modules

2013-04-24 Thread Chris “Kwpolska” Warrick
On Wed, Apr 24, 2013 at 6:54 PM, The Night Tripper  wrote:
> Hi all
> I have a small suite of python modules, say
>
> A.py
> B.py
> C.py
>
> which can be invoked in a variety of ways. eg.
>
> 1) A.py is invoked directly; this imports and uses B.py and C.py
>
> 2) B.py is invoked; this imports and uses A.py and C.py
>
> I use the logging module in all of these python modules, and I want to be
> able to use a single logger across the entire suite of whichever set of
> scripts is running.
>
> The way I do this at the moment is to have a separate module mylogger.py:
>
> == mylogger.py ==
>
> import logging
>
> class MyLogger:   #using python 2.4 ;-o
> def __init__(self):
> self.log = logging.getLogger(MY_APP_NAME)
> def setupLogging(self):
> self.log.setlevel(logging.DEBUG)
> # ...
>
> # our singleton logging object
> mylogger = Mylogger()
> # EOF
>
> and then in my other modules A.py, B.py etc. I have something like:
>
> == A.py ==
>
> import mylogger
> gLog = mylogger.mylogger
>
> if __name__ == "__main__":
> gLog.setupLogging()
> gLog.info("Module A running as main")
> main()
> #EOF
>
> == B.py ==
>
> import mylogger
> gLog = mylogger.mylogger
>
> if __name__ == "__main__":
> gLog.setupLogging()
> gLog.info("Module B running as main")
> main()
> # EOF
>
> This works, but I can't help thinking I'm missing a trick here. Any
> suggestions?
>
> Thanks
> j^n
>
> --
> http://mail.python.org/mailman/listinfo/python-list

No need to do such magic.  Just set logging up as you would normally.
The first logging instance should pick up logs from everywhere.  For
example:

=== aurqt/aqds.py ===
class AQDS:
logging.basicConfig(format='%(asctime)-15s [%(levelname)-7s] '
':%(name)-10s: %(message)s',
filename=os.path.join(confdir, 'aurqt.log'),
level=logging.DEBUG)
log = logging.getLogger('aurqt')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter('[%(levelname)-7s] '
 ':%(name)-10s: %(message)s'))
logging.getLogger('').addHandler(console)
log.info('*** aurqt v' + __version__)

=== pkgbuilder/pbds.py ===
class PBDS:
logging.basicConfig(format='%(asctime)-15s [%(levelname)-7s] '
':%(name)-10s: %(message)s',
filename=os.path.join(confdir, 'pkgbuilder.log'),
level=logging.DEBUG)
log = logging.getLogger('pkgbuilder')
log.info('*** PKGBUILDer v' + __version__)

=== aurqt/__init__.py ===
from .aqds import AQDS
DS = AQDS()
import pkgbuilder # ← also imports pkgbuilder.DS = pkgbuilder.pbds.PBDS()

=== bin/aurqt output ===
[INFO   ] :aurqt : *** aurqt v0.1.0
[INFO   ] :requests.packages.urllib3.connectionpool: Starting new
HTTPS connection (1): aur.archlinux.org
[WARNING] :pkgbuilder: tty-clock version is a date, ignored for downgrade.

=== {confdir}/aurqt.log ===
2013-04-24 19:34:21,079 [INFO   ] :aurqt : *** aurqt v0.1.0
2013-04-24 19:35:19,096 [WARNING]
:requests.packages.urllib3.connectionpool: Starting new HTTPS
connection (1): aur.archlinux.org
2013-04-24 19:35:21,004 [WARNING] :pkgbuilder: tty-clock version is a
date, ignored for downgrade.

--
Kwpolska  | GPG KEY: 5EAAEA16
stop html mail| always bottom-post
http://asciiribbon.org| http://caliburn.nl/topposting.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: improvements sought re. logging across modules

2013-04-24 Thread Fábio Santos
Maybe import mylogger.mylogger as gLog? I don't know what you mean by
"missing a trick". Your example seems pretty pythonic to me, except for the
fact that you use a singleton where you could have a couple of functions
and use the module as the namespace.
On 24 Apr 2013 17:58, "The Night Tripper"  wrote:

> Hi all
> I have a small suite of python modules, say
>
> A.py
> B.py
> C.py
>
> which can be invoked in a variety of ways. eg.
>
> 1) A.py is invoked directly; this imports and uses B.py and C.py
>
> 2) B.py is invoked; this imports and uses A.py and C.py
>
> I use the logging module in all of these python modules, and I want to be
> able to use a single logger across the entire suite of whichever set of
> scripts is running.
>
> The way I do this at the moment is to have a separate module mylogger.py:
>
> == mylogger.py ==
>
> import logging
>
> class MyLogger:   #using python 2.4 ;-o
> def __init__(self):
> self.log = logging.getLogger(MY_APP_NAME)
> def setupLogging(self):
> self.log.setlevel(logging.DEBUG)
> # ...
>
> # our singleton logging object
> mylogger = Mylogger()
> # EOF
>
> and then in my other modules A.py, B.py etc. I have something like:
>
> == A.py ==
>
> import mylogger
> gLog = mylogger.mylogger
>
> if __name__ == "__main__":
> gLog.setupLogging()
> gLog.info("Module A running as main")
> main()
> #EOF
>
> == B.py ==
>
> import mylogger
> gLog = mylogger.mylogger
>
> if __name__ == "__main__":
> gLog.setupLogging()
> gLog.info("Module B running as main")
> main()
> # EOF
>
> This works, but I can't help thinking I'm missing a trick here. Any
> suggestions?
>
> Thanks
> j^n
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using pandoc instead of rst to document python

2013-04-24 Thread R. Michael Weylandt
On Wed, Apr 24, 2013 at 12:14 AM, Peng Yu  wrote:
> I currently use sphinx to generate the doc (in rst). How to figure it
> to support pandoc's markdown?

If I understand the desired workflow, it's just 1) write in markdown;
2) then run pandoc to convert to rst; 3) then run Sphinx to render
html or whatever you want.

You could even script this in python ;-)

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


Re: QTableWidget updating columns in a single row

2013-04-24 Thread Sara Lochtie
On Tuesday, April 23, 2013 11:22:29 PM UTC-7, Sara Lochtie wrote:
> I have written a GUI that gets data sent to it in real time and this data is 
> displayed in a table. Every time data is sent in it is displayed in the table 
> in a new row. My problem is that I would like to have the data just replace 
> the old in the first row.
> 
> 
> 
> The table has 6 columns (A, B, C, D, E, F) I want the new data to continue 
> replacing the old data in the same row unless the data that goes under column 
> A changes, at which point a new row would be added.
> 
> 
> 
> Does anyone have tips on how to approach this? I can post a portion of my 
> code to get a better idea of what I have done.

So that is where I am stuck. I don't how to compare them and I am trying to 
avoiding saving the data to a file.  

This is the code that I have:





if msg.arg2() != ERROR:
entry = (A, B, C, D, E, F) 
self.data.append(entry) 

data = self.data 

# Display how many runs occurred
self.statusBar().showMessage('Data read. %s Run(s) Occurred.' % 
self.runCount)

# Populates table by adding only new entries to the end of the table
lastRow = self.table.rowCount()
self.table.setRowCount(len(data))
for entryPos in range(lastRow, len(data)): 
for fieldPos in range(6):   
item = QtGui.QTableWidgetItem(str(data[entryPos][fieldPos]))
self.table.setItem(entryPos, fieldPos, item)
self.table.resizeColumnsToContents()
self.table.horizontalHeader().setStretchLastSection(True)   
   
self.currentRunLabel.setText('Current Run: ' + str(self.runCount))
self.currentLineLabel.setText('Number of lines: ' + str(len(self.data)))
print('End of %s. run:%s. entries found' % (self.runCount, 
len(self.data)))
-- 
http://mail.python.org/mailman/listinfo/python-list


My gui

2013-04-24 Thread Daniel Kersgaard
Today, being the last day of lectures at school, my instructor ran briefly 
through Tkninter and GUIs. I'd been looking forward to this particular lesson 
all semester, but when I got home and copied a sample program from my textbook 
verbatim, IDLE does nothing. No error, no nothing. Any ideas? Here  is the code 
from my program. I'm not sure if this is appropriate, but suggestions are 
helpful.

import tkinter
import tkinter.messagebox

class MyGui:
def _init_(self):
self.main_window = tkinter.Tk()

self.top_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)

self.prompt_label = tkinter.Label(self.top_frame, text = 'Enter a 
distance in Kilometers: ')
self.kilo_entry = tkinter.Entry(self.top_frame, width = 10)

self.prompt_label.pack(side = 'left')
self.kilo_entry.pack(side = 'left')

self.calc_button = tkinter.Button(self.bottom_frame, text = 'Convert', 
command = self.convert)

self.quit_button = tkinter.Button(self.bottom_frame, text = 'Quit', 
command = self.main_window.destroy)

self.calc_button.pack(side = 'left')
self.quit_button.pack(side = 'left')

self.top_frame.pack()
self.bottom_frame.pack()

tkinter.mainloop()

def convert(self):
kilo = float(self.kilo_entry.get())

miles = kilo * 0.6214

tkinter.messagebox.showinfo('Result', str(kilo) + ' kilometers is equal 
to ' + str(miles) + 'miles.')

poop = MyGui()

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


improvements sought re. logging across modules

2013-04-24 Thread The Night Tripper
Hi all
I have a small suite of python modules, say

A.py
B.py
C.py

which can be invoked in a variety of ways. eg. 

1) A.py is invoked directly; this imports and uses B.py and C.py

2) B.py is invoked; this imports and uses A.py and C.py

I use the logging module in all of these python modules, and I want to be 
able to use a single logger across the entire suite of whichever set of 
scripts is running. 

The way I do this at the moment is to have a separate module mylogger.py:

== mylogger.py ==

import logging

class MyLogger:   #using python 2.4 ;-o
def __init__(self):
self.log = logging.getLogger(MY_APP_NAME)
def setupLogging(self):
self.log.setlevel(logging.DEBUG)
# ...

# our singleton logging object
mylogger = Mylogger()
# EOF

and then in my other modules A.py, B.py etc. I have something like:

== A.py ==

import mylogger
gLog = mylogger.mylogger

if __name__ == "__main__":
gLog.setupLogging()
gLog.info("Module A running as main")
main()
#EOF

== B.py ==

import mylogger
gLog = mylogger.mylogger

if __name__ == "__main__":
gLog.setupLogging()
gLog.info("Module B running as main")
main()
# EOF

This works, but I can't help thinking I'm missing a trick here. Any 
suggestions?

Thanks
j^n

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


Re: Using SciPy in application

2013-04-24 Thread Maarten
On Wednesday, April 24, 2013 1:40:14 PM UTC+2, Robert Kern wrote:
> On 2013-04-24 17:04, Roozbeh wrote:
> 
> > On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote:
> 
> >> Hi all, I want to use spline interpolation function from SciPy in an 
> >> application and at the same time, I don't want the end user to have to 
> >> install SciPy separately. Is there a way around this problem? Thanks in 
> >> advance for your help
> 
> > Any idea where can I find the recipe for the spline interpolation that does 
> > not rely on NumPy and/or SciPy and is written pure Python (no C code)?
> 
> 
> If Google can't find it, it probably doesn't exist. Very few people would do 
> this without numpy.

A trivial 'pure python spline' google search yields this:
http://urchin.earth.li/~twic/splines.py

(Warning: old code, python 2.2 era).

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


Re: Using SciPy in application

2013-04-24 Thread Roozbeh
On Wednesday, April 24, 2013 3:52:50 PM UTC+2, Miki Tebeka wrote:
> > I want to use spline interpolation function from SciPy in an application 
> > and at the same time, I don't want the end user to have to install SciPy 
> > separately. You can pack you application with py2exe, pyinstaller ... and 
> > then they won't even need to install Python. Another option (which is not 
> > always possible) is to make you application a web site and then only you 
> > need to install SciPy on the server.


I thought about the py2exe option but the problem is, this application is a 
plug-in written for Abaqus CAE and hence it will use the python version that 
comes with Abaqus CAE distribution and Abaqus must be able to compile the 
Python codes every time on the start-up otherwise it won't recognize the 
plug-in and thats why SciPy and NumPy are also not an option. 
I guess as Alex said, I will have to use DLLs or write it myself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Miki Tebeka
> I want to use spline interpolation function from SciPy in an application and 
> at the same time, I don't want the end user to have to install SciPy 
> separately.
You can pack you application with py2exe, pyinstaller ... and then they won't 
even need to install Python.

Another option (which is not always possible) is to make you application a web 
site and then only you need to install SciPy on the server.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ALL function arguments in a common dictionary

2013-04-24 Thread Fábio Santos
A quick hack:

>>> from inspect import getargspec
>>>
>>> def func(a, b, c=3, **kwargs):
... out_dict = {}
... args, _, keywords, _ = getargspec(func)
... for argname in args:
... out_dict[argname] = locals()[argname]
... if keywords:
... out_dict.update(locals()[keywords])
... return out_dict
...
>>> func(1,2, gah=123)
{'a': 1, 'c': 3, 'b': 2, 'gah': 123}
>>>

On Wed, Apr 24, 2013 at 2:36 PM, Wolfgang Maier
 wrote:
> Hi everybody,
> what is the recommended way of stuffing *all* function arguments (not just
> the ones passed by **kwargs) into a common dictionary?
>
> The following sort of works when used as the first block in a function:
> try:
> kwargs.update(locals())
> except NameError:
> kwargs = locals().copy()
>
> except that it's nesting pre-existing kwargs.
>
> Thanks for your help,
> Wolfgang
>
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Fábio Santos
-- 
http://mail.python.org/mailman/listinfo/python-list


ALL function arguments in a common dictionary

2013-04-24 Thread Wolfgang Maier
Hi everybody,
what is the recommended way of stuffing *all* function arguments (not just
the ones passed by **kwargs) into a common dictionary?

The following sort of works when used as the first block in a function:
try:
kwargs.update(locals())
except NameError:
kwargs = locals().copy()

except that it's nesting pre-existing kwargs.

Thanks for your help,
Wolfgang

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


Re: What is the reason for defining classes within classes in Python?

2013-04-24 Thread vasudevram
Interesting. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the reason for defining classes within classes in Python?

2013-04-24 Thread Peter Otten
vasudevram wrote:

> On Wednesday, April 24, 2013 6:20:36 AM UTC+5:30, alex23 wrote:
>> 
>> A nested class definition will be defined as an attribute of the class
>> 
>> its defined within:
>> 
>> 
>> 
>> >>> class Outer(object):
>> 
>> ... foo = 'FOO'
>> 
>> ... class Inner(object):
>> 
>> ... bar = 'BAR'
>> 
>> ...
>> 
>> >>> Outer.Inner

> Just one other doubt:
> 
>> >>> Outer.Inner
>> 
>> 
>> 
> 
> In the above output, I would have thought Python would print
> __main__.Outer.Inner or Outer.Inner instead of __main__.Inner, since Inner
> is an attribute of Outer?

The Python developers seem to agree with you and have made the compiler 
smart enough to accomodate your expectations in Python 3.3:

$ cat tmp.py
class Outer:
class Inner:
pass

print(Outer.Inner)
$ python3.2 tmp.py

$ python3.3 tmp.py



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


Re: Using SciPy in application

2013-04-24 Thread Alex van der Spek
On Wed, 24 Apr 2013 04:34:44 -0700, Roozbeh wrote:

The scipy interpolation routines (splev, splrep, etc.) are on netlib:

http://www.netlib.org/dierckx/

This gives you FORTRAN source codes which you will have to compile 
yourself to either a DLL or an SO. Call them from python using ctypes.

I have done that for a number of the dierckx routines. No problems at all.

Hope this helps,
Alex van der Spek



> On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote:
>> Hi all, I want to use spline interpolation function from SciPy in an
>> application and at the same time, I don't want the end user to have to
>> install SciPy separately. Is there a way around this problem? Thanks in
>> advance for your help
> 
> Any idea where can I find the recipe for the spline interpolation that
> does not rely on NumPy and/or SciPy and is written pure Python (no C
> code)?

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


Re: Fixing escaped characters python-xbee

2013-04-24 Thread Peter Otten
pablobl...@gmail.com wrote:

> I am using a XBee to receive data from an arduino network.
> 
> But they have AP=2 which means escaped characters are used when a 11 or 13
> appears (and some more...)
> 
> When this occurs, XBee sends 7D and inmediatly XOR operation with char and
> 0x20.
> 
> I am trying to recover the original character in python but I don't know
> ho to do it.
> 
> I tried something like this:
> 
> read = ser.read(4) #Read 4 chars from serial port
> for x in range (0,4):
> if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal just for
> checking purposes if(x < 3):
> read[x] = logical_xor(read[x+1], 20) #XOR
> for y in range (x+1,3):
> read[y] = read[y+1]
> read[3] = ser.read()
> else:
> read[x] = logical_xor(ser.read(), 20) #XOR
> 
> data = struct.unpack(' 
> logical_xor is:
> 
> def logical_xor(str1, str2):
> return bool(str1) ^ bool(str2)
> 
> I check if 7D character is in the first 3 chars read, I use the next char
> to convert it, if it is the 4th, I read another one.
> 
> But I read in python strings are inmutables and I can't change their value
> once they have one.
> 
> What would you do in this case? I started some days ago with python and I
> don't know how to solve this kind of things...

As you cannot change the old string you have to compose a new one. I think 
the simplest approach is to always read one byte, and if it's the escape 
marker read another one and decode it. The decoded bytes/chars are then 
stored in a list and finally joined:

# Python 2
# untested
def read_nbytes(ser, n):
accu = []
for i in xrange(n):
b = ser.read(1)
if b == "\x7d":
b = chr(ord(ser.read(1)) ^ 0x20)
accu.append(b)
return "".join(accu)

b = read_nbytes(ser, 4)
data = struct.unpack('http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Robert Kern

On 2013-04-24 17:04, Roozbeh wrote:

On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote:

Hi all, I want to use spline interpolation function from SciPy in an 
application and at the same time, I don't want the end user to have to install 
SciPy separately. Is there a way around this problem? Thanks in advance for 
your help


Any idea where can I find the recipe for the spline interpolation that does not 
rely on NumPy and/or SciPy and is written pure Python (no C code)?


If Google can't find it, it probably doesn't exist. Very few people would do 
this without numpy.


--
Robert Kern

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

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


Re: Using SciPy in application

2013-04-24 Thread Roozbeh
On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote:
> Hi all, I want to use spline interpolation function from SciPy in an 
> application and at the same time, I don't want the end user to have to 
> install SciPy separately. Is there a way around this problem? Thanks in 
> advance for your help

Any idea where can I find the recipe for the spline interpolation that does not 
rely on NumPy and/or SciPy and is written pure Python (no C code)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Roozbeh
On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote:
> Hi all, I want to use spline interpolation function from SciPy in an 
> application and at the same time, I don't want the end user to have to 
> install SciPy separately. Is there a way around this problem? Thanks in 
> advance for your help

The thing is that the SciPy code for spline interpolation imports NumPy which 
also I don't want to use. So, I think I will have to write the code myself I 
guess.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Roozbeh
On Wednesday, April 24, 2013 11:13:45 AM UTC+2, Roozbeh wrote: > Hi all, I want 
to use spline interpolation function from SciPy in an application and at the 
same time, I don't want the end user to have to install SciPy separately. Is 
there a way around this problem? Thanks in advance for your help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Robert Kern

On 2013-04-24 16:34, Oscar Benjamin wrote:

On 24 April 2013 10:13, Roozbeh  wrote:


I want to use spline interpolation function from SciPy in an application and at 
the same time, I don't want the end user to have to install SciPy separately. 
Is there a way around this problem?


They cannot use the function from scipy if scipy is not installed.
There are three ways round this problem:
1) Rewrite the interpolation function you need in your own code.


Variant:

1.a) Copy the interpolation code from scipy into your own code.

--
Robert Kern

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

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


Re: What is the reason for defining classes within classes in Python?

2013-04-24 Thread vasudevram
On Wednesday, April 24, 2013 6:20:36 AM UTC+5:30, alex23 wrote:
> On Apr 24, 9:13 am, vasudevram  wrote:
> 
> > On Wednesday, April 24, 2013 3:52:57 AM UTC+5:30, Ian wrote:
> 
> > > On Tue, Apr 23, 2013 at 3:50 PM, vasudevram  wrote:
> 
> > > > I saw an example of defining a class within another class
> 
> > > > In what way is this useful?
> 
> >
> 
> > > In that particular case they're just using it as a namespace.
> 
> >
> 
> > Not clear. An example or more explanation might help, if you can. Thanks.
> 
> 
> 
> Namespaces are used to allow for the same label to be applied to
> 
> different concepts without the labels conflicting with each other. If
> 
> I was writing a program that dealt with the mathematics of morality, I
> 
> might want to use the sine function and refer to it in the standard
> 
> way as 'sin', and I might also want to store a value representing your
> 
> lack of goodness as 'sin'. As you can't use the same label in the same
> 
> scope to refer to two different objects, one way of dealing with this
> 
> that lets you still use what you feel are the most appropriate names
> 
> is to put them into a namespace. So you could express this as:
> 
> 
> 
> class Math(object):
> 
> sin = function()
> 
> 
> 
> class Morality(object):
> 
> sin = True
> 
> 
> 
> Then in your code you can clearly distinguish between the two by using
> 
> Math.sin and Morality.sin. Modules & packages are also namespaces, so
> 
> in this example we'd replace the Math class with `import math`, which
> 
> has a sin function defined within it.
> 
> 
> 
> A nested class definition will be defined as an attribute of the class
> 
> its defined within:
> 
> 
> 
> >>> class Outer(object):
> 
> ... foo = 'FOO'
> 
> ... class Inner(object):
> 
> ... bar = 'BAR'
> 
> ...
> 
> >>> Outer.Inner
> 
> 
> 
> >>> Outer.Inner.bar
> 
> 'BAR'
> 
> 
> 
> With peewee, the Model class looks for a Meta attribute and uses
> 
> attributes on it to perform some tasks, like where to retrieve/store
> 
> the model data. This allows for a way of distinguishing between
> 
> attributes used to define fields, and attributes needed for those
> 
> tasks. It also means your Models can use field names that the class
> 
> would otherwise reserve for its own internal purposes:
> 
> 
> 
> class DatabaseDetails(Model):
> 
> # these attributes are fields
> 
> database = CharField()
> 
> owner = CharField()
> 
> 
> 
> # ...but the Meta attribute isn't
> 
> class Meta:
> 
> # these attributes are used by the Model class
> 
> database = db
> 
> 
> 
> Here, database as a field is a text string that could contain a
> 
> database name, while DatabaseDetails.Meta.database contains a
> 
> reference to an actual database where the DatabaseDetails record would
> 
> be stored.

Actually, I did know what namespaces are in general. What I didn't get was how 
the inner class Meta in the peewee example was being used as a namespace. Your 
explanation makes things very clear. Thank you.

Just one other doubt:

> >>> Outer.Inner
> 
> 
> 

In the above output, I would have thought Python would print 
__main__.Outer.Inner or Outer.Inner instead of __main__.Inner, since Inner is 
an attribute of Outer?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using SciPy in application

2013-04-24 Thread Oscar Benjamin
On 24 April 2013 10:13, Roozbeh  wrote:
>
> I want to use spline interpolation function from SciPy in an application and 
> at the same time, I don't want the end user to have to install SciPy 
> separately. Is there a way around this problem?

They cannot use the function from scipy if scipy is not installed.
There are three ways round this problem:
1) Rewrite the interpolation function you need in your own code.
2) Require the user to install scipy.
3) Require the user to install some other package that has
interpolation functions.

Rewriting the interpolation function is probably not that difficult
depending on the type of interpolation you're using.


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


Re: Fixing escaped characters python-xbee

2013-04-24 Thread MRAB

On 24/04/2013 08:33, pablobl...@gmail.com wrote:

I am using a XBee to receive data from an arduino network.

But they have AP=2 which means escaped characters are used when a 11 or 13 
appears (and some more...)

When this occurs, XBee sends 7D and inmediatly XOR operation with char and 0x20.

I am trying to recover the original character in python but I don't know ho to 
do it.

I tried something like this:

read = ser.read(4) #Read 4 chars from serial port
for x in range (0,4):
if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal 
just for checking purposes
if(x < 3):
read[x] = logical_xor(read[x+1], 20) #XOR
for y in range (x+1,3):
read[y] = read[y+1] 

read[3] = ser.read()
else:
read[x] = logical_xor(ser.read(), 20) #XOR

data = struct.unpack('
You could try converting to a list, which is mutable.

# Python 3
read = list(ser.read(4))

pos = 0
try:
while True:
pos = read.index(0x7D, pos)
del read[pos]
read.extend(ser.read())
read[pos] ^= 0x20
except ValueError:
# There are no (more) 0x7D in the data.
pass

data = struct.unpack('http://mail.python.org/mailman/listinfo/python-list


examples of pyraknet

2013-04-24 Thread Jorge Alberto Diaz Orozco
do anyone has examples of pyraknet???

I've being seen these ones (http://nullege.com/codes/search/pyraknet) but I 
still don't understand lot of things about it and I can't find anything else.


http://www.uci.cu
-- 
http://mail.python.org/mailman/listinfo/python-list


Using SciPy in application

2013-04-24 Thread Roozbeh
Hi all,

I want to use spline interpolation function from SciPy in an application and at 
the same time, I don't want the end user to have to install SciPy separately. 
Is there a way around this problem?

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


Re: List Count

2013-04-24 Thread Blind Anagram
On 24/04/2013 02:59, Steven D'Aprano wrote:
> On Tue, 23 Apr 2013 17:57:17 +0100, Blind Anagram wrote:

[snip]

> In my opinion, it is more important to be efficient for large sieves, not 
> small. As they say, for small N, everything is fast. Nobody is going to 
> care about the difference between small-N taking 1ms or 10ms, but they 
> will care about the difference between big-N taking 1 minute or 1 hour. 
> So, as a general rule, optimize the expensive cases, and if the cheap 
> cases are a little less cheap than they otherwise would have been, nobody 
> will care or notice.

I agree in general but it is often the case that more sophisticated
algorithms only gain traction over simpler ones at much higher points
than might be expected from a simple analysis.  In my experience a naive
sieve is an efficient solution for a general purpose sieve class
primarily intended for situations where the sieve length can be large
but not huge.

As I think you have pointed out, memory is cheap and the memory
operations needed to do copying and counting operations are fast. So
using up memory is not normally an issue.  I have just found a situation
where a copy can have a serious impact on performance in an admittedly
limiting, minority use case.   It the fact that this copy is not, in
principle, necessary, that I find disappointing.

[snip]
> In this case, I would say that adding a limit argument to list.count is 
> *absolutely not* worthwhile, because it is insufficiently general. To be 
> general enough to be worthwhile, you would have to add three arguments:
> 
> list.count(value, start=0, end=None, step=1)
> 
> But even there I don't think it's general enough to cover the costs. I 
> believe that a better solution would be to create list views to offer a 
> subset of the list without actually copying.

I don't know a great deal about Python internals but I suspect that
these solutions would offer more but also cost more.  So where the
balance of advantages would lie is unclear.  But I am not pushing for a
particular (or, indeed, any) solution.

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


Re: QTableWidget updating columns in a single row

2013-04-24 Thread Chris “Kwpolska” Warrick
On Wed, Apr 24, 2013 at 8:22 AM, Sara Lochtie  wrote:
> I have written a GUI that gets data sent to it in real time and this data is 
> displayed in a table. Every time data is sent in it is displayed in the table 
> in a new row. My problem is that I would like to have the data just replace 
> the old in the first row.
>
> The table has 6 columns (A, B, C, D, E, F) I want the new data to continue 
> replacing the old data in the same row unless the data that goes under column 
> A changes, at which point a new row would be added.
>
> Does anyone have tips on how to approach this? I can post a portion of my 
> code to get a better idea of what I have done.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list

My suggestion: compare the new data’s column A with the existing data
(store a copy of the old data somewhere?).  If it differs, add a new
row; if it doesn’t, change an existing one.  If you need help with the
exact implementation, show the *entire* code.

--
Kwpolska  | GPG KEY: 5EAAEA16
stop html mail| always bottom-post
http://asciiribbon.org| http://caliburn.nl/topposting.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Fixing escaped characters python-xbee

2013-04-24 Thread pabloblo85
I am using a XBee to receive data from an arduino network.

But they have AP=2 which means escaped characters are used when a 11 or 13 
appears (and some more...)

When this occurs, XBee sends 7D and inmediatly XOR operation with char and 0x20.

I am trying to recover the original character in python but I don't know ho to 
do it.

I tried something like this:

read = ser.read(4) #Read 4 chars from serial port
for x in range (0,4):
if(toHex(read[x]) != '7d'): #toHex converts it to hexadecimal 
just for checking purposes
if(x < 3):
read[x] = logical_xor(read[x+1], 20) #XOR
for y in range (x+1,3):
read[y] = read[y+1] 

read[3] = ser.read()
else:
read[x] = logical_xor(ser.read(), 20) #XOR

data = struct.unpack('http://mail.python.org/mailman/listinfo/python-list