content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Communicating to server with queries through stream. What is the right way? I'm writing my first network application. It manipulates jabber client and communicates with some service with IQ-stanzas. But details are not important. This interaction works through twisted xmlstream (python language). Typical situations are described here: http://juick.com/help/api/xmpp/ To be short, I can send a "query" and server relies me with "result". I implemented some basic actions like "send message", "do action on message received". The problem is in operating with stream. Is it better to use deferreds to request any data from server? And how to return the result to the place where it is needed? You can look through my code here: http://bitbucket.org/boh/tmp/src/56c131cd1e62/juick_app/twisted_app.py I tried to make it minimalistic. A: To pair a response with a reply, you use the iq.id attribute. You can store a few deferreds in a cache indexed by id and run them when they get a reply. Since XMPP is TCP-based, you will mostly get replies in the right order anyway. You can cap the cache and run the deferred's errback if the deferred has been in the cache for a while.
Communicating to server with queries through stream. What is the right way?
I'm writing my first network application. It manipulates jabber client and communicates with some service with IQ-stanzas. But details are not important. This interaction works through twisted xmlstream (python language). Typical situations are described here: http://juick.com/help/api/xmpp/ To be short, I can send a "query" and server relies me with "result". I implemented some basic actions like "send message", "do action on message received". The problem is in operating with stream. Is it better to use deferreds to request any data from server? And how to return the result to the place where it is needed? You can look through my code here: http://bitbucket.org/boh/tmp/src/56c131cd1e62/juick_app/twisted_app.py I tried to make it minimalistic.
[ "To pair a response with a reply, you use the iq.id attribute. You can store a few deferreds in a cache indexed by id and run them when they get a reply. Since XMPP is TCP-based, you will mostly get replies in the right order anyway. You can cap the cache and run the deferred's errback if the deferred has been in the cache for a while.\n" ]
[ 0 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0002128545_networking_python_twisted.txt
Q: Python: Optimizing, or at least getting fresh ideas for a tree generator I have written a program that generates random expressions and then uses genetic techniques to select for fitness. The following part of the program generates the random expression and stores it in a tree structure. As this can get called billions of times during a run, I thought it should be optimized for time. I'm new to programming and I work (play) by myself so, as much as I search on the inernet for ideas, I'd like some input as I feel like I'm doing this in isolation. The bottlenecks seem to be Node.init (), (22% of total time) and random.choice(), (14% of total time) import random def printTreeIndented(data, level=0): '''utility to view the tree ''' if data == None: return printTreeIndented(data.right, level+1) print ' '*level + ' '+ str(data.cargo)#+ ' '+ str(data.seq)+ ' '+ str(data.branch) printTreeIndented(data.left, level+1) #These are the global constants used in the Tree.build_nodes() method. Depth = 5 Ratio = .6 #probability of terminating the current branch. Atoms = ['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] #dict of operators. the structure is: operator: number of arguements Operators = {'+': 2, '-': 2, '*': 2, '/': 2, '**': 2} class KeySeq: '''Iterator to produce sequential integers for keys in Tree.thedict ''' def __init__(self, data = 0): self.data = data def __iter__(self): return self def next(self): self.data = self.data + 1 return self.data KS = KeySeq() class Node(object): ''' ''' def __init__(self, cargo, left=None, right=None): object.__init__(self) self.isRoot = False self.cargo = cargo self.left = left self.right = right self.parent = None self.branch = None self.seq = 0 class Tree(object): def __init__(self): self.thedict = {} #provides access to the nodes for further mutation and # crossbreeding. #When the Tree is instantiated, it comes filled with data. self.data = self.build_nodes() # Uncomment the following lines to see the data and a crude graphic of the tree. # print 'data: ' # for v in self.thedict.itervalues(): # print v.cargo, # print # print # printTreeIndented(self.data) def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): ''' ''' r = float() r = random.random() #If r > Ratio, it forces a terminal node regardless of #the value of depth. #If entry = 1, then it's the root node and we don't want # a tree with just a value in the root node. if (depth <= 0) or ((r > Ratio) and (not (entry))): ''' Add a terminal node. ''' this_atom = (random.choice(Atoms)) this_atom = str(this_atom) this_node = Node(this_atom) this_node.parent = pparent this_node.branch = bbranch this_node.seq = KS.next() self.thedict[this_node.seq] = this_node return this_node else: ''' Add a node that has branches. ''' this_operator = (random.choice(Operators.keys())) this_node = Node(this_operator) if entry: this_node.isRoot = True this_node.parent = pparent this_node.branch = bbranch this_node.seq = KS.next() self.thedict[this_node.seq] = this_node #branch as many times as 'number of arguements' # it's only set up for 2 arguements now. for i in range(Operators[this_operator]): depth =(depth - 1) if i == 0: this_node.left = (self.build_nodes(entry = 0, depth =(depth), pparent = this_node, bbranch = 'left')) else: this_node.right = (self.build_nodes(entry = 0, depth =(depth), pparent = this_node, bbranch = 'right')) return this_node def Main(): for i in range(100000): t = Tree() return t if __name__ == '__main__': rresult = Main() A: Below, I've summarized some of the more obvious optimization efforts, without really touching the algorithm much. All timings are done with Python 2.6.4 on a Linux x86-64 system. Initial time: 8.3s Low-Hanging Fruits jellybean already pointed some out. Just fixing those already improves the runtime a little bit. Replacing the repeated calls to Operators.keys() by using the same list again and again also saves some time. Time: 6.6s Using itertools.count Pointed out by Dave Kirby, simply using itertools.count also saves you some time: from itertools import count KS = count() Time: 6.2s Improving the Constructor Since you're not setting all attributes of Node in the ctor, you can just move the attribute declarations into the class body: class Node(object): isRoot = False left = None right = None parent = None branch = None seq = 0 def __init__(self, cargo): self.cargo = cargo This does not change the semantics of the class as far as you're concerned, since all values used in the class body are immutable (False, None, 0), if you need other values, read this answer on class attributes first. Time: 5.2s Using namedtuple In your code, you're not changing the expression tree any more, so you might as well use an object that is immutable. Node also does not have any behavior, so using a namedtuple is a good option. This does have an implication though, since the parent member had to be dropped for now. Judging from the fact that you might introduce operators with more than two arguments, you would have to replace left/right with a list of children anyway, which is mutable again and would allow creating the parent node before all the children. from collections import namedtuple Node = namedtuple("Node", ["cargo", "left", "right", "branch", "seq", "isRoot"]) # ... def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): r = random.random() if (depth <= 0) or ((r > Ratio) and (not (entry))): this_node = Node( random.choice(Atoms), None, None, bbranch, KS.next(), False) self.thedict[this_node.seq] = this_node return this_node else: this_operator = random.choice(OpKeys) this_node = Node( this_operator, self.build_nodes(entry = 0, depth = depth - 1, pparent = None, bbranch = 'left'), self.build_nodes(entry = 0, depth = depth - 2, pparent = None, bbranch = 'right'), bbranch, KS.next(), bool(entry)) self.thedict[this_node.seq] = this_node return this_node I've kept the original behavior of the operand loop, that decrements the depth at each iteration. I'm not sure this is wanted behavior, but changing it increases runtime and therefore makes comparison impossible. Final time: 4.1s Where to go from here If you want to have support for more than two operators and/or support for the parent attribute, use something along the lines of the following code: from collections import namedtuple Node = namedtuple("Node", ["cargo", "args", "parent", "branch", "seq", "isRoot"]) def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): r = random.random() if (depth <= 0) or ((r > Ratio) and (not (entry))): this_node = Node( random.choice(Atoms), None, pparent, bbranch, KS.next(), False) self.thedict[this_node.seq] = this_node return this_node else: this_operator = random.choice(OpKeys) this_node = Node( this_operator, [], pparent, bbranch, KS.next(), bool(entry)) this_node.args.extend( self.build_nodes(entry = 0, depth = depth - (i + 1), pparent = this_node, bbranch = i) for i in range(Operators[this_operator])) self.thedict[this_node.seq] = this_node return this_node This code also decreases the depth with the operator position. A: You can omit lots of braces in your code, that's one of Python's benefits. E.g. when putting braces around conditions, like if (depth <= 0) or ((r > Ratio) and (not (entry))): just write if depth <= 0 or (r > Ratio and not entry): And I think there are a couple of redundant calls, e.g. this_atom = str(this_atom) (this_atom will already be a string, and building strings is always expensive, so just omit this line) or the call to the object constructor object.__init__(self) which isn't necessary, either. As for the Node.__init__ method being the "bottleneck": I guess spending most of your time there cannot be avoided, since when constructing trees like this there's not much else you'll be doing but creating new Nodes. A: You can replace the KeySeq generator with itertools.count which does exactly the same thing but is implemented in C. I don't see any way of speeding up the Node constructor. The call to random.choice you could optimise by inlining the code - cut & paste it from the source for the random module. This will eliminate a function call, which are relatively expensive in Python. You could speed it up by running under psyco, which is a kind of JIT optimiser. However this only works for 32 bit Intel builds of Python. Alternatively you could use cython - this converts python(ish) code into C, which can be compiled into a Python C module. I say pythonish since there some things that cannot be converted, and you can add C data type annotations to make the generated code more efficient.
Python: Optimizing, or at least getting fresh ideas for a tree generator
I have written a program that generates random expressions and then uses genetic techniques to select for fitness. The following part of the program generates the random expression and stores it in a tree structure. As this can get called billions of times during a run, I thought it should be optimized for time. I'm new to programming and I work (play) by myself so, as much as I search on the inernet for ideas, I'd like some input as I feel like I'm doing this in isolation. The bottlenecks seem to be Node.init (), (22% of total time) and random.choice(), (14% of total time) import random def printTreeIndented(data, level=0): '''utility to view the tree ''' if data == None: return printTreeIndented(data.right, level+1) print ' '*level + ' '+ str(data.cargo)#+ ' '+ str(data.seq)+ ' '+ str(data.branch) printTreeIndented(data.left, level+1) #These are the global constants used in the Tree.build_nodes() method. Depth = 5 Ratio = .6 #probability of terminating the current branch. Atoms = ['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] #dict of operators. the structure is: operator: number of arguements Operators = {'+': 2, '-': 2, '*': 2, '/': 2, '**': 2} class KeySeq: '''Iterator to produce sequential integers for keys in Tree.thedict ''' def __init__(self, data = 0): self.data = data def __iter__(self): return self def next(self): self.data = self.data + 1 return self.data KS = KeySeq() class Node(object): ''' ''' def __init__(self, cargo, left=None, right=None): object.__init__(self) self.isRoot = False self.cargo = cargo self.left = left self.right = right self.parent = None self.branch = None self.seq = 0 class Tree(object): def __init__(self): self.thedict = {} #provides access to the nodes for further mutation and # crossbreeding. #When the Tree is instantiated, it comes filled with data. self.data = self.build_nodes() # Uncomment the following lines to see the data and a crude graphic of the tree. # print 'data: ' # for v in self.thedict.itervalues(): # print v.cargo, # print # print # printTreeIndented(self.data) def build_nodes (self, depth = Depth, entry = 1, pparent = None, bbranch = None): ''' ''' r = float() r = random.random() #If r > Ratio, it forces a terminal node regardless of #the value of depth. #If entry = 1, then it's the root node and we don't want # a tree with just a value in the root node. if (depth <= 0) or ((r > Ratio) and (not (entry))): ''' Add a terminal node. ''' this_atom = (random.choice(Atoms)) this_atom = str(this_atom) this_node = Node(this_atom) this_node.parent = pparent this_node.branch = bbranch this_node.seq = KS.next() self.thedict[this_node.seq] = this_node return this_node else: ''' Add a node that has branches. ''' this_operator = (random.choice(Operators.keys())) this_node = Node(this_operator) if entry: this_node.isRoot = True this_node.parent = pparent this_node.branch = bbranch this_node.seq = KS.next() self.thedict[this_node.seq] = this_node #branch as many times as 'number of arguements' # it's only set up for 2 arguements now. for i in range(Operators[this_operator]): depth =(depth - 1) if i == 0: this_node.left = (self.build_nodes(entry = 0, depth =(depth), pparent = this_node, bbranch = 'left')) else: this_node.right = (self.build_nodes(entry = 0, depth =(depth), pparent = this_node, bbranch = 'right')) return this_node def Main(): for i in range(100000): t = Tree() return t if __name__ == '__main__': rresult = Main()
[ "Below, I've summarized some of the more obvious optimization efforts, without really touching the algorithm much. All timings are done with Python 2.6.4 on a Linux x86-64 system.\nInitial time: 8.3s\nLow-Hanging Fruits\njellybean already pointed some out. Just fixing those already improves the runtime a little bit. Replacing the repeated calls to Operators.keys() by using the same list again and again also saves some time.\nTime: 6.6s\nUsing itertools.count\nPointed out by Dave Kirby, simply using itertools.count also saves you some time:\nfrom itertools import count\nKS = count()\n\nTime: 6.2s\nImproving the Constructor\nSince you're not setting all attributes of Node in the ctor, you can just move the attribute declarations into the class body:\nclass Node(object):\n isRoot = False\n left = None\n right = None\n parent = None\n branch = None\n seq = 0\n\n def __init__(self, cargo):\n self.cargo = cargo\n\nThis does not change the semantics of the class as far as you're concerned, since all values used in the class body are immutable (False, None, 0), if you need other values, read this answer on class attributes first.\nTime: 5.2s\nUsing namedtuple\nIn your code, you're not changing the expression tree any more, so you might as well use an object that is immutable. Node also does not have any behavior, so using a namedtuple is a good option. This does have an implication though, since the parent member had to be dropped for now. Judging from the fact that you might introduce operators with more than two arguments, you would have to replace left/right with a list of children anyway, which is mutable again and would allow creating the parent node before all the children.\nfrom collections import namedtuple\nNode = namedtuple(\"Node\", [\"cargo\", \"left\", \"right\", \"branch\", \"seq\", \"isRoot\"])\n# ...\n def build_nodes (self, depth = Depth, entry = 1, pparent = None,\n bbranch = None):\n r = random.random()\n\n if (depth <= 0) or ((r > Ratio) and (not (entry))):\n this_node = Node(\n random.choice(Atoms), None, None, bbranch, KS.next(), False)\n self.thedict[this_node.seq] = this_node\n return this_node\n\n else:\n this_operator = random.choice(OpKeys)\n\n this_node = Node(\n this_operator,\n self.build_nodes(entry = 0, depth = depth - 1,\n pparent = None, bbranch = 'left'),\n self.build_nodes(entry = 0, depth = depth - 2,\n pparent = None, bbranch = 'right'),\n bbranch, \n KS.next(), \n bool(entry))\n\n self.thedict[this_node.seq] = this_node \n return this_node\n\nI've kept the original behavior of the operand loop, that decrements the depth at each iteration. I'm not sure this is wanted behavior, but changing it increases runtime and therefore makes comparison impossible.\nFinal time: 4.1s\nWhere to go from here\nIf you want to have support for more than two operators and/or support for the parent attribute, use something along the lines of the following code:\nfrom collections import namedtuple\nNode = namedtuple(\"Node\", [\"cargo\", \"args\", \"parent\", \"branch\", \"seq\", \"isRoot\"])\n\n def build_nodes (self, depth = Depth, entry = 1, pparent = None,\n bbranch = None):\n r = random.random()\n\n if (depth <= 0) or ((r > Ratio) and (not (entry))):\n this_node = Node(\n random.choice(Atoms), None, pparent, bbranch, KS.next(), False)\n self.thedict[this_node.seq] = this_node\n return this_node\n\n else:\n this_operator = random.choice(OpKeys)\n\n this_node = Node(\n this_operator, [], pparent, bbranch,\n KS.next(), bool(entry))\n this_node.args.extend(\n self.build_nodes(entry = 0, depth = depth - (i + 1),\n pparent = this_node, bbranch = i)\n for i in range(Operators[this_operator]))\n\n self.thedict[this_node.seq] = this_node \n return this_node\n\nThis code also decreases the depth with the operator position.\n", "You can omit lots of braces in your code, that's one of Python's benefits. E.g. when putting braces around conditions, like\nif (depth <= 0) or ((r > Ratio) and (not (entry))):\n\njust write\nif depth <= 0 or (r > Ratio and not entry):\n\nAnd I think there are a couple of redundant calls, e.g.\nthis_atom = str(this_atom)\n\n(this_atom will already be a string, and building strings is always expensive, so just omit this line)\nor the call to the object constructor\nobject.__init__(self)\n\nwhich isn't necessary, either.\nAs for the Node.__init__ method being the \"bottleneck\": I guess spending most of your time there cannot be avoided, since when constructing trees like this there's not much else you'll be doing but creating new Nodes.\n", "You can replace the KeySeq generator with itertools.count which does exactly the same thing but is implemented in C.\nI don't see any way of speeding up the Node constructor. The call to random.choice you could optimise by inlining the code - cut & paste it from the source for the random module. This will eliminate a function call, which are relatively expensive in Python.\nYou could speed it up by running under psyco, which is a kind of JIT optimiser. However this only works for 32 bit Intel builds of Python. Alternatively you could use cython - this converts python(ish) code into C, which can be compiled into a Python C module. I say pythonish since there some things that cannot be converted, and you can add C data type annotations to make the generated code more efficient.\n" ]
[ 4, 2, 2 ]
[]
[]
[ "expression_trees", "optimization", "python" ]
stackoverflow_0002127680_expression_trees_optimization_python.txt
Q: Python - Rpy2 - Can't import a bunch of packages I've just started using rpy2 with Python. I've installed it and am able to do basic things, like call R's plot function from inside Python. For everything I've done, I've used import calls like: import rpy2 import rpy2.robjects From robjects I can do most things I want to do. However, if I want to use things like ggplot2, I am unable to get the relevant imports to work. Following the steps here, I try: from rpy2.robjects.packages import importr But I get an error message telling me that there is no module called "packages." I'm not really sure why this is happening, as I am able to import other things from robjects, like rpy2.robjects.numpy2ri. I'm hoping this is some obvious problem other people have dealt with! I did some googling and tried messing around with the env variable $PYTHONPATH but I don't think that is the issue. A: packages is new in 2.1. You're probably still using 2.0.x. A: You can use the normal library() command from robjects.r to load a library in rpy2 2.0.x: from rpy2.robjects import r r.library("lattice") r.library("ggplot2") Or you can upgrade to the 2.1 alpha and see if the new way works for you.
Python - Rpy2 - Can't import a bunch of packages
I've just started using rpy2 with Python. I've installed it and am able to do basic things, like call R's plot function from inside Python. For everything I've done, I've used import calls like: import rpy2 import rpy2.robjects From robjects I can do most things I want to do. However, if I want to use things like ggplot2, I am unable to get the relevant imports to work. Following the steps here, I try: from rpy2.robjects.packages import importr But I get an error message telling me that there is no module called "packages." I'm not really sure why this is happening, as I am able to import other things from robjects, like rpy2.robjects.numpy2ri. I'm hoping this is some obvious problem other people have dealt with! I did some googling and tried messing around with the env variable $PYTHONPATH but I don't think that is the issue.
[ "packages is new in 2.1. You're probably still using 2.0.x.\n", "You can use the normal library() command from robjects.r to load a library in rpy2 2.0.x:\nfrom rpy2.robjects import r\nr.library(\"lattice\")\nr.library(\"ggplot2\")\n\nOr you can upgrade to the 2.1 alpha and see if the new way works for you.\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002128806_python.txt
Q: Running django on IronPython There have been some questions and answers here on stackoverflow, but no one asked if it's a good solution to run django on IIS. Any experience is welcome, both good and bad. A: One thing I know is that Django has no official support for IronPython - just CPython and Jython. In addition, PIL - which provides Django's support for image fields - does not natively support IronPython, though the ironclad project could help with that. (Caveat: I have never actually used IronPython, this is just based on research.) My recommendation would be to use a standard Python interpreter to run Django and use either FastCGI or isapi_wsgi to connect it to your IIS, as Django has more support for FastCGI and WSGI.
Running django on IronPython
There have been some questions and answers here on stackoverflow, but no one asked if it's a good solution to run django on IIS. Any experience is welcome, both good and bad.
[ "One thing I know is that Django has no official support for IronPython - just CPython and Jython. In addition, PIL - which provides Django's support for image fields - does not natively support IronPython, though the ironclad project could help with that. (Caveat: I have never actually used IronPython, this is just based on research.)\nMy recommendation would be to use a standard Python interpreter to run Django and use either FastCGI or isapi_wsgi to connect it to your IIS, as Django has more support for FastCGI and WSGI.\n" ]
[ 2 ]
[]
[]
[ ".net", "django", "iis", "ironpython", "python" ]
stackoverflow_0002128740_.net_django_iis_ironpython_python.txt
Q: Python, len, and size of ints So, cPython (2.4) has some interesting behaviour when the length of something gets near to 1<<32 (the size of an int). r = xrange(1<<30) assert len(r) == 1<<30 is fine, but: r = xrange(1<<32) assert len(r) == 1<<32 ValueError: xrange object size cannot be reported`__len__() should return 0 <= outcome Alex's wowrange has this behaviour as well. wowrange(1<<32).l is fine, but len(wowrange(1<<32)) is bad. I'm guessing there is some floating point behaviour (being read as negative) action going on here. What exactly is happening here? (this is pretty well-solved below!) How can I get around it? Longs? (My specific application is random.sample(xrange(1<<32),ABUNCH)) if people want to tackle that question directly!) A: cPython assumes that lists fit in memory. This extends to objects that behave like lists, such as xrange. essentially, the len function expects the __len__ method to return something that is convertable to size_t, which won't happen if the number of logical elements is too large, even if those elements don't actually exist in memory. A: You'll find that xrange(1 << 31 - 1) is the last one that behaves as you want. This is because the maximum signed (32-bit) integer is 2^31 - 1. 1 << 32 is not a positive signed 32-bit integer (Python's int datatype), so that's why you're getting that error. In Python 2.6, I can't even do xrange(1 << 32) or xrange(1 << 31) without getting an error, much less len on the result. Edit If you want a little more detail... 1 << 31 represents the number 0x80000000 which in 2's complement representation is the lowest representable negative number (-1 * 2^31) for a 32-bit int. So yes, due to the bit-wise representation of the numbers you're working with, it's actually becoming negative. For a 32-bit 2's complement number, 0x7FFFFFFF is the highest representable integer (2^31 - 1) before you "overflow" into negative numbers. Further reading, if you're interested. Note that when you see something like 2147483648L in the prompt, the "L" at the end signifies that it's now being represented as a "long integer" (64 bits, usually, I can't make any promises on how Python handles it because I haven't read up on it). A: 1<<32, when treated as a signed integer, is negative.
Python, len, and size of ints
So, cPython (2.4) has some interesting behaviour when the length of something gets near to 1<<32 (the size of an int). r = xrange(1<<30) assert len(r) == 1<<30 is fine, but: r = xrange(1<<32) assert len(r) == 1<<32 ValueError: xrange object size cannot be reported`__len__() should return 0 <= outcome Alex's wowrange has this behaviour as well. wowrange(1<<32).l is fine, but len(wowrange(1<<32)) is bad. I'm guessing there is some floating point behaviour (being read as negative) action going on here. What exactly is happening here? (this is pretty well-solved below!) How can I get around it? Longs? (My specific application is random.sample(xrange(1<<32),ABUNCH)) if people want to tackle that question directly!)
[ "cPython assumes that lists fit in memory. This extends to objects that behave like lists, such as xrange. essentially, the len function expects the __len__ method to return something that is convertable to size_t, which won't happen if the number of logical elements is too large, even if those elements don't actually exist in memory.\n", "You'll find that\nxrange(1 << 31 - 1)\n\nis the last one that behaves as you want. This is because the maximum signed (32-bit) integer is 2^31 - 1.\n1 << 32 is not a positive signed 32-bit integer (Python's int datatype), so that's why you're getting that error.\nIn Python 2.6, I can't even do xrange(1 << 32) or xrange(1 << 31) without getting an error, much less len on the result.\nEdit If you want a little more detail...\n1 << 31 represents the number 0x80000000 which in 2's complement representation is the lowest representable negative number (-1 * 2^31) for a 32-bit int. So yes, due to the bit-wise representation of the numbers you're working with, it's actually becoming negative. \nFor a 32-bit 2's complement number, 0x7FFFFFFF is the highest representable integer (2^31 - 1) before you \"overflow\" into negative numbers.\nFurther reading, if you're interested.\nNote that when you see something like 2147483648L in the prompt, the \"L\" at the end signifies that it's now being represented as a \"long integer\" (64 bits, usually, I can't make any promises on how Python handles it because I haven't read up on it).\n", "1<<32, when treated as a signed integer, is negative.\n" ]
[ 12, 5, 1 ]
[]
[]
[ "int", "python" ]
stackoverflow_0002128989_int_python.txt
Q: Error setting up Mercurial on Windows Server 2008 I want to set up a Mercurial SC server and have been following the instructions found here: http//stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis I have checked all my settings multiple times and cannot seem to get passed this error after completing the configuration. Any advice would be helpful. Thank you. Server Error in Application "DEFAULT WEB SITE/HG"Internet Information Services 7.5 Error Summary HTTP Error 502.2 - Bad Gateway The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are "Traceback (most recent call last): File "C:\inetpub\hgcgi\hgwebdir.cgi", line 12, in <module> from mercurial import demandimport; demandimport.enable() ImportError: No module named mercurial ". Detailed Error InformationModule CgiModule Notification ExecuteRequestHandler Handler Python 2.5 **Error Code 0x00000001** Requested URL http://localhost:80/hg/hgwebdir.cgi Physical Path C:\inetpub\hgcgi\hgwebdir.cgi Logon Method Anonymous Logon User Anonymous Most likely causes: The CGI process was shut down or terminated unexpectedly before it finished processing the request. The CGI process has a flaw and does not return a complete set of HTTP headers. Things you can try: Check the event logs on the system to see whether the CGI process is shutting down unexpectedly. Troubleshoot the CGI application to determine why it is not sending a complete set of HTTP headers. A: The traceback in the very long line says that mercurial isn't found in your PYTHON_PATH. Try making the hgwebdir.cgi edit as seen in step 5.1 from the HgWebDirStopByStep page. # adjust python path if not a system-wide install: import sys sys.path.insert(0, "c:/dev/Mercurial/lib") Where, of course, the path element that's being inserted is adjusted to reference wherever your mercurial library files are.
Error setting up Mercurial on Windows Server 2008
I want to set up a Mercurial SC server and have been following the instructions found here: http//stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis I have checked all my settings multiple times and cannot seem to get passed this error after completing the configuration. Any advice would be helpful. Thank you. Server Error in Application "DEFAULT WEB SITE/HG"Internet Information Services 7.5 Error Summary HTTP Error 502.2 - Bad Gateway The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are "Traceback (most recent call last): File "C:\inetpub\hgcgi\hgwebdir.cgi", line 12, in <module> from mercurial import demandimport; demandimport.enable() ImportError: No module named mercurial ". Detailed Error InformationModule CgiModule Notification ExecuteRequestHandler Handler Python 2.5 **Error Code 0x00000001** Requested URL http://localhost:80/hg/hgwebdir.cgi Physical Path C:\inetpub\hgcgi\hgwebdir.cgi Logon Method Anonymous Logon User Anonymous Most likely causes: The CGI process was shut down or terminated unexpectedly before it finished processing the request. The CGI process has a flaw and does not return a complete set of HTTP headers. Things you can try: Check the event logs on the system to see whether the CGI process is shutting down unexpectedly. Troubleshoot the CGI application to determine why it is not sending a complete set of HTTP headers.
[ "The traceback in the very long line says that mercurial isn't found in your PYTHON_PATH. Try making the hgwebdir.cgi edit as seen in step 5.1 from the HgWebDirStopByStep page.\n# adjust python path if not a system-wide install:\nimport sys\nsys.path.insert(0, \"c:/dev/Mercurial/lib\")\n\nWhere, of course, the path element that's being inserted is adjusted to reference wherever your mercurial library files are.\n" ]
[ 6 ]
[]
[]
[ "mercurial", "python", "windows_server_2008" ]
stackoverflow_0002123798_mercurial_python_windows_server_2008.txt
Q: What are the advantages of using Django insead of app-engine's default web framework? I'm building my first python app on app-engine and wondering if I should use Django or not. What are the strong points of each? If you have references that support your answer, please post them. Maybe we can make a wiki out of this question. A: Aral Balkan wrote a really nice piece addressing this very question. Its a year or so old, so take it with a grain of salt - I think that a lot more emphasis should be put on the awesomeness of django's Object-Relational-Model. Basically, IMHO, it all comes down to whether or not you have a preference for using DJango's object model (which I happen to). A: If it's not a small project, I try to use Django. You can use the App Engine Patch (http://code.google.com/p/app-engine-patch/). However, the ORM cannot use Django's meaning your models.py will still be using GAE's Datastore. One of the advantages of using Django on GAE is session management. GAE does not have a built-in session. You won't be able to using most Django 3rd-party apps though especially those with model changes. I had to build my own tagging app for GAE.
What are the advantages of using Django insead of app-engine's default web framework?
I'm building my first python app on app-engine and wondering if I should use Django or not. What are the strong points of each? If you have references that support your answer, please post them. Maybe we can make a wiki out of this question.
[ "Aral Balkan wrote a really nice piece addressing this very question. Its a year or so old, so take it with a grain of salt - I think that a lot more emphasis should be put on the awesomeness of django's Object-Relational-Model. Basically, IMHO, it all comes down to whether or not you have a preference for using DJango's object model (which I happen to).\n", "If it's not a small project, I try to use Django. You can use the App Engine Patch (http://code.google.com/p/app-engine-patch/). However, the ORM cannot use Django's meaning your models.py will still be using GAE's Datastore.\nOne of the advantages of using Django on GAE is session management. GAE does not have a built-in session.\nYou won't be able to using most Django 3rd-party apps though especially those with model changes. I had to build my own tagging app for GAE.\n" ]
[ 5, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002125612_django_google_app_engine_python.txt
Q: Python: xml.dom.minidom empty nodeValue nonempty toxml() value I have a line that gets the nodeValue of a Node: parent.getElementsByTagName("Url")[0].nodeValue that returns nothing: <br/> When I do: parent.getElementsByTagName("Url")[0].toxml() it returns: < Url>www.something.com< /Url> I am not sure what is going on here. Another data point: when I do nodeName instead of nodeValue it returns, as expected, Url. Any thoughts? A: Try this: parent.getElementsByTagName('Url')[0].childNodes[0].nodeValue A: The DOM Level 2 documentation states that nodeName for an element node is the tag name, the nodeValue is always null and attributes is a NamedNodeMap, so this code behaves as expected.
Python: xml.dom.minidom empty nodeValue nonempty toxml() value
I have a line that gets the nodeValue of a Node: parent.getElementsByTagName("Url")[0].nodeValue that returns nothing: <br/> When I do: parent.getElementsByTagName("Url")[0].toxml() it returns: < Url>www.something.com< /Url> I am not sure what is going on here. Another data point: when I do nodeName instead of nodeValue it returns, as expected, Url. Any thoughts?
[ "Try this:\nparent.getElementsByTagName('Url')[0].childNodes[0].nodeValue\n\n", "The DOM Level 2 documentation states that nodeName for an element node is the tag name, the nodeValue is always null and attributes is a NamedNodeMap, so this code behaves as expected.\n" ]
[ 6, 1 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0002129252_minidom_python_xml.txt
Q: Code translation, from Python to Ruby I would like to convert a few Python lines on Ruby, from this excellent article signed by Thomas Guest at: http://wordaligned.org/articles/drawing-chess-positions (note: I'm a really bigger Python noob) Here is a copy of the original Python version: def expand_blanks(fen): '''Expand the digits in an FEN string into spaces >>> expand_blanks("rk4q3") 'rk q ' ''' def expand(match): return ' ' * int(match.group(0)) return re.compile(r'\d').sub(expand, fen) def outer_join(sep, ss): '''Like string.join, but encloses the result with outer separators. Example: >>> outer_join('|', ['1', '2', '3']) '|1|2|3|' ''' return '%s%s%s' % (sep, sep.join(ss), sep) def ascii_draw_chess_position(fen): '''Returns an ASCII picture of pieces on a chessboard.''' pieces = expand_blanks(fen).replace('/', '') divider = '+-+-+-+-+-+-+-+-+\n' rows = ((outer_join('|', pieces[r: r + 8]) + '\n') for r in range(0, 8 * 8, 8)) return outer_join(divider, rows) Usage example: >>> fen = "r2q1rk1/pp2ppbp/1np2np1/2Q3B1/3PP1b1/2N2N2/PP3PPP/3RKB1R" >>> print ascii_draw_chess_position(fen) +-+-+-+-+-+-+-+-+ |r| | |q| |r|k| | +-+-+-+-+-+-+-+-+ |p|p| | |p|p|b|p| +-+-+-+-+-+-+-+-+ | |n|p| | |n|p| | +-+-+-+-+-+-+-+-+ | | |Q| | | |B| | +-+-+-+-+-+-+-+-+ | | | |P|P| |b| | +-+-+-+-+-+-+-+-+ | | |N| | |N| | | +-+-+-+-+-+-+-+-+ |P|P| | | |P|P|P| +-+-+-+-+-+-+-+-+ | | | |R|K|B| |R| +-+-+-+-+-+-+-+-+ I have trying to do some modifications to convert each line in Ruby... And I wonder if it's bad start :s But I publish it anyway: def expand_blanks(fen) def expand(match) return ' ' * int(match.group(0)) end # bugged: re.compile(r'\d').sub(expand, fen) end def outer_join(sep, ss) sep + sep.join(ss) + sep end def ascii_draw_chess_position(fen) pieces = expand_blanks(fen).replace('/', '') puts pieces.class divider = "+-+-+-+-+-+-+-+-+\n" # bugged lines: rows = ((outer_join('|', pieces[r, r + 8]) + '\n') for r in range(0, 8 * 8, 8)) return outer_join(divider, rows) end end fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" puts ascii_draw_chess_position(fen) If you see some lines that I can fix, I would be cool for me. Thank you all. A: Looking at each method in turn, starting with outer_join. In Python, join is a method on strings that takes a sequence and joins the elements delimited by the string. e.g. '|'.join(['p, 'p', 'p']) In Ruby, join is a method on arrays that takes the delimiter as an argument e.g. ['p', 'p', 'p'].join('|') so the Ruby version of outer_join would be: def outer_join(sep, ss): sep + ss.join(sep) + sep end Next look at expand_blanks, the intention here is to replace a digit with the equivalent number of spaces. In Ruby this can be achieved using gsub to replace all occurrences of a pattern in a string. gsub can be called with a block that will be passed each match substring and returns the string that the match should be replaced with. So the Ruby code would be: def expand_blanks(fen) fen.gsub(/\d/) { |match| ' ' * match.to_i } end Finally in ascii_draw_chess_position we can use gsub again as an equivalent to Python's replace method and use Ruby's map function in place of what was achieved using a list comprehension in Python as follows: def ascii_draw_chess_position(fen) pieces = expand_blanks(fen).gsub('/', '') divider = "+-+-+-+-+-+-+-+-+\n" rows = (0...8).map do |i| row = pieces[i * 8...(i + 1) * 8].split('') outer_join("|",row) + "\n" end puts outer_join(divider, rows) end Let me know if you need any more details on the above. A: This will do what you want: def expand(match) ' ' * match.to_i end def expand_blanks(fen) fen.gsub(/\d/) {|d| expand d} end def outer_join(sep, ss) sep + ss.join(sep) + sep end def ascii_draw_chess_position(fen) pieces = expand_blanks(fen).gsub('/', '') divider = "+-+-+-+-+-+-+-+-+\n" rows = (0...8).collect do |i| row = pieces[i*8...(i+1)*8].split('') outer_join("|",row) + "\n" end puts outer_join(divider, rows) end Let me know if there's any code here you don't understand - but make sure you've looked up the methods in the ruby docs If you're interested in the differences between ruby and python, see here https://stackoverflow.com/questions/234721/what-are-the-biggest-differences-between-python-and-ruby-from-a-philosophical-per or http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/, and for some good examples, see http://ruby.brian-amberg.de/editierdistanz/.
Code translation, from Python to Ruby
I would like to convert a few Python lines on Ruby, from this excellent article signed by Thomas Guest at: http://wordaligned.org/articles/drawing-chess-positions (note: I'm a really bigger Python noob) Here is a copy of the original Python version: def expand_blanks(fen): '''Expand the digits in an FEN string into spaces >>> expand_blanks("rk4q3") 'rk q ' ''' def expand(match): return ' ' * int(match.group(0)) return re.compile(r'\d').sub(expand, fen) def outer_join(sep, ss): '''Like string.join, but encloses the result with outer separators. Example: >>> outer_join('|', ['1', '2', '3']) '|1|2|3|' ''' return '%s%s%s' % (sep, sep.join(ss), sep) def ascii_draw_chess_position(fen): '''Returns an ASCII picture of pieces on a chessboard.''' pieces = expand_blanks(fen).replace('/', '') divider = '+-+-+-+-+-+-+-+-+\n' rows = ((outer_join('|', pieces[r: r + 8]) + '\n') for r in range(0, 8 * 8, 8)) return outer_join(divider, rows) Usage example: >>> fen = "r2q1rk1/pp2ppbp/1np2np1/2Q3B1/3PP1b1/2N2N2/PP3PPP/3RKB1R" >>> print ascii_draw_chess_position(fen) +-+-+-+-+-+-+-+-+ |r| | |q| |r|k| | +-+-+-+-+-+-+-+-+ |p|p| | |p|p|b|p| +-+-+-+-+-+-+-+-+ | |n|p| | |n|p| | +-+-+-+-+-+-+-+-+ | | |Q| | | |B| | +-+-+-+-+-+-+-+-+ | | | |P|P| |b| | +-+-+-+-+-+-+-+-+ | | |N| | |N| | | +-+-+-+-+-+-+-+-+ |P|P| | | |P|P|P| +-+-+-+-+-+-+-+-+ | | | |R|K|B| |R| +-+-+-+-+-+-+-+-+ I have trying to do some modifications to convert each line in Ruby... And I wonder if it's bad start :s But I publish it anyway: def expand_blanks(fen) def expand(match) return ' ' * int(match.group(0)) end # bugged: re.compile(r'\d').sub(expand, fen) end def outer_join(sep, ss) sep + sep.join(ss) + sep end def ascii_draw_chess_position(fen) pieces = expand_blanks(fen).replace('/', '') puts pieces.class divider = "+-+-+-+-+-+-+-+-+\n" # bugged lines: rows = ((outer_join('|', pieces[r, r + 8]) + '\n') for r in range(0, 8 * 8, 8)) return outer_join(divider, rows) end end fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" puts ascii_draw_chess_position(fen) If you see some lines that I can fix, I would be cool for me. Thank you all.
[ "Looking at each method in turn, starting with outer_join.\nIn Python, join is a method on strings that takes a sequence and joins the elements delimited by the string. e.g. '|'.join(['p, 'p', 'p'])\nIn Ruby, join is a method on arrays that takes the delimiter as an argument e.g. ['p', 'p', 'p'].join('|')\nso the Ruby version of outer_join would be:\ndef outer_join(sep, ss):\n sep + ss.join(sep) + sep\nend\n\nNext look at expand_blanks, the intention here is to replace a digit with the equivalent number of spaces. In Ruby this can be achieved using gsub to replace all occurrences of a pattern in a string. gsub can be called with a block that will be passed each match substring and returns the string that the match should be replaced with. So the Ruby code would be:\ndef expand_blanks(fen)\n fen.gsub(/\\d/) { |match| ' ' * match.to_i }\nend\n\nFinally in ascii_draw_chess_position we can use gsub again as an equivalent to Python's replace method and use Ruby's map function in place of what was achieved using a list comprehension in Python as follows:\ndef ascii_draw_chess_position(fen)\n pieces = expand_blanks(fen).gsub('/', '')\n divider = \"+-+-+-+-+-+-+-+-+\\n\"\n rows = (0...8).map do |i|\n row = pieces[i * 8...(i + 1) * 8].split('')\n outer_join(\"|\",row) + \"\\n\"\n end\n puts outer_join(divider, rows)\nend\n\nLet me know if you need any more details on the above.\n", "This will do what you want:\ndef expand(match)\n ' ' * match.to_i\nend\n\ndef expand_blanks(fen)\n fen.gsub(/\\d/) {|d| expand d}\nend\n\ndef outer_join(sep, ss)\n sep + ss.join(sep) + sep\nend\n\ndef ascii_draw_chess_position(fen)\n pieces = expand_blanks(fen).gsub('/', '')\n divider = \"+-+-+-+-+-+-+-+-+\\n\"\n rows = (0...8).collect do |i|\n row = pieces[i*8...(i+1)*8].split('')\n outer_join(\"|\",row) + \"\\n\"\n end\n puts outer_join(divider, rows)\nend\n\nLet me know if there's any code here you don't understand - but make sure you've looked up the methods in the ruby docs\nIf you're interested in the differences between ruby and python, see here https://stackoverflow.com/questions/234721/what-are-the-biggest-differences-between-python-and-ruby-from-a-philosophical-per or http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/, and for some good examples, see http://ruby.brian-amberg.de/editierdistanz/.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0002129227_python_ruby.txt
Q: Python to C# Code Explanation My ultimate aim is to convert the below code in python to C#, but I'd like to do it my self by learning the python syntax. I understand that the code is recursive. The code produces polynomials of degree n with k variables. More specifically the list of exponents for each variable. def multichoose(n,k): if k < 0 or n < 0: return "Error" if not k: return [[0]*n] if not n: return [] if n == 1: return [[k]] return [[0]+val for val in multichoose(n-1,k)] + \ [[val[0]+1]+val[1:] for val in multichoose(n,k-1)] Here is the conversion I have so far: public double[] MultiChoose(int n, int k) { if (k < 0 || n < 0) { throw new Exception(); } if (k == 0) { return [[0]*n]; // I have no idea what the [[0]*n] syntax means } if (n == 0) { return new double[0]; // I think this is just an empty array } if (n == 1) { return new double[1] {k}; // I think this is just an empty array } //Part I don't understand return [[0]+val for val in MultiChoose(n-1,k)] + \ [[val[0]+1]+val[1:] for val in MultiChoose(n,k-1)] } My question is: How do I convert the python code? A: I would use LINQ in C# to translate the code: [] is the empty list. Enumerable.Empty<T>() [x] is the list containing a single item, x. Enumerable.Repeat(x, 1) [[0]*n] is the list containing the list containing n copies of 0. Enumerable.Repeat(Enumerable.Repeat(0, n), 1) [X for Y in Z] is a list comprehension. from Y in Z select X - or - Z.Select(Y => X); X + Y (where X and Y are lists) is list concatenation. Enumerable.Concat(X, Y) The signature of MultiChoose would be: public IEnumerable<IEnumerable<double>> MultiChoose(int n, int k); A: [0] * n returns a list with n 0s. [] is an empty list. [[k]] is a list that contains a list that contains k. The last part uses list comprehensions. The basic forms of a list comprehension are: [<new value> for <name> in <sequence>] [<new value> for <name> in <sequence> if <condition>] It creates a new list containing the new values each time the optional condition is true. A: Some comments: Pythons return "Error" is not throwing an exception. It returns the string value "Error". Pythons if not k: is not equivalent to if (k == 0) there are more things that are "not", like empty lists, the None value, etc (that may not make a difference in this case). Pythons foo = [for x in bar] is a list comprehension. It's equivalent to: foo = [] for x in bar: foo.append(x) A: I found this one intriguing and after some help with understanding the Python code I took a stab at it. C# 3.0 and .NET Framework 3.5 needed. public static IEnumerable<IEnumerable<int>> MultiChoose(int n, int k) { if (k < 0 || n < 0) throw new Exception(); if (k == 0) return Enumerable.Repeat(Enumerable.Repeat(0, n), 1); if (n == 0) return Enumerable.Repeat(Enumerable.Empty<int>(), 0); if (n == 1) return Enumerable.Repeat(Enumerable.Repeat(k, 1), 1); return (from val in MultiChoose(n - 1, k) select new [] { 0 }.Concat(val)) .Concat(from val in MultiChoose(n, k - 1) select new [] { val.First() + 1 }.Concat(val.Skip(1))); } Here's a version in Ruby def multichoose(n,k) if k<0 || n<0: raise "Error" end if k==0: return [[0]*n] end if n==0: return [] end if n==1: return [[k]] end multichoose(n-1,k).map{|val| [0]+val} + \ multichoose(n,k-1).map{|val| [val.first+1]+val[1..-1]} end and some output examples: >> multichoose(2,2) => [[0, 2], [1, 1], [2, 0]] >> multichoose(3,2) => [[0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0]] >> multichoose(3,3) => [[0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0]]
Python to C# Code Explanation
My ultimate aim is to convert the below code in python to C#, but I'd like to do it my self by learning the python syntax. I understand that the code is recursive. The code produces polynomials of degree n with k variables. More specifically the list of exponents for each variable. def multichoose(n,k): if k < 0 or n < 0: return "Error" if not k: return [[0]*n] if not n: return [] if n == 1: return [[k]] return [[0]+val for val in multichoose(n-1,k)] + \ [[val[0]+1]+val[1:] for val in multichoose(n,k-1)] Here is the conversion I have so far: public double[] MultiChoose(int n, int k) { if (k < 0 || n < 0) { throw new Exception(); } if (k == 0) { return [[0]*n]; // I have no idea what the [[0]*n] syntax means } if (n == 0) { return new double[0]; // I think this is just an empty array } if (n == 1) { return new double[1] {k}; // I think this is just an empty array } //Part I don't understand return [[0]+val for val in MultiChoose(n-1,k)] + \ [[val[0]+1]+val[1:] for val in MultiChoose(n,k-1)] } My question is: How do I convert the python code?
[ "I would use LINQ in C# to translate the code:\n\n[] is the empty list.\nEnumerable.Empty<T>()\n\n[x] is the list containing a single item, x.\nEnumerable.Repeat(x, 1)\n\n[[0]*n] is the list containing the list containing n copies of 0.\nEnumerable.Repeat(Enumerable.Repeat(0, n), 1)\n\n[X for Y in Z] is a list comprehension.\nfrom Y in Z select X\n - or -\nZ.Select(Y => X);\n\nX + Y (where X and Y are lists) is list concatenation.\nEnumerable.Concat(X, Y)\n\n\nThe signature of MultiChoose would be:\n public IEnumerable<IEnumerable<double>> MultiChoose(int n, int k);\n\n", "[0] * n returns a list with n 0s. [] is an empty list. [[k]] is a list that contains a list that contains k.\nThe last part uses list comprehensions. The basic forms of a list comprehension are:\n[<new value> for <name> in <sequence>]\n[<new value> for <name> in <sequence> if <condition>]\n\nIt creates a new list containing the new values each time the optional condition is true.\n", "Some comments:\nPythons return \"Error\" is not throwing an exception. It returns the string value \"Error\".\nPythons if not k: is not equivalent to if (k == 0) there are more things that are \"not\", like empty lists, the None value, etc (that may not make a difference in this case).\nPythons foo = [for x in bar] is a list comprehension. It's equivalent to:\nfoo = []\nfor x in bar:\n foo.append(x)\n\n", "I found this one intriguing and after some help with understanding the Python code I took a stab at it. C# 3.0 and .NET Framework 3.5 needed.\npublic static IEnumerable<IEnumerable<int>> MultiChoose(int n, int k)\n{\n if (k < 0 || n < 0) throw new Exception();\n if (k == 0) return Enumerable.Repeat(Enumerable.Repeat(0, n), 1);\n if (n == 0) return Enumerable.Repeat(Enumerable.Empty<int>(), 0);\n if (n == 1) return Enumerable.Repeat(Enumerable.Repeat(k, 1), 1);\n\n return (from val in MultiChoose(n - 1, k) select new [] { 0 }.Concat(val))\n .Concat(from val in MultiChoose(n, k - 1) select new [] { val.First() + 1 }.Concat(val.Skip(1)));\n}\n\nHere's a version in Ruby\ndef multichoose(n,k)\n if k<0 || n<0: raise \"Error\" end\n if k==0: return [[0]*n] end\n if n==0: return [] end\n if n==1: return [[k]] end\n multichoose(n-1,k).map{|val| [0]+val} + \\\n multichoose(n,k-1).map{|val| [val.first+1]+val[1..-1]}\nend\n\nand some output examples:\n>> multichoose(2,2)\n=> [[0, 2], [1, 1], [2, 0]]\n>> multichoose(3,2)\n=> [[0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0]]\n>> multichoose(3,3)\n=> [[0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0]]\n\n" ]
[ 3, 1, 1, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0002128784_c#_python.txt
Q: Trying to run a Python program but all that opens is a DOS Window I just completed a program that should (hopefully) play a GUI Tetris program. I've cleaned up all the syntax errors, but now when I double-click, or go through the Command Prompt to run the program a DOS window pops up for less than a second and disappears without ever running the program. What's going on? Heres a link to the code at codepad.org http://codepad.org/tq4et1rO A: Wow, there's really a huge number of errors in your code. I started running it under pdb, identifying and fixing them one by one, but after 20 or so I gave up. What I fixed so far (in diff's output, lines start with < to mean they're in your version, or with > to mean they're in my partially fixed version). Note the variety: you often write Flase instead of False, use wrong capitalization, use - (minus) instead of = (equals), misspell variables (e.g. Boardd instead of Board, even instead of event), rnage instead of range, and so on, and so forth. 37c37 < self.isStarted = Flase --- > self.isStarted = False 63c63 < self.isWaitingAfterLine - Flase --- > self.isWaitingAfterLine = False 87c87 < for i in range(Board.BoardHeight * Board.Boardwidth): --- > for i in range(Board.BoardHeight * Board.BoardWidth): 135c135 < if even.GetId() == Boardd.ID_TIMER: --- > if event.GetId() == Board.ID_TIMER: 205c205 < self.curY = Board.Height - 1 + self.curPiece.minY() --- > self.curY = Board.BoardHeight - 1 + self.curPiece.minY() 214c214 < for i in rnage(4): --- > for i in range(4): 217c217 < if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.Boardheight: --- > if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight: 278c278 < self.coords = [[0, 0] for i in rnage(4)] --- > self.coords = [[0, 0] for i in range(4)] 356c356,357 < Tetris(None, -1, 'Tetris') --- > tetris = Tetris(None, -1, 'Tetris') > app.SetTopWindow(tetris) After all these fixes, I've stopped upon spotting one more typo (you def sqaureHeight when you clearly mean squareHeight) -- I have no idea how many typos and other mistakes are still hiding in these 360 lines of code... A density of more such bugs than 1/10th of the lines is plenty high enough for me. I heartily recommend that you start with much less ambitious projects and teach yourself to carefully "copyedit" your code for these typos you appear to be so prone to: it's possible to be dyslexic and an excellent programmer at the same time, but it does take extra effort and diligence on your part. Tools such as pylint may also help a little, although they do have limits. Edit: as it turns out, after fixing a couple of occurences of sqaure into square, the program does run -- and immediately shows an empty window saying "Game Over" and gets to the raw_input prompt you have as your very last line. So beyond the many typos there must be one or more nasty logic-level bugs as well. I repeat the entreaty to start with something much, much simpler in your first forays into programming. A: Running your script actually does produce a traceback: Traceback (most recent call last): File "tetris.py", line 356, in <module> Tetris(None, -1, 'Tetris') File "tetris.py", line 10, in __init__ self.statusbar - self.CreateStatusBar() AttributeError: 'Tetris' object has no attribute 'statusbar' Your script has an error on line 10: self.statusbar - self.CreateStatusBar() You mean to be assigning there, not subtracting from an attribute that does not yet exist. A: An error occurred. Unfortunately, the DOS window closed (because the Python program ended) and you didn't get to see the actual error. Start a DOS window yourself (start -> run -> 'cmd') and run the program from there. That will show you the traceback. A: The DOS window pops up because you are using the wrong python binary (python.exe instead of pythonw.exe?) It does not show anything because, there is a bug in you program. If there is no stack trace I guess you forgot to enter the main loop. Try posting some code. A: Traceback (most recent call last): Line 3, in <module> import wx ImportError: No module named wx You need to install wxPython A: You may want to change (at the bottom of your script) app = wx.App() to app = wx.App(redirect=False) Otherwise the segmentation faults that happen as wxPython is starting up won't be printed to the console, and can be a nightmare to track down.
Trying to run a Python program but all that opens is a DOS Window
I just completed a program that should (hopefully) play a GUI Tetris program. I've cleaned up all the syntax errors, but now when I double-click, or go through the Command Prompt to run the program a DOS window pops up for less than a second and disappears without ever running the program. What's going on? Heres a link to the code at codepad.org http://codepad.org/tq4et1rO
[ "Wow, there's really a huge number of errors in your code. I started running it under pdb, identifying and fixing them one by one, but after 20 or so I gave up. What I fixed so far (in diff's output, lines start with < to mean they're in your version, or with > to mean they're in my partially fixed version). Note the variety: you often write Flase instead of False, use wrong capitalization, use - (minus) instead of = (equals), misspell variables (e.g. Boardd instead of Board, even instead of event), rnage instead of range, and so on, and so forth.\n37c37\n< self.isStarted = Flase\n---\n> self.isStarted = False\n63c63\n< self.isWaitingAfterLine - Flase\n---\n> self.isWaitingAfterLine = False\n87c87\n< for i in range(Board.BoardHeight * Board.Boardwidth):\n---\n> for i in range(Board.BoardHeight * Board.BoardWidth):\n135c135\n< if even.GetId() == Boardd.ID_TIMER:\n---\n> if event.GetId() == Board.ID_TIMER:\n205c205\n< self.curY = Board.Height - 1 + self.curPiece.minY()\n---\n> self.curY = Board.BoardHeight - 1 + self.curPiece.minY()\n214c214\n< for i in rnage(4):\n---\n> for i in range(4):\n217c217\n< if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.Boardheight:\n---\n> if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:\n278c278\n< self.coords = [[0, 0] for i in rnage(4)]\n---\n> self.coords = [[0, 0] for i in range(4)]\n356c356,357\n< Tetris(None, -1, 'Tetris')\n---\n> tetris = Tetris(None, -1, 'Tetris')\n> app.SetTopWindow(tetris)\n\nAfter all these fixes, I've stopped upon spotting one more typo (you def sqaureHeight when you clearly mean squareHeight) -- I have no idea how many typos and other mistakes are still hiding in these 360 lines of code... A density of more such bugs than 1/10th of the lines is plenty high enough for me.\nI heartily recommend that you start with much less ambitious projects and teach yourself to carefully \"copyedit\" your code for these typos you appear to be so prone to: it's possible to be dyslexic and an excellent programmer at the same time, but it does take extra effort and diligence on your part. Tools such as pylint may also help a little, although they do have limits.\nEdit: as it turns out, after fixing a couple of occurences of sqaure into square, the program does run -- and immediately shows an empty window saying \"Game Over\" and gets to the raw_input prompt you have as your very last line. So beyond the many typos there must be one or more nasty logic-level bugs as well. I repeat the entreaty to start with something much, much simpler in your first forays into programming.\n", "Running your script actually does produce a traceback:\nTraceback (most recent call last):\n File \"tetris.py\", line 356, in <module>\n Tetris(None, -1, 'Tetris')\n File \"tetris.py\", line 10, in __init__\n self.statusbar - self.CreateStatusBar()\nAttributeError: 'Tetris' object has no attribute 'statusbar'\n\nYour script has an error on line 10:\nself.statusbar - self.CreateStatusBar()\n\nYou mean to be assigning there, not subtracting from an attribute that does not yet exist.\n", "An error occurred. Unfortunately, the DOS window closed (because the Python program ended) and you didn't get to see the actual error. Start a DOS window yourself (start -> run -> 'cmd') and run the program from there. That will show you the traceback.\n", "The DOS window pops up because you are using the wrong python binary (python.exe instead of pythonw.exe?)\nIt does not show anything because, there is a bug in you program. If there is no stack trace I guess you forgot to enter the main loop. Try posting some code.\n", "Traceback (most recent call last):\n Line 3, in <module>\n import wx\nImportError: No module named wx\n\nYou need to install wxPython\n", "You may want to change (at the bottom of your script)\napp = wx.App()\n\nto\napp = wx.App(redirect=False)\n\nOtherwise the segmentation faults that happen as wxPython is starting up won't be printed to the console, and can be a nightmare to track down.\n" ]
[ 9, 8, 2, 0, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002129421_python_wxpython.txt
Q: How limiting are web frameworks This is a general question about how limiting are web development frameworks such as Django and ruby-on-rails. I am planning on building a RESTful web service which will have a purely JSON/XML interface, no GUI. The service will rely on a database however for a few of the more important operations there is no clear way of persisting a "model" object directly into a database table. In addition I require full control over when and how the data is being written to the database. I will need to maintain multiple database connections in order to use some connections only for reads and others only for writes. I've looked at the "full" MVC frameworks such as Django and more basic ones such web.py and pylons. The impression I currently have is that if I go with the full framework initially things will go faster but eventually I will get stuck because I will be limited by the framework in what I can do. If I go with a more basic framework it will take much longer to get everything running but I will be free to do what I need. This is what it seems like but I suspect that it might be an incorrect impression given how many sites are written in Django and Rails. Could you please provide your opinion. Am I totally wrong and there is a way to easily do anything with a framework like Django or Rails or given my requirements I should go with something like web.py? Thank you! A: Web frameworks tend to optimize around building websites, making most normal use cases simpler to accomplish. Once you start to do more "out of the box" stuff with a framework, you might find that you spend more time working around it then you save using it in the first place. It's hard to generalize here (especially since I've really only worked in-depth with Django), so I'll offer some advice based on my own experiences developing a JSON API using Django: Simple put, I don't recommend using Django to write a REST API. In my own experience, I really didn't find anything worth writing home about. I didn't need Django's templating system, so all that I really made use of was the URL dispatching and ORM. Even then, I had to do some hacks to get the URL dispatcher to do what I wanted -- had I not used other features it would've been faster to use a different URL system, in fact. In your case, Django's ORM wouldn't even be suitable since it doesn't support multiple databases (unless you're using 1.2 alphas...). Compound that with Django's lack of a good startup signal, and Django starts to look pretty bad for the job. If I were in your shoes, I'd dig around for specific libraries that did what I needed (ORM, WSGI, etc) and just use them, rather than trying to bend and hammer Django into something that suits my needs. On a totally different note, you might want to take a look at Tornado as a possible HTTP frontend. It's both simple and fast. A: Most web sites will be well suited to rich frameworks like Rails or Django -- but you're building a web service , and that has very different tradeoffs. Personally, I prefer to use very light frameworks for web services: in Python, that means relying primarily on WSGI (which is a standard, not a framework), with a minimum of highly modular components to provide some little extras that I may need depending on the services' details (WSGI's very good at allowing modular composition of "middleware" bits and pieces). My personal favorite collection of modular WSGI components is Werkzeug, with WebOb for request and response objects; if I need templates, these days, I tend to go with Django Templates, and if I need a relational DB I prefer to write SQL directly (though SQLAlchemy has its strong points!-). But the cool thing about using modular components rather than integrated frameworks is that you can change each and every one of these choices (and mix-and-match at will depending on your exact needs, preferences, and tastes!-). A: You can still use the full potential of the language in question, even if you also use a framework. A framework isn't a limiting factor, it's basically a tool to ease development of certain parts of your application. Django and rails, for instance, abstract away some database functionality, so you'll only have to worry about your model objects. That doesn't mean you can't do stuff on your own as well... A: In average, the more complete and helpful the web framework is, the more limiting it is when you try to do things another way than the way the web framework thinks is The Right Way. Some web frameworks try to be very helpful and still not restrictive, and some do that better than others. And the general recommendation there is: Don't fight the framework. You will lose. So it's important to chose a framework that helps you with the things you want to do, but doesn't enforce anything else. For your webservice case, this should not be a problem. There are tons of minimalistic web frameworks out there, at least in the Python world (which is all I care about). Bobo, BFG, Pylons, Werkzeug, etc, etc. None of these will get in your way one bit. Also don't forget that you often can use several frameworks together by having them run side by side. Especially using techniques such as Dexterity/XDV. Plone.org for example is mostly Plon (duh) an excellent content management system, but extremely restrictive if you want to do something else. So part of the site is Trac, the excellent Python bug tracker. It's all integrated to look the same. A: Rails is as helpful or not as you need it to be, overall. If you need to load a collection with straight SQL, it's straightforward. If in the same line you want to use all the built-in ActiveRecord Fu, you can. RESTful routing is extremely simple, but again if the particular Rails flavor of REST doesn't meet your needs, the routing is completely configurable. In a Rails app you can use as much or as little of the defaults as you need to, and reconfiguration is available at all levels. A: If you're not using the presentation layer of Rails, you're missing out on a huge part of it. The functionality required to dump objects to json/xml is so small the only real remaining advantages you could gain from it would be ActiveRecord and routing, and if you can't imagine your data cleanly fitting a model, then that doesn't leave much. I think you really just need a minimalist framework to take care of some of the basics. Something that provides you with some niceties on request/response handling and routing and gets the hell out of the way. The Python equivalent of something like Sinatra might be up your alley. I use a similar framework in Scala called Step for xml/json based webservices where I care about performance (and there's no presentation going on). I'm glancing over web.py, it seems to cover a similar level of functionality to Sinatra/Step. I feel that's a more appropriate direction than some of the more full features frameworks. I didn't regret my choice of Step, the codebase is so comically small it's impossible not to understand it, and that makes it easy to extend slightly should you have the need. A: I have used Ruby/Rails for years now, and unlike just about every other language/framework I have used (across nearly 15 years of Java, PHP, ColdFusion, ASP, etc etc) it gets out of the way when you need it to. It sounds like you might benefit from a "lighter-weight" framework like Sinatra, but with the upcoming Rails 3 release the benefits are becoming less pronounced. Rails 3 makes everything configurable ... in fact, Rails will now just be a particular set of plugins and extensions sitting onto of an infinitely flexible core. I am interested in this statement: "The service will rely on a database however for a few of the more important operations there is no clear way of persisting a "model" object directly into a database table." Not sure what you mean by this statement ... at some point you have something going into the database, right? In most non-trivial applications you rarely have a single model tied to the end of a request ... you might actually have a quite complex network of models that are returned or updated. If you are working with JSON, I would definitely suggest looking at a database like MongoDB. MongoDB is based entirely on storing JSON data, and may therefore fit really neatly with your application. A: You have written down no requirements, you have written down technology decisions. That's something totally different. What do you want to achieve? Then we might be able to help you with how to achieve them. A: If you know you're not going to use an ORM, or create a user interface, then you've just eliminated about 90% of what you'd use a web application framework for in the first place. If you look at the feature set of Django, for instance: what parts of that would you use to implement a web service that you couldn't get from using something much simpler, like Werkzeug or CherryPy? The principal differences between building a web service and building any old black box that takes input and produces output are the various technical limitations imposed by the API being HTTP-based, the problem of statelessness, and the problem of idempotence. A web application framework is going to give you a little help with those issues, but not much. A: You'll be much more limited by the abilities of yourself versus a diverse community of developers working on a large project to share all those common parts. A: Give a try to Spring 3.0 : See this post
How limiting are web frameworks
This is a general question about how limiting are web development frameworks such as Django and ruby-on-rails. I am planning on building a RESTful web service which will have a purely JSON/XML interface, no GUI. The service will rely on a database however for a few of the more important operations there is no clear way of persisting a "model" object directly into a database table. In addition I require full control over when and how the data is being written to the database. I will need to maintain multiple database connections in order to use some connections only for reads and others only for writes. I've looked at the "full" MVC frameworks such as Django and more basic ones such web.py and pylons. The impression I currently have is that if I go with the full framework initially things will go faster but eventually I will get stuck because I will be limited by the framework in what I can do. If I go with a more basic framework it will take much longer to get everything running but I will be free to do what I need. This is what it seems like but I suspect that it might be an incorrect impression given how many sites are written in Django and Rails. Could you please provide your opinion. Am I totally wrong and there is a way to easily do anything with a framework like Django or Rails or given my requirements I should go with something like web.py? Thank you!
[ "Web frameworks tend to optimize around building websites, making most normal use cases simpler to accomplish. Once you start to do more \"out of the box\" stuff with a framework, you might find that you spend more time working around it then you save using it in the first place.\nIt's hard to generalize here (especially since I've really only worked in-depth with Django), so I'll offer some advice based on my own experiences developing a JSON API using Django:\nSimple put, I don't recommend using Django to write a REST API. In my own experience, I really didn't find anything worth writing home about. I didn't need Django's templating system, so all that I really made use of was the URL dispatching and ORM. Even then, I had to do some hacks to get the URL dispatcher to do what I wanted -- had I not used other features it would've been faster to use a different URL system, in fact. In your case, Django's ORM wouldn't even be suitable since it doesn't support multiple databases (unless you're using 1.2 alphas...). Compound that with Django's lack of a good startup signal, and Django starts to look pretty bad for the job.\nIf I were in your shoes, I'd dig around for specific libraries that did what I needed (ORM, WSGI, etc) and just use them, rather than trying to bend and hammer Django into something that suits my needs.\nOn a totally different note, you might want to take a look at Tornado as a possible HTTP frontend. It's both simple and fast.\n", "Most web sites will be well suited to rich frameworks like Rails or Django -- but you're building a web service , and that has very different tradeoffs.\nPersonally, I prefer to use very light frameworks for web services: in Python, that means relying primarily on WSGI (which is a standard, not a framework), with a minimum of highly modular components to provide some little extras that I may need depending on the services' details (WSGI's very good at allowing modular composition of \"middleware\" bits and pieces).\nMy personal favorite collection of modular WSGI components is Werkzeug, with WebOb for request and response objects; if I need templates, these days, I tend to go with Django Templates, and if I need a relational DB I prefer to write SQL directly (though SQLAlchemy has its strong points!-).\nBut the cool thing about using modular components rather than integrated frameworks is that you can change each and every one of these choices (and mix-and-match at will depending on your exact needs, preferences, and tastes!-).\n", "You can still use the full potential of the language in question, even if you also use a framework. A framework isn't a limiting factor, it's basically a tool to ease development of certain parts of your application. Django and rails, for instance, abstract away some database functionality, so you'll only have to worry about your model objects. That doesn't mean you can't do stuff on your own as well...\n", "In average, the more complete and helpful the web framework is, the more limiting it is when you try to do things another way than the way the web framework thinks is The Right Way. Some web frameworks try to be very helpful and still not restrictive, and some do that better than others.\nAnd the general recommendation there is: Don't fight the framework. You will lose. So it's important to chose a framework that helps you with the things you want to do, but doesn't enforce anything else. For your webservice case, this should not be a problem. There are tons of minimalistic web frameworks out there, at least in the Python world (which is all I care about). Bobo, BFG, Pylons, Werkzeug, etc, etc. None of these will get in your way one bit.\nAlso don't forget that you often can use several frameworks together by having them run side by side. Especially using techniques such as Dexterity/XDV. Plone.org for example is mostly Plon (duh) an excellent content management system, but extremely restrictive if you want to do something else. So part of the site is Trac, the excellent Python bug tracker. It's all integrated to look the same.\n", "Rails is as helpful or not as you need it to be, overall. If you need to load a collection with straight SQL, it's straightforward. If in the same line you want to use all the built-in ActiveRecord Fu, you can. RESTful routing is extremely simple, but again if the particular Rails flavor of REST doesn't meet your needs, the routing is completely configurable. In a Rails app you can use as much or as little of the defaults as you need to, and reconfiguration is available at all levels. \n", "If you're not using the presentation layer of Rails, you're missing out on a huge part of it. The functionality required to dump objects to json/xml is so small the only real remaining advantages you could gain from it would be ActiveRecord and routing, and if you can't imagine your data cleanly fitting a model, then that doesn't leave much.\nI think you really just need a minimalist framework to take care of some of the basics. Something that provides you with some niceties on request/response handling and routing and gets the hell out of the way. The Python equivalent of something like Sinatra might be up your alley. I use a similar framework in Scala called Step for xml/json based webservices where I care about performance (and there's no presentation going on).\nI'm glancing over web.py, it seems to cover a similar level of functionality to Sinatra/Step. I feel that's a more appropriate direction than some of the more full features frameworks. I didn't regret my choice of Step, the codebase is so comically small it's impossible not to understand it, and that makes it easy to extend slightly should you have the need.\n", "I have used Ruby/Rails for years now, and unlike just about every other language/framework I have used (across nearly 15 years of Java, PHP, ColdFusion, ASP, etc etc) it gets out of the way when you need it to.\nIt sounds like you might benefit from a \"lighter-weight\" framework like Sinatra, but with the upcoming Rails 3 release the benefits are becoming less pronounced. Rails 3 makes everything configurable ... in fact, Rails will now just be a particular set of plugins and extensions sitting onto of an infinitely flexible core. \nI am interested in this statement:\n\n\"The service will rely on a database however for a few of the more important operations\n there is no clear way of persisting a \"model\" object directly into a database table.\"\n\nNot sure what you mean by this statement ... at some point you have something going into the database, right?\nIn most non-trivial applications you rarely have a single model tied to the end of a request ... you might actually have a quite complex network of models that are returned or updated.\nIf you are working with JSON, I would definitely suggest looking at a database like MongoDB. MongoDB is based entirely on storing JSON data, and may therefore fit really neatly with your application. \n", "You have written down no requirements, you have written down technology decisions. That's something totally different. What do you want to achieve? Then we might be able to help you with how to achieve them.\n", "If you know you're not going to use an ORM, or create a user interface, then you've just eliminated about 90% of what you'd use a web application framework for in the first place. If you look at the feature set of Django, for instance: what parts of that would you use to implement a web service that you couldn't get from using something much simpler, like Werkzeug or CherryPy?\nThe principal differences between building a web service and building any old black box that takes input and produces output are the various technical limitations imposed by the API being HTTP-based, the problem of statelessness, and the problem of idempotence. A web application framework is going to give you a little help with those issues, but not much.\n", "You'll be much more limited by the abilities of yourself versus a diverse community of developers working on a large project to share all those common parts.\n", "Give a try to Spring 3.0 : See this post\n" ]
[ 8, 6, 5, 2, 1, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "django", "python", "rest", "ruby_on_rails" ]
stackoverflow_0002125865_django_python_rest_ruby_on_rails.txt
Q: Using Django's Model API without having to *include* the full Django stack Currently an application of mine is using SQLAlchemy, but I have been considering the possibility of using Django model API. Django 1.1.1 is about 3.6 megabytes in size, whereas SQLAlchemy is about 400 kilobytes (as reported by PyPM - which is essentially the size of the files installed by python setup.py install). I would like to use the Django models (so as to not have other developers learn yet-another-ORM), but do not want to include 3.6 megabytes of stuff most of which are not needed. (FYI - the application, final executable that is, actually bundles the install_requires from setup.py) A: The Django ORM is usable on its own - you can use "settings.configure()" to set up the database settings. That said, you'll have to do the stripping down and repackaging yourself, and you'll have to experiment with how much you can actually strip away. I'm sure you can ditch contrib/, forms/, template/, and probably several other unrelated pieces. The ORM definitely relies on conf/, and quite likely on core/ and util/ as well. A few quick greps through db/* should make it clear what's imported. A: You may be able to get a good idea of what is safe to strip out by checking which files don't have their access time updated when you run your application.
Using Django's Model API without having to *include* the full Django stack
Currently an application of mine is using SQLAlchemy, but I have been considering the possibility of using Django model API. Django 1.1.1 is about 3.6 megabytes in size, whereas SQLAlchemy is about 400 kilobytes (as reported by PyPM - which is essentially the size of the files installed by python setup.py install). I would like to use the Django models (so as to not have other developers learn yet-another-ORM), but do not want to include 3.6 megabytes of stuff most of which are not needed. (FYI - the application, final executable that is, actually bundles the install_requires from setup.py)
[ "The Django ORM is usable on its own - you can use \"settings.configure()\" to set up the database settings. That said, you'll have to do the stripping down and repackaging yourself, and you'll have to experiment with how much you can actually strip away. I'm sure you can ditch contrib/, forms/, template/, and probably several other unrelated pieces. The ORM definitely relies on conf/, and quite likely on core/ and util/ as well. A few quick greps through db/* should make it clear what's imported.\n", "You may be able to get a good idea of what is safe to strip out by checking which files don't have their access time updated when you run your application.\n" ]
[ 1, 1 ]
[]
[]
[ "deployment", "django", "python", "size", "sqlalchemy" ]
stackoverflow_0002126433_deployment_django_python_size_sqlalchemy.txt
Q: copying functions located in instances Here's some (simplified) code for what I'm trying to do: class a: pass class b: def printSelf(self): print self instOfA = a() instOfB = b() instOfA.printSelf = instOfB.printSelf instOfA.printSelf() <__main__.b instance at 0x0295D238> When I call instOfA.printSelf(), it prints self as being instOfB. But I want self to be instOfA when I call instOfA.printSelf(), and instOfB when I call instOfB.printSelf() How would I go about doing this without manually defining printSelf in class a? To those wondering why I would even want to do something like this, here's a longer example: #Acts as a template for aInstance. I would have several aInstances that have common rules, which are defined by an instance of the aDefinition class (though I'd have multiple rule sets too) class aDefinitionClass: def setInput(self, val): self.inputStr = val def checkInputByLength(self): return len(self.inputStr) < 5 def checkInputByCase(self): return self.inputStr == self.inputStr.upper() checkInput = checkInputByLength class aInstance(aDefinition): inputStr = "" def __init__(self, ruleDefinition): self.checkInput = ruleDefinition.checkInput aDef = aDefinitionClass() aDef.checkInput = aDef.checkInputByCase #Changing one of the rules. aInst = aInstance(aDef) aInst.setInput("ABC") aInst.checkInput() AttributeError: aDefinitionClass instance has no attribute 'inputStr' I realize it's a bit unusual, but I couldn't think of a different way of doing it. I'm effectively trying to subclass an instance. It'd look something like this if Python allowed it: class aInstance(aDef): inputStr = "" A: You can use the descriptor of the method to get a bound method: instOfA.printSelf = b.printSelf.__get__(instOfA) Of course, you can use __class__ if you don't know the type of instOfB: instOfA.printSelf = instOfB.__class__.printSelf.__get__(instOfA) If instOfA doesn't need the method stored, you can just pass in an instance of a as self: instOfB.printSelf.__func__(instOfA) A: The issue is that instOfB.printSelf is a bound method - the self variable is set to be instOfB when you create the object. What I would do, frankly, is just to set up the function slightly differently: class b: def printSelf(self, other): print other Then you simply do instOfA = a() instOfB = b() instOfA.printSelf = instOfB.printSelf instOfA.printSelf(instOfA) And if you want to do that with instOfB: instOfB.printSelf(instOfB) It's slightly uglier that way, but it's a bit cleaner and more obvious than Brian's solution (which works just fine as well). Edit: An even better way is to use descriptors (although this still requires modifying your code): class b: @staticmethod def printSelf(self): print self Though you still have to include the instance of the object when calling the function.
copying functions located in instances
Here's some (simplified) code for what I'm trying to do: class a: pass class b: def printSelf(self): print self instOfA = a() instOfB = b() instOfA.printSelf = instOfB.printSelf instOfA.printSelf() <__main__.b instance at 0x0295D238> When I call instOfA.printSelf(), it prints self as being instOfB. But I want self to be instOfA when I call instOfA.printSelf(), and instOfB when I call instOfB.printSelf() How would I go about doing this without manually defining printSelf in class a? To those wondering why I would even want to do something like this, here's a longer example: #Acts as a template for aInstance. I would have several aInstances that have common rules, which are defined by an instance of the aDefinition class (though I'd have multiple rule sets too) class aDefinitionClass: def setInput(self, val): self.inputStr = val def checkInputByLength(self): return len(self.inputStr) < 5 def checkInputByCase(self): return self.inputStr == self.inputStr.upper() checkInput = checkInputByLength class aInstance(aDefinition): inputStr = "" def __init__(self, ruleDefinition): self.checkInput = ruleDefinition.checkInput aDef = aDefinitionClass() aDef.checkInput = aDef.checkInputByCase #Changing one of the rules. aInst = aInstance(aDef) aInst.setInput("ABC") aInst.checkInput() AttributeError: aDefinitionClass instance has no attribute 'inputStr' I realize it's a bit unusual, but I couldn't think of a different way of doing it. I'm effectively trying to subclass an instance. It'd look something like this if Python allowed it: class aInstance(aDef): inputStr = ""
[ "You can use the descriptor of the method to get a bound method:\ninstOfA.printSelf = b.printSelf.__get__(instOfA)\n\nOf course, you can use __class__ if you don't know the type of instOfB:\ninstOfA.printSelf = instOfB.__class__.printSelf.__get__(instOfA)\n\nIf instOfA doesn't need the method stored, you can just pass in an instance of a as self:\ninstOfB.printSelf.__func__(instOfA)\n\n", "The issue is that instOfB.printSelf is a bound method - the self variable is set to be instOfB when you create the object. What I would do, frankly, is just to set up the function slightly differently:\nclass b:\n def printSelf(self, other):\n print other\n\nThen you simply do\ninstOfA = a()\ninstOfB = b()\ninstOfA.printSelf = instOfB.printSelf\ninstOfA.printSelf(instOfA)\n\nAnd if you want to do that with instOfB:\ninstOfB.printSelf(instOfB)\n\nIt's slightly uglier that way, but it's a bit cleaner and more obvious than Brian's solution (which works just fine as well).\nEdit:\nAn even better way is to use descriptors (although this still requires modifying your code):\nclass b:\n @staticmethod\n def printSelf(self):\n print self\n\nThough you still have to include the instance of the object when calling the function.\n" ]
[ 2, 0 ]
[]
[]
[ "function", "multiple_instances", "python", "self" ]
stackoverflow_0002129930_function_multiple_instances_python_self.txt
Q: Image embossing in Python with PIL -- adding depth, azimuth, etc I am trying to emboss an image using PIL. PIL provides a basic way to emboss an image ( using ImageFilter.EMBOSS). In image editing packages like GIMP, you can vary parameters like Azimuth, depth and elevation in this embossed image. How to do this with PIL? At the very least I want to adjust the "depth" of the embossed image. Update: I tried things suggested by Paul (modifying the filterargssuch as scale, offset and the matrix), but I couldn't change the "depth" effect. So still looking for an answer. Here is the comparison of embossing effect using PIL (left) and GIMP (right). The original picture is located here, http://www.linuxtopia.org/online_books/graphics_tools/gimp_advanced_guide/gimp_guide_node74.html. A: If you cannot achieve your goal by using or combination of operations (like rotating, then applying the EMBOSS filter, the re-rotating), (or enhancing the contrast then embossing) then you may resort to changing (or creating your own) filter matrix. Within ImageFilter.py you will find this class: ## # Embossing filter. class EMBOSS(BuiltinFilter): name = "Emboss" filterargs = (3, 3), 1, 128, ( -1, 0, 0, 0, 1, 0, 0, 0, 0 ) Placing a -1 in a different corner of the matrix will change the azimuth and making it a -2 may have the effect you are looking for. The matrix is applied pixel-by-pixel. Each element in the matrix corresponds to the current pixel and surrounding pixels; the center value representing the current pixel. The new, transformed current pixel will be created as a combination of all 9 pixels, weighted by the values in the matrix. For example, a matrix with all zeros and a 1 in the center will not change the image. Additional parameters are scale and offset. For the built-in EMBOSS, the values are 1 (scale) and 128 (offset). Changing these will change the overall strength of the result. From ImageFilter.py: # @keyparam scale Scale factor. If given, the result for each # pixel is divided by this value. The default is the sum # of the kernel weights. # @keyparam offset Offset. If given, this value is added to the # result, after it has been divided by the scale factor. As I am unfamiliar with the effects of GIMP's "depth" parameter, I cannot say which is most likely to do what you want. You can also make the matrix a different size. Replace the (3,3) with (5,5), and then create 25-element matrix. To make temporary changes to the filter without re-saving source code, just do this: ImageFilter.EMBOSS.filterargs=((3, 3), 1, 128, (-1, 0, 0, 0, 1, 0, 0, 0, 0)) Edit: (taking the NumPy approach) from PIL import Image import numpy # defining azimuth, elevation, and depth ele = numpy.pi/2.2 # radians azi = numpy.pi/4. # radians dep = 10. # (0-100) # get a B&W version of the image img = Image.open('daisy.jpg').convert('L') # get an array a = numpy.asarray(img).astype('float') # find the gradient grad = numpy.gradient(a) # (it is two arrays: grad_x and grad_y) grad_x, grad_y = grad # getting the unit incident ray gd = numpy.cos(ele) # length of projection of ray on ground plane dx = gd*numpy.cos(azi) dy = gd*numpy.sin(azi) dz = numpy.sin(ele) # adjusting the gradient by the "depth" factor # (I think this is how GIMP defines it) grad_x = grad_x*dep/100. grad_y = grad_y*dep/100. # finding the unit normal vectors for the image leng = numpy.sqrt(grad_x**2 + grad_y**2 + 1.) uni_x = grad_x/leng uni_y = grad_y/leng uni_z = 1./leng # take the dot product a2 = 255*(dx*uni_x + dy*uni_y + dz*uni_z) # avoid overflow a2 = a2.clip(0,255) # you must convert back to uint8 /before/ converting to an image img2 = Image.fromarray(a2.astype('uint8')) img2.save('daisy2.png') I hope this helps. I can see now why you were disappointed with PIL's results. Wolfram Mathworld is a good resource for a vector algebra refresher. Before After A: To increase the depth of an emboss filter, increase the radius of the filter's mask. Low depth: h = [[1, 0, 0] [0, 0, 0] [0, 0, -1]] versus high depth: h = [[1, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, -1]] To change the azimuth, place the nonzero coefficients at a different angle: h = [[0, 0, 1] [0, 0, 0] [-1, 0, 0]] I'm not really sure about elevation. You may need to change the nonzero coefficient values? I just know it needs to be a high-pass filter. In any case, to compute and display the image using a Scipy solution: import scipy.misc, scipy.signal im = scipy.misc.imread(filename) im_out = scipy.signal.convolve2d(im, h, 'same') scipy.misc.imshow(im_out) Hope this helps. EDIT: Okay, as Paul hinted with PIL, you can adjust filter parameters, or even define a completely new kernel. The scale and offset parameters have nothing to do with what you are looking for. The size of the filter is most important for adjusting depth. Upon further investigation, PIL does not let you change the filter size beyond 5x5. Seems strange. Therefore, you will not get as dramatic a change in depth as you probably expect. For total control, you may want to try the Scipy solution I and Paul mentioned earlier. Change the filter size to something ridiculous, like 21x21, and see if it makes the type of difference you want.
Image embossing in Python with PIL -- adding depth, azimuth, etc
I am trying to emboss an image using PIL. PIL provides a basic way to emboss an image ( using ImageFilter.EMBOSS). In image editing packages like GIMP, you can vary parameters like Azimuth, depth and elevation in this embossed image. How to do this with PIL? At the very least I want to adjust the "depth" of the embossed image. Update: I tried things suggested by Paul (modifying the filterargssuch as scale, offset and the matrix), but I couldn't change the "depth" effect. So still looking for an answer. Here is the comparison of embossing effect using PIL (left) and GIMP (right). The original picture is located here, http://www.linuxtopia.org/online_books/graphics_tools/gimp_advanced_guide/gimp_guide_node74.html.
[ "If you cannot achieve your goal by using or combination of operations (like rotating, then applying the EMBOSS filter, the re-rotating), (or enhancing the contrast then embossing) then you may resort to changing (or creating your own) filter matrix.\nWithin ImageFilter.py you will find this class:\n##\n# Embossing filter.\n\nclass EMBOSS(BuiltinFilter):\n name = \"Emboss\"\n filterargs = (3, 3), 1, 128, (\n -1, 0, 0,\n 0, 1, 0,\n 0, 0, 0\n )\n\nPlacing a -1 in a different corner of the matrix will change the azimuth and making it a -2 may have the effect you are looking for.\nThe matrix is applied pixel-by-pixel. Each element in the matrix corresponds to the current pixel and surrounding pixels; the center value representing the current pixel. The new, transformed current pixel will be created as a combination of all 9 pixels, weighted by the values in the matrix. For example, a matrix with all zeros and a 1 in the center will not change the image. \nAdditional parameters are scale and offset. For the built-in EMBOSS, the values are 1 (scale) and 128 (offset). Changing these will change the overall strength of the result.\nFrom ImageFilter.py:\n# @keyparam scale Scale factor. If given, the result for each\n# pixel is divided by this value. The default is the sum\n# of the kernel weights.\n# @keyparam offset Offset. If given, this value is added to the\n# result, after it has been divided by the scale factor.\n\nAs I am unfamiliar with the effects of GIMP's \"depth\" parameter, I cannot say which is most likely to do what you want.\nYou can also make the matrix a different size. Replace the (3,3) with (5,5), and then create 25-element matrix.\nTo make temporary changes to the filter without re-saving source code, just do this:\nImageFilter.EMBOSS.filterargs=((3, 3), 1, 128, (-1, 0, 0, 0, 1, 0, 0, 0, 0))\n\n\nEdit: (taking the NumPy approach)\nfrom PIL import Image\nimport numpy\n\n# defining azimuth, elevation, and depth\nele = numpy.pi/2.2 # radians\nazi = numpy.pi/4. # radians\ndep = 10. # (0-100)\n\n# get a B&W version of the image\nimg = Image.open('daisy.jpg').convert('L') \n# get an array\na = numpy.asarray(img).astype('float')\n# find the gradient\ngrad = numpy.gradient(a)\n# (it is two arrays: grad_x and grad_y)\ngrad_x, grad_y = grad\n# getting the unit incident ray\ngd = numpy.cos(ele) # length of projection of ray on ground plane\ndx = gd*numpy.cos(azi)\ndy = gd*numpy.sin(azi)\ndz = numpy.sin(ele)\n# adjusting the gradient by the \"depth\" factor\n# (I think this is how GIMP defines it)\ngrad_x = grad_x*dep/100.\ngrad_y = grad_y*dep/100.\n# finding the unit normal vectors for the image\nleng = numpy.sqrt(grad_x**2 + grad_y**2 + 1.)\nuni_x = grad_x/leng\nuni_y = grad_y/leng\nuni_z = 1./leng\n# take the dot product\na2 = 255*(dx*uni_x + dy*uni_y + dz*uni_z)\n# avoid overflow\na2 = a2.clip(0,255)\n# you must convert back to uint8 /before/ converting to an image\nimg2 = Image.fromarray(a2.astype('uint8')) \nimg2.save('daisy2.png')\n\nI hope this helps. I can see now why you were disappointed with PIL's results. Wolfram Mathworld is a good resource for a vector algebra refresher.\nBefore\n\nAfter\n\n", "To increase the depth of an emboss filter, increase the radius of the filter's mask. Low depth:\nh = [[1, 0, 0]\n [0, 0, 0]\n [0, 0, -1]]\n\nversus high depth:\nh = [[1, 0, 0, 0, 0, 0, 0]\n [0, 0, 0, 0, 0, 0, 0]\n [0, 0, 0, 0, 0, 0, 0]\n [0, 0, 0, 0, 0, 0, 0]\n [0, 0, 0, 0, 0, 0, 0]\n [0, 0, 0, 0, 0, 0, 0]\n [0, 0, 0, 0, 0, 0, -1]]\n\nTo change the azimuth, place the nonzero coefficients at a different angle:\nh = [[0, 0, 1]\n [0, 0, 0]\n [-1, 0, 0]]\n\nI'm not really sure about elevation. You may need to change the nonzero coefficient values? I just know it needs to be a high-pass filter.\nIn any case, to compute and display the image using a Scipy solution:\nimport scipy.misc, scipy.signal\nim = scipy.misc.imread(filename)\nim_out = scipy.signal.convolve2d(im, h, 'same')\nscipy.misc.imshow(im_out)\n\nHope this helps.\nEDIT: Okay, as Paul hinted with PIL, you can adjust filter parameters, or even define a completely new kernel. The scale and offset parameters have nothing to do with what you are looking for. The size of the filter is most important for adjusting depth.\nUpon further investigation, PIL does not let you change the filter size beyond 5x5. Seems strange. Therefore, you will not get as dramatic a change in depth as you probably expect.\nFor total control, you may want to try the Scipy solution I and Paul mentioned earlier. Change the filter size to something ridiculous, like 21x21, and see if it makes the type of difference you want.\n" ]
[ 10, 2 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0002034037_image_processing_python_python_imaging_library.txt
Q: Is it possible to narrow down the generated query in SQLAlchemy if it was created via query_property? I have another quick question about SQLAlchemy. If I have added a query_property [1] field in my SQLAlchemy Table class, is it possible to narrow down the SELECTed fields? Here is what I mean. Suppose my class Comments has this: class Comments: query = Session.query_property() ... Then if I do the following: >>> print Session.query(Comment) Then SQLAlchemy generates the following query which includes ALL the columns in my comments table: SELECT comments.comment_id AS comments_comment_id, comments.comment AS comments_comment ... more columns ... FROM comments But I want to narrow down this query and select only (let's say) the comment field as in the following construct: >>> print Session.query(Comment.comment) SELECT comments.comment AS comments_comment FROM comments Is it possible to do this via Comment.query construct? I tried the following but it didn't work: >>> print Comment.query(Comment.comment) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Query' object is not callable Please help me with an advice. Thanks, Boda Cydo. [1] http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.scoping.ScopedSession.query_property A: Try using query.values(Comment.comment). Note that it returns generator, not modified query, so this method should called last after applying all filters.
Is it possible to narrow down the generated query in SQLAlchemy if it was created via query_property?
I have another quick question about SQLAlchemy. If I have added a query_property [1] field in my SQLAlchemy Table class, is it possible to narrow down the SELECTed fields? Here is what I mean. Suppose my class Comments has this: class Comments: query = Session.query_property() ... Then if I do the following: >>> print Session.query(Comment) Then SQLAlchemy generates the following query which includes ALL the columns in my comments table: SELECT comments.comment_id AS comments_comment_id, comments.comment AS comments_comment ... more columns ... FROM comments But I want to narrow down this query and select only (let's say) the comment field as in the following construct: >>> print Session.query(Comment.comment) SELECT comments.comment AS comments_comment FROM comments Is it possible to do this via Comment.query construct? I tried the following but it didn't work: >>> print Comment.query(Comment.comment) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Query' object is not callable Please help me with an advice. Thanks, Boda Cydo. [1] http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.scoping.ScopedSession.query_property
[ "Try using query.values(Comment.comment). Note that it returns generator, not modified query, so this method should called last after applying all filters.\n" ]
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002128809_python_sql_sqlalchemy.txt
Q: Dynamically assign special methods to objects but not classes in Python I would like to do the following: class A(object): pass a = A() a.__int__ = lambda self: 3 i = int(a) Unfortunately, this throws: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: int() argument must be a string or a number, not 'A' This only seems to work if I assign the "special" method to the class A instead of an instance of it. Is there any recourse? One way I thought of was: def __int__(self): # No infinite loop if type(self).__int__.im_func != self.__int__.im_func: return self.__int__() raise NotImplementedError() But that looks rather ugly. Thanks. A: Python always looks up special methods on the class, not the instance (except in the old, aka "legacy", kind of classes -- they're deprecated and have gone away in Python 3, because of the quirky semantics that mostly comes from looking up special methods on the instance, so you really don't want to use them, believe me!-). To make a special class whose instances can have special methods independent from each other, you need to give each instance its own class -- then you can assign special methods on the instance's (individual) class without affecting other instances, and live happily ever after. If you want to make it look like you're assigning to an attribute the instance, while actually assigning to an attribute of the individualized per-instance class, you can get that with a special __setattr__ implementation, of course. Here's the simple case, with explicit "assign to class" syntax: >>> class Individualist(object): ... def __init__(self): ... self.__class__ = type('GottaBeMe', (self.__class__, object), {}) ... >>> a = Individualist() >>> b = Individualist() >>> a.__class__.__int__ = lambda self: 23 >>> b.__class__.__int__ = lambda self: 42 >>> int(a) 23 >>> int(b) 42 >>> and here's the fancy version, where you "make it look like" you're assigning the special method as an instance attribute (while behind the scene it still goes to the class of course): >>> class Sophisticated(Individualist): ... def __setattr__(self, n, v): ... if n[:2]=='__' and n[-2:]=='__' and n!='__class__': ... setattr(self.__class__, n, v) ... else: ... object.__setattr__(self, n, v) ... >>> c = Sophisticated() >>> d = Sophisticated() >>> c.__int__ = lambda self: 54 >>> d.__int__ = lambda self: 88 >>> int(c) 54 >>> int(d) 88 A: The only recourse that works for new-style classes is to have a method on the class that calls the attribute on the instance (if it exists): class A(object): def __int__(self): if '__int__' in self.__dict__: return self.__int__() raise ValueError a = A() a.__int__ = lambda: 3 int(a) Note that a.__int__ will not be a method (only functions that are attributes of the class will become methods) so self is not passed implicitly. A: I have nothing to add about the specifics of overriding __int__. But I noticed one thing about your sample that bears discussing. When you manually assign new methods to an object, "self" is not automatically passed in. I've modified your sample code to make my point clearer: class A(object): pass a = A() a.foo = lambda self: 3 a.foo() If you run this code, it throws an exception because you passed in 0 arguments to "foo" and 1 is required. If you remove the "self" it works fine. Python only automatically prepends "self" to the arguments if it had to look up the method in the class of the object and the function it found is a "normal" function. (Examples of "abnormal" functions: class methods, callable objects, bound method objects.) If you stick callables in to the object itself they won't automatically get "self". If you want self there, use a closure.
Dynamically assign special methods to objects but not classes in Python
I would like to do the following: class A(object): pass a = A() a.__int__ = lambda self: 3 i = int(a) Unfortunately, this throws: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: int() argument must be a string or a number, not 'A' This only seems to work if I assign the "special" method to the class A instead of an instance of it. Is there any recourse? One way I thought of was: def __int__(self): # No infinite loop if type(self).__int__.im_func != self.__int__.im_func: return self.__int__() raise NotImplementedError() But that looks rather ugly. Thanks.
[ "Python always looks up special methods on the class, not the instance (except in the old, aka \"legacy\", kind of classes -- they're deprecated and have gone away in Python 3, because of the quirky semantics that mostly comes from looking up special methods on the instance, so you really don't want to use them, believe me!-).\nTo make a special class whose instances can have special methods independent from each other, you need to give each instance its own class -- then you can assign special methods on the instance's (individual) class without affecting other instances, and live happily ever after. If you want to make it look like you're assigning to an attribute the instance, while actually assigning to an attribute of the individualized per-instance class, you can get that with a special __setattr__ implementation, of course.\nHere's the simple case, with explicit \"assign to class\" syntax:\n>>> class Individualist(object):\n... def __init__(self):\n... self.__class__ = type('GottaBeMe', (self.__class__, object), {})\n... \n>>> a = Individualist()\n>>> b = Individualist()\n>>> a.__class__.__int__ = lambda self: 23\n>>> b.__class__.__int__ = lambda self: 42\n>>> int(a)\n23\n>>> int(b)\n42\n>>> \n\nand here's the fancy version, where you \"make it look like\" you're assigning the special method as an instance attribute (while behind the scene it still goes to the class of course):\n>>> class Sophisticated(Individualist):\n... def __setattr__(self, n, v):\n... if n[:2]=='__' and n[-2:]=='__' and n!='__class__':\n... setattr(self.__class__, n, v)\n... else:\n... object.__setattr__(self, n, v)\n... \n>>> c = Sophisticated()\n>>> d = Sophisticated()\n>>> c.__int__ = lambda self: 54\n>>> d.__int__ = lambda self: 88\n>>> int(c)\n54\n>>> int(d)\n88\n\n", "The only recourse that works for new-style classes is to have a method on the class that calls the attribute on the instance (if it exists):\nclass A(object):\n def __int__(self):\n if '__int__' in self.__dict__:\n return self.__int__()\n raise ValueError\n\na = A()\na.__int__ = lambda: 3\nint(a)\n\nNote that a.__int__ will not be a method (only functions that are attributes of the class will become methods) so self is not passed implicitly.\n", "I have nothing to add about the specifics of overriding __int__. But I noticed one thing about your sample that bears discussing.\nWhen you manually assign new methods to an object, \"self\" is not automatically passed in. I've modified your sample code to make my point clearer:\nclass A(object): pass\n\na = A()\na.foo = lambda self: 3\n\na.foo()\n\nIf you run this code, it throws an exception because you passed in 0 arguments to \"foo\" and 1 is required. If you remove the \"self\" it works fine.\nPython only automatically prepends \"self\" to the arguments if it had to look up the method in the class of the object and the function it found is a \"normal\" function. (Examples of \"abnormal\" functions: class methods, callable objects, bound method objects.) If you stick callables in to the object itself they won't automatically get \"self\".\nIf you want self there, use a closure.\n" ]
[ 8, 2, 0 ]
[]
[]
[ "dynamic", "methods", "python" ]
stackoverflow_0002129643_dynamic_methods_python.txt
Q: Adding a string in front of a string for each item in a list in python I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change. n is my list of websites h is "http" for p in n: if p[0]!="h": p= h+ p else: continue return n when i return the list, it returns my original list and with no appending of the "http". Can somebody help me? A: This could also be done using list comprehension: n = [i if i.startswith('h') else 'http' + i for i in n] A: You need to reassign the list item -- strings are immutable, so += is making a new string, not mutating the old one. I.e.: for i, p in enumerate(n): if not p.startswith('h'): n[i] = 'http' + p A: n = [{True: '', False: 'http'}[p.startswith('h')] + p for p in n] Don't really do this. Although it does work. A: >>> n=["abcd","http","xyz"] >>> n=[x[:1]=='h' and x or 'http'+x for x in n] >>> n ['httpabcd', 'http', 'httpxyz']
Adding a string in front of a string for each item in a list in python
I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change. n is my list of websites h is "http" for p in n: if p[0]!="h": p= h+ p else: continue return n when i return the list, it returns my original list and with no appending of the "http". Can somebody help me?
[ "This could also be done using list comprehension:\nn = [i if i.startswith('h') else 'http' + i for i in n]\n\n", "You need to reassign the list item -- strings are immutable, so += is making a new string, not mutating the old one. I.e.:\nfor i, p in enumerate(n):\n if not p.startswith('h'):\n n[i] = 'http' + p\n\n", "n = [{True: '', False: 'http'}[p.startswith('h')] + p for p in n]\n\nDon't really do this. Although it does work.\n", ">>> n=[\"abcd\",\"http\",\"xyz\"]\n\n>>> n=[x[:1]=='h' and x or 'http'+x for x in n]\n\n>>> n\n['httpabcd', 'http', 'httpxyz']\n\n" ]
[ 15, 3, 0, 0 ]
[]
[]
[ "for_loop", "loops", "python", "string" ]
stackoverflow_0002130552_for_loop_loops_python_string.txt
Q: sqlite python insert I have asked similar question before , here is detailed explanation of what i'm trying to achieve I have two sqlite tables table1 - is standard table - has fields like server,id,status table2 - has fields like server,id,status,number,logfile Table2 is empty and Table1 has values. I'm trying to fill table2 with entries from table1. I can retrieve records from table1 ,but while trying to insert into table2 it fails.(but inserting a single field works) self.cursor.execute("select * from server_table1 limit (?)",t) #insert into server_process for record in self.server_pool_list: print "--->",record # geting output like ---> (u'cloud_sys1', u'free', u'192.168.1.111') self.cursor.execute("insert into server_table2(server,status,id) values (?,?,?)",(record[0],)(record[1],),(record[2],)); And also let me know how to produce more useful error messages when insert fails A: This statement is broken: self.cursor.execute("insert into server_table2(server,status,id) values (?,?,?)",(record[0],)(record[1],),(record[2],)); it should read: self.cursor.execute("insert into server_table2(server,status,id) values (?,?,?)",record[0:2]) And you might want to look into executemany as I think it could save you a ton of time.
sqlite python insert
I have asked similar question before , here is detailed explanation of what i'm trying to achieve I have two sqlite tables table1 - is standard table - has fields like server,id,status table2 - has fields like server,id,status,number,logfile Table2 is empty and Table1 has values. I'm trying to fill table2 with entries from table1. I can retrieve records from table1 ,but while trying to insert into table2 it fails.(but inserting a single field works) self.cursor.execute("select * from server_table1 limit (?)",t) #insert into server_process for record in self.server_pool_list: print "--->",record # geting output like ---> (u'cloud_sys1', u'free', u'192.168.1.111') self.cursor.execute("insert into server_table2(server,status,id) values (?,?,?)",(record[0],)(record[1],),(record[2],)); And also let me know how to produce more useful error messages when insert fails
[ "This statement is broken:\nself.cursor.execute(\"insert into server_table2(server,status,id) values (?,?,?)\",(record[0],)(record[1],),(record[2],));\n\nit should read:\nself.cursor.execute(\"insert into server_table2(server,status,id) values (?,?,?)\",record[0:2])\n\nAnd you might want to look into executemany as I think it could save you a ton of time.\n" ]
[ 3 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002130641_python_sqlite.txt
Q: django error in my code ,what does i do from django.core.management import setup_environ from register2 import settings setup_environ(settings) from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class AuthenticationRememberMeForm ( AuthenticationForm ): """ Subclass of Django ``AuthenticationForm`` which adds a remember me checkbox. """ remember_me = forms.BooleanField ( label = _( 'Remember Me' ), initial = False, required = False, ) print AuthenticationRememberMeForm.remember_me Traceback (most recent call last): File "D:\zjm_code\register2\b.py", line 26, in <module> print AuthenticationRememberMeForm['remember_me'] TypeError: 'DeclarativeFieldsMetaclass' object is unsubscriptable A: The django forms module uses a metaclass to facilitate declarative syntax for form fields. As a consequence, you should consider remember_me to be a field of your form instance, not a class attribute. So accessing the field as so makes sense: form = AuthenticationRememberMeForm() field_obj = form.fields['remember_me'] or, similarly, the value: form = AuthenticationRememberMeForm(data) if form.is_valid(): remember_me_value = form.cleaned_data['remember_me'] Obviously, django.forms is doing a bit of work behind the scenes to make this happen. If you want to understand how, check out the relevant code. If you just want to make your forms work, try to follow the usage outlined in the docs.
django error in my code ,what does i do
from django.core.management import setup_environ from register2 import settings setup_environ(settings) from django import forms from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ class AuthenticationRememberMeForm ( AuthenticationForm ): """ Subclass of Django ``AuthenticationForm`` which adds a remember me checkbox. """ remember_me = forms.BooleanField ( label = _( 'Remember Me' ), initial = False, required = False, ) print AuthenticationRememberMeForm.remember_me Traceback (most recent call last): File "D:\zjm_code\register2\b.py", line 26, in <module> print AuthenticationRememberMeForm['remember_me'] TypeError: 'DeclarativeFieldsMetaclass' object is unsubscriptable
[ "The django forms module uses a metaclass to facilitate declarative syntax for form fields. As a consequence, you should consider remember_me to be a field of your form instance, not a class attribute. So accessing the field as so makes sense:\nform = AuthenticationRememberMeForm()\nfield_obj = form.fields['remember_me']\n\nor, similarly, the value:\nform = AuthenticationRememberMeForm(data)\nif form.is_valid():\n remember_me_value = form.cleaned_data['remember_me']\n\nObviously, django.forms is doing a bit of work behind the scenes to make this happen. If you want to understand how, check out the relevant code. If you just want to make your forms work, try to follow the usage outlined in the docs.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002129992_django_python.txt
Q: Clojure Jython interop I was wondering if anyone has tried somehow calling Jython functions from within Clojure, and how you went about doing this if so. I have not used Jython, but I would imagine the Jython interpreter can be invoked in the same way as any other java code, and Python programs can be run within it. However I wonder if it would be possible to somehow call individual python functions from Clojure. Like I said, I have not tried this yet, so it might actually be straightforward and obvious. I'm just wondering if anyone has tried doing this. Thanks, Rob A: A note: I just realised that the question is specifically about calling Jython functions from Clojure and not about building a full-fledged Jython-Clojure interop solution... But! I've already produced a smallish write-up on my initial thoughts on the latter and I guess that's the logical next step anyway. I mean, how'd you go about using interesting Python packages without reasonably convenient access to Python classes? Writing Python functions to wrap method calls and the like is a possible idea... but rather a horrible one. So here goes anyway. For basic calling of Jython-executed Python functions from Clojure read the second paragraph below this point and the code snippets. Then read the rest for fun and unanticipated profit. I think that the experience would initially be far from seamless... In fact, my prediction would be that smoothing out the bumps could really be a royal pain. Still, I have a hunch it could actually be easier then calling into Jython from Java. Just a longish €0.02 from me... May someone more knowledgeable come and show me I don't know what I'm talking about. ;-) The first thing to notice is that Jython wraps everything in its own classes, all deriving from org.python.core.PyObject, doesn't bother to make Python callables Callable or Runnable etc. This might actually not be too much of a problem with some multimethod / macro wrappers. Python classes can be used from Java, but my (possibly flawed) understanding is that normally, when trying to act upon Jython-made instances of Python classes, Java code only sees the methods inherited from a Java base class or interface... Otherwise a specially formatted docstring (!) is required. Here's a link to the relevant page on the JythonWiki. (No idea how up-to-date it is.) The cool thing is, apparently a PyObjectDerived (an instance of a user-defined Python class) can be convinced to call its methods with the given arguments. So, with a dilligent wrapping effort, one might hope to be able to use somewhat bearable syntax to do it. In fact, let's see some code: ;; a handy instance of PythonInterpreter... (def python (org.python.util.PythonInterpreter.)) (.eval python "5") ; -> #<PyInteger 5> Well, things are wrapped. A fun Clojuresque unwrapper: (defmulti py-wrap class) ;; but let's not wrap if already a PyObject... (defmethod py-wrap org.python.core.PyObject [pyo] pyo) (defmethod py-wrap Integer [n] (org.python.core.PyInteger n)) (defmethod py-wrap Long [n] (org.python.core.PyLong n)) (defmethod py-wrap BigInteger [n] (org.python.core.PyLong n)) (defmethod py-wrap String [s] (org.python.core.PyString s)) And a counterpart to the above: (defmulti py-unwrap class) ;; if unsure, hope it's not a PyObject at all... (defmethod py-unwrap :default [x] x) (defmethod py-unwrap org.python.core.PyInteger [n] (.getValue n)) (defmethod py-unwrap org.python.core.PyString [s] (.toString s)) The functions: You can .__call__ them and you can ._jcall them. The latter option is somewhat more pleasing, as it accepts a Java array of regular Java objects, although it still returns a PyObject. The former takes an appropriate number of positional arguments which should already by PyObjects. I've no idea how to pass in keyword arguments... though Jython does that somehow, so there must be a way. Here's an ultra-basic helper for ._jcall-type calls: (defn py-call [pyf & args] (apply (fn [pyf & args] (._jcall pyf (into-array args))) (map #(if (string? %) (py-eval %) %) (cons pyf args))) You can .exec a string containing a Python definition of fact, then do (py-call "fact" 10) to get a #<PyInteger 5> back; unwrap if you feel like it. And so on and so forth... What I don't know is: What kind of effort would be needed to make this useful enough to interface interesting Clojure code with interesting Python code. Would providing a reasonable syntax for calls into Python necessitate doing anything really bad for performance.
Clojure Jython interop
I was wondering if anyone has tried somehow calling Jython functions from within Clojure, and how you went about doing this if so. I have not used Jython, but I would imagine the Jython interpreter can be invoked in the same way as any other java code, and Python programs can be run within it. However I wonder if it would be possible to somehow call individual python functions from Clojure. Like I said, I have not tried this yet, so it might actually be straightforward and obvious. I'm just wondering if anyone has tried doing this. Thanks, Rob
[ "A note: I just realised that the question is specifically about calling Jython functions from Clojure and not about building a full-fledged Jython-Clojure interop solution... But! I've already produced a smallish write-up on my initial thoughts on the latter and I guess that's the logical next step anyway. I mean, how'd you go about using interesting Python packages without reasonably convenient access to Python classes? Writing Python functions to wrap method calls and the like is a possible idea... but rather a horrible one. So here goes anyway.\nFor basic calling of Jython-executed Python functions from Clojure read the second paragraph below this point and the code snippets. Then read the rest for fun and unanticipated profit.\nI think that the experience would initially be far from seamless... In fact, my prediction would be that smoothing out the bumps could really be a royal pain. Still, I have a hunch it could actually be easier then calling into Jython from Java. Just a longish €0.02 from me... May someone more knowledgeable come and show me I don't know what I'm talking about. ;-)\nThe first thing to notice is that Jython wraps everything in its own classes, all deriving from org.python.core.PyObject, doesn't bother to make Python callables Callable or Runnable etc. This might actually not be too much of a problem with some multimethod / macro wrappers.\nPython classes can be used from Java, but my (possibly flawed) understanding is that normally, when trying to act upon Jython-made instances of Python classes, Java code only sees the methods inherited from a Java base class or interface... Otherwise a specially formatted docstring (!) is required. Here's a link to the relevant page on the JythonWiki. (No idea how up-to-date it is.) The cool thing is, apparently a PyObjectDerived (an instance of a user-defined Python class) can be convinced to call its methods with the given arguments. So, with a dilligent wrapping effort, one might hope to be able to use somewhat bearable syntax to do it.\nIn fact, let's see some code:\n;; a handy instance of PythonInterpreter...\n(def python (org.python.util.PythonInterpreter.))\n(.eval python \"5\")\n; -> #<PyInteger 5>\n\nWell, things are wrapped. A fun Clojuresque unwrapper:\n(defmulti py-wrap class)\n;; but let's not wrap if already a PyObject...\n(defmethod py-wrap org.python.core.PyObject [pyo] pyo)\n(defmethod py-wrap Integer [n] (org.python.core.PyInteger n))\n(defmethod py-wrap Long [n] (org.python.core.PyLong n))\n(defmethod py-wrap BigInteger [n] (org.python.core.PyLong n))\n(defmethod py-wrap String [s] (org.python.core.PyString s))\n\nAnd a counterpart to the above:\n(defmulti py-unwrap class)\n;; if unsure, hope it's not a PyObject at all...\n(defmethod py-unwrap :default [x] x)\n(defmethod py-unwrap org.python.core.PyInteger [n] (.getValue n))\n(defmethod py-unwrap org.python.core.PyString [s] (.toString s))\n\nThe functions: You can .__call__ them and you can ._jcall them. The latter option is somewhat more pleasing, as it accepts a Java array of regular Java objects, although it still returns a PyObject. The former takes an appropriate number of positional arguments which should already by PyObjects. I've no idea how to pass in keyword arguments... though Jython does that somehow, so there must be a way.\nHere's an ultra-basic helper for ._jcall-type calls:\n(defn py-call [pyf & args]\n (apply (fn [pyf & args] (._jcall pyf (into-array args)))\n (map #(if (string? %) (py-eval %) %)\n (cons pyf args)))\n\nYou can .exec a string containing a Python definition of fact, then do (py-call \"fact\" 10) to get a #<PyInteger 5> back; unwrap if you feel like it.\nAnd so on and so forth... What I don't know is:\n\nWhat kind of effort would be needed to make this useful enough to interface interesting Clojure code with interesting Python code.\nWould providing a reasonable syntax for calls into Python necessitate doing anything really bad for performance.\n\n" ]
[ 13 ]
[]
[]
[ "clojure", "interop", "jython", "lisp", "python" ]
stackoverflow_0002129253_clojure_interop_jython_lisp_python.txt
Q: Python Qt: Qprinter not defined I am trying to put the printer to run the output from an html document. Here is a small function to do that: def callPrinterHtml(self,document): self.printer = QPrinter() self.printer.setPageSize(QPrinter.Letter) dialog = QPrintDialog(self.printer, self) if dialog.exec_(): document.print_(self.printer) However the message pops up: self.printer = QPrinter() NameError: global name 'QPrinter' is not defined The printer definition is clearly inside the function. So, what am I missing here? All comments and suggestions are highly appreciated. A: Did you import the module that contains QPrinter? using an import directive? Is the module containing QPrinter in your python path?
Python Qt: Qprinter not defined
I am trying to put the printer to run the output from an html document. Here is a small function to do that: def callPrinterHtml(self,document): self.printer = QPrinter() self.printer.setPageSize(QPrinter.Letter) dialog = QPrintDialog(self.printer, self) if dialog.exec_(): document.print_(self.printer) However the message pops up: self.printer = QPrinter() NameError: global name 'QPrinter' is not defined The printer definition is clearly inside the function. So, what am I missing here? All comments and suggestions are highly appreciated.
[ "\nDid you import the module that contains QPrinter? using an import directive?\nIs the module containing QPrinter in your python path?\n\n" ]
[ 2 ]
[]
[]
[ "document", "html", "printing", "python", "qt" ]
stackoverflow_0002130895_document_html_printing_python_qt.txt
Q: How to get IUnknown from WDM driver CreateInstance In documentation (C++ example) LUnknown* pIUnknown = CreateInstance(slot); I try this >> import ctypes >> print type(ctypes.cdll.lcomp.CreateInstance(0)) <type 'int'> How to get IUNKNOWN and QueryInterface? A: I guess that accessing COM object with ctypes might be a bit difficult. I would recommend to have a look to win32com included in the windows extensions by Mark Hammond. You can start with this tutorial : http://www.boddie.org.uk/python/COM.html I hope it helps
How to get IUnknown from WDM driver CreateInstance
In documentation (C++ example) LUnknown* pIUnknown = CreateInstance(slot); I try this >> import ctypes >> print type(ctypes.cdll.lcomp.CreateInstance(0)) <type 'int'> How to get IUNKNOWN and QueryInterface?
[ "I guess that accessing COM object with ctypes might be a bit difficult. I would recommend to have a look to win32com included in the windows extensions by Mark Hammond.\nYou can start with this tutorial : http://www.boddie.org.uk/python/COM.html\nI hope it helps\n" ]
[ 0 ]
[]
[]
[ "com", "ctypes", "iunknown", "python" ]
stackoverflow_0002130559_com_ctypes_iunknown_python.txt
Q: Good language to develop a game server in? I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution? A: I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the "self" variable class references) and likewise just as easy to write C++ with clean syntax. If you're looking to deploy cross-platform and want to develop cross-platform as well, your best bet would probably be Java. It shorter development cycles than compiled languages like C and C++, but is higher performance (arguable, but I've always been anti-Java =P) than interpreted languages like Python and Perl and you don't have to work with unofficial implementations like Mono that may from time to time not support all of a language's features. A: I might be going slightly off-topic here, but the topic interests me as I have (hobby-wise) worked on quite a few game servers (MMORPG servers) - on others' code as well as mine. There is literature out there that will be of interest to you, drop me a note if you want some references. One thing that strikes me in your question is the want to serve a thousand users off a multithreaded application. From my humble experience, that does not work too well. :-) When you serve thousands of users you want a design that is as modular as possible, because one of your primary goals will be to keep the service as a whole up and running. Game servers tend to be rather complex, so there will be quite a few show-stopping bugs. Don't make your life miserable with a single point of failure (one application!). Instead, try to build multiple processes that can run on a multitude of hosts. My humble suggestion is the following: Make them independent, so a failing process will be irrelevant to the service. Make them small, so that the different parts of the service and how they interact are easy to grasp. Don't let users communicate with the gamelogic OR DB directly. Write a proxy - network stacks can and will show odd behaviour on different architectures when you have a multitude of users. Also make sure that you can later "clean"/filter what the proxies forward. Have a process that will only monitor other processes to see if they are still working properly, with the ability to restart parts. Make them distributable. Coordinate processes via TCP from the start or you will run into scalability problems. If you have large landscapes, consider means to dynamically divide load by dividing servers by geography. Don't have every backend process hold all the data in memory. I have ported a few such engines written in C++ and C# for hosts operating on Linux, FreeBSD and also Solaris (on an old UltraSparc IIi - yes, mono still runs there :). From my experience, C# is well fast enough, considering on what ancient hardware it operates on that sparc machine. The industry (as far as I know) tends to use a lot of C++ for the serving work and embeds scripting languages for the actual game logic. Ah, written too much already - way cool topic. A: Erlang is a language which is designed around concurrency and distribution over several servers, which is perfect for server software. Some links about Erlang and game-servers: http://www.devmaster.net/articles/mmo-scalable-server/ http://www.erlang-consulting.com/euc2005/mmog/mmog_in_erlang.htm I'm thinking of writing a game-server in Erlang myself. A: Speaking of pure performance, if you can run Java 6 you get about 1:1 performance when compared to optimized C++ (special cases notwithstanding, sometimes Java is faster, sometimes C++), the only problem you will have is of course stuff like database libraries, interconnectivity, scalability and such. I believe there's a variety of good to great solutions available to each of these problems but you won't find one language which would solve everything for you so I have to give you the age old advice: Choose the language you like and use that one. Oh, you're still reading this? :) Well, here's some extra pointers. EVE Online uses Python for its client and server side code and it's both bug-ridden and laggy as something I don't think I should write here so that'd be an example of how Python can be extended to (poorly) serve vast amounts of users. While Java has some good to great solutions to various related problems, it's really not the best language out there for vast amount of users; it doesn't scale well to extremes without tuning. However there's multi-VM solutions to this which somewhat fix the issue, for example Terracotta is said to do the job well. While C++ is rather cumbersome, it allows for such a low-level interaction with the system that you may actually find yourself doing things you thought you couldn't do. I'm thinking of something like dynamic per-core microclustering of runtime code blocks for "filling" every possible clock cycle of the processor as efficiently as possible for maximum performance and things like that. Mono is far behind the .NET VM/equivalent on Windows platforms so you wouldn't be able to use the latest and fanciest features of C#. However Windows XP (x64) OEM licenses are so laughably cheap at the moment that with small investment you could get a bunch of those and you could then run your code on the platform it was meant to be. And don't fall into the Linux hype, Linux is your saviour only if you really know how to use it and especially XP is pretty damn fast and stable nowadays. A: What kind of performance do you need? twisted is great for servers that need lots of concurrency, as is erlang. Either supports massive concurrency easily and has facilities for distributed computing. If you want to span more than one core in a python app, do the same thing you'd do if you wanted to span more than one machine — run more than one process. A: More details about this game server might help folks better answer your question. Is this a game server in the sense of something like a Counter Strike dedicated server which sits in the background and hosts multiplayer interactions or are you writing something which will be hosted on an HTTP webserver? Personally, if it were me, I'd be considering Java or C++. My personal preference and skill set would probably lead me towards C++ because I find Java clumsy to work with on both platforms (moreso on Linux) and don't have the confidence that C# is ready for prime-time in Linux yet. That said, you also need to have a pretty significant community hammering on said server before performance of your language is going to be so problematic. My advise would be to write it in whatever language you can at the moment and if your game grows to be of sufficient size, invest in a rewrite at that time. A: You could as well use Java and compile the code using GCC to a native executable. That way you don't get the performance hit of the bytecode engine (Yes, I know - Java out of the box is as fast as C++. It must be just me who always measures a factor 5 performance difference). The drawback is that the GCC Java-frontend does not support all of the Java 1.6 language features. Another choice would be to use your language of choice, get the code working first and then move the performance critical stuff into native code. Nearly all languages support binding to compiled libraries. That does not solve your "python does not multithread well"-problem, but it gives you more choices. A: The obvious candidates are Java and Erlang: Pro Java: ease of development good development environments stability, good stack traces well-known (easy to find experienced programmers, lots of libraries, books, ...) quite fast, mature VM Pro Erlang: proven in systems that need >99.9% uptime ability to have software updates without downtime scalable (not only multi-core, but also multi-machine) Contra Erlang: unfamiliar syntax and programming paradigm not so well known; hard to get experienced programmers for VM is not nearly as fast as java If your game server mainly works as a event dispatcher (with a bit of a database tucked on), Erlang's message-driven paradigm should be a good match. In this day and age, I would not consider using an unmanaged language (like C or C++); the marginal performance benefits simply aren't worth the hassle. A: It may depend a lot on what language your "game logic" (you may know this term as "business logic") is best expressed in. For example, if the game logic is best expressed in Python (or any other particular language) it might be best to just write it in Python and deal with the performance issues the hard way with either multi-threading or clustering. Even though it may cost you a lot of time to get the performance you want out of Python it will be less that the time it will take you to express "player A now casts a level 70 Spell of darkness in the radius of 7 units effecting all units that have spoken with player B and .... " in C++. Something else to consider is what protocol you will be using to communicate with the clients. If you have a complex binary protocol C++ may be easier (esp. if you already had experience doing it before) while a JSON (or similar) may be easier to parse in Python. Yes, i know C++ and python aren't languages you are limited to (or even considering) but i'm refer to them generally here. Probably comes down to what language you are the best at. A poorly written program which you hated writing will be worse that one written in a language you know and enjoy, even if the poorly written program was in an arguable more powerful language. A: You could also look at jRuby. It comes with lots of the benefits of Java and lots of the benefits of Ruby in one neat package. You'll have access to huge libraries from both languages. A: What are your objectives? Not the creation of the game itself, but why are you creating it? If you're doing it to learn a new language, then pick the one that seems the most interesting to you (i.e., the one you most want to learn). If it is for any other reason, then the best language will be the one that you already know best and enjoy using most. This will allow you to focus on working out the game logic and getting something up and running so that you can see progress and remain motivated to continue, rather than getting bogged down in details of the language you're using and losing interest. If your favorite language proves inadequate in some ways (too slow, not expressive enough, whatever), then you can rewrite the problem sections in a more suitable language when issues come up - and you won't know the best language to address the specific problems until you know what the problems end up being. Even if your chosen language proves entirely unsuitable for final production use and the whole thing has to be rewritten, it will give you a working prototype with tested game logic, which will make dealing with the new language far easier. A: You could take a look at Stackless Python. It's an alternative Python interpreter that provides greater support for concurrency. Both EVE Online's server and client software use Stackless Python. Disclaimer: I haven't used Stackless Python extensively myself, so I can't provide any first-hand accounts of its effectiveness. A: There is a pretty cool framework in development that addresses all your needs: Project Darkstar from Sun. So I'd say Java seems to be a good language for game server development :-) A: I know facebook uses a combination of Erlang and C++ for their chat engine. Whatever you decide, if you choose a combination of languages, check out facebook's thrift framework for cross language services deployment. They open sourced it about a year+ back: http://incubator.apache.org/thrift/
Good language to develop a game server in?
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out). I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development? Please help me and my picky self arrive on a solution. UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
[ "I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the \"self\" variable class references) and likewise just as easy to write C++ with clean syntax.\nIf you're looking to deploy cross-platform and want to develop cross-platform as well, your best bet would probably be Java. It shorter development cycles than compiled languages like C and C++, but is higher performance (arguable, but I've always been anti-Java =P) than interpreted languages like Python and Perl and you don't have to work with unofficial implementations like Mono that may from time to time not support all of a language's features.\n", "I might be going slightly off-topic here, but the topic interests me as I have (hobby-wise) worked on quite a few game servers (MMORPG servers) - on others' code as well as mine. There is literature out there that will be of interest to you, drop me a note if you want some references.\nOne thing that strikes me in your question is the want to serve a thousand users off a multithreaded application. From my humble experience, that does not work too well. :-) \nWhen you serve thousands of users you want a design that is as modular as possible, because one of your primary goals will be to keep the service as a whole up and running. Game servers tend to be rather complex, so there will be quite a few show-stopping bugs. Don't make your life miserable with a single point of failure (one application!).\nInstead, try to build multiple processes that can run on a multitude of hosts. My humble suggestion is the following:\n\nMake them independent, so a failing process will be irrelevant to the service.\nMake them small, so that the different parts of the service and how they interact are easy to grasp.\nDon't let users communicate with the gamelogic OR DB directly. Write a proxy - network stacks can and will show odd behaviour on different architectures when you have a multitude of users. Also make sure that you can later \"clean\"/filter what the proxies forward.\nHave a process that will only monitor other processes to see if they are still working properly, with the ability to restart parts.\nMake them distributable. Coordinate processes via TCP from the start or you will run into scalability problems.\nIf you have large landscapes, consider means to dynamically divide load by dividing servers by geography. Don't have every backend process hold all the data in memory.\n\nI have ported a few such engines written in C++ and C# for hosts operating on Linux, FreeBSD and also Solaris (on an old UltraSparc IIi - yes, mono still runs there :). From my experience, C# is well fast enough, considering on what ancient hardware it operates on that sparc machine.\nThe industry (as far as I know) tends to use a lot of C++ for the serving work and embeds scripting languages for the actual game logic. Ah, written too much already - way cool topic.\n", "Erlang is a language which is designed around concurrency and distribution over several servers, which is perfect for server software. Some links about Erlang and game-servers:\nhttp://www.devmaster.net/articles/mmo-scalable-server/\nhttp://www.erlang-consulting.com/euc2005/mmog/mmog_in_erlang.htm\nI'm thinking of writing a game-server in Erlang myself.\n", "Speaking of pure performance, if you can run Java 6 you get about 1:1 performance when compared to optimized C++ (special cases notwithstanding, sometimes Java is faster, sometimes C++), the only problem you will have is of course stuff like database libraries, interconnectivity, scalability and such. I believe there's a variety of good to great solutions available to each of these problems but you won't find one language which would solve everything for you so I have to give you the age old advice: Choose the language you like and use that one.\nOh, you're still reading this? :) Well, here's some extra pointers.\n\nEVE Online uses Python for its client and server side code and it's both bug-ridden and laggy as something I don't think I should write here so that'd be an example of how Python can be extended to (poorly) serve vast amounts of users.\nWhile Java has some good to great solutions to various related problems, it's really not the best language out there for vast amount of users; it doesn't scale well to extremes without tuning. However there's multi-VM solutions to this which somewhat fix the issue, for example Terracotta is said to do the job well.\nWhile C++ is rather cumbersome, it allows for such a low-level interaction with the system that you may actually find yourself doing things you thought you couldn't do. I'm thinking of something like dynamic per-core microclustering of runtime code blocks for \"filling\" every possible clock cycle of the processor as efficiently as possible for maximum performance and things like that.\nMono is far behind the .NET VM/equivalent on Windows platforms so you wouldn't be able to use the latest and fanciest features of C#. However Windows XP (x64) OEM licenses are so laughably cheap at the moment that with small investment you could get a bunch of those and you could then run your code on the platform it was meant to be. And don't fall into the Linux hype, Linux is your saviour only if you really know how to use it and especially XP is pretty damn fast and stable nowadays.\n\n", "What kind of performance do you need?\ntwisted is great for servers that need lots of concurrency, as is erlang. Either supports massive concurrency easily and has facilities for distributed computing.\nIf you want to span more than one core in a python app, do the same thing you'd do if you wanted to span more than one machine — run more than one process.\n", "More details about this game server might help folks better answer your question. Is this a game server in the sense of something like a Counter Strike dedicated server which sits in the background and hosts multiplayer interactions or are you writing something which will be hosted on an HTTP webserver?\nPersonally, if it were me, I'd be considering Java or C++. My personal preference and skill set would probably lead me towards C++ because I find Java clumsy to work with on both platforms (moreso on Linux) and don't have the confidence that C# is ready for prime-time in Linux yet.\nThat said, you also need to have a pretty significant community hammering on said server before performance of your language is going to be so problematic. My advise would be to write it in whatever language you can at the moment and if your game grows to be of sufficient size, invest in a rewrite at that time.\n", "You could as well use Java and compile the code using GCC to a native executable.\nThat way you don't get the performance hit of the bytecode engine (Yes, I know - Java out of the box is as fast as C++. It must be just me who always measures a factor 5 performance difference). The drawback is that the GCC Java-frontend does not support all of the Java 1.6 language features. \nAnother choice would be to use your language of choice, get the code working first and then move the performance critical stuff into native code. Nearly all languages support binding to compiled libraries.\nThat does not solve your \"python does not multithread well\"-problem, but it gives you more choices.\n", "The obvious candidates are Java and Erlang:\nPro Java:\n\nease of development\ngood development environments\nstability, good stack traces\nwell-known (easy to find experienced programmers, lots of libraries, books, ...)\nquite fast, mature VM\n\nPro Erlang:\n\nproven in systems that need >99.9% uptime\nability to have software updates without downtime\nscalable (not only multi-core, but also multi-machine)\n\nContra Erlang:\n\nunfamiliar syntax and programming paradigm\nnot so well known; hard to get experienced programmers for\nVM is not nearly as fast as java\n\nIf your game server mainly works as a event dispatcher (with a bit of a database tucked on), Erlang's message-driven paradigm should be a good match.\nIn this day and age, I would not consider using an unmanaged language (like C or C++); the marginal performance benefits simply aren't worth the hassle.\n", "It may depend a lot on what language your \"game logic\" (you may know this term as \"business logic\") is best expressed in. For example, if the game logic is best expressed in Python (or any other particular language) it might be best to just write it in Python and deal with the performance issues the hard way with either multi-threading or clustering. Even though it may cost you a lot of time to get the performance you want out of Python it will be less that the time it will take you to express \"player A now casts a level 70 Spell of darkness in the radius of 7 units effecting all units that have spoken with player B and .... \" in C++.\nSomething else to consider is what protocol you will be using to communicate with the clients. If you have a complex binary protocol C++ may be easier (esp. if you already had experience doing it before) while a JSON (or similar) may be easier to parse in Python. Yes, i know C++ and python aren't languages you are limited to (or even considering) but i'm refer to them generally here.\nProbably comes down to what language you are the best at. A poorly written program which you hated writing will be worse that one written in a language you know and enjoy, even if the poorly written program was in an arguable more powerful language.\n", "You could also look at jRuby. It comes with lots of the benefits of Java and lots of the benefits of Ruby in one neat package. You'll have access to huge libraries from both languages.\n", "What are your objectives? Not the creation of the game itself, but why are you creating it?\nIf you're doing it to learn a new language, then pick the one that seems the most interesting to you (i.e., the one you most want to learn).\nIf it is for any other reason, then the best language will be the one that you already know best and enjoy using most. This will allow you to focus on working out the game logic and getting something up and running so that you can see progress and remain motivated to continue, rather than getting bogged down in details of the language you're using and losing interest.\nIf your favorite language proves inadequate in some ways (too slow, not expressive enough, whatever), then you can rewrite the problem sections in a more suitable language when issues come up - and you won't know the best language to address the specific problems until you know what the problems end up being. Even if your chosen language proves entirely unsuitable for final production use and the whole thing has to be rewritten, it will give you a working prototype with tested game logic, which will make dealing with the new language far easier.\n", "You could take a look at Stackless Python. It's an alternative Python interpreter that provides greater support for concurrency. Both EVE Online's server and client software use Stackless Python.\nDisclaimer: I haven't used Stackless Python extensively myself, so I can't provide any first-hand accounts of its effectiveness.\n", "There is a pretty cool framework in development that addresses all your needs:\nProject Darkstar from Sun. So I'd say Java seems to be a good language for game server development :-)\n", "I know facebook uses a combination of Erlang and C++ for their chat engine. \nWhatever you decide, if you choose a combination of languages, check out facebook's thrift framework for cross language services deployment. They open sourced it about a year+ back:\nhttp://incubator.apache.org/thrift/ \n" ]
[ 20, 18, 17, 9, 7, 3, 2, 2, 1, 0, 0, 0, 0, 0 ]
[ "C++ and Java are quite slow compared to C. The language should be a tool but not a crutch.\n" ]
[ -1 ]
[ "c#", "java", "networking", "python" ]
stackoverflow_0000392624_c#_java_networking_python.txt
Q: How can I convert a digraph to an undirected graph in networkx? I am using the networkx package. Is there a function in networkx which can do the task for me? A: I found the function http://networkx.lanl.gov/reference/generated/networkx.DiGraph.to_undirected.html?highlight=digraph
How can I convert a digraph to an undirected graph in networkx?
I am using the networkx package. Is there a function in networkx which can do the task for me?
[ "I found the function \nhttp://networkx.lanl.gov/reference/generated/networkx.DiGraph.to_undirected.html?highlight=digraph\n" ]
[ 5 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002131005_networkx_python.txt
Q: Classes, methods, and polymorphism in Python I made a module prototype with the aim of building complex timer schedules in python. The class prototypes emulate Timer objects, each with their waiting times, Repeat objects that group Timer and other Repeat objects, and a Schedule class, just for holding a whole construction or Timers and Repeat instances. The construction can be as complex as needed and needs to be flexible. Each of these three classes has a .run() method, permitting to go through the whole schedule. Whatever the Class, the .run() method either runs a timer, a repeat group for a certain number of iterations, or a schedule. Is this polymorphism-oriented approach sound or silly? What are other appropriate approaches I should consider to build such a versatile utility that permits to put all building blocks together in as complex a way as desired with simplicity? Thanks! Here is the module code: ##################### ## Importing modules from time import time, sleep ##################### ## Class definitions class Timer: """ Timer object with duration. """ def __init__(self, duration): self.duration = duration def run(self): print "Waiting for %i seconds" % self.duration wait(self.duration) chime() class Repeat: """ Repeat grouped objects for a certain number of repetitions. """ def __init__(self, objects=[], rep=1): self.rep = rep self.objects = objects def run(self): print "Repeating group for %i times" % self.rep for i in xrange(self.rep): for group in self.objects: group.run() class Schedule: """ Groups of timers and repetitions. Maybe redundant with class Repeat. """ def __init__(self, schedule=[]): self.schedule = schedule def run(self): for group in self.schedule: group.run() ######################## ## Function definitions def wait(duration): """ Wait a certain number of seconds. """ time_end = time() + float(duration) #uncoment for minutes# * 60 time_diff = time_end - time() while time_diff > 0: sleep(1) time_diff = time_end - time() def chime(): print "Ding!" A: The duck-typing-based approach is fine. If you want to be able to check if a given class is supposed to run in your framework, you can use Abstract Base Classes (needs Python 2.6). PEP 3119 states: [...] there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking 'is this object a mutable sequence container?', one can look for a base class of 'list', or one can look for a method named 'getitem'. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positives.[...] This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object's inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance(), and the presence of a particular ABC means that the test has passed. You can implement an ABC and use isinstance or issubclass to test whether classes or instances are written for your framework: from abc import ABCMeta, abstractmethod class Runnable(object): __metaclass__ = ABCMeta @abstractmethod def run(self): raise NotImplementedError class Schedule(Runnable): ... The important point is that it is also possible to register other classes (on which you might have no control, because you did not write them) as runnables, and the isinstance and issubclass methods will reflect that: >>> issubclass(SomeOtherClass, Runnable) False >>> Runnable.register(SomeOtherClass) >>> issubclass(SomeOtherClass, Runnable) True A: This is called duck typing and it's used in Python all the time. A: It is indeed used all the time and is perfectly fine. If you want to be really careful, you can use hasattr to make sure the object you expect to have a run method actually has one fairly early on. That helps makes sure exceptions get thrown as close to the point of error as possible. But otherwise, it's fine and done frequently.
Classes, methods, and polymorphism in Python
I made a module prototype with the aim of building complex timer schedules in python. The class prototypes emulate Timer objects, each with their waiting times, Repeat objects that group Timer and other Repeat objects, and a Schedule class, just for holding a whole construction or Timers and Repeat instances. The construction can be as complex as needed and needs to be flexible. Each of these three classes has a .run() method, permitting to go through the whole schedule. Whatever the Class, the .run() method either runs a timer, a repeat group for a certain number of iterations, or a schedule. Is this polymorphism-oriented approach sound or silly? What are other appropriate approaches I should consider to build such a versatile utility that permits to put all building blocks together in as complex a way as desired with simplicity? Thanks! Here is the module code: ##################### ## Importing modules from time import time, sleep ##################### ## Class definitions class Timer: """ Timer object with duration. """ def __init__(self, duration): self.duration = duration def run(self): print "Waiting for %i seconds" % self.duration wait(self.duration) chime() class Repeat: """ Repeat grouped objects for a certain number of repetitions. """ def __init__(self, objects=[], rep=1): self.rep = rep self.objects = objects def run(self): print "Repeating group for %i times" % self.rep for i in xrange(self.rep): for group in self.objects: group.run() class Schedule: """ Groups of timers and repetitions. Maybe redundant with class Repeat. """ def __init__(self, schedule=[]): self.schedule = schedule def run(self): for group in self.schedule: group.run() ######################## ## Function definitions def wait(duration): """ Wait a certain number of seconds. """ time_end = time() + float(duration) #uncoment for minutes# * 60 time_diff = time_end - time() while time_diff > 0: sleep(1) time_diff = time_end - time() def chime(): print "Ding!"
[ "The duck-typing-based approach is fine. If you want to be able to check if a given class is supposed to run in your framework, you can use Abstract Base Classes (needs Python 2.6). PEP 3119 states:\n\n[...] there are many different ways to test whether an object conforms to a particular protocol or not. For example, if asking 'is this object a mutable sequence container?', one can look for a base class of 'list', or one can look for a method named 'getitem'. But note that although these tests may seem obvious, neither of them are correct, as one generates false negatives, and the other false positives.[...] This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object's inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance(), and the presence of a particular ABC means that the test has passed.\n\nYou can implement an ABC and use isinstance or issubclass to test whether classes or instances are written for your framework:\nfrom abc import ABCMeta, abstractmethod\n\nclass Runnable(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def run(self):\n raise NotImplementedError\n\n class Schedule(Runnable):\n ...\n\nThe important point is that it is also possible to register other classes (on which you might have no control, because you did not write them) as runnables, and the isinstance and issubclass methods will reflect that:\n >>> issubclass(SomeOtherClass, Runnable)\n False\n >>> Runnable.register(SomeOtherClass)\n >>> issubclass(SomeOtherClass, Runnable)\n True\n\n", "This is called duck typing and it's used in Python all the time.\n", "It is indeed used all the time and is perfectly fine. If you want to be really careful, you can use hasattr to make sure the object you expect to have a run method actually has one fairly early on. That helps makes sure exceptions get thrown as close to the point of error as possible.\nBut otherwise, it's fine and done frequently.\n" ]
[ 6, 3, 2 ]
[]
[]
[ "oop", "polymorphism", "python", "timer" ]
stackoverflow_0002129891_oop_polymorphism_python_timer.txt
Q: Google App Engine (python) authorization web services /third party client I have a google app engine project and i want to make my REST API available to third parties. Like twitter API. Twitter requests the user and password to be sent so thet they can be authorized - can i do this with google user accounts? I have read somewhere on this site this is not a prefered method as their credentials are entered into a thirdparty app/passed etc. I dont want to over complicate and redirect them to a googles own login/captcha and so on. I have seen a implementation of this - also with desktop/phone/widgets this may not even work. Is a solution for a third party apps to call my service - the app calls a page on my site (which asks for login - i just add login rights) the user then logs in and my app then creates a long token that is then passed back to third party app which then stores this in their own repository and pass it as a Token arg in the post/put/delete request. My REST service then checks the token and against a lookup (token|user key) pairs and allows/rejects the method call. I could also ask the app for their domain? and store this too. I guess i can read the url of the request on the REST service and check they match etc? Is this a reasonable solution or am i living in the 90's? A: OAuth was created with this situation in mind. It's a specification for the sort of auth-token scheme you just described, and it's reasonably widespread these days. For balance, see this recent StackOverflow thread.
Google App Engine (python) authorization web services /third party client
I have a google app engine project and i want to make my REST API available to third parties. Like twitter API. Twitter requests the user and password to be sent so thet they can be authorized - can i do this with google user accounts? I have read somewhere on this site this is not a prefered method as their credentials are entered into a thirdparty app/passed etc. I dont want to over complicate and redirect them to a googles own login/captcha and so on. I have seen a implementation of this - also with desktop/phone/widgets this may not even work. Is a solution for a third party apps to call my service - the app calls a page on my site (which asks for login - i just add login rights) the user then logs in and my app then creates a long token that is then passed back to third party app which then stores this in their own repository and pass it as a Token arg in the post/put/delete request. My REST service then checks the token and against a lookup (token|user key) pairs and allows/rejects the method call. I could also ask the app for their domain? and store this too. I guess i can read the url of the request on the REST service and check they match etc? Is this a reasonable solution or am i living in the 90's?
[ "OAuth was created with this situation in mind. It's a specification for the sort of auth-token scheme you just described, and it's reasonably widespread these days.\nFor balance, see this recent StackOverflow thread.\n" ]
[ 1 ]
[]
[]
[ "authorization", "google_app_engine", "python", "rest" ]
stackoverflow_0002130899_authorization_google_app_engine_python_rest.txt
Q: posix_memalign within python I cannot seem to figure it out why the following does not work import ctypes from ctypes.util import find_library libc = ctypes.CDLL(find_library('c')) userpointer = ctypes.c_void_p sizeimage = 320*240*2 if libc.posix_memalign(userpointer, libc.getpagesize(), sizeimage) != 0: raise Exception('ENOMEM') I am trying to capture using v4l2. I cannot allocate memory. I tried passing ctypes.addressof(userpointer) I tried to cast userpointer to c_void_p but still nothing. A: You have two problems in your code: you make userpointer the ctypes.c_void_p type rather than an instance of it, and you're passing the void* that is userpointer to posix_memalign directly, instead of the void** that posix_memalign requires. The following will do what you want: import ctypes from ctypes.util import find_library libc = ctypes.CDLL(find_library('c')) userpointer = ctypes.c_void_p() sizeimage = 320*240*2 if libc.posix_memalign(ctypes.byref(userpointer), libc.getpagesize(), sizeimage) != 0: raise Exception('ENOMEM')
posix_memalign within python
I cannot seem to figure it out why the following does not work import ctypes from ctypes.util import find_library libc = ctypes.CDLL(find_library('c')) userpointer = ctypes.c_void_p sizeimage = 320*240*2 if libc.posix_memalign(userpointer, libc.getpagesize(), sizeimage) != 0: raise Exception('ENOMEM') I am trying to capture using v4l2. I cannot allocate memory. I tried passing ctypes.addressof(userpointer) I tried to cast userpointer to c_void_p but still nothing.
[ "You have two problems in your code: you make userpointer the ctypes.c_void_p type rather than an instance of it, and you're passing the void* that is userpointer to posix_memalign directly, instead of the void** that posix_memalign requires. The following will do what you want:\nimport ctypes\nfrom ctypes.util import find_library\nlibc = ctypes.CDLL(find_library('c'))\n\nuserpointer = ctypes.c_void_p()\nsizeimage = 320*240*2\n\nif libc.posix_memalign(ctypes.byref(userpointer), libc.getpagesize(),\n sizeimage) != 0:\n raise Exception('ENOMEM')\n\n" ]
[ 1 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0002131946_ctypes_python.txt
Q: saving python variable to .mat file with scipy.io.savemat Here is my python code. >>import numpy as np >>import scipy.io >>exon = [ np.array([[1, 2], [3, 4], [5, 6]]), np.array([[7, 8], [9, 10]]) ] >>obj_arr = np.zeros((2,), dtype=np.object) >>obj_arr[0] = exon[0] >>obj_arr[1] = exon[1] >>scipy.io.savemat('/tmp/out.mat', mdict={'exon': obj_arr}, format='5') But I am getting an error message Traceback (most recent call last): File "save_mat.py", line 12, in <module> scipy.io.savemat('out.mat', mdict={'exon':obj_arr}, format='5') TypeError: savemat() got an unexpected keyword argument 'format' Many thanks for helping to figure out the problem. Vipin T S A: Looks like your scipy.io.savemat() doesn't take a 'format' keyword. Looks like it was added in SciPy 0.7, perhaps you need to upgrade?
saving python variable to .mat file with scipy.io.savemat
Here is my python code. >>import numpy as np >>import scipy.io >>exon = [ np.array([[1, 2], [3, 4], [5, 6]]), np.array([[7, 8], [9, 10]]) ] >>obj_arr = np.zeros((2,), dtype=np.object) >>obj_arr[0] = exon[0] >>obj_arr[1] = exon[1] >>scipy.io.savemat('/tmp/out.mat', mdict={'exon': obj_arr}, format='5') But I am getting an error message Traceback (most recent call last): File "save_mat.py", line 12, in <module> scipy.io.savemat('out.mat', mdict={'exon':obj_arr}, format='5') TypeError: savemat() got an unexpected keyword argument 'format' Many thanks for helping to figure out the problem. Vipin T S
[ "Looks like your scipy.io.savemat() doesn't take a 'format' keyword. Looks like it was added in SciPy 0.7, perhaps you need to upgrade?\n" ]
[ 3 ]
[]
[]
[ "mat_file", "python", "scipy", "typeerror" ]
stackoverflow_0002132106_mat_file_python_scipy_typeerror.txt
Q: Python: Best method to reload class in XMLRPC Server I have a multit-threaded xmlrpc service running which stores a huge amount of data ~2G in memory. Currently, if I want to update a method the server exposes I have to restart the service. The problem here is that if I restart the service it needs to load all of the data it had in memory back into memory by using a database or using shelved data. I am using methods like this: xmlrpc_getUser(self, uid): return self.users[uid] What I was hoping I could do is just use these methods as a proxy to another module, so my methods would look more like this xmlrpc_getUser(self, uid): return self.proxy.getUser(uid) This way I could update code on the development server then simply copy my update proxy module to the production server without the need for a restart. I tried adding import service_proxy to the constructor of my xmlrpc service controller, but I think the module is cached and won't reload. Is there a good way to do this? Thanks. A: You could use the reload method. You would need to write some code to check the last modified time of the modules file. A: If reload doesn't work, you could try twisted.python.rebuild; your application need not be written in Twisted to use this twisted.python utility. I also recently saw this livecoding thing ("a code reloading library for Python"), but it talks about a custom module system and I don't know what's going on there.
Python: Best method to reload class in XMLRPC Server
I have a multit-threaded xmlrpc service running which stores a huge amount of data ~2G in memory. Currently, if I want to update a method the server exposes I have to restart the service. The problem here is that if I restart the service it needs to load all of the data it had in memory back into memory by using a database or using shelved data. I am using methods like this: xmlrpc_getUser(self, uid): return self.users[uid] What I was hoping I could do is just use these methods as a proxy to another module, so my methods would look more like this xmlrpc_getUser(self, uid): return self.proxy.getUser(uid) This way I could update code on the development server then simply copy my update proxy module to the production server without the need for a restart. I tried adding import service_proxy to the constructor of my xmlrpc service controller, but I think the module is cached and won't reload. Is there a good way to do this? Thanks.
[ "You could use the reload method. You would need to write some code to check the last modified time of the modules file.\n", "If reload doesn't work, you could try twisted.python.rebuild; your application need not be written in Twisted to use this twisted.python utility.\nI also recently saw this livecoding thing (\"a code reloading library for Python\"), but it talks about a custom module system and I don't know what's going on there.\n" ]
[ 4, 1 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0002064935_python_xml_rpc.txt
Q: Function called three times when in facebook? I'm using the following code to add one to two values in case the user wins a challege. def challengewin(request): uid = 1313693 tempuser = User.objects.get(id=uid) tempuser.challengeswon = tempuser.challengeswon + 1 tempuser.silver = tempuser.silver + 1 tempuser.save() return HttpResponse() this works fine if I am working outside the facebook canvas page, inside the canvas page 3 is added instead of 1 everytime. Any Ideas? A: I would guess that the code you have included is not the culprit. Have you confirmed that challengewin(request); is not being called 3 times?
Function called three times when in facebook?
I'm using the following code to add one to two values in case the user wins a challege. def challengewin(request): uid = 1313693 tempuser = User.objects.get(id=uid) tempuser.challengeswon = tempuser.challengeswon + 1 tempuser.silver = tempuser.silver + 1 tempuser.save() return HttpResponse() this works fine if I am working outside the facebook canvas page, inside the canvas page 3 is added instead of 1 everytime. Any Ideas?
[ "I would guess that the code you have included is not the culprit.\nHave you confirmed that challengewin(request); is not being called 3 times?\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0002132215_facebook_python.txt
Q: Using Python like PHP in Apache/Windows I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but I'm confused about it: This is a sample configuration I found for web.py: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias /appname /var/www/webpy-app/code.py/ Alias /appname/static /var/www/webpy-app/static/ AddType text/html .py <Directory /var/www/webpy-app/> Order deny,allow Allow from all </Directory> So... I understand I have to configure my web server to point to the python application? Isn't there a way to use it like PHP, where, when you request a .py file, Python interprets it? How can I get my web server to the very basic state, where I can upload a file containing print "Hello World", request it, and have it say "Hello World"? A: Most similar to the PHP model is perhaps Python Server Pages, PSP. mod_python has a PSP handler. The files you create look like this: <html> <body> <% for n in range(3): # This indent will persist %> <p>This paragraph will be repeated 3 times.</p> <% # This line will cause the block to end %> This line will only be shown once. </body> </html> Spyce takes the PSP model a step further, as does Webware for Python. This article is a good introduction to mod_python's PSP. A: I think you can use mod_cgi with apache and put in the URL of an accessible python file, with the first line of the script #!/usr/bin/python however this is a VERY inefficient way of accessing the python code because apache has to reload python every time the page is accessed. Ok for a one-off maintenance script only you call every now and then, but not suitable for active content accessed by users. Edit: I didn't realise you were on Windows. Something similar should be possible. Try googling python apache cgi. Edit: If you have apache working in cgi mode, you don't need to restart it every time. If the script is present and executable at the URL path given it will run. If it isn't then you'll get a 404 page not found error Edit: I did a very quick Google search for 'python cgi' and found these slides from ten years ago by Python's creator. They document an obsolete version of the languange but the slides from 41 onwards may be useful to you. Like I say, people have moved away from scripting web applications using this method but if your requirements are simple it will still work. http://legacy.python.org/doc/essays/ppt/sd99east/index.htm Edit: The best approach depends on what you are trying to do. Using a framework that handles the serving for you may be useful. I can recommend Web2py as very capable, secure framework that would allow you to write scripts and add them dynamically. It has a windows version that includes a simple web server, or you can configure apache as well. As everything is included you could be up and running within minutes if you read the introductory information. If you've not used web frameworks before and aren't familiar with lanugage such as "model view controller" then don't be put off. http://www.web2py.com/ A: I don't think WSGI/mod_wsgi is compatible with what you want to do-- a WSGI application generally takes over URL parsing, which makes it incompatible with your "works like PHP" requirement. If you don't want to use CGI, I think mod_python's Publisher is closer to what you want: http://modpython.org/live/mod_python-3.3.1/doc-html/tut-pub.html A: Contrary to what others say, you can get mostly where you want. StackOverflow is however not a very good place to get an explanation of what to do. Instead, you would in this case be better off going over to the official mod_wsgi mailing list on Google Groups at: http://groups.google.com/group/modwsgi You can also get some ideas of the path required by reading: http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines For something truly akin to how PHP works in respect or URL mapping, you don't want to be using WSGIScriptAlias and instead should use the AddHandler method of designating files as being WSGI script files. I would also advise reading: http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode That latter isn't the whole picture though in respecting of code reloading as there are changes in mod_wsgi 3.X which aren't documented in there which add even more options for automatic source code reloading. Overall, although you could follow the PHP model of doing things, I would very much suggest a high level Python web framework. That in conjunction with daemon mode feature of mod_wsgi for triggering reloads by touching the WSGI script file is generally more than enough and more predictable. A: Wandering a bit afield from your original question, but trying to answer some of what's come up in reply to sparklewhiskers: For an example of how WSGI works in a shared hosting environment, see these pages on Passenger's WSGI support at A Small Orange and Dreamhost, in which the necessary server configuration is done through a .htaccess file or a web panel. I think Python hosting on shared servers is still relatively uncommon; I expect more Python applications are run on some sort of VPS or Google AppEngine. Some Python webapps aren't launched from an apache or nginx module at all, they have their own persistent server, and if you want to have them on the same server as something else you configure your other server to proxy to your Python server. But that's another story entirely.
Using Python like PHP in Apache/Windows
I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but I'm confused about it: This is a sample configuration I found for web.py: LoadModule wsgi_module modules/mod_wsgi.so WSGIScriptAlias /appname /var/www/webpy-app/code.py/ Alias /appname/static /var/www/webpy-app/static/ AddType text/html .py <Directory /var/www/webpy-app/> Order deny,allow Allow from all </Directory> So... I understand I have to configure my web server to point to the python application? Isn't there a way to use it like PHP, where, when you request a .py file, Python interprets it? How can I get my web server to the very basic state, where I can upload a file containing print "Hello World", request it, and have it say "Hello World"?
[ "Most similar to the PHP model is perhaps Python Server Pages, PSP.\nmod_python has a PSP handler. The files you create look like this:\n<html>\n<body>\n<%\nfor n in range(3):\n # This indent will persist\n%>\n<p>This paragraph will be \nrepeated 3 times.</p>\n<%\n# This line will cause the block to end\n%>\nThis line will only be shown once.\n</body>\n</html>\n\nSpyce takes the PSP model a step further, as does Webware for Python.\nThis article is a good introduction to mod_python's PSP.\n", "I think you can use mod_cgi with apache and put in the URL of an accessible python file, with the first line of the script\n#!/usr/bin/python\n\nhowever this is a VERY inefficient way of accessing the python code because apache has to reload python every time the page is accessed. Ok for a one-off maintenance script only you call every now and then, but not suitable for active content accessed by users.\nEdit: I didn't realise you were on Windows. Something similar should be possible. Try googling python apache cgi. \nEdit: If you have apache working in cgi mode, you don't need to restart it every time. If the script is present and executable at the URL path given it will run. If it isn't then you'll get a 404 page not found error\nEdit: I did a very quick Google search for 'python cgi' and found these slides from ten years ago by Python's creator. They document an obsolete version of the languange but the slides from 41 onwards may be useful to you. Like I say, people have moved away from scripting web applications using this method but if your requirements are simple it will still work. http://legacy.python.org/doc/essays/ppt/sd99east/index.htm\nEdit: The best approach depends on what you are trying to do. Using a framework that handles the serving for you may be useful. I can recommend Web2py as very capable, secure framework that would allow you to write scripts and add them dynamically. It has a windows version that includes a simple web server, or you can configure apache as well. As everything is included you could be up and running within minutes if you read the introductory information. If you've not used web frameworks before and aren't familiar with lanugage such as \"model view controller\" then don't be put off. http://www.web2py.com/ \n", "I don't think WSGI/mod_wsgi is compatible with what you want to do-- a WSGI application generally takes over URL parsing, which makes it incompatible with your \"works like PHP\" requirement.\nIf you don't want to use CGI, I think mod_python's Publisher is closer to what you want:\nhttp://modpython.org/live/mod_python-3.3.1/doc-html/tut-pub.html\n", "Contrary to what others say, you can get mostly where you want. StackOverflow is however not a very good place to get an explanation of what to do. Instead, you would in this case be better off going over to the official mod_wsgi mailing list on Google Groups at:\nhttp://groups.google.com/group/modwsgi\nYou can also get some ideas of the path required by reading:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines\nFor something truly akin to how PHP works in respect or URL mapping, you don't want to be using WSGIScriptAlias and instead should use the AddHandler method of designating files as being WSGI script files.\nI would also advise reading:\nhttp://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide\nhttp://code.google.com/p/modwsgi/wiki/ReloadingSourceCode\nThat latter isn't the whole picture though in respecting of code reloading as there are changes in mod_wsgi 3.X which aren't documented in there which add even more options for automatic source code reloading.\nOverall, although you could follow the PHP model of doing things, I would very much suggest a high level Python web framework. That in conjunction with daemon mode feature of mod_wsgi for triggering reloads by touching the WSGI script file is generally more than enough and more predictable.\n", "Wandering a bit afield from your original question, but trying to answer some of what's come up in reply to sparklewhiskers:\nFor an example of how WSGI works in a shared hosting environment, see these pages on Passenger's WSGI support at A Small Orange and Dreamhost, in which the necessary server configuration is done through a .htaccess file or a web panel.\nI think Python hosting on shared servers is still relatively uncommon; I expect more Python applications are run on some sort of VPS or Google AppEngine.\nSome Python webapps aren't launched from an apache or nginx module at all, they have their own persistent server, and if you want to have them on the same server as something else you configure your other server to proxy to your Python server. But that's another story entirely.\n" ]
[ 6, 4, 2, 2, 1 ]
[]
[]
[ "apache", "configuration", "python" ]
stackoverflow_0002131417_apache_configuration_python.txt
Q: How to run two functions simultaneously I am running test but I want to run 2 functions at the same time. I have a camera and I am telling it to move via suds, I am then logging into the camera via SSH to check the speed the camera is set to. When I check the speed the camera has stopped so no speed is available. Is there a way I can get these functions to run at the same time to test the speed of the camera. Sample code is below: class VerifyPan(TestAbsoluteMove): def runTest(self): self.dest.PanTilt._x=350 # Runs soap move command threading.Thread(target = SudsMove).start() self.command = './ptzpanposition -c 0 -u degx10' # Logs into camera and checks speed TestAbsoluteMove.Ssh(self) # Position of the camera verified through Ssh (No decimal point added to the Ssh value) self.assertEqual(self.Value, '3500') I have now tried the threading module as mentioned below. The thread does not run in sync with the function TestAbsoluteMove.Ssh(). Is there any other code I need to make this work. I have looked at putting arguments into the thread statement that state the thread runs when the Ssh() function. Does anyone know what to enter in this statement? Sorry if I haven't explained correctly. The 'SudsMove' function moves the camera and the 'Ssh' function logs into the camera and checks the speed the camera is currently moving at. The problem is that by the time the 'Ssh' function logs in the camera has stopped. I need both functions to run in parallel so I can check the camera speed while it is still moving. Thanks A: Import the threading module and run SudsMove() like so: threading.Thread(target = SudsMove).start() That will create and start a background thread which does the movement. ANSWER TO EDITED QUESTION: As far as I understand this, TestAbsoluteMove.Ssh(self) polls the speed once and stores the result in self.Value?! And you're testing the expected end tilt/rotation/position with self.assertEqual(self.Value, '3500')?! If that's correct, you should wait for the camera to start its movement. You could probably poll the speed in a certain interval: # Move camera in background thread threading.Thread(target = SudsMove).start() # What does this do? self.command = './ptzpanposition -c 0 -u degx10' # Poll the current speed in an interval of 250 ms import time measuredSpeedsList = [] for i in xrange(20): # Assuming that this call will put the result in self.Value TestAbsoluteMove.Ssh(self) measuredSpeedsList.append(self.Value) time.sleep(0.25) print "Measured movement speeds: ", measuredSpeedsList The movement speed will be the biggest value in measuredSpeedsList (i.e. max(measuredSpeedsList)). Hope that makes sense... A: If you want to use the common Python implementation (CPython), you can certainly use the multiprocessing module, which does wonders (you can pass non-pickleable arguments to subprocesses, kill tasks,…), offers an interface similar to that of threads, and does not suffer from the Global Interpreter Lock. The downside is that subprocesses are spawned, which takes more time than creating threads; this should only be a problem if you have many, many short tasks. Also, since data is passed (via serialization) between processes, large data both takes a long time to pass around and ends up having a large memory footprint (as it is duplicated between each process). In situations where each task takes a "long" time and the data in and out of each task is not too large, the multiprocessing module should be great. A: There can only be one thread running at the same time. This has been answered extensively here. One solution will be to use two separate processes. The above answer provides some tips. A: If you can get your code to run under Jython or IronPython, then you can run several threads simultaneously; they don't have that goofy "Global Interpreter Lock" thing of CPython.
How to run two functions simultaneously
I am running test but I want to run 2 functions at the same time. I have a camera and I am telling it to move via suds, I am then logging into the camera via SSH to check the speed the camera is set to. When I check the speed the camera has stopped so no speed is available. Is there a way I can get these functions to run at the same time to test the speed of the camera. Sample code is below: class VerifyPan(TestAbsoluteMove): def runTest(self): self.dest.PanTilt._x=350 # Runs soap move command threading.Thread(target = SudsMove).start() self.command = './ptzpanposition -c 0 -u degx10' # Logs into camera and checks speed TestAbsoluteMove.Ssh(self) # Position of the camera verified through Ssh (No decimal point added to the Ssh value) self.assertEqual(self.Value, '3500') I have now tried the threading module as mentioned below. The thread does not run in sync with the function TestAbsoluteMove.Ssh(). Is there any other code I need to make this work. I have looked at putting arguments into the thread statement that state the thread runs when the Ssh() function. Does anyone know what to enter in this statement? Sorry if I haven't explained correctly. The 'SudsMove' function moves the camera and the 'Ssh' function logs into the camera and checks the speed the camera is currently moving at. The problem is that by the time the 'Ssh' function logs in the camera has stopped. I need both functions to run in parallel so I can check the camera speed while it is still moving. Thanks
[ "Import the threading module and run SudsMove() like so:\nthreading.Thread(target = SudsMove).start()\n\nThat will create and start a background thread which does the movement.\nANSWER TO EDITED QUESTION:\nAs far as I understand this, TestAbsoluteMove.Ssh(self) polls the speed once and stores the result in self.Value?! And you're testing the expected end tilt/rotation/position with self.assertEqual(self.Value, '3500')?!\nIf that's correct, you should wait for the camera to start its movement. You could probably poll the speed in a certain interval:\n# Move camera in background thread\nthreading.Thread(target = SudsMove).start()\n\n# What does this do?\nself.command = './ptzpanposition -c 0 -u degx10'\n\n# Poll the current speed in an interval of 250 ms\nimport time\nmeasuredSpeedsList = []\n\nfor i in xrange(20):\n # Assuming that this call will put the result in self.Value\n TestAbsoluteMove.Ssh(self)\n measuredSpeedsList.append(self.Value)\n time.sleep(0.25)\n\nprint \"Measured movement speeds: \", measuredSpeedsList\n\nThe movement speed will be the biggest value in measuredSpeedsList (i.e. max(measuredSpeedsList)). Hope that makes sense...\n", "If you want to use the common Python implementation (CPython), you can certainly use the multiprocessing module, which does wonders (you can pass non-pickleable arguments to subprocesses, kill tasks,…), offers an interface similar to that of threads, and does not suffer from the Global Interpreter Lock.\nThe downside is that subprocesses are spawned, which takes more time than creating threads; this should only be a problem if you have many, many short tasks. Also, since data is passed (via serialization) between processes, large data both takes a long time to pass around and ends up having a large memory footprint (as it is duplicated between each process). In situations where each task takes a \"long\" time and the data in and out of each task is not too large, the multiprocessing module should be great.\n", "There can only be one thread running at the same time. This has been answered extensively here. One solution will be to use two separate processes. The above answer provides some tips.\n", "If you can get your code to run under Jython or IronPython, then you can run several threads simultaneously; they don't have that goofy \"Global Interpreter Lock\" thing of CPython.\n" ]
[ 13, 6, 2, 1 ]
[]
[]
[ "function", "multithreading", "python", "synchronization", "testing" ]
stackoverflow_0002108126_function_multithreading_python_synchronization_testing.txt
Q: How to return the count of related entities in sqlalchemy query I'm new to sqlalchemy, and while the documentation seems fairly thorough, I couldn't find a way to do quite what I want. Say I have two tables: forum and post. Each forum has a parent forum, and any number of posts. What I want is: A list of top-level forums Eagerly loaded child forums accessible through the top-level forums A count of posts for each child forum So I started with: query(Forum).filter(Forum.parent==None).all() Which gives me all the top level forums. Of course accessing the child forums yields n select queries. query(Forum).options(eagerload('children')).filter(Forum.parent==None).all() This solves the n select problem. Now my best guess goes something like this: query(Forum, func.count(Forum.children.posts)).options(eagerload('children')).filter(Forum.parent==None).group_by(Forum.children.id).all() But all I get is: AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'posts' I've tried a few variations, but haven't got any further. Just for clarity I'm looking for the equivalent of this SQL: select Forum.*, Child.*, count(Post.id) from Forum left join Forum Child on Child.parent = Forum.id left join Message on Message.forum = Child.id where Forum.parent is null group by Child.id A: Because you want the post count to be accessible on the child Forum objects you'll need to declare it as a column property when setting up the mappers. The column property declaration should look something like this (assuming you use declarative): Forum.post_count = column_property(select([func.count()], Message.__table__.c.forum == Forum.__table__.c.id ).correlate(Forum.__table__).as_scalar().label('post_count'), deferred=True) Then you can phrase your query like this: query(Forum).filter_by(parent=None).options( eagerload('children'), undefer('children.post_count')) Another option would be to select the children and counts separately. In this case you'll need to do the result grouping yourself: ChildForum = aliased(Forum) q = (query(Forum, ChildForum, func.count(Message.id)) .filter(Forum.parent == None) .outerjoin((ChildForum, Forum.children)) .outerjoin(ChildForum.posts) .group_by(Forum, ChildForum) ) from itertools import groupby from operator import attrgetter for forum, childforums in groupby(q, key=attrgetter('Node')): for _, child, post_count in childforums: if child is None: # No children break # do something with child
How to return the count of related entities in sqlalchemy query
I'm new to sqlalchemy, and while the documentation seems fairly thorough, I couldn't find a way to do quite what I want. Say I have two tables: forum and post. Each forum has a parent forum, and any number of posts. What I want is: A list of top-level forums Eagerly loaded child forums accessible through the top-level forums A count of posts for each child forum So I started with: query(Forum).filter(Forum.parent==None).all() Which gives me all the top level forums. Of course accessing the child forums yields n select queries. query(Forum).options(eagerload('children')).filter(Forum.parent==None).all() This solves the n select problem. Now my best guess goes something like this: query(Forum, func.count(Forum.children.posts)).options(eagerload('children')).filter(Forum.parent==None).group_by(Forum.children.id).all() But all I get is: AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'posts' I've tried a few variations, but haven't got any further. Just for clarity I'm looking for the equivalent of this SQL: select Forum.*, Child.*, count(Post.id) from Forum left join Forum Child on Child.parent = Forum.id left join Message on Message.forum = Child.id where Forum.parent is null group by Child.id
[ "Because you want the post count to be accessible on the child Forum objects you'll need to declare it as a column property when setting up the mappers. The column property declaration should look something like this (assuming you use declarative):\nForum.post_count = column_property(select([func.count()],\n Message.__table__.c.forum == Forum.__table__.c.id\n ).correlate(Forum.__table__).as_scalar().label('post_count'),\n deferred=True)\n\nThen you can phrase your query like this:\nquery(Forum).filter_by(parent=None).options(\n eagerload('children'),\n undefer('children.post_count'))\n\nAnother option would be to select the children and counts separately. In this case you'll need to do the result grouping yourself:\nChildForum = aliased(Forum)\nq = (query(Forum, ChildForum, func.count(Message.id))\n .filter(Forum.parent == None)\n .outerjoin((ChildForum, Forum.children))\n .outerjoin(ChildForum.posts)\n .group_by(Forum, ChildForum)\n )\n\nfrom itertools import groupby\nfrom operator import attrgetter\n\nfor forum, childforums in groupby(q, key=attrgetter('Node')):\n for _, child, post_count in childforums:\n if child is None:\n # No children\n break\n # do something with child\n\n" ]
[ 8 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002125041_python_sql_sqlalchemy.txt
Q: Parse .strings file with Python I'm trying to write a small Python script to parse the .strings file in my iPhone application project and determine which keys might not be in use. I'm, also doing some string matching to filter out some of the results. This is where my problems start :). If I try something like for file_line in strings_file: if 'search_keyword' in file_line: ... the search keyword will often not match, even though if I print every file line in the same for I seem to be reading the text correctly and my search keywords appear. The problem is these .strings files are in some binary format. Does anyone know of a proper way to parse these files? A: Use correct encoding to open the .strings-file and in your source code. According to documentation the encoding of your file could be utf-16. # -*- coding: utf-8 -*- import codecs for line in codecs.open(u'your_file.strings', encoding='utf-16'): if u'keyword' in line: # process line A: No experience with those .strings files, but here is the reason why you don't find matches: strings_file.read() returns a string with the full content of the file. Iterating over a string iterates over single characters, i.e. in your for loop, file_line isn't a line, it's always just one single character (a string of length 1), which obviously can't contain a multi-character search word. A: It sounds like the stings file was saved as data. If python can't read it as is you can convert it to a plain text file in Objective-c. Just: (1) read the strings file into a file with the proper encoding. (2) Convert to dictionary (3) write dictionary to another file. So: NSString *strings=[NSString stringWithContentsOfFile:filePath encoding:NSUTF16StringEncoding error:&error]; NSDictionary *dict=[strings propertyList]; [dict writeToFile:anotherFilePath atomically:NO];
Parse .strings file with Python
I'm trying to write a small Python script to parse the .strings file in my iPhone application project and determine which keys might not be in use. I'm, also doing some string matching to filter out some of the results. This is where my problems start :). If I try something like for file_line in strings_file: if 'search_keyword' in file_line: ... the search keyword will often not match, even though if I print every file line in the same for I seem to be reading the text correctly and my search keywords appear. The problem is these .strings files are in some binary format. Does anyone know of a proper way to parse these files?
[ "Use correct encoding to open the .strings-file and in your source code. According to documentation the encoding of your file could be utf-16.\n# -*- coding: utf-8 -*-\nimport codecs\n\nfor line in codecs.open(u'your_file.strings', encoding='utf-16'):\n if u'keyword' in line:\n # process line\n\n", "No experience with those .strings files, but here is the reason why you don't find matches:\nstrings_file.read()\n\nreturns a string with the full content of the file. Iterating over a string iterates over single characters, i.e. in your for loop, file_line isn't a line, it's always just one single character (a string of length 1), which obviously can't contain a multi-character search word.\n", "It sounds like the stings file was saved as data. If python can't read it as is you can convert it to a plain text file in Objective-c. \nJust: (1) read the strings file into a file with the proper encoding. (2) Convert to dictionary (3) write dictionary to another file.\nSo:\nNSString *strings=[NSString stringWithContentsOfFile:filePath encoding:NSUTF16StringEncoding error:&error];\nNSDictionary *dict=[strings propertyList];\n[dict writeToFile:anotherFilePath atomically:NO]; \n\n" ]
[ 3, 2, 0 ]
[]
[]
[ "core_foundation", "iphone", "objective_c", "python" ]
stackoverflow_0002132291_core_foundation_iphone_objective_c_python.txt
Q: TextMate and Django Integration - Supporting {% %} markup I have installed a TextMate bundle that I believe enables the ability for automatic closing of the "{{" markup (so that it will automatically close the markup with "}}"), but this does not seem to be possible with the other markup that uses "{%" and "%}". So, I was wondering if anyone out there knows how to get TextMate to add the automatic closing tags for the {% %} just like is already done with {{ }}. Any help is appreciated! A: It's possible - the Rails bundle does this for ERB (<% automatically gets closing %> tags). So that's a place you could go look. A: I don't think that's possible, but the Django bundle for TextMate does allow you to insert the opening and closing tags in one go, placing the cursor in the middle, with ctrl-% (ctrl-shift-5). Click the Bundles -> Python Django Templates menu to see all the shortcuts that are available.
TextMate and Django Integration - Supporting {% %} markup
I have installed a TextMate bundle that I believe enables the ability for automatic closing of the "{{" markup (so that it will automatically close the markup with "}}"), but this does not seem to be possible with the other markup that uses "{%" and "%}". So, I was wondering if anyone out there knows how to get TextMate to add the automatic closing tags for the {% %} just like is already done with {{ }}. Any help is appreciated!
[ "It's possible - the Rails bundle does this for ERB (<% automatically gets closing %> tags).\nSo that's a place you could go look.\n", "I don't think that's possible, but the Django bundle for TextMate does allow you to insert the opening and closing tags in one go, placing the cursor in the middle, with ctrl-% (ctrl-shift-5).\nClick the Bundles -> Python Django Templates menu to see all the shortcuts that are available.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python", "textmate" ]
stackoverflow_0002127956_django_python_textmate.txt
Q: ArcGIS: accessing python list output from listFields geoprocessor I'm trying to access the output from the listFields geoprocessing object using the following code: sFields = gp.ListFields(linktofeatureclass) for j in range(len(sFields)): print sFields[j] How do I get information about the fields that I have enumerated? Printing them (i.e. sFields in the above) just returns "geoprocessing describe field object object at 0x00E42E18". I'm looking for the field name, type, length, etc. Thanks A: try this: sFields = gp.ListFields(linktofeatureclass) for field in sFields: print field.Name, field.Type, field.Scale For more information, consult with the docs.
ArcGIS: accessing python list output from listFields geoprocessor
I'm trying to access the output from the listFields geoprocessing object using the following code: sFields = gp.ListFields(linktofeatureclass) for j in range(len(sFields)): print sFields[j] How do I get information about the fields that I have enumerated? Printing them (i.e. sFields in the above) just returns "geoprocessing describe field object object at 0x00E42E18". I'm looking for the field name, type, length, etc. Thanks
[ "try this:\nsFields = gp.ListFields(linktofeatureclass)\nfor field in sFields:\n print field.Name, field.Type, field.Scale\n\nFor more information, consult with the docs.\n" ]
[ 1 ]
[]
[]
[ "arcgis", "python" ]
stackoverflow_0002133576_arcgis_python.txt
Q: How to import or include data structures (e.g. a dict) into a Python file from a separate file I know I can include Python code from a common file using import MyModuleName - but how do I go about importing just a dict? The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non-programmer. script.py airportName = 'BRISTOL' myAirportCode = airportCode[airportName] myDict.py airportCode = {'ABERDEEN': 'ABZ', 'BELFAST INTERNATIONAL': 'BFS', 'BIRMINGHAM INTERNATIONAL': 'BHX', 'BIRMINGHAM INTL': 'BHX', 'BOURNMOUTH': 'BOH', 'BRISTOL': 'BRS'} How do I access the airportCode dict from within script.py? A: Just import it import myDict print myDict.airportCode or, better from myDict import airportCode print airportCode Just be careful to put both scripts on the same directory (or make a python package, a subdir with __init__.py file; or put the path to script.py on the PYTHONPATH; but these are "advanced options", just put it on the same directory and it'll be fine). A: Assuming your import myDict works, you need to do the following: from myDict import airportCode A: Well, it doesn't need to be a .py file. You could just do: eval(open("myDict").read()) It's a gaping security hole, though. Another module you might want to look at is csv for importing CSV files. Then your users could edit it with a spreadsheet and you don't have to teach them Python syntax. A: If your dict has to be hand-editable by a non-programmer, perhaps it might make more sense using a CSV file for this. Then you editor can even use Excel. So you can use: import csv csvfile = csv.reader(open("airports.csv")) airportCode = dict(csvfile) to read a CSV file like "ABERDEEN","ABZ" "BELFAST INTERNATIONAL","BFS" "BIRMINGHAM INTERNATIONAL","BHX" "BIRMINGHAM INTL","BHX" "BOURNMOUTH","BOH" "BRISTOL","BRS" Careful: If an airport were in that list twice, the last occurrence would silently "overwrite" any previous one(s). A: When you perform an import in python you are really just pulling in names into your current namespace. It does not really matter what those names refer to so: from myDict import airportCode Will work regardless of whether airportCode is a function, class or just a field as in your case. A: Use csv. Stick import csv with the rest of your module imports, and then you can do as follows: f = open('somefile.csv') reader = csv.DictReader(f, (airport, iatacode)) for row in reader: print row which should give you a list of dictionaries: airport | iatacode __________________ Aberdeen| ABZ to create the csv file: f = open('somefile.csv', 'w') writer = csv.DictWriter(f, (airport, iatacode)) for row in airportcode: writer.writerow() f.close() which will create a csv file with airports and IATA TLAs in two columns with airport and iatacode as the headers. You can also skip the dicts and just have strings by using Reader and Writer rather than DictReader and DictWriter. By default, the csv module produces excel-style csv, but you can set whatever dialect you like as a kwarg. A: from myDict import airportCode airportNode = 'BRISTOL' myAirportCode = airportCode[airportName] If myDict should get accessed from a Python module in a different directory, you have to provide a __init__.py module. For more Information about this topic have a look at the module chapter of the Python documentation.
How to import or include data structures (e.g. a dict) into a Python file from a separate file
I know I can include Python code from a common file using import MyModuleName - but how do I go about importing just a dict? The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non-programmer. script.py airportName = 'BRISTOL' myAirportCode = airportCode[airportName] myDict.py airportCode = {'ABERDEEN': 'ABZ', 'BELFAST INTERNATIONAL': 'BFS', 'BIRMINGHAM INTERNATIONAL': 'BHX', 'BIRMINGHAM INTL': 'BHX', 'BOURNMOUTH': 'BOH', 'BRISTOL': 'BRS'} How do I access the airportCode dict from within script.py?
[ "Just import it\nimport myDict\nprint myDict.airportCode\n\nor, better\nfrom myDict import airportCode\nprint airportCode\n\nJust be careful to put both scripts on the same directory (or make a python package, a subdir with __init__.py file; or put the path to script.py on the PYTHONPATH; but these are \"advanced options\", just put it on the same directory and it'll be fine). \n", "Assuming your import myDict works, you need to do the following:\nfrom myDict import airportCode\n\n", "Well, it doesn't need to be a .py file. You could just do:\neval(open(\"myDict\").read())\n\nIt's a gaping security hole, though.\nAnother module you might want to look at is csv for importing CSV files. Then your users could edit it with a spreadsheet and you don't have to teach them Python syntax.\n", "If your dict has to be hand-editable by a non-programmer, perhaps it might make more sense using a CSV file for this. Then you editor can even use Excel.\nSo you can use:\nimport csv\ncsvfile = csv.reader(open(\"airports.csv\"))\nairportCode = dict(csvfile)\n\nto read a CSV file like\n\"ABERDEEN\",\"ABZ\"\n\"BELFAST INTERNATIONAL\",\"BFS\"\n\"BIRMINGHAM INTERNATIONAL\",\"BHX\"\n\"BIRMINGHAM INTL\",\"BHX\"\n\"BOURNMOUTH\",\"BOH\"\n\"BRISTOL\",\"BRS\"\n\nCareful: If an airport were in that list twice, the last occurrence would silently \"overwrite\" any previous one(s).\n", "When you perform an import in python you are really just pulling in names into your current namespace. It does not really matter what those names refer to so:\nfrom myDict import airportCode\n\nWill work regardless of whether airportCode is a function, class or just a field as in your case.\n", "Use csv. Stick import csv with the rest of your module imports,\nand then you can do as follows:\nf = open('somefile.csv')\nreader = csv.DictReader(f, (airport, iatacode))\nfor row in reader:\n print row\n\nwhich should give you a list of dictionaries:\nairport | iatacode\n__________________\nAberdeen| ABZ\n\nto create the csv file:\nf = open('somefile.csv', 'w')\nwriter = csv.DictWriter(f, (airport, iatacode))\nfor row in airportcode:\n writer.writerow()\nf.close()\n\nwhich will create a csv file with airports and IATA TLAs in two columns with airport and iatacode as the headers.\nYou can also skip the dicts and just have strings by using Reader and Writer rather than DictReader and DictWriter.\nBy default, the csv module produces excel-style csv, but you can set whatever dialect you like as a kwarg.\n", "from myDict import airportCode\nairportNode = 'BRISTOL'\nmyAirportCode = airportCode[airportName]\n\nIf myDict should get accessed from a Python module in a different directory, you have to provide a __init__.py module.\nFor more Information about this topic have a look at the module chapter of the Python documentation.\n" ]
[ 74, 16, 2, 2, 2, 1, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0002132985_import_module_python.txt
Q: Paramiko equvalent of pipeline controls and input/output pipes I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as: ssh server "cat remote_file" > local_file with paramiko channels? Can paramiko.Transport.open_channel() or Message() do the job? I am unsure of how to proceed. A: The following may be useful as a starting point (e.g. ./sshpipe host "command"): #! /usr/bin/env python import sys import paramiko def sshpipe(host, line) : client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host) stdin, stdout, stderr = client.exec_command(line) output = stdout.read() sys.stdout.write(output) stdin.close() stdout.close() stderr.close() client.close() sshpipe(sys.argv[1], sys.argv[2])
Paramiko equvalent of pipeline controls and input/output pipes
I need a method of paramiko based file transfer with a lightweight SSH2 server (dropbear) which has no support for SCP or SFTP. Is there a way of achieving a cat and redirect style file transfer, such as: ssh server "cat remote_file" > local_file with paramiko channels? Can paramiko.Transport.open_channel() or Message() do the job? I am unsure of how to proceed.
[ "The following may be useful as a starting point (e.g. ./sshpipe host \"command\"):\n#! /usr/bin/env python\n\nimport sys\nimport paramiko\n\ndef sshpipe(host, line) :\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(host)\n stdin, stdout, stderr = client.exec_command(line)\n output = stdout.read()\n sys.stdout.write(output)\n stdin.close()\n stdout.close()\n stderr.close()\n client.close()\n\nsshpipe(sys.argv[1], sys.argv[2])\n\n" ]
[ 3 ]
[]
[]
[ "file", "paramiko", "python", "transfer" ]
stackoverflow_0002133326_file_paramiko_python_transfer.txt
Q: put stockprices into groups when they are within 0.5% of each other Thanks for the answers, I have not used StackOverflow before so I was suprised by the number of answers and the speed of them - its fantastic. I have not been through the answers properly yet, but thought I should add some information to the problem specification. See the image below. I can't post an image in this because i don't have enough points but you can see an image at http://journal.acquitane.com/2010-01-20/image003.jpg This image may describe more closely what I'm trying to achieve. So you can see on the horizontal lines across the page are price points on the chart. Now where you get a clustering of lines within 0.5% of each, this is considered to be a good thing and why I want to identify those clusters automatically. You can see on the chart that there is a cluster at S2 & MR1, R2 & WPP1. So everyday I produce these price points and then I can identify manually those that are within 0.5%. - but the purpose of this question is how to do it with a python routine. I have reproduced the list again (see below) with labels. Just be aware that the list price points don't match the price points in the image because they are from two different days. [YR3,175.24,8] [SR3,147.85,6] [YR2,144.13,8] [SR2,130.44,6] [YR1,127.79,8] [QR3,127.42,5] [SR1,120.94,6] [QR2,120.22,5] [MR3,118.10,3] [WR3,116.73,2] [DR3,116.23,1] [WR2,115.93,2] [QR1,115.83,5] [MR2,115.56,3] [DR2,115.53,1] [WR1,114.79,2] [DR1,114.59,1] [WPP,113.99,2] [DPP,113.89,1] [MR1,113.50,3] [DS1,112.95,1] [WS1,112.85,2] [DS2,112.25,1] [WS2,112.05,2] [DS3,111.31,1] [MPP,110.97,3] [WS3,110.91,2] [50MA,110.87,4] [MS1,108.91,3] [QPP,108.64,5] [MS2,106.37,3] [MS3,104.31,3] [QS1,104.25,5] [SPP,103.53,6] [200MA,99.42,7] [QS2,97.05,5] [YPP,96.68,8] [SS1,94.03,6] [QS3,92.66,5] [YS1,80.34,8] [SS2,76.62,6] [SS3,67.12,6] [YS2,49.23,8] [YS3,32.89,8] I did make a mistake with the original list in that Group C is wrong and should not be included. Thanks for pointing that out. Also the 0.5% is not fixed this value will change from day to day, but I have just used 0.5% as an example for spec'ing the problem. Thanks Again. Mark PS. I will get cracking on checking the answers now now. Hi: I need to do some manipulation of stock prices. I have just started using Python, (but I think I would have trouble implementing this in any language). I'm looking for some ideas on how to implement this nicely in python. Thanks Mark Problem: I have a list of lists (FloorLevels (see below)) where the sublist has two items (stockprice, weight). I want to put the stockprices into groups when they are within 0.5% of each other. A groups strength will be determined by its total weight. For example: Group-A 115.93,2 115.83,5 115.56,3 115.53,1 ------------- TotalWeight:12 ------------- Group-B 113.50,3 112.95,1 112.85,2 ------------- TotalWeight:6 ------------- FloorLevels[ [175.24,8] [147.85,6] [144.13,8] [130.44,6] [127.79,8] [127.42,5] [120.94,6] [120.22,5] [118.10,3] [116.73,2] [116.23,1] [115.93,2] [115.83,5] [115.56,3] [115.53,1] [114.79,2] [114.59,1] [113.99,2] [113.89,1] [113.50,3] [112.95,1] [112.85,2] [112.25,1] [112.05,2] [111.31,1] [110.97,3] [110.91,2] [110.87,4] [108.91,3] [108.64,5] [106.37,3] [104.31,3] [104.25,5] [103.53,6] [99.42,7] [97.05,5] [96.68,8] [94.03,6] [92.66,5] [80.34,8] [76.62,6] [67.12,6] [49.23,8] [32.89,8] ] A: I suggest a repeated use of k-means clustering -- let's call it KMC for short. KMC is a simple and powerful clustering algorithm... but it needs to "be told" how many clusters, k, you're aiming for. You don't know that in advance (if I understand you correctly) -- you just want the smallest k such that no two items "clustered together" are more than X% apart from each other. So, start with k equal 1 -- everything bunched together, no clustering pass needed;-) -- and check the diameter of the cluster (a cluster's "diameter", from the use of the term in geometry, is the largest distance between any two members of a cluster). If the diameter is > X%, set k += 1, perform KMC with k as the number of clusters, and repeat the check, iteratively. In pseudo-code: def markCluster(items, threshold): k = 1 clusters = [items] maxdist = diameter(items) while maxdist > threshold: k += 1 clusters = Kmc(items, k) maxdist = max(diameter(c) for c in clusters) return clusters assuming of course we have suitable diameter and Kmc Python functions. Does this sound like the kind of thing you want? If so, then we can move on to show you how to write diameter and Kmc (in pure Python if you have a relatively limited number of items to deal with, otherwise maybe by exploiting powerful third-party add-on frameworks such as numpy) -- but it's not worthwhile to go to such trouble if you actually want something pretty different, whence this check!-) A: A stock s belong in a group G if for each stock t in G, s * 1.05 >= t and s / 1.05 <= t, right? How do we add the stocks to each group? If we have the stocks 95, 100, 101, and 105, and we start a group with 100, then add 101, we will end up with {100, 101, 105}. If we did 95 after 100, we'd end up with {100, 95}. Do we just need to consider all possible permutations? If so, your algorithm is going to be inefficient. A: You need to specify your problem in more detail. Just what does "put the stockprices into groups when they are within 0.5% of each other" mean? Possibilities: (1) each member of the group is within 0.5% of every other member of the group (2) sort the list and split it where the gap is more than 0.5% Note that 116.23 is within 0.5% of 115.93 -- abs((116.23 / 115.93 - 1) * 100) < 0.5 -- but you have put one number in Group A and one in Group C. Simple example: a, b, c = (0.996, 1, 1.004) ... Note that a and b fit, b and c fit, but a and c don't fit. How do you want them grouped, and why? Is the order in the input list relevant? Possibility (1) produces ab,c or a,bc ... tie-breaking rule, please Possibility (2) produces abc (no big gaps, so only one group) A: You won't be able to classify them into hard "groups". If you have prices (1.0,1.05, 1.1) then the first and second should be in the same group, and the second and third should be in the same group, but not the first and third. A quick, dirty way to do something that you might find useful: def make_group_function(tolerance = 0.05): from math import log10, floor # I forget why this works. tolerance_factor = -1.0/(-log10(1.0 + tolerance)) # well ... since you might ask # we want: log(x)*tf - log(x*(1+t))*tf = -1, # so every 5% change has a different group. The minus is just so groups # are ascending .. it looks a bit nicer. # # tf = -1/(log(x)-log(x*(1+t))) # tf = -1/(log(x/(x*(1+t)))) # tf = -1/(log(1/(1*(1+t)))) # solved .. but let's just be more clever # tf = -1/(0-log(1*(1+t))) # tf = -1/(-log((1+t)) def group_function(value): # don't just use int - it rounds up below zero, and down above zero return int(floor(log10(value)*tolerance_factor)) return group_function Usage: group_function = make_group_function() import random groups = {} for i in range(50): v = random.random()*500+1000 group = group_function(v) if group in groups: groups[group].append(v) else: groups[group] = [v] for group in sorted(groups): print 'Group',group for v in sorted(groups[group]): print v print A: For a given set of stock prices, there is probably more than one way to group stocks that are within 0.5% of each other. Without some additional rules for grouping the prices, there's no way to be sure an answer will do what you really want. A: apart from the proper way to pick which values fit together, this is a problem where a little Object Orientation dropped in can make it a lot easier to deal with. I made two classes here, with a minimum of desirable behaviors, but which can make the classification a lot easier -- you get a single point to play with it on the Group class. I can see the code bellow is incorrect, in the sense the limtis for group inclusion varies as new members are added -- even it the separation crieteria remaisn teh same, you heva e torewrite the get_groups method to use a multi-pass approach. It should nto be hard -- but the code would be too long to be helpfull here, and i think this snipped is enoguh to get you going: from copy import copy class Group(object): def __init__(self,data=None, name=""): if data: self.data = data else: self.data = [] self.name = name def get_mean_stock(self): return sum(item[0] for item in self.data) / len(self.data) def fits(self, item): if 0.995 < abs(item[0]) / self.get_mean_stock() < 1.005: return True return False def get_weight(self): return sum(item[1] for item in self.data) def __repr__(self): return "Group-%s\n%s\n---\nTotalWeight: %d\n\n" % ( self.name, "\n".join("%.02f, %d" % tuple(item) for item in self.data ), self.get_weight()) class StockGrouper(object): def __init__(self, data=None): if data: self.floor_levels = data else: self.floor_levels = [] def get_groups(self): groups = [] floor_levels = copy(self.floor_levels) name_ord = ord("A") - 1 while floor_levels: seed = floor_levels.pop(0) name_ord += 1 group = Group([seed], chr(name_ord)) groups.append(group) to_remove = [] for i, item in enumerate(floor_levels): if group.fits(item): group.data.append(item) to_remove.append(i) for i in reversed(to_remove): floor_levels.pop(i) return groups testing: floor_levels = [ [stock. weight] ,... <paste the data above> ] s = StockGrouper(floor_levels) s.get_groups() A: For the grouping element, could you use itertools.groupby()? As the data is sorted, a lot of the work of grouping it is already done, and then you could test if the current value in the iteration was different to the last by <0.5%, and have itertools.groupby() break into a new group every time your function returned false.
put stockprices into groups when they are within 0.5% of each other
Thanks for the answers, I have not used StackOverflow before so I was suprised by the number of answers and the speed of them - its fantastic. I have not been through the answers properly yet, but thought I should add some information to the problem specification. See the image below. I can't post an image in this because i don't have enough points but you can see an image at http://journal.acquitane.com/2010-01-20/image003.jpg This image may describe more closely what I'm trying to achieve. So you can see on the horizontal lines across the page are price points on the chart. Now where you get a clustering of lines within 0.5% of each, this is considered to be a good thing and why I want to identify those clusters automatically. You can see on the chart that there is a cluster at S2 & MR1, R2 & WPP1. So everyday I produce these price points and then I can identify manually those that are within 0.5%. - but the purpose of this question is how to do it with a python routine. I have reproduced the list again (see below) with labels. Just be aware that the list price points don't match the price points in the image because they are from two different days. [YR3,175.24,8] [SR3,147.85,6] [YR2,144.13,8] [SR2,130.44,6] [YR1,127.79,8] [QR3,127.42,5] [SR1,120.94,6] [QR2,120.22,5] [MR3,118.10,3] [WR3,116.73,2] [DR3,116.23,1] [WR2,115.93,2] [QR1,115.83,5] [MR2,115.56,3] [DR2,115.53,1] [WR1,114.79,2] [DR1,114.59,1] [WPP,113.99,2] [DPP,113.89,1] [MR1,113.50,3] [DS1,112.95,1] [WS1,112.85,2] [DS2,112.25,1] [WS2,112.05,2] [DS3,111.31,1] [MPP,110.97,3] [WS3,110.91,2] [50MA,110.87,4] [MS1,108.91,3] [QPP,108.64,5] [MS2,106.37,3] [MS3,104.31,3] [QS1,104.25,5] [SPP,103.53,6] [200MA,99.42,7] [QS2,97.05,5] [YPP,96.68,8] [SS1,94.03,6] [QS3,92.66,5] [YS1,80.34,8] [SS2,76.62,6] [SS3,67.12,6] [YS2,49.23,8] [YS3,32.89,8] I did make a mistake with the original list in that Group C is wrong and should not be included. Thanks for pointing that out. Also the 0.5% is not fixed this value will change from day to day, but I have just used 0.5% as an example for spec'ing the problem. Thanks Again. Mark PS. I will get cracking on checking the answers now now. Hi: I need to do some manipulation of stock prices. I have just started using Python, (but I think I would have trouble implementing this in any language). I'm looking for some ideas on how to implement this nicely in python. Thanks Mark Problem: I have a list of lists (FloorLevels (see below)) where the sublist has two items (stockprice, weight). I want to put the stockprices into groups when they are within 0.5% of each other. A groups strength will be determined by its total weight. For example: Group-A 115.93,2 115.83,5 115.56,3 115.53,1 ------------- TotalWeight:12 ------------- Group-B 113.50,3 112.95,1 112.85,2 ------------- TotalWeight:6 ------------- FloorLevels[ [175.24,8] [147.85,6] [144.13,8] [130.44,6] [127.79,8] [127.42,5] [120.94,6] [120.22,5] [118.10,3] [116.73,2] [116.23,1] [115.93,2] [115.83,5] [115.56,3] [115.53,1] [114.79,2] [114.59,1] [113.99,2] [113.89,1] [113.50,3] [112.95,1] [112.85,2] [112.25,1] [112.05,2] [111.31,1] [110.97,3] [110.91,2] [110.87,4] [108.91,3] [108.64,5] [106.37,3] [104.31,3] [104.25,5] [103.53,6] [99.42,7] [97.05,5] [96.68,8] [94.03,6] [92.66,5] [80.34,8] [76.62,6] [67.12,6] [49.23,8] [32.89,8] ]
[ "I suggest a repeated use of k-means clustering -- let's call it KMC for short. KMC is a simple and powerful clustering algorithm... but it needs to \"be told\" how many clusters, k, you're aiming for. You don't know that in advance (if I understand you correctly) -- you just want the smallest k such that no two items \"clustered together\" are more than X% apart from each other. So, start with k equal 1 -- everything bunched together, no clustering pass needed;-) -- and check the diameter of the cluster (a cluster's \"diameter\", from the use of the term in geometry, is the largest distance between any two members of a cluster).\nIf the diameter is > X%, set k += 1, perform KMC with k as the number of clusters, and repeat the check, iteratively.\nIn pseudo-code:\ndef markCluster(items, threshold):\n k = 1\n clusters = [items]\n maxdist = diameter(items)\n while maxdist > threshold:\n k += 1\n clusters = Kmc(items, k)\n maxdist = max(diameter(c) for c in clusters)\n return clusters\n\nassuming of course we have suitable diameter and Kmc Python functions.\nDoes this sound like the kind of thing you want? If so, then we can move on to show you how to write diameter and Kmc (in pure Python if you have a relatively limited number of items to deal with, otherwise maybe by exploiting powerful third-party add-on frameworks such as numpy) -- but it's not worthwhile to go to such trouble if you actually want something pretty different, whence this check!-)\n", "A stock s belong in a group G if for each stock t in G, s * 1.05 >= t and s / 1.05 <= t, right?\nHow do we add the stocks to each group? If we have the stocks 95, 100, 101, and 105, and we start a group with 100, then add 101, we will end up with {100, 101, 105}. If we did 95 after 100, we'd end up with {100, 95}.\nDo we just need to consider all possible permutations? If so, your algorithm is going to be inefficient. \n", "You need to specify your problem in more detail. Just what does \"put the stockprices into groups when they are within 0.5% of each other\" mean?\nPossibilities:\n(1) each member of the group is within 0.5% of every other member of the group\n(2) sort the list and split it where the gap is more than 0.5% \nNote that 116.23 is within 0.5% of 115.93 -- abs((116.23 / 115.93 - 1) * 100) < 0.5 -- but you have put one number in Group A and one in Group C.\nSimple example: a, b, c = (0.996, 1, 1.004) ... Note that a and b fit, b and c fit, but a and c don't fit. How do you want them grouped, and why? Is the order in the input list relevant? \nPossibility (1) produces ab,c or a,bc ... tie-breaking rule, please\nPossibility (2) produces abc (no big gaps, so only one group)\n", "You won't be able to classify them into hard \"groups\". If you have prices (1.0,1.05, 1.1) then the first and second should be in the same group, and the second and third should be in the same group, but not the first and third.\nA quick, dirty way to do something that you might find useful:\ndef make_group_function(tolerance = 0.05):\n from math import log10, floor\n # I forget why this works. \n tolerance_factor = -1.0/(-log10(1.0 + tolerance))\n # well ... since you might ask\n # we want: log(x)*tf - log(x*(1+t))*tf = -1, \n # so every 5% change has a different group. The minus is just so groups \n # are ascending .. it looks a bit nicer.\n #\n # tf = -1/(log(x)-log(x*(1+t)))\n # tf = -1/(log(x/(x*(1+t))))\n # tf = -1/(log(1/(1*(1+t)))) # solved .. but let's just be more clever\n # tf = -1/(0-log(1*(1+t)))\n # tf = -1/(-log((1+t))\n def group_function(value):\n # don't just use int - it rounds up below zero, and down above zero\n return int(floor(log10(value)*tolerance_factor))\n return group_function\n\nUsage:\ngroup_function = make_group_function()\nimport random\ngroups = {}\nfor i in range(50):\n v = random.random()*500+1000\n group = group_function(v)\n if group in groups:\n groups[group].append(v)\n else:\n groups[group] = [v]\n\nfor group in sorted(groups):\n print 'Group',group\n for v in sorted(groups[group]):\n print v\n print\n\n", "For a given set of stock prices, there is probably more than one way to group stocks that are within 0.5% of each other. Without some additional rules for grouping the prices, there's no way to be sure an answer will do what you really want.\n", "apart from the proper way to pick which values fit together, this is a problem where a little Object Orientation dropped in can make it a lot easier to deal with.\nI made two classes here, with a minimum of desirable behaviors, but which can make the classification a lot easier -- you get a single point to play with it on the Group class.\nI can see the code bellow is incorrect, in the sense the limtis for group inclusion varies as new members are added -- even it the separation crieteria remaisn teh same, you heva e torewrite the get_groups method to use a multi-pass approach. It should nto be hard -- but the code would be too long to be helpfull here, and i think this snipped is enoguh to get you going:\nfrom copy import copy\n\nclass Group(object):\n def __init__(self,data=None, name=\"\"):\n if data:\n self.data = data\n else:\n self.data = []\n self.name = name\n\n def get_mean_stock(self):\n return sum(item[0] for item in self.data) / len(self.data)\n\n def fits(self, item):\n if 0.995 < abs(item[0]) / self.get_mean_stock() < 1.005:\n return True\n return False\n\n def get_weight(self):\n return sum(item[1] for item in self.data)\n\n def __repr__(self):\n return \"Group-%s\\n%s\\n---\\nTotalWeight: %d\\n\\n\" % (\n self.name,\n \"\\n\".join(\"%.02f, %d\" % tuple(item) for item in self.data ),\n self.get_weight())\n\n\nclass StockGrouper(object):\n def __init__(self, data=None):\n if data:\n self.floor_levels = data\n else:\n self.floor_levels = []\n\n def get_groups(self):\n groups = []\n floor_levels = copy(self.floor_levels)\n name_ord = ord(\"A\") - 1\n while floor_levels:\n seed = floor_levels.pop(0)\n name_ord += 1\n group = Group([seed], chr(name_ord))\n groups.append(group)\n to_remove = []\n for i, item in enumerate(floor_levels):\n if group.fits(item):\n group.data.append(item)\n to_remove.append(i)\n for i in reversed(to_remove):\n floor_levels.pop(i)\n return groups\n\ntesting:\nfloor_levels = [ [stock. weight] ,... <paste the data above> ]\ns = StockGrouper(floor_levels)\ns.get_groups()\n\n", "For the grouping element, could you use itertools.groupby()? As the data is sorted, a lot of the work of grouping it is already done, and then you could test if the current value in the iteration was different to the last by <0.5%, and have itertools.groupby() break into a new group every time your function returned false.\n" ]
[ 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "cluster_analysis", "grouping", "list", "python", "stocks" ]
stackoverflow_0002130202_cluster_analysis_grouping_list_python_stocks.txt
Q: gtk.Builder() and multiple glade files breaks I have a glade gui, and I want to insert another object using a glade file as well. When I do it as bellow (this is essentially what I am doing) the whole app hangs and the self.show() and maxes out the CPU at 100%. If I replace the first line of one's init() with self.builder = gtk.Builder() then the app runs, I can set widgets, ie: set contents of entry's, set and change the values of comboboxes. But I cant respond to signals, button clicks never call the handler. In the real code the object two is set as a page in a note book, and I have multiple other pages, the gtk.main() is in the object that owns the notebook. All these work as expected, it's just the object one that fails. Any clues? I have tried calling self.builder.connect_signals() for every widget but it still fails to notice them. class one(gtk.VBox): def __init__(self, builder): gtk.VBox.__init__(self) self.builder = builder # if this is self.builder = gtk.Builder() app runs but widget signals go missing. self.builder.add_from_file("ui_for_one.glade") self.show() # Endless loop here? class two(object): # This is the page in a notebook. def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("ui_for_two.glade") self.some_container = self.builder.get_object("some_container") self.one = one(self.builder) self.some_container.pack_start(self.one, False, False) A: Is there a good reason for using the same gtk.Builder object in two classes? This might be the cause of your problem. In your one class, you load a glade file but you never do anything with its widgets. Something like this should work: class one(gtk.VBox): def __init__(self): gtk.VBox.__init__(self) self.builder = gtk.Builder() self.builder.add_from_file("ui_for_one.glade") some_widget = self.builder.get_object("some_widget") self.add(some_widget) self.builder.connect_signals(self) # No reason to call self.show() here, that should be done manually. #Your callback functions here class two(object): # This is the page in a notebook. def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("ui_for_two.glade") self.some_container = self.builder.get_object("some_container") self.one = one() self.some_container.pack_start(self.one, False, False) self.some_container.show_all() #recursively show some_container and all its child widgets self.builder.connect_signals(self) For more info, check out these Glade tutorials.
gtk.Builder() and multiple glade files breaks
I have a glade gui, and I want to insert another object using a glade file as well. When I do it as bellow (this is essentially what I am doing) the whole app hangs and the self.show() and maxes out the CPU at 100%. If I replace the first line of one's init() with self.builder = gtk.Builder() then the app runs, I can set widgets, ie: set contents of entry's, set and change the values of comboboxes. But I cant respond to signals, button clicks never call the handler. In the real code the object two is set as a page in a note book, and I have multiple other pages, the gtk.main() is in the object that owns the notebook. All these work as expected, it's just the object one that fails. Any clues? I have tried calling self.builder.connect_signals() for every widget but it still fails to notice them. class one(gtk.VBox): def __init__(self, builder): gtk.VBox.__init__(self) self.builder = builder # if this is self.builder = gtk.Builder() app runs but widget signals go missing. self.builder.add_from_file("ui_for_one.glade") self.show() # Endless loop here? class two(object): # This is the page in a notebook. def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("ui_for_two.glade") self.some_container = self.builder.get_object("some_container") self.one = one(self.builder) self.some_container.pack_start(self.one, False, False)
[ "Is there a good reason for using the same gtk.Builder object in two classes?\nThis might be the cause of your problem. In your one class, you load a glade file but you never do anything with its widgets. Something like this should work:\nclass one(gtk.VBox):\n\n def __init__(self):\n gtk.VBox.__init__(self)\n self.builder = gtk.Builder()\n self.builder.add_from_file(\"ui_for_one.glade\")\n some_widget = self.builder.get_object(\"some_widget\")\n self.add(some_widget)\n self.builder.connect_signals(self)\n # No reason to call self.show() here, that should be done manually.\n\n #Your callback functions here\n\nclass two(object): # This is the page in a notebook. \n\n def __init__(self):\n self.builder = gtk.Builder()\n self.builder.add_from_file(\"ui_for_two.glade\")\n self.some_container = self.builder.get_object(\"some_container\")\n self.one = one()\n self.some_container.pack_start(self.one, False, False)\n self.some_container.show_all() #recursively show some_container and all its child widgets\n\n self.builder.connect_signals(self)\n\nFor more info, check out these Glade tutorials.\n" ]
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002129369_gtk_pygtk_python.txt
Q: Most Pythonic way to concatenate strings Given this harmless little list: >>> lst = ['o','s','s','a','m','a'] My goal is to Pythonically concatenate the little devils using one of the following ways: A. A plain old string function to get the job done, short, no imports >>> ''.join(lst) 'ossama' B. Lambda, lambda, lambda >>> reduce(lambda x, y: x + y, lst) 'ossama' C. Globalization (do nothing, import everything) >>> import functools, operator >>> functools.reduce(operator.add, lst) 'ossama' What are other Pythonic ways to achieve this magnanimous task? Please rank (Pythonic level) and rate solutions giving concise explanations. In this case, is the most pythonic solution the best coding solution? A: ''.join(lst) The only Pythonic way: clear (that is what all the big boys do and what they expect to see), simple (no additional imports needed, and stable across all versions), fast (written in C) and concise (on an empty string, join elements of iterable!). A: Have a look at Guido's essay on Python optimization. It covers converting lists of numbers to strings. Unless you have a good reason to do otherwise, use the join example. A: Of course it's join. How do I know? Let's do it in a really stupid way: If the problem was only adding 2 strings, you'd most likely use str1 + str2. What does it take to get that to the next level? Instinctively, for most (I think), will be to use sum. Let's see how that goes: In [1]: example = ['a', 'b', 'c'] In [2]: sum(example, '') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython console> in <module>() TypeError: sum() can't sum strings [use ''.join(seq) instead] Wow! Python simply told me what to use! :) A: Here's the least Pythonic way: out = "" for x in range(len(lst)): for y in range(len(lst)): if x + y == len(lst)-1: out = lst[y] + out A: I myself use the "join" way, but from Python 2.6 there is a base type that is little used: bytearray. Bytearrays can be incredible useful -- for string containing texts, since the best thing is to have then in Unicode, the "join" way is the way to go -- but if you are dealing with binary data instead, bytearrays can be both more Pythonic and more efficient: >>> lst = ['o','s','s','a','m','a'] >>> a = bytearray(lst) >>> a bytearray(b'ossama') >>> print a ossama It is a built-in data type: no imports needed - just use then -- and you can use a bytearray instead of a list to start with - so they should be more efficient than the "join", since there isn’t any data copying to get the string representation for a bytearray. A: There is a great answer from SilentGhost, but just a few words about the presented reduce "alternative": Unless you've got a very very very good reason to concatenate strings using + or operator.add (the most frequent one, that you've got few, fixed number of strings), you should use always join. Just because each + generates a new string which is the concatenation of two strings, unlike join that only generates one final string. So, imagine you've got three strings: A + B + C --> D = A + B final = D + C Ok, it doesn't seems not much, but you've got to reserve memory for D. Also, due Python's use of strings, generating a new, intermediate, string, it's somehow expensive... Now, with five strings, A + B + C + D + E --> F = A + B G = F + C H = G + D final = H + E Assuming the best scenario (if we do (A+B) + (C+D) + E, we'll end having three intermediate strings at the same time on memory), and that's generating three intermediate strings... You've got to generate a new Python object, reserve memory space, and release the memory a few times... Also there is the overhead of calling a Python function (that is not small). Now think of it with 200 strings. We'll end up with a ridiculous big number of intermediate strings, each of which is consuming combining quite a lot of time on being a complete list over Python , and calling a lot of operator.add functions, each with its overhead... Even if you use reduce functions, it won't help. It's a problem that has to be managed with a different approach: join, which only generates one complete Python string, the final one and calls one Python function. (Of course, join, or other similar, specialized function for arrays.)
Most Pythonic way to concatenate strings
Given this harmless little list: >>> lst = ['o','s','s','a','m','a'] My goal is to Pythonically concatenate the little devils using one of the following ways: A. A plain old string function to get the job done, short, no imports >>> ''.join(lst) 'ossama' B. Lambda, lambda, lambda >>> reduce(lambda x, y: x + y, lst) 'ossama' C. Globalization (do nothing, import everything) >>> import functools, operator >>> functools.reduce(operator.add, lst) 'ossama' What are other Pythonic ways to achieve this magnanimous task? Please rank (Pythonic level) and rate solutions giving concise explanations. In this case, is the most pythonic solution the best coding solution?
[ "''.join(lst)\n\nThe only Pythonic way:\n\nclear (that is what all the big boys do and what they expect to see),\nsimple (no additional imports needed, and stable across all versions),\nfast (written in C) and\nconcise (on an empty string, join elements of iterable!).\n\n", "Have a look at Guido's essay on Python optimization. It covers converting lists of numbers to strings. Unless you have a good reason to do otherwise, use the join example.\n", "Of course it's join. How do I know? Let's do it in a really stupid way:\nIf the problem was only adding 2 strings, you'd most likely use str1 + str2. What does it take to get that to the next level? Instinctively, for most (I think), will be to use sum. Let's see how that goes:\nIn [1]: example = ['a', 'b', 'c']\nIn [2]: sum(example, '')\n---------------------------------------------------------------------------\nTypeError Traceback (most recent call last)\n<ipython console> in <module>()\n TypeError: sum() can't sum strings [use ''.join(seq) instead]\n\nWow! Python simply told me what to use! :)\n", "Here's the least Pythonic way:\nout = \"\"\nfor x in range(len(lst)):\n for y in range(len(lst)):\n if x + y == len(lst)-1:\n out = lst[y] + out\n\n", "I myself use the \"join\" way, but from Python 2.6 there is a base type that is little used: bytearray.\nBytearrays can be incredible useful -- for string containing texts, since the best thing is to have then in Unicode, the \"join\" way is the way to go -- but if you are dealing with binary data instead, bytearrays can be both more Pythonic and more efficient:\n>>> lst = ['o','s','s','a','m','a']\n>>> a = bytearray(lst)\n>>> a\nbytearray(b'ossama')\n>>> print a\nossama\n\nIt is a built-in data type: no imports needed - just use then -- and you can use a bytearray instead of a list to start with - so they should be more efficient than the \"join\", since there isn’t any data copying to get the string representation for a bytearray.\n", "There is a great answer from SilentGhost, but just a few words about the presented reduce \"alternative\":\nUnless you've got a very very very good reason to concatenate strings using + or operator.add (the most frequent one, that you've got few, fixed number of strings), you should use always join.\nJust because each + generates a new string which is the concatenation of two strings, unlike join that only generates one final string. So, imagine you've got three strings:\nA + B + C\n-->\nD = A + B\nfinal = D + C\n\nOk, it doesn't seems not much, but you've got to reserve memory for D. Also, due Python's use of strings, generating a new, intermediate, string, it's somehow expensive...\nNow, with five strings,\nA + B + C + D + E\n-->\nF = A + B\nG = F + C\nH = G + D\nfinal = H + E\n\nAssuming the best scenario (if we do (A+B) + (C+D) + E, we'll end having three intermediate strings at the same time on memory), and that's generating three intermediate strings... You've got to generate a new Python object, reserve memory space, and release the memory a few times... Also there is the overhead of calling a Python function (that is not small).\nNow think of it with 200 strings. We'll end up with a ridiculous big number of intermediate strings, each of which is consuming combining quite a lot of time on being a complete list over Python , and calling a lot of operator.add functions, each with its overhead...\nEven if you use reduce functions, it won't help. It's a problem that has to be managed with a different approach: join, which only generates one complete Python string, the final one and calls one Python function.\n(Of course, join, or other similar, specialized function for arrays.)\n" ]
[ 71, 40, 18, 8, 6, 4 ]
[]
[]
[ "concatenation", "python" ]
stackoverflow_0002133571_concatenation_python.txt
Q: Filtering models with ReferenceProperties I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties. eg. class Group(db.Model): name = db.StringProperty(required=True) creator = db.ReferenceProperty(User) class GroupMember(db.Model): group = db.ReferenceProperty(Group) user = db.ReferenceProperty(User) And I have tried writing something like this: members = models.GroupMember.all().filter('group.name =', group_name) and various other things that don't work. Hopefully someone can give me a prod in the right direction... A: If your groups are uniquely named, then your "group.name" is a unique identifier of a Group entity. That means you can write: members = models.GroupMember.all().filter( "group =",model.Group.gql("WHERE name=:1", group_name).get() ) though you only need to do that if you don't already have the group entity lying around in the stack somewhere. Google's essay on many-to-many with appengine is here. A: If what you want is to get the members of a group, ReferenceProperties have that built-in. class GroupMember(db.Model): group = db.ReferenceProperty(Group, collection_name="groupMembers") user = db.ReferenceProperty(User, collection_name="groupMembers") Then you can write: # get the group entity somehow group = Group.get(group_key) # do something with the members, such as list the nicknames nicknames = [x.user.nickname for x in group.groupMembers] A: This would require a join, which isn't possible in App Engine. If you want to filter by a property of another model, you need to include that property on the model you're querying against. A: This would result in two datastore hits but should work. If you use memcache shouldnt be a problem. group = models.Group.all().filter("name =", group_name).get() members = models.GroupMember.all().filter('group =', group) A: Using the Models that you defined in your question, lets say you want to list all members of a group called "Space monkeys". mygroup = Group.gql("WHERE name = :1",'Space monkeys') for group_member in mygroup.groupmember_set: print 'group members name is: %s' % (group_member.user.name) The "groupmember_set" is called a "implicit collection property" and is very useful. You can call it whatever you want by over-riding the default name using the collection_name keyword parameter to ReferenceProperty. For an example see the answer by Thomas L Holaday. This is all explained in a very good paper by Rafe Kapla: Modeling Entity Relationships.
Filtering models with ReferenceProperties
I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties. eg. class Group(db.Model): name = db.StringProperty(required=True) creator = db.ReferenceProperty(User) class GroupMember(db.Model): group = db.ReferenceProperty(Group) user = db.ReferenceProperty(User) And I have tried writing something like this: members = models.GroupMember.all().filter('group.name =', group_name) and various other things that don't work. Hopefully someone can give me a prod in the right direction...
[ "If your groups are uniquely named, then your \"group.name\" is a unique identifier of a Group entity.\nThat means you can write:\n members = models.GroupMember.all().filter(\n \"group =\",model.Group.gql(\"WHERE name=:1\", group_name).get()\n )\n\nthough you only need to do that if you don't already have the group entity lying around in the stack somewhere.\nGoogle's essay on many-to-many with appengine is here.\n", "If what you want is to get the members of a group, ReferenceProperties have that built-in. \nclass GroupMember(db.Model):\n group = db.ReferenceProperty(Group, collection_name=\"groupMembers\")\n user = db.ReferenceProperty(User, collection_name=\"groupMembers\")\n\nThen you can write:\n# get the group entity somehow\ngroup = Group.get(group_key) \n# do something with the members, such as list the nicknames\nnicknames = [x.user.nickname for x in group.groupMembers]\n\n", "This would require a join, which isn't possible in App Engine. If you want to filter by a property of another model, you need to include that property on the model you're querying against.\n", "This would result in two datastore hits but should work. If you use memcache shouldnt be a problem.\ngroup = models.Group.all().filter(\"name =\", group_name).get()\nmembers = models.GroupMember.all().filter('group =', group) \n\n", "Using the Models that you defined in your question, lets say you want to list all members of a group called \"Space monkeys\".\nmygroup = Group.gql(\"WHERE name = :1\",'Space monkeys')\n\nfor group_member in mygroup.groupmember_set:\n print 'group members name is: %s' % (group_member.user.name)\n\nThe \"groupmember_set\" is called a \"implicit collection property\" and is very useful. You can call it whatever you want by over-riding the default name using the collection_name keyword parameter to ReferenceProperty. For an example see the answer by Thomas L Holaday.\nThis is all explained in a very good paper by Rafe Kapla: Modeling Entity Relationships.\n" ]
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000448120_google_app_engine_python.txt
Q: gnomevfs or gio? For async IO using Python, is it preferable to rely on gio or gnomevfs? Also, which one is more "cross-platform"? A: Use GIO. GnomeVFS has been deprecated since GNOME 2.22, in favour of GIO.
gnomevfs or gio?
For async IO using Python, is it preferable to rely on gio or gnomevfs? Also, which one is more "cross-platform"?
[ "Use GIO.\nGnomeVFS has been deprecated since GNOME 2.22, in favour of GIO.\n" ]
[ 4 ]
[]
[]
[ "gio", "python" ]
stackoverflow_0002134691_gio_python.txt
Q: PID files hanging around for daemons after server restart I have some daemons that use PID files to prevent parallel execution of my program. I have set up a signal handler to trap SIGTERM and do the necessary clean-up including the PID file. This works great when I test using "kill -s SIGTERM #PID". However, when I reboot the server the PID files are still hanging around preventing start-up of the daemons. It is my understanding that SIGTERM is sent to all processes when a server is shutting down. Should I be trapping another signal (SIGINT, SIGQUIT?) in my daemon? A: Use flock (or lockf) on your pidfile, if it succeeds, you can rewrite the pidfile and continue. This SO answer has a good example on how this is done. A: Not a direct solution but it might be a good idea to check for an actual process running with the pid in the pid file at startup and if none exists, to cleanup the stale file. It's possible that your process is getting a SIGKILL before it has a chance to cleanup the pid file. A: Remember that, after sending SIGTERM to all processes, the kernel wait some time (usually about 2 or 3 seconds), and then send SIGKILL. You can find that in /etc/rc.d/rc0.d/S01halt or similar (might vary depending on your distribution). For example, on my Fedora 11 you have: action $"Sending all processes the TERM signal..." /sbin/killall5 -15 sleep 2 action $"Sending all processes the KILL signal..." /sbin/killall5 -9 So if you are not fast enough, either increase the delay, or make sure you are faster!
PID files hanging around for daemons after server restart
I have some daemons that use PID files to prevent parallel execution of my program. I have set up a signal handler to trap SIGTERM and do the necessary clean-up including the PID file. This works great when I test using "kill -s SIGTERM #PID". However, when I reboot the server the PID files are still hanging around preventing start-up of the daemons. It is my understanding that SIGTERM is sent to all processes when a server is shutting down. Should I be trapping another signal (SIGINT, SIGQUIT?) in my daemon?
[ "Use flock (or lockf) on your pidfile, if it succeeds, you can rewrite the pidfile and continue.\nThis SO answer has a good example on how this is done.\n", "Not a direct solution but it might be a good idea to check for an actual process running with the pid in the pid file at startup and if none exists, to cleanup the stale file. \nIt's possible that your process is getting a SIGKILL before it has a chance to cleanup the pid file.\n", "Remember that, after sending SIGTERM to all processes, the kernel wait some time (usually about 2 or 3 seconds), and then send SIGKILL. You can find that in /etc/rc.d/rc0.d/S01halt or similar (might vary depending on your distribution).\nFor example, on my Fedora 11 you have:\naction $\"Sending all processes the TERM signal...\" /sbin/killall5 -15\nsleep 2\naction $\"Sending all processes the KILL signal...\" /sbin/killall5 -9\n\nSo if you are not fast enough, either increase the delay, or make sure you are faster!\n" ]
[ 4, 3, 2 ]
[]
[]
[ "linux", "python", "sigterm" ]
stackoverflow_0002134732_linux_python_sigterm.txt
Q: Looking for input in model design for Django Schools Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input. Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems. Features: - Create multiple schools - Track student population per school - Track student demographics, parent contact info, etc. - Grade books - Transcripts - Track disciplinary record. - Fees schedules and payment tracking - Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic) -- Automated PDF report email to parents for student reports. Given those feature requirements, here is the model layout that I currently have: Models * Person o ID: char or int o FirstName: char o MiddleName: char o FamilyName: char o Sex: multiple choice o Ethnicity: multiple choice o BirthDate: date o Email: char o HomePhone: char o WordPhone: char o CellPhone: char o Address: one-to-one with Location * Student (inherent Person) o Classes: one-to-many with Class o Parents: one-to-many with Parent o Account: one-to-one with PaymentSchedule o Tasks: one-to-many with Tasks o Diciplin: one-to-many with Discipline * Parent (inherent Person) o Children: one-to-many with Student * Teacher (inherent Person) o Classes: one-to-many with Class * Location o Address: char o Address2: char o Address3: char o City: char o StateProvince: char o PostalCode: char o Country: multiple choice * Course o Name: char o Description: text field o Grade: int * Class o School: one-to-one with School o Course: one-to-one with Course o Teacher: one-to-one with Teacher o Students: one-to-many with Student * School o ID: char or int o Name: char o Location: one-to-one with location * Tasks o ID: auto increment o Type: multiple choice (assignment, test, etc.) o DateAssigned: date o DateCompleted: date o Score: real o Weight: real o Class: one-to-one with class o Student: one-to-one with Student * Discipline o ID: auto-increment o Discription: text-field o Reaction: text-field o Students: one-to-many with Student * PaymentSchedule o ID: auto-increment o YearlyCost: real o PaymentSchedule: multiple choice o ScholarshipType: multiple choice, None if N/A o ScholarshipAmount: real, 0 if N/A o Transactions: one-to-many with Payments * Payments o auto-increment o Amount: real o Date: date If you have ideas on how this could be improved upon, I'd love to year them! Update I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link. http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files A: From a quick look I think that its fairly comprehensive. Perhaps you should allow multiple teachers on a course, and allow reuse of addresses/locations between parents and students. As a general rule I would say that you should start implementing and then you will find where you need improvement. A: Some possible issues: For the location object, what if in the future you need to hold a home address, work address, etc. for a person? Same for email addresses and phone numbers - I would have phone numbers be their own object. Include an Address_3 on your address object. A: Looks like an interesting project. Do note that Django has higher-level types than SQL, so you can make use of things like the email address type. If you're planning on targeting GAE, you should find a similarly rich set of model types. A: hey...i agree...it looks pretty good. someone advised me to use auto-increment on all tables just to be sure there really is a unique id on every record. it's your choice if you'd like to go that route. A: You should link paiement (transaction) to the person concerned. A: I would advise you to not worry about the underling relational database. Yes, you'll need to understand what a foreign key is and the difference between many-to-many and one-to-many, etc., but you should think about your models in terms of Django classes. That's how you'll have to write them anyway, so that's where I would start. The Django documenation on models is great, and will help you a lot. I think everyone here would be glad to help you with the Python classes; you should rewrite your example using Django. For example, your Person table would look like this: from django.db import models SEX_CHOICES = ( ('M', 'Male'), ('F', 'Female') ) ETHNICITY_CHOICES = ( # follow the same format as SEX_CHOICES: # (database_value, human_friendly_name) ) class Person(models.Model): first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) familiy_name = models.CharField(max_length=200) sex = models.CharField(max_length=1, choices=SEX_CHOICES) ethnicity = models.CharField(max_length=1, choices=ETHNICITY_CHOICES) birth_date = models.DateField() email = models.EmailField() home_phone = models.CharField(max_length=10) # USA phone numbers work_phone = models.CharField(max_length=10) cell_phone = models.CharField(max_length=10) address = models.ForeignKey(Location) class Location(models.Model): # left as an exercise for the reader # more classes... A: A student doesn't have a class. He/She attends a class that has them (in the roster). Here's another way to look at the class situation. (notice the model's name. that's just because I tend not to name anything 'Class' because it's easy to get into name clashes that way.) class SchoolClass(models.Model): teacher = models.ManyToManyField(Teacher, related_name='teachers') student = models.ManyToManyField(Student, related_name='students') prerequisites = models.ForeignKey('self') startdate = models.DateField() enddate = models.DateField() ... and so on ... This is more natural because you can have a class with students and take attendance according to the students list, or aggregate grades, student ages, etc. in a natural way.
Looking for input in model design for Django Schools
Today I'm starting a little project to create a Django based school administration program. I'm currently designing the models and their corresponding relationships. Being rather new to Django and relational databases in general, I would like some input. Before I show you the current model layout, you need to have an idea of what the program is meant to do. Keep in mind that it is my goal for the software to be usable by both individual schools and entire school systems. Features: - Create multiple schools - Track student population per school - Track student demographics, parent contact info, etc. - Grade books - Transcripts - Track disciplinary record. - Fees schedules and payment tracking - Generate reports (student activity, student transcripts, class progress, progress by demographic, payment reports, disciplinary report by student class and demographic) -- Automated PDF report email to parents for student reports. Given those feature requirements, here is the model layout that I currently have: Models * Person o ID: char or int o FirstName: char o MiddleName: char o FamilyName: char o Sex: multiple choice o Ethnicity: multiple choice o BirthDate: date o Email: char o HomePhone: char o WordPhone: char o CellPhone: char o Address: one-to-one with Location * Student (inherent Person) o Classes: one-to-many with Class o Parents: one-to-many with Parent o Account: one-to-one with PaymentSchedule o Tasks: one-to-many with Tasks o Diciplin: one-to-many with Discipline * Parent (inherent Person) o Children: one-to-many with Student * Teacher (inherent Person) o Classes: one-to-many with Class * Location o Address: char o Address2: char o Address3: char o City: char o StateProvince: char o PostalCode: char o Country: multiple choice * Course o Name: char o Description: text field o Grade: int * Class o School: one-to-one with School o Course: one-to-one with Course o Teacher: one-to-one with Teacher o Students: one-to-many with Student * School o ID: char or int o Name: char o Location: one-to-one with location * Tasks o ID: auto increment o Type: multiple choice (assignment, test, etc.) o DateAssigned: date o DateCompleted: date o Score: real o Weight: real o Class: one-to-one with class o Student: one-to-one with Student * Discipline o ID: auto-increment o Discription: text-field o Reaction: text-field o Students: one-to-many with Student * PaymentSchedule o ID: auto-increment o YearlyCost: real o PaymentSchedule: multiple choice o ScholarshipType: multiple choice, None if N/A o ScholarshipAmount: real, 0 if N/A o Transactions: one-to-many with Payments * Payments o auto-increment o Amount: real o Date: date If you have ideas on how this could be improved upon, I'd love to year them! Update I've written the initial models.py code, which is probably in need of much love. If you would like to take a look, or even join the project, check out the link. http://bazaar.launchpad.net/~djangoschools/djangoschools/trunk/files
[ "From a quick look I think that its fairly comprehensive. Perhaps you should allow multiple teachers on a course, and allow reuse of addresses/locations between parents and students.\nAs a general rule I would say that you should start implementing and then you will find where you need improvement.\n", "Some possible issues:\nFor the location object, what if in the future you need to hold a home address, work address, etc. for a person? Same for email addresses and phone numbers - I would have phone numbers be their own object.\nInclude an Address_3 on your address object.\n", "Looks like an interesting project. Do note that Django has higher-level types than SQL, so you can make use of things like the email address type.\nIf you're planning on targeting GAE, you should find a similarly rich set of model types.\n", "hey...i agree...it looks pretty good. someone advised me to use auto-increment on all tables just to be sure there really is a unique id on every record. it's your choice if you'd like to go that route.\n", "You should link paiement (transaction) to the person concerned.\n", "I would advise you to not worry about the underling relational database. Yes, you'll need to understand what a foreign key is and the difference between many-to-many and one-to-many, etc., but you should think about your models in terms of Django classes. That's how you'll have to write them anyway, so that's where I would start. The Django documenation on models is great, and will help you a lot.\nI think everyone here would be glad to help you with the Python classes; you should rewrite your example using Django. For example, your Person table would look like this:\nfrom django.db import models\n\nSEX_CHOICES = (\n ('M', 'Male'),\n ('F', 'Female')\n)\n\nETHNICITY_CHOICES = (\n # follow the same format as SEX_CHOICES:\n # (database_value, human_friendly_name)\n)\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=200)\n middle_name = models.CharField(max_length=200)\n familiy_name = models.CharField(max_length=200) \n\n sex = models.CharField(max_length=1, choices=SEX_CHOICES)\n ethnicity = models.CharField(max_length=1, choices=ETHNICITY_CHOICES)\n birth_date = models.DateField()\n\n email = models.EmailField()\n home_phone = models.CharField(max_length=10) # USA phone numbers\n work_phone = models.CharField(max_length=10)\n cell_phone = models.CharField(max_length=10)\n address = models.ForeignKey(Location)\n\nclass Location(models.Model):\n # left as an exercise for the reader\n\n# more classes...\n\n", "A student doesn't have a class. He/She attends a class that has them (in the roster). Here's another way to look at the class situation. (notice the model's name. that's just because I tend not to name anything 'Class' because it's easy to get into name clashes that way.)\nclass SchoolClass(models.Model):\n teacher = models.ManyToManyField(Teacher, related_name='teachers')\n student = models.ManyToManyField(Student, related_name='students')\n prerequisites = models.ForeignKey('self')\n startdate = models.DateField()\n enddate = models.DateField()\n ... and so on ...\n\nThis is more natural because you can have a class with students and take attendance according to the students list, or aggregate grades, student ages, etc. in a natural way.\n" ]
[ 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000344826_django_django_models_python.txt
Q: Writing Pythons Errors to a txt file I am having trouble getting this to work correctly (obviously) - I am ALMOST there, and I have a good idea of WHY it is not working - just not sure how to make it work. This is suppose to attempt to read a file into memory, if it fails it goes to the "except" clause of the block of code (that part is 'duh'). The error file prints: "<main.DebugOutput instance at 0x04021EB8>". What I want it to do is print the actual Error. Like a FileIOError or TraceBackError or whatever it is to that error file. This is just the beginning stages and I plan to add things like date stamps and to have it append, not write/create - I just need the actual error printed to the file. Advice? import os, sys try: myPidFile = "Zeznadata.txt" myOpenPID_File = open(myPidFile, "r") #Attempts to open the file print "Sucessfully opened the file: \"" + myPidFile + "\"." except: print "This file, \"" + myPidFile + "\", does not exist. Please check the file name and try again. " myFileErr = open("PIDErrorlog.txt", "w") myStdError = str(sys.stderr) myFileErr.write(myStdError) myFileErr.close() print "\nThis error was logged in the file (and stored in the directory): " A: First, you should use a logging library. It will help you deal with different logging levels (info/warn/error), timestamps and more. http://docs.python.org/library/logging.html Second, you need to catch the error, and then you can log details about it. This example comes from the Python documentation. import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) except ValueError: print "Could not convert data to an integer." except: print "Unexpected error:", sys.exc_info()[0] raise See how it catches an IOError and assigns the error number and error message to variables? You can have an except block for each type of error you want to deal with. In the last (generic error) block, it uses sys.exc_info()[0] to get the error details. http://docs.python.org/tutorial/errors.html A: the problem is here: myStdError = str(sys.stderr) myFileErr.write(myStdError) sys.stderr is a file-like interface defined in POSIX standards, called standard error, not "error text" that you can write to a file. So what you (probably) wanted to do is: sys.stderr = myFileErr This is the python equivalent to python your_python_sctipt.py 2> PIDErrorLog.txt in unix shell. A: Use the logging module. The logging module have exception formatters that will help you print exceptions in a pretty way. http://docs.python.org/library/logging.html A: Like Kimvais says, your problem is: myStdError = str(sys.stderr) myFileErr.write(myStdError) sys.stderr is a file handle to stderr (stdout is what print writes to). You should do something like: try: ...open file... except IOError as (errno, strerror): ...open errfile... errfile.write(strerror) errfile.close() Alison's answer is also very good and well written.
Writing Pythons Errors to a txt file
I am having trouble getting this to work correctly (obviously) - I am ALMOST there, and I have a good idea of WHY it is not working - just not sure how to make it work. This is suppose to attempt to read a file into memory, if it fails it goes to the "except" clause of the block of code (that part is 'duh'). The error file prints: "<main.DebugOutput instance at 0x04021EB8>". What I want it to do is print the actual Error. Like a FileIOError or TraceBackError or whatever it is to that error file. This is just the beginning stages and I plan to add things like date stamps and to have it append, not write/create - I just need the actual error printed to the file. Advice? import os, sys try: myPidFile = "Zeznadata.txt" myOpenPID_File = open(myPidFile, "r") #Attempts to open the file print "Sucessfully opened the file: \"" + myPidFile + "\"." except: print "This file, \"" + myPidFile + "\", does not exist. Please check the file name and try again. " myFileErr = open("PIDErrorlog.txt", "w") myStdError = str(sys.stderr) myFileErr.write(myStdError) myFileErr.close() print "\nThis error was logged in the file (and stored in the directory): "
[ "First, you should use a logging library. It will help you deal with different logging levels (info/warn/error), timestamps and more.\nhttp://docs.python.org/library/logging.html\nSecond, you need to catch the error, and then you can log details about it. This example comes from the Python documentation.\nimport sys\n\ntry:\n f = open('myfile.txt')\n s = f.readline()\n i = int(s.strip())\n\nexcept IOError as (errno, strerror):\n print \"I/O error({0}): {1}\".format(errno, strerror)\nexcept ValueError:\n print \"Could not convert data to an integer.\"\nexcept:\n print \"Unexpected error:\", sys.exc_info()[0]\n raise\n\nSee how it catches an IOError and assigns the error number and error message to variables? You can have an except block for each type of error you want to deal with. In the last (generic error) block, it uses sys.exc_info()[0] to get the error details.\nhttp://docs.python.org/tutorial/errors.html\n", "the problem is here:\n myStdError = str(sys.stderr)\n myFileErr.write(myStdError)\n\nsys.stderr is a file-like interface defined in POSIX standards, called standard error, not \"error text\" that you can write to a file. So what you (probably) wanted to do is:\nsys.stderr = myFileErr\n\nThis is the python equivalent to python your_python_sctipt.py 2> PIDErrorLog.txt in unix shell.\n", "Use the logging module. The logging module have exception formatters that will help you print exceptions in a pretty way.\nhttp://docs.python.org/library/logging.html\n", "Like Kimvais says, your problem is:\nmyStdError = str(sys.stderr)\nmyFileErr.write(myStdError)\n\nsys.stderr is a file handle to stderr (stdout is what print writes to).\nYou should do something like:\ntry:\n ...open file...\nexcept IOError as (errno, strerror):\n ...open errfile...\n errfile.write(strerror)\n errfile.close()\n\nAlison's answer is also very good and well written.\n" ]
[ 7, 3, 1, 0 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0002135174_error_handling_python.txt
Q: Using LaTeX Beamer to display code I'm using the following LaTeX code in a Beamer presentation: \begin{frame} \begin{figure} \centering \tiny \lstset{language=python} \lstinputlisting{code/get_extent.py} \end{figure} \end{frame} Is it possible to select specific lines from my get_extent.py file rather than displaying it all? A: This has nothing to do with beamer; it's about a listings feature. Its excellent manual has more. For example: \lstinputlisting[firstline=2,lastline=5]{code/get_extent.py}
Using LaTeX Beamer to display code
I'm using the following LaTeX code in a Beamer presentation: \begin{frame} \begin{figure} \centering \tiny \lstset{language=python} \lstinputlisting{code/get_extent.py} \end{figure} \end{frame} Is it possible to select specific lines from my get_extent.py file rather than displaying it all?
[ "This has nothing to do with beamer; it's about a listings feature. Its excellent manual has more. For example:\n\\lstinputlisting[firstline=2,lastline=5]{code/get_extent.py}\n\n" ]
[ 12 ]
[]
[]
[ "beamer", "latex", "python" ]
stackoverflow_0002135339_beamer_latex_python.txt
Q: python: processing a 16-element list into an 8-element list I have a list of 16 elements [a00,a01,a02,...,a15] and would like to compute a list [b0,b1,b2,b3,b4,b5,b6,b7] where b0 = a00*256+a01 b1 = a02*256+a03 b2 = a04*256+a05 (etc.) what's the easiest way of doing this? (I'm a beginner in python) A: b_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(8)] Note that this only works if a has 16 elements. A more general solution would be: b_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(len(a_list) / 2)] as long as a_list has an even number of elements. A: Not to get too golfy, but if you'd like to avoid subscript hell, you can use this handy zip idiom: a = range(16) b = [x*256+y for x,y in zip(*[iter(a)]*2)] A: You can make a comprehension list... a = [a00, a01,.... ] #Readed, take a list with 0,2,4... len(a) [15, will stop at 14] # then make a[i]*256 + a[i+1], so # a[0]*256+a[1], a[2]*256+a[3], ... a[14]*256+a[15] b = [ a[i]*256+a[i+1] for i in range(0,len(a),2) ] A: lst = [a01, a02, ... ] result = [256 * a + b for a, b in zip(lst[::2], lst[1::2])] This avoids the unpythonic use of range. A: The first thing that comes to mind: >>> a=range(16) >>> b=[a[i]*256+a[i+1] for i in range(0,len(a),+2)] [1, 515, 1029, 1543, 2057, 2571, 3085, 3599]
python: processing a 16-element list into an 8-element list
I have a list of 16 elements [a00,a01,a02,...,a15] and would like to compute a list [b0,b1,b2,b3,b4,b5,b6,b7] where b0 = a00*256+a01 b1 = a02*256+a03 b2 = a04*256+a05 (etc.) what's the easiest way of doing this? (I'm a beginner in python)
[ "b_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(8)]\nNote that this only works if a has 16 elements.\nA more general solution would be:\nb_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(len(a_list) / 2)]\nas long as a_list has an even number of elements.\n", "Not to get too golfy, but if you'd like to avoid subscript hell, you can use this handy zip idiom:\na = range(16)\nb = [x*256+y for x,y in zip(*[iter(a)]*2)]\n\n", "You can make a comprehension list...\na = [a00, a01,.... ]\n#Readed, take a list with 0,2,4... len(a) [15, will stop at 14]\n# then make a[i]*256 + a[i+1], so\n# a[0]*256+a[1], a[2]*256+a[3], ... a[14]*256+a[15]\nb = [ a[i]*256+a[i+1] for i in range(0,len(a),2) ]\n\n", "lst = [a01, a02, ... ]\nresult = [256 * a + b for a, b in zip(lst[::2], lst[1::2])]\n\nThis avoids the unpythonic use of range.\n", "The first thing that comes to mind:\n>>> a=range(16)\n>>> b=[a[i]*256+a[i+1] for i in range(0,len(a),+2)]\n[1, 515, 1029, 1543, 2057, 2571, 3085, 3599]\n\n" ]
[ 4, 4, 2, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002135454_list_python.txt
Q: parsing a text string for dates - not the standard convert problem! Does anyone know of a library - ideally Python, that can have a stab at pulling dates out of text? "Shall we go to the library today" -> 21 Jan 10 "Starting on the 1st of January" -> 1 Jan 10 "Anytime between 3nd and 5th of Feb 2009" -> 3 Feb 09, 5 Feb 09 It's a tough problem and probably why I havn't found anything! Already using NLTK by the way if that helps. A: Looks like this module is what you are looking for: parsedatetime A: The PyParsing site has a little bonus script for parsing time expressions. I would say that is worth a look for you! Edit: I see you already ended up there as I was typing my suggestion. Good luck to you! A: Thanks for the contributions - in the end I followed up one of the comments, that led to pyparsing, which led to the beginnings of a solution. many thanks all. Have posted the work in progress, two pyparsing snippets of code here http://pbjots.blogspot.com/2010/01/using-pyparsing-to-extract-dates-from.html in case they help anyone.
parsing a text string for dates - not the standard convert problem!
Does anyone know of a library - ideally Python, that can have a stab at pulling dates out of text? "Shall we go to the library today" -> 21 Jan 10 "Starting on the 1st of January" -> 1 Jan 10 "Anytime between 3nd and 5th of Feb 2009" -> 3 Feb 09, 5 Feb 09 It's a tough problem and probably why I havn't found anything! Already using NLTK by the way if that helps.
[ "Looks like this module is what you are looking for: parsedatetime\n", "The PyParsing site has a little bonus script for parsing time expressions. I would say that is worth a look for you!\nEdit: I see you already ended up there as I was typing my suggestion. Good luck to you!\n", "Thanks for the contributions - in the end I followed up one of the comments, that led to pyparsing, which led to the beginnings of a solution. many thanks all.\nHave posted the work in progress, two pyparsing snippets of code here http://pbjots.blogspot.com/2010/01/using-pyparsing-to-extract-dates-from.html in case they help anyone.\n" ]
[ 4, 2, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0002109014_parsing_python.txt
Q: Creating a socket restricted to localhost connections only I have a python program with many threads. I was thinking of creating a socket, bind it to localhost, and have the threads read/write to this central location. However I do not want this socket open to the rest of the network, just connections from 127.0.0.1 should be accepted. How would I do this (in Python)? And is this a suitable design? Or is there something a little more elegant? A: Given a socket created with socket.socket(), you can use bind() before listening: socket.bind(('127.0.0.1', 80)) Using the address 127.0.0.1 indicates that the socket should bind to the local interface only. A: http://www.amk.ca/python/howto/sockets/ Shows some socket example. This tidbit is interesting to you I think we used socket.gethostname() so that the socket would be visible to the outside world. If we had used s.bind(('', 80)) or s.bind(('localhost', 80)) or s.bind(('127.0.0.1', 80)) we would still have a "server" socket, but one that was only visible within the same machine. I guess there is your answer (see below for correction) As to the validity of using this method for thread communications. I'm not sure how well this handles multiple threads and reading/writing EDIT There seems to be a python recipe linked below that does some inter-thread communication http://code.activestate.com/recipes/491281/ Have fun! EDIT The article is incorrect and as pointed out "s.bind(('', 80)) will bind to INADDR_ANY" A: If you are running on a UNIX-based system, you might want to consider using UNIX Domain Sockets instead of Internet sockets. I think something like the following should work: >>> # in one window/shell >>> import socket >>> sd = socket.socket(socket.AF_UNIX) >>> sd.bind('/path/to/my/socket') >>> sd.listen(5) >>> (client,addr) = sd.accept() >>> client.recv(1024) 'hello' >>> >>> # in a different shell >>> import socket >>> sd = socket.socket(socket.AF_UNIX) >>> sd.connect('/path/to/my/socket') >>> sd.send('hello') A: You might want to use the queue module from the standard library instead. It's designed specifically to facilitate communication between threads. A quote from the docs: The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module. A: If you do sock.bind((port,'127.0.0.1')) it will only listen on localhost, and not on other interfaces, so that's all you need. A: notionOn TCP/IP networks 127.0.0.0/8 is a non-routeable network, so you should not be able to send an IP datagram destined to 127.0.0.1 across a routed infrastructure. The router will just discard the datagram. However, it is possible to construct and send datagrams with a destination address of 127.0.0.1, so a host on the same network (IP sense of network) as your host could possibly get the datagram to your host's TCP/IP stack. This is where your local firewal comes into play. Your local (host) firewall should have a rule that discards IP datagrams destined for 127.0.0.0/8 coming into any interface other than lo0 (or the equivalent loopback interface). If your host either 1) has such firewall rules in place or 2) exists on its own network (or shared with only completely trusted hosts) and behind a well configured router, you can safely just bind to 127.0.0.1 and be fairly certain any datagrams you receive on the socket came from the local machine. The prior answers address how to open and bind to 127.0.0.1.
Creating a socket restricted to localhost connections only
I have a python program with many threads. I was thinking of creating a socket, bind it to localhost, and have the threads read/write to this central location. However I do not want this socket open to the rest of the network, just connections from 127.0.0.1 should be accepted. How would I do this (in Python)? And is this a suitable design? Or is there something a little more elegant?
[ "Given a socket created with socket.socket(), you can use bind() before listening:\nsocket.bind(('127.0.0.1', 80))\n\nUsing the address 127.0.0.1 indicates that the socket should bind to the local interface only.\n", "http://www.amk.ca/python/howto/sockets/\nShows some socket example. This tidbit is interesting to you I think\n\nwe used socket.gethostname() so that the socket would be visible to the outside world. If we had used s.bind(('', 80)) or s.bind(('localhost', 80)) or s.bind(('127.0.0.1', 80)) we would still have a \"server\" socket, but one that was only visible within the same machine. \n\nI guess there is your answer (see below for correction)\nAs to the validity of using this method for thread communications. I'm not sure how well this handles multiple threads and reading/writing\nEDIT\nThere seems to be a python recipe linked below that does some inter-thread communication\nhttp://code.activestate.com/recipes/491281/\nHave fun!\nEDIT\nThe article is incorrect and as pointed out \"s.bind(('', 80)) will bind to INADDR_ANY\"\n", "If you are running on a UNIX-based system, you might want to consider using UNIX Domain Sockets instead of Internet sockets. I think something like the following should work:\n>>> # in one window/shell\n>>> import socket\n>>> sd = socket.socket(socket.AF_UNIX)\n>>> sd.bind('/path/to/my/socket')\n>>> sd.listen(5)\n>>> (client,addr) = sd.accept()\n>>> client.recv(1024)\n'hello'\n>>>\n\n>>> # in a different shell\n>>> import socket\n>>> sd = socket.socket(socket.AF_UNIX)\n>>> sd.connect('/path/to/my/socket')\n>>> sd.send('hello')\n\n", "You might want to use the queue module from the standard library instead. It's designed specifically to facilitate communication between threads. A quote from the docs:\n\nThe Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.\n\n", "If you do sock.bind((port,'127.0.0.1')) it will only listen on localhost, and not on other interfaces, so that's all you need.\n", "notionOn TCP/IP networks 127.0.0.0/8 is a non-routeable network, so you should not be able to send an IP datagram destined to 127.0.0.1 across a routed infrastructure. The router will just discard the datagram. However, it is possible to construct and send datagrams with a destination address of 127.0.0.1, so a host on the same network (IP sense of network) as your host could possibly get the datagram to your host's TCP/IP stack. This is where your local firewal comes into play. Your local (host) firewall should have a rule that discards IP datagrams destined for 127.0.0.0/8 coming into any interface other than lo0 (or the equivalent loopback interface). If your host either 1) has such firewall rules in place or 2) exists on its own network (or shared with only completely trusted hosts) and behind a well configured router, you can safely just bind to 127.0.0.1 and be fairly certain any datagrams you receive on the socket came from the local machine. The prior answers address how to open and bind to 127.0.0.1.\n" ]
[ 8, 5, 3, 2, 0, 0 ]
[]
[]
[ "client_server", "python" ]
stackoverflow_0002135595_client_server_python.txt
Q: Enumerate a DateRange I have 2 dates and I am trying to build labels of an x-axis of a plot. As such, I need a way to take 2 datetime objects, i.e 2009-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a list like so: ["2009-10-12", "2009-10-13", "2009-10-14", ..., "2009-10-19", "2009-10-20"] What libraries should I use to assist? I have a feeling the datetime module and the timedelta functionality will help quite a bit. I can include code if it makes sense to, but I have a feeling there's something built in to the python libraries that allow for this to be real easy. I seem to just be missing it. A: import datetime first=datetime.date(2009,10,12) last=datetime.date(2009,10,20) adate=first dates=[] while adate<=last: dates.append(adate) adate+=datetime.timedelta(1) print(dates) Or, for lovers of list comprehension: len=(last-first).days dates=[first+datetime.timedelta(n) for n in range(len+1)] A: from datetime import date, timedelta a, b = date(1010, 10, 12), date(1010, 10, 20) times = [a + timedelta(x) for x in xrange((b-a).days)] # If you want to format them: times = [x.strftime('%Y-%m-%d') for x in times]
Enumerate a DateRange
I have 2 dates and I am trying to build labels of an x-axis of a plot. As such, I need a way to take 2 datetime objects, i.e 2009-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a list like so: ["2009-10-12", "2009-10-13", "2009-10-14", ..., "2009-10-19", "2009-10-20"] What libraries should I use to assist? I have a feeling the datetime module and the timedelta functionality will help quite a bit. I can include code if it makes sense to, but I have a feeling there's something built in to the python libraries that allow for this to be real easy. I seem to just be missing it.
[ "import datetime\n\nfirst=datetime.date(2009,10,12)\nlast=datetime.date(2009,10,20)\nadate=first\ndates=[]\nwhile adate<=last:\n dates.append(adate)\n adate+=datetime.timedelta(1)\nprint(dates)\n\nOr, for lovers of list comprehension:\nlen=(last-first).days\ndates=[first+datetime.timedelta(n) for n in range(len+1)]\n\n", "from datetime import date, timedelta\n\na, b = date(1010, 10, 12), date(1010, 10, 20)\ntimes = [a + timedelta(x) for x in xrange((b-a).days)]\n\n# If you want to format them:\ntimes = [x.strftime('%Y-%m-%d') for x in times]\n\n" ]
[ 2, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002136151_datetime_python.txt
Q: Interacting with a verified location? - Google Maps Ok so there are loads of Businesses marked on Google Maps these days. But I cannot interact with these in any way. This is the information I have: venue name: Ministry of Sound address: 103 Gaunt Street London, SE1 6DP Google's Geolocation only gives me Coordinates (lat, long) Formatted Address I want an application to access this page -> Ministry of Sound - Google Page I would like to: Add reviews (eg. sites like Qype, ViewLondon, Frommers do it!) Add photos and videos Add Other Content Also I would like to: Link an address to the Business automatically if possible eg. if the business shares the same address Edit: SilentGhost said "Google just indexes and aggregates information from the sites" If the only way to get reviews and information on the site is to get it indexed... how do I tell Google that what my site contains are: Photo of the Venues Reviews of the Venue Information about the Venue? Help would be very much appreciated. thanks! :) A: In response to your edited question: You should look at microformats like hReview, Google indexes and uses these in search results if not on the page you linked to. See: http://googlewebmastercentral.blogspot.com/2009/05/introducing-rich-snippets.html A: I think there is a certain confusion here. The main reason that you cannot interact with this information and for the lack of API is because none of these things (reviews, photos, videos, other content) is actually owned by Google. Google just indexes and aggregates information from the sites like Qype, ViewLondon, etc. It is a catalogue of sorts to get an overview and explore certain aspects further. A: You probably would have to get in touch with Google to let them know about your site and get them to include your reviews in their maps. Have a look at this and this page which is specifically aimed at businesses who want to distribute their content through the Google apps. A: The Google product of local business entries you are referring to is called "Local Business Cent[er|re]". As far as I know, there is no API to access and manipulate these entries *. You can, however, add coupons, photos, videos, etc. via web interface, even in bulk. Note that you can not add reviews to your own listings. If you only want to access the Place Page, there are various ways (address, coordinates) to do so. * The closest it gets is the AdWords Location Extensions, which lets AdWords pull addresses directly from your Local Business Center (LBC) account (and put their map data into your ads).
Interacting with a verified location? - Google Maps
Ok so there are loads of Businesses marked on Google Maps these days. But I cannot interact with these in any way. This is the information I have: venue name: Ministry of Sound address: 103 Gaunt Street London, SE1 6DP Google's Geolocation only gives me Coordinates (lat, long) Formatted Address I want an application to access this page -> Ministry of Sound - Google Page I would like to: Add reviews (eg. sites like Qype, ViewLondon, Frommers do it!) Add photos and videos Add Other Content Also I would like to: Link an address to the Business automatically if possible eg. if the business shares the same address Edit: SilentGhost said "Google just indexes and aggregates information from the sites" If the only way to get reviews and information on the site is to get it indexed... how do I tell Google that what my site contains are: Photo of the Venues Reviews of the Venue Information about the Venue? Help would be very much appreciated. thanks! :)
[ "In response to your edited question: \nYou should look at microformats like hReview, Google indexes and uses these in search results if not on the page you linked to. See: http://googlewebmastercentral.blogspot.com/2009/05/introducing-rich-snippets.html\n", "I think there is a certain confusion here. The main reason that you cannot interact with this information and for the lack of API is because none of these things (reviews, photos, videos, other content) is actually owned by Google. Google just indexes and aggregates information from the sites like Qype, ViewLondon, etc. It is a catalogue of sorts to get an overview and explore certain aspects further.\n", "You probably would have to get in touch with Google to let them know about your site and get them to include your reviews in their maps. Have a look at this and this page which is specifically aimed at businesses who want to distribute their content through the Google apps.\n", "The Google product of local business entries you are referring to is called \"Local Business Cent[er|re]\". As far as I know, there is no API to access and manipulate these entries *. You can, however, add coupons, photos, videos, etc. via web interface, even in bulk. Note that you can not add reviews to your own listings.\nIf you only want to access the Place Page, there are various ways (address, coordinates) to do so.\n* The closest it gets is the AdWords Location Extensions, which lets AdWords pull addresses directly from your Local Business Center (LBC) account (and put their map data into your ads). \n" ]
[ 2, 1, 1, 0 ]
[]
[]
[ "django", "google_maps", "javascript", "python" ]
stackoverflow_0002121780_django_google_maps_javascript_python.txt
Q: Dynamic Django model creation based on existing DB table I'm trying to figure out how I can use the type() module to dynamically create a Django model based on existing DB tables without having to either write it out manually or use the manage.py generator to inspect the DB. Reason is my schema changes frequently -- adding new tables, adding/deleting columns, etc. Anyone have a good solution? Something similar to this would be awesome: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ A: You can look at inspectdb code, and instead of outputting code return classes.
Dynamic Django model creation based on existing DB table
I'm trying to figure out how I can use the type() module to dynamically create a Django model based on existing DB tables without having to either write it out manually or use the manage.py generator to inspect the DB. Reason is my schema changes frequently -- adding new tables, adding/deleting columns, etc. Anyone have a good solution? Something similar to this would be awesome: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/
[ "You can look at inspectdb code, and instead of outputting code return classes.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002136371_django_django_models_python.txt
Q: Python / Linux/ Daemon process trying to show gtk.messagedialog on Ubuntu 8/9, i'm trying to write a daemon in python, that monitors a certain network condition and informs the user using a gtk.messagedialog. I installed this script using rc-update. The daemon starts at boot, but doesn't show the dialog even after I login. I assume because init.d starts my daemon at tty1 and no gnome is available. Tried running the dialog through a subprocess, but it seems to inherit the same run environment. Whats the best practice for this sort of thing. A: If five users are logged in to X sessions, who gets the message? Everyone? If someone is logged in locally but only using the tty, and not X11, should they see the message? If someone is logged in remotely via ssh -X to run a graphic application on their own system off of your CPU, should they see the message? How would you get it to them? Linux is too flexible for your current approach. The standard way to do this is for any user who is interested in the kind of message you are sending to run an application that receives the message and displays it in a way of its choosing. Dbus is a popular way of setting up the messaging process. This way remote users or users logged in with TTY mode only still have an option for seeing the message. A: In order to find out whether your code works at all, you should first try and execute the daemon as normal program in a graphical shell (on a GNOME desktop). You could also call zenity. A: You may use notify-send (from libnotify-bin package) to send notifications to desktop users from your daemon.
Python / Linux/ Daemon process trying to show gtk.messagedialog
on Ubuntu 8/9, i'm trying to write a daemon in python, that monitors a certain network condition and informs the user using a gtk.messagedialog. I installed this script using rc-update. The daemon starts at boot, but doesn't show the dialog even after I login. I assume because init.d starts my daemon at tty1 and no gnome is available. Tried running the dialog through a subprocess, but it seems to inherit the same run environment. Whats the best practice for this sort of thing.
[ "If five users are logged in to X sessions, who gets the message? Everyone?\nIf someone is logged in locally but only using the tty, and not X11, should they see the message?\nIf someone is logged in remotely via ssh -X to run a graphic application on their own system off of your CPU, should they see the message? How would you get it to them?\nLinux is too flexible for your current approach. The standard way to do this is for any user who is interested in the kind of message you are sending to run an application that receives the message and displays it in a way of its choosing. Dbus is a popular way of setting up the messaging process. This way remote users or users logged in with TTY mode only still have an option for seeing the message.\n", "In order to find out whether your code works at all, you should first try and execute the daemon as normal program in a graphical shell (on a GNOME desktop).\nYou could also call zenity.\n", "You may use notify-send (from libnotify-bin package) to send notifications to desktop users from your daemon.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "daemon", "gtk", "linux", "python", "ubuntu" ]
stackoverflow_0002124455_daemon_gtk_linux_python_ubuntu.txt
Q: pyinstaller exe's not dying after sys.exit() I have a cherrypy app compiled with pyinstaller. One function does the following: cherrypy.engine.stop() sys.exit() the cherrypy engine stops without problem, but the process doesn't actually die and I can't figure out why. A: Try with os._exit(), which is a real system exit. I can't see why PyInstaller should change a thing when it comes to process quitting, though. A: One thing to keep in mind: sys.exit() doesn't actually kill the process: it raises SystemExit, which usually results in the process ending, but doesn't have to.
pyinstaller exe's not dying after sys.exit()
I have a cherrypy app compiled with pyinstaller. One function does the following: cherrypy.engine.stop() sys.exit() the cherrypy engine stops without problem, but the process doesn't actually die and I can't figure out why.
[ "Try with os._exit(), which is a real system exit. I can't see why PyInstaller should change a thing when it comes to process quitting, though.\n", "One thing to keep in mind: sys.exit() doesn't actually kill the process: it raises SystemExit, which usually results in the process ending, but doesn't have to.\n" ]
[ 1, 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0002129935_pyinstaller_python.txt
Q: Using multiple modules/types with Python C API? I've got two different Python extension modules; let's call them A and B. Module A contains a storage class type called container that I want to use within Module B as the return type of a class method. I can't seem to find any documentation on how I'm supposed to do this. I roughly followed this article to create the modules/classes, except I didn't declare all the methods as static, so they would be accessible: http://nedbatchelder.com/text/whirlext.html My question is then, how do I go about creating an instance of container that I can pass back as the PyObject* return value of a class method in module B? The container definition looks like this: typedef struct { PyObject_HEAD storageclass* cnt_; } container; I tried simply doing the following within the method in question, where container_init is the method I have registered as tp_init for the container class: pycnt::container* retval; pycnt::container_init(retval, NULL, NULL); return (PyObject*)retval; However according to the Python interpreter I'm getting back the class that I called the method on. (i.e., myclassinstance.mymethod() is returning myclassinstance). I'm obviously going about this the wrong way, but I have no idea what the right way is. Any suggestions? Just to cut anybody off that's going to suggest it - no I am not interested in using SWIG or Boost::Python. I tried that already and the underlying storage class for container didn't play nicely with either (SWIG couldn't even parse it). So far doing the extensions myself has been pretty painless, but I'm stumped on this one. A: Your problem is that type->tp_init doesn't do what you want. type->tp_init is called after an object is allocated to do the instantiation. You'd first have to allocate the object using type->tp_new, then pass that object as the first argument to type->tp_init. Since you pass an uninitialized pointer to tp_init, all bets are off. You typically don't call either function directly, though, and instead call one of PyObject_Call*() on the type object itself to create a new instance. Or provide a normal C function to create a new instance, a la PyFoo_New(). That said, the usual way to do intercommunication between two extension modules is to do it through the Python API. If you want module B to import and use module A, you call PyImport_Import() to get the module object, PyObject_GetAttrString() to get the type object you care about, and one of PyObject_Call*() to instantiate it. Any place you want to store a pointer to that type, you would just take a PyObject *.
Using multiple modules/types with Python C API?
I've got two different Python extension modules; let's call them A and B. Module A contains a storage class type called container that I want to use within Module B as the return type of a class method. I can't seem to find any documentation on how I'm supposed to do this. I roughly followed this article to create the modules/classes, except I didn't declare all the methods as static, so they would be accessible: http://nedbatchelder.com/text/whirlext.html My question is then, how do I go about creating an instance of container that I can pass back as the PyObject* return value of a class method in module B? The container definition looks like this: typedef struct { PyObject_HEAD storageclass* cnt_; } container; I tried simply doing the following within the method in question, where container_init is the method I have registered as tp_init for the container class: pycnt::container* retval; pycnt::container_init(retval, NULL, NULL); return (PyObject*)retval; However according to the Python interpreter I'm getting back the class that I called the method on. (i.e., myclassinstance.mymethod() is returning myclassinstance). I'm obviously going about this the wrong way, but I have no idea what the right way is. Any suggestions? Just to cut anybody off that's going to suggest it - no I am not interested in using SWIG or Boost::Python. I tried that already and the underlying storage class for container didn't play nicely with either (SWIG couldn't even parse it). So far doing the extensions myself has been pretty painless, but I'm stumped on this one.
[ "Your problem is that type->tp_init doesn't do what you want. type->tp_init is called after an object is allocated to do the instantiation. You'd first have to allocate the object using type->tp_new, then pass that object as the first argument to type->tp_init. Since you pass an uninitialized pointer to tp_init, all bets are off. You typically don't call either function directly, though, and instead call one of PyObject_Call*() on the type object itself to create a new instance. Or provide a normal C function to create a new instance, a la PyFoo_New().\nThat said, the usual way to do intercommunication between two extension modules is to do it through the Python API. If you want module B to import and use module A, you call PyImport_Import() to get the module object, PyObject_GetAttrString() to get the type object you care about, and one of PyObject_Call*() to instantiate it. Any place you want to store a pointer to that type, you would just take a PyObject *.\n" ]
[ 3 ]
[]
[]
[ "binding", "c", "python", "python_c_api", "python_extensions" ]
stackoverflow_0002136337_binding_c_python_python_c_api_python_extensions.txt
Q: Python web frontend, retaining interpreter state I have a python script that parses a large set of data into an internal memory structure, and implements various fetch functions on the structure. I want to built a simple web frontend for this script, with the condition that the data is only initialized/loaded once (since re-loading upon each fetch would consume too much time/resources). Essentially, the python handler needs to maintain its state between calls, so the data structure is preserved in memory. Note: PHP's exec() or similar will not work, as this instantiates a new python handler per request. I have heard vague references to using mod_python for this purpose? A: I have implemented a solution to a very similar problem. My solution was to use an xmlrpc server, specifically twisted.web.xmlrpc I have a method that allows for injection of new data, and have methods for retrieving the data. A: Use a persistent server like CherryPy or Twisted Web. All requests will be served by the same process.
Python web frontend, retaining interpreter state
I have a python script that parses a large set of data into an internal memory structure, and implements various fetch functions on the structure. I want to built a simple web frontend for this script, with the condition that the data is only initialized/loaded once (since re-loading upon each fetch would consume too much time/resources). Essentially, the python handler needs to maintain its state between calls, so the data structure is preserved in memory. Note: PHP's exec() or similar will not work, as this instantiates a new python handler per request. I have heard vague references to using mod_python for this purpose?
[ "I have implemented a solution to a very similar problem. My solution was to use an xmlrpc server, specifically \ntwisted.web.xmlrpc\n\nI have a method that allows for injection of new data, and have methods for retrieving the data. \n", "Use a persistent server like CherryPy or Twisted Web. All requests will be served by the same process.\n" ]
[ 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0002136457_php_python.txt
Q: Read last n lines of file (tail) without reading it line-by-line? Possible Duplicate: Get last n lines of a file with Python, similar to tail Hello, How can I have Python return the last n lines of a file without reading it line by line? A: Something like this: Use seek() to get something like the last 4096 bytes of a file. See how many newlines you have in those bytes. If you have n or more, then you're done. If you have fewer, then read the previous 4096 bytes until you're done. Not sure if there's a built-in way to do this.
Read last n lines of file (tail) without reading it line-by-line?
Possible Duplicate: Get last n lines of a file with Python, similar to tail Hello, How can I have Python return the last n lines of a file without reading it line by line?
[ "Something like this:\n\nUse seek() to get something like the last 4096 bytes of a file.\nSee how many newlines you have in those bytes. If you have n or more, then you're done. If you have fewer, then read the previous 4096 bytes until you're done.\n\nNot sure if there's a built-in way to do this.\n" ]
[ 1 ]
[]
[]
[ "file", "file_io", "python", "tail" ]
stackoverflow_0002136800_file_file_io_python_tail.txt
Q: python Qt: main widget scroll bar We are trying to put scrollbar on the main widget, so if the user resizes the main window, the scrollbar appears, and let he move up and down to see child widgets that is outside the smaller window widget, allowing it to move right and left. Here is the code for the main widget with the scroll-bar.. def centralWDG(self,MainWindow): self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.summaryBox = QtGui.QGroupBox("Project Management Layout") self.summaryBox.setMinimumHeight(300) self.summaryBox.setMinimumWidth(500) self.summaryBoxScroll = QtGui.QScrollArea() self.summaryBoxScroll.setFrameStyle(QtGui.QFrame.NoFrame) self.summaryBoxTopLayout = QtGui.QVBoxLayout(self.summaryBox) self.summaryBoxTopLayout.setContentsMargins(1,1,1,1) self.summaryBoxTopLayout.addWidget(self.summaryBoxScroll) self.summaryBoxScroll.setWidget(self.centralwidget) self.summaryBoxLayout = QtGui.QFormLayout() self.summaryBoxLayout.setSpacing(1) self.summaryBoxLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize) self.summaryBoxLayout = QtGui.QFormLayout(self.centralwidget) self.summaryBoxLayout.setSpacing(1) self.summaryBoxLayout.setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize) self.callchildGUIs() MainWindow.setCentralWidget(self.centralwidget) The system is started, all GUIs work nicely, but the scroll-bar doesn't show up, it doesn't matter if we resize the windows to very small size. So, what is missing here? All comments and suggestions are highly appreciated. A: You use centralWidget (which is a QWidget) as the central widget of the main window, the scroll area is never added to the window. Having it contain the central widget is not enough. The following code has been generated by pyuic: def setupUi(self, MainWindow): self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.scrollArea = QtGui.QScrollArea(self.centralwidget) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout.addWidget(self.scrollArea) self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea) self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 778, 527)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_2.setObjectName("verticalLayout_2") MainWindow.setCentralWidget(self.centralwidget) The scroll area is added to the layout of the central widget and has its own content widget. If you add controls to verticalLayout_2 (and scrollAreaWidgetContents as the parent widget), they will receive scroll bars. A: I added some of the suggestions you send me. thanks. To use self.scrollArea.setWidget(self.scrollAreaWidgetContents), scrollAreaWidgetContents must be declared first. Here is the code updated -- doing everything nicely: def centralWDG(self,MainWindow): self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName("verticalLayout") self.scrollArea = QtGui.QScrollArea() self.scrollArea.setWidgetResizable(False) self.scrollArea.setObjectName("scrollArea") self.scrollArea.setMinimumHeight(400) self.scrollArea.setMinimumWidth(400) self.scrollArea.setMaximumHeight(1200) self.scrollArea.setMaximumWidth(1200) self.verticalLayout.addWidget(self.scrollArea) self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea) self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1400, 1200)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.callchildGUIs(self.scrollAreaWidgetContents) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_2.setObjectName("verticalLayout_2") MainWindow.setCentralWidget(self.centralwidget) Now it works fine!
python Qt: main widget scroll bar
We are trying to put scrollbar on the main widget, so if the user resizes the main window, the scrollbar appears, and let he move up and down to see child widgets that is outside the smaller window widget, allowing it to move right and left. Here is the code for the main widget with the scroll-bar.. def centralWDG(self,MainWindow): self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.summaryBox = QtGui.QGroupBox("Project Management Layout") self.summaryBox.setMinimumHeight(300) self.summaryBox.setMinimumWidth(500) self.summaryBoxScroll = QtGui.QScrollArea() self.summaryBoxScroll.setFrameStyle(QtGui.QFrame.NoFrame) self.summaryBoxTopLayout = QtGui.QVBoxLayout(self.summaryBox) self.summaryBoxTopLayout.setContentsMargins(1,1,1,1) self.summaryBoxTopLayout.addWidget(self.summaryBoxScroll) self.summaryBoxScroll.setWidget(self.centralwidget) self.summaryBoxLayout = QtGui.QFormLayout() self.summaryBoxLayout.setSpacing(1) self.summaryBoxLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize) self.summaryBoxLayout = QtGui.QFormLayout(self.centralwidget) self.summaryBoxLayout.setSpacing(1) self.summaryBoxLayout.setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize) self.callchildGUIs() MainWindow.setCentralWidget(self.centralwidget) The system is started, all GUIs work nicely, but the scroll-bar doesn't show up, it doesn't matter if we resize the windows to very small size. So, what is missing here? All comments and suggestions are highly appreciated.
[ "You use centralWidget (which is a QWidget) as the central widget of the main window, the scroll area is never added to the window. Having it contain the central widget is not enough.\nThe following code has been generated by pyuic:\ndef setupUi(self, MainWindow):\n self.centralwidget = QtGui.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n\n self.scrollArea = QtGui.QScrollArea(self.centralwidget)\n self.scrollArea.setWidgetResizable(True)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.verticalLayout.addWidget(self.scrollArea)\n\n self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 778, 527))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n\n self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n\n MainWindow.setCentralWidget(self.centralwidget)\n\nThe scroll area is added to the layout of the central widget and has its own content widget. If you add controls to verticalLayout_2 (and scrollAreaWidgetContents as the parent widget), they will receive scroll bars.\n", "I added some of the suggestions you send me. thanks.\nTo use self.scrollArea.setWidget(self.scrollAreaWidgetContents), scrollAreaWidgetContents must be declared first. Here is the code updated -- doing everything nicely:\ndef centralWDG(self,MainWindow):\n self.centralwidget = QtGui.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n\n self.scrollArea = QtGui.QScrollArea()\n self.scrollArea.setWidgetResizable(False)\n self.scrollArea.setObjectName(\"scrollArea\")\n self.scrollArea.setMinimumHeight(400)\n self.scrollArea.setMinimumWidth(400)\n self.scrollArea.setMaximumHeight(1200)\n self.scrollArea.setMaximumWidth(1200)\n\n self.verticalLayout.addWidget(self.scrollArea)\n\n self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1400, 1200))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n\n self.callchildGUIs(self.scrollAreaWidgetContents)\n\n self.scrollArea.setWidget(self.scrollAreaWidgetContents)\n self.verticalLayout_2 = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n\n MainWindow.setCentralWidget(self.centralwidget)\n\nNow it works fine!\n" ]
[ 3, 1 ]
[]
[]
[ "python", "qt", "scrollbar", "widget" ]
stackoverflow_0002130446_python_qt_scrollbar_widget.txt
Q: shared data utilizing multiple processor in python I have a cpu intensive code which uses a heavy dictionary as data (around 250M data). I have a multicore processor and want to utilize it so that i can run more than one task at a time. The dictionary is mostly read only and may be updated once a day. How can i write this in python without duplicating the dictionary? I understand that python threads don't use native threads and will not offer true concurrency. Can i use multiprocessing module without data being serialized between processes? I come from java world and my requirement would be something like java threads which can share data, run on multiple processors and offers synchronization primitives. A: Use shelve for the dictionary. Since writes are infrequent there shouldn't be an issue with sharing it. A: You can share read-only data among processes simply with a fork (on Unix; no easy way on Windows), but that won't catch the "once a day change" (you'd need to put an explicit way in place for each process to update its own copy). Native Python structures like dict are just not designed to live at arbitrary addresses in shared memory (you'd have to code a dict variant supporting that in C) so they offer no solace. You could use Jython (or IronPython) to get a Python implementation with exactly the same multi-threading abilities as Java (or, respectively, C#), including multiple-processor usage by multiple simultaneous threads. A: Take a look at this in the stdlib: http://docs.python.org/library/multiprocessing.html There are a bunch of wonderful features that will allow you to share data structures between processes very easily.
shared data utilizing multiple processor in python
I have a cpu intensive code which uses a heavy dictionary as data (around 250M data). I have a multicore processor and want to utilize it so that i can run more than one task at a time. The dictionary is mostly read only and may be updated once a day. How can i write this in python without duplicating the dictionary? I understand that python threads don't use native threads and will not offer true concurrency. Can i use multiprocessing module without data being serialized between processes? I come from java world and my requirement would be something like java threads which can share data, run on multiple processors and offers synchronization primitives.
[ "Use shelve for the dictionary. Since writes are infrequent there shouldn't be an issue with sharing it.\n", "You can share read-only data among processes simply with a fork (on Unix; no easy way on Windows), but that won't catch the \"once a day change\" (you'd need to put an explicit way in place for each process to update its own copy). Native Python structures like dict are just not designed to live at arbitrary addresses in shared memory (you'd have to code a dict variant supporting that in C) so they offer no solace.\nYou could use Jython (or IronPython) to get a Python implementation with exactly the same multi-threading abilities as Java (or, respectively, C#), including multiple-processor usage by multiple simultaneous threads.\n", "Take a look at this in the stdlib:\nhttp://docs.python.org/library/multiprocessing.html\nThere are a bunch of wonderful features that will allow you to share data structures between processes very easily.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "concurrency", "python", "shared_memory" ]
stackoverflow_0002136885_concurrency_python_shared_memory.txt
Q: Python multiple inheritance: which __new__ to call? I have a class Parent. I want to define a __new__ for Parent so it does some magic upon instantiation (for why, see footnote). I also want children classes to inherit from this and other classes to get Parent's features. The Parent's __new__ would return an instance of a subclass of the child class's bases and the Parent class. This is how the child class would be defined: class Child(Parent, list): pass But now I don't know what __new__ to call in Parent's __new__. If I call object.__new__, the above Child example complains that list.__new__ should be called. But how would Parent know that? I made it work so it loops through all the __bases__, and call each __new__ inside a try: block: class Parent(object): def __new__(cls, *args, **kwargs): # There is a special wrapper function for instantiating instances of children # classes that passes in a 'bases' argument, which is the __bases__ of the # Children class. bases = kwargs.get('bases') if bases: cls = type('name', bases + (cls,), kwargs.get('attr', {})) for base in cls.__mro__: if base not in (cls, MyMainType): try: obj = base.__new__(cls) break except TypeError: pass return obj return object.__new__(cls) But this just looks like a hack. Surely, there must be a better way of doing this? Thanks. The reason I want to use __new__ is so I can return an object of a subclass that has some dynamic attributes (the magic __int__ attributes, etc) assigned to the class. I could have done this in __init__, but I would not be able to modify self.__class__ in __init__ if the new class has a different internal structure, which is the case here due to multiple inheritance. A: I think this will get you what you want: return super(Parent, cls).__new__(cls, *args, **kwargs) and you won't need the bases keyword argument. Unless I'm getting you wrong and you're putting that in there on purpose.
Python multiple inheritance: which __new__ to call?
I have a class Parent. I want to define a __new__ for Parent so it does some magic upon instantiation (for why, see footnote). I also want children classes to inherit from this and other classes to get Parent's features. The Parent's __new__ would return an instance of a subclass of the child class's bases and the Parent class. This is how the child class would be defined: class Child(Parent, list): pass But now I don't know what __new__ to call in Parent's __new__. If I call object.__new__, the above Child example complains that list.__new__ should be called. But how would Parent know that? I made it work so it loops through all the __bases__, and call each __new__ inside a try: block: class Parent(object): def __new__(cls, *args, **kwargs): # There is a special wrapper function for instantiating instances of children # classes that passes in a 'bases' argument, which is the __bases__ of the # Children class. bases = kwargs.get('bases') if bases: cls = type('name', bases + (cls,), kwargs.get('attr', {})) for base in cls.__mro__: if base not in (cls, MyMainType): try: obj = base.__new__(cls) break except TypeError: pass return obj return object.__new__(cls) But this just looks like a hack. Surely, there must be a better way of doing this? Thanks. The reason I want to use __new__ is so I can return an object of a subclass that has some dynamic attributes (the magic __int__ attributes, etc) assigned to the class. I could have done this in __init__, but I would not be able to modify self.__class__ in __init__ if the new class has a different internal structure, which is the case here due to multiple inheritance.
[ "I think this will get you what you want:\nreturn super(Parent, cls).__new__(cls, *args, **kwargs)\n\nand you won't need the bases keyword argument. Unless I'm getting you wrong and you're putting that in there on purpose.\n" ]
[ 4 ]
[]
[]
[ "class_hierarchy", "multiple_inheritance", "new_operator", "python" ]
stackoverflow_0002137150_class_hierarchy_multiple_inheritance_new_operator_python.txt
Q: Web2Py Working Directory Well I want to use WEb2Py because it's pretty nice.. I just need to change the working directory to the directory where all my modules/libraries/apps are so i can use them. I want to be able to import my real program when I use the web2py interface/applications. I need to do this instead of putting all my apps and stuff inside the Web2Py folder... I'm trying to give my program a web frontend without putting the program in the Web2Py folder.. Sorry if this is hard to understand . A: In any multi-threaded Python program (and not only Python) you should not use os.chdir and you should not change sys.path when you have more than one thread running. It is not safe because it affects other threads. Moreover you should not sys.path.append() in a loop because it may explode. All web frameworks are multi-threaded and requests are executed in a loop. Some web frameworks do not allow you to install/un-install applications without restarting the web server and therefore IF os.chdir/sys.path.append are only executed at startup then there is no problem. In web2py we want to be able to install/uninstall applications without restarting the web server. We want apps to be very dynamical (for example define models based on information provided with the http request). We want each app to have its own models folder and we want complete separation between apps so that if two apps need to different versions of the same module, they do not conflict with each other, so we provide APIs to do so (request.folder, local_import). You can still use the normal os.chdir and sys.path.append but you should do it outside threads (and this is not a web2py specific issue). You can use import anywhere you like as you would in any other Python program. I strongly suggest moving this discussion to the web2py mailing list. A: os.chdir lets you change the OS's working directory, but for your purposes (enabling imports of a bunch of modules &c which are constrained to live in some strange place) it seems better to add the needed directories to sys.path instead. A: I had to do this very thing. I have few modules that I wanted to use from my controllers. If you want to be able to use the code that resides in the modules directory in the controller, you can use: # use this in your controller code impname = local_import('module_in_modules', reload=True) # reload true will ensure that it will re load whenever # there are changes to the module Jay
Web2Py Working Directory
Well I want to use WEb2Py because it's pretty nice.. I just need to change the working directory to the directory where all my modules/libraries/apps are so i can use them. I want to be able to import my real program when I use the web2py interface/applications. I need to do this instead of putting all my apps and stuff inside the Web2Py folder... I'm trying to give my program a web frontend without putting the program in the Web2Py folder.. Sorry if this is hard to understand .
[ "In any multi-threaded Python program (and not only Python) you should not use os.chdir and you should not change sys.path when you have more than one thread running. It is not safe because it affects other threads. Moreover you should not sys.path.append() in a loop because it may explode.\nAll web frameworks are multi-threaded and requests are executed in a loop. Some web frameworks do not allow you to install/un-install applications without restarting the web server and therefore IF os.chdir/sys.path.append are only executed at startup then there is no problem.\nIn web2py we want to be able to install/uninstall applications without restarting the web server. We want apps to be very dynamical (for example define models based on information provided with the http request). We want each app to have its own models folder and we want complete separation between apps so that if two apps need to different versions of the same module, they do not conflict with each other, so we provide APIs to do so (request.folder, local_import).\nYou can still use the normal os.chdir and sys.path.append but you should do it outside threads (and this is not a web2py specific issue). You can use import anywhere you like as you would in any other Python program.\nI strongly suggest moving this discussion to the web2py mailing list.\n", "os.chdir lets you change the OS's working directory, but for your purposes (enabling imports of a bunch of modules &c which are constrained to live in some strange place) it seems better to add the needed directories to sys.path instead.\n", "I had to do this very thing. I have few modules that I wanted to use from my controllers. If you want to be able to use the code that resides in the modules directory in the controller, you can use:\n# use this in your controller code\nimpname = local_import('module_in_modules', reload=True)\n# reload true will ensure that it will re load whenever\n# there are changes to the module\n\nJay\n" ]
[ 5, 0, 0 ]
[]
[]
[ "directory", "python", "web2py" ]
stackoverflow_0001978188_directory_python_web2py.txt
Q: Pyparsing - where order of tokens in unpredictable I want to be able to pull out the type and count of letters from a piece of text where the letters could be in any order. There is some other parsing going on which I have working, but this bit has me stumped! input -> result "abc" -> [['a',1], ['b',1],['c',1]] "bbbc" -> [['b',3],['c',1]] "cccaa" -> [['a',2],['c',3]] I could use search or scan and repeat for each possible letter, but is there a clean way of doing it? This is as far as I got: from pyparsing import * def handleStuff(string, location, tokens): return [tokens[0][0], len(tokens[0])] stype = Word("abc").setParseAction(handleStuff) section = ZeroOrMore(stype("stype")) print section.parseString("abc").dump() print section.parseString("aabcc").dump() print section.parseString("bbaaa").dump() A: One solution: text = 'sufja srfjhvlasfjkhv lasjfvhslfjkv hlskjfvh slfkjvhslk' print([(x,text.count(x)) for x in set(text)]) No pyparsing involved, but it seems like overkill. A: I wasn't clear from your description whether the input characters could be mixed like "ababc", since in all your test cases, the letters were always grouped together. If the letters are always grouped together, you could use this pyparsing code: def makeExpr(ch): expr = Word(ch).setParseAction(lambda tokens: [ch,len(tokens[0])]) return expr expr = Each([Optional(makeExpr(ch)) for ch in "abc"]) for t in tests: print t,expr.parseString(t).asList() The Each construct takes care of matching out of order, and Word(ch) handles the 1-to-n repetition. The parse action takes care of converting the parsed tokens into the (character, count) tuples. A: I like Lennart's one-line solution. Alex mentions another great option if you're using 3.1 Yet another option is collections.defaultdict: >>> from collections import defaultdict >>> mydict = defaultdict(int) >>> for c in 'bbbc': ... mydict[c] += 1 ... >>> mydict defaultdict(<type 'int'>, {'c': 1, 'b': 3}) A: If you want a pure-pyparsing approach, this feels about right: from pyparsing import * # lambda to define expressions def makeExpr(ch): expr = Literal(ch).setResultsName(ch, listAllMatches=True) return expr expr = OneOrMore(MatchFirst(makeExpr(c) for c in "abc")) expr.setParseAction(lambda tokens: [[a,len(b)] for a,b in tokens.items()]) tests = """\ abc bbbc cccaa """.splitlines() for t in tests: print t,expr.parseString(t).asList() Prints: abc [['a', 1], ['c', 1], ['b', 1]] bbbc [['c', 1], ['b', 3]] cccaa [['a', 2], ['c', 3]] But this starts to get into an obscure code area, since it relies on some of the more arcane features of pyparsing. In general, I like frequency counters that use defaultdict (haven't tried Counter yet), since it's pretty clear just what you are doing. A: pyparsing apart -- in Python 3.1, collections.Counter makes such counting tasks really easy. A good version of Counter for Python 2 can be found here.
Pyparsing - where order of tokens in unpredictable
I want to be able to pull out the type and count of letters from a piece of text where the letters could be in any order. There is some other parsing going on which I have working, but this bit has me stumped! input -> result "abc" -> [['a',1], ['b',1],['c',1]] "bbbc" -> [['b',3],['c',1]] "cccaa" -> [['a',2],['c',3]] I could use search or scan and repeat for each possible letter, but is there a clean way of doing it? This is as far as I got: from pyparsing import * def handleStuff(string, location, tokens): return [tokens[0][0], len(tokens[0])] stype = Word("abc").setParseAction(handleStuff) section = ZeroOrMore(stype("stype")) print section.parseString("abc").dump() print section.parseString("aabcc").dump() print section.parseString("bbaaa").dump()
[ "One solution:\ntext = 'sufja srfjhvlasfjkhv lasjfvhslfjkv hlskjfvh slfkjvhslk'\nprint([(x,text.count(x)) for x in set(text)])\n\nNo pyparsing involved, but it seems like overkill.\n", "I wasn't clear from your description whether the input characters could be mixed like \"ababc\", since in all your test cases, the letters were always grouped together. If the letters are always grouped together, you could use this pyparsing code:\ndef makeExpr(ch):\n expr = Word(ch).setParseAction(lambda tokens: [ch,len(tokens[0])])\n return expr\n\nexpr = Each([Optional(makeExpr(ch)) for ch in \"abc\"])\n\nfor t in tests:\n print t,expr.parseString(t).asList()\n\nThe Each construct takes care of matching out of order, and Word(ch) handles the 1-to-n repetition. The parse action takes care of converting the parsed tokens into the (character, count) tuples.\n", "I like Lennart's one-line solution.\nAlex mentions another great option if you're using 3.1\nYet another option is collections.defaultdict:\n>>> from collections import defaultdict\n>>> mydict = defaultdict(int)\n>>> for c in 'bbbc':\n... mydict[c] += 1\n...\n>>> mydict\ndefaultdict(<type 'int'>, {'c': 1, 'b': 3})\n\n", "If you want a pure-pyparsing approach, this feels about right:\nfrom pyparsing import *\n\n# lambda to define expressions\ndef makeExpr(ch):\n expr = Literal(ch).setResultsName(ch, listAllMatches=True)\n return expr\n\nexpr = OneOrMore(MatchFirst(makeExpr(c) for c in \"abc\"))\nexpr.setParseAction(lambda tokens: [[a,len(b)] for a,b in tokens.items()])\n\n\ntests = \"\"\"\\\nabc\nbbbc\ncccaa\n\"\"\".splitlines()\n\nfor t in tests:\n print t,expr.parseString(t).asList()\n\nPrints:\nabc [['a', 1], ['c', 1], ['b', 1]]\nbbbc [['c', 1], ['b', 3]]\ncccaa [['a', 2], ['c', 3]]\n\nBut this starts to get into an obscure code area, since it relies on some of the more arcane features of pyparsing. In general, I like frequency counters that use defaultdict (haven't tried Counter yet), since it's pretty clear just what you are doing.\n", "pyparsing apart -- in Python 3.1, collections.Counter makes such counting tasks really easy. A good version of Counter for Python 2 can be found here.\n" ]
[ 6, 6, 3, 2, 1 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0002134416_pyparsing_python.txt
Q: multiprocess or threading in python? I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation? I attempted to use threading but had some trouble, often some of the tasks would never actually fire. A: If you are truly compute bound, using the multiprocessing module is probably the lightest weight solution (in terms of both memory consumption and implementation difficulty.) If you are I/O bound, using the threading module will usually give you good results. Make sure that you use thread safe storage (like the Queue) to hand data to your threads. Or else hand them a single piece of data that is unique to them when they are spawned. PyPy is focused on performance. It has a number of features that can help with compute-bound processing. They also have support for Software Transactional Memory, although that is not yet production quality. The promise is that you can use simpler parallel or concurrent mechanisms than multiprocessing (which has some awkward requirements.) Stackless Python is also a nice idea. Stackless has portability issues as indicated above. Unladen Swallow was promising, but is now defunct. Pyston is another (unfinished) Python implementation focusing on speed. It is taking an approach different to PyPy, which may yield better (or just different) speedups. A: Tasks runs like sequentially but you have the illusion that are run in parallel. Tasks are good when you use for file or connection I/O and because are lightweights. Multiprocess with Pool may be the right solution for you because processes runs in parallel so are very good with intensive computing because each process run in one CPU (or core). Setup multiprocess may be very easy: from multiprocessing import Pool def worker(input_item): output = do_some_work() return output pool = Pool() # it make one process for each CPU (or core) of your PC. Use "Pool(4)" to force to use 4 processes, for example. list_of_results = pool.map(worker, input_list) # Launch all automatically A: For small collections of data, simply create subprocesses with subprocess.Popen. Each subprocess can simply get it's piece of data from stdin or from command-line arguments, do it's processing, and simply write the result to an output file. When the subprocesses have all finished (or timed out), you simply merge the output files. Very simple. A: You might consider looking into Stackless Python. If you have control over the function that takes a long time, you can just throw some stackless.schedule()s in there (saying yield to the next coroutine), or else you can set Stackless to preemptive multitasking. In Stackless, you don't have threads, but tasklets or greenlets which are essentially very lightweight threads. It works great in the sense that there's a pretty good framework with very little setup to get multitasking going. However, Stackless hinders portability because you have to replace a few of the standard Python libraries -- Stackless removes reliance on the C stack. It's very portable if the next user also has Stackless installed, but that will rarely be the case. A: Using CPython's threading model will not give you any performance improvement, because the threads are not actually executed in parallel, due to the way garbage collection is handled. Multiprocess would allow parallel execution. Obviously in this case you have to have multiple cores available to farm out your parallel jobs to. There is much more information available in this related question. A: If you can easily partition and separate the data you have, it sounds like you should just do that partitioning externally, and feed them to several processes of your program. (i.e. several processes instead of threads) A: IronPython has real multithreading, unlike CPython and it's GIL. So depending on what you're doing it may be worth looking at. But it sounds like your use case is better suited to the multiprocessing module. To the guy who recommends stackless python, I'm not an expert on it, but it seems to me that he's talking about software "multithreading", which is actually not parallel at all (still runs in one physical thread, so cannot scale to multiple cores.) It's merely an alternative way to structure asynchronous (but still single-threaded, non-parallel) application. A: You may want to look at Twisted. It is designed for asynchronous network tasks.
multiprocess or threading in python?
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation? I attempted to use threading but had some trouble, often some of the tasks would never actually fire.
[ "If you are truly compute bound, using the multiprocessing module is probably the lightest weight solution (in terms of both memory consumption and implementation difficulty.)\nIf you are I/O bound, using the threading module will usually give you good results. Make sure that you use thread safe storage (like the Queue) to hand data to your threads. Or else hand them a single piece of data that is unique to them when they are spawned.\nPyPy is focused on performance. It has a number of features that can help with compute-bound processing. They also have support for Software Transactional Memory, although that is not yet production quality. The promise is that you can use simpler parallel or concurrent mechanisms than multiprocessing (which has some awkward requirements.) \nStackless Python is also a nice idea. Stackless has portability issues as indicated above. Unladen Swallow was promising, but is now defunct. Pyston is another (unfinished) Python implementation focusing on speed. It is taking an approach different to PyPy, which may yield better (or just different) speedups. \n", "Tasks runs like sequentially but you have the illusion that are run in parallel. Tasks are good when you use for file or connection I/O and because are lightweights.\nMultiprocess with Pool may be the right solution for you because processes runs in parallel so are very good with intensive computing because each process run in one CPU (or core).\nSetup multiprocess may be very easy:\nfrom multiprocessing import Pool\n\ndef worker(input_item):\n output = do_some_work()\n return output\n\npool = Pool() # it make one process for each CPU (or core) of your PC. Use \"Pool(4)\" to force to use 4 processes, for example.\nlist_of_results = pool.map(worker, input_list) # Launch all automatically\n\n", "For small collections of data, simply create subprocesses with subprocess.Popen.\nEach subprocess can simply get it's piece of data from stdin or from command-line arguments, do it's processing, and simply write the result to an output file.\nWhen the subprocesses have all finished (or timed out), you simply merge the output files.\nVery simple.\n", "You might consider looking into Stackless Python. If you have control over the function that takes a long time, you can just throw some stackless.schedule()s in there (saying yield to the next coroutine), or else you can set Stackless to preemptive multitasking.\nIn Stackless, you don't have threads, but tasklets or greenlets which are essentially very lightweight threads. It works great in the sense that there's a pretty good framework with very little setup to get multitasking going.\nHowever, Stackless hinders portability because you have to replace a few of the standard Python libraries -- Stackless removes reliance on the C stack. It's very portable if the next user also has Stackless installed, but that will rarely be the case.\n", "Using CPython's threading model will not give you any performance improvement, because the threads are not actually executed in parallel, due to the way garbage collection is handled. Multiprocess would allow parallel execution. Obviously in this case you have to have multiple cores available to farm out your parallel jobs to.\nThere is much more information available in this related question.\n", "If you can easily partition and separate the data you have, it sounds like you should just do that partitioning externally, and feed them to several processes of your program. (i.e. several processes instead of threads)\n", "IronPython has real multithreading, unlike CPython and it's GIL. So depending on what you're doing it may be worth looking at. But it sounds like your use case is better suited to the multiprocessing module.\nTo the guy who recommends stackless python, I'm not an expert on it, but it seems to me that he's talking about software \"multithreading\", which is actually not parallel at all (still runs in one physical thread, so cannot scale to multiple cores.) It's merely an alternative way to structure asynchronous (but still single-threaded, non-parallel) application.\n", "You may want to look at Twisted. It is designed for asynchronous network tasks. \n" ]
[ 30, 9, 7, 7, 0, 0, 0, 0 ]
[]
[]
[ "multiprocess", "multithreading", "python" ]
stackoverflow_0001226584_multiprocess_multithreading_python.txt
Q: Python,multi-threads,fetch webpages,download webpages I want to batch dowload webpages in one site. There are 5000000 urls links in my 'urls.txt' file. It's about 300M. How make a multi-threads link these urls and dowload these webpages? or How batch dowload these webpages? my ideas: with open('urls.txt','r') as f: for el in f: ##fetch these urls or twisted? Is there a good solution for it? A: If this isn't part of a larger program, then notnoop's idea of using some existing tool to accomplish this is a pretty good one. If a shell loop invoking wget solves your problem, that'll be a lot easier than anything involving more custom software development. However, if you need to fetch these resources as part of a larger program, then doing it with shell may not be ideal. In this case, I'll strongly recommend Twisted, which will make it easy to do many requests in parallel. A few years ago I wrote up an example of how to do just this. Take a look at http://jcalderone.livejournal.com/24285.html. A: Definitely downloading 5M web pages in one go is not a good idea, because you'll max out a lot of things, including your network bandwidth and your OS's file descriptors. I'd go in batches of 100-1000. You can use urllib.urlopen to get a socket and then just read() on several threads. You may be able to use select.select. If so, then go ahead and download all 1000 at once and distribute each file handle that select returns to say 10 worker threads. If select won't work, then limit your batches to 100 downloads and use one thread per download. Certainly you shouldn't start more than 100 threads as your OS might blow up or at least go a bit slow. A: First parse your file and push the urls into a queue then spawn 5-10 worker threads to pull urls out of the queue and download. Queue's are your friend with this. A: A wget script is probably simplest, but if you're looking for a python-twisted crawling solution, check out scrapy
Python,multi-threads,fetch webpages,download webpages
I want to batch dowload webpages in one site. There are 5000000 urls links in my 'urls.txt' file. It's about 300M. How make a multi-threads link these urls and dowload these webpages? or How batch dowload these webpages? my ideas: with open('urls.txt','r') as f: for el in f: ##fetch these urls or twisted? Is there a good solution for it?
[ "If this isn't part of a larger program, then notnoop's idea of using some existing tool to accomplish this is a pretty good one. If a shell loop invoking wget solves your problem, that'll be a lot easier than anything involving more custom software development.\nHowever, if you need to fetch these resources as part of a larger program, then doing it with shell may not be ideal. In this case, I'll strongly recommend Twisted, which will make it easy to do many requests in parallel.\nA few years ago I wrote up an example of how to do just this. Take a look at http://jcalderone.livejournal.com/24285.html.\n", "Definitely downloading 5M web pages in one go is not a good idea, because you'll max out a lot of things, including your network bandwidth and your OS's file descriptors. I'd go in batches of 100-1000. You can use urllib.urlopen to get a socket and then just read() on several threads. You may be able to use select.select. If so, then go ahead and download all 1000 at once and distribute each file handle that select returns to say 10 worker threads. If select won't work, then limit your batches to 100 downloads and use one thread per download. Certainly you shouldn't start more than 100 threads as your OS might blow up or at least go a bit slow.\n", "First parse your file and push the urls into a queue then spawn 5-10 worker threads to pull urls out of the queue and download. Queue's are your friend with this.\n", "A wget script is probably simplest, but if you're looking for a python-twisted crawling solution, check out scrapy\n" ]
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "twisted", "web_scraping" ]
stackoverflow_0002135047_python_twisted_web_scraping.txt
Q: Matching one-line JavaScript comments (//) with re I'd like to filter out (mostly one-line) comments from (mostly valid) JavaScript using python's re module. For example: // this is a comment var x = 2 // and this is a comment too var url = "http://www.google.com/" // and "this" too url += 'but // this is not a comment' // however this one is url += 'this "is not a comment' + " and ' neither is this " // only this I'm now trying this for more than half an hour without any success. Can anyone please help me? EDIT 1: foo = 'http://stackoverflow.com/' // these // are // comments // too // EDIT 2: bar = 'http://no.comments.com/' A: My regex powers had gone a bit stale so I've used your question to fresh what I remember. It became a fairly large regex mostly because I also wanted to filter multi-line comments. import re reexpr = r""" ( # Capture code "(?:\\.|[^"\\])*" # String literal | '(?:\\.|[^'\\])*' # String literal | (?:[^/\n"']|/[^/*\n"'])+ # Any code besides newlines or string literals | \n # Newline )| (/\* (?:[^*]|\*[^/])* \*/) # Multi-line comment | (?://(.*)$) # Comment $""" rx = re.compile(reexpr, re.VERBOSE + re.MULTILINE) This regex matches with three different subgroups. One for code and two for comment contents. Below is a example of how to extract those. code = r"""// this is a comment var x = 2 * 4 // and this is a comment too var url = "http://www.google.com/" // and "this" too url += 'but // this is not a comment' // however this one is url += 'this "is not a comment' + " and ' neither is this " // only this bar = 'http://no.comments.com/' // these // are // comments bar = 'text // string \' no // more //\\' // comments bar = 'http://no.comments.com/' bar = /var/ // comment /* comment 1 */ bar = open() /* comment 2 */ bar = open() /* comment 2b */// another comment bar = open( /* comment 3 */ file) // another comment """ parts = rx.findall(code) print '*' * 80, '\nCode:\n\n', '\n'.join([x[0] for x in parts if x[0].strip()]) print '*' * 80, '\nMulti line comments:\n\n', '\n'.join([x[1] for x in parts if x[1].strip()]) print '*' * 80, '\nOne line comments:\n\n', '\n'.join([x[2] for x in parts if x[2].strip()]) A: It might be easier to parse if you had explicit semi-colons. In any case, this works: import re rx = re.compile(r'.*(//(.*))$') lines = ["// this is a comment", "var x = 2 // and this is a comment too", """var url = "http://www.google.com/" // and "this" too""", """url += 'but // this is not a comment' // however this one is""", """url += 'this "is not a comment' + " and ' neither is this " // only this""",] for line in lines: print rx.match(line).groups() Output of the above: ('// this is a comment', ' this is a comment') ('// and this is a comment too', ' and this is a comment too') ('// and "this" too', ' and "this" too') ('// however this one is', ' however this one is') ('// only this', ' only this') I'm not sure what you're doing with the javascript after removing the comments, but JSMin might help. It removes comments well enough anyway, and there is an implementation in python.
Matching one-line JavaScript comments (//) with re
I'd like to filter out (mostly one-line) comments from (mostly valid) JavaScript using python's re module. For example: // this is a comment var x = 2 // and this is a comment too var url = "http://www.google.com/" // and "this" too url += 'but // this is not a comment' // however this one is url += 'this "is not a comment' + " and ' neither is this " // only this I'm now trying this for more than half an hour without any success. Can anyone please help me? EDIT 1: foo = 'http://stackoverflow.com/' // these // are // comments // too // EDIT 2: bar = 'http://no.comments.com/'
[ "My regex powers had gone a bit stale so I've used your question to fresh what I remember.\nIt became a fairly large regex mostly because I also wanted to filter multi-line comments.\nimport re\n\nreexpr = r\"\"\"\n ( # Capture code\n \"(?:\\\\.|[^\"\\\\])*\" # String literal\n |\n '(?:\\\\.|[^'\\\\])*' # String literal\n |\n (?:[^/\\n\"']|/[^/*\\n\"'])+ # Any code besides newlines or string literals\n |\n \\n # Newline\n )|\n (/\\* (?:[^*]|\\*[^/])* \\*/) # Multi-line comment\n |\n (?://(.*)$) # Comment\n $\"\"\"\nrx = re.compile(reexpr, re.VERBOSE + re.MULTILINE)\n\nThis regex matches with three different subgroups. One for code and two for comment contents.\nBelow is a example of how to extract those.\ncode = r\"\"\"// this is a comment\nvar x = 2 * 4 // and this is a comment too\nvar url = \"http://www.google.com/\" // and \"this\" too\nurl += 'but // this is not a comment' // however this one is\nurl += 'this \"is not a comment' + \" and ' neither is this \" // only this\n\nbar = 'http://no.comments.com/' // these // are // comments\nbar = 'text // string \\' no // more //\\\\' // comments\nbar = 'http://no.comments.com/'\nbar = /var/ // comment\n\n/* comment 1 */\nbar = open() /* comment 2 */\nbar = open() /* comment 2b */// another comment\nbar = open( /* comment 3 */ file) // another comment \n\"\"\"\n\nparts = rx.findall(code)\nprint '*' * 80, '\\nCode:\\n\\n', '\\n'.join([x[0] for x in parts if x[0].strip()])\nprint '*' * 80, '\\nMulti line comments:\\n\\n', '\\n'.join([x[1] for x in parts if x[1].strip()])\nprint '*' * 80, '\\nOne line comments:\\n\\n', '\\n'.join([x[2] for x in parts if x[2].strip()])\n\n", "It might be easier to parse if you had explicit semi-colons. \nIn any case, this works: \nimport re\n\nrx = re.compile(r'.*(//(.*))$')\n\nlines = [\"// this is a comment\", \n \"var x = 2 // and this is a comment too\",\n \"\"\"var url = \"http://www.google.com/\" // and \"this\" too\"\"\",\n \"\"\"url += 'but // this is not a comment' // however this one is\"\"\",\n \"\"\"url += 'this \"is not a comment' + \" and ' neither is this \" // only this\"\"\",]\n\nfor line in lines: \n print rx.match(line).groups()\n\n\nOutput of the above: \n('// this is a comment', ' this is a comment')\n('// and this is a comment too', ' and this is a comment too')\n('// and \"this\" too', ' and \"this\" too')\n('// however this one is', ' however this one is')\n('// only this', ' only this')\n\n\nI'm not sure what you're doing with the javascript after removing the comments, but JSMin might help. It removes comments well enough anyway, and there is an implementation in python.\n" ]
[ 7, 1 ]
[]
[]
[ "javascript", "python", "regex", "replace" ]
stackoverflow_0002136363_javascript_python_regex_replace.txt
Q: urllib2 times out but doesn't close socket connection I'm making a python URL grabber program. For my purposes, I want it to time out really really fast, so I'm doing urllib2.urlopen("http://.../", timeout=2) Of course it times out correctly as it should. However, it doesn't bother to close the connection to the server, so the server thinks the client is still connected. How can I ask urllib2 to just close the connection after it times out? Running gc.collect() doesn't work and I'd like to not use httplib if I can't help it. The closest I can get is: the first try will time out. The server reports that the connection closed just as the second try times out. Then, the server reports the connection closed just as the third try times out. Ad infinitum. Many thanks. A: I have a suspicion that the socket is still open in the stack frames. When Python raises an exception it stores the stack frames so debuggers and other tools can view the stack and introspect values. For historical reasons, and now for backwards compatibility, the stack information is stored (on a per-thread basis) in sys (see sys.exc_info(), sys.exc_type and others). This is one of the things which has been removed in Python 3.0. What that means for you is the stack is still alive, and referenced. There stack contains the local data for some function which has the open socket. That's why the socket isn't yet closed. It's only when the stack trace is removed that everything will be gc'ed. To test if that's the case, insert something like try: 1/0 except ZeroDivisionError: pass in your except clause. That's a quick way to replace the current exception with something else. A: This is SUCH a hack, but the following code works. If the request is in another function AND it does not raise an exception, then the socket is always closed. def _fetch(self, url): try: return urllib2.urlopen(urllib2.Request(url), timeout=5).read() except urllib2.URLError, e: if isinstance(e.reason, socket.timeout): return None else: raise e def fetch(self, url): x = None while x is None: x = self._fetch(url) print "Timeout" return x Does ANYONE have a better way?
urllib2 times out but doesn't close socket connection
I'm making a python URL grabber program. For my purposes, I want it to time out really really fast, so I'm doing urllib2.urlopen("http://.../", timeout=2) Of course it times out correctly as it should. However, it doesn't bother to close the connection to the server, so the server thinks the client is still connected. How can I ask urllib2 to just close the connection after it times out? Running gc.collect() doesn't work and I'd like to not use httplib if I can't help it. The closest I can get is: the first try will time out. The server reports that the connection closed just as the second try times out. Then, the server reports the connection closed just as the third try times out. Ad infinitum. Many thanks.
[ "I have a suspicion that the socket is still open in the stack frames. When Python raises an exception it stores the stack frames so debuggers and other tools can view the stack and introspect values.\nFor historical reasons, and now for backwards compatibility, the stack information is stored (on a per-thread basis) in sys (see sys.exc_info(), sys.exc_type and others). This is one of the things which has been removed in Python 3.0.\nWhat that means for you is the stack is still alive, and referenced. There stack contains the local data for some function which has the open socket. That's why the socket isn't yet closed. It's only when the stack trace is removed that everything will be gc'ed.\nTo test if that's the case, insert something like\ntry:\n 1/0\nexcept ZeroDivisionError:\n pass\n\nin your except clause. That's a quick way to replace the current exception with something else.\n", "This is SUCH a hack, but the following code works. If the request is in another function AND it does not raise an exception, then the socket is always closed.\ndef _fetch(self, url):\n try:\n return urllib2.urlopen(urllib2.Request(url), timeout=5).read()\n except urllib2.URLError, e:\n if isinstance(e.reason, socket.timeout):\n return None\n else:\n raise e\n\ndef fetch(self, url):\n x = None\n while x is None:\n x = self._fetch(url)\n print \"Timeout\"\n return x\n\nDoes ANYONE have a better way?\n" ]
[ 2, 0 ]
[]
[]
[ "http", "python", "sockets", "timeout", "urllib2" ]
stackoverflow_0002137335_http_python_sockets_timeout_urllib2.txt
Q: Django - Store unescaped html in model I am trying to store raw, unescaped HTML inside one of my Django models for display on my home page. However, when I store it in a TextField it gets escaped, and ends up just being displayed as raw text. How can I store raw HTML in a Django model? ** EDIT ** It seems as if its not getting escaped in the model layer, but in the Template layer. Is there a special tag I should use? I checked the value in the shell and it's just fine, but for some reason when i did {{ block.html } (html is the attribute of the block object that stores the actual HTML) in the template, it comes out like this: &lt;p&gt;This is a &lt;strong&gt;very&lt;/strong&gt; &lt;em&gt;important&lt;/em&gt; &lt;span style=&quot;text-decoration: underline;&quot;&gt;block&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot;padding-left: 30px;&quot;&gt;it has very significant content!&lt;/p&gt; A: You can use the safe filter to present unescaped text, or escape filter to present escaped text. You can also use autoescape tag to set a block. ({% autoescape on %} or {% autoescape off %})
Django - Store unescaped html in model
I am trying to store raw, unescaped HTML inside one of my Django models for display on my home page. However, when I store it in a TextField it gets escaped, and ends up just being displayed as raw text. How can I store raw HTML in a Django model? ** EDIT ** It seems as if its not getting escaped in the model layer, but in the Template layer. Is there a special tag I should use? I checked the value in the shell and it's just fine, but for some reason when i did {{ block.html } (html is the attribute of the block object that stores the actual HTML) in the template, it comes out like this: &lt;p&gt;This is a &lt;strong&gt;very&lt;/strong&gt; &lt;em&gt;important&lt;/em&gt; &lt;span style=&quot;text-decoration: underline;&quot;&gt;block&lt;/span&gt;&lt;/p&gt; &lt;p style=&quot;padding-left: 30px;&quot;&gt;it has very significant content!&lt;/p&gt;
[ "You can use the safe filter to present unescaped text, or escape filter to present escaped text. You can also use autoescape tag to set a block. ({% autoescape on %} or {% autoescape off %})\n" ]
[ 17 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002137736_django_django_models_python.txt
Q: Depth-First search in Python I'm trying to do a Depth-First search in Python but it's not working. Basically we have a peg-solitaire board: [1,1,1,1,1,0,1,1,1,1] 1's represent a peg, and 0 is an open spot. You must move a peg one at a time TWO SLOTS backwards or forward ONLY to an empty spot. If you jump over another peg in the process it becomes an empty slot. You do this until one peg remains. So basically, a game goes like: [1, 1, 1, 1, 1, 0, 1, 1, 1, 1] [1, 1, 1, 0, 0, 1, 1, 1, 1, 1] [1, 0, 0, 1, 0, 1, 1, 1, 1, 1] [1, 0, 0, 1, 1, 0, 0, 1, 1, 1] [1, 0, 0, 0, 0, 1, 0, 1, 1, 1] [1, 0, 0, 0, 0, 1, 1, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1, 0, 1] #etc until only 1 peg left Here's what I have: class MiniPeg(): def start(self): ''' returns the starting board ''' board = [1,1,1,1,1,0,1,1,1,1] return board def goal(self, node): pegs = 0 for pos in node: if pos == 1: pegs += 1 return (pegs == 1) # returns True if there is only 1 peg def succ(self, node): pos = 0 for peg in node: if peg == 1: if pos < (len(node) - 2): # try to go forward if node[pos+2] == 0 and node[pos+1] == 1: return create_new_node(node, pos, pos+2) if pos > 2: # try to go backwards if node[pos-2] == 0 and node[pos-1] == 1: return create_new_node(node, pos, pos-2) pos += 1 def create_new_node(node, fr, to): node[fr] = 0 node[to] = 1 if fr > to: node[fr-1] = 0 else: node[fr+1] = 0 return node if __name__ == "__main__": s = MiniPeg() b = s.start() while not s.goal(b): print b b = s.succ(b) So, now my questions: Is this the right way to do a Depth-First search for this? My algorithm doesn't work!!! It gets stuck. I've been struggling on this for days before asking here so please help. Looks like I'm not following DRY, any suggestions? omg help me? A: The normal way to implement DFS in a situation where each step is a "move" from a "board position" to some possible next one, until a goal is reached, is as follows (pseudocode) seenpositions = set() currentpositions = set([startingposition]) while currentpositions: nextpositions = set() for p in currentpositions: seenpositions.add(p) succ = possiblesuccessors(p) for np in succ: if np in seenpositions: continue if isending(np): raise FoundSolution(np) nextpositions.add(np) currentpositions = nextpositions raise NoSolutionExists() You probably also want to keep backward links to be able to emit, at the end, the series of moves leading to the found solution (if any), but that's an ancillary problem. I don't recognize a trace of this general structure (or reasonable variant thereof) in your code. Why not try to record it this way? You only need to code possiblesuccessors and isending (if you insist on keeping a position as a list you'll have to turn it into a tuple to check membership in set and add to set, but, that's pretty minor;-). A: It doesn't appear that you're creating new nodes, just re-using existing ones. DFS requires some kind of stack (either the call stack, or your own stack). Where is that? A: Well, first of all a depth-first search assumes a tree. Now, that makes sense here as you have several possible moves in most cases. A depth first-search would simply try the first possible move, and then the first possible move in the new situation, and the first possible move in that new situation, until success or no more possible moves, in which case it would back up until it finds a move it hasn't tried, and go down again. The "correct" way of doing that is with recursion. You have no recursion in your system as far as I can see. Something like this would work (pythonic psuedo codeish english): def try_next_move(self, board): for each of the pegs in the board: if the peg can be moved: new_board = board with the peg moved if new_board is solved: return True if self.try_next_move(new_board): return True # That move didn't lead to a solution. Try the next. # No move worked. return False A: The basic algorithmic problem is that the succ function always only produces just one possible move for a given board state. Even if there would be more than one possible moves, the succ function just returns the first one it can find. A depth first search needs to process all possible moves in each state. Further problems might then come from the fact that create_new_node, despite it's name, doesn't really create a new node, but modifies the existing one. For depth first search where you want to keep the previous node around it would be better if this function actually created a copy of the list it get's as a parameter. Also, when checking for the possibility to go backwards in succ, you only try to do so if pos > 2. That's too restrictive, pos > 1 would also be ok.
Depth-First search in Python
I'm trying to do a Depth-First search in Python but it's not working. Basically we have a peg-solitaire board: [1,1,1,1,1,0,1,1,1,1] 1's represent a peg, and 0 is an open spot. You must move a peg one at a time TWO SLOTS backwards or forward ONLY to an empty spot. If you jump over another peg in the process it becomes an empty slot. You do this until one peg remains. So basically, a game goes like: [1, 1, 1, 1, 1, 0, 1, 1, 1, 1] [1, 1, 1, 0, 0, 1, 1, 1, 1, 1] [1, 0, 0, 1, 0, 1, 1, 1, 1, 1] [1, 0, 0, 1, 1, 0, 0, 1, 1, 1] [1, 0, 0, 0, 0, 1, 0, 1, 1, 1] [1, 0, 0, 0, 0, 1, 1, 0, 0, 1] [1, 0, 0, 0, 0, 0, 0, 1, 0, 1] #etc until only 1 peg left Here's what I have: class MiniPeg(): def start(self): ''' returns the starting board ''' board = [1,1,1,1,1,0,1,1,1,1] return board def goal(self, node): pegs = 0 for pos in node: if pos == 1: pegs += 1 return (pegs == 1) # returns True if there is only 1 peg def succ(self, node): pos = 0 for peg in node: if peg == 1: if pos < (len(node) - 2): # try to go forward if node[pos+2] == 0 and node[pos+1] == 1: return create_new_node(node, pos, pos+2) if pos > 2: # try to go backwards if node[pos-2] == 0 and node[pos-1] == 1: return create_new_node(node, pos, pos-2) pos += 1 def create_new_node(node, fr, to): node[fr] = 0 node[to] = 1 if fr > to: node[fr-1] = 0 else: node[fr+1] = 0 return node if __name__ == "__main__": s = MiniPeg() b = s.start() while not s.goal(b): print b b = s.succ(b) So, now my questions: Is this the right way to do a Depth-First search for this? My algorithm doesn't work!!! It gets stuck. I've been struggling on this for days before asking here so please help. Looks like I'm not following DRY, any suggestions? omg help me?
[ "The normal way to implement DFS in a situation where each step is a \"move\" from a \"board position\" to some possible next one, until a goal is reached, is as follows (pseudocode)\nseenpositions = set()\ncurrentpositions = set([startingposition])\nwhile currentpositions:\n nextpositions = set()\n for p in currentpositions:\n seenpositions.add(p)\n succ = possiblesuccessors(p)\n for np in succ:\n if np in seenpositions: continue\n if isending(np): raise FoundSolution(np)\n nextpositions.add(np)\n currentpositions = nextpositions\nraise NoSolutionExists()\n\nYou probably also want to keep backward links to be able to emit, at the end, the series of moves leading to the found solution (if any), but that's an ancillary problem.\nI don't recognize a trace of this general structure (or reasonable variant thereof) in your code. Why not try to record it this way? You only need to code possiblesuccessors and isending (if you insist on keeping a position as a list you'll have to turn it into a tuple to check membership in set and add to set, but, that's pretty minor;-).\n", "It doesn't appear that you're creating new nodes, just re-using existing ones. DFS requires some kind of stack (either the call stack, or your own stack). Where is that?\n", "Well, first of all a depth-first search assumes a tree. Now, that makes sense here as you have several possible moves in most cases. A depth first-search would simply try the first possible move, and then the first possible move in the new situation, and the first possible move in that new situation, until success or no more possible moves, in which case it would back up until it finds a move it hasn't tried, and go down again.\nThe \"correct\" way of doing that is with recursion. You have no recursion in your system as far as I can see.\nSomething like this would work (pythonic psuedo codeish english):\ndef try_next_move(self, board):\n for each of the pegs in the board:\n if the peg can be moved:\n new_board = board with the peg moved\n if new_board is solved:\n return True\n if self.try_next_move(new_board):\n return True\n # That move didn't lead to a solution. Try the next.\n # No move worked.\n return False\n\n", "The basic algorithmic problem is that the succ function always only produces just one possible move for a given board state. Even if there would be more than one possible moves, the succ function just returns the first one it can find. A depth first search needs to process all possible moves in each state.\nFurther problems might then come from the fact that create_new_node, despite it's name, doesn't really create a new node, but modifies the existing one. For depth first search where you want to keep the previous node around it would be better if this function actually created a copy of the list it get's as a parameter.\nAlso, when checking for the possibility to go backwards in succ, you only try to do so if pos > 2. That's too restrictive, pos > 1 would also be ok.\n" ]
[ 10, 1, 0, 0 ]
[]
[]
[ "depth_first_search", "python" ]
stackoverflow_0002137731_depth_first_search_python.txt
Q: Change class instance inside an instance method Any idea if there is a way to make the following code to work class Test(object): def __init__(self, var): self.var = var def changeme(self): self = Test(3) t = Test(1) assert t.var == 1 t.changeme() assert t.var == 3 is something like the following safe to use for more complex objects (like django models, to hot swap the db entry the instance is referring to) class Test(object): def __init__(self, var): self.var = var def changeme(self): new_instance = Test(3) self.__dict__ = new_instance.__dict__ t = Test(1) assert t.var == 1 t.changeme() assert t.var == 3 A: self = Test(3) is re-binding the local name self, with no externally observable effects. Assigning self.__dict__ (unless you're talking about instances with __slots__ or from classes with non-trivial metaclasses) is usually OK, and so is self.__init__(3) to re-initialize the instance. However I'd prefer to have a specific method self.restart(3) which knows it's being called on an already-initialized instance and does whatever's needed to cater for that specific and unusual case. A: No, and no. Having said that, you can change the class, but don't do that either. A: The former code works, except it won't do much, seeing as it just replaces the object named 'self' within the scope of changeme(). Python names aren't locked to values, they are always relative to their scope or namespace. To do what you want you'd need to have access to a name outside the class, which you could assign to from within it: class Test: def changeme(self): global myclass myclass = Test(3) myclass = Test(2) myclass.changeme() print myclass # 3 This basically just overwrites the name 'myclass' to point to the new instance. It doesn't "overwrite" the first instance like you might think. The old instance still lives, and will be garbage collected unless referenced elsewhere.
Change class instance inside an instance method
Any idea if there is a way to make the following code to work class Test(object): def __init__(self, var): self.var = var def changeme(self): self = Test(3) t = Test(1) assert t.var == 1 t.changeme() assert t.var == 3 is something like the following safe to use for more complex objects (like django models, to hot swap the db entry the instance is referring to) class Test(object): def __init__(self, var): self.var = var def changeme(self): new_instance = Test(3) self.__dict__ = new_instance.__dict__ t = Test(1) assert t.var == 1 t.changeme() assert t.var == 3
[ "self = Test(3) is re-binding the local name self, with no externally observable effects.\nAssigning self.__dict__ (unless you're talking about instances with __slots__ or from classes with non-trivial metaclasses) is usually OK, and so is self.__init__(3) to re-initialize the instance. However I'd prefer to have a specific method self.restart(3) which knows it's being called on an already-initialized instance and does whatever's needed to cater for that specific and unusual case.\n", "No, and no.\nHaving said that, you can change the class, but don't do that either.\n", "The former code works, except it won't do much, seeing as it just replaces the object named 'self' within the scope of changeme(). Python names aren't locked to values, they are always relative to their scope or namespace.\nTo do what you want you'd need to have access to a name outside the class, which you could assign to from within it:\nclass Test:\n def changeme(self):\n global myclass\n myclass = Test(3)\n\nmyclass = Test(2)\nmyclass.changeme()\nprint myclass # 3\n\nThis basically just overwrites the name 'myclass' to point to the new instance. It doesn't \"overwrite\" the first instance like you might think. The old instance still lives, and will be garbage collected unless referenced elsewhere.\n" ]
[ 7, 2, 2 ]
[]
[]
[ "class", "hotswap", "instance", "python" ]
stackoverflow_0002137772_class_hotswap_instance_python.txt
Q: Problems using PIL 1.1.7 The trivial import Image im = Image.OPEN('C:\abc.bmp') results in the following exception Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> im = Image.OPEN('C:\Documents and Settings\umair.ahmed\My Documents\My Pictures\avanza.bmp') TypeError: 'dict' object is not callable not sure if i am missing something, kindly help. A: Use: Image.open() It's case-sensitive. A: I don't think the error message came from your input, because the file names are different, but you should not use 'C:\abc.bmp', in your open() call, but use either C:/abc.bmp, or r'C:\abc.bmp'. Backslash is an escape character in Python.
Problems using PIL 1.1.7
The trivial import Image im = Image.OPEN('C:\abc.bmp') results in the following exception Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> im = Image.OPEN('C:\Documents and Settings\umair.ahmed\My Documents\My Pictures\avanza.bmp') TypeError: 'dict' object is not callable not sure if i am missing something, kindly help.
[ "Use:\nImage.open()\n\nIt's case-sensitive.\n", "I don't think the error message came from your input, because the file names are different, but you should not use 'C:\\abc.bmp', in your open() call, but use either C:/abc.bmp, or r'C:\\abc.bmp'. Backslash is an escape character in Python.\n" ]
[ 4, 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002137953_python_python_imaging_library.txt
Q: (python) sgmlparser and how to extract data between tags, not attributes/values Every example I see for sgmlparser involves finding a tag, then finding the attributes/values of the tag. So for it would be the ability to extract 'google.com' out. but i want the data between tags. so if i used sgmlparser, i would look for and extract out everything in that div until it's closing tag. is that the job of sgmlparser, or am i using the wrong library? A: Because you mention div's, I gather you want to parse HTML. For doing that your best choice is BeautifulSoup.
(python) sgmlparser and how to extract data between tags, not attributes/values
Every example I see for sgmlparser involves finding a tag, then finding the attributes/values of the tag. So for it would be the ability to extract 'google.com' out. but i want the data between tags. so if i used sgmlparser, i would look for and extract out everything in that div until it's closing tag. is that the job of sgmlparser, or am i using the wrong library?
[ "Because you mention div's, I gather you want to parse HTML. For doing that your best choice is BeautifulSoup.\n" ]
[ 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0002135964_html_python.txt
Q: How can I keep on-the-fly application-level statistics in an application running under Apache? I have an application running under apache that I want to keep "in the moment" statistics on. I want to have the application tell me things like: requests per second, broken down by types of request latency to make requests to various backend services via thrift (broken down by service and server) number of errors being served per second etc. I want to do this without any external dependencies. However, I'm running into issues sharing statistics between apache processes. Obviously, I can't just use global memory. What is a good pattern for this sort of issue? The application is written in python using pylons, though I suspect this is more of a "communication across processes" design question than something that's python specific. A: Perhaps you could keep the relevant counters and other statistics in a memcached, that is accessed by all apache processes? A: I want to do this without any external dependencies. What if your apache dies somehow? (Separation of concerns?) Personally I am using (redundant) Nagios to monitor the hardware itself, services, and application metrics. This way i can easily/automatically plot "requests per second/users online", "cpu load/user activy X per second" etc. graphs which help with lots of things. Writing plugins for nagios is really easy, also there are thousands of premade scripts in any language. Apache monitoring I am monitoring apache by extracting the information I need from the apache mod_status page via nagios plugin. Example plugin response: APACHE OK - 0.080 sec. response time, Busy/Idle 18/16, open 766/800, ReqPerSec 12.4, BytesPerReq 3074, BytesPerSec 38034 Application Monitoring I used mod_status just as an example for your list of things you'd like to monitor. For our application we have a very small framework for Nagios plugins, so basically every nagios check is a small class which runs its check against a cache or database and returns its value to nagios (small and simple commandline-script). more examples: Memcache: OK - consumption: 82.88% (106.1 MBytes/128.0 MBytes), connections: 2, requests/s: 10.99, hitrate: 95.2% (34601210/36346999), getrate: 50.1% (36346999/72542987) Application feature #1 usage: OK - last 5m: 22 last 24h: 655 ever: 26121 Application feature #2 usage: OK - last 5m: 39 last 24h: 11011 Other applications metrics: OK - users online: 556 What I want to say: Extending Nagios for application monitoring is very easy. With my little framework which took me 3-4 hours to write, any check I am adding takes me just some minutes now. Nagios plug-in development guidelines
How can I keep on-the-fly application-level statistics in an application running under Apache?
I have an application running under apache that I want to keep "in the moment" statistics on. I want to have the application tell me things like: requests per second, broken down by types of request latency to make requests to various backend services via thrift (broken down by service and server) number of errors being served per second etc. I want to do this without any external dependencies. However, I'm running into issues sharing statistics between apache processes. Obviously, I can't just use global memory. What is a good pattern for this sort of issue? The application is written in python using pylons, though I suspect this is more of a "communication across processes" design question than something that's python specific.
[ "Perhaps you could keep the relevant counters and other statistics in a memcached, that is accessed by all apache processes?\n", "\nI want to do this without any external\n dependencies.\n\nWhat if your apache dies somehow? (Separation of concerns?)\nPersonally I am using (redundant) Nagios to monitor the hardware itself, services, and application metrics. This way i can easily/automatically plot \"requests per second/users online\", \"cpu load/user activy X per second\" etc. graphs which help with lots of things.\nWriting plugins for nagios is really easy, also there are thousands of premade scripts in any language.\nApache monitoring\nI am monitoring apache by extracting the information I need from the apache mod_status page via nagios plugin.\nExample plugin response:\nAPACHE OK - 0.080 sec. response time, Busy/Idle 18/16, open 766/800, ReqPerSec 12.4, BytesPerReq 3074, BytesPerSec 38034\nApplication Monitoring\nI used mod_status just as an example for your list of things you'd like to monitor.\nFor our application we have a very small framework for Nagios plugins, so basically every nagios check is a small class which runs its check against a cache or database and returns its value to nagios (small and simple commandline-script).\nmore examples:\nMemcache:\nOK - consumption: 82.88% (106.1 MBytes/128.0 MBytes), connections: 2, requests/s: 10.99, hitrate: 95.2% (34601210/36346999), getrate: 50.1% (36346999/72542987)\n\nApplication feature #1 usage:\nOK - last 5m: 22 last 24h: 655 ever: 26121\n\nApplication feature #2 usage:\nOK - last 5m: 39 last 24h: 11011\n\nOther applications metrics:\nOK - users online: 556\n\nWhat I want to say: Extending Nagios for application monitoring is very easy.\nWith my little framework which took me 3-4 hours to write, any check I am adding takes me just some minutes now.\nNagios plug-in development guidelines\n" ]
[ 1, 1 ]
[ "Use pylons.g object. It is an instance of Globals class in your Pylons application's lib/app_globals.py file. Its state changes will be visible to all threads, so stuff in it needs to be threadsafe.\nlib/app_globals.py:\nclass Globals(object):\n def __init__(self):\n self.requests_served = 0\n\ncontrollers/status.py:\nfrom pylons import g\n\nclass StatusController(BaseController):\n def status(self):\n g.requests_served += 1\n return \"Served %d requests.\" % g.requests_served\n\n" ]
[ -1 ]
[ "apache", "fork", "multithreading", "pylons", "python" ]
stackoverflow_0002113352_apache_fork_multithreading_pylons_python.txt
Q: Convert Line Number Into its corresponding co-ordinates I have a application written in PyGtk. I need to convert a particular line number into its corresponding window co-ordinates in a GtkTextView. How can this be done? A: Begin by using gtk_text_buffer_get_iter_at_line() to get a handle on the line. Then use gtk_text_view_get_line_yrange() to convert that into pixel coordinates. Finally use gtk_text_view_buffer_to_window_coords() to convert the buffer pixel coordinates into window coordinates. These are links to the C API calls, but converting to PyGtk should be trivial. A: It can't be done, in general. If you're talking about a line of your pygtk program, then you would need an API for your IDE (development environment) to find out where a particular source code line is currently displayed on the screen, if anywhere. If by "line number" you mean something else, then as Ignacio says, you'll need to provide a lot more detail.
Convert Line Number Into its corresponding co-ordinates
I have a application written in PyGtk. I need to convert a particular line number into its corresponding window co-ordinates in a GtkTextView. How can this be done?
[ "Begin by using gtk_text_buffer_get_iter_at_line() to get a handle on the line. Then use gtk_text_view_get_line_yrange() to convert that into pixel coordinates. Finally use gtk_text_view_buffer_to_window_coords() to convert the buffer pixel coordinates into window coordinates.\nThese are links to the C API calls, but converting to PyGtk should be trivial.\n", "It can't be done, in general. If you're talking about a line of your pygtk program, then you would need an API for your IDE (development environment) to find out where a particular source code line is currently displayed on the screen, if anywhere. If by \"line number\" you mean something else, then as Ignacio says, you'll need to provide a lot more detail.\n" ]
[ 2, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002137517_gtk_pygtk_python.txt
Q: How can I link (C++) with renamed Python .lib and .dll? When I include "Python.h" from Python 2.5 in a C++ project, it knows through some magical process that it has to link with "python25.lib" and load "python25.dll" at runtime, though I didn't specified anything neither in "Linker -> Additional Dependencies" nor in "Linker -> Additional Library Directories". Now I would like to rename python25.lib/.dll to something like gpython25.lib/.dll and link with them. This is to be sure to link with THIS python dll and not another python25.dll from another installed application, independently from the PATH search order. Is there a way to do that? Thanks -David A: MSVC supports this feature through pragmas: #pragma comment(lib, "python25.lib"); More info in MSDN. Look into Python.h file and modify the name of the linkage, if that what you want.
How can I link (C++) with renamed Python .lib and .dll?
When I include "Python.h" from Python 2.5 in a C++ project, it knows through some magical process that it has to link with "python25.lib" and load "python25.dll" at runtime, though I didn't specified anything neither in "Linker -> Additional Dependencies" nor in "Linker -> Additional Library Directories". Now I would like to rename python25.lib/.dll to something like gpython25.lib/.dll and link with them. This is to be sure to link with THIS python dll and not another python25.dll from another installed application, independently from the PATH search order. Is there a way to do that? Thanks -David
[ "MSVC supports this feature through pragmas:\n#pragma comment(lib, \"python25.lib\");\n\nMore info in MSDN.\nLook into Python.h file and modify the name of the linkage, if that what you want.\n" ]
[ 1 ]
[]
[]
[ "c++", "dll", "linker", "python" ]
stackoverflow_0002138625_c++_dll_linker_python.txt
Q: How do I abort the execution of a Python script? I have a simple Python script that I want to stop executing if a condition is met. For example: done = True if done: # quit/stop/exit else: # do other stuff Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code. A: To exit a script you can use, import sys sys.exit() You can also provide an exit status value, usually an integer. import sys sys.exit(0) Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero. import sys sys.exit("aa! errors!") Prints "aa! errors!" and exits with a status code of 1. There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used. The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances. A: You could put the body of your script into a function and then you could return from that function. def main(): done = True if done: return # quit/stop/exit else: # do other stuff if __name__ == "__main__": #Run as main program main() A: import sys sys.exit() A: You can either use: import sys sys.exit(...) or: raise SystemExit(...) The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword). A: Try sys.exit("message") It is like the perl die("message") if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function A: exit() should do the trick A: exit() should do it. A: If the entire program should stop use sys.exit() otherwise just use an empty return.
How do I abort the execution of a Python script?
I have a simple Python script that I want to stop executing if a condition is met. For example: done = True if done: # quit/stop/exit else: # do other stuff Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.
[ "To exit a script you can use,\nimport sys\nsys.exit()\n\nYou can also provide an exit status value, usually an integer.\nimport sys\nsys.exit(0)\n\nExits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.\nimport sys\nsys.exit(\"aa! errors!\")\n\nPrints \"aa! errors!\" and exits with a status code of 1.\nThere is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used. \nThe Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.\n", "You could put the body of your script into a function and then you could return from that function.\ndef main():\n done = True\n if done:\n return\n # quit/stop/exit\n else:\n # do other stuff\n\nif __name__ == \"__main__\":\n #Run as main program\n main()\n\n", "import sys\nsys.exit()\n\n", "You can either use:\nimport sys\nsys.exit(...)\n\nor:\nraise SystemExit(...)\n\nThe optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).\n", "Try\nsys.exit(\"message\")\n\nIt is like the perl\ndie(\"message\")\n\nif this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function\n", "exit() should do the trick\n", "exit() should do it.\n", "If the entire program should stop use sys.exit() otherwise just use an empty return.\n" ]
[ 325, 21, 20, 19, 6, 4, 4, 3 ]
[]
[]
[ "exit", "python", "scripting", "syntax" ]
stackoverflow_0000179369_exit_python_scripting_syntax.txt
Q: Creating an Instance of a Class with a variable in Python I had this question posted earlier, but it wasn't very clear, and I had trouble with the answers. Since I edited it to make MUCH more sense it seems that people haven't been looking at it, perhaps because they see it already has 6 answers. So I'm re=-posting it here: I'm still new to Python and Programming in general, so I need simple explanations! I don't even know what this dictionary thing you're talking about is! I'm trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with. I created a class Toy and want to create a function, getNewToy(name, data1, data2, data3, data4, data5). I want this function to create a new instance of the class Toy, and I want the function to be able to be called multiple times each time creating a new instance. In my experience you create an instance with: class Toy: def __init__(self, name, data1, data2, data3, data4, data5): pass myToy = Toy(myToy, 1, 2, 3, 4, 5) then to use methods from the class with: myToy.method1() Seeing as I want to have the ability to have multiple toys, each with a playWith() method I want the instance to reflect the name of the Toy each time one is called. I want the instance to be different each time I call the method getNewToy(,...) and the instance to reflect the name. Remember I'm new to programming, so can you keep explanations simple. Thank you very much, it's much easier to understand now! A: There is no point in making a special getNewToy function. Just create the class: newtoy = Toy(name, data1, data2, data3, data4, data5) That's all you need to do. "method I want the instance to reflect the name of the Toy each time one is called." class Toy: def __repr__(self): return "<type Toy name=%s>" % self.name A: Heres how I would do what you explained: # The following two classes are toys, both have a playWith # as you wanted, each playWith do different things class Ball: def __init__(self): self.name = "ball" def playWith(self): print "the ball bounces" class Car: def __init__(self): self.name = "car" def playWith(self): print "the car is fast" # This is a Python generator, every time .next() is called on it, # the next "yield-value" is returned def generator(): while True: yield Ball() yield Car() # This is the creator, it has to be a class rather than a function # since you wanted a new toy each time getNewToy is called # and as such the generator needs to be tracked class ToyCreator: def __init__(self): self.generator = generator() def getNewToy(self): return self.generator.next() # Create five toys, print their name and play with them # Do note here that even though we ask for five toys but only have # two "yields" in the generator, the generator "wraps around" (since, # internally, its just an endless loop) toyCreator = ToyCreator() for i in range(5): toy = toyCreator.getNewToy() print "Toy",i,toy.name,"\t:", toy.playWith() If youre having trouble understanding the yield business, take a look at the documentation for the python generator. What youre trying to do is implement a design pattern, a factory pattern, to be more precise. Still feeling confused? Read again, think a little but dont hesitate to ask. Were here to help. :) A: I don't see why you need a getNewToy method. Every time you call Toy() you will get a new instance of your class. You probably want code like this: class Toy: def __init__(self, name, data1, data2, data3, data4, data5): self.name = name self.data1 = data1 # ... myToy = Toy("firsttoy", 1, 2, 3, 4, 5) myToy2 = Toy("2ndToy", 6, 7, 8, 9, 10) A: Perhaps you will always have 5 data items, but even if so, consider using *args: class Toy: def __init__(self, name, *args): self.name = name self.data = args
Creating an Instance of a Class with a variable in Python
I had this question posted earlier, but it wasn't very clear, and I had trouble with the answers. Since I edited it to make MUCH more sense it seems that people haven't been looking at it, perhaps because they see it already has 6 answers. So I'm re=-posting it here: I'm still new to Python and Programming in general, so I need simple explanations! I don't even know what this dictionary thing you're talking about is! I'm trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with. I created a class Toy and want to create a function, getNewToy(name, data1, data2, data3, data4, data5). I want this function to create a new instance of the class Toy, and I want the function to be able to be called multiple times each time creating a new instance. In my experience you create an instance with: class Toy: def __init__(self, name, data1, data2, data3, data4, data5): pass myToy = Toy(myToy, 1, 2, 3, 4, 5) then to use methods from the class with: myToy.method1() Seeing as I want to have the ability to have multiple toys, each with a playWith() method I want the instance to reflect the name of the Toy each time one is called. I want the instance to be different each time I call the method getNewToy(,...) and the instance to reflect the name. Remember I'm new to programming, so can you keep explanations simple. Thank you very much, it's much easier to understand now!
[ "There is no point in making a special getNewToy function. Just create the class:\n newtoy = Toy(name, data1, data2, data3, data4, data5)\n\nThat's all you need to do.\n\"method I want the instance to reflect the name of the Toy each time one is called.\"\nclass Toy:\n def __repr__(self):\n return \"<type Toy name=%s>\" % self.name\n\n", "Heres how I would do what you explained:\n# The following two classes are toys, both have a playWith \n# as you wanted, each playWith do different things\nclass Ball:\n def __init__(self):\n self.name = \"ball\"\n\n def playWith(self):\n print \"the ball bounces\"\n\nclass Car:\n def __init__(self):\n self.name = \"car\"\n\n def playWith(self):\n print \"the car is fast\"\n\n# This is a Python generator, every time .next() is called on it,\n# the next \"yield-value\" is returned\ndef generator():\n while True:\n yield Ball()\n yield Car()\n\n# This is the creator, it has to be a class rather than a function\n# since you wanted a new toy each time getNewToy is called\n# and as such the generator needs to be tracked\nclass ToyCreator:\n def __init__(self):\n self.generator = generator()\n\n def getNewToy(self):\n return self.generator.next()\n\n# Create five toys, print their name and play with them\n# Do note here that even though we ask for five toys but only have\n# two \"yields\" in the generator, the generator \"wraps around\" (since,\n# internally, its just an endless loop) \ntoyCreator = ToyCreator()\nfor i in range(5):\n toy = toyCreator.getNewToy()\n print \"Toy\",i,toy.name,\"\\t:\",\n toy.playWith()\n\nIf youre having trouble understanding the yield business, take a look at the documentation for the python generator.\nWhat youre trying to do is implement a design pattern, a factory pattern, to be more precise.\nStill feeling confused? Read again, think a little but dont hesitate to ask. Were here to help. :)\n", "I don't see why you need a getNewToy method. Every time you call Toy() you will get a new instance of your class. You probably want code like this:\nclass Toy: \n def __init__(self, name, data1, data2, data3, data4, data5): \n self.name = name\n self.data1 = data1\n # ...\n\nmyToy = Toy(\"firsttoy\", 1, 2, 3, 4, 5)\nmyToy2 = Toy(\"2ndToy\", 6, 7, 8, 9, 10)\n\n", "Perhaps you will always have 5 data items, but even if so, consider using *args:\nclass Toy:\n def __init__(self, name, *args):\n self.name = name\n self.data = args\n\n" ]
[ 2, 2, 1, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002138027_class_python.txt
Q: Import by file/module name in GAE I am trying to make a simple localization module that takes a key name and returns the localized string based on the language given. The language is one of the constants and maps to a python file that contains the string table. I want to do this dynamically at runtime. Below is my approach, but GAE does not support the imp module. Is there an alternative way to do this? import logging import imp import localizable LANGUAGE_EN = "en" LANGUAGE_JP = "ja" class Localizer(object): """ Returns a localized string corresponding to unique keys """ @classmethod def localize(cls, language = LANGUAGE_EN, key = None): user_language = imp.load_source("localizable.%s" % language, "/") if (user_language): return user_language.Locale.localize(key) else: logging.error("Localizable file was not found") return "" I put the language files in localizable/en.py, etc. A: The alternative to the imp module that (I believe) should be available in GAE is __import__(). It's in fact what the 'import' statement calls to do the actual importing. user_language = getattr(__import__('localizable.%s' % language), language) or user_language __import__('localizable.%s' % language, {}, globals(), ['']) (passing a non-empty fourth argument to __import__ causes it to return the right-most module in the first argument, instead of the left-most. It's a little hacky, so people tend to prefer the first solution over the second.)
Import by file/module name in GAE
I am trying to make a simple localization module that takes a key name and returns the localized string based on the language given. The language is one of the constants and maps to a python file that contains the string table. I want to do this dynamically at runtime. Below is my approach, but GAE does not support the imp module. Is there an alternative way to do this? import logging import imp import localizable LANGUAGE_EN = "en" LANGUAGE_JP = "ja" class Localizer(object): """ Returns a localized string corresponding to unique keys """ @classmethod def localize(cls, language = LANGUAGE_EN, key = None): user_language = imp.load_source("localizable.%s" % language, "/") if (user_language): return user_language.Locale.localize(key) else: logging.error("Localizable file was not found") return "" I put the language files in localizable/en.py, etc.
[ "The alternative to the imp module that (I believe) should be available in GAE is __import__(). It's in fact what the 'import' statement calls to do the actual importing.\nuser_language = getattr(__import__('localizable.%s' % language), language)\n\nor\nuser_language __import__('localizable.%s' % language, {}, globals(), [''])\n\n(passing a non-empty fourth argument to __import__ causes it to return the right-most module in the first argument, instead of the left-most. It's a little hacky, so people tend to prefer the first solution over the second.)\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002139110_google_app_engine_python.txt
Q: how to install open-library on ubuntu? i want to install openlibrary in my ubuntu system and i followed the instruction from the below link http://openlibrary.org/dev/docs/setup $ ./scripts/openlibrary-server openlibrary.yml while i am using the above command it shows infogami module not found error message A: You will need to install 'infogami'. See here
how to install open-library on ubuntu?
i want to install openlibrary in my ubuntu system and i followed the instruction from the below link http://openlibrary.org/dev/docs/setup $ ./scripts/openlibrary-server openlibrary.yml while i am using the above command it shows infogami module not found error message
[ "You will need to install 'infogami'. See here\n" ]
[ 2 ]
[]
[]
[ "installation", "python", "ubuntu" ]
stackoverflow_0002139262_installation_python_ubuntu.txt
Q: Python Process blocked by urllib2 I set up a process that read a queue for incoming urls to download but when urllib2 open a connection the system hangs. import urllib2, multiprocessing from threading import Thread from Queue import Queue from multiprocessing import Queue as ProcessQueue, Process def download(url): """Download a page from an url. url [str]: url to get. return [unicode]: page downloaded. """ if settings.DEBUG: print u'Downloading %s' % url request = urllib2.Request(url) response = urllib2.urlopen(request) encoding = response.headers['content-type'].split('charset=')[-1] content = unicode(response.read(), encoding) return content def downloader(url_queue, page_queue): def _downloader(url_queue, page_queue): while True: try: url = url_queue.get() page_queue.put_nowait({'url': url, 'page': download(url)}) except Exception, err: print u'Error downloading %s' % url raise err finally: url_queue.task_done() ## Init internal workers internal_url_queue = Queue() internal_page_queue = Queue() for num in range(multiprocessing.cpu_count()): worker = Thread(target=_downloader, args=(internal_url_queue, internal_page_queue)) worker.setDaemon(True) worker.start() # Loop waiting closing for url in iter(url_queue.get, 'STOP'): internal_url_queue.put(url) # Wait for closing internal_url_queue.join() # Init the queues url_queue = ProcessQueue() page_queue = ProcessQueue() # Init the process download_worker = Process(target=downloader, args=(url_queue, page_queue)) download_worker.start() From another module I can add urls and when I want I can stop the process and wait the process closing. import module module.url_queue.put('http://foobar1') module.url_queue.put('http://foobar2') module.url_queue.put('http://foobar3') module.url_queue.put('STOP') downloader.download_worker.join() The problem is that when I use urlopen ("response = urllib2.urlopen(request)") it remain all blocked. There are no problem if I call the download() function or when I use only threads without Process. A: The issue here is not urllib2, but the use of the multiprocessing module. When using the multiprocessing module under Windows, you must not use code that runs immediately when importing your module - instead, put things in the main module inside a if __name__=='__main__' block. See section "Safe importing of main module" here. For your code, make this change following in the downloader module: #.... def start(): global download_worker download_worker = Process(target=downloader, args=(url_queue, page_queue)) download_worker.start() And in the main module: import module if __name__=='__main__': module.start() module.url_queue.put('http://foobar1') #.... Because you didn't do this, each time the subprocess was started it would run the main code again and start another process, causing the hang.
Python Process blocked by urllib2
I set up a process that read a queue for incoming urls to download but when urllib2 open a connection the system hangs. import urllib2, multiprocessing from threading import Thread from Queue import Queue from multiprocessing import Queue as ProcessQueue, Process def download(url): """Download a page from an url. url [str]: url to get. return [unicode]: page downloaded. """ if settings.DEBUG: print u'Downloading %s' % url request = urllib2.Request(url) response = urllib2.urlopen(request) encoding = response.headers['content-type'].split('charset=')[-1] content = unicode(response.read(), encoding) return content def downloader(url_queue, page_queue): def _downloader(url_queue, page_queue): while True: try: url = url_queue.get() page_queue.put_nowait({'url': url, 'page': download(url)}) except Exception, err: print u'Error downloading %s' % url raise err finally: url_queue.task_done() ## Init internal workers internal_url_queue = Queue() internal_page_queue = Queue() for num in range(multiprocessing.cpu_count()): worker = Thread(target=_downloader, args=(internal_url_queue, internal_page_queue)) worker.setDaemon(True) worker.start() # Loop waiting closing for url in iter(url_queue.get, 'STOP'): internal_url_queue.put(url) # Wait for closing internal_url_queue.join() # Init the queues url_queue = ProcessQueue() page_queue = ProcessQueue() # Init the process download_worker = Process(target=downloader, args=(url_queue, page_queue)) download_worker.start() From another module I can add urls and when I want I can stop the process and wait the process closing. import module module.url_queue.put('http://foobar1') module.url_queue.put('http://foobar2') module.url_queue.put('http://foobar3') module.url_queue.put('STOP') downloader.download_worker.join() The problem is that when I use urlopen ("response = urllib2.urlopen(request)") it remain all blocked. There are no problem if I call the download() function or when I use only threads without Process.
[ "The issue here is not urllib2, but the use of the multiprocessing module. When using the multiprocessing module under Windows, you must not use code that runs immediately when importing your module - instead, put things in the main module inside a if __name__=='__main__' block. See section \"Safe importing of main module\" here.\nFor your code, make this change following in the downloader module:\n#....\ndef start():\n global download_worker\n download_worker = Process(target=downloader, args=(url_queue, page_queue))\n download_worker.start()\n\nAnd in the main module:\nimport module\nif __name__=='__main__':\n module.start()\n module.url_queue.put('http://foobar1')\n #....\n\nBecause you didn't do this, each time the subprocess was started it would run the main code again and start another process, causing the hang.\n" ]
[ 4 ]
[]
[]
[ "multiprocess", "multithreading", "python", "urllib2" ]
stackoverflow_0002137187_multiprocess_multithreading_python_urllib2.txt
Q: user pointer in python *I am trying to display preview from webcam captured using v4l. Here is an idea of how the code looks like: from ctypes import * from v4l2 import * from Image import fromstring from Tkinter import Tk, Label from ImageTk import PhotoImage from ctypes.util import find_library libc = CDLL(find_library('c')) posix_memalign = libc.posix_memalign getpagesize = libc.getpagesize device_name = '/dev/video0' ps = preview_settings = { 'width': 320, 'height': 240, 'pixformat': 'RGB', } PIX_FMT = V4L2_PIX_FMT_RGB555 preview = Tk() image = PhotoImage(ps['pixformat'], (ps['width'], ps['height'])) label = Label(preview, text='Preview', image=image, width=ps['width'], height=ps['height']) label.pack() capability = v4l2_capability() size = v4l2_frmsizeenum() format = v4l2_format() request = v4l2_requestbuffers() buffer = v4l2_buffer() b_address = c_void_p() frame_name_count = '0' type = V4L2_BUF_TYPE_VIDEO_CAPTURE device = open(device_name, 'rw') ioctl(device, VIDIOC_QUERYCAP, addr(capability)) size.pixel_format = PIX_FMT size.index = 0 format.type = type format.fmt.pix.pixelformat = PIX_FMT format.fmt.pix.width = size.discrete.width format.fmt.pix.height = size.discrete.height format.fmt.pix.field = V4L2_FIELD_NONE format.fmt.pix.bytesperline = 0 format.fmt.pix.sizeimage = 0 request.type = type request.memory = V4L2_MEMORY_USERPTR request.count = 1 ioctl(device, VIDIOC_S_FMT, addr(format)) ioctl(device, VIDIOC_G_FMT, addr(format)) ioctl(device, VIDIOC_REQBUFS, addr(request)) posix_memalign(addressof(b_address), getpagesize(), format.fmt.pix.sizeimage) buffer.type = request.type buffer.memory = request.memory buffer.index = 0 buffer.m.userptr = b_address.value buffer.length = format.fmt.pix.sizeimage while True: ioctl(device, VIDIOC_QBUF, addr(buffer)) ioctl(device, VIDIOC_STREAMON, cast(type, c_void_p)) ioctl(device, VIDIOC_DQBUF, addr(buffer)) preview_data = string_at(buffer.m.userptr, buffer.length) im = fromstring(ps['pixformat'], (ps['width'], ps['height']), preview_data) image.paste(im) preview.update() and I get ValueError: not enough image data well, I import c_lib = CDLL(find_library('c')) posix_memalign = c_lib.posix_memalign getpagesize = c_lib.getpagesize and then after ioctl(device, VIDIOC_S_FMT, addr(format)) ioctl(device, VIDIOC_G_FMT, addr(format)) and stuff like that, I try to acquire memory posix_memalign(addressof(b_address), getpagesize(), format.fmt.pix.sizeimage) now b_address is no longer = None b_address is something like c_void_p(145014784) then I start the loop, QBUF, DQBUF, etc.. the thing is, that when I call pygame.image.frombuffer pg_img = pygame.image.frombuffer( buffer.m.userptr, (format.fmt.pix.width, format.fmt.pix.height), preview_settings['pixformat'] ) I get TypeError: expected a character buffer object A: Looks like ctypes.string_at(address, size) is what you want. That'll give you a python string buffer with the contents of the memory at your pointer's address. This should be suitable to pass to Image.fromstring or pygame.image.frombuffer. A: I don't know much about ctypes, but I am doing a similar thing (wrapped c++ webcam capture, displayed with DirectPython). In my case I just made a buffer in python like this: bufferSize = imageWidth * imageHeight buf = "\0" * bufferSize Pass buf to your image capture function for filling? Maybe post a more complete code sample... A: Have you tried passing buffer directly as the first arg? If that doesn't work and you want to make a writeable character buffer with ctypes, create_string_buffer is the only way I know (I don't understand where you're getting the b_address.value from). A: OK, what I did was to leave pygame for Tkinter and PIL now after the same allocation I pass buffer.m.userptr *to fromstring method from Image first I have, of course, the following: import Image import Tkinter tk = Tkinter.Tk() preview = ImageTk.PhotoImage(ps['pixformat'], (ps['width'], ps['height'])) label = Tkinter.Label(tk, text='Preview', image=preview, width=ps['width'], height=ps['height']) label.pack() and now preview: im = Image.fromstring(ps['pixformat'], (format.fmt.pix.width, format.fmt.pix.height), '\0'*buffer.m.userptr) preview.paste(im) tk.update() I did what @sipickles said, with '\0' to see if the whole thing will work And it did :) the thing is how to pas that userptr correctly and is the data in it actually what it needs to be passed to the preview I am really lost here. Someone knows v4l2? A: Ok. so for now I fixed the sizeimage problem by setting the sizeimage myself: Now frombuffer displays something that is not the frame from the buffer. from ctypes import * from v4l2 import * from Image import fromstring from Tkinter import Tk, Label from ImageTk import PhotoImage from ctypes.util import find_library libc = CDLL(find_library('c')) posix_memalign = libc.posix_memalign getpagesize = libc.getpagesize device_name = '/dev/video0' ps = preview_settings = { 'width': 320, 'height': 240, 'pixformat': 'RGB', } PIX_FMT = V4L2_PIX_FMT_RGB555 preview = Tk() image = PhotoImage(ps['pixformat'], (ps['width'], ps['height'])) label = Label(preview, text='Preview', image=image, width=ps['width'], height=ps['height']) label.pack() capability = v4l2_capability() size = v4l2_frmsizeenum() format = v4l2_format() request = v4l2_requestbuffers() buffer = v4l2_buffer() b_address = c_void_p() type = V4L2_BUF_TYPE_VIDEO_CAPTURE device = open(device_name, 'rw') ioctl(device, VIDIOC_QUERYCAP, capability) size.pixel_format = PIX_FMT size.index = 0 format.type = type format.fmt.pix.pixelformat = PIX_FMT format.fmt.pix.width = size.discrete.width format.fmt.pix.height = size.discrete.height format.fmt.pix.field = V4L2_FIELD_NONE request.type = type request.memory = V4L2_MEMORY_USERPTR request.count = 1 format.fmt.pix.sizeimage = format.fmt.pix.width * format.fmt.pix.height * 4 buffer.length = format.fmt.pix.sizeimage ioctl(device, VIDIOC_S_FMT, format) posix_memalign(byref(b_address), getpagesize(), format.fmt.pix.sizeimage) buffer.m.userptr = b_address.value buffer.type = request.type buffer.memory = request.memory ioctl(device, VIDIOC_REQBUFS, request) while True: ioctl(device, VIDIOC_QBUF, buffer) ioctl(device, VIDIOC_STREAMON, cast(type, c_void_p)) ioctl(device, VIDIOC_DQBUF, buffer) **# What happens here? preview_data is wrong?** preview_data = string_at(buffer.m.userptr, buffer.length) im = frombuffer(ps['pixformat'], (ps['width'], ps['height']), preview_data) image.paste(im) preview.update()
user pointer in python
*I am trying to display preview from webcam captured using v4l. Here is an idea of how the code looks like: from ctypes import * from v4l2 import * from Image import fromstring from Tkinter import Tk, Label from ImageTk import PhotoImage from ctypes.util import find_library libc = CDLL(find_library('c')) posix_memalign = libc.posix_memalign getpagesize = libc.getpagesize device_name = '/dev/video0' ps = preview_settings = { 'width': 320, 'height': 240, 'pixformat': 'RGB', } PIX_FMT = V4L2_PIX_FMT_RGB555 preview = Tk() image = PhotoImage(ps['pixformat'], (ps['width'], ps['height'])) label = Label(preview, text='Preview', image=image, width=ps['width'], height=ps['height']) label.pack() capability = v4l2_capability() size = v4l2_frmsizeenum() format = v4l2_format() request = v4l2_requestbuffers() buffer = v4l2_buffer() b_address = c_void_p() frame_name_count = '0' type = V4L2_BUF_TYPE_VIDEO_CAPTURE device = open(device_name, 'rw') ioctl(device, VIDIOC_QUERYCAP, addr(capability)) size.pixel_format = PIX_FMT size.index = 0 format.type = type format.fmt.pix.pixelformat = PIX_FMT format.fmt.pix.width = size.discrete.width format.fmt.pix.height = size.discrete.height format.fmt.pix.field = V4L2_FIELD_NONE format.fmt.pix.bytesperline = 0 format.fmt.pix.sizeimage = 0 request.type = type request.memory = V4L2_MEMORY_USERPTR request.count = 1 ioctl(device, VIDIOC_S_FMT, addr(format)) ioctl(device, VIDIOC_G_FMT, addr(format)) ioctl(device, VIDIOC_REQBUFS, addr(request)) posix_memalign(addressof(b_address), getpagesize(), format.fmt.pix.sizeimage) buffer.type = request.type buffer.memory = request.memory buffer.index = 0 buffer.m.userptr = b_address.value buffer.length = format.fmt.pix.sizeimage while True: ioctl(device, VIDIOC_QBUF, addr(buffer)) ioctl(device, VIDIOC_STREAMON, cast(type, c_void_p)) ioctl(device, VIDIOC_DQBUF, addr(buffer)) preview_data = string_at(buffer.m.userptr, buffer.length) im = fromstring(ps['pixformat'], (ps['width'], ps['height']), preview_data) image.paste(im) preview.update() and I get ValueError: not enough image data well, I import c_lib = CDLL(find_library('c')) posix_memalign = c_lib.posix_memalign getpagesize = c_lib.getpagesize and then after ioctl(device, VIDIOC_S_FMT, addr(format)) ioctl(device, VIDIOC_G_FMT, addr(format)) and stuff like that, I try to acquire memory posix_memalign(addressof(b_address), getpagesize(), format.fmt.pix.sizeimage) now b_address is no longer = None b_address is something like c_void_p(145014784) then I start the loop, QBUF, DQBUF, etc.. the thing is, that when I call pygame.image.frombuffer pg_img = pygame.image.frombuffer( buffer.m.userptr, (format.fmt.pix.width, format.fmt.pix.height), preview_settings['pixformat'] ) I get TypeError: expected a character buffer object
[ "Looks like ctypes.string_at(address, size) is what you want. That'll give you a python string buffer with the contents of the memory at your pointer's address. This should be suitable to pass to Image.fromstring or pygame.image.frombuffer.\n", "I don't know much about ctypes, but I am doing a similar thing (wrapped c++ webcam capture, displayed with DirectPython).\nIn my case I just made a buffer in python like this:\nbufferSize = imageWidth * imageHeight\nbuf = \"\\0\" * bufferSize\n\nPass buf to your image capture function for filling?\nMaybe post a more complete code sample...\n", "Have you tried passing buffer directly as the first arg? If that doesn't work and you want to make a writeable character buffer with ctypes, create_string_buffer is the only way I know (I don't understand where you're getting the b_address.value from).\n", "OK, what I did was to leave pygame for Tkinter and PIL\nnow after the same allocation I pass buffer.m.userptr *to fromstring method from Image\nfirst I have, of course, the following:\nimport Image\nimport Tkinter\n\ntk = Tkinter.Tk()\npreview = ImageTk.PhotoImage(ps['pixformat'], (ps['width'], ps['height']))\nlabel = Tkinter.Label(tk, text='Preview', image=preview, width=ps['width'], height=ps['height'])\nlabel.pack()\n\nand now preview:\nim = Image.fromstring(ps['pixformat'], (format.fmt.pix.width, format.fmt.pix.height), '\\0'*buffer.m.userptr)\npreview.paste(im)\ntk.update()\n\nI did what @sipickles said, with '\\0' to see if the whole thing will work\nAnd it did :)\nthe thing is how to pas that userptr correctly and is the data in it actually what it needs to be passed to the preview\nI am really lost here. Someone knows v4l2?\n", "Ok. so for now I fixed the sizeimage problem by setting the sizeimage myself:\nNow frombuffer displays something that is not the frame from the buffer.\nfrom ctypes import *\nfrom v4l2 import *\nfrom Image import fromstring\nfrom Tkinter import Tk, Label\nfrom ImageTk import PhotoImage\nfrom ctypes.util import find_library\n\nlibc = CDLL(find_library('c'))\nposix_memalign = libc.posix_memalign\ngetpagesize = libc.getpagesize\n\n\ndevice_name = '/dev/video0'\nps = preview_settings = {\n 'width': 320,\n 'height': 240,\n 'pixformat': 'RGB',\n }\nPIX_FMT = V4L2_PIX_FMT_RGB555\n\n\npreview = Tk()\nimage = PhotoImage(ps['pixformat'], (ps['width'], ps['height']))\nlabel = Label(preview, text='Preview', image=image, width=ps['width'], height=ps['height'])\nlabel.pack()\n\n\ncapability = v4l2_capability()\nsize = v4l2_frmsizeenum()\nformat = v4l2_format()\nrequest = v4l2_requestbuffers()\nbuffer = v4l2_buffer()\nb_address = c_void_p()\ntype = V4L2_BUF_TYPE_VIDEO_CAPTURE\n\ndevice = open(device_name, 'rw')\n\nioctl(device, VIDIOC_QUERYCAP, capability)\n\nsize.pixel_format = PIX_FMT \nsize.index = 0\n\nformat.type = type\nformat.fmt.pix.pixelformat = PIX_FMT\nformat.fmt.pix.width = size.discrete.width\nformat.fmt.pix.height = size.discrete.height\nformat.fmt.pix.field = V4L2_FIELD_NONE\n\nrequest.type = type\nrequest.memory = V4L2_MEMORY_USERPTR\nrequest.count = 1\n\nformat.fmt.pix.sizeimage = format.fmt.pix.width * format.fmt.pix.height * 4\nbuffer.length = format.fmt.pix.sizeimage\n\nioctl(device, VIDIOC_S_FMT, format)\n\nposix_memalign(byref(b_address), getpagesize(), format.fmt.pix.sizeimage)\n\nbuffer.m.userptr = b_address.value\n\nbuffer.type = request.type\nbuffer.memory = request.memory\n\nioctl(device, VIDIOC_REQBUFS, request)\n\nwhile True:\n\n ioctl(device, VIDIOC_QBUF, buffer)\n\n ioctl(device, VIDIOC_STREAMON, cast(type, c_void_p))\n\n ioctl(device, VIDIOC_DQBUF, buffer)\n\n **# What happens here? preview_data is wrong?**\n preview_data = string_at(buffer.m.userptr, buffer.length)\n\n im = frombuffer(ps['pixformat'], (ps['width'], ps['height']), preview_data)\n image.paste(im)\n preview.update()\n\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "ctypes", "python", "v4l2" ]
stackoverflow_0002070768_ctypes_python_v4l2.txt
Q: How to read a CSV line with "? A trivial CSV line could be spitted using string split function. But some lines could have ", e.g. "good,morning", 100, 300, "1998,5,3" thus directly using string split would not solve the problem. My solution is to first split out the line using , and then combining the strings with " at then begin or end of the string. What's the best practice for this problem? I am interested if there's a Python or F# code snippet for this. EDIT: I am more interested in the implementation detail, rather than using a library. A: There's a csv module in Python, which handles this. Edit: This task falls into "build a lexer" category. The standard way to do such tasks is to build a state machine (or use a lexer library/framework that will do it for you.) The state machine for this task would probably only need two states: Initial one, where it reads every character except comma and newline as part of field (exception: leading and trailing spaces) , comma as the field separator, newline as record separator. When it encounters an opening quote it goes into read-quoted-field state, where every character (including comma & newline) excluding quote is treated as part of field, a quote not followed by a quote means end of read-quoted-field (back to initial state), a quote followed by a quote is treated as a single quote (escaped quote). By the way, your concatenating solution will break on "Field1","Field2" or "Field1"",""Field2". A: From python's CSV module: reading a normal CSV file: import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: print row Reading a file with an alternate format: import csv reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE) for row in reader: print row There are some nice usage examples in LinuxJournal.com. If you're interested with the details, read "split string at commas respecting quotes when string not in csv format" showing some nice regexen related to this problem, or simply read the csv module source. A: Chapter 4 of The Practice of Programming gave both C and C++ implementations of the CSV parser. A: The generic implementation detail would be something like this (untested) def csvline2fields(line): fields = [] quote = None while line.strip(): line = line.strip() if line[0] in ("'", '"'): # Find the next quote: end = line.find(line[0]) fields.append(line[1:end]) # Find the beginning of the next field next = line.find(SEPARATOR) if next == -1: break line = line[next+1:] continue # find the next separator: next = line.find(SEPARATOR) fields.append(line[0:next]) line = line[next+1:]
How to read a CSV line with "?
A trivial CSV line could be spitted using string split function. But some lines could have ", e.g. "good,morning", 100, 300, "1998,5,3" thus directly using string split would not solve the problem. My solution is to first split out the line using , and then combining the strings with " at then begin or end of the string. What's the best practice for this problem? I am interested if there's a Python or F# code snippet for this. EDIT: I am more interested in the implementation detail, rather than using a library.
[ "There's a csv module in Python, which handles this.\nEdit: This task falls into \"build a lexer\" category. The standard way to do such tasks is to build a state machine (or use a lexer library/framework that will do it for you.) \nThe state machine for this task would probably only need two states:\n\nInitial one, where it reads every character except comma and newline as part of field (exception: leading and trailing spaces) , comma as the field separator, newline as record separator. When it encounters an opening quote it goes into\nread-quoted-field state, where every character (including comma & newline) excluding quote is treated as part of field, a quote not followed by a quote means end of read-quoted-field (back to initial state), a quote followed by a quote is treated as a single quote (escaped quote).\n\nBy the way, your concatenating solution will break on \"Field1\",\"Field2\" or \"Field1\"\",\"\"Field2\".\n", "From python's CSV module:\nreading a normal CSV file:\nimport csv\nreader = csv.reader(open(\"some.csv\", \"rb\"))\nfor row in reader:\n print row\n\nReading a file with an alternate format:\nimport csv\nreader = csv.reader(open(\"passwd\", \"rb\"), delimiter=':', quoting=csv.QUOTE_NONE)\nfor row in reader:\n print row\n\nThere are some nice usage examples in LinuxJournal.com.\nIf you're interested with the details, read \"split string at commas respecting quotes when string not in csv format\" showing some nice regexen related to this problem, or simply read the csv module source.\n", "Chapter 4 of The Practice of Programming gave both C and C++ implementations of the CSV parser.\n", "The generic implementation detail would be something like this (untested)\ndef csvline2fields(line):\n fields = []\n quote = None\n while line.strip():\n line = line.strip()\n if line[0] in (\"'\", '\"'):\n # Find the next quote:\n end = line.find(line[0])\n fields.append(line[1:end])\n # Find the beginning of the next field\n next = line.find(SEPARATOR)\n if next == -1:\n break\n line = line[next+1:]\n continue\n # find the next separator:\n next = line.find(SEPARATOR)\n fields.append(line[0:next])\n line = line[next+1:]\n\n" ]
[ 11, 3, 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002139750_csv_python.txt
Q: Bash or Python or Awk to match and modify files I have a set of 10000 files c1.dat ... c10000.dat. Each of these files contains a line which starts with @ and contains a string with spaces specific for this file, lije c37 7.379 6.23. I have another set of 10000 files kind of determined_cXXX_send.dat (where XXX goes from 1 to 10000). Each of these files has only one line. Each line is of thsis type: _1 1 3456.000000 -21 0 -98.112830 -20.326192 What I would like to do is, for each number XXX (between 1 to 10000), get from the cXXX.dat file the string like c37 7.379 6.23 , and add it in the file determined_cXXX_send.dat to the beginning of the file so I get: c37 7.379 6.23 _1 1 3456.000000 -21 0 -98.112830 -20.326192 I tried with both bash and python but got no good solution. What would be the best approach? thanks A: A language basically made for processing text: Perl! A: If each of the two types of files only has one line: for i in {1..10000} do paste "c${i}.dat" "determined_c${i}_send.dat" > c${i}.out && mv "c{$i}.out" "determined_c${i}_send.dat" done Edit: for i in {1..10000} do line=$(grep -o "^c${i}.*") line="${line#@*}" read data < determined_c${i}_send.dat echo "$line $data" > c${i}.out && mv "c{$i}.out" "determined_c${i}_send.dat" done A: In Python, you could do something like that # loop on all the files for num in range(1,1000): cfile = open ( 'c%u.dat'%num, mode='r') # find the specific line for line in cfile: if line[0]=='@': # open the determined file and add the line dfile = open( 'determined_c%u_send.dat'%num, mode='a') dfile.write( line[1:-1] ) dfile.close() cfile.close() It's untested, but it should work EDIT: I realized you wanted to add the line at the beginning of the determined_cXXX_send.dat, not at the end. So, based on Dennis Williamson's answer, I can also propose the following bash code for i in {1..2} do mv "determined_c${i}_send.dat" "temp.out" cat c1.dat | grep @ | tr -d "@" > "determined_c${i}_send.dat" cat temp.out >> "determined_c${i}_send.dat" done rm temp.out A: Doing this in Python should be pretty trivial. It's probably possible in awk, but sounds a bit too complicated to be fun. It's surely is possible in bash, but programming in bash is for masochists. I'd go with Python, of the given options, although Perl and Ruby are good options too if you know them. A: if "c37 7.379 6.23" is constant, then there's no need to grab this string from cXXX.dat files. But i am guessing this string is dynamic ,and it comes after @., so you can try this #!/bin/bash shopt -s nullglob for file in c{1..1000}.dat do if [ -e "$file" ];then tag=${file%.dat} while read -r line do case "$line" in @*) mystring=${line##@};; esac done < "$file" if [ -e "determined_${tag}_send.dat" ]; then while read -r line do echo "$mystring $line" done < "determined_${tag}_send.dat" > temp mv temp "determined_${tag}_send.dat" fi fi done output $ cat c1.dat @ c37 7.379 6.23 $ cat determined_c1_send.dat _1 1 3456.000000 -21 0 -98.112830 -20.326192 $ ./shell.sh $ cat determined_c1_send.dat c37 7.379 6.23 _1 1 3456.000000 -21 0 -98.112830 -20.326192
Bash or Python or Awk to match and modify files
I have a set of 10000 files c1.dat ... c10000.dat. Each of these files contains a line which starts with @ and contains a string with spaces specific for this file, lije c37 7.379 6.23. I have another set of 10000 files kind of determined_cXXX_send.dat (where XXX goes from 1 to 10000). Each of these files has only one line. Each line is of thsis type: _1 1 3456.000000 -21 0 -98.112830 -20.326192 What I would like to do is, for each number XXX (between 1 to 10000), get from the cXXX.dat file the string like c37 7.379 6.23 , and add it in the file determined_cXXX_send.dat to the beginning of the file so I get: c37 7.379 6.23 _1 1 3456.000000 -21 0 -98.112830 -20.326192 I tried with both bash and python but got no good solution. What would be the best approach? thanks
[ "A language basically made for processing text: Perl!\n", "If each of the two types of files only has one line:\nfor i in {1..10000}\ndo\n paste \"c${i}.dat\" \"determined_c${i}_send.dat\" > c${i}.out && \n mv \"c{$i}.out\" \"determined_c${i}_send.dat\"\ndone\n\nEdit:\nfor i in {1..10000}\ndo\n line=$(grep -o \"^c${i}.*\")\n line=\"${line#@*}\"\n read data < determined_c${i}_send.dat\n echo \"$line $data\" > c${i}.out &&\n mv \"c{$i}.out\" \"determined_c${i}_send.dat\"\ndone\n\n", "In Python, you could do something like that\n# loop on all the files\nfor num in range(1,1000):\n\n cfile = open ( 'c%u.dat'%num, mode='r')\n\n # find the specific line\n for line in cfile:\n if line[0]=='@':\n\n # open the determined file and add the line\n dfile = open( 'determined_c%u_send.dat'%num, mode='a')\n dfile.write( line[1:-1] )\n dfile.close()\n\n cfile.close()\n\nIt's untested, but it should work\nEDIT: I realized you wanted to add the line at the beginning of the determined_cXXX_send.dat, not at the end.\nSo, based on Dennis Williamson's answer, I can also propose the following bash code\nfor i in {1..2}\ndo\n mv \"determined_c${i}_send.dat\" \"temp.out\"\n cat c1.dat | grep @ | tr -d \"@\" > \"determined_c${i}_send.dat\"\n cat temp.out >> \"determined_c${i}_send.dat\"\ndone\nrm temp.out\n\n", "Doing this in Python should be pretty trivial. It's probably possible in awk, but sounds a bit too complicated to be fun. It's surely is possible in bash, but programming in bash is for masochists.\nI'd go with Python, of the given options, although Perl and Ruby are good options too if you know them.\n", "if \"c37 7.379 6.23\" is constant, then there's no need to grab this string from cXXX.dat files. But i am guessing this string is dynamic ,and it comes after @., so you can try this\n#!/bin/bash\nshopt -s nullglob\nfor file in c{1..1000}.dat\ndo\n if [ -e \"$file\" ];then\n tag=${file%.dat}\n while read -r line\n do\n case \"$line\" in\n @*)\n mystring=${line##@};;\n esac\n done < \"$file\"\n if [ -e \"determined_${tag}_send.dat\" ]; then\n while read -r line\n do\n echo \"$mystring $line\"\n done < \"determined_${tag}_send.dat\" > temp\n mv temp \"determined_${tag}_send.dat\"\n fi\n fi\ndone\n\noutput\n$ cat c1.dat\n@ c37 7.379 6.23\n\n$ cat determined_c1_send.dat\n_1 1 3456.000000 -21 0 -98.112830 -20.326192\n\n$ ./shell.sh\n$ cat determined_c1_send.dat\n c37 7.379 6.23 _1 1 3456.000000 -21 0 -98.112830 -20.326192\n\n" ]
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "awk", "bash", "python" ]
stackoverflow_0002139823_awk_bash_python.txt
Q: Ping a network using threads and testing it I am trying to ping two different networks with thread. I am able to get the response I want but I want to convert it into a test. I have the code that I have tried below but the test runner says that no tests were run. The code is below: #!/home/workspace/downloads/Python-2.6.4/python from threading import Thread import subprocess, unittest from Queue import Queue class TestPing(unittest.TestCase): num_threads = 4 queue = Queue() ips = ["10.51.54.100", "10.51.54.122"] #wraps system ping command def RunTest(i, q): """Pings subnet""" while True: ip = q.get() print "Thread %s: Pinging %s" % (i, ip) ret = subprocess.call("ping -c 1 %s" % ip, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) if ret == 0: print "%s: is alive" % ip assert True else: print "%s: did not respond" % ip assert False q.task_done() #Spawn thread pool for i in range(num_threads): worker = Thread(target=pinger, args=(i, queue)) worker.setDaemon(True) worker.start() #Place work in queue for ip in ips: queue.put(ip) #Wait until worker threads are done to exit queue.join() class PingTestSuite(unittest.TestSuite): def makePingTestSuite(): suite = unittest.TestSuite() suite.addTest(TestPingMove("TestPing")) return suite def suite(): return unittest.makeSuite(TestPing) if __name__ == '__main__': unittest.main() I want the test to assert either true and false if a network gives no response and to run two tests for the 2 networks to be pinged. Does anyone know where I have gone wrong? A: When you subclass unittest.TestCase, all methods whose name begins with test, get run automatically. Otherwise, the code is not run as a test. (So RunTest is not getting run). So if you change RunTest to (the not so mellifluous) test_RunTest: class TestPing(unittest.TestCase): def test_RunTest(self): add code here then the code will run. Also note, that unittest expects test_RunTest's first and only argument to be self. If you want to test that func(args) raises an error, then use self.assertRaises like this: self.assertRaises(AssertionError, func, args) Or, if func returns True or False, then you can tests that the proper value is returned by using self.assertTrue or self.assertFalse. Also, when you write unit tests, it would be wise to place all your functions/classes in a module, import the module for the unittest script, and then test that the functions are returning or raising what you expect in the unittest script. I could be wrong, but it seems as though at the moment you have the two pieces mixed together.
Ping a network using threads and testing it
I am trying to ping two different networks with thread. I am able to get the response I want but I want to convert it into a test. I have the code that I have tried below but the test runner says that no tests were run. The code is below: #!/home/workspace/downloads/Python-2.6.4/python from threading import Thread import subprocess, unittest from Queue import Queue class TestPing(unittest.TestCase): num_threads = 4 queue = Queue() ips = ["10.51.54.100", "10.51.54.122"] #wraps system ping command def RunTest(i, q): """Pings subnet""" while True: ip = q.get() print "Thread %s: Pinging %s" % (i, ip) ret = subprocess.call("ping -c 1 %s" % ip, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) if ret == 0: print "%s: is alive" % ip assert True else: print "%s: did not respond" % ip assert False q.task_done() #Spawn thread pool for i in range(num_threads): worker = Thread(target=pinger, args=(i, queue)) worker.setDaemon(True) worker.start() #Place work in queue for ip in ips: queue.put(ip) #Wait until worker threads are done to exit queue.join() class PingTestSuite(unittest.TestSuite): def makePingTestSuite(): suite = unittest.TestSuite() suite.addTest(TestPingMove("TestPing")) return suite def suite(): return unittest.makeSuite(TestPing) if __name__ == '__main__': unittest.main() I want the test to assert either true and false if a network gives no response and to run two tests for the 2 networks to be pinged. Does anyone know where I have gone wrong?
[ "When you subclass unittest.TestCase, all methods whose name begins with test, get run automatically. Otherwise, the code is not run as a test. (So RunTest is not getting run).\nSo if you change RunTest to (the not so mellifluous) test_RunTest:\nclass TestPing(unittest.TestCase):\n def test_RunTest(self):\n add code here\n\nthen the code will run. Also note, that unittest expects test_RunTest's first and only argument to be self.\nIf you want to test that func(args) raises an error, then use self.assertRaises like this:\nself.assertRaises(AssertionError, func, args)\n\nOr, if func returns True or False, then you can tests that the proper value is returned by using self.assertTrue or self.assertFalse.\nAlso, when you write unit tests, it would be wise to place all your functions/classes in a module, import the module for the unittest script, and then test that the functions are returning or raising what you expect in the unittest script. I could be wrong, but it seems as though at the moment you have the two pieces mixed together.\n" ]
[ 3 ]
[]
[]
[ "multithreading", "ping", "python", "testing" ]
stackoverflow_0002139947_multithreading_ping_python_testing.txt
Q: How to build standalone python installation How can I build python interpreter which can be installed by just extracting the archive? e.g. I want to python-2.6.tar.gz. User will extract it in any directory, and start using it. A: Maybe portablepython (currently Windows only) will help. You can try using it directly, or follow the install process to learn how to create such an environment. Portable Python is a Python® programming language preconfigured to run directly from any USB storage device, enabling you to have, at any time, a portable programming environment. A: I went another way, on debian, and wrote a script to automate the install of python. This is python-specific, but uses fabric and paramiko to deploy python on remote machines. see: http://bitbucket.org/chris.mahan/debian-stable-python-2.6.4-deployer/ This may help you.
How to build standalone python installation
How can I build python interpreter which can be installed by just extracting the archive? e.g. I want to python-2.6.tar.gz. User will extract it in any directory, and start using it.
[ "Maybe portablepython (currently Windows only) will help. You can try using it directly, or follow the install process to learn how to create such an environment.\n\nPortable Python is a Python® programming language preconfigured to run directly from any USB storage device, enabling you to have, at any time, a portable programming environment.\n\n", "I went another way, on debian, and wrote a script to automate the install of python. \nThis is python-specific, but uses fabric and paramiko to deploy python on remote machines. see:\nhttp://bitbucket.org/chris.mahan/debian-stable-python-2.6.4-deployer/\nThis may help you. \n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002130608_python.txt
Q: How to write a wrapper over functions and member functions that executes some code before and after the wrapped function? I'm trying to write some wrapper class or function that allows me to execute some code before and after the wrapped function. float foo(int x, float y) { return x * y; } BOOST_PYTHON_MODULE(test) { boost::python::def("foo", <somehow wrap "&foo">); } Ideally, the wrapper should be generic, working for functions and member functions alike, with any signature. More info: I'm looking for a simple way to release/re-acquire the GIL around my expensive C++ calls without having to manually write thin wrappers like this: float foo_wrapper(int x, float y) { Py_BEGIN_ALLOW_THREADS int result = foo(x, y); Py_END_ALLOW_THREADS return result; } BOOST_PYTHON_MODULE(test) { boost::python::def("foo", &foo_wrapper); } This kind of wrapper will be repeated several times for all kinds of functions, and I would like to find a solution that would allow me to avoid coding all of them. I have tried some approaches, but the best I could come with required the user to explicitly state the types of return values and parameters, like: boost::python::def("foo", &wrap_gil<float, int, float>(&foo_wrapper)); But it seems to me it should be possible to just pass the pointer to the function (&foo_wrapper) and let the compiler figure out the types. Does anyone know a technique I could use or point me in the right direction? Cheers! A: In this case, you can write a Functor class that wraps over your function, and then overload boost::python::detail::get_signature to accept your Functor! UPDATE: Added support for member functions too! Example: #include <boost/shared_ptr.hpp> #include <boost/python.hpp> #include <boost/python/signature.hpp> #include <boost/mpl/vector.hpp> #include <iostream> #include <string> #include <sstream> static boost::shared_ptr<std::ostringstream> test_stream_data; std::ostringstream& test_stream() { if (!test_stream_data) { test_stream_data.reset(new std::ostringstream); } return *test_stream_data; } std::string get_value_and_clear_test_stream() { std::string result; if (test_stream_data) { result = test_stream_data->str(); } test_stream_data.reset(new std::ostringstream); return result; } std::string func(int a, double b) { std::ostringstream oss; oss << "func(a=" << a << ", b=" << b << ")"; std::string result = oss.str(); test_stream() << "- In " << result << std::endl; return result; } class MyClass { public: MyClass(std::string p_name) : m_name(p_name) { test_stream() << "- In MyClass::MyClass(p_name=\"" << p_name << "\")" << std::endl; } MyClass(MyClass const& p_another) : m_name(p_another.m_name) { test_stream() << "- In MyClass::MyClass(p_another=MyClass(\"" << p_another.m_name << "\"))" << std::endl; } ~MyClass() { test_stream() << "- In MyClass(\"" << this->m_name << "\")::~MyClass()" << std::endl; } boost::shared_ptr<MyClass> clone_and_change(std::string p_new_name) { test_stream() << "- In MyClass(\"" << this->m_name << "\").clone_and_change(p_new_name=\"" << p_new_name << "\")" << std::endl; boost::shared_ptr<MyClass> result(new MyClass(*this)); result->m_name = p_new_name; return result; } std::string get_name() { test_stream() << "- In MyClass(\"" << this->m_name << "\").get_name()" << std::endl; return this->m_name; } std::string m_name; }; struct ScopePreAndPostActions { ScopePreAndPostActions() { test_stream() << "[Before action...]" << std::endl; } ~ScopePreAndPostActions() { test_stream() << "[After action...]" << std::endl; } }; template <class FuncType_> struct FuncWrapper; // You can code-generate specializations for other arities... template <class R_, class A0_, class A1_> struct FuncWrapper<R_ (A0_, A1_)> { typedef R_ (*func_type)(A0_, A1_); typedef typename boost::add_const<typename boost::add_reference<typename A0_>::type>::type AC0_; typedef typename boost::add_const<typename boost::add_reference<typename A1_>::type>::type AC1_; func_type m_wrapped_func; FuncWrapper(func_type p_wrapped_func) : m_wrapped_func(p_wrapped_func) { } R_ operator()(AC0_ p0, AC1_ p1) { ScopePreAndPostActions actions_guard; return this->m_wrapped_func(p0, p1); } }; template < class R_, class C_, class A0_=void, class A1_=void, class A2_=void // ... > struct MemberFuncWrapper; template <class R_, class C_, class A0_> struct MemberFuncWrapper<R_, C_, A0_> { typedef R_ (C_::*member_func_type)(A0_); typedef typename boost::add_const<typename boost::add_reference<typename A0_>::type>::type AC0_; member_func_type m_wrapped_method; MemberFuncWrapper(member_func_type p_wrapped_method) : m_wrapped_method(p_wrapped_method) { } R_ operator()(C_* p_self, AC0_ p0) { ScopePreAndPostActions actions_guard; return (p_self->*(this->m_wrapped_method))(p0); return R_(); } }; namespace boost { namespace python { namespace detail { // You can code-generate specializations for other arities... template <class R_, class P0_, class P1_> inline boost::mpl::vector<R_, P0_, P1_> get_signature(FuncWrapper<R_ (P0_, P1_)>, void* = 0) { return boost::mpl::vector<R_, P0_, P1_>(); } template <class R_, class C_, class P0_> inline boost::mpl::vector<R_, C_*, P0_> get_signature(MemberFuncWrapper<R_, C_, P0_>, void* = 0) { return boost::mpl::vector<R_, C_*, P0_>(); } } } } // ------------------------------------------------------------------- template <class FuncPtr_> void make_wrapper(FuncPtr_); // You can code-generate specializations for other arities... template <class R_, class A0_, class A1_> FuncWrapper<R_ (A0_, A1_)> make_wrapper(R_ (*p_wrapped_func)(A0_, A1_)) { return FuncWrapper<R_ (A0_, A1_)>(p_wrapped_func); } template <class R_, class C_, class A0_> MemberFuncWrapper<R_, C_, A0_> make_wrapper(R_ (C_::*p_wrapped_method)(A0_)) { return MemberFuncWrapper<R_, C_, A0_>(p_wrapped_method); } template <class R_, class C_, class A0_, class A1_> MemberFuncWrapper<R_, C_, A0_, A1_> make_wrapper(R_ (C_::*p_wrapped_method)(A0_, A1_)) { return MemberFuncWrapper<R_, C_, A0_, A1_>(p_wrapped_method); } using namespace boost::python; void RegisterTestWrapper() { def("GetValueAndClearTestStream", &get_value_and_clear_test_stream); def("TestFunc", &func); def( "TestWrappedFunctor", make_wrapper(&func) ); { class_< MyClass, shared_ptr<MyClass>, boost::noncopyable > c("MyClass", init<std::string>()); c.def("CloneAndChange", &MyClass::clone_and_change); c.def("GetName", &MyClass::get_name); c.def("WrappedCloneAndChange", make_wrapper(&MyClass::clone_and_change)); } } And on python: import unittest from _test_wrapper import GetValueAndClearTestStream, TestFunc, TestWrappedFunctor, MyClass class Test(unittest.TestCase): def setUp(self): GetValueAndClearTestStream() def testWrapper(self): self.assertEqual(TestFunc(69, 1.618), 'func(a=69, b=1.618)') self.assertEqual(GetValueAndClearTestStream(), '- In func(a=69, b=1.618)\n') self.assertEqual(TestWrappedFunctor(69, 1.618), 'func(a=69, b=1.618)') self.assertEqual( GetValueAndClearTestStream(), ( '[Before action...]\n' '- In func(a=69, b=1.618)\n' '[After action...]\n' ), ) def testWrappedMemberFunction(self): from textwrap import dedent x = MyClass("xx") y = x.WrappedCloneAndChange("yy") z = y.WrappedCloneAndChange("zz") self.assertEqual(x.GetName(), "xx") self.assertEqual(y.GetName(), "yy") self.assertEqual(z.GetName(), "zz") self.assertEqual( GetValueAndClearTestStream(), dedent('''\ - In MyClass::MyClass(p_name="xx") [Before action...] - In MyClass("xx").clone_and_change(p_new_name="yy") - In MyClass::MyClass(p_another=MyClass("xx")) [After action...] [Before action...] - In MyClass("yy").clone_and_change(p_new_name="zz") - In MyClass::MyClass(p_another=MyClass("yy")) [After action...] - In MyClass("xx").get_name() - In MyClass("yy").get_name() - In MyClass("zz").get_name() '''), ) A: Have you looked at the function wrapping technique described by Stroustrup in his "Wrapping C++ Member Function Calls" paper? There's also a SO response here that demonstrates how to implement it in a concise manner. Basically you'd implement a template that overloads operator->(). Within that operator's implementation you'd construct a temporary object before your actual function call. The temporary object's constructor and destructor take care of invoking your "pre-" and "post-" code before and after your actual function call, respectively.
How to write a wrapper over functions and member functions that executes some code before and after the wrapped function?
I'm trying to write some wrapper class or function that allows me to execute some code before and after the wrapped function. float foo(int x, float y) { return x * y; } BOOST_PYTHON_MODULE(test) { boost::python::def("foo", <somehow wrap "&foo">); } Ideally, the wrapper should be generic, working for functions and member functions alike, with any signature. More info: I'm looking for a simple way to release/re-acquire the GIL around my expensive C++ calls without having to manually write thin wrappers like this: float foo_wrapper(int x, float y) { Py_BEGIN_ALLOW_THREADS int result = foo(x, y); Py_END_ALLOW_THREADS return result; } BOOST_PYTHON_MODULE(test) { boost::python::def("foo", &foo_wrapper); } This kind of wrapper will be repeated several times for all kinds of functions, and I would like to find a solution that would allow me to avoid coding all of them. I have tried some approaches, but the best I could come with required the user to explicitly state the types of return values and parameters, like: boost::python::def("foo", &wrap_gil<float, int, float>(&foo_wrapper)); But it seems to me it should be possible to just pass the pointer to the function (&foo_wrapper) and let the compiler figure out the types. Does anyone know a technique I could use or point me in the right direction? Cheers!
[ "In this case, you can write a Functor class that wraps over your function, and then overload boost::python::detail::get_signature to accept your Functor!\nUPDATE: Added support for member functions too!\nExample:\n#include <boost/shared_ptr.hpp>\n#include <boost/python.hpp>\n#include <boost/python/signature.hpp>\n#include <boost/mpl/vector.hpp>\n\n#include <iostream>\n#include <string>\n#include <sstream>\n\nstatic boost::shared_ptr<std::ostringstream> test_stream_data;\n\nstd::ostringstream& test_stream()\n{\n if (!test_stream_data) {\n test_stream_data.reset(new std::ostringstream);\n }\n return *test_stream_data;\n}\n\n\nstd::string get_value_and_clear_test_stream()\n{\n std::string result;\n if (test_stream_data) {\n result = test_stream_data->str();\n }\n test_stream_data.reset(new std::ostringstream);\n return result;\n}\n\n\nstd::string func(int a, double b)\n{\n std::ostringstream oss;\n oss << \"func(a=\" << a << \", b=\" << b << \")\";\n std::string result = oss.str();\n test_stream() << \"- In \" << result << std::endl;\n return result;\n}\n\n\nclass MyClass\n{\npublic:\n MyClass(std::string p_name)\n : m_name(p_name)\n {\n test_stream() << \"- In MyClass::MyClass(p_name=\\\"\" << p_name << \"\\\")\" << std::endl;\n }\n\n MyClass(MyClass const& p_another)\n : m_name(p_another.m_name)\n {\n test_stream()\n << \"- In MyClass::MyClass(p_another=MyClass(\\\"\"\n << p_another.m_name << \"\\\"))\" << std::endl;\n }\n\n ~MyClass()\n {\n test_stream() << \"- In MyClass(\\\"\" << this->m_name << \"\\\")::~MyClass()\" << std::endl;\n }\n\n boost::shared_ptr<MyClass> clone_and_change(std::string p_new_name)\n {\n test_stream()\n << \"- In MyClass(\\\"\" << this->m_name << \"\\\").clone_and_change(p_new_name=\\\"\"\n << p_new_name << \"\\\")\" << std::endl;\n\n boost::shared_ptr<MyClass> result(new MyClass(*this));\n result->m_name = p_new_name;\n\n return result;\n }\n\n std::string get_name()\n {\n test_stream() << \"- In MyClass(\\\"\" << this->m_name << \"\\\").get_name()\" << std::endl;\n return this->m_name;\n }\n\n std::string m_name;\n};\n\n\nstruct ScopePreAndPostActions\n{\n ScopePreAndPostActions()\n {\n test_stream() << \"[Before action...]\" << std::endl;\n }\n\n ~ScopePreAndPostActions()\n {\n test_stream() << \"[After action...]\" << std::endl;\n }\n};\n\n\n\n\n\ntemplate <class FuncType_>\nstruct FuncWrapper;\n\n// You can code-generate specializations for other arities...\n\ntemplate <class R_, class A0_, class A1_>\nstruct FuncWrapper<R_ (A0_, A1_)>\n{\n typedef R_ (*func_type)(A0_, A1_);\n\n typedef typename boost::add_const<typename boost::add_reference<typename A0_>::type>::type AC0_;\n typedef typename boost::add_const<typename boost::add_reference<typename A1_>::type>::type AC1_;\n\n func_type m_wrapped_func;\n\n FuncWrapper(func_type p_wrapped_func)\n : m_wrapped_func(p_wrapped_func)\n {\n }\n\n R_ operator()(AC0_ p0, AC1_ p1)\n {\n ScopePreAndPostActions actions_guard;\n return this->m_wrapped_func(p0, p1);\n }\n};\n\ntemplate <\n class R_,\n class C_,\n class A0_=void,\n class A1_=void,\n class A2_=void\n // ...\n>\nstruct MemberFuncWrapper;\n\ntemplate <class R_, class C_, class A0_>\nstruct MemberFuncWrapper<R_, C_, A0_>\n{\n typedef R_ (C_::*member_func_type)(A0_);\n\n typedef typename boost::add_const<typename boost::add_reference<typename A0_>::type>::type AC0_;\n\n member_func_type m_wrapped_method;\n\n MemberFuncWrapper(member_func_type p_wrapped_method)\n : m_wrapped_method(p_wrapped_method)\n {\n }\n\n R_ operator()(C_* p_self, AC0_ p0)\n {\n ScopePreAndPostActions actions_guard;\n return (p_self->*(this->m_wrapped_method))(p0);\n return R_();\n }\n};\n\n\n\nnamespace boost { namespace python { namespace detail {\n\n // You can code-generate specializations for other arities...\n\n template <class R_, class P0_, class P1_>\n inline boost::mpl::vector<R_, P0_, P1_>\n get_signature(FuncWrapper<R_ (P0_, P1_)>, void* = 0)\n {\n return boost::mpl::vector<R_, P0_, P1_>();\n }\n\n template <class R_, class C_, class P0_>\n inline boost::mpl::vector<R_, C_*, P0_>\n get_signature(MemberFuncWrapper<R_, C_, P0_>, void* = 0)\n {\n return boost::mpl::vector<R_, C_*, P0_>();\n }\n\n} } }\n\n// -------------------------------------------------------------------\n\ntemplate <class FuncPtr_>\nvoid make_wrapper(FuncPtr_);\n\n// You can code-generate specializations for other arities...\n\ntemplate <class R_, class A0_, class A1_>\nFuncWrapper<R_ (A0_, A1_)> make_wrapper(R_ (*p_wrapped_func)(A0_, A1_))\n{\n return FuncWrapper<R_ (A0_, A1_)>(p_wrapped_func);\n}\n\ntemplate <class R_, class C_, class A0_>\nMemberFuncWrapper<R_, C_, A0_> make_wrapper(R_ (C_::*p_wrapped_method)(A0_))\n{\n return MemberFuncWrapper<R_, C_, A0_>(p_wrapped_method);\n}\n\ntemplate <class R_, class C_, class A0_, class A1_>\nMemberFuncWrapper<R_, C_, A0_, A1_> make_wrapper(R_ (C_::*p_wrapped_method)(A0_, A1_))\n{\n return MemberFuncWrapper<R_, C_, A0_, A1_>(p_wrapped_method);\n}\n\n\nusing namespace boost::python;\n\nvoid RegisterTestWrapper()\n{\n def(\"GetValueAndClearTestStream\", &get_value_and_clear_test_stream);\n def(\"TestFunc\", &func);\n def(\n \"TestWrappedFunctor\",\n make_wrapper(&func)\n );\n\n {\n class_< MyClass, shared_ptr<MyClass>, boost::noncopyable > c(\"MyClass\", init<std::string>());\n c.def(\"CloneAndChange\", &MyClass::clone_and_change);\n c.def(\"GetName\", &MyClass::get_name);\n c.def(\"WrappedCloneAndChange\", make_wrapper(&MyClass::clone_and_change));\n }\n}\n\nAnd on python:\nimport unittest\nfrom _test_wrapper import GetValueAndClearTestStream, TestFunc, TestWrappedFunctor, MyClass\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n GetValueAndClearTestStream()\n\n def testWrapper(self):\n self.assertEqual(TestFunc(69, 1.618), 'func(a=69, b=1.618)')\n self.assertEqual(GetValueAndClearTestStream(), '- In func(a=69, b=1.618)\\n')\n\n self.assertEqual(TestWrappedFunctor(69, 1.618), 'func(a=69, b=1.618)')\n self.assertEqual(\n GetValueAndClearTestStream(),\n (\n '[Before action...]\\n'\n '- In func(a=69, b=1.618)\\n'\n '[After action...]\\n'\n ),\n )\n\ndef testWrappedMemberFunction(self):\n from textwrap import dedent\n x = MyClass(\"xx\")\n y = x.WrappedCloneAndChange(\"yy\")\n z = y.WrappedCloneAndChange(\"zz\")\n\n self.assertEqual(x.GetName(), \"xx\")\n self.assertEqual(y.GetName(), \"yy\")\n self.assertEqual(z.GetName(), \"zz\")\n\n self.assertEqual(\n GetValueAndClearTestStream(),\n dedent('''\\\n - In MyClass::MyClass(p_name=\"xx\")\n [Before action...]\n - In MyClass(\"xx\").clone_and_change(p_new_name=\"yy\")\n - In MyClass::MyClass(p_another=MyClass(\"xx\"))\n [After action...]\n [Before action...]\n - In MyClass(\"yy\").clone_and_change(p_new_name=\"zz\")\n - In MyClass::MyClass(p_another=MyClass(\"yy\"))\n [After action...]\n - In MyClass(\"xx\").get_name()\n - In MyClass(\"yy\").get_name()\n - In MyClass(\"zz\").get_name()\n '''),\n )\n\n", "Have you looked at the function wrapping technique described by Stroustrup in his \"Wrapping C++ Member Function Calls\" paper? There's also a SO response here that demonstrates how to implement it in a concise manner. Basically you'd implement a template that overloads operator->(). Within that operator's implementation you'd construct a temporary object before your actual function call. The temporary object's constructor and destructor take care of invoking your \"pre-\" and \"post-\" code before and after your actual function call, respectively.\n" ]
[ 11, 0 ]
[]
[]
[ "binding", "boost_python", "c++", "python", "wrapper" ]
stackoverflow_0002135457_binding_boost_python_c++_python_wrapper.txt
Q: How to invoke a method that has been discovered through inspect.getmembers? import re import sys import inspect import testcases testClass = re.compile(r'.*Case$') testMethod = re.compile(r'.*Test$') for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass): if testClass.match(class_name): for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod): if testMethod.match(method_name): # RIGHT HERE I WOULD LIKE TO INVOKE method_name A: Right after your code: for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass): if testClass.match(class_name): for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod): if testMethod.match(method_name): # RIGHT HERE I WOULD LIKE TO INVOKE method_name you could do: methodobj = getattr(classobj, method_name) methodobj("appropriate arguments go here") if, that is, you had any clue whatsoever about what the "appropriate arguments" are. The first argument is presumably going to be an instance of the class -- which instance? How do you retrieve or create it? And, what about all the other arguments? What are they and what values do you want to pass for them? Getting the method object, ready to be called, is the least of your issues -- getattr, as you see, does that really well and most easily!-) -- but you need sensible answers to the other questions above regarding the arguments (especially the first one, the instance on which you want to call the method) before your question actually makes much sense at all!-) A: Thank you very much alex for the quick response. The first argument is presumably going to be an instance of the class -- which instance? How do you retrieve or create it? Okay, so if i understood you correctly, the first arugment of the method call methodobj should be an instance of classobj? How about the following. methodobj = getattr(classobj, method_name) methodobj(classobj()) What about all the other arguments? What are they and what values do you want to pass for them? Naaah, no other arguments, Those are test cases with set variables in the methods. I just wanna be able to add test cases without having to modify other code in order to run them. Thanks again, i haven't tried it yet, but out of what i read about getattr, it seems like its what i'm looking for. With some playing around i can make it work.
How to invoke a method that has been discovered through inspect.getmembers?
import re import sys import inspect import testcases testClass = re.compile(r'.*Case$') testMethod = re.compile(r'.*Test$') for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass): if testClass.match(class_name): for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod): if testMethod.match(method_name): # RIGHT HERE I WOULD LIKE TO INVOKE method_name
[ "Right after your code:\nfor class_name, class_obj in inspect.getmembers(testcases, inspect.isclass):\n if testClass.match(class_name):\n for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod):\n if testMethod.match(method_name):\n # RIGHT HERE I WOULD LIKE TO INVOKE method_name\n\nyou could do:\n methodobj = getattr(classobj, method_name)\n methodobj(\"appropriate arguments go here\")\n\nif, that is, you had any clue whatsoever about what the \"appropriate arguments\" are. The first argument is presumably going to be an instance of the class -- which instance? How do you retrieve or create it? And, what about all the other arguments? What are they and what values do you want to pass for them?\nGetting the method object, ready to be called, is the least of your issues -- getattr, as you see, does that really well and most easily!-) -- but you need sensible answers to the other questions above regarding the arguments (especially the first one, the instance on which you want to call the method) before your question actually makes much sense at all!-)\n", "Thank you very much alex for the quick response.\n\nThe first argument is presumably going to be an instance of the class -- which instance? How do you retrieve or create it?\n\nOkay, so if i understood you correctly, the first arugment of the method call methodobj should be an instance of classobj? How about the following. \nmethodobj = getattr(classobj, method_name)\nmethodobj(classobj())\n\n\nWhat about all the other arguments?\n What are they and what values do you want to pass for them?\n\nNaaah, no other arguments, Those are test cases with set variables in the methods. I just wanna be able to add test cases without having to modify other code in order to run them. \nThanks again, i haven't tried it yet, but out of what i read about getattr, it seems like its what i'm looking for. With some playing around i can make it work. \n" ]
[ 8, 0 ]
[]
[]
[ "inspect", "python" ]
stackoverflow_0002137539_inspect_python.txt
Q: How can I make this long_description and README differ by a couple of sentences? For a package of mine, I have a README.rst file that is read into the setup.py's long description like so: readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( ... long_description = README_TEXT, .... ) This way that I can have the README file show up on my github page every time I commit and on the pypi page every time I python setup.py register. There's only one problem. I'd like the github page to say something like "This document reflects a pre-release version of envbuilder. For the most recent release, see pypi." I could just put those lines in README.rst and delete them before I python setup.py register, but I know that there's going to be a time that I forget to remove the sentences before I push to pypi. I'm trying to think of the best way to automate this so I don't have to worry about it. Anyone have any ideas? Is there any setuptools/distutils magic I can do? A: You can just use a ReST comment with some text like "split here", and then split on that in your setup.py. Ian Bicking does that in virtualenv with index.txt and setup.py. A: Another option is to side-step the issue completely by adding a paragraph that works in both environments: "The latest unstable code is on github. The latest stable kits are on pypi." After all, why assume that pypi people don't want to be pointed to github? This would be more helpful to both audiences, and simplifies your setup.py. A: You could always do this: GITHUB_ALERT = 'This document reflects a pre-release version...' readme = open('README.rst', 'r') README_TEXT = readme.read().replace(GITHUB_ALERT, '') readme.close() setup( ... long_description = README_TEXT, .... ) But then you'd have to keep that GITHUB_ALERT string in sync with the actual wording of the README. Using a regular expression instead (to, say, match a line beginning with Note for Github Users: or something) might give you a little more flexibility.
How can I make this long_description and README differ by a couple of sentences?
For a package of mine, I have a README.rst file that is read into the setup.py's long description like so: readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( ... long_description = README_TEXT, .... ) This way that I can have the README file show up on my github page every time I commit and on the pypi page every time I python setup.py register. There's only one problem. I'd like the github page to say something like "This document reflects a pre-release version of envbuilder. For the most recent release, see pypi." I could just put those lines in README.rst and delete them before I python setup.py register, but I know that there's going to be a time that I forget to remove the sentences before I push to pypi. I'm trying to think of the best way to automate this so I don't have to worry about it. Anyone have any ideas? Is there any setuptools/distutils magic I can do?
[ "You can just use a ReST comment with some text like \"split here\", and then split on that in your setup.py. Ian Bicking does that in virtualenv with index.txt and setup.py.\n", "Another option is to side-step the issue completely by adding a paragraph that works in both environments: \"The latest unstable code is on github. The latest stable kits are on pypi.\"\nAfter all, why assume that pypi people don't want to be pointed to github? This would be more helpful to both audiences, and simplifies your setup.py.\n", "You could always do this:\nGITHUB_ALERT = 'This document reflects a pre-release version...'\nreadme = open('README.rst', 'r')\nREADME_TEXT = readme.read().replace(GITHUB_ALERT, '')\nreadme.close()\n\nsetup(\n ...\n long_description = README_TEXT,\n ....\n )\n\nBut then you'd have to keep that GITHUB_ALERT string in sync with the actual wording of the README. Using a regular expression instead (to, say, match a line beginning with Note for Github Users: or something) might give you a little more flexibility.\n" ]
[ 9, 5, 2 ]
[]
[]
[ "distutils", "github", "pypi", "python", "setuptools" ]
stackoverflow_0002134941_distutils_github_pypi_python_setuptools.txt
Q: Reformatting code with Regular Expressions We have an ArrayList of items in several classes which are giving me trouble every time I'd like to insert a new item into the list. It was a mistake on my part to have designed the classes in the way I did but changing the design now would be more headache than it's worth (bureaucratic waterfall model.) I should have anticipated format changes to the documents the customer was supplying us waterfall be damned. I'd like to write a simple script in python which goes into a class, adds the item to the list, and then increments all retrievals for the following items. That doesn't sound very explanatory: Foo extends Bar{ public Foo(){ m_Tags.add("Jane"); m_Tags.add("Bob"); m_Tags.add("Jim"); } public String GetJane() { return m_ParsedValue.get( m_Tags.get(1) ); } public String GetBob() { return m_ParsedValue.get( m_Tags.get(2) ); } public String GetJim() { return m_ParsedValue.get( m_Tags.get(3) ); } } You see if I want to add a value between "Jane" and "Bob" I then have to increment the integers in the Get* functions. I just want to write a simple script in Python that does the work for me. Someone I very much respect suggested regex. Edit: Yes, LinkedHashMap. So simple, so easy and so not in the design specs now. I hate waterfall. Hate it with a passion. This whole bit was a "small" and "easy" part that "shouldn't take much time to design." I made mistakes. It's stuck in stone now. A: Don't do this with regexp. Create symbolic constants (using for example an enum) that map the names to numbers. A: You want your regular expression to be as flexible as the compiler will be with respect to whitespace between tokens. Doing so and mimicking whitespace usage makes the pattern pretty messy. The code below (sorry: Perl, not Python) edits your source files in-place. #! /usr/bin/perl -i.bak use warnings; use strict; my $template = '^( public String Get)(\w+)( \( \) { return m_ParsedValue . get \( m_Tags . get \( )(\d+)( \) \) ; } )$'; $template =~ s/ +/\\s*/g; $template =~ s/(\r?\n)+/\\s+/g; my $getter = qr/$template/x; die "Usage: $0 after new-name source ..\n" unless @ARGV >= 3; my $after = shift; my $add = shift; my $index; while (<>) { unless (/$getter/) { print; next; } my($abc,$name,$lmno,$i,$xyz) = ($1,$2,$3,$4,$5); if (defined $index) { print join "" => $abc, $name, $lmno, ++$index, $xyz; } else { if ($name eq $after) { $index = $i; print; print join "" => $abc, $add, $lmno, ++$index, $xyz; } else { print; } } } For example, $ ./add-after Jane Foo code.java $ cat code.java Foo extends Bar{ public Foo(){ m_Tags.add("Jane"); m_Tags.add("Bob"); m_Tags.add("Jim"); } public String GetJane() { return m_ParsedValue.get( m_Tags.get(1) ); } public String GetFoo() { return m_ParsedValue.get( m_Tags.get(2) ); } public String GetBob() { return m_ParsedValue.get( m_Tags.get(3) ); } public String GetJim() { return m_ParsedValue.get( m_Tags.get(4) ); } } A: Comments about bad-practices apart - here is the code you asked in the language you asked for. The best thing if you are keeping the system this way, probably would be to make these java files be automatically generated in the build process itself -- you 'd just keep a names list in a .txt file in the directory. This script is suitable to do that. (It won't modify your files, it genrate new ones based on the template you posted here) import re, sys template = """Foo extends Bar{ public Foo(){ %s } %s } """ tag_templ = """ m_Tags.add("%s");""" getter_templ = """ public String GetJane() { return m_ParsedValue.get( m_Tags.get(%d) ); }""" def parse_names(filename): data = open(filename).read() names = re.findall(r'm_Tags\.add\("(.*?)"', data) return names def create_file(filename, names): tag_lines = [tag_templ % name for name in names] getter_lines = [getter_templ % (i + 1) for i in range(len(names))] code = template % ("\n".join(tag_lines), "\n".join(getter_lines)) file = open(filename,"wt") file.write(code) file.close() def insert_name(after, new_name, names): names.insert(names.index(after) + 1, new_name) if __name__ == "__main__": if len(sys.argv ) < 4: sys.stderr.write("Usage: changer.py <filename> <name-before-insertion> <new-name>") sys.exit(1) filename, name_before, new_name = sys.argv[1:] names = parse_names(filename) insert_name(name_before, new_name, names) create_file(filename, names) A: I'm doing this (well, something very similar) right now, but using Excel and VBA macros. All of the Business Values are organized and ordered in a spreadsheet. I just have to click a button to generate the appropriate code for the selected cells, then copy-paste to the IDE. Better yet, I have several "code columns" for each row. Some of them generate queries, some XSL transformations, and some procedures. For one row of business data, I can get all three types of generated code very easily. I found this (re-generate) to be MUCH easier than re-formatting the existing code I had.
Reformatting code with Regular Expressions
We have an ArrayList of items in several classes which are giving me trouble every time I'd like to insert a new item into the list. It was a mistake on my part to have designed the classes in the way I did but changing the design now would be more headache than it's worth (bureaucratic waterfall model.) I should have anticipated format changes to the documents the customer was supplying us waterfall be damned. I'd like to write a simple script in python which goes into a class, adds the item to the list, and then increments all retrievals for the following items. That doesn't sound very explanatory: Foo extends Bar{ public Foo(){ m_Tags.add("Jane"); m_Tags.add("Bob"); m_Tags.add("Jim"); } public String GetJane() { return m_ParsedValue.get( m_Tags.get(1) ); } public String GetBob() { return m_ParsedValue.get( m_Tags.get(2) ); } public String GetJim() { return m_ParsedValue.get( m_Tags.get(3) ); } } You see if I want to add a value between "Jane" and "Bob" I then have to increment the integers in the Get* functions. I just want to write a simple script in Python that does the work for me. Someone I very much respect suggested regex. Edit: Yes, LinkedHashMap. So simple, so easy and so not in the design specs now. I hate waterfall. Hate it with a passion. This whole bit was a "small" and "easy" part that "shouldn't take much time to design." I made mistakes. It's stuck in stone now.
[ "Don't do this with regexp. Create symbolic constants (using for example an enum) that map the names to numbers.\n", "You want your regular expression to be as flexible as the compiler will be with respect to whitespace between tokens. Doing so and mimicking whitespace usage makes the pattern pretty messy. The code below (sorry: Perl, not Python) edits your source files in-place.\n#! /usr/bin/perl -i.bak \nuse warnings;\nuse strict;\nmy $template =\n '^( public\n String\n Get)(\\w+)( \\( \\) { return\n m_ParsedValue . get \\( m_Tags . get \\( )(\\d+)( \\) \\) ; } )$';\n$template =~ s/ +/\\\\s*/g;\n$template =~ s/(\\r?\\n)+/\\\\s+/g;\nmy $getter = qr/$template/x;\n\ndie \"Usage: $0 after new-name source ..\\n\" unless @ARGV >= 3;\nmy $after = shift;\nmy $add = shift;\nmy $index;\nwhile (<>) {\n unless (/$getter/) {\n print;\n next;\n }\n my($abc,$name,$lmno,$i,$xyz) = ($1,$2,$3,$4,$5);\n if (defined $index) {\n print join \"\" => $abc, $name, $lmno, ++$index, $xyz;\n }\n else {\n if ($name eq $after) {\n $index = $i;\n print; print join \"\" => $abc, $add, $lmno, ++$index, $xyz;\n }\n else { print; }\n }\n}\n\nFor example,\n$ ./add-after Jane Foo code.java\n$ cat code.java\nFoo extends Bar{\n public Foo(){\n m_Tags.add(\"Jane\");\n m_Tags.add(\"Bob\");\n m_Tags.add(\"Jim\");\n }\n\n public String GetJane() { return m_ParsedValue.get( m_Tags.get(1) ); }\n public String GetFoo() { return m_ParsedValue.get( m_Tags.get(2) ); }\n public String GetBob() { return m_ParsedValue.get( m_Tags.get(3) ); }\n public String GetJim() { return m_ParsedValue.get( m_Tags.get(4) ); }\n}\n", "Comments about bad-practices apart - here is the code you asked in the language you asked for.\nThe best thing if you are keeping the system this way, probably would be to make these java files be automatically generated in the build process itself -- you 'd just keep a names list in a .txt file in the directory. This script is suitable to do that. \n(It won't modify your files, it genrate new ones based on the template you posted here)\nimport re, sys\n\ntemplate = \"\"\"Foo extends Bar{\n public Foo(){\n%s\n }\n\n%s\n}\n\"\"\"\n\ntag_templ = \"\"\" m_Tags.add(\"%s\");\"\"\"\ngetter_templ = \"\"\" public String GetJane() { return m_ParsedValue.get( m_Tags.get(%d) ); }\"\"\"\n\ndef parse_names(filename):\n data = open(filename).read()\n names = re.findall(r'm_Tags\\.add\\(\"(.*?)\"', data)\n return names\n\ndef create_file(filename, names):\n tag_lines = [tag_templ % name for name in names]\n getter_lines = [getter_templ % (i + 1) for i in range(len(names))]\n code = template % (\"\\n\".join(tag_lines), \"\\n\".join(getter_lines))\n file = open(filename,\"wt\")\n file.write(code)\n file.close()\n\ndef insert_name(after, new_name, names):\n names.insert(names.index(after) + 1, new_name)\n\nif __name__ == \"__main__\":\n if len(sys.argv ) < 4:\n sys.stderr.write(\"Usage: changer.py <filename> <name-before-insertion> <new-name>\")\n sys.exit(1)\n filename, name_before, new_name = sys.argv[1:]\n names = parse_names(filename)\n insert_name(name_before, new_name, names)\n create_file(filename, names)\n\n", "I'm doing this (well, something very similar) right now, but using Excel and VBA macros. All of the Business Values are organized and ordered in a spreadsheet. I just have to click a button to generate the appropriate code for the selected cells, then copy-paste to the IDE. Better yet, I have several \"code columns\" for each row. Some of them generate queries, some XSL transformations, and some procedures. For one row of business data, I can get all three types of generated code very easily.\nI found this (re-generate) to be MUCH easier than re-formatting the existing code I had.\n" ]
[ 4, 4, 4, 0 ]
[]
[]
[ "java", "perl", "python", "regex" ]
stackoverflow_0002140268_java_perl_python_regex.txt
Q: using the symbol font for Greek symbols in TeX via matplotlib To annotate my figures with Greek letters in the matplotlib package of Python, I use the following: import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) plt.rcParams['ps.useafm'] = True rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) plt.rcParams['pdf.fonttype'] = 42 # plot figure # ... # annotate figure plt.xlabel(r'$\mu$ = 50') plt.ylabel(r'$\sigma$ = 1.5') This makes the equal symbol and everything to the right of it in the Helvetica font, as intended, and the Greek symbols default to the usual TeX font (which I believe is Times New Roman.) How can I make it so the font used for the Greek letters is the "Symbol" font instead? It's important for me not to have it appear in the default Times font of TeX. thanks for your help. A: Funny you should ask this; I've been struggling with similar problems not too long ago. Considering how complicated font handling is in TeX, I'd sidestep TeX altogether. However, any decent Helvetica has the Greek letters built-in, so you don't need to use the Symbol font. Just put some Unicode code points into your string, like this: plt.xlabel(u'\u03bc = 50') plt.ylabel(u'\u03c3 = 1.5') For finding the code points, this Unicode codepoint lookup/search tool is really convenient. I'm not sure if and how matplotlib handles Unicode strings. If the above fails, encode in some encoding that matplotlib expects. (If you really insist on using Symbol: I don't think you can use multiple fonts within the same label, so then you'll have to add multiple labels and write some code to align them to each other. It's not pretty, but it can be done.)
using the symbol font for Greek symbols in TeX via matplotlib
To annotate my figures with Greek letters in the matplotlib package of Python, I use the following: import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) plt.rcParams['ps.useafm'] = True rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) plt.rcParams['pdf.fonttype'] = 42 # plot figure # ... # annotate figure plt.xlabel(r'$\mu$ = 50') plt.ylabel(r'$\sigma$ = 1.5') This makes the equal symbol and everything to the right of it in the Helvetica font, as intended, and the Greek symbols default to the usual TeX font (which I believe is Times New Roman.) How can I make it so the font used for the Greek letters is the "Symbol" font instead? It's important for me not to have it appear in the default Times font of TeX. thanks for your help.
[ "Funny you should ask this; I've been struggling with similar problems not too long ago. Considering how complicated font handling is in TeX, I'd sidestep TeX altogether.\nHowever, any decent Helvetica has the Greek letters built-in, so you don't need to use the Symbol font. Just put some Unicode code points into your string, like this:\nplt.xlabel(u'\\u03bc = 50')\nplt.ylabel(u'\\u03c3 = 1.5')\n\nFor finding the code points, this Unicode codepoint lookup/search tool is really convenient.\nI'm not sure if and how matplotlib handles Unicode strings. If the above fails, encode in some encoding that matplotlib expects.\n(If you really insist on using Symbol: I don't think you can use multiple fonts within the same label, so then you'll have to add multiple labels and write some code to align them to each other. It's not pretty, but it can be done.)\n" ]
[ 15 ]
[]
[]
[ "latex", "matplotlib", "python" ]
stackoverflow_0002140865_latex_matplotlib_python.txt
Q: Python bind - allow multiple keys to be pressed simultaniously I have a problem in Python. I'm using Tkinter and have four bind events, that listen to key presses on my form. My problem is, that these don't run asynchronously. So, for example I can press one button, and the events are recognized. But when I press and hold two keys at the same time, just one event gets fired. Is there an alternative way to do this? self.f.bind("w", self.player1Up) self.f.bind("s", self.player1Down) self.f.bind("o", self.player2Up) self.f.bind("l", self.player2Down) A: Unfortunately, you are somewhat at the mercy of the underlying auto-repeat mechanism of your system. For example, on the mac I'm using at the moment if I press and hold "w" I'll get a stream of press and release events. While pressed, if I press "o" I get a stream of presses and releases for "o" but no more events for "w". You will need to set up a mini state machine, and bind to both key press and key release events. This will let you track which keys are pressed and which are not. Then, each time you draw a frame you can query the machine to see which keys are pressed and act accordingly. Here's a quick hack I threw together. I've only tested it on my mac, and only with python 2.5. I've made no real attempt at being "pythonic" or efficient. The code merely serves to illustrate the technique. With this code you can simultaneously press either "w" or "s" and "o" or "l" to move two paddles up and down. '''Example that demonstrates keeping track of multiple key events''' from Tkinter import * class Playfield: def __init__(self): # this dict keeps track of keys that have been pressed but not # released self.pressed = {} self._create_ui() def start(self): self._animate() self.root.mainloop() def _create_ui(self): self.root = Tk() self.p1label = Label(text="press w, s to move player 1 up, down", anchor="w") self.p2label = Label(text="press o, l to move player 2 up, down", anchor="w") self.canvas = Canvas(width=440, height=440) self.canvas.config(scrollregion=(-20, -20, 420, 420)) self.p1label.pack(side="top", fill="x") self.p2label.pack(side="top", fill="x") self.canvas.pack(side="top", fill="both", expand="true") self.p1 = Paddle(self.canvas, tag="p1", color="red", x=0, y=0) self.p2 = Paddle(self.canvas, tag="p2", color="blue", x=400, y=0) self._set_bindings() def _animate(self): if self.pressed["w"]: self.p1.move_up() if self.pressed["s"]: self.p1.move_down() if self.pressed["o"]: self.p2.move_up() if self.pressed["l"]: self.p2.move_down() self.p1.redraw() self.p2.redraw() self.root.after(10, self._animate) def _set_bindings(self): for char in ["w","s","o", "l"]: self.root.bind("<KeyPress-%s>" % char, self._pressed) self.root.bind("<KeyRelease-%s>" % char, self._released) self.pressed[char] = False def _pressed(self, event): self.pressed[event.char] = True def _released(self, event): self.pressed[event.char] = False class Paddle(): def __init__(self, canvas, tag, color="red", x=0, y=0): self.canvas = canvas self.tag = tag self.x = x self.y = y self.color = color self.redraw() def move_up(self): self.y = max(self.y -2, 0) def move_down(self): self.y = min(self.y + 2, 400) def redraw(self): x0 = self.x - 10 x1 = self.x + 10 y0 = self.y - 20 y1 = self.y + 20 self.canvas.delete(self.tag) self.canvas.create_rectangle(x0,y0,x1,y1,tags=self.tag, fill=self.color) if __name__ == "__main__": p = Playfield() p.start()
Python bind - allow multiple keys to be pressed simultaniously
I have a problem in Python. I'm using Tkinter and have four bind events, that listen to key presses on my form. My problem is, that these don't run asynchronously. So, for example I can press one button, and the events are recognized. But when I press and hold two keys at the same time, just one event gets fired. Is there an alternative way to do this? self.f.bind("w", self.player1Up) self.f.bind("s", self.player1Down) self.f.bind("o", self.player2Up) self.f.bind("l", self.player2Down)
[ "Unfortunately, you are somewhat at the mercy of the underlying auto-repeat mechanism of your system. For example, on the mac I'm using at the moment if I press and hold \"w\" I'll get a stream of press and release events. While pressed, if I press \"o\" I get a stream of presses and releases for \"o\" but no more events for \"w\".\nYou will need to set up a mini state machine, and bind to both key press and key release events. This will let you track which keys are pressed and which are not. Then, each time you draw a frame you can query the machine to see which keys are pressed and act accordingly.\nHere's a quick hack I threw together. I've only tested it on my mac, and only with python 2.5. I've made no real attempt at being \"pythonic\" or efficient. The code merely serves to illustrate the technique. With this code you can simultaneously press either \"w\" or \"s\" and \"o\" or \"l\" to move two paddles up and down. \n'''Example that demonstrates keeping track of multiple key events'''\nfrom Tkinter import *\n\nclass Playfield:\n def __init__(self):\n # this dict keeps track of keys that have been pressed but not\n # released\n self.pressed = {}\n\n self._create_ui()\n\n def start(self):\n self._animate()\n self.root.mainloop()\n\n def _create_ui(self):\n self.root = Tk()\n self.p1label = Label(text=\"press w, s to move player 1 up, down\", \n anchor=\"w\")\n self.p2label = Label(text=\"press o, l to move player 2 up, down\", \n anchor=\"w\")\n self.canvas = Canvas(width=440, height=440)\n self.canvas.config(scrollregion=(-20, -20, 420, 420))\n\n self.p1label.pack(side=\"top\", fill=\"x\")\n self.p2label.pack(side=\"top\", fill=\"x\")\n self.canvas.pack(side=\"top\", fill=\"both\", expand=\"true\")\n\n self.p1 = Paddle(self.canvas, tag=\"p1\", color=\"red\", x=0, y=0)\n self.p2 = Paddle(self.canvas, tag=\"p2\", color=\"blue\", x=400, y=0)\n\n self._set_bindings()\n\n def _animate(self):\n if self.pressed[\"w\"]: self.p1.move_up()\n if self.pressed[\"s\"]: self.p1.move_down()\n if self.pressed[\"o\"]: self.p2.move_up()\n if self.pressed[\"l\"]: self.p2.move_down()\n self.p1.redraw()\n self.p2.redraw()\n self.root.after(10, self._animate)\n\n def _set_bindings(self):\n for char in [\"w\",\"s\",\"o\", \"l\"]:\n self.root.bind(\"<KeyPress-%s>\" % char, self._pressed)\n self.root.bind(\"<KeyRelease-%s>\" % char, self._released)\n self.pressed[char] = False\n\n def _pressed(self, event):\n self.pressed[event.char] = True\n\n def _released(self, event):\n self.pressed[event.char] = False\n\nclass Paddle():\n def __init__(self, canvas, tag, color=\"red\", x=0, y=0):\n self.canvas = canvas\n self.tag = tag\n self.x = x\n self.y = y\n self.color = color\n self.redraw()\n\n def move_up(self):\n self.y = max(self.y -2, 0)\n\n def move_down(self):\n self.y = min(self.y + 2, 400)\n\n def redraw(self):\n x0 = self.x - 10\n x1 = self.x + 10\n y0 = self.y - 20\n y1 = self.y + 20\n self.canvas.delete(self.tag)\n self.canvas.create_rectangle(x0,y0,x1,y1,tags=self.tag, fill=self.color)\n\nif __name__ == \"__main__\":\n p = Playfield()\n p.start()\n\n" ]
[ 9 ]
[ "You could bind to \"<Key>\" and then check event.char and perform the action you want based on the value of that? Granted, I have no idea if this works when multiple keys are pressed at the same time, it may still run in to the exact same problem. I haven't used Tk in ages.\n\"<Key> The user pressed any key. The key is provided in the char member of the event object passed to the callback (this is an empty string for special keys).\"\n" ]
[ -1 ]
[ "bind", "keyboard_events", "python", "tkinter" ]
stackoverflow_0002138518_bind_keyboard_events_python_tkinter.txt
Q: Which technology is preferable to build a web based GUI Client? I've well developed Python Server having workflows, views, object - ORM/OSV, etc... Server/Client communication based on socket protocol, can be done by any of service 1. XMLRPC Service 2. Socket Service now I want to develop a Fully Ajax based GUI web Client.. I've web/socket services to communicate with server. what I need is to select the technology, I've several options like, ExtJS - CherryPy GWT Ext-GWT CheeryPy Django + JQuery Django + Extjs ??? ???... A: Try using pyjamas, which is a port of GWT for Python. Instead of writing code in js, which is pretty disturbing experience, you can code in Python and compile it to js. A: You've said you have a server. So what protocol is understood by it? If it is just HTTP you don't need a web framework like Django/CherryPy. You could take any JS framework like (jQuery + jQuery Tools, MooTools, ExtJS, whatever) and write down JS scripts that will talk to your server via AJAX requests and visualize replies in form of html. If your server is something that should be talked to with custom TCP/IP protocol you have to build a proxy. You could use a framework for this like Django, but for simplicity I recommend to take plain WSGI + Werkzeug. A: I'm not sure I understood exactly on the server side, but i'm a big fan of Flex as a way to develop proper software for the browser, rather than mess of trying to make HTML do things it was never made for. Partly an idealistic reasoning, but I also am still not impressed by the 'feel' of JS-based GUIs. Flex has good server-communication options... web-services, sockets, remote objects, etc. A: If you like Django for the server-side bits of your front-end, consider dojango -- it helps integrate Django on the server side with the dojo Javascript toolkit on the browser side of things (Dojo is not quite as popular as jQuery, nevertheless it's just about as powerful, and some of us prefer it for architectural and stylistic reasons;-). A: How about Pylons + SQLAlchemy + ExtJS? We use it and it works great!
Which technology is preferable to build a web based GUI Client?
I've well developed Python Server having workflows, views, object - ORM/OSV, etc... Server/Client communication based on socket protocol, can be done by any of service 1. XMLRPC Service 2. Socket Service now I want to develop a Fully Ajax based GUI web Client.. I've web/socket services to communicate with server. what I need is to select the technology, I've several options like, ExtJS - CherryPy GWT Ext-GWT CheeryPy Django + JQuery Django + Extjs ??? ???...
[ "Try using pyjamas, which is a port of GWT for Python. Instead of writing code in js, which is pretty disturbing experience, you can code in Python and compile it to js.\n", "You've said you have a server. So what protocol is understood by it? If it is just HTTP you don't need a web framework like Django/CherryPy. You could take any JS framework like (jQuery + jQuery Tools, MooTools, ExtJS, whatever) and write down JS scripts that will talk to your server via AJAX requests and visualize replies in form of html.\nIf your server is something that should be talked to with custom TCP/IP protocol you have to build a proxy. You could use a framework for this like Django, but for simplicity I recommend to take plain WSGI + Werkzeug.\n", "I'm not sure I understood exactly on the server side, but i'm a big fan of Flex as a way to develop proper software for the browser, rather than mess of trying to make HTML do things it was never made for. Partly an idealistic reasoning, but I also am still not impressed by the 'feel' of JS-based GUIs.\nFlex has good server-communication options... web-services, sockets, remote objects, etc.\n", "If you like Django for the server-side bits of your front-end, consider dojango -- it helps integrate Django on the server side with the dojo Javascript toolkit on the browser side of things (Dojo is not quite as popular as jQuery, nevertheless it's just about as powerful, and some of us prefer it for architectural and stylistic reasons;-).\n", "How about Pylons + SQLAlchemy + ExtJS? We use it and it works great!\n" ]
[ 5, 1, 1, 1, 0 ]
[]
[]
[ "django", "extjs", "gwt", "python", "webclient" ]
stackoverflow_0002138868_django_extjs_gwt_python_webclient.txt
Q: How are debug consoles implemented in Python? I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool. Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated! A: You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory. A: Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local context by passing in the result of the locals() function to the InteractiveConsole constructor. I couldn't find a way to close the InteractiveConsole without killing the application, so I've extended it to just close the console when it catches the SystemExit exception. I don't like it, but I haven't yet found a better way. Here's some (fairly trivial) sample code that demonstrates the debug console. import code class EmbeddedConsole(code.InteractiveConsole): def start(self): try: self.interact("Debug console starting...") except: print("Debug console closing...") def print_names(): print(adam) print(bob) adam = "I am Adam" bob = "I am Bob" print_names() console = EmbeddedConsole(locals()) console.start() print_names() A: http://docs.python.org/3.0/library/functions.html#input http://docs.python.org/3.0/library/functions.html#eval def start_interpreter(): while(True): code = input("Python Console >") eval(code) I'm sure, however, that their implementation is much more foolsafe than this. A: Python has a debugger framework in the bdb module. I'm not sure if the IDE's you list use it but it's certainly possible to implement a full Python debugger with it. A: If you want to experiment with your own Python console then this is a nice start: cmd = None while cmd != 'exit': cmd = raw_input('>>> ') try: exec(cmd) except: print 'exception' But for real work use the InteractiveConsole instead.
How are debug consoles implemented in Python?
I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool. Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!
[ "You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory.\n", "Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local context by passing in the result of the locals() function to the InteractiveConsole constructor. I couldn't find a way to close the InteractiveConsole without killing the application, so I've extended it to just close the console when it catches the SystemExit exception. I don't like it, but I haven't yet found a better way.\nHere's some (fairly trivial) sample code that demonstrates the debug console.\nimport code\n\nclass EmbeddedConsole(code.InteractiveConsole):\n def start(self):\n try:\n self.interact(\"Debug console starting...\")\n except:\n print(\"Debug console closing...\")\n\ndef print_names():\n print(adam)\n print(bob)\n\nadam = \"I am Adam\"\nbob = \"I am Bob\"\n\nprint_names()\nconsole = EmbeddedConsole(locals())\nconsole.start()\nprint_names()\n\n", "http://docs.python.org/3.0/library/functions.html#input\nhttp://docs.python.org/3.0/library/functions.html#eval\ndef start_interpreter():\n while(True):\n code = input(\"Python Console >\")\n eval(code)\n\nI'm sure, however, that their implementation is much more foolsafe than this.\n", "Python has a debugger framework in the bdb module. I'm not sure if the IDE's you list use it but it's certainly possible to implement a full Python debugger with it.\n", "If you want to experiment with your own Python console then this is a nice start:\ncmd = None\nwhile cmd != 'exit':\n cmd = raw_input('>>> ')\n try:\n exec(cmd)\n except:\n print 'exception'\n\nBut for real work use the InteractiveConsole instead.\n" ]
[ 6, 3, 2, 1, 0 ]
[]
[]
[ "debugging", "interactive", "python" ]
stackoverflow_0000444509_debugging_interactive_python.txt
Q: Addressing part of a string via the array syntax in Python Is it, in Python, possible to address a specific character in a string by the standard array syntax? Example, PHP: $foo = 'bar'; echo $foo[1]; // Output: a It didn't work like in PHP so I wanted to know if it is possible using some other way? A: As Adam pointed out, reading from a string array is possible in Python using the indexing syntax. What isn't possible though is writing to a string using this syntax: >>> s = 'bar' >>> s[2] = 'z' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment Maybe this was the problem you ran into? A: Yes, this works. In fact, it works exactly like it does in PHP. The only difference is that variable names in Python are not preceeded by the $ character. foo = 'bar' print foo[1] # Output: a Is Python, strings are one of a number of sequence types. You can find all of the operations that you can perform on sequence types in the Python documentation.
Addressing part of a string via the array syntax in Python
Is it, in Python, possible to address a specific character in a string by the standard array syntax? Example, PHP: $foo = 'bar'; echo $foo[1]; // Output: a It didn't work like in PHP so I wanted to know if it is possible using some other way?
[ "As Adam pointed out, reading from a string array is possible in Python using the indexing syntax. What isn't possible though is writing to a string using this syntax:\n>>> s = 'bar'\n>>> s[2] = 'z'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'str' object does not support item assignment\n\nMaybe this was the problem you ran into?\n", "Yes, this works. In fact, it works exactly like it does in PHP. The only difference is that variable names in Python are not preceeded by the $ character.\nfoo = 'bar'\nprint foo[1] # Output: a\n\nIs Python, strings are one of a number of sequence types. You can find all of the operations that you can perform on sequence types in the Python documentation.\n" ]
[ 5, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002141334_python_string.txt
Q: Retrieving text from password field [python][pyqt4] def welcomeStage (self): self.test = QtGui.QLineEdit (self) self.test.move (50, 150) QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.passwordStage) def passwordStage (self): self.email = self.test.text() self.test.clear() self.test.setEchoMode (QtGui.QLineEdit.Password) QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.loginStage) def loginStage (self): self.pwd = self.test.text() print self.pwd if len (self.pwd) < 0: welcomeStage () return Simply put, I am making a login form. The user enters their email, then the text field is cleared and echo mode is set to Password mode. The text() function returns the email fine, but when I call text() after I have changed the echo mode, it returns 0. I've been pouring over the documentation looking for anything regarding the text() function and how it operates when Password mode is on, however I have not found anything. Does anybody know how this is done? A: I can't offer a fix for using a QLineEdit, but you can get passwords in a QInputDialog by specifying mode in the getText() method. Like this: diag = QtGui.QInputDialog s = None while s is None: qstring, ok = diag.getText(self, QtCore.QString(title), QtCore.QString(text), mode=QtGui.QLineEdit.Password) s = str(qstring) if ok is False: # user pressed Cancel return None if s == '': # user entered nothing s = None return s
Retrieving text from password field [python][pyqt4]
def welcomeStage (self): self.test = QtGui.QLineEdit (self) self.test.move (50, 150) QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.passwordStage) def passwordStage (self): self.email = self.test.text() self.test.clear() self.test.setEchoMode (QtGui.QLineEdit.Password) QtCore.QObject.connect (self.test, QtCore.SIGNAL ('returnPressed()'), self.loginStage) def loginStage (self): self.pwd = self.test.text() print self.pwd if len (self.pwd) < 0: welcomeStage () return Simply put, I am making a login form. The user enters their email, then the text field is cleared and echo mode is set to Password mode. The text() function returns the email fine, but when I call text() after I have changed the echo mode, it returns 0. I've been pouring over the documentation looking for anything regarding the text() function and how it operates when Password mode is on, however I have not found anything. Does anybody know how this is done?
[ "I can't offer a fix for using a QLineEdit, but you can get passwords in a QInputDialog by specifying mode in the getText() method. Like this:\ndiag = QtGui.QInputDialog\ns = None\nwhile s is None:\n qstring, ok = diag.getText(self, QtCore.QString(title), QtCore.QString(text), mode=QtGui.QLineEdit.Password)\n s = str(qstring)\n if ok is False: # user pressed Cancel\n return None\n if s == '': # user entered nothing\n s = None\nreturn s\n\n" ]
[ 0 ]
[]
[]
[ "passwords", "pyqt4", "python", "user_interface" ]
stackoverflow_0002141808_passwords_pyqt4_python_user_interface.txt
Q: problems Wrapping Patricia Tries using Swig, python I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes. So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it breaks. typedef struct _patricia_node_t { u_int bit; /* flag if this node used */ prefix_t *prefix; /* who we are in patricia tree */ struct _patricia_node_t *l, *r; /* left and right children */ struct _patricia_node_t *parent;/* may be used */ void *data; /* pointer to data */ void *user1; /* pointer to usr data (ex. route flap info) */ } patricia_node_t; Specifically: >>> N = patricia.patricia_node_t() >>> assert N.data == None >>> N.data = 1 TypeError: in method 'patricia_node_t_data_set', argument 2 of type 'void *' Now my C is weak. From what I read in the SWIG book, I think this means I need to pass it a pointer to data. According to the book : Also, if you need to pass the raw pointer value to some external python library, you can do it by casting the pointer object to an integer... However, the inverse operation is not possible, i.e., you can't build a Swig pointer object from a raw integer value. Questions: am I understanding this correctly? how do I get around this? Is %extends? typemap? Specifics would be very helpful. Notes: I can't change the C source, but I can extend it in additional .h files or the interface .i file. From what I understand, that "data" field should be able to contain "anything" for some reasonable value of "anything" that I don't really know. A: I haven't used SWIG in a while, but I am pretty sure that you want to use a typemap that will take a PyObject* and cast it to the required void* and vice versa. Be sure to keep track of reference counts, of course. A: It looks like you should pass SWIG a pointer to an integer. For example, if this was all in C, your error would be like this: void set(struct _patricia_node_t *tree, void *data) { tree->data = data; } ... int value = 1; set(tree, &value); // OK! HOORAY! set(tree, value); // NOT OK! FIRE SCORPIONS! And it seems to me you're doing the Python equivalent of set(tree, value). Now I'm not an expert with SWIG but perhaps you could pass a tuple instead of an integer? Does N.data = (1,) work? This was the answer suggested by an Allegro CL + SWIG example, but I dunno how well it applies to Python. A: An alternative is use PyRadix, which uses the same underlying code.
problems Wrapping Patricia Tries using Swig, python
I'm trying to wrap the Patricia Tries (Perl's NET::Patricia) to be exposed in python. I am having difficulty with one of the classes. So instances the patricia node (below) as viewed from python have a "data" property. Reading it goes fine, but writing to it breaks. typedef struct _patricia_node_t { u_int bit; /* flag if this node used */ prefix_t *prefix; /* who we are in patricia tree */ struct _patricia_node_t *l, *r; /* left and right children */ struct _patricia_node_t *parent;/* may be used */ void *data; /* pointer to data */ void *user1; /* pointer to usr data (ex. route flap info) */ } patricia_node_t; Specifically: >>> N = patricia.patricia_node_t() >>> assert N.data == None >>> N.data = 1 TypeError: in method 'patricia_node_t_data_set', argument 2 of type 'void *' Now my C is weak. From what I read in the SWIG book, I think this means I need to pass it a pointer to data. According to the book : Also, if you need to pass the raw pointer value to some external python library, you can do it by casting the pointer object to an integer... However, the inverse operation is not possible, i.e., you can't build a Swig pointer object from a raw integer value. Questions: am I understanding this correctly? how do I get around this? Is %extends? typemap? Specifics would be very helpful. Notes: I can't change the C source, but I can extend it in additional .h files or the interface .i file. From what I understand, that "data" field should be able to contain "anything" for some reasonable value of "anything" that I don't really know.
[ "I haven't used SWIG in a while, but I am pretty sure that you want to use a typemap that will take a PyObject* and cast it to the required void* and vice versa. Be sure to keep track of reference counts, of course.\n", "It looks like you should pass SWIG a pointer to an integer. For example, if this was all in C, your error would be like this:\nvoid set(struct _patricia_node_t *tree, void *data) {\n tree->data = data;\n}\n\n...\n\nint value = 1;\nset(tree, &value); // OK! HOORAY!\nset(tree, value); // NOT OK! FIRE SCORPIONS!\n\nAnd it seems to me you're doing the Python equivalent of set(tree, value). Now I'm not an expert with SWIG but perhaps you could pass a tuple instead of an integer? Does N.data = (1,) work? This was the answer suggested by an Allegro CL + SWIG example, but I dunno how well it applies to Python.\n", "An alternative is use PyRadix, which uses the same underlying code. \n" ]
[ 1, 0, 0 ]
[]
[]
[ "c", "pointers", "python", "swig" ]
stackoverflow_0000674494_c_pointers_python_swig.txt
Q: Python and Rpy2: Calling plot function with options that have "." in them I'm just starting to learn how to use rpy2 with python. I'm able to make simple plots and such, but I've run into the problem that many options in R use ".". For example, here's an R call that works: barplot(t, col=heat.colors(2), names.arg=c("pwn", "pwn2")) where t is a matrix. I want to use the same call in python, but it rejects the "." part of names.arg. My understanding was that in python you replace the "." with "_", so names_arg for example, but that is not working either. I know this is a basic problem so I hope someone has seen this and knows the fix. Thanks! A: You can use a dictionary here for the named arguments (using **) as described in the docs, and call R directly for the functions. Also remember that RPy2 expects its own vector objects. Yes, it's a bit awkward, but on the plus side, you should be able to do anything in rpy2 you could do in R. from rpy2 import robjects color = robjects.r("heat.colors")() names = robjects.StrVector(("pwn", "pwn2")) robjects.r.barplot(t, col=color, **{"names.arg":names}) (Note that this is for rpy2 version 2.0.x; there are some changes in the unreleased 2.1 which I haven't had a chance to look at yet.) A: I don't know whether Rpy will accept this, but you can have keyword parameters with periods in them. You have to pass them through a dictionary though. Like this: >>> def f(**kwds): print kwds ... >>> f(a=5, b_c=6) {'a': 5, 'b_c': 6} >>> f(a=5, b.c=6) Traceback ( File "<interactive input>", line 1 SyntaxError: keyword cant be an expression (<interactive input>, line 1) >>> f(**{'a': 5, 'b.c': 6}) {'a': 5, 'b.c': 6} A: With rpy2-2.1.0, one way to write it would be: from rpy2.robjects.packages import importr graphics = importr("graphics") grdevices = importr("grDevices") graphics.barplot_default(t, col = grdevices.heat_colors(2), names_arg = StrVector(("pwn", "pwn2"))) Having to use barplot_default (rather that barplot) is due to the extensive use of the ellipsis '...' in R'sfunction signatures and to the fact that save parameter name translation would require analysis of the R code a function contains. More, and an example of a function to perform systematic translation of '.' to '_' is at: http://rpy.sourceforge.net/rpy2/doc-2.1/html/robjects.html#functions
Python and Rpy2: Calling plot function with options that have "." in them
I'm just starting to learn how to use rpy2 with python. I'm able to make simple plots and such, but I've run into the problem that many options in R use ".". For example, here's an R call that works: barplot(t, col=heat.colors(2), names.arg=c("pwn", "pwn2")) where t is a matrix. I want to use the same call in python, but it rejects the "." part of names.arg. My understanding was that in python you replace the "." with "_", so names_arg for example, but that is not working either. I know this is a basic problem so I hope someone has seen this and knows the fix. Thanks!
[ "You can use a dictionary here for the named arguments (using **) as described in the docs, and call R directly for the functions. Also remember that RPy2 expects its own vector objects. Yes, it's a bit awkward, but on the plus side, you should be able to do anything in rpy2 you could do in R.\nfrom rpy2 import robjects\ncolor = robjects.r(\"heat.colors\")()\nnames = robjects.StrVector((\"pwn\", \"pwn2\"))\nrobjects.r.barplot(t, col=color, **{\"names.arg\":names})\n\n(Note that this is for rpy2 version 2.0.x; there are some changes in the unreleased 2.1 which I haven't had a chance to look at yet.)\n", "I don't know whether Rpy will accept this, but you can have keyword parameters with periods in them. You have to pass them through a dictionary though. Like this:\n>>> def f(**kwds): print kwds\n... \n>>> f(a=5, b_c=6)\n{'a': 5, 'b_c': 6}\n>>> f(a=5, b.c=6)\nTraceback ( File \"<interactive input>\", line 1\nSyntaxError: keyword cant be an expression (<interactive input>, line 1)\n>>> f(**{'a': 5, 'b.c': 6})\n{'a': 5, 'b.c': 6}\n\n", "With rpy2-2.1.0, one way to write it would be:\nfrom rpy2.robjects.packages import importr\ngraphics = importr(\"graphics\")\ngrdevices = importr(\"grDevices\")\n\ngraphics.barplot_default(t, \n col = grdevices.heat_colors(2),\n names_arg = StrVector((\"pwn\", \"pwn2\")))\n\nHaving to use barplot_default (rather that barplot) is due to the\nextensive use of the ellipsis '...' in R'sfunction signatures and\nto the fact that save parameter name translation would require \nanalysis of the R code a function contains.\nMore, and an example of a function to perform systematic translation\nof '.' to '_' is at:\nhttp://rpy.sourceforge.net/rpy2/doc-2.1/html/robjects.html#functions\n" ]
[ 9, 1, 0 ]
[]
[]
[ "python", "rpy2" ]
stackoverflow_0002125218_python_rpy2.txt
Q: Stored Procedures in Python for PostgreSQL we are still pretty new to Postgres and came from Microsoft Sql Server. We are wanting to write some stored procedures now. Well, after struggling to get something more complicated than a hello world to work in pl/pgsql, we decided it's better if we are going to learn a new language we might as well learn Python because we got the same query working in it in about 15 minutes(note, none of us actually know python). So I have some questions about it in comparison to pl/psql. Is pl/Pythonu slower than pl/pgsql? Is there any kind of "good" reference for how to write good stored procedures using it? Five short pages in the Postgres documentation doesn't really tell us enough. What about query preparation? Should it always be used? If we use the SD and GD arrays for a lot of query plans, will it ever get too full or have a negative impact on the server? Will it automatically delete old values if it gets too full? Is there any hope of it becoming a trusted language? Also, our stored procedure usage is extremely light. Right now we only have 4, but we are still trying to convert little bits of code over from Sql Server specific syntax(such as variables, which can't be used in Postgres outside of stored procedures) A: Depends on what operations you're doing. Well, combine that with a general Python documentation, and that's about what you have. No. Again, depends on what you're doing. If you're only going to run a query once, no point in preparing it separately. If you are using persistent connections, it might. But they get cleared out whenever a connection is closed. Not likely. Sandboxing is broken in Python and AFAIK nobody is really interested in fixing it. I heard someone say that python-on-parrot may be the most viable way, once we have pl/parrot (which we don't yet). Bottom line though - if your stored procedures are going to do database work, use pl/pgsql. Only use pl/python if you are going to do non-database stuff, such as talking to external libraries.
Stored Procedures in Python for PostgreSQL
we are still pretty new to Postgres and came from Microsoft Sql Server. We are wanting to write some stored procedures now. Well, after struggling to get something more complicated than a hello world to work in pl/pgsql, we decided it's better if we are going to learn a new language we might as well learn Python because we got the same query working in it in about 15 minutes(note, none of us actually know python). So I have some questions about it in comparison to pl/psql. Is pl/Pythonu slower than pl/pgsql? Is there any kind of "good" reference for how to write good stored procedures using it? Five short pages in the Postgres documentation doesn't really tell us enough. What about query preparation? Should it always be used? If we use the SD and GD arrays for a lot of query plans, will it ever get too full or have a negative impact on the server? Will it automatically delete old values if it gets too full? Is there any hope of it becoming a trusted language? Also, our stored procedure usage is extremely light. Right now we only have 4, but we are still trying to convert little bits of code over from Sql Server specific syntax(such as variables, which can't be used in Postgres outside of stored procedures)
[ "\nDepends on what operations you're doing.\nWell, combine that with a general Python documentation, and that's about what you have.\nNo. Again, depends on what you're doing. If you're only going to run a query once, no point in preparing it separately.\nIf you are using persistent connections, it might. But they get cleared out whenever a connection is closed.\nNot likely. Sandboxing is broken in Python and AFAIK nobody is really interested in fixing it. I heard someone say that python-on-parrot may be the most viable way, once we have pl/parrot (which we don't yet).\n\nBottom line though - if your stored procedures are going to do database work, use pl/pgsql. Only use pl/python if you are going to do non-database stuff, such as talking to external libraries.\n" ]
[ 9 ]
[]
[]
[ "plpgsql", "postgresql", "python", "stored_procedures" ]
stackoverflow_0002141589_plpgsql_postgresql_python_stored_procedures.txt
Q: Build Python scripts and call methods from C# Is there any way to make this scenario work? There is a Python script. It is built into a DLL by running this script with IronPython: import clr clr.CompileModules("CompiledScript.dll", "script.py") The goal is to call this DLL's methods from C# code. .NET Reflector shows there is one class in the DLL - DLRCashedCode and the methods we are interested in are private static methods of this class. For example, there is a function in the script: def scriptMethod(self, text): ... Its representation in the DLL is: private static object scriptMethod(Closure closure1, PythonFunction $function, object self, object text) { ... } Closure and PythonFunction are IronPython classes (from Microsoft.Scripting.dll and IronPython.dll). So far so good. Is it possible this method to be called by C# code? The idea of using reflection like Type t = typeof(DLRCachedCode); string methodName = "scriptMethod"; MethodInfo method = t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); object[] parameters = new object[] { "param1", "param2" }; // the "params problem" method.Invoke(null, parameters); seems harder because of setting the method's parameters. If they are (any how) initialized correctly, could we expect the method to work smoothly? Is there a better way to call this methods from C#? For various different reasons we prefer to have the script built as a .NET assembly and not to call the script itself. A: Sort of. You cannot access the Python methods directly from C# code. Unless you are playing with C# 4.0 and the dynamic keyword or you are very, very special ;). However, you can compile an IronPython class to a DLL and then use IronPython hosting in C# to access the methods (this is for IronPython 2.6 and .NET 2.0). Create a C# program like this: using System; using System.IO; using System.Reflection; using IronPython.Hosting; using Microsoft.Scripting.Hosting; // we get access to Action and Func on .Net 2.0 through Microsoft.Scripting.Utils using Microsoft.Scripting.Utils; namespace TestCallIronPython { class Program { public static void Main(string[] args) { Console.WriteLine("Hello World!"); ScriptEngine pyEngine = Python.CreateEngine(); Assembly myclass = Assembly.LoadFile(Path.GetFullPath("MyClass.dll")); pyEngine.Runtime.LoadAssembly(myclass); ScriptScope pyScope = pyEngine.Runtime.ImportModule("MyClass"); // Get the Python Class object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass")); // Invoke a method of the class pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]); // create a callable function to 'somemethod' Action SomeMethod2 = pyEngine.Operations.GetMember<Action>(MyClass, "somemethod"); SomeMethod2(); // create a callable function to 'isodd' Func<int, bool> IsOdd = pyEngine.Operations.GetMember<Func<int, bool>>(MyClass, "isodd"); Console.WriteLine(IsOdd(1).ToString()); Console.WriteLine(IsOdd(2).ToString()); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } } Make a trivial Python class like this: class MyClass: def __init__(self): print "I'm in a compiled class (I hope)" def somemethod(self): print "in some method" def isodd(self, n): return 1 == n % 2 Compile it (I use SharpDevelop) but the clr.CompileModules method should also work. Then shove the compiled MyClass.dll into the directory where the compiled C# program lives and run it. You should get this as the result: Hello World! I'm in a compiled class (I hope) in some method in some method True False Press any key to continue . . . This incorporates Jeff's more direct solution that eliminates having to create and compile a small Python 'stub' and also shows how you can create C# function calls that access the methods in the Python class. A: The clr.CompileModules is purely a load-time optimization - it doesn't make the scripts directly available to a static languge like C#. You'll need to host the IronPython runtime, and then you can load the DLL into the runtime and use IronPython's hosting interfaces to access it.
Build Python scripts and call methods from C#
Is there any way to make this scenario work? There is a Python script. It is built into a DLL by running this script with IronPython: import clr clr.CompileModules("CompiledScript.dll", "script.py") The goal is to call this DLL's methods from C# code. .NET Reflector shows there is one class in the DLL - DLRCashedCode and the methods we are interested in are private static methods of this class. For example, there is a function in the script: def scriptMethod(self, text): ... Its representation in the DLL is: private static object scriptMethod(Closure closure1, PythonFunction $function, object self, object text) { ... } Closure and PythonFunction are IronPython classes (from Microsoft.Scripting.dll and IronPython.dll). So far so good. Is it possible this method to be called by C# code? The idea of using reflection like Type t = typeof(DLRCachedCode); string methodName = "scriptMethod"; MethodInfo method = t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); object[] parameters = new object[] { "param1", "param2" }; // the "params problem" method.Invoke(null, parameters); seems harder because of setting the method's parameters. If they are (any how) initialized correctly, could we expect the method to work smoothly? Is there a better way to call this methods from C#? For various different reasons we prefer to have the script built as a .NET assembly and not to call the script itself.
[ "Sort of. You cannot access the Python methods directly from C# code. Unless you are playing with C# 4.0 and the dynamic keyword or you are very, very special ;). However, you can compile an IronPython class to a DLL and then use IronPython hosting in C# to access the methods (this is for IronPython 2.6 and .NET 2.0).\nCreate a C# program like this:\nusing System;\nusing System.IO;\nusing System.Reflection;\nusing IronPython.Hosting;\nusing Microsoft.Scripting.Hosting;\n// we get access to Action and Func on .Net 2.0 through Microsoft.Scripting.Utils\nusing Microsoft.Scripting.Utils;\n\n\nnamespace TestCallIronPython\n{\n class Program\n {\n public static void Main(string[] args)\n {\n Console.WriteLine(\"Hello World!\");\n ScriptEngine pyEngine = Python.CreateEngine();\n\n Assembly myclass = Assembly.LoadFile(Path.GetFullPath(\"MyClass.dll\"));\n pyEngine.Runtime.LoadAssembly(myclass);\n ScriptScope pyScope = pyEngine.Runtime.ImportModule(\"MyClass\");\n\n // Get the Python Class\n object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable(\"MyClass\"));\n\n // Invoke a method of the class\n pyEngine.Operations.InvokeMember(MyClass, \"somemethod\", new object[0]);\n\n // create a callable function to 'somemethod'\n Action SomeMethod2 = pyEngine.Operations.GetMember<Action>(MyClass, \"somemethod\");\n SomeMethod2();\n\n // create a callable function to 'isodd'\n Func<int, bool> IsOdd = pyEngine.Operations.GetMember<Func<int, bool>>(MyClass, \"isodd\");\n Console.WriteLine(IsOdd(1).ToString());\n Console.WriteLine(IsOdd(2).ToString());\n\n Console.Write(\"Press any key to continue . . . \");\n Console.ReadKey(true);\n }\n }\n}\n\nMake a trivial Python class like this:\nclass MyClass:\n def __init__(self):\n print \"I'm in a compiled class (I hope)\"\n\n def somemethod(self):\n print \"in some method\"\n\n def isodd(self, n):\n return 1 == n % 2\n\nCompile it (I use SharpDevelop) but the clr.CompileModules method should also work. Then shove the compiled MyClass.dll into the directory where the compiled C# program lives and run it. You should get this as the result:\nHello World!\nI'm in a compiled class (I hope)\nin some method\nin some method\nTrue\nFalse\nPress any key to continue . . .\n\nThis incorporates Jeff's more direct solution that eliminates having to create and compile a small Python 'stub' and also shows how you can create C# function calls that access the methods in the Python class.\n", "The clr.CompileModules is purely a load-time optimization - it doesn't make the scripts directly available to a static languge like C#. You'll need to host the IronPython runtime, and then you can load the DLL into the runtime and use IronPython's hosting interfaces to access it.\n" ]
[ 8, 6 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0002139202_c#_ironpython_python.txt