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: quickest way to split a file into two files randomly python: what is the quickest way to split a file into two files, each file having half of the number of lines in the original file, such that the lines in each of the two files are random? for example: if the file is 1 2 3 4 5 6 7 8 9 10 it could be split into: 3 2 10 9 1 4 6 8 5 7 A: This sort of operation is often called "partition". Although there isn't a built-in partition function, I found this article: Partition in Python. Given that definition, you can do this: import random def partition(l, pred): yes, no = [], [] for e in l: if pred(e): yes.append(e) else: no.append(e) return yes, no lines = open("file.txt").readlines() lines1, lines2 = partition(lines, lambda x: random.random() < 0.5) Note that this won't necessarily exactly split the file in two, but it will on average. A: You can just load the file, call random.shuffle on the resulting list, and then split it into two files (untested code): def shuffle_split(infilename, outfilename1, outfilename2): from random import shuffle with open(infilename, 'r') as f: lines = f.readlines() # append a newline in case the last line didn't end with one lines[-1] = lines[-1].rstrip('\n') + '\n' shuffle(lines) with open(outfilename1, 'w') as f: f.writelines(lines[:len(lines) // 2]) with open(outfilename2, 'w') as f: f.writelines(lines[len(lines) // 2:]) random.shuffle shuffles lines in-place, and pretty much does all the work here. Python's sequence indexing system (e.g. lines[len(lines) // 2:]) makes things really convenient. I'm assuming that the file isn't huge, i.e. that it will fit comfortably in memory. If that's not the case, you'll need to do something a bit more fancy, probably using the linecache module to read random line numbers from your input file. I think probably you would want to generate two lists of line numbers, using a similar technique to what's shown above. update: changed / to // to evade issues when __future__.division is enabled. A: import random data=open("file").readlines() random.shuffle(data) c=1 f=open("test."+str(c),"w") for n,i in enumerate(data): if n==len(data)/2: c+=1 f.close() f=open("test."+str(c),"w") f.write(i) A: Other version: from random import shuffle def shuffle_split(infilename, outfilename1, outfilename2): with open(infilename, 'r') as f: lines = f.read().splitlines() shuffle(lines) half_lines = len(lines) // 2 with open(outfilename1, 'w') as f: f.write('\n'.join(lines.pop() for count in range(half_lines))) with open(outfilename2, 'w') as f: f.writelines('\n'.join(lines))
python: quickest way to split a file into two files randomly
python: what is the quickest way to split a file into two files, each file having half of the number of lines in the original file, such that the lines in each of the two files are random? for example: if the file is 1 2 3 4 5 6 7 8 9 10 it could be split into: 3 2 10 9 1 4 6 8 5 7
[ "This sort of operation is often called \"partition\". Although there isn't a built-in partition function, I found this article: Partition in Python.\nGiven that definition, you can do this:\nimport random\n\ndef partition(l, pred):\n yes, no = [], []\n for e in l:\n if pred(e):\n yes.append...
[ 5, 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003895482_python.txt
Q: using subprocess.popen in python with os.tmp file while passing in optional parameters I am writing a python program in linux and in part of it running the pdftotext executable to convert a pdf text. The code I am currently using is given below. pdfData = currentPDF.read() tf = os.tmpfile() tf.write(pdfData) tf.seek(0) out, err = subprocess.Popen(["pdftotext", "-", "-"], stdin = tf, stdout=subprocess.PIPE ).communicate() This works fine, but now I want to run the pdftotext executable with the -layout option (preserves layout of document). I tried replacing the "-" with layout, replacing "pdftotext" with "pdftotext -layout" etc. None of it works. They all give me an empty text. Since the input is being piped in via the temp file, I am having trouble figureing out the argument list. Most of the documentation on Popen assumes all the parameters are being passed in through the argument list, but in my case the input is being passed in through the temp file. Any help would be greatly appreciated. A: This works for me: out, err = subprocess.Popen( ["pdftotext", '-layout', "-", "-"], stdin = tf, stdout=subprocess.PIPE ).communicate() Although I couldn't find explicit confirmation in the man page, I believe the first - tells pdftotext to expect PDF-file to come from stdin, and the second - tells pdftotext to expect text-file to be sent to stdout. A: You can pass the full command in string with shell=True: out, err = subprocess.Popen('pdftotext -layout - -', shell=True, stdin=tf, stdout=subprocess.PIPE).communicate()
using subprocess.popen in python with os.tmp file while passing in optional parameters
I am writing a python program in linux and in part of it running the pdftotext executable to convert a pdf text. The code I am currently using is given below. pdfData = currentPDF.read() tf = os.tmpfile() tf.write(pdfData) tf.seek(0) out, err = subprocess.Popen(["pdftotext", "-", "-"], stdin = tf, stdout=subprocess.PIPE ).communicate() This works fine, but now I want to run the pdftotext executable with the -layout option (preserves layout of document). I tried replacing the "-" with layout, replacing "pdftotext" with "pdftotext -layout" etc. None of it works. They all give me an empty text. Since the input is being piped in via the temp file, I am having trouble figureing out the argument list. Most of the documentation on Popen assumes all the parameters are being passed in through the argument list, but in my case the input is being passed in through the temp file. Any help would be greatly appreciated.
[ "This works for me:\nout, err = subprocess.Popen(\n [\"pdftotext\", '-layout', \"-\", \"-\"], stdin = tf, stdout=subprocess.PIPE ).communicate()\n\nAlthough I couldn't find explicit confirmation in the man page, I believe the first - tells pdftotext to expect PDF-file to come from stdin, and the second - tells p...
[ 2, 0 ]
[]
[]
[ "linux", "pdftotext", "python" ]
stackoverflow_0003896795_linux_pdftotext_python.txt
Q: Finding rendered HTML element positions using WebKit (or Gecko) I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, (top-left,top-right,bottom-left,bottom-right) Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up. I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko. Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful. A: lxml isn't going to help you at all. It isn't concerned about front-end rendering at all. To accurately work out how something renders, you need to render it. For that you need to hook into a browser, spawn the page and run some JS on the page to find the DOM element and get its attributes. It's totally possible but I think you should start by looking at how website screenshot factories work (as they'll share 90% of the code you need to get a browser launching and showing the right page). You may want to still use lxml to inject your javascript into the page. A: I agree with Oli, rendering the page in question and inspecting DOM via JavaScript is the most practical way IMHO. You might find jQuery very useful here: $(document).ready(function() { var elem = $("div#some_container_id h1") var elem_offset = elem.offset(); /* elem_offset is an object literal: elem_offset = { x: 25, y: 140 } */ var elem_height = elem.height(); var elem_width = elem.width(); /* bottom_right is then { x: elem_offset.x + elem_width, y: elem_offset.y + elem_height } }); Related documentation is here. A: Yes, Javascript is the way to go: var allElements=document.getElementsByTagName("*"); will select all the elements in the page. Then you can loop through this a extract the information you need from each element. Good documentation about getting the dimensions and positions of an element is here. getElementsByTagName returns a nodelist not an array (so if your JS changes your HTML those changes will be reflected in the nodelist), so I'd be tempted to build the data into an AJAX post and send it to a server when it's done. A: I was not able to find any easy solution (ie. Java/Perl/Python :) to hook onto Webkit/Gecko to solve the above rendering problem. The best I could find was the Lobo rendering engine written in Java which has a very clear API that does exactly what I want - access to both DOM and the rendering attributes of HTML elements. JRex is a Java wrapper to Gecko rendering engine. A: you have three main options: 1) http://www.gnu.org/software/pythonwebkit is webkit-based; 2) python-comtypes for accessing MSHTML (windows only) 3) hulahop (python-xpcom) which is xulrunner-based you should get the pyjamas-desktop source code and look in the pyjd/ directory for "startup" code which will allow you to create a web browser application and begin, once the "page loaded" callback has been called by the engine, to manipulate the DOM. you can perform node-walking, and can access the properties of the DOM elements that you require. you can look at the pyjamas/library/pyjamas/DOM.py module to see many of the things that you will need to be using in order to do what you want. but if the three options above are not enough then you should read the page http://wiki.python.org/moin/WebBrowserProgramming for further options, many of which have been mentioned here by other people. l. A: The problem is that current browsers don't render things quite the same. If you're looking for the standards compliant way of doing things, you could probably write something in Python to render the page, but that's going to be a hell of a lot of work. You could use the wxHTML control from wxWidgets to render each part of a page individually to get an idea of it's size. If you have a Mac you could try WebKit. That same article has some suggestions for solutions on other platforms too. A: You might consider looking at WWW::Selenium. With it (and selenium rc) you can puppet string IE, Firefox, or Safari from inside of Perl.
Finding rendered HTML element positions using WebKit (or Gecko)
I would like to get the dimensions (coordinates) for all the HTML elements of a webpage as they are rendered by a browser, that is the positions they are rendered at. For example, (top-left,top-right,bottom-left,bottom-right) Could not find this in lxml. So, is there any library in Python that does this? I had also looked at Mechanize::Mozilla in Perl but, that seems difficult to configure/set-up. I think the best way to do this for my requirement is to use a rendering engine - like WebKit or Gecko. Are there any perl/python bindings available for the above two rendering engines? Google searches for tutorials on how to "plug-in" to the WebKit rendering engine is not very helpful.
[ "lxml isn't going to help you at all. It isn't concerned about front-end rendering at all.\nTo accurately work out how something renders, you need to render it. For that you need to hook into a browser, spawn the page and run some JS on the page to find the DOM element and get its attributes.\nIt's totally possible...
[ 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "html", "perl", "python", "rendering", "rendering_engine" ]
stackoverflow_0000980058_html_perl_python_rendering_rendering_engine.txt
Q: How can I programmatically send events to Qt's webkit? I would like to create a specialized browser that can enter certain information semi-automatically into pages that are browsed. I am using for this Qt Webkit (in particular the python bindings). How can I do this? A: it's doable, using javascript code-snippets. take a look at the pyjamas-desktop "failed experiment" pyjd/pyqt4.py runtime, noting the rather important addition of the words "failed". you would be strongly advised to avoid pywebkitqt4 for this particular purpose, instead looking at either python-hulahop (originally part of the OLPC project) or perhaps python-webkit - http://www.gnu.org/software/pythonwebkit l.
How can I programmatically send events to Qt's webkit?
I would like to create a specialized browser that can enter certain information semi-automatically into pages that are browsed. I am using for this Qt Webkit (in particular the python bindings). How can I do this?
[ "it's doable, using javascript code-snippets. take a look at the pyjamas-desktop \"failed experiment\" pyjd/pyqt4.py runtime, noting the rather important addition of the words \"failed\".\nyou would be strongly advised to avoid pywebkitqt4 for this particular purpose, instead looking at either python-hulahop (orig...
[ 0 ]
[]
[]
[ "browser", "pyqt4", "python", "qt4", "webbrowser_control" ]
stackoverflow_0003372841_browser_pyqt4_python_qt4_webbrowser_control.txt
Q: Dictionaries in Python I have a problem. I want to make a dictionary that translates english words to estonian. I started, but don't know how to continue. Please, help. Dictionary is a text document where tab separates english and estonian words. file = open("dictionary.txt","r") eng = [] est = [] while True : lines = file.readline() if lines == "" : break pair = lines.split("\t") eng.append(pair[0]) est.append(pair[1]) for i in range...... Please, help. A: For a dictionary, you should use the dictionary type which maps keys to values and is much more efficient for lookups. I also made some other changes to your code, keep them if you wish: engToEstDict = {} # The with statement automatically closes the file afterwards. Furthermore, one shouldn't # overwrite builtin names like "file", "dict" and so on (even though it's possible). with open("dictionary.txt", "r") as f: for line in f: if not line: break # Map the Estonian to the English word in the dictionary-typed variable pair = lines.split("\t") engToEstDict[pair[0]] = pair[1] # Then, lookup of Estonian words is simple print engToEstDict["hello"] # should probably print "tere", says Google Translator Mind that the reverse lookup (Estonian to English) is not so easy. If you need that, too, you might be better off creating a second dictionary variable with the reversed key-value mapping (estToEngDict[pair[1]] = pair[0]) because lookup will be a lot faster than your list-based approach. A: It would be better to use the appropriately named dict instead of two lists: d = {} # ... d[pair[0]] = pair[1] Then to use it: translated = d["hello"] You should also note that when you call readline() that the resulting string includes the trailing new-line so you should strip this before storing the string in the dictionary.
Dictionaries in Python
I have a problem. I want to make a dictionary that translates english words to estonian. I started, but don't know how to continue. Please, help. Dictionary is a text document where tab separates english and estonian words. file = open("dictionary.txt","r") eng = [] est = [] while True : lines = file.readline() if lines == "" : break pair = lines.split("\t") eng.append(pair[0]) est.append(pair[1]) for i in range...... Please, help.
[ "For a dictionary, you should use the dictionary type which maps keys to values and is much more efficient for lookups. I also made some other changes to your code, keep them if you wish:\nengToEstDict = {}\n\n# The with statement automatically closes the file afterwards. Furthermore, one shouldn't\n# overwrite bui...
[ 3, 1 ]
[]
[]
[ "dictionary", "iteration", "python" ]
stackoverflow_0003897460_dictionary_iteration_python.txt
Q: How to change file names using regular expressions in Python? I have a directory which contains subdirectories which contain files. All the file names have a prefix which I want to eliminate. The prefix is not exactly the same among all the files, but I have a regular expression that represents exactly the language of these prefixes. I'm trying to write a script in Python to change the name of each file to its name without the prefix. I don't know yet how to "play" with files in Python (know just basic i/o operations). Could you help a little? I use Python 3. A: You might find these functions useful: os.listdir os.path.join os.rename You might want to look at using glob.glob if the prefixes you are trying to match are supported by the language glob uses (it doesn't support full regular expressions, but it does allow some wildcards).
How to change file names using regular expressions in Python?
I have a directory which contains subdirectories which contain files. All the file names have a prefix which I want to eliminate. The prefix is not exactly the same among all the files, but I have a regular expression that represents exactly the language of these prefixes. I'm trying to write a script in Python to change the name of each file to its name without the prefix. I don't know yet how to "play" with files in Python (know just basic i/o operations). Could you help a little? I use Python 3.
[ "You might find these functions useful:\n\nos.listdir\nos.path.join\nos.rename\n\nYou might want to look at using glob.glob if the prefixes you are trying to match are supported by the language glob uses (it doesn't support full regular expressions, but it does allow some wildcards).\n" ]
[ 4 ]
[]
[]
[ "file", "python", "regex" ]
stackoverflow_0003897654_file_python_regex.txt
Q: Which language to use for writing an admin console à la webmin? We have an in house developed web-based admin console that uses a combination of C CGI and Perl scripts to administer our mail server stack. Of late we have been thinking of cleaning up the code (well, replacing most of it), making the implementation more secure, and improving the overall behavior. I don't have much programming knowledge, but I use Ruby on and off (mainly for writing erb templates), and hence was thinking of using ruby/rails for developing such an app (off-duty for now, I also need to learn stuff !). Before blindly picking up a language though, what would you folks suggest ? Please let me know if this is too vague a question, I'll try to supply more information, if needed. A: Have you considered writing your applications as Webmin modules? You get a lot of stuff for free when you do so (users and groups, tons of security features, a pretty big variety of helper functions related to config files, and tons of existing code for most aspects of a UNIX/Linux system). You also get a lot of stuff for nearly free, like action logging, packages and updates via wbm or apt or yum, an online help system, etc. There are some cons, as well. It's an old codebase, so it has some clunky bits in the API among other places. A lot of the old modules can be a bit hard to grok if you're not an old-school Perl programmer. But, it's a well-maintained codebase, and it's been banged on by millions of users for over a dozen years. It's pretty robust. The UI isn't beautiful, but it is relatively theme-able, and if you're distributing a minimized version it becomes easier to customize the UI. I suspect you can be up and running a lot faster than starting from scratch or using most existing frameworks that aren't targeted specifically to building systems management interfaces the way Webmin is. Also, it's BSD licensed, so you can do whatever you want with it, including building a custom commercial app with it (hundreds of companies have done so over the years). A: Without knowing much about your existing application I'd say that this effectively boils down to "which language do you like to work with?". Python and Ruby are both mature languages with ample library infrastructure. They also boast popular, similar web application frameworks namely Django and Ruby-on-Rails respectively. Since you are porting an existing Perl app(lets) it may be worthwhile to note that Ruby is relatively more similar to Perl. Not surprising given that Ruby was influenced "primarily by Perl, Smalltalk, Eiffel and Lisp". A: If you already know a bit of ruby, then there's no reason not to use that. If you're interested specifically in learning another language, then what you're trying to do could be done in pretty much any language/framework, it's just a matter of which one you want to learn. A: django has a nice admin interface
Which language to use for writing an admin console à la webmin?
We have an in house developed web-based admin console that uses a combination of C CGI and Perl scripts to administer our mail server stack. Of late we have been thinking of cleaning up the code (well, replacing most of it), making the implementation more secure, and improving the overall behavior. I don't have much programming knowledge, but I use Ruby on and off (mainly for writing erb templates), and hence was thinking of using ruby/rails for developing such an app (off-duty for now, I also need to learn stuff !). Before blindly picking up a language though, what would you folks suggest ? Please let me know if this is too vague a question, I'll try to supply more information, if needed.
[ "Have you considered writing your applications as Webmin modules?\nYou get a lot of stuff for free when you do so (users and groups, tons of security features, a pretty big variety of helper functions related to config files, and tons of existing code for most aspects of a UNIX/Linux system). You also get a lot of ...
[ 2, 0, 0, 0 ]
[]
[]
[ "administration", "migration", "python", "ruby" ]
stackoverflow_0003861102_administration_migration_python_ruby.txt
Q: Start simple web server and launch browser simultaneously in Python I want to start a simple web server locally, then launch a browser with an url just served. This is something that I'd like to write, from wsgiref.simple_server import make_server import webbrowser srv = make_server(...) srv.blocking = False srv.serve_forever() webbrowser.open_new_tab(...) try: srv.blocking = True except KeyboardInterrupt: pass print 'Bye' The problem is, I couldn't find a way to set a blocking option for the wsgiref simple server. By default, it's blocking, so the browser would be launched only after I stopped it. If I launch the browser first, the request is not handled yet. I'd prefer to use a http server from the standard library, not an external one, like tornado. A: You either have to spawn a thread with the server, so you can continue with your control flow, or you have to use 2 python processes. untested code, you should get the idea class ServerThread(threading.Thread): def __init__(self, port): threading.Thread.__init__(self) def run(self): srv = make_server(...) srv.serve_forever() if '__main__'==__name__: ServerThread().start() webbrowser.open_new_tab(...)
Start simple web server and launch browser simultaneously in Python
I want to start a simple web server locally, then launch a browser with an url just served. This is something that I'd like to write, from wsgiref.simple_server import make_server import webbrowser srv = make_server(...) srv.blocking = False srv.serve_forever() webbrowser.open_new_tab(...) try: srv.blocking = True except KeyboardInterrupt: pass print 'Bye' The problem is, I couldn't find a way to set a blocking option for the wsgiref simple server. By default, it's blocking, so the browser would be launched only after I stopped it. If I launch the browser first, the request is not handled yet. I'd prefer to use a http server from the standard library, not an external one, like tornado.
[ "You either have to spawn a thread with the server, so you can continue with your control flow, or you have to use 2 python processes.\nuntested code, you should get the idea\n\nclass ServerThread(threading.Thread):\n\n def __init__(self, port):\n threading.Thread.__init__(self)\n\n def run(self):\n ...
[ 1 ]
[]
[]
[ "nonblocking", "python", "webserver", "wsgiref" ]
stackoverflow_0003897896_nonblocking_python_webserver_wsgiref.txt
Q: Python: how can i find minimum and maximum values in subarrays elements? I've the following array: [[499, 3], [502, 3], [502, 353], [499, 353]] They are the verteces of a rectangle. I need to find the top-left, top-right, bottom-left and bottom-right vertex. What's the best python code to do it ? thanks A: edit: thanks to tokand for pointing out that this can be done with tuple unpacking. you could sort it. (bottomleft, bottomright,topleft, topright) = sorted(vertices) or you could do it in place with corners.sort() (bottomleft, bottomright,topleft, topright) = corners # the unpacking here is redundant but demonstrative For reference, the output of sorted is: >>> a = [[499, 3], [502, 3], [502, 353], [499, 353]] >>> sorted(a) [[499, 3], [499, 353], [502, 3], [502, 353]] >>> This will be O(nlogn) whereas there are surely O(n) solutions available. But for a list of this size, I don't think it's a biggy unless you have a ton of them, (in which case, the speed of the native C implementation will outperform a custom python function anyways so it's still optimal from a practical perspective.) A: vertices = [[499, 3], [499, 353], [502, 3], [502, 353]] # if the origin is the top left (topleft, bottomleft, topright, bottomright) = sorted(vertices) # if the origin is the bottom left (bottomleft, topleft, bottomright, topright) = sorted(vertices)
Python: how can i find minimum and maximum values in subarrays elements?
I've the following array: [[499, 3], [502, 3], [502, 353], [499, 353]] They are the verteces of a rectangle. I need to find the top-left, top-right, bottom-left and bottom-right vertex. What's the best python code to do it ? thanks
[ "edit: thanks to tokand for pointing out that this can be done with tuple unpacking.\nyou could sort it.\n(bottomleft, bottomright,topleft, topright) = sorted(vertices)\n\nor you could do it in place with\ncorners.sort()\n(bottomleft, bottomright,topleft, topright) = corners\n# the unpacking here is redundant but d...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003897938_python.txt
Q: Can I use Python to run html i am writing an HTML editor and would like to make a section so that you can view how it would look in web browser directly in the program is this possible? Thanks so much A: I wouldn't do this - your renderer will quickly differ from real browsers.
Can I use Python to run html
i am writing an HTML editor and would like to make a section so that you can view how it would look in web browser directly in the program is this possible? Thanks so much
[ "I wouldn't do this - your renderer will quickly differ from real browsers.\n" ]
[ 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003897932_html_python.txt
Q: Is there way to turn list of answers from script as yielded values? I have long running program that I want to keep responsive. The algorithm is recursive, so sometimes even the sub-tasks in longer running calls can be longer than shorter whole runs. I have tried to make it to use yield but only ended up with list full of generators in various levels of recursive list structure (list also multilevel hierarchy, recording depth of calls). I finally made simple print the answers version, but it prints the answers in the end. I must not print the recursive calls results only, also the results need post processing before printing. Is there simple pattern to make top level function call to yield values, but recursive calls to return the answers? Should I use for loops over recursive call results or make list() of the aswers from recursive calls? Should I just put depth parameter and return with depth > 0 and yield at depth 0? Anyway, is there easy way to turn one answer per line outputing call to yield the lines back to main Python program? Or should I still return the full list from module call? I could easily run the os call version in separate interpreter with 'bg' in Linux system couldn't I? The problem is complete covering problem, an example useful to my application would be for example to do same as this without the combinations, only adding numbers until they go over the limit recursively returning the exact sums: from __future__ import print_function def subset(seq, mask): """ binary mask of len(seq) bits, return generator for the sequence """ return (c for ind,c in enumerate(seq) if mask & (1<<ind)) numbers = [1, 5, 3, 9, 4] print('Numbers: ',numbers) print('Possible sums',min(numbers),'..',sum(numbers)) for i in range(1,2**len(numbers)): sub = list(subset(numbers, i)) print(sum(sub),'=',' + '.join(str(s) for s in sub)) print() target = 11 print ('Finding subsequence for sum = %i' % target) check = None for check in (subset(numbers, mask) for mask in range(1,2**len(numbers)) if sum(subset(numbers, mask))==target): print (' + '.join(str(s) for s in check), ' = ', target) if not check: print('No solutions') A: You're a little bit short on details of what you're actually trying to do, but here's my best guess (note: you'll need Python 2.6): def do_stuff(num): children = [ _do_stuff(x + 1) for x in range(num) ] for child in children: child.send(None) count = 0 while children: child = children.pop(0) try: count += child.send(count) except StopIteration: continue children.append(child) def _do_stuff(num): to_add = 0 for x in range(num): from_parent = (yield (to_add + x)) print "child %s got %s" %(num, from_parent) to_add += from_parent Which will work like this: >>> do_stuff(3) child 1 got 0 child 2 got 0 child 3 got 1 child 2 got 3 child 3 got 3 child 3 got 9 Sorry that this example is a bit confusing — my brain isn't up to coming up with a better example right now. Also, some notes: * The children could yield another generator, which could be added to the list of children * This implementation is slow (popping from the head of a list requires O(n) time) — see dequeue module * The child.send(None) is needed to "prime" the generators (that is, execute up to the first yield) A: Your question isn't very clear. Maybe this will help. Making a recursive generator is straightforward; the function just has to iterate over itself instead of call itself. For instance, if you wanted to write a generator that flattened a tree, it might look like this: def descendants(node): for child in children(node): yield child for descendant in descendants(child): yield descendant This approach is returning each descendant node to the caller as it is found. If, for some reason, the children function were itself a generator that took a whole second to return each node, the descendants function would return a descendant node to its caller once a second. This all assumes that the process is synchronous. If it is (or can be made to be) asynchronous, you have a very different problem that requires a very different approach. You can wrap an asynchronous process in a generator that yields results as they become available; if you do this, every call to the generator will block and wait until a background thread (or process) produces whatever next result is available. This provides a simple facade to hide the complexities of asynchronous code behind; the caller just does: for x in get_things(param): print x and the get_things() function creates threads (or processes) and yields the objects as the threads return them. How the get_things() function does this is, of course, a big question, and totally dependent on what your problem actually is.
Is there way to turn list of answers from script as yielded values?
I have long running program that I want to keep responsive. The algorithm is recursive, so sometimes even the sub-tasks in longer running calls can be longer than shorter whole runs. I have tried to make it to use yield but only ended up with list full of generators in various levels of recursive list structure (list also multilevel hierarchy, recording depth of calls). I finally made simple print the answers version, but it prints the answers in the end. I must not print the recursive calls results only, also the results need post processing before printing. Is there simple pattern to make top level function call to yield values, but recursive calls to return the answers? Should I use for loops over recursive call results or make list() of the aswers from recursive calls? Should I just put depth parameter and return with depth > 0 and yield at depth 0? Anyway, is there easy way to turn one answer per line outputing call to yield the lines back to main Python program? Or should I still return the full list from module call? I could easily run the os call version in separate interpreter with 'bg' in Linux system couldn't I? The problem is complete covering problem, an example useful to my application would be for example to do same as this without the combinations, only adding numbers until they go over the limit recursively returning the exact sums: from __future__ import print_function def subset(seq, mask): """ binary mask of len(seq) bits, return generator for the sequence """ return (c for ind,c in enumerate(seq) if mask & (1<<ind)) numbers = [1, 5, 3, 9, 4] print('Numbers: ',numbers) print('Possible sums',min(numbers),'..',sum(numbers)) for i in range(1,2**len(numbers)): sub = list(subset(numbers, i)) print(sum(sub),'=',' + '.join(str(s) for s in sub)) print() target = 11 print ('Finding subsequence for sum = %i' % target) check = None for check in (subset(numbers, mask) for mask in range(1,2**len(numbers)) if sum(subset(numbers, mask))==target): print (' + '.join(str(s) for s in check), ' = ', target) if not check: print('No solutions')
[ "You're a little bit short on details of what you're actually trying to do, but here's my best guess (note: you'll need Python 2.6):\ndef do_stuff(num):\n children = [ _do_stuff(x + 1) for x in range(num) ]\n for child in children:\n child.send(None)\n\n count = 0\n while children:\n child...
[ 1, 0 ]
[]
[]
[ "generator", "python", "recursion", "yield" ]
stackoverflow_0003897712_generator_python_recursion_yield.txt
Q: How would I save time with or statements in Python? I'm writing a AI program in Python and want to save time when interacting with the bot. Instead of using this code: if "how are you" or "How are you" in talk: perform_action() I want to be able to interpret it even if it's not capitalize or not. If you don't what I'm saying let's say I asked the bot, "how are you?", but the bot was only programmed to answer to that question if it was said like this, "How are you?". I want to simplify the coding so I won't have to use a "or" statement. Please provide example code. A: if talk.upper() == "HOW ARE YOU": perform_action() or, if you prefer to search for substrings if "HOW ARE YOU" in talk.upper(): perform_action() A: Easy way would be to lowercase everything: if "how are you" == talk.lower():
How would I save time with or statements in Python?
I'm writing a AI program in Python and want to save time when interacting with the bot. Instead of using this code: if "how are you" or "How are you" in talk: perform_action() I want to be able to interpret it even if it's not capitalize or not. If you don't what I'm saying let's say I asked the bot, "how are you?", but the bot was only programmed to answer to that question if it was said like this, "How are you?". I want to simplify the coding so I won't have to use a "or" statement. Please provide example code.
[ "if talk.upper() == \"HOW ARE YOU\":\n perform_action()\n\nor, if you prefer to search for substrings\nif \"HOW ARE YOU\" in talk.upper():\n perform_action()\n\n", "Easy way would be to lowercase everything:\nif \"how are you\" == talk.lower():\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003898010_python.txt
Q: How to get setuptools to use a relative path in easy-install.pth when doing "setup.py develop" I'm installing a python egg using setuptools with the "python setup.py develop" command. It's important that all install paths be relative. I see that I can do: python setup.py develop --egg-path ../../../../my_directory and the .egg-link file uses that relative path. However, the path added to easy-install.pth still is an absolute path. How do I make the path in the easy-install.pth file a relative path? A: If your sourcecode is in a subdirectory of the installation directory, it will be made relative automatically. Why do you need it to be relative, anyway?
How to get setuptools to use a relative path in easy-install.pth when doing "setup.py develop"
I'm installing a python egg using setuptools with the "python setup.py develop" command. It's important that all install paths be relative. I see that I can do: python setup.py develop --egg-path ../../../../my_directory and the .egg-link file uses that relative path. However, the path added to easy-install.pth still is an absolute path. How do I make the path in the easy-install.pth file a relative path?
[ "If your sourcecode is in a subdirectory of the installation directory, it will be made relative automatically.\nWhy do you need it to be relative, anyway?\n" ]
[ 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0003886667_python_setuptools.txt
Q: Python: how can I get rid of the second element of each sublist? I have a list of sublists, such as: [[501, 4], [501, 4], [501, 4], [501, 4]] How can I get rid of the second element for each sublist ? (i.e. 4) [501, 501, 501, 501] Should I iterate the list or is there a faster way ? thanks A: You can use a list comprehension to take the first element of each sublist: xs = [[501, 4], [501, 4], [501, 4], [501, 4]] [x[0] for x in xs] # [501, 501, 501, 501] A: a = [[501, 4], [501, 4], [501, 4], [501, 4]] b = [c[0] for c in a] A: A less pythonic, functional version using map: a = [[501, 4], [501, 4], [501, 4], [501, 4]] map(lambda x: x[0], a) Less pythonic, since it does not use list comprehensions. See here.
Python: how can I get rid of the second element of each sublist?
I have a list of sublists, such as: [[501, 4], [501, 4], [501, 4], [501, 4]] How can I get rid of the second element for each sublist ? (i.e. 4) [501, 501, 501, 501] Should I iterate the list or is there a faster way ? thanks
[ "You can use a list comprehension to take the first element of each sublist:\nxs = [[501, 4], [501, 4], [501, 4], [501, 4]]\n[x[0] for x in xs]\n# [501, 501, 501, 501]\n\n", "a = [[501, 4], [501, 4], [501, 4], [501, 4]]\nb = [c[0] for c in a]\n\n", "A less pythonic, functional version using map:\na = [[501, 4],...
[ 7, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003898065_python.txt
Q: Simple interpreter to embed and extend inside an C++ Windows application I need a simple interpreter which will do execution (evaluation) of simple expressions/statements and also call functions from main C++ applications. At the moment I do not need scripting of the application, but it may be useful later. It should also be strait-forward for other team members to pull my application from Source Repository and to build it, without having to install additional application, libraries, etc. Searching reveled options like: Python (via Boost and / or Python API), Lua, Guile, TinyScheme. I am the closest to Python, but using Boost, building Python library, complicated task of interfacing main application with Python makes this choice an overkill, maybe I am wrong. There should be a simple solution for this request, what are your experiences and suggestions? A: Two great options you've already listed are Python and Lua. Here are some of the tradeoffs for your consideration: Python A much more complete and powerful language (IMHO!) with libraries for anything and tons of support and communities everywhere you look. Syntax is not entirely C-like Although Python wasn't designed specifically for embedding (it's much more often used as a standalone language extended by code in C/C++), it's tot really hard to embed. The official docs contain some examples, and following Boost's examples shouldn't be much harder. Lua Designed from bottom up for embedding, so it should be the simplest one to embed. Syntax more C-like than Python's If you foresee a definite future need for scripting, building in a scripting engine early is a good idea as it may open some interesting possibilities for you as you go on developing the program. Both options listed above are good ones, you should have no problems embedding any of them without much effort. A: If you only want to evaluate arithmetic expressions, try ae, a simple interface to Lua for that task. A: No matter which scripting language you choose (and I would probably vote for Python), you might consider using SWIG (www.swig.org) to ease the burden of interfacing to C++. While normally used to build C++ extensions for python (or ruby, lua, guile, any many others), it can be used to aid in embedding too. You had mentioned boost::python, which is certainly a full featured option, and allows for a somewhat closer Python/C++ integration (especially where virtual functions are involved). However, in my experience, SWIG is a lot easier to integrate, works with scads of scripting languages, and for python, is natively supported by Python's distutils. A: Guile is easy to embed and extend, and scheme if powerfull programming language. You can compile libguile and add it to the repository in lib directory or add source for guile and compile it when user compile the project. But I don't try to use guile on Windows.
Simple interpreter to embed and extend inside an C++ Windows application
I need a simple interpreter which will do execution (evaluation) of simple expressions/statements and also call functions from main C++ applications. At the moment I do not need scripting of the application, but it may be useful later. It should also be strait-forward for other team members to pull my application from Source Repository and to build it, without having to install additional application, libraries, etc. Searching reveled options like: Python (via Boost and / or Python API), Lua, Guile, TinyScheme. I am the closest to Python, but using Boost, building Python library, complicated task of interfacing main application with Python makes this choice an overkill, maybe I am wrong. There should be a simple solution for this request, what are your experiences and suggestions?
[ "Two great options you've already listed are Python and Lua. Here are some of the tradeoffs for your consideration:\nPython\n\nA much more complete and powerful language (IMHO!) with libraries for anything and tons of support and communities everywhere you look.\nSyntax is not entirely C-like\nAlthough Python wasn'...
[ 4, 3, 2, 1 ]
[]
[]
[ "c++", "lua", "python", "scripting" ]
stackoverflow_0003896313_c++_lua_python_scripting.txt
Q: South's syncdb/migrate creates pages of output? I'm working a small, personal Django project and I've added South (latest mercurial as of 10/9/10) to my project. However, whenever I run "./manage.py syncdb" or "./manage.py migrate " I get about 13 pages (40 lines each) of output solely regarding 'initial_data' files not being found. I don't have any initial_data nor do I really want any, yet I get over 200 attempts at reading them for all the different apps in my project, including django's own apps. Is there any way to quiet South? I haven't given South any input beyond adding it to my INSTALLED_APPS tuple and throwing an initial migration on, but I've gotten this annoying output since I installed it. A: How is Your logging configured? I have turned much of the output by configuring logging to higher level, as in: [formatters] keys=simple [handlers] keys=console [loggers] keys=root,south [formatter_simple] format=%(asctime)s %(levelname)7s %(message)s datefmt=%Y-%m-%d %H:%M:%S [handler_console] class=StreamHandler args=[] formatter=simple [logger_root] level=INFO qualname=root handlers=console [logger_south] level=INFO qualname=south handlers=console Also beware that logging config has to be called AFTER south logging has been imported, because of some magic. From my project, in my settings: # south is setting logging on import-time; import it before setting our logger # so it is not overwriting our settings try: import south.logger except ImportError: pass import logging.config if LOGGING_CONFIG_FILE: logging.config.fileConfig(LOGGING_CONFIG_FILE)
South's syncdb/migrate creates pages of output?
I'm working a small, personal Django project and I've added South (latest mercurial as of 10/9/10) to my project. However, whenever I run "./manage.py syncdb" or "./manage.py migrate " I get about 13 pages (40 lines each) of output solely regarding 'initial_data' files not being found. I don't have any initial_data nor do I really want any, yet I get over 200 attempts at reading them for all the different apps in my project, including django's own apps. Is there any way to quiet South? I haven't given South any input beyond adding it to my INSTALLED_APPS tuple and throwing an initial migration on, but I've gotten this annoying output since I installed it.
[ "How is Your logging configured?\nI have turned much of the output by configuring logging to higher level, as in:\n[formatters]\nkeys=simple\n\n[handlers]\nkeys=console\n\n[loggers]\nkeys=root,south\n\n[formatter_simple]\nformat=%(asctime)s %(levelname)7s %(message)s\ndatefmt=%Y-%m-%d %H:%M:%S\n\n[handler_console]\...
[ 2 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0003898239_django_django_south_python.txt
Q: Calculating the remaining time to a repeating event in Python The scenario is as follows: given a totally arbitrary starting date in UTC there is an event that repeats every 24 hours. I need to calculate, given the current local time, how much time is left before the next event. Ideally an ideal function would do: time_since_start = now - start_time remaining_seconds = time_remaining(time_since_start) EDIT: Some clarifications. start_time defines the "epoch", the global start time since the event started repeating. Secondly, now is an arbitrary time occurring after start_time, local. The issue is not calculating the occurrence of the next event (which would be simply adding 24 hours to start_time) but if I pick a time that falls between one event and the other, how much time is left before the next event. I'd opt seconds as they can be quickly parsed into days, minutes and hours. Usage of datetime would be preferred (but not required) over other third-party modules as I am trying to reduce the number of dependencies. I tried using datetime and timedelta, but the difference is always incorrect. What is the best way to proceed there? A: What you want is start_time - now + (one day)
Calculating the remaining time to a repeating event in Python
The scenario is as follows: given a totally arbitrary starting date in UTC there is an event that repeats every 24 hours. I need to calculate, given the current local time, how much time is left before the next event. Ideally an ideal function would do: time_since_start = now - start_time remaining_seconds = time_remaining(time_since_start) EDIT: Some clarifications. start_time defines the "epoch", the global start time since the event started repeating. Secondly, now is an arbitrary time occurring after start_time, local. The issue is not calculating the occurrence of the next event (which would be simply adding 24 hours to start_time) but if I pick a time that falls between one event and the other, how much time is left before the next event. I'd opt seconds as they can be quickly parsed into days, minutes and hours. Usage of datetime would be preferred (but not required) over other third-party modules as I am trying to reduce the number of dependencies. I tried using datetime and timedelta, but the difference is always incorrect. What is the best way to proceed there?
[ "What you want is start_time - now + (one day)\n" ]
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003898397_datetime_python.txt
Q: Ordering a django model on many-to-may field. Denormalization required? I have a system for composing items from parts in certain categories For instance take the following categories: 1: (Location) 2: (Material) And the following parts: Wall (FK=1) Roof (FK=1) Roof (FK=1) Brick (FK=2) Tile (FK=2) Wood (FK=2) To compose these items: Wall.Brick, Roof.Wood, Wall.Wood class Category(models.Model): ordering = models.IntegerField() desc = models.CharField() class Part: name = models.CharField() category = models.ForeignKey(Category) class Meta: unique_together = ('name', 'category') ordering = ['category','name'] class Item: parts = ManyToManyField(Part) def __unicode__(self): return ".".join([p.name for p in self.parts.all()]) Now the question: how do i order the Items? I'd prefer to have them ordered ascending by the composed name, but dont know how. One way of doing things could be an extra field for the name, that gets updated on the save() method. That would mean denormalizing the model... A: If I understand correctly, sort key do not exist in database, so database cannot sort it (or at least on trivially, like using Django ORM). Under those conditions, yes - denormalize. It's no shame. As said, normalized dataset is for sissies...
Ordering a django model on many-to-may field. Denormalization required?
I have a system for composing items from parts in certain categories For instance take the following categories: 1: (Location) 2: (Material) And the following parts: Wall (FK=1) Roof (FK=1) Roof (FK=1) Brick (FK=2) Tile (FK=2) Wood (FK=2) To compose these items: Wall.Brick, Roof.Wood, Wall.Wood class Category(models.Model): ordering = models.IntegerField() desc = models.CharField() class Part: name = models.CharField() category = models.ForeignKey(Category) class Meta: unique_together = ('name', 'category') ordering = ['category','name'] class Item: parts = ManyToManyField(Part) def __unicode__(self): return ".".join([p.name for p in self.parts.all()]) Now the question: how do i order the Items? I'd prefer to have them ordered ascending by the composed name, but dont know how. One way of doing things could be an extra field for the name, that gets updated on the save() method. That would mean denormalizing the model...
[ "If I understand correctly, sort key do not exist in database, so database cannot sort it (or at least on trivially, like using Django ORM).\nUnder those conditions, yes - denormalize.\nIt's no shame. As said, normalized dataset is for sissies...\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003896310_django_python.txt
Q: Import from a Django project with a different top-level folder name I recently setup a deployment solution for my Django project using Fabric. The basic workflow being: Check out the latest source from git on the server. Copy it to a 'releases' directory and add a timestamp to the directory name. Update the 'current' symlink to point to the latest build. This works just fine, only problem is, since the top level directory is a symlink called 'current' and that points to a folder like 'project_name_2010_10_04' ALL of the following Import statements will fail: from project_name.app import models ... INSTALLED_APPS = ( 'project_name.app' ) ... urlpatterns = patterns('', (r'^$', 'project_name.app.views.index'), ) So the solution I've found is to remove EVERY single reference to 'project_name' in my project, and the app seems to deploy and work just fine (for now). But this doesn't seem like the right way to solve the problem... mostly because in a newly created Django project the 'urls.py', 'settings.py' all reference the project name by default and also various Django documentation mentions using the project name for various things. So to sum up my problem, is there a way to specify a package name that differs from the actual directory name? A: Simply put, you really shouldn't be using your project name hard-coded anywhere, especially in specific apps, as it just completely breaks their portability and re-usability. A: It seems that You have manage.py, urls.py and friends directly in the root of Your repository. This is not right: on top-level, there should be setup.py, requirements.txt and project directory, inside which manage.py and friends should live. (OK, if You want to be more compatible with non-Python world, it should live inside top-level src/ directory...)
Import from a Django project with a different top-level folder name
I recently setup a deployment solution for my Django project using Fabric. The basic workflow being: Check out the latest source from git on the server. Copy it to a 'releases' directory and add a timestamp to the directory name. Update the 'current' symlink to point to the latest build. This works just fine, only problem is, since the top level directory is a symlink called 'current' and that points to a folder like 'project_name_2010_10_04' ALL of the following Import statements will fail: from project_name.app import models ... INSTALLED_APPS = ( 'project_name.app' ) ... urlpatterns = patterns('', (r'^$', 'project_name.app.views.index'), ) So the solution I've found is to remove EVERY single reference to 'project_name' in my project, and the app seems to deploy and work just fine (for now). But this doesn't seem like the right way to solve the problem... mostly because in a newly created Django project the 'urls.py', 'settings.py' all reference the project name by default and also various Django documentation mentions using the project name for various things. So to sum up my problem, is there a way to specify a package name that differs from the actual directory name?
[ "Simply put, you really shouldn't be using your project name hard-coded anywhere, especially in specific apps, as it just completely breaks their portability and re-usability.\n", "It seems that You have manage.py, urls.py and friends directly in the root of Your repository.\nThis is not right: on top-level, ther...
[ 4, 0 ]
[]
[]
[ "django", "fabric", "importerror", "python" ]
stackoverflow_0003864615_django_fabric_importerror_python.txt
Q: python thread queue question Hell All. i was made some python script with thread which checking some of account exist in some website if i run thread 1 , it working well but if increase thread such like 3~5 and above, result was very different compare with thread 1 and i was checked manually and if i increase thread result was not correct. i think some of my thread code have to tune or how about use Queue module ? anyone can advice or tuneing my script? Thanks in advance! # -*- coding: cp949 -*- import sys,os import mechanize, urllib import cookielib import re from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag import re,sys,os,mechanize,urllib,threading,time # Maximum number of process to spawn at any one given time. MAX_PROCS =5 maillist = "daum.txt" threads = [] SAVEFILE = 'valid_joyhunt.txt' # Threading class class CheckMyThread ( threading.Thread ): llemail = "" llpassword = "" def __init__ ( self , lemail, lpassword): self.llemail = lemail self.llpassword = lpassword threading.Thread.__init__( self ) pass def run ( self ): valid = [] llemail = self.llemail llpassword = self.llpassword try: params = urllib.urlencode({'userid':llemail, 'passwd':llpassword}) rq = mechanize.Request("http://www.joyhunting.com/include/member/login_ok1.asp", params) rs = mechanize.urlopen(rq) data = rs.read() logged_in = r'var _id' in data #정상 로그인 if logged_in : rq = mechanize.Request("http://www.joyhunting.com/myjoy/new_myjoy.asp") rs = mechanize.urlopen(rq) maindata = rs.read(50024) jun_member = r"준회원" save = open(SAVEFILE, 'a') for match in re.finditer(r'<td height="28" colspan="2" style="PADDING-left: 16px">현재 <strong>(.*?)</strong>', maindata): matched = match.group(1) for match2 in re.finditer(r"var _gd(.*?);", data): matched2 = match2.group(1) print '%s, %s' %(matched, matched2) break rq1=mechanize.Request("http://www.joyhunting.com/webchat/applyweb/sendmessage_HPCK_step1.asp?reURL=1&myid="+llemail+"&ToID=undefined&hide=undefined") rs1=mechanize.urlopen(rq1) sendmsg= rs1.read() #print sendmsg match3 = '' for match3 in re.finditer(r":'\+(.*?)\);", sendmsg): matched3 = match3.group(1) #print matched3 print 'bad' break if match3 =='': save.write('%s, %s, %s:%s ' %(matched, matched2, llemail, llpassword + '\n')) save.close() print '[+] Checking: %s:%s -> Good!' % (llemail, llpassword) else: print '[-] Checking: %s:%s -> bad account!' % (llemail, llpassword) return 0 except: print '[!] Exception checking %s.' % (llemail) return 1 return 0 try: listhandle = open(maillist); #Bail out if the file doesn't exist except: print '[!] %s does not exist. Please create the file!' % (maillist) exit (2) #Loop through the file for line in listhandle: #Parse the line try: details = line.split(':') email = details[0] password = details[1].replace('\n', '') #Throw an error and exit. except: print '[!] Parse Error in %s on line %n.' % (maillist, currline) exit #Run a while statement: if len(threads) < MAX_PROCS: #Fork out into another process print '[ ] Starting thread to check account %s.' % (email); thread = CheckMyThread(email, password) thread.start() threads.append(thread) else: #Wait for a thread to exit. gonext = 0 while 1 == 1: i = 0 #print '[ ] Checking for a thread to exit...' while i < len(threads): #print '[ ] %d' % (i) try: if threads[i]: if not threads[i].isAlive(): #print '[-] Thread %d is dead' % (i) threads.pop(i) print '[ ] Starting thread to check account %s.' % (email); thread = CheckMyThread(email, password) thread.start() threads.append(thread) gonext = 1 break else: #print '[+] Thread %d is still running' % (i) pass else: print '[ ] Crap.'; except NameError: print '[ ] AWWW COME ON!!!!' i = i + 1 time.sleep(0.050); if gonext: break A: Can You please specify what are different results? From what I see, code is doing much more than verifying account. From what I see, You're appending to a single file from multiple threads, I'd say it's not thread-safe. Also, AFAIK Mechanize uses shared cookie storage for all requests, so they are probably interfering. Use separate mechanize.Browser() inside run() instead of mechanize.Request().
python thread queue question
Hell All. i was made some python script with thread which checking some of account exist in some website if i run thread 1 , it working well but if increase thread such like 3~5 and above, result was very different compare with thread 1 and i was checked manually and if i increase thread result was not correct. i think some of my thread code have to tune or how about use Queue module ? anyone can advice or tuneing my script? Thanks in advance! # -*- coding: cp949 -*- import sys,os import mechanize, urllib import cookielib import re from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag import re,sys,os,mechanize,urllib,threading,time # Maximum number of process to spawn at any one given time. MAX_PROCS =5 maillist = "daum.txt" threads = [] SAVEFILE = 'valid_joyhunt.txt' # Threading class class CheckMyThread ( threading.Thread ): llemail = "" llpassword = "" def __init__ ( self , lemail, lpassword): self.llemail = lemail self.llpassword = lpassword threading.Thread.__init__( self ) pass def run ( self ): valid = [] llemail = self.llemail llpassword = self.llpassword try: params = urllib.urlencode({'userid':llemail, 'passwd':llpassword}) rq = mechanize.Request("http://www.joyhunting.com/include/member/login_ok1.asp", params) rs = mechanize.urlopen(rq) data = rs.read() logged_in = r'var _id' in data #정상 로그인 if logged_in : rq = mechanize.Request("http://www.joyhunting.com/myjoy/new_myjoy.asp") rs = mechanize.urlopen(rq) maindata = rs.read(50024) jun_member = r"준회원" save = open(SAVEFILE, 'a') for match in re.finditer(r'<td height="28" colspan="2" style="PADDING-left: 16px">현재 <strong>(.*?)</strong>', maindata): matched = match.group(1) for match2 in re.finditer(r"var _gd(.*?);", data): matched2 = match2.group(1) print '%s, %s' %(matched, matched2) break rq1=mechanize.Request("http://www.joyhunting.com/webchat/applyweb/sendmessage_HPCK_step1.asp?reURL=1&myid="+llemail+"&ToID=undefined&hide=undefined") rs1=mechanize.urlopen(rq1) sendmsg= rs1.read() #print sendmsg match3 = '' for match3 in re.finditer(r":'\+(.*?)\);", sendmsg): matched3 = match3.group(1) #print matched3 print 'bad' break if match3 =='': save.write('%s, %s, %s:%s ' %(matched, matched2, llemail, llpassword + '\n')) save.close() print '[+] Checking: %s:%s -> Good!' % (llemail, llpassword) else: print '[-] Checking: %s:%s -> bad account!' % (llemail, llpassword) return 0 except: print '[!] Exception checking %s.' % (llemail) return 1 return 0 try: listhandle = open(maillist); #Bail out if the file doesn't exist except: print '[!] %s does not exist. Please create the file!' % (maillist) exit (2) #Loop through the file for line in listhandle: #Parse the line try: details = line.split(':') email = details[0] password = details[1].replace('\n', '') #Throw an error and exit. except: print '[!] Parse Error in %s on line %n.' % (maillist, currline) exit #Run a while statement: if len(threads) < MAX_PROCS: #Fork out into another process print '[ ] Starting thread to check account %s.' % (email); thread = CheckMyThread(email, password) thread.start() threads.append(thread) else: #Wait for a thread to exit. gonext = 0 while 1 == 1: i = 0 #print '[ ] Checking for a thread to exit...' while i < len(threads): #print '[ ] %d' % (i) try: if threads[i]: if not threads[i].isAlive(): #print '[-] Thread %d is dead' % (i) threads.pop(i) print '[ ] Starting thread to check account %s.' % (email); thread = CheckMyThread(email, password) thread.start() threads.append(thread) gonext = 1 break else: #print '[+] Thread %d is still running' % (i) pass else: print '[ ] Crap.'; except NameError: print '[ ] AWWW COME ON!!!!' i = i + 1 time.sleep(0.050); if gonext: break
[ "Can You please specify what are different results?\nFrom what I see, code is doing much more than verifying account.\nFrom what I see, You're appending to a single file from multiple threads, I'd say it's not thread-safe.\nAlso, AFAIK Mechanize uses shared cookie storage for all requests, so they are probably inte...
[ 0 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0003836565_multithreading_python_queue.txt
Q: django.contrib.admin like application for cherrypy Is there a django.contrib.admin like app / module for cherrypy? I really like the simplicity of cherrypy, but it would be nice, to have the user authentication and password management type things taken care of... Or is it possible to run a cherrypy application behind the django admin app ? A: Django admin is much more, but is bound to Models. Without them, You will not gain much and as there is no such concept in CherryPy, I doubt there is similar application. However, Django admin is phpmyadmin for masses exploited. Don't be constrained by it and create much more usable admin apps, leveraging CherryPy simplicity ^_^ A: There is no database backend in CherryPy so there cannot be any Admin-interface for it. But you can use any database backend with CherryPy. For example you could use CouchDB. It has an admin interface called Futon. Futon is of course somewhat low level compared to Django Admin/Models.
django.contrib.admin like application for cherrypy
Is there a django.contrib.admin like app / module for cherrypy? I really like the simplicity of cherrypy, but it would be nice, to have the user authentication and password management type things taken care of... Or is it possible to run a cherrypy application behind the django admin app ?
[ "Django admin is much more, but is bound to Models. Without them, You will not gain much and as there is no such concept in CherryPy, I doubt there is similar application.\nHowever, Django admin is phpmyadmin for masses exploited. Don't be constrained by it and create much more usable admin apps, leveraging CherryP...
[ 3, 2 ]
[]
[]
[ "cherrypy", "django", "python" ]
stackoverflow_0003861027_cherrypy_django_python.txt
Q: Is it time to cut over to Python 3.x now or not? Is 2.x still the norm or would you recommend just coding in v3 at this point? A: Python 3 is still a long way off having universal support from tools, libraries and distros, so its use in production would depend very much on whether the bits you need (or are likely to need in the near future) have been ported. For exploratory, educational and other uses, it depends very much on your own proclivity for living on the bleeding edge. If you are happy building from source and debugging and hacking third-party libraries to get things working, then you'll probably have no issues with Python 3. Otherwise, stick to the latest your distro offers, and if it is stuck on a really old Python — CentOS is still on 2.4! — you have my commiserations. Personally, I steer clear of CentOS for precisely this reason. A: Google App Engine documentation states it uses Python 2.5 Today I happened to notice that Python Imaging Library is till not released for 3.x. So, if you need those libraries or services, I guess you should wait. A: Do the frameworks and libraries you use have Python 3 versions? Libraries you use for development, and does your deploy stack support Python 3? Many Python projects have a lot of dependancies, especially web based projects, most of which aren't Py3K ready yet. If your stack is good, sure - Python 3 is the future, might as well embrace it now. A: My main use of Python is Django. Support for 3.x for this framework still lies in the future, unfortunately, and who knows about any related modules - so no, it's not quite time for many people. I actually bought Python 3 books last year when I started learning Python, thinking "I'll just start with 3 from the beginning!". That didn't work out, though. A: I've always used v3 primarily. "Hacking 3rd party libraries" to me is just like importing any other module. The only thing is since most stuff still uses v2 you have to know both versions and keep them straight when looking at others code.
Is it time to cut over to Python 3.x now or not?
Is 2.x still the norm or would you recommend just coding in v3 at this point?
[ "Python 3 is still a long way off having universal support from tools, libraries and distros, so its use in production would depend very much on whether the bits you need (or are likely to need in the near future) have been ported.\nFor exploratory, educational and other uses, it depends very much on your own procl...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003898411_python.txt
Q: How to do cloud computing with Python and Java? Final Year project For my final year project I plan to code a cloud in Python. The client will be written in Java by the other member of my team. The client will have a tabbed interface and it will provide a text editor, a media player, a couple of small Java based games and a maybe a few more services. The server will work like this: 1) Validate the user. 2) Send a file, called "dump" to the user. Dump will contain all the file names and file types that the user created by himself or the files which the user can read/write. This info will be fetched from the database. 3) The tabs in the client will display the file types associated with the tab application. e.g the media tab will only select and show the media files from the dump readable by user. The text editor tab will show only the txt files from the dump readable by the user. 4) A request to open the file will send the file back to client, which the associated application will open. 5) All the changes made to the files and all the actions (overwriting, saving, deleting etc.) will be sent back to the server along with the new object. Something similar will be done to the newly created objects. My Questions are: What are the best approaches for the communication between the client and the server. For the dump I plan to use some sort of encrypted XML file. For the other way round, I don't have a clue :/. For easy integration with the database, I was planning to use Django (which I started few days back). How can I send my requests from the client to the server (without Django I'd use SQL queries) and the files from the server to the client? Maybe GET and POST will work for the former problem? Any other suggestions? A: Q1: how should I transfer data between client/server securely A: HTTPS to support encryption & JSON to serialise objects between languages (Python/Java) seems to be the most natural. You could experiment with XML-RPC over SSL or TSL if you want to be creative. Q2: How do I send queries to the server's db? A: My first response is to say talk to the person coding the server, and see what's easiest on that end. However, I think that your client should stick to HTTP. The server developer would ensure the server supports RESTful URIs. Then your client only access a URI and have the results processed by the server. At its most raw, this could be implemented like this: https://www.example.com/db?q="SELECT * FROM docs" There are smarter ways to do it, but you get the idea. A: If you're going to use a web framework on the server, it makes sense to use an HTTP-based protocol. The downside is that only the client can initiate a connection (e.g., the client needs to first ask for the "dump" file), but a simple GET request will suffice (remember, the server can send anything in the HTTP response, including your XML file). Regarding encryption, it's best to use an existing protocol like HTTPS. There are well-vetted libraries that will correctly establish a secure connection between your client and the server. Overall, I'm advocating the highest-level protocols that are appropriate for your application. HTTP(S) goes hand-in-hand with your web-based architecture, so make use of it. A: Stick to Django. It's really productive. I would use JSON instead of XML. More convenient. import json. This should help you in communicating between client-server. Also cloud computing is just a recent word that's just thrown around for (client+server+some services). Oh by the way all that you want to do can be completely done in Django itself. No need to go to JAVA. Django is Cool :)
How to do cloud computing with Python and Java? Final Year project
For my final year project I plan to code a cloud in Python. The client will be written in Java by the other member of my team. The client will have a tabbed interface and it will provide a text editor, a media player, a couple of small Java based games and a maybe a few more services. The server will work like this: 1) Validate the user. 2) Send a file, called "dump" to the user. Dump will contain all the file names and file types that the user created by himself or the files which the user can read/write. This info will be fetched from the database. 3) The tabs in the client will display the file types associated with the tab application. e.g the media tab will only select and show the media files from the dump readable by user. The text editor tab will show only the txt files from the dump readable by the user. 4) A request to open the file will send the file back to client, which the associated application will open. 5) All the changes made to the files and all the actions (overwriting, saving, deleting etc.) will be sent back to the server along with the new object. Something similar will be done to the newly created objects. My Questions are: What are the best approaches for the communication between the client and the server. For the dump I plan to use some sort of encrypted XML file. For the other way round, I don't have a clue :/. For easy integration with the database, I was planning to use Django (which I started few days back). How can I send my requests from the client to the server (without Django I'd use SQL queries) and the files from the server to the client? Maybe GET and POST will work for the former problem? Any other suggestions?
[ "Q1: how should I transfer data between client/server securely\nA: HTTPS to support encryption & JSON to serialise objects between languages (Python/Java) seems to be the most natural. You could experiment with XML-RPC over SSL or TSL if you want to be creative.\nQ2: How do I send queries to the server's db?\nA: My...
[ 1, 0, 0 ]
[]
[]
[ "cloud", "django", "python" ]
stackoverflow_0003896741_cloud_django_python.txt
Q: Python, Webkit: how to get the DOM after the page has loaded? In my code I've connected to the WebView's load-finished event. The particular callback function takes a webview object and frame object as arguments. Then I tried executing get_dom_document() on the frame & the webview objects respectively. It seems this method doesn't exist for those objects... PS: i started with the tips i got here http://www.gnu.org/software/pythonwebkit/ UPDATE (11-Sep-2010): I think the link I shared relates to a new & different project. Its not a solution per se. My bad! A: it's definitely there. and you can't just "take the tips from http://www.gnu.org/software/pythonwebkit/" you actually have to COMPILE THE CODE (reason: standard pywebkitgtk DOES NOT have W3C DOM accessor functions). then take a look in pythonwebkit/pywebkitgtk/examples and run browser.py and you'll see what to do. l. A: i forgot to mention (and it wasn't on the documentation, which i've now updated): you specifically need to check out the "python_codegen" branch, otherwise you just end up with plain vanilla webkit. which is of absolutely no use to you.
Python, Webkit: how to get the DOM after the page has loaded?
In my code I've connected to the WebView's load-finished event. The particular callback function takes a webview object and frame object as arguments. Then I tried executing get_dom_document() on the frame & the webview objects respectively. It seems this method doesn't exist for those objects... PS: i started with the tips i got here http://www.gnu.org/software/pythonwebkit/ UPDATE (11-Sep-2010): I think the link I shared relates to a new & different project. Its not a solution per se. My bad!
[ "it's definitely there.\nand you can't just \"take the tips from http://www.gnu.org/software/pythonwebkit/\" you actually have to COMPILE THE CODE (reason: standard pywebkitgtk DOES NOT have W3C DOM accessor functions).\nthen take a look in pythonwebkit/pywebkitgtk/examples and run browser.py and you'll see what t...
[ 2, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "webkit" ]
stackoverflow_0003893577_gtk_pygtk_python_webkit.txt
Q: Django/Celery can't find importlib So I just updated django to 1.2.3 and now when I try to run 'python manage.py shell' to work in the django environment, I'm getting the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 220, in execute output = self.handle(*args, **options) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 351, in handle return self.handle_noargs(**options) File "/opt/local/lib/python2.5/site-packages/django/core/management/commands/shell.py", line 18, in handle_noargs loaded_models = get_models() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/models/loading.py", line 167, in get_models self._populate() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/models/loading.py", line 64, in _populate self.load_app(app_name) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/models/loading.py", line 78, in load_app models = import_module('.models', app_name) File "/opt/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/opt/local/lib/python2.5/site-packages/django_celery-2.0.3-py2.5.egg/djcelery/models.py", line 7, in <module> from celery import conf File "/opt/local/lib/python2.5/site-packages/celery-2.0.3-py2.5.egg/celery/conf.py", line 6, in <module> from celery import routes File "/opt/local/lib/python2.5/site-packages/celery-2.0.3-py2.5.egg/celery/routes.py", line 2, in <module> from celery.utils import instantiate, firstmethod, mpromise File "/opt/local/lib/python2.5/site-packages/celery-2.0.3-py2.5.egg/celery/utils/__init__.py", line 9, in <module> import importlib ImportError: No module named importlib Any ideas. I can't seem to find what's going on here and for all I can tell I'm running the same versions on my web server and I don't have the same error showing up. A: importlib which was added in Python 2.7/3.1, I believe. You can download a port for pyton 2.5 here: importlib 1.0.1 - Backport of importlib.import_module() from Python 2.7 Also check the setup.cfg for celery near the bottom and make sure all the other requirements are met (toward the bottom of the script). A: importlib was added to Python in version 3.1, and then backported to Python 2.7. Third party backports are available on PyPI. Also note that 'backported to 2.7' doesn't imply that all versions after 2.7 will have importlib. Python 3.0, I believe, does not have importlib.
Django/Celery can't find importlib
So I just updated django to 1.2.3 and now when I try to run 'python manage.py shell' to work in the django environment, I'm getting the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 220, in execute output = self.handle(*args, **options) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 351, in handle return self.handle_noargs(**options) File "/opt/local/lib/python2.5/site-packages/django/core/management/commands/shell.py", line 18, in handle_noargs loaded_models = get_models() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/models/loading.py", line 167, in get_models self._populate() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/models/loading.py", line 64, in _populate self.load_app(app_name) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/models/loading.py", line 78, in load_app models = import_module('.models', app_name) File "/opt/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/opt/local/lib/python2.5/site-packages/django_celery-2.0.3-py2.5.egg/djcelery/models.py", line 7, in <module> from celery import conf File "/opt/local/lib/python2.5/site-packages/celery-2.0.3-py2.5.egg/celery/conf.py", line 6, in <module> from celery import routes File "/opt/local/lib/python2.5/site-packages/celery-2.0.3-py2.5.egg/celery/routes.py", line 2, in <module> from celery.utils import instantiate, firstmethod, mpromise File "/opt/local/lib/python2.5/site-packages/celery-2.0.3-py2.5.egg/celery/utils/__init__.py", line 9, in <module> import importlib ImportError: No module named importlib Any ideas. I can't seem to find what's going on here and for all I can tell I'm running the same versions on my web server and I don't have the same error showing up.
[ "importlib which was added in Python 2.7/3.1, I believe. You can download a port for pyton 2.5 here:\n\nimportlib 1.0.1 - Backport of importlib.import_module() from Python 2.7\n\nAlso check the setup.cfg for celery near the bottom and make sure all the other requirements are met (toward the bottom of the script).\...
[ 8, 1 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0003897436_celery_django_python.txt
Q: Is using multiple Timers in Python dangerous? I am working on a text-based game in Python 3.1 that would use timing as it's major source of game play. In order to do this effectively (rather than check the time every mainloop, my current method, which can be inaccurate, and slow if multiple people are playing the game at once) I was thinking about using the Threading.Timer class. Is it a bad thing to have multiple timers going at the same time? if so, how many timers is recommended? For example, the user inputs to start the game. every second after the game starts it decides whether or not something happens, so there's a Timer(1) for every user playing at the same time. If something happens, the player has a certain time to react to it, so a timer must be set for that. If the user reacts quickly enough, that timer needs to end and it will set a new timer depending on what's going to happen next, etc A: I think its a bad idea to use Timers in your case. Using the delayed threads in python will result in more complex code, less accuracy, and quite possible worse performance. Basically, the rule is that if you think you need threads, you don't. Very few programs benefit from the use of threads. I don't know what you are doing for input. You make reference to multiple players and I'm not sure whether thats on a single keyboard or perhaps networked. Regardless, your current strategy of a main loop may well be the best strategy. Although without seeing how your main loop operates its hard to say for certain. A: It should be perfectly safe to have multiple timers going at the same time. Beware that it may not give much of a performance boost, as the CPython interpreter (the standard Python interpreter) uses a GIL (Global Interpreter Lock) which makes threading stuff a bit.... slow.
Is using multiple Timers in Python dangerous?
I am working on a text-based game in Python 3.1 that would use timing as it's major source of game play. In order to do this effectively (rather than check the time every mainloop, my current method, which can be inaccurate, and slow if multiple people are playing the game at once) I was thinking about using the Threading.Timer class. Is it a bad thing to have multiple timers going at the same time? if so, how many timers is recommended? For example, the user inputs to start the game. every second after the game starts it decides whether or not something happens, so there's a Timer(1) for every user playing at the same time. If something happens, the player has a certain time to react to it, so a timer must be set for that. If the user reacts quickly enough, that timer needs to end and it will set a new timer depending on what's going to happen next, etc
[ "I think its a bad idea to use Timers in your case.\nUsing the delayed threads in python will result in more complex code, less accuracy, and quite possible worse performance. Basically, the rule is that if you think you need threads, you don't. Very few programs benefit from the use of threads.\nI don't know what ...
[ 3, 1 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0003898740_python_timer.txt
Q: Python audio library for simultaneous audio creation and playback I'm working on an audio creation framework. It'll be generating large audio files, say 3 minute long audio files that take about 1 minute to generate. So what I want is a system much like streaming audio from the internet, where I play the sound as I generate it. Pygame's mixer allows me to edit the sound as it's playing. But I cannot figure out how to change the sample rate, sample size, or number of channels. Snack allows me to edit sounds, as well as their sample rate, sample size, length, and number of channels. But I cannot figure out how to edit sounds as they are playing. Could anybody point me to a library that allows me to edit a sound as it is playing, as well as configure the number of channels, sample rate, and length (all known ahead of time)? If not, perhaps somebody knows of a tutorial to do this in C++? [EDIT] Pymedia.audio would work fine for me. However, I can't get it to work under Python 2.6. Any ideas? A: pymedia.audio does work with Python 2.6. Take a look at this SO post: Pymedia installation on Windows with Python 2.6 You can append audio to Output objects, as they are playing. So as each sample is generated, it can also be appended to the stream. The example in their documentation shows just how to do this: http://pymedia.org/docs/pymedia.audio.sound.html
Python audio library for simultaneous audio creation and playback
I'm working on an audio creation framework. It'll be generating large audio files, say 3 minute long audio files that take about 1 minute to generate. So what I want is a system much like streaming audio from the internet, where I play the sound as I generate it. Pygame's mixer allows me to edit the sound as it's playing. But I cannot figure out how to change the sample rate, sample size, or number of channels. Snack allows me to edit sounds, as well as their sample rate, sample size, length, and number of channels. But I cannot figure out how to edit sounds as they are playing. Could anybody point me to a library that allows me to edit a sound as it is playing, as well as configure the number of channels, sample rate, and length (all known ahead of time)? If not, perhaps somebody knows of a tutorial to do this in C++? [EDIT] Pymedia.audio would work fine for me. However, I can't get it to work under Python 2.6. Any ideas?
[ "pymedia.audio does work with Python 2.6. Take a look at this SO post: Pymedia installation on Windows with Python 2.6\nYou can append audio to Output objects, as they are playing. So as each sample is generated, it can also be appended to the stream. The example in their documentation shows just how to do this: ht...
[ 0 ]
[]
[]
[ "audio", "audio_player", "c++", "python" ]
stackoverflow_0003895757_audio_audio_player_c++_python.txt
Q: what's wrong with the way I am splitting a string in python? I looked in my book and in the documentation, and did this: a = "hello" b = a.split(sep= ' ') print(b) I get an error saying split() takes no keyword arguments. What is wrong? I want to have ['h','e','l','l','o'] I tried not passing sep and just a.split(' '), and got ['hello'] A: Python allows a concept called "keyword arguments", where you tell it which parameter you're passing in the call to the function. However, the standard split() function does not take this kind of parameter. To split a string into a list of characters, use list(): >>> a = "hello" >>> list(a) ['h', 'e', 'l', 'l', 'o'] As an aside, an example of keyword parameters might be: def foo(bar, baz=0, quux=0): print "bar=", bar print "baz=", baz print "quux=", quux You can call this function in a few different ways: foo(1, 2, 3) foo(1, baz=2, quux=3) foo(1, quux=3, baz=2) Notice how you can change the order of keyword parameters. A: try just: a = "hello" b = a.split(' ') print(b) notice the difference: a.split(' ') instead of a.split(sep=' '). Even though the documentation names the argument "sep", that's really just for documentation purposes. It doesn't actually accept keyword arguments. In response to the OP's comment on this post: "a b c,d e".split(' ') seperates "a b c,d e" into an array of strings. Each ' ' that is found is treated as a seperator. So the seperated strings are ["a", "b", "c,d", "e"]. "hello".split(' ') splits "hello" everytime it see's a space, but there are no spaces in "hello" If you want an array of letters, use a list comprehension. [letter for letter in string], eg [letter for letter in "hello"], or just use the list constructor as in list("hello"). A: Given a string x, the Pythonic way to split it into individual characters is: for c in x: print c If you absolutely needed a list then redundant_list = list(x) I call the list redundant for a string split into a list of characters is less concise and often reflects C influenced patterns of string handling. A: Try: a = "hello" b = list(a)
what's wrong with the way I am splitting a string in python?
I looked in my book and in the documentation, and did this: a = "hello" b = a.split(sep= ' ') print(b) I get an error saying split() takes no keyword arguments. What is wrong? I want to have ['h','e','l','l','o'] I tried not passing sep and just a.split(' '), and got ['hello']
[ "Python allows a concept called \"keyword arguments\", where you tell it which parameter you're passing in the call to the function. However, the standard split() function does not take this kind of parameter.\nTo split a string into a list of characters, use list():\n>>> a = \"hello\"\n>>> list(a)\n['h', 'e', 'l',...
[ 6, 4, 2, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0003898882_python_split.txt
Q: What is this cProfile result telling me I need to fix? I would like to improve the performance of a Python script and have been using cProfile to generate a performance report: python -m cProfile -o chrX.prof ./bgchr.py ...args... I opened this chrX.prof file with Python's pstats and printed out the statistics: Python 2.7 (r27:82500, Oct 5 2010, 00:24:22) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pstats >>> p = pstats.Stats('chrX.prof') >>> p.sort_stats('name') >>> p.print_stats() Sun Oct 10 00:37:30 2010 chrX.prof 8760583 function calls in 13.780 CPU seconds Ordered by: function name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 {_locale.setlocale} 1 1.128 1.128 1.128 1.128 {bz2.decompress} 1 0.002 0.002 13.780 13.780 {execfile} 1750678 0.300 0.000 0.300 0.000 {len} 48 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'close' of 'file' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1750676 0.496 0.000 0.496 0.000 {method 'join' of 'str' objects} 1 0.007 0.007 0.007 0.007 {method 'read' of 'file' objects} 1 0.000 0.000 0.000 0.000 {method 'readlines' of 'file' objects} 1 0.034 0.034 0.034 0.034 {method 'rstrip' of 'str' objects} 23 0.000 0.000 0.000 0.000 {method 'seek' of 'file' objects} 1757785 1.230 0.000 1.230 0.000 {method 'split' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'startswith' of 'str' objects} 1750676 0.872 0.000 0.872 0.000 {method 'write' of 'file' objects} 1 0.007 0.007 13.778 13.778 ./bgchr:3(<module>) 1 0.000 0.000 13.780 13.780 <string>:1(<module>) 1 0.001 0.001 0.001 0.001 {open} 1 0.000 0.000 0.000 0.000 {sys.exit} 1 0.000 0.000 0.000 0.000 ./bgchr:36(checkCommandLineInputs) 1 0.000 0.000 0.000 0.000 ./bgchr:27(checkInstallation) 1 1.131 1.131 13.701 13.701 ./bgchr:97(extractData) 1 0.003 0.003 0.007 0.007 ./bgchr:55(extractMetadata) 1 0.064 0.064 13.771 13.771 ./bgchr:5(main) 1750677 8.504 0.000 11.196 0.000 ./bgchr:122(parseJarchLine) 1 0.000 0.000 0.000 0.000 ./bgchr:72(parseMetadata) 1 0.000 0.000 0.000 0.000 /home/areynolds/proj/tools/lib/python2.7/locale.py:517(setlocale) Question: What can I do about join, split and write operations to reduce the apparent impact they have on the performance of this script? If it is relevant, here is the full source code to the script in question: #!/usr/bin/env python import sys, os, time, bz2, locale def main(*args): # Constants global metadataRequiredFileSize metadataRequiredFileSize = 8192 requiredVersion = (2,5) # Prep global whichChromosome whichChromosome = "all" checkInstallation(requiredVersion) checkCommandLineInputs() extractMetadata() parseMetadata() if whichChromosome == "--list": listMetadata() sys.exit(0) # Extract extractData() return 0 def checkInstallation(rv): currentVersion = sys.version_info if currentVersion[0] == rv[0] and currentVersion[1] >= rv[1]: pass else: sys.stderr.write( "\n\t[%s] - Error: Your Python interpreter must be %d.%d or greater (within major version %d)\n" % (sys.argv[0], rv[0], rv[1], rv[0]) ) sys.exit(-1) return def checkCommandLineInputs(): cmdName = sys.argv[0] argvLength = len(sys.argv[1:]) if (argvLength == 0) or (argvLength > 2): sys.stderr.write( "\n\t[%s] - Usage: %s [<chromosome> | --list] <bjarch-file>\n\n" % (cmdName, cmdName) ) sys.exit(-1) else: global inFile global whichChromosome if argvLength == 1: inFile = sys.argv[1] elif argvLength == 2: whichChromosome = sys.argv[1] inFile = sys.argv[2] if inFile == "-" or inFile == "--list": sys.stderr.write( "\n\t[%s] - Usage: %s [<chromosome> | --list] <bjarch-file>\n\n" % (cmdName, cmdName) ) sys.exit(-1) return def extractMetadata(): global metadataList global dataHandle metadataList = [] dataHandle = open(inFile, 'rb') try: for data in dataHandle.readlines(metadataRequiredFileSize): metadataLine = data metadataLines = metadataLine.split('\n') for line in metadataLines: if line: metadataList.append(line) except IOError: sys.stderr.write( "\n\t[%s] - Error: Could not extract metadata from %s\n\n" % (sys.argv[0], inFile) ) sys.exit(-1) return def parseMetadata(): global metadataList global metadata metadata = [] if not metadataList: # equivalent to "if len(metadataList) > 0" sys.stderr.write( "\n\t[%s] - Error: No metadata in %s\n\n" % (sys.argv[0], inFile) ) sys.exit(-1) for entryText in metadataList: if entryText: # equivalent to "if len(entryText) > 0" entry = entryText.split('\t') filename = entry[0] chromosome = entry[0].split('.')[0] size = entry[1] entryDict = { 'chromosome':chromosome, 'filename':filename, 'size':size } metadata.append(entryDict) return def listMetadata(): for index in metadata: chromosome = index['chromosome'] filename = index['filename'] size = long(index['size']) sys.stdout.write( "%s\t%s\t%ld" % (chromosome, filename, size) ) return def extractData(): global dataHandle global pLength global lastEnd locale.setlocale(locale.LC_ALL, 'POSIX') dataHandle.seek(metadataRequiredFileSize, 0) # move cursor past metadata for index in metadata: chromosome = index['chromosome'] size = long(index['size']) pLength = 0L lastEnd = "" if whichChromosome == "all" or whichChromosome == index['chromosome']: dataStream = dataHandle.read(size) uncompressedData = bz2.decompress(dataStream) lines = uncompressedData.rstrip().split('\n') for line in lines: parseJarchLine(chromosome, line) if whichChromosome == chromosome: break else: dataHandle.seek(size, 1) # move cursor past chromosome chunk dataHandle.close() return def parseJarchLine(chromosome, line): global pLength global lastEnd elements = line.split('\t') if len(elements) > 1: if lastEnd: start = long(lastEnd) + long(elements[0]) lastEnd = long(start + pLength) sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, start, lastEnd, '\t'.join(elements[1:]))) else: lastEnd = long(elements[0]) + long(pLength) sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, long(elements[0]), lastEnd, '\t'.join(elements[1:]))) else: if elements[0].startswith('p'): pLength = long(elements[0][1:]) else: start = long(long(lastEnd) + long(elements[0])) lastEnd = long(start + pLength) sys.stdout.write("%s\t%ld\t%ld\n" % (chromosome, start, lastEnd)) return if __name__ == '__main__': sys.exit(main(*sys.argv)) EDIT If I comment out the sys.stdout.write statement in the first conditional of parseJarchLine(), then my runtime goes from 10.2 sec to 4.8 sec: # with first conditional's "sys.stdout.write" enabled $ time ./bgchr chrX test.bjarch > /dev/null real 0m10.186s user 0m9.917s sys 0m0.160s # after first conditional's "sys.stdout.write" is commented out $ time ./bgchr chrX test.bjarch > /dev/null real 0m4.808s user 0m4.561s sys 0m0.156s Is writing to stdout really that expensive in Python? A: ncalls is relevant only to the extent that comparing the numbers against other counts such as number of chars/fields/lines in a file may highligh anomalies; tottime and cumtime is what really matters. cumtime is the time spent in the function/method including the time spent in the functions/methods that it calls; tottime is the time spent in the function/method excluding the time spent in the functions/methods that it calls. I find it helpful to sort the stats on tottime and again on cumtime, not on name. bgchar definitely refers to the execution of the script and is not irrelevant as it takes up 8.9 seconds out of 13.5; that 8.9 seconds does NOT include time in the functions/methods that it calls! Read carefully what @Lie Ryan says about modularising your script into functions, and implement his advice. Likewise what @jonesy says. string is mentioned because you import string and use it in only one place: string.find(elements[0], 'p'). On another line in the output you'll notice that string.find was called only once, so it's not a performance problem in this run of this script. HOWEVER: You use str methods everywhere else. string functions are deprecated nowadays and are implemented by calling the corresponding str method. You would be better writing elements[0].find('p') == 0 for an exact but faster equivalent, and might like to use elements[0].startswith('p') which would save readers wondering whether that == 0 should actually be == -1. The four methods mentioned by @Bernd Petersohn take up only 3.7 seconds out of a total execution time of 13.541 seconds. Before worrying too much about those, modularise your script into functions, run cProfile again, and sort the stats by tottime. Update after question revised with changed script: """Question: What can I do about join, split and write operations to reduce the apparent impact they have on the performance of this script?"" Huh? Those 3 together take 2.6 seconds out of the total of 13.8. Your parseJarchLine function is taking 8.5 seconds (which doesn't include time taken by functions/methods that it calls. assert(8.5 > 2.6) Bernd has already pointed you at what you might consider doing with those. You are needlessly splitting the line completely only to join it up again when writing it out. You need to inspect only the first element. Instead of elements = line.split('\t') do elements = line.split('\t', 1) and replace '\t'.join(elements[1:]) by elements[1]. Now let's dive into the body of parseJarchLine. The number of uses in the source and manner of the uses of the long built-in function are astonishing. Also astonishing is the fact that long is not mentioned in the cProfile output. Why do you need long at all? Files over 2 Gb? OK, then you need to consider that since Python 2.2, int overflow causes promotion to long instead of raising an exception. You can take advantage of faster execution of int arithmetic. You also need to consider that doing long(x) when x is already demonstrably a long is a waste of resources. Here is the parseJarchLine function with removing-waste changes marked [1] and changing-to-int changes marked [2]. Good idea: make changes in small steps, re-test, re-profile. def parseJarchLine(chromosome, line): global pLength global lastEnd elements = line.split('\t') if len(elements) > 1: if lastEnd != "": start = long(lastEnd) + long(elements[0]) # [1] start = lastEnd + long(elements[0]) # [2] start = lastEnd + int(elements[0]) lastEnd = long(start + pLength) # [1] lastEnd = start + pLength sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, start, lastEnd, '\t'.join(elements[1:]))) else: lastEnd = long(elements[0]) + long(pLength) # [1] lastEnd = long(elements[0]) + pLength # [2] lastEnd = int(elements[0]) + pLength sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, long(elements[0]), lastEnd, '\t'.join(elements[1:]))) else: if elements[0].startswith('p'): pLength = long(elements[0][1:]) # [2] pLength = int(elements[0][1:]) else: start = long(long(lastEnd) + long(elements[0])) # [1] start = lastEnd + long(elements[0]) # [2] start = lastEnd + int(elements[0]) lastEnd = long(start + pLength) # [1] lastEnd = start + pLength sys.stdout.write("%s\t%ld\t%ld\n" % (chromosome, start, lastEnd)) return Update after question about sys.stdout.write If the statement that you commented out was anything like the original one: sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, start, lastEnd, '\t'.join(elements[1:]))) Then your question is ... interesting. Try this: payload = "%s\t%ld\t%ld\t%s\n" % (chromosome, start, lastEnd, '\t'.join(elements[1:])) sys.stdout.write(payload) Now comment out the sys.stdout.write statement ... By the way, someone mentioned in a comment about breaking this into more than one write ... have you considered this? How many bytes on average in elements[1:] ? In chromosome? === change of topic: It worries me that you initialise lastEnd to "" rather than to zero, and that nobody has commented on it. Any way, you should fix this, which allows a rather drastic simplification plus adding in others' suggestions: def parseJarchLine(chromosome, line): global pLength global lastEnd elements = line.split('\t', 1) if elements[0][0] == 'p': pLength = int(elements[0][1:]) return start = lastEnd + int(elements[0]) lastEnd = start + pLength sys.stdout.write("%s\t%ld\t%ld" % (chromosome, start, lastEnd)) if elements[1:]: sys.stdout.write(elements[1]) sys.stdout.write(\n) Now I'm similarly worried about the two global variables lastEnd and pLength -- the parseJarchLine function is now so small that it can be folded back into the body of its sole caller, extractData, which saves two global variables, and a gazillion function calls. You could also save a gazillion lookups of sys.stdout.write by putting write = sys.stdout.write once up the front of extractData and using that instead. BTW, the script tests for Python 2.5 or better; have you tried profiling on 2.5 and 2.6? A: This output is going to be more useful if your code is more modular as Lie Ryan has stated. However, a couple of things you can pick up from the output and just looking at the source code: You're doing a lot of comparisons that aren't actually necessary in Python. For example, instead of: if len(entryText) > 0: You can just write: if entryText: An empty list evaluates to False in Python. Same is true for an empty string, which you also test for in your code, and changing it would also make the code a bit shorter and more readable, so instead of this: for line in metadataLines: if line == '': break else: metadataList.append(line) You can just do: for line in metadataLines: if line: metadataList.append(line) There are several other issues with this code in terms of both organization and performance. You assign variables multiple times to the same thing instead of just creating an object instance once and doing all accesses on the object, for example. Doing this would reduce the number of assignments, and also the number of global variables. I don't want to sound overly critical, but this code doesn't appear to be written with performance in mind.
What is this cProfile result telling me I need to fix?
I would like to improve the performance of a Python script and have been using cProfile to generate a performance report: python -m cProfile -o chrX.prof ./bgchr.py ...args... I opened this chrX.prof file with Python's pstats and printed out the statistics: Python 2.7 (r27:82500, Oct 5 2010, 00:24:22) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pstats >>> p = pstats.Stats('chrX.prof') >>> p.sort_stats('name') >>> p.print_stats() Sun Oct 10 00:37:30 2010 chrX.prof 8760583 function calls in 13.780 CPU seconds Ordered by: function name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 {_locale.setlocale} 1 1.128 1.128 1.128 1.128 {bz2.decompress} 1 0.002 0.002 13.780 13.780 {execfile} 1750678 0.300 0.000 0.300 0.000 {len} 48 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'close' of 'file' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1750676 0.496 0.000 0.496 0.000 {method 'join' of 'str' objects} 1 0.007 0.007 0.007 0.007 {method 'read' of 'file' objects} 1 0.000 0.000 0.000 0.000 {method 'readlines' of 'file' objects} 1 0.034 0.034 0.034 0.034 {method 'rstrip' of 'str' objects} 23 0.000 0.000 0.000 0.000 {method 'seek' of 'file' objects} 1757785 1.230 0.000 1.230 0.000 {method 'split' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'startswith' of 'str' objects} 1750676 0.872 0.000 0.872 0.000 {method 'write' of 'file' objects} 1 0.007 0.007 13.778 13.778 ./bgchr:3(<module>) 1 0.000 0.000 13.780 13.780 <string>:1(<module>) 1 0.001 0.001 0.001 0.001 {open} 1 0.000 0.000 0.000 0.000 {sys.exit} 1 0.000 0.000 0.000 0.000 ./bgchr:36(checkCommandLineInputs) 1 0.000 0.000 0.000 0.000 ./bgchr:27(checkInstallation) 1 1.131 1.131 13.701 13.701 ./bgchr:97(extractData) 1 0.003 0.003 0.007 0.007 ./bgchr:55(extractMetadata) 1 0.064 0.064 13.771 13.771 ./bgchr:5(main) 1750677 8.504 0.000 11.196 0.000 ./bgchr:122(parseJarchLine) 1 0.000 0.000 0.000 0.000 ./bgchr:72(parseMetadata) 1 0.000 0.000 0.000 0.000 /home/areynolds/proj/tools/lib/python2.7/locale.py:517(setlocale) Question: What can I do about join, split and write operations to reduce the apparent impact they have on the performance of this script? If it is relevant, here is the full source code to the script in question: #!/usr/bin/env python import sys, os, time, bz2, locale def main(*args): # Constants global metadataRequiredFileSize metadataRequiredFileSize = 8192 requiredVersion = (2,5) # Prep global whichChromosome whichChromosome = "all" checkInstallation(requiredVersion) checkCommandLineInputs() extractMetadata() parseMetadata() if whichChromosome == "--list": listMetadata() sys.exit(0) # Extract extractData() return 0 def checkInstallation(rv): currentVersion = sys.version_info if currentVersion[0] == rv[0] and currentVersion[1] >= rv[1]: pass else: sys.stderr.write( "\n\t[%s] - Error: Your Python interpreter must be %d.%d or greater (within major version %d)\n" % (sys.argv[0], rv[0], rv[1], rv[0]) ) sys.exit(-1) return def checkCommandLineInputs(): cmdName = sys.argv[0] argvLength = len(sys.argv[1:]) if (argvLength == 0) or (argvLength > 2): sys.stderr.write( "\n\t[%s] - Usage: %s [<chromosome> | --list] <bjarch-file>\n\n" % (cmdName, cmdName) ) sys.exit(-1) else: global inFile global whichChromosome if argvLength == 1: inFile = sys.argv[1] elif argvLength == 2: whichChromosome = sys.argv[1] inFile = sys.argv[2] if inFile == "-" or inFile == "--list": sys.stderr.write( "\n\t[%s] - Usage: %s [<chromosome> | --list] <bjarch-file>\n\n" % (cmdName, cmdName) ) sys.exit(-1) return def extractMetadata(): global metadataList global dataHandle metadataList = [] dataHandle = open(inFile, 'rb') try: for data in dataHandle.readlines(metadataRequiredFileSize): metadataLine = data metadataLines = metadataLine.split('\n') for line in metadataLines: if line: metadataList.append(line) except IOError: sys.stderr.write( "\n\t[%s] - Error: Could not extract metadata from %s\n\n" % (sys.argv[0], inFile) ) sys.exit(-1) return def parseMetadata(): global metadataList global metadata metadata = [] if not metadataList: # equivalent to "if len(metadataList) > 0" sys.stderr.write( "\n\t[%s] - Error: No metadata in %s\n\n" % (sys.argv[0], inFile) ) sys.exit(-1) for entryText in metadataList: if entryText: # equivalent to "if len(entryText) > 0" entry = entryText.split('\t') filename = entry[0] chromosome = entry[0].split('.')[0] size = entry[1] entryDict = { 'chromosome':chromosome, 'filename':filename, 'size':size } metadata.append(entryDict) return def listMetadata(): for index in metadata: chromosome = index['chromosome'] filename = index['filename'] size = long(index['size']) sys.stdout.write( "%s\t%s\t%ld" % (chromosome, filename, size) ) return def extractData(): global dataHandle global pLength global lastEnd locale.setlocale(locale.LC_ALL, 'POSIX') dataHandle.seek(metadataRequiredFileSize, 0) # move cursor past metadata for index in metadata: chromosome = index['chromosome'] size = long(index['size']) pLength = 0L lastEnd = "" if whichChromosome == "all" or whichChromosome == index['chromosome']: dataStream = dataHandle.read(size) uncompressedData = bz2.decompress(dataStream) lines = uncompressedData.rstrip().split('\n') for line in lines: parseJarchLine(chromosome, line) if whichChromosome == chromosome: break else: dataHandle.seek(size, 1) # move cursor past chromosome chunk dataHandle.close() return def parseJarchLine(chromosome, line): global pLength global lastEnd elements = line.split('\t') if len(elements) > 1: if lastEnd: start = long(lastEnd) + long(elements[0]) lastEnd = long(start + pLength) sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, start, lastEnd, '\t'.join(elements[1:]))) else: lastEnd = long(elements[0]) + long(pLength) sys.stdout.write("%s\t%ld\t%ld\t%s\n" % (chromosome, long(elements[0]), lastEnd, '\t'.join(elements[1:]))) else: if elements[0].startswith('p'): pLength = long(elements[0][1:]) else: start = long(long(lastEnd) + long(elements[0])) lastEnd = long(start + pLength) sys.stdout.write("%s\t%ld\t%ld\n" % (chromosome, start, lastEnd)) return if __name__ == '__main__': sys.exit(main(*sys.argv)) EDIT If I comment out the sys.stdout.write statement in the first conditional of parseJarchLine(), then my runtime goes from 10.2 sec to 4.8 sec: # with first conditional's "sys.stdout.write" enabled $ time ./bgchr chrX test.bjarch > /dev/null real 0m10.186s user 0m9.917s sys 0m0.160s # after first conditional's "sys.stdout.write" is commented out $ time ./bgchr chrX test.bjarch > /dev/null real 0m4.808s user 0m4.561s sys 0m0.156s Is writing to stdout really that expensive in Python?
[ "ncalls is relevant only to the extent that comparing the numbers against other counts such as number of chars/fields/lines in a file may highligh anomalies; tottime and cumtime is what really matters. cumtime is the time spent in the function/method including the time spent in the functions/methods that it calls; ...
[ 29, 2 ]
[ "The entries relevant for possible optimization are those with high values for ncalls and tottime. bgchr:4(<module>) and <string>:1(<module>) probably refer to the execution of your module body and are not relevant here.\nObviously, your performance problem comes from string processing. This should perhaps be reduc...
[ -1 ]
[ "cprofile", "performance", "profile", "profiling", "python" ]
stackoverflow_0003898266_cprofile_performance_profile_profiling_python.txt
Q: How do I actually use WSGI? Suppose I have a function def app2(environ, start_response) If I know that a server implements WSGI, how can I tell the server to call app2 when it receives a HTTP request? app2 here is a function that takes a dictionary and returns a response (a WSGI application). A: Depends on the server. The WSGI-Spec says nothing about that. But mod_wsgi for example expects to find the WSGI-Applications under the name application in the specified module, but you can configure that with the WSGICallableObject configuration directive. A: If, as it sounds from your comment, your question is about Google App Engine, it provides a convenience function run_wsgi_app for running WSGI apps. So if your function is called app2, you would run def main(): run_wsgi_app(app2) For more, see http://code.google.com/appengine/docs/python/tools/webapp/utilmodule.html#run_wsgi_app
How do I actually use WSGI?
Suppose I have a function def app2(environ, start_response) If I know that a server implements WSGI, how can I tell the server to call app2 when it receives a HTTP request? app2 here is a function that takes a dictionary and returns a response (a WSGI application).
[ "Depends on the server. The WSGI-Spec says nothing about that. But mod_wsgi for example expects to find the WSGI-Applications under the name application in the specified module, but you can configure that with the WSGICallableObject configuration directive.\n", "If, as it sounds from your comment, your question i...
[ 0, 0 ]
[]
[]
[ "http", "python", "wsgi" ]
stackoverflow_0003898229_http_python_wsgi.txt
Q: Google App Engine Example Modified I took an official example of Google App Engine, that creates a Shoppinglist, and modified it so it would: Create two tables (contact and Phonenumber) instead of one Shoppinglist. This is to understand how google deals with two tables and the Foreignkey (see code below). It displays everything until line 47: data = PhoneNumber(data=self.request.POST) data2 = Contact(data2=self.request.POST) Somehow it cant deal with the second "data2" object and gives me and error: TypeError: init() got an unexpected keyword argument 'data2' Why? What can I do to make it work? Thanks for the time. import cgi from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.db import djangoforms class Contact(db.Model): name = db.StringProperty() birth_day = db.DateProperty() address = db.PostalAddressProperty() class PhoneNumber(db.Model): contact = db.ReferenceProperty(Contact, collection_name='phone_numbers') phone_type = db.StringProperty( choices=('home', 'work', 'fax', 'mobile', 'other')) number = db.PhoneNumberProperty() class PhoneNumberForm(djangoforms.ModelForm): class Meta: model = PhoneNumber class ContactForm(djangoforms.ModelForm): class Meta: model = Contact class MainPage(webapp.RequestHandler): def get(self): self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') # This generates our PhoneNumber, Contact list form and writes it in the response self.response.out.write(PhoneNumberForm()) self.response.out.write(ContactForm()) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') def post(self): #print self.request #print self.request.POST data = PhoneNumber(data=self.request.POST) data2 = Contact(data2=self.request.POST) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') if data2.is_valid(): # Save the data, and redirect to the view page entity = data2.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write(data2) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') class ItemPage(webapp.RequestHandler): def get(self): query = db.GqlQuery("SELECT * FROM PhoneNumber ORDER BY name") for item in query: self.response.out.write('<a href="/edit?id=%d">Edit</a> - ' % item.key().id()) self.response.out.write("%s - Need to buy %d, cost $%0.2f each<br>" % (item.name, item.quantity, item.target_price)) class EditPage(webapp.RequestHandler): def get(self): id = int(self.request.get('id')) item = Item.get(db.Key.from_path('Item', id)) self.response.out.write('<html><body>' '<form method="POST" ' 'action="/edit">' '<table>') self.response.out.write(PhoneNumberForm(instance=PhoneNumber)) self.response.out.write(ContactForm(instance=Contact)) self.response.out.write('</table>' '<input type="hidden" name="_id" value="%s">' '<input type="submit">' '</form></body></html>' % id) def post(self): id = int(self.request.get('_id')) PhoneNumber = PhoneNumber.get(db.Key.from_path('PhoneNumber', id)) Contact = Contact.get(db.Key.from_path('Contact', id)) data = PhoneNumberForm(data=self.request.POST) data2 = ContactForm(data2=self.request.POST) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') if data2.is_valid(): # Save the data, and redirect to the view page entity = data2.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write(data2) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') def main(): application = webapp.WSGIApplication( [('/', MainPage), ('/edit', EditPage), ('/items.html', ItemPage), ], debug=True) run_wsgi_app(application) if __name__=="__main__": main() A: I haven't used Django forms, but my guess would be something like this: def post(self): #print self.request #print self.request.POST data = PhoneNumberForm(data=self.request.POST) data2 = ContactForm(data=self.request.POST) if data.is_valid() and data2.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() entity = data2.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write(data2) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') It is the form classes not the model classes which you need to create from self.request.POST. These have an argument called data, not data2. A: You could actually simplify your code a bit. class Contact(db.Model): name = db.StringProperty() birth_day = db.DateProperty() address = db.PostalAddressProperty() added_by = db.UserProperty(auto_current_user_add=True) class PhoneNumber(db.Model): contact = db.ReferenceProperty(Contact, collection_name='phone_numbers') phone_type = db.StringProperty( choices=('home', 'work', 'fax', 'mobile', 'other')) number = db.PhoneNumberProperty() added_by = db.UserProperty(auto_current_user_add=True) You don't need to add the current user in the form's save method, you can have appengine do it automatically. In your def post(self): function, you shouldn't be instantiating the form with a data2 argument, that's invalid. I generally do something like this: def post(self): form1 = PhoneNumberForm(self.request.POST or None) form2 = Contact(self.request.POST or None) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() else: # re-display page.... There are two spots in your question where you are incorrectly passing 'data2' to the form's constructor (MainPage class and EditPage class), be sure to correct them both. A: This seemed to work for me. Changed data = PhoneNumber(data=self.request.POST) data2 = Contact(data=self.request.POST) To data = PhoneNumberForm(data=self.request.POST) data2 = ContactForm(data=self.request.POST) def post(self): #print self.request #print self.request.POST data = PhoneNumberForm(data=self.request.POST) data2 = ContactForm(data=self.request.POST) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') if data2.is_valid(): # Save the data, and redirect to the view page entity = data2.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write(data2) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>')
Google App Engine Example Modified
I took an official example of Google App Engine, that creates a Shoppinglist, and modified it so it would: Create two tables (contact and Phonenumber) instead of one Shoppinglist. This is to understand how google deals with two tables and the Foreignkey (see code below). It displays everything until line 47: data = PhoneNumber(data=self.request.POST) data2 = Contact(data2=self.request.POST) Somehow it cant deal with the second "data2" object and gives me and error: TypeError: init() got an unexpected keyword argument 'data2' Why? What can I do to make it work? Thanks for the time. import cgi from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext.db import djangoforms class Contact(db.Model): name = db.StringProperty() birth_day = db.DateProperty() address = db.PostalAddressProperty() class PhoneNumber(db.Model): contact = db.ReferenceProperty(Contact, collection_name='phone_numbers') phone_type = db.StringProperty( choices=('home', 'work', 'fax', 'mobile', 'other')) number = db.PhoneNumberProperty() class PhoneNumberForm(djangoforms.ModelForm): class Meta: model = PhoneNumber class ContactForm(djangoforms.ModelForm): class Meta: model = Contact class MainPage(webapp.RequestHandler): def get(self): self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') # This generates our PhoneNumber, Contact list form and writes it in the response self.response.out.write(PhoneNumberForm()) self.response.out.write(ContactForm()) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') def post(self): #print self.request #print self.request.POST data = PhoneNumber(data=self.request.POST) data2 = Contact(data2=self.request.POST) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') if data2.is_valid(): # Save the data, and redirect to the view page entity = data2.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write(data2) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') class ItemPage(webapp.RequestHandler): def get(self): query = db.GqlQuery("SELECT * FROM PhoneNumber ORDER BY name") for item in query: self.response.out.write('<a href="/edit?id=%d">Edit</a> - ' % item.key().id()) self.response.out.write("%s - Need to buy %d, cost $%0.2f each<br>" % (item.name, item.quantity, item.target_price)) class EditPage(webapp.RequestHandler): def get(self): id = int(self.request.get('id')) item = Item.get(db.Key.from_path('Item', id)) self.response.out.write('<html><body>' '<form method="POST" ' 'action="/edit">' '<table>') self.response.out.write(PhoneNumberForm(instance=PhoneNumber)) self.response.out.write(ContactForm(instance=Contact)) self.response.out.write('</table>' '<input type="hidden" name="_id" value="%s">' '<input type="submit">' '</form></body></html>' % id) def post(self): id = int(self.request.get('_id')) PhoneNumber = PhoneNumber.get(db.Key.from_path('PhoneNumber', id)) Contact = Contact.get(db.Key.from_path('Contact', id)) data = PhoneNumberForm(data=self.request.POST) data2 = ContactForm(data2=self.request.POST) if data.is_valid(): # Save the data, and redirect to the view page entity = data.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') if data2.is_valid(): # Save the data, and redirect to the view page entity = data2.save(commit=False) entity.added_by = users.get_current_user() entity.put() self.redirect('/items.html') else: # Reprint the form self.response.out.write('<html><body>' '<form method="POST" ' 'action="/">' '<table>') self.response.out.write(data) self.response.out.write(data2) self.response.out.write('</table>' '<input type="submit">' '</form></body></html>') def main(): application = webapp.WSGIApplication( [('/', MainPage), ('/edit', EditPage), ('/items.html', ItemPage), ], debug=True) run_wsgi_app(application) if __name__=="__main__": main()
[ "I haven't used Django forms, but my guess would be something like this:\ndef post(self): \n #print self.request \n #print self.request.POST \n data = PhoneNumberForm(data=self.request.POST) \n data2 = ContactForm(data=self.request.POST) \n if data.is_valid() and data2.is_valid(): \n # Save th...
[ 1, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003656357_google_app_engine_python.txt
Q: How to accelerate reads from batches of files I read many files from my system. I want to read them faster, maybe like this: results=[] for file in open("filenames.txt").readlines(): results.append(open(file,"r").read()) I don't want to use threading. Any advice is appreciated. the reason why i don't want to use threads is because it will make my code unreadable,i want to find so tricky way to make speed faster and code lesser,unstander easier yesterday i have test another solution with multi-processing,it works bad,i don't know why, here is the code as follows: def xml2db(file): s=pq(open(file,"r").read()) dict={} for field in g_fields: dict[field]=s("field[@name='%s']"%field).text() p=Product() for k,v in dict.iteritems(): if v is None or v.strip()=="": pass else: if hasattr(p,k): setattr(p,k,v) session.commit() @cost_time @statistics_db def batch_xml2db(): from multiprocessing import Pool,Queue p=Pool(5) #q=Queue() files=glob.glob(g_filter) #for file in files: # q.put(file) def P(): while q.qsize()<>0: xml2db(q.get()) p.map(xml2db,files) p.join() A: results = [open(f.strip()).read() for f in open("filenames.txt").readlines()] This may be insignificantly faster, but it's probably less readable (depending on the reader's familiarity with list comprehensions). Your main problem here is that your bottleneck is disk IO - buying a faster disk will make much more of a difference than modifying your code. A: Well, if you want to improve performance then improve the algorithm, right? What are you doing with all this data? Do you really need it all in memory at the same time, potentially causing OOM if filenames.txt specifies too many or too large of files? If you're doing this with lots of files I suspect you are thrashing, hence your 700s+ (1 hour+) time. Even my poor little HD can sustain 42 MB/s writes (42 * 714s = 30GB). Take that grain of salt knowing you must read and write, but I'm guessing you don't have over 8 GB of RAM available for this application. A related SO question/answer suggested you use mmap, and the answer above that suggested an iterative/lazy read like what you get in Haskell for free. These are probably worth considering if you really do have tens of gigabytes to munge. A: Is this a one-off requirement or something that you need to do regularly? If it's something you're going to be doing often, consider using MySQL or another database instead of a file system. A: Not sure if this is still the code you are using. A couple adjustments I would consider making. Original: def xml2db(file): s=pq(open(file,"r").read()) dict={} for field in g_fields: dict[field]=s("field[@name='%s']"%field).text() p=Product() for k,v in dict.iteritems(): if v is None or v.strip()=="": pass else: if hasattr(p,k): setattr(p,k,v) session.commit() Updated: remove the use of the dict, it is extra object creation, iteration and collection. def xml2db(file): s=pq(open(file,"r").read()) p=Product() for k in g_fields: v=s("field[@name='%s']"%field).text() if v is None or v.strip()=="": pass else: if hasattr(p,k): setattr(p,k,v) session.commit() You could profile the code using the python profiler. This might tell you where the time being spent is. It may be in session.Commit() this may need to be reduced to every couple of files. I have no idea what it does so that is really a stab in the dark, you may try and run it without sending or writing any output. If you can separate your code into Reading, Processing and Writing. A) You can see how long it takes to read all the files. Then by loading a single file into memory process it enough time to represent the entire job without extra reading IO. B) Processing cost Then save a whole bunch of sessions representative of your job size. C) Output cost Test the cost of each stage individually. This should show you what is taking the most time and if any improvement can be made in any area.
How to accelerate reads from batches of files
I read many files from my system. I want to read them faster, maybe like this: results=[] for file in open("filenames.txt").readlines(): results.append(open(file,"r").read()) I don't want to use threading. Any advice is appreciated. the reason why i don't want to use threads is because it will make my code unreadable,i want to find so tricky way to make speed faster and code lesser,unstander easier yesterday i have test another solution with multi-processing,it works bad,i don't know why, here is the code as follows: def xml2db(file): s=pq(open(file,"r").read()) dict={} for field in g_fields: dict[field]=s("field[@name='%s']"%field).text() p=Product() for k,v in dict.iteritems(): if v is None or v.strip()=="": pass else: if hasattr(p,k): setattr(p,k,v) session.commit() @cost_time @statistics_db def batch_xml2db(): from multiprocessing import Pool,Queue p=Pool(5) #q=Queue() files=glob.glob(g_filter) #for file in files: # q.put(file) def P(): while q.qsize()<>0: xml2db(q.get()) p.map(xml2db,files) p.join()
[ "results = [open(f.strip()).read() for f in open(\"filenames.txt\").readlines()]\n\nThis may be insignificantly faster, but it's probably less readable (depending on the reader's familiarity with list comprehensions).\nYour main problem here is that your bottleneck is disk IO - buying a faster disk will make much m...
[ 1, 0, 0, 0 ]
[]
[]
[ "concurrency", "file", "io", "performance", "python" ]
stackoverflow_0003869357_concurrency_file_io_performance_python.txt
Q: How do I set the timeout of a SocketServer in Python? I want to use server.get_request() to receive requests, but I want it to timeout after 500 milliseconds. Is this correct? Doesn't seem to work... thanks. class UDPServer(SocketServer.BaseRequestHandler): timeout = .500 if __name__ == "__main__": server = SocketServer.UDPServer(('localhost', '12345'), UDPServer) server.get_request() A: I feel there are some places wrong: The class derived from SocketServer.BaseRequestHandler should be MyUDPServerHandler or something else, but should not be UDPServer which is a built-in class in SocketServer It should be server = SocketServer.UDPServer(('localhost', '12345'), MyUDPServerhandler) Then maybe it should be server.timeout = .500. And define a handle_timeout() method
How do I set the timeout of a SocketServer in Python?
I want to use server.get_request() to receive requests, but I want it to timeout after 500 milliseconds. Is this correct? Doesn't seem to work... thanks. class UDPServer(SocketServer.BaseRequestHandler): timeout = .500 if __name__ == "__main__": server = SocketServer.UDPServer(('localhost', '12345'), UDPServer) server.get_request()
[ "I feel there are some places wrong:\n\nThe class derived from SocketServer.BaseRequestHandler should be MyUDPServerHandler or something else, but should not be UDPServer which is a built-in class in SocketServer\nIt should be server = SocketServer.UDPServer(('localhost', '12345'), MyUDPServerhandler)\nThen maybe i...
[ 3 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0003899200_python_sockets_udp.txt
Q: Does python's fcntl.flock function provide thread level locking of file access? Python's fcnt module provides a method called [flock][1] to proved file locking. It's description reads: Perform the lock operation op on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated using fcntl().) Looking up the linux man page for flock, it only refers to cross process locking, for example: A call to flock() may block if an incompatible lock is held by another process. To make a non-blocking request, include LOCK_NB (by ORing) with any of the above operations. So my question is: will flock() also provide thread safe locking and lock multiple threads within the same process as well as threads from different processes? [1]: http://docs.python.org/library/fcntl.html#fcntl.flockfunction is emulated using fcntl().) A: flock locks don't care about threads--in fact, they don't care about processes, either. If you take the same file descriptor in two processes (inherited through a fork), either process locking the file with that FD will acquire a lock for both processes. In other words, in the following code both flock calls will return success: the child process locks the file, and then the parent process acquires the same lock rather than blocking, because they're both the same FD. import fcntl, time, os f = open("testfile", "w+") print "Locking..." fcntl.flock(f.fileno(), fcntl.LOCK_EX) print "locked" fcntl.flock(f.fileno(), fcntl.LOCK_UN) if os.fork() == 0: # We're in the child process, and we have an inherited copy of the fd. # Lock the file. print "Child process locking..." fcntl.flock(f.fileno(), fcntl.LOCK_EX) print "Child process locked..." time.sleep(1000) else: # We're in the parent. Give the child process a moment to lock the file. time.sleep(0.5) print "Parent process locking..." fcntl.flock(f.fileno(), fcntl.LOCK_EX) print "Parent process locked" time.sleep(1000) On the same token, if you lock the same file twice, but with different file descriptors, the locks will block each other--regardless of whether you're in the same process or the same thread. See flock(2): If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated independently by flock(). An attempt to lock the file using one of these file descriptors may be denied by a lock that the calling process has already placed via another descriptor. It's useful to remember that to the Linux kernel, processes and threads are essentially the same thing, and they're generally treated the same by kernel-level APIs. For the most part, if a syscall documents interprocess child/parent behavior, the same will hold for threads. Of course, you can (and probably should) test this behavior yourself.
Does python's fcntl.flock function provide thread level locking of file access?
Python's fcnt module provides a method called [flock][1] to proved file locking. It's description reads: Perform the lock operation op on file descriptor fd (file objects providing a fileno() method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated using fcntl().) Looking up the linux man page for flock, it only refers to cross process locking, for example: A call to flock() may block if an incompatible lock is held by another process. To make a non-blocking request, include LOCK_NB (by ORing) with any of the above operations. So my question is: will flock() also provide thread safe locking and lock multiple threads within the same process as well as threads from different processes? [1]: http://docs.python.org/library/fcntl.html#fcntl.flockfunction is emulated using fcntl().)
[ "flock locks don't care about threads--in fact, they don't care about processes, either. If you take the same file descriptor in two processes (inherited through a fork), either process locking the file with that FD will acquire a lock for both processes. In other words, in the following code both flock calls wil...
[ 5 ]
[]
[]
[ "flock", "linux", "locking", "multithreading", "python" ]
stackoverflow_0003899435_flock_linux_locking_multithreading_python.txt
Q: Finding length of items from a list I have two list in a python list1=['12aa','2a','c2'] list2=['2ac','c2a','1ac'] First- Finding combinations of each two item from list1. Second- Finding combinations of each two item from list2. Third- Finding combinations of each two items from list1 and list2 Fourth- Calculating each combinations total length Advice and help in Python is appreciated. Thank you A: import itertools as it list1=['12aa','2a','c2'] list2=['2ac','c2a','1ac'] # First- Finding combinations of each two item from list1. first = list(it.combinations(list1, 2)) # Second- Finding combinations of each two item from list2. second = list(it.combinations(list2, 2)) # Third- Finding combinations of each two items from list1 and list2 third = list(it.product(list1, list2)) # Fourth- Calculating each combinations total length for combination in first: # first, second, third print combination, len(''.join(combination))
Finding length of items from a list
I have two list in a python list1=['12aa','2a','c2'] list2=['2ac','c2a','1ac'] First- Finding combinations of each two item from list1. Second- Finding combinations of each two item from list2. Third- Finding combinations of each two items from list1 and list2 Fourth- Calculating each combinations total length Advice and help in Python is appreciated. Thank you
[ "import itertools as it\n\nlist1=['12aa','2a','c2']\nlist2=['2ac','c2a','1ac']\n\n# First- Finding combinations of each two item from list1.\nfirst = list(it.combinations(list1, 2))\n\n# Second- Finding combinations of each two item from list2.\nsecond = list(it.combinations(list2, 2))\n\n# Third- Finding combinati...
[ 3 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0003899593_arrays_python.txt
Q: Convert SHA Hash Computation in Python to C# Can someone please help me convert the following two lines of python to C#. hash = hmac.new(secret, data, digestmod = hashlib.sha1) key = hash.hexdigest()[:8] The rest looks like this if you're intersted: #!/usr/bin/env python import hmac import hashlib secret = 'mySecret' data = 'myData' hash = hmac.new(secret, data, digestmod = hashlib.sha1) key = hash.hexdigest()[:8] print key Thanks A: You could use the HMACSHA1 class to compute the hash: class Program { static void Main() { var secret = "secret"; var data = "data"; var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data)); Console.WriteLine(BitConverter.ToString(hash)); } }
Convert SHA Hash Computation in Python to C#
Can someone please help me convert the following two lines of python to C#. hash = hmac.new(secret, data, digestmod = hashlib.sha1) key = hash.hexdigest()[:8] The rest looks like this if you're intersted: #!/usr/bin/env python import hmac import hashlib secret = 'mySecret' data = 'myData' hash = hmac.new(secret, data, digestmod = hashlib.sha1) key = hash.hexdigest()[:8] print key Thanks
[ "You could use the HMACSHA1 class to compute the hash:\nclass Program\n{\n static void Main()\n {\n var secret = \"secret\";\n var data = \"data\";\n var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));\n var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));\n Conso...
[ 7 ]
[]
[]
[ "c#", "hash", "python", "sha1" ]
stackoverflow_0003899644_c#_hash_python_sha1.txt
Q: How google docs shows my .PPT files without using a flash viewer? I want to show .ppt (PowerPoint) files uploaded by my user on my website. I could do this by converting them into Flash files, then showing the Flash files on the web page. But I don't want to use Flash to do this. I want to show it, like google docs shows, without using Flash. I've already solved the problem for .pdf files by converting them into images using ImageMagick, but now I have trouble with .ppt files. A: I would maybe try using google docs API to first upload a ppt presentation and then download it back in a different format. I think it should be possible though I have not tested it. A: You can embed Google docs presentations in your site. A: Now i found a solution to showing .ppt file on my website without using the flash the solution is: just convert the .ppt file to .pdf files using any language or using software(e.g. open office) and then use Imagemagick to convert that .pdf into image and show to your web page once again thanks to you all for answering my question.
How google docs shows my .PPT files without using a flash viewer?
I want to show .ppt (PowerPoint) files uploaded by my user on my website. I could do this by converting them into Flash files, then showing the Flash files on the web page. But I don't want to use Flash to do this. I want to show it, like google docs shows, without using Flash. I've already solved the problem for .pdf files by converting them into images using ImageMagick, but now I have trouble with .ppt files.
[ "I would maybe try using google docs API to first upload a ppt presentation and then download it back in a different format. I think it should be possible though I have not tested it. \n", "You can embed Google docs presentations in your site.\n", "Now i found a solution to showing .ppt file on my website witho...
[ 1, 1, 0 ]
[]
[]
[ "c++", "google_docs", "java", "powerpoint", "python" ]
stackoverflow_0003882249_c++_google_docs_java_powerpoint_python.txt
Q: Emulate javascript _dopostback in python, web scraping Here LINK it is suggested that it is possible to "Figure out what the JavaScript is doing and emulate it in your Python code: " This is what I would like help doing ie my question. How do I emulate javascript:__doPostBack ? Code from a website (full page source here LINK: <a style="color: Black;" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$gvSearchResults','Page$2')">2</a> Of course I have basically know idea where to go from here. Thanks in advance for your help and ideas Ok there are lots of posts asking how to CLICK a javascript button when web scraping with python libraries mechanize, beautifulsoup....,similar. I see a lot of "that is not supported" responses use THIS non python solution. I think a python solution to this problem would be of great benefit to many. In that light I am not looking for answers like use x,y or z which are not python code or require interacting with a browser. A: The mechanize page is not suggesting that you can emulate JavaScript in Python. It is saying that you can change a hidden field in a form, thus tricking the web server that a human1 has selected the field. You still need to analyse the target yourself. There will be no Python-based solution to this problem, unless you wish to create a JavaScript interpreter in Python. My thoughts on this problem have led me to three possible solutions: create an XULRunner application browser automation attempt to interpret the client-side code Of those three, I've only really seen discussion of 2. I've seen something close to 1 in a commercial scraping application, where you basically create scripts by browsing on sites and selecting things on the pages that you would like the script to extract in the future. 1 could possibly made to work with a Python script by accepting a serialisation (JSON ?) of wsgi Request objects, getting the app to fetch the URL, then sending the processed page as a wsgi Response object. You could possibly wrap some middleware around urllib2 to achieve this. Overkill probably, but kind of fun to think about. 2 is usually achieved via Selenium RC (Remote Control), a testing-centric tool. It provides a few methods like getHtmlSource but most people that I've heard using it get don't like its API. 3 I have no idea about. node.js is very hot right now, but I haven't touched it. I've never been able to build spidermonkey on my Ubuntu machine, so I haven't touched that either. My hunch is that in order to do this, you would provide the HTML source and your details to a JS interpreter, that would need to fake being your User-Agent etc in case the JavaScript wanted to reconnect with the server. 1 well, more technically, a JavaScript compliant User-Agent, which is almost always a web browser used by a human
Emulate javascript _dopostback in python, web scraping
Here LINK it is suggested that it is possible to "Figure out what the JavaScript is doing and emulate it in your Python code: " This is what I would like help doing ie my question. How do I emulate javascript:__doPostBack ? Code from a website (full page source here LINK: <a style="color: Black;" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$gvSearchResults','Page$2')">2</a> Of course I have basically know idea where to go from here. Thanks in advance for your help and ideas Ok there are lots of posts asking how to CLICK a javascript button when web scraping with python libraries mechanize, beautifulsoup....,similar. I see a lot of "that is not supported" responses use THIS non python solution. I think a python solution to this problem would be of great benefit to many. In that light I am not looking for answers like use x,y or z which are not python code or require interacting with a browser.
[ "The mechanize page is not suggesting that you can emulate JavaScript in Python. It is saying that you can change a hidden field in a form, thus tricking the web server that a human1 has selected the field. You still need to analyse the target yourself. \nThere will be no Python-based solution to this problem, unle...
[ 3 ]
[]
[]
[ "dopostback", "javascript", "mechanize", "python", "web_scraping" ]
stackoverflow_0003898660_dopostback_javascript_mechanize_python_web_scraping.txt
Q: How to save and load QListWidjet contents to/from QSetting with PyQt4? I've got a QListWidget in my PyQt4 app. It contains folders paths. I want to save its contents to QSettings and load them later. I used this code to do this: def foldersSave(self): folders = {} '''create dict to store data''' foldersnum = self.configDialog.FolderLIST.count() '''get number of items''' if foldersnum: for i in range(foldersnum): folders[i] = self.configDialog.FolderLIST.item(i).text() '''save items text to dict''' return str(folders) '''return string of folders to store in QSettings''' return None But if I make so folders paths are stored in config file like: musicfolders={0: PyQt4.QtCore.QString(u'/home/sam/Ubuntu One')} So I have no idea how to load them then. I've tryed something like this in different variants: def foldersLoad(self): folders = eval(self.tunSettings.value('musicfolders').toString()) It returns error: TypeError: eval() arg 1 must be a string or code object It looks like I just need to save data some other way then I do now. Gooled a lot, but have no clue. I'm sure the answer is trivial, but I'm stuck. A: The solution is very simply. I were to use QStringList. def foldersSave(self): folders = QtCore.QStringList() foldersnum = self.configDialog.FolderLIST.count() if foldersnum: for i in range(foldersnum): print (i, " position is saved: ", self.configDialog.FolderLIST.item(i).text()) folders.append(self.configDialog.FolderLIST.item(i).text()) return folders return None and load def foldersLoad(self): folders = QtCore.QStringList() folders = self.tunSettings.value('musicfolders', None).toStringList() if folders.count(): foldersnum = folders.count() for i in range(foldersnum): self.configDialog.FolderLIST.addItem(folders.takeFirst())
How to save and load QListWidjet contents to/from QSetting with PyQt4?
I've got a QListWidget in my PyQt4 app. It contains folders paths. I want to save its contents to QSettings and load them later. I used this code to do this: def foldersSave(self): folders = {} '''create dict to store data''' foldersnum = self.configDialog.FolderLIST.count() '''get number of items''' if foldersnum: for i in range(foldersnum): folders[i] = self.configDialog.FolderLIST.item(i).text() '''save items text to dict''' return str(folders) '''return string of folders to store in QSettings''' return None But if I make so folders paths are stored in config file like: musicfolders={0: PyQt4.QtCore.QString(u'/home/sam/Ubuntu One')} So I have no idea how to load them then. I've tryed something like this in different variants: def foldersLoad(self): folders = eval(self.tunSettings.value('musicfolders').toString()) It returns error: TypeError: eval() arg 1 must be a string or code object It looks like I just need to save data some other way then I do now. Gooled a lot, but have no clue. I'm sure the answer is trivial, but I'm stuck.
[ "The solution is very simply. I were to use QStringList.\ndef foldersSave(self):\n folders = QtCore.QStringList()\n foldersnum = self.configDialog.FolderLIST.count()\n if foldersnum:\n for i in range(foldersnum):\n print (i, \" position is saved: \", self.configDialog.FolderLIST.item(i).t...
[ 0 ]
[]
[]
[ "pyqt4", "python", "qlistwidget", "qt4" ]
stackoverflow_0003870081_pyqt4_python_qlistwidget_qt4.txt
Q: How do I close a Python 2.5.2 Popen subprocess once I have the data I need? I am running the following version of Python: $ /usr/bin/env python --version Python 2.5.2 I am running the following Python code to write data from a child subprocess to standard output, and reading that into a Python variable called metadata: # Extract metadata (snippet from extractMetadata.py) inFileAsGzip = "%s.gz" % inFile if os.path.exists(inFileAsGzip): os.remove(inFileAsGzip) os.symlink(inFile, inFileAsGzip) extractMetadataCommand = "bgzip -c -d -b 0 -s %s %s" % (metadataRequiredFileSize, inFileAsGzip) metadataPipes = subprocess.Popen(extractMetadataCommand, stdin=None, stdout=subprocess.PIPE, shell=True, close_fds=True) metadata = metadataPipes.communicate()[0] metadataPipes.stdout.close() os.remove(inFileAsGzip) print metadata The use case is as follows, to pull the first ten lines of standard output from the aforementioned code snippet: $ extractMetadata.py | head The error will appear if I pipe into head, awk, grep, etc. The script ends with the following error: close failed: [Errno 32] Broken pipe I would have thought closing the pipes would be sufficient, but obviously that's not the case. A: Hmmm. I've seen some "Broken pipe" strangeness with subprocess + gzip before. I never did figure out exactly why it was happening but by changing my implementation approach, I was able to avoid the problem. It looks like you're just trying to use a backend gzip process to decompress a file (probably because Python's builtin module is horrendously slow... no idea why but it definitely is). Rather than using communicate() you can, instead, treat the process as a fully asynchronous backend and just read it's output as it arrives. When the process dies, the subprocess module will take care of cleaning things up for you. The following snippit should provide the same basic functionality without any broken pipe issues. import subprocess gz_proc = subprocess.Popen(['gzip', '-c', '-d', 'test.gz'], stdout=subprocess.PIPE) l = list() while True: dat = gz_proc.stdout.read(4096) if not d: break l.append(d) file_data = ''.join(l) A: I think this exception has nothing to do with the subprocess call nor its file descriptors (after calling communicate the popen object is closed). This seems to be the classic problem of closing sys.stdout in a pipe: http://bugs.python.org/issue1596 Despite being a 3-year old bug it has not been solved. Since sys.stdout.write(...) does not seem to help either, you may resort to a lower-level call, try this out: os.write(sys.stdout.fileno(), metadata) A: There's not enough information to answer this conclusively, but I can make some educated guesses. First, os.remove should definitely not be failing with EPIPE. It doesn't look like it is, either; the error is close failed: [Errno 32] Broken pipe, not remove failed. It looks like close is failing, not remove. It's possible for closing a pipe's stdout to give this error. If data is buffered, Python will flush the data before closing the file. If the underlying process is gone, doing this will raise IOError/EPIPE. However, note that this isn't a fatal error: even when this happens, the file is still closed. The following code reproduces this about 50% of the time, and demonstrates that the file is closed after the exception. (Watch out; I think the behavior of bufsize has changed across versions.) import os, subprocess metadataPipes = subprocess.Popen("echo test", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, close_fds=True, bufsize=4096) metadataPipes.stdin.write("blah"*1000) print metadataPipes.stdin try: metadataPipes.stdin.close() except IOError, e: print "stdin after failure: %s" % metadataPipes.stdin This is racy; it only happens part of the time. That may explain why it looked like removing or adding the os.remove call affects the error. That said, I can't see how this would happen with the code you've provided, since you don't write to stdin. It's the closest I can get without a usable repro, though, and maybe it'll point you in the right direction. As a side note, you shouldn't check os.path.exists before deleting a file that may not exist; it'll cause race conditions if another process deletes the file at the same time. Instead, do this: try: os.remove(inFileAsGzip) except OSError, e: if e.errno != errno.ENOENT: raise ... which I usually wrap in a function like rm_f. Finally, if you explicitly want to kill a subprocess, there's metadataPipes.kill--just closing its pipes won't do that--but that doesn't help explain the error. Also, again, if you're just reading gzip files you're much better off with the gzip module than a subprocess. http://docs.python.org/library/gzip.html A: Getting the first 10 lines from a process output might work better this way: ph = os.popen(cmdline, 'r') lines = [] for s in ph: lines.append(s.rstrip()) if len(lines) == 10: break print '\n'.join(lines) ph.close()
How do I close a Python 2.5.2 Popen subprocess once I have the data I need?
I am running the following version of Python: $ /usr/bin/env python --version Python 2.5.2 I am running the following Python code to write data from a child subprocess to standard output, and reading that into a Python variable called metadata: # Extract metadata (snippet from extractMetadata.py) inFileAsGzip = "%s.gz" % inFile if os.path.exists(inFileAsGzip): os.remove(inFileAsGzip) os.symlink(inFile, inFileAsGzip) extractMetadataCommand = "bgzip -c -d -b 0 -s %s %s" % (metadataRequiredFileSize, inFileAsGzip) metadataPipes = subprocess.Popen(extractMetadataCommand, stdin=None, stdout=subprocess.PIPE, shell=True, close_fds=True) metadata = metadataPipes.communicate()[0] metadataPipes.stdout.close() os.remove(inFileAsGzip) print metadata The use case is as follows, to pull the first ten lines of standard output from the aforementioned code snippet: $ extractMetadata.py | head The error will appear if I pipe into head, awk, grep, etc. The script ends with the following error: close failed: [Errno 32] Broken pipe I would have thought closing the pipes would be sufficient, but obviously that's not the case.
[ "Hmmm. I've seen some \"Broken pipe\" strangeness with subprocess + gzip before. I never did figure out exactly why it was happening but by changing my implementation approach, I was able to avoid the problem. It looks like you're just trying to use a backend gzip process to decompress a file (probably because Pyth...
[ 4, 1, 0, 0 ]
[]
[]
[ "pipe", "popen", "python" ]
stackoverflow_0003861087_pipe_popen_python.txt
Q: How o Delete ALL Pages of agw.aui.notebook in One shot? I have a auiNotebook built from agw library. Now i have added few pages Now i have to delete ALL pages at one shot. Please let me know how to do this. Or is there any method which gives me List of Page Indexs for All Added Pages so that i can use Delete Page method to delete all pages Enviroment: Windows,wxpython A: This works. while(notebook.GetPageCount()): notebook.DeletePage(0)
How o Delete ALL Pages of agw.aui.notebook in One shot?
I have a auiNotebook built from agw library. Now i have added few pages Now i have to delete ALL pages at one shot. Please let me know how to do this. Or is there any method which gives me List of Page Indexs for All Added Pages so that i can use Delete Page method to delete all pages Enviroment: Windows,wxpython
[ "This works.\n while(notebook.GetPageCount()):\n notebook.DeletePage(0)\n\n" ]
[ 3 ]
[]
[]
[ "python", "wxnotebook", "wxpython" ]
stackoverflow_0003900052_python_wxnotebook_wxpython.txt
Q: Accessing a Panatone Huey via Python I have a Panatone Huey, a monitor calibration probe (device you attach to the monitor, and it gives you colour readings) - I want to get readings from the device in Python. Having never written such a device driver before, I'm not sure where to start. I've found are two open-source C/C++ projects that interface with the Heuy - ArgyllCMS and mcalib. ArgyllCMS comes with a spotread command which returns readings from the device, although it only functions as an interactive command line tool, so running it via subprocess will not (easily) work. The code ArgyllCMS uses to communicate with the device is in spectro/huey.c Not tried it (only just found it while writing this question), but mcalib contains much less code, mainly just heuy.cpp - however it has a worrying number of FIXME comments and incomplete methods, and the code appears to have been automatically generated (unhelpful variable names) There seems to be three options: Modify spotread to work without any interactive prompts, call it via subprocess Create a C-based Python module around huey.c or huey.cpp Re-implement the interface using something like PyUSB Being much more familiar with Python, I'm tempted to use PyUSB, but will this be substantially more work than wrapping existing code with the Python C API? Is there anything obvious in either of the C implementations that will not be easily doable in PyUSB? A: Given the existence of spotread the easiest (though perhaps not the best) way to proceed would be to use pexpect. It allows you to interact with other command-line programs.
Accessing a Panatone Huey via Python
I have a Panatone Huey, a monitor calibration probe (device you attach to the monitor, and it gives you colour readings) - I want to get readings from the device in Python. Having never written such a device driver before, I'm not sure where to start. I've found are two open-source C/C++ projects that interface with the Heuy - ArgyllCMS and mcalib. ArgyllCMS comes with a spotread command which returns readings from the device, although it only functions as an interactive command line tool, so running it via subprocess will not (easily) work. The code ArgyllCMS uses to communicate with the device is in spectro/huey.c Not tried it (only just found it while writing this question), but mcalib contains much less code, mainly just heuy.cpp - however it has a worrying number of FIXME comments and incomplete methods, and the code appears to have been automatically generated (unhelpful variable names) There seems to be three options: Modify spotread to work without any interactive prompts, call it via subprocess Create a C-based Python module around huey.c or huey.cpp Re-implement the interface using something like PyUSB Being much more familiar with Python, I'm tempted to use PyUSB, but will this be substantially more work than wrapping existing code with the Python C API? Is there anything obvious in either of the C implementations that will not be easily doable in PyUSB?
[ "Given the existence of spotread the easiest (though perhaps not the best) way to proceed would be to use pexpect. It allows you to interact with other command-line programs.\n" ]
[ 3 ]
[]
[]
[ "colors", "device_driver", "python", "usb" ]
stackoverflow_0003900118_colors_device_driver_python_usb.txt
Q: list.extend and list comprehension When I need to add several identical items to the list I use list.extend: a = ['a', 'b', 'c'] a.extend(['d']*3) Result ['a', 'b', 'c', 'd', 'd', 'd'] But, how to do the similar with list comprehension? a = [['a',2], ['b',2], ['c',1]] [[x[0]]*x[1] for x in a] Result [['a', 'a'], ['b', 'b'], ['c']] But I need this one ['a', 'a', 'b', 'b', 'c'] Any ideas? A: Stacked LCs. [y for x in a for y in [x[0]] * x[1]] A: An itertools approach: import itertools def flatten(it): return itertools.chain.from_iterable(it) pairs = [['a',2], ['b',2], ['c',1]] flatten(itertools.repeat(item, times) for (item, times) in pairs) # ['a', 'a', 'b', 'b', 'c'] A: >>> a = [['a',2], ['b',2], ['c',1]] >>> [i for i, n in a for k in range(n)] ['a', 'a', 'b', 'b', 'c'] A: If you prefer extend over list comprehensions: a = [] for x, y in l: a.extend([x]*y) A: >>> a = [['a',2], ['b',2], ['c',1]] >>> sum([[item]*count for item,count in a],[]) ['a', 'a', 'b', 'b', 'c'] A: import operator a = [['a',2], ['b',2], ['c',1]] nums = [[x[0]]*x[1] for x in a] nums = reduce(operator.add, nums)
list.extend and list comprehension
When I need to add several identical items to the list I use list.extend: a = ['a', 'b', 'c'] a.extend(['d']*3) Result ['a', 'b', 'c', 'd', 'd', 'd'] But, how to do the similar with list comprehension? a = [['a',2], ['b',2], ['c',1]] [[x[0]]*x[1] for x in a] Result [['a', 'a'], ['b', 'b'], ['c']] But I need this one ['a', 'a', 'b', 'b', 'c'] Any ideas?
[ "Stacked LCs.\n[y for x in a for y in [x[0]] * x[1]]\n\n", "An itertools approach:\nimport itertools\n\ndef flatten(it):\n return itertools.chain.from_iterable(it)\n\npairs = [['a',2], ['b',2], ['c',1]]\nflatten(itertools.repeat(item, times) for (item, times) in pairs)\n# ['a', 'a', 'b', 'b', 'c']\n\n", ">>>...
[ 59, 14, 6, 6, 2, 1 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0003899645_list_list_comprehension_python.txt
Q: Ignore an element while building list in python I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None. How can I do that ? A: We could create a "subquery". [r for r in (f(char) for char in string) if r is not None] If you allow all False values (0, False, None, etc.) to be ignored as well, filter could be used: filter(None, (f(char) for char in string) ) # or, using itertools.imap, filter(None, imap(f, string))
Ignore an element while building list in python
I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None. How can I do that ?
[ "We could create a \"subquery\".\n[r for r in (f(char) for char in string) if r is not None]\n\nIf you allow all False values (0, False, None, etc.) to be ignored as well, filter could be used:\nfilter(None, (f(char) for char in string) )\n# or, using itertools.imap,\nfilter(None, imap(f, string))\n\n" ]
[ 37 ]
[]
[]
[ "list", "python", "syntactic_sugar" ]
stackoverflow_0003900215_list_python_syntactic_sugar.txt
Q: How to check whether elements appears in the list only once in python? I have a list: a = [1, 2, 6, 4, 3, 5, 7] Please, explain to me how to check whether element appears only once in in the list? Please, also explain if all elements from 1 to len(a) are in the list. For instance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5], then not all elements from 1 to 4 are not in the list. Thank you! A: When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then def occurs_once(a, item): return a.count(item) == 1 will be true only if item occurs in the list exactly once. See Pokes answer for the second question A: len( set( a ) ) == len( a ) for the first question, and ( len( set( a ) ) == len( a ) == max( a ) ) and min( a ) == 1 for the second. A: For your first question if your elements are hashable you can create a set containing the elements and check its length: len(set(a)) == len(a) Alternatively you can use this function which can give better performance than the above if the result is False (but worse performance when the result is True): def are_all_elements_unique(l): seen = set() for x in l: if x in seen: return False seen.add(x) return True A: For the second question you might want to check sorted(a) == range(1, len(a) + 1) A: i understood you want something like that: [x for x in a if a.count(x) == 1]
How to check whether elements appears in the list only once in python?
I have a list: a = [1, 2, 6, 4, 3, 5, 7] Please, explain to me how to check whether element appears only once in in the list? Please, also explain if all elements from 1 to len(a) are in the list. For instance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5], then not all elements from 1 to 4 are not in the list. Thank you!
[ "When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then\ndef occurs_once(a, item):\n return a.count(item) == 1\n\nwill be true only if item occurs in the list exactly once. \nSee Pokes answer for the second question \n", ...
[ 8, 6, 5, 4, 3 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0003899782_iteration_list_python.txt
Q: Lists in Python Possible Duplicate: What is the easiest way to convert list with str into list with int? =) Is it possible to transform: a = ['1', '2', '3', '4'] to a = [1, 2, 3, 4] Thank You! A: You could use map to apply a function to each element of a list, and a get the resulting list (Python 2.x) / iterable (Python 3.x) back. map(int, a) It could be done with list comprehension too. [int(x) for x in a] A: Another way: result = [int(x) for x in a] This is called a list comprehension.
Lists in Python
Possible Duplicate: What is the easiest way to convert list with str into list with int? =) Is it possible to transform: a = ['1', '2', '3', '4'] to a = [1, 2, 3, 4] Thank You!
[ "You could use map to apply a function to each element of a list, and a get the resulting list (Python 2.x) / iterable (Python 3.x) back.\nmap(int, a)\n\nIt could be done with list comprehension too.\n[int(x) for x in a]\n\n", "Another way:\nresult = [int(x) for x in a]\n\nThis is called a list comprehension.\n" ...
[ 2, 2 ]
[]
[]
[ "list", "python", "transformation" ]
stackoverflow_0003900344_list_python_transformation.txt
Q: python: Convert tcpdump into text2pcap readable format Recently there was a requirement for me to convert the textual output of "tcpdump -i eth0 -neXXs0" into a pcap file. So I wrote a python script which converts the information into an intermediate format understandable by text2pcap. Since this is my first program in python there would obviously be scope for improvement. I want knowledgeable folks to weed out any descrepancy and/or enhance it. Input The tcpdump output is in the following format: 20:11:32.001190 00:16:76:7f:2b:b1 > 00:11:5c:78:ca:c0, ethertype IPv4 (0x0800), length 72: 123.236.188.140.41756 > 94.59.34.210.45931: UDP, length 30 0x0000: 0011 5c78 cac0 0016 767f 2bb1 0800 4500 ..\x....v.+...E. 0x0010: 003a 0000 4000 4011 812d 7bec bc8c 5e3b .:..@.@..-{...^; 0x0020: 22d2 a31c b36b 0026 b9bd 2033 6890 ad33 "....k.&...3h..3 0x0030: e845 4b8d 2ba1 0685 0cb3 70dd 9b98 76d8 .EK.+.....p...v. 0x0040: 8fc6 8293 bf33 325a .....32Z Output enter code here Format understandable by text2pcap: 20:11:32.001190 0000: 00 11 5c 78 ca c0 00 16 76 7f 2b b1 08 00 45 00 ..\x....v.+...E. 0010: 00 3a 00 00 40 00 40 11 81 2d 7b ec bc 8c 5e 3b .:..@.@..-{...^; 0020: 22 d2 a3 1c b3 6b 00 26 b9 bd 20 33 68 90 ad 33 "....k.&...3h..3 0030: e8 45 4b 8d 2b a1 06 85 0c b3 70 dd 9b 98 76 d8 .EK.+.....p...v. 0040: 8f c6 82 93 bf 33 32 5a .....32Z Following is my Code. import re # Identify time of the current packet. time = re.compile ('(..:..:..\.[\w]*) ') # Get individual elements from the packet. ie. offset, hexdump, chars all = re.compile('[ |\t]+0x([\w]+:) +(.+) +(.*)') # Regex for two spaces twoSpaces = re.compile(' +') # Regex for single space singleSpace = re.compile(' ') # Single byte pattern. singleBytePattern = re.compile(r'([\w][\w])') # Open files. f = open ('pcap.txt', 'r') outfile = open ('ashu.txt', 'w') for line in f: result = time.match (line) if result: # If current line contains time format dump only time print result.group() outfile.write (result.group() + '\n') else: print line, # Split line containing hex dump and tokenize into list elements. result = all.split (line) if result: i = 0 for values in result: if (i == 2): # Strip off additional spaces in hex dump # Useful when hex dump does not end in 16 bytes boundary. val = twoSpaces.sub ('', values) # Tokenize individual elements seperated by single space. byteResult = singleSpace.split (val) for twoByte in byteResult: # Identify individual byte singleByte = singleBytePattern.split(twoByte) byteOffset = 0 for oneByte in singleByte: if ((byteOffset == 1) or (byteOffset == 3)): # Write out individual byte with a space char appended print oneByte, outfile.write (oneByte+ ' ') byteOffset = byteOffset + 1 elif (i == 3): # Write of char format of hex dump print " "+values, outfile.write (' ' + values+ ' ') elif (i == 4): outfile.write (values) else: print values, outfile.write (values + ' ') i=i+1 else: print "could not split" f.close () outfile.close () A: Use the -w option of tcpdump to write to a pcap format file tcpdump -w filename.pcap Wireshark should be able to read it.
python: Convert tcpdump into text2pcap readable format
Recently there was a requirement for me to convert the textual output of "tcpdump -i eth0 -neXXs0" into a pcap file. So I wrote a python script which converts the information into an intermediate format understandable by text2pcap. Since this is my first program in python there would obviously be scope for improvement. I want knowledgeable folks to weed out any descrepancy and/or enhance it. Input The tcpdump output is in the following format: 20:11:32.001190 00:16:76:7f:2b:b1 > 00:11:5c:78:ca:c0, ethertype IPv4 (0x0800), length 72: 123.236.188.140.41756 > 94.59.34.210.45931: UDP, length 30 0x0000: 0011 5c78 cac0 0016 767f 2bb1 0800 4500 ..\x....v.+...E. 0x0010: 003a 0000 4000 4011 812d 7bec bc8c 5e3b .:..@.@..-{...^; 0x0020: 22d2 a31c b36b 0026 b9bd 2033 6890 ad33 "....k.&...3h..3 0x0030: e845 4b8d 2ba1 0685 0cb3 70dd 9b98 76d8 .EK.+.....p...v. 0x0040: 8fc6 8293 bf33 325a .....32Z Output enter code here Format understandable by text2pcap: 20:11:32.001190 0000: 00 11 5c 78 ca c0 00 16 76 7f 2b b1 08 00 45 00 ..\x....v.+...E. 0010: 00 3a 00 00 40 00 40 11 81 2d 7b ec bc 8c 5e 3b .:..@.@..-{...^; 0020: 22 d2 a3 1c b3 6b 00 26 b9 bd 20 33 68 90 ad 33 "....k.&...3h..3 0030: e8 45 4b 8d 2b a1 06 85 0c b3 70 dd 9b 98 76 d8 .EK.+.....p...v. 0040: 8f c6 82 93 bf 33 32 5a .....32Z Following is my Code. import re # Identify time of the current packet. time = re.compile ('(..:..:..\.[\w]*) ') # Get individual elements from the packet. ie. offset, hexdump, chars all = re.compile('[ |\t]+0x([\w]+:) +(.+) +(.*)') # Regex for two spaces twoSpaces = re.compile(' +') # Regex for single space singleSpace = re.compile(' ') # Single byte pattern. singleBytePattern = re.compile(r'([\w][\w])') # Open files. f = open ('pcap.txt', 'r') outfile = open ('ashu.txt', 'w') for line in f: result = time.match (line) if result: # If current line contains time format dump only time print result.group() outfile.write (result.group() + '\n') else: print line, # Split line containing hex dump and tokenize into list elements. result = all.split (line) if result: i = 0 for values in result: if (i == 2): # Strip off additional spaces in hex dump # Useful when hex dump does not end in 16 bytes boundary. val = twoSpaces.sub ('', values) # Tokenize individual elements seperated by single space. byteResult = singleSpace.split (val) for twoByte in byteResult: # Identify individual byte singleByte = singleBytePattern.split(twoByte) byteOffset = 0 for oneByte in singleByte: if ((byteOffset == 1) or (byteOffset == 3)): # Write out individual byte with a space char appended print oneByte, outfile.write (oneByte+ ' ') byteOffset = byteOffset + 1 elif (i == 3): # Write of char format of hex dump print " "+values, outfile.write (' ' + values+ ' ') elif (i == 4): outfile.write (values) else: print values, outfile.write (values + ' ') i=i+1 else: print "could not split" f.close () outfile.close ()
[ "Use the -w option of tcpdump to write to a pcap format file\ntcpdump -w filename.pcap\n\nWireshark should be able to read it.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003900431_python.txt
Q: access to google with python how i can access to google !! i had try that code urllib.urlopen('http://www.google.com') but it's show message prove you are human or some think like dat some people say try user agent !! i dunno ! A: You should use the Google API for accessing the search. Here's an example for python. Unutbu provided a link to an older SO answer which contains a corrected version of the same example code. #!/usr/bin/python import urllib, urllib2 import json api_key, userip = None, None query = {'q' : 'search google python api'} referrer = "https://stackoverflow.com/q/3900610" if userip: query.update(userip=userip) if api_key: query.update(key=api_key) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % ( urllib.urlencode(query)) request = urllib2.Request(url, headers=dict(Referer=referrer)) json = json.load(urllib2.urlopen(request)) results = json['responseData']['results'] for r in results: print r['title'] + ": " + r['url'] A: A user agent string is indeed the way to go... pick any valid user agent from any common browser. In python 2.x, the following code should give you what you want: import urllib2 r = urllib2.Request('http://www.google.com/') r.add_header('User-Agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.19) ' 'Gecko/20081202 Firefox (Debian-2.0.0.19-0etch1)') html = urllib2.urlopen(r).read() Having said that, unutbu's recommendation to use the google search API (if you're looking to do searches) is by far the better way to go... avoids all that messy HTML parsing.
access to google with python
how i can access to google !! i had try that code urllib.urlopen('http://www.google.com') but it's show message prove you are human or some think like dat some people say try user agent !! i dunno !
[ "You should use the Google API for accessing the search. Here's an example for python. Unutbu provided a link to an older SO answer which contains a corrected version of the same example code.\n#!/usr/bin/python\nimport urllib, urllib2\nimport json\n\napi_key, userip = None, None\nquery = {'q' : 'search google pyth...
[ 10, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003900610_python.txt
Q: Writing a TCP to RS232 driver I need to expose an RS232 connection to clients via a network socket. I plan to write in python a TCP socket server which will listen on some port, allow client to connect and handle outgoing and manage and control requests and replies to from the R2232 port. My question is, how do I synchronize the clients, each client will send some string to the serial port and after the reply is sent back I need to return that client the result. Only then do I need to process the next request. How to I synchronize access to the serial port ? A: To expand on Sjoerd's answer, building a single-thread server (e.g. http://docs.python.org/library/basehttpserver.html) that then controls the port (via something like http://pyserial.sourceforge.net/pyserial_api.html), plus a trivial URL structure, gives you a simple, RESTful way of exposing and handling the requests. I use something very similar to this (a little more elaborate with a webby interface) to control our landscape irrigation system; my wife loves it. A: The simplest way is to simply accept a connection, handle the request, and close the connection. This way, your program handles only one request at a time. An alternative is to use locking or semaphores, to prevent multiple clients accessing the RS232 port simultaneously.
Writing a TCP to RS232 driver
I need to expose an RS232 connection to clients via a network socket. I plan to write in python a TCP socket server which will listen on some port, allow client to connect and handle outgoing and manage and control requests and replies to from the R2232 port. My question is, how do I synchronize the clients, each client will send some string to the serial port and after the reply is sent back I need to return that client the result. Only then do I need to process the next request. How to I synchronize access to the serial port ?
[ "To expand on Sjoerd's answer, building a single-thread server (e.g. http://docs.python.org/library/basehttpserver.html) that then controls the port (via something like http://pyserial.sourceforge.net/pyserial_api.html), plus a trivial URL structure, gives you a simple, RESTful way of exposing and handling the requ...
[ 2, 1 ]
[]
[]
[ "python", "serial_port", "sockets" ]
stackoverflow_0003900403_python_serial_port_sockets.txt
Q: Python - question about factory functions I have a series of classes that I'll be registering as services to a higher level abstraction class. The high-level class will have a function that gets the lower level class based on init args, etc. Does this sound berserk? Also, what is this called? I call it factory function/class, but I really have no idea (which makes it harder to Google best practices). A: It's called "metaclass programming". In recent versions of Python it's implemented by defining the __new__() static method and returning an object of the appropriate type. class C(object): def __new__(cls, val): if val == 5: return 'five' else: return super(C, cls).__new__(cls) c1 = C(3) print c1 c2 = C(5) print c2
Python - question about factory functions
I have a series of classes that I'll be registering as services to a higher level abstraction class. The high-level class will have a function that gets the lower level class based on init args, etc. Does this sound berserk? Also, what is this called? I call it factory function/class, but I really have no idea (which makes it harder to Google best practices).
[ "It's called \"metaclass programming\". In recent versions of Python it's implemented by defining the __new__() static method and returning an object of the appropriate type.\nclass C(object):\n def __new__(cls, val):\n if val == 5:\n return 'five'\n else:\n return super(C, cls).__new__(cls)\n\nc1 ...
[ 2 ]
[]
[]
[ "factory_pattern", "python" ]
stackoverflow_0003900896_factory_pattern_python.txt
Q: Adding and removing audio sources to/from GStreamer pipeline on-the-go I wrote a little Python script which uses an Adder plugin to mix two source streams together. After starting the program, you hear a 1kHz tone generated by the audiotestsrc plugin. When you press Enter, an another 500Hz test tone is connected to the Adder so you hear them together. (By the way, i don't really get why should i set the pipeline again to playing state here to hear the mix. Is there any way i can plug in new sources without having to restart the pipeline?) When you press Enter once again, the 1kHz tone should be removed from the mix and the 500Hz tone should keep playing, but instead i hear nothing anymore. I get a pulse pulsesink.c:528:gst_pulsering_stream_underflow_cb:<pulseaudio_output> Got underflow in the debug output as the last line. I don't really know what to try next. Here is the full source code: #!/usr/bin/python # On-the-go source removal doesn't work this way with GStreamer. Why? import gobject; gobject.threads_init() import gst; if __name__ == "__main__": pipe = gst.Pipeline("mypipe") adder = gst.element_factory_make("adder","audiomixer") pipe.add(adder) buzzer = gst.element_factory_make("audiotestsrc","buzzer") buzzer.set_property("freq",1000) pipe.add(buzzer) pulse = gst.element_factory_make("pulsesink", "pulseaudio_output") pipe.add(pulse) buzzer.link(adder) adder.link(pulse) pipe.set_state(gst.STATE_PLAYING) raw_input("1kHz test sound. Press <ENTER> to continue.") buzzer2=gst.element_factory_make("audiotestsrc","buzzer2") buzzer2.set_property("freq",500) pipe.add(buzzer2) buzzer2.link(adder) pipe.set_state(gst.STATE_PLAYING) raw_input("1kHz + 500Hz test sound playing simoultenously. Press <ENTER> to continue.") buzzer.unlink(adder) pipe.set_state(gst.STATE_PLAYING) raw_input("Only 500Hz test sound. Press <ENTER> to stop.") A: I've found the solution on my own. I had to use request pads with Adder and use the pad blocking capability of GStreamer. Here's the working source code with some descriptions: #!/usr/bin/python import gobject; gobject.threads_init() import gst; if __name__ == "__main__": # First create our pipeline pipe = gst.Pipeline("mypipe") # Create a software mixer with "Adder" adder = gst.element_factory_make("adder","audiomixer") pipe.add(adder) # Gather a request sink pad on the mixer sinkpad1=adder.get_request_pad("sink%d") # Create the first buzzer.. buzzer1 = gst.element_factory_make("audiotestsrc","buzzer1") buzzer1.set_property("freq",1000) pipe.add(buzzer1) # .. and connect it's source pad to the previously gathered request pad buzzersrc1=buzzer1.get_pad("src") buzzersrc1.link(sinkpad1) # Add some output output = gst.element_factory_make("autoaudiosink", "audio_out") pipe.add(output) adder.link(output) # Start the playback pipe.set_state(gst.STATE_PLAYING) raw_input("1kHz test sound. Press <ENTER> to continue.") # Get an another request sink pad on the mixer sinkpad2=adder.get_request_pad("sink%d") # Create an another buzzer and connect it the same way buzzer2 = gst.element_factory_make("audiotestsrc","buzzer2") buzzer2.set_property("freq",500) pipe.add(buzzer2) buzzersrc2=buzzer2.get_pad("src") buzzersrc2.link(sinkpad2) # Start the second buzzer (other ways streaming stops because of starvation) buzzer2.set_state(gst.STATE_PLAYING) raw_input("1kHz + 500Hz test sound playing simoultenously. Press <ENTER> to continue.") # Before removing a source, we must use pad blocking to prevent state changes buzzersrc1.set_blocked(True) # Stop the first buzzer buzzer1.set_state(gst.STATE_NULL) # Unlink from the mixer buzzersrc1.unlink(sinkpad1) # Release the mixers first sink pad adder.release_request_pad(sinkpad1) # Because here none of the Adder's sink pads block, streaming continues raw_input("Only 500Hz test sound. Press <ENTER> to stop.")
Adding and removing audio sources to/from GStreamer pipeline on-the-go
I wrote a little Python script which uses an Adder plugin to mix two source streams together. After starting the program, you hear a 1kHz tone generated by the audiotestsrc plugin. When you press Enter, an another 500Hz test tone is connected to the Adder so you hear them together. (By the way, i don't really get why should i set the pipeline again to playing state here to hear the mix. Is there any way i can plug in new sources without having to restart the pipeline?) When you press Enter once again, the 1kHz tone should be removed from the mix and the 500Hz tone should keep playing, but instead i hear nothing anymore. I get a pulse pulsesink.c:528:gst_pulsering_stream_underflow_cb:<pulseaudio_output> Got underflow in the debug output as the last line. I don't really know what to try next. Here is the full source code: #!/usr/bin/python # On-the-go source removal doesn't work this way with GStreamer. Why? import gobject; gobject.threads_init() import gst; if __name__ == "__main__": pipe = gst.Pipeline("mypipe") adder = gst.element_factory_make("adder","audiomixer") pipe.add(adder) buzzer = gst.element_factory_make("audiotestsrc","buzzer") buzzer.set_property("freq",1000) pipe.add(buzzer) pulse = gst.element_factory_make("pulsesink", "pulseaudio_output") pipe.add(pulse) buzzer.link(adder) adder.link(pulse) pipe.set_state(gst.STATE_PLAYING) raw_input("1kHz test sound. Press <ENTER> to continue.") buzzer2=gst.element_factory_make("audiotestsrc","buzzer2") buzzer2.set_property("freq",500) pipe.add(buzzer2) buzzer2.link(adder) pipe.set_state(gst.STATE_PLAYING) raw_input("1kHz + 500Hz test sound playing simoultenously. Press <ENTER> to continue.") buzzer.unlink(adder) pipe.set_state(gst.STATE_PLAYING) raw_input("Only 500Hz test sound. Press <ENTER> to stop.")
[ "I've found the solution on my own. I had to use request pads with Adder and use the pad blocking capability of GStreamer.\nHere's the working source code with some descriptions:\n#!/usr/bin/python\n\nimport gobject;\ngobject.threads_init()\nimport gst;\n\nif __name__ == \"__main__\":\n # First create our pipeli...
[ 6 ]
[]
[]
[ "audio", "gstreamer", "mixing", "python" ]
stackoverflow_0003899666_audio_gstreamer_mixing_python.txt
Q: What is better in python, a Dictionary or Mysql? What would be faster ? Query mysql to see if the piece of information i need is there, OR load a python dictionary with all the information then just check if the id is there If python is faster, then whats the best what to check if the id exists? Im using python 2.4.3 Im searching for data which is tagged to a square on a board, im searching for x&y. Theres only one entry per square, the information wont change and it needs be recalled several times a second. Thankyou ! Finished I worked out it was python. I ran the code bellow, and mysql did it in 0.0003 of a second, but python did it in 0.000006 of a second and mysql had far far less to search and the test was run how the code would be running in real life. Which one had less overhead in terns of CPU and RAM i will never know but if speed is anything to go by python did much better. And thankyou for your answers ! def speedtest(): global search global data qb = time.time() search.execute("SELECT * FROM `nogo` where `1`='11' AND `2`='13&3'") qa = search.fetchall() print qa[0] qc = time.time() print "mysql" print qb print qc print qc - qb data = {} for qa in range(15): data[qa] = {} for qb in range(300): data[qa][str(qb)] = 'nogo' qw = 5 qe = '50' qb = time.time() print data[qw][qe] qc = time.time() print "dictionary" print qb print qc print qc - qb A: Generally speaking, if you want information from a database, ask the database for what you need. MySQL (and other database engines) are designed to retrieve data as efficiently as possible. Trying to write your own procedures for retrieving data is trying to outsmart the talented people who have already imbued MySQL with so much data processing power. This isn't to say it's never appropriate to load data into Python, but you should be sure that a database query isn't the right way to go first. A: I can't speak for how fast MySQL would be (I lack the knowhow to benchmark it equitably), but Python dict have pretty much optimal performance too and don't require any IO (as opposed to database queries). Assuming (x_pos, y_pos) tuples as keys and a 55 x 55 field (you mentioned 3000 records, 55^2 is roughly 3000). >>> the_dict = { (x, y) : None for x in range(55) for y in range (55) } >>> len(the_dict) 3025 >>> import random >>> xs = [random.randrange(0,110) for _ in range(55)] >>> ys = [random.randrange(0,110) for _ in range(55)] >>> import timeit >>> total_secs = timeit.timeit("for x,y in zip(xs, ys): (x,y) in the_dict", setup="from __main__ import xs, ys, the_dict", number=100000) >>> each_secs = total_secs / 100000 >>> each_secs 1.1723998441142385e-05 >>> each_usecs = 1000000 * each_secs >>> each_usecs 11.723998441142385 >>> usecs_per_lookup = each_usecs / (55*55) >>> usecs_per_lookup 0.0038757019640140115 0.004 microseconds(!) per lookup - good luck beating that, DBMS of choice ;) But since you use 2.4, YMMV slightly. Admittedly, tuples of ints hash make very efficient keys (integers (that fit into the hash datatype) hash to themselves, tuples just hash and xor their members). Also, this doesn't say anything about how fast loading the data would be (although you can use the pickle module for efficient serialization). But your question reads like you load the data once and then process it a million times. A: Python ought to be much faster, but this largely depends on your specific scenario. my_dict.has_key('foobar') You may want to check out Bloom filters as well. A: In general I think python is faster but: it depends on 1) how big is the table you want to load (if its too big it will not be efficient with python), and 2) how many function calls you are about to execute (so sometimes it is better to load the table to a dict and execute all your queries within one function).
What is better in python, a Dictionary or Mysql?
What would be faster ? Query mysql to see if the piece of information i need is there, OR load a python dictionary with all the information then just check if the id is there If python is faster, then whats the best what to check if the id exists? Im using python 2.4.3 Im searching for data which is tagged to a square on a board, im searching for x&y. Theres only one entry per square, the information wont change and it needs be recalled several times a second. Thankyou ! Finished I worked out it was python. I ran the code bellow, and mysql did it in 0.0003 of a second, but python did it in 0.000006 of a second and mysql had far far less to search and the test was run how the code would be running in real life. Which one had less overhead in terns of CPU and RAM i will never know but if speed is anything to go by python did much better. And thankyou for your answers ! def speedtest(): global search global data qb = time.time() search.execute("SELECT * FROM `nogo` where `1`='11' AND `2`='13&3'") qa = search.fetchall() print qa[0] qc = time.time() print "mysql" print qb print qc print qc - qb data = {} for qa in range(15): data[qa] = {} for qb in range(300): data[qa][str(qb)] = 'nogo' qw = 5 qe = '50' qb = time.time() print data[qw][qe] qc = time.time() print "dictionary" print qb print qc print qc - qb
[ "Generally speaking, if you want information from a database, ask the database for what you need. MySQL (and other database engines) are designed to retrieve data as efficiently as possible. \nTrying to write your own procedures for retrieving data is trying to outsmart the talented people who have already imbued M...
[ 5, 2, 1, 1 ]
[]
[]
[ "dictionary", "mysql", "python", "variables" ]
stackoverflow_0003900762_dictionary_mysql_python_variables.txt
Q: Edit regex in python script The following python script allows me to scrape email addresses from a given file using regular expressions. I'm trying to add phone numbers to the regular expression also. I created this regex and seems to work on 7 and 10 digit numbers: (\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}) Can this just be added to my existing regular expression? I figure I need to edit where I use re.compile but not completely sure how to do this in python. Any help would be appreciated. # filename variables filename = 'file.txt' newfilename = 'result.txt' # read the file if os.path.exists(filename): data = open(filename,'r') bulkemails = data.read() else: print "File not found." raise SystemExit # regex = something@whatever.xxx r = re.compile(r'(\b[\w.]+@+[\w.]+.+[\w.]\b)') results = r.findall(bulkemails) emails = "" for x in results: emails += str(x)+"\n" # function to write file def writefile(): f = open(newfilename, 'w') f.write(emails) f.close() print "File written." EDIT When running on http://en.wikipedia.org/wiki/Telephone_number It produces the following output: 2678400 2678400 2678400 2678400 2678400 2678400 2678400 2678400 2678400 8790468 9664261 555-1212 555-9225 555-1212 869-1234 555-5555 555-1212 867-5309 867-5309 867-5309 (267) 867-5309 (212) 736-5000 243-3460 2977743 1000000 2048000 2048000 8790468 9070412 9664261 9664261 9664261 A: I would not advise combining the two regexes. It's possible, but it will make for code which is harder to understand and maintain down the road. (Also, leaving the regexes separate will let you handle emails and phone numbers differently down the line, which you're likely to want to do.) A: For one, I would simplify your regex: (?:\(?\b\d{3}\)?[-.\s]*)?\d{3}[-.\s]*\d{4}\b will match the same correct numbers as before and have fewer false hits. Second, your e-mail regex will miss a lot of valid e-mail addresses and have many false positives, too (it would match aaaa@@@@aaaa, for example). While you can never match e-mail address with 100 % reliability using regex, the following one is better, too: \b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b (Use the case insensitive option when compiling it). To restrict yourself to some few TLDs, you can use \b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+(?:asia|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[A-Z]{2})\b
Edit regex in python script
The following python script allows me to scrape email addresses from a given file using regular expressions. I'm trying to add phone numbers to the regular expression also. I created this regex and seems to work on 7 and 10 digit numbers: (\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}) Can this just be added to my existing regular expression? I figure I need to edit where I use re.compile but not completely sure how to do this in python. Any help would be appreciated. # filename variables filename = 'file.txt' newfilename = 'result.txt' # read the file if os.path.exists(filename): data = open(filename,'r') bulkemails = data.read() else: print "File not found." raise SystemExit # regex = something@whatever.xxx r = re.compile(r'(\b[\w.]+@+[\w.]+.+[\w.]\b)') results = r.findall(bulkemails) emails = "" for x in results: emails += str(x)+"\n" # function to write file def writefile(): f = open(newfilename, 'w') f.write(emails) f.close() print "File written." EDIT When running on http://en.wikipedia.org/wiki/Telephone_number It produces the following output: 2678400 2678400 2678400 2678400 2678400 2678400 2678400 2678400 2678400 8790468 9664261 555-1212 555-9225 555-1212 869-1234 555-5555 555-1212 867-5309 867-5309 867-5309 (267) 867-5309 (212) 736-5000 243-3460 2977743 1000000 2048000 2048000 8790468 9070412 9664261 9664261 9664261
[ "I would not advise combining the two regexes. It's possible, but it will make for code which is harder to understand and maintain down the road. \n(Also, leaving the regexes separate will let you handle emails and phone numbers differently down the line, which you're likely to want to do.)\n", "For one, I would ...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003901252_python_regex.txt
Q: Nested Lists in Dict : Accessing members of list within the list of a dictionary def index_dir(self, base_path): num_files_indexed = 0 allfiles = os.listdir(base_path) self._documents = os.listdir(base_path) num_files_indexed = len(allfiles) docnumber = 0 self._inverted_index = collections.defaultdict(list) docnumlist = [] for file in allfiles: self.documents = [base_path+file] #list of all text files f = open(base_path+file, 'r') lines = f.read() tokens = self.tokenize(lines) docnumber = docnumber + 1 for term in tokens: # check if the key/term already exists in the dictionary, # if yes, just add a new key value/term into the dict if term not in sorted(self._inverted_index.keys()): newlist=[] tf=1 self._inverted_index[term] = [] #self._inverted_index[term][docnumber] +=1 newlist.append(docnumber) newlist.append(tf) self._inverted_index[term].append(newlist) #appending list to a list else: if docnumber not in self._inverted_index.get(term): newlist=[] tf=1 newlist.append(docnumber) newlist.append(tf) self._inverted_index[term].append(newlist) f.close() print '\n \n' print 'Dictionary contents: \n' for term in sorted(self._inverted_index): print term, '->', self._inverted_index.get(term) return num_files_indexed return 0 What I get from this code: dictionary in this format: term <- [[docnumber, term freq][docnumber, term freq]] for ex: if the word cat occurs in doc 1.txt for three times and in Doc 3.txt twice: I get: cat <- [[1,1],[1,1],[1,1],[3,1][3,1]] so, instead of getting [1,1] three times, I want [1,3] added to the list I don't know how to get rid of repetitive members of the list and increment the term freq. What I should get: cat <- [[1,3],[3,2]] i.e. thrice in Doc 1 and twice in doc 3. I have tried ways to work it out, but I get access errors all the time. Thanks in advance. A: >>> from itertools import groupby >>> from operator import itemgetter >>> cat = [[1,1],[1,1],[1,1],[3,1],[3,1]] >>> [(k,len(list(v))) for k, v in groupby(cat,itemgetter(0))] [(1, 3), (3, 2)] will fix your code. But that doesn't solve the problem of why the code is doing the wrong thing in the first place! The solution is to use the collections.Counter class, which will do the work for you if you just feed it a list of words. >>> words = "Lorem ipsum dolor sit ames, lorem ipsum dolor sit ames.".split(" ") >>> Counter(words) Counter({'ipsum': 2, 'sit': 2, 'dolor': 2, 'lorem': 1, 'ames.': 1, 'ames,': 1, 'Lorem': 1}) >>> Counter(map(str.lower, words)) Counter({'ipsum': 2, 'sit': 2, 'dolor': 2, 'lorem': 2, 'ames.': 1, 'ames,': 1}) A: final counts: {'cat':[[1,3], [3,2]]} Words in current document: {'cat':3} I like that you have chosen to use defaultdict. It makes the following possible and is faster then looping through the keys. from collections import defaultdict all_word_counts = defaultdict(list) all_word_counts['cat'].append([1, 3]) First count the word frequency in a given document word_count = defaultdict(int) #reset each document for term in self.tokenize(lines): word_count[term] += 1 Before moving on to the next document update the all_word_counts for word, count in word_count.iteritems(): all_word_counts[word].append([docnumber, count])
Nested Lists in Dict : Accessing members of list within the list of a dictionary
def index_dir(self, base_path): num_files_indexed = 0 allfiles = os.listdir(base_path) self._documents = os.listdir(base_path) num_files_indexed = len(allfiles) docnumber = 0 self._inverted_index = collections.defaultdict(list) docnumlist = [] for file in allfiles: self.documents = [base_path+file] #list of all text files f = open(base_path+file, 'r') lines = f.read() tokens = self.tokenize(lines) docnumber = docnumber + 1 for term in tokens: # check if the key/term already exists in the dictionary, # if yes, just add a new key value/term into the dict if term not in sorted(self._inverted_index.keys()): newlist=[] tf=1 self._inverted_index[term] = [] #self._inverted_index[term][docnumber] +=1 newlist.append(docnumber) newlist.append(tf) self._inverted_index[term].append(newlist) #appending list to a list else: if docnumber not in self._inverted_index.get(term): newlist=[] tf=1 newlist.append(docnumber) newlist.append(tf) self._inverted_index[term].append(newlist) f.close() print '\n \n' print 'Dictionary contents: \n' for term in sorted(self._inverted_index): print term, '->', self._inverted_index.get(term) return num_files_indexed return 0 What I get from this code: dictionary in this format: term <- [[docnumber, term freq][docnumber, term freq]] for ex: if the word cat occurs in doc 1.txt for three times and in Doc 3.txt twice: I get: cat <- [[1,1],[1,1],[1,1],[3,1][3,1]] so, instead of getting [1,1] three times, I want [1,3] added to the list I don't know how to get rid of repetitive members of the list and increment the term freq. What I should get: cat <- [[1,3],[3,2]] i.e. thrice in Doc 1 and twice in doc 3. I have tried ways to work it out, but I get access errors all the time. Thanks in advance.
[ ">>> from itertools import groupby\n>>> from operator import itemgetter\n>>> cat = [[1,1],[1,1],[1,1],[3,1],[3,1]]\n>>> [(k,len(list(v))) for k, v in groupby(cat,itemgetter(0))]\n[(1, 3), (3, 2)]\n\nwill fix your code. But that doesn't solve the problem of why the code is doing the wrong thing in the first place! T...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003861597_python.txt
Q: Performance comparison of immutable string concatenation between Java and Python UPDATES: thanks a lot to Gabe and Glenn for the detailed explanation. The test is wrote not for language comparison benchmark, just for my studying on VM optimization technologies. I did a simple test to understand the performance of string concatenation between Java and Python. The test is target for the default immutable String object/type in both languages. So I don't use StringBuilder/StringBuffer in Java test. The test simply adds strings for 100k times. Java consumes ~32 seconds to finish, while Python only uses ~13 seconds for Unicode string and 0.042 seconds for non Unicode string. I'm a bit surprise about the results. I thought Java should be faster than Python. What optimization technology does Python leverage to achieve better performance? Or String object is designed too heavy in Java? OS: Ubuntu 10.04 x64 JDK: Sun 1.6.0_21 Python: 2.6.5 Java test did use -Xms1024m to minimize GC activities. Java code: public class StringConcateTest { public static void test(int n) { long start = System.currentTimeMillis(); String a = ""; for (int i = 0; i < n; i++) { a = a.concat(String.valueOf(i)); } long end = System.currentTimeMillis(); System.out.println(a.length() + ", time:" + (end - start)); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { test(1000 * 100); } } } Python code: import time def f(n): start = time.time() a = u'' #remove u to use non Unicode string for i in xrange(n): a = a + str(i) print len(a), 'time', (time.time() - start)*1000.0 for j in xrange(10): f(1000 * 100) A: @Gabe's answer is correct, but needs to be shown clearly rather than hypothesized. CPython (and probably only CPython) does an in-place string append when it can. There are limitations on when it can do this. First, it can't do it for interned strings. That's why you'll never see this if you test with a = "testing"; a = a + "testing", because assigning a string literal results in an interned string. You have to create the string dynamically, as this code does with str(12345). (This isn't much of a limitation; once you do an append this way once, the result is an uninterned string, so if you append string literals in a loop this will only happen the first time.) Second, Python 2.x only does this for str, not unicode. Python 3.x does do this for Unicode strings. This is strange: it's a major performance difference--a difference in complexity. This discourages using Unicode strings in 2.x, when they should be encouraging it to help the transition to 3.x. And finally, there can be no other references to the string. >>> a = str(12345) >>> id(a) 3082418720 >>> a += str(67890) >>> id(a) 3082418720 This explains why the non-Unicode version is so much faster in your test than the Unicode version. The actual code for this is string_concatenate in Python/ceval.c, and works for both s1 = s1 + s2 and s1 += s2. The function _PyString_Resize in Objects/stringobject.c also says explicitly: The following function breaks the notion that strings are immutable. See also http://bugs.python.org/issue980695. A: My guess is that Python just does a realloc on the string rather than create a new one with a copy of the old one. Since realloc takes no time when there is enough empty space following the allocation, it is very fast. So how come Python can call realloc and Java can't? Python's garbage collector uses reference counting so it can tell that nobody else is using the string and it won't matter if the string changes. Java's garbage collector doesn't maintain reference counts so it can't tell whether any other reference to the string is extant, meaning it has no choice but to create a whole new copy of the string on every concatenation. EDIT: Although I don't know that Python actually does call realloc on a concat, here's the comment for _PyString_Resize in stringobject.c indicating why it can: The following function breaks the notion that strings are immutable: it changes the size of a string. We get away with this only if there is only one module referencing the object. You can also think of it as creating a new string object and destroying the old one, only more efficiently. In any case, don't use this if the string may already be known to some other part of the code... A: I don't think your test means a lot, since Java and Python handle strings differently (I am no expert in Python but I do know my way in Java). StringBuilders/Buffers exists for a reason in Java. The language designers didn't do any kind of more efficient memory management/manipulation exactly for this reason: there are other tools than the "String" object to do this kind of manipulation and they expect you to use them when you code. When you do things the way they are meant to be done in Java, you will be surprised how fast the platform is... But I have to admit that I have been pretty much impressed by the performance of some Python applications I have tried recently. A: I do not know the answer for sure. But here are some thoughts. First, Java internally stores strings as char [] arrays containing the UTF-16 encoding of the string. This means that every character in the strings takes at least two bytes. So just in terms of raw storage, Java would have to copy around twice as much data as python strings. Python unicode strings are therefore the better test because they are similarly capable. Perhaps python stores unicode strings as UTF-8 encoded bytes. In that case, if all you are storing in these are ASCII characters, then again you'd have Java using twice as much space and therefore doing twice as much copying. To get a better comparison you should concatenate strings containing more interesting characters that require two or more bytes in their UTF-8 encoding. A: I ran Java code with a StringBuilder in place of a String and saw an average finish time of 10ms (high 34ms, low 5ms). As for the Python code, using "Method 6" here (found to be the fastest method), I was able to achieve an average of 84ms (high 91ms, low 81ms) using unicode strings. Using non-unicode strings reduced these numbers by ~25ms. As such, it can be said based on these highly unscientific tests that using the fastest available method for string concatenation, Java is roughly an order of magnitude faster than Python. But I still <3 Python ;)
Performance comparison of immutable string concatenation between Java and Python
UPDATES: thanks a lot to Gabe and Glenn for the detailed explanation. The test is wrote not for language comparison benchmark, just for my studying on VM optimization technologies. I did a simple test to understand the performance of string concatenation between Java and Python. The test is target for the default immutable String object/type in both languages. So I don't use StringBuilder/StringBuffer in Java test. The test simply adds strings for 100k times. Java consumes ~32 seconds to finish, while Python only uses ~13 seconds for Unicode string and 0.042 seconds for non Unicode string. I'm a bit surprise about the results. I thought Java should be faster than Python. What optimization technology does Python leverage to achieve better performance? Or String object is designed too heavy in Java? OS: Ubuntu 10.04 x64 JDK: Sun 1.6.0_21 Python: 2.6.5 Java test did use -Xms1024m to minimize GC activities. Java code: public class StringConcateTest { public static void test(int n) { long start = System.currentTimeMillis(); String a = ""; for (int i = 0; i < n; i++) { a = a.concat(String.valueOf(i)); } long end = System.currentTimeMillis(); System.out.println(a.length() + ", time:" + (end - start)); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { test(1000 * 100); } } } Python code: import time def f(n): start = time.time() a = u'' #remove u to use non Unicode string for i in xrange(n): a = a + str(i) print len(a), 'time', (time.time() - start)*1000.0 for j in xrange(10): f(1000 * 100)
[ "@Gabe's answer is correct, but needs to be shown clearly rather than hypothesized.\nCPython (and probably only CPython) does an in-place string append when it can. There are limitations on when it can do this.\nFirst, it can't do it for interned strings. That's why you'll never see this if you test with a = \"te...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "concatenation", "java", "performance", "python", "string" ]
stackoverflow_0003901124_concatenation_java_performance_python_string.txt
Q: gnuplot syntax error when using python I am just about to find out how python and gnuplot work together. On http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module I found an introduction and I wanted to execute it on my Ubuntu machine. import Gnuplot gp = Gnuplot.Gnuplot(persist = 1) gp('set data style lines') # The first data set (a quadratic) data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]] # The second data set (a straight line) data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]] plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic") plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title gp.plot(plot1, plot2) However, I get the following error message: ./demo.py ./demo.py: line 2: syntax error near unexpected token `(' ./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)' any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package? A: Did you put the bangline in the first line? i.e: #!/usr/bin/python Looks like it is not the Python interpreter who is executing the file. A: Well the python interpreter thinks that while parsing there was an syntax error. Check again your quotes, make sure that for convenience sake you only use either double or single quotes in your entire script (except of course when you need to put in a literal quote like "'" or '"'). If you are unsure what goes wrong what you can do is open the interactive interpreter and write each line in there. A: Your demo.py file is somehow corrupted - make sure that the open-parenthesis character is really that. Grub the installer from the project page to make sure. You can access the current SVN version of the file (choose download of the HEAD revision). A: If I copy and paste your code into Emacs I get this: gp = Gnuplot.Gnuplot(persist = 1) gp('set data style lines') data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]] # The first data set (a quadratic) data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]] # The second data set (a straight line) plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic") plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title gp.plot(plot1, plot2) If I remove the whitespaces at the beginning of the three lines it works for me.
gnuplot syntax error when using python
I am just about to find out how python and gnuplot work together. On http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module I found an introduction and I wanted to execute it on my Ubuntu machine. import Gnuplot gp = Gnuplot.Gnuplot(persist = 1) gp('set data style lines') # The first data set (a quadratic) data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]] # The second data set (a straight line) data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]] plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic") plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title gp.plot(plot1, plot2) However, I get the following error message: ./demo.py ./demo.py: line 2: syntax error near unexpected token `(' ./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)' any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package?
[ "Did you put the bangline in the first line? i.e:\n#!/usr/bin/python\n\nLooks like it is not the Python interpreter who is executing the file.\n", "Well the python interpreter thinks that while parsing there was an syntax error.\nCheck again your quotes, make sure that for convenience sake you only use either dou...
[ 2, 0, 0, 0 ]
[ "I've been using pylab instead. Pylab homepage\nFrom debian repos:\npython-matplotlib - Python based plotting system in a style similar to Matlab.\n\n" ]
[ -1 ]
[ "gnuplot", "python" ]
stackoverflow_0001037919_gnuplot_python.txt
Q: Characters not making it from a master to a slave pseudo-terminal I am currently trying to send binary data out through pexpect. For some reason, the data gets through just find except for a 0x04, which is just skipped over. I tracked down the pexpect call to determine that all thats happening is an os.write() call to a file descriptor opened from a pty.fork() command. Any ideas? (example code that exemplifies the problem) import os, pty, sys pid, child_fd = pty.fork() if pid: # Parent os.write(child_fd, b"'\x04hmm\x04'\n") buf = os.read(child_fd, 100) print buf else: # Child text = sys.stdin.readline() print ''.join(["%02X " % ord(x) for x in text]) Result: $ python test.py 'hmm' 27 68 6D 6D 27 0A A: 0x04 is ^D, which is the end-of-file keypress. Has the pty been set in raw mode? Maybe the driver is eating it. If you make it: os.write(child_fd, b"'\x04hmm\x16\x04'\n") you can see that indeed the driver is doing translation. \x16 is the same as ^V, which is how you quote things. It makes sense the translation would only be happening from the master (the pretend physical terminal) and the slave. The pretend physical terminal is where (on a normal terminal device) the person would be typing I'm not sure how to get the driver to stop doing that. If the child sets its terminal to raw mode then that will likely do it.
Characters not making it from a master to a slave pseudo-terminal
I am currently trying to send binary data out through pexpect. For some reason, the data gets through just find except for a 0x04, which is just skipped over. I tracked down the pexpect call to determine that all thats happening is an os.write() call to a file descriptor opened from a pty.fork() command. Any ideas? (example code that exemplifies the problem) import os, pty, sys pid, child_fd = pty.fork() if pid: # Parent os.write(child_fd, b"'\x04hmm\x04'\n") buf = os.read(child_fd, 100) print buf else: # Child text = sys.stdin.readline() print ''.join(["%02X " % ord(x) for x in text]) Result: $ python test.py 'hmm' 27 68 6D 6D 27 0A
[ "0x04 is ^D, which is the end-of-file keypress. Has the pty been set in raw mode? Maybe the driver is eating it.\nIf you make it:\nos.write(child_fd, b\"'\\x04hmm\\x16\\x04'\\n\")\n\nyou can see that indeed the driver is doing translation. \\x16 is the same as ^V, which is how you quote things. It makes sense th...
[ 2 ]
[]
[]
[ "pty", "python", "unix" ]
stackoverflow_0003901658_pty_python_unix.txt
Q: Following the result of pressing a submit button in Python Mechanize So I have an authenticated site that I want to access via the mechanize module. I'm able to log in, and then go to the page I want. However, because the page recognizes that mechanize doesn't have javascript enabled, it wants me to click a submit button to get redirected to a non javascript part of the site. How can I simply click the button and then read the contents of the page that follows that? Or, is there a way to trick it into thinking that my javascript is enables? Thanks! A: if that submit button is really a submit input element of the form, and the redirection works as usual form submit action, and provided that it's the only form in the page, your mechanize browser instance is br, following should work br.select_form(nr=0) # select the first form br.submit() afaik, there's no simple or moderately possible way, how to emulate javascript in mechanize, possible workarounds depend on what is javascript exactly doing
Following the result of pressing a submit button in Python Mechanize
So I have an authenticated site that I want to access via the mechanize module. I'm able to log in, and then go to the page I want. However, because the page recognizes that mechanize doesn't have javascript enabled, it wants me to click a submit button to get redirected to a non javascript part of the site. How can I simply click the button and then read the contents of the page that follows that? Or, is there a way to trick it into thinking that my javascript is enables? Thanks!
[ "if that submit button is really a submit input element of the form, and the redirection works as usual form submit action, and provided that it's the only form in the page, your mechanize browser instance is br, following should work\nbr.select_form(nr=0) # select the first form\nbr.submit()\n\nafaik, there's no s...
[ 3 ]
[]
[]
[ "browser", "mechanize", "python" ]
stackoverflow_0003901218_browser_mechanize_python.txt
Q: pymongo (python+mongodb) drop collection/gridfs? Anyone know the commands to drop a collection of documents and also drop a gridfs database? A: To delete a collection, you can either call the drop() method on it, or use the drop_collection() method on the database object: my_collection = db['collection_name'] my_collection.drop() # Or... db.drop_collection('collection_name') GridFS files are stored in a collection called fs by default. To delete the GridFS files, just drop that collection: db.drop_collection('fs')
pymongo (python+mongodb) drop collection/gridfs?
Anyone know the commands to drop a collection of documents and also drop a gridfs database?
[ "To delete a collection, you can either call the drop() method on it, or use the drop_collection() method on the database object:\nmy_collection = db['collection_name']\nmy_collection.drop()\n\n# Or...\n\ndb.drop_collection('collection_name')\n\nGridFS files are stored in a collection called fs by default. To delet...
[ 11 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0003895572_mongodb_pymongo_python.txt
Q: how reduce the number of points of a waveform? I have this, f = audiolab.Sndfile('test.wav', 'r') data = f.read_frames(f.nframes, dtype=numpy.int16) pyplot.rcParams['figure.figsize'] = 10, 2 pyplot.plot(data) pyplot.xticks([]) pyplot.yticks([]) pyplot.show() but the ploting is slow and freeze the pc, hoy I can reduce the numbers of points or how can I increase the performance of the code? A: Use something like NumPy to resample the data to a lower frequency before adding it to the plot. A: You could take (roughly) 1000 evenly spaced points from your data this way: n = len(data) pyplot.plot(data[::n/1000])
how reduce the number of points of a waveform?
I have this, f = audiolab.Sndfile('test.wav', 'r') data = f.read_frames(f.nframes, dtype=numpy.int16) pyplot.rcParams['figure.figsize'] = 10, 2 pyplot.plot(data) pyplot.xticks([]) pyplot.yticks([]) pyplot.show() but the ploting is slow and freeze the pc, hoy I can reduce the numbers of points or how can I increase the performance of the code?
[ "Use something like NumPy to resample the data to a lower frequency before adding it to the plot.\n", "You could take (roughly) 1000 evenly spaced points from your data this way:\nn = len(data)\npyplot.plot(data[::n/1000])\n\n" ]
[ 0, 0 ]
[]
[]
[ "audio", "python", "waveform" ]
stackoverflow_0003901324_audio_python_waveform.txt
Q: Installing rpy2 -2.1.5 on Mac OS X 10.5.8 fails I've searched far and wide, read a previous question in stackoverflow but cant seem to solve the problem of installing rpy2 on my Mac with OS X 10.5.8. I have Xcode 3.1.4 installed and R 2.1.11. when I run: sudo python setup.py build install I get this: running build running build_py running build_ext building 'rpy2.rinterface.rinterface' extension gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch ppc -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DR_INTERFACE_PTRS=1 -DHAVE_POSIX_SIGJMP=1 -DCSTACK_DEFNS=1 -DRIF_HAS_RSIGHAND=1 -Irpy/rinterface -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -c rpy/rinterface/rinterface.c -o build/temp.macosx-10.5-fat3-2.7/rpy/rinterface/rinterface.o -F/Library/Frameworks/R.framework/.. -framework R -L/Library/Frameworks/R.framework/Resources/lib/i386 -lRlapack -L/Library/Frameworks/R.framework/Resources/lib/i386 -lRblas i686-apple-darwin9-gcc-4.0.1: -lRlapack: linker input file unused because linking not done i686-apple-darwin9-gcc-4.0.1: -lRblas: linker input file unused because linking not done i686-apple-darwin9-gcc-4.0.1: -lRlapack: linker input file unused because linking not done i686-apple-darwin9-gcc-4.0.1: -lRblas: linker input file unused because linking not done powerpc-apple-darwin9-gcc-4.0.1: -lRlapack: linker input file unused because linking not done powerpc-apple-darwin9-gcc-4.0.1: -lRblas: linker input file unused because linking not done gcc-4.0 -arch i386 -arch ppc -arch x86_64 -isysroot / -g -bundle -undefined dynamic_lookup build/temp.macosx-10.5-fat3-2.7/rpy/rinterface/rinterface.o -L-F/Library/Frameworks/R.framework/.. -L-framework -LR -L/Library/Frameworks/R.framework/Resources/modules -L-F/Library/Frameworks/R.framework/.. -L-framework -LR L/Library/Frameworks/R.framework/Resources/modules -lR -o build/lib.macosx-10.5-fat3-2.7/rpy2/rinterface/rinterface.so ld: library not found for -lR ld: library not found for -lR collect2: ld returned 1 exit status ldcollect2: : library ld returned 1 exit status not found for -lR collect2: ld returned 1 exit status lipo: can't open input file: /var/tmp//ccFngK8H.out (No such file or directory) error: command 'gcc-4.0' failed with exit status 1 any help would be greatly appreciated. A: Can you try a snapshot from the mercurial repository ? (either branch version_2.1.x - future version 2.1.6 -, or version_2.2.x - future version 2.2.0) The build procedure has been streamlined and should accomodate better OS X.
Installing rpy2 -2.1.5 on Mac OS X 10.5.8 fails
I've searched far and wide, read a previous question in stackoverflow but cant seem to solve the problem of installing rpy2 on my Mac with OS X 10.5.8. I have Xcode 3.1.4 installed and R 2.1.11. when I run: sudo python setup.py build install I get this: running build running build_py running build_ext building 'rpy2.rinterface.rinterface' extension gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch ppc -arch x86_64 -g -O2 -DNDEBUG -g -O3 -DR_INTERFACE_PTRS=1 -DHAVE_POSIX_SIGJMP=1 -DCSTACK_DEFNS=1 -DRIF_HAS_RSIGHAND=1 -Irpy/rinterface -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -c rpy/rinterface/rinterface.c -o build/temp.macosx-10.5-fat3-2.7/rpy/rinterface/rinterface.o -F/Library/Frameworks/R.framework/.. -framework R -L/Library/Frameworks/R.framework/Resources/lib/i386 -lRlapack -L/Library/Frameworks/R.framework/Resources/lib/i386 -lRblas i686-apple-darwin9-gcc-4.0.1: -lRlapack: linker input file unused because linking not done i686-apple-darwin9-gcc-4.0.1: -lRblas: linker input file unused because linking not done i686-apple-darwin9-gcc-4.0.1: -lRlapack: linker input file unused because linking not done i686-apple-darwin9-gcc-4.0.1: -lRblas: linker input file unused because linking not done powerpc-apple-darwin9-gcc-4.0.1: -lRlapack: linker input file unused because linking not done powerpc-apple-darwin9-gcc-4.0.1: -lRblas: linker input file unused because linking not done gcc-4.0 -arch i386 -arch ppc -arch x86_64 -isysroot / -g -bundle -undefined dynamic_lookup build/temp.macosx-10.5-fat3-2.7/rpy/rinterface/rinterface.o -L-F/Library/Frameworks/R.framework/.. -L-framework -LR -L/Library/Frameworks/R.framework/Resources/modules -L-F/Library/Frameworks/R.framework/.. -L-framework -LR L/Library/Frameworks/R.framework/Resources/modules -lR -o build/lib.macosx-10.5-fat3-2.7/rpy2/rinterface/rinterface.so ld: library not found for -lR ld: library not found for -lR collect2: ld returned 1 exit status ldcollect2: : library ld returned 1 exit status not found for -lR collect2: ld returned 1 exit status lipo: can't open input file: /var/tmp//ccFngK8H.out (No such file or directory) error: command 'gcc-4.0' failed with exit status 1 any help would be greatly appreciated.
[ "Can you try a snapshot from the mercurial repository ?\n(either branch version_2.1.x - future version 2.1.6 -, or version_2.2.x - future version 2.2.0)\nThe build procedure has been streamlined and should accomodate better OS X.\n" ]
[ 1 ]
[]
[]
[ "macos", "python", "r", "rpy2" ]
stackoverflow_0003900790_macos_python_r_rpy2.txt
Q: I'm new to python, and trying to program a sales tax button for a calculator I just started programming in python not long ago, and I'm having trouble figuring out the rounding issue when it comes to tax and money. I can't seem to get decimals to always round up to the nearest hundredths place. for instance, in our state, sales takes is 9.5%, so a purchase of 5 dollars would make tax $.48, but in reality its $.475. I've tried math.ceil, but it seems like that only works to the nearest integer. Is there a simple way to enable a round up on any thousands digit? (ex .471 would round to .48) Thanks A: For money amounts it is better to use Python's decimal, where you don't have problems with floating-point representation and the numbers will keep rounded to two decimals (cents). import decimal def calculateVat(price): VAT = decimal.Decimal('0.095') return (price * VAT).quantize(price, rounding=decimal.ROUND_UP) price = decimal.Decimal('5.00') # calculateVat(price) returns: # Decimal('0.48') A: You might want to rethink how you're representing your numbers. It might be best to represent all values as integers and then format them later when you need to print or display your output. This will give you the freedom of not worrying about floating-point errors and additionally will let you use math.ceil. A: To round to 2 digits, use round: round(5*0.095,2) EDIT: I see now that you wanted to round up. For that, I think you'll have to go with math.ceil(100*x)/100. A: Doug Hellmann has an awesome blog called Python Module of the Week where he breaks down a module in the Python library in very clear detail. I think his post on the module math might be worth taking a look at: http://www.doughellmann.com/PyMOTW/math/ A: i think that fix is the thing you're looking for: >>> from fpformat import fix >>> fix('4.75', 1) '4.8' >>> fix('4.75', 2) '4.75' >>> fix('4.75', 3) '4.750' >>> then if you need to use it, you can use float()
I'm new to python, and trying to program a sales tax button for a calculator
I just started programming in python not long ago, and I'm having trouble figuring out the rounding issue when it comes to tax and money. I can't seem to get decimals to always round up to the nearest hundredths place. for instance, in our state, sales takes is 9.5%, so a purchase of 5 dollars would make tax $.48, but in reality its $.475. I've tried math.ceil, but it seems like that only works to the nearest integer. Is there a simple way to enable a round up on any thousands digit? (ex .471 would round to .48) Thanks
[ "For money amounts it is better to use Python's decimal, where you don't have problems with floating-point representation and the numbers will keep rounded to two decimals (cents).\nimport decimal\n\ndef calculateVat(price):\n VAT = decimal.Decimal('0.095')\n return (price * VAT).quantize(price, rounding=deci...
[ 6, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003901444_python.txt
Q: Finding combination in Python without importing itertools I want following task to be done in Python without importing any modules. My Code consists Two List --------- list1=['aun','2ab','acd','3aa'] list2=['ca3','ba2','dca','aa3'] Function --------- Where it will: Generates 2 items combination from list1 Generates 2 items combination from list2 Generates 2 items combination from list1 and list2 I don't need to print these all combinations of two items But I want to pass all these 2 items combinations to further task and show results analysize R.. **ca3** .... and ... **2ab** // Combinations of two items from list1 and list2 Print analysize A: Well, you already got the answer how to do it with itertools. If you want to do it without importing that module (for whatever reason...), you could still take a look at the docs and read the source: def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) and def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices)
Finding combination in Python without importing itertools
I want following task to be done in Python without importing any modules. My Code consists Two List --------- list1=['aun','2ab','acd','3aa'] list2=['ca3','ba2','dca','aa3'] Function --------- Where it will: Generates 2 items combination from list1 Generates 2 items combination from list2 Generates 2 items combination from list1 and list2 I don't need to print these all combinations of two items But I want to pass all these 2 items combinations to further task and show results analysize R.. **ca3** .... and ... **2ab** // Combinations of two items from list1 and list2 Print analysize
[ "Well, you already got the answer how to do it with itertools. If you want to do it without importing that module (for whatever reason...), you could still take a look at the docs and read the source:\ndef product(*args, **kwds):\n # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy\n # product(range(2), repe...
[ 6 ]
[]
[]
[ "combinations", "python" ]
stackoverflow_0003902009_combinations_python.txt
Q: Calling C# object from IronPython I have the following C# code to compile it into MyMath.dll assembly. namespace MyMath { public class Arith { public Arith() {} public int Add(int x, int y) { return x + y; } } } And I have the following IronPython code to use this object. import clr clr.AddReferenceToFile("MyMath.dll") import MyMath arith = Arith() print arith.Add(10,20) When I run this code with IronPython, I get the following error. Traceback (most recent call last): File ipycallcs, line unknown, in Initialize NameError: name 'Arith' is not defined What might be wrong? ADDED arith = Arith() should have been arith = MyMath.Arith() A: You should be doing the following: from MyMath import Arith Or: from MyMath import * Otherwise, you'll have to refer to the Arith class as MyMath.Arith.
Calling C# object from IronPython
I have the following C# code to compile it into MyMath.dll assembly. namespace MyMath { public class Arith { public Arith() {} public int Add(int x, int y) { return x + y; } } } And I have the following IronPython code to use this object. import clr clr.AddReferenceToFile("MyMath.dll") import MyMath arith = Arith() print arith.Add(10,20) When I run this code with IronPython, I get the following error. Traceback (most recent call last): File ipycallcs, line unknown, in Initialize NameError: name 'Arith' is not defined What might be wrong? ADDED arith = Arith() should have been arith = MyMath.Arith()
[ "You should be doing the following:\nfrom MyMath import Arith\n\nOr:\nfrom MyMath import *\n\nOtherwise, you'll have to refer to the Arith class as MyMath.Arith.\n" ]
[ 6 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0003902018_c#_ironpython_python.txt
Q: How to detect CPU speed and H.D.D rpm in objective-c or python I'm new to objective-c, for an academic reason I need to read CPU speed and H.D.D rpm What is the simplest way to access some system setting in objective-c or python I can choose between objective-c and python for this project. A: I think you would have to use a C++ module with Python to detect CPU speed or RPM of a hard drive. Calculate total CPU usage could help you here I don't know anything about Obj-C, so couldn't tell you if it is possible with that language! A: This can get the reported CPU speed for Windows 2000 and up by reading the registry using python: import _winreg key = _winreg.OpenKey( _winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") value, type = _winreg.QueryValueEx(key, "~MHz") print 'CPU speed is:', value I don't know how to do it for other operating systems nor how to get the HDD rpms though. A: Checking CPU speed isn't really an Objective C thing, it is an OS thing. On OS X (and I assume iOS) you want to look at sysctlbyname(3) and the hw.cpufrequency property, something like: int hz; size_t hz_size = sizeof(hz); int rc = sysctlbyname("hw.cpufrequency", &hz, &hz_size, NULL, 0); if (0 == rc) { fprintf(stderr, "Clockspeed is %d hz\n", hz); } I don't know a good way to get the RPM of a disk drive, but I do know a bad way. Parse the output of system_profiler, the info is in there (as "Rotational Rate"): Hitachi HTS543232L9SA02: Capacity: 320.07 GB (320,072,933,376 bytes) Model: Hitachi HTS543232L9SA02 Revision: FB4AC50F Serial Number: (omitted) Native Command Queuing: Yes Queue Depth: 32 Removable Media: No Detachable Drive: No BSD Name: disk0 Rotational Rate: 5400 Medium Type: Rotational Partition Map Type: GPT (GUID Partition Table) S.M.A.R.T. status: Verified Volumes: Macintosh HD: Capacity: 319.73 GB (319,728,959,488 bytes) Available: 12.4 GB (12,397,940,736 bytes) Writable: Yes File System: Journaled HFS+ BSD Name: disk0s2 Mount Point: / There is likely a better abstraction to use, I just don't know it.
How to detect CPU speed and H.D.D rpm in objective-c or python
I'm new to objective-c, for an academic reason I need to read CPU speed and H.D.D rpm What is the simplest way to access some system setting in objective-c or python I can choose between objective-c and python for this project.
[ "I think you would have to use a C++ module with Python to detect CPU speed or RPM of a hard drive. Calculate total CPU usage could help you here\nI don't know anything about Obj-C, so couldn't tell you if it is possible with that language!\n", "This can get the reported CPU speed for Windows 2000 and up by readi...
[ 2, 1, 1 ]
[]
[]
[ "objective_c", "python", "system_setting" ]
stackoverflow_0003900345_objective_c_python_system_setting.txt
Q: findPattern() Python Code...not executing correctly? my homework assignment was to: "write a function called findPattern() which accepts two strings as parameters, a filename and a pattern. The function reads in the file specified by the given filename and searches the file’s contents for the given pattern. It then returns the line number and index of the line where the first instance of this pattern is found. If no match is found, your function should return -1 for both the line number and index." I was fairly certain that my code was accurate until it would execute the first commands and then just ignore the rest of the code. I tried a couple different ways of writing it, but all three yielded the result of...not working. I'll post the two relevant codes below: Code 1: def findPattern (filename, pattern): f=open(filename) linecount = 0 lettercount = 0 for line in f: lineCount +=1 for letter in range(len(line)): if line(letter)==pattern: letterCount+=1 return[lineCount,line] return "Did not find " + pattern Code 2: print filename = raw_input("Enter a file name: ") pattern = raw_input("Enter a pattern: ") def findPattern (filename,pattern): f=open(filename) lineCount = 0 letterCount = 0 for line in f: lineCount +=1 for letter in range(len(line)): if line(letter)==pattern: letterCount+=1 print ("Found pattern " + pattern + " at " + str((lineCount, letter))) I think code 2 would be more likely to work but it isn't yielding any results. Any input would be appriciated. -Thanks! A: Your variable names are misspelled: linecount vs. lineCount, lettern vs. letter. Python doesn't always warn against this type of error. If this is just a copying error, then line(letter) is the error: an index is given by []. What kind of pattern are you searching for, a single character or a string? line[letter] will only return a single character. Next time, please post not only the code and that it gives an error, but also what kind of error. Most Python errors result in exceptions being thrown (such as TypeError), which can tell you (and us) a lot about what's been going wrong. A: You're calling line as a function but it is a string. Use pattern.find(line) on each line to find your pattern.
findPattern() Python Code...not executing correctly?
my homework assignment was to: "write a function called findPattern() which accepts two strings as parameters, a filename and a pattern. The function reads in the file specified by the given filename and searches the file’s contents for the given pattern. It then returns the line number and index of the line where the first instance of this pattern is found. If no match is found, your function should return -1 for both the line number and index." I was fairly certain that my code was accurate until it would execute the first commands and then just ignore the rest of the code. I tried a couple different ways of writing it, but all three yielded the result of...not working. I'll post the two relevant codes below: Code 1: def findPattern (filename, pattern): f=open(filename) linecount = 0 lettercount = 0 for line in f: lineCount +=1 for letter in range(len(line)): if line(letter)==pattern: letterCount+=1 return[lineCount,line] return "Did not find " + pattern Code 2: print filename = raw_input("Enter a file name: ") pattern = raw_input("Enter a pattern: ") def findPattern (filename,pattern): f=open(filename) lineCount = 0 letterCount = 0 for line in f: lineCount +=1 for letter in range(len(line)): if line(letter)==pattern: letterCount+=1 print ("Found pattern " + pattern + " at " + str((lineCount, letter))) I think code 2 would be more likely to work but it isn't yielding any results. Any input would be appriciated. -Thanks!
[ "Your variable names are misspelled: linecount vs. lineCount, lettern vs. letter. Python doesn't always warn against this type of error. If this is just a copying error, then line(letter) is the error: an index is given by []. What kind of pattern are you searching for, a single character or a string? line[letter] ...
[ 1, 0 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003902102_design_patterns_python.txt
Q: resources for learning 3D basics (Python / JavaScript) While I consider myself a reasonably competent programmer, I have no experience with even the most basic graphics programming. Are there any recommended resources for learning the basics of 3D programming - preferably using a high-level language like Python or JavaScript? Ideally, I'd like a simple hello world example in canvas or WebGL with a space ship moving inside a cube (all wireframes). A: http://learningwebgl.com/blog/ A: Unity is what I recommend but I've also heard about (but never tried) Panda3D and Worldviz Vizard. If you want to build it from the ground up yourself you might try Pygame though you may have to hunt for the right libraries. Other things you might look at:VPython, and PyOpenGL.
resources for learning 3D basics (Python / JavaScript)
While I consider myself a reasonably competent programmer, I have no experience with even the most basic graphics programming. Are there any recommended resources for learning the basics of 3D programming - preferably using a high-level language like Python or JavaScript? Ideally, I'd like a simple hello world example in canvas or WebGL with a space ship moving inside a cube (all wireframes).
[ "http://learningwebgl.com/blog/\n", "Unity is what I recommend but I've also heard about (but never tried)\nPanda3D and Worldviz Vizard. If you want to build it from the ground up yourself you might try Pygame though you may have to hunt for the right libraries. Other things you might look at:VPython, and PyOpe...
[ 2, 1 ]
[]
[]
[ "3d", "canvas", "javascript", "python" ]
stackoverflow_0003902054_3d_canvas_javascript_python.txt
Q: How do I count words in an nltk plaintextcorpus faster? I have a set of documents, and I want to return a list of tuples where each tuple has the date of a given document and the number of times a given search term appears in that document. My code (below) works, but is slow, and I'm a n00b. Are there obvious ways to make this faster? Any help would be much appreciated, mostly so that I can learn better coding, but also so that I can get this project done faster! def searchText(searchword): counts = [] corpus_root = 'some_dir' wordlists = PlaintextCorpusReader(corpus_root, '.*') for id in wordlists.fileids(): date = id[4:12] month = date[-4:-2] day = date[-2:] year = date[:4] raw = wordlists.raw(id) tokens = nltk.word_tokenize(raw) text = nltk.Text(tokens) count = text.count(searchword) counts.append((month, day, year, count)) return counts A: If you just want a frequency of word counts, then you don't need to create nltk.Text objects, or even use nltk.PlainTextReader. Instead, just go straight to nltk.FreqDist. files = list_of_files fd = nltk.FreqDist() for file in files: with open(file) as f: for sent in nltk.sent_tokenize(f.lower()): for word in nltk.word_tokenize(sent): fd.inc(word) Or, if you don't want to do any analysis - just use a dict. files = list_of_files fd = {} for file in files: with open(file) as f: for sent in nltk.sent_tokenize(f.lower()): for word in nltk.word_tokenize(sent): try: fd[word] = fd[word]+1 except KeyError: fd[word] = 1 These could be made much more efficient with generator expressions, but I'm used for loops for readability.
How do I count words in an nltk plaintextcorpus faster?
I have a set of documents, and I want to return a list of tuples where each tuple has the date of a given document and the number of times a given search term appears in that document. My code (below) works, but is slow, and I'm a n00b. Are there obvious ways to make this faster? Any help would be much appreciated, mostly so that I can learn better coding, but also so that I can get this project done faster! def searchText(searchword): counts = [] corpus_root = 'some_dir' wordlists = PlaintextCorpusReader(corpus_root, '.*') for id in wordlists.fileids(): date = id[4:12] month = date[-4:-2] day = date[-2:] year = date[:4] raw = wordlists.raw(id) tokens = nltk.word_tokenize(raw) text = nltk.Text(tokens) count = text.count(searchword) counts.append((month, day, year, count)) return counts
[ "If you just want a frequency of word counts, then you don't need to create nltk.Text objects, or even use nltk.PlainTextReader. Instead, just go straight to nltk.FreqDist.\nfiles = list_of_files\nfd = nltk.FreqDist()\nfor file in files:\n with open(file) as f:\n for sent in nltk.sent_tokenize(f.lower()):...
[ 8 ]
[]
[]
[ "corpus", "nlp", "nltk", "python" ]
stackoverflow_0003902044_corpus_nlp_nltk_python.txt
Q: Converting flat sequence to 2d sequence in python I have a piece of code that will return a flat sequence for every pixel in a image. import Image im = Image.open("test.png") print("Picture size is ", width, height) data = list(im.getdata()) for n in range(width*height): if data[n] == (0, 0, 0): print(data[n], n) This codes returns something like this ((0, 0, 0), 1250) ((0, 0, 0), 1251) ((0, 0, 0), 1252) ((0, 0, 0), 1253) ((0, 0, 0), 1254) ((0, 0, 0), 1255) ((0, 0, 0), 1256) ((0, 0, 0), 1257) The first three values are the RGB of the pixel and the last one is the index in the sequence. Knowing the width and height of the image and the pixels index in sequence how can i convert that sequence back into a 2d sequence? A: Simple math: you have n, width, height and want x, y x, y = n % width, n / width or (does the same but more efficient) y, x = divmod(n, width) A: You could easily make a function that would emulate 2d data: def data2d(x,y,width): return data[y*width+x] But if you want to put the data in a 2dish data structure, you could do something like this: data2d = [] for n in range(height): datatmp = [] for m in rante(width): datatmp.append(data[n*width+m]) data2d[n] = datatmp You may need to do a deep copy in that last line. This will make data2d a list of lists so you can access the pixel in row, column as data[row][column].
Converting flat sequence to 2d sequence in python
I have a piece of code that will return a flat sequence for every pixel in a image. import Image im = Image.open("test.png") print("Picture size is ", width, height) data = list(im.getdata()) for n in range(width*height): if data[n] == (0, 0, 0): print(data[n], n) This codes returns something like this ((0, 0, 0), 1250) ((0, 0, 0), 1251) ((0, 0, 0), 1252) ((0, 0, 0), 1253) ((0, 0, 0), 1254) ((0, 0, 0), 1255) ((0, 0, 0), 1256) ((0, 0, 0), 1257) The first three values are the RGB of the pixel and the last one is the index in the sequence. Knowing the width and height of the image and the pixels index in sequence how can i convert that sequence back into a 2d sequence?
[ "Simple math: you have n, width, height and want x, y\nx, y = n % width, n / width\n\nor (does the same but more efficient)\ny, x = divmod(n, width)\n\n", "You could easily make a function that would emulate 2d data:\ndef data2d(x,y,width):\n return data[y*width+x]\n\nBut if you want to put the data in a 2dish d...
[ 1, 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0003902306_image_python_python_imaging_library.txt
Q: What are methods of programmatically detecting many-to-many relationships in a RDMBS? I'm currently busy making a Python ORM which gets all of its information from a RDBMS via introspection (I would go with XRecord if I was happy with it in other respects) — meaning, the end-user only tells which tables/views to look at, and the ORM does everything else automatically (if it makes you actually write something and you're not looking for weird things and dangerous adventures, it's a bug). The major part of that is detecting relationships, provided that the database has all relevant constraints in place and you have no naming conventions at all — I want to be able to have this ORM work with a database made by any crazy DBA which has his own views on what the columns and tables should be named like. And I'm stuck at many-to-many relationships. First, there can be compound keys. Then, there can be MTM relationships with three or more tables. Then, a MTM intermediary table might have its own data apart from keys — some data common to all tables it ties together. What I want is a method to programmatically detect that a table X is an intermediary table tying tables A and B, and that any non-key data it has must belong to both A and B (and if I change a common attribute from within A, it should affect the same attribute in B). Are there common algorithms to do that? Or at least to make guesses which are right in 80% of the cases (provided the DBA is sane)? A: If you have to ask, you shouldn't be doing this. I'm not saying that to be cruel, but Python already has several excellent ORMs that are well-tested and widely used. For example, SQLAlchemy supports the autoload=True attribute when defining tables that makes it read the table definition - including all the stuff you're asking about - directly from the database. Why re-invent the wheel when someone else has already done 99.9% of the work? My answer is to pick a Python ORM (such as SQLAlchemy) and add any "missing" functionality to that instead of starting from scratch. If it turns out to be a good idea, release your changes back to the main project so that everyone else can benefit from them. If it doesn't work out like you hoped, at least you'll already be using a common ORM that many other programmers can help you with. A: Theoretically, any table with multiple foreign keys is in essence a many-to-many relation, which makes your question trivial. I suspect that what you need is a heuristic of when to use MTM patterns (rather than standard classes) in the object model. In that case, examine what are the limitations of the patterns you chose. For example, you can model a simple MTM relationship (two tables, no attributes) by having lists as attributes on both types of objects. However, lists will not be enough if you have additional data on the relationship itself. So only invoke this pattern for tables with two columns, both with foreign keys. A: So far, I see the only one technique covering more than two tables in relation. A table X is assumed related to table Y, if and only if X is referenced to Y no more than one table away. That is: "Zero tables away" means X contains the foreign key to Y. No big deal, that's how we detect many-to-ones. "One table away" means there is a table Z which itself has a foreign key referencing table X (these are easy to find), and a foreign key referencing table Y. This reduces the scope of traits to look for a lot (we don't have to care if the intermediary table has any other attributes), and it covers any number of tables tied together in a MTM relation. If there are some interesting links or other methods, I'm willing to hear them.
What are methods of programmatically detecting many-to-many relationships in a RDMBS?
I'm currently busy making a Python ORM which gets all of its information from a RDBMS via introspection (I would go with XRecord if I was happy with it in other respects) — meaning, the end-user only tells which tables/views to look at, and the ORM does everything else automatically (if it makes you actually write something and you're not looking for weird things and dangerous adventures, it's a bug). The major part of that is detecting relationships, provided that the database has all relevant constraints in place and you have no naming conventions at all — I want to be able to have this ORM work with a database made by any crazy DBA which has his own views on what the columns and tables should be named like. And I'm stuck at many-to-many relationships. First, there can be compound keys. Then, there can be MTM relationships with three or more tables. Then, a MTM intermediary table might have its own data apart from keys — some data common to all tables it ties together. What I want is a method to programmatically detect that a table X is an intermediary table tying tables A and B, and that any non-key data it has must belong to both A and B (and if I change a common attribute from within A, it should affect the same attribute in B). Are there common algorithms to do that? Or at least to make guesses which are right in 80% of the cases (provided the DBA is sane)?
[ "If you have to ask, you shouldn't be doing this. I'm not saying that to be cruel, but Python already has several excellent ORMs that are well-tested and widely used. For example, SQLAlchemy supports the autoload=True attribute when defining tables that makes it read the table definition - including all the stuff y...
[ 1, 0, 0 ]
[]
[]
[ "introspection", "metaprogramming", "orm", "python", "relationships" ]
stackoverflow_0003901961_introspection_metaprogramming_orm_python_relationships.txt
Q: Can't *copy* an index from list to another with a twist in Python I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for the "hero" to fight. The issue I am running into is that python is copying from list to list by reference, not value (I think), because of the code shown below... import random #ene = [HP,MAXHP,loDMG,hiDMG] enemies = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]] genENE = [] #skews # of ene's to be gen, favoring 1,2, and 3 eneAppears = 3 for i in range(0,eneAppears): num = random.randint(5,5) if num <= 5: genENE.insert(i,enemies[0]) elif num >= 6 and num <=8: genENE.insert(i,enemies[1]) else: genENE.insert(i,enemies[2]) #genENE = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]] for i in range(0,eneAppears): if eneAppears == 1: print "A " + genENE[0][4] + " appears!" else: while i < eneAppears: print "A " + genENE[i][4] + " appears!" i = eneAppears genENE[1][0] = genENE[1][0] - 1 print genENE Basically I have a "master" list of enemies that I use to copy whatever one I want over into an index of another list during my first "for" loop. Normally the randomly generated numbers are 1 through 10, but the problem I'm having is more easily shown by forcing the same enemy to be inserted into my "copy" list several times. Basically when I try to subtract a value of an enemy with the same name in my "copy" list, they all subtract that value (see last two lines of code). I've done a lot of searching and cannot find a way to copy just a single index from one list to another. Any suggestions? Thanks! A: Change genENE.insert(i,enemies[0]) to genENE.insert(i,enemies[0][:]) This will force the list to be copied rather than referenced. Also, I would use append rather than insert in this instance. A: they all subtract that value What do you mean do they all? If you mean both lists, you're problem is because you're only referencing the list NOT creating a second one.
Can't *copy* an index from list to another with a twist in Python
I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for the "hero" to fight. The issue I am running into is that python is copying from list to list by reference, not value (I think), because of the code shown below... import random #ene = [HP,MAXHP,loDMG,hiDMG] enemies = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]] genENE = [] #skews # of ene's to be gen, favoring 1,2, and 3 eneAppears = 3 for i in range(0,eneAppears): num = random.randint(5,5) if num <= 5: genENE.insert(i,enemies[0]) elif num >= 6 and num <=8: genENE.insert(i,enemies[1]) else: genENE.insert(i,enemies[2]) #genENE = [[8,8,1,5,"Ene1"],[9,9,3,6,"Ene2"],[15,15,2,8,"Ene3"]] for i in range(0,eneAppears): if eneAppears == 1: print "A " + genENE[0][4] + " appears!" else: while i < eneAppears: print "A " + genENE[i][4] + " appears!" i = eneAppears genENE[1][0] = genENE[1][0] - 1 print genENE Basically I have a "master" list of enemies that I use to copy whatever one I want over into an index of another list during my first "for" loop. Normally the randomly generated numbers are 1 through 10, but the problem I'm having is more easily shown by forcing the same enemy to be inserted into my "copy" list several times. Basically when I try to subtract a value of an enemy with the same name in my "copy" list, they all subtract that value (see last two lines of code). I've done a lot of searching and cannot find a way to copy just a single index from one list to another. Any suggestions? Thanks!
[ "Change\ngenENE.insert(i,enemies[0])\n\nto\ngenENE.insert(i,enemies[0][:])\n\nThis will force the list to be copied rather than referenced. Also, I would use append rather than insert in this instance.\n", "they all subtract that value What do you mean do they all? If you mean both lists, you're problem is beca...
[ 1, 0 ]
[]
[]
[ "copy", "indexing", "list", "python" ]
stackoverflow_0003902608_copy_indexing_list_python.txt
Q: Jython/Grinder/Grinderstone: self arg can't be coerced to net.grinder.plugin.http.HTTPUtilities A grinder script i have been building out for the past few days has been working pretty well up until just now. I am getting a runtime error initially saying: self.token___LASTFOCUS = HTTPUtilities.valueFromHiddenInput('__LASTFOCUS') TypeError: valueFromHiddenInput(): expected 2-3 args; got 1 so i added [another arg][1], something i knew would be at the beginning of the script, and got a slightly more useful error. Although now I am not sure what to do with this self.token___LASTFOCUS = HTTPUtilities.valueFromHiddenInput('__LASTFOCUS', '') TypeError: valueFromHiddenInput(): self arg can't be coerced to net.grinder.plugin.http.HTTPUtilities Any idea why 'self' isn't being coerced? [1]: http://grinder.sourceforge.net/g3/script-javadoc/net/grinder/plugin/http/HTTPUtilities.html#valueFromHiddenInput(java.lang.String, java.lang.String) A: found the answer i needed these lines from net.grinder.plugin.http import HTTPPluginControl httpUtilities = HTTPPluginControl.getHTTPUtilities() It looks like HTTPUtilities might be a singleton or has a factory method. Not to sure on what that specific architecture is.
Jython/Grinder/Grinderstone: self arg can't be coerced to net.grinder.plugin.http.HTTPUtilities
A grinder script i have been building out for the past few days has been working pretty well up until just now. I am getting a runtime error initially saying: self.token___LASTFOCUS = HTTPUtilities.valueFromHiddenInput('__LASTFOCUS') TypeError: valueFromHiddenInput(): expected 2-3 args; got 1 so i added [another arg][1], something i knew would be at the beginning of the script, and got a slightly more useful error. Although now I am not sure what to do with this self.token___LASTFOCUS = HTTPUtilities.valueFromHiddenInput('__LASTFOCUS', '') TypeError: valueFromHiddenInput(): self arg can't be coerced to net.grinder.plugin.http.HTTPUtilities Any idea why 'self' isn't being coerced? [1]: http://grinder.sourceforge.net/g3/script-javadoc/net/grinder/plugin/http/HTTPUtilities.html#valueFromHiddenInput(java.lang.String, java.lang.String)
[ "found the answer i needed these lines\nfrom net.grinder.plugin.http import HTTPPluginControl\nhttpUtilities = HTTPPluginControl.getHTTPUtilities()\n\nIt looks like HTTPUtilities might be a singleton or has a factory method.\nNot to sure on what that specific architecture is.\n" ]
[ 1 ]
[]
[]
[ "grinder", "java", "jython", "python" ]
stackoverflow_0003902029_grinder_java_jython_python.txt
Q: Python, is it proper for one thread to spawn another I am writing an update application in Python 2.x. I have one thread (ticket_server) sitting on a database (CouchDB) url in longpoll mode. Update requests are dumped into this database from an outside application. When a change comes, ticket_server triggers a worker thread (update_manager). The heavy lifting is done in this update_manager thread. There will be telnet connections and ftp uploads performed. So it is of highest importance that this process not be interrupted. My question is, is it safe to spawn update_manager threads from the ticket_server threads? The other option might be to put requests into a queue, and have another function wait for a ticket to enter the queue and then pass the request off to an update_manager thread. But, Id rather keeps tings simple (Im assuming the ticket_server spawning update_manager is simple) until I have a reason to expand. # Here is the heavy lifter class Update_Manager(threading.Thread): def __init__(self) threading.Thread.__init__(self, ticket, telnet_ip, ftp_ip) self.ticket = ticket self.telnet_ip = telnet_ip self.ftp_ip = ftp_ip def run(self): # This will be a very lengthy process. self.do_some_telnet() self.do_some_ftp() def do_some_telnet(self) ... def do_some_ftp(self) ... # This guy just passes work orders off to Update_Manager class Ticket_Server(threading.Thread): def __init__(self) threading.Thread.__init__(self, database_ip) self.database_ip def run(self): # This function call will block this thread only. ticket = self.get_ticket(database_ip) # Here is where I question what to do. # Should I 1) call the Update thread right from here... up_man = Update_Manager(ticket) up_man.start # Or should I 2) put the ticket into a queue and let some other function # not in this thread fire the Update_Manager. def get_ticket() # This function will 'wait' for a ticket to get posted. # for those familiar with couchdb: url = 'http://' + database_ip:port + '/_changes?feed=longpoll&since=' + update_seq response = urllib2.urlopen(url) This is just a lot of code to ask which approach is the safer/more efficient/more pythonic Im only a few months old with python so these question get my brain stuck in a while loop. A: The main thread of a program is a thread; the only way to spawn a thread is from another thread. Of course, you need to make sure your blocking thread is releasing the GIL while it waits, or other Python threads won't run. All mature Python database bindings will do this, but I've never heard of couchdb.
Python, is it proper for one thread to spawn another
I am writing an update application in Python 2.x. I have one thread (ticket_server) sitting on a database (CouchDB) url in longpoll mode. Update requests are dumped into this database from an outside application. When a change comes, ticket_server triggers a worker thread (update_manager). The heavy lifting is done in this update_manager thread. There will be telnet connections and ftp uploads performed. So it is of highest importance that this process not be interrupted. My question is, is it safe to spawn update_manager threads from the ticket_server threads? The other option might be to put requests into a queue, and have another function wait for a ticket to enter the queue and then pass the request off to an update_manager thread. But, Id rather keeps tings simple (Im assuming the ticket_server spawning update_manager is simple) until I have a reason to expand. # Here is the heavy lifter class Update_Manager(threading.Thread): def __init__(self) threading.Thread.__init__(self, ticket, telnet_ip, ftp_ip) self.ticket = ticket self.telnet_ip = telnet_ip self.ftp_ip = ftp_ip def run(self): # This will be a very lengthy process. self.do_some_telnet() self.do_some_ftp() def do_some_telnet(self) ... def do_some_ftp(self) ... # This guy just passes work orders off to Update_Manager class Ticket_Server(threading.Thread): def __init__(self) threading.Thread.__init__(self, database_ip) self.database_ip def run(self): # This function call will block this thread only. ticket = self.get_ticket(database_ip) # Here is where I question what to do. # Should I 1) call the Update thread right from here... up_man = Update_Manager(ticket) up_man.start # Or should I 2) put the ticket into a queue and let some other function # not in this thread fire the Update_Manager. def get_ticket() # This function will 'wait' for a ticket to get posted. # for those familiar with couchdb: url = 'http://' + database_ip:port + '/_changes?feed=longpoll&since=' + update_seq response = urllib2.urlopen(url) This is just a lot of code to ask which approach is the safer/more efficient/more pythonic Im only a few months old with python so these question get my brain stuck in a while loop.
[ "The main thread of a program is a thread; the only way to spawn a thread is from another thread.\nOf course, you need to make sure your blocking thread is releasing the GIL while it waits, or other Python threads won't run. All mature Python database bindings will do this, but I've never heard of couchdb.\n" ]
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003902696_multithreading_python.txt
Q: How to change default django User model to fit my needs? The default Django's User model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not? I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the User class, as it gives me an easy way to have parts of site restricted only for users logged in. How do I do it? A: Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields. For one site I used the "first_name" field as the "publicly displayed name" of a user and stuff a slugified version of that into the "username" field (for use in URLs). I wrote a custom auth backend to allow people to log in using their "public name" or their email address, and I enforce the uniqueness of both of those at registration time. This plays nicely with other reusable apps and doesn't introduce extra tables or queries. For another site I didn't want usernames at all, just unique emails. In order to satisfy Django's need for a unique username, I just hashed the email address and used that as the username (you have to base64-encode the hash to squeeze it under 30 characters). Custom auth backend to allow login with email. If backwards-compatibility weren't an issue, there are a lot of improvements I'd love to see made to django.contrib.auth and the User model to make them more flexible. But there's quite a lot you can do inside the current constraints with a little creativity. A: The Django User model is structured very sensibly. You really don't want to allow arbitrary characters in a username, for instance, and there are ways to achieve email address login, without hacking changes to the base model. To simply store additional information around a user account, Django supports the notion of user profiles. While you don't need to rely on the built in support to handle this, it is a convention that is commonly followed and it will allow you to play nice with the reusable Django apps that are floating around in the ether. For more information, see here. If you want to actually modify the core User model but also "play nice" with reusable apps that rely on it, you're opening a bit of a Pandora's Box. Developers make base assumptions about how the core library is structured, so any changes may cause unexpected breakage. Nonetheless, you can monkeypatch changes to the base model, or branch a copy of Django locally. I would discourage the latter, and only recommend the former if you know what you're doing. A: I misread the question. Hope this post is helpful to anyone else. #in models.py from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User) #other fields here def __str__(self): return "%s's profile" % self.user def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) #in settings.py AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile' This will create a userprofile each time a user is saved if it is created. You can then use user.get_profile().whatever Here is some more info from the docs http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users A: You face a bit of a dilemma which really has two solutions if you're committed to avoiding the profile-based customization already pointed out. Change the User model itself, per Daniel's suggestions Write a CustomUser class, subclassing User or copying its functionality. The latter suggestion means that you would have to implement some things that User does automatically manually, but I wonder whether that's as bad as it sounds, especially if you're at the beginning of your project. All you'd have to do is rewrite a middle-ware class and some decorators. Of course, I don't think this buys you anything that 1 won't get you, except that your project shouldn't break if you svn update your django. It may avoid some of the compatibility problems with other apps, but my guess is most problems will exist either way. A: There are anumber of ways to do this, but here's what I'd do: I'd allow a user to enter an email, username (which must contain at least one letter and no @ symbols) or mobile number. Then, when I validate it: Check for the presence of @. If so, set it as the user's email, hash it appropriately and set it as their username as well. Check to see if it's only numbers, dashes and +. Then, strip the appropriate characters and store it as both mobile number and username (if you're storing the mobile number in another model for SMS purposes or something). If it's not either, just set it as username. I'd also validate the user/phone/email field similarly on login and look in the appropriate place so that if, say, a user signs up with their mobile number and then changes their username (for some other purpose), they can still sign in with their mobile number.
How to change default django User model to fit my needs?
The default Django's User model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not? I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the User class, as it gives me an easy way to have parts of site restricted only for users logged in. How do I do it?
[ "Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields. \nFor one site I used the \"first_name\" field as the \"publicly displayed name\" of a user and stuff a slugified version of that into the \"username\" field (for use in URLs). I wrote a custom auth bac...
[ 10, 7, 7, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000896421_django_django_models_python.txt
Q: How to replace openSSL calls with C# code? Today I ran into a problem when I was making a new theme creator for chrome. As you may know, Chrome uses a "new" file format, called CRX, to manage it's plugins and themes. It is a basic zip file, but a bit modified: "Cr24" + derkey + signature + zipFile And here comes the problem. There are only two CRX creators, written in Ruby or Python. I don't know neither language too much (had some basic experience in Python though, but mostly with PyS60), so I would like to ask you to help me convert this python app to a C# code that doesn't depend on external programs. Also, here is the source of crxmake.py: #!/usr/bin/python # Cribbed from http://github.com/Constellation/crxmake/blob/master/lib/crxmake.rb # and http://src.chromium.org/viewvc/chrome/trunk/src/chrome/tools/extensions/chromium_extension.py?revision=14872&content-type=text/plain&pathrev=14872 # from: http://grack.com/blog/2009/11/09/packing-chrome-extensions-in-python/ import sys from array import * from subprocess import * import os import tempfile def main(argv): arg0,dir,key,output = argv # zip up the directory input = dir + ".zip" if not os.path.exists(input): os.system("cd %(dir)s; zip -r ../%(input)s . -x '.svn/*'" % locals()) else: print "'%s' already exists using it" % input # Sign the zip file with the private key in PEM format signature = Popen(["openssl", "sha1", "-sign", key, input], stdout=PIPE).stdout.read(); # Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header derkey = Popen(["openssl", "rsa", "-pubout", "-inform", "PEM", "-outform", "DER", "-in", key], stdout=PIPE).stdout.read(); out=open(output, "wb"); out.write("Cr24") # Extension file magic number header = array("l"); header.append(2); # Version 2 header.append(len(derkey)); header.append(len(signature)); header.tofile(out); out.write(derkey) out.write(signature) out.write(open(input).read()) os.unlink(input) print "Done." if __name__ == '__main__': main(sys.argv) Please could you help me? A: For Linux, there are a variety of utilities to do this - including one for bash - but it sounds like you want something for windows (guessing from your C# comment). I had tried to include links to all of them - but I am new stackoverflow user, and can only post 1 link.. Anyway, all of those can work in windows, however they require setup of the language interpreter and OpenSSL - so I spent a few hours and put together a version in C which runs on windows or linux (though, I'm not sure why you would use it in linux). It has OpenSSL statically linked so there are no interpreter or library requirements. The repository can be found here: http://github.com/kylehuff/buildcrx It should be noted, I do not use windows - this was written on Linux and the win32 binary was cross-compiled on Linux (as well as the OpenSSL libraries) - I did test it in windows - but not extensively. If you have trouble with it, please don't request support here; I will not respond. Use the issues page at the link above. Also, I will not convert this to C# - I can see no reason to use C# for such a simple utility and that would just perpetuate the need for "other software" in order for it be useful on other platforms.
How to replace openSSL calls with C# code?
Today I ran into a problem when I was making a new theme creator for chrome. As you may know, Chrome uses a "new" file format, called CRX, to manage it's plugins and themes. It is a basic zip file, but a bit modified: "Cr24" + derkey + signature + zipFile And here comes the problem. There are only two CRX creators, written in Ruby or Python. I don't know neither language too much (had some basic experience in Python though, but mostly with PyS60), so I would like to ask you to help me convert this python app to a C# code that doesn't depend on external programs. Also, here is the source of crxmake.py: #!/usr/bin/python # Cribbed from http://github.com/Constellation/crxmake/blob/master/lib/crxmake.rb # and http://src.chromium.org/viewvc/chrome/trunk/src/chrome/tools/extensions/chromium_extension.py?revision=14872&content-type=text/plain&pathrev=14872 # from: http://grack.com/blog/2009/11/09/packing-chrome-extensions-in-python/ import sys from array import * from subprocess import * import os import tempfile def main(argv): arg0,dir,key,output = argv # zip up the directory input = dir + ".zip" if not os.path.exists(input): os.system("cd %(dir)s; zip -r ../%(input)s . -x '.svn/*'" % locals()) else: print "'%s' already exists using it" % input # Sign the zip file with the private key in PEM format signature = Popen(["openssl", "sha1", "-sign", key, input], stdout=PIPE).stdout.read(); # Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header derkey = Popen(["openssl", "rsa", "-pubout", "-inform", "PEM", "-outform", "DER", "-in", key], stdout=PIPE).stdout.read(); out=open(output, "wb"); out.write("Cr24") # Extension file magic number header = array("l"); header.append(2); # Version 2 header.append(len(derkey)); header.append(len(signature)); header.tofile(out); out.write(derkey) out.write(signature) out.write(open(input).read()) os.unlink(input) print "Done." if __name__ == '__main__': main(sys.argv) Please could you help me?
[ "For Linux, there are a variety of utilities to do this - including one for bash - but it sounds like you want something for windows (guessing from your C# comment).\nI had tried to include links to all of them - but I am new stackoverflow user, and can only post 1 link..\nAnyway, all of those can work in windows, ...
[ 0 ]
[]
[]
[ "c#", "openssl", "python" ]
stackoverflow_0002528810_c#_openssl_python.txt
Q: Convert Python List to Column in CSV I have a list of values (v1, v2, v3) and I want to write these to a column called VALUES in a csv. I'm using csvreader and csvwriter to get as far as I have. I've only figured out how to write them to rows using csvwriter.writerow. A: It sounds like you have tried: values = [1, 2, 3, 4, 5] thecsv = csv.writer(open("your.csv", 'wb')) thecsv.writerow(values) Perhaps you should try: values = [1, 2, 3, 4, 5] thecsv = csv.writer(open("your.csv", 'wb')) for value in values: thecsv.writerow(value)
Convert Python List to Column in CSV
I have a list of values (v1, v2, v3) and I want to write these to a column called VALUES in a csv. I'm using csvreader and csvwriter to get as far as I have. I've only figured out how to write them to rows using csvwriter.writerow.
[ "It sounds like you have tried:\nvalues = [1, 2, 3, 4, 5]\nthecsv = csv.writer(open(\"your.csv\", 'wb'))\nthecsv.writerow(values)\n\nPerhaps you should try:\nvalues = [1, 2, 3, 4, 5]\nthecsv = csv.writer(open(\"your.csv\", 'wb'))\nfor value in values:\n thecsv.writerow(value)\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003902944_python.txt
Q: How to know which row a user selects from an HTML table - GAE Python Sorry if this is a newbie question. I have searched but found nothing... Using Python on GAE, I will display a table of, say, customers on an HTML table. The table will show their name and phone number. I want the user to double-click on a row and have the python Post() method know either the row number double-clicked or the customer number of that row. A 'Select' button on each row would be an acceptable alternative to the double-click. (I am trying to replicate or simulate the Windows / Delphi double-click event on a TStringgrid). My question: is this possible? If so, how or where should I look? many thanks David A: I have never used Python or Delphi (assuming by "I come from Delphi" you mean you are using the Delphi programming language) so forgive me if my answer is not relevant. One method you could use is to give each tr a custom attribute. For example <tr custID='...'>...</tr>. You could then use jQuery to extract the custID from the tr on double click. For example: $("tr").dblclick(function() { $(selector).load("http://myurl/pageName.extension?custID='"+$(this).attr("custID")+"'"); }); I think this should do what you want. I have never used the POST method in jQuery, but this would work for GET. You can always look up the POST method on the jQuery website. Edit: For compliance with HTML 5 (although it will be non-compliant with HTML 4) you are recommended to use data- attributes, for example data-custID.
How to know which row a user selects from an HTML table - GAE Python
Sorry if this is a newbie question. I have searched but found nothing... Using Python on GAE, I will display a table of, say, customers on an HTML table. The table will show their name and phone number. I want the user to double-click on a row and have the python Post() method know either the row number double-clicked or the customer number of that row. A 'Select' button on each row would be an acceptable alternative to the double-click. (I am trying to replicate or simulate the Windows / Delphi double-click event on a TStringgrid). My question: is this possible? If so, how or where should I look? many thanks David
[ "I have never used Python or Delphi (assuming by \"I come from Delphi\" you mean you are using the Delphi programming language) so forgive me if my answer is not relevant.\nOne method you could use is to give each tr a custom attribute. For example <tr custID='...'>...</tr>. You could then use jQuery to extract the...
[ 3 ]
[]
[]
[ "google_app_engine", "html", "python" ]
stackoverflow_0003903414_google_app_engine_html_python.txt
Q: Taking list's tail in a Pythonic way? from random import randrange data = [(randrange(8), randrange(8)) for x in range(8)] And we have to test if the first item equals to one of a tail. I am curious, how we would do it in most simple way without copying tail items to the new list? Please take into account this piece of code gets executed many times in, say, update() method, and therefore it has to be quick as possible. Using an additional list (unnesessary memory wasting, i guess): head = data[0] result = head in data[1:] Okay, here's another way (too lengthy): i = 1 while i < len(data): result = head == data[i] if result: break i+=1 What is the most Pythonic way to solve this? Thanks. A: Nick D's Answer is better use islice. It doesn't make a copy of the list and essentially embeds your second (elegant but verbose) solution in a C module. import itertools head = data[0] result = head in itertools.islice(data, 1, None) for a demo: >>> a = [1, 2, 3, 1] >>> head = a[0] >>> tail = itertools.islice(a, 1, None) >>> head in tail True Note that you can only traverse it once but if all you want to do is check that the head is or is not in the tail and you're worried about memory, then I think that this is the best bet. A: Alternative ways, # 1 result = data.count(data[0]) > 1 # 2 it = iter(data) result = it.next() in it
Taking list's tail in a Pythonic way?
from random import randrange data = [(randrange(8), randrange(8)) for x in range(8)] And we have to test if the first item equals to one of a tail. I am curious, how we would do it in most simple way without copying tail items to the new list? Please take into account this piece of code gets executed many times in, say, update() method, and therefore it has to be quick as possible. Using an additional list (unnesessary memory wasting, i guess): head = data[0] result = head in data[1:] Okay, here's another way (too lengthy): i = 1 while i < len(data): result = head == data[i] if result: break i+=1 What is the most Pythonic way to solve this? Thanks.
[ "Nick D's Answer is better\nuse islice. It doesn't make a copy of the list and essentially embeds your second (elegant but verbose) solution in a C module.\nimport itertools\n\nhead = data[0]\nresult = head in itertools.islice(data, 1, None)\n\nfor a demo:\n>>> a = [1, 2, 3, 1]\n>>> head = a[0]\n>>> tail = itertool...
[ 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003903467_python.txt
Q: Activate Python program every 5 minutes? Is there an easy way to get a python code segment to run every 5 minutes? I know I could do it using time.sleep() but was there any other way? For example I want to run this every 5 minutes: x = 0 def run_5(): print "5 minutes later" global x += 5 print x, "minutes since start" That's only a fake example but the idea is there. Any ideas? I am on linux and would happily use cron but was just wondering if there was a python alternative? A: you can do it with the threading module >>> import threading >>> END = False >>> def run(x=0): ... x += 5 ... print x ... if not END: ... threading.Timer(1.0, run, [x]).start() ... >>> threading.Timer(1.0, run, [x]).start() >>> 5 10 15 20 25 30 35 40 Then when you want it to stop, set END = True. A: You might want to have a look at cron if you are running a *nix type OS. You could easily have it run you program every 5 minutes http://www.unixgeeks.org/security/newbie/unix/cron-1.html https://help.ubuntu.com/community/CronHowto A: If you are on a windows platform, you could use a scheduled task. Otherwise, use cron, wonderful, wonderful cron.
Activate Python program every 5 minutes?
Is there an easy way to get a python code segment to run every 5 minutes? I know I could do it using time.sleep() but was there any other way? For example I want to run this every 5 minutes: x = 0 def run_5(): print "5 minutes later" global x += 5 print x, "minutes since start" That's only a fake example but the idea is there. Any ideas? I am on linux and would happily use cron but was just wondering if there was a python alternative?
[ "you can do it with the threading module\n>>> import threading\n>>> END = False\n>>> def run(x=0):\n... x += 5\n... print x\n... if not END:\n... threading.Timer(1.0, run, [x]).start()\n... \n>>> threading.Timer(1.0, run, [x]).start()\n>>> 5\n10\n15\n20\n25\n30\n35\n40\n\nThen when you want it t...
[ 2, 2, 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0003904033_python_time.txt
Q: How to catch python syntax errors? try: pattern=r'<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>' except: try: pattern=r"<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>" except: pattern=r"""<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>""" I'm writing regular expressions through a tool, and then generate the python code. There are some situations where I need to use ' or " or """ to wrap the regular expression. I want to try/except the error. If the error is captured, then I can try another. But it didn't work. Any help? A: You need to escape your quotes inside the RE. In your first line, all the single quotes need to be escaped as \'. Don't use a try block to fix your faulty RE. Just do it right the first time. A: The try/except statement in Python is used for errors that happen while your program is running. On the other hand, you are encountering errors that happen during compilation. In this case, try/except will not help you. It looks like you would be best off always using """ to surround your regular expressions that contain different kinds of quotes. In Python, the only thing you can't put inside a triple-quoted string is a triple-quote.
How to catch python syntax errors?
try: pattern=r'<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>' except: try: pattern=r"<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>" except: pattern=r"""<tr><td><a href='(?P<link>[\s\S]*?)'[\s\S]*?><img src='(?P<img>[\s\S]*?)' width='130' height='130'[\s\S]*?/></a></td>""" I'm writing regular expressions through a tool, and then generate the python code. There are some situations where I need to use ' or " or """ to wrap the regular expression. I want to try/except the error. If the error is captured, then I can try another. But it didn't work. Any help?
[ "You need to escape your quotes inside the RE. In your first line, all the single quotes need to be escaped as \\'.\nDon't use a try block to fix your faulty RE. Just do it right the first time.\n", "The try/except statement in Python is used for errors that happen while your program is running. On the other hand...
[ 0, 0 ]
[]
[]
[ "error_handling", "python", "regex", "try_except" ]
stackoverflow_0003904054_error_handling_python_regex_try_except.txt
Q: Restore Python class to original state I have a class where I add some attributes dynamically and at some point I want to restore the class to it's pristine condition without the added attributes. The situation: class Foo(object): pass Foo.x = 1 # <insert python magic here> o = Foo() # o should not have any of the previously added attributes print o.x # Should raise exception My initial thought was to create a copy of the original class: class _Foo(object): pass Foo = _Foo Foo.x = 1 Foo = _Foo # Clear added attributes o = Foo() print o.x # Should raise exception But since Foo is just a reference to _Foo any attributes get added to the original _Foo as well. I also tried Foo = copy.deepcopy(_Foo) in case that would help but apparently it does not. clarification: The user should not need to care about how the class is implemented. It should, therefore, have the same features of a "normally defined" class, i.e. introspection, built-in help, subclassing, etc. This pretty much rules out anything based on __getattr__ A: I agree with Glenn that this is a horribly broken idea. Anyways, here how you'd do it with a decorator. Thanks to Glenn's post as well for reminding me that you can delete items from a class's dictionary, just not directly. Here's the code. def resetable(cls): cls._resetable_cache_ = cls.__dict__.copy() return cls def reset(cls): cache = cls._resetable_cache_ # raises AttributeError on class without decorator for key in [key for key in cls.__dict__ if key not in cache]: delattr(cls, key) for key, value in cache.items(): # reset the items to original values try: setattr(cls, key, value) except AttributeError: pass I'm torn on whether to reset the values by catching attempts to update non-assignable attributes with a try as I've shown or building a list of such attributes. I'll leave it up to you. And here's a use: @resetable # use resetable on a class that you want to do this with class Foo(object): pass Foo.x = 1 print Foo.x reset(Foo) o = Foo() print o.x # raises AttributeError as expected A: You have to record the original state and restore it explicitly. If the value existed before you changed it, restore that value; otherwise delete the value you set. class Foo(object): pass try: original_value = getattr(Foo, 'x') originally_existed = True except AttributeError: originally_existed = False Foo.x = 1 if originally_existed: Foo.x = original_value else: del Foo.x o = Foo() # o should not have any of the previously added attributes print o.x # Should raise exception You probably don't want to be doing this. There are valid cases for monkey patching, but you generally don't want to try to monkey unpatch. For example, if two independent bits of code monkey patch the same class, one of them trying to reverse the action without being aware of the other is likely to break things. For an example of a case where this is actually useful, see https://stackoverflow.com/questions/3829742#3829849. A: You can use inspect and maintain an original list of members and than delete all members that are not in the original list import inspect orig_members = [] for name, ref in inspect.getmembers(o): orig_members.append(name) ... Now, when you need to restore back to original for name, ref in inspect.getmembers(o): if name in orig_members: pass else: #delete ref here A: The simplest way I found was this: def foo_maker(): class Foo(object): pass return Foo Foo = foo_maker() Foo.x = 1 Foo = foo_maker() # Foo is now clean again o = Foo() # Does not have any of the previously added attributes print o.x # Raises exception edit: As pointed out in comments, does not actually reset class but has the same effect in practice. A: I don't fully understand why you need this, but I'll have a go. Ordinary inheritance probably won't do because you want to 'reset' to the old state. How about a proxy pattern? class FooProxy(object): def __init__(self, f): self.f = foo self.magic = {} def set_magic(self, k, v): self.magic[k] = v def get_magic(self, k): return self.magic.get(k) def __getattr__(self, k): return getattr(self.f, k) def __setattr__(self, k, v): setattr(self.f, k, v) f = Foo() p = FooProxy(f) p.set_magic('m_bla', 123) use f for ordinary, 'original' access, use p for proxied access, it should behave mostly like Foo. Re-proxy f with new configuration if you need to A: I don't know if you can accept an additional module file for class, if you can: my_class.py class Foo(object): pass You main script: import my_class Foo = my_class.Foo Foo.x = 1 p = Foo() print p.x # Printing '1' # Some code.... reload(my_class) # reload to reset Foo = my_class.Foo o = Foo() print p.x # Printing '1' print o.__class__ == p.__class__ # Printing 'False' print o.x # Raising exception I am not sure if there is any side-effect. It seems to do what OP wants, though this is really unusal. A: In your second example you're making a reference to the class rather than an instance. Foo = _Foo # Reference If you instead made an instance copy, what you want to do is exactly the way it will work. You can modify the instance all you want and 'revert' it by creating a new instance. Foo = _Foo() #!/usr/bin/python class FooClass(object): pass FooInstance = FooClass() # Create an instance FooInstance.x = 100 # Modify the instance print dir(FooClass) # Verify FooClass doesn't have an 'x' attribute FooInstance = FooClass() # Creates a new instance print FooInstance.x # Exception A: I don't understand what you are trying to do, but keep in mind that you don't have to add attributes to the class in order to make it look like you added attributes to the class. You can give the class a __getattr__ method that will be invoked for any missing attribute. Where it gets the value from is up to you: class MyTrickyClass(object): self.magic_prefix = "m_" self.other_attribute_source = SomeOtherObject() def __getattr__(self, name): if name.startswith(self.magic_prefix): stripped = name[len(self.magic_prefix):] return getattr(self.other_attribute_source, stripped) raise AttributeError m = MyTrickyClass() assert hasattr(m, "m_other") MyTrickyClass.magic_prefix = "f_" assert hasattr(m, "f_other") A: If all the stuff you added starts with a given distinctive prefix, you could search the object's __dict__ for members with that prefix, and delete them, when it's time to restore.
Restore Python class to original state
I have a class where I add some attributes dynamically and at some point I want to restore the class to it's pristine condition without the added attributes. The situation: class Foo(object): pass Foo.x = 1 # <insert python magic here> o = Foo() # o should not have any of the previously added attributes print o.x # Should raise exception My initial thought was to create a copy of the original class: class _Foo(object): pass Foo = _Foo Foo.x = 1 Foo = _Foo # Clear added attributes o = Foo() print o.x # Should raise exception But since Foo is just a reference to _Foo any attributes get added to the original _Foo as well. I also tried Foo = copy.deepcopy(_Foo) in case that would help but apparently it does not. clarification: The user should not need to care about how the class is implemented. It should, therefore, have the same features of a "normally defined" class, i.e. introspection, built-in help, subclassing, etc. This pretty much rules out anything based on __getattr__
[ "I agree with Glenn that this is a horribly broken idea. Anyways, here how you'd do it with a decorator. Thanks to Glenn's post as well for reminding me that you can delete items from a class's dictionary, just not directly. Here's the code.\ndef resetable(cls):\n cls._resetable_cache_ = cls.__dict__.copy()\n ...
[ 5, 3, 3, 1, 0, 0, 0, 0, 0 ]
[ "To create a deep copy of a class you can use the new.classobj function\nclass Foo:\n pass\n\nimport new, copy\nFooSaved = new.classobj(Foo.__name__, Foo.__bases__, copy.deepcopy(Foo.__dict__))\n\n# ...play with original class Foo...\n\n# revert changes\nFoo = FooSaved\n\nUPD: module new is deprecated. Instead y...
[ -1 ]
[ "python" ]
stackoverflow_0003899454_python.txt
Q: Python trouble with repeater Im trying to write a program so that I get a result of... 5 : Rowan 6 : Rowan 7 : Rowan 8 : Rowan 9 : Rowan 10 : Rowan 11 : Rowan 12 : Rowan I want to be able to set it so that I can change the starting number, the amount of times it repeats and the word that it repeats. this is what i have so far... def hii(howMany, start, Word): Word for howMany in range (howMany): print howMany + start, ":", "-" Im just having trouble making it so i can change the word that repeats A: The range iterator takes a start value: def hii(howMany, start, Word): for i in range(start, start+howMany): print i, ":", Word Note that it's not a good idea to use the same name for a local variable as for a parameter (howMany). I have used i instead. A: From Python 2.6 upwards enumerate has a start parameter: import itertools def hii(how_many, start, word): seq = itertools.repeat(word, how_many) return enumerate(seq, start=start) for n, w in hii(8, 5, 'Rowan'): print n, w A: How about: def hii(howMany, start, Word): for howMany in range (howMany): print howMany + start, ":", Word Is there anything wrong with that? To use: hii(10, 4, "Weeee!!!!") A: python 2.x >>> def repeater(start, end, word): ... for i in range(start, end): ... print i, ":", word >>> repeater(2,8, "hello") for python3.x >>> def repeater(start, end, word): ... for i in range(start, end): ... print(i , ":" , word) >>> repeater(2,8, "hello")
Python trouble with repeater
Im trying to write a program so that I get a result of... 5 : Rowan 6 : Rowan 7 : Rowan 8 : Rowan 9 : Rowan 10 : Rowan 11 : Rowan 12 : Rowan I want to be able to set it so that I can change the starting number, the amount of times it repeats and the word that it repeats. this is what i have so far... def hii(howMany, start, Word): Word for howMany in range (howMany): print howMany + start, ":", "-" Im just having trouble making it so i can change the word that repeats
[ "The range iterator takes a start value:\ndef hii(howMany, start, Word):\n for i in range(start, start+howMany):\n print i, \":\", Word\n\nNote that it's not a good idea to use the same name for a local variable as for a parameter (howMany). I have used i instead.\n", "From Python 2.6 upwards enumerate ...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003903263_python.txt
Q: how to get all the users from the list in twitter? I want to get all the user from a list using twitter api. But i have some query regarding this. Does this needs oauth authentication? I am using python. A: Returning the members of a specified list does require authentication.
how to get all the users from the list in twitter?
I want to get all the user from a list using twitter api. But i have some query regarding this. Does this needs oauth authentication? I am using python.
[ "Returning the members of a specified list does require authentication.\n" ]
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003904262_python_twitter.txt
Q: Immutable types allowing subclassing in Python I want to have immutable types that can, ideally, sort out their own hashing and equality, but can be easily subclassed. I started off using namedtuple: class Command(namedtuple('Command', 'cmd_string')): def valid_msg(msg): return True def make_command(msg): if self.valid_msg(msg): return '%s:%s' % (self.cmd_string, msg) else: raise ValueError(INVALID_MSG) ...but this does not lend itself to subclassing. Directly subclassing this means that the name of the tuple remains the same (for printing... not such a big deal), but more importantly you can't add fields: class LimitedLengthCommand(Command): # I want to have self.length! Where does it go? def valid_msg(msg): return len(msg) <= self.length Simply creating another named tuple (as per the docs) means I don't inherit any methods! What is the simplest and easiest way to do something like this? I intend to have multiple subclasses of Command (eg. hex literals, 1-or-0, etc), but nothing complicated. Playing nice with multiple inheritance is not essential. A: Here's a metaclass to do what you want (I think). It works by storing the methods to be inherited in a dictionary and manually inserting them into the new classes dictionary. It also stores the attribute string that gets passed to the namedtuple constructor and merges that with the attribute string from the subclass. It then passes that to namedtuple and returns a class that's inherited from the resulting namedtuple with all appropriate methods in its dictionary. Because the metaclass is derived from abc.ABCMeta, you get working type checking for free. Here's how constructing a couple of classes looks: class Foo(object): __metaclass__ = ImmutableMeta _attributes_ = 'a b' def sayhi(self): print "Hello from {0}".format(type(self).__name__) class Bar(Foo): _attributes_ = 'c' def saybye(self): print "Goodbye from {0}".format(type(self).__name__) Here's the metaclass: import collections as co import abc class ImmutableMeta(abc.ABCMeta): _classes = {} def __new__(meta, clsname, bases, clsdict): attributes = clsdict.pop('_attributes_') if bases[0] is object: # 'new' class methods = clsdict else: # we're 'inheriting' from an existing class base = bases[0] attributes = meta._classes[base]['attributes'] + ' ' + attributes base_methods = meta._classes[base]['methods'].copy() base_methods.update(clsdict) methods = base_methods # construct the actual base class and create the return class new_base = co.namedtuple(clsname + 'Base', attributes) cls = super(ImmutableMeta, meta).__new__(meta, clsname, (new_base,), methods) # register the data necessary to 'inherit' from the class # and make sure that it passes typechecking meta._classes[cls] = {'attributes': attributes, 'methods': methods} if bases[0] is not object: base.register(cls) return cls And here's some paltry test code. a = Foo(1, 2) a.sayhi() b = Bar(1, 2, 3) b.sayhi() # 'inherited' from class Foo b.saybye() try: b.c = 1 # will raise an AttributeError except AttributeError: print "Immutable" print "issubclass(Bar, Foo): {0}".format(issubclass(Bar, Foo)) try: d = {b: 1} # No problems except TypeError: print "Cant put it in a dict" else: print "Can put it in a dict" Hope that helps. If you would prefer not to attach every method to every class that is supposed to inherit it, you could also provide a default __getattr__ that looks through the metaclasses dictionary and finds the appropriate method out of that. That would require somehow hardcoding the baseclass into method, probably using a closure.
Immutable types allowing subclassing in Python
I want to have immutable types that can, ideally, sort out their own hashing and equality, but can be easily subclassed. I started off using namedtuple: class Command(namedtuple('Command', 'cmd_string')): def valid_msg(msg): return True def make_command(msg): if self.valid_msg(msg): return '%s:%s' % (self.cmd_string, msg) else: raise ValueError(INVALID_MSG) ...but this does not lend itself to subclassing. Directly subclassing this means that the name of the tuple remains the same (for printing... not such a big deal), but more importantly you can't add fields: class LimitedLengthCommand(Command): # I want to have self.length! Where does it go? def valid_msg(msg): return len(msg) <= self.length Simply creating another named tuple (as per the docs) means I don't inherit any methods! What is the simplest and easiest way to do something like this? I intend to have multiple subclasses of Command (eg. hex literals, 1-or-0, etc), but nothing complicated. Playing nice with multiple inheritance is not essential.
[ "Here's a metaclass to do what you want (I think). It works by storing the methods to be inherited in a dictionary and manually inserting them into the new classes dictionary. It also stores the attribute string that gets passed to the namedtuple constructor and merges that with the attribute string from the subcla...
[ 1 ]
[]
[]
[ "immutability", "python" ]
stackoverflow_0003904441_immutability_python.txt
Q: Converting while to generator 3.4 times slow down What is happening? Can somebody explain me what happens here, I changed in tight loop: ## j=i ## while j < ls - 1 and len(wordlist[j]) > lc: j+=1 j = next(j for j in range(i,ls) if len(wordlist[j]) <= lc) The commented while version ran the whole program: 625 ms, the next generator version ran the whole program in time of 2.125 s. What can be reason that this more pythonic version cause such a catastroph in performance? EDIT: Maybe it is caused by use of psyco module? Surely at least the running time with Python 2.7 which has not psyco, was 2.141 for the next version, means almost same as Python 2.6 with psyco. After removing the *.pyc files I got notthe code to slow down. Then when I removed import of psyco from library module also, I got 2.6 timing also for use without psyco, results for the non psyco version and psyco version (as now the library routine slows down also and it's timing is also relevant:) not psyco: while: preparation in library: 532 ms, total running time 2.625 s next: preparation in library: 532 ms, total running time (time.clock()): 2.844 s (version with xrange same wall time) psyco: while: preparation in library: 297 ms, total running time : 609..675 ms next: preparation in library: 297 ms, total running time: 1.922 s (version with range instead of xrange everywhere in program: 1.985 s) Running in WindowsXP AMD Sempron 3100+ system with 2GB RAM. Counting the loops and calls with two globals: j=i callcount += 1 while j < ls - 1 and len(wordlist[j]) > lc: j+=1 loopcount += 1 Result for the test input with psyco: Finished in 625 ms Loopcount: 78317 Callcount: 47970 Ration: 1.633 So the loop is inside tight loop, but is on average executed only couple of times (notice that two increments of global counters did not slow down the code in psyco) CONCLUSIONS: Despite the highly sensitive nature of the algorithm relative to vocabulary length, which caused me to pass some imposible words from consideration by this loop, later the basic cases of recursion are checked by dictionary lookup which is O(n), therefore the highly beneficial earlier optimization is become not very beneficial, even with longer input and moving the callcount counter in beginning of the function, showed that call count is not affected by the vocabulary length, but outer loop count is slichtly reduced (the code originally posted is in elif part of if statement). Longer run times (29 372 solutions) with while loop and the whole loop removed (using i instead of j) (library preparation 312 ms): Without the loop: elif branch count: 485488, outerloopcount: 10129147, ratio: 0,048, runtime 6,000 s (without counters: 4,594 s) With the loop: loopcount: 19355114, outercount: 8194033, ratio: 0,236, runtime 5,704 s (without counters: 4,688 s) (running time without loop, counters and psyco: 32,792 s, library 608 ms) So without the extra counters the benefit of this loop using psyco is in the harder case: (4688-4594)*100/4688.0 % = 2 % This inspired me to reverse another earlier optimization, which I had wondered about in DaniWeb. Earlier version of code run faster, when the smallest word size was global, not paramerter. According to documentation, local variable calls are faster, but apparantly the cost in making recursion heavier outweighted that. Now in the harder case this other reversal of optimization brought more expected performance behaviour in the case of no optimization of word lenght: the run time with psyco was 312 ms preparations, 4,469..4,484 s total running time. So this made code cleaner and brought more benefit in this case as the removed loop had. And putting the parameter to version with while loop, did not change the running time much (the variation became greater for library preparation code) **What I learned from this: If you do n optimizations for speed you must check the first n-1 optimizations after doing nth one** A: I've found that using generators can often be slower than generating the whole list, which is a little counter-intuitive. I've managed to fix performance bottlenecks just by adding a [] pair. For example compare these: $ python -m timeit -n 1000 "' '.join(c for c in 'hello world')" 1000 loops, best of 3: 6.11 usec per loop $ python -m timeit -n 1000 "' '.join([c for c in 'hello world'])" 1000 loops, best of 3: 3.79 usec per loop It's almost twice as quick to generate the whole list first rather than use a generator even for such a simple case! Edit: As Thomas Wouters points out in the comments the reason the generator is slower here is because it's such a simple case. For balance here is his test in which the generator is the clear winner: $ python -m timeit -s "s = 'hello world' * 10000" -s "class C: pass" "for i in (C() for c in s): pass" 10 loops, best of 3: 33.6 msec per loop $ python -m timeit -s "s = 'hello world' * 10000" -s "class C: pass" "for i in [C() for c in s]: pass" 10 loops, best of 3: 172 msec per loop A: The two are not equivalent. j=i while j < ls - 1 and len(wordlist[j]) > lc: j+=1 will stop the while loop as soon as wordlist[j] <= lc. It could conceivably go through the loop zero times if the first word in the list is shorter than or equal to lc. j = next(j for j in range(i,ls) if len(wordlist[j]) <= lc) will continue iterating through the whole range i to ls, regardless of the length of the words in the list. Edit: Ignore the above - as Amber pointed out, the call to next() means that the generator expression is only evaluated up until the first result is returned. In that case I suspect the time difference comes from using range() instead of xrange() (unless this is Python 3.x). In Python 2.x range() will create the full list in memory, even if the generator expression only returns the first value.
Converting while to generator 3.4 times slow down
What is happening? Can somebody explain me what happens here, I changed in tight loop: ## j=i ## while j < ls - 1 and len(wordlist[j]) > lc: j+=1 j = next(j for j in range(i,ls) if len(wordlist[j]) <= lc) The commented while version ran the whole program: 625 ms, the next generator version ran the whole program in time of 2.125 s. What can be reason that this more pythonic version cause such a catastroph in performance? EDIT: Maybe it is caused by use of psyco module? Surely at least the running time with Python 2.7 which has not psyco, was 2.141 for the next version, means almost same as Python 2.6 with psyco. After removing the *.pyc files I got notthe code to slow down. Then when I removed import of psyco from library module also, I got 2.6 timing also for use without psyco, results for the non psyco version and psyco version (as now the library routine slows down also and it's timing is also relevant:) not psyco: while: preparation in library: 532 ms, total running time 2.625 s next: preparation in library: 532 ms, total running time (time.clock()): 2.844 s (version with xrange same wall time) psyco: while: preparation in library: 297 ms, total running time : 609..675 ms next: preparation in library: 297 ms, total running time: 1.922 s (version with range instead of xrange everywhere in program: 1.985 s) Running in WindowsXP AMD Sempron 3100+ system with 2GB RAM. Counting the loops and calls with two globals: j=i callcount += 1 while j < ls - 1 and len(wordlist[j]) > lc: j+=1 loopcount += 1 Result for the test input with psyco: Finished in 625 ms Loopcount: 78317 Callcount: 47970 Ration: 1.633 So the loop is inside tight loop, but is on average executed only couple of times (notice that two increments of global counters did not slow down the code in psyco) CONCLUSIONS: Despite the highly sensitive nature of the algorithm relative to vocabulary length, which caused me to pass some imposible words from consideration by this loop, later the basic cases of recursion are checked by dictionary lookup which is O(n), therefore the highly beneficial earlier optimization is become not very beneficial, even with longer input and moving the callcount counter in beginning of the function, showed that call count is not affected by the vocabulary length, but outer loop count is slichtly reduced (the code originally posted is in elif part of if statement). Longer run times (29 372 solutions) with while loop and the whole loop removed (using i instead of j) (library preparation 312 ms): Without the loop: elif branch count: 485488, outerloopcount: 10129147, ratio: 0,048, runtime 6,000 s (without counters: 4,594 s) With the loop: loopcount: 19355114, outercount: 8194033, ratio: 0,236, runtime 5,704 s (without counters: 4,688 s) (running time without loop, counters and psyco: 32,792 s, library 608 ms) So without the extra counters the benefit of this loop using psyco is in the harder case: (4688-4594)*100/4688.0 % = 2 % This inspired me to reverse another earlier optimization, which I had wondered about in DaniWeb. Earlier version of code run faster, when the smallest word size was global, not paramerter. According to documentation, local variable calls are faster, but apparantly the cost in making recursion heavier outweighted that. Now in the harder case this other reversal of optimization brought more expected performance behaviour in the case of no optimization of word lenght: the run time with psyco was 312 ms preparations, 4,469..4,484 s total running time. So this made code cleaner and brought more benefit in this case as the removed loop had. And putting the parameter to version with while loop, did not change the running time much (the variation became greater for library preparation code) **What I learned from this: If you do n optimizations for speed you must check the first n-1 optimizations after doing nth one**
[ "I've found that using generators can often be slower than generating the whole list, which is a little counter-intuitive. I've managed to fix performance bottlenecks just by adding a [] pair.\nFor example compare these:\n$ python -m timeit -n 1000 \"' '.join(c for c in 'hello world')\"\n1000 loops, best of 3: 6.11...
[ 4, 0 ]
[]
[]
[ "generator", "optimization", "performance", "python", "while_loop" ]
stackoverflow_0003902522_generator_optimization_performance_python_while_loop.txt
Q: facebook self.graph.put_object I using the Python SDK (http://github.com/facebook/python-sdk/) with Google app engine. I can post message on user wall with the self.graph.put_object function while the user is online. How do post a message to user wall directly from the server even the user is offline? A: I am assuming you know how to kick the work off and just need the calls to authenticate for the user. Your facebook app must request extended permissions from the user. http://developers.facebook.com/docs/authentication/permissions offline_access Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived. NOTE: If you have requested the publish_stream permission, you can publish content to a user's feed at any time, without requiring offline_access. Once you have done this the oauth_access_token returned from Facebook is an offline_access token and can be used anytime until the user revokes your app access or extended permission.
facebook self.graph.put_object
I using the Python SDK (http://github.com/facebook/python-sdk/) with Google app engine. I can post message on user wall with the self.graph.put_object function while the user is online. How do post a message to user wall directly from the server even the user is offline?
[ "I am assuming you know how to kick the work off and just need the calls to authenticate for the user.\nYour facebook app must request extended permissions from the user.\nhttp://developers.facebook.com/docs/authentication/permissions\noffline_access\n\nEnables your application to perform\n authorized requests on ...
[ 1 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003903761_facebook_python.txt
Q: return html for a web server and not plain text in python here is my code : import socket import sys import re import base64 import binascii import time class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("GET.*?HTTP") try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 28000) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) except : time.sleep(2) self.__init__() # Listen for incoming connections sock.listen(1) off = 2 self.message = "" while True: # Wait for a connection print >>sys.stderr, 'waiting for a connection' if off == 2 or off == 1: connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it while True: data = connection.recv(1024) print >>sys.stderr, 'received "%s"' % data if data: self.message = self.traitement(data) connection.sendall(self.message) connection.close() connection, client_address = sock.accept() else: print >>sys.stderr, 'no more data from', client_address break finally: # Clean up the connection connection.close() def traitement(self,data): url = self.GET.findall(data) url = self.POST.findall(data) url = url[0].replace("GET","") url = url.replace("POST","") url = url.replace("HTTP","") url = url.replace(" ","") print url if url == "/favicon.ico": return binascii.a2b_base64( """AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAA7PT7/3zF6/9Ptu//RbHx/0227/+Tzvb/9vv5/97h0f9JeBz/NHoA/z98Av9AfAD/ PHsA/0F6AP8AAAAA/vz7/1+33/8Mp+z/FrHw/xWy8f8bs/T/Hqrx/3zE7v////7/t8qp/zF2A/87 gwH/P4ID/z59AP8+egD/Q3kA/97s8v8botj/ELn3/wy58f8PtfL/D7Lw/xuz9P8vq+f/8/n///77 9v9KhR3/OYYA/0GFAv88hgD/QIAC/z17AP/0+/j/N6bM/wC07/8Cxf7/CsP7/wm+9v8Aqur/SrDb //7+/v///P7/VZEl/zSJAP87jQD/PYYA/0OBBf8+fQH///3//9Dp8/84sM7/CrDf/wC14/8CruL/ KqnW/9ns8f/8/v//4OjX/z+GDf85kAD/PIwD/z2JAv8+hQD/PoEA/9C7pv/97uv////+/9Xw+v+w 3ej/ls/e/+rz9///////+/z6/22mSf8qjQH/OJMA/zuQAP85iwL/PIgA/zyFAP+OSSL/nV44/7J+ Vv/AkG7/7trP//7//f/9//7/6/Lr/2uoRv8tjQH/PJYA/zuTAP87kwD/PY8A/z2KAP89hAD/olkn /6RVHP+eSgj/mEgR//Ho3//+/v7/5Ozh/1GaJv8tlAD/OZcC/zuXAv84lAD/O5IC/z2PAf89iwL/ OIkA/6hWFf+cTxD/pm9C/76ihP/8/v//+////8nav/8fdwL/NZsA/zeZAP83mgD/PJQB/zyUAf84 jwD/PYsB/z6HAf+fXif/1r6s//79///58u//3r+g/+3i2v/+//3/mbiF/yyCAP87mgP/OpgD/zeW AP85lgD/OpEB/z+TAP9ChwH/7eHb/////v/28ej/tWwo/7tUAP+5XQ7/5M+5/////v+bsZn/IHAd /zeVAP89lgP/O5MA/zaJCf8tZTr/DyuK//3////9////0qmC/7lTAP/KZAT/vVgC/8iQWf/+//3/ //j//ygpx/8GGcL/ESax/xEgtv8FEMz/AALh/wAB1f///f7///z//758O//GXQL/yGYC/8RaAv/O jlf/+/////////9QU93/BAD0/wAB//8DAP3/AAHz/wAA5f8DAtr///////v7+/+2bCT/yGMA/89m AP/BWQD/0q+D///+/////P7/Rkbg/wEA+f8AA/z/AQH5/wMA8P8AAev/AADf///7/P////7/uINQ /7lXAP/MYwL/vGIO//Lm3P/8/v//1dT2/woM5/8AAP3/AwH+/wAB/f8AAfb/BADs/wAC4P8AAAAA //z7/+LbzP+mXyD/oUwE/9Gshv/8//3/7/H5/zo/w/8AAdX/AgL6/wAA/f8CAP3/AAH2/wAA7v8A AAAAgAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAgAEAAA==""") else : return "Content-type:text/html;charset=utf8\n\n<html><body>test</body></html>" if __name__ == "__main__": s = Serverhttp() why does the line: return "Content-type:text/html;charset=utf8\n\n<html><body>test</body></html>" display plain text in a browser and not html? A: Replace your return statement with the following return "HTTP/1.0 200 OK\r\nContent-type:text/html;charset=utf8\r\n\r\n<html><body>test</body></html>" Note: You should understand how to respond and handle HTTP requests properly. If you are serious in building your own web server, you should first read and understand the HTTP RFC. A: I don't know python but you shouldn't write header informations in HTML. You can specify Content-type with a <meta> in <head> tag. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <body> test </body> </html>
return html for a web server and not plain text in python
here is my code : import socket import sys import re import base64 import binascii import time class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("GET.*?HTTP") try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 28000) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) except : time.sleep(2) self.__init__() # Listen for incoming connections sock.listen(1) off = 2 self.message = "" while True: # Wait for a connection print >>sys.stderr, 'waiting for a connection' if off == 2 or off == 1: connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it while True: data = connection.recv(1024) print >>sys.stderr, 'received "%s"' % data if data: self.message = self.traitement(data) connection.sendall(self.message) connection.close() connection, client_address = sock.accept() else: print >>sys.stderr, 'no more data from', client_address break finally: # Clean up the connection connection.close() def traitement(self,data): url = self.GET.findall(data) url = self.POST.findall(data) url = url[0].replace("GET","") url = url.replace("POST","") url = url.replace("HTTP","") url = url.replace(" ","") print url if url == "/favicon.ico": return binascii.a2b_base64( """AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAA7PT7/3zF6/9Ptu//RbHx/0227/+Tzvb/9vv5/97h0f9JeBz/NHoA/z98Av9AfAD/ PHsA/0F6AP8AAAAA/vz7/1+33/8Mp+z/FrHw/xWy8f8bs/T/Hqrx/3zE7v////7/t8qp/zF2A/87 gwH/P4ID/z59AP8+egD/Q3kA/97s8v8botj/ELn3/wy58f8PtfL/D7Lw/xuz9P8vq+f/8/n///77 9v9KhR3/OYYA/0GFAv88hgD/QIAC/z17AP/0+/j/N6bM/wC07/8Cxf7/CsP7/wm+9v8Aqur/SrDb //7+/v///P7/VZEl/zSJAP87jQD/PYYA/0OBBf8+fQH///3//9Dp8/84sM7/CrDf/wC14/8CruL/ KqnW/9ns8f/8/v//4OjX/z+GDf85kAD/PIwD/z2JAv8+hQD/PoEA/9C7pv/97uv////+/9Xw+v+w 3ej/ls/e/+rz9///////+/z6/22mSf8qjQH/OJMA/zuQAP85iwL/PIgA/zyFAP+OSSL/nV44/7J+ Vv/AkG7/7trP//7//f/9//7/6/Lr/2uoRv8tjQH/PJYA/zuTAP87kwD/PY8A/z2KAP89hAD/olkn /6RVHP+eSgj/mEgR//Ho3//+/v7/5Ozh/1GaJv8tlAD/OZcC/zuXAv84lAD/O5IC/z2PAf89iwL/ OIkA/6hWFf+cTxD/pm9C/76ihP/8/v//+////8nav/8fdwL/NZsA/zeZAP83mgD/PJQB/zyUAf84 jwD/PYsB/z6HAf+fXif/1r6s//79///58u//3r+g/+3i2v/+//3/mbiF/yyCAP87mgP/OpgD/zeW AP85lgD/OpEB/z+TAP9ChwH/7eHb/////v/28ej/tWwo/7tUAP+5XQ7/5M+5/////v+bsZn/IHAd /zeVAP89lgP/O5MA/zaJCf8tZTr/DyuK//3////9////0qmC/7lTAP/KZAT/vVgC/8iQWf/+//3/ //j//ygpx/8GGcL/ESax/xEgtv8FEMz/AALh/wAB1f///f7///z//758O//GXQL/yGYC/8RaAv/O jlf/+/////////9QU93/BAD0/wAB//8DAP3/AAHz/wAA5f8DAtr///////v7+/+2bCT/yGMA/89m AP/BWQD/0q+D///+/////P7/Rkbg/wEA+f8AA/z/AQH5/wMA8P8AAev/AADf///7/P////7/uINQ /7lXAP/MYwL/vGIO//Lm3P/8/v//1dT2/woM5/8AAP3/AwH+/wAB/f8AAfb/BADs/wAC4P8AAAAA //z7/+LbzP+mXyD/oUwE/9Gshv/8//3/7/H5/zo/w/8AAdX/AgL6/wAA/f8CAP3/AAH2/wAA7v8A AAAAgAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAgAEAAA==""") else : return "Content-type:text/html;charset=utf8\n\n<html><body>test</body></html>" if __name__ == "__main__": s = Serverhttp() why does the line: return "Content-type:text/html;charset=utf8\n\n<html><body>test</body></html>" display plain text in a browser and not html?
[ "Replace your return statement with the following \nreturn \"HTTP/1.0 200 OK\\r\\nContent-type:text/html;charset=utf8\\r\\n\\r\\n<html><body>test</body></html>\"\n\nNote: You should understand how to respond and handle HTTP requests properly. If you are serious in building your own web server, you should first read...
[ 4, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003904584_html_python.txt
Q: How to support recursive include when parsing xml I'm defining an xml schema of my own which supports the additional tag "insert_tag", which when reached should insert the text file at that point in the stream and then continue the parsing: Here is an example: my.xml: <xml> Something <insert_file name="foo.html"/> or another </xml> I'm using xmlreader as follows: class HtmlHandler(xml.sax.handler.ContentHandler): def __init__(self): xml.sax.handler.ContentHandler.__init__(self) parser = xml.sax.make_parser() parser.setContentHandle(HtmlHandler()) parser.parse(StringIO(html)) The question is how do I insert the included contents directly into the parsing stream? Of course I could recursively build up the non-interpolated text by repeatedly inserting included text, but that means that I have to parse the xml multiple times. I tried replacing StringIO(html) with my own stream that allows inserting contents mid stream, but it doesn't work because the sax parser reads the stream buffered. Update: I did find a solution that is hackish at the best. It is built on the following stream class: class InsertReader(): """A reader class that supports the concept of pushing another reader in the middle of the use of a first reader. This may be used for supporting insertion commands.""" def __init__(self): self.reader_stack = [] def push(self,reader): self.reader_stack += [reader] def pop(self): self.reader_stack.pop() def __iter__(self): return self def read(self,n=-1): """Read from the top most stack element. Never trancends elements. Should it? The code below is a hack. It feeds only a single token back to the reader. """ while len(self.reader_stack)>0: # Return a single token ret_text = StringIO() state = 0 while 1: c = self.reader_stack[-1].read(1) if c=='': break ret_text.write(c) if c=='>': break ret_text = ret_text.getvalue() if ret_text == '': self.reader_stack.pop() continue return ret_text return '' def next(self): while len(self.reader_stack)>0: try: v = self.reader_stack[-1].next() except StopIteration: self.reader_stack.pop() continue return v raise StopIteration This class creates a stream structure that restricts the amount of characters that are returned to the user of the stream. I.e. even if the xml parser does read(16386) the class will only return bytes up to the next '>' character. Since the '>' character also signifies the end of tags, we have the opportunity to inject our recursive include into the stream at this point. What is hackish about this solution is the following: Reading one character at a time from a stream is slow. This has an implicit assumption about how the sax stream class is reading text. This solves the problem for me, but I'm still interested in a more beautiful solution. A: Have you considered using xinclude? The lxml library has builtin support for it.
How to support recursive include when parsing xml
I'm defining an xml schema of my own which supports the additional tag "insert_tag", which when reached should insert the text file at that point in the stream and then continue the parsing: Here is an example: my.xml: <xml> Something <insert_file name="foo.html"/> or another </xml> I'm using xmlreader as follows: class HtmlHandler(xml.sax.handler.ContentHandler): def __init__(self): xml.sax.handler.ContentHandler.__init__(self) parser = xml.sax.make_parser() parser.setContentHandle(HtmlHandler()) parser.parse(StringIO(html)) The question is how do I insert the included contents directly into the parsing stream? Of course I could recursively build up the non-interpolated text by repeatedly inserting included text, but that means that I have to parse the xml multiple times. I tried replacing StringIO(html) with my own stream that allows inserting contents mid stream, but it doesn't work because the sax parser reads the stream buffered. Update: I did find a solution that is hackish at the best. It is built on the following stream class: class InsertReader(): """A reader class that supports the concept of pushing another reader in the middle of the use of a first reader. This may be used for supporting insertion commands.""" def __init__(self): self.reader_stack = [] def push(self,reader): self.reader_stack += [reader] def pop(self): self.reader_stack.pop() def __iter__(self): return self def read(self,n=-1): """Read from the top most stack element. Never trancends elements. Should it? The code below is a hack. It feeds only a single token back to the reader. """ while len(self.reader_stack)>0: # Return a single token ret_text = StringIO() state = 0 while 1: c = self.reader_stack[-1].read(1) if c=='': break ret_text.write(c) if c=='>': break ret_text = ret_text.getvalue() if ret_text == '': self.reader_stack.pop() continue return ret_text return '' def next(self): while len(self.reader_stack)>0: try: v = self.reader_stack[-1].next() except StopIteration: self.reader_stack.pop() continue return v raise StopIteration This class creates a stream structure that restricts the amount of characters that are returned to the user of the stream. I.e. even if the xml parser does read(16386) the class will only return bytes up to the next '>' character. Since the '>' character also signifies the end of tags, we have the opportunity to inject our recursive include into the stream at this point. What is hackish about this solution is the following: Reading one character at a time from a stream is slow. This has an implicit assumption about how the sax stream class is reading text. This solves the problem for me, but I'm still interested in a more beautiful solution.
[ "Have you considered using xinclude? The lxml library has builtin support for it.\n" ]
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003901419_python_xml.txt
Q: Multiproccessing with DB connection I have some processes with python gui application and i want to connect with them to sql server. i use the following modules form multiproccessing import pool import pymssql conn = pymssql.connect(host=host,user=user,password=password,database=database) for data in my_list : self.pool.apply_async(fun,data,conn) i it possible to use the same connection on all the processes or i need to open a new connection to the sql server with every processs. A: A new one for every process, because per definition processes can not share in memory ressources.
Multiproccessing with DB connection
I have some processes with python gui application and i want to connect with them to sql server. i use the following modules form multiproccessing import pool import pymssql conn = pymssql.connect(host=host,user=user,password=password,database=database) for data in my_list : self.pool.apply_async(fun,data,conn) i it possible to use the same connection on all the processes or i need to open a new connection to the sql server with every processs.
[ "A new one for every process, because per definition processes can not share in memory ressources.\n" ]
[ 4 ]
[]
[]
[ "multiprocessing", "python", "sql_server" ]
stackoverflow_0003905141_multiprocessing_python_sql_server.txt
Q: Not able to install a python module "Pycrypto-2.3" I tried installing a python module "Pycrypto-2.3".But its giving the following long list of errors: running install running build running build_py running build_ext building 'Crypto.PublicKey._fastmath' extension /usr/lib/python2.6/pycc -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/usr/include/python2.6 -c src/_fastmath.c -o build/temp.solaris-2.11-i86pc-2.6/src/_fastmath.o In file included from /usr/include/python2.6/Python.h:8, from src/_fastmath.c:32: /usr/include/python2.6/pyconfig.h:969:1: warning: "_FILE_OFFSET_BITS" redefined In file included from /usr/include/stdio.h:37, from src/_fastmath.c:30: /usr/include/sys/feature_tests.h:209:1: warning: this is the location of the previous definition src/_fastmath.c:34:17: gmp.h: No such file or directory src/_fastmath.c:39: error: syntax error before "n" src/_fastmath.c:42: error: syntax error before "m" The list is long.Though i have followed the correct steps of installation..Can anyone identify the problem, Thanks.. A: The following error: src/_fastmath.c:34:17: gmp.h: No such file or directory is probably the cause of your problems. It's part of the "gnu multiprecision library", and you need the "dev" part of it. On Debian. the package is libgmp2-dev, for Redhat it's gmp-devel. For other platforms you'll have to search yourself. A: It seems that as your on Solaris your going to have to go to the source: GMPlib It has good instructions and support there.
Not able to install a python module "Pycrypto-2.3"
I tried installing a python module "Pycrypto-2.3".But its giving the following long list of errors: running install running build running build_py running build_ext building 'Crypto.PublicKey._fastmath' extension /usr/lib/python2.6/pycc -std=c99 -O3 -fomit-frame-pointer -Isrc/ -I/usr/include/python2.6 -c src/_fastmath.c -o build/temp.solaris-2.11-i86pc-2.6/src/_fastmath.o In file included from /usr/include/python2.6/Python.h:8, from src/_fastmath.c:32: /usr/include/python2.6/pyconfig.h:969:1: warning: "_FILE_OFFSET_BITS" redefined In file included from /usr/include/stdio.h:37, from src/_fastmath.c:30: /usr/include/sys/feature_tests.h:209:1: warning: this is the location of the previous definition src/_fastmath.c:34:17: gmp.h: No such file or directory src/_fastmath.c:39: error: syntax error before "n" src/_fastmath.c:42: error: syntax error before "m" The list is long.Though i have followed the correct steps of installation..Can anyone identify the problem, Thanks..
[ "The following error:\nsrc/_fastmath.c:34:17: gmp.h: No such file or directory\n\nis probably the cause of your problems. It's part of the \"gnu multiprecision library\", and you need the \"dev\" part of it. On Debian. the package is libgmp2-dev, for Redhat it's gmp-devel. For other platforms you'll have to search ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003903863_python.txt
Q: Adding database module I am new to django I would like to start a project but when i run it i get this error Error loading MySQLdb module How do i add the MYSQL module or any other module for that matter A: Install it on your system, using either a native installer or package, via pip or easy_install, or by running setup.py in the tarball. A: you should install a mysql client and a mysql python client for that client. So you should execute following commands(For Debian systems) apt-get install mysql-client apt-get install python-mysqldb
Adding database module
I am new to django I would like to start a project but when i run it i get this error Error loading MySQLdb module How do i add the MYSQL module or any other module for that matter
[ "Install it on your system, using either a native installer or package, via pip or easy_install, or by running setup.py in the tarball.\n", "you should install a mysql client and a mysql python client for that client. So you should execute following commands(For Debian systems)\napt-get install mysql-client\napt-...
[ 2, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003905548_django_mysql_python.txt
Q: How to remove repeating non-adjacent string Given lines that look like the following: Blah \cite[9.1173]{Joyce:1986aa}\autocite[42]{Kenner:1970ab}\autocite[108]{Hall:1960aa} bbb.\n I’d like to remove the second (and any subsequent) occurrence of \autocite, resulting in the following: Blah \autocite[9.1173]{Joyce:1986aa}[42]{Kenner:1970ab}[108]{Hall:1960aa} bbb.\n I’m struggling to express this in regex form (I’m using the python 2.7 RE module), however, as I’m not sure how to formulate “remove only the second and subsequent occurrences of \autocite when followed by […]{…}, until a space or period is encountered”. A: Regular expressions are not a panacea. l = s.split('\\autocite') print '%s\\autocite%s' % (l[0], ''.join(l[1:])) A: If you absolutly want regexes you can use (?<=\\autocite)(.*?)\\autocite(.*) and replace with \1\2. But @Ignacio Vazquez-Abrams answer is way better an efficient.
How to remove repeating non-adjacent string
Given lines that look like the following: Blah \cite[9.1173]{Joyce:1986aa}\autocite[42]{Kenner:1970ab}\autocite[108]{Hall:1960aa} bbb.\n I’d like to remove the second (and any subsequent) occurrence of \autocite, resulting in the following: Blah \autocite[9.1173]{Joyce:1986aa}[42]{Kenner:1970ab}[108]{Hall:1960aa} bbb.\n I’m struggling to express this in regex form (I’m using the python 2.7 RE module), however, as I’m not sure how to formulate “remove only the second and subsequent occurrences of \autocite when followed by […]{…}, until a space or period is encountered”.
[ "Regular expressions are not a panacea.\nl = s.split('\\\\autocite')\nprint '%s\\\\autocite%s' % (l[0], ''.join(l[1:]))\n\n", "If you absolutly want regexes you can use (?<=\\\\autocite)(.*?)\\\\autocite(.*) and replace with \\1\\2.\nBut @Ignacio Vazquez-Abrams answer is way better an efficient.\n" ]
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003905509_python_regex.txt
Q: Change dtype of a single column in a 2d numpy array I am creating a 2d array full of zeros with the following line of code: MyNewArray=zeros([4,12],float) However, the first column will need to be populated with string-type textual data, while all the other columns will need to be populated with numerical data that can be manipulated mathematically. How can I edit the code above so that the first column in the matrix can be of the string data type while keeping all the other columns as float? A: You might want to use structured arrays MyNewArray = zeros(12, dtype='S10,f4,f4,f4') There are several ways of defining the structure, here I have defined 4 fields: one text with 10 characters, and three floats (you could write float instead of f4). It is important to note that the number of characters of the array has to be specified, for array memory management reasons. You won't be able to store strings longer than this maximum length. Each field is referenced by a field name, in this case, default field names f0 to f3 will been used. For example, to get the whole first column (the textual one): MyNewArray['f0'] Of course, you can modifiy field names as you wish.
Change dtype of a single column in a 2d numpy array
I am creating a 2d array full of zeros with the following line of code: MyNewArray=zeros([4,12],float) However, the first column will need to be populated with string-type textual data, while all the other columns will need to be populated with numerical data that can be manipulated mathematically. How can I edit the code above so that the first column in the matrix can be of the string data type while keeping all the other columns as float?
[ "You might want to use structured arrays\nMyNewArray = zeros(12, dtype='S10,f4,f4,f4')\n\nThere are several ways of defining the structure, here I have defined 4 fields: one text with 10 characters, and three floats (you could write float instead of f4).\nIt is important to note that the number of characters of the...
[ 5 ]
[]
[]
[ "2d", "arrays", "numpy", "python", "types" ]
stackoverflow_0003904289_2d_arrays_numpy_python_types.txt
Q: EOF while scanning triple-quoted string literal i've looked on the web and here but i didn't find an answer : here is my code zlib.decompress(""" xワᆳヤ=ラᄇHナs~Ʀᄑç\ムîà Z@ÑÁÔQÇlxÇÆïPP~ýVãì゙M6ÛÐ|ê֭ᄁᄂヤ=)}éÓUe﬿ö3ᄎᄌú"}ʿïÿ÷1þ8ñ́U÷ᄏñíLÒVi:`ᄈᄎL!Ê҆p6-%Fë^ヘ÷à,Q.K!ユô`ÄA!ÑêweÌ ÊÚAロYøøÂjôóᅠÂcñ䊧fᆴùテúN :nüzAÝ7%ᄌcdUタᄌ3ôPۂタlンyHᆲᄑ$/yzᄒíàヌ'ÕÓ&`|S!<'ᄂ÷Zļᄐ2ホモ;ニ(ÅÛfb!úü$ナテᄒ,9ßhàPᄎᄄێフÑbØὛホQᄍ-Ü}(n;ᄄホLヤ\^ï9ᆭᄍラDdВéÞ|åPOGᄂÐÙ%â&AÔë)ÎTÐC ᄐïc枢í%Èï!フᄋëiq*ᄌVKÐNᄡ[ᄁfOq{OᆭÆÊ,0GᄂリmtツᄈOᄌΥ$#îヘqbYᄆメUニᄉÞáP` ヨ×ᆵÃPwaレǩâ×)ハFcêÚ=!Åöᄊ )AFñᄈ/cMᄃ!NóNΈór?pàÜòXw Bvæ0ïçIÉoマ>5pᆭ-ØWÚNᄆùFᄆØPçÃþdᅠ;ル1[Oᄈホ~6ツᄈᆬŕìᄄޠ=øð@ネV﾿ᄅ)÷%ユÜib{HᄆKŅVlDCテîfÑWì÷ìáár.ワîv﾿<dᄎn~ú*ÁÕ7ýá}EsYᆵWᄂÈ:R×ãQңメ?Ø1vヘäツ~èR1ᄉÜ*ᄡónAᆬjmNoツユᄈÌښᆬf[8ᆭÛ>゙OWラ|ÌbDᄁÖ녡M=Ð÷èâミム'ÂÝÐ ;ë mᄎQÂäԤۢ:モᄆdᄎᄑLȂ1ᄈ_÷YZᆲNòÛ â\ロxÐlݵᆵムᆱøm5Ëá=ïoÍlMᆪ[×#Ypᅠトx[ÉÊyæツoモナz)ᆭᄀÝÏìò """) so it was a string that i got by zlib.compress an other string. How can i decompress this string ? Regards Bussiere A: The zlib.decompress should work if you pass it the output of zlib.compress. Since the compressed string is really not text it is a binary string. It will not play friendly with displaying to the terminal as you have found. You can use base64 encoding to give you something safe to drop into unittests, paste into code etc. >>> import zlib >>> a = zlib.compress('fooo') >>> b = a.encode('base64') >>> b 'eJxLy8/PBwAENgG0\n' >>> c = 'eJxLy8/PBwAENgG0\n'.decode('base64') >>> zlib.decompress(c) 'fooo' >>> zlib.decompress(a) 'fooo' a as an output is ok for binary transmission or saving to a file. b is friendly to use with the clipboard, send in email, etc. A: I would not have it in that representation. Use repr() in the other code to generate an ASCII-clean representation, and use that instead. Then just look for triple quotes in the result and break them up.
EOF while scanning triple-quoted string literal
i've looked on the web and here but i didn't find an answer : here is my code zlib.decompress(""" xワᆳヤ=ラᄇHナs~Ʀᄑç\ムîà Z@ÑÁÔQÇlxÇÆïPP~ýVãì゙M6ÛÐ|ê֭ᄁᄂヤ=)}éÓUe﬿ö3ᄎᄌú"}ʿïÿ÷1þ8ñ́U÷ᄏñíLÒVi:`ᄈᄎL!Ê҆p6-%Fë^ヘ÷à,Q.K!ユô`ÄA!ÑêweÌ ÊÚAロYøøÂjôóᅠÂcñ䊧fᆴùテúN :nüzAÝ7%ᄌcdUタᄌ3ôPۂタlンyHᆲᄑ$/yzᄒíàヌ'ÕÓ&`|S!<'ᄂ÷Zļᄐ2ホモ;ニ(ÅÛfb!úü$ナテᄒ,9ßhàPᄎᄄێフÑbØὛホQᄍ-Ü}(n;ᄄホLヤ\^ï9ᆭᄍラDdВéÞ|åPOGᄂÐÙ%â&AÔë)ÎTÐC ᄐïc枢í%Èï!フᄋëiq*ᄌVKÐNᄡ[ᄁfOq{OᆭÆÊ,0GᄂリmtツᄈOᄌΥ$#îヘqbYᄆメUニᄉÞáP` ヨ×ᆵÃPwaレǩâ×)ハFcêÚ=!Åöᄊ )AFñᄈ/cMᄃ!NóNΈór?pàÜòXw Bvæ0ïçIÉoマ>5pᆭ-ØWÚNᄆùFᄆØPçÃþdᅠ;ル1[Oᄈホ~6ツᄈᆬŕìᄄޠ=øð@ネV﾿ᄅ)÷%ユÜib{HᄆKŅVlDCテîfÑWì÷ìáár.ワîv﾿<dᄎn~ú*ÁÕ7ýá}EsYᆵWᄂÈ:R×ãQңメ?Ø1vヘäツ~èR1ᄉÜ*ᄡónAᆬjmNoツユᄈÌښᆬf[8ᆭÛ>゙OWラ|ÌbDᄁÖ녡M=Ð÷èâミム'ÂÝÐ ;ë mᄎQÂäԤۢ:モᄆdᄎᄑLȂ1ᄈ_÷YZᆲNòÛ â\ロxÐlݵᆵムᆱøm5Ëá=ïoÍlMᆪ[×#Ypᅠトx[ÉÊyæツoモナz)ᆭᄀÝÏìò """) so it was a string that i got by zlib.compress an other string. How can i decompress this string ? Regards Bussiere
[ "The zlib.decompress should work if you pass it the output of zlib.compress.\nSince the compressed string is really not text it is a binary string. It will not play friendly with displaying to the terminal as you have found.\nYou can use base64 encoding to give you something safe to drop into unittests, paste into...
[ 2, 0 ]
[]
[]
[ "eof", "python", "string" ]
stackoverflow_0003905025_eof_python_string.txt
Q: Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket here is my dirty little web server : class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("POST.*?HTTP") try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 36000) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) except : time.sleep(2) self.__init__() # Listen for incoming connections sock.listen(1) off = 2 self.message = "" while True: # Wait for a connection print >>sys.stderr, 'waiting for a connection' if off == 2 or off == 1: connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it while True: data = connection.recv(1024) print >>sys.stderr, 'received "%s"' % data if data: self.message = self.traitement(data) connection.sendall(self.message) connection.close() connection, client_address = sock.accept() else: print >>sys.stderr, 'no more data from', client_address break finally: # Clean up the connection connection.close() sock.close() del(sock) it works more or less but if i quit the server the port is still open and i can't reconnect on the same port. So i'am looking for a way to kill precedent socket or to exit in a nice way. Regards and thanks Bussiere A: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) Should do the trick.
Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket
here is my dirty little web server : class Serverhttp: def __init__(self): self.GET = re.compile("GET.*?HTTP") self.POST = re.compile("POST.*?HTTP") try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 36000) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) except : time.sleep(2) self.__init__() # Listen for incoming connections sock.listen(1) off = 2 self.message = "" while True: # Wait for a connection print >>sys.stderr, 'waiting for a connection' if off == 2 or off == 1: connection, client_address = sock.accept() try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it while True: data = connection.recv(1024) print >>sys.stderr, 'received "%s"' % data if data: self.message = self.traitement(data) connection.sendall(self.message) connection.close() connection, client_address = sock.accept() else: print >>sys.stderr, 'no more data from', client_address break finally: # Clean up the connection connection.close() sock.close() del(sock) it works more or less but if i quit the server the port is still open and i can't reconnect on the same port. So i'am looking for a way to kill precedent socket or to exit in a nice way. Regards and thanks Bussiere
[ "sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nShould do the trick.\n" ]
[ 4 ]
[]
[]
[ "kill", "python", "shutdown", "sockets" ]
stackoverflow_0003905832_kill_python_shutdown_sockets.txt
Q: Chromosome representation for real numbers? I am trying to solve a problem using genetic algorithms. The problem is to find the set of integral and real values that optimizes a function. I need to represent the problem using a binary string (simply because I understand the concept of crossover/mutation etc much better when applied to binary string chromosomes). A candidate solution S would be the set {I1, I2, ... IN, R1, R2, RM } Where the I variables are integers and the R variables are floating point numbers. I want to be able to transform the candidate solution S into a binary string, but I don't know how to encode the floating point numbers. Any ideas on how to encode the set S into a chromosome? Although the solution is supposed to be language agnostic, my prefered choice of language (in decreasing order of preference for this particular task) is: Python, C++, C BTW, I am coding the problem using Pyevolve A: No, I think that binary representation is wrong for your problem. Your basic data is not binary, so, why use binary? Do mutation and crossover on real and integer numbers, not on their binary representation. Simplest crossover: first parent: ABCDE where A, B, ... are floating points numbers, second parents MNOPQ. Choose randomly D, first spring: ABCDQ, second: MNOPE. A: i would suggest rethinking if you actually need the bit string representation.. the conversion from float to bit and back is a bit much maybe. if you could just stay with floating point values i.e. a single solution candidate is an array of N floats you can pass that easily to your evaluation function (objective function). then use crossover methods like simulated binary crossover (SBX, http://www.slideshare.net/paskorn/self-adaptive-simulated-binary-crossover-presentation) which mimics the effects you'd get after converting your floats to a binary representation and performing crossover on that. the results of SBX are pretty good and also the analogy to what woudl happen if you'd deal with bit strings becomes pretty clear after a while.. it looks like much in this slideshow.. but it all comes down to just a few lines of implementing the sbx crossover. A: You can pack binary data into buffers with the facilities provided in the struct module. See here: http://docs.python.org/library/struct.html That said, I personally love Python, BUT: if you want to repeatedly and efficiently take a set of integers and floating point numbers, treat it as one big bitsring, and apply bitwise mutation to it, I don't think Python is the best choice for a language. This is much more straightforward (and fast) in lower-level languages -- I'd go for C. Good luck with the algorithm! A: Use IEEE754 representation for floating-point numbers and two's complement representation for integers. Or, use integers and floating-point numbers, safe in the knowledge that behind the scenes your computer is already using these binary representations. A: If I understand the problem correctly, this is completely language agnostic. You should be able to represent the floating point number in the standardized IEEE representation. Here's a tutorial. Once you have that representation you don't what is what, you just apply whatever crossover (single, double point whatever) to your bits.
Chromosome representation for real numbers?
I am trying to solve a problem using genetic algorithms. The problem is to find the set of integral and real values that optimizes a function. I need to represent the problem using a binary string (simply because I understand the concept of crossover/mutation etc much better when applied to binary string chromosomes). A candidate solution S would be the set {I1, I2, ... IN, R1, R2, RM } Where the I variables are integers and the R variables are floating point numbers. I want to be able to transform the candidate solution S into a binary string, but I don't know how to encode the floating point numbers. Any ideas on how to encode the set S into a chromosome? Although the solution is supposed to be language agnostic, my prefered choice of language (in decreasing order of preference for this particular task) is: Python, C++, C BTW, I am coding the problem using Pyevolve
[ "No, I think that binary representation is wrong for your problem. Your basic data is not binary, so, why use binary? Do mutation and crossover on real and integer numbers, not on their binary representation.\nSimplest crossover: first parent: ABCDE where A, B, ... are floating points numbers, second parents MNOPQ....
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "genetic_algorithm", "python" ]
stackoverflow_0003885626_genetic_algorithm_python.txt
Q: Capturing output from buffered StdOut program I'm trying to capture the output of a windows program using Qt and Python. I'm starting the process with QProcess, but the problem is the output is being buffered. Unfortunately I don't have access to the source, and therefore can't flush the output. From my searching around, I found the program "Expect", but I don't know if there is a free Windows version floating around. It would be nice to do it purely in python though. A: Please take a look at QShared Memory http://doc.trolltech.com/main-snapshot/ipc-sharedmemory.html ... What you want to achieve is inter process communication, QShared memory works fine on Linux and Windows alike.
Capturing output from buffered StdOut program
I'm trying to capture the output of a windows program using Qt and Python. I'm starting the process with QProcess, but the problem is the output is being buffered. Unfortunately I don't have access to the source, and therefore can't flush the output. From my searching around, I found the program "Expect", but I don't know if there is a free Windows version floating around. It would be nice to do it purely in python though.
[ "Please take a look at QShared Memory http://doc.trolltech.com/main-snapshot/ipc-sharedmemory.html ... What you want to achieve is inter process communication, QShared memory works fine on Linux and Windows alike. \n" ]
[ 0 ]
[]
[]
[ "pyqt", "python", "stdout" ]
stackoverflow_0003902997_pyqt_python_stdout.txt
Q: Why thread is interrupted before the changes are complete I'm attempting to create python module for getting MAC adresses by IP addresses. def getMACs(addressesList): def _processArp(pkt): spa = _inet_ntoa(pkt.spa) if pkt.op == dpkt.arp.ARP_OP_REPLY and spa in _cache.macTable: lock.acquire() try: _cache.macTable[spa] = _packedToMacStr(pkt.sha) _cache.notFilledMacs -= 1 finally: lock.release() if _cache.notFilledMacs == 0: thrd.stop() addresses = _parseAddresses(addressesList) _cache.registerCacheEntry("macTable", {}) _cache.registerCacheEntry("notFilledMacs", 0) _events.arpPacket += _processArp lock = threading.Lock() thrd = _CaptureThread(promisc=False, timeout_ms=30, filter="arp") thrd.start() for addr in addresses: if _sendArpQuery(addr): _cache.macTable[str(addr)] = None _cache.notFilledMacs += 1 thrd.join(125) thrd.stop() return _cache.macTable if __name__ == "__main__": macTable = getMACs([IPAddress("192.168.1.1"), IPAddress("192.168.1.3")]) _pprint.pprint(macTable) When I run this module I get {'192.168.1.1': '00:11:95:9E:25:B1', '192.168.1.3': None} When I debug _processArp step by step I get {'192.168.1.1': '00:11:95:9E:25:B1', '192.168.1.3': '00:21:63:78:98:8E'} Class CaptureThread: class CaptureThread(threading.Thread): def __init__ (self, name=None, snaplen=65535, promisc=True, timeout_ms=0, immediate=False, filter=None): threading.Thread.__init__(self) self.__running = True self.__name = name self.__snaplen = snaplen self.__promisc = promisc self.__timeout_ms = timeout_ms self.__immediate = immediate self.__filter = filter def stop(self): self.__running = False def run(self): self.__pc = pcap.pcap(self.__name, self.__snaplen, self.__promisc, self.__timeout_ms, self.__immediate) if self.__filter: self.__pc.setfilter(self.__filter) while self.__running: self.__pc.dispatch(1, self.__processPacket) def __processPacket(self, timestamp, pkt): peth = dpkt.ethernet.Ethernet(pkt) if isinstance(peth.data, dpkt.arp.ARP): _events.arpPacket(peth.data) A: Stupid error. As always when working with threads - because of thread synchronization. One of my conditions for interrupting thread is "_cache.notFilledMacs == 0". In the main thread _cache.notFilledMacs did not have time to get the value of 2 when in the CaptureThread value is decreased.
Why thread is interrupted before the changes are complete
I'm attempting to create python module for getting MAC adresses by IP addresses. def getMACs(addressesList): def _processArp(pkt): spa = _inet_ntoa(pkt.spa) if pkt.op == dpkt.arp.ARP_OP_REPLY and spa in _cache.macTable: lock.acquire() try: _cache.macTable[spa] = _packedToMacStr(pkt.sha) _cache.notFilledMacs -= 1 finally: lock.release() if _cache.notFilledMacs == 0: thrd.stop() addresses = _parseAddresses(addressesList) _cache.registerCacheEntry("macTable", {}) _cache.registerCacheEntry("notFilledMacs", 0) _events.arpPacket += _processArp lock = threading.Lock() thrd = _CaptureThread(promisc=False, timeout_ms=30, filter="arp") thrd.start() for addr in addresses: if _sendArpQuery(addr): _cache.macTable[str(addr)] = None _cache.notFilledMacs += 1 thrd.join(125) thrd.stop() return _cache.macTable if __name__ == "__main__": macTable = getMACs([IPAddress("192.168.1.1"), IPAddress("192.168.1.3")]) _pprint.pprint(macTable) When I run this module I get {'192.168.1.1': '00:11:95:9E:25:B1', '192.168.1.3': None} When I debug _processArp step by step I get {'192.168.1.1': '00:11:95:9E:25:B1', '192.168.1.3': '00:21:63:78:98:8E'} Class CaptureThread: class CaptureThread(threading.Thread): def __init__ (self, name=None, snaplen=65535, promisc=True, timeout_ms=0, immediate=False, filter=None): threading.Thread.__init__(self) self.__running = True self.__name = name self.__snaplen = snaplen self.__promisc = promisc self.__timeout_ms = timeout_ms self.__immediate = immediate self.__filter = filter def stop(self): self.__running = False def run(self): self.__pc = pcap.pcap(self.__name, self.__snaplen, self.__promisc, self.__timeout_ms, self.__immediate) if self.__filter: self.__pc.setfilter(self.__filter) while self.__running: self.__pc.dispatch(1, self.__processPacket) def __processPacket(self, timestamp, pkt): peth = dpkt.ethernet.Ethernet(pkt) if isinstance(peth.data, dpkt.arp.ARP): _events.arpPacket(peth.data)
[ "Stupid error. As always when working with threads - because of thread synchronization.\nOne of my conditions for interrupting thread is \"_cache.notFilledMacs == 0\". In the main thread _cache.notFilledMacs did not have time to get the value of 2 when in the CaptureThread value is decreased.\n" ]
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003901766_multithreading_python.txt
Q: calculating means of many matrices in numpy I have many csv files which each contain roughly identical matrices. Each matrix is 11 columns by either 5 or 6 rows. The columns are variables and the rows are test conditions. Some of the matrices do not contain data for the last test condition, which is why there are 5 rows in some matrices and six rows in other matrices. My application is in python 2.6 using numpy and sciepy. My question is this: How can I most efficiently create a summary matrix that contains the means of each cell across all of the identical matrices? The summary matrix would have the same structure as all of the other matrices, except that the value in each cell in the summary matrix would be the mean of the values stored in the identical cell across all of the other matrices. If one matrix does not contain data for the last test condition, I want to make sure that its contents are not treated as zeros when the averaging is done. In other words, I want the means of all the non-zero values. Can anyone show me a brief, flexible way of organizing this code so that it does everything I want to do with as little code as possible and also remain as flexible as possible in case I want to re-use this later with other data structures? I know how to pull all the csv files in and how to write output. I just don't know the most efficient way to structure flow of data in the script, including whether to use python arrays or numpy arrays, and how to structure the operations, etc. I have tried coding this in a number of different ways, but they all seem to be rather code intensive and inflexible if I later want to use this code for other data structures. A: You could use masked arrays. Say N is the number of csv files. You can store all your data in a masked array A, of shape (N,11,6). from numpy import * A = ma.zeros((N,11,6)) A.mask = zeros_like(A) # fills the mask with zeros: nothing is masked A.mask = (A.data == 0) # another way of masking: mask all data equal to zero A.mask[0,0,0] = True # mask a value A[1,2,3] = 12. # fill a value: like an usual array Then, the mean values along first axis, and taking into account masked values, are given by: mean(A, axis=0) # the returned shape is (11,6)
calculating means of many matrices in numpy
I have many csv files which each contain roughly identical matrices. Each matrix is 11 columns by either 5 or 6 rows. The columns are variables and the rows are test conditions. Some of the matrices do not contain data for the last test condition, which is why there are 5 rows in some matrices and six rows in other matrices. My application is in python 2.6 using numpy and sciepy. My question is this: How can I most efficiently create a summary matrix that contains the means of each cell across all of the identical matrices? The summary matrix would have the same structure as all of the other matrices, except that the value in each cell in the summary matrix would be the mean of the values stored in the identical cell across all of the other matrices. If one matrix does not contain data for the last test condition, I want to make sure that its contents are not treated as zeros when the averaging is done. In other words, I want the means of all the non-zero values. Can anyone show me a brief, flexible way of organizing this code so that it does everything I want to do with as little code as possible and also remain as flexible as possible in case I want to re-use this later with other data structures? I know how to pull all the csv files in and how to write output. I just don't know the most efficient way to structure flow of data in the script, including whether to use python arrays or numpy arrays, and how to structure the operations, etc. I have tried coding this in a number of different ways, but they all seem to be rather code intensive and inflexible if I later want to use this code for other data structures.
[ "You could use masked arrays. Say N is the number of csv files. You can store all your data in a masked array A, of shape (N,11,6).\nfrom numpy import *\nA = ma.zeros((N,11,6))\nA.mask = zeros_like(A) # fills the mask with zeros: nothing is masked\nA.mask = (A.data == 0) # another way of masking: mask all data equa...
[ 2 ]
[]
[]
[ "arrays", "mean", "numpy", "python" ]
stackoverflow_0003904983_arrays_mean_numpy_python.txt
Q: Twisted factory protocol instance based callback Hey, I got a ReconnectingClientFactory and I wonder if I can somehow define protocol-instance-based connectionMade/connectionLost callbacks so that i can use the factory to connect to different hosts ans distinguish between each connection. Thanks in advance. A: No. Write a class that does the interaction with one user. In connectionMade you check if a instance of this class already exists, if not you make a new one and store it on the factory, ie in a { addr : handler } dict. If the connection exists alreay you get the old handler from the factory.
Twisted factory protocol instance based callback
Hey, I got a ReconnectingClientFactory and I wonder if I can somehow define protocol-instance-based connectionMade/connectionLost callbacks so that i can use the factory to connect to different hosts ans distinguish between each connection. Thanks in advance.
[ "No. Write a class that does the interaction with one user. In connectionMade you check if a instance of this class already exists, if not you make a new one and store it on the factory, ie in a { addr : handler } dict. If the connection exists alreay you get the old handler from the factory.\n" ]
[ 1 ]
[]
[]
[ "factory", "python", "twisted" ]
stackoverflow_0003905791_factory_python_twisted.txt