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: Recommendation Engin for One of a Kind "Products" A market we are building allows people to list their stuff to sell but in batches / bags / boxes. We are looking to build in a recommendation engine for this, but most of the articles out there seem better suited for markets that "sell" large quantities of many pr...
Recommendation Engin for One of a Kind "Products"
A market we are building allows people to list their stuff to sell but in batches / bags / boxes. We are looking to build in a recommendation engine for this, but most of the articles out there seem better suited for markets that "sell" large quantities of many products - ie amazon, netflix etc. Because every listing...
[ "There are several things you can filter with a recommendation engine. You can filter on what a particular user has bought before (in your case, which features have been present in the products they have bought). You can also filter on social groupings--users like them, or on product groupings--other products lik...
[ 2, 0 ]
[]
[]
[ "c++", "java", "python", "recommendation_engine", "ruby" ]
stackoverflow_0005426723_c++_java_python_recommendation_engine_ruby.txt
Q: Python code to animate a rotating fan to appear in place I need to print out rotating fan based on this answer with Python. import threading import subprocess I = 0 class RepeatingTimer(threading._Timer): def run(self): while True: self.finished.wait(self.interval) if self.fin...
Python code to animate a rotating fan to appear in place
I need to print out rotating fan based on this answer with Python. import threading import subprocess I = 0 class RepeatingTimer(threading._Timer): def run(self): while True: self.finished.wait(self.interval) if self.finished.is_set(): return else: ...
[ "\\n (new line) is automatically inserted by your print statement. The way to avoid it is to end your statement with a comma.\nIf you want your fan to be on a line on it's own, use:\nprint icons[I]+\"\\r\",\n\n\\r represents the carriage return.\nIf you want your fan to be at the end of a non-empty line, use \\b fo...
[ 3, 3, 1, 0 ]
[]
[]
[ "printing", "python" ]
stackoverflow_0005437395_printing_python.txt
Q: References to code sample of complex django models and views Where can I find good code samples and best practices in building complex django model structure and (non-generic) views? Tutorials usually comes with models and views with only one or two layers of models. (e.g. Polls and Choices in Django tutorials)...
References to code sample of complex django models and views
Where can I find good code samples and best practices in building complex django model structure and (non-generic) views? Tutorials usually comes with models and views with only one or two layers of models. (e.g. Polls and Choices in Django tutorials) I'm looking for code samples with hierarchy of models and best p...
[ "I'd recommend looking through and learning from some well written django projects on github or bitbucket. Django-cms has quite a few models and might be an example of what you're looking for:\nhttps://github.com/divio/django-cms/tree/develop/cms/models\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0005437323_django_django_models_django_views_python.txt
Q: Open file with Python DirSelector is it somehow possible to open a file (instead of a directory) with Python's DirSelector. It's also fine to make a wx.FileSelector to open also a directory. I just need one dialog window to open both, files and directories. A: You might be able to use the wx.GenericDirCtrl for t...
Open file with Python DirSelector
is it somehow possible to open a file (instead of a directory) with Python's DirSelector. It's also fine to make a wx.FileSelector to open also a directory. I just need one dialog window to open both, files and directories.
[ "You might be able to use the wx.GenericDirCtrl for this, although it's a little ugly. There's also the pure python MultiDirDialog widget which can be found in wx.lib.agw.multidirdialog. While it doesn't appear to support the display and selection of files now, since it's pure Python, you can probably hack it.\n" ]
[ 1 ]
[]
[]
[ "filedialog", "python", "wxpython" ]
stackoverflow_0005430272_filedialog_python_wxpython.txt
Q: How do I make my website on Google App Engine accessible to visitors in China? China blocks appspot -- How do I get around this? Assuming the censorship was not an issue, how bad are the latency issues? A: Assuming Google has, and routes to, Datacenters in Asia, the latency should be reasonable. The reverse prox...
How do I make my website on Google App Engine accessible to visitors in China?
China blocks appspot -- How do I get around this? Assuming the censorship was not an issue, how bad are the latency issues?
[ "Assuming Google has, and routes to, Datacenters in Asia, the latency should be reasonable.\nThe reverse proxy to avoid the firewall should be in a country that does not censor and is as near as possible to the target area.\nIn those conditions, google would choose a datacenter near your reverse proxy, and the late...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005436249_google_app_engine_python.txt
Q: Easiest "daytime" service client in Python? What's the easiest way to write a daytime client in Python? And if there's more data of unknown size but still plain text - how do I read until the server closes the connection? A: This works: #!/usr/bin/python import socket s = socket.socket(socket.AF_INET, socket.SOC...
Easiest "daytime" service client in Python?
What's the easiest way to write a daytime client in Python? And if there's more data of unknown size but still plain text - how do I read until the server closes the connection?
[ "This works:\n#!/usr/bin/python\nimport socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = \"time.nist.gov\"\nport = 13\ns.connect((host,port))\nwhile True:\n data = s.recv(10000)\n if data:\n print data\n else:\n break\n\ns.close()\n\n", "#!/usr/bin/env python\nimport so...
[ 4, 1, 0 ]
[]
[]
[ "networking", "python", "tcp" ]
stackoverflow_0001873214_networking_python_tcp.txt
Q: Any idea why i am getting this error? I am trying to install django-cms in my ubuntu pc. I am getting this error: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 43...
Any idea why i am getting this error?
I am trying to install django-cms in my ubuntu pc. I am getting this error: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute()...
[ "It's looking for a settings.CMS_TEMPLATES. It's trying to make None a tuple which would throw that error.\nMake sure you have a CMS_TEMPLATES defined.\nhttp://docs.django-cms.org/en/2.1.3/getting_started/tutorial.html#configuration-and-setup\n", "Your CMS_TEMPLATES settings is None, I have no idea what that is, ...
[ 2, 1, 1, 1 ]
[]
[]
[ "django", "django_cms", "python", "ubuntu" ]
stackoverflow_0005437768_django_django_cms_python_ubuntu.txt
Q: How to make an voice command program to android using python? I have a school project and I have this idea for my android phone. But I don't really know if it can be done and I don't know how I could do it. Does someone know if it can be done? If not can you write a programme for android using python? What is the ...
How to make an voice command program to android using python?
I have a school project and I have this idea for my android phone. But I don't really know if it can be done and I don't know how I could do it. Does someone know if it can be done? If not can you write a programme for android using python? What is the easiest way?
[ "The easiest way is using AppInventor from Google. It makes the programing of apps for Android a kids game.\n" ]
[ 1 ]
[]
[]
[ "android", "python", "voice_recognition" ]
stackoverflow_0004733022_android_python_voice_recognition.txt
Q: Runtime grammar productions creation I am interested in natural languge processing with python-django. My project requires creation of grammar productions at runtime. That means, whenever i ask a question or write a sentence, basic nlp steps like pos-tagging should be done and get them added to grammar productions...
Runtime grammar productions creation
I am interested in natural languge processing with python-django. My project requires creation of grammar productions at runtime. That means, whenever i ask a question or write a sentence, basic nlp steps like pos-tagging should be done and get them added to grammar productions or any other structure ( even if the word...
[ "NLTK is the most popular python framework for NLP processing as I know it can do POS tagging, deep parsing, and allow you to write extraction rules based on those outputs.\n" ]
[ 1 ]
[]
[]
[ "django", "nlp", "python" ]
stackoverflow_0005431571_django_nlp_python.txt
Q: How to get multiple values from a for loop? I have a list of records from a column, the list is named as dates. I am trying to get different dates out of the list. The list have many repetitive dates, such as 1/1/2010,1/1/2010, …. but there are different dates too. But if i use: for date in dates: .... it's repe...
How to get multiple values from a for loop?
I have a list of records from a column, the list is named as dates. I am trying to get different dates out of the list. The list have many repetitive dates, such as 1/1/2010,1/1/2010, …. but there are different dates too. But if i use: for date in dates: .... it's repeating the loop for every single date(no matter if...
[ "for date in set(dates):\n\nset() makes a collection out of the unique elements in another collection. Note: this may not preserve the order of the original list, so if you require that order to be preserved, go with @GregHewgill's answer.\n", "You can use the itertools module to group by the dates. For example:\...
[ 5, 5, 0, 0 ]
[]
[]
[ "for_loop", "python", "set", "unique_values" ]
stackoverflow_0005437451_for_loop_python_set_unique_values.txt
Q: Crop non symmetric area of an image with Python/PIL Is there a way to cut out non rectangular areas of an image with Python PIL? e.g. in this picture I want to exclude all black areas as well as towers, rooftops and poles. http://img153.imageshack.us/img153/5330/skybig.jpg I guess the ImagePath Module can do that,...
Crop non symmetric area of an image with Python/PIL
Is there a way to cut out non rectangular areas of an image with Python PIL? e.g. in this picture I want to exclude all black areas as well as towers, rooftops and poles. http://img153.imageshack.us/img153/5330/skybig.jpg I guess the ImagePath Module can do that, but furthermore, how can I read data of e.g. a svg file ...
[ "If I understood correctly, you want to make some areas transparent within the image. And these areas are random shaped. Easiest way (that I can think of) is to create a mask and put it to the alpha channel of the image. Below is a code that shows how to do this.\nIf your question was \"How to create a polygon mask...
[ 8 ]
[]
[]
[ "crop", "image_processing", "path", "python", "python_imaging_library" ]
stackoverflow_0003707567_crop_image_processing_path_python_python_imaging_library.txt
Q: python operator overload and friends I wanted to know if anyone could give me an example of how to overload an operator within a class, in my case the + operator. Could I define a function (not a class method) that does it? I'm a newbie so I don't really know how to do it. Thanks A: Define its __add__() method. ...
python operator overload and friends
I wanted to know if anyone could give me an example of how to overload an operator within a class, in my case the + operator. Could I define a function (not a class method) that does it? I'm a newbie so I don't really know how to do it. Thanks
[ "Define its __add__() method.\nSee here.\n", "class MyNum(object):\n def __init__(self, val):\n super(MyNum,self).__init__()\n self.val = val\n\n def __add__(self, num):\n return self.__class__.(self.val + num)\n\n def __str__(self):\n return self.__class__.__name__ + '(' + st...
[ 3, 2, 2 ]
[]
[]
[ "operator_keyword", "overloading", "python" ]
stackoverflow_0005438574_operator_keyword_overloading_python.txt
Q: how to show pixel array of an image in python or java??? help me I am new in python n java. I've given the task at my class for showing pixel array image from an image. Please help me?? Thanks A: Are you trying to get a 2D array if each pixel color? In the Java BufferedImage class, there is the method: getRGB(in...
how to show pixel array of an image in python or java??? help me
I am new in python n java. I've given the task at my class for showing pixel array image from an image. Please help me?? Thanks
[ "Are you trying to get a 2D array if each pixel color? In the Java BufferedImage class, there is the method:\ngetRGB(int x, int y)\n\nTherefore, you could just loop through each pixel and add it to your array, like this:\nint[][] array = new int[img.getWidth()][img.getHeight()];\nfor (int i = 0; i < img.getWidth();...
[ 1, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0005427198_java_python.txt
Q: Replace the built-in min functions in python I should write a function min_in_list(munbers), which takes a list of numbers and returns the smallest one. NOTE: built-in function min is NOT allowed! def min_in_list(numbers): the_smallest = [n for n in numbers if n < n+1] return the_smallest What's wrong? A...
Replace the built-in min functions in python
I should write a function min_in_list(munbers), which takes a list of numbers and returns the smallest one. NOTE: built-in function min is NOT allowed! def min_in_list(numbers): the_smallest = [n for n in numbers if n < n+1] return the_smallest What's wrong?
[ "def min_of_two(x, y):\n if x >= y: return x\n else: return y\n\ndef min_in_list(numbers):\n return reduce(min_of_two, numbers)\n\nYou have to produce 1 number from list, not just another list. And this is work for reduce function (of course, you can implement it without reduce, but by analogy with it).\n"...
[ 1, 0, 0 ]
[]
[]
[ "min", "python" ]
stackoverflow_0004008897_min_python.txt
Q: How to override nested blocks in Jinja2 If I define a block inside a block in a Jinja template, and extend it, How do I reference the nested block in the child template? A: You reference the nested block the same way you reference any block, e.g., given {% block outer_block %} Outer things {% block inner_bl...
How to override nested blocks in Jinja2
If I define a block inside a block in a Jinja template, and extend it, How do I reference the nested block in the child template?
[ "You reference the nested block the same way you reference any block, e.g., given\n{% block outer_block %} \n Outer things\n {% block inner_block %}\n Inner things\n {% endblock %}\n More outer things\n{% endblock %}\n\nYou'd override inner_block with \n{% block inner_block %} \n customized inner content\n...
[ 14 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0005436590_jinja2_python.txt
Q: Building boost library I'm trying to build boost library under Arch Linux $ uname -a Linux wincode 2.6.37-ARCH #1 SMP PREEMPT Fri Feb 25 07:53:43 CET 2011 x86_64 AMD Athlon(tm) 64 X2 Dual Core Processor 5200+ AuthenticAMD GNU/Linux $ python --version Python 3.2 $ ls /usr/include/python python2.7/ python3.2mu/ ...
Building boost library
I'm trying to build boost library under Arch Linux $ uname -a Linux wincode 2.6.37-ARCH #1 SMP PREEMPT Fri Feb 25 07:53:43 CET 2011 x86_64 AMD Athlon(tm) 64 X2 Dual Core Processor 5200+ AuthenticAMD GNU/Linux $ python --version Python 3.2 $ ls /usr/include/python python2.7/ python3.2mu/ $ ls /usr/lib/python python...
[ "Quick google search comes up with http://lists.boost.org/boost-build/2006/04/13457.php.\nBasically, add your python include directory to the include search paths.\n" ]
[ 0 ]
[]
[]
[ "boost", "c++", "compilation", "python" ]
stackoverflow_0005273038_boost_c++_compilation_python.txt
Q: Accessing the Rotation of a blender Object I'm just starting out with Blender and Python and I've been trying to access the rotation properties of a cube using the blender game engine with Python 2.5.1 I have this python script attached to a cube in my scene: cont = GameLogic.getCurrentController() own = cont.owne...
Accessing the Rotation of a blender Object
I'm just starting out with Blender and Python and I've been trying to access the rotation properties of a cube using the blender game engine with Python 2.5.1 I have this python script attached to a cube in my scene: cont = GameLogic.getCurrentController() own = cont.owner print own.RotX, own.RotY, own.RotZ All I get...
[ "You can use the property localOrientation, which seems to be the only way to access rotation in the game engine without using the motion actuator which doesn't allow the printing of the current rotation.\nlocalOrientation consists of a list of lists, or a 3x3 matrix. each row of the matrix is a point that the corr...
[ 3, 1 ]
[]
[]
[ "blender", "game_engine", "python", "rotation" ]
stackoverflow_0005432722_blender_game_engine_python_rotation.txt
Q: Separate city and state in string? A string, citystate, could be formatted like: "Greenwich, CT" "Greenwich,CT" "Greenwich CT" How can I split the string, citystate, into two separate strings, city and state (using Python)? (such that city == Greenwich and state == CT) Thanks for the help! A: import re city, sta...
Separate city and state in string?
A string, citystate, could be formatted like: "Greenwich, CT" "Greenwich,CT" "Greenwich CT" How can I split the string, citystate, into two separate strings, city and state (using Python)? (such that city == Greenwich and state == CT) Thanks for the help!
[ "import re\ncity, state = re.split(r' ?,? ?', location)\n\nTo solve the New York, NY problem, use slicing:\nsplit_loc = re.split(r' ?,? ?', location)\ncity = ' '.join(split_loc[:-1]) # Everything up to last element joined by space\nstate = split_loc[-1]\n\n", "Making some assumptions:\n(1) A state code is two cha...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005436334_python.txt
Q: Overwrite entire object in place x = something_mutable y = x z = x # sometime later make z reference something else, e.g. a list my_list = [1, 2, 3] # how to make x, y, z to reference my_list without using x and y explicitly ??? Is it possible? Not really going to use it, but curious. Related question. How to e...
Overwrite entire object in place
x = something_mutable y = x z = x # sometime later make z reference something else, e.g. a list my_list = [1, 2, 3] # how to make x, y, z to reference my_list without using x and y explicitly ??? Is it possible? Not really going to use it, but curious. Related question. How to erase the entire list/dictionary conten...
[ "In answer to the first question: You can't do it, and if you could then you shouldn't.\nIn answer to the second question: For a list, a[:]=b. For a dict, a.clear(); a.update(b).\n", "The thing to remember about Python is that you have objects, which are chunks of data that are \"out there\" somewhere; and you ha...
[ 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005438362_python.txt
Q: Carry a variable across two files in different classes I want to carry the variable user once a person is logged in, to another file that will populate or carry over that user variable so that I can use it in an SQL Statement. def ViewScore(self, event): root = Tk() root.title("You last 5 attempts for ...
Carry a variable across two files in different classes
I want to carry the variable user once a person is logged in, to another file that will populate or carry over that user variable so that I can use it in an SQL Statement. def ViewScore(self, event): root = Tk() root.title("You last 5 attempts for this topic") user = user_management.getuser() app = ...
[ "I'm guessing the function that sets sql is some kind of GUI callback, not something you'd be calling directly with arguments. Have you tried calling a function in UserScore.py that sets a global variable, then having the function that sets sql access that global variable?\nProbably not the most Pythonic way to do ...
[ 0 ]
[]
[]
[ "class", "global", "methods", "python", "static" ]
stackoverflow_0005439015_class_global_methods_python_static.txt
Q: Pylons and Facebook The following is my oauth template top.location.href='https://graph.facebook.com/oauth/authorize?client_id=${config['facebook.appid']}&redirect_uri=${config['facebook.callbackurl']}&display=page&scope=publish_stream'; Click here to authorize this application When I hit the page I am prompted...
Pylons and Facebook
The following is my oauth template top.location.href='https://graph.facebook.com/oauth/authorize?client_id=${config['facebook.appid']}&redirect_uri=${config['facebook.callbackurl']}&display=page&scope=publish_stream'; Click here to authorize this application When I hit the page I am prompted to login (desired), ...
[ "I think you should modify your code to look like this\ndef index(self):\n if request.params.has_key('session'):\n access_token = simplejson.loads(request.params['session'])['access_token']\n graph = facebook.GraphAPI(access_token)\n tmpl_context.user = graph.get_object(\"me\")\n return rende...
[ 1 ]
[]
[]
[ "facebook", "pylons", "python" ]
stackoverflow_0005370555_facebook_pylons_python.txt
Q: Python subprocess to call Unix commands, a question about how output is stored I am writing a python script that reads a line/string, calls Unix, uses grep to search a query file for lines that contain the string, and then prints the results. from subprocess import call for line in infilelines: output = call...
Python subprocess to call Unix commands, a question about how output is stored
I am writing a python script that reads a line/string, calls Unix, uses grep to search a query file for lines that contain the string, and then prints the results. from subprocess import call for line in infilelines: output = call(["grep", line, "path/to/query/file"]) print output print line` When I look...
[ "call returns the process return code.\nIf using Python 2.7, use check_output.\nfrom subprocess import check_output\noutput = check_output([\"grep\", line, \"path/to/query/file\"])\n\nIf using anything before that, use communicate.\nimport subprocess\nprocess = subprocess.Popen([\"grep\", line, \"path/to/query/file...
[ 6, 4 ]
[ "Why would you want to execute a call to external grep when Python itself can do it? This is extra overhead and your code will then be dependent on grep being installed. This is how you do simple grep in Python with \"in\" operator.\nquery=open(\"/path/to/query/file\").readlines()\nquery=[ i.rstrip() for i in quer...
[ -2 ]
[ "call", "python", "subprocess", "unix" ]
stackoverflow_0005437156_call_python_subprocess_unix.txt
Q: Python - Check If Multiple String Entries Contain Invalid Chars Using Python v2.x, I have 3 variables that I want to ask the user for, as below: def Main(): Class_A_Input = int(raw_input('Enter Class A tickets sold: ')) Class_B_Input = int(raw_input('Enter Class B tickets sold: ')) Class_C_Input = int(...
Python - Check If Multiple String Entries Contain Invalid Chars
Using Python v2.x, I have 3 variables that I want to ask the user for, as below: def Main(): Class_A_Input = int(raw_input('Enter Class A tickets sold: ')) Class_B_Input = int(raw_input('Enter Class B tickets sold: ')) Class_C_Input = int(raw_input('Enter Class C tickets sold: ')) How can I check if the us...
[ "Calling int on something that isn't a valid integer will raise a ValueError exception. You can just catch that. Or is there some further restriction you want that goes beyond that?\n", "\nimport sys\ntry:\n Class_A_Input = int(raw_input('Enter Class A tickets sold: '))\nexcept ValueError:\n print \"First i...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005439731_python.txt
Q: Python & Matplotlib - Creating date ticks from string I have an array of strings which contain dates formatted as such: '01/01/09'. I also have an array of floats with the date values. I want to take these dates and ultimately display them as x tick labels on my graph. How do I use the floats or strings to label t...
Python & Matplotlib - Creating date ticks from string
I have an array of strings which contain dates formatted as such: '01/01/09'. I also have an array of floats with the date values. I want to take these dates and ultimately display them as x tick labels on my graph. How do I use the floats or strings to label the ticks on the x-axis on my matplotlib graph? (using somet...
[ "You set the count (and values) of the ticks using set_xticks. You set the text of the ticks using set_xticklabels\nfrom matplotlib import pyplot as plt\nplt.plot([1,2,3],[3,4,3])\nax = plt.gca()\nax.set_xticks([1,2,3])\nax.set_xticklabels(['1/1','1/2','1/3'])\n\n" ]
[ 7 ]
[]
[]
[ "datetime", "matplotlib", "plot", "python" ]
stackoverflow_0005439708_datetime_matplotlib_plot_python.txt
Q: Python: Test if dictionary (dict) entry has been modified I have written a small wrapper for the dict built-in class that loads entries (values) of a dictionary from cPickled files as soon as the respective key is first accessed. When the dictionary is destroyed all loaded entries are written back to disk. Now it ...
Python: Test if dictionary (dict) entry has been modified
I have written a small wrapper for the dict built-in class that loads entries (values) of a dictionary from cPickled files as soon as the respective key is first accessed. When the dictionary is destroyed all loaded entries are written back to disk. Now it would be convenient if I could check if any of the values has b...
[ "I think that you can overwrite the __setitem__() method to keep track of the changes of the values, storing the changed values in a list, and use this list to choose the correct values to write out.\n", "I might approach it with a sort of publish-subscribe model, where the containing dictionary subscribes to ea...
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "wrapper" ]
stackoverflow_0005431185_dictionary_python_wrapper.txt
Q: Flaskr SyntaxError I'm trying out the Flaskr tutorial(http://flask.pocoo.org/docs/) and I got the following error after I tried to run flaskr.py using the terminal: if __name__ == '__main__': ^ SyntaxError: invalid syntax I have absolutely no idea why I got this error. Can someone hel...
Flaskr SyntaxError
I'm trying out the Flaskr tutorial(http://flask.pocoo.org/docs/) and I got the following error after I tried to run flaskr.py using the terminal: if __name__ == '__main__': ^ SyntaxError: invalid syntax I have absolutely no idea why I got this error. Can someone help me please?
[ "You have forgotten a closing parenthesis in your return line, above your if __name__ == \"__main__\": statement, you put\nreturn redirect(url_for('show_entries')\n\nand it should be\nreturn redirect(url_for('show_entries'))\n\n" ]
[ 14 ]
[]
[]
[ "flask", "python", "web_frameworks" ]
stackoverflow_0005439917_flask_python_web_frameworks.txt
Q: Python - Check If Multiple String Entries Contain Invalid Chars Using Python v2.x, I have 3 variables that I want to ask the user for, as below: def Main(): chars = set('0123456789') while True: Class_A_Input = raw_input('Enter Class A tickets sold: ') Class_B_Input = raw_input('Enter Clas...
Python - Check If Multiple String Entries Contain Invalid Chars
Using Python v2.x, I have 3 variables that I want to ask the user for, as below: def Main(): chars = set('0123456789') while True: Class_A_Input = raw_input('Enter Class A tickets sold: ') Class_B_Input = raw_input('Enter Class B tickets sold: ') Class_C_Input = raw_input('Enter Class C ...
[ "def getInt(msg):\n while True:\n try:\n return int(raw_input(msg))\n except ValueError:\n pass\n\ndef total_profit(a, b, c):\n return 35.0*a + 25.0*b + 10.0*c\n\ndef main():\n class_a = getInt('Enter Class A tickets sold: ')\n class_b = getInt('Enter Class B tickets ...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005439786_python.txt
Q: How do I generate a file using the mac os9 line terminators? I need a 10MB file for testing. It needs to be line terminated with \r I believe that unixes uses \n and windows uses \r\n. How do I generate this file in python or java ? A: with open("mac", "wb") as f: for ind in xrange(1000000): f.writ...
How do I generate a file using the mac os9 line terminators?
I need a 10MB file for testing. It needs to be line terminated with \r I believe that unixes uses \n and windows uses \r\n. How do I generate this file in python or java ?
[ "with open(\"mac\", \"wb\") as f:\n for ind in xrange(1000000):\n f.write(\"a\" * 9 + \"\\r\")\n\nThe 'b' prevents Windows from screwing up your line endings. \nOn Python 3, it also means you have to write bytes instead of strings to the file. As a consequence, you need to change the last line to:\nf.wr...
[ 3 ]
[ "if you already have a file that's ~10MB and have Perl available, its as easy as:\nperl -pi -e 's/\\n/\\r/' file.txt\n\nwhere file.txt is the file you want to operate on. this will replace every lf with a cr. if you open the file in vi or something else that lets you see eol characters, it should look like one re...
[ -2 ]
[ "java", "python" ]
stackoverflow_0005440155_java_python.txt
Q: String Interpolation Causing MysqlDB Errors I'm trying to use mysqlDB, but I've run into a problem that doesn't make sense to me at all. My problem is centered around the table name in the following execute statements. This works: c.execute(u'''insert into AIN0 (Date_Info, Raw_Data, Calculation_Formula, Calculated...
String Interpolation Causing MysqlDB Errors
I'm trying to use mysqlDB, but I've run into a problem that doesn't make sense to me at all. My problem is centered around the table name in the following execute statements. This works: c.execute(u'''insert into AIN0 (Date_Info, Raw_Data, Calculation_Formula, Calculated_Data) values (%s, %s, %s, %s)''', ...
[ "If by \"string interpolation\" you mean like Python's string formatting, that's NOT what you are using. cursor.execute() does SQL parameter insertion, which has its own set of rules. The confusion happens because some database interfaces (including mysqlDB) use %s as a placeholder ... other database interfaces use...
[ 4 ]
[]
[]
[ "interpolation", "mysql", "mysql_python", "python", "string" ]
stackoverflow_0005440346_interpolation_mysql_mysql_python_python_string.txt
Q: Include / extend modules in python I don't now if this is the correct title for my question, I don't know how this is called in python specifically. What I want is "simple". I have a file 1.py which says: x = 10 And I have another which is 2.py print x Which should print ten. What I'm searching for is is the equ...
Include / extend modules in python
I don't now if this is the correct title for my question, I don't know how this is called in python specifically. What I want is "simple". I have a file 1.py which says: x = 10 And I have another which is 2.py print x Which should print ten. What I'm searching for is is the equivalente of extends in Java or or includ...
[ "How about import?\nfrom file1 import x\nprint x\n\nOr:\nimport file1\nprint file1.x\n\nThe first imports x into the global namespace, the second imports file1's namespace.\nThis is not similar to extends in Java (it's actually very similar to import in Java), that would be accomplished using Python inheritance:\nc...
[ 2 ]
[]
[]
[ "import", "include", "python" ]
stackoverflow_0005440397_import_include_python.txt
Q: Python - Check Multiple String Value For Chars I know this is a double up of the other questions I have asked today. But this is the most current, and I have put in for the others to be deleted. This is my code currently: def Main(): chars = set('0123456789') while True: Class_A_Input = raw_input('Enter Class ...
Python - Check Multiple String Value For Chars
I know this is a double up of the other questions I have asked today. But this is the most current, and I have put in for the others to be deleted. This is my code currently: def Main(): chars = set('0123456789') while True: Class_A_Input = raw_input('Enter Class A tickets sold: ') Class_B_Input = raw_input('En...
[ "I think you want to check if the input of users has digit number, if that is right,\nthen you can use \nimport re\n\ndef hasDigit(s):\n return not not re.search(\"\\d\", s)\n\ndef Main():\n while True:\n Class_A_Input = raw_input('Enter Class A tickets sold: ')\n Class_B_Input = raw_input('Ent...
[ 2, 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0005440352_python_while_loop.txt
Q: The Pythonic way of validating a long chain of conditions in Python So I have a long chain of conditions that should be validated to be true. Instead of chaining a long if condition, I tried to be "innovative" and did it this way, which I reckon is more readable. But my question is, is this the optimal way of doin...
The Pythonic way of validating a long chain of conditions in Python
So I have a long chain of conditions that should be validated to be true. Instead of chaining a long if condition, I tried to be "innovative" and did it this way, which I reckon is more readable. But my question is, is this the optimal way of doing it? Or is there a pythonic way of doing it? PS: Please respond with an ...
[ "A simpler approach is to build a tuple of the conditions and compare the tuples:\ndef site_info(s):\n return s.getId(), s.getName(), s.getCustomer().getId()\n\nif site_info(site) == site_info(site_listing):\n return site_listing\nelse:\n continue\n\nIf you have a lot of conditions, or the conditions are e...
[ 10, 6, 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005431613_python.txt
Q: Beautifulsoup: how to getting elements between other elements html: <h2>...</h2> <p>...</p> <p>...</p> <p>...</p> <h2>...</h2> <p>...</p> <p>...</p> <p>...</p> <p>...</p> Expected result: <p>...</p> <p>...</p> <p>...</p> I mean, getting all content between h2 elements A: Every element has a nextSibling method...
Beautifulsoup: how to getting elements between other elements
html: <h2>...</h2> <p>...</p> <p>...</p> <p>...</p> <h2>...</h2> <p>...</p> <p>...</p> <p>...</p> <p>...</p> Expected result: <p>...</p> <p>...</p> <p>...</p> I mean, getting all content between h2 elements
[ "Every element has a nextSibling method, so you can just get the first h2 element, then loop through the next siblings until you hit the second element.\nPseudo Code (assuming firstElem is the h2 element):\np_tags = []\nnext = firstElem.nextSilbing\nwhile next.name != \"h2\":\n p_tags.append(next)\n next = next.n...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0005440098_beautifulsoup_python_web_scraping.txt
Q: How can I group a large dataset I have simple text file containing two columns, both integers 1 5 1 12 2 5 2 341 2 12 and so on.. I need to group the dataset by second value, such that the output will be. 5 1 2 12 1 2 341 2 Now the problem is that the file is very big around 34 Gb in size, I tried writing a pyt...
How can I group a large dataset
I have simple text file containing two columns, both integers 1 5 1 12 2 5 2 341 2 12 and so on.. I need to group the dataset by second value, such that the output will be. 5 1 2 12 1 2 341 2 Now the problem is that the file is very big around 34 Gb in size, I tried writing a python script to group them into a dicti...
[ "Assuming you have ~17 characters per line (a number I picked randomly to make the math easier), you have about 2 billion records in this file. Unless you are running with much physical memory on a 64-bit system, you will thrash your pagefile to death trying to hold all this in memory in a single dict. And that's...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "apache_pig", "data_structures", "hadoop", "python" ]
stackoverflow_0003403800_apache_pig_data_structures_hadoop_python.txt
Q: Which GTK widget combination to use for scrollable column of widgets? I'm working with PyGTK, trying to come up with a combination of widgets that will do the following: Let me add an endless number of widgets in a column Provide a vertical scrollbar to get to the ones that run off the bottom Make the widgets' wi...
Which GTK widget combination to use for scrollable column of widgets?
I'm working with PyGTK, trying to come up with a combination of widgets that will do the following: Let me add an endless number of widgets in a column Provide a vertical scrollbar to get to the ones that run off the bottom Make the widgets' width adjust to fill available horizontal space when the window is resized T...
[ "\nAn endless number of widgets in a column: Sounds like a GtkVBox.\nVertical scrollbar: Put your VBox in a GtkScrolledWindow.\nHorizontal stretching: This requires setting the appropriate properties for the VBox, ScrolledWindow, and your other widgets. At least in Glade the defaults seem to mostly handle this ...
[ 8, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "widget" ]
stackoverflow_0000474034_gtk_pygtk_python_widget.txt
Q: Access properties of navigation buttons in wxPython's wxWizard I'm using the wxWizard widget in wxPython. Is there any way I could change the text of the next button on a page? Can i change the visibility of the navigation buttons on any page? Can I enable/disable the navigation buttons? I tried looking for answer...
Access properties of navigation buttons in wxPython's wxWizard
I'm using the wxWizard widget in wxPython. Is there any way I could change the text of the next button on a page? Can i change the visibility of the navigation buttons on any page? Can I enable/disable the navigation buttons? I tried looking for answers to these questions on the wxPython site but it doesn't seem to be ...
[ "Use wx.FindWindowById(wx.ID_FORWARD) this will return a wxWindow object representing the Next button. Call methods on it. e.g. \nwx.FindWindowById(wx.ID_FORWARD).disable() would disable the Next Button.\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002829993_python_wxpython.txt
Q: Counting recursion in a python program! I need to count the number of times recursion in a python program. So basically I need a static variable kind of thing (like in C) which can count the number of times the function is called. A: Just pass a counter with the recursion def recur(n, count=0): if n == 0: ...
Counting recursion in a python program!
I need to count the number of times recursion in a python program. So basically I need a static variable kind of thing (like in C) which can count the number of times the function is called.
[ "Just pass a counter with the recursion\ndef recur(n, count=0):\n if n == 0:\n return \"Finished count %s\" % count\n return recur(n-1, count+1)\n\nOr im sure there is some fancy decorator, Im gonna investigate that now...\n", "Another method using global:\n>>> def recur(n):\n... global counter\n...
[ 44, 20, 9, 5, 1 ]
[]
[]
[ "python", "recursion", "static" ]
stackoverflow_0005441244_python_recursion_static.txt
Q: Python Dicts : Needed a better output guys I've written a piece of code which gives the output. Now, this is a trie. Now I want to display in a aesthetic manner. Someone help me out here . My representation should be like this http://en.wikipedia.org/wiki/File:Trie_example.svg But what I want is how to convert thi...
Python Dicts : Needed a better output
guys I've written a piece of code which gives the output. Now, this is a trie. Now I want to display in a aesthetic manner. Someone help me out here . My representation should be like this http://en.wikipedia.org/wiki/File:Trie_example.svg But what I want is how to convert this huge monster output to the neat output li...
[ "You should try Pydot ! This package allow you to create some graphs line :\nimport pydot \n\nedges = [(1,2), (1,3), (1,4), (3,4)] \ng = pydot.graph_from_edges(edges) \ng.write_jpeg('graph_from_edges_dot.jpg', prog='dot')\n\n\nTo install it :\npip install pydot\n\n(you can also use easy_install or PyPM if you prefe...
[ 16 ]
[]
[]
[ "dictionary", "python", "trie" ]
stackoverflow_0005441555_dictionary_python_trie.txt
Q: patching text files I'm trying to successively build up a text file with diff patches. starting from an empty text file I need to apply 600+ patches to end up with the final document (a text I have written + tracked the changes with mercurial). to each change in the file extra information needs to be added, so I c...
patching text files
I'm trying to successively build up a text file with diff patches. starting from an empty text file I need to apply 600+ patches to end up with the final document (a text I have written + tracked the changes with mercurial). to each change in the file extra information needs to be added, so I can't simply use diff and ...
[ "there was indeed a bug in the code -- I wasn't interpreting the diff files correctly (didn't realize there needed to be a line shift, when there are multiple hunks in one diff file)\ndef process_diff(filename, date, step_nr):\n merge_file = open(\"thesis_merged.txt\", \"r\")\n merge_file_lines = [line.rstrip...
[ 1, 0 ]
[]
[]
[ "diff", "patch", "python" ]
stackoverflow_0004717732_diff_patch_python.txt
Q: Boost/Python: How can I use/convert extracted objects? Suppose: using namespace boost::python; void myClass::test(numeric::array& arrayParam) { const tuple &shape = extract<tuple>(arrayParam.attr("shape")); } I would like to transform it to an int and print for example. I tried int x = shape[0]; but it gives ...
Boost/Python: How can I use/convert extracted objects?
Suppose: using namespace boost::python; void myClass::test(numeric::array& arrayParam) { const tuple &shape = extract<tuple>(arrayParam.attr("shape")); } I would like to transform it to an int and print for example. I tried int x = shape[0]; but it gives me a "cannot convert ‘boost::python::api::const_object_item’...
[ "shape[0] gives you a Python object. To convert it to an int or another C++ type, you need to extract the value:\nint x = extract<int>(shape[0]);\n\n" ]
[ 10 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0005440447_boost_boost_python_c++_python.txt
Q: How to make this script "thread-safe"? import os, sys, time from threading import Thread from threading import currentThread import SimpleXMLRPCServer servAddr = ("localhost", 8000) serv = SimpleXMLRPCServer.SimpleXMLRPCServer(servAddr) tt = [] import SimpleXMLRPCServer class myThread(Thread): def __ini...
How to make this script "thread-safe"?
import os, sys, time from threading import Thread from threading import currentThread import SimpleXMLRPCServer servAddr = ("localhost", 8000) serv = SimpleXMLRPCServer.SimpleXMLRPCServer(servAddr) tt = [] import SimpleXMLRPCServer class myThread(Thread): def __init__ (self,p): self.p = p Th...
[ "Python objects like dict are already thread safe, so in that sense your script is already thread safe. What other specific thing you want to make thread safe, at-least for now it looks ok\n" ]
[ 2 ]
[ "I am not really familiar with python, but can't you use Semaphores / Monitors for atomic insurance? \n" ]
[ -2 ]
[ "multithreading", "python", "thread_safety" ]
stackoverflow_0005441522_multithreading_python_thread_safety.txt
Q: Python: threading + lock slows my app down considerably Say I have a function that writes to a file. I also have a function that loops repeatedly reading from said file. I have both of these functions running in separate threads. (Actually I am reading/writing to registers via MDIO which is why I can't have both t...
Python: threading + lock slows my app down considerably
Say I have a function that writes to a file. I also have a function that loops repeatedly reading from said file. I have both of these functions running in separate threads. (Actually I am reading/writing to registers via MDIO which is why I can't have both threads executing concurrently, only one or the other, but for...
[ "Do you use threading on a multicore machine? \nIf the answer is yes, then unless your Python version is 3.2+ you are going to suffer reduced performance when running threaded applications.\nDavid Beazly has put considerable effort to find what is going on with GIL on multicores and has made it easy for the rest of...
[ 4, 4 ]
[]
[]
[ "locking", "multithreading", "python" ]
stackoverflow_0005426533_locking_multithreading_python.txt
Q: SQLAlchemy model definition at execution I'm writing an ORM using Elixir and SQLAlchemy to handle moving spreadsheet-like data into SQL. In general, the content of the spreadsheet-like data is unknown, and pyparsing parses (meta) data about the spreadsheet-like data from a text file (example: the census publishes...
SQLAlchemy model definition at execution
I'm writing an ORM using Elixir and SQLAlchemy to handle moving spreadsheet-like data into SQL. In general, the content of the spreadsheet-like data is unknown, and pyparsing parses (meta) data about the spreadsheet-like data from a text file (example: the census publishes the Current Population Survey in fixed with f...
[ "My first thought would be that elixir won't benefit you much towards a solution.\nMy advice would be to go with 2) in that you try to build up a table based on the metadata that you have.\n(re)read the schema docs to see how you'd add columns programmatically and then create the table:\nhttp://www.sqlalchemy.org/d...
[ 3 ]
[]
[]
[ "python", "python_elixir", "sql", "sqlalchemy" ]
stackoverflow_0005424942_python_python_elixir_sql_sqlalchemy.txt
Q: python: os.path.isdir return false for directory with dot on end Windows 7, python 2.6.6, 2.7 Create directory 'c:\1\test.' Try check if it is dir or file, but it is neither: >>> os.listdir('c:/1') ['test.'] >>> os.path.isdir('c:/1') True >>> os.path.exists('c:/1/test.') False >>> os.path.isdir('c:/1/test.') False...
python: os.path.isdir return false for directory with dot on end
Windows 7, python 2.6.6, 2.7 Create directory 'c:\1\test.' Try check if it is dir or file, but it is neither: >>> os.listdir('c:/1') ['test.'] >>> os.path.isdir('c:/1') True >>> os.path.exists('c:/1/test.') False >>> os.path.isdir('c:/1/test.') False >>> os.path.isfile('c:/1/test.') False Why directory with . at end n...
[ "As was said in the comments, on Windows, file names that end with a dot, begin/end with spaces, are \"aux\", etc. etc. etc. - cannot be accessed normally from explorer or from most programming languages.\nIf you do want to access directories such as \"test.\" from python (or other) code, you can prefix the path wi...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0005441961_python.txt
Q: How to delete rows from the datastore that our app uses in google appengine? All the videos and tutorials show only how to add stuff to the datastore and fetch through the GqlQuery. How to delete stuff from the datastore? Does a 'DELETE FROM mytable WHERE condition' query work? A: The answers by systempuntout an...
How to delete rows from the datastore that our app uses in google appengine?
All the videos and tutorials show only how to add stuff to the datastore and fetch through the GqlQuery. How to delete stuff from the datastore? Does a 'DELETE FROM mytable WHERE condition' query work?
[ "The answers by systempuntout and Forest are both correct -- however, you may want to know that you can also batch some datastore operations together for higher efficiency (see this blog post from the App Engine team).\nYou could modify systempuntout's response like this:\nq = db.GqlQuery(\"SELECT * FROM Foo\")\nre...
[ 6, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005440666_google_app_engine_python.txt
Q: Remove empty element but keep zeros as values I have a list as follows: lst = [-1.33, '', -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, '', 1.37, 0] where there are two empty elements '' in the list with several zeroes and float numbers. How can I remove the empty elements but keep the zeroes? as follows... ls...
Remove empty element but keep zeros as values
I have a list as follows: lst = [-1.33, '', -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, '', 1.37, 0] where there are two empty elements '' in the list with several zeroes and float numbers. How can I remove the empty elements but keep the zeroes? as follows... lst2 = [-1.33, -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0,...
[ "Why not simply remove all '' ?\n>>> lst2 = [x for x in lst if x != '']\n>>> lst2\n[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]\n>>>\n\nor you could keep only floats and ints: \n>>> [x for x in lst if isinstance(x, (float, int))]\n[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]\n\n# or a bit ...
[ 9, 3, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005442921_list_python.txt
Q: python pack output in string format I have done the following. from struct import pack, unpack t = 1234 tt = str(pack("<I", t)) printing tt gives \xf3\xe0\x01\x00. How do I get original value of t back from tt? I tried using unpacking the repr(tt) but that does not work out. How do I go about doing this? A: >>...
python pack output in string format
I have done the following. from struct import pack, unpack t = 1234 tt = str(pack("<I", t)) printing tt gives \xf3\xe0\x01\x00. How do I get original value of t back from tt? I tried using unpacking the repr(tt) but that does not work out. How do I go about doing this?
[ ">>> t=1234\n>>> tt=pack('<I', t)\n>>> tt\n'\\xd2\\x04\\x00\\x00'\n>>> unpack('<I', tt)\n(1234,)\n\n>>> ttt, = unpack('<I', tt) \n>>> ttt\n1234\n\n", "you are using the wrong package for serialization. the struct package is only useful for python code which interacts with C code. \nfor serialization into a string...
[ 7, 1, 1 ]
[]
[]
[ "pack", "python", "struct" ]
stackoverflow_0005442984_pack_python_struct.txt
Q: web2py and DB transactions When exactly the database transaction is being commited? Is it for example at the end of every response generation? To explain the question: I need to develop a bit more sophisticated application where I have to control DB transactions less or more manually. Especialy I have to be able t...
web2py and DB transactions
When exactly the database transaction is being commited? Is it for example at the end of every response generation? To explain the question: I need to develop a bit more sophisticated application where I have to control DB transactions less or more manually. Especialy I have to be able to design a set of forms with som...
[ "you can call db.commit() and db.rollback() pretty much everywhere. If you do not and the action does not raise an exception, it commits before returning a response to the client. If it raises an exception and it is not explicitly caught, it rollsback. \n", "Have you checked out the official documentation? It ex...
[ 1, 0 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0004979392_python_web2py.txt
Q: Python CGI Script Not Executing Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code, here is the HTML code <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-...
Python CGI Script Not Executing
Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code, here is the HTML code <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>Admin ...
[ "Most likely, your webserver is not configured to execute the script. Even if it's marked as 'executable' in the file system, that doesn't necessarily mean the webserver knows that it should be executing .py files (rather than just serving them 'straight up'). Have a look here if you're running Apache: http://httpd...
[ 3, 2 ]
[]
[]
[ "cgi", "html", "python" ]
stackoverflow_0005440952_cgi_html_python.txt
Q: A Simple Clock Class in python Class Clock: def __init__(self): self._hours = 12 self._minutes = 0 self._seconds = 0 def getHours(self): return self._hours def getMinutes(self): return self._minutes def getSeconds(self): return self._seconds ...
A Simple Clock Class in python
Class Clock: def __init__(self): self._hours = 12 self._minutes = 0 self._seconds = 0 def getHours(self): return self._hours def getMinutes(self): return self._minutes def getSeconds(self): return self._seconds def show(self): print "%d:...
[ "You can initialize the time in the class constructor:\nClass Clock: \n def __init__(self, hours, minutes, seconds):\n self._hours = hours\n self._minutes = minutes\n self._seconds = seconds\n....\n\n\nclk = Clock(12, 34, 2)\n\n", "It looks correct to me, except for two things. You might...
[ 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005440271_python.txt
Q: Python - issues with numbers in pathnames I need to open all PDFs in a certain directory, so I first generate a list of the file paths using os.path: filenames = [ normpath(join(directoryname, filename)) for filename in listdir(directoryname) if filename.lower().endswith('.'+extension) ...
Python - issues with numbers in pathnames
I need to open all PDFs in a certain directory, so I first generate a list of the file paths using os.path: filenames = [ normpath(join(directoryname, filename)) for filename in listdir(directoryname) if filename.lower().endswith('.'+extension) ] So an item in that list looks like this: D:\...
[ "The backslash is special in C-style strings like Python uses, just like in C++, C#, and Java. Either use a double-backslash to say “yes, I really mean a backslash,” not the character code \\201, or use an r'' string that does not interpret backslash sequences:\n'D:\\\\Folder\\\\2010\\\\file.pdf'\nr'D:\\Folder\\20...
[ 15, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005443200_python.txt
Q: Distribution of elements Python I have text file(test.data), which include(this is just example other files have more values....) 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 I need to make a table where in the first,second, etc. column are values and in last column is class name. For e...
Distribution of elements Python
I have text file(test.data), which include(this is just example other files have more values....) 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 I need to make a table where in the first,second, etc. column are values and in last column is class name. For example in my case I want this: 4.5 ...
[ "Look into the csv module.\n", "import csv\nreader = csv.reader(open('test.data', 'r'))\nfor row in reader:\n print '\\t'.join(row)\n\nimport csv\nreader = csv.reader(open('test.data', 'r'))\nresult = []\nfor row in reader:\n result.append(row)\nprint result[0][1]\n\n" ]
[ 1, 0 ]
[]
[]
[ "distribution", "forms", "python" ]
stackoverflow_0005443582_distribution_forms_python.txt
Q: Force unbuffered output for script made with buildout and zc.recipe.egg:scripts I need to use unbuffered output in a script that is built with buildout. My approach was to specify the -u flag for Python in the generated script. Here's my buildout.cfg: [buildout] parts = python develop = . [python] recipe = zc.rec...
Force unbuffered output for script made with buildout and zc.recipe.egg:scripts
I need to use unbuffered output in a script that is built with buildout. My approach was to specify the -u flag for Python in the generated script. Here's my buildout.cfg: [buildout] parts = python develop = . [python] recipe = zc.recipe.egg:scripts eggs = myproject And setup.py: from setuptools import setup, find_pa...
[ "You can force unbuffered I/O from within your Python script by re-opening stdin or stdout by opening a new file object on the filenumber:\nimport io, os, sys\ntry:\n # Python 3, open as binary, then wrap in a TextIOWrapper\n unbuffered = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True...
[ 4 ]
[]
[]
[ "buildout", "python", "setuptools" ]
stackoverflow_0005443080_buildout_python_setuptools.txt
Q: Pickling inner classes I have a python module called model with basically the following content: class Database: class Publiation(object): pass class Article(Publication): pass class Book(Publication): pass class AnotherDatabase: class Seminar(object): pass ...
Pickling inner classes
I have a python module called model with basically the following content: class Database: class Publiation(object): pass class Article(Publication): pass class Book(Publication): pass class AnotherDatabase: class Seminar(object): pass ... I define the objects i...
[ "When an inner class is created, there is no way for the interpreter to know which class it was defined inside of, this information is not recorded. This is why pickle does not know where to look for the class Article.\nBecause of this there are numerous issues when using inner classes, not just when it comes to pi...
[ 5, 2 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0005443699_pickle_python.txt
Q: PYTHON: how to create a function to receive a variable input and then send it to another function I'm using Learn Python the Hard Way and exercise 35's extra credit says to simplify. I would like to create a function that will ask the user for variable next and then return it to the other functions. in case I am ...
PYTHON: how to create a function to receive a variable input and then send it to another function
I'm using Learn Python the Hard Way and exercise 35's extra credit says to simplify. I would like to create a function that will ask the user for variable next and then return it to the other functions. in case I am making no sense... def action(): next = raw_input (">> ") return next def star...
[ "You need to store the return value of the function somewhere; once it exits, the whole little indented namespace beneath the function goes away, along with the next variable. I think you really want:\nnext = action()\n\nThat way, with the function's little namespace destroyed, you will still have a copy of next ou...
[ 2, 1, 1 ]
[]
[]
[ "function", "new_operator", "python" ]
stackoverflow_0005443535_function_new_operator_python.txt
Q: Python table classification I have text file(test.data), which include some values and class name, for example 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 I need to classify this data to rows(matrix), where 1,2 row etc is data, last one is class. So I started with this code: reader = c...
Python table classification
I have text file(test.data), which include some values and class name, for example 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 I need to classify this data to rows(matrix), where 1,2 row etc is data, last one is class. So I started with this code: reader = csv.reader(open('test.data', 'r'))...
[ "Edit: Original code snippet modified to handle N-column input (last is class). This requirement was mentioned by the OP in a later reply.\nreader = csv.reader(open('test.data', 'r'))\nresult = {}\nfor row in reader:\n uclass=row[-1]\n if result.has_key(uclass):\n result[uclass].append(row[0:-1])\n ...
[ 1 ]
[]
[]
[ "distribution", "forms", "python" ]
stackoverflow_0005443803_distribution_forms_python.txt
Q: General question about Binary files I am a beginner and I am having trouble in grasping binary files. When I write to a file in binary mode (in python), I just write normal text. There is nothing binary about it. I know every file on my computer is a binary file but I am having trouble distinguishing between files...
General question about Binary files
I am a beginner and I am having trouble in grasping binary files. When I write to a file in binary mode (in python), I just write normal text. There is nothing binary about it. I know every file on my computer is a binary file but I am having trouble distinguishing between files written in binary mode by me and files l...
[ "Here's a literal answer to your question:\nimport struct\nwith open('gibberish.bin', 'wb') as f:\n f.write(struct.pack('<4d', 3.14159, 42.0, 123.456, 987.654))\n\nThat's packing those 4 floating point numbers into a binary format (little-endian IEEE 756 64-bit floating point).\nHere's (some of) what you need to...
[ 4, 4, 3, 2, 0, 0 ]
[]
[]
[ "binary_data", "binaryfiles", "python" ]
stackoverflow_0005444023_binary_data_binaryfiles_python.txt
Q: Python multiprocessing: restrict number of cores used I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all pr...
Python multiprocessing: restrict number of cores used
I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all processors, bogging down the system. I assume the multiproces...
[ "If you are on linux, use taskset when you launch the program\nA child created via fork(2) inherits its parent’s CPU affinity mask. The affinity mask is preserved across an execve(2).\n\nTASKSET(1)\n Linux User’s Manual\n TASKSET(1)\nNAME\n taskset - retrieve or set a process’s CPU affinity\nSYNOPSIS\n...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001575067_multiprocessing_python.txt
Q: What's the most efficient way of intersecting to collections in Python? I'm new in python, sorry if there's anything wrong. I'd like to intersect several collections (20 o 30) with a big amount of elements in them. I've been reading and know that Sets are similar to hashtables (work with the same principle). Sets...
What's the most efficient way of intersecting to collections in Python?
I'm new in python, sorry if there's anything wrong. I'd like to intersect several collections (20 o 30) with a big amount of elements in them. I've been reading and know that Sets are similar to hashtables (work with the same principle). Sets has the intersect method, i've been trying it and works really fine. But, wo...
[ "result = set1.intersection(set2, set3, set4, ...)\n\nhttp://docs.python.org/library/stdtypes.html\n" ]
[ 1 ]
[]
[]
[ "algorithm", "collections", "performance", "python" ]
stackoverflow_0005444517_algorithm_collections_performance_python.txt
Q: Python table classification I have different type of data for example: 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 I need output: 'U1': [['4.5', '3.5'], ['4.5', '6'], ['5', '7'], ['7', '6.5']] 'U2': [['4.5', '10.5'], ['3.5', '10.5'], ['3.5', '10.5']] So my code is: import csv reader ...
Python table classification
I have different type of data for example: 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 I need output: 'U1': [['4.5', '3.5'], ['4.5', '6'], ['5', '7'], ['7', '6.5']] 'U2': [['4.5', '10.5'], ['3.5', '10.5'], ['3.5', '10.5']] So my code is: import csv reader = csv.reader(open('test.data', 'r...
[ "result[uclass].append(row[:-1])\n\nand\nresult[uclass] = row[:-1] \n\nThis notation is called slicing.\n", "This perhaps?\ndata = \"\"\"\\\n4.5,3.5,U1\n4.5,10.5,U2\n4.5,6,U1\n3.5,10.5,U2\n3.5,10.5,U2\n5,7,U1\n7,6.5,U1\"\"\".splitlines()\n\nfrom collections import defaultdict\ndd = defaultdict(list)\nfor d in da...
[ 2, 2, 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0005444571_arrays_python.txt
Q: How to remove unsafe characters to save file I would like to save a file with the name that has the most valid characters remaining intact, f.e. if I get supplied the filename: >This\ Ăwesomé_Song?©.mp3 and I want to save it under Windows 7, it won't let me save it until I remove >, \ and ?. The characters Ă, © a...
How to remove unsafe characters to save file
I would like to save a file with the name that has the most valid characters remaining intact, f.e. if I get supplied the filename: >This\ Ăwesomé_Song?©.mp3 and I want to save it under Windows 7, it won't let me save it until I remove >, \ and ?. The characters Ă, © and é are totally fine and I would like to keep the...
[ ">>> import re\n>>> print re.sub(r'[\\\\/:\"*?<>|]+', \"\", \"This\\ Ăwesomé_Song?©.mp3\")\nThis Ăwesomé_Song©.mp3\n>>> \n\n", "In posix, only two octets are reserved, forward slash (/, 0x2F, dec 42), and null (\\0, 0x00, dec 0). Any other character could appear in a filename.\n", "You may use this pattern fro...
[ 8, 1, 0 ]
[]
[]
[ "python", "regex", "string", "validation", "windows" ]
stackoverflow_0005444810_python_regex_string_validation_windows.txt
Q: Python: TemporaryFile returns empty string when read I need to create a file from a string so I can use it as an attachment for an email in Django. After some Googling I found the tempfile module with TemporaryFile but it's not working as I expect. the following code returns an empty string. >>> f = tempfile.Temp...
Python: TemporaryFile returns empty string when read
I need to create a file from a string so I can use it as an attachment for an email in Django. After some Googling I found the tempfile module with TemporaryFile but it's not working as I expect. the following code returns an empty string. >>> f = tempfile.TemporaryFile() >>> f.write('foobar') >>> f.read() ''
[ "When you call read, it is trying to read from where it left off, which is at the end of the file. You need to jump to the beginning of the file before you read it:\nf.seek(0)\nf.read()\n\nIf you need to write again, you should jump to the end before writing if you don't want to overwrite your stuff:\nf.seek(0, os....
[ 10, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005444809_django_python.txt
Q: SWIG + SCIPY = Import Error on PyArray_TYPE Hey gang, so I've written a swig wrapper for some C code. I'm trying to bridge the gap between scipy arrays and C arrays, which I know is messy. After a clean compilation (well...not including some warnings...) I'm getting this issue when I load the python-swig-c module:...
SWIG + SCIPY = Import Error on PyArray_TYPE
Hey gang, so I've written a swig wrapper for some C code. I'm trying to bridge the gap between scipy arrays and C arrays, which I know is messy. After a clean compilation (well...not including some warnings...) I'm getting this issue when I load the python-swig-c module: undefined symbol: PyArray_TYPE I've added my sw...
[ "Why don't you use ctypes or pyrex/cython instead of SWIG?\n(see Python: SWIG vs ctypes)\n" ]
[ 0 ]
[]
[]
[ "python", "scipy", "swig" ]
stackoverflow_0003919041_python_scipy_swig.txt
Q: How to integrate a numpy array in scipy? I have a relatively expensive-to-calculate function which, given a single scalar, returns a numpy.array() object. When I try to integrate this function with respect to the scalar argument, using scipy.integrate.romberg, I get an error internal to scipy from the condition it...
How to integrate a numpy array in scipy?
I have a relatively expensive-to-calculate function which, given a single scalar, returns a numpy.array() object. When I try to integrate this function with respect to the scalar argument, using scipy.integrate.romberg, I get an error internal to scipy from the condition it uses to determine convergence: Traceback (mos...
[ "The problem appears to be here:\nabs(result - lastresult) > tol\n\nresult and lastresult are likely numpy.arrays (instead of single values). The above entire expression is therefore evaluating to an array of truth values, rather than a single True/False. Therefore when you and the result of the above expression ...
[ 2, 0 ]
[ "http://www.sagemath.org may provide alternative ways of numerical integration.\n" ]
[ -2 ]
[ "arrays", "numpy", "python", "scipy" ]
stackoverflow_0004110024_arrays_numpy_python_scipy.txt
Q: RW-locking a Windows file in Python, so that at most one test instance runs per night I have written a custom test harness in Python (existing stuff was not a good fit due to lots of custom logic). Windows task scheduler kicks it off once per hour every day. As my tests now take more than 2 hours to run and are gr...
RW-locking a Windows file in Python, so that at most one test instance runs per night
I have written a custom test harness in Python (existing stuff was not a good fit due to lots of custom logic). Windows task scheduler kicks it off once per hour every day. As my tests now take more than 2 hours to run and are growing, I am running into problems. Right now I just check the system time and do nothing un...
[ "When you start running a test make a file called __LOCK__ or something. Delete it when you finish, using a try...finally block to ensure that it always gets cleared up. Don't run the test if the file exists. If the computer crashes or similar, delete the file by hand. I doubt you need more cleverness than that.\nA...
[ 1 ]
[]
[]
[ "file_locking", "python", "race_condition", "windows" ]
stackoverflow_0005443781_file_locking_python_race_condition_windows.txt
Q: Python PIL library perfomance The problem I've got is that I have a Python script that encodes about thousands of images each time I execute it and it doesn't take the most of memory and CPU. How could I improve the perfomance avoiding the I/O overhead? The script generates 5000 thumbnails each time is executed an...
Python PIL library perfomance
The problem I've got is that I have a Python script that encodes about thousands of images each time I execute it and it doesn't take the most of memory and CPU. How could I improve the perfomance avoiding the I/O overhead? The script generates 5000 thumbnails each time is executed and I was wondering if it would be po...
[ "It's possible you could exploit some i/o concurrency by running several threads concurrently. This may help in two ways:\n\nMore TCP connections == faster (although being a good Internet citizen is important sometimes too).\nThe program you currently have first reads the remote url into memory, then processes it, ...
[ 2, 0 ]
[]
[]
[ "memory", "performance", "python", "python_imaging_library" ]
stackoverflow_0005444892_memory_performance_python_python_imaging_library.txt
Q: String In python with my unicode? Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> str_version = 'នយោបាយ' >>> type(str_version) <class 'str'> >>> print (str_version) នយោបាយ >>> unicode_version = 'នយោបាយ'.decode('...
String In python with my unicode?
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> str_version = 'នយោបាយ' >>> type(str_version) <class 'str'> >>> print (str_version) នយោបាយ >>> unicode_version = 'នយោបាយ'.decode('utf-8') Traceback (most recent call las...
[ "There is nothing wrong with your string! You just have confused encode() and decode(). The string is meaningful symbols. To turn it into bytes that could be stored in a file or transmitted over the Internet, use encode() with an encoding like UTF-8. Each encoding is a scheme for converting meaningful symbols to f...
[ 10, 7, 3 ]
[]
[]
[ "python", "python_3.x", "unicode" ]
stackoverflow_0005445250_python_python_3.x_unicode.txt
Q: Enter compound statements interactivly I am having trouble running this simple statement in the IDLE prompt. if True: print("True") # need to press ENTER twice? else: print("False") # need to press ENTER twice? Any help is appreciated. A: IDLE is automatically indenting when you press return. Press dele...
Enter compound statements interactivly
I am having trouble running this simple statement in the IDLE prompt. if True: print("True") # need to press ENTER twice? else: print("False") # need to press ENTER twice? Any help is appreciated.
[ "IDLE is automatically indenting when you press return. Press delete to remove the automatic indentation.\nif True:\n print(\"True\") # press return, then backspace\nelse:\n print(\"False\")\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005445462_python_python_3.x.txt
Q: 3d game engine suggestions I am developing a 3d shooter game that I would like to run on Computers/Phones/Tablets and would like some help to choose which engine to use. I would like to write the application once and port it over to Android/iOS/windows/mac with ease. I would like to make the application streamabl...
3d game engine suggestions
I am developing a 3d shooter game that I would like to run on Computers/Phones/Tablets and would like some help to choose which engine to use. I would like to write the application once and port it over to Android/iOS/windows/mac with ease. I would like to make the application streamable over the internet. The engine...
[ "For the requirements that you have Unity3d is probably one of your best bets. As roy said there aren't any other 3D engines out there that will span that wide a range of platforms. Why do you think that going to a completely code based system would save you from creating a variety of classes with various responsib...
[ 2, 1, 0 ]
[]
[]
[ "game_engine", "javascript", "python" ]
stackoverflow_0005445166_game_engine_javascript_python.txt
Q: Techniques for categorising natural language strings? What is available in terms of libraries / open-source software for processing and categorising natural language? I've got a database full of strings which are user descriptions of a particular item. I'd like to categorise these words to weed out the useless and...
Techniques for categorising natural language strings?
What is available in terms of libraries / open-source software for processing and categorising natural language? I've got a database full of strings which are user descriptions of a particular item. I'd like to categorise these words to weed out the useless and make an educated guess as to what category the item fits i...
[ "As to Python, for the moment I can recommend looking into:\nhttp://www.nltk.org/\nIt has good documentation, and lots of lots of functionality in the field of natural language processing. Also there is a package in the Ubuntu repository (python-nltk), so it's easy to install and experiment with.\nFor most situatio...
[ 3, 2, 1, 1, 1 ]
[]
[]
[ "java", "nlp", "python", "ruby" ]
stackoverflow_0005439672_java_nlp_python_ruby.txt
Q: On enter action? Hey I'm working on a python project that requires an action that takes a couple minutes. The thing is since it takes a couple minutes I'd like the user to be able to press enter to see the current status of the action. How can I do this in Python 2? A: @Space_C0wb0y is right, a progress bar is a...
On enter action?
Hey I'm working on a python project that requires an action that takes a couple minutes. The thing is since it takes a couple minutes I'd like the user to be able to press enter to see the current status of the action. How can I do this in Python 2?
[ "@Space_C0wb0y is right, a progress bar is a good solution. However, this demonstrates one way to do what you asked for. Some code pinched from here: Non-blocking read on a subprocess.PIPE in python\nimport fcntl, os, sys\n\n# make stdin a non-blocking file\nfd = sys.stdin.fileno()\nfl = fcntl.fcntl(fd, fcntl.F_GET...
[ 0 ]
[]
[]
[ "action", "enter", "key", "python" ]
stackoverflow_0005445574_action_enter_key_python.txt
Q: Fast Reading of 10000 Binary Files? I have 10,000 binary files, named like this: file0.bin file1.bin ............ ............ file10000.bin Each of the above files contains exactly 391 float values (1564 bytes per file). my goal is to read all of the files into a python array in the fastest way possible. If I ope...
Fast Reading of 10000 Binary Files?
I have 10,000 binary files, named like this: file0.bin file1.bin ............ ............ file10000.bin Each of the above files contains exactly 391 float values (1564 bytes per file). my goal is to read all of the files into a python array in the fastest way possible. If I open & close each file using a script, it ta...
[ "If you want even faster make ramdisk:\n# mkfs -q /dev/ram1 $(( 2 * 10000)) ## roughly the size you need\n# mkdir -p /ramcache\n# mount /dev/ram1 /ramcache\n# df -H | grep ramcache\n\nnow concat\n# cat file{1..10000}.bin >> /ramcache/concat.bin ## thanks SiegeX\n\nThen let your script on that file\nSince I haven't ...
[ 2, 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005187705_linux_python.txt
Q: How do I match this URL in Django's urls.py? I want to match a url that: begins with /signup and ends with password=goodbye That's it. If something begins with that and ends with that, how do I match that in regex? I understand that I should do this in urls.py, but I have to because of certain reasons. Please answ...
How do I match this URL in Django's urls.py?
I want to match a url that: begins with /signup and ends with password=goodbye That's it. If something begins with that and ends with that, how do I match that in regex? I understand that I should do this in urls.py, but I have to because of certain reasons. Please answer how I would match it this way. I have to becaus...
[ "Don't ever send passwords in the URL. They belong in the POST body, which is not stored by browsers (you can repeat POSTs in browsers, but POST data is not stored in the history).\n", "(r'^/signup/(.*)password=goodbye$', ...\n\n", "You should just match for /signup. You can get the password through the request...
[ 6, 2, 1, 1 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0005445994_django_python_regex.txt
Q: python 'matrix' problem I have input data(test.data) 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 code I have: import csv reader = csv.reader(open('test.data', 'r')) result = {} for row in reader: uclass=row[-1] if result.has_key(uclass): result[uclass].append(row[:-1])...
python 'matrix' problem
I have input data(test.data) 4.5,3.5,U1 4.5,10.5,U2 4.5,6,U1 3.5,10.5,U2 3.5,10.5,U2 5,7,U1 7,6.5,U1 code I have: import csv reader = csv.reader(open('test.data', 'r')) result = {} for row in reader: uclass=row[-1] if result.has_key(uclass): result[uclass].append(row[:-1]) else: result[ucl...
[ "In programming, if you don't know how to do something, break it into smaller pieces. I'm not entirely clear on what you want, so I'm going to assume its the following.\nYou have a list \nx = [4.5, 6.9, 7.5, 9.2, ...]\n\nYou want a new list that takes the first third of that list. But you don't know how to do it. S...
[ 2, 0 ]
[]
[]
[ "matrix", "python", "row" ]
stackoverflow_0005445122_matrix_python_row.txt
Q: Python Arrays vs Lists What is the main advantage of using the array module instead of lists? A: The arrays will take less space. I've never used the array module, numpy provides the same benefits plus many many more. A: Arrays are very similar to lists "except that the type of objects stored in them is constr...
Python Arrays vs Lists
What is the main advantage of using the array module instead of lists?
[ "The arrays will take less space.\nI've never used the array module, numpy provides the same benefits plus many many more.\n", "Arrays are very similar to lists \"except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single ch...
[ 6, 5, 0 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0005445777_arrays_list_python.txt
Q: Reading metadata from online mp3-file I would like to read the mp3 bitrate of an online MP3 file, f.e. this one, preferrably without downloading it in its entirety. I've been able to find out that ffmpeg allows one to do this, f.e. like so: ffmpeg -i http://physics.ujep.cz/~mmaly/mp3/Mozart/Mass_in_C_Minor_New_b...
Reading metadata from online mp3-file
I would like to read the mp3 bitrate of an online MP3 file, f.e. this one, preferrably without downloading it in its entirety. I've been able to find out that ffmpeg allows one to do this, f.e. like so: ffmpeg -i http://physics.ujep.cz/~mmaly/mp3/Mozart/Mass_in_C_Minor_New_by_Levin/sbory_vyssi_kvalita/01_Kyrie.mp3 b...
[ "I think the id3 tag is stored at the beginning of an mp3 file, you'd likely want to first learn the mp3 fileformat so you know how the data is stored. Then you'd begin downloading the file, and close the connection when you have enough data to read the bitrate.\nHere's a link to the fileformat spec: http://www.mpg...
[ 0, 0 ]
[ "Download the file and use your favorite id3 bindings for Python.\n" ]
[ -2 ]
[ "audio", "ffmpeg", "metadata", "mp3", "python" ]
stackoverflow_0005436827_audio_ffmpeg_metadata_mp3_python.txt
Q: Is unladen-swallow dead? My project has deferred solution on integration C++ with Python until now. But now this question is raised again. Do anybody know status of project? On Google: (http://code.google.com/p/unladen-swallow) there is no actual info at all. Can we reckon on this project? A: Unladen Swallow is ...
Is unladen-swallow dead?
My project has deferred solution on integration C++ with Python until now. But now this question is raised again. Do anybody know status of project? On Google: (http://code.google.com/p/unladen-swallow) there is no actual info at all. Can we reckon on this project?
[ "Unladen Swallow is dead in the sense that activity is low and there seems little hope of being a standalone Unladen Swallow branch like Jython or Ironpython.\nThat said, a lot of the optimizations and advances are going to get merged into CPython. Moreover, there is still hope that the Unladen Swallow team will co...
[ 6, 4 ]
[]
[]
[ "python", "unladen_swallow" ]
stackoverflow_0003855611_python_unladen_swallow.txt
Q: How do I restart my script? from Tkinter import * import Tkinter as tk import tkMessageBox import time import re import string from random import randint print "Hangman v1.7 - by Josh & Paul" bsrly2 = False bsrly = False notlie = True turns = 8 rec = '' exp = '^[a-z]+$' textfile = open('dictionary.txt', 'r') words...
How do I restart my script?
from Tkinter import * import Tkinter as tk import tkMessageBox import time import re import string from random import randint print "Hangman v1.7 - by Josh & Paul" bsrly2 = False bsrly = False notlie = True turns = 8 rec = '' exp = '^[a-z]+$' textfile = open('dictionary.txt', 'r') words = textfile.read().split() n = ra...
[ "Insted of putting program logic into module top-level put it into functions. Once you've done that, you just call again your function. With the code structure you have now it is impossible to restart your program (well, at least not without writing another one). \nEdit:\nExample. Encapsulate this code in a functio...
[ 0 ]
[]
[]
[ "python", "restart" ]
stackoverflow_0005446430_python_restart.txt
Q: Example Usage of Threading in Python 2.1 I need some help implementing threading using Python 2.1. I would readily update to a newer version of Python, but unfortunately, I'm working within an interpreter built into a video game, so 2.1 is written in stone for me. To be clear, I need an example of how to do thread...
Example Usage of Threading in Python 2.1
I need some help implementing threading using Python 2.1. I would readily update to a newer version of Python, but unfortunately, I'm working within an interpreter built into a video game, so 2.1 is written in stone for me. To be clear, I need an example of how to do threading without using 'import threading'. 'import ...
[ "I'd recommend using the threading module. If you don't have it, you can get the version from Python 2.1 here: http://pastebin.com/5f9NBmcg\nNote that it imports thread, so if your system has a problem with threads, it still won't work.\nIf you need specific modules from Python 2.1, go to the release page and click...
[ 2 ]
[]
[]
[ "multithreading", "python", "python_multithreading" ]
stackoverflow_0005446387_multithreading_python_python_multithreading.txt
Q: Is there a difference between developing a web2py app on Windows or Linux? I recall setting up other frameworks in a Windows environment were extremely painful :) A: It's actually extremely easy to set up web2py on Windows -- it will literally take you about a minute. Just go to the download page, download the "...
Is there a difference between developing a web2py app on Windows or Linux?
I recall setting up other frameworks in a Windows environment were extremely painful :)
[ "It's actually extremely easy to set up web2py on Windows -- it will literally take you about a minute. Just go to the download page, download the \"For Windows\" version, unzip the downloaded file, and click the 'web2py.exe' file in the 'web2py' folder. Voilà -- you're running web2py and ready to build an app. You...
[ 10, 4, 2 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0005444798_python_web2py.txt
Q: Using GoogleAppEngine with Python in Eclipse A while back I asked this question "Using Google App Engine template from PyDev in Eclipse on Mac" and got a response. I've come back to this endeavour and find I now get a different error when trying to create a project: Invalid Google App Engine directory. Did not fin...
Using GoogleAppEngine with Python in Eclipse
A while back I asked this question "Using Google App Engine template from PyDev in Eclipse on Mac" and got a response. I've come back to this endeavour and find I now get a different error when trying to create a project: Invalid Google App Engine directory. Did not find: /Applications/GoogleAppEngineLauncher.app/Conte...
[ "Wow, I feel like some kind of hardcore Mac expert.\nI created a symlink like so:\nln -s \"/usr/local/google_appengine/lib/django_1_2/\" \"/usr/local/google_appengine/lib/django\"\nAnd all seems well. Should I expect ill effects from this fix/hack?\n" ]
[ 2 ]
[]
[]
[ "eclipse", "google_app_engine", "python" ]
stackoverflow_0005446488_eclipse_google_app_engine_python.txt
Q: data type not understood I'm trying to use a matrix to compute stuff. The code is this import numpy as np # some code mmatrix = np.zeros(nrows, ncols) print mmatrix[0, 0] but I get 'data type not understood', and it works if I do it from terminal. A: Try: mmatrix = np.zeros((nrows, ncols)) Since the shape para...
data type not understood
I'm trying to use a matrix to compute stuff. The code is this import numpy as np # some code mmatrix = np.zeros(nrows, ncols) print mmatrix[0, 0] but I get 'data type not understood', and it works if I do it from terminal.
[ "Try:\nmmatrix = np.zeros((nrows, ncols))\n\nSince the shape parameter has to be an int or sequence of ints\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html\nOtherwise you are passing ncols to np.zeros as the dtype.\n" ]
[ 163 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0005446522_matrix_numpy_python.txt
Q: Python open() Mac OS X Komodo Edit I started now to learn Python, so my question is kinda stupid I have this piece of code #!/usr/local/bin/python3 # encoding: utf-8 fh = open("lines.txt") for lines in readlines(): print(lines) the text file lines.txt exits and it is at the same directory of my page, I usin...
Python open() Mac OS X Komodo Edit
I started now to learn Python, so my question is kinda stupid I have this piece of code #!/usr/local/bin/python3 # encoding: utf-8 fh = open("lines.txt") for lines in readlines(): print(lines) the text file lines.txt exits and it is at the same directory of my page, I using Komodo Edit, when I run the file, I ge...
[ "You're getting this error because by default when you run a script in Komodo Edit it does not run it from the directory the script is saved in (unlike when you run normally from the command terminal).\nTo fix this - when you select the 'Run Command' option in Komodo Edit - Click 'More' to bring down a further opti...
[ 2, 0 ]
[]
[]
[ "komodoedit", "macos", "python" ]
stackoverflow_0005446610_komodoedit_macos_python.txt
Q: How to reassemble TCP packets in Python? How to reassemble TCP packets in Python? Is there any existing tools for this? Thanks! :-) A: To do perform TCP reassembly you'll need to use something like pynids http://jon.oberheide.org/pynids/. You can also build your own using pylibpcap, dpkt or scapy. TCP reassembly...
How to reassemble TCP packets in Python?
How to reassemble TCP packets in Python? Is there any existing tools for this? Thanks! :-)
[ "To do perform TCP reassembly you'll need to use something like pynids http://jon.oberheide.org/pynids/.\nYou can also build your own using pylibpcap, dpkt or scapy.\nTCP reassembly is very tricky with a LOT of edge cases. I wouldn't recommend doing it yourself if you need a robust solution.\n", "Yes... the TCP p...
[ 14, 5 ]
[]
[]
[ "packet", "python", "tcp" ]
stackoverflow_0005216332_packet_python_tcp.txt
Q: Initialize class but with different parents in python In python, is there a way, when initializing a Class, to change the superclass in function of the value of a class attribute? Here's an example of what I want to do. First I have theses classes: class A(object): pass class B(A): # extend and override c...
Initialize class but with different parents in python
In python, is there a way, when initializing a Class, to change the superclass in function of the value of a class attribute? Here's an example of what I want to do. First I have theses classes: class A(object): pass class B(A): # extend and override class A pass class C(A or B): # extend and override...
[ "I ended by using cooperative multiple inheritance. It works fine. The only drawback is that we need to be sure that for methods that need to be call on many parent classes (like methods that are present in A and B and C), there's a super() call in each method definitions of each classes and that they have the same...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005386400_python.txt
Q: Scrapy Yahoo Group spider Trying to scrape a Y! Group and I can get data from one page but that's it. I've got some basic rules but clearly they aren't right. Anyone already solved this one? class YgroupSpider(CrawlSpider): name = "yahoo.com" allowed_domains = ["launch.groups.yahoo.com"] start_urls = [ "http:/...
Scrapy Yahoo Group spider
Trying to scrape a Y! Group and I can get data from one page but that's it. I've got some basic rules but clearly they aren't right. Anyone already solved this one? class YgroupSpider(CrawlSpider): name = "yahoo.com" allowed_domains = ["launch.groups.yahoo.com"] start_urls = [ "http://launch.groups.yahoo.com/group/...
[ "Looks like you have almost no idea what you are doing. I'm pretty new to Scrapy but I think you will want to have something like\nRule(SgmlLinkExtractor(allow=('http\\://example\\.com/message/.*\\.aspx', )), callback='parse_item'),\nTry to write a regular expression that matches the complete link URL you want. A...
[ 0 ]
[]
[]
[ "python", "scrapy", "yahoo" ]
stackoverflow_0005406832_python_scrapy_yahoo.txt
Q: URL Sniffing in Python Does anyone know how to write a live data sniffer in Python which extracts the originating IP address and the full URL that was being accessed? I have looked at pulling data from urlsnarf however IPv6 is not supported (and the connections will be to IPv6 hosts). While I can pull data from tc...
URL Sniffing in Python
Does anyone know how to write a live data sniffer in Python which extracts the originating IP address and the full URL that was being accessed? I have looked at pulling data from urlsnarf however IPv6 is not supported (and the connections will be to IPv6 hosts). While I can pull data from tcpdump and greping for GET/PO...
[ "Unfortunately, with IPv6 you are stuck doing your own TCP re-assembly. The good news that you are only concerned with URL data which should (generally) be in one or two packets.\nYou should be able to get away with using pylibpcap to do this. You'll want to use setfilter on your pcap object to make sure you are o...
[ 2 ]
[]
[]
[ "ipv6", "libpcap", "python", "sniffing", "url" ]
stackoverflow_0005436185_ipv6_libpcap_python_sniffing_url.txt
Q: How come this Django matching doesn't work in urls.py? (r'^signup(.*)password=goodbye$','abc.wall.views.register_goodbye'), This doesn't work. It doesn't match! Even when I hit this: www.mydomain.com/signup?password=goodbye It does not match it and simply skips over it. Why? Note: I understand this is not good p...
How come this Django matching doesn't work in urls.py?
(r'^signup(.*)password=goodbye$','abc.wall.views.register_goodbye'), This doesn't work. It doesn't match! Even when I hit this: www.mydomain.com/signup?password=goodbye It does not match it and simply skips over it. Why? Note: I understand this is not good practice to match the GET parameter. However, it's forced and...
[ "Because urls.py doesn't match against query parameters.\n", "URLs don't match on query parameters. They take the path (everything before the ?) from the request, and attempts to match against your URL regex. \nWhat you need to do is handle the GET parameters in your view, and route from there to other functions ...
[ 1, 1 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0005446818_django_python_regex.txt
Q: Copy data from csv file I am trying to follow one copy_from example describe in stackoverflow but i modify little as i need to read data from csv file. Following this example i wrote a small program where the file is to be readed from file stored in disk and then copy data from that file to created table, My code ...
Copy data from csv file
I am trying to follow one copy_from example describe in stackoverflow but i modify little as i need to read data from csv file. Following this example i wrote a small program where the file is to be readed from file stored in disk and then copy data from that file to created table, My code is : def importFile(): pa...
[ "Look at your .csv file with a text editor. You want to be sure that\n\nthe field-separator is a tab character\nthere are no quote-chars\nthere is no header row\n\nIf this is true, the following should work:\nimport psycopg2\n\ndef importFromCsv(conn, fname, table):\n with open(fname) as inf:\n conn.curso...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005445569_python.txt
Q: python numpy cast problem I'm trying to interpolate with the following code self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] ) self.samples = np.interp(self.indeces, tmp_idx, tmp_s) where tmp_idx and tmp_s are numpy arrays. I get the following error: array cannot be safely cast to required type Do y...
python numpy cast problem
I'm trying to interpolate with the following code self.indeces = np.arange( tmp_idx[len(tmp_idx) -1] ) self.samples = np.interp(self.indeces, tmp_idx, tmp_s) where tmp_idx and tmp_s are numpy arrays. I get the following error: array cannot be safely cast to required type Do you know how to fix this? UPDATE...
[ "One of your possible issues is that when you have the following line:\ntmp_s = np.array; tmp_idx = np.array;\n\nYou are setting tmp_s and tmp_idx to the built-in function np.array. Then when you append, you have have object type arrays, which np.interp has no idea how to deal with. I think you probably thought tha...
[ 2 ]
[]
[]
[ "casting", "interpolation", "numpy", "python" ]
stackoverflow_0005446855_casting_interpolation_numpy_python.txt
Q: How fast is Python Image Library's (PIL) ImageDraw Module, for instance as compared to OpenGL? I have some .png images and I want to be able to quickly: (a) Load a .png from a file. (b) Draw some simple lines on top of the .png. (c) Get the contents (bytes) of the resulting image to return as the result of an http...
How fast is Python Image Library's (PIL) ImageDraw Module, for instance as compared to OpenGL?
I have some .png images and I want to be able to quickly: (a) Load a .png from a file. (b) Draw some simple lines on top of the .png. (c) Get the contents (bytes) of the resulting image to return as the result of an http request. It sounds like PIL is a good candidate for doing this with relatively little code. However...
[ "\"Draw some simple lines on top of the .png\" is not a computationally intensive task. \nThis doesn't seems to be a good candidate for the GPU since they are better suited for more complex tasks. You've got to realize that the image is initially loaded on the RAM, making it your job to send this data to the GPU me...
[ 2 ]
[]
[]
[ "gpu", "opengl", "python", "python_imaging_library" ]
stackoverflow_0005446816_gpu_opengl_python_python_imaging_library.txt
Q: UnicodeEncodeError with csvwriter I have one more error to fix. row = OpenThisLink + titleTag + JD try: csvwriter.writerow([row]) except (UnicodeEncodeError, UnicodeDecodeError): pass This gives the error (for this character: "ń") row = OpenThisLink + str(titleTag) + JD ...
UnicodeEncodeError with csvwriter
I have one more error to fix. row = OpenThisLink + titleTag + JD try: csvwriter.writerow([row]) except (UnicodeEncodeError, UnicodeDecodeError): pass This gives the error (for this character: "ń") row = OpenThisLink + str(titleTag) + JD UnicodeEncodeError: 'ascii' codec can't...
[ "\nAnd indeed, my exception doesn't seem\n to work. Any suggestions?\n\nrow = OpenThisLink + titleTag + JD is outside the try/except block and so any exceptions raised while that statement is running will not be caught. This, however, will catch the exception:\ntry:\n row = OpenThisLink + titleTag + JD\n csv...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001843999_python.txt
Q: Twisted getPage(): process memory grow when requesting lot of pages I am writing a script for contstant (each 30-120 sec) grabbing of information quering a large set of URLs (Icecast/Shoutcast servers status pages), about 500 urls. It works fine, but the python process resident size is constantly keep growing. I a...
Twisted getPage(): process memory grow when requesting lot of pages
I am writing a script for contstant (each 30-120 sec) grabbing of information quering a large set of URLs (Icecast/Shoutcast servers status pages), about 500 urls. It works fine, but the python process resident size is constantly keep growing. I am sure it is endless grow as I left it running for several hours and it t...
[ "My guess is that you're scheduling these page fetches based on a fixed timer, and you're not paying attention to where the fetches actually end. Pretend that each page takes 60 seconds to fetch. You have a huge pile of fetches scheduled for 30 seconds, and then again in 30 seconds, more and more piling up as you...
[ 1 ]
[]
[]
[ "cpython", "memory_leaks", "python", "twisted" ]
stackoverflow_0005432358_cpython_memory_leaks_python_twisted.txt
Q: How do I design a twisted factory to handle disconnects? I have a ReconnectingClientFactory in a module. I'd like the module to be as flexible as possible. I only need a single TCP connection. I use the factory as a persistent interface to this connection. In the past the factory would respond to disconnection...
How do I design a twisted factory to handle disconnects?
I have a ReconnectingClientFactory in a module. I'd like the module to be as flexible as possible. I only need a single TCP connection. I use the factory as a persistent interface to this connection. In the past the factory would respond to disconnections by endlessly retrying the connection, never informing the to...
[ "This question is a bit too abstract to provide a direct answer. It depends on what your top-level module is doing.\nHowever, you should consider using endpoints, rather than ClientFactory. This might address some of your design questions. Receiving connection lost notifications is a little tricker (since Client...
[ 3 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0005447020_python_twisted.txt
Q: SyntaxError in print() Python3.2? I'm getting this error in Python3.2 on a simple print statement. I'm going through some tutorials, and this is exactly the code example is written: fh = open('lines.txt') for line in fh.readlines(): print(line, end="") But this is what i get File "./forloop.py", line 5 pri...
SyntaxError in print() Python3.2?
I'm getting this error in Python3.2 on a simple print statement. I'm going through some tutorials, and this is exactly the code example is written: fh = open('lines.txt') for line in fh.readlines(): print(line, end="") But this is what i get File "./forloop.py", line 5 print(line, end="") ^ S...
[ "As I said in the comment, I'm quite sure you are on 2.x.\nTry this\nimport sys\nprint sys.version\n\nIf that doesn't give you an error, and says \"2.x\" then you are certainly. using 2.x\nIf it gives you a syntax error, its \"3.x\" \n(besides the obvious task of checking what sys.version holds, \"print sys.version...
[ 6, 4 ]
[]
[]
[ "debugging", "python", "python_3.x" ]
stackoverflow_0005447062_debugging_python_python_3.x.txt
Q: Python web client programming library I am working on a client-server simulation software. And I want the client to be implemented on the web, and also require that the client can do computations like matrix multiplication, random number generation etc., which framework can I use? And also I hope that the client s...
Python web client programming library
I am working on a client-server simulation software. And I want the client to be implemented on the web, and also require that the client can do computations like matrix multiplication, random number generation etc., which framework can I use? And also I hope that the client side and server side communicate using simpl...
[ "I'm assuming \"on the web\" means \"HTTP\", i.e. via an AJAX-like interface.\nThe relevant Python built-in libraries are httplib (HTTP client) and random (random numbers; may be better in NumPy). For matrix multiplication, you'll want the third-party library NumPy. You may want to look into SciPy as well.\n", "...
[ 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0005447104_c++_python.txt
Q: Why cant map the url to my request handler ('/\d+\?fmt=json',JsonHandler) class JsonHandler(webapp.RequestHandler): def get(self): self.response.out.write("hello") Hey, I am using google app engine python and tring to map the url to my request handler. The url is digits followed by ?fmt=json, but it just doe...
Why cant map the url to my request handler
('/\d+\?fmt=json',JsonHandler) class JsonHandler(webapp.RequestHandler): def get(self): self.response.out.write("hello") Hey, I am using google app engine python and tring to map the url to my request handler. The url is digits followed by ?fmt=json, but it just doesnt print out "hello" and the regex test returns...
[ "You shouldn't include the query parameter in the regex.\n('/\\d+',JsonHandler)\n\nclass JsonHandler(webapp.RequestHandler): \n def get(self):\n if self.request.get(\"fmt\") == \"json\": #check the query string in the get handler\n self.response.out.write(\"hello\")\n\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0005446490_google_app_engine_python_regex.txt
Q: Wordpress widget type functionality in Django I've been working with django over past couple of months. It seems that if I need some new value in a template, the only way to accomplish that is to pass it through the view function directly or an object that can be somehow used to retrieve that information. What if...
Wordpress widget type functionality in Django
I've been working with django over past couple of months. It seems that if I need some new value in a template, the only way to accomplish that is to pass it through the view function directly or an object that can be somehow used to retrieve that information. What if I want to "PULL" information from the template? Co...
[ "Ah, you have encountered one of the fundamental differences between Django (and most Python templating frameworks) and WordPress (and most PHP frameworks). PHP has a huge global name space that can be accessed from pretty much any place in the page creation process. Python, on the other hand, does not. Many of us ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005447266_django_python.txt
Q: Error Handling Variables in a calculator program, Error handling numbers are fine My problem is, as you can see by the title, error handling. Specifically with variables and symbols, those always seem to cause a NameError and shut down the program. My, well experimented with calculator from a tutorial online, calc...
Error Handling Variables in a calculator program, Error handling numbers are fine
My problem is, as you can see by the title, error handling. Specifically with variables and symbols, those always seem to cause a NameError and shut down the program. My, well experimented with calculator from a tutorial online, calculator program: #Calculator Program #this variable tells the loop whether it should loo...
[ "My feedback as follows : \n\nprint \" \" can be replaced with just print.\nelif choice == a does not work since a is not defined.\nSince all the operations take 2 operands, why not call them op1 and op2\nUse raw_input instead of input. input will eval the user input. For example, you can enter 1+2 for choice and ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005228641_python.txt
Q: URL encoding for Python OAuth2 I am using %20 to encode a url using oauth2 for python. It does not seem to work. I see that it encodes %20 as %252B . Is there a way around? Edited with example import oauth2 as oauth client = oauth.Client(consumer) url = 'http://localhost:8080/api/v1/search?Name=Julian' method= 'G...
URL encoding for Python OAuth2
I am using %20 to encode a url using oauth2 for python. It does not seem to work. I see that it encodes %20 as %252B . Is there a way around? Edited with example import oauth2 as oauth client = oauth.Client(consumer) url = 'http://localhost:8080/api/v1/search?Name=Julian' method= 'GET' response,content = client.reques...
[ "This could be a double quoting issue.\nurllib2.quote('%')\n'%25'\n\nCan you try not encoding your url before giving it to oauth?\n" ]
[ 1 ]
[]
[]
[ "oauth", "python", "urlencode" ]
stackoverflow_0005447160_oauth_python_urlencode.txt