Re: member functions in a class
Karl Kobata wrote: I am new to python and am wondering. When I create a class, with ‘def’ functions and if this class is instantiated say 50 times. Does this mean that all the ‘def’ functions code within the class is duplicated for each instance? Can someone give me a short and simple answer as to what happens in python? Thanks No code is duplicated. 50 "objects" are created. Each object has its own copy of the data attributes, and a reference to the (one and only) class object where the method attributes are located. That's a short answer. Perhaps too short? Gary Herron -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-schema 'best practice' question
On 18 Set, 08:28, Frank Millman <[EMAIL PROTECTED]> wrote: > I am thinking of adding a check to see if a document has changed since > it was last validated, and if not, skip the validation step. However, > I then do not get the default values filled in. > > I can think of two possible solutions. I just wondered if this is a > common design issue when it comes to xml and schemas, and if there is > a 'best practice' to handle it. > > 1. Don't use default values - create the document with all values > filled in. > > 2. Use python to check for missing values and fill in the defaults > when processing the document. > > Or maybe the best practice is to *always* validate a document before > processing it. The stated problem rings a lot of premature optimization bells; performing the validation and default-filling step every time, unconditionally, is certainly the least crooked approach. In case you really want to avoid unnecessary schema processing, if you are willing to use persistent data to check for changes (for example, by comparing a hash or the full text of the current document with the one from the last time you performed validation) you can also store the filled-in document that you computed, either as XML or as serialized Python data structures. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
Re: member functions in a class
Karl Kobata wrote: I am new to python and am wondering. When I create a class, with ‘def’ functions and if this class is instantiated say 50 times. Does this mean that all the ‘def’ functions code within the class is duplicated for each instance? Can someone give me a short and simple answer as to what happens in python? To expand slightly on Gary's answer. Dotted names -- ob.attr -- are typically (but not always) resolved as follows: does ob have attribute attr? If yes, get the corresponding object. If no, does type(ob) have attribute attr? If yes, get the corresponding object. In no, look in the baseclasses of type(ob) in some order (details not important here). So, instance methods are class attributes and instance.method will resolve to the method attribute of type(instance) -- assuming that the instance does not have an attribute of the same name. Lookup for special methods (with reserved __xxx__ names) may go directly to the class and never look at the instance attributes. -- http://mail.python.org/mailman/listinfo/python-list
Re: ssl server
On Sep 17, 10:53 pm, "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:
> On 17 Set, 19:33, Seb <[EMAIL PROTECTED]> wrote:
>
>
>
> > I'm making a ssl server, but I'm not sure how I can verify the
> > clients. What do I actually need to place in _verify to actually
> > verify that the client cert is signed by me?
>
> > 50 class SSLTCPServer(TCPServer):
> > 51 keyFile = "sslcert/server.key"
> > 52 certFile = "sslcert/server.crt"
> > 53 def __init__(self, server_address, RequestHandlerClass):
> > 54 ctx = SSL.Context(SSL.SSLv23_METHOD)
> > 55 ctx.use_privatekey_file(self.keyFile)
> > 56 ctx.use_certificate_file(self.certFile)
> > 57 ctx.set_verify(SSL.VERIFY_PEER |
> > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE,
> > self._verify)
> > 58 ctx.set_verify_depth(10)
> > 59 ctx.set_session_id('DFS')
> > 60
> > 61 self.server_address = server_address
> > 62 self.RequestHandlerClass = RequestHandlerClass
> > 63 self.socket = socket.socket(self.address_family,
> > self.socket_type)
> > 64 self.socket = SSL.Connection(ctx, self.socket)
> > 65 self.socket.bind(self.server_address)
> > 66 self.socket.listen(self.request_queue_size)
> > 67
> > 68 def _verify(self, conn, cert, errno, depth, retcode):
> > 69 return not cert.has_expired() and
> > cert.get_issuer().organizationName == 'DFS'
>
> What library are you using? PyOpenSSL?
> In that case I think you'll have more luck by posting on their mailing
> list.
Thanks, I did that and it worked.
--
http://mail.python.org/mailman/listinfo/python-list
Re: ssl server
On Sep 18, 1:05 am, Michael Palmer <[EMAIL PROTECTED]> wrote:
> On Sep 17, 1:33 pm, Seb <[EMAIL PROTECTED]> wrote:
>
>
>
> > I'm making a ssl server, but I'm not sure how I can verify the
> > clients. What do I actually need to place in _verify to actually
> > verify that the client cert is signed by me?
>
> > 50 class SSLTCPServer(TCPServer):
> > 51 keyFile = "sslcert/server.key"
> > 52 certFile = "sslcert/server.crt"
> > 53 def __init__(self, server_address, RequestHandlerClass):
> > 54 ctx = SSL.Context(SSL.SSLv23_METHOD)
> > 55 ctx.use_privatekey_file(self.keyFile)
> > 56 ctx.use_certificate_file(self.certFile)
> > 57 ctx.set_verify(SSL.VERIFY_PEER |
> > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE,
> > self._verify)
> > 58 ctx.set_verify_depth(10)
> > 59 ctx.set_session_id('DFS')
> > 60
> > 61 self.server_address = server_address
> > 62 self.RequestHandlerClass = RequestHandlerClass
> > 63 self.socket = socket.socket(self.address_family,
> > self.socket_type)
> > 64 self.socket = SSL.Connection(ctx, self.socket)
> > 65 self.socket.bind(self.server_address)
> > 66 self.socket.listen(self.request_queue_size)
> > 67
> > 68 def _verify(self, conn, cert, errno, depth, retcode):
> > 69 return not cert.has_expired() and
> > cert.get_issuer().organizationName == 'DFS'
>
> If I were you, I would just just hide behind apache, nginx oder
> another server that does ssl. just have that server proxy locally to
> your python server over http, and firewall the python server port.
Good idea, however atm this is a school project so thats not really an
option right now. However I might take this a bit furtherer and use
that solution.
--
http://mail.python.org/mailman/listinfo/python-list
Re: ssl server
On Sep 17, 7:33 pm, Seb <[EMAIL PROTECTED]> wrote:
> I'm making a ssl server, but I'm not sure how I can verify the
> clients. What do I actually need to place in _verify to actually
> verify that the client cert is signed by me?
>
> 50 class SSLTCPServer(TCPServer):
> 51 keyFile = "sslcert/server.key"
> 52 certFile = "sslcert/server.crt"
> 53 def __init__(self, server_address, RequestHandlerClass):
> 54 ctx = SSL.Context(SSL.SSLv23_METHOD)
> 55 ctx.use_privatekey_file(self.keyFile)
> 56 ctx.use_certificate_file(self.certFile)
> 57 ctx.set_verify(SSL.VERIFY_PEER |
> SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE,
> self._verify)
> 58 ctx.set_verify_depth(10)
> 59 ctx.set_session_id('DFS')
> 60
> 61 self.server_address = server_address
> 62 self.RequestHandlerClass = RequestHandlerClass
> 63 self.socket = socket.socket(self.address_family,
> self.socket_type)
> 64 self.socket = SSL.Connection(ctx, self.socket)
> 65 self.socket.bind(self.server_address)
> 66 self.socket.listen(self.request_queue_size)
> 67
> 68 def _verify(self, conn, cert, errno, depth, retcode):
> 69 return not cert.has_expired() and
> cert.get_issuer().organizationName == 'DFS'
Simply return retcode and it will work... assuming you have the certs
setup properly.
--
http://mail.python.org/mailman/listinfo/python-list
Program works great, except under less, cron or execl (Unicode?)
I have a program which works great when run from the command line. But when I run it combined with something else such as: - piping it through less - cron - execl (i.e. calling it from another python program) it gives me a unicode error File "../myparser.py", line 261, in set_attributes print "self.atd['Name'] is: ", self.atd['Name'] UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 7: ordinal not in range(128) I'd post the whole program here, except it involves weird Unicode strings. I could probably change the program to get it working under less/cron/ etc. But I'd rather understand exactly what the issue is. Why does it work fine when run directly from the command line, but not otherwise? -- http://mail.python.org/mailman/listinfo/python-list
how to do easy_install to source code, not egg?
Hi all, how to do easy_install to source code, not egg? (I don't mean "develop" option, it shouldn't call compiled egg-file). Thank you in advance, Dmitrey. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to do easy_install to source code, not egg?
dmitrey wrote: > Hi all, > how to do easy_install to source code, not egg? > > (I don't mean "develop" option, it shouldn't call compiled egg-file). $ easy_install --help --editable (-e)Install specified packages in editable form You additionally need to give the -b-option, like this: $ easy_install -eb . FooBar Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Program works great, except under less, cron or execl (Unicode?)
Sam wrote: > I have a program which works great when run from the command line. > > But when I run it combined with something else such as: > - piping it through less > - cron > - execl (i.e. calling it from another python program) > > it gives me a unicode error > > File "../myparser.py", line 261, in set_attributes > print "self.atd['Name'] is: ", self.atd['Name'] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in > position 7: ordinal not in range(128) > > I'd post the whole program here, except it involves weird Unicode > strings. > > I could probably change the program to get it working under less/cron/ > etc. > > But I'd rather understand exactly what the issue is. Why does it work > fine when run directly from the command line, but not otherwise? Most probably because when to running directly inside a terminal, it gets it's stdin/stdout as pipes - and python can't attempt to guess the proper encoding on that, as it does on a terminal. And thus, when you print unicode to the pipe, it can't decide which encoding to use. To circumvene this, try & wrap stdout into a codecs-module wrapper with a proper encoding applied (e.g. utf-8). You might make that conditionally based on the sys.stdout.encoding-variable being set or not, albeit I'm not 100% sure to what it actually gets set when used in a subprocess. But this should give you the idea where to look. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Program works great, except under less, cron or execl (Unicode?)
> Most probably because when to running directly inside a terminal, it gets That was of course meant to be "not running directly inside a terminal". > it's stdin/stdout as pipes - and python can't attempt to guess the proper > encoding on that, as it does on a terminal. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for the iPhone?
Yes it does involve Jailbreaking. Python GCC Java and Ruby are all available to run on the iPhone after you Jailbreak it. Just run the Cydia appliacation (jailbreak's AppStore) to install anything you want. For me I have not installed Python (yet). Jailbreak was only to tether iPhone to my Macbook since I've moved house and living out of a hotel until move into my next house. I would never have jailbroken if Apple did not killswitch the NetShare application. Tethering is 100% legal in my country and Apple just lost me in only 2 weeks of iPhone ownership. Cydia -> OpenSSH. Then I just reverse ssh socks proxied into my iPhone and shazam. Internet access here I am. (Downloading all my Mac updates as I type). Cheers, PN On 17/09/2008, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Anybody tried this port of Python to the iPhone? > > http://www.modmyi.com/nativeapps/python-v251/ > http://iphone.natetrue.com/ > > Hasn't been updated since July 2007. Maybe just a proof-of-concept? I'm > guessing it involves jailbreaking the phone. > > Skip > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Determine Name of the Day in the Week
Keo Sophon wrote: I've tried calendar.month_name[0], it displays empty string, while calendar.month_name[1] is "January"? Why does calendar.month_name's index not start with index 0 as calendar.day_name? the lists are set up to match the values used by the time and datetime modules; see e.g. http://docs.python.org/lib/module-time.html http://docs.python.org/lib/datetime-date.html -- http://mail.python.org/mailman/listinfo/python-list
Re: decorator and API
Steven D'Aprano wrote: I agree with you that the simple explicit approach is better. Now, to answer the question the OP didn't ask: > def choose_with_weighting(actions, weights=None): > if weights is None: > weights = [1]*len(actions) # equal weights > # Taken virtually unchanged from your code. > # I hope it does what you want it to do! It probably doesn't. > assert len(weights) == len(actions) > total = sum(weights) > choice = random.randrange(total) > while choice > weights[0]: > choice -= weights[0] > weights.pop(0) > actions.pop(0) > return actions[0] Assume two actions with equal weights [1, 1]. total becomes 2, and choice is either 0 or 1, but never > weights[0]. While this can be fixed by changing the while condition to while choice >= weights[0]: #... I prefer an approach that doesn't destroy the actions and weights lists, something like import bisect def choose_with_weighting(actions, weights=None, acc_weights=None): if acc_weights is None: if weights is None: return random.choice(actions) else: sigma = 0 acc_weights = [] for w in weights: sigma += w acc_weights.append(sigma) return actions[bisect.bisect(acc_weights, random.randrange(acc_weights[-1]))] especially if you prepare the acc_weights list once outside the function. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: SSH using PEXPECT
Hi, Wanting to use pexpect on windows too, I ran into wexpect. http://sage.math.washington.edu/home/goreckc/sage/wexpect/ I haven't given it a try yet. Does anyone have experience with that? Almar 2008/9/13 nntpman68 <[EMAIL PROTECTED]> > Hi, > > [EMAIL PROTECTED] wrote: > >> On Sep 10, 7:01 pm, Sean DiZazzo <[EMAIL PROTECTED]> wrote: >> > > I am using windows and for reason it wont let me use pexpect even tho >> I have CYGWIN installed >> >> >> I get the following error >> >> Traceback (most recent call last): >> File "new.py", line 1, in >>import ssh_session >> File "C:\Python25\lib\ssh_session.py", line 7, in >>from pexpect import * >> File "C:\Python25\lib\site-packages\pexpect.py", line 85, in >> >>support it. Pexpect is intended for UNIX-like operating >> systems.""") >> ImportError: No module named resource >> >> > You might have cygwin installed, > but the error mesage sems to indicatem that you don't use cygwin's pythonm > but the normal windows python, > > You see, that it complains about pexpcet in > C:\Python25\lib\site-packages\pexpect.py > > > > just open a cygwin window: > > then cd to the directory containign your script and type > python new.py. > > you should have at least another error message > > > bye > > > N > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: minimum install & pickling
On 17 Sep, 22:18, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Sep 17, 4:43 am, Paul Boddie <[EMAIL PROTECTED]> wrote: > > >http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > These solutions have at least the same bugs that the bare bones > solution in the corresponding framework has. Malicious code has fewer > options, but constructive code does too. If you're running foreign > code, what do you want it to do? What does it want to do? The more > options it needs, the more code you have to trust. As I noted, instead of just forbidding access to external resources, what you'd want to do is to control access instead. This idea is not exactly new: although Brett Cannon was working on a sandbox capability for CPython, the underlying concepts involving different privilege domains have been around since Safe-Tcl, if not longer. The advantage of using various operating system features, potentially together with tools like fakechroot or, I believe, Plash, is that they should work for non-Python programs. Certainly, the chances of successfully introducing people to such capabilities are increased if you don't have to persuade the CPython core developers to incorporate your changes into their code. > The only way a Python script can return a value is with sys.exit, and > only an integer at that. It is going to have output; maybe there's a > way to place a maximum limit on its consumption. It's going to have > input, so that the output is relative to something. You just make > copies to prevent it from destroying data. Maybe command-line > parameters are enough. IIRC if I recall correctly, Win32 has a way to > examine how much time a process has owned so far, and a way to > terminate it, which could be in Python's future. There is support for imposing limits on processes in the Python standard library: http://docs.python.org/lib/node521.html My experimental package, jailtools, relies on each process's sandbox being set up explicitly before the process is run, so you'd definitely want to copy data into the sandbox. Setting limits on the amount of data produced would probably require support from the operating system. Generally, when looking into these kinds of systems, most of the solutions ultimately come from the operating system: process control, resource utilisation, access control, and so on. (This is the amusing thing about Java: that Sun attempted to reproduce lots of things that a decent operating system would provide *and* insist on their use when deploying Java code in a controlled server environment, despite actually having a decent operating system to offer already.) > PyPy sandbox says: "The C code generated by PyPy is not > segfaultable." I find that to be a bold claim (whether it's true or > not). > > I'm imagining in the general case, you want the foreign code to make > changes to objects in your particular context, such as exec x in > vars. In that case, x can still be productive without any libraries, > just less productive. Defining an interface between trusted and untrusted code can be awkward. When I looked into this kind of thing for my undergraduate project, I ended up using something similar to CORBA, and my conclusion was that trusted code would need to expose an interface that untrusted "agents" would rely on to request operations outside the sandbox. That seems restrictive, but as the situation with rexec has shown, if you expose a broad interface to untrusted programs, it becomes increasingly difficult to verify whether or not the solution is actually secure. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Test if list contains another list
On Sep 9, 9:09 pm, "J. Cliff Dyer" <[EMAIL PROTECTED]> wrote: > On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > > Matimus a écrit : > > > On Sep 8, 12:32 am, Bruno Desthuilliers > > > <[EMAIL PROTECTED]> wrote: > > (snip) > > >> >>> set(a).issubset(set(b)) > > >> True > > > > Just to clarify, doing it using sets is not going to preserve order OR > > > number of elements that are the same. > > > > That is: > > > a = [1,1,2,3,4] > > b = [4,5,3,7,2,6,1] > > set(a).issubset(set(b)) > > > True > > > > This will return True if b contains at least on of each element found > > > in a. If the OP wanted to check that list `a` appeared in order > > > somewhere in list `b` then sets won't work. > > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > > If preserving order is important, strings have many of the properties > you're looking for, but it might take some work to figure out a suitable > way to convert to a string. The problem is easier if you know something > about the inputs. If all inputs are known to be numbers between 0 and > 15, you can just do: > > if ''.join(map(hex, a)) in ''.join(map(hex, b)): > return True > > Hmm... actually, with the '0x' prefix that hex() puts on numbers, I > think this works for arbitrary integers. > > Cheers, > Cliff Hi, I looked inside this thread for my query which brought me the following google search result "Test if list contains another list - comp.lang.python | Google Groups" But then I was disappointed to see the question asked was not exactly right. Other programmers have already answered to the main question. But what if you actually have to find out if a list has all its element inside another list in the same order. For that I wrote the code and that's what I came up with.. let me know if there are any bugs in this code. #!C:\Python24 def findAllMatchingList(mainList, subList): resultIndex = [] globalIndex = 0 for i in range(len(mainList)): if i < globalIndex: continue globalIndex = i increment = 0 for j in range(len(subList)): if mainList[globalIndex] == subList[j]: globalIndex += 1 increment += 1 if j == (len(subList)-1): resultIndex.append(globalIndex-increment) else: break return resultIndex if __name__ == "__main__": #Test case mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3, 'a', 1, 2, 3, 4 ]; #mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6] sL = [ 1, 2, 3 ] result = findList( mL, sL ) for i in result: print str(i) Regards, Gaurav. -- http://mail.python.org/mailman/listinfo/python-list
Re: Test if list contains another list
On Sep 18, 3:24 pm, [EMAIL PROTECTED] wrote: > On Sep 9, 9:09 pm, "J. Cliff Dyer" <[EMAIL PROTECTED]> wrote: > > > > > On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > > > Matimus a écrit : > > > > On Sep 8, 12:32 am, Bruno Desthuilliers > > > > <[EMAIL PROTECTED]> wrote: > > > (snip) > > > >> >>> set(a).issubset(set(b)) > > > >> True > > > > > Just to clarify, doing it using sets is not going to preserve order OR > > > > number of elements that are the same. > > > > > That is: > > > > a = [1,1,2,3,4] > > > b = [4,5,3,7,2,6,1] > > > set(a).issubset(set(b)) > > > > True > > > > > This will return True if b contains at least on of each element found > > > > in a. If the OP wanted to check that list `a` appeared in order > > > > somewhere in list `b` then sets won't work. > > > > Indeed, and I should have mentionned this myself. Thanks for this > > > reminder. > > > If preserving order is important, strings have many of the properties > > you're looking for, but it might take some work to figure out a suitable > > way to convert to a string. The problem is easier if you know something > > about the inputs. If all inputs are known to be numbers between 0 and > > 15, you can just do: > > > if ''.join(map(hex, a)) in ''.join(map(hex, b)): > > return True > > > Hmm... actually, with the '0x' prefix that hex() puts on numbers, I > > think this works for arbitrary integers. > > > Cheers, > > Cliff > > Hi, > > I looked inside this thread for my query which brought me the > following google search result > "Test if list contains another list - comp.lang.python | Google > Groups" > > But then I was disappointed to see the question asked was not exactly > right. Other programmers have already answered to the main question. > But what if you actually have to find out if a list has all its > element inside another list in the same order. For that I wrote the > code and that's what I came up with.. let me know if there are any > bugs in this code. > > #!C:\Python24 > > def findAllMatchingList(mainList, subList): > resultIndex = [] > globalIndex = 0 > for i in range(len(mainList)): > if i < globalIndex: > continue > globalIndex = i > increment = 0 > for j in range(len(subList)): > if mainList[globalIndex] == subList[j]: > globalIndex += 1 > increment += 1 > if j == (len(subList)-1): > resultIndex.append(globalIndex-increment) > else: > break > > return resultIndex > > if __name__ == "__main__": > #Test case > mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3, > 'a', 1, 2, 3, 4 ] > #mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6] > sL = [ 1, 2, 3 ] > result = findAllMatchingList( mL, sL ) > for i in result: > print str(i) > > Regards, > Gaurav. -- http://mail.python.org/mailman/listinfo/python-list
how can I use a callable object as a method
Hello, I would like to use a callable object as a method of a class. So, when I have such normal class: class f: version = 17 def a(self): return self.version f1 = f() print f1.a() I want to change it to something like that: class add: def __call__(self, another_self): return another_self.version class f: version = 17 a = add() f1 = f() print f1.a() However, the second version does not work. I think I understand why. That's because "a" inside f1 is not a function (but an object). So f1.a is not a method. So when I do f1.a(), the implicit argument self is not passed. Q1: Am I right? Is this the problem? Q2: What can I do to make it work? -- http://mail.python.org/mailman/listinfo/python-list
Re: decorator and API
Lee Harr wrote:
I have a class with certain methods from which I want to select
one at random, with weighting.
The way I have done it is this
import random
def weight(value):
def set_weight(method):
method.weight = value
return method
return set_weight
class A(object):
def actions(self):
'return a list of possible actions'
return [getattr(self, method)
for method in dir(self)
if method.startswith('action_')]
def action(self):
'Select a possible action using weighted choice'
actions = self.actions()
weights = [method.weight for method in actions]
total = sum(weights)
choice = random.randrange(total)
while choice> weights[0]:
choice -= weights[0]
weights.pop(0)
actions.pop(0)
return actions[0]
@weight(10)
def action_1(self):
print "A.action_1"
@weight(20)
def action_2(self):
print "A.action_2"
a = A()
a.action()()
The problem I have now is that if I subclass A and want to
change the weighting of one of the methods, I am not sure
how to do that.
One idea I had was to override the method using the new
weight in the decorator, and then call the original method:
class B(A):
@weight(50)
def action_1(self):
A.action_1(self)
That works, but it feels messy.
Another idea was to store the weightings as a dictionary
on each instance, but I could not see how to update that
from a decorator.
I like the idea of having the weights in a dictionary, so I
am looking for a better API, or a way to re-weight the
methods using a decorator.
Any suggestions appreciated.
Here is another approach:
8<---
import random
from bisect import bisect
#by George Sakkis
def take_random_action(obj, actions, weights):
total = float(sum(weights))
cum_norm_weights = [0.0]*len(weights)
for i in xrange(len(weights)):
cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/total
return actions[bisect(cum_norm_weights, random.random())](obj)
class randomiser(object):
_cache = []
@classmethod
def alert(cls, func):
assert hasattr(func, 'weight')
cls._cache.append(func)
@classmethod
def register(cls, name, obj):
actions = {}
weights = []
for klass in obj.__class__.__mro__:
for val in klass.__dict__.itervalues():
if hasattr(val, '__name__'):
key = val.__name__
if key in actions:
continue
elif val in cls._cache:
actions[key] = val
weights.append(val.weight)
actions = actions.values()
#setattr(cls, name, classmethod(lambda cls:
random.choice(actions)(obj)))
setattr(cls, name, classmethod(lambda cls:
take_random_action(obj, actions, weights)))
def randomised(weight):
def wrapper(func):
func.weight = weight
randomiser.alert(func)
return func
return wrapper
class A(object):
@randomised(20)
def foo(self):
print 'foo'
@randomised(10)
def bar(self):
print 'bar'
class B(A):
@randomised(50)
def foo(self):
print 'foo'
8<---
randomiser.register('a', A())
randomiser.register('b', B())
print 'A'
randomiser.a()
randomiser.a()
randomiser.a()
randomiser.a()
randomiser.a()
randomiser.a()
print 'B'
randomiser.b()
randomiser.b()
randomiser.b()
randomiser.b()
randomiser.b()
randomiser.b()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python for the iPhone?
On 17 Sep, 11:54, [EMAIL PROTECTED] wrote: > Anybody tried this port of Python to the iPhone? > > http://www.modmyi.com/nativeapps/python-v251/ > http://iphone.natetrue.com/ > > Hasn't been updated since July 2007. Maybe just a proof-of-concept? I'm > guessing it involves jailbreaking the phone. There's a very brief summary of iPhone drawbacks with respect to openness in this very interesting presentation from PyCon UK: http://freshfoo.com/presentations/PyCon_UK-2008/slides/ Although it probably doesn't tell you anything you didn't already know about Apple's disdain for people running "unauthorised" software on the iPhone, I think the Python involvement in Openmoko is very interesting and deserving of wider attention, especially amongst those considering getting a mobile device for its Python capabilities. Paul -- http://mail.python.org/mailman/listinfo/python-list
PEP proposal optparse
Hi,
I would like to know your thoughts on a proposed change to optparse
that I have planned. It is possible to add default values to multiple
options using the set_defaults. However, when adding descriptions to
options the developer has to specify it in each add_option() call.
This results in unreadable code such as:
parser.add_option('-q', '--quiet', action="store_false",
dest='verbose',
help = 'Output less information')
parser.add_option('-o', '--output' , type='string',
dest='castordir' , metavar='' ,
help = 'specify the wanted CASTOR directory where to store the
results tarball')
parser.add_option('-r', '--prevrel' , type='string',
dest='previousrel' , metavar='' ,
help = 'Top level dir of previous release for regression
analysis' )
The same code could become much more readable if there was an
equivalent method of set_defaults for the description/help of the
option. The same code could then become:
parser.set_description(
verbose = 'Output less information',
castordir= 'specify the wanted CASTOR directory where
to store the results tarball',
previousrel = 'Top level dir of previous release for
regression analysis')
parser.add_option('-q', '--quiet', action="store_false",
dest='verbose')
parser.add_option('-o', '--output' , type='string',
dest='castordir' , metavar='' )
parser.add_option('-r', '--prevrel' , type='string',
dest='previousrel' , metavar='' )
Help descriptions can often be quite long and separating them in this
fashion would, IMHO, be desirable.
Kind Regards,
James Nicolson
--
http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
Hi James,
I can't say I really agree with your
proposal. I tend to keep the help
descriptions of my options short
and concise and to the point.
Also, one must use the language's
features (indentation) to your advantage,
as doing so ensure readability.
For example (from my bhimport tool):
def parse_options():
"""parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
"""
parser = optparse.OptionParser(usage=USAGE, version=VERSION)
parser.add_option("", "--date-format",
action="store",type="str", default="%d/%m/%Y",
dest="dateFormat",
help="date format string")
parser.add_option("", "--time-format",
action="store", type="str", default="%H:%M:%S",
dest="timeFormat",
help="time format string")
parser.add_option("", "--datetime-format",
action="store", type="str", default="%H:%M:%S %d/%m/%Y",
dest="datetimeFormat",
help="datetime format string")
opts, args = parser.parse_args()
if len(args) < 2:
parser.print_help()
raise SystemExit, 1
return opts, args
As you can see (as long as you're
reading this in fixed-width fonts)
it _is_ very readable.
cheers
James
On 9/18/08, James <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would like to know your thoughts on a proposed change to optparse
> that I have planned. It is possible to add default values to multiple
> options using the set_defaults. However, when adding descriptions to
> options the developer has to specify it in each add_option() call.
> This results in unreadable code such as:
>
> parser.add_option('-q', '--quiet', action="store_false",
> dest='verbose',
> help = 'Output less information')
> parser.add_option('-o', '--output' , type='string',
> dest='castordir' , metavar='' ,
> help = 'specify the wanted CASTOR directory where to store the
> results tarball')
> parser.add_option('-r', '--prevrel' , type='string',
> dest='previousrel' , metavar='' ,
> help = 'Top level dir of previous release for regression
> analysis' )
>
> The same code could become much more readable if there was an
> equivalent method of set_defaults for the description/help of the
> option. The same code could then become:
>
> parser.set_description(
> verbose = 'Output less information',
> castordir= 'specify the wanted CASTOR directory where
> to store the results tarball',
> previousrel = 'Top level dir of previous release for
> regression analysis')
>
> parser.add_option('-q', '--quiet', action="store_false",
> dest='verbose')
> parser.add_option('-o', '--output' , type='string',
> dest='castordir' , metavar='' )
> parser.add_option('-r', '--prevrel' , type='string',
> dest='previousrel' , metavar='' )
>
> Help descriptions can often be quite long and separating them in this
> fashion would, IMHO, be desirable.
>
> Kind Regards,
> James Nicolson
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list
ANN: bbfreeze 0.96.5
Hi all, I uploaded bbfreeze 0.96.5 to the python package index. bbfreeze creates standalone executables from python scripts (similar to py2exe). bbfreeze works on windows and unix-like operating systems (no OS X unfortunately). bbfreeze is able to freeze multiple scripts, handle egg files and track binary dependencies. This release features a new bdist_bbfreeze command, which integrates bbfreeze into setup.py scripts (contributed by Hartmut Goebel, thanks). More information can be found at the python package index: http://pypi.python.org/pypi/bbfreeze/ Regards, - Ralf -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
Perhaps it is better to keep descriptions short and store longer
descriptions elsewhere, but there are many programs that have long
descriptions, for example try: ls --help (at least on my machine a lot
of these descriptions are quite long).
2008/9/18 James Mills <[EMAIL PROTECTED]>:
> Hi James,
>
> I can't say I really agree with your
> proposal. I tend to keep the help
> descriptions of my options short
> and concise and to the point.
>
> Also, one must use the language's
> features (indentation) to your advantage,
> as doing so ensure readability.
>
> For example (from my bhimport tool):
>
>
> def parse_options():
> """parse_options() -> opts, args
>
> Parse any command-line options given returning both
> the parsed options and arguments.
> """
>
> parser = optparse.OptionParser(usage=USAGE, version=VERSION)
>
> parser.add_option("", "--date-format",
> action="store",type="str", default="%d/%m/%Y",
> dest="dateFormat",
> help="date format string")
> parser.add_option("", "--time-format",
> action="store", type="str", default="%H:%M:%S",
> dest="timeFormat",
> help="time format string")
> parser.add_option("", "--datetime-format",
> action="store", type="str", default="%H:%M:%S %d/%m/%Y",
> dest="datetimeFormat",
> help="datetime format string")
>
> opts, args = parser.parse_args()
>
> if len(args) < 2:
> parser.print_help()
> raise SystemExit, 1
>
> return opts, args
>
>
> As you can see (as long as you're
> reading this in fixed-width fonts)
> it _is_ very readable.
>
> cheers
> James
>
> On 9/18/08, James <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I would like to know your thoughts on a proposed change to optparse
>> that I have planned. It is possible to add default values to multiple
>> options using the set_defaults. However, when adding descriptions to
>> options the developer has to specify it in each add_option() call.
>> This results in unreadable code such as:
>>
>> parser.add_option('-q', '--quiet', action="store_false",
>> dest='verbose',
>> help = 'Output less information')
>> parser.add_option('-o', '--output' , type='string',
>> dest='castordir' , metavar='' ,
>> help = 'specify the wanted CASTOR directory where to store the
>> results tarball')
>> parser.add_option('-r', '--prevrel' , type='string',
>> dest='previousrel' , metavar='' ,
>> help = 'Top level dir of previous release for regression
>> analysis' )
>>
>> The same code could become much more readable if there was an
>> equivalent method of set_defaults for the description/help of the
>> option. The same code could then become:
>>
>> parser.set_description(
>> verbose = 'Output less information',
>> castordir= 'specify the wanted CASTOR directory where
>> to store the results tarball',
>> previousrel = 'Top level dir of previous release for
>> regression analysis')
>>
>> parser.add_option('-q', '--quiet', action="store_false",
>> dest='verbose')
>> parser.add_option('-o', '--output' , type='string',
>> dest='castordir' , metavar='' )
>> parser.add_option('-r', '--prevrel' , type='string',
>> dest='previousrel' , metavar='' )
>>
>> Help descriptions can often be quite long and separating them in this
>> fashion would, IMHO, be desirable.
>>
>> Kind Regards,
>> James Nicolson
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
> --
> --
> -- "Problems are solved by method"
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
James Mills wrote: As you can see (as long as you're reading this in fixed-width fonts) it _is_ very readable. given that it only relies on indentation from the left margin, it's no less readable in a proportional font (unless you're using an font with variable-width spaces, that is ;-). -- http://mail.python.org/mailman/listinfo/python-list
XML Processing
Guys, I'm running python 2.5 and currently using ElementTree to perform my XML parsing and creation. ElementTree really is a great package for doing this, however, I've been tasked by our deployment guys to try and move away from external libraries where possible as it makes their job easier. Simple question I suppose to start with, does Python have any inbuilt XML processing modules? If the answer is no then I'll stick with eTree, if python does have one, then I'll look at some migration steps. Many thanks All, Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I use a callable object as a method
Piotr Sobolewski <[EMAIL PROTECTED]> writes: > I would like to use a callable object as a method of a class. So, when I > have such normal class: > > I want to change it to something like that: > > class add: > def __call__(self, another_self): > return another_self.version > > class f: > version = 17 > a = add() > > f1 = f() > print f1.a() > > However, the second version does not work. I think I understand why. That's > because "a" inside f1 is not a function (but an object). So f1.a is not a > method. So when I do f1.a(), the implicit argument self is not passed. > > Q1: Am I right? Is this the problem? > Q2: What can I do to make it work? Use the right argument for the call. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class add: def __call__(self, another_self): return another_self.version ... ... ... >>> class f: version = 17 a = add() ... ... ... >>> f1 = f() >>> f1 <__main__.f instance at 0x00A805D0> >>> f1.a <__main__.add instance at 0x00A80DA0> >>> f1.a() Traceback (most recent call last): File "", line 1, in TypeError: __call__() takes exactly 2 arguments (1 given) >>> f1.a(f1) 17 >>> HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I use a callable object as a method
Piotr Sobolewski <[EMAIL PROTECTED]> writes: > However, the second version does not work. I think I understand > why. That's because "a" inside f1 is not a function (but an object). An object that defines __call__ is perfectly usable as a function. Your problem is that it doesn't know how to convert itself to a method, so that f1.a() knows how to pass f1 as another_self to add.__call__. To do that, add needs to be a bit smarter: >>> class add(object): ... def __call__(self, another_self): ... return another_self.version ... def __get__(self, obj, type=None): ... return lambda: self(obj) ... >>> class f(object): ... version = 17 ... a = add() ... >>> f1 = f() >>> f1.a() 17 If you can't modify add, you can probably use an adaptor that defines __get__ in a similar way. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Processing
2008/9/18 Robert Rawlins <[EMAIL PROTECTED]>: > Guys, > > > > I'm running python 2.5 and currently using ElementTree to perform my XML > parsing and creation. ElementTree really is a great package for doing this, > however, I've been tasked by our deployment guys to try and move away from > external libraries where possible as it makes their job easier. > > > > Simple question I suppose to start with, does Python have any inbuilt XML > processing modules? If the answer is no then I'll stick with eTree, if > python does have one, then I'll look at some migration steps. > ElementTree is not an external package starting from Python 2.5. It's in stdlib under 'xml.etree.ElementTree' name. There's also a lot of other XML processing modules in stdlib's 'xml' package. > > > Many thanks All, > > > > Robert > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Processing
Robert Rawlins wrote: I’m running python 2.5 and currently using ElementTree to perform my XML parsing and creation. ElementTree really is a great package for doing this, however, I’ve been tasked by our deployment guys to try and move away from external libraries where possible as it makes their job easier. Some is going to kick themselves when they realise that ElementTree *is* built in to Python 2.5 http://docs.python.org/whatsnew/modules.html#SECTION000142 TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-schema 'best practice' question
Frank> 1. Don't use default values - create the document with all values Frank> filled in. Frank> 2. Use python to check for missing values and fill in the defaults Frank> when processing the document. Frank> Or maybe the best practice is to *always* validate a document Frank> before processing it. Frank> How do experienced practitioners handle this situation? 3. Don't use XML. (sorry, couldn't resist) Skip -- http://mail.python.org/mailman/listinfo/python-list
improving a huge double-for cycle
Hello there :) , I am a python newbie and need to run following code for a task in an external simulation programm called "Abaqus" which makes use of python to access the mesh (ensamble of nodes with xy coordinates) of a certain geometrical model. [IN is the starting input containing the nodes to be check, there are some double nodes with the same x and y coordinates which need to be removed. SN is the output containing such double nodes] Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) Unfortunately my len(IN) is about 100.000 and the running time about 15h :( Any idea to improve it? I have already tried to group the "if statements" in a single one: Code: Select all if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and if IN[i].coordinates[1] == IN[j].coordinates[1]: but no improvements. Many thanks, Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Alex> Unfortunately my len(IN) is about 100.000 and the running time Alex> about 15h :( Alex> Any idea to improve it? numpy? http://numpy.scipy.org/ http://www.scipy.org/Numpy_Example_List More immediately, note that you are building a list of len(IN) ints every time through the inner loop. A quick hit might be this simple change: indexes = range(len(IN)) for i in indexes: #scan all elements of the list IN for j in indexes: if i != j: if (IN[i].coordinates[0] == IN[j].coordinates[0] and IN[i].coordinates[1] == IN[j].coordinates[1]): SN.append(IN[i].label) Skip -- http://mail.python.org/mailman/listinfo/python-list
RE: XML Processing
> Some is going to kick themselves when they realise > that ElementTree *is* built in to Python 2.5 > > http://docs.python.org/whatsnew/modules.html#SECTION000142 Tim, Andrii, Thanks for the heads up on that! I hadn't noticed they're made it part of the platform modules, that's excellent news. In theory I should just be able to amend my import paths and we'll be good to go, no install external modules. Thanks for this, Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: >if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h :( > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > > but no improvements. > > Many thanks, Alex When you're looking for duplicates an efficient solution is likely to be based on a set or dict object. # untested from collections import defaultdict groups = defaultdict(list) for item in IN: c = item.coordinates groups[c[0], c[1]].append(item.label) SN = [] for labels in groups.itervalues(): if len(labels) > 1: SN.extend(labels) # or labels[1:] if you want to keep one item Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) Unfortunately my len(IN) is about 100.000 and the running time about 15h :( Any idea to improve it? [snip] I have already tried to group the "if statements" in a single one: Code: Select all if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and if IN[i].coordinates[1] == IN[j].coordinates[1]: but no improvements. It's like rearranging deck-chairs on the Titanic :) Yes, it may give a speed up, but what's 3 seconds when you're waiting 15hr :) Not knowing the len(IN[x].coordinates) or their structure, if it's a list of len==2, you should be able to just do if i <> j and IN[i].coordinates == IN[j].coordinates or if i <> j and IN[i].coordinates[:2] == IN[j].coordinates[:2] However, again, this is just polish. The big problem is that you have an O(N^2) algorithm that's killing you. 1) use xrange instead of range to save eating memory with a huge unneeded array. 2) unless you need to append duplicate labels, you know that when I and J are swapped, you'll reach the same condition again, so it might be worth writing the outer loops to eliminate this scenario, and in the process, but just starting at i+1 rather than i, you can forgo the check if "i<>j". Such changes might look something like for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates == IN[j].coordinates: SN.append(IN[i].label) If my college algorithms memory serves me sufficiently, this reduces your O(N^2) to O(N log N) which will garner you some decent time savings. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
On Thu, 18 Sep 2008 03:37:54 -0700, James wrote:
> Hi,
>
> I would like to know your thoughts on a proposed change to optparse that
> I have planned. It is possible to add default values to multiple options
> using the set_defaults. However, when adding descriptions to options the
> developer has to specify it in each add_option() call. This results in
> unreadable code such as:
[snip]
I don't find it unreadable at all. I find it very helpful to have the
help text associated right there with the rest of the option, instead of
hidden in a different function call.
[...]
> Help descriptions can often be quite long and separating them in this
> fashion would, IMHO, be desirable.
If the help descriptions are so long that they are a problem, then the
solution I would choose is to put them in their own module, then do
something like this:
import docs
parser.add_option('-q', '--quiet', action="store_false",
dest='verbose', help=docs.quiet)
parser.add_option('-o', '--output', type='string',
dest='castordir', metavar='', help=docs.output)
etc.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Skip: > indexes = range(len(IN)) > for i in indexes: #scan all elements of the list IN > for j in indexes: Nope, use xrange in both situations, and save a list. Tim Chase: >for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): >if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) > > If my college algorithms memory serves me sufficiently, this > reduces your O(N^2) to O(N log N) which will garner you some > decent time savings. That's O(n^2) still, it's just half matrix, a triangle. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] XPN 1.2.5
Nemesis wrote: > XPN (X Python Newsreader) is a multi-platform newsreader with Unicode > support. It is written with Python+GTK. It has features like > scoring/actions, X-Face and Face decoding, muting of quoted text, > newsrc import/export, find article and search in the body, spoiler > char/rot13, random taglines and configurable attribution lines. Thanks! It works great. What I especially like about it is that it can be run from the directory it is in, without needing to be installed. This enabled me to run it under Ubuntu from another Ubuntu computer using sshfs. After some tinkering I was also able to run the same instance from a windows XP computer using a samba share. (Although the samba share was rather hard to set up because all the subdirectories needed permissions ... something like sudo chmod o+rw -R *). To make it run from that XP computer I also needed to add an sys.path.insert(0,'./') after import sys in xpn.py . But anyway, I can now run it from anywhere and I'm really looking forward to start tinkering with whatever other functionality I can think of to add to it, but unfortunately it is rather complete :-) . Did you know there is a tab in Articles_DB.py line 8? :-) Ducking ... P. -- http://mail.python.org/mailman/listinfo/python-list
Login to website using urllib2
Hi All, I am trying to fetch HTML content from a website that has different version of pages for "logged" users and "guseuests" users. I need to fetch the "logged" user pages. The problem is, even with the use of basic authentication, I am getting "guest" user page with urllib2.urlopen. The code can be seen here. http://pastebin.com/m7301084a Any suggestions/pointers/solutions? Thanks and regards, Mohit Ranka. -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
On Thu, 18 Sep 2008 05:25:02 -0700, Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a certain > geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: >if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) Here's a better version of your algorithm, one which avoids the minor inefficiencies but keeps the huge inefficiency: for node1 in IN: for node2 in IN: if node1 is not node2: if node1.coordinates == node2.coordinates: SN.append(node1.label) This assumes that node.coordinates is a type where equality is defined. If they are a tuple or list, that should work fine. But the huge inefficiency is that you are checking each node not once, not twice, but 100,000 times! So you have to iterate 10,000,000,000 times, which is going to be slow no matter what you do. Especially in pure Python. Here's a better idea: iterate over the list once only: seen = set() for node in IN: coords = tuple(node.coordinates) if coords in seen: SN.append(node.label) else: seen.add(coords) Hope this helps. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Python GUI development using XULRunner
On 17 Set, 03:29, Todd Whiteman <[EMAIL PROTECTED]> wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI > application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd well, it just works. Now let's see how :-) Nice job, Riccardo p.s. I'm on a Gentoo Linux 64 bit, no problems at all -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Tim Chase: for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates == IN[j].coordinates: SN.append(IN[i].label) If my college algorithms memory serves me sufficiently, this reduces your O(N^2) to O(N log N) which will garner you some decent time savings. That's O(n^2) still, it's just half matrix, a triangle. Ah, good catch as I'm thinking about it more, you're right...it's O((N^2)/2) which is just O(N^2). Sigh. I'm not awake enough yet. However, dividing the time by 2 (from 15hr to 7.5hr) is still a significant savings in my book :) However, if list-comprehensions are faster as well, you might be able to do something like SN = [d.label for (i,d) in enumerate(IN) for j in xrange(i+1, len(IN)) if d.coordinates == IN[j].coordinates ] or the slightly more verbose (but closer to my original code) version SN = [IN[i].label for i in xrange(len(IN)) for j in xrange(i+1, len(IN)) if IN[i].coordinates == IN[j].coordinates ] To the OP: As always, throw some timing code on the various samples you get back from the list and see what works for you. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: XPN 1.2.5
On Sep 18, 3:17 pm, pataphor <[EMAIL PROTECTED]> wrote: > >XPN(X Python Newsreader) is a multi-platform newsreader with Unicode > > support. It is written with Python+GTK. It has features like > > scoring/actions, X-Face and Face decoding, muting of quoted text, > > newsrc import/export, find article and search in the body, spoiler > > char/rot13, random taglines and configurable attribution lines. > > Thanks! It works great. thank you :-) > What I especially like about it is that it can > be run from the directory it is in, without needing to be installed. I dislike installation procedures ;-) > But anyway, I can now run it from anywhere and I'm really looking > forward to start tinkering with whatever other functionality I can > think of to add to it, but unfortunately it is rather complete :-) . there is always space for improvements, and some help would be very apreciated. What could be improved is the speed and the code should be also refactored. > Did you know there is a tab in Articles_DB.py line 8? :-) Ducking ... NO! thank you, damned tabs. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Processing
Robert Rawlins wrote: Some is going to kick themselves when they realise that ElementTree *is* built in to Python 2.5 http://docs.python.org/whatsnew/modules.html#SECTION000142 Tim, Andrii, Thanks for the heads up on that! I hadn't noticed they're made it part of the platform modules, that's excellent news. In theory I should just be able to amend my import paths and we'll be good to go, no install external modules. I imagine I'm not the only person with conditional imports of this type: try: from xml.etree import cElementTree as ET except ImportError: from elementtree import ElementTree as ET TJG -- http://mail.python.org/mailman/listinfo/python-list
matplotlib in interactive mode locks when run from subprocess
Hi, In wxpython, I made an interactive shell, which creates a remote python subprocess to do the interpreting. Communication is done via a pipe. The idea is that the python session is an actual process separate from the GUI, which has some advantages, like I can have multiple such shells in my application, and I can kill them without worrying that my wx app will crash. To do this I use the wx.Process class, which allows asynchronous communication with the remote process. This all works really, I will also launch wxpython apps. So I was quite happy, untill I tried doing some plotting with matplotlib (in TkAgg backend). The problem is that the process becomes unresponsive when I plot something (No prompt is written to the stdout/stderr). (more details below) I don't know much about creating subprocess and how they are different from a normal process. So can anyone offer some help as to what the problem might be? Thanks in advance, Almar To get to the details: - When I start a process with command "python -u -i" -- When interactive mode is off, the whole process becomes unresponsive when doing pylab.show() -- When interactive mode in on, on doing pylab.plot(), a figure appears, which I can zoom etc., but the process is now stuck, also after closing the figure - When I start a process with command "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is how Pype does it). -- When interactive mode is off, the figures show when doing pylab.show() and the process behaves as normal after closing the figure(s). -- When interactive mode in on, on doing pylab.plot(), a figure appears, but most of the time it is not drawn and emmediately unresponsive, just like the process itself. I have also tried an asynchronous Popen recipe by Joshiah Carlson I found on activestate. And I made my own process class using win32process.CreateProcess. Both alternatives to wx.Process resulted in the same sympoms. Oh, and I run windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
On Thu, 2008-09-18 at 07:57 -0500, Tim Chase wrote: > > Code: Select all > > for i in range(len(IN)): #scan all elements of the list IN > > for j in range(len(IN)): > > if i <> j: > > if IN[i].coordinates[0] == IN[j].coordinates[0]: > >if IN[i].coordinates[1] == IN[j].coordinates[1]: > > SN.append(IN[i].label) > > > > > Such changes might look something like > >for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): >if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) If you aren't checking j values less than i, you might want to do both SN.append(IN[i].label) SN.append(IN[j].label) on the same pass. > If my college algorithms memory serves me sufficiently, this > reduces your O(N^2) to O(N log N) which will garner you some > decent time savings. > > -tkc > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
fwd: member functions in a class
Gary, No the answer is not too short, thank you for your reply, I am learning rapidly. Terry, The expanded answer is also useful. Now I am getting a better insight on how python resolves object attributes. This also gives me more insight on the difference between import vs from from *. Thanks karl -- http://mail.python.org/mailman/listinfo/python-list
Cython dynamic library problem
I am trying to learn how to use cython, and while I am following the cython-dev mailing list I didn't feel like this question was totally appropriate for its audience so I am trying here first. I am on a max os x 10.5.4 running drtgrav% python ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 17:40:23) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> I have a pure python file that I am wanting to try to speed up some, so I ran the file through cython, compiled it with gcc and tried to call it from a python file > cython integrations.pyx > gcc -arch ppc -shared -c -fPIC -I/usr/include/python2.5 integration.c -o pyx_integration.so > python integration_test.py Traceback (most recent call last): File "integration_test.py", line 1, in from astroPyX import pyx_integration ImportError: dlopen(/Users/drtgrav/Work/myCode/Python/astroPyX/ pyx_integration.so, 2): no suitable image found. Did find: /Users/drtgrav/Work/myCode/Python/astroPyX/pyx_integration.so: can't map where integration_test.py is from astroPyX import pyx_integration pyx_integration.test(0) pyx_integration.test(100) Does anyone know what the ImportError means and how to correct it? Cheers Tommy -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem occured while sending mail
On Wed, 17 Sep 2008 23:53:36 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote: > On Sep 17, 8:04 pm, Peter Pearson <[EMAIL PROTECTED]> wrote: >> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <[EMAIL PROTECTED]> wrote: [snip] >> > socket.error: (110, 'Connection timed out') [snip] >> As a simple connectivity test, you might see whether you can connect >> using telnet: [snip] > even i couldnt connect using telnet > msg comes host is down Then your problem is a networking problem. I know even less about networking than I know about Python. Can you ping the destination? Perhaps tracepath or traceroute will help you find where your messages are being refused. Perhaps you are trying to work through an internet access provider (e.g., ISP) that doesn't allow direct connections to remote mail servers. If I might add a grouchy comment, you really should learn a little about netiquette. When you don't bother to trim the quoted context or even to punctuate your text, you broadcast a conspicuous implication that you value your own time much more than you value the time of the people whose help you're soliciting, which is incongruous and insulting. A more carefully presented request might have gotten a response from someone more knowledgeable -- and less grouchy -- than me. -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
dict generator question
Hi,
Let's say I have an arbitrary list of minor software versions of an
imaginary software product:
l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
I'd like to create a dict with major_version : count.
(So, in this case:
dict_of_counts = { "1.1" : "1",
"1.2" : "2",
"1.3" : "2" }
Something like:
dict_of_counts = dict([(v[0:3], "count") for v in l])
I can't seem to figure out how to get "count", as I cannot do x += 1
or x++ as x may or may not yet exist, and I haven't found a way to
create default values.
I'm most probably not thinking pythonically enough... (I know I could
do this pretty easily with a couple more lines, but I'd like to
understand if there's a way to use a dict generator for this).
Thanks in advance
SM
--
Simon Mullis
--
http://mail.python.org/mailman/listinfo/python-list
Re: A unique instance of Python GUI program
On 2008-09-16, akineko <[EMAIL PROTECTED]> wrote: > This may not be a Python specific challenge. I have a GUI > program written in Python + Tkinter. It works very well. > > Now, I would like to start it from a shell script. As my GUI > program includes a server, it should not have more than one > instance. Is there any easy way to check if another instance > of the program is already running. > > I vaguely remember that Windows programming provides a way to > check. On unix the solution is usually a lockfile placed in a predefined location. Other people use a socket, but that's a bit more susceptible to namespace collisions with unrelated programs. > A platform independent approach would be nice but a solution > for X is sufficient for my application. I don't see what X has to do with it. > Any comments will be greatly appreciated. This question is asked and answered about once a week, and I'm always surprised at how frequently it comes up. I've been doing sw development for decades and apart from Unix system daemons, I don't remember ever needing to prevent multiple instances of an application from running. Can somebody lend me a clue as to why this question comes up so often? There can't be that many people writing Unix daemons in Python (and if they were, they'd probably already know about lockfiles). Just curious... -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.comGARBAGE CAN? -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying the system menu
On Sep 18, 6:39 am, [EMAIL PROTECTED] wrote: > I tested it again and found that the behaviour is a little different > from what I mentioned previously in the mailchain. > The item is working perfectly the first time around. Now if I close > the application and run it again (which was what I did earlier), if > that application system menu is already modified, it is causing this > issue. > > Why would this happen? If it is that the file handle is not obtained, > it wouldnt have gone through the following check at all? > > > hw = win32gui.GetSystemMenu(hwnd, False) > > if hw != None: > > win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); > > Not only did it go through, it failed with an invalid menu handle > error. More worryingly, this happens randomly. Am I doing some mistake here? -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
On Sep 18, 8:25 am, Alexzive <[EMAIL PROTECTED]> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: >if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > but no improvements. > > Many thanks, Alex dup=set() SN=[] for item in IN: c=item.coordinates[0], item.coordinates[1] if c in dup: SN.append(item.label) else: dup.add(c) -- http://mail.python.org/mailman/listinfo/python-list
unicode in multi-line strings
Hello, I have a problem with international characters in multi-line strings. Works: '''á''' Works: ''' a''' Does not work: ''' á''' By does not work I mean the infamous 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128) I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, from scripts, or from scripts with the encoding specified at the top. Making the string unicode (u''' ... ''') does not change anything. It could be an interpreter issue but I didn't know where else I should turn for help. Thank you! Jiri -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Python GUI development using XULRunner
On Sep 17, 5:53 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > On Sep 17, 1:21 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote: > >> Don Spaulding wrote: > >>> On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming > language. > The tutorial covers how to build a Python/XULRunner GUI > application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > >>> I get to the "Running" step and run into "Couldn't load XPCOM." > >>> Does this work on x86_64? Or have I made a rookie mistake? > >> Hi Don, > > >> A good question. Mozilla only provide 32-bit XulRunner applications by > >> default, you you'll need to install the necessary 32-bit compatability > >> libraries on your Linux machine, i.e. for Ubuntu it's something like: > >> sudo apt-get install ia32-libs ia32-libs-gtk > > >> Then you should be able to run the example. You can check the > >> dependencies using something the following commands, there should be no > >> missing dependencies: > >> $ cd pyxpcom_gui_app/xulrunner > >> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin > > >> It is possible to use a 64-bit version, but you'll need to compile this > >> yourself (or find somewhere that provides these x86_64 versions). Note > >> that the PythonExt project does not offer Python bindings for x86_64 > >> either (it's on my todo list), you can compile the PythonExt part > >> yourself as well if you need a 64-bit version. > > >> Cheers, > >> Todd > > > Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs > > and ia32-libs-gtk installed. > > > ldd shows that I'm missing the following libs, even though the proper > > packages are installed, and the files show up in /usr/lib. > > > libxcb-render-util.so.0 => not found > > libxcb-render.so.0 => not found > > > There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- > > util, so I wonder if that could be part of the problem? > > > Don > > Hi Don, > > I'm thinking there may be additional 32-bit packages necessary then (I'm > not sure which package). > > Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04 > x86_64 machine and my dependencies list the following for the latest > 32-bit build of XulRunner: > > $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb > libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000) > libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000) > > Cheers, > Todd No worries Todd, it is alpha. It was a very recent bug in the 8.10 ia32-libs package, which is now fixed :-D Thanks for the excellent writeup, BTW! I've been wondering what was involved in doing this for a while, it just never made it up my priority list to figure out. Again, thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
Simon Mullis napisał(a): > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. It seems to me that the "count" you're looking for is the number of elements from l whose first 3 characters are the same as the v[0:3] thing. So you may try: >>> dict_of_counts = dict((v[0:3], sum(1 for x in l if x[:3] == v[:3])) for v >>> in l) But this isn't particularly efficient. The 'canonical way' to construct such histograms/frequency counts in python is probably by using defaultdict: >>> dict_of_counts = collections.defaultdict(int) >>> for x in l: >>> dict_of_counts[x[:3]] += 1 Regards, Marek -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode in multi-line strings
Jiri Barton wrote: > Hello, > > I have a problem with international characters in multi-line strings. > > > Works: '''á''' > > Works: ''' > a''' > > Does not work: ''' > á''' > > > By does not work I mean the infamous > > 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not > in range(128) > > I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, > from scripts, or from scripts with the encoding specified at the top. > Making the string unicode (u''' ... ''') does not change anything. > > It could be an interpreter issue but I didn't know where else I should > turn for help. Please show a self-contained example that does not work. The above won't puke on you as you claim - because they are simple byte-strings, and thus aren't subject to any automatic en/decoding whatsoever, unless somehow *used*. Which you don't show how you do it. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Let's say I have an arbitrary list of minor software versions of an
> imaginary software product:
>
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> I'd like to create a dict with major_version : count.
>
> (So, in this case:
>
> dict_of_counts = { "1.1" : "1",
>"1.2" : "2",
>"1.3" : "2" }
>
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.
>
> I'm most probably not thinking pythonically enough... (I know I could
> do this pretty easily with a couple more lines, but I'd like to
> understand if there's a way to use a dict generator for this).
>
> Thanks in advance
>
> SM
>
> --
> Simon Mullis
3 lines:
from collections import defaultdict
dd=defaultdict(int)
for x in l: dd[x[0:3]]+=1
--
http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Let's say I have an arbitrary list of minor software versions of an
> imaginary software product:
>
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> I'd like to create a dict with major_version : count.
>
> (So, in this case:
>
> dict_of_counts = { "1.1" : "1",
>"1.2" : "2",
>"1.3" : "2" }
>
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.
>
> I'm most probably not thinking pythonically enough... (I know I could
> do this pretty easily with a couple more lines, but I'd like to
> understand if there's a way to use a dict generator for this).
Not everything has to be a one-liner; also v[0:3] is wrong if any sub-
version is greater than 9. Here's a standard idiom (in 2.5+ at least):
from collection import defaultdict
versions = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
major2count = defaultdict(int)
for v in versions:
major2count['.'.join(v.split('.',2)[:2])] += 1
print major2count
HTH,
George
--
http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
psyco might help a fair bit (10x-40x) here ;-> perhaps look at dumping the data into sqlite then pulling it back out. It (or the other databases) are designed for tossing around large lumps of data. Alexzive wrote: Hello there :) , I am a python newbie and need to run following code for a task in an external simulation programm called "Abaqus" which makes use of python to access the mesh (ensamble of nodes with xy coordinates) of a certain geometrical model. [IN is the starting input containing the nodes to be check, there are some double nodes with the same x and y coordinates which need to be removed. SN is the output containing such double nodes] Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) Unfortunately my len(IN) is about 100.000 and the running time about 15h :( Any idea to improve it? I have already tried to group the "if statements" in a single one: Code: Select all if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and if IN[i].coordinates[1] == IN[j].coordinates[1]: but no improvements. Many thanks, Alex -- http://mail.python.org/mailman/listinfo/python-list -- Vapour Forge Jake Anderson Project Manager Mobile: 0412 897 125 Email: [EMAIL PROTECTED] Web Page: www.vapourforge.com Your source for custom IT services -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
Simon Mullis wrote:
Hi,
Let's say I have an arbitrary list of minor software versions of an
imaginary software product:
l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
I'd like to create a dict with major_version : count.
(So, in this case:
dict_of_counts = { "1.1" : "1",
"1.2" : "2",
"1.3" : "2" }
[...]
data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
from itertools import groupby
datadict = \
dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
print datadict
--
http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Hi, Alexzive wrote: Hello there :) , I am a python newbie and need to run following code for a task in an external simulation programm called "Abaqus" which makes use of python to access the mesh (ensamble of nodes with xy coordinates) of a certain geometrical model. [IN is the starting input containing the nodes to be check, there are some double nodes with the same x and y coordinates which need to be removed. SN is the output containing such double nodes] Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) data=dict() for item in IN: # (what a name! ;) data.setdefault(item.coordinates,[]).append(item) # provided coordinates is a tuple dupes=[items for items in data.values() if len(items)>1] should give you a resulting list of lists of elements in IN which occur more then once per coordinates. You can then decide which ones to remove or whatever. If you want to have the output only containing nodes to remove, the following would work: dupes=[] for items in data.values(): dupes.extend(items[1:]) HTH Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Let's say I have an arbitrary list of minor software versions of an
> imaginary software product:
>
> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> I'd like to create a dict with major_version : count.
>
> (So, in this case:
>
> dict_of_counts = { "1.1" : "1",
>"1.2" : "2",
>"1.3" : "2" }
>
> Something like:
>
> dict_of_counts = dict([(v[0:3], "count") for v in l])
>
> I can't seem to figure out how to get "count", as I cannot do x += 1
> or x++ as x may or may not yet exist, and I haven't found a way to
> create default values.
>
> I'm most probably not thinking pythonically enough... (I know I could
> do this pretty easily with a couple more lines, but I'd like to
> understand if there's a way to use a dict generator for this).
>
> Thanks in advance
>
> SM
>
> --
> Simon Mullis
Considering 3 identical "simultpost" solutions I'd say:
"one obvious way to do it" FTW :-)
--
http://mail.python.org/mailman/listinfo/python-list
Installing pySerial
Hi All, Background === I have installed Python for windows today from the python web site .I also installed pySerial using the Windows installer from the sourceforge web site. Both installs use the default directories. Phyton version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 pySerial 2.4 July 6th Problem : Errors Screen output >>> import serial Traceback (most recent call last): File "", line 1, in import serial File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in from serialwin32 import * File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in import win32file # The base COM port and file IO functions. ImportError: No module named win32file >>> So it looks like Python can not see some of the modules Here's the active paths >>> print sys.path ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages'] >>> It seems that C:\Python25\Lib\site-packages\serial needs to be added to the PYTHONPATH QUESTION = Q1. How do I add C:\Python25\Lib\site-packages\serial to the PYTHONPATH ? Q2. How do I check that I have installed pySerial corretly (using the Windows installer) Thanks in advance Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
Tino Wildenhain wrote: Hi, Alexzive wrote: Hello there :) , I am a python newbie and need to run following code for a task in an external simulation programm called "Abaqus" which makes use of python to access the mesh (ensamble of nodes with xy coordinates) of a certain geometrical model. [IN is the starting input containing the nodes to be check, there are some double nodes with the same x and y coordinates which need to be removed. SN is the output containing such double nodes] Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) data=dict() for item in IN: # (what a name! ;) data.setdefault(item.coordinates,[]).append(item) # provided coordinates is a tuple dupes=[items for items in data.values() if len(items)>1] should give you a resulting list of lists of elements in IN which occur more then once per coordinates. You can then decide which ones to remove or whatever. If you want to have the output only containing nodes to remove, the following would work: dupes=[] for items in data.values(): dupes.extend(items[1:]) I did a small test - I don't know if it reflects the actual problem good enough but it seems it all runs below 1 sec each so this would be very fast compared to 15h: >>> import random >>> class Node(object): ... def __init__(self,x,y): ... self.coordinates=(x,y) >>> IN=[Node(random.randint(0,100),random.randint(0,100)) for i in xrange(10)] >>> data=dict() >>> for item in IN: data.setdefault(item.coordinates,[]).append(item) ... >>> dupes=[items for items in data.values() if len(items)>1] >>> len(dupes) 10190 >>> Cheers Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
On Sep 18, 11:43 am, Gerard flanagan <[EMAIL PROTECTED]> wrote:
> Simon Mullis wrote:
> > Hi,
>
> > Let's say I have an arbitrary list of minor software versions of an
> > imaginary software product:
>
> > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> > I'd like to create a dict with major_version : count.
>
> > (So, in this case:
>
> > dict_of_counts = { "1.1" : "1",
> >"1.2" : "2",
> >"1.3" : "2" }
>
> [...]
> data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>
> from itertools import groupby
>
> datadict = \
>dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3]))
> print datadict
Note that this works correctly only if the versions are already sorted
by major version.
George
--
http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
Haha!
Thanks for all of the suggestions... (I love this list!)
SM
2008/9/18 <[EMAIL PROTECTED]>:
> On Sep 18, 10:54 am, "Simon Mullis" <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> Let's say I have an arbitrary list of minor software versions of an
>> imaginary software product:
>>
>> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"]
>>
>> I'd like to create a dict with major_version : count.
>>
>> (So, in this case:
>>
>> dict_of_counts = { "1.1" : "1",
>>"1.2" : "2",
>>"1.3" : "2" }
>>
>> Something like:
>>
>> dict_of_counts = dict([(v[0:3], "count") for v in l])
>>
>> I can't seem to figure out how to get "count", as I cannot do x += 1
>> or x++ as x may or may not yet exist, and I haven't found a way to
>> create default values.
>>
>> I'm most probably not thinking pythonically enough... (I know I could
>> do this pretty easily with a couple more lines, but I'd like to
>> understand if there's a way to use a dict generator for this).
>>
>> Thanks in advance
>>
>> SM
>>
>> --
>> Simon Mullis
>
> Considering 3 identical "simultpost" solutions I'd say:
> "one obvious way to do it" FTW :-)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
Simon Mullis
_
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
ANN: Wing IDE for Python v. 3.1.4 released
Hi, Wingware has released version 3.1.4 of Wing IDE. This bug fix release is available for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Debugger support for Python 2.6 * Support zope buildout directories not named "instance" * Added highlighted keywords for caml, d, escript, lisp, ps, and yaml files * Don't display message that save is unavailable before running pylint * VI mode fix: After / de-select the search match once Enter is pressed * About 20 other bug fixes: see the change log for details http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.4 http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.4http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.4 http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license:https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing pySerial
Joe G (Home) wrote: Hi All, Background === I have installed Python for windows today from the python web site .I also installed pySerial using the Windows installer from the sourceforge web site. Both installs use the default directories. Phyton version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 pySerial 2.4 July 6th Problem : Errors Screen output import serial Traceback (most recent call last): File "", line 1, in import serial File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in from serialwin32 import * File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in import win32file # The base COM port and file IO functions. ImportError: No module named win32file You need to install the pywin32 extensions from: http://pywin32.sf.net They're so commonly used (and, if you install the ActiveState distro of Python, even bundled) that I imagine many Windows Pythoneers like myself simply install them automatically as soon as we've installed the main python.org Python. Once you've done that, the rest should just work: it's clear from the traceback that the serial module is getting imported; it's just trying to find the win32file module. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing pySerial
"Joe G (Home)" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I have installed Python for windows today from the python web site .I also > installed > pySerial using the Windows installer from the sourceforge web site. You need to read the pySerial smallprint, where it says: "The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (pywin32) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)" -- http://mail.python.org/mailman/listinfo/python-list
Automated Build System ?
Hi, I'm working on a python Package which includes some extension modules and unit tests. I want to automate some tasks like "build extsion module, then copy xxx.pyd to folder yyy and run all unit tests from folder ". I used google but found no hints to existing solutions. Can anybody help me ? Greetings, Uwe -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
While we're making suggestions, I've always wished that the --help output displayed the default values for options in addition to the help text specified by the user. I end up having to enter the default values twice -- once as a keyword argument and again in the help text. Then later when I decide to change the default value, things get out-of-sync. -- Grant Edwards grante Yow! Did you move a lot of at KOREAN STEAK KNIVES this visi.comtrip, Dingy? -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Bold Text
Is there any way to highlight, bold or change the color of one word in a variable to be displayed on a Tkinter GUI? Like: material = "Plastic" introVal = "This report describes the construction of the %s." % (material) this is what I want: This report describes the construction of the Plastic. Plastic is Bold or Blue or Green Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing pySerial
On 2008-09-18, Joe G (Home) <[EMAIL PROTECTED]> wrote: > Hi All, > > Background >=== > I have installed Python for windows today from the python web site .I also > installed pySerial using the Windows installer from the sourceforge web > site. Both installs use the default directories. > > Phyton version: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > pySerial 2.4 July 6th > > > Problem : Errors Screen output > import serial > > Traceback (most recent call last): > File "", line 1, in > import serial > File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > > from serialwin32 import * > File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > > import win32file # The base COM port and file IO functions. > ImportError: No module named win32file > > So it looks like Python can not see some of the modules Do you have the win32 modules installed? > Here's the active paths > print sys.path > ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', > 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', > 'C:\\Python25\\lib\\site-packages'] > > It seems that C:\Python25\Lib\site-packages\serial needs to be added to > the PYTHONPATH I don't see how you came to that conclusion. Is the "missing" module (win32file) located in C:\Python25\Lib\site-packages\serial? > QUESTION >= > Q1. How do I add C:\Python25\Lib\site-packages\serial to the PYTHONPATH ? Dunno. > Q2. How do I check that I have installed pySerial corretly > (using the Windows installer) If you used the installer, you almost undoubtedly have it installed correctly. I think you're missing the win32 package. http://python.net/crew/mhammond/win32/Downloads.html -- Grant Edwards grante Yow! I'm not an Iranian!! at I voted for Dianne visi.comFeinstein!! -- http://mail.python.org/mailman/listinfo/python-list
Re: locks
yea... sorry... i just have all python stuff in the same folder and messed up... [EMAIL PROTECTED] wrote: kalin> mailman has been locking one list out. the web interface just kalin> hangs and it generates a bunch of locks. it seems that it can not kalin> write to a log but not sure which one. errors are like: ... You'd probably be better off asking about Mailman problems on [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
Grant Edwards wrote: While we're making suggestions, I've always wished that the --help output displayed the default values for options in addition to the help text specified by the user. I end up having to enter the default values twice -- once as a keyword argument and again in the help text. Then later when I decide to change the default value, things get out-of-sync. Tangential to this thread, what's the preferred way to get changes into optparse? Based on the comments I've read in the optparse.py file, it looks like it's the generated output of some other process. I've patched my local version to include some changes for handling newlines in help text (which has cropped up on the list occasionally, as the current version eats newlines), but am not sure whether I need to be patching against the optparse.py or against the file that generated it (which I don't have in my install, AFAIK). Perhaps one of the core devs that works on optparse could tell me how they'd prefer such changes submitted? Thanks, -tkc -- http://mail.python.org/mailman/listinfo/python-list
TCP Server
Dear List, I am looking to write a TCP socket server and was wondering what are the pros and cons of using twisted over the sockets modules bundled in python? Thanks James -- http://www.goldwatches.com/ -- http://mail.python.org/mailman/listinfo/python-list
Out of memory issue with dialog box
Hi, We have a mutilthreaded process in which one of the threads uses too much memory causing the process to run out of memory. However when this happens we see a dialog box pop up with the message "fatal error in GC : too many heap sections." When you click "ok" only then does the process die. Is there a way for the process to crash directly without going through the dialog box. Any help would be appreciated? -- http://mail.python.org/mailman/listinfo/python-list
Re: Cython dynamic library problem
Tommy Grav <[EMAIL PROTECTED]> writes:
> I am trying to learn how to use cython, and while I am following the
> cython-dev
> mailing list I didn't feel like this question was totally appropriate
> for its audience
> so I am trying here first.
[...]
> Does anyone know what the ImportError means and how to correct it?
I would try to use `distutils` because this package is much wiser
than me and knows all necessary switches for gcc. ;)
# test_cython.pyx
def test(x):
return x * x
# test_cython.py
from pyx_test import test
print test(0)
print test(10)
# setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext as build_pyx
setup(name = 'pyx_test',
ext_modules=[Extension('pyx_test', ['test_cython.pyx'])],
cmdclass = { 'build_ext': build_pyx })
$ python2.5 setup.py build_ext -i
running build_ext
cythoning test_cython.pyx to test_cython.c
building 'pyx_test' extension
creating build/temp.linux-i686-2.5
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes
-fPIC -I/usr/include/python2.5 -c test_cython.c -o
build/temp.linux-i686-2.5/test_cython.o
test_cython.c:86: warning: function declaration isn’t a prototype
test_cython.c:241: warning: function declaration isn’t a prototype
test_cython.c:59: warning: ‘__pyx_skip_dispatch’ defined but not used
gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o
pyx_test.so
$ python2.5 test_cython.py
0
100
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Blanket font setting?
I'm doing an app with the AUI manager capabilities (using some of the wxPython demo's for help). All is well, except I'm a bit disappointed with the font management. The default font for all the widgets (TextCtrl's, StaticText's etc) are a bit large for my design intent and as I try to adjust that, it appears I have to do a font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) Then, for every texty thing: myTextThing.setfont(font) someOtherThing.setfont(font) Thus if I have hundreds of texty things, I've got to assign that hundreds of times. Is there any sort of blanket font setting, perhaps like: wx.SystemSettings_SetFont(font) #this doesn't exist that could set everything with one fell swoop? Thanks for your attention... Ross. -- http://mail.python.org/mailman/listinfo/python-list
Extracting hte font name from a TrueType font file
Does anyone have a Python recipe for this? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote: > While we're making suggestions, I've always wished that the --help > output displayed the default values for options in addition to the help > text specified by the user. I end up having to enter the default values > twice -- once as a keyword argument and again in the help text. '%default' in the help text will be replaced by the default value. See the last option in the first example here: http://docs.python.org/lib/optparse-generating-help.html Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Cython dynamic library problem
Rob Wolfe:
> # setup.py
> from distutils.core import setup
> from distutils.extension import Extension
> from Cython.Distutils import build_ext as build_pyx
>
> setup(name = 'pyx_test',
> ext_modules=[Extension('pyx_test', ['test_cython.pyx'])],
> cmdclass = { 'build_ext': build_pyx })
>
> $ python2.5 setup.py build_ext -i
> running build_ext
> cythoning test_cython.pyx to test_cython.c
> building 'pyx_test' extension
> creating build/temp.linux-i686-2.5
> gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes
> -fPIC -I/usr/include/python2.5 -c test_cython.c -o
> build/temp.linux-i686-2.5/test_cython.o
> test_cython.c:86: warning: function declaration isn’t a prototype
> test_cython.c:241: warning: function declaration isn’t a prototype
> test_cython.c:59: warning: ‘__pyx_skip_dispatch’ defined but not used
> gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o
> pyx_test.so
> $ python2.5 test_cython.py
> 0
> 100
With some intelligence added to Cython, probably there are ways to
reduce all this, and most of the times avoid any setup.py module too.
Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list
Re: append on lists
[EMAIL PROTECTED] wrote: > On Sep 16, 6:03 am, Peter Anderson <[EMAIL PROTECTED]> > wrote: >> "/... I don't think you've thought this one through, really./" >> snip >> >> We ought to try and be a little kinder to others on the list, don't you >> think? :-) >> >> snip > > Well said! >From personal experience I find that honest attempts to straighten people out lead to accusations of exploiting "seniority" to attack people. There goes the neighborhood, I guess. Of course we should try to maintain c.l.py's deserved reputation for civil behavior, but things like that aren't easy to police. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Bold Text
Is there any way to highlight, bold or change the color of one word in a variable to be displayed on a Tkinter GUI? Like: material = "Plastic" introVal = "This report describes the construction of the %s." % (material) this is what I want: This report describes the construction of the Plastic. Plastic is Bold or Blue or Green Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Bold Text
On Thu, Sep 18, 2008 at 1:06 PM, April Lekin <[EMAIL PROTECTED]> wrote: > Is there any way to highlight, bold or change the color of one word in a > variable to be displayed on a Tkinter GUI? Yes. > > Like: > > material = "Plastic" > introVal = "This report describes the construction of the %s." % (material) > You could separate them in two labels (if you are using labels), or apply a different tag if you are using a Text widget. > this is what I want: > This report describes the construction of the Plastic. > Plastic is Bold or Blue or Green > Changing the color is easier, you only change the foreground option. Changing to bold may not work for you, because depending on your Tk version and platform it will already be bold, so you won't notice anything. There is also a "catch" in changing text to bold, if you only set the text option of your Label to "-weight bold" it will probably get you a bold text, but with a different font than the one being used by other Labels. Now, something you could use as a base: import Tkinter import tkFont root = Tkinter.Tk() otherpart = Tkinter.Label(text="some text here") special = Tkinter.Label(text="special", foreground='blue') otherpart.pack(side='left') special.pack(side='left') f = tkFont.Font(font=otherpart['font']) f['weight'] = 'bold' f['underline'] = True special['font'] = f.name root.mainloop() > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
Re: Zsi interoperability
Mailing List SVR <[EMAIL PROTECTED]> writes on Tue, 16 Sep 2008 08:31:13 +0200: > ... > however my server require client > certificate authentication, > > does soaplib or zsi work in this environment? ZSI allows you to provide an alternative transport. That's the usual way to let ZSI work over "https" rather than "http". I do not know whether Python supports a client certificate authentication transport out of the box -- but at least the problem is split into two easier parts. Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: Zsi interoperability
"Marco Bizzarri" <[EMAIL PROTECTED]> writes on Mon, 15 Sep 2008 20:26:27 +0200: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <[EMAIL PROTECTED]> wrote: > > Mailing List SVR wrote: > >> I have to implement a soap web services from wsdl, the server is > >> developed using oracle, is zsi or some other python library for soap > >> interoperable with oracle soa? > > > > No idea, but I'd definitely try soaplib before ZSI. > > > > Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it The ZSI documentation (2.0) says that SOAP attachments are supported -- but I never tried it. Dieter -- http://mail.python.org/mailman/listinfo/python-list
Re: Cython dynamic library problem
On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote: I would try to use `distutils` because this package is much wiser than me and knows all necessary switches for gcc. ;) That worked! Thanks Cheers Tommy -- http://mail.python.org/mailman/listinfo/python-list
Re: append on lists
Armin wrote: > Duncan Booth wrote: >> "Chris Rebert" <[EMAIL PROTECTED]> wrote: >>> On Tue, Sep 16, 2008 at 1:20 AM, Armin <[EMAIL PROTECTED]> wrote: [1,2,3,4,7].append(c) -> Is this a valid expression? >>> Literally, no, because you can't call methods on literals. >> >> Rubbish. There is no restriction about calling methods on literals. >> That expression is perfectly valid but has no practical use that I can >> see. > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, but the first expression doesn't provide > a value. Strange by design ... > Have a care, there. The semantics are different. lst = [1, 2, 3, 4, 7] lst.append([8, 9]) makes lst [1, 2, 3, 4, 7, [8, 9]] whereas lst = [1, 2, 3, 4, 7] lst = lst + [8, 9] makes lst [1, 2, 3, 4, 5, 7, 8, 9] I suspect you meant [1, 2, 3, 4, 5, 7] + [c] regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
On Sep 18, 11:18 am, [EMAIL PROTECTED] wrote: > dup=set() > SN=[] > for item in IN: > c=item.coordinates[0], item.coordinates[1] > if c in dup: > SN.append(item.label) > else: > dup.add(c) +1 for O(N) If item.coordinates is just an (x, y) pair, you can skip building c and save a little memory: seen_coords = set() for node in IN: if node.coordinates in seen_coords: SN.append(node.label) else: seen_coords.add(node.coordinates) seen_coords gets populated with references to the existing node.coordinates objects, instead of new tuples. Geoff G-T -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Determine Name of the Day in the Week
On Sep 18, 12:01 am, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote:
> > And technically, weeks begin on Sunday, not Monday, but business likes
> > to think of Monday as day 0 of the week and it doesn't conflict with any
> > prior date format.
>
> There's no "technically" about it.
Sure there is, within the tradition I was refering to.
Within that tradition, the start of the week isn't arbitray.
Besides, the documentation specifically says it's using
the European system
By default, these calendars have Monday as the first day
of the week, and Sunday as the last (the European convention).
Use setfirstweekday() to set the first day of the week to
Sunday (6) or to any other weekday.
So, by default, Python doesn't use the American convention
of weeks starting on Sunday (an American technicality).
This does not contradict what I said.
> It's an arbitrary starting point,
Amongst different systems, it's never arbitrary within a system.
> and
> consequently there are different traditions to it, even in English.
I know, that's why I added the caveat.
>
> Besides, I don't think many businesses think of "day 0" at all. Most
> people outside of IT start counting from 1, not 0.
The accounting software I use to fill out my timesheet
electronically was obviously created by IT people and
the week begins on Monday. Their will is, of course,
forced on all employees whether they are IT or not.
>
> In British Commonwealth countries, Sunday is the last day of the week,
> not the first, although under American influence that's changing in
> Australia at least.
>
> In Poland, the week begins with Monday ("poniedziałek"). Tuesday,
> "wtorek", means "second day". Other Slavic countries also start with
> Monday.
>
> Similarly, the Lithuanian calendar simple enumerates the days of the
> week, starting with Monday, "pirmadienis" ("first day").
>
> In China, there are at least three different systems of naming the week
> days. In two of them, the week starts with Sunday, but in the third
> system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first
> of cycle").
Last time I was in Borders, I don't recall seeing any
Polish, Lithuanian or Chinese calendars for sale.
>
> --
> Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Zsi interoperability
On Thu, Sep 18, 2008 at 7:10 PM, Dieter Maurer <[EMAIL PROTECTED]> wrote: > "Marco Bizzarri" <[EMAIL PROTECTED]> writes on Mon, 15 Sep 2008 20:26:27 > +0200: >> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <[EMAIL PROTECTED]> wrote: >> > Mailing List SVR wrote: >> >> I have to implement a soap web services from wsdl, the server is >> >> developed using oracle, is zsi or some other python library for soap >> >> interoperable with oracle soa? >> > >> > No idea, but I'd definitely try soaplib before ZSI. >> > >> > Stefan >> >> I'm working on a project where I need to write a client for SOAP with >> Attachments; I can see ZSI does not support it > > The ZSI documentation (2.0) says that SOAP attachments are supported -- > but I never tried it. > > > Dieter > -- > http://mail.python.org/mailman/listinfo/python-list > That's right; but if you look at the code, it seems like it is able to create a server which behaves in that way, but not to create a client for it. But I'm still exploring... -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP proposal optparse
On 2008-09-18, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote: > >> While we're making suggestions, I've always wished that the --help >> output displayed the default values for options in addition to the help >> text specified by the user. I end up having to enter the default values >> twice -- once as a keyword argument and again in the help text. > > '%default' in the help text will be replaced by the default value. See > the last option in the first example here: > > http://docs.python.org/lib/optparse-generating-help.html Great! I guess I should scan the doc pages for changes more often. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Extracting hte font name from a TrueType font file
> -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] g] On Behalf Of Steve Holden > Sent: Thursday, September 18, 2008 5:59 PM > To: [email protected] > Subject: Extracting hte font name from a TrueType font file > > Does anyone have a Python recipe for this? > > regards > Steve > -- > Steve Holden+1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > Can't help with a recipe, but here's the formal spec if want to figure it out yourself. http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6.html Hope that helps. Cheers, Drea -- http://mail.python.org/mailman/listinfo/python-list
PyCon 2009 (US) - Call for Tutorials
*Pycon 2009 (US) – Call for Tutorials* The period for submitting tutorial proposals for Pycon 2009 (US) is now open and will continue through Friday, October 31th. This year features two "pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday March 26 in Chicago. This allows for more classes than ever. Tutorials are 3-hours long on a specific topic of your choice. Last year we featured classes on Learning Python, Web Development, Scientific Computing, and many more. Class size varied from 10 to over 60 students. The extended time spent in class allows teachers to cover a lot of material while allowing for interaction with students. The full Call for Tutorial Proposals, including submission details, an example proposal as well as a template, is available at < http://us.pycon.org/2009/tutorials/proposals/>. Tutorial selections will be announced in early December to give you time to prepare your class. PyCon will compensate instructors US$1,500 per tutorial. If you have any questions, please contact [EMAIL PROTECTED] Greg Lindstrom Tutorial Coordinator, PyCon 2009 -- http://mail.python.org/mailman/listinfo/python-list
Re: Cython dynamic library problem
On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote: I would try to use `distutils` because this package is much wiser than me and knows all necessary switches for gcc. ;) That worked! Thanks Cheers Tommy -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
On Thu, 18 Sep 2008 Alexzive wrote: >I am a python newbie and need to run following code for a task in an >external simulation programm called "Abaqus" which makes use of python >to access the mesh (ensamble of nodes with xy coordinates) of a >certain geometrical model. > >[IN is the starting input containing the nodes to be check, there are >some double nodes with the same x and y coordinates which need to be >removed. SN is the output containing such double nodes] > >Code: Select all >for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): >if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) I did not test the syntax, but here is an idea with sorted lists. It should be O(NlogN). def sk(x): return x.coordinates[0] IN.sort(key=sk) for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) else: break Harald -- http://mail.python.org/mailman/listinfo/python-list
