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: Python code that doesn't work from the command line A module that I have written (test.py) in Python 2.6 can be imported and run perfectly well from with the Python IDLE with the commands: import test test.run_test_suite() However if I use the command "python test.py" at the command line, it crashes apparently (according to traceback) on the command "import os". As you can see from the code below, when run from the command line it should perform the same as when run inside the IDLE. Why would not running this in the IDLE cause a problem? My google-foo only can up with results when code would run at the command line but not in IDLE. if __name__ == "__main__": table = run_test_suite() print '---=== Results ===---' print_table(table) It should be pointed out that this module is doing nothing more than large amounts of basic maths to check some externally calculated data is feasible. the full traceback is: Traceback (most recent call last): File "...\Python\test.py", line 170, in <module> print '---=== Results ===---' File "...\Python\test.py", line 160, in build_data if Links == False: File "...\Python\test.py", line 103, in load_table if Abbrev[M.solution_type()] == 'pos': File "...\Python\test.py", line 85, in build_example import os File "SnapPy.pyx", line 173, in snappy.SnapPy.uFatalError (SnapPy.c:5507) snappy.SnapPy.SnapPeaFatalError: SnapPea crashed in function cusp_modulus(), defined in cusp_modulus.c. A: Are you using the same python version in both cases? When starting from the commandline, you get the first Python in your path, while IDLE is most probably executed directly from a shortcut. If you have more than one version of python installed on your machine, this could translate in two complete different environments. A: Look for a file named os.py in your current working directory. If you have one, rename it. Or check the Python documentation for "absolute import".
Python code that doesn't work from the command line
A module that I have written (test.py) in Python 2.6 can be imported and run perfectly well from with the Python IDLE with the commands: import test test.run_test_suite() However if I use the command "python test.py" at the command line, it crashes apparently (according to traceback) on the command "import os". As you can see from the code below, when run from the command line it should perform the same as when run inside the IDLE. Why would not running this in the IDLE cause a problem? My google-foo only can up with results when code would run at the command line but not in IDLE. if __name__ == "__main__": table = run_test_suite() print '---=== Results ===---' print_table(table) It should be pointed out that this module is doing nothing more than large amounts of basic maths to check some externally calculated data is feasible. the full traceback is: Traceback (most recent call last): File "...\Python\test.py", line 170, in <module> print '---=== Results ===---' File "...\Python\test.py", line 160, in build_data if Links == False: File "...\Python\test.py", line 103, in load_table if Abbrev[M.solution_type()] == 'pos': File "...\Python\test.py", line 85, in build_example import os File "SnapPy.pyx", line 173, in snappy.SnapPy.uFatalError (SnapPy.c:5507) snappy.SnapPy.SnapPeaFatalError: SnapPea crashed in function cusp_modulus(), defined in cusp_modulus.c.
[ "Are you using the same python version in both cases? When starting from the commandline, you get the first Python in your path, while IDLE is most probably executed directly from a shortcut.\nIf you have more than one version of python installed on your machine, this could translate in two complete different envir...
[ 0, 0 ]
[]
[]
[ "command_line", "debugging", "python", "python_idle" ]
stackoverflow_0003790268_command_line_debugging_python_python_idle.txt
Q: Would it be a good idea to make python store compile code in file stream instead of pyc files? I'm wondering if it wouldn't be a better if Python would store the compiled code in a file stream of the original source file. This would work on file systems supporting forks/data-streams, and fall-back if this is not possible. On Windows using ADS (Alternative Data Streams) On OS X using resource forks On Linux using extended file attributes if compiled file is under 32k Doing this will solve the problem of polluting the source tree or having problems like after the removal of a .py the .pyc remained and was loaded and used. What do you think about this, sounds like a good idea or not? What issues to do see. A: One problem I forsee is that it then means that each platform has different behaviour. The next is that not every filesystem OS X supports also supports resource forks (and the way it stores them in non-hfs filesystems is universally hated by everyone else: ._ ) Having said that, I have often been bitten by a .pyc file being used by apache because the apache process can't read the .py file I have replaced. But I think that this is not the solution: a better deployment process is ;) A: You sure do sacrifice an awful lot of portability this way -- right now .pyc files are uncommonly portable (often used by heterogeneous systems on a LAN through some kind of network file system arrangement, for example, though I've never been a fan of the performance characteristics of that approach), while your approach would only work on very specific filesystems and (I suspect) never across a network mount on heterogenous machines. So, it would be a dire mistake to make the behavior you want the default one -- but it would surely be neat to have it as an option available for specific request if your deployment environment doesn't care about all of the above issues and does care about some of those you mention. Another "cool option to have", that I would actually use about 100 times more often, is to put the .pyc "files" in a database instead of having them in filesystems. The cool thing is that this is (relatively) easily accomplished as an add-on "import hack" one way or another (depending on Python versons) -- most easily in recent-enough versions with importlib, Brett Cannon's masterpiece (but that might make backporting to older Python versions harder than other ways... too much depends on exactly what versions you need to support, a detail which I don't see in your Q, so I won't go into the implementation details, but the general idea doesn't change much across implementations).
Would it be a good idea to make python store compile code in file stream instead of pyc files?
I'm wondering if it wouldn't be a better if Python would store the compiled code in a file stream of the original source file. This would work on file systems supporting forks/data-streams, and fall-back if this is not possible. On Windows using ADS (Alternative Data Streams) On OS X using resource forks On Linux using extended file attributes if compiled file is under 32k Doing this will solve the problem of polluting the source tree or having problems like after the removal of a .py the .pyc remained and was loaded and used. What do you think about this, sounds like a good idea or not? What issues to do see.
[ "One problem I forsee is that it then means that each platform has different behaviour.\nThe next is that not every filesystem OS X supports also supports resource forks (and the way it stores them in non-hfs filesystems is universally hated by everyone else: ._ )\nHaving said that, I have often been bitten by a .p...
[ 1, 1 ]
[]
[]
[ "ads", "fork", "python" ]
stackoverflow_0003793745_ads_fork_python.txt
Q: Django get_object_or_create() not working on deployment server I'm having major trouble with a get_or_create call. I have it working locally absolutely fine, and the same script is working online on another site. Has anyone got an idea what's going on? I get "IntegrityError: (1062, "Duplicate entry '2147483647' for key 'PRIMARY'")" whenever I run the script... for tweet in TwitterSearchFeed.entries: if tweet.id[0:3] == 'tag': tweet_id = tweet.id.split(':')[2] # tweet.id[tweet.id.rindex(':')+1:] #tag:search.twitter.com,2005:10016544708 screen_name = tweet.author.split('(')[0].strip() text = smart_unicode(tweet.title) pub_time = time.strptime(tweet.published, "%Y-%m-%dT%H:%M:%SZ") #2010-01-01T22:20:55Z pub_time = datetime.datetime.fromtimestamp(time.mktime(pub_time)) # UTC name = tweet.author.split('(')[1].split(')')[0].strip() # make sure tweet comes after 30 mins before kickoff if pub_time > (game.kickoff - datetime.timedelta(minutes=30)): # filter RTs if not text[0:3] == "RT ": # add or get tweet tweet_dict = { 'twitter_id': tweet_id, 'pub_time': pub_time, 'text': text, 'name': name, 'username': screen_name, 'game': game, 'atthegame': atthegame } obj, created = Tweet.objects.get_or_create(twitter_id=tweet_id, defaults=tweet_dict) if created: output += "Tweet added - %s, %s, '%s'<br />" % (tweet_id, screen_name, text) else: output += "Tweet %s already exists<br />" % tweet_id else: output += "Tweet id error<br />" return HttpResponse(output) A: My guess is that you suffer from this: How do I deal with this race condition in django?
Django get_object_or_create() not working on deployment server
I'm having major trouble with a get_or_create call. I have it working locally absolutely fine, and the same script is working online on another site. Has anyone got an idea what's going on? I get "IntegrityError: (1062, "Duplicate entry '2147483647' for key 'PRIMARY'")" whenever I run the script... for tweet in TwitterSearchFeed.entries: if tweet.id[0:3] == 'tag': tweet_id = tweet.id.split(':')[2] # tweet.id[tweet.id.rindex(':')+1:] #tag:search.twitter.com,2005:10016544708 screen_name = tweet.author.split('(')[0].strip() text = smart_unicode(tweet.title) pub_time = time.strptime(tweet.published, "%Y-%m-%dT%H:%M:%SZ") #2010-01-01T22:20:55Z pub_time = datetime.datetime.fromtimestamp(time.mktime(pub_time)) # UTC name = tweet.author.split('(')[1].split(')')[0].strip() # make sure tweet comes after 30 mins before kickoff if pub_time > (game.kickoff - datetime.timedelta(minutes=30)): # filter RTs if not text[0:3] == "RT ": # add or get tweet tweet_dict = { 'twitter_id': tweet_id, 'pub_time': pub_time, 'text': text, 'name': name, 'username': screen_name, 'game': game, 'atthegame': atthegame } obj, created = Tweet.objects.get_or_create(twitter_id=tweet_id, defaults=tweet_dict) if created: output += "Tweet added - %s, %s, '%s'<br />" % (tweet_id, screen_name, text) else: output += "Tweet %s already exists<br />" % tweet_id else: output += "Tweet id error<br />" return HttpResponse(output)
[ "My guess is that you suffer from this: How do I deal with this race condition in django?\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003794428_django_python.txt
Q: does python 2.5 have an equivalent to Tcl's uplevel command? Does python have an equivalent to Tcl's uplevel command? For those who don't know, the "uplevel" command lets you run code in the context of the caller. Here's how it might look in python: def foo(): answer = 0 print "answer is", answer # should print 0 bar() print "answer is", answer # should print 42 def bar(): uplevel("answer = 42") It's more than just setting variables, however, so I'm not looking for a solution that merely alters a dictionary. I want to be able to execute any code. A: In general, what you ask is not possible (with the results you no doubt expect). E.g., imagine the "any code" is x = 23. Will this add a new variable x to your caller's set of local variables, assuming you do find a black-magical way to execute this code "in the caller"? No it won't -- the crucial optimization performed by the Python compiler is to define once and for all, when def executes, the exact set of local variables (all the barenames that get assigned, or otherwise bound, in the function's body), and turn every access and setting to those barenames into very fast indexing into the stackframe. (You could systematically defeat that crucial optimization e.g. by having an exec '' at the start of every possible caller -- and see your system's performance crash through the floor in consequence). Except for assigning to the caller's local barenames, exec thecode in thelocals, theglobals may do roughly what you want, and the inspect module lets you get the locals and globals of the caller in a semi-reasonable way (in as far as deep black magic -- which would make me go postal on any coworker suggesting it be perpetrated in production code -- can ever be honored with the undeserved praise of calling it "semi-reasonable", that is;-). But you do specify "I want to be able to execute any code." and the only solution to that unambiguous specification (and thanks for being so precise, as it makes answering easier!) is: then, use a different programming language. A: Is the third party library written in Python? If yes, you could rewrite and rebind the function "foo" at runtime with your own implementation. Like so: import third_party original_foo = third_party.foo def my_foo(*args, **kwds): # do your magic... original_foo(*args, **kwds) third_party.foo = my_foo I guess monkey-patching is slighly better than rewriting frame locals. ;)
does python 2.5 have an equivalent to Tcl's uplevel command?
Does python have an equivalent to Tcl's uplevel command? For those who don't know, the "uplevel" command lets you run code in the context of the caller. Here's how it might look in python: def foo(): answer = 0 print "answer is", answer # should print 0 bar() print "answer is", answer # should print 42 def bar(): uplevel("answer = 42") It's more than just setting variables, however, so I'm not looking for a solution that merely alters a dictionary. I want to be able to execute any code.
[ "In general, what you ask is not possible (with the results you no doubt expect). E.g., imagine the \"any code\" is x = 23. Will this add a new variable x to your caller's set of local variables, assuming you do find a black-magical way to execute this code \"in the caller\"? No it won't -- the crucial optimizat...
[ 3, 1 ]
[]
[]
[ "python", "tcl", "uplevel" ]
stackoverflow_0003794461_python_tcl_uplevel.txt
Q: why i can't reverse a list of list in python i wanted to do something like this but this code return list of None (i think it's because list.reverse() is reversing the list in place): map(lambda row: row.reverse(), figure) i tried this one, but the reversed return an iterator : map(reversed, figure) finally i did something like this , which work for me , but i don't know if it's the right solution: def reverse(row): """func that reverse a list not in place""" row.reverse() return row map(reverse, figure) if someone has a better solution that i'm not aware of please let me know kind regards, A: The mutator methods of Python's mutable containers (such as the .reverse method of lists) almost invariably return None -- a few return one useful value, e.g. the .pop method returns the popped element, but the key concept to retain is that none of those mutators returns the mutated container: rather, the container mutates in-place and the return value of the mutator method is not that container. (This is an application of the CQS principle of design -- not quite as fanatical as, say, in Eiffel, the language devised by Bertrand Meyer, who also invented CQS, but that's just because in Python "practicality beats purity, cfr import this;-). Building a list is often costlier than just building an iterator, for the overwhelmingly common case where all you want to do is loop on the result; therefore, built-ins such as reversed (and all the wonderful building blocks in the itertools module) return iterators, not lists. But what if you therefore have an iterator x but really truly need the equivalent list y? Piece of cake -- just do y = list(x). To make a new instance of type list, you call type list -- this is such a general Python idea that it's even more crucial to retain than the pretty-important stuff I pointed out in the first two paragraphs!-) So, the code for your specific problem is really very easy to put together based on the crucial notions in the previous paragraphs: [list(reversed(row)) for row in figure] Note that I'm using a list comprehension, not map: as a rule of thumb, map should only be used as a last-ditch optimization when there is no need for a lambda to build it (if a lambda is involved then a listcomp, as well as being clearer as usual, also tends to be faster anyway!-). Once you're a "past master of Python", if your profiling tells you that this code is a bottleneck, you can then know to try alternatives such as [row[::-1] for row in figure] applying a negative-step slicing (aka "Martian Smiley") to make reversed copies of the rows, knowing it's usually faster than the list(reversed(row)) approach. But -- unless your code is meant to be maintained only by yourself or somebody at least as skilled at Python -- it's a defensible position to use the simplest "code from first principles" approach except where profiling tells you to push down on the pedal. (Personally I think the "Martian Smiley" is important enough to avoid applying this good general philosophy to this specific use case, but, hey, reasonable people could differ on this very specific point!-). A: You can also use a slice to get the reversal of a single list (not in place): >>> a = [1,2,3,4] >>> a[::-1] [4, 3, 2, 1] So something like: all_reversed = [lst[::-1] for lst in figure] ...or... all_reversed = map(lambda x: x[::-1], figure) ...will do what you want. A: reversed_lists = [list(reversed(x)) for x in figure] A: map(lambda row: list(reversed(row)), figure) A: You can also simply do for row in figure: row.reverse() to change each row in place.
why i can't reverse a list of list in python
i wanted to do something like this but this code return list of None (i think it's because list.reverse() is reversing the list in place): map(lambda row: row.reverse(), figure) i tried this one, but the reversed return an iterator : map(reversed, figure) finally i did something like this , which work for me , but i don't know if it's the right solution: def reverse(row): """func that reverse a list not in place""" row.reverse() return row map(reverse, figure) if someone has a better solution that i'm not aware of please let me know kind regards,
[ "The mutator methods of Python's mutable containers (such as the .reverse method of lists) almost invariably return None -- a few return one useful value, e.g. the .pop method returns the popped element, but the key concept to retain is that none of those mutators returns the mutated container: rather, the containe...
[ 27, 8, 3, 1, 0 ]
[]
[]
[ "list", "map_function", "python", "reverse" ]
stackoverflow_0003794486_list_map_function_python_reverse.txt
Q: Does thread-local mean thread safe? Specifically I'm talking about Python. I'm trying to hack something (just a little) by seeing an object's value without ever passing it in, and I'm wondering if it is thread safe to use thread local to do that. Also, how do you even go about doing such a thing? A: No -- thread local means that each thread gets its own copy of that variable. Using it is (at least normally) thread-safe, simply because each thread uses its own variable, separate from variables by the same name that's accessible to other threads. OTOH, they're not (normally) useful for communication between threads.
Does thread-local mean thread safe?
Specifically I'm talking about Python. I'm trying to hack something (just a little) by seeing an object's value without ever passing it in, and I'm wondering if it is thread safe to use thread local to do that. Also, how do you even go about doing such a thing?
[ "No -- thread local means that each thread gets its own copy of that variable. Using it is (at least normally) thread-safe, simply because each thread uses its own variable, separate from variables by the same name that's accessible to other threads. OTOH, they're not (normally) useful for communication between th...
[ 8 ]
[]
[]
[ "multithreading", "python", "thread_local", "thread_safety" ]
stackoverflow_0003794868_multithreading_python_thread_local_thread_safety.txt
Q: Python - how can I override the functionality of a class before it's imported by a different module? I have a class that's being imported in module_x for instantiation, but first I want to override one of the class's methods to include a specific feature dynamically (inside some middleware that runs before module_x is loaded. A: You should know that each class type (like C in class C: ...) is an object, so you can simply overwrite the class methods. As long as instances don't overwrite their own methods (won't happen too often because that's not really useful for single inntances), each instance uses the methods as inherited from its class type. This way, you can even replace a method after an instance has been created. For example: class C: def m(self): print "original" c1 = C() c1.m() # prints "original" def replacement(self): print "replaced!" C.m = replacement c1.m() # prints "replaced!" C().m() # prints "replaced!" A: Neither AndiDog's nor Andrew's answer answer your question completely. But they have given the most important tools to be able to solve your problem (+1 to both). I will be using one of their suggestions in my answer: You will need 3 files: File 1: myClass.py class C: def func(self): #do something File 2: importer.py from myClass import * def changeFunc(): A = C() A.func = lambda : "I like pi" return A if __name__ == "importer": A = changeFunc() File 3: module_x.py from importer import * print A.func() The output of module_x would print "I like pi" Hope this helps A: Since every python class is actually a dictionary (not only objects!) You can easily override class methods by associate them with new function. class A: def f(self): return 5 a = A() a.f() #5 A.f = lambda self: 10 a.f() #10 You should use it with care. In most cases decorators & proper OO-design will work for you and if you forced to override class method, maybe, you make something wrong.
Python - how can I override the functionality of a class before it's imported by a different module?
I have a class that's being imported in module_x for instantiation, but first I want to override one of the class's methods to include a specific feature dynamically (inside some middleware that runs before module_x is loaded.
[ "You should know that each class type (like C in class C: ...) is an object, so you can simply overwrite the class methods. As long as instances don't overwrite their own methods (won't happen too often because that's not really useful for single inntances), each instance uses the methods as inherited from its clas...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003794905_python.txt
Q: Transform game pseudo code into python Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again. Pseudocode - Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries I need some serious help! I don't understand any of this stuff at all! This is all I have def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() and I don't even know if it's right! A: Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem. I would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like high and low. The way to understand variables is to consider them slots that values can be stored. At any given time, a variable has some value, like the number 5, or a reference to an open file. That value can be summoned at any time by using its name, or it can be given a new value by assigning to it, and the old value will be forgotten with the new value taking its place. The pseudocode references three variables, high, low and tries. It also tells you what their initial values should be. After the second line has executed, those values are set to 1000, 1 and 1, respectively, but they take on new values as the program progresses. Another feature of the pseudocode is a conditional loop, and a case analysis of the user input. Your translation of the pseudocode's loop is incorrect. In your case, you have created a new variable, i and have instructed your program to run the loop body with every value of i between 1 and 1000. Obviously this doesn't have a whole lot to do with the pseudocode. Instead what you want to do is loop forever, until some condition (which changes in the loop body) becomes false. In python, the while statement does this. If you're familiar with an if statement, while looks the same, but after the body is done, the condition is re-evaluated and the body is executed again if it is still true. Finally, the case analysis in the body of the loop requires comparing something to expected values. Although some other languages have a number of ways of expressing this, in python we only have if-elif-else clauses. Outside of transforming pseudocode to working code, it is probably useful to understand what the program is actually doing. The key here is on line 4, where the program guesses the average of two values. after that the program acts on how well the guess worked out. In the first run through the loop, with high containing 1000 and low containing 1, the average is 500 (actually the average is 500.5, but since we're averaging whole numbers, python guesses that we want the result of the division to also be an integer). Obviously that guess has only a 0.1% chance of being right, but if it's wrong, the user is expected to tell us if it was too high, or too low. Either way, that answer completely eliminates 50% of the possible guesses. If, for instance, the user was thinking of a low number, then when the program guessed 500, the user would tell the program that 500 was too high, and then the program wouldn't ever have to guess that the number was in the range of 501 thru 1000. That can save the computer a lot of work. To put that information to use, the program keeps track of the range of possible values the goal number could be. When the number guessed is too high, the program adjusts its upper bound downward, just below the guess, and if the guess was too low, the program adjusts its lower bound upward to just above the guess. When the program guesses again, the guess is right in the middle of the possible range, cutting the range in half again. The number of possible guesses went from the original 1000 to 500 in one guess, to 250 in two guesses. If the program has terrible luck, and can't get it two (which is actually pretty likely), then by the third, it has only 125 numbers left to worry about. After the fourth guess, only 62 numbers remain in range. This continues, and after eight guesses, only 3 numbers remain, and the program tries the middle number for its ninth guess. If that turns out to be wrong, only one number is left, and the program guesses it! This technique of splitting a range in half and then continuing to the closer half is called bisection and appears in a wide range topics of interest to computer science. How about some CODE! Since i don't want to deprive you of the learning experience, I'll just give you some snippets that might help you along. python is a language designed for interactive exploration, so fire up your interpreter and give this a shot. I'll be posting examples with the prompts shown, don't actually type that. Here's an example using the while clause: >>> x = 1000 >>> while x > 1: ... x = x/2 ... print x ... 500 250 125 62 31 15 7 3 1 >>> x 1 Getting console input from the user should be done through the raw_input() function. It just returns whatever the user types. This is a little harder to show. To simplify things, after every line of python that requires input, I'll type "Hello World!" (without the quotes) >>> raw_input() Hello World! 'Hello World!' >>> y = raw_input() Hello World! >>> print y Hello World! >>> How about some combining of concepts! >>> myvar = '' >>> while myvar != 'exit': ... myvar = raw_input() ... if myvar == 'apples': ... print "I like apples" ... elif myvar == 'bananas': ... print "I don't like bananas" ... else: ... print "I've never eaten", myvar ... apples I like apples mangoes I've never eaten mangoes bananas I don't like bananas exit I've never eaten exit >>> Oops. little bit of a bug there. See if you can fix it! A: I don't understand any of this stuff at all! That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins: Print instructions to the user So you don't understand ANY of the stuff, you say, so that means you don't understand this part either. Well: "the user" is the person who's running your program. "Instructions" are English sentences that tell him or her what to do to play the game, as per the following quote from this excellently clear and detailed assignment: The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. "print" is a Python instruction that emits information; for example, try a program containing only print "some information" to see how it works. OK, can you please edit your answer to show us that you've gotten this point, so we can move to the next one? Feel free to comment here with further questions if any words or concepts I'm using are still too advanced for you, and I'll try to clarify! A: You're obviously very new to programming, and I guess that is one of the reasons for a delayed response from the community. It's tough to decide where to start and how to guide you through this whole exercise. So, before you get a good answer here that includes making you understand what's happening there, and guiding you through building the solution yourself (ideally!) I would suggest you visit this page to try to get a grasp of the actual problem itself. http://www.openbookproject.net/pybiblio/gasp/course/4-highlow.html In the meantime, look at all the answers in this thread and keep editing your post so that we know you're getting it. A: Doesn't match the psudocode exactly but it works. lol ;) I know this is a wicked old post but this is the same assignment I got also. Here is what I ended up with: high = 1000 low = 1 print "Pick a number between 1 and 1000." print "I will guess your number in 10 tries or less." print "Or at least i'll try to. ;)" print "My first guess is 500." guess = 500 tries = 0 answer = 1 print "Enter 1 if it's higher." print "Enter -1 if it's lower." print "Enter 0 if I guessed it!" print "" while (answer != 0): answer = int(raw_input("Am I close?")) if answer == 1: tries = tries + 1 low = guess guess = (high + low) / 2 print "My next guess is:" print guess elif answer == -1: tries = tries + 1 high = guess guess = (high + low) / 2 print "My next guess is:" print guess elif answer == 0: tries = tries + 1 print "Your number is:" print guess print "Yay! I got it! Number of guesses:" print tries A: Okay, the nice part about using Python is that it's almost pseudocode anyway. Now, let's think about the individual steps: How do you get the average between high and low? How do you ask the user if the answerr is correct What do "if" statements look like in Python, and how would you write the pseudocode out as if statements? Here's another hint -- you can run python as an interpreter and try individual statements along, so, for example, you could do high=23 low=7 then compute what you think should be the average or midpoint between them (hint: 15) A: Welcome to Stack Overflow! The trick here is to realize that your Python program should look almost like the pseudocode. First let's try to understand exactly what the pseudocode is doing. If we had to interact with the program described by the pseudocode, it would look something like this: Think of a number between 1 and 1000 and press Enter. >>> Is it 500? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. >>> 1 Is it 750? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. >>> -1 Is it 625? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher. etc. When we first think of our number, the program knows only that it is between 1 and 1000. It represents this knowledge by setting the variable 'low' to 1 and the variable 'high' to 1000. Its first guess is the average of these numbers, which is 500. After we tell the program that our number is greater than 500, it updates the value of 'low' to 501. In other words the program then knows that our number is between 501 and 1000. It then guesses the average of 501 and 1000, which is 750. We tell it that our number is lower, so the program updates the value of 'high' to 749 and guesses the average of 501 and 749 next, and so on until it guesses right, or it has narrowed the possible range down to a single number (meaning its next guess will be right). So back to writing the program in Python: We basically just translate the pseudocode line for line. For example our program loop should look just like it does in the pseucode: while high > low: # Guess (high + low) / 2 and ask user to respond # Handle user response There is no need for a for-loop as you have in your code. To take input we can do something like this: guess = (high + low) / 2 response = input('Is it ' + str(guess) + '? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.') Now the user input is stored in the variable 'response', and we can handle the possibilities with if statements like 'if response == -1:' for example. Just remember to print the instructions and set 'high' and 'low' to their initial values before entering the while loop and you should be all set. Good luck! A: Here's a few hints to get you started: Average = Value + Value + Value [...] / Number of Values; (for instance, ((2 + 5 + 3) / (3)) Many programming languages use different operator precedence. When I am programming, I always use parentheses when I am unsure about operator precedence. In my example above, if you only did 2 + 5 + 3 / 3, the program would do division operations before addition - so it would evaulate to 2 + 5 + (3 / 3), or 2 + 5 + 1 == 7. Skip this for python users /* Secondly: your earliest programs can benefit from const correctness (here is a good explanation of what it is and why it is EXTREMELY good practice). Please read through that and understand why you should use constants (or whatever the python equivalent is). Also look up "magic numbers," which is a big area where constants are used. */ Google "Please Excuse My Dear Aunt Sally" (NOTE: this only deals with mathematical operators, and mostly holds true for programming languages; for a more comprehensive study of operator precedence, look up your chosen language's documentation for precedence - also note that most programs don't have built in power operators, but most standard libraries have pow functions). Speaking of standard library: Get acquainted with standard library functions (I have never used Python, I don't know how it implements a SL, but I would be extremely surprised if a language that popular didn't have a well developed SL). If you don't know what that is, and your book/tutorial doesn't have it, get a new one. Any resource that doesn't reference a standard library is not worth the time. Lastly: while this post may look like I know what I'm talking about, I really am still in the early phases of learning, just like you. A few things you might want to get used to early on (when I skipped these parts, it slowed my learning a lot): The use of references and pointers (Q for comments: does Python have pointers?), the difference between the data IN a memory location and the actual memory location (often times, the location of the value in memory will be more useful than the value itself, at least when writing data structures). Especially get used to the standard library; look for copy, find, etc. type functions useful in string manipulation. Actually, rereading your original post, I did not realize this was a homework type assignment. If you aren't doing this for fun, you will probably never take my advice. Just remember that programming can be extremely fun, if you don't make it a chore - and don't get frustrated when your code doesn't compile (or...interpret), or you get unexpected results, etc.
Transform game pseudo code into python
Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete program is given below; your task is to turn it into a working python program. The program should start by printing instructions to the screen, explaining that the user should pick a number between 1 and 1000 and the computer will guess it in no more than 10 tries. It then starts making guesses, and after each guess it asks the user for feedback. The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right, and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again. Pseudocode - Print instructions to the user -Start with high = 1000, low = 1, and tries = 1 - While high is greater than low - Guess the average of high and low - Ask the user to respond to the guess - Handle the four possible outcomes: - If the guess was right, print a message that tries guesses were required and quit the program - If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries - If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries - If the user entered an incorrect value, print out the instructions again - high and low must be equal, so print out the answer and the value of tries I need some serious help! I don't understand any of this stuff at all! This is all I have def main(x, nums, low, high): input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ") for i in range (1, 1001): main() and I don't even know if it's right!
[ "Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem. \nI would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like high and low. The way to understand vari...
[ 14, 11, 4, 2, 1, 1, 0 ]
[]
[]
[ "pseudocode", "python" ]
stackoverflow_0000992076_pseudocode_python.txt
Q: Display dynamically added methods and attributes in python help I have a class where I add new methods and properties dynamically. The new properties are handled by overriding __getattr__ and __setattr__ while the new methods are added directly (obj.mymethod = foo). Is there a way to make these show up if I do "help(inst)" where inst is an instance of my class? Right now I only see the methods and attributes I have "hardcoded" in the source. The methods do show up if I do "dir(inst)". A: The issue is that help(inst) provides the information about class from which that instance "inst" is derived from. say obj is derived from class A, then instead of doing obj.mymethod = foo, if you did A.mymethod = foo, then this will show up in help(obj) Look at the example below and it's output. class A(object): def __init__(self): pass def method1(self): "This is method1 of class A" pass a = A() help(a) def method2(self): """ Method 2 still not associated""" pass A.method2 = method2 # if you did a.method2 = method2 # Then it won't show up in the help() statement below help(a) As per the documentation, if the argument is any other kind of object, a help page on the object is generated. But from the example above, I see that adding the method in the namespace of class is shown up in help() function but if you added the method to just one instance of that class, then it does not show up in the help().
Display dynamically added methods and attributes in python help
I have a class where I add new methods and properties dynamically. The new properties are handled by overriding __getattr__ and __setattr__ while the new methods are added directly (obj.mymethod = foo). Is there a way to make these show up if I do "help(inst)" where inst is an instance of my class? Right now I only see the methods and attributes I have "hardcoded" in the source. The methods do show up if I do "dir(inst)".
[ "The issue is that help(inst) provides the information about class from which that instance \"inst\" is derived from.\nsay obj is derived from class A, then instead of doing obj.mymethod = foo, if you did A.mymethod = foo, then this will show up in help(obj)\nLook at the example below and it's output.\nclass A(obje...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003795139_python.txt
Q: how to manage lock-write mechanism in django i've been searching for a while for a way to handle the lock-write mechanism in( whenever user is updating , the record should be locked for the others ) . and i've been told that the web-frame work is responsible for this. check this out : https://serverfault.com/questions/184666/how-to-configure-apache-server my question is : how do i do that with django , in other words . what title should i be searching under this is an Emergence task . please help thanks in advance A: Locks on the Database are provided by your DBMS like MySql or MSSQL Server. Not your framework or webserver. http://en.wikipedia.org/wiki/Lock_(database)
how to manage lock-write mechanism in django
i've been searching for a while for a way to handle the lock-write mechanism in( whenever user is updating , the record should be locked for the others ) . and i've been told that the web-frame work is responsible for this. check this out : https://serverfault.com/questions/184666/how-to-configure-apache-server my question is : how do i do that with django , in other words . what title should i be searching under this is an Emergence task . please help thanks in advance
[ "Locks on the Database are provided by your DBMS like MySql or MSSQL Server. Not your framework or webserver.\nhttp://en.wikipedia.org/wiki/Lock_(database)\n" ]
[ 1 ]
[]
[]
[ "django", "locking", "python" ]
stackoverflow_0003795348_django_locking_python.txt
Q: stomp.py based durable client fills up subscribers list in ActiveMQ I have a problem with a durable client on ActiveMQ. I am using stomp.py in Python. conn.start() conn.connect(wait=True, header = {'client-id': 'myhostname' }) conn.subscribe( '/topic/testTopic', ack='auto', headers = { 'activemq.subscriptionName': 'myhostname', 'selector': "clientid <> '%s'" % 'myhostname' } ) As you can see from my code, I am setting my clientId to be my own hostname. As shown in the attached screenshot (below), the clientId is shown to be something like "ID:Atlas....". The problem is that every time I disconnect my stomp.py-based client, I get a new "clientId" the next time I connect again. That causes the list of subscribers in ActiveMQ to fill up: (The image above shows a subscriber on my ActiveMQ broker. Next time I disconnect and then connect, the entry above will still remain, and another one will be added. Pretty soon I have many subscribers in the list). The strange thing is that the selector works 100% (I verify that by changing <> to be =, so that the messages come back to me), so the clientId must be working somehow. A: I solved it, the whole thing was due to a simple spelling mistake. The line: conn.connect(wait=True, header = {'client-id': 'myhostname' }) Should contain 'headers' in plural form.
stomp.py based durable client fills up subscribers list in ActiveMQ
I have a problem with a durable client on ActiveMQ. I am using stomp.py in Python. conn.start() conn.connect(wait=True, header = {'client-id': 'myhostname' }) conn.subscribe( '/topic/testTopic', ack='auto', headers = { 'activemq.subscriptionName': 'myhostname', 'selector': "clientid <> '%s'" % 'myhostname' } ) As you can see from my code, I am setting my clientId to be my own hostname. As shown in the attached screenshot (below), the clientId is shown to be something like "ID:Atlas....". The problem is that every time I disconnect my stomp.py-based client, I get a new "clientId" the next time I connect again. That causes the list of subscribers in ActiveMQ to fill up: (The image above shows a subscriber on my ActiveMQ broker. Next time I disconnect and then connect, the entry above will still remain, and another one will be added. Pretty soon I have many subscribers in the list). The strange thing is that the selector works 100% (I verify that by changing <> to be =, so that the messages come back to me), so the clientId must be working somehow.
[ "I solved it, the whole thing was due to a simple spelling mistake. The line:\nconn.connect(wait=True, header = {'client-id': 'myhostname' })\n\nShould contain 'headers' in plural form.\n" ]
[ 3 ]
[]
[]
[ "activemq", "python", "stomp" ]
stackoverflow_0003774152_activemq_python_stomp.txt
Q: Finding a Value within a Range in a List of Tuple Values in Python I'm trying to get the Body Mass Index (BMI) classification for a BMI value that falls within a standard BMI range - for instance, if someone's BMI were 26.2, they'd be in the "Overweight" range. I made a list of tuples of the values (see below), although of course I'm open to any other data structure. This would be easy to do with SQL's BETWEEN but I'd like to do it in pure Python, mostly because it means one fewer DB connections but also as an exercise in doing more in "pure" Python. bmi_ranges = [] bmi_ranges.append((u'Underweight', u'Severe Thinness', 0, 15.99)) bmi_ranges.append((u'Underweight', u'Moderate Thinness', 16.00, 16.99)) bmi_ranges.append((u'Underweight', u'Mild Thinness', 17.00, 18.49)) bmi_ranges.append((u'Normal Range', u'Normal Range', 18.50, 24.99)) bmi_ranges.append((u'Overweight', u'Overweight', 25.00, 29.99)) bmi_ranges.append((u'Obese', u'Obese Class I', 30.00, 34.99)) bmi_ranges.append((u'Obese', u'Obese Class II', 35.00, 39.99)) bmi_ranges.append((u'Obese', u'Obese Class III', 40.00, 1000.00)) If a range is exactly in the list of tuples it's easy enough to just iterate through with a listcomp, but how do I find that a value is within the range of any of the other values? A: # bmi = <whatever> found_bmi_range = [bmi_range for bmi_range in bmi_ranges if bmi_ranges[2] <= bmi <= bmi_ranges[3] ][0] You can add if clauses to list comprehensions that filter what items are included in the result. Note: you may want to adjust your range specifications to use a non-inclusive upper bound (i.e. [a,b) + [b,c) + [c,d) et cetera), and then change the conditional to a <= b < c, that way you don't have issues with edge cases. A: You can do this with a list comprehension: >>> result = [r for r in bmi_ranges if r[2] <= 32 <= r[3]] >>> print result [(u'Obese', u'Obese Class I', 30.0, 34.99)] However it would probably be faster to request the database to do this for you as otherwise you are requesting more data than you need. I don't understand how using a BETWEEN requires using one more data connection. If you could expand on that it would be useful. Are you talking about the pros and cons of caching data versus always asking for live data? You may also want to create a class for your data so that you don't have to refer to fields as x[2], but instead can use more meaningful names. You could also look at namedtuples. A: I'm not sure if I understand why you can't do this just by iterating over the list (I know there are more efficient datastructures, but this is very short and iteration would be more understandable). What's wrong with def check_bmi(bmi, bmi_range): for cls, name, a, b in bmi_range: if a <= bmi <= b: return cls # or name or whatever you need. A: bmi = 26.2 bmi_ranges = [] bmi_ranges.append((u'Underweight', u'Severe Thinness', 0, 15.99)) bmi_ranges.append((u'Underweight', u'Moderate Thinness', 16.00, 16.99)) bmi_ranges.append((u'Underweight', u'Mild Thinness', 17.00, 18.49)) bmi_ranges.append((u'Normal Range', u'Normal Range', 18.50, 24.99)) bmi_ranges.append((u'Overweight', u'Overweight', 25.00, 29.99)) bmi_ranges.append((u'Obese', u'Obese Class I', 30.00, 34.99)) bmi_ranges.append((u'Obese', u'Obese Class II', 35.00, 39.99)) bmi_ranges.append((u'Obese', u'Obese Class III', 40.00, 1000.00)) print filter(lambda x: x[2] <= bmi <= x[3], bmi_ranges) A: This is how I would deal with it: import random bmi_ranges = [(u'Underweight', u'Severe Thinness', 16.0), (u'Underweight', u'Moderate Thinness', 17.0), (u'Underweight', u'Mild Thinness', 18.5), (u'Normal Range', u'Normal Range', 25.0), (u'Overweight', u'Overweight', 30.0), (u'Obese', u'Obese Class I', 35.0), (u'Obese', u'Obese Class II', 40.0), (u'Obese', u'Obese Class III', 1000.0)] def bmi_lookup(bmi_value): return next((classification, description, lessthan) for classification, description, lessthan in bmi_ranges if bmi_value < lessthan) for bmi in range(20): random_bmi = random.random()*50 print random_bmi, bmi_lookup(random_bmi)
Finding a Value within a Range in a List of Tuple Values in Python
I'm trying to get the Body Mass Index (BMI) classification for a BMI value that falls within a standard BMI range - for instance, if someone's BMI were 26.2, they'd be in the "Overweight" range. I made a list of tuples of the values (see below), although of course I'm open to any other data structure. This would be easy to do with SQL's BETWEEN but I'd like to do it in pure Python, mostly because it means one fewer DB connections but also as an exercise in doing more in "pure" Python. bmi_ranges = [] bmi_ranges.append((u'Underweight', u'Severe Thinness', 0, 15.99)) bmi_ranges.append((u'Underweight', u'Moderate Thinness', 16.00, 16.99)) bmi_ranges.append((u'Underweight', u'Mild Thinness', 17.00, 18.49)) bmi_ranges.append((u'Normal Range', u'Normal Range', 18.50, 24.99)) bmi_ranges.append((u'Overweight', u'Overweight', 25.00, 29.99)) bmi_ranges.append((u'Obese', u'Obese Class I', 30.00, 34.99)) bmi_ranges.append((u'Obese', u'Obese Class II', 35.00, 39.99)) bmi_ranges.append((u'Obese', u'Obese Class III', 40.00, 1000.00)) If a range is exactly in the list of tuples it's easy enough to just iterate through with a listcomp, but how do I find that a value is within the range of any of the other values?
[ "# bmi = <whatever>\nfound_bmi_range = [bmi_range for bmi_range\n in bmi_ranges\n if bmi_ranges[2] <= bmi <= bmi_ranges[3]\n ][0]\n\nYou can add if clauses to list comprehensions that filter what items are included in the result.\nNote: you may want to adjust you...
[ 2, 0, 0, 0, 0 ]
[ "If you like a lighter original data structure and one import from standard library:\nimport bisect\n\nbmi_ranges = []\nbmi_ranges.append((u'Underweight', u'Severe Thinness', 0, 15.99))\nbmi_ranges.append((u'Underweight', u'Moderate Thinness', 16.00, 16.99))\nbmi_ranges.append((u'Underweight', u'Mild Thinness', 17....
[ -1, -1 ]
[ "python", "search", "sequence", "tuples" ]
stackoverflow_0003795032_python_search_sequence_tuples.txt
Q: How to force execution of a different thread I have one main thread that does some rather CPU intensive operation. The thread has to hold a lock for all its calculations. Then there are some other threads which occasionally require the same lock for brief amounts of time. How can I force the main the main thread to occasionally allow the other threads to execute without slowing it down if there are no other threads? A periodic lock.release() time.sleep(x) lock.acquire() for some x would pass control to another thread, but slow the main thread down if there are no other threads. On the other hand, without the sleep() call the GIL seems to interfere here. Since the main thread has the GIL when it executes release(), the other thread is apparently not able to return from acquire() immediately. Therefore, the main thread continues with its own acquire() method and the other threads never get the lock unless a GIL switch happens to coincide exactly with me releasing my own lock. What's the proper solution for this problem? Is there a way to force a GIL release? Basically I want some magic piece of code that makes sure that in the following test script the second thread always gets the lock first: import threading import time class t1 (threading.Thread): def run(self): print "Second thread waiting for lock" lock.acquire() print "Second thread got lock" lock.release() lock = threading.Lock() lock.acquire() t = t1() t.start() time.sleep(1) lock.release() time.sleep(0) # this works very often, but not all the time lock.acquire() print "Main thread got lock" lock.release() A: Merely releasing the GIL doesn't guarantee that other threads will have a chance to run. In Unix, the call you really want is sched_yield(). There's no interface to that function in the Python standard library; it would be straightforward to add one with a native module. usleep(0) and select() are sometimes used for the same purpose, though it's not always the same depending on the system scheduler. Windows, you want Sleep(0). Use time.sleep(0) for both of those. A: Calling select.select() with a timeout of 0 will release the GIL for a brief moment.
How to force execution of a different thread
I have one main thread that does some rather CPU intensive operation. The thread has to hold a lock for all its calculations. Then there are some other threads which occasionally require the same lock for brief amounts of time. How can I force the main the main thread to occasionally allow the other threads to execute without slowing it down if there are no other threads? A periodic lock.release() time.sleep(x) lock.acquire() for some x would pass control to another thread, but slow the main thread down if there are no other threads. On the other hand, without the sleep() call the GIL seems to interfere here. Since the main thread has the GIL when it executes release(), the other thread is apparently not able to return from acquire() immediately. Therefore, the main thread continues with its own acquire() method and the other threads never get the lock unless a GIL switch happens to coincide exactly with me releasing my own lock. What's the proper solution for this problem? Is there a way to force a GIL release? Basically I want some magic piece of code that makes sure that in the following test script the second thread always gets the lock first: import threading import time class t1 (threading.Thread): def run(self): print "Second thread waiting for lock" lock.acquire() print "Second thread got lock" lock.release() lock = threading.Lock() lock.acquire() t = t1() t.start() time.sleep(1) lock.release() time.sleep(0) # this works very often, but not all the time lock.acquire() print "Main thread got lock" lock.release()
[ "Merely releasing the GIL doesn't guarantee that other threads will have a chance to run.\nIn Unix, the call you really want is sched_yield(). There's no interface to that function in the Python standard library; it would be straightforward to add one with a native module.\nusleep(0) and select() are sometimes use...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003795119_python.txt
Q: What are python generators? Possible Duplicate: What can you use Python generator functions for? I tried to read about python generators but did not understand much about the concept as to what we can do with generators, I am new to python please let me know Thank you A: Simply put, a generator in Python is a function that can maintain state between values produced. Read this. A: The presentation here explains generators very well: http://www.dabeaz.com/generators/index.html I have yet to find a use for the more advanced pipelining stuff, but I use the general technique all the time to parse logfiles. A: While Yassin's answer is completely correct, I would rather explain it differently: A generator is a function that returns multiple values over time, where each value is generated (and returned) when you ask for it. A: http://docs.python.org/tutorial/classes.html#generators Read this first. Basically, generators are iterable objects. The magic word here is yield. Instead of using the return statement, you use yield, which doesn't stop the execution of a function, but returns something. In order for you to be able to consume what the generator returns, you have to iterate through it.
What are python generators?
Possible Duplicate: What can you use Python generator functions for? I tried to read about python generators but did not understand much about the concept as to what we can do with generators, I am new to python please let me know Thank you
[ "Simply put, a generator in Python is a function that can maintain state between values produced. Read this.\n", "The presentation here explains generators very well:\nhttp://www.dabeaz.com/generators/index.html\nI have yet to find a use for the more advanced pipelining stuff, but I use the general technique all ...
[ 1, 1, 1, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0003795656_generator_python.txt
Q: Python tool for incorporating imported items Is there a tool in python to rewrite some code which imports things such that it no longer has to import anything? Take a library that draws a box called box.py def box(text='Hello, World!') draw the box magic return Now in another program (we'll call it warning.py) it says: from box import box box('Warning, water found in hard drive') Is there a tool that I can use that will see it importing the box function (or a class for that matter) from box and insert that function (or class, or even variable definitions) into the warning.py script removing the import line (thus making it more portable)? With thanks, Narnie A: It sounds like you're wanting to effectively copy-paste everything into one file to be able to distribute a single file instead of several? In that case, look into using a zipped module instead of copy-pasting everything into one file... This is far more maintainable in the long run. Python will execute a zip file if there's a __main__.py file inside of it. E.g.: echo "def foo(): print 'code inside a.py'" > a.py echo "def bar(): print 'code inside b.py'" > b.py echo "import a; import b; a.foo(); b.bar()" > __main__.py zip test.zip a.py b.py __main__.py rm a.py b.py __main__.py python test.zip This creates a zip file with 3 python files inside of it. It can be executed with python test.zip. Everything is completely self-contained. (I believe this requires python >= 2.6, by the way...) A: If you're trying to make your scripts easier to distribute, this isn't the right way to go about doing it. For windows, look into py2exe which will convert all your files into one executable file. For linux, the preferred method is to use a package which the user's package manager will install. If you have your distutils bits properly set up, it should not be difficult at all to create a package for your software.
Python tool for incorporating imported items
Is there a tool in python to rewrite some code which imports things such that it no longer has to import anything? Take a library that draws a box called box.py def box(text='Hello, World!') draw the box magic return Now in another program (we'll call it warning.py) it says: from box import box box('Warning, water found in hard drive') Is there a tool that I can use that will see it importing the box function (or a class for that matter) from box and insert that function (or class, or even variable definitions) into the warning.py script removing the import line (thus making it more portable)? With thanks, Narnie
[ "It sounds like you're wanting to effectively copy-paste everything into one file to be able to distribute a single file instead of several? \nIn that case, look into using a zipped module instead of copy-pasting everything into one file... This is far more maintainable in the long run.\nPython will execute a zip ...
[ 7, 0 ]
[]
[]
[ "import", "parsing", "python" ]
stackoverflow_0003795629_import_parsing_python.txt
Q: Does Python use a compiler or interpreter or a combination? Possible Duplicate: CPython is bytecode interpreter? My question is: Does Python use a compiler, an interpreter or a combination of them? A: Python uses a virtual machine aproach (as PHP, Ruby, .NET languages etc), python implementation uses a compiler to create intermediate language that is executed on a virtual machine.
Does Python use a compiler or interpreter or a combination?
Possible Duplicate: CPython is bytecode interpreter? My question is: Does Python use a compiler, an interpreter or a combination of them?
[ "Python uses a virtual machine aproach (as PHP, Ruby, .NET languages etc), python implementation uses a compiler to create intermediate language that is executed on a virtual machine.\n" ]
[ 2 ]
[ "yes it use an interpreter, just run the .py and then it will be ecxecuted! if you want to compile your script to run on another machine as a .exe program you can compile it with th py2exe library\n" ]
[ -1 ]
[ "compiler_construction", "interpreter", "python" ]
stackoverflow_0003795893_compiler_construction_interpreter_python.txt
Q: Given a Python list, how to write a function that returns a given range of elements? I have def findfreq(nltktext, atitem) fdistscan = FreqDist(nltktext) distlist = fdistscan.keys() return distlist[:atitem] which relies on FreqDist from the NLTK package, and does not work. The problem seems to be the part of the function where I try to return only the first n items of the list, using the variable atitem. So I generalize this function like so def giveup(listname, lowerbound, upperbound) return listname[lowerbound:upperbound] returning the usual error >>> import bookroutines Traceback (most recent call last): File "<stdin>", line 1, in <module> File "bookroutines.py", line 70 def giveup(listname, lowerbound, upperbound) ^ SyntaxError: invalid syntax but hopefully also an answer from some kind person whose Python is much more fluent than mine. A: You need a colon (:) at the end of the def line. def findfreq(nltktext, atitem): fdistscan = FreqDist(nltktext) distlist = fdistscan.keys() return distlist[:atitem] Python's function declaration syntax is: def FuncName(Args): # code A: operator.itemgetter() will return a function that slices a sequence if you pass it a slice object.
Given a Python list, how to write a function that returns a given range of elements?
I have def findfreq(nltktext, atitem) fdistscan = FreqDist(nltktext) distlist = fdistscan.keys() return distlist[:atitem] which relies on FreqDist from the NLTK package, and does not work. The problem seems to be the part of the function where I try to return only the first n items of the list, using the variable atitem. So I generalize this function like so def giveup(listname, lowerbound, upperbound) return listname[lowerbound:upperbound] returning the usual error >>> import bookroutines Traceback (most recent call last): File "<stdin>", line 1, in <module> File "bookroutines.py", line 70 def giveup(listname, lowerbound, upperbound) ^ SyntaxError: invalid syntax but hopefully also an answer from some kind person whose Python is much more fluent than mine.
[ "You need a colon (:) at the end of the def line.\ndef findfreq(nltktext, atitem):\n fdistscan = FreqDist(nltktext)\n distlist = fdistscan.keys()\n return distlist[:atitem]\n\nPython's function declaration syntax is:\ndef FuncName(Args):\n # code\n\n", "operator.itemgetter() will return a function tha...
[ 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003795928_list_python.txt
Q: when we need use sudo python xxx.py or just python xxx.py or xxx.py I have write a website,what confused me is when i run the website,first i need start the the app, so there are 3 ways: sudo python xxx.py python xxx.py xxx.py I didn't clear with how to use each of them,the NO.3 method currently in my computer dosen't work well A: sudo will run the application with superuser permissions. Considering that you're referring to a website, this is certainly not what you want to do. (For a webapp, if it requires superuser permissions, it's broken. That's far, far too big of a security risk to consider actually using.) Under other circumstances you might have a python program that does some sort of system maintaince and requires being run as root. In this case, you'd use sudo, but you would never want to do this for something that's publicly accessible and could potentially be exploited. In fact, for anything other than testing, you should probably run the webapp as a separate user with very limited access (e.g. with their shell set to /dev/null, no read or write access to anything that they don't need, etc...). The other two are effectively identical (in therms of what they do), but the last option (executing the script directly) will require: the executable bit to be set (on unix-y systems) (e.g. chmod +x whatever.py) a shebang on the first line(e.g. #! /usr/bin/python) pointing to the python execuctable that you want to run things with (again, this only applies to unix-y systems) Calling python to run the code (python whatever.py) and following the steps above (resulting in a script that you can call directly with whatever.py) do exactly the same thing (assuming that the shebang in the python file points to the same python executable as "python" does, anyway...)
when we need use sudo python xxx.py or just python xxx.py or xxx.py
I have write a website,what confused me is when i run the website,first i need start the the app, so there are 3 ways: sudo python xxx.py python xxx.py xxx.py I didn't clear with how to use each of them,the NO.3 method currently in my computer dosen't work well
[ "sudo will run the application with superuser permissions. Considering that you're referring to a website, this is certainly not what you want to do. (For a webapp, if it requires superuser permissions, it's broken. That's far, far too big of a security risk to consider actually using.) \nUnder other circumstan...
[ 4 ]
[]
[]
[ "env", "python", "sudo" ]
stackoverflow_0003795942_env_python_sudo.txt
Q: 404 Response in Google Buzz API I'm playing around with Google Buzz API from Python, During the OAuth process when I reach the part of authorizing the token from browser, I go to this URL https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?oauth_token=..., and when I press OK, continue I expect to be directed to a page like this one http://code.google.com/apis/accounts/images/OauthUX_nocallback.png but instead I get a 404 Not Found error on this URL https://www.google.com/buzz/api/auth/OAuthPost :( What's wrong? Has anyone tried the Google Buzz API for Installed Applications?? A: It seems that providing the domain parameter is essential even in Installed Applications, I set it to anonymous since I'm testing and the problem was solved :) Sorry to bother you but I'm sure this will help others in the future ;)
404 Response in Google Buzz API
I'm playing around with Google Buzz API from Python, During the OAuth process when I reach the part of authorizing the token from browser, I go to this URL https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?oauth_token=..., and when I press OK, continue I expect to be directed to a page like this one http://code.google.com/apis/accounts/images/OauthUX_nocallback.png but instead I get a 404 Not Found error on this URL https://www.google.com/buzz/api/auth/OAuthPost :( What's wrong? Has anyone tried the Google Buzz API for Installed Applications??
[ "It seems that providing the domain parameter is essential even in Installed Applications, I set it to anonymous since I'm testing and the problem was solved :)\nSorry to bother you but I'm sure this will help others in the future ;)\n" ]
[ 1 ]
[]
[]
[ "google_api", "google_buzz", "http_status_code_404", "python" ]
stackoverflow_0003795941_google_api_google_buzz_http_status_code_404_python.txt
Q: AttributeError: 'NoneType' object has no attribute 'findSongBySize' I'm new to Ubuntu (and the Python scripts that go with it) and I've been hitting this error with the iTunesToRhythm script. **Traceback (most recent call last): File "/home/amylee/iTunesToRhythm.py", line 220, in <module> main(sys.argv) File "/home/amylee/iTunesToRhythm.py", line 48, in main match = correlator.correlateSong( song, options.confirm, options.fastAndLoose, options.promptForDisambiguate ) File "/home/amylee/iTunesToRhythm.py", line 133, in correlateSong matches = self.parser.findSongBySize( song.size ); AttributeError: 'NoneType' object has no attribute 'findSongBySize'** I understand the concept behind fixing the issue but have no idea how to go about it. I've looked at answers to similar problems but none really help me, especially since I have no clue as to what I am doing. I've included the full script below. Thanks in advance, dudes who know way more about this stuff than I do. ----iTunesToRhythm.py---- import sys import platform if platform.system() == "Darwin": sys.path.append('/sw/lib/python2.5/site-packages/') from dumpitunesmac import iTunesMacParser, iTunesMacSong import libxml2 import linecache from optparse import OptionParser, OptionGroup from dumprhythm import RhythmLibraryParser, RhythmSong from dumpitunes import iTunesLibraryParser, iTunesSong def main(argv): # process command line options, args = processCommandLine(argv) print "Reading input from " + args[0] inputParser = getParser(args[0], options ) print "Writing to output " + args[1] destinationParser = getParser(args[1], options ) #retrieve destination songs allDestinationSongs = destinationParser.getSongs() # go through each song in destination library correlator = SongCorrelator(inputParser) for song in allDestinationSongs: print song.artist + " - " + song.album + " - " + song.title + " - " + str(song.size) if song.size != None and song.size != "Unknown": # find equivalent itunes song match = correlator.correlateSong( song, options.confirm, options.fastAndLoose, options.promptForDisambiguate ) # update database, if match if match != None and options.writeChanges == True: if options.noratings == False: song.setRating( match.rating ) print "\t\t\tRating changed to " + str( match.rating ) if options.noplaycounts == False: song.setPlaycount( match.playcount ) print "\t\t\tPlay count changed to " + str( match.playcount ) # dump summary results print "\nSummary\n------------------------------------" print "manually resolved matches = " + str( correlator.manuallyResolvedMatches) print "full matches = " + str( correlator.fullMatches ) print "partial matches = " + str( correlator.partialMatches) print "no matches = " + str( correlator.zeroMatches ) print "unresolved ambiguous matches = " + str( correlator.ambiguousMatches ) # save if options.writeChanges == True: destinationParser.save() print "Changes were written to destination" else: print "Changes were not written to destination \n\tuse -w to actually write changes to disk" def getParser( file, options ): if file == "mysql": print "\tassuming amarok database" return AmarokLibraryParser(options.servername, options.database, options.username, options.password ) if file == "itunes": print "\tassuming itunes on the mac" return iTunesMacParser() desc = linecache.getline( file, 2) if desc.find("Apple Computer") != -1: #open itunes linbrary print "\tdetected Itunes library" return iTunesLibraryParser(file); if desc.find("rhythmdb") != -1: print "\tdetected Rhythm box library" return RhythmLibraryParser(file) def processCommandLine( argv ): parser = OptionParser("iTunesToRhythm [options] <inputfile>|itunes|mysql <outputfile>|mysql|itunes") parser.add_option("-c", "--confirm", action="store_true", dest="confirm", default = False, help="confirm every match" ) parser.add_option("-w", "--writechanges", action="store_true", dest="writeChanges", default = False, help="write changes to destination file" ) parser.add_option("-a", "--disambiguate", action="store_true", dest="promptForDisambiguate", default = False, help="prompt user to resolve ambiguities" ) parser.add_option("-l", "--fastandloose", action="store_true", dest= "fastAndLoose", default = False, help = "ignore differences in files name when a file size match is made against a single song. Will not resolve multiple matches" ) parser.add_option("--noplaycounts", action="store_true", dest= "noplaycounts", default = False, help = "do not update play counts" ) parser.add_option("--noratings", action="store_true", dest= "noratings", default = False, help = "do not update ratings" ) amarokGroup = OptionGroup(parser, "Amarok options", "Options for connecting to an Amarok MySQL remote database") amarokGroup.add_option("-s", "--server", dest="servername", help = "host name of the MySQL database server") amarokGroup.add_option("-d", "--database", dest="database", help = "database name of the amarok database") amarokGroup.add_option("-u", "--username", dest="username", help = "login name of the amarok database") amarokGroup.add_option("-p", "--password", dest="password", help = "password of the user") parser.add_option_group(amarokGroup) # parse options options, args = parser.parse_args() # check that files are specified if len(args) != 2: parser.print_help() parser.error( "you must supply 2 file names or 1 file name and the word mysql followed by database information. Specyfing itunes will use a running instance of iTunes on the Mac" ) # make surce source & destination are not the same if args[0] == args[1]: parser.error("source and destination cannot be the same") # we're ok return options, args class SongCorrelator: def __init__(self, parser ): self.parser = parser self.zeroMatches = 0 self.fullMatches = 0 self.ambiguousMatches = 0; self.partialMatches = 0; self.manuallyResolvedMatches = 0; # attempt to find matching song in database def correlateSong( self, song, confirm, fastAndLoose, promptForDisambiguate ): match = None matches = self.parser.findSongBySize( song.size ); matchcount = len(matches) # no results if matchcount == 0: print "\t no matches found" self.zeroMatches = self.zeroMatches + 1 # full match elif matchcount == 1: match = matches[0] if match.title == song.title: print "\t 100% match on " + self.dumpMatch( match ) self.fullMatches = self.fullMatches + 1 else: if fastAndLoose == False: match = self.disambiguate( song, matches, promptForDisambiguate ) else: print "\t 50% match on " + self.dumpMatch( match ) self.partialMatches = self.partialMatches + 1 # multiple matches else: print "\t multiple matches" for match in matches: print "\t\t " + self.dumpMatch( match ) # attempt a resolution match = self.disambiguate( song, matches, promptForDisambiguate ) #review if confirm == True: foo = raw_input( 'press <enter> to continue, Ctrl-C to cancel') #done return match def dumpMatch( self, match ): return match.title + ", playcount = " + str(match.playcount) + ", rating = " + str(match.rating) def disambiguate(self,song,matches,prompt): # attempt to disambiguate by title print "\t looking for secondary match on title" titlematchcount = 0 for match in matches: if match.title == song.title: titlematchcount = titlematchcount + 1 latstitlematch = match if titlematchcount == 1: # we successfully disambiguated using the title print "\t\t disambiguated using title" self.fullMatches = self.fullMatches + 1 return latstitlematch if prompt == True: print "\t\t cannot disambiguate. Trying to match " + song.filePath print "Please select file or press <Enter> for no match:" numMatch = 0 for match in matches: numMatch = numMatch + 1 print "\t\t\t\t[" + str(numMatch) + "] " + self.dumpMatch(match) + ", " + match.filePath selection = self.inputNumber("\t\t\t\t? ", 1, len(matches) ) if selection > 0: self.manuallyResolvedMatches = self.manuallyResolvedMatches + 1 return matches[selection - 1] # user did not select, record ambiguity self.ambiguousMatches = self.ambiguousMatches + 1 return None def inputNumber(self, msg, min, max): result = raw_input(msg) if len(result) == 0: return 0 try: resultNum = int(result) if resultNum < min or resultNum > max: print "out of range" return self.inputNumber( msg, min, max ) return resultNum except: print "invalid input" return self.inputNumber(msg, min, max) if __name__ == "__main__": main(sys.argv) A: I'm the original developer. I updated the script to throw an exception if the file format is not recognized (I think this is what you are running into). I also incorporated some useful patches from another user. Please download the files again and e-mail me if you still have trouble. A: Your problem appears to be that getParser is returning None, presumably because all the if conditions have failed. Check that args[0] and options are the values that you expect them to be. I'd suggest raising an exception at the end of the getParser method if the arguments are not valid so that the error is raised close to the cause of the problem rather in some unrelated code much later.
AttributeError: 'NoneType' object has no attribute 'findSongBySize'
I'm new to Ubuntu (and the Python scripts that go with it) and I've been hitting this error with the iTunesToRhythm script. **Traceback (most recent call last): File "/home/amylee/iTunesToRhythm.py", line 220, in <module> main(sys.argv) File "/home/amylee/iTunesToRhythm.py", line 48, in main match = correlator.correlateSong( song, options.confirm, options.fastAndLoose, options.promptForDisambiguate ) File "/home/amylee/iTunesToRhythm.py", line 133, in correlateSong matches = self.parser.findSongBySize( song.size ); AttributeError: 'NoneType' object has no attribute 'findSongBySize'** I understand the concept behind fixing the issue but have no idea how to go about it. I've looked at answers to similar problems but none really help me, especially since I have no clue as to what I am doing. I've included the full script below. Thanks in advance, dudes who know way more about this stuff than I do. ----iTunesToRhythm.py---- import sys import platform if platform.system() == "Darwin": sys.path.append('/sw/lib/python2.5/site-packages/') from dumpitunesmac import iTunesMacParser, iTunesMacSong import libxml2 import linecache from optparse import OptionParser, OptionGroup from dumprhythm import RhythmLibraryParser, RhythmSong from dumpitunes import iTunesLibraryParser, iTunesSong def main(argv): # process command line options, args = processCommandLine(argv) print "Reading input from " + args[0] inputParser = getParser(args[0], options ) print "Writing to output " + args[1] destinationParser = getParser(args[1], options ) #retrieve destination songs allDestinationSongs = destinationParser.getSongs() # go through each song in destination library correlator = SongCorrelator(inputParser) for song in allDestinationSongs: print song.artist + " - " + song.album + " - " + song.title + " - " + str(song.size) if song.size != None and song.size != "Unknown": # find equivalent itunes song match = correlator.correlateSong( song, options.confirm, options.fastAndLoose, options.promptForDisambiguate ) # update database, if match if match != None and options.writeChanges == True: if options.noratings == False: song.setRating( match.rating ) print "\t\t\tRating changed to " + str( match.rating ) if options.noplaycounts == False: song.setPlaycount( match.playcount ) print "\t\t\tPlay count changed to " + str( match.playcount ) # dump summary results print "\nSummary\n------------------------------------" print "manually resolved matches = " + str( correlator.manuallyResolvedMatches) print "full matches = " + str( correlator.fullMatches ) print "partial matches = " + str( correlator.partialMatches) print "no matches = " + str( correlator.zeroMatches ) print "unresolved ambiguous matches = " + str( correlator.ambiguousMatches ) # save if options.writeChanges == True: destinationParser.save() print "Changes were written to destination" else: print "Changes were not written to destination \n\tuse -w to actually write changes to disk" def getParser( file, options ): if file == "mysql": print "\tassuming amarok database" return AmarokLibraryParser(options.servername, options.database, options.username, options.password ) if file == "itunes": print "\tassuming itunes on the mac" return iTunesMacParser() desc = linecache.getline( file, 2) if desc.find("Apple Computer") != -1: #open itunes linbrary print "\tdetected Itunes library" return iTunesLibraryParser(file); if desc.find("rhythmdb") != -1: print "\tdetected Rhythm box library" return RhythmLibraryParser(file) def processCommandLine( argv ): parser = OptionParser("iTunesToRhythm [options] <inputfile>|itunes|mysql <outputfile>|mysql|itunes") parser.add_option("-c", "--confirm", action="store_true", dest="confirm", default = False, help="confirm every match" ) parser.add_option("-w", "--writechanges", action="store_true", dest="writeChanges", default = False, help="write changes to destination file" ) parser.add_option("-a", "--disambiguate", action="store_true", dest="promptForDisambiguate", default = False, help="prompt user to resolve ambiguities" ) parser.add_option("-l", "--fastandloose", action="store_true", dest= "fastAndLoose", default = False, help = "ignore differences in files name when a file size match is made against a single song. Will not resolve multiple matches" ) parser.add_option("--noplaycounts", action="store_true", dest= "noplaycounts", default = False, help = "do not update play counts" ) parser.add_option("--noratings", action="store_true", dest= "noratings", default = False, help = "do not update ratings" ) amarokGroup = OptionGroup(parser, "Amarok options", "Options for connecting to an Amarok MySQL remote database") amarokGroup.add_option("-s", "--server", dest="servername", help = "host name of the MySQL database server") amarokGroup.add_option("-d", "--database", dest="database", help = "database name of the amarok database") amarokGroup.add_option("-u", "--username", dest="username", help = "login name of the amarok database") amarokGroup.add_option("-p", "--password", dest="password", help = "password of the user") parser.add_option_group(amarokGroup) # parse options options, args = parser.parse_args() # check that files are specified if len(args) != 2: parser.print_help() parser.error( "you must supply 2 file names or 1 file name and the word mysql followed by database information. Specyfing itunes will use a running instance of iTunes on the Mac" ) # make surce source & destination are not the same if args[0] == args[1]: parser.error("source and destination cannot be the same") # we're ok return options, args class SongCorrelator: def __init__(self, parser ): self.parser = parser self.zeroMatches = 0 self.fullMatches = 0 self.ambiguousMatches = 0; self.partialMatches = 0; self.manuallyResolvedMatches = 0; # attempt to find matching song in database def correlateSong( self, song, confirm, fastAndLoose, promptForDisambiguate ): match = None matches = self.parser.findSongBySize( song.size ); matchcount = len(matches) # no results if matchcount == 0: print "\t no matches found" self.zeroMatches = self.zeroMatches + 1 # full match elif matchcount == 1: match = matches[0] if match.title == song.title: print "\t 100% match on " + self.dumpMatch( match ) self.fullMatches = self.fullMatches + 1 else: if fastAndLoose == False: match = self.disambiguate( song, matches, promptForDisambiguate ) else: print "\t 50% match on " + self.dumpMatch( match ) self.partialMatches = self.partialMatches + 1 # multiple matches else: print "\t multiple matches" for match in matches: print "\t\t " + self.dumpMatch( match ) # attempt a resolution match = self.disambiguate( song, matches, promptForDisambiguate ) #review if confirm == True: foo = raw_input( 'press <enter> to continue, Ctrl-C to cancel') #done return match def dumpMatch( self, match ): return match.title + ", playcount = " + str(match.playcount) + ", rating = " + str(match.rating) def disambiguate(self,song,matches,prompt): # attempt to disambiguate by title print "\t looking for secondary match on title" titlematchcount = 0 for match in matches: if match.title == song.title: titlematchcount = titlematchcount + 1 latstitlematch = match if titlematchcount == 1: # we successfully disambiguated using the title print "\t\t disambiguated using title" self.fullMatches = self.fullMatches + 1 return latstitlematch if prompt == True: print "\t\t cannot disambiguate. Trying to match " + song.filePath print "Please select file or press <Enter> for no match:" numMatch = 0 for match in matches: numMatch = numMatch + 1 print "\t\t\t\t[" + str(numMatch) + "] " + self.dumpMatch(match) + ", " + match.filePath selection = self.inputNumber("\t\t\t\t? ", 1, len(matches) ) if selection > 0: self.manuallyResolvedMatches = self.manuallyResolvedMatches + 1 return matches[selection - 1] # user did not select, record ambiguity self.ambiguousMatches = self.ambiguousMatches + 1 return None def inputNumber(self, msg, min, max): result = raw_input(msg) if len(result) == 0: return 0 try: resultNum = int(result) if resultNum < min or resultNum > max: print "out of range" return self.inputNumber( msg, min, max ) return resultNum except: print "invalid input" return self.inputNumber(msg, min, max) if __name__ == "__main__": main(sys.argv)
[ "I'm the original developer. I updated the script to throw an exception if the file format is not recognized (I think this is what you are running into). I also incorporated some useful patches from another user.\nPlease download the files again and e-mail me if you still have trouble.\n", "Your problem appears...
[ 7, 1 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0003795143_attributes_python.txt
Q: retrieve application/json document with twill/mechanize in authenticated session I need to retrieve a document with MIME type "application/json". I'm using twill to log in to a site and when I attempt to go to the URL pointing to the JSON document and show it, I get this message: 'The HTTP header field "Accept" with value "text/html; */*" could not be parsed.' I have tried changing the "Accept" field to "application/json" but still no dice. Thanks!! A: This is by no means the answer I'm looking for, but zope.testbrowser will do what I want. The interface is slightly more complicated than twill, but not by much. Still looking for a twill solution! A: Looks like you have Accept: text/html; */* which seems syntactically wrong to me: per w3.org, the syntax is <field> = Accept: <entry> *[ , <entry> ] <entry> = <content type> *[ ; <param> ] <param> = <attr> = <float> <attr> = q / mxs / mxb <float> = <ANSI-C floating point text represntation> so that */*, since it follows a semicolon rather than a comma, should be a <param>, but not in fact of the form <attr> = <float>. Did you mean to have a q=something, after the semicolon, and forgot to give it? Else, just text/html, */* -- i.e., with a comma, not a semicolon -- seems to be the right syntax.
retrieve application/json document with twill/mechanize in authenticated session
I need to retrieve a document with MIME type "application/json". I'm using twill to log in to a site and when I attempt to go to the URL pointing to the JSON document and show it, I get this message: 'The HTTP header field "Accept" with value "text/html; */*" could not be parsed.' I have tried changing the "Accept" field to "application/json" but still no dice. Thanks!!
[ "This is by no means the answer I'm looking for, but zope.testbrowser will do what I want.\nThe interface is slightly more complicated than twill, but not by much.\nStill looking for a twill solution!\n", "Looks like you have Accept: text/html; */* which seems syntactically wrong to me: per w3.org, the syntax is\...
[ 0, 0 ]
[]
[]
[ "json", "mechanize", "python", "twill" ]
stackoverflow_0003796009_json_mechanize_python_twill.txt
Q: Can I override Python list displays? I'd like to change the behavior of Python's list displays so that instead of producing a list, they produce a subclass of list that I've written. (Note: I don't think this is a good idea; I'm doing it for fun, not actual use.) Here's what I've done: old_list = list class CallableList(old_list): def __init__(self, *args): old_list.__init__(self) for arg in args: self.append(arg) def __call__(self, start, end=None): if end: return self[start:end] return self[start] list = CallableList Once that's done, this returns the third element of the list: x = list(1, 2, 3) print x(2) but this still gives an error: x = [1, 2, 3] print x(2) The error is pretty straightforward: Traceback (most recent call last): File "list_test.py", line 23, in <module> print x(2) TypeError: 'list' object is not callable I think there's probably no way of doing this, but I can't find anything that says so definitively. Any ideas? A: You cannot trivially override the syntactic sugar used for built-in types, since this happens at the compiler level. Always call the constructor explicitly. A: You can't change it from within Python. Constructs such as list-comprehensions always use the built-in list type, not whatever you've defined the word list to in the current namespace. If you want to change the built-in type, you have to edit the Python source code and recompile. Assuming you're using the CPython implementation, it lives in Objects/listobject.c.
Can I override Python list displays?
I'd like to change the behavior of Python's list displays so that instead of producing a list, they produce a subclass of list that I've written. (Note: I don't think this is a good idea; I'm doing it for fun, not actual use.) Here's what I've done: old_list = list class CallableList(old_list): def __init__(self, *args): old_list.__init__(self) for arg in args: self.append(arg) def __call__(self, start, end=None): if end: return self[start:end] return self[start] list = CallableList Once that's done, this returns the third element of the list: x = list(1, 2, 3) print x(2) but this still gives an error: x = [1, 2, 3] print x(2) The error is pretty straightforward: Traceback (most recent call last): File "list_test.py", line 23, in <module> print x(2) TypeError: 'list' object is not callable I think there's probably no way of doing this, but I can't find anything that says so definitively. Any ideas?
[ "You cannot trivially override the syntactic sugar used for built-in types, since this happens at the compiler level. Always call the constructor explicitly.\n", "You can't change it from within Python. Constructs such as list-comprehensions always use the built-in list type, not whatever you've defined the word...
[ 3, 1 ]
[ " >>> print(x(2)) # works in 2.7\n 3\n >>> type(x)\n <class '__main__.CallableList'>\n >>> y = [1,2,3]\n >>> type(y)\n <type 'list'>\n\nso you haven't really redefined type 'list,' you've only changed your namespace so that the type list's list() method now clashes with your type CallableList type. To...
[ -1 ]
[ "list", "overriding", "python" ]
stackoverflow_0003795591_list_overriding_python.txt
Q: Combine picture and plot with Python Matplotlib I have a plot which has timestamps on the x-axis and some signal data on the y-axis. As a documentation I want to put timestamped pictures in relation to specific points in the plot. Is it possible to draw a line in a plot to a picture in a sequence of pictures below the plot? A: This demo from the matplotlib gallery shows how to insert pictures, draw lines to them, etc. I'll post the image from the gallery, and you can follow the link to see the code. And here's the code (from version 2.1.2): import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Circle from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage, AnnotationBbox) from matplotlib.cbook import get_sample_data if 1: fig, ax = plt.subplots() # Define a 1st position to annotate (display it with a marker) xy = (0.5, 0.7) ax.plot(xy[0], xy[1], ".r") # Annotate the 1st position with a text box ('Test 1') offsetbox = TextArea("Test 1", minimumdescent=False) ab = AnnotationBbox(offsetbox, xy, xybox=(-20, 40), xycoords='data', boxcoords="offset points", arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) # Annotate the 1st position with another text box ('Test') offsetbox = TextArea("Test", minimumdescent=False) ab = AnnotationBbox(offsetbox, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) # Define a 2nd position to annotate (don't display with a marker this time) xy = [0.3, 0.55] # Annotate the 2nd position with a circle patch da = DrawingArea(20, 20, 0, 0) p = Circle((10, 10), 10) da.add_artist(p) ab = AnnotationBbox(da, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) # Annotate the 2nd position with an image (a generated array of pixels) arr = np.arange(100).reshape((10, 10)) im = OffsetImage(arr, zoom=2) im.image.axes = ax ab = AnnotationBbox(im, xy, xybox=(-50., 50.), xycoords='data', boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) # Annotate the 2nd position with another image (a Grace Hopper portrait) fn = get_sample_data("grace_hopper.png", asfileobj=False) arr_img = plt.imread(fn, format='png') imagebox = OffsetImage(arr_img, zoom=0.2) imagebox.image.axes = ax ab = AnnotationBbox(imagebox, xy, xybox=(120., -80.), xycoords='data', boxcoords="offset points", pad=0.5, arrowprops=dict( arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3") ) ax.add_artist(ab) # Fix the display limits to see everything ax.set_xlim(0, 1) ax.set_ylim(0, 1) plt.show() A: If I understand the question correctly, then perhaps this may help: import scipy import pylab fig = pylab.figure() axplot = fig.add_axes([0.07,0.25,0.90,0.70]) axplot.plot(scipy.randn(100)) numicons = 8 for k in range(numicons): axicon = fig.add_axes([0.07+0.11*k,0.05,0.1,0.1]) axicon.imshow(scipy.rand(4,4),interpolation='nearest') axicon.set_xticks([]) axicon.set_yticks([]) fig.show() fig.savefig('iconsbelow.png')
Combine picture and plot with Python Matplotlib
I have a plot which has timestamps on the x-axis and some signal data on the y-axis. As a documentation I want to put timestamped pictures in relation to specific points in the plot. Is it possible to draw a line in a plot to a picture in a sequence of pictures below the plot?
[ "This demo from the matplotlib gallery shows how to insert pictures, draw lines to them, etc. I'll post the image from the gallery, and you can follow the link to see the code.\n\nAnd here's the code (from version 2.1.2):\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.patches import Circle...
[ 26, 19 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003765056_matplotlib_python.txt
Q: Python to check if file status is being uploading Python 2.6 My script needs to monitor some 1G files on the ftp, when ever it's changed/modified, the script will download it to another place. Those file name will remain unchanged, people will delete the original file on ftp first, then upload a newer version. My script will checking the file metadata like file size and date modified to see if any difference. The question is when the script checking metadata, the new file may be still being uploading. How to handle this situation? Is there any file attribute indicates uploading status (like the file is locked)? Thanks. A: There is no such attribute. You may be unable to GET such file, but it depends on the server software. Also, file access flags may be set one way while the file is being uploaded and then changed when upload is complete; or incomplete file may have modified name (e.g. original_filename.ext.part) -- it all depends on the server-side software used for upload. If you control the server, make your own metadata, e.g. create an empty flag file alongside the newly uploaded file when upload is finished. In the general case, I'm afraid, the best you can do is monitor file size and consider the file completely uploaded if its size is not changing for a while. Make this interval sufficiently large (on the order of minutes). A: Your question leaves out a few details, but I'll try to answer. If you're running your status checker program on the same server thats running ftp: 1) Depending on your operating system, if you're using Linux and you've built inotify into your kernel you could use pyinotify to watch your upload directory -- inotify distinguishes from open, modify, close events and lets you asynchronously watch filesystem events so you're not polling constantly. OSX and Windows both have similar but differently implemented facilities. 2) You could pythonically tail -f to see when a new file is put on the server (if you're even logging that) and just update when you see related update messages. If you're running your program remotely 3) If your status checking utility has to run on a remote host from the FTP server, you'd have to poll the file for status and build in some logic to detect size changes. You can use the FTP 'SIZE' command for this for an easily parse-able string. You'd have to put some logic into it such that if the filesize gets smaller you would assume it's being replaced, and then wait for it to get bigger until it stops growing and stays the same size for some duration. If the archive is compressed in a way that you could verify the sum you could then download it, checksum, and then reupload to the remote site.
Python to check if file status is being uploading
Python 2.6 My script needs to monitor some 1G files on the ftp, when ever it's changed/modified, the script will download it to another place. Those file name will remain unchanged, people will delete the original file on ftp first, then upload a newer version. My script will checking the file metadata like file size and date modified to see if any difference. The question is when the script checking metadata, the new file may be still being uploading. How to handle this situation? Is there any file attribute indicates uploading status (like the file is locked)? Thanks.
[ "There is no such attribute. You may be unable to GET such file, but it depends on the server software. Also, file access flags may be set one way while the file is being uploaded and then changed when upload is complete; or incomplete file may have modified name (e.g. original_filename.ext.part) -- it all depends ...
[ 4, 3 ]
[]
[]
[ "ftp", "metadata", "python" ]
stackoverflow_0003795605_ftp_metadata_python.txt
Q: Yahoo BOSS API Python Library Error i've just downloaded the Yahoo BOSS Mashup framework from http://developer.yahoo.com/search/boss/mashup.html, and I have a problem: I'm receiving the following error for all examples. For instance, for example.ex3.py: File "ex3.py", line 33 tb = db.group(by=["ynews$title"], key="dg$diggs", reducer=lambda d1, d2: d1 + d2, as: 'rank', table=tb, norm=text.norm) ^ SyntaxError: invalid syntax I read the post at Python 2.6 DB error but i do not understand the solution. How do i fix the problem? Is there any other alternate libraries i can use? Any suggestions are welcomed! A: oh, i manage to fix it. What i did is that i changed the key word "as" and replace it with some other word. I used "as" to "as1" and reinstalled the framework. Now it works. Hope this helps all other people.
Yahoo BOSS API Python Library Error
i've just downloaded the Yahoo BOSS Mashup framework from http://developer.yahoo.com/search/boss/mashup.html, and I have a problem: I'm receiving the following error for all examples. For instance, for example.ex3.py: File "ex3.py", line 33 tb = db.group(by=["ynews$title"], key="dg$diggs", reducer=lambda d1, d2: d1 + d2, as: 'rank', table=tb, norm=text.norm) ^ SyntaxError: invalid syntax I read the post at Python 2.6 DB error but i do not understand the solution. How do i fix the problem? Is there any other alternate libraries i can use? Any suggestions are welcomed!
[ "oh, i manage to fix it. What i did is that i changed the key word \"as\" and replace it with some other word.\nI used \"as\" to \"as1\" and reinstalled the framework. Now it works. Hope this helps all other people. \n" ]
[ 0 ]
[]
[]
[ "python", "yahoo_boss_api" ]
stackoverflow_0003796747_python_yahoo_boss_api.txt
Q: Qt uses CSS to color objects? Is there another way to go about this? I am learning PyQt from this site. The tutorial is building a widget that colours a square. In this, they are using CSS to colour the square, rather than give it some sort of concrete property of colour. Why is this? Is there another way to do this without CSS or is this the preferred method? It seems awfully strange.. A: Every widget has QPalette, that can be modified and accessed via QWidget::palette() and QWidget::setPalette(p). You can find some useful details here: QPalette in Qt 4.6. CSS is just more clean and simple (and declarative, which is SOoo popular nowadays :) ) way to determine it. Note, that if you want only to modify your widget's background, there is a convenience method just for you: QWidget::setBackgroundRole(QPalette::ColorRole). A: This is one of the strengths of Qt. You can modify the UI with simple CSS. It turns out very nice if you treat correctly. Would you be interested in taking a look at my GhostQt SDK. I am using CSS for my Ghost Menu, to give it rounded corners and apply a transparent background. http://traipse.assembla.com/spaces/ghostqt (It's a side project so there is not much there)
Qt uses CSS to color objects? Is there another way to go about this?
I am learning PyQt from this site. The tutorial is building a widget that colours a square. In this, they are using CSS to colour the square, rather than give it some sort of concrete property of colour. Why is this? Is there another way to do this without CSS or is this the preferred method? It seems awfully strange..
[ "Every widget has QPalette, that can be modified and accessed via QWidget::palette() and QWidget::setPalette(p).\nYou can find some useful details here: QPalette in Qt 4.6. CSS is just more clean and simple (and declarative, which is SOoo popular nowadays :) ) way to determine it.\nNote, that if you want only to mo...
[ 4, 0 ]
[]
[]
[ "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0003695799_pyqt_python_qt_user_interface.txt
Q: object oriented programming basics (python) Level: Beginner In the following code my 'samePoint' function returns False where i am expecting True. Any hints? import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self.x) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) class pPoint: def __init__(self,r,a): self.radius = r self.angle = a self.x = r * math.cos(a) self.y = r * math.sin(a) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) def samePoint(p, q): return (p.cartesian == q.cartesian) >>> p = cPoint(1.0000000000000002, 2.0) >>> q = pPoint(2.23606797749979, 1.1071487177940904) >>> p.cartesian() (1.0000000000000002, 2.0) >>> q.cartesian() (1.0000000000000002, 2.0) >>> samePoint(p, q) False >>> source: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008 A: Looking at your code def samePoint(p, q): return (p.cartesian == q.cartesian) p.cartesian, q.cartesian are functions and you are comparing function rather than function result. Since the comparing two distinct functions, the result is False What you should have been coding is def samePoint(p, q): return (p.cartesian() == q.cartesian()) A: You are not calling the methods on the equal check. So you are comparing the methods to each othter. Try: return (p.cartesian() == q.cartesian()) A: After you get the function calling thing fixed, you'll have floating point issues. try, def is_same_point(p1, p2, e): for c1, c2 in zip(c1, c2): if abs(c1 - c2) > e: return False return True I'm really surprised that it's working out for you with the code sample you posted. You must have constructed it to do so. In general, you can't directly compare floating point values for equality. A more pythonic way to write the above function is def is_same_point(point1, point2, e): return not any(abs(c1 - c2) > e for c1, c2 in zip(point1, point2)) you still have to pass the e (for epsilon) around though and that's gonna get old fast. def make_point_tester(e): def is_same_point(point1, point2): return not any(abs(c1 - c2) > e for c1, c2 in zip(point1, point2)) return is_same_point is_same_point = make_point_tester(.001) You've allready run into functions being first class objects, so you shouldn't have any trouble with this code ;)
object oriented programming basics (python)
Level: Beginner In the following code my 'samePoint' function returns False where i am expecting True. Any hints? import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self.x) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) class pPoint: def __init__(self,r,a): self.radius = r self.angle = a self.x = r * math.cos(a) self.y = r * math.sin(a) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) def samePoint(p, q): return (p.cartesian == q.cartesian) >>> p = cPoint(1.0000000000000002, 2.0) >>> q = pPoint(2.23606797749979, 1.1071487177940904) >>> p.cartesian() (1.0000000000000002, 2.0) >>> q.cartesian() (1.0000000000000002, 2.0) >>> samePoint(p, q) False >>> source: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008
[ "Looking at your code \ndef samePoint(p, q):\n return (p.cartesian == q.cartesian)\n\np.cartesian, q.cartesian are functions and you are comparing function rather than function result. Since the comparing two distinct functions, the result is False\nWhat you should have been coding is\ndef samePoint(p, q):\n ...
[ 6, 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003797219_oop_python.txt
Q: python script in crontab gets input arguments of another process running at the same time I run 2 python scripts from crontab at the same time each 30 min, e.g. 00,30 6-19 * * 0-5 /.../x.py site1 */3 6-19 * * 0-5 /.../y.py site2 At the beginning the both scripts make import of a module that prints some data to a log, e.g. name = os.path.basename(sys.argv[0]) site = sys.argv[1] pid = os.getpid() Occasionally (!) the second script y prints to the log input arguments of script x: name = x and site = site1 printed PID of the processes is not the same. Why this is happening and how can i avoid this? P.S. I suspect the problem is related to the logger I use. Can a script use a logger created in another script? In this case it will print on each line data related to the first script. Each script executes the same code: log = logging.getLogger('MyLog') log.setLevel(logging.INFO) dh = RotatingSqliteHandler(os.path.join(progDirs['log'],'sqlitelog'),processMeta, 5000000) log.addHandler(dh) The logger handler is defined as follows: class RotatingSqliteHandler(logging.Handler): def __init__(self, filename, progData, maxBytes=0): logging.Handler.__init__(self) self.user = progData['user'] self.host = progData['host'] self.progName = progData['name'] self.site = progData['site'] self.pid = random.getrandbits(50) ..... in the log I see that process ID which logger generates in the last line is the same for the both scripts. I'll try to use logger name unique to each script run instead of 'MyLog'. Although it is strange that a logger instance can be got from another process. A: When two scripts "run at the same time", the lines that they print can be mixed, depending on how the operating system allocates priority to the processes. You can thus obtain, in your logs, something like: x.py: /tmp/x.py … … # Other processes logging information … y.py: /tmp/y.py x.py: site1 # Not printed by y!! x.py: PID = 123 … … # Other processes logging information … y.py: site2 y.py: PID = 124 Do you still observe the problem if you prefix each line by each program base name? A: It's not possible for one Python process to access an object from another Python process, unless specific provision is made for this using e.g. the multiprocessing module. So I don't believe that's what's happening, no matter how much it looks like it on the surface. To confirm this, use an alterative handler (such as a FileHandler or RotatingFileHandler) to see if the problem still occurs. If it doesn't, then you should examine the RotatingSqliteHandler logic. If it does, and if you can come up with a small standalone script which demonstrates the problem repeatably, please post an issue to bugs.python.org and I'll certainly take a look. (I maintain the Python logging package.) A: Could this be related in any way to the following point? getLogger() returns a reference to a logger instance with the specified name if it is provided, or root if not. The names are period-separated hierarchical structures. Multiple calls to getLogger() with the same name will return a reference to the same logger object. Could both of your scripts be "connected" enough to each other that this plays a role? For instance, if y.py import x.py, then you get the same logger in both x.py and y.py when you call logging.getLogger('myLog') in each of them. A: This question puzzles me: here is yet another idea! The random generator can be seeded with "the current system time" (if not source of random numbers exists on the computer). In Python 2.7, this is done through a call to time.time(). The point is that "not all systems provide time with a better precision than 1 second." More generally, would it be possible that sometimes your x.py and y.py run sufficiently close to each other that time.time() is the same for both processes, so that random.getrandbits(50) yields the same for both of them? This would be compatible with the problem only appearing exceptionally, as you observed. What is the "resolution" of time.time() on your machine (smallest interval between different times)? maybe it's large enough for the two random generators to exceptionally be seeded in the same way.
python script in crontab gets input arguments of another process running at the same time
I run 2 python scripts from crontab at the same time each 30 min, e.g. 00,30 6-19 * * 0-5 /.../x.py site1 */3 6-19 * * 0-5 /.../y.py site2 At the beginning the both scripts make import of a module that prints some data to a log, e.g. name = os.path.basename(sys.argv[0]) site = sys.argv[1] pid = os.getpid() Occasionally (!) the second script y prints to the log input arguments of script x: name = x and site = site1 printed PID of the processes is not the same. Why this is happening and how can i avoid this? P.S. I suspect the problem is related to the logger I use. Can a script use a logger created in another script? In this case it will print on each line data related to the first script. Each script executes the same code: log = logging.getLogger('MyLog') log.setLevel(logging.INFO) dh = RotatingSqliteHandler(os.path.join(progDirs['log'],'sqlitelog'),processMeta, 5000000) log.addHandler(dh) The logger handler is defined as follows: class RotatingSqliteHandler(logging.Handler): def __init__(self, filename, progData, maxBytes=0): logging.Handler.__init__(self) self.user = progData['user'] self.host = progData['host'] self.progName = progData['name'] self.site = progData['site'] self.pid = random.getrandbits(50) ..... in the log I see that process ID which logger generates in the last line is the same for the both scripts. I'll try to use logger name unique to each script run instead of 'MyLog'. Although it is strange that a logger instance can be got from another process.
[ "When two scripts \"run at the same time\", the lines that they print can be mixed, depending on how the operating system allocates priority to the processes.\nYou can thus obtain, in your logs, something like:\nx.py: /tmp/x.py\n…\n… # Other processes logging information\n…\ny.py: /tmp/y.py\nx.py: site1 # Not prin...
[ 2, 2, 0, 0 ]
[]
[]
[ "crontab", "logging", "python" ]
stackoverflow_0003744751_crontab_logging_python.txt
Q: Django with multiple database I have a Django application with two configured databases first_DB and second_DB The configurations seems as following DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME' : 'emonitor', # Or path to database file if using sqlite3. 'USER' : 'emonitor', # Not used with sqlite3. 'PASSWORD': 'emonitor', # Not used with sqlite3. 'HOST' : '', # Set to empty string for localhost. Not used with sqlite3. 'PORT' : '', # Set to empty string for default. Not used with sqlite3. }, 'nagios': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'nagios', 'USER' : 'emonitor', 'PASSWORD': 'emonitor', 'HOST' : 'nagios.edc', 'PORT' : '', }, } The nagios database is readonly and this is configured in the routers module. The nagios database is on a remote machine my application gets data from nagios DB and inserts it into my local DB If the nagios machine is down, or mysql on nagios machine is turned off, the django server starts with the following error enter code here_mysql_exceptions.OperationalError: (2005, "Unknown MySQL server host 'nagios.edc' (1)") and the application does not work What I understand is that Django server tries to connect to all the configured databases but I want to get my application working even if the second database is unreachable How can I do that? A: If you don't know where the 500 error is coming from, set DEBUG=True in your settings, and look at the debug stack trace page that is produced. It will show you where the exception is being raised.
Django with multiple database
I have a Django application with two configured databases first_DB and second_DB The configurations seems as following DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME' : 'emonitor', # Or path to database file if using sqlite3. 'USER' : 'emonitor', # Not used with sqlite3. 'PASSWORD': 'emonitor', # Not used with sqlite3. 'HOST' : '', # Set to empty string for localhost. Not used with sqlite3. 'PORT' : '', # Set to empty string for default. Not used with sqlite3. }, 'nagios': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'nagios', 'USER' : 'emonitor', 'PASSWORD': 'emonitor', 'HOST' : 'nagios.edc', 'PORT' : '', }, } The nagios database is readonly and this is configured in the routers module. The nagios database is on a remote machine my application gets data from nagios DB and inserts it into my local DB If the nagios machine is down, or mysql on nagios machine is turned off, the django server starts with the following error enter code here_mysql_exceptions.OperationalError: (2005, "Unknown MySQL server host 'nagios.edc' (1)") and the application does not work What I understand is that Django server tries to connect to all the configured databases but I want to get my application working even if the second database is unreachable How can I do that?
[ "If you don't know where the 500 error is coming from, set DEBUG=True in your settings, and look at the debug stack trace page that is produced. It will show you where the exception is being raised.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003797119_django_python.txt
Q: What does cpython do to help detect object cycles(reference counting)? From what I've read about cpython it seems like it does reference counting + something extra to detect/free objects pointing to each other.(Correct me if I'm wrong). Could someone explain the something extra? Also does this guarantee* no cycle leaking? If not is there any research into an algorithm proven to add to reference counting to make it never leak*? Would this be just running a non reference counting tracing gc every so often? *discounting bugs and problems with modules using foreign function interface A: As explained in the documentation for gc.garbage, there is no guarantee that no leaks occur; specifically, cyclic objects with __del__ methods are not collected by default. For such objects, the cyclic links have to be manually broken to enable further GC. From what I understand by browsing the CPython sourcecode, the interpreter keeps references to all objects under its control. The "extra" garbage collector runs a mark-and-sweep-like algorithm through the heap, remembers for each object if it is reachable from the "outside" and, if not, deletes it. (The GC is generational, but it may be run explicitly from the gc module with a generation argument.) The only efficient algorithm that I could think of that satisfies your criteria would indeed be a "full" GC algorithm to augment reference counting and this is what seems to be implemented in Python. I'm not an expert in these matters though.
What does cpython do to help detect object cycles(reference counting)?
From what I've read about cpython it seems like it does reference counting + something extra to detect/free objects pointing to each other.(Correct me if I'm wrong). Could someone explain the something extra? Also does this guarantee* no cycle leaking? If not is there any research into an algorithm proven to add to reference counting to make it never leak*? Would this be just running a non reference counting tracing gc every so often? *discounting bugs and problems with modules using foreign function interface
[ "As explained in the documentation for gc.garbage, there is no guarantee that no leaks occur; specifically, cyclic objects with __del__ methods are not collected by default. For such objects, the cyclic links have to be manually broken to enable further GC.\nFrom what I understand by browsing the CPython sourcecode...
[ 4 ]
[]
[]
[ "cpython", "garbage_collection", "proof", "python", "reference_counting" ]
stackoverflow_0003797220_cpython_garbage_collection_proof_python_reference_counting.txt
Q: Overuse of mixin is evil and what are the alternative solutions? Sometimes using mixin with multiple inheritance can help us improve reusability of our code. For example, the following design class FollowableMixin(object): def get_followers(self): ... ... class User(FollowableMixin): ... may be better reused than simply adding get_followers to User: class User(object): def get_followers(self): ... ... because later we may consider supporting other followable entities that are potential clients of get_followers: class BookStore(FollowableMixin): ... However, if this pattern is overused, code may get too complex. class User(FollowableMixin, RunnableMixin, FlyableMixin, WhatMixin ...): ... With all these mixin classes injecting properties and methods to your class, it becomes very difficult to understand your code. For example, you don't know where the method you are calling is from, and this method may in turn include an invocation of a method in another mixin ... What should I do to simplify this programme? A: Sometimes it can help to collect together related features in a single class if they are often used together. class FooMixin(FollowableMixin, RunnableMixin): pass Then when you come to use it you only have one or two direct base classes instead of many. Obviously you should only do this if it makes sense - it can be abused. Without knowing more about your specific example it is hard to know whether it makes sense to do this or not in your case. A: If your User class really has that many characteristics that are appropriate, then you may simply have a complex application. Having five mixins is better than having five functions copied from other places. Some possibilities for simplifying: Your User class is trying to do too much. Break it into smaller classes. Aggregate some of your mixins. For example, you may find there are five classes each of which is Followable and Runnable and Flyable. Makes an intermediate class FollowRunFly that derives from those three mixins, then use FollowRunFly in your five classes. Perhaps you don't have to slice your mixins so finely. Make one big mixin, and use it on your classes, and let the code determine at runtime whether the object can fly or be followed. A: Use adapters instead of mixins. So in your case you would have an IFollowable interface and adapters from BookStore or User to IFollowable. See http://ginstrom.com/scribbles/2009/03/27/the-adapter-pattern-in-python/ for one description of adapters in Python and in particular the comments from Martijn Faassen about using factories and interfaces and grokcore.component. A: With paper and pencil, write down the concrete classes that actually get instantiated (e.g. User and BookStore). List all the methods that you want those classes to perform. Only by seeing this list can you rationally decide what class hierarchy best fits your situation. The slowness of writing by hand may force you to think about the relationships between your objects in a new way. Try explaining your classes in detail to an imaginary friend (or us!) who is smart but knows nothing about your problem. The slowness of articulating the details may lead to insight. Mixins may give you a lot of generality to allow your project to grow, but you are often forced to make a compromise between generality (which is complex) and practicality (which is often simpler). Four mixins allows for 2**4 possible concrete classes. If in practice you have far fewer concrete classes, then mixins may not be the right tool for the job. If you feel the generality is overwhelming you, I think it would be wise to back off the generality, freeze the features, and code in the simplest way that accommodates those features. Then, when you have a working product, you can think about adding new features, and refactor if necessary.
Overuse of mixin is evil and what are the alternative solutions?
Sometimes using mixin with multiple inheritance can help us improve reusability of our code. For example, the following design class FollowableMixin(object): def get_followers(self): ... ... class User(FollowableMixin): ... may be better reused than simply adding get_followers to User: class User(object): def get_followers(self): ... ... because later we may consider supporting other followable entities that are potential clients of get_followers: class BookStore(FollowableMixin): ... However, if this pattern is overused, code may get too complex. class User(FollowableMixin, RunnableMixin, FlyableMixin, WhatMixin ...): ... With all these mixin classes injecting properties and methods to your class, it becomes very difficult to understand your code. For example, you don't know where the method you are calling is from, and this method may in turn include an invocation of a method in another mixin ... What should I do to simplify this programme?
[ "Sometimes it can help to collect together related features in a single class if they are often used together.\nclass FooMixin(FollowableMixin, RunnableMixin):\n pass\n\nThen when you come to use it you only have one or two direct base classes instead of many.\nObviously you should only do this if it makes sense...
[ 6, 6, 4, 4 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0003797446_design_patterns_oop_python.txt
Q: python django how can i filter object_set.all by current user in template http://pastebin.com/Aa5rJxv8 i have django problem above, i tried to explain i need to show ratings given by current user to books in user shelves thanks A: One way to do this in the template would be to define a custom filter. This custom filter can accept a queryset and the currently logged in user as arguments and do the necessary filtering. @register.filter def filter_by_user(queryset, user): """Filter the queryset by (currently logged in) user""" return queryset.filter(added_by = user) And in the template: <td>{{ book.rating_set.all|filter_by_user:user|safeseq|join:", " }}</td>
python django how can i filter object_set.all by current user in template
http://pastebin.com/Aa5rJxv8 i have django problem above, i tried to explain i need to show ratings given by current user to books in user shelves thanks
[ "One way to do this in the template would be to define a custom filter. This custom filter can accept a queryset and the currently logged in user as arguments and do the necessary filtering. \n@register.filter\ndef filter_by_user(queryset, user):\n \"\"\"Filter the queryset by (currently logged in) user\"\"\"\n ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003797774_django_python.txt
Q: How to get around error 304 in urllib2, Python For the openers, opener = urllib2.build_opener(), if I try to add an header: request.add_header('if-modified-since',request.headers.get('last-nodified')) I get the error code: Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> feeddata = opener.open(request) File "C:\Python27\lib\urllib2.py", line 391, in open response = self._open(req, data) File "C:\Python27\lib\urllib2.py", line 409, in _open '_open', req) File "C:\Python27\lib\urllib2.py", line 369, in _call_chain result = func(*args) File "C:\Python27\lib\urllib2.py", line 1173, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python27\lib\urllib2.py", line 1142, in do_open h.request(req.get_method(), req.get_selector(), req.data, headers) File "C:\Python27\lib\httplib.py", line 946, in request self._send_request(method, url, body, headers) File "C:\Python27\lib\httplib.py", line 986, in _send_request self.putheader(hdr, value) File "C:\Python27\lib\httplib.py", line 924, in putheader str = '%s: %s' % (header, '\r\n\t'.join(values)) TypeError: sequence item 0: expected string, NoneType found How do you get around this? I tried building a class from urllib2.BaseHandler and it doesn't work. A: Your traceback says: expected string, NoneType found from which I deduce that you've stored a None value as a header. Did you really write 'last-nodified'? The header you mean was probably 'last-modified', but even then you should check that it existed and not re-use it as a header if request.headers.get() returns None.
How to get around error 304 in urllib2, Python
For the openers, opener = urllib2.build_opener(), if I try to add an header: request.add_header('if-modified-since',request.headers.get('last-nodified')) I get the error code: Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> feeddata = opener.open(request) File "C:\Python27\lib\urllib2.py", line 391, in open response = self._open(req, data) File "C:\Python27\lib\urllib2.py", line 409, in _open '_open', req) File "C:\Python27\lib\urllib2.py", line 369, in _call_chain result = func(*args) File "C:\Python27\lib\urllib2.py", line 1173, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python27\lib\urllib2.py", line 1142, in do_open h.request(req.get_method(), req.get_selector(), req.data, headers) File "C:\Python27\lib\httplib.py", line 946, in request self._send_request(method, url, body, headers) File "C:\Python27\lib\httplib.py", line 986, in _send_request self.putheader(hdr, value) File "C:\Python27\lib\httplib.py", line 924, in putheader str = '%s: %s' % (header, '\r\n\t'.join(values)) TypeError: sequence item 0: expected string, NoneType found How do you get around this? I tried building a class from urllib2.BaseHandler and it doesn't work.
[ "Your traceback says: expected string, NoneType found from which I deduce that you've stored a None value as a header. Did you really write 'last-nodified'? The header you mean was probably 'last-modified', but even then you should check that it existed and not re-use it as a header if request.headers.get() returns...
[ 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003797902_python_urllib2.txt
Q: How to select a Radio Button? I am using mechanize and I am trying to select a button from a radio button list. This list has 5 items. How can I select the first item? Docs didn't help me. >>> br.form <ClientForm.HTMLForm instance at 0x9ac0d4c> >>> print(br.form) <form1 POST http://www.example.com application/x-www-form-urlencoded <HiddenControl(DD=17010200) (readonly)> <RadioControl(prodclass=[1, 2, 3, 4, 5])> <SubmitControl(submit=text) (readonly)>> A: It should be as simple as br.form['prodclass'] = ['1'] I prefer the more verbose: br.form.set_value(['1'],name='prodclass')
How to select a Radio Button?
I am using mechanize and I am trying to select a button from a radio button list. This list has 5 items. How can I select the first item? Docs didn't help me. >>> br.form <ClientForm.HTMLForm instance at 0x9ac0d4c> >>> print(br.form) <form1 POST http://www.example.com application/x-www-form-urlencoded <HiddenControl(DD=17010200) (readonly)> <RadioControl(prodclass=[1, 2, 3, 4, 5])> <SubmitControl(submit=text) (readonly)>>
[ "It should be as simple as\nbr.form['prodclass'] = ['1']\n\nI prefer the more verbose:\nbr.form.set_value(['1'],name='prodclass')\n\n" ]
[ 13 ]
[]
[]
[ "mechanize", "python", "radio_button" ]
stackoverflow_0003798138_mechanize_python_radio_button.txt
Q: Combining a url with urlunparse I'm writing something to 'clean' a URL. In this case all I'm trying to do is return a faked scheme as urlopen won't work without one. However, if I test this with www.python.org It'll return http:///www.python.org. Does anyone know why the extra /, and is there a way to return this without it? def FixScheme(website): from urlparse import urlparse, urlunparse scheme, netloc, path, params, query, fragment = urlparse(website) if scheme == '': return urlunparse(('http', netloc, path, params, query, fragment)) else: return website A: Problem is that in parsing the very incomplete URL www.python.org, the string you give is actually taken as the path component of the URL, with the netloc (network location) one being empty as well as the scheme. For defaulting the scheme you can actually pass a second parameter scheme to urlparse (simplifying your logic) but that does't help with the "empty netloc" problem. So you need some logic for that case, e.g. if not netloc: netloc, path = path, '' A: It's because urlparse is interpreting "www.python.org" not as the hostname (netloc), but as the path, just as a browser would if it encountered that string in an href attribute. Then urlunparse seems to interpret scheme "http" specially. If you put in "x" as the scheme, you'll get "x:www.python.org". I don't know what range of inputs you're dealing with, but it looks like you might not want urlparse and urlunparse.
Combining a url with urlunparse
I'm writing something to 'clean' a URL. In this case all I'm trying to do is return a faked scheme as urlopen won't work without one. However, if I test this with www.python.org It'll return http:///www.python.org. Does anyone know why the extra /, and is there a way to return this without it? def FixScheme(website): from urlparse import urlparse, urlunparse scheme, netloc, path, params, query, fragment = urlparse(website) if scheme == '': return urlunparse(('http', netloc, path, params, query, fragment)) else: return website
[ "Problem is that in parsing the very incomplete URL www.python.org, the string you give is actually taken as the path component of the URL, with the netloc (network location) one being empty as well as the scheme. For defaulting the scheme you can actually pass a second parameter scheme to urlparse (simplifying yo...
[ 9, 1 ]
[]
[]
[ "python", "urlparse" ]
stackoverflow_0003798269_python_urlparse.txt
Q: object oriented programming basics: inheritance & shadowing (Python) Level: Beginner I'm doing my first steps in Object Oriented programming. The code is aimed at showing how methods are passed up the chain. So when i call UG.say(person, 'but i like') the method say is instructed to call class MITPerson. Given that MITPerson does not contain a say method it will pass it up to class Person. I think there is nothing wrong with the code as it is part of a lecture (see source below). I think it is me who is omitting to define something when i run the code. Not sure what though. I think that the UG instance the error message is looking for as first argument is refering to self but that, in principle, doesn't need to be provided, correct? Any hints? class Person(object): def __init__(self, family_name, first_name): self.family_name = family_name self.first_name = first_name def familyName(self): return self.family_name def firstName(self): return self.first_name def say(self,toWhom,something): return self.first_name + ' ' + self.family_name + ' says to ' + toWhom.firstName() + ' ' + toWhom.familyName() + ': ' + something class MITPerson(Person): def __init__(self, familyName, firstName): Person.__init__(self, familyName, firstName) class UG(MITPerson): def __init__(self, familyName, firstName): MITPerson.__init__(self, familyName, firstName) self.year = None def say(self,toWhom,something): return MITPerson.say(self,toWhom,'Excuse me, but ' + something) >>> person = Person('Jon', 'Doe') >>> person_mit = MITPerson('Quin', 'Eil') >>> ug = UG('Dylan', 'Bob') >>> UG.say(person, 'but i like') UG.say(person, 'bla') **EDIT (for completeness)**: it should say UG.say(person, 'but i like') #the 'bla' creeped in from a previous test TypeError: unbound method say() must be called with UG instance as first argument (got Person instance instead) source: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008 A: You are calling class instead of instance. >>> ug = UG('Dylan', 'Bob') >>> UG.say(person, 'but i like') UG.say(person, 'bla') Call instance instead >>> ug = UG('Dylan', 'Bob') >>> ug.say(person, 'but i like') A: The answers are quite fine, but there's a side note I think is important to make. Take the snippet (in class MITPerson): def __init__(self, familyName, firstName): Person.__init__(self, familyName, firstName) This code is completely useless and redundant. When a subclass does not need to override anything in its superclass's implementation of a method, it's totally useless for the subclass to look like it's "overriding" that method... and then just delegate all the work, without any changes, to the superclass anyway. Code which has absolutely no purpose, can never make any difference (except marginally slowing down the whole system), and can therefore be removed without any harm, should be removed: why have it there at all?! Any code that's present in your program, but not at all useful, is inevitably hurting the quality of your program: such useless "ballast" dilutes the useful, working code, making your program harder to read, maintain, debug, and so on. Most people seem to grasp this intuitively in most situations (so you don't see a lot of code around which "fake-overrides" most methods but in the method body just punts to the superclass implementation) except for __init__ -- where many, for some reason, seem to have a mental blind spot and just can't see that exactly the same rule applies as for other methods. This blind spot may come from being familiar with other, completely different languages, where the rule does not apply to a class's constructor, plus a misconception that sees __init__ as a constructor where it actually isn't (it's an initializer). So, to summarize: a subclass should define __init__ if, and only if, it needs to do something else before, or after, or both before and after, the superclass's own initializer (very rarely it may want to do something instead, i.e., not delegate to the superclass initializer at all, but that's hardly ever good practice). If the subclass's __init__ body has just a call to the superclass's __init__, with exactly the same parameters in the same order, expunge the subclass's __init__ from your code (just as you would do for any other similarly-redundant method). A: Change UG.say(person, 'but i like') to ug.say(person, 'but i like') UG.say returns the unbound method say. "Unbound" implies that the first argument to say is not automatically filled in for you. The unbound method say takes 3 arguments, and the first one must be an instance of UG. Instead, UG.say(person, 'but i like') sends an instance of Person as the first argument. This explains the error message Python gives to you. In contrast, ug.say returns the bound method say. "Bound" implies that the first argument to say will be ug. The bound method takes 2 arguments, toWhom and something. Thus, ug.say(person, 'but i like') works as expected. The concept of unbound method has been removed from Python3. Instead, UG.say just returns a function which (still) expects 3 arguments. The only difference is that there is no more type checking on the first argument. You'll still end up with an error, however, just a different one: TypeError: say() takes exactly 3 positional arguments (2 given) PS. When beginning to learn Python, I think I'd just try to accept that UG.say returns an unbound method (expecting 3 arguments), and ug.say is the normal proper way to call a method (expecting 2 arguments). Later, to really learn how Python implements this difference of behavior (while maintaining the same qualified name syntax), you'll want to research descriptors and the rules of attribute lookup. A: OK, time for a short tutorial on Python methods. When you define a functions inside a class: >>> class MITPerson: ... def say(self): ... print ("I am an MIT person.") ... >>> class UG(MITPerson): ... def say(self): ... print ("I am an MIT undergrad.") ... and then retrieve that function using a dotted lookup, you get a special object back called a "bound method", in which the first argument is automatically passed through to the function as the instance upon which it is called. See: >>> ug = UG() >>> ug.say <bound method UG.say of <__main__.UG object at 0x022359D0>> But, since that function was also defined on the class, you can look it up through the class instead of through a specific instance. If you do that, though, you won't get a bound method (obviously -- there's nothing to bind!). You'll get the original function, to which you need to pass the instance that you want to call it on: >>> UG.say() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method say() must be called with UG instance as first argument (got nothing instead) >>> ug.say() I am an MIT undergrad. >>> UG.say(ug) I am an MIT undergrad. The first call fails, since the function say expects an instance of UG as its first argument and gets nothing. The second call automatically binds the first argument, so it works; the third manually passes the instance you want to use. The second and third are equivalent. There's one more thing to mention, which is that it doesn't seem like the say function actually needs the instance of UG which is doing the saying. If not, you can register it as a "static method", which tells Python not to bind the first attribute: >>> class UG: ... @staticmethod ... def say(): ... print("foo") ... >>> ug = UG() >>> UG.say() foo >>> ug.say() foo
object oriented programming basics: inheritance & shadowing (Python)
Level: Beginner I'm doing my first steps in Object Oriented programming. The code is aimed at showing how methods are passed up the chain. So when i call UG.say(person, 'but i like') the method say is instructed to call class MITPerson. Given that MITPerson does not contain a say method it will pass it up to class Person. I think there is nothing wrong with the code as it is part of a lecture (see source below). I think it is me who is omitting to define something when i run the code. Not sure what though. I think that the UG instance the error message is looking for as first argument is refering to self but that, in principle, doesn't need to be provided, correct? Any hints? class Person(object): def __init__(self, family_name, first_name): self.family_name = family_name self.first_name = first_name def familyName(self): return self.family_name def firstName(self): return self.first_name def say(self,toWhom,something): return self.first_name + ' ' + self.family_name + ' says to ' + toWhom.firstName() + ' ' + toWhom.familyName() + ': ' + something class MITPerson(Person): def __init__(self, familyName, firstName): Person.__init__(self, familyName, firstName) class UG(MITPerson): def __init__(self, familyName, firstName): MITPerson.__init__(self, familyName, firstName) self.year = None def say(self,toWhom,something): return MITPerson.say(self,toWhom,'Excuse me, but ' + something) >>> person = Person('Jon', 'Doe') >>> person_mit = MITPerson('Quin', 'Eil') >>> ug = UG('Dylan', 'Bob') >>> UG.say(person, 'but i like') UG.say(person, 'bla') **EDIT (for completeness)**: it should say UG.say(person, 'but i like') #the 'bla' creeped in from a previous test TypeError: unbound method say() must be called with UG instance as first argument (got Person instance instead) source: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008
[ "You are calling class instead of instance.\n>>> ug = UG('Dylan', 'Bob')\n>>> UG.say(person, 'but i like')\n\n\nUG.say(person, 'bla')\n\nCall instance instead\n>>> ug = UG('Dylan', 'Bob')\n>>> ug.say(person, 'but i like')\n\n", "The answers are quite fine, but there's a side note I think is important to make. Ta...
[ 4, 3, 2, 2 ]
[]
[]
[ "inheritance", "oop", "python", "shadowing" ]
stackoverflow_0003798194_inheritance_oop_python_shadowing.txt
Q: Write MP3 in Python I have a bunch of frames (generated by a function) that I want to write to a MP3 file using Python. I tried using pymedia but I always get a Segmentation fault. Doe anyone know an extension to write MP3 files using Python? Thanks! A: If you're on Gnome, soundconverter might help; but I don't know of a stand-alone equivalent.
Write MP3 in Python
I have a bunch of frames (generated by a function) that I want to write to a MP3 file using Python. I tried using pymedia but I always get a Segmentation fault. Doe anyone know an extension to write MP3 files using Python? Thanks!
[ "If you're on Gnome, soundconverter might help; but I don't know of a stand-alone equivalent.\n" ]
[ 2 ]
[]
[]
[ "file", "mp3", "python" ]
stackoverflow_0003798386_file_mp3_python.txt
Q: Why urllib2.urlopen can not open pages like "http://localhost/new-post#comment-29"? I'm curious, how come I get 404 error running this line: urllib2.urlopen("http://localhost/new-post#comment-29") While everything works fine surfing http://localhost/new-post#comment-29 in any browser... urlopen method does not parse urls with "#" in it? Anybody knows? A: In the HTTP protocol, the fragment (from # onwards) is not sent to the server across the network: it's locally retained by the browser and used, once the server's response is fully received, to somehow "visually locate" the exact spot in the page to be shown as "current" (for example, if the returned page is in HTML, this will be done by parsing the HTML and looking for the first suitable <a> flag). So, the procedure is: remove the fragment e.g. via urlparse.urlparse; use the rest to fetch the resource; parse it appropriately based on the server response's content-type header; then take whatever visual action your program does regarding the "current spot" on the resource, based on locating within the parsed resource the fragment you retained in the first step.
Why urllib2.urlopen can not open pages like "http://localhost/new-post#comment-29"?
I'm curious, how come I get 404 error running this line: urllib2.urlopen("http://localhost/new-post#comment-29") While everything works fine surfing http://localhost/new-post#comment-29 in any browser... urlopen method does not parse urls with "#" in it? Anybody knows?
[ "In the HTTP protocol, the fragment (from # onwards) is not sent to the server across the network: it's locally retained by the browser and used, once the server's response is fully received, to somehow \"visually locate\" the exact spot in the page to be shown as \"current\" (for example, if the returned page is i...
[ 7 ]
[]
[]
[ "fragment_identifier", "python", "urllib2", "urlopen" ]
stackoverflow_0003798422_fragment_identifier_python_urllib2_urlopen.txt
Q: Using Both jQuery And FormEncode To Validate Forms Without Repetition I'm working on a Pylons-based web app. Because I am sane, I am using jQuery (and plugins) instead of writing raw JavaScript. I am also using FormEncode to validate forms for my app (especially new user registration). FormEncode is great for validating forms after they're submitted. jQuery, when JavaScript is available, validates forms quite well before they're submitted. I'm greedy: I want to use both kinds of validation - and I don't want to repeat myself. If there are two sets of validation rules, there's an extra workload generated by keeping them in sync. How can I use jQuery to access my FormEncode validation rules, so that both jQuery and FormEncode investigate form data based on the same rules without having to write the rules down twice ? A: My current solution is to have the FormEncode rules in the controller, and to give the controller one method that responds to a complete form being submitted, and another method that responds to AJAX requests, and validate both methods again the same FormEncode rules. That means that I can have jQuery make requests to the controller's AJAX-y method, and have regular form submissions go to the controller's normal form-submission method, and in both cases the same set of form-validation rules will be applied.
Using Both jQuery And FormEncode To Validate Forms Without Repetition
I'm working on a Pylons-based web app. Because I am sane, I am using jQuery (and plugins) instead of writing raw JavaScript. I am also using FormEncode to validate forms for my app (especially new user registration). FormEncode is great for validating forms after they're submitted. jQuery, when JavaScript is available, validates forms quite well before they're submitted. I'm greedy: I want to use both kinds of validation - and I don't want to repeat myself. If there are two sets of validation rules, there's an extra workload generated by keeping them in sync. How can I use jQuery to access my FormEncode validation rules, so that both jQuery and FormEncode investigate form data based on the same rules without having to write the rules down twice ?
[ "My current solution is to have the FormEncode rules in the controller, and to give the controller one method that responds to a complete form being submitted, and another method that responds to AJAX requests, and validate both methods again the same FormEncode rules. That means that I can have jQuery make reques...
[ 2 ]
[]
[]
[ "ajax", "formencode", "jquery", "python", "validation" ]
stackoverflow_0003773714_ajax_formencode_jquery_python_validation.txt
Q: Scraping Flash: accessing background files, perhaps in Mechanize? I'm scraping a website in Flash, writing in Python. I can see in Firebug that the page loads its Flash file and then some background data in an .asmx file. The background data is what I'm interested in - so how can I get hold of the .asmx file? I already know what it's called. I can't get at the .asmx file directly, but can I grab it using Mechanize? --- UPDATE ---- The page I'm scraping is http://www.citroen.co.uk/new-cars/car-range/#/configurator/1C58AF/pop/pre-configuration/ The .asmx file is https://sfg-bpf.servicesgp.mpsa.com/uk/services/ServicePSAGF_Dealer.asmx - I can view it in Firebug. A: can I grab it using Mechanize? I don't believe so. The .asmx extension says that the resource you are accessing is a (SOAP-based) .NET Web service, written in a language such as C# or VB.NET. Normally the .asmx code would return a SOAP response, perhaps to be parsed by the Flash application. But it's hard to see what's going on without a little more detail - for example, whether the .asmx request is a separate Ajax request. Update: The link to the Flash page doesn't work for me now; it worked once, then subsequent requests get redirected to an error page. The .asmx page you linked to just shows the entry point to the Web service; you'd have to make a request to a specific entry point with appropriate parameters to get the actual XML data (assuming of course that you're authorised).
Scraping Flash: accessing background files, perhaps in Mechanize?
I'm scraping a website in Flash, writing in Python. I can see in Firebug that the page loads its Flash file and then some background data in an .asmx file. The background data is what I'm interested in - so how can I get hold of the .asmx file? I already know what it's called. I can't get at the .asmx file directly, but can I grab it using Mechanize? --- UPDATE ---- The page I'm scraping is http://www.citroen.co.uk/new-cars/car-range/#/configurator/1C58AF/pop/pre-configuration/ The .asmx file is https://sfg-bpf.servicesgp.mpsa.com/uk/services/ServicePSAGF_Dealer.asmx - I can view it in Firebug.
[ "\ncan I grab it using Mechanize?\n\nI don't believe so. The .asmx extension says that the resource you are accessing is a (SOAP-based) .NET Web service, written in a language such as C# or VB.NET. Normally the .asmx code would return a SOAP response, perhaps to be parsed by the Flash application. But it's hard to ...
[ 1 ]
[]
[]
[ "flash", "mechanize", "python" ]
stackoverflow_0003799000_flash_mechanize_python.txt
Q: How can I monitor mouse events with Python Xlib instead of capture them? I need to monitor and filter mouse events with Xlib in Python. So far I have found out that this code receives events, but does not pass them on, so I can't actually do anything with the mouse anymore. from Xlib.display import Display from Xlib import X display = Display(':0') root = display.screen().root root.grab_pointer(True, X.ButtonPressMask | X.ButtonReleaseMask, X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime) while True: print "Event:" print display.next_event() Alternatives I found are using root.change_attributes(event_mask=X.ButtonPressMask | X.ButtonReleaseMask) Which does not work at all or using the RECORD extension to Xlib, which I can't figure out how it works. A: The link was broken. I think this is the latest one: http://github.com/pepijndevos/PyMouse/blob/master/pymouse/unix.py Line 58 A: The answer seemed to be to use Xlib with RECORD, the result can be seen here: http://github.com/pepijndevos/PyMouse/blob/master/unix.py#L38
How can I monitor mouse events with Python Xlib instead of capture them?
I need to monitor and filter mouse events with Xlib in Python. So far I have found out that this code receives events, but does not pass them on, so I can't actually do anything with the mouse anymore. from Xlib.display import Display from Xlib import X display = Display(':0') root = display.screen().root root.grab_pointer(True, X.ButtonPressMask | X.ButtonReleaseMask, X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime) while True: print "Event:" print display.next_event() Alternatives I found are using root.change_attributes(event_mask=X.ButtonPressMask | X.ButtonReleaseMask) Which does not work at all or using the RECORD extension to Xlib, which I can't figure out how it works.
[ "The link was broken. I think this is the latest one: http://github.com/pepijndevos/PyMouse/blob/master/pymouse/unix.py Line 58\n", "The answer seemed to be to use Xlib with RECORD, the result can be seen here:\nhttp://github.com/pepijndevos/PyMouse/blob/master/unix.py#L38\n" ]
[ 2, 0 ]
[]
[]
[ "event_handling", "python", "xlib" ]
stackoverflow_0002585647_event_handling_python_xlib.txt
Q: How is possible to create a python shell script like top unix command? I'm need to create a Python shell script that refresh output every n seconds like top unix command. what 's the best way to do this? A: One way to do this is to write a script that prints your output (once), and then run your script using the watch command. The watch command will automatically clear the screen and run your script every few seconds (usually 2 by default). If you really want to do this in pure Python, you can use the curses module, or if you know your terminal is VT100-compatible you can go considerably simpler: print "\x1b[H\x1b[2J", print "hello clear world"
How is possible to create a python shell script like top unix command?
I'm need to create a Python shell script that refresh output every n seconds like top unix command. what 's the best way to do this?
[ "One way to do this is to write a script that prints your output (once), and then run your script using the watch command. The watch command will automatically clear the screen and run your script every few seconds (usually 2 by default).\nIf you really want to do this in pure Python, you can use the curses module,...
[ 4 ]
[]
[]
[ "cmd", "python", "shell" ]
stackoverflow_0003799400_cmd_python_shell.txt
Q: Help with XML parsing in Python I have a XML file which contains 100s of documents inside . Each block looks like this: <DOC> <DOCNO> FR940104-2-00001 </DOCNO> <PARENT> FR940104-2-00001 </PARENT> <TEXT> <!-- PJG FTAG 4703 --> <!-- PJG STAG 4703 --> <!-- PJG ITAG l=90 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=90 g=1 f=4 --> Federal Register <!-- PJG /ITAG --> <!-- PJG ITAG l=90 g=1 f=1 --> / Vol. 59, No. 2 / Tuesday, January 4, 1994 / Notices <!-- PJG 0012 frnewline --> <!-- PJG /ITAG --> <!-- PJG ITAG l=01 g=1 f=1 --> Vol. 59, No. 2 <!-- PJG 0012 frnewline --> <!-- PJG /ITAG --> <!-- PJG ITAG l=02 g=1 f=1 --> Tuesday, January 4, 1994 <!-- PJG 0012 frnewline --> <!-- PJG 0012 frnewline --> <!-- PJG /ITAG --> <!-- PJG /STAG --> <!-- PJG /FTAG --> </TEXT> </DOC> I want load this XML doc into a dictionary Text. Key as DOCNO & Value as text inside tags. Also this text should not contain all the comments. Example Text['FR940104-2-00001'] must contain Federal Register / Vol. 59, No. 2 / Tuesday, January 4, 1994 / Notices Vol. 59, No. 2 Tuesday, January 4, 1994. This is the code I wrote. L = doc.getElementsByTagName("DOCNO") for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: docno.append(node3.data); #print node2.data L = doc.getElementsByTagName("TEXT") i = 0 for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: Text[docno[i]] = node3.data i = i+1 Surprisingly, with my code I'm getting Text['FR940104-2-00001'] as u'\n' How come?? How to get what I want A: You could avoid looping through the doc twice by using xml.sax.handler: import xml.sax.handler import collections class DocBuilder(xml.sax.handler.ContentHandler): def __init__(self): self.state='' self.docno='' self.text=collections.defaultdict(list) def startElement(self, name, attrs): self.state=name def endElement(self, name): if name==u'TEXT': self.docno='' def characters(self,content): content=content.strip() if content: if self.state==u'DOCNO': self.docno+=content elif self.state==u'TEXT': if content: self.text[self.docno].append(content) with open('test.xml') as f: data=f.read() builder = DocBuilder() xml.sax.parseString(data, builder) for key,value in builder.text.iteritems(): print('{k}: {v}'.format(k=key,v=' '.join(value))) # FR940104-2-00001: Federal Register / Vol. 59, No. 2 / Tuesday, January 4, 1994 / Notices Vol. 59, No. 2 Tuesday, January 4, 1994 A: Similar to unutbu's answer, though I think simpler: from lxml import etree with open('test.xml') as f: doc=etree.parse(f) result={} for elm in doc.xpath("/DOC[DOCNO]"): key = elm.xpath("DOCNO")[0].text.strip() value = "".join(t.strip() for t in elm.xpath("TEXT/text()") if t.strip()) result[key] = value The XPath that finds the DOC element in this example needs to be changed to be appropriate for your real document - e.g. if there's a single top-level element that all the DOC elements are children of, you'd change it to /*/DOC. The predicate on that XPath skips any DOC element that doesn't have a DOCNO child, which would otherwise cause an exception when setting the key. A: Using lxml: import lxml.etree as le with open('test.xml') as f: doc=le.parse(f) texts={} for docno in doc.xpath('DOCNO'): docno_text=docno.text.strip() text=' '.join([t.strip() for t in docno.xpath('following-sibling::TEXT[1]/text()') if t.strip()]) texts[docno.text]=text print(texts) # {'FR940104-2-00001': 'Federal Register / Vol. 59, No. 2 / Tuesday, January 4, 1994 / Notices Vol. 59, No. 2 Tuesday, January 4, 1994'} This version is a tad simpler than my first lxml solution. It handles multiple instances of DOCNO, TEXT nodes. The DOCNO/TEXT nodes should alternate, but in any case, the DOCNO is associated with the closest TEXT node that follows it. A: Your line Text[docno[i]] = node3.data replaces the value of the mapping instead of appending the new one. Your <TEXT> node has both text and comment children, interleaved with each other. A: DOM parser strips out the comments automatically for you. Each line is a Node. So, You need to use: Text[docno[i]]+= node3.data but before that you need to have an empty dictionary with all the keys. So, you can add Text[node3.data] = ''; in your first block of code. So, your code becomes: L = doc.getElementsByTagName("DOCNO") for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: docno.append(node3.data); Text[node3.data] = ''; #print node2.data L = doc.getElementsByTagName("TEXT") i = 0 for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: Text[docno[i]]+= node3.data i = i+1
Help with XML parsing in Python
I have a XML file which contains 100s of documents inside . Each block looks like this: <DOC> <DOCNO> FR940104-2-00001 </DOCNO> <PARENT> FR940104-2-00001 </PARENT> <TEXT> <!-- PJG FTAG 4703 --> <!-- PJG STAG 4703 --> <!-- PJG ITAG l=90 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=90 g=1 f=4 --> Federal Register <!-- PJG /ITAG --> <!-- PJG ITAG l=90 g=1 f=1 --> / Vol. 59, No. 2 / Tuesday, January 4, 1994 / Notices <!-- PJG 0012 frnewline --> <!-- PJG /ITAG --> <!-- PJG ITAG l=01 g=1 f=1 --> Vol. 59, No. 2 <!-- PJG 0012 frnewline --> <!-- PJG /ITAG --> <!-- PJG ITAG l=02 g=1 f=1 --> Tuesday, January 4, 1994 <!-- PJG 0012 frnewline --> <!-- PJG 0012 frnewline --> <!-- PJG /ITAG --> <!-- PJG /STAG --> <!-- PJG /FTAG --> </TEXT> </DOC> I want load this XML doc into a dictionary Text. Key as DOCNO & Value as text inside tags. Also this text should not contain all the comments. Example Text['FR940104-2-00001'] must contain Federal Register / Vol. 59, No. 2 / Tuesday, January 4, 1994 / Notices Vol. 59, No. 2 Tuesday, January 4, 1994. This is the code I wrote. L = doc.getElementsByTagName("DOCNO") for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: docno.append(node3.data); #print node2.data L = doc.getElementsByTagName("TEXT") i = 0 for node2 in L: for node3 in node2.childNodes: if node3.nodeType == Node.TEXT_NODE: Text[docno[i]] = node3.data i = i+1 Surprisingly, with my code I'm getting Text['FR940104-2-00001'] as u'\n' How come?? How to get what I want
[ "You could avoid looping through the doc twice by using xml.sax.handler:\nimport xml.sax.handler\nimport collections\n\n\nclass DocBuilder(xml.sax.handler.ContentHandler):\n def __init__(self):\n self.state=''\n self.docno=''\n self.text=collections.defaultdict(list)\n def startElement(se...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003795984_python_xml.txt
Q: "Zero Iteration" - end to end acceptance test in simple contact-form feature I was reading "Growing Object-Oriented Software, Guided by Tests" lately. Authors of this book sugested to always start developing a feature with an end-to-end acceptance test (before starting TDD cycle) to not loose a track of progress and to make sure that you're still on the same page while unit-testing. Ok, so I've start writing a veeeery simple application in python+django just to try this approach out. I want User to be able to ask a question via contact-form, the question should be then stored in a db, and a signal after completion should be send to notify mailer which will send follow-up message. Question is - how you'd approach this first end-to-end test in this case? Do you have contain all possibilities in this first test, or maybe I'm misunderstanding this whole technique. Any examples would be most welcome. A: You don't have to contain all possibilities in acceptance tests at all - you will still write unit tests. So I would say that a single tests "user can fill in the form, save it and load it back" is enough to start with. Then you can add more tests if you think that a particular aspect of your system is important enough that it needs an acceptance tests. Don't worry about handling all possibilities here, you will still write tons of unit tests where you will test everything! The easiest way to start is to grow your acceptance test in parallel with the code: so start with testing that the user can input data, implement it until it stops failing, then add to the test the condition that the user has to load this data back etc. It will take a while to implement the initial infrastructure for the acceptance test, before you even start writing production code, but you can't escape from it anyway, and there are various benefits to have tests upfront. A: This use-case leads to several test-cases (every tests a dedicated possible path of execution). When writing tests focus on one possible outcome, after a while test-suite grows. The first tests then also give you safety net as regression tests to not break anything which you already implemented successfully. My first tests would be: Happy path 1st part frontend-form + controller layer: User passes correct data, controller take the form and log to console/stdout Happy path 2nd part: Instead of logging to stdout, things get stored to database Happy path 3rd part: Follow-up mail gets sent and received by User Validation error handling (user fills form out incorrectly, e.g. misses mandatory fields, wrong email-pattern) ... Fill out the rest ;) Depends on the more detailed requirements... Remember to implement above as simple as possible. When all tests are in place, refactor ruthlessly to make "internal quality" nice.
"Zero Iteration" - end to end acceptance test in simple contact-form feature
I was reading "Growing Object-Oriented Software, Guided by Tests" lately. Authors of this book sugested to always start developing a feature with an end-to-end acceptance test (before starting TDD cycle) to not loose a track of progress and to make sure that you're still on the same page while unit-testing. Ok, so I've start writing a veeeery simple application in python+django just to try this approach out. I want User to be able to ask a question via contact-form, the question should be then stored in a db, and a signal after completion should be send to notify mailer which will send follow-up message. Question is - how you'd approach this first end-to-end test in this case? Do you have contain all possibilities in this first test, or maybe I'm misunderstanding this whole technique. Any examples would be most welcome.
[ "You don't have to contain all possibilities in acceptance tests at all - you will still write unit tests. So I would say that a single tests \"user can fill in the form, save it and load it back\" is enough to start with. Then you can add more tests if you think that a particular aspect of your system is important...
[ 1, 0 ]
[]
[]
[ "bdd", "django", "python", "tdd", "unit_testing" ]
stackoverflow_0003798629_bdd_django_python_tdd_unit_testing.txt
Q: Python: How to use os.spawnv with a lot of arguments? Im working in a Python plugin for XBMC (xbmc.org) and I want to execute a program (ffmpeg.exe) from my plugin without the cmd window appears. If I use os.system() to call ffmpeg.exe works fine but the xbmc minimizes because os.system open a cmd window a few seconds. So, I try to use os.spawnv() that I think its possible that allow me to call ffmpeg.exe without cmd window appears. The problem is I know how to use os.system but I dont know how to use os.spawnv. Im trying this, but doesnt work: os.spawnv(os.P_DETACH,'"C:\Program Files (x86)\XBMC\scripts\Base De Datos\ffmpeg.exe" -y -ss 30 -i "C:\Program Files (x86)\XBMC\scripts\Base De Datos\Movie.avi" -f mjpeg -vframes 1 -s 720x400 -an "C:\Program Files (x86)\XBMC\scripts\Base De Datos\thumbnail.jpg"') "C:\Program Files (x86)\XBMC\scripts\Base De Datos\ffmpeg.exe" = The path of the ffmpeg.exe -y -ss 30 -i = Arguments for ffmpeg.exe "C:\Program Files (x86)\XBMC\scripts\Base De Datos\Movie.avi" = The path of the movie I want to use with ffmpeg.exe to make a thumbnail (argument for ffmpeg.exe) -f mjpeg -vframes 1 -s 720x400 = More arguments for ffmpeg.exe "C:\Program Files (x86)\XBMC\scripts\Base De Datos\thumbnail.jpg" = The path for save the thumbnail. I trying a lot of methods to make a thumbnail but its seems to me there is really complicated in a xbmc plugin, I cannot use pyffmpeg because I cannot import the module from my plugin without installing it into de S.O. and my plugin must be portable, I could use PIL but only could make thumbnails of pictures and I need to make thumbnails of videos. I know some modules in python that allow me to call process without cmd window appears but depends of others modules like win32api that I cannot import for the same reasons I cannot use/import pyffmpeg... so I triying the "bad way" using this method, with os.system works but I loose control of my plugin window. If someone know other way to make a thumbnail of a video using python, please tell me. The other matter is my plugin must be multiplataform (Win and Linux at least) so this way is not good enought but it could be a big step for me. Thanks a lot. A: As per http://docs.python.org/library/os.html#os.spawnv, pass the arguments in a list: os.spawnv(os.P_DETACH, "path\to\program.exe", ["arg1", "arg2", "arg3"])
Python: How to use os.spawnv with a lot of arguments?
Im working in a Python plugin for XBMC (xbmc.org) and I want to execute a program (ffmpeg.exe) from my plugin without the cmd window appears. If I use os.system() to call ffmpeg.exe works fine but the xbmc minimizes because os.system open a cmd window a few seconds. So, I try to use os.spawnv() that I think its possible that allow me to call ffmpeg.exe without cmd window appears. The problem is I know how to use os.system but I dont know how to use os.spawnv. Im trying this, but doesnt work: os.spawnv(os.P_DETACH,'"C:\Program Files (x86)\XBMC\scripts\Base De Datos\ffmpeg.exe" -y -ss 30 -i "C:\Program Files (x86)\XBMC\scripts\Base De Datos\Movie.avi" -f mjpeg -vframes 1 -s 720x400 -an "C:\Program Files (x86)\XBMC\scripts\Base De Datos\thumbnail.jpg"') "C:\Program Files (x86)\XBMC\scripts\Base De Datos\ffmpeg.exe" = The path of the ffmpeg.exe -y -ss 30 -i = Arguments for ffmpeg.exe "C:\Program Files (x86)\XBMC\scripts\Base De Datos\Movie.avi" = The path of the movie I want to use with ffmpeg.exe to make a thumbnail (argument for ffmpeg.exe) -f mjpeg -vframes 1 -s 720x400 = More arguments for ffmpeg.exe "C:\Program Files (x86)\XBMC\scripts\Base De Datos\thumbnail.jpg" = The path for save the thumbnail. I trying a lot of methods to make a thumbnail but its seems to me there is really complicated in a xbmc plugin, I cannot use pyffmpeg because I cannot import the module from my plugin without installing it into de S.O. and my plugin must be portable, I could use PIL but only could make thumbnails of pictures and I need to make thumbnails of videos. I know some modules in python that allow me to call process without cmd window appears but depends of others modules like win32api that I cannot import for the same reasons I cannot use/import pyffmpeg... so I triying the "bad way" using this method, with os.system works but I loose control of my plugin window. If someone know other way to make a thumbnail of a video using python, please tell me. The other matter is my plugin must be multiplataform (Win and Linux at least) so this way is not good enought but it could be a big step for me. Thanks a lot.
[ "As per http://docs.python.org/library/os.html#os.spawnv, pass the arguments in a list:\nos.spawnv(os.P_DETACH, \"path\\to\\program.exe\", [\"arg1\", \"arg2\", \"arg3\"])\n\n" ]
[ 0 ]
[ "This way:\nos.system(\"\"C:\\\\Program Files (x86)\\\\XBMC\\\\scripts\\\\Base De Datos\\\\ffmpeg.exe\" -y -ss 423 -i \"C:\\Program Files (x86)\\XBMC\\scripts\\Base De Datos\\Movie.avi\" -f mjpeg -vframes 1 -s 720x320 -an \"C:/Program Files (x86)/XBMC/scripts/Base De Datos/thumbnail.jpg\"\")\n\nWorks fine but minim...
[ -1 ]
[ "ffmpeg", "python", "thumbnails" ]
stackoverflow_0003799531_ffmpeg_python_thumbnails.txt
Q: Python - Best way to compare two strings, record stats comparing serial position of particular item? I'm dealing with two files, both of which have lines that look like the following: This is || an example || line . In one of the files, the above line would appear, whereas the corresponding line in the other file would be identical BUT might have the '||' items in a different position: This || is an || example || line . I just need to collect stats for how often a "||" fell in the "right" place in the second file (we're assuming the first file is always "right"), how often a "||" fell in a place where the first file didn't have a "||", and how the number of overall "||" markers differed for that particular line. I know I could do this alone, but wondered if you brilliant folks knew some incredibly easy way of doing this? The basic stuff (such as reading the files in) is all stuff I'm familiar with--I'm really just looking for advice on how to do the actual comparisons of lines and collect the stats! Best, Georgina A: Is this what you are looking for? This code assumes that every line is formatted in the same way as in your examples fileOne = open('theCorrectFile', 'r') fileTwo = open('theSecondFile', 'r') for corrrectLine in fileOne: otherLine = fileTwo.readline() for i in len(correctLine.split("||")): count = 0 wrongPlacement = 0 if (len(otherLine.split("||")) >= i+1) and (correctLine.split("||")[i] == otherLine.split("||")[i]): count += 1 else: wrongPLacement += 1 print 'there are %d out of %d "||" in the correct places and %d in the wrong places' %(count, len(correctLine.split("||"), wrongPlacement) A: I'm not sure how easy this is, since it does make use of some more advanced concepts like generators, but it's at least robust and well-documented. The actual code is at the bottom and is fairly concise. The basic idea is that the function iter_delim_sets returns an iterator over (aka a sequence of) tuples containing the line number, the set of indices in the "expected" string where the delimiter was found, and a similar set for the "actual" string. There's one such tuple generated for each pair of (expected, result) lines. Those tuples are succinctly formalized into a collections.namedtuple type called DelimLocations. Then the function analyze just returns higher-level information based on such a data set, stored in a DelimAnalysis namedtuple. This is done using basic set algebra. """Compare two sequences of strings. Test data: >>> from pprint import pprint >>> delimiter = '||' >>> expected = ( ... delimiter.join(("one", "fish", "two", "fish")), ... delimiter.join(("red", "fish", "blue", "fish")), ... delimiter.join(("I do not like them", "Sam I am")), ... delimiter.join(("I do not like green eggs and ham.",))) >>> actual = ( ... delimiter.join(("red", "fish", "blue", "fish")), ... delimiter.join(("one", "fish", "two", "fish")), ... delimiter.join(("I do not like spam", "Sam I am")), ... delimiter.join(("I do not like", "green eggs and ham."))) The results: >>> pprint([analyze(v) for v in iter_delim_sets(delimiter, expected, actual)]) [DelimAnalysis(index=0, correct=2, incorrect=1, count_diff=0), DelimAnalysis(index=1, correct=2, incorrect=1, count_diff=0), DelimAnalysis(index=2, correct=1, incorrect=0, count_diff=0), DelimAnalysis(index=3, correct=0, incorrect=1, count_diff=1)] What they mean: >>> pprint(delim_analysis_doc) (('index', ('The number of the lines from expected and actual', 'used to perform this analysis.')), ('correct', ('The number of delimiter placements in ``actual``', 'which were correctly placed.')), ('incorrect', ('The number of incorrect delimiters in ``actual``.',)), ('count_diff', ('The difference between the number of delimiters', 'in ``expected`` and ``actual`` for this line.'))) And a trace of the processing stages: >>> def dump_it(it): ... '''Wraps an iterator in code that dumps its values to stdout.''' ... for v in it: ... print v ... yield v >>> for v in iter_delim_sets(delimiter, ... dump_it(expected), dump_it(actual)): ... print v ... print analyze(v) ... print '======' one||fish||two||fish red||fish||blue||fish DelimLocations(index=0, expected=set([9, 3, 14]), actual=set([9, 3, 15])) DelimAnalysis(index=0, correct=2, incorrect=1, count_diff=0) ====== red||fish||blue||fish one||fish||two||fish DelimLocations(index=1, expected=set([9, 3, 15]), actual=set([9, 3, 14])) DelimAnalysis(index=1, correct=2, incorrect=1, count_diff=0) ====== I do not like them||Sam I am I do not like spam||Sam I am DelimLocations(index=2, expected=set([18]), actual=set([18])) DelimAnalysis(index=2, correct=1, incorrect=0, count_diff=0) ====== I do not like green eggs and ham. I do not like||green eggs and ham. DelimLocations(index=3, expected=set([]), actual=set([13])) DelimAnalysis(index=3, correct=0, incorrect=1, count_diff=1) ====== """ from collections import namedtuple # Data types ## Here ``expected`` and ``actual`` are sets DelimLocations = namedtuple('DelimLocations', 'index expected actual') DelimAnalysis = namedtuple('DelimAnalysis', 'index correct incorrect count_diff') ## Explanation of the elements of DelimAnalysis. ## There's no real convenient way to add a docstring to a variable. delim_analysis_doc = ( ('index', ("The number of the lines from expected and actual", "used to perform this analysis.")), ('correct', ("The number of delimiter placements in ``actual``", "which were correctly placed.")), ('incorrect', ("The number of incorrect delimiters in ``actual``.",)), ('count_diff', ("The difference between the number of delimiters", "in ``expected`` and ``actual`` for this line."))) # Actual functionality def iter_delim_sets(delimiter, expected, actual): """Yields a DelimLocations tuple for each pair of strings. ``expected`` and ``actual`` are sequences of strings. """ from re import escape, compile as compile_ from itertools import count, izip index = count() re = compile_(escape(delimiter)) def delimiter_locations(string): """Set of the locations of matches of ``re`` in ``string``.""" return set(match.start() for match in re.finditer(string)) string_pairs = izip(expected, actual) return (DelimLocations(index=index.next(), expected=delimiter_locations(e), actual=delimiter_locations(a)) for e, a in string_pairs) def analyze(locations): """Returns an analysis of a DelimLocations tuple. ``locations.expected`` and ``locations.actual`` are sets. """ return DelimAnalysis( index=locations.index, correct=len(locations.expected & locations.actual), incorrect=len(locations.actual - locations.expected), count_diff=(len(locations.actual) - len(locations.expected)))
Python - Best way to compare two strings, record stats comparing serial position of particular item?
I'm dealing with two files, both of which have lines that look like the following: This is || an example || line . In one of the files, the above line would appear, whereas the corresponding line in the other file would be identical BUT might have the '||' items in a different position: This || is an || example || line . I just need to collect stats for how often a "||" fell in the "right" place in the second file (we're assuming the first file is always "right"), how often a "||" fell in a place where the first file didn't have a "||", and how the number of overall "||" markers differed for that particular line. I know I could do this alone, but wondered if you brilliant folks knew some incredibly easy way of doing this? The basic stuff (such as reading the files in) is all stuff I'm familiar with--I'm really just looking for advice on how to do the actual comparisons of lines and collect the stats! Best, Georgina
[ "Is this what you are looking for?\nThis code assumes that every line is formatted in the same way as in your examples\nfileOne = open('theCorrectFile', 'r')\nfileTwo = open('theSecondFile', 'r')\n\nfor corrrectLine in fileOne:\n otherLine = fileTwo.readline()\n for i in len(correctLine.split(\"||\")):\n ...
[ 1, 0 ]
[]
[]
[ "compare", "python", "string" ]
stackoverflow_0003799407_compare_python_string.txt
Q: Optimizing find and replace over large files in Python I am a complete beginner to Python or any serious programming language for that matter. I finally got a prototype code to work but I think it will be too slow. My goal is to find and replace some Chinese characters across all files (they are csv) in a directory with integers as per a csv file I have. The files are nicely numbered by year-month, for example 2000-01.csv, and will be the only files in that directory. I will be looping across about 25 files that are in the neighborhood of 500mb each (and about a million lines). The dictionary I will be using will have about 300 elements and I will be changing unicode (Chinese character) to integers. I tried with a test run and, assuming everything scales up linearly (?), it looks like it would take about a week for this to run. Thanks in advance. Here is my code (don't laugh!): # -*- coding: utf-8 -*- import os, codecs dir = "C:/Users/Roy/Desktop/test/" Dict = {'hello' : 'good', 'world' : 'bad'} for dirs, subdirs, files in os.walk(dir): for file in files: inFile = codecs.open(dir + file, "r", "utf-8") inFileStr = inFile.read() inFile.close() inFile = codecs.open(dir + file, "w", "utf-8") for key in Dict: inFileStr = inFileStr.replace(key, Dict[key]) inFile.write(inFileStr) inFile.close() A: In your current code, you're reading the whole file into memory at once. Since they're 500Mb files, that means 500Mb strings. And then you do repeated replacements of them, which means Python has to create a new 500Mb string with the first replacement, then destroy the first string, then create a second 500Mb string for the second replacement, then destroy the second string, et cetera, for each replacement. That turns out to be quite a lot of copying of data back and forth, not to mention using a lot of memory. If you know the replacements will always be contained in a line, you can read the file line by line by iterating over it. Python will buffer the read, which means it will be fairly optimized. You should open a new file, under a new name, for writing the new file simultaneously. Perform the replacement on each line in turn, and write it out immediately. Doing this will greatly reduce the amount of memory used and the amount of memory copied back and forth as you do the replacements: for file in files: fname = os.path.join(dir, file) inFile = codecs.open(fname, "r", "utf-8") outFile = codecs.open(fname + ".new", "w", "utf-8") for line in inFile: newline = do_replacements_on(line) outFile.write(newline) inFile.close() outFile.close() os.rename(fname + ".new", fname) If you can't be certain if they'll always be on one line, things get a little harder; you'd have to read in blocks manually, using inFile.read(blocksize), and keep careful track of whether there might be a partial match at the end of the block. Not as easy to do, but usually still worth it to avoid the 500Mb strings. Another big improvement would be if you could do the replacements in one go, rather than trying a whole bunch of replacements in order. There are several ways of doing that, but which fits best depends entirely on what you're replacing and with what. For translating single characters into something else, the translate method of unicode objects may be convenient. You pass it a dict mapping unicode codepoints (as integers) to unicode strings: >>> u"\xff and \ubd23".translate({0xff: u"255", 0xbd23: u"something else"}) u'255 and something else' For replacing substrings (and not just single characters), you could use the re module. The re.sub function (and the sub method of compiled regexps) can take a callable (a function) as the first argument, which will then be called for each match: >>> import re >>> d = {u'spam': u'spam, ham, spam and eggs', u'eggs': u'saussages'} >>> p = re.compile("|".join(re.escape(k) for k in d)) >>> def repl(m): ... return d[m.group(0)] ... >>> p.sub(repl, u"spam, vikings, eggs and vikings") u'spam, ham, spam and eggs, vikings, saussages and vikings' A: I think you can lower memory use greatly (and thus limit swap use and make things faster) by reading a line at a time and writing it (after the regexp replacements already suggested) to a temporary file - then moving the file to replace the original. A: A few things (unrelated to the optimization problem): dir + file should be os.path.join(dir, file) You might want to not reuse infile, but instead open (and write to) a separate outfile. This also won't increase performance, but is good practice. I don't know if you're I/O bound or cpu bound, but if your cpu utilization is very high, you may want to use threading, with each thread operating on a different file (so with a quad core processor, you'd be reading/writing 4 different files simultaneously). A: Open the files read/write ('r+') and avoid the double open/close (and likely associated buffer flush). Also, if possible, don't write back the entire file, seek and write back only the changed areas after doing the replace on the file's contents. Read, replace, write changed areas (if any). That still won't help performance too much though: I'd profile and determine where the performance hit actually is and then move onto optimising it. It could just be the reading of the data from disk that's very slow, and there's not much you can do about that in Python.
Optimizing find and replace over large files in Python
I am a complete beginner to Python or any serious programming language for that matter. I finally got a prototype code to work but I think it will be too slow. My goal is to find and replace some Chinese characters across all files (they are csv) in a directory with integers as per a csv file I have. The files are nicely numbered by year-month, for example 2000-01.csv, and will be the only files in that directory. I will be looping across about 25 files that are in the neighborhood of 500mb each (and about a million lines). The dictionary I will be using will have about 300 elements and I will be changing unicode (Chinese character) to integers. I tried with a test run and, assuming everything scales up linearly (?), it looks like it would take about a week for this to run. Thanks in advance. Here is my code (don't laugh!): # -*- coding: utf-8 -*- import os, codecs dir = "C:/Users/Roy/Desktop/test/" Dict = {'hello' : 'good', 'world' : 'bad'} for dirs, subdirs, files in os.walk(dir): for file in files: inFile = codecs.open(dir + file, "r", "utf-8") inFileStr = inFile.read() inFile.close() inFile = codecs.open(dir + file, "w", "utf-8") for key in Dict: inFileStr = inFileStr.replace(key, Dict[key]) inFile.write(inFileStr) inFile.close()
[ "In your current code, you're reading the whole file into memory at once. Since they're 500Mb files, that means 500Mb strings. And then you do repeated replacements of them, which means Python has to create a new 500Mb string with the first replacement, then destroy the first string, then create a second 500Mb stri...
[ 18, 3, 1, 0 ]
[]
[]
[ "optimization", "python", "replace" ]
stackoverflow_0003800086_optimization_python_replace.txt
Q: Help interpreting code snippet I am very new to python and beautifulsoup. In the for statement, what is incident? Is it a class, type, variable? The line following the for.. totally lost. Can someone please explain this code to me? for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() print what.strip() break print 'done' A: The first statement starts a loop which parses an HTML document looking for td elements with width set to 90%. The object representing the td element is bound to the name incident. The second line is a multiple assignment and can be rewritten as follows: where = incident.contents[0] linebreak = incident.contents[1] what = incident.contents[2] In other words it extracts the contents from the td tag and gives each element a more meaningful name. The final line in the loop causes the loop to break after checking only the first element. The code could have been rewritten to not use a loop which would have made it more clear. A: Welcome to Stack Overflow! Let's take a look at what's happening. I've added links to further reading along the way, do take a look at them before asking further questions. for incident in soup('td', width="90%"): incidentis just an arbitrary local variable for the iterable returned by soup. Generally speaking, the local variable in a for statement is probably a list, but may be a tuple or even a string. If it's possible to iterate over something, like a file, then Python will probably accept for to go through the items. In this case, soup is returning a list of td HTML elements with a width of 90%. We can see this because of what happens on the next line: where, linebreak, what = incident.contents[:3] where, linebreak and what are all arbitrary local variables as well. They are all being assigned in a single statement. In Python, this is known as multiple assignment. Where do those three elements come from?incident.contents[:3] is asking for the first three elements, using slice notation. print where.strip() print what.strip() These two lines print where and what onto the screen.¹ But what is strip doing? It's removing white space. So, " some text " become "some text". break break is just breaking the for loop after its first cycle. It doesn't break the whole program. Instead, it returns the program's flow to the next line after the loop. print 'done' This is just doing what it says, sending the words 'done' to the screen. If you are using this program, you know it is complete when you see 'done' (without the quotes) appear on the screen. ¹ To be more technically precise, they send the bytes to standard out (normally known as stdout). A: First off, Python cares about where newlines and spaces are, so you should use the code tag to present Python code. As is, I have to guess at how your code was originally formatted. for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() print what.strip() break print 'done' The 'for x in y:' statement assumes that 'y' is some kind of iterable (list-like) thing - an ordered collection of objects. Then, for each element in the list, it assigns the element to the name 'x', and runs the indented block. In this case, there appears to be a function, soup(), which returns a list of incidents. Each incident is an object which contains an attribute, called 'contents', which is itself a list; [:3] means 'the first three elements of the list'. So that line is taking the first three things in the contents of the incident and assigning them the names 'where', 'linebreak', and 'what'. The strip() function removes whitespace off the start and end of a string. So we print the 'where' and the 'what'. 'break' exits from the for-loop, so in this case it only runs once, which is a little odd.
Help interpreting code snippet
I am very new to python and beautifulsoup. In the for statement, what is incident? Is it a class, type, variable? The line following the for.. totally lost. Can someone please explain this code to me? for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() print what.strip() break print 'done'
[ "The first statement starts a loop which parses an HTML document looking for td elements with width set to 90%. The object representing the td element is bound to the name incident.\nThe second line is a multiple assignment and can be rewritten as follows:\nwhere = incident.contents[0]\nlinebreak = incident.content...
[ 3, 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003799402_beautifulsoup_python.txt
Q: How to generate a random partition from an iterator in Python Given the desired number of partitions, the partitions should be nearly equal in size. This question handles the problem for a list. They do not have the random property, but that is easily added. My problem is, that I have an iterator as input, so shuffle does not apply. The reason for that is that I want to randomly partition the nodes of graph. The graph can be very large, so I am looking for a solution that does not just create an intermediate list. My first idea was to use compress() with a random number function as selector. But that only works for two partitions. A: You're just dealing to various partitions, right? def dealer( iterator, size ): for item in iterator yield random.randrange( size ), item Won't that get you started by assigning each item to a partition? Then you can do something like this to make lists. Maybe not a good thing, but it shows how to use the function. def make_lists( iterator, size ): the_lists = []*size for partition, item in dealer( iterator, size ): the_lists[partition].append(item) return the_lists A: You could just create k list. When you receive a value, pick a random integer x between 0 and k-1, and put that value into the x-th list. On average each list will contain N/k elements, but with a standard deviation of √(N * 1/k * (1-1/k)). def random_partition(k, iterable): results = [[] for i in range(k)] for value in iterable: x = random.randrange(k) results[x].append(value) return results A: You can make the length of lists more uniform by adjusting the weights depending on the number of nodes generated so far in each partition. They'll be roughly equal-length if you pick a function so that the weight is 0 when (number of nodes in partition n) > (number of nodes)/(number of partions), i.e. weight[i] = max(numNodes/numPartitions - nodesSoFar[i],0) (The max() is to stop negative weights, which might happen if you have 4 nodes and 3 partitions.) Then pick a random number from 1 to sum(weights) (or 0 to sum(weights)-1) and pick the partition appropriately. compress() works provided you use a different selector per partition; something like (x == n for x in random_partition_numbers) where random_partition_numbers is a generator. You'll need to copy random_partition_numbers for each partition, of course. This design is inherently slower, since it needs to iterate through the list of nodes for each partition.
How to generate a random partition from an iterator in Python
Given the desired number of partitions, the partitions should be nearly equal in size. This question handles the problem for a list. They do not have the random property, but that is easily added. My problem is, that I have an iterator as input, so shuffle does not apply. The reason for that is that I want to randomly partition the nodes of graph. The graph can be very large, so I am looking for a solution that does not just create an intermediate list. My first idea was to use compress() with a random number function as selector. But that only works for two partitions.
[ "You're just dealing to various partitions, right?\ndef dealer( iterator, size ):\n for item in iterator\n yield random.randrange( size ), item\n\nWon't that get you started by assigning each item to a partition?\nThen you can do something like this to make lists. Maybe not a good thing, but it shows how...
[ 1, 1, 0 ]
[]
[]
[ "iterator", "partitioning", "python", "random" ]
stackoverflow_0003760752_iterator_partitioning_python_random.txt
Q: Pythonic way to modify python path relative to current directory I have a project that is structured like this (cut down a lot to give the gist)... State_Editor/ bin/ state_editor/ __init__.py main.py features/ __init__.py # .py files io/ __init__.py # .py files # etc. You get the idea. Now say for example that foobar.py in features did this... from state_editor.io.fileop import subInPath. Obviously State_Editor needs to be in the path. I've read about sys.path.append and path configuration files, but I'm not sure how to accomplish what I need to accomplish, or what the most pythonic way to do it is. The biggest problem is I don't know how to specify "one directory up". Obviously this is .., but I'm not sure how to avoid this being interpreted as a string literal. For example if I do sys.path.append('../') it will literally append ../ to the path. So my question is, what is the most "pythonic" way to accomplish this? A: In the question as stated, you need 2 leading dots (the module containing the import was state_editor.features.foobar). So: from ..io.fileop import SubInPath Full docs: http://docs.python.org/reference/simple_stmts.html#the-import-statement A: In recent-enough Python versions, "relative imports" as recommended by @fseto may be best (perhaps with a from __future__ import absolute_import at the top of your module). For a solution compatible with a wide range of Python versions, e.g., import sys import os sys.path.append(os.path.abspath(os.pardir))
Pythonic way to modify python path relative to current directory
I have a project that is structured like this (cut down a lot to give the gist)... State_Editor/ bin/ state_editor/ __init__.py main.py features/ __init__.py # .py files io/ __init__.py # .py files # etc. You get the idea. Now say for example that foobar.py in features did this... from state_editor.io.fileop import subInPath. Obviously State_Editor needs to be in the path. I've read about sys.path.append and path configuration files, but I'm not sure how to accomplish what I need to accomplish, or what the most pythonic way to do it is. The biggest problem is I don't know how to specify "one directory up". Obviously this is .., but I'm not sure how to avoid this being interpreted as a string literal. For example if I do sys.path.append('../') it will literally append ../ to the path. So my question is, what is the most "pythonic" way to accomplish this?
[ "In the question as stated, you need 2 leading dots (the module containing the import was state_editor.features.foobar). So:\nfrom ..io.fileop import SubInPath \n\nFull docs:\nhttp://docs.python.org/reference/simple_stmts.html#the-import-statement\n", "In recent-enough Python versions, \"relative imports\" as re...
[ 3, 1 ]
[]
[]
[ "filepath", "filesystems", "python" ]
stackoverflow_0003800411_filepath_filesystems_python.txt
Q: Is this a Dictionary in an older Python version? I'm new to Python and am reading a book that came out in 2009 and so uses Python 2.5 syntax. It does the following: _fields_ = [ ("cb", DWORD), ("lpReserved", LPTSTR), ... ] To me it looks like a list of tuples, but at the same time it feels like a Map/Dictionary. Was this the older syntax? A: It's perfectly good, current syntax, and expresses a list of pairs (two-item tuples). If you need a dict (and have no problem with duplicate keys;-), dict(_fields_) will make you one (much like somedict.items() makes you a list of pairs from a dict -- list(somedict.items()) if you're in Python 3 but insist on getting a list rather than just a view/iterator, btw;-). A: No, this was always a list of tuples. That looks like a datatype "mapping" for the purposes of ctypes, but it's just a list, not a real map. A: No, that's just a list of tuples. Dictionaries in Python have always used the {} notation.
Is this a Dictionary in an older Python version?
I'm new to Python and am reading a book that came out in 2009 and so uses Python 2.5 syntax. It does the following: _fields_ = [ ("cb", DWORD), ("lpReserved", LPTSTR), ... ] To me it looks like a list of tuples, but at the same time it feels like a Map/Dictionary. Was this the older syntax?
[ "It's perfectly good, current syntax, and expresses a list of pairs (two-item tuples). If you need a dict (and have no problem with duplicate keys;-), dict(_fields_) will make you one (much like somedict.items() makes you a list of pairs from a dict -- list(somedict.items()) if you're in Python 3 but insist on get...
[ 6, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003800617_python.txt
Q: How do you implement 'EXIT_CODES' in python? Initially i thought to do something like: #EXIT CODES class ExitCode(object): (USERHOME_INVALID, \ USERHOME_CANNOT_WRITE, \ USERHOME_CANNOT_READ, \ BASHRC_INVALID) = range(-1, -5, -1) But than I've realized that I'll have to know exactly the total number of EXIT_CODES, so that I can pass it to the range() function. Let's suppose I'll have 87 (arbitrary) EXIT_CODES... I don't want to count to 87 (not that it's hard) but I am looking for a more elegant solution. Any suggestions ? EDIT: EXIT_CODE is a negative int that will be passed to sys.exit . Instead of writing the number I prefer to use some sort of constants (something like #defines or enums in C, or enums in Java). A: Sounds like what you want is the Python equivalent of an enumeration in C# or other similar languages. How can I represent an 'Enum' in Python? provides several solutions, though they still require the number of items you have. EDIT: How can I represent an 'Enum' in Python? looks way better. Or you could try something like this (probably not the best solution, though): class _ExitCode: _exit_codes=["EXIT_CODE","EXIT_CODE_TWO"] def __getattr__(self, name): if name in _ExitCode._exit_codes: return -(_ExitCode._exit_codes.index(name)+1) raise AttributeError("Exit code %s not found" % name) ExitCode=_ExitCode() print ExitCode.EXIT_CODE #-1 A: Maybe I don't understand the question, but why don't you simply make a dictionary of exit codes and implement the desired behaviour in a function? EXIT_CODES = dict(SUCCESS=0, USER_NAME_INVALID=-1, OTHER_ERROR=-2) def exit(code): try: return EXIT_CODES[code] except KeyError: raise KeyError("exit code %s is not implemented" % code) So you can use it like # some computation goes here return exit("SUCCESS") And if you want to make "automatic" assignment of numbers (I don't recommend this) you can simply create a list of exit codes and return the negative of the index: EXIT_CODES = ['SUCCESS', 'ERROR_1', 'ERROR_2'] return -EXIT_CODES.index('ERROR_1') # will return -1 (for the last one, you can implement a function similar to the dictionary-based one) A: I must note that it's not at all certain a negative status makes sense for sys.exit(); at least on Linux, it will be interpreted as an unsigned 8-bit value (range 0-255). As for an enumerated type, it's possible to do something like: class ExitStatus: pass for code, name in enumerate("Success Failure CriticalFailure".split()): setattr(ExitStatus, name, code) Resulting in something like: >>> ExitStatus.__dict__ {'CriticalFailure': 2, 'Failure': 1, '__module__': '__main__', '__doc__': None, 'Success': 0} The predefined values in normal Unix systems are EXIT_FAILURE=1 and EXIT_SUCCESS=0. Addendum: Considering the concern about IDE identification of identifiers, one could also do something like: class EnumItem: pass def adjustEnum(enum): value=0 enumdict=enum.__dict__ for k,v in enumdict.items(): if isinstance(v,int): if v>=value: value=v+1 for k,v in enumdict.items(): if v is EnumItem: enumdict[k]=value value+=1 class ExitStatus: Success=0 Failure=EnumItem CriticalFailure=EnumItem adjustEnum(ExitStatus) Second edit: Couldn't keep away. Here's a variant that assigns the values in the order you've written the names. class EnumItem: serial=0 def __init__(self): self.serial=self.__class__.serial self.__class__.serial+=1 def adjustEnum(enum): enumdict=enum.__dict__ value=0 unknowns={} for k,v in enumdict.items(): if isinstance(v,int): if v>=value: value=v+1 elif isinstance(v,EnumItem): unknowns[v.serial]=k for i,k in sorted(unknowns.items()): enumdict[k]=value value+=1 return enum @adjustEnum class ExitStatus: Success=0 Failure=EnumItem() CriticalFailure=EnumItem() Obviously the growing complexity is inelegant, but it does work. A: I guess I looked at this question earlier and didn't see it, but one obvious thing to do is use a dict. def make_exit_codes(*exit_codes): return dict((name, -value - 1) for name, value in enumerate(exit_codes)) EXIT_CODES = make_exit_codes('USERHOME_INVALID', 'USERHOME_CANNOT_WRITE', 'USERHOME_CANNOT_READ', 'BASHRC_INVALID') A: You can create variables (or class attributes) on-the-fly with Python. For example ExitCodes = '''USERHOME_INVALID, USERHOME_CANNOT_WRITE, USERHOME_CANNOT_READ, BASHRC_INVALID''' for i, s in enumerate(ExitCodes.split(','), 1): exec('%s = %d' % (s.strip(), -i)) print USERHOME_INVALID print USERHOME_CANNOT_WRITE print USERHOME_CANNOT_READ print BASHRC_INVALID sys.exit(USERHOME_INVALID) >>> -1 >>> -2 >>> -3 >>> -4
How do you implement 'EXIT_CODES' in python?
Initially i thought to do something like: #EXIT CODES class ExitCode(object): (USERHOME_INVALID, \ USERHOME_CANNOT_WRITE, \ USERHOME_CANNOT_READ, \ BASHRC_INVALID) = range(-1, -5, -1) But than I've realized that I'll have to know exactly the total number of EXIT_CODES, so that I can pass it to the range() function. Let's suppose I'll have 87 (arbitrary) EXIT_CODES... I don't want to count to 87 (not that it's hard) but I am looking for a more elegant solution. Any suggestions ? EDIT: EXIT_CODE is a negative int that will be passed to sys.exit . Instead of writing the number I prefer to use some sort of constants (something like #defines or enums in C, or enums in Java).
[ "Sounds like what you want is the Python equivalent of an enumeration in C# or other similar languages. How can I represent an 'Enum' in Python? provides several solutions, though they still require the number of items you have. \nEDIT: How can I represent an 'Enum' in Python? looks way better.\nOr you could try so...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "exit_code", "python" ]
stackoverflow_0003731532_exit_code_python.txt
Q: problem with QSqlTalbeModel . table is not showing i have a QsqlTableModel that is assigned to a table view . my problem is that it doesn't populate the table inside the table view . it's still empty and it says (Unable to find table shots) - when printing lastError.text() - the function retrieveShotResults..(check code below) is to test if there is a table called shots and yes it prints everything just fine , and the connection is fine also .. but the table view is still empty . am i doing anything wrong ? please help thanks is advance class SqlModel(QtSql.QSqlTableModel): def __init__(self): super(SqlModel,self).__init__() self.connect() self.retrieveResult() self.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.setTable("""shots""") self.select() def connect(self): # dataBase connection db = QSqlDatabase.addDatabase("QMYSQL") db.setHostName("localhost") db.setDatabaseName("magenta") db.setUserName("admin") db.setPassword("moayyad") def retrieveShotResult(self): query = QtSql.QSqlQuery() query.exec_("""select * from shots""") while query.next(): table = query.value(1).toString() print table A: i found it ^_^ . the (connect) function should be called in the mainloop
problem with QSqlTalbeModel . table is not showing
i have a QsqlTableModel that is assigned to a table view . my problem is that it doesn't populate the table inside the table view . it's still empty and it says (Unable to find table shots) - when printing lastError.text() - the function retrieveShotResults..(check code below) is to test if there is a table called shots and yes it prints everything just fine , and the connection is fine also .. but the table view is still empty . am i doing anything wrong ? please help thanks is advance class SqlModel(QtSql.QSqlTableModel): def __init__(self): super(SqlModel,self).__init__() self.connect() self.retrieveResult() self.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.setTable("""shots""") self.select() def connect(self): # dataBase connection db = QSqlDatabase.addDatabase("QMYSQL") db.setHostName("localhost") db.setDatabaseName("magenta") db.setUserName("admin") db.setPassword("moayyad") def retrieveShotResult(self): query = QtSql.QSqlQuery() query.exec_("""select * from shots""") while query.next(): table = query.value(1).toString() print table
[ "i found it ^_^ . the (connect) function should be called in the mainloop \n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python", "qtsql" ]
stackoverflow_0003800522_pyqt4_python_qtsql.txt
Q: Python function help Please help! cannot figure this out for the life of me Given the function f(x,n)= n**x(n-1) 5c. Using this function, calculate the rate of change of (((2^3 + 3^2)^4 -2^4)^2 + (3^4 – (6^2 + 3)^4)^3)^3 This is what I came up with in IDLE: def function(x, n): return (n*(x**(n-1))) assertEqual ( function (((( function (2.0, 3.0))+( function (3.0, 2.0)), 4.0)-( function (2.0, 4.0)), 2.0)+(( function (3.0, 4.0))-(( function (6.0, 2.0))+( function (3.0, 1.0)), 4.0), 3.0), 3.0), 35994405888.0) and after I save and run it, I get this message: Traceback (most recent call last): File "C:\Users\Jonathan Cohen\Desktop\School\CISC 106\lab2.py", line 83, in <module> assertEqual (function ((((function (2.0, 3.0))+(function (3.0, 2.0)), 4.0)-(function (2.0, 4.0)), 2.0)+((function (3.0, 4.0))-((function (6.0, 2.0))+(function (3.0, 1.0)), 4.0), 3.0), 3.0), 35994405888.0) TypeError: unsupported operand type(s) for -: 'tuple' and 'float' A: (function(a, b), c) is a 2-tuple consisting of the result of function(a,b) and c. If you want to represent (a^b)^c, you'd need something like function(function(a,b), c) (assuming function() computes its first parameter raised to the second.) A: There are a few occurances of this, but here is the first one. function ((((function (2.0, 3.0))+(function (3.0, 2.0)), 4.0)-(function (2.0, 4.0)), 2.0)+((function (3.0, 4.0))-((function (6.0, 2.0))+(function (3.0, 1.0)), 4.0), 3.0), 3.0) ((function (2.0, 3.0))+(function (3.0, 2.0)), 4.0) The segment that I've blocked out, produces a tuple of (18.0, 4.0). You then try to do normal math on this, which fails. In response to the comment, this particular segment would work better if you did the following: function((function (2.0, 3.0))+(function (3.0, 2.0)), 4.0) A: This starts off looking like calculus to me, but quickly goes off the rails. Elementary differential calculus says that if you have a function: then the first derivative with respect to the independent variable x is: It looks to me like you're trying to evaluate something like this with Python, but the tuple expression you give makes no sense to me. Was there supposed to be an independent variable hidden in there somewhere? A: So after two weeks of pulling my hair out trying to figure this out I think I finally got it. Thanks so much everybody, all your input really helped! I broke down each part and rewrote everything according to what you all suggested. This is what I came up with: def function (x,n): return (n*(x**(n-1))) assertEqual (function (function (function((function (2, 3))+(function (3, 2)), 4)-function(function (2, 4), 1), 2)+function (function ((function (3,4)),1)-function ((function (6,2))+(function (3,1)),4),3),3), 161027925052617363) after saving it and running it, the Python shell tells me it's successful, what do you all say? Once again thanks for all your help!
Python function help
Please help! cannot figure this out for the life of me Given the function f(x,n)= n**x(n-1) 5c. Using this function, calculate the rate of change of (((2^3 + 3^2)^4 -2^4)^2 + (3^4 – (6^2 + 3)^4)^3)^3 This is what I came up with in IDLE: def function(x, n): return (n*(x**(n-1))) assertEqual ( function (((( function (2.0, 3.0))+( function (3.0, 2.0)), 4.0)-( function (2.0, 4.0)), 2.0)+(( function (3.0, 4.0))-(( function (6.0, 2.0))+( function (3.0, 1.0)), 4.0), 3.0), 3.0), 35994405888.0) and after I save and run it, I get this message: Traceback (most recent call last): File "C:\Users\Jonathan Cohen\Desktop\School\CISC 106\lab2.py", line 83, in <module> assertEqual (function ((((function (2.0, 3.0))+(function (3.0, 2.0)), 4.0)-(function (2.0, 4.0)), 2.0)+((function (3.0, 4.0))-((function (6.0, 2.0))+(function (3.0, 1.0)), 4.0), 3.0), 3.0), 35994405888.0) TypeError: unsupported operand type(s) for -: 'tuple' and 'float'
[ "(function(a, b), c) is a 2-tuple consisting of the result of function(a,b) and c.\nIf you want to represent (a^b)^c, you'd need something like function(function(a,b), c) (assuming function() computes its first parameter raised to the second.)\n", "There are a few occurances of this, but here is the first one.\nf...
[ 3, 2, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003799786_function_python.txt
Q: MongoDB for realtime ajax stuff? Howdie stackoverflow people! So I've been doing some digging regarding these NoSQL databases, MongoDB, CouchDB etc. Though I am still not sure about real time-ish stuff therefore I thought i'd ask around to see if someone have any practical experience. Let's think about web stuff, let's say we've got a very dynamic super ajaxified webapp that asks for various types of data every 5-20 seconds, our backend is python or php or anything other than java really... in cases such as these obviously a MySQL or similar db would be under heavy pressure (with lots of users), would MongoDB / CouchDB run this without breaking a sweat and without the need to create some super ultra complex cluster/caching etc solution? Yes, that's basically my question, if you think that no.. then yes I know there are several types of solutions for this, nodeJS/websockets/antigravity/worm-hole super tech, but I am just interested in these NoSQL things atm and more specifically if they can handle this type of thing. Let's say we have 5000 users at the same time, every 5, 10 or 20 seconds ajax requests that updates various interfaces. Shoot ;] A: Let's say we have 5000 users at the same time, every 5, 10 or 20 seconds ajax requests that updates various interfaces. OK, so to get this right, you're talking about 250 to 1000 writes per second? Yeah, MongoDB can handle that. The real key on performance is going to be whether or not these are queries, updates or inserts. For queries, Mongo can probably handle this load. It's really going to be about data size to memory size ratios. If you have a server with 1GB of RAM and 150GB of data, then you're probably not going to get 250 queries / second (with any DB technology). But with reasonable hardware specs, Mongo can hit this speed on a single 64-bit server. If you have 5,000 active users and you're constantly updating existing records then Mongo will be really fast (on par with updating memcached on a single machine). The reason here is simply that Mongo will likely keep the record in memory. So a user will send updates every 5 seconds and the in-memory object will be updated. If you are constantly inserting new records, then the limitation is really going to be one of throughput. When you're writing lots of new data, you're also forcing the index to expand. So if you're planning to pump in Gigs of new data, then you risk saturating the disk throughput and you'll need to shard. So based on your questions, it looks like you're mostly querying/updating. You'll be writing new records, but not 1000 new records / second. If this is the case, then MongoDB is probably right for you. It will definitely get around a lot of caching concerns. A: It depends heavily on the server running said NoSQL solution, amount of data etc... I have played around with Mongo a bit and it is very easy to setup multiple servers to run simultaneously and you would most likely be able to accomplish high concurrency by starting multiple instances on the same box and having them act like a cluster. Luckily Mongo, at least, handles all the specifics so servers can be killed and introduced without skipping a beat (depending on version). By default I believe the max connections is 1000 so starting 5 servers with said configuration would suffice (if your server can handle it obviously) but realistically you would most likely never be hitting 5000 users at the exact same time. I hope for your hardware's sake you would at least come up with a solution that can check to see if new data is available before a full-on fetch. Either via timestamps or Memcache etc... Overall I would tend to believe NoSQL would be much faster than traditional databases assuming you are fetching data and not running reports etc... and your datastore design is intelligent enough to compensate for the lack of complex joins.
MongoDB for realtime ajax stuff?
Howdie stackoverflow people! So I've been doing some digging regarding these NoSQL databases, MongoDB, CouchDB etc. Though I am still not sure about real time-ish stuff therefore I thought i'd ask around to see if someone have any practical experience. Let's think about web stuff, let's say we've got a very dynamic super ajaxified webapp that asks for various types of data every 5-20 seconds, our backend is python or php or anything other than java really... in cases such as these obviously a MySQL or similar db would be under heavy pressure (with lots of users), would MongoDB / CouchDB run this without breaking a sweat and without the need to create some super ultra complex cluster/caching etc solution? Yes, that's basically my question, if you think that no.. then yes I know there are several types of solutions for this, nodeJS/websockets/antigravity/worm-hole super tech, but I am just interested in these NoSQL things atm and more specifically if they can handle this type of thing. Let's say we have 5000 users at the same time, every 5, 10 or 20 seconds ajax requests that updates various interfaces. Shoot ;]
[ "\nLet's say we have 5000 users at the\n same time, every 5, 10 or 20 seconds\n ajax requests that updates various\n interfaces.\n\nOK, so to get this right, you're talking about 250 to 1000 writes per second? Yeah, MongoDB can handle that.\nThe real key on performance is going to be whether or not these are que...
[ 2, 0 ]
[]
[]
[ "ajax", "mongodb", "php", "python", "real_time" ]
stackoverflow_0003798728_ajax_mongodb_php_python_real_time.txt
Q: Overriding a parent class's methods Something that I see people doing all the time is: class Man(object): def say_hi(self): print('Hello, World.') class ExcitingMan(Man): def say_hi(self): print('Wow!') super(ExcitingMan, self).say_hi() # Calling the parent version once done with custom stuff. Something that I never see people doing is: class Man(object): def say_hi(self): print('Hello, World.') class ExcitingMan(Man): def say_hi(self): print('Wow!') return super(ExcitingMan, self).say_hi() # Returning the value of the call, so as to fulfill the parent class's contract. Is this because I hang with all the wrong programmers, or is it for a good reason? A: I'd argue that explicitly returning the return value of the super class method is more prudent (except in the rare case where the child wants to suppress it). Especially when you don't know what exactly super is doing. Agreed, in Python you can usually look up the super class method and find out what it does, but still. Of course the people who wrote the other version might have written the parent class themselves and/or known that it has no return value. In that case they'd have decided to do without and explicit return statement. A: In the example you give the parent class method has no explicit return statement and so is returning None. So in this one case there's no immediate issue. But note that should someone modify the parent to return a value we now probably need to modify each child. I think your suggestion is correct. A: I would suspect that, at least in this case, because the parent function doesn't return anything, there is no point in returning its result. In general though, when the parent function does return something, I think it's a fine practice. Really, whether or not you return what the super class does depends on exactly what you want the code to do. Do it if it's what you want and what's appropriate.
Overriding a parent class's methods
Something that I see people doing all the time is: class Man(object): def say_hi(self): print('Hello, World.') class ExcitingMan(Man): def say_hi(self): print('Wow!') super(ExcitingMan, self).say_hi() # Calling the parent version once done with custom stuff. Something that I never see people doing is: class Man(object): def say_hi(self): print('Hello, World.') class ExcitingMan(Man): def say_hi(self): print('Wow!') return super(ExcitingMan, self).say_hi() # Returning the value of the call, so as to fulfill the parent class's contract. Is this because I hang with all the wrong programmers, or is it for a good reason?
[ "I'd argue that explicitly returning the return value of the super class method is more prudent (except in the rare case where the child wants to suppress it). Especially when you don't know what exactly super is doing. Agreed, in Python you can usually look up the super class method and find out what it does, but ...
[ 8, 5, 3 ]
[]
[]
[ "class", "methods", "overriding", "python", "subclass" ]
stackoverflow_0003801484_class_methods_overriding_python_subclass.txt
Q: python regex speed regarding regex (specifically python re), if we ignore the way the expression is written, is the length of the text the only factor for the time required to process the document? Or are there other factors (like how the text is structured) that play important roles too? A: One important consideration can also be whether the text actually matches the regular expression. Take (as a contrived example) the regex (x+x+)+y from this regex tutorial. When applied to xxxxxxxxxxy it matches, taking the regex engine 7 steps. When applied to xxxxxxxxxx, it fails (of course), but it takes the engine 2558 steps to arrive at this conclusion. For xxxxxxxxxxxxxxy vs. xxxxxxxxxxxxxx it's already 7 vs 40958 steps, and so on exponentially... This happens especially easily with nested repetitions or regexes where the same text can be matched by two or more different parts of the regex, forcing the engine to try all permutations before being able to declare failure. This is then called catastrophic backtracking. A: Both the length of the text and its contents are important. As an example the regular expression a+b will fail to match quickly on a string containing one million bs but more slowly on a string containing one million as. This is because more backtracking will be required in the second case. import timeit x = "re.search('a+b', s)" print timeit.timeit(x, "import re;s='a'*10000", number=10) print timeit.timeit(x, "import re;s='b'*10000", number=10) Results: 6.85791902323 0.00795443275612
python regex speed
regarding regex (specifically python re), if we ignore the way the expression is written, is the length of the text the only factor for the time required to process the document? Or are there other factors (like how the text is structured) that play important roles too?
[ "One important consideration can also be whether the text actually matches the regular expression. Take (as a contrived example) the regex (x+x+)+y from this regex tutorial.\nWhen applied to xxxxxxxxxxy it matches, taking the regex engine 7 steps. When applied to xxxxxxxxxx, it fails (of course), but it takes the e...
[ 6, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003801576_python_regex.txt
Q: permissive equality test on string I'm a python newbie with a problem too hard to tackle. I have a string defining a path, were all the spaces have been converted to underscores. How can I find if it corresponds to a real path? e.g. a string like /some/path_to/directory_1/and_to/directory_2 with a real path: /some/path_to/directory 1/and_to/directory 2 notice that the real path can contain BOTH spaces and underscores. How can I feed it to os.path.exists() ??? thanks alessandro A: Use glob but replacing every underscore with a range [ _]: import glob glob.glob('/some/path_to/directory_1/and_to/directory_2'.replace('_', '[ _]')) Note that this will fail if your path contains the character [. You can fix this by first replacing [ with [[].
permissive equality test on string
I'm a python newbie with a problem too hard to tackle. I have a string defining a path, were all the spaces have been converted to underscores. How can I find if it corresponds to a real path? e.g. a string like /some/path_to/directory_1/and_to/directory_2 with a real path: /some/path_to/directory 1/and_to/directory 2 notice that the real path can contain BOTH spaces and underscores. How can I feed it to os.path.exists() ??? thanks alessandro
[ "Use glob but replacing every underscore with a range [ _]:\nimport glob\nglob.glob('/some/path_to/directory_1/and_to/directory_2'.replace('_', '[ _]'))\n\nNote that this will fail if your path contains the character [. You can fix this by first replacing [ with [[].\n" ]
[ 5 ]
[]
[]
[ "path", "python" ]
stackoverflow_0003802450_path_python.txt
Q: Fetching multiple IMAP messages at once The examples I've seen about loading emails over IMAP using python do a search and then for each message id in the results, do a query. I want to speed things up by fetching them all at once. A: RFC 3501 says fetch takes a sequence set, but I didn't see a definition for that and the example uses a range form (2:4 = messages 2, 3, and 4). I figured out that a comma separated list of ids works. In python with imaplib, I've got something like: status, email_ids = con.search(None, query) if status != 'OK': raise Exception("Error running imap search for spinvox messages: " "%s" % status) fetch_ids = ','.join(email_ids[0].split()) status, data = con.fetch(fetch_ids, '(RFC822.HEADER BODY.PEEK[1])') if status != 'OK': raise Exception("Error running imap fetch for spinvox message: " "%s" % status) for i in range(len(email_ids[0].split())): header_msg = email.message_from_string(data[i * 3 + 0][1]) subject = header_msg['Subject'], date = header_msg['Date'], body = data[i * 3 + 1][1] # includes some mime multipart junk A: You can try this to fetch the header information of all the mails in just 1 Go to server. import imaplib import email obj = imaplib.IMAP4_SSL('imap.gmail.com', 993) obj.login('username', 'password') obj.select('folder_name') resp,data = obj.uid('FETCH', '1:*' , '(RFC822.HEADER)') messages = [data[i][1].strip() + "\r\nSize:" + data[i][0].split()[4] + "\r\nUID:" + data[i][0].split()[2] for i in xrange(0, len(data), 2)] for msg in messages: msg_str = email.message_from_string(msg) message_id = msg_str.get('Message-ID')
Fetching multiple IMAP messages at once
The examples I've seen about loading emails over IMAP using python do a search and then for each message id in the results, do a query. I want to speed things up by fetching them all at once.
[ "RFC 3501 says fetch takes a sequence set, but I didn't see a definition for that and the example uses a range form (2:4 = messages 2, 3, and 4). I figured out that a comma separated list of ids works. In python with imaplib, I've got something like:\n status, email_ids = con.search(None, query)\n if status !...
[ 16, 3 ]
[]
[]
[ "imap", "imaplib", "python" ]
stackoverflow_0003581657_imap_imaplib_python.txt
Q: What is correct python syntax for this kind of list comprehension? task: {x*y such that x belongs to S & y is iteration count } where S is some other set something like this: j=0 [i*j for j++ and i in S] [s1*1, s2*2, s3*3...] A: for your edited question, you want [i * j for j, i in enumerate(S)] python doesn't have ++ because it keeps a clear distinction between statements and expressions. use [(i + 40) * i for i in xrange(60)] another way to do this is [i * j for i, j in enumerate(xrange(60), start=40)] and yet another way is [i * j for i, j in zip(xrange(40, 100), xrange(60))] I think that the first is the best way to do it because it reduces function calls and is the most readable. Also, if you don't know that you absolutely need a list, use a generator expression ((i + 40) * i for i in xrange(60)) This will allow you to process the results one at a time and never store a whole list in memory. You can pass a generator expression to stuff like sum, max, min and most other builtins. A: S = range(40,100) [i*j for i,j in enumerate(S)] A: One way to do this would be to use enumerate in conjunction with range: [x * (count + 1) for count, x in enumerate(range(40, 100))] Look at other answers for (a lot of) other ways to do this :) :) A: I'd do it in a generator: def fooGen(S): j = 1 for i in S: yield i * j J += 1 A: """ task: {x*y such that x belongs to S & y is iteration count } where S is some other set [snip unfortunate introduction of i and j] [s1*1, s2*2, s3*3...] """ a very simple translation: [x * y for y, x in enumerate(S, start=1)] or [x * (y + 1) for y, x in enumerate(S)] A: you can use the current element index as an incrementor >>> S=[2,4,6,8] >>> [i*(S.index(i)+1) for i in S] [2, 8, 18, 32] >>> so your c-ish "j++" is S.index(i)+1
What is correct python syntax for this kind of list comprehension?
task: {x*y such that x belongs to S & y is iteration count } where S is some other set something like this: j=0 [i*j for j++ and i in S] [s1*1, s2*2, s3*3...]
[ "\nfor your edited question, you want\n[i * j for j, i in enumerate(S)]\n\n\npython doesn't have ++ because it keeps a clear distinction between statements and expressions. use\n[(i + 40) * i for i in xrange(60)]\n\nanother way to do this is\n[i * j for i, j in enumerate(xrange(60), start=40)]\n\nand yet another wa...
[ 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003802653_list_comprehension_python.txt
Q: Qt: No border on buttons making them non-clickable? I'm trying to set a style to a button so that it has no border, but it seems the lack of border then makes the button non-clickable. Is there a better way of getting no border? button = QtGui.QPushButton(todo, self) button.move(0, i * 32) button.setFixedSize(200,32) button.setCheckable(True) button.setStyleSheet("QPushButton { background: rgb(75, 75, 75); color: rgb(255, 255, 255); text-align: left; font-size: 12pt; border: none;}") A: EDIT: WHOOPS, just noticed this is a Question regarding Qt/Python (and not Qt/C++), well maybe my answer helps anyways.. Just tried it, and it works for me... Here is the code i used: #include <QtGui/QApplication> #include <QtGui/QPushButton> int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; QPushButton* button = new QPushButton("i am toggleable", &w); button->setFixedSize(200,32); button->setCheckable(true); button->setStyleSheet( "QPushButton { \ background: rgb(75, 75, 75);\ color: rgb(255, 255, 255);\ text-align: left;\ font-size: 12pt;\ border: none;\ }\ QPushButton:checked {\ background: rgb(105, 105, 105);\ }\ "); w.show(); return a.exec(); } notice i added a additional CSS rule for checked buttons, so it gets visible if a Button is checked or not. Are you sure your buttons dont work, or could it be, that you just dont see that they are working ?! EDIT2: If it doesnt work for you, you could just use setFlat(True), and use additional CSS rules to fix the colors (like in my example).
Qt: No border on buttons making them non-clickable?
I'm trying to set a style to a button so that it has no border, but it seems the lack of border then makes the button non-clickable. Is there a better way of getting no border? button = QtGui.QPushButton(todo, self) button.move(0, i * 32) button.setFixedSize(200,32) button.setCheckable(True) button.setStyleSheet("QPushButton { background: rgb(75, 75, 75); color: rgb(255, 255, 255); text-align: left; font-size: 12pt; border: none;}")
[ "EDIT: WHOOPS, just noticed this is a Question regarding Qt/Python (and not Qt/C++), well maybe my answer helps anyways..\nJust tried it, and it works for me...\nHere is the code i used:\n#include <QtGui/QApplication>\n#include <QtGui/QPushButton>\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, arg...
[ 1 ]
[]
[]
[ "pyside", "python", "qt" ]
stackoverflow_0003800757_pyside_python_qt.txt
Q: How can I pairwise sum two equal-length tuples How can I get the pairwise sum of two equal length tuples? For example if I have (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer. A: tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7)))) If you prefer to avoid map and lambda then you can do: tuple(x + y for x,y in zip((0,-1,7), (3,4,-7))) EDIT: As one of the answers pointed out, you can use sum instead of explicitly splitting the tuples returned by zip. Therefore you can rewrite the above code sample as shown below: tuple(sum(t) for t in zip((0,-1,7), (3,4,-7))) Reference: zip, map, sum. A: Use sum(): >>> tuple(sum(pair) for pair in zip((0,-1,7), (3,4,-7))) or >>> tuple(map(sum, zip((0,-1,7), (3,4,-7)))) A: >>> t1 = (0,-1,7) >>> t2 = (3,4,-7) >>> tuple(i + j for i, j in zip(t1, t2)) (3, 3, 0) A: Alternatively (good if you have very big tuples or you plan to do other mathematical operations with them): > import numpy as np > t1 = (0, -1, 7) > t2 = (3, 4, -7) > at1 = np.array(t1) > at2 = np.array(t2) > tuple(at1 + at2) (3, 3, 0) Cons: more data preparation is needed. Could be overkill in most cases. Pros: operations are very explicit and isolated. Probably very fast with big tuples.
How can I pairwise sum two equal-length tuples
How can I get the pairwise sum of two equal length tuples? For example if I have (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer.
[ "tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7))))\n\nIf you prefer to avoid map and lambda then you can do:\ntuple(x + y for x,y in zip((0,-1,7), (3,4,-7)))\n\nEDIT: As one of the answers pointed out, you can use sum instead of explicitly splitting the tuples returned by zip. Therefore you can rewrite the ...
[ 14, 6, 4, 3 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0003802760_python_tuples.txt
Q: Whats the correct way of writing this list comprehension? I'm getting an error: name 'i' is not defined k = [ [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) ] for j in range(0,len(furs[i])) ] but k = [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) for j in range(0,len(furs[i])) ] works surprisingly! EDIT: What is the correct way of writing it them? I'm trying to generate a 2D matrix with i as iterator for outer for loop & j as iterator for inner for loop. A: for j in range(0,len(furs[i])) in your first example: i is not in scope here, due to the preceding ]. A: Look carefully at the second for loop: for j in range(0,len(furs[i])). You are referring to i here even though it is created and used in the preceding first list comprehension ([ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) ]). The i is limited to the scope of that first comprehension; thereby it is not visible to the second comprehension. Consequently you get the error. The second variant works because both i and j are declared and used in the same list comprehension. Let us simplify the snippet a bit. Try this: >>> [ [ i * j for i in range(0,10) ] for j in range(0, i) ] Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> [ [ i * j for i in range(0,10) ] for j in range(0, i) ] NameError: name 'i' is not defined >>> Now combine the comprehensions, thereby bringing i and j into the same scope: >>> [ i * j for i in range(0,10) for j in range(0, i) ] [0, 0, 2, 0, 3, 6, 0, 4, 8, 12, 0, 5, 10, 15, 20, 0, 6, 12, 18, 24, 30, 0, 7, 14, 21, 28, 35, 42, 0, 8, 16, 24, 32, 40, 48, 56, 0, 9, 18, 27, 36, 45, 54, 63, 72] >>> Now (cheeky =P) try the first comprehension again: >>> [ [ i * j for i in range(0,10) ] for j in range(0, i) ] [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [0, 3, 6, 9, 12, 15, 18, 21, 24, 27], [0, 4, 8, 12, 16, 20, 24, 28, 32, 36], [0, 5, 10, 15, 20, 25, 30, 35, 40, 45], [0, 6, 12, 18, 24, 30, 36, 42, 48, 54], [0, 7, 14, 21, 28, 35, 42, 49, 56, 63], [0, 8, 16, 24, 32, 40, 48, 56, 64, 72]] >>> Ta da! It works but gives a different result. Why is this so? The reason is that the (last) value of i is available in the outermost scope after example two. That is, variables created inside a list comprehension are available in the REPL scope. (PS: I believe the above paragraph can be reworded. Better Pythonistas here, please help out) To verify this, try deleting i and run example 3 again. >>> del i >>> [ [ i * j for i in range(0,10) ] for j in range(0, i) ] Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> [ [ i * j for i in range(0,10) ] for j in range(0, i) ] NameError: name 'i' is not defined >>> And we are back to square one. A: k = [ [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) ] for j in range(0,len(furs[i])) ] In the above statement i exists only till the first ] and i is out of scope after that.
Whats the correct way of writing this list comprehension?
I'm getting an error: name 'i' is not defined k = [ [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) ] for j in range(0,len(furs[i])) ] but k = [ rids[i][j][0]['a'] * rids[i][j][1]['b'] for i in range(0,10) for j in range(0,len(furs[i])) ] works surprisingly! EDIT: What is the correct way of writing it them? I'm trying to generate a 2D matrix with i as iterator for outer for loop & j as iterator for inner for loop.
[ "for j in range(0,len(furs[i])) in your first example: i is not in scope here, due to the preceding ].\n", "Look carefully at the second for loop: for j in range(0,len(furs[i])). You are referring to i here even though it is created and used in the preceding first list comprehension ([ rids[i][j][0]['a'] * rids[...
[ 1, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003803241_list_comprehension_python.txt
Q: sqlalchemy polymorhic_identity not working I'm trying to use polymorphic_on on a python class with several inheritances: engine = create_engine( 'mysql://xxx:yyy@localhost:3306/zzz?charset=utf8&use_unicode=0', pool_recycle=3600, echo=True) Base = declarative_base() class AbstractPersistent(object): version = Column('VERSION', Integer) last_modified_by = Column('LAST_MODIFIED_BY', String(255)) last_modified_date = Column('LAST_MODIFIED_DATE', Date) created_by = Column('CREATED_BY', String(255)) created_date = Column('CREATED_DATE', Date) class AbstractNamed(AbstractPersistent): eid = Column('ENTERPRISE_ID', String(255)) title = Column('TITLE', String(255)) description = Column('DESCRIPTION', String(255)) class AbstractContainer(AbstractNamed): __tablename__ = 'CM_MEMBER_CONTAINER_T' id = Column('MEMBER_CONTAINER_ID',Integer,primary_key=True) discriminator = Column('CLASS_DISCR', String(100)) __mapper_args__ = {'polymorphic_on': discriminator } class CourseSet(Base,AbstractContainer): __mapper_args__ = {'polymorphic_identity': 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'} As you can see, CourseSet contains all the columns of its parents and has the column CLASS_DISCR sets to 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'. But when it make a query fro all CourseSet: Session = sessionmaker(bind=engine) session = Session() course_sets = session.query(CourseSet).all() print(course_sets) It returns all the entries of 'CM_MEMBER_CONTAINER_T', but I want only the ones with CLASS_DISCR set to 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl' Any ideas ? A: Thanks to Michael on the google group sqlalchemy, this is the answer: AbstractContainer is not mapped, its a mixin, so its __mapper_args__ are not used until a subclass of Base is invoked, which starts up a declarative mapping. Your only mapped class then is CourseSet, which has its own __mapper_args__ , that override those of AbstractContainer - they are ignored. To combine __mapper_args__ from a mapped class with those of a mixin, see the example at http://www.sqlalchemy.org/docs/orm/extensions/declarative.html?highlight=declarative#combining-table-mapper-arguments-from-multiple-mixins It uses __table_args__ but the same concept of creating a full dictionary of arguments applies for __mapper_args__ as well.
sqlalchemy polymorhic_identity not working
I'm trying to use polymorphic_on on a python class with several inheritances: engine = create_engine( 'mysql://xxx:yyy@localhost:3306/zzz?charset=utf8&use_unicode=0', pool_recycle=3600, echo=True) Base = declarative_base() class AbstractPersistent(object): version = Column('VERSION', Integer) last_modified_by = Column('LAST_MODIFIED_BY', String(255)) last_modified_date = Column('LAST_MODIFIED_DATE', Date) created_by = Column('CREATED_BY', String(255)) created_date = Column('CREATED_DATE', Date) class AbstractNamed(AbstractPersistent): eid = Column('ENTERPRISE_ID', String(255)) title = Column('TITLE', String(255)) description = Column('DESCRIPTION', String(255)) class AbstractContainer(AbstractNamed): __tablename__ = 'CM_MEMBER_CONTAINER_T' id = Column('MEMBER_CONTAINER_ID',Integer,primary_key=True) discriminator = Column('CLASS_DISCR', String(100)) __mapper_args__ = {'polymorphic_on': discriminator } class CourseSet(Base,AbstractContainer): __mapper_args__ = {'polymorphic_identity': 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'} As you can see, CourseSet contains all the columns of its parents and has the column CLASS_DISCR sets to 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl'. But when it make a query fro all CourseSet: Session = sessionmaker(bind=engine) session = Session() course_sets = session.query(CourseSet).all() print(course_sets) It returns all the entries of 'CM_MEMBER_CONTAINER_T', but I want only the ones with CLASS_DISCR set to 'org.sakaiproject.coursemanagement.impl.CourseSetCmImpl' Any ideas ?
[ "Thanks to Michael on the google group sqlalchemy, this is the answer:\n\nAbstractContainer is not mapped, its a mixin, so its __mapper_args__ are not\n used until a subclass of Base is invoked, which starts up a declarative\n mapping. Your only mapped class then is CourseSet, which has its own\n __mapper_args_...
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003799841_python_sqlalchemy.txt
Q: Create variables from dictionary? Is something like the following possible in Python? >>> vars = {'a': 5} >>> makevars(vars) >>> print a 5 So, makevars converts the dictionary into variables. (What is this called in general?) A: It's possible, sometimes, but it's generally a very bad idea. In spite of their name, variables themselves should not be variable. They're part of your code, part of its logic. Trying to 'replace' local variables this way makes code inefficient (since Python has to drop some of its optimizations), buggy (since it can accidentally replace something you didn't expect), very hard to debug (since you can't see what's going on) and plain unreadable. Having 'dynamic values' is what dicts and lists and other containers are for. A: I think this works: locals().update(vars)
Create variables from dictionary?
Is something like the following possible in Python? >>> vars = {'a': 5} >>> makevars(vars) >>> print a 5 So, makevars converts the dictionary into variables. (What is this called in general?)
[ "It's possible, sometimes, but it's generally a very bad idea. In spite of their name, variables themselves should not be variable. They're part of your code, part of its logic. Trying to 'replace' local variables this way makes code inefficient (since Python has to drop some of its optimizations), buggy (since it ...
[ 10, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0003803419_python_variables.txt
Q: zc.buildout, Installing requirements into the parts directory? I am attempting to write a zc.buildout package that installs some of it's requirements into the parts directory. Any idea how this can be done? The reason for this is because the zc.buildout application itself is being distributed out, but parts of my package cannot go with it. So instead i would like to install them into the project/parts directory so that locally they can be used, but when the application is distributed they are left behind. To further clarify, take the following setup.py snipplet: include_package_data = True, install_requires = [ 'some_package', 'some_other_package', ], entry_points = { Now if i used that, some_package and some_other_package would be installed into the distributed application section. Then when the app is distributed, those would go with, which should not happen. Note that those two packages are any packages from pypi, i do not have control over their code. Any ideas? Currently i am experimenting with downloading the zipped packages myself, and unpacking them into the parts dir. This should work, but obviously it is missing much of the functionality of the packaging system, as i am statically linking to a single version of the package. Any help would be much appreciated! A: You can use omelette recipe in order to unzip all eggs and put in to one directory in parts directory. Example buildout.cfg [buildout] parts = my_omelette eggs = BeautifulSoup django-registration other_package_from_pypi unzip = true [my_omelette] recipe = collective.recipe.omelette eggs = ${buildout:eggs} This will install and unpack all eggs in to directory parts/my_omelette
zc.buildout, Installing requirements into the parts directory?
I am attempting to write a zc.buildout package that installs some of it's requirements into the parts directory. Any idea how this can be done? The reason for this is because the zc.buildout application itself is being distributed out, but parts of my package cannot go with it. So instead i would like to install them into the project/parts directory so that locally they can be used, but when the application is distributed they are left behind. To further clarify, take the following setup.py snipplet: include_package_data = True, install_requires = [ 'some_package', 'some_other_package', ], entry_points = { Now if i used that, some_package and some_other_package would be installed into the distributed application section. Then when the app is distributed, those would go with, which should not happen. Note that those two packages are any packages from pypi, i do not have control over their code. Any ideas? Currently i am experimenting with downloading the zipped packages myself, and unpacking them into the parts dir. This should work, but obviously it is missing much of the functionality of the packaging system, as i am statically linking to a single version of the package. Any help would be much appreciated!
[ "You can use omelette recipe in order to unzip all eggs and put in to one directory in parts directory. Example buildout.cfg\n[buildout]\nparts = my_omelette\neggs = \n BeautifulSoup\n django-registration\n other_package_from_pypi\n\nunzip = true\n\n[my_omelette]\nrecipe = collective.recipe.omelette\neggs ...
[ 2 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0003720231_buildout_python.txt
Q: Using mod_rewrite to hide the .py extension of a Python script accessed on a web browser I want to hide the .py extension of a Python script loaded in a web browser and still have the script run. For example: typing url.dev/basics/pythonscript in the address bar fires pythonscript.py and shows the results in the browser window. The URL url.dev/basics/pythonscript fetches the static file /pythonscript.py The browser still displays the url url.dev/basics//pythonscript Typing in url.dev/basics/pythonscript.py DOES work and the Python script results is displayed. I can also get mod_rewrite to rewrite url.dev/basics/phpscript to url.dev/basics/phpscript.php and run the PHP code successfully behind the scenes. But url.dev/basics/pythonscript does NOT redirect to url.dev/basics/pythonscript.py (I get a 404 Not Found). Background Info A) PHP rewriting works: the following in an .htaccess located in url.dev/basics/ WORKS for PHP scripts: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /basics/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php </IfModule> B) Python rewriting does NOT work: the following in an .htaccess located in url.dev/basics/ does NOT work for Python scripts (I get a 404 Not Found): <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /basics/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.py -f RewriteRule ^(.*)$ $1.py </IfModule> C) I am a beginning programmer working through Exercise 2: Your first program in the Basics section of Software Engineering for Internet Applications. I am trying to follow the recommendation to use an execution environment where 'One URL = one file', but want to use Python rather than PHP. I realize that this is not the best way to build a web application down the line. It is only a convention to be used during the initial part of the course linked above. D) I set up the Virtual Hosts development environment in OS 10.6 Snow Leopard so that I can access my development at url.dev as per 'Hacky Holidays' at adactio.com. My Python version is Python 2.6.1. E) I plan to use Django eventually, but want to work on simpler code first if possible so I can better understand what is going on. F) I have the following in my httpd.conf: TypesConfig /private/etc/apache2/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddHandler cgi-script .py and: LoadModule php5_module libexec/apache2/libphp5.so LoadModule fastcgi_module libexec/apache2/mod_fastcgi.so G) My Apache version (seen in server log after restarting the server): Apache/2.2.14 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.8l DAV/2 PHP/5.3.1 mod_fastcgi/2.4.2 configured -- resuming normal operations Looking forward to any help! A: If you are running on a linux box, dont use mod-rewrite - rename the script. you can call the script - pythonscript not pythonscript.py you add to the first line of the script pointing to your python interpreter and set the file to be executable with chmod +x pythonscript when the file is executed - it will read the first line of the file and execute the interpeter in the first line #!/usr/bin/python and then set the directory to execute the script to make this work, you change the files in the directory executable in your .htaccess file basics/.htaccess ----------- Options +ExecCGI SetHandler cgi-script ----------- Your python script will look like this basics/pythonscript ------- #!/usr/bin/python print "STATUS: 200 OK\n\n" print "hello world" ------ Warning... You may get an error in your error_log file that looks like this. [Thu Aug 05 19:26:34 2010] [alert] [client 127.0.0.1] /home/websites/testing/htdocs/basics/.htaccess: Option ExecCGI not allowed here If that happens your webserver is not allowing the changes from your .htaccess file Your webserver will need to be able to allow changes in your htaccess file so you may need to enable Allowoverride All in your httpd.conf file <Directory "/"> .... Allowoverride All </Directory> A: I found the solution: I needed to add the application MIME type so that the Apache Web Server understands it should run the code. In url.dev/basics/.htaccess add: <IfModule mime_module> AddType application/x-httpd-py .py </IfModule> Don't forget to restart Apache: sudo apachectl graceful And it works! http://url.dev/basics/pythonscript runs the code in pythonscript.py! Note that I'm not sure if this is the best way to do it, but it works. Here is my complete .htaccess file: # Options +ExecCGI # SetHandler cgi-script <IfModule mime_module> AddType application/x-httpd-py .py </IfModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /basics/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.py -f RewriteRule ^(.*)$ $1.py </IfModule>
Using mod_rewrite to hide the .py extension of a Python script accessed on a web browser
I want to hide the .py extension of a Python script loaded in a web browser and still have the script run. For example: typing url.dev/basics/pythonscript in the address bar fires pythonscript.py and shows the results in the browser window. The URL url.dev/basics/pythonscript fetches the static file /pythonscript.py The browser still displays the url url.dev/basics//pythonscript Typing in url.dev/basics/pythonscript.py DOES work and the Python script results is displayed. I can also get mod_rewrite to rewrite url.dev/basics/phpscript to url.dev/basics/phpscript.php and run the PHP code successfully behind the scenes. But url.dev/basics/pythonscript does NOT redirect to url.dev/basics/pythonscript.py (I get a 404 Not Found). Background Info A) PHP rewriting works: the following in an .htaccess located in url.dev/basics/ WORKS for PHP scripts: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /basics/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php </IfModule> B) Python rewriting does NOT work: the following in an .htaccess located in url.dev/basics/ does NOT work for Python scripts (I get a 404 Not Found): <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /basics/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.py -f RewriteRule ^(.*)$ $1.py </IfModule> C) I am a beginning programmer working through Exercise 2: Your first program in the Basics section of Software Engineering for Internet Applications. I am trying to follow the recommendation to use an execution environment where 'One URL = one file', but want to use Python rather than PHP. I realize that this is not the best way to build a web application down the line. It is only a convention to be used during the initial part of the course linked above. D) I set up the Virtual Hosts development environment in OS 10.6 Snow Leopard so that I can access my development at url.dev as per 'Hacky Holidays' at adactio.com. My Python version is Python 2.6.1. E) I plan to use Django eventually, but want to work on simpler code first if possible so I can better understand what is going on. F) I have the following in my httpd.conf: TypesConfig /private/etc/apache2/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddHandler cgi-script .py and: LoadModule php5_module libexec/apache2/libphp5.so LoadModule fastcgi_module libexec/apache2/mod_fastcgi.so G) My Apache version (seen in server log after restarting the server): Apache/2.2.14 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.8l DAV/2 PHP/5.3.1 mod_fastcgi/2.4.2 configured -- resuming normal operations Looking forward to any help!
[ "If you are running on a linux box, dont use mod-rewrite - rename the script. \nyou can call the script - pythonscript not pythonscript.py \nyou add to the first line of the script \n pointing to your python interpreter \nand set the file to be executable \nwith \nchmod +x pythonscript \n\nwhen the file is executed...
[ 4, 1 ]
[]
[]
[ "apache", "mod_rewrite", "python" ]
stackoverflow_0003418687_apache_mod_rewrite_python.txt
Q: Using regex in python i have the following problem. I want to escape all special characters in a python string. str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\1', str) 'eFEx\\1x\\1k\\1\\1\\1' str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\1', str) 'eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\\1', str) I can't seem to win here. '\1' indicates the special character and i want to add a '\' before this special character. but using \1 removes its special meaning and \\1 also does not help. A: Use r'\\\1'. That's a backslash (escaped, so denoted \\) followed by \1. To verify that this works, try: str = 'eFEx-x?k=;-' print re.sub("([^a-zA-Z0-9])",r'\\\1', str) This prints: eFEx\-x\?k\=\;\- which I think is what you want. Don't be confused when the interpreter outputs 'eFEx\\-x\\?k\\=\\;\\-'; the double backslashes are there because the interpreter quotes it output, unless you use print. A: Why don't you use re.escape()? str = 'eFEx-x?k=;-' re.escape(str) 'eFEx\\-x\\?k\\=\\;\\-' A: Try adding another backslash: s = 'eFEx-x?k=;-' print re.sub("([^a-zA-Z0-9])",r'\\\1', s)
Using regex in python
i have the following problem. I want to escape all special characters in a python string. str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\1', str) 'eFEx\\1x\\1k\\1\\1\\1' str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\1', str) 'eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\\1', str) I can't seem to win here. '\1' indicates the special character and i want to add a '\' before this special character. but using \1 removes its special meaning and \\1 also does not help.
[ "Use r'\\\\\\1'. That's a backslash (escaped, so denoted \\\\) followed by \\1.\nTo verify that this works, try:\nstr = 'eFEx-x?k=;-'\nprint re.sub(\"([^a-zA-Z0-9])\",r'\\\\\\1', str)\n\nThis prints:\neFEx\\-x\\?k\\=\\;\\-\n\nwhich I think is what you want. Don't be confused when the interpreter outputs 'eFEx\\\\-x...
[ 7, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003804149_python_regex.txt
Q: wx.TreeCtrl drag and drop, copy and move I'm trying to implement drag and drop on a wx.TreeCtrl and I need to handle both "copy" and "move" operations (if the user keeps CTRL pressed). First of all, I searched the wiki for an example and I'm confused as to which method to use.. Should I use DropSource/DropTarget or just handle EVT_TREE_BEGIN_DRAG and EVT_TREE_END_DRAG? If the latter, how can I tell if the user is requesting a "move" operation? (wxPython 2.8.9.1 on Ubuntu Jaunty) A: Reading the relevant paragraph from Cross-Platform GUI Programming with wxWidgets gave me the necessary insight to solve the issue :) In the end I went for the first solution (DropSource/DropTarget), so: tree.SetDropTarget(MyDropTarget()) tree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.on_drag) tree.GetMainWindow().Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda x: None) (The second bind avoids a mysterious "window that captured the mouse didn't process wxEVT_MOUSE_CAPTURE_LOST" on dragging) def on_drag(self, evt): # No evt.Allow() here, I won't use TreeCtrl's internal DND support item = evt.GetItem() if item == self.tree.GetRootItem(): return dropsrc = wx.DropSource(self) # Populate dropsource # ... dropsrc.DoDragDrop(wx.Drag_AllowMove)
wx.TreeCtrl drag and drop, copy and move
I'm trying to implement drag and drop on a wx.TreeCtrl and I need to handle both "copy" and "move" operations (if the user keeps CTRL pressed). First of all, I searched the wiki for an example and I'm confused as to which method to use.. Should I use DropSource/DropTarget or just handle EVT_TREE_BEGIN_DRAG and EVT_TREE_END_DRAG? If the latter, how can I tell if the user is requesting a "move" operation? (wxPython 2.8.9.1 on Ubuntu Jaunty)
[ "Reading the relevant paragraph from Cross-Platform GUI Programming with wxWidgets gave me the necessary insight to solve the issue :)\nIn the end I went for the first solution (DropSource/DropTarget), so:\ntree.SetDropTarget(MyDropTarget())\ntree.Bind(wx.EVT_TREE_BEGIN_DRAG, self.on_drag)\ntree.GetMainWindow().Bin...
[ 3 ]
[]
[]
[ "drag_and_drop", "python", "wxpython" ]
stackoverflow_0003803386_drag_and_drop_python_wxpython.txt
Q: network programming in python how do i run a python program that is received by a client from server without writing it into a new python file? A: code = "for a in range(10):\n\tprint 'lol'\n" eval(compile(code, 'downloaded_code_fake_filename', 'exec')) but Beware of Security Issues ! The source code should be cryptographically signed and not transmitted in plaintext. A: I'd recommend using execnet. It's well supported and from what I've read much safer than a raw exec or eval. For what you're trying to do check out the basic examples. A: see http://docs.python.org/py3k/library/functions.html#exec for the exec() function. it is not deprecated in py3.1. i recommend doing simply exec(code). values can be passed by inspecting variables in either the globals or locals dictionary: code = """ def f(): return 42 R = f() """ d = {} exec( code, d ) print( d[ 'R' ] ) A: Dcolish's answer is good. I'm not sure the idea of executing code that comes in on a network interface is good in itself, though - you will need to take care to verify that you can trust the sending party, especially if this interface is going to be exposed to the Internet or really any production network.
network programming in python
how do i run a python program that is received by a client from server without writing it into a new python file?
[ "code = \"for a in range(10):\\n\\tprint 'lol'\\n\"\neval(compile(code, 'downloaded_code_fake_filename', 'exec'))\n\nbut Beware of Security Issues ! The source code should be cryptographically signed and not transmitted in plaintext.\n", "I'd recommend using execnet. It's well supported and from what I've read m...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003798067_python.txt
Q: uploading records of list of files in parallel using python to DB I have a list of files each file have mass of records separting by \n , i need to proccess those records in parallel and upload them to some sql server could someone provide an idea what is the best way to do this with python A: The best way might not be to upload in parallell but use SQL Servers bulk importing mechanisims e.g. BULK INSERT bcp EDIT: If you need to process them then a way I have often used is 1) bulk load the data into a staging table 2) Process the data on the database 3) Insert into main tables Stages 2 and 3 can be combined if the processing is of a reasonable type. This could be faster as there are less round trips to the server and processing a set of data rather than row by row is usually quicker. Also I thing that SQL server will make use of more than one CPU in doing this processing so you get your processing parallel for free A: I would use a Pool. I have provided an example. For optimum throughput you will want to batch your inserts to the database. A simple way to do this is to process all of your records in python, then use the BULK INSERT tool from Mark's comment to do the inserts. It will be slower if you insert one at a time, since your program has to wait for the network round trip to the SQL server. from multiprocessing import Pool import sys def worker(record): print "Processing... %s" % (record) pool = Pool(processes=8) for record in sys.stdin: pool.apply_async(worker, [record]) pool.close() pool.join()
uploading records of list of files in parallel using python to DB
I have a list of files each file have mass of records separting by \n , i need to proccess those records in parallel and upload them to some sql server could someone provide an idea what is the best way to do this with python
[ "The best way might not be to upload in parallell but use SQL Servers bulk importing mechanisims\ne.g.\nBULK INSERT\nbcp\nEDIT:\nIf you need to process them then a way I have often used is\n1) bulk load the data into a staging table\n2) Process the data on the database\n3) Insert into main tables \nStages 2 and 3 ...
[ 1, 0 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0003802800_asynchronous_multithreading_python.txt
Q: Does File exist in Python? Possible Duplicate: Pythonic way to check if a file exists? How can Check if file exist with python 2.6? If file exists run exec redo.py. If file does not exists exec file start.py The file is a 0kb, but name Xxx100926.csv Ans seems to be from os path import exists from __future__ import with_statement if exists('Xxx100926.csv'): from redo import main #execfile(u'C:\redo.py') else: from start import main #execfile(u'C:\start.py') with open(Xxx100926.csv, 'a'): pass #and run main function main() A: you can put main function in redo.py and start.py and then from os path import exists if exists('Xxx100926.csv'): from redo import main else: from start import main #and run main function main()
Does File exist in Python?
Possible Duplicate: Pythonic way to check if a file exists? How can Check if file exist with python 2.6? If file exists run exec redo.py. If file does not exists exec file start.py The file is a 0kb, but name Xxx100926.csv Ans seems to be from os path import exists from __future__ import with_statement if exists('Xxx100926.csv'): from redo import main #execfile(u'C:\redo.py') else: from start import main #execfile(u'C:\start.py') with open(Xxx100926.csv, 'a'): pass #and run main function main()
[ "you can put main function in redo.py and start.py and then\nfrom os path import exists\n\nif exists('Xxx100926.csv'):\n from redo import main\nelse:\n from start import main\n\n#and run main function\nmain()\n\n" ]
[ 3 ]
[]
[]
[ "exists", "file_io", "path", "python" ]
stackoverflow_0003805132_exists_file_io_path_python.txt
Q: Inserting additional items into an inherited list in Django/Python I'm using some subclasses in my Django app, and I'm continuing that logic through to my admin implementation. Currently, I have this admin defintion: class StellarObjectAdmin(admin.ModelAdmin): list_display = ('title','created_at','created_by','updated_at','updated_by) Now, I have a Planet class, that is a subclass of StellarObject, with an additional field. I want to add this field to the list_display (not replace StellarObject's display entirely). If I try something like this: class PlanetAdmin(StellarObjectAdmin): list_display.insert(1,'size') I get the following error: name 'list_display' is not defined I will admit, I'm very new to python, and inheritance in general, so I'm sure that there is something simple I am missing. Thank you A: You'll need to use: StellarObjectAdmin.list_display.insert(1, 'size') Also, you'll need to change list_display from a tuple (which is immutable) to a list. Eg: list_display = [ ... ]. Finally, you'll probably be surprised by what happens: by inserting the item, you're going to be changing the list on StellarObjectAdmin. What you probably want to do is: list_display = list(StellarObjectAdmin.list_display) # copy the list list_display.insert(1, 'size') Which will create a new copy of the list for your PlanetAdmin class. This happens because of the way Python does inheritance. Basically, Python never injects names into a namespace (eg, some languages inject a magic this "variable" into methods, while Python forces you to explicitly define the equivalent — self — as the first argument of methods), and since a class is just another namespace, nothing (like, eg, values in its super classes) gets injected into it. When you've got a class, B, which inherits from another class, A, and you try to look up a property on B — B.foo — it first checks to see if foo is in B's namespace, and if it isn't, it goes on to check A's namespace, and so on. I hope that's clear… If not, I can clarify (or try to find relevant documentation). A: David is spot on. Also, as a note, if you want to reference the variable within the class, you'll need to use 'self.' Example: Class A: mylist = [1,2,3] def display_list(self): for i in self.mylist: print i
Inserting additional items into an inherited list in Django/Python
I'm using some subclasses in my Django app, and I'm continuing that logic through to my admin implementation. Currently, I have this admin defintion: class StellarObjectAdmin(admin.ModelAdmin): list_display = ('title','created_at','created_by','updated_at','updated_by) Now, I have a Planet class, that is a subclass of StellarObject, with an additional field. I want to add this field to the list_display (not replace StellarObject's display entirely). If I try something like this: class PlanetAdmin(StellarObjectAdmin): list_display.insert(1,'size') I get the following error: name 'list_display' is not defined I will admit, I'm very new to python, and inheritance in general, so I'm sure that there is something simple I am missing. Thank you
[ "You'll need to use:\nStellarObjectAdmin.list_display.insert(1, 'size')\n\nAlso, you'll need to change list_display from a tuple (which is immutable) to a list. Eg: list_display = [ ... ].\nFinally, you'll probably be surprised by what happens: by inserting the item, you're going to be changing the list on StellarO...
[ 2, 1 ]
[]
[]
[ "django", "django_admin", "list", "python" ]
stackoverflow_0003804666_django_django_admin_list_python.txt
Q: run out of system resource (execute many programs in a shell script) I'm running a shell script on the university's server. In this shell script, I will execute java, c, c++, python and perl programs. Because every program will be executed many many times(I'm a teaching assistant and will test the students' programs with many different inputs). The server always gives me an error: "running out of system resource". I guess this is due to I do not release the resource. I heard that running a program in the shell script one time will active one process. So I think maybe there are so many processes that the system recourse allocated for me has been run out. Is there any way to figure this problem out? I pose part of my shell code as following: # maxconnect4 is the compiled c code for ((i = 1; i <= 21; i++)) do maxconnect4 input1.txt done Thanks Zhong A: You seem to be running maxconnect4, then waitng for it to finish before starting the next run, so I don't think your shell script itself is the isuue. The big question is what maxconnect4 is doing. It could be very hungry for resources, or it itself could start child processes and return to your script. I would try a few experiments such as by hand start maxconnect4 a few times, do you se the resource error? I would also use system tools to invetsigate. For example use ps to see whether there are lots of processes running. Use vmstat to look at CPU and memory usage. A: Since you are automatically running students' programs then it may be that their programs are badly written and using more RAM than similar programs written by more skilled programmers would require. Even Java and Python programs can be written in such a way as to leak memory (think about a stack that never gets anything popped off of it, only more things pushed on). You should test your setup with known good implementations of the assignments you are about to grade as a sanity check. You should also look at the source code for the students' work. Especially if you get the error on their assignment. You may also just have an overloaded system, and may need to run these tests on another machine. Using a machine that does not have other users is a good idea for this type of thing, since things outside of your and the program you are testing aren't likely to mess up your tests. You may also want to keep top running on that machine on another terminal while you run the test to monitor resource usage.
run out of system resource (execute many programs in a shell script)
I'm running a shell script on the university's server. In this shell script, I will execute java, c, c++, python and perl programs. Because every program will be executed many many times(I'm a teaching assistant and will test the students' programs with many different inputs). The server always gives me an error: "running out of system resource". I guess this is due to I do not release the resource. I heard that running a program in the shell script one time will active one process. So I think maybe there are so many processes that the system recourse allocated for me has been run out. Is there any way to figure this problem out? I pose part of my shell code as following: # maxconnect4 is the compiled c code for ((i = 1; i <= 21; i++)) do maxconnect4 input1.txt done Thanks Zhong
[ "You seem to be running maxconnect4, then waitng for it to finish before starting the next run, so I don't think your shell script itself is the isuue. The big question is what maxconnect4 is doing. It could be very hungry for resources, or it itself could start child processes and return to your script.\nI would t...
[ 1, 1 ]
[]
[]
[ "c", "c++", "java", "python", "shell" ]
stackoverflow_0003801552_c_c++_java_python_shell.txt
Q: C# vs Python: XML Handling/Processing Productivity I am planning on writing a medium size web application that will be XML heavy. I will need to do heavy xml processing. When a user requests a webpage the program will fetch the XML from the database then it will process the XML then render the results to the browser. The XML is not big but i will need to make changes to the xml rules from time to time. My choices are asp.net mvc c# or python django. I need to know which one of these languages have the highest productivity in handling XML. Also, if you have any other suggestions besides c# or python please voice them. Thanks A: I am not familiar with C# but I dare say that it can competently mangle XML. So can Python, especially if you use something like lxml. Given this, and not knowing more about your specific background, I'd say it boils down to choice of programming language. If you like Python, Django is probably the most popular web framework. If you find C# more fun I guess ASP.NET MVC will be the way to go. I'd like to add a note about web hosting. If you are budget limited then you might find Python compatible (read *NIX) hosting cheaper compared to Windows. If budget is not such a big constraint then disregard this factor. Some people might have reservations about IDE support for Python. I have found PyDev quite up to the task for Python. There are of course plenty of other IDEs. A: I am not familiar with Python, but I dare say that it can competently mangle XML. So can .NET, especially if you use something like LINQ to XML. Given this, and not knowing more about your specific background, I'd say it boils down to choice of programming language. If you like C#, ASP.NET MVC will be the way to go. If you find Python more fun I guess Django is probably the most popular web framework. On a more serious, less cut-and-paste note, LINQ to XML is the nicest XML API I've used. Once you've grokked it - including the conversion operators available, and how it interacts with LINQ to Objects - it's truly lovely. Of course, the exact web framework you use is somewhat irrelevant to the XML processing - if your app is going to be doing lots of XML work, I'd certainly hope that most of the work would be done away from the UI layer anyway. Obviously it'll be somewhat easier if they're based on the same platform, but you could use IronPython for the UI and C# for the XML mangling, or vice versa.
C# vs Python: XML Handling/Processing Productivity
I am planning on writing a medium size web application that will be XML heavy. I will need to do heavy xml processing. When a user requests a webpage the program will fetch the XML from the database then it will process the XML then render the results to the browser. The XML is not big but i will need to make changes to the xml rules from time to time. My choices are asp.net mvc c# or python django. I need to know which one of these languages have the highest productivity in handling XML. Also, if you have any other suggestions besides c# or python please voice them. Thanks
[ "I am not familiar with C# but I dare say that it can competently mangle XML. So can Python, especially if you use something like lxml. Given this, and not knowing more about your specific background, I'd say it boils down to choice of programming language. If you like Python, Django is probably the most popular we...
[ 4, 4 ]
[]
[]
[ "asp.net_mvc_2", "c#", "django", "python" ]
stackoverflow_0003805563_asp.net_mvc_2_c#_django_python.txt
Q: Matplotlib draw boxes I have a set of data, where each value has a (x, y) coordinate. Different values can have the same coordinate. And I want to draw them in a rectangular collection of boxes. For example, if I have the data: A -> (0, 0) B -> (0, 1) C -> (1, 2) D -> (0, 1) I want to get the following drawing: 0 1 2 +++++++++++++ 0 + A + B + + + + D + + +++++++++++++ 1 + + + C + +++++++++++++ 2 + + + + +++++++++++++ How can I do it in Python using Matplotlib? THANKS! A: Just thought, maybe what you actually wanted to know was just this: def drawbox(list,x,y): # write some graphics code to draw box index x,y containing items 'list' [[drawbox(u,x,y) for u in X.keys() if X[u]==(y,x)] for x in range(0,3) for y in range(0,3)] A: Perhaps it would be better to use the ReportLab. Example A: # enter the data like this X={'A':(0,0),'B':(0,1),'C':(1,2),'D':(0,1)} # size of grid xi=map(tuple.__getitem__,X.values(),[1]*len(X)) yi=map(tuple.__getitem__,X.values(),[0]*len(X)) xrng = (min(xi), max(xi)+1) yrng = (min(yi), max(yi)+1) for y in range(*yrng): # rows print '+' * ((xrng[1]-xrng[0])*3) + '+' k={} # each item k[x] is list of elements in xth box in this row for x in range(*xrng): # list of items in this cell k[x]=[u for u in X.keys() if X[u]==(y,x)] h=max(map(len, k.values())) # row height for v in range(h): # lines of row c=[] for x in range(*xrng): # columns if k[x]: c.append(k[x][0]) del k[x][0] else: c.append(' ') # shorter cell s="+ " + "+ ".join(c) + "+" print s print "+" * ((xrng[1]-xrng[0])*3) + '+'
Matplotlib draw boxes
I have a set of data, where each value has a (x, y) coordinate. Different values can have the same coordinate. And I want to draw them in a rectangular collection of boxes. For example, if I have the data: A -> (0, 0) B -> (0, 1) C -> (1, 2) D -> (0, 1) I want to get the following drawing: 0 1 2 +++++++++++++ 0 + A + B + + + + D + + +++++++++++++ 1 + + + C + +++++++++++++ 2 + + + + +++++++++++++ How can I do it in Python using Matplotlib? THANKS!
[ "Just thought, maybe what you actually wanted to know was just this:\ndef drawbox(list,x,y):\n # write some graphics code to draw box index x,y containing items 'list'\n\n[[drawbox(u,x,y) for u in X.keys() if X[u]==(y,x)] for x in range(0,3) for y in range(0,3)]\n\n", "Perhaps it would be better to use the Repor...
[ 2, 1, 1 ]
[]
[]
[ "drawing", "matplotlib", "python" ]
stackoverflow_0003805000_drawing_matplotlib_python.txt
Q: Convert ascii encoding to int and back again in python (quickly) I have a file format (fastq format) that encodes a string of integers as a string where each integer is represented by an ascii code with an offset. Unfortunately, there are two encodings in common use, one with an offset of 33 and the other with an offset of 64. I typically have several 100 million strings of length 80-150 to convert from one offset to the other. The simplest code that I could come up with for doing this type of thing is: def phred64ToStdqual(qualin): return(''.join([chr(ord(x)-31) for x in qualin])) This works just fine, but it is not particularly fast. For 1 million strings, it takes about 4 seconds on my machine. If I change to using a couple of dicts to do the translation, I can get this down to about 2 seconds. ctoi = {} itoc = {} for i in xrange(127): itoc[i]=chr(i) ctoi[chr(i)]=i def phred64ToStdqual2(qualin): return(''.join([itoc[ctoi[x]-31] for x in qualin])) If I blindly run under cython, I get it down to just under 1 second. It seems like at the C-level, this is simply a cast to int, subtract, and then cast to char. I haven't written this up, but I'm guessing it is quite a bit faster. Any hints including how to better code a this in python or even a cython version to do this would be quite helpful. Thanks, Sean A: If you look at the code for urllib.quote, there is something that is similar to what you're doing. It looks like: _map = {} def phred64ToStdqual2(qualin): if not _map: for i in range(31, 127): _map[chr(i)] = chr(i - 31) return ''.join(map(_map.__getitem__, qualin)) Note that the above function works in case the mappings are not the same length (in urllib.quote, you have to take '%' -> '%25'. But actually, since every translation is the same length, python has a function that does just this very quickly: maketrans and translate. You probably won't get much faster than: import string _trans = None def phred64ToStdqual4(qualin): global _trans if not _trans: _trans = string.maketrans(''.join(chr(i) for i in range(31, 127)), ''.join(chr(i) for i in range(127 - 31))) return qualin.translate(_trans)
Convert ascii encoding to int and back again in python (quickly)
I have a file format (fastq format) that encodes a string of integers as a string where each integer is represented by an ascii code with an offset. Unfortunately, there are two encodings in common use, one with an offset of 33 and the other with an offset of 64. I typically have several 100 million strings of length 80-150 to convert from one offset to the other. The simplest code that I could come up with for doing this type of thing is: def phred64ToStdqual(qualin): return(''.join([chr(ord(x)-31) for x in qualin])) This works just fine, but it is not particularly fast. For 1 million strings, it takes about 4 seconds on my machine. If I change to using a couple of dicts to do the translation, I can get this down to about 2 seconds. ctoi = {} itoc = {} for i in xrange(127): itoc[i]=chr(i) ctoi[chr(i)]=i def phred64ToStdqual2(qualin): return(''.join([itoc[ctoi[x]-31] for x in qualin])) If I blindly run under cython, I get it down to just under 1 second. It seems like at the C-level, this is simply a cast to int, subtract, and then cast to char. I haven't written this up, but I'm guessing it is quite a bit faster. Any hints including how to better code a this in python or even a cython version to do this would be quite helpful. Thanks, Sean
[ "If you look at the code for urllib.quote, there is something that is similar to what you're doing. It looks like:\n_map = {}\ndef phred64ToStdqual2(qualin):\n if not _map:\n for i in range(31, 127):\n _map[chr(i)] = chr(i - 31)\n return ''.join(map(_map.__getitem__, qualin))\n\nNote that th...
[ 4 ]
[]
[]
[ "algorithm", "cython", "performance", "python" ]
stackoverflow_0003805763_algorithm_cython_performance_python.txt
Q: My facebook authentication is not working? I changed my domain from abc.com to xyz.com. After that my facebook authentication is not working. It is throwing a key error KeyError: 'access_token'I am using python as my language. A: You probably need to update the domain in the facebook settings/api key which allow you access.
My facebook authentication is not working?
I changed my domain from abc.com to xyz.com. After that my facebook authentication is not working. It is throwing a key error KeyError: 'access_token'I am using python as my language.
[ "You probably need to update the domain in the facebook settings/api key which allow you access.\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003806082_facebook_python.txt
Q: Django web interface components I am using python and django and like it a lot. But than i use it, I catch myself thinking what i do a lot of work to render result data and write specific actions for it. For example than i pass result set of objects to template i must render all data and write all possible actions such as sorting by columns,filtering,deletion,edit etc, for each of this i need to write code in urls.py and views.py, sometimes helps generic view but it's has poor functions. Is there some solutions to automate this work? i mean use some interface compontents (such as "model list renderer with column filter and pagination") to wich i need only "bind my model", all other routing work for drawing common interface action must be allready implemented in these components. i think i need something like configurable components for fast building html web interface for models (such as model forms do fast generation forms for models). What do you think can help in this case? A: must render all data and write all possible actions such as sorting by columns,filtering,deletion,edit etc Like django.contrib.admin? But I guess it's way to complicated and bloated for your needs. sometimes helps generic view but it's has poor functions And that's the way, I think, you should be going. If you write same views over and over again, just make your own generic views. As an example of more robust views and a source of inspiration I recommend you to look at class-based generic views. Also consider using model inheritance and custom managers.
Django web interface components
I am using python and django and like it a lot. But than i use it, I catch myself thinking what i do a lot of work to render result data and write specific actions for it. For example than i pass result set of objects to template i must render all data and write all possible actions such as sorting by columns,filtering,deletion,edit etc, for each of this i need to write code in urls.py and views.py, sometimes helps generic view but it's has poor functions. Is there some solutions to automate this work? i mean use some interface compontents (such as "model list renderer with column filter and pagination") to wich i need only "bind my model", all other routing work for drawing common interface action must be allready implemented in these components. i think i need something like configurable components for fast building html web interface for models (such as model forms do fast generation forms for models). What do you think can help in this case?
[ "\nmust render all data and write all\n possible actions such as sorting by\n columns,filtering,deletion,edit etc\n\nLike django.contrib.admin? But I guess it's way to complicated and bloated for your needs.\n\nsometimes helps generic view but it's\n has poor functions\n\nAnd that's the way, I think, you should ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003805970_django_python.txt
Q: How do I create a Django model field that evaluates based on other fields? I'll try to describe my problem with a simple example. Say I have items of type Item and every item relates to a certain type of Category. Now I can take any two items and combine into an itemcombo of type ItemCombo. This itemcombo relates to a certain category called ComboCategory. The ComboCategory is based on which categories the items relate to, therefore I'm not to keen on hardcoding the combocategory in ItemCombo in case the items categories would change. Can I somehow make combocategory a virtual field in ItemCombo that evaluates just in time? class Category(models.Model): value = models.CharField(max_length=1) class Item(models.Model): value = models.CharField(max_length=10) category = models.ForeignKey(Category) class ComboCategory(models.Model): category1 = models.ForeignKey(Category) category2 = models.ForeignKey(Category) value = models.CharField(max_length=1) class ItemCombo(models.Model): item1 = models.ForeignKey(Item) item2 = models.ForeignKey(Item) combocategory = models.ForeignKey(ComboCategory) A: Your model classes are full Python classes, so you can add attributes, methods, and properties to them: class ItemCombo(models.Model): item1 = models.ForeignKey(Item) item2 = models.ForeignKey(Item) @property def combocategory(self): return .. # some mumbo-jumbo of item1 and item2 A: The issue is that you can only do queries on fields that are stored in the database. Now you should look at aggregation for a way to evaluate your ItemCombo just in time and do filtering on it.
How do I create a Django model field that evaluates based on other fields?
I'll try to describe my problem with a simple example. Say I have items of type Item and every item relates to a certain type of Category. Now I can take any two items and combine into an itemcombo of type ItemCombo. This itemcombo relates to a certain category called ComboCategory. The ComboCategory is based on which categories the items relate to, therefore I'm not to keen on hardcoding the combocategory in ItemCombo in case the items categories would change. Can I somehow make combocategory a virtual field in ItemCombo that evaluates just in time? class Category(models.Model): value = models.CharField(max_length=1) class Item(models.Model): value = models.CharField(max_length=10) category = models.ForeignKey(Category) class ComboCategory(models.Model): category1 = models.ForeignKey(Category) category2 = models.ForeignKey(Category) value = models.CharField(max_length=1) class ItemCombo(models.Model): item1 = models.ForeignKey(Item) item2 = models.ForeignKey(Item) combocategory = models.ForeignKey(ComboCategory)
[ "Your model classes are full Python classes, so you can add attributes, methods, and properties to them:\nclass ItemCombo(models.Model):\n item1 = models.ForeignKey(Item)\n item2 = models.ForeignKey(Item)\n\n @property\n def combocategory(self):\n return .. # some mumbo-jumbo of i...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003804502_django_django_models_python.txt
Q: Python regular expressions what is the regular expressions that will identify the class of valid NRIC numbers (inclusive of the ending alphabets) A: Assuming you mean the Singaporean National Registration Identity Card, try: ^[SFTG]\d{7}[A-Z]$ This follows the structure documented by Wikipedia. Note that the last letter is a checksum, and that if you want to check the checksum you’ll have to do so separately. A: Regex patterns for many common uses can be found at regexlib.com. For NRIC try: http://www.regexlib.com/Search.aspx?k=nric This suggests a pattern of: ^[SFTG]\d{7}[A-Z]$ A: Let us see. Alphabet for the first letter: [a-z] (We'll ignore case later) Seven digits: \d{7} (hint: d is for digits ;)) Another alphabet: [a-z] Putting them together we get: [a-z]\d{7}[a-z]. In python this would be: import re obj = re.compile('[a-z]\d{7}[a-z]', re.IGNORECASE) obj.match('S1234567E') You don't have to compile() the regular expression if you are planning to use it only once. But in case you are planning to match the same expression against multiple strings then it would be a good idea to compile it. Reference: documentation for the re module.
Python regular expressions
what is the regular expressions that will identify the class of valid NRIC numbers (inclusive of the ending alphabets)
[ "Assuming you mean the Singaporean National Registration Identity Card, try:\n^[SFTG]\\d{7}[A-Z]$\n\nThis follows the structure documented by Wikipedia.\nNote that the last letter is a checksum, and that if you want to check the checksum you’ll have to do so separately.\n", "Regex patterns for many common uses ca...
[ 5, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003806155_python_regex.txt
Q: New to google app engine ! what to do next? I want to develop some web apps using Google app engine. I had deployed a guest book application which was their in "gooleappengine" folder by changing its ID.and also was successful.This is simple one.But not getting how to develop complex web apps. Can anyone please suggest me any good Tutarial or example codes Or any books to refer. A: Here are some good resources : Articles : Official documentation : http://code.google.com/appengine/docs/python/overview.html Nick Johnson's blog : http://blog.notdot.net Google App Engine articles : http://code.google.com/appengine/articles/ Code examples : Google App Engine Cookbook : http://appengine-cookbook.appspot.com/ Github repositories : http://github.com/search?type=Repositories&language=python&q=appengine Google Project Hosting projects : http://code.google.com/hosting/search?q=label%3Apython+label%3AAppEngine&btn=Search+projects A: Typically when I end up doing something more than a trivial demo I need a reason. Figure out something you want to make and stumble through it, learning as you go until it's working. I'd use the google app engine community as a place to get questions answered, they're pretty good for that. As a first app, I'd just have a goal that you're working towards and start asking the community "how do I do this...?"
New to google app engine ! what to do next?
I want to develop some web apps using Google app engine. I had deployed a guest book application which was their in "gooleappengine" folder by changing its ID.and also was successful.This is simple one.But not getting how to develop complex web apps. Can anyone please suggest me any good Tutarial or example codes Or any books to refer.
[ "Here are some good resources :\nArticles :\n\nOfficial documentation :\nhttp://code.google.com/appengine/docs/python/overview.html\nNick Johnson's blog :\nhttp://blog.notdot.net\nGoogle App Engine articles :\nhttp://code.google.com/appengine/articles/\n\nCode examples :\n\nGoogle App Engine Cookbook :\nhttp://appe...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003805802_google_app_engine_python.txt
Q: How to get field with ForeignKey('self') without the possibility to link to same entry? I came in touch with a little problem while building a model with a foreign key to itself. Here an example: class Example (model.Model): parent = models.ForeignKey('self', null=True, blank=True) # and some other fields After creating a new entry in the admin panel and going into this example for editing some content, I realize that I could set the parent to the current entry. But thats not what I wanted to get with the ForeignKey and the relation to itself. Is it possible to disallow the link to itself? Maybe it's better to use a integer field with the right choices but I'm not quiet sure how to realize this an a smooth and Python like way. A: one way to do this would be to override the model's clean method class Example(model.Model): #... def clean(self): if self.parent.id == self.id: raise ValidationError("no self referential models") this will be called as the second step of object validation and will prevent the object from being inserted in the database. A: It is possible to disallow a link from an instance to the same instance. One way to achieve this would be to add a custom model validation. For e.g. class Example(models.Model): ... def clean_fields(self): if self.id and self.parent.id == self.id: raise ValidationError(...)
How to get field with ForeignKey('self') without the possibility to link to same entry?
I came in touch with a little problem while building a model with a foreign key to itself. Here an example: class Example (model.Model): parent = models.ForeignKey('self', null=True, blank=True) # and some other fields After creating a new entry in the admin panel and going into this example for editing some content, I realize that I could set the parent to the current entry. But thats not what I wanted to get with the ForeignKey and the relation to itself. Is it possible to disallow the link to itself? Maybe it's better to use a integer field with the right choices but I'm not quiet sure how to realize this an a smooth and Python like way.
[ "one way to do this would be to override the model's clean method\nclass Example(model.Model):\n #...\n def clean(self):\n if self.parent.id == self.id:\n raise ValidationError(\"no self referential models\")\n\nthis will be called as the second step of object validation and will prevent the...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003806346_django_django_models_python.txt
Q: How to change my wx.toolbar event? I have a wx.toolbar with some buttons. One of the buttons makes pan left! I want to click on the button and while I keep it pressed, the pan left is made. For now I only saw that the wx.EVT_TOOL only works when mouse left is up. Is there a way to do what I intend ? A: In the toolbar button's event, you should be able to get the state of the mouse via wx.GetMouseState. Alternatively, you can make your own toolbar with a panel and some wx.Buttons (or other button widgets).
How to change my wx.toolbar event?
I have a wx.toolbar with some buttons. One of the buttons makes pan left! I want to click on the button and while I keep it pressed, the pan left is made. For now I only saw that the wx.EVT_TOOL only works when mouse left is up. Is there a way to do what I intend ?
[ "In the toolbar button's event, you should be able to get the state of the mouse via wx.GetMouseState.\nAlternatively, you can make your own toolbar with a panel and some wx.Buttons (or other button widgets).\n" ]
[ 1 ]
[]
[]
[ "events", "mouseevent", "python", "wxpython" ]
stackoverflow_0003793526_events_mouseevent_python_wxpython.txt
Q: PyObject_CallFunction Access violation writing location 0x0000000c I am trying to wrap a c communication library in python and am having some trouble when I attempt to handle large amounts of data. The following code will work for smaller messages but when the message is larger than 400MB I get the following error from the PyObject_CallFunction call: Unhandled exception at 0x1e00d65f in python.exe: 0xC0000005: Access violation writing location 0x0000000c. int request_callback(c_request* req, c_msg* msg, void* client) { PyGILState_STATE gstate; PyObject* callback; PyObject* result; unsigned int request_addr; PyObject* py_request_addr; PyObject* message; gstate = PyGILState_Ensure(); request_addr = (unsigned int)req; py_request_addr = PyInt_FromLong(request_addr); if (PyDict_Contains(request_callback_dict, py_request_addr) == 1) { callback = PyDict_GetItem(request_callback_dict, py_request_addr); message = PyString_FromStringAndSize(msg->data, msg->len); result = PyObject_CallFunction(callback, "O", message); } PyGILState_Release(gstate); return 0; } Any thoughts as to what could cause this. Thanks. A: After debugging the code further it is actually a problem with the the python code that uses the string. The string is a google protocol buffer and when the data is written from a file and the bytes are parsed I can catch a python exception thrown by the library.
PyObject_CallFunction Access violation writing location 0x0000000c
I am trying to wrap a c communication library in python and am having some trouble when I attempt to handle large amounts of data. The following code will work for smaller messages but when the message is larger than 400MB I get the following error from the PyObject_CallFunction call: Unhandled exception at 0x1e00d65f in python.exe: 0xC0000005: Access violation writing location 0x0000000c. int request_callback(c_request* req, c_msg* msg, void* client) { PyGILState_STATE gstate; PyObject* callback; PyObject* result; unsigned int request_addr; PyObject* py_request_addr; PyObject* message; gstate = PyGILState_Ensure(); request_addr = (unsigned int)req; py_request_addr = PyInt_FromLong(request_addr); if (PyDict_Contains(request_callback_dict, py_request_addr) == 1) { callback = PyDict_GetItem(request_callback_dict, py_request_addr); message = PyString_FromStringAndSize(msg->data, msg->len); result = PyObject_CallFunction(callback, "O", message); } PyGILState_Release(gstate); return 0; } Any thoughts as to what could cause this. Thanks.
[ "After debugging the code further it is actually a problem with the the python code that uses the string. The string is a google protocol buffer and when the data is written from a file and the bytes are parsed I can catch a python exception thrown by the library.\n" ]
[ 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003805025_c_python.txt
Q: Function to validate an E-mail (IDN aware) Is there any python function that validates E-mail addresses, aware of IDN domains ? For instance, user@example.com should be as correct as user@zääz.de or user@納豆.ac.jp Thanks. A: Django supports IDN email validation as of version 1.2. See the code for validation here: http://code.djangoproject.com/svn/django/trunk/django/core/validators.py Reference: http://docs.djangoproject.com/en/1.2/ref/forms/fields/#emailfield Example: Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from django.core.validators import validate_email >>> try: validate_email(u'user@example.com'); print "passed" ... except: print "failed" ... passed >>> try: validate_email(u'user@zääz.de'); print "passed" ... except: print "failed" ... passed >>> try: validate_email(u'user@納豆.ac.jp'); print "passed" ... except: print "failed" ... passed >>> try: validate_email(u'this-should-fail@@納豆.ac.jp'); print "passed" ... except: print "failed" ... failed You may need to define some environment settings before you can use Django modules, see documentation here: http://docs.djangoproject.com/en/dev/ A: It is very difficult to validate an e-mail address because the syntax is so flexible. The best strategy is to send a test e-mail to the entered address. A: I think the best method is to open the mail server port via a HTTP Request and see if it responds web = httplib.HTTPConnection(domain, 25, timeout=5) web.connect() And check to see if that opens up.
Function to validate an E-mail (IDN aware)
Is there any python function that validates E-mail addresses, aware of IDN domains ? For instance, user@example.com should be as correct as user@zääz.de or user@納豆.ac.jp Thanks.
[ "Django supports IDN email validation as of version 1.2. \nSee the code for validation here: http://code.djangoproject.com/svn/django/trunk/django/core/validators.py\nReference: http://docs.djangoproject.com/en/1.2/ref/forms/fields/#emailfield\nExample:\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003806393_python.txt
Q: Altering data in GQL I need to change values for an entry, but the following code doesn't work. logList = db.GqlQuery("SELECT * FROM Log ORDER BY date DESC LIMIT 1") logList[0].content = "some text" db.put(logList) The value for the newest element doesn't change when I run this. I checked the output with Print, it gives correct value (to what the content field should be changed & the correct old value) and gives the following status code: Status: 302 Moved Temporarily Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Location: http://localhost:8080/admin/editl Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 0 What is wrong with my code? The used method of altering data was mentioned in the official docs. A: logList = db.GqlQuery("SELECT * FROM Log ORDER BY date DESC LIMIT 1") result = logList.get() result.content = "some text" result.put() Try this. You are confusing the GqlQuery object for the results of actually eexecuting the query.
Altering data in GQL
I need to change values for an entry, but the following code doesn't work. logList = db.GqlQuery("SELECT * FROM Log ORDER BY date DESC LIMIT 1") logList[0].content = "some text" db.put(logList) The value for the newest element doesn't change when I run this. I checked the output with Print, it gives correct value (to what the content field should be changed & the correct old value) and gives the following status code: Status: 302 Moved Temporarily Content-Type: text/html; charset=utf-8 Cache-Control: no-cache Location: http://localhost:8080/admin/editl Expires: Fri, 01 Jan 1990 00:00:00 GMT Content-Length: 0 What is wrong with my code? The used method of altering data was mentioned in the official docs.
[ "logList = db.GqlQuery(\"SELECT * FROM Log ORDER BY date DESC LIMIT 1\")\nresult = logList.get()\nresult.content = \"some text\"\nresult.put()\n\nTry this. You are confusing the GqlQuery object for the results of actually eexecuting the query.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0003806023_google_app_engine_gql_python.txt
Q: Subsetting data in Python I want to use the equivalent of the subset command in R for some Python code I am writing. Here is my data: col1 col2 col3 col4 col5 100002 2006 1.1 0.01 6352 100002 2006 1.2 0.84 304518 100002 2006 2 1.52 148219 100002 2007 1.1 0.01 6292 10002 2006 1.1 0.01 5968 10002 2006 1.2 0.25 104318 10002 2007 1.1 0.01 6800 10002 2007 4 2.03 25446 10002 2008 1.1 0.01 6408 I want to subset the data based on contents of col1 and col2. (The unique values in col1 are 100002 and 10002, and in col2 are 2006,2007 and 2008.) This can be done in R using the subset command, is there anything similar in Python? A: While the iterator-based answers are perfectly fine, if you're working with numpy arrays (as you mention that you are) there are better and faster ways of selecting things: import numpy as np data = np.array([ [100002, 2006, 1.1, 0.01, 6352], [100002, 2006, 1.2, 0.84, 304518], [100002, 2006, 2, 1.52, 148219], [100002, 2007, 1.1, 0.01, 6292], [10002, 2006, 1.1, 0.01, 5968], [10002, 2006, 1.2, 0.25, 104318], [10002, 2007, 1.1, 0.01, 6800], [10002, 2007, 4, 2.03, 25446], [10002, 2008, 1.1, 0.01, 6408] ]) subset1 = data[data[:,0] == 100002] subset2 = data[data[:,0] == 10002] This yields subset1: array([[ 1.00002e+05, 2.006e+03, 1.10e+00, 1.00e-02, 6.352e+03], [ 1.00002e+05, 2.006e+03, 1.20e+00, 8.40e-01, 3.04518e+05], [ 1.00002e+05, 2.006e+03, 2.00e+00, 1.52e+00, 1.48219e+05], [ 1.00002e+05, 2.007e+03, 1.10e+00, 1.00e-02, 6.292e+03]]) subset2: array([[ 1.0002e+04, 2.006e+03, 1.10e+00, 1.00e-02, 5.968e+03], [ 1.0002e+04, 2.006e+03, 1.20e+00, 2.50e-01, 1.04318e+05], [ 1.0002e+04, 2.007e+03, 1.10e+00, 1.00e-02, 6.800e+03], [ 1.0002e+04, 2.007e+03, 4.00e+00, 2.03e+00, 2.5446e+04], [ 1.0002e+04, 2.008e+03, 1.10e+00, 1.00e-02, 6.408e+03]]) If you didn't know the unique values in the first column beforehand, you can use either numpy.unique1d or the builtin function set to find them. Edit: I just realized that you wanted to select data where you have unique combinations of two columns... In that case, you might do something like this: col1 = data[:,0] col2 = data[:,1] subsets = {} for val1, val2 in itertools.product(np.unique(col1), np.unique(col2)): subset = data[(col1 == val1) & (col2 == val2)] if np.any(subset): subsets[(val1, val2)] = subset (I'm storing the subsets as a dict, with the key being a tuple of the combination... There are certainly other (and better, depending on what you're doing) ways to do this!) A: subset() in R is pretty much analogous to filter() in Python. As the reference notes, this will be used implicitly by list comprehensions, so the most concise and clear way to write the code might be [ item for item in items if item.col2 == 2006 ] if, for example, your data rows were in an iterable called items. A: Since I'm not familiar with R nor how this subset command works based upon your description I can suggest you take a look at itertool's groupby functionality. If given a function which outputs a value, you can form groups based upon that function's output. Taken from groupby: groups = [] uniquekeys = [] data = sorted(data, key=keyfunc) for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) and then you've got your subsets. However, do be careful as the values returned are not full fledged lists. They're iterators. I am assuming that your values are being returned on a row-by-row basis.
Subsetting data in Python
I want to use the equivalent of the subset command in R for some Python code I am writing. Here is my data: col1 col2 col3 col4 col5 100002 2006 1.1 0.01 6352 100002 2006 1.2 0.84 304518 100002 2006 2 1.52 148219 100002 2007 1.1 0.01 6292 10002 2006 1.1 0.01 5968 10002 2006 1.2 0.25 104318 10002 2007 1.1 0.01 6800 10002 2007 4 2.03 25446 10002 2008 1.1 0.01 6408 I want to subset the data based on contents of col1 and col2. (The unique values in col1 are 100002 and 10002, and in col2 are 2006,2007 and 2008.) This can be done in R using the subset command, is there anything similar in Python?
[ "While the iterator-based answers are perfectly fine, if you're working with numpy arrays (as you mention that you are) there are better and faster ways of selecting things:\nimport numpy as np\ndata = np.array([\n [100002, 2006, 1.1, 0.01, 6352],\n [100002, 2006, 1.2, 0.84, 304518],\n [100002,...
[ 21, 5, 2 ]
[]
[]
[ "arrays", "numpy", "python", "r", "subset" ]
stackoverflow_0003806878_arrays_numpy_python_r_subset.txt
Q: how to have command as input for a shell launched inside a python subprocess I want to create a GUI python script to launch several processes. All of these processes originally were called by setting up a shell with a perl script (start_workspace.perl), and type the executable file name under the shell. inside, start_workspace.perl, it first set some ENV variables, and then call exec(/bin/bash), which launch the shell, so you can type "execfile" under the prompt to launch. my problem, from my python script, I still want to use this shell (by subprocess.popen("perl start_workspace.perl")), but I do not want to be stopped to manually input "execfile". I want someway that I can specify the "execfile" at step of calling "start_workspace.perl", and the process can completed without any intervention. something like command redirection. but I do not know if it is possible. subprocess.popen(("perl start_workspace.perl") < "execfile") A: You are very close. In the subprocess documentation, see: stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. stdin, stderr, and stdout are named parameters for the popen method. You can open the input file and pass its file descriptor as stdin to your new process. A: Using the subprocess module, it could be achieved this way. You can use the stdin stream to write your command to execute once the actual environment has been set. start_workspace.perl print "Perl: Setting some env variables\n"; $ENV{"SOME_VAR"} = "some value"; print "Perl: Starting bash\n"; exec('bash'); In python: import subprocess p = subprocess.Popen( "perl start_workspace.perl", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) p.stdin.write('echo "Python: $SOME_VAR"\n') p.stdin.write("make\n") (stdoutdata, stderrdata) = p.communicate() print stdoutdata print stderrdata Output is Perl: Setting some env variables Perl: Starting bash Python: some value make: *** No targets specified and no makefile found. Stop.
how to have command as input for a shell launched inside a python subprocess
I want to create a GUI python script to launch several processes. All of these processes originally were called by setting up a shell with a perl script (start_workspace.perl), and type the executable file name under the shell. inside, start_workspace.perl, it first set some ENV variables, and then call exec(/bin/bash), which launch the shell, so you can type "execfile" under the prompt to launch. my problem, from my python script, I still want to use this shell (by subprocess.popen("perl start_workspace.perl")), but I do not want to be stopped to manually input "execfile". I want someway that I can specify the "execfile" at step of calling "start_workspace.perl", and the process can completed without any intervention. something like command redirection. but I do not know if it is possible. subprocess.popen(("perl start_workspace.perl") < "execfile")
[ "You are very close. In the subprocess documentation, see:\n\nstdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indica...
[ 2, 1 ]
[]
[]
[ "command", "input", "python", "subprocess" ]
stackoverflow_0003806784_command_input_python_subprocess.txt
Q: AI and Design of an El-fish like simulator environment? first post here on stack overflow, hoping to get some advice on how to construct a simulation program akin to the 1993 maxis simulator known as El-Fish wiki here , Also, game info here . Are there known "Simulation system" algorithm groups that can function and create real life interaction etc... e.g. the visualization known as 'flocking' ? Or, is there an open-source code base to study off of already in construction? Programming wise, would this also be able to be easily done in a purely functional language? if done in an OOP way, i was thinking of prototyping it in python. Anyways thanks for any direction in pointing me towards a good starting place. I hope to build a graphical view of an idea/data world. It will be hopefully controlled by underlying simulation AI(heuristics maybe?) A: In terms of simulation systems, I recommend you search for "agent-based modeling" software. There are a lot of free toolkits available. The two I like the most are NetLogo and Repast. Also, it looks like you are implementing a "genetic algorithm". There are many good books and pages on that topic. Python is good, but so are many other languages. Most of your time will be spent doing the graphics: animating the fish so they look realistic. Unless you can find a free fish-animation-library. A: I recommend you try my own GarlicSim framework. It's written in Python and you'll be writing your specific simulation in Python. It can definitely handle the kind of simulation you want. There are tutorials available which will teach you the basics of GarlicSim in 30 minutes. I'll be happy to help you build your simulation package, just say hello on the mailing list and I'll guide you from there. A: I'm not sure about "real life", but there is a flocking algorithm called boids that might be a good example to start from. There are a couple python versions of it as well. There's one that is an example in the owyl project on google code.
AI and Design of an El-fish like simulator environment?
first post here on stack overflow, hoping to get some advice on how to construct a simulation program akin to the 1993 maxis simulator known as El-Fish wiki here , Also, game info here . Are there known "Simulation system" algorithm groups that can function and create real life interaction etc... e.g. the visualization known as 'flocking' ? Or, is there an open-source code base to study off of already in construction? Programming wise, would this also be able to be easily done in a purely functional language? if done in an OOP way, i was thinking of prototyping it in python. Anyways thanks for any direction in pointing me towards a good starting place. I hope to build a graphical view of an idea/data world. It will be hopefully controlled by underlying simulation AI(heuristics maybe?)
[ "In terms of simulation systems, I recommend you search for \"agent-based modeling\" software. There are a lot of free toolkits available. The two I like the most are NetLogo and Repast.\nAlso, it looks like you are implementing a \"genetic algorithm\". There are many good books and pages on that topic.\nPython is ...
[ 2, 1, 1 ]
[]
[]
[ "artificial_intelligence", "python", "simulation" ]
stackoverflow_0003745093_artificial_intelligence_python_simulation.txt
Q: Printing results in reverse order from raw_input in python When using raw_input in a loop, until a certain character is typed (say 'a'), how can I print all the inputs before that, in reverse order, without storing the inputs in a data structure? Using a string is simple: def foo(): x = raw_input("Enter character: ") string = "" while not (str(x) == "a"): string = str(x) + "\n" + string x = raw_input("Enter character: ") print string.strip() but how could I do the same without a string? A: This is not a practical approach, but since you asked for it: def getchar(): char = raw_input("Enter character: ") if char != 'a': getchar() print char getchar() Of course this only means that I'm using "hidden" data structures, the local namespace and the call stack. A: You have to store the results in some data structure. Instead of a string, however, you could store each input in a list and avoid all the string concatenation: l = [] x = raw_input("Enter character: ") while not (str(x) == 'a'): l.append(x) x = raw_input("Enter character: ") print '\n'.join(l[::-1])
Printing results in reverse order from raw_input in python
When using raw_input in a loop, until a certain character is typed (say 'a'), how can I print all the inputs before that, in reverse order, without storing the inputs in a data structure? Using a string is simple: def foo(): x = raw_input("Enter character: ") string = "" while not (str(x) == "a"): string = str(x) + "\n" + string x = raw_input("Enter character: ") print string.strip() but how could I do the same without a string?
[ "This is not a practical approach, but since you asked for it:\ndef getchar():\n char = raw_input(\"Enter character: \")\n if char != 'a':\n getchar()\n print char\n\ngetchar()\n\nOf course this only means that I'm using \"hidden\" data structures, the local namespace and the call stack.\n", "...
[ 5, 2 ]
[]
[]
[ "python", "raw_input" ]
stackoverflow_0003807336_python_raw_input.txt
Q: python, subprocess: reading output from subprocess I have following script: #!/usr/bin/python while True: x = raw_input() print x[::-1] I am calling it from ipython: In [5]: p = Popen('./script.py', stdin=PIPE) In [6]: p.stdin.write('abc\n') cba and it works fine. However, when I do this: In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [8]: p.stdin.write('abc\n') In [9]: p.stdout.read() the interpreter hangs. What am I doing wrong? I would like to be able to both write and read from another process multiple times, to pass some tasks to this process. What do I need to do differently? EDIT 1 If I use communicate, I get this: In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [8]: p.communicate('abc\n') Traceback (most recent call last): File "./script.py", line 4, in <module> x = raw_input() EOFError: EOF when reading a line Out[8]: ('cba\n', None) EDIT 2 I tried flushing: #!/usr/bin/python import sys while True: x = raw_input() print x[::-1] sys.stdout.flush() and here: In [5]: from subprocess import PIPE, Popen In [6]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [7]: p.stdin.write('abc') In [8]: p.stdin.flush() In [9]: p.stdout.read() but it hangs again. A: I believe there are two problems at work here: 1) Your parent script calls p.stdout.read(), which will read all data until end-of-file. However, your child script runs in an infinite loop so end-of-file will never happen. Probably you want p.stdout.readline()? 2) In interactive mode, most programs do buffer only one line at a time. When run from another program, they buffer much more. The buffering improves efficiency in many cases, but causes problems when two programs need to communicate interactively. After p.stdin.write('abc\n') add: p.stdin.flush() In your subprocess script, after print x[::-1] add the following within the loop: sys.stdout.flush() (and import sys at the top) A: The subprocess method check_output can be useful for this: output = subprocess.check_output('./script.py') And output will be the stdout from the process. If you need stderr, too: output = subprocess.check_output('./script.py', stderr=subprocess.STDOUT) Because you avoid managing pipes directly, it may circumvent your issue. A: If you'd like to pass several lines to script.py then you need to read/write simultaneously: #!/usr/bin/env python import sys from subprocess import PIPE, Popen from threading import Thread def print_output(out, ntrim=80): for line in out: print len(line) if len(line) > ntrim: # truncate long output line = line[:ntrim-2]+'..' print line.rstrip() if __name__=="__main__": p = Popen(['python', 'script.py'], stdin=PIPE, stdout=PIPE) Thread(target=print_output, args=(p.stdout,)).start() for s in ['abc', 'def', 'ab'*10**7, 'ghi']: print >>p.stdin, s p.stdin.close() sys.exit(p.wait()) #NOTE: read http://docs.python.org/library/subprocess.html#subprocess.Popen.wait Output: 4 cba 4 fed 20000001 bababababababababababababababababababababababababababababababababababababababa.. 4 ihg Where script.py: #!/usr/bin/env python """Print reverse lines.""" while True: try: x = raw_input() except EOFError: break # no more input else: print x[::-1] Or #!/usr/bin/env python """Print reverse lines.""" import sys for line in sys.stdin: print line.rstrip()[::-1] Or #!/usr/bin/env python """Print reverse lines.""" import fileinput for line in fileinput.input(): # accept files specified as command line arguments print line.rstrip()[::-1] A: You're probably tripping over Python's output buffering. Here's what python --help has to say about it. -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u' A: When you are through writing to p.stdin, close it: p.stdin.close()
python, subprocess: reading output from subprocess
I have following script: #!/usr/bin/python while True: x = raw_input() print x[::-1] I am calling it from ipython: In [5]: p = Popen('./script.py', stdin=PIPE) In [6]: p.stdin.write('abc\n') cba and it works fine. However, when I do this: In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [8]: p.stdin.write('abc\n') In [9]: p.stdout.read() the interpreter hangs. What am I doing wrong? I would like to be able to both write and read from another process multiple times, to pass some tasks to this process. What do I need to do differently? EDIT 1 If I use communicate, I get this: In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [8]: p.communicate('abc\n') Traceback (most recent call last): File "./script.py", line 4, in <module> x = raw_input() EOFError: EOF when reading a line Out[8]: ('cba\n', None) EDIT 2 I tried flushing: #!/usr/bin/python import sys while True: x = raw_input() print x[::-1] sys.stdout.flush() and here: In [5]: from subprocess import PIPE, Popen In [6]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE) In [7]: p.stdin.write('abc') In [8]: p.stdin.flush() In [9]: p.stdout.read() but it hangs again.
[ "I believe there are two problems at work here:\n1) Your parent script calls p.stdout.read(), which will read all data until end-of-file. However, your child script runs in an infinite loop so end-of-file will never happen. Probably you want p.stdout.readline()?\n2) In interactive mode, most programs do buffer on...
[ 15, 3, 3, 1, 1 ]
[ "Use communicate() instead of .stdout.read().\nExample:\nfrom subprocess import Popen, PIPE\np = Popen('./script.py', stdin=PIPE, stdout=PIPE, stderr=PIPE)\ninput = 'abc\\n'\nstdout, stderr = p.communicate(input)\n\nThis recommendation comes from the Popen objects section in the subprocess documentation:\n\nWarning...
[ -3 ]
[ "python", "stdout", "subprocess" ]
stackoverflow_0003804727_python_stdout_subprocess.txt
Q: How to construct GQL to not contain a value from a set? Is it possible to select from a google app engine db where the key of a db.Model object is not in a given list? If so, what would be the syntax? Ex of a model class: class Spam(db.Model): field1 = db.BooleanProperty(default=false) field2 = db.IntegerProperty() Example of a query which I'd like to work but can't figure out: spam_results = db.GqlQuery( "SELECT * FROM Spam WHERE key NOT IN :1 LIMIT 10", ['ag1waWNreXByZXNlbnRzchMLEgxBbm5vdW5jZW1lbnQYjAEM', 'ag1waWNreXByZXNlbnRzchMLEgxBbm5vdW5jZW1lbnQYjgEM']) for eggs in spam_results: print "id: %s" % a.key().id() A: No Though app engine supports an "IN" query, it does not support a "NOT IN" query. However, if your list of entities you don't want is small, then you might as well just retrieve every entity and filter out the ones you don't need yourself. Alternatively, if the list of entities you want to exclude is a large fraction of all entities, then the above solution would be rather inefficient. Instead, perhaps you could add an additional property to your model which you could use to filter out entities you don't want (whether or not this is possible will depend on your specific needs and data).
How to construct GQL to not contain a value from a set?
Is it possible to select from a google app engine db where the key of a db.Model object is not in a given list? If so, what would be the syntax? Ex of a model class: class Spam(db.Model): field1 = db.BooleanProperty(default=false) field2 = db.IntegerProperty() Example of a query which I'd like to work but can't figure out: spam_results = db.GqlQuery( "SELECT * FROM Spam WHERE key NOT IN :1 LIMIT 10", ['ag1waWNreXByZXNlbnRzchMLEgxBbm5vdW5jZW1lbnQYjAEM', 'ag1waWNreXByZXNlbnRzchMLEgxBbm5vdW5jZW1lbnQYjgEM']) for eggs in spam_results: print "id: %s" % a.key().id()
[ "No Though app engine supports an \"IN\" query, it does not support a \"NOT IN\" query.\nHowever, if your list of entities you don't want is small, then you might as well just retrieve every entity and filter out the ones you don't need yourself.\nAlternatively, if the list of entities you want to exclude is a lar...
[ 6 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python" ]
stackoverflow_0003807591_google_app_engine_gql_gqlquery_python.txt
Q: Django TemplateSyntaxError I am getting a TemplateSyntaxError, that is only happening on my dev server, but works fine on the django testing server locally. Here's the error Caught SyntaxError while rendering: invalid syntax (urls.py, line 1) and the html: <li><a href="{% url plan.views.profile %}">Plan Details</a></li> and here is the profile view: @login_required def profile(request): ... here's the traceback: Traceback: File "/django/lib/python2.5/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/django/lib/python2.5/django/contrib/auth/decorators.py" in _wrapped_view 25. return view_func(request, *args, **kwargs) File "/django/myapp/plan/views.py" in profile 121. }, context_instance=RequestContext(request) ) File "/django/lib/python2.5/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/django/lib/python2.5/django/template/loader.py" in render_to_string 186. return t.render(context_instance) File "/django/lib/python2.5/django/template/__init__.py" in render 173. return self._render(context) File "/django/lib/python2.5/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/django/lib/python2.5/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/loader_tags.py" in render 62. result = block.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/loader_tags.py" in render 139. return self.template.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 173. return self._render(context) File "/django/lib/python2.5/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 253. return self.nodelist_false.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 253. return self.nodelist_false.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 251. return self.nodelist_true.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 366. url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) File "/django/lib/python2.5/django/core/urlresolvers.py" in reverse 350. *args, **kwargs))) File "/django/lib/python2.5/django/core/urlresolvers.py" in reverse 271. possibilities = self.reverse_dict.getlist(lookup_view) File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/django/lib/python2.5/django/core/urlresolvers.py" in _populate 173. for name in pattern.reverse_dict: File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/django/lib/python2.5/django/core/urlresolvers.py" in _populate 162. for pattern in reversed(self.url_patterns): File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_url_patterns 243. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_urlconf_module 238. self._urlconf_module = import_module(self.urlconf_name) File "/django/lib/python2.5/django/utils/importlib.py" in import_module 35. __import__(name) I've check my urls.py file and it is fine. The first line is: from django.conf.urls.defaults import * A: In your urls.py use named urls via url function ie. urlpatterns = patterns('your_app.views', url(r'^somehiing/$', 'your_view_function', name='my_view'), ) Then in your template use {% url my_view %}. If it will not help, paste here your urls.py - maybe it's just some tiny syntax error. A: Here's one possibility. The path to your views file seems to be /django/myapp/plan/views.py: File "/django/myapp/plan/views.py" in profile 121. }, context_instance=RequestContext(request) ) If your python path is configured to include /django, then you'll need to change your template/html to: {% url myapp.plan.views.profile %} If this isn't the case, then per bx2's suggestion, you might want to check your urls.py file for syntax errors.
Django TemplateSyntaxError
I am getting a TemplateSyntaxError, that is only happening on my dev server, but works fine on the django testing server locally. Here's the error Caught SyntaxError while rendering: invalid syntax (urls.py, line 1) and the html: <li><a href="{% url plan.views.profile %}">Plan Details</a></li> and here is the profile view: @login_required def profile(request): ... here's the traceback: Traceback: File "/django/lib/python2.5/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/django/lib/python2.5/django/contrib/auth/decorators.py" in _wrapped_view 25. return view_func(request, *args, **kwargs) File "/django/myapp/plan/views.py" in profile 121. }, context_instance=RequestContext(request) ) File "/django/lib/python2.5/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/django/lib/python2.5/django/template/loader.py" in render_to_string 186. return t.render(context_instance) File "/django/lib/python2.5/django/template/__init__.py" in render 173. return self._render(context) File "/django/lib/python2.5/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/loader_tags.py" in render 125. return compiled_parent._render(context) File "/django/lib/python2.5/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/loader_tags.py" in render 62. result = block.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/loader_tags.py" in render 139. return self.template.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 173. return self._render(context) File "/django/lib/python2.5/django/template/__init__.py" in _render 167. return self.nodelist.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 253. return self.nodelist_false.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 253. return self.nodelist_false.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 251. return self.nodelist_true.render(context) File "/django/lib/python2.5/django/template/__init__.py" in render 796. bits.append(self.render_node(node, context)) File "/django/lib/python2.5/django/template/debug.py" in render_node 72. result = node.render(context) File "/django/lib/python2.5/django/template/defaulttags.py" in render 366. url = reverse(self.view_name, args=args, kwargs=kwargs, current_app=context.current_app) File "/django/lib/python2.5/django/core/urlresolvers.py" in reverse 350. *args, **kwargs))) File "/django/lib/python2.5/django/core/urlresolvers.py" in reverse 271. possibilities = self.reverse_dict.getlist(lookup_view) File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/django/lib/python2.5/django/core/urlresolvers.py" in _populate 173. for name in pattern.reverse_dict: File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_reverse_dict 193. self._populate() File "/django/lib/python2.5/django/core/urlresolvers.py" in _populate 162. for pattern in reversed(self.url_patterns): File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_url_patterns 243. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/django/lib/python2.5/django/core/urlresolvers.py" in _get_urlconf_module 238. self._urlconf_module = import_module(self.urlconf_name) File "/django/lib/python2.5/django/utils/importlib.py" in import_module 35. __import__(name) I've check my urls.py file and it is fine. The first line is: from django.conf.urls.defaults import *
[ "In your urls.py use named urls via url function ie.\nurlpatterns = patterns('your_app.views',\n url(r'^somehiing/$', 'your_view_function', name='my_view'),\n)\n\nThen in your template use {% url my_view %}.\nIf it will not help, paste here your urls.py - maybe it's just some tiny syntax error.\n", "Here's one...
[ 3, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003807401_django_django_templates_python.txt
Q: Set timeout on getaddrinfo() in Python Is it possible to set a timeout on a getaddrinfo() call in CPython 2.7? socket.setdefaulttimeout() does not work. I don't really want a solution that wraps a function using threads or signals. A solution that only uses the standard library is best, but using a third-party package would be acceptable. For example, I want to do this: socket.getaddrinfo("""!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_""", None) And have it raise a socket.error in 1 second. (Note that when I run this on OS X it times out rapidly anyway, but running on Debian it takes about 60 seconds to fail). A: My understanding is that getaddrinfo is wrapper over OS provided library: On unix: int getaddrinfo(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res); On Windows: int WSAAPI getaddrinfo( __in_opt PCSTR pNodeName, __in_opt PCSTR pServiceName, __in_opt const ADDRINFOA *pHints, __out PADDRINFOA *ppResult ); None of them uses has a timeout value and hence Python can not provide you directly. You have to either code that using threads or use a third party library.
Set timeout on getaddrinfo() in Python
Is it possible to set a timeout on a getaddrinfo() call in CPython 2.7? socket.setdefaulttimeout() does not work. I don't really want a solution that wraps a function using threads or signals. A solution that only uses the standard library is best, but using a third-party package would be acceptable. For example, I want to do this: socket.getaddrinfo("""!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_""", None) And have it raise a socket.error in 1 second. (Note that when I run this on OS X it times out rapidly anyway, but running on Debian it takes about 60 seconds to fail).
[ "My understanding is that getaddrinfo is wrapper over OS provided library:\nOn unix:\nint getaddrinfo(const char *nodename, const char *servname,\n const struct addrinfo *hints, struct addrinfo **res);\n\nOn Windows:\nint WSAAPI getaddrinfo(\n __in_opt PCSTR pNodeName,\n __in_opt PCSTR pServiceNa...
[ 4 ]
[]
[]
[ "python", "sockets", "timeout" ]
stackoverflow_0003807822_python_sockets_timeout.txt
Q: Google Apps Engine / Django, calling action upon user login? I'm new to Google Apps Engine (working on an existing project for someone else) and it seems a bit different than Django as far as the login as the login is handled by Google, I'm trying to make it so the app creates a custom cookie for a user upon their logging in but can't seem to find the handler for the login action... I apologize for the newbie question but would appreciate if anyone can point me in the right direction on how to accomplish this. (just calling an action upon a user's login) I'm looking at some tutorials, like this one: http://www.browse-tutorials.net/tutorial/login-register-logout-python-appengine and it basically says you just generate the links since google handles the login so I can't seem to figure a solution to an issue like this. Thanks A: I solved that problem using the Django middleware system and a session. I think the use of a session is the best way to guarantee that the action only happens on login (whereas an url can be reloaded manually). Django sessions does not work out of the box, so I implemented my own sessions. However, there exists good appengine-specific implementation as this article points out: http://blog.notdot.net/2010/02/Webapps-on-App-Engine-Part-5-Sessions I implemented my middleware class like this, and added it to MIDDLEWARE_CLASSES in settings.py: class LoginManager(object): def process_view(self, request, view_func, view_args, view_kwargs): user = users.get_current_user() if user is not None: marker = Session.get(user.user_id()) if marker is None: login_action() Session.set(user.user_id(), "true")
Google Apps Engine / Django, calling action upon user login?
I'm new to Google Apps Engine (working on an existing project for someone else) and it seems a bit different than Django as far as the login as the login is handled by Google, I'm trying to make it so the app creates a custom cookie for a user upon their logging in but can't seem to find the handler for the login action... I apologize for the newbie question but would appreciate if anyone can point me in the right direction on how to accomplish this. (just calling an action upon a user's login) I'm looking at some tutorials, like this one: http://www.browse-tutorials.net/tutorial/login-register-logout-python-appengine and it basically says you just generate the links since google handles the login so I can't seem to figure a solution to an issue like this. Thanks
[ "I solved that problem using the Django middleware system and a session. I think the use of a session is the best way to guarantee that the action only happens on login (whereas an url can be reloaded manually).\nDjango sessions does not work out of the box, so I implemented my own sessions. However, there exists g...
[ 0 ]
[]
[]
[ "authentication", "django", "google_app_engine", "python", "session" ]
stackoverflow_0003773956_authentication_django_google_app_engine_python_session.txt
Q: Pass success_url to the activate Docs say : ``success_url`` The name of a URL pattern to redirect to on successful acivation. This is optional; if not specified, this will be obtained by calling the backend's ``post_activation_redirect()`` method. How can I do it ? A: You can do it in your urls.py, e.g.: url(r'^account/activate/(?P<activation_key>\w+)/$', 'registration.views.activate', {'success_url': 'registration_activation_complete'}, name='registration_activate'), url(r'^account/activate/success/$', direct_to_template, {'template': 'registration/activation_complete.html', name='registration_activation_complete'), The other approach is to create your own backend (which is simpler than it sounds) by inheriting from the default backend: from registration.backends.default import DefaultBackend class MyRegistrationBackend(DefaultBackend): def post_activation_redirect(self, request, user): # return your URL here The easiest solution is to just name your URL pattern that django-registration should use registration_activation_complete. See Naming URL patterns in the Django docs.
Pass success_url to the activate
Docs say : ``success_url`` The name of a URL pattern to redirect to on successful acivation. This is optional; if not specified, this will be obtained by calling the backend's ``post_activation_redirect()`` method. How can I do it ?
[ "You can do it in your urls.py, e.g.:\nurl(r'^account/activate/(?P<activation_key>\\w+)/$', 'registration.views.activate', {'success_url': 'registration_activation_complete'}, name='registration_activate'),\nurl(r'^account/activate/success/$', direct_to_template, {'template': 'registration/activation_complete.html'...
[ 7 ]
[]
[]
[ "django", "django_registration", "python" ]
stackoverflow_0003808241_django_django_registration_python.txt
Q: twisted: unhelpful "AlreadyCalled" error My twisted python program keeps spewing this message ever so often: Unhandled error in Deferred: Traceback (most recent call last): File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 757, in gotResult _inlineCallbacks(r, g, deferred) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 747, in _inlineCallbacks deferred.errback() File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 269, in errback self._startRunCallbacks(fail) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 312, in _startRunCallbacks self._runCallbacks() --- <exception caught here> --- File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 328, in _runCallbacks self.result = callback(self.result, *args, **kw) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 243, in callback self._startRunCallbacks(result) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 298, in _startRunCallbacks raise AlreadyCalledError twisted.internet.defer.AlreadyCalledError: It's not too helpful, as it has no reference to my source code... I also happen to be using defer.inlineCallbacks. Any idea what might have gone wrong? A: If you don't have any other hints about what's going wrong (like your unit tests pointing out the specific cases which cause this, or if pyfunc's answer doesn't make it obvious why this would be happening) then enable Deferred debugging to get information about where the first (and only allowed) result of the Deferred is being specified: from twisted.internet import defer defer.setDebugging(True) Or twistd --debug [...] Or trial --debug [...] You'll get extra stack traces with error reports like the one you've encountered. The extra stack traces will tell you where the Deferred in question was created and where it was first invoked (had .callback() or .errback() called on it). Since you're using inlineCallbacks, you don't get a nice stack trace about where the actual error is occurring, but the information about where the Deferred is first triggered might give you a hint about where the subsequent activation might come from. Unfortunately the added obscurity is just a cost of using inlineCallbacks at the moment. It's probably surmountable, but someone needs to take on that task. A: I guess some where in your code, you are explicitly calling the callback of deferred. This is also happening multiple times. A deferred callback can be fired only once which indicates the completion of a long awaited task resulting in a error or positive result. Twisted has a mechanism to throw the above exception, if you tried to fire a deferred more than once. Consider the following code: from twisted.internet.defer import Deferred def func(x): print x d = Deferred() d.addCallbacks(func, func) d.callback('First fire') d.callback('Second fire') This will result in the following error: raise AlreadyCalledError twisted.internet.defer.AlreadyCalledError Check out in your code the possibility of such multiple firings. This might be the issue.
twisted: unhelpful "AlreadyCalled" error
My twisted python program keeps spewing this message ever so often: Unhandled error in Deferred: Traceback (most recent call last): File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 757, in gotResult _inlineCallbacks(r, g, deferred) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 747, in _inlineCallbacks deferred.errback() File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 269, in errback self._startRunCallbacks(fail) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 312, in _startRunCallbacks self._runCallbacks() --- <exception caught here> --- File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 328, in _runCallbacks self.result = callback(self.result, *args, **kw) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 243, in callback self._startRunCallbacks(result) File "c:\python25\lib\site-packages\twisted\internet\defer.py", line 298, in _startRunCallbacks raise AlreadyCalledError twisted.internet.defer.AlreadyCalledError: It's not too helpful, as it has no reference to my source code... I also happen to be using defer.inlineCallbacks. Any idea what might have gone wrong?
[ "If you don't have any other hints about what's going wrong (like your unit tests pointing out the specific cases which cause this, or if pyfunc's answer doesn't make it obvious why this would be happening) then enable Deferred debugging to get information about where the first (and only allowed) result of the Defe...
[ 7, 2 ]
[]
[]
[ "debugging", "python", "twisted" ]
stackoverflow_0003807666_debugging_python_twisted.txt
Q: Django Google app engine reference issues I am working on an application on Django and google application engine. In my application I have several models with several ReferenceProperty fields. The issue is that if any of the ReferenceProperty field gets deleted it produces a ReferenceProperty related errors in all the other models where it has been used. What I want is, when a field is deleted say a User is deleted, all the fields having User as the ReferenceProperty should still work without any error messages displaying the associated user as unavailable or something like that. Can someone please suggest how that can be done? Thanks in advance. A: You could also just set a flag, say deleted, on the entity you're deleting, and then leave it in the datastore. This has the advantage of avoiding all referential integrity problems in the first place, but it comes at the cost of two main disadvantages: All your existing queries need to be changed to deal with entities that have the deleted property set, either by omitting them from the result set or by special casing them somehow. "Deleted" data stays in the datastore; this can bloat the datastore, and also may not be an option for sensitive information. This doesn't really solve your problem at all, but I thought I'd mention it for completeness's sake. A: When I have the same problem ago, I could not find a general solution. The only way I found is to do try/except for every reference property. If you find another answer post it here. A: Two possible solutions: Check if the reference still exists, before you access it: if not obj.reference: # Referenced entity was deleted When you delete a model object that may be referenced, query all models that might reference it, and set their reference property to None.
Django Google app engine reference issues
I am working on an application on Django and google application engine. In my application I have several models with several ReferenceProperty fields. The issue is that if any of the ReferenceProperty field gets deleted it produces a ReferenceProperty related errors in all the other models where it has been used. What I want is, when a field is deleted say a User is deleted, all the fields having User as the ReferenceProperty should still work without any error messages displaying the associated user as unavailable or something like that. Can someone please suggest how that can be done? Thanks in advance.
[ "You could also just set a flag, say deleted, on the entity you're deleting, and then leave it in the datastore. This has the advantage of avoiding all referential integrity problems in the first place, but it comes at the cost of two main disadvantages:\n\nAll your existing queries need to be changed to deal with ...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_models", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003759003_django_django_models_google_app_engine_google_cloud_datastore_python.txt
Q: Mapping Languages to Paradigms I recently read Eric Steven Raymond's article "How To Become A Hacker" and I like his suggestion of learning 5 key languages (he suggests Python, C/C++, Lisp, Java, and Perl) as a way of covering the main programming paradigms in use today. His advice is that it's not so important which specific languages a programmer knows. It's more important to know different approaches to programming, for two reasons. The first reason is that it makes it trivial to pick up a new language, once you know the general approach to the way it solves problems. The second reason is that there is no one best language - they all have trade-offs. It would be best to know what type of language to pick given a specific type of problem. This is what I'm most interested in, but I'm having a problem really distinguishing between the 5 languages he suggests. There seems to be a lot of overlap. So my specific question is, given these 5 languages, what is their intended programming paradigm, and give one example of the type of problem it would be best suited for. An example answer (and I'm not sure this answer is correct): Perl - mainly a functional language - great for quick text substitutions in multiple files from the command line. I found a few other similar questions posted, but I'd like to know about these 5 languages in particular. I'm just looking for a starting point, nothing too detailed. Thanks in advance! A: I think you're approaching it wrong. As esr himself says, it's not the language that matters, it's the paradigm. So when you say that Perl is a functional language It's great for quick text substitutions in multiple files from the command line you are missing one of the main points of a functional language which is that they are great for building large systems using a bottom up approach: solve a bunch of (well chosen) small problems with well designed functions until we have a complete system. We cut down on code duplication by identifying what algorithms that we are using have in common and using higher order functions to encapsulate their commonality. We minimize (overt) branching behavior by using higher order functions to cook up just the function that we need for a given situation. Likewise, I could say that Java is mainly an OOP language It's good for writing large, robust systems, but that misses the point that OOP languages are about modeling concepts from the problem domain in code so that we are left with a clear way to imperatively solve the problem at hand. We cut down on code duplication by identifying what the relevant concepts have in common and encapsulating the code that deals with those commonalities in a class that describes it. We minimize (overt) branching behavior by providing different subclasses of an abstraction with appropriately different behavior. On the whole, the basic point of programming languages and their associated paradigms is to allow you to not think about anything that doesn't affect the quality of the resulting program. If that wasn't a (largely) desirable thing, then we would all be writing machine code. This is accomplished by (among other things) providing a set of tools for building abstractions. Shop around and pick one that you like and get good at. Just make sure that you learn when the other ones allow for a better solution (this will probably mean getting good at them eventually too ;). I think that you can mainly take "good solution" to mean, "clear mapping of code to ideas". (modulo concerns about efficiency that would force you (provide an excuse?) to write in a language like C)
Mapping Languages to Paradigms
I recently read Eric Steven Raymond's article "How To Become A Hacker" and I like his suggestion of learning 5 key languages (he suggests Python, C/C++, Lisp, Java, and Perl) as a way of covering the main programming paradigms in use today. His advice is that it's not so important which specific languages a programmer knows. It's more important to know different approaches to programming, for two reasons. The first reason is that it makes it trivial to pick up a new language, once you know the general approach to the way it solves problems. The second reason is that there is no one best language - they all have trade-offs. It would be best to know what type of language to pick given a specific type of problem. This is what I'm most interested in, but I'm having a problem really distinguishing between the 5 languages he suggests. There seems to be a lot of overlap. So my specific question is, given these 5 languages, what is their intended programming paradigm, and give one example of the type of problem it would be best suited for. An example answer (and I'm not sure this answer is correct): Perl - mainly a functional language - great for quick text substitutions in multiple files from the command line. I found a few other similar questions posted, but I'd like to know about these 5 languages in particular. I'm just looking for a starting point, nothing too detailed. Thanks in advance!
[ "I think you're approaching it wrong. As esr himself says, it's not the language that matters, it's the paradigm. So when you say that \n\n\nPerl is a functional language\nIt's great for quick text substitutions in multiple files from the command line\n\n\nyou are missing one of the main points of a functional lang...
[ 11 ]
[ "If you can, go to a school that will give you experience with a variety of languages.\n\nPython: multi-paradigm, focused on OO and polymorphism-based generic programming.\nC/C++: Are two separate languages. Having grouped them together reflects ESR's level of, er, practicality.\n\nC: classic imperative language.\n...
[ -2, -2 ]
[ "c++", "java", "lisp", "perl", "python" ]
stackoverflow_0003793030_c++_java_lisp_perl_python.txt