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: How to sort a list by the 2nd tuple element in python and C# I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this: sorted(myList, key=lambda x: x[1]) which is great. My question is, is there an equally succinct way o...
How to sort a list by the 2nd tuple element in python and C#
I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this: sorted(myList, key=lambda x: x[1]) which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the ob...
[ "Another way to do it in python is this\nfrom operator import itemgetter\nsorted(myList, key=itemgetter(1))\n\n", "Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>> (a sequence of tuples represented using Tuple<..> class from .NET 4.0), you can write the following using LINQ extension metho...
[ 14, 6 ]
[]
[]
[ "c#", "python", "sorting" ]
stackoverflow_0002909652_c#_python_sorting.txt
Q: Is it bad practice to use python's getattr extensively? I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python. For flexibility's sake...
Is it bad practice to use python's getattr extensively?
I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python. For flexibility's sake (mostly for parsing commands), I'm thinking of changing my s...
[ "The difference between direct attribute access and using getattr() should be fairly negligible. You can tell the difference between the two versions' bytecodes by using Python's dis module to compare the two approaches:\n>>> import dis\n>>> dis.dis(lambda x: x.foo)\n 1 0 LOAD_FAST 0 (x)\n...
[ 27, 10 ]
[]
[]
[ "getattr", "performance", "python", "shell" ]
stackoverflow_0002909423_getattr_performance_python_shell.txt
Q: Python: Why Does a Method Behave Differently with an Added Parameter? I have a method in a Pygame Sprite subclass, defined as such: def walk(self): """move across screen""" displacement = self.rect.move((self.move, 0)) if self.rect.left < self.area.left or self.rect.right > self.area.right: sel...
Python: Why Does a Method Behave Differently with an Added Parameter?
I have a method in a Pygame Sprite subclass, defined as such: def walk(self): """move across screen""" displacement = self.rect.move((self.move, 0)) if self.rect.left < self.area.left or self.rect.right > self.area.right: self.move = -self.move displacement = self.rect.move((self.move, 0)) ...
[ "You don't explain how it's \"broken\", but the main difference is that\nspeed_x = -speed_x\n\nwhich you have in your second version, is only changing the local variable (arguments are local variables!) speed_x, so that changed value does not persist.\nIn the first version,\nself.move = -self.move \n\ndoes alter se...
[ 3, 1, 1, 1 ]
[]
[]
[ "oop", "pygame", "python" ]
stackoverflow_0002909948_oop_pygame_python.txt
Q: python grep reverse matching I would like to build a small python script that basicaly does the reverse of grep. I want to match the files in a directory/subdirectory that doesn't have a "searched_string". So far i've done that: import os filefilter = ['java','.jsp'] path= "/home/patate/code/project" for path, s...
python grep reverse matching
I would like to build a small python script that basicaly does the reverse of grep. I want to match the files in a directory/subdirectory that doesn't have a "searched_string". So far i've done that: import os filefilter = ['java','.jsp'] path= "/home/patate/code/project" for path, subdirs, files in os.walk(path): ...
[ "To check if a file with a path bound to variable f contains a string bound to name s, simplest (and acceptable for most reasonably-sized files) is something like\nwith open(f) as fp:\n if s in fp.read():\n print '%s has the string' % f\n else:\n print '%s doesn't have the string' % f\n\nIn your...
[ 1, 0 ]
[]
[]
[ "pattern_matching", "python" ]
stackoverflow_0002910106_pattern_matching_python.txt
Q: NZEC Run time Error Occured import math def gen_caller(a): for z in a: x,y=z if x==1: x=2 if y>=x and y-x<=100000: for i in range(x,y+1): flag=0 fo...
NZEC Run time Error Occured
import math def gen_caller(a): for z in a: x,y=z if x==1: x=2 if y>=x and y-x<=100000: for i in range(x,y+1): flag=0 for j in range(2,(long(math.sqrt(i)...
[ "Try using Python 3.1. Just change \"long\" to \"int\", \"raw_input\" to \"input\" and put brackets around what you want to print. I didn't get an error, probably because of better support of very large numbers in Python 3.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002772199_python.txt
Q: Running an allocation simulation repeatedly breaks after the first run Background I have a bunch of students, their desired projects and the supervisors for the respective projects. I'm running a battery of simulations to see which projects the students end up with, which will allow me to get some useful statistic...
Running an allocation simulation repeatedly breaks after the first run
Background I have a bunch of students, their desired projects and the supervisors for the respective projects. I'm running a battery of simulations to see which projects the students end up with, which will allow me to get some useful statistics required for feedback. So, this is essentially a Monte-Carlo simulation wh...
[ "Do you really intend to set the supervisor's quota to 0 in resetData()? Doesn't that mean all their projects are now blocked?\nQuoth the raven:\n\nThe supervisor has a fixed quota of students he can supervise. This is decremented by 1. Once the quota hits 0, all the projects from that supervisor become blocked and...
[ 0 ]
[]
[]
[ "montecarlo", "python" ]
stackoverflow_0002910240_montecarlo_python.txt
Q: Requesting information from the user inside a GTK main loop I am learning Python by building a simple PyGTK application that fetches data from some SVN repositories, using pysvn. The pysvn Client has a callback you can specify that it calls when Subversion needs authentication information for a repository. When th...
Requesting information from the user inside a GTK main loop
I am learning Python by building a simple PyGTK application that fetches data from some SVN repositories, using pysvn. The pysvn Client has a callback you can specify that it calls when Subversion needs authentication information for a repository. When that happens, I would like to open a dialog to ask the user for the...
[ "This is the way we do it in RabbitVCS. Essentially, the main application creates the dialog and runs it using the PyGTK gtk.Dialog run() method.\nBreaking it down, from the main app we have (see action.py):\ndef get_login(self, realm, username, may_save):\n\n # ...other code omitted...\n\n gtk.gdk.threads_en...
[ 1 ]
[]
[]
[ "multithreading", "pygtk", "pysvn", "python" ]
stackoverflow_0002865438_multithreading_pygtk_pysvn_python.txt
Q: Log flexlm licence usage from remote machine We have several software packages (SolidWorks, Pro/ENGINEER, OrCAD, Minitab... ) that use FlexLM to manage network licences. I have written a python program to poll the FlexLM daemons every few mintues using lmutil lmstat -a. However, this requires lmutil to be installe...
Log flexlm licence usage from remote machine
We have several software packages (SolidWorks, Pro/ENGINEER, OrCAD, Minitab... ) that use FlexLM to manage network licences. I have written a python program to poll the FlexLM daemons every few mintues using lmutil lmstat -a. However, this requires lmutil to be installed on the same machine as the python program. Our F...
[ "It seems the only way to get licence usage over a network is to poll the flexlm daemon using:\nlmutil lmstat -a -c <port-number@license-server>\n\nI've not marked orenhg's repsonse as an answer as it is advertising his product rather than answering the question.\n" ]
[ 4 ]
[]
[]
[ "flexlm", "python" ]
stackoverflow_0002789540_flexlm_python.txt
Q: python processs complete list files matched I'm trying to get simple code working, unfortunately I'm a python beginner. My script should return a list of files that doesn't match a pattern, more information here : python grep reverse matching My code is running but doesn't process the complete list of files found ...
python processs complete list files matched
I'm trying to get simple code working, unfortunately I'm a python beginner. My script should return a list of files that doesn't match a pattern, more information here : python grep reverse matching My code is running but doesn't process the complete list of files found as it should : import sys,os filefilter = ['.xml...
[ "Try using os.path.splitext to check for a matching file extension. \nfor path, subdirs, files in os.walk(path):\n for name in files:\n if os.path.splitext(name)[1] in filefilter:\n f = str(os.path.join(path, name))\n with open(f) as fp:\n if s in fp.read():\n ...
[ 0 ]
[]
[]
[ "os.walk", "python" ]
stackoverflow_0002910605_os.walk_python.txt
Q: Including a Django app's url.py is resulting in a 404 I have the following code in the urls.py in mysite project. /mysite/urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^gallery/$', include('mysite.gallery.urls')), ) This results in a 404 page when I try to access a url set in g...
Including a Django app's url.py is resulting in a 404
I have the following code in the urls.py in mysite project. /mysite/urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^gallery/$', include('mysite.gallery.urls')), ) This results in a 404 page when I try to access a url set in gallery/urls.py. /mysite/gallery/urls.py from django.conf.ur...
[ "Remove the $ from the regex of main urls.py\nurlpatterns = patterns('',\n (r'^gallery/', include('mysite.gallery.urls')),\n)\n\nYou don't need gallery in the included Urlconf.\nurlpatterns = patterns('', \n (r'^browse/$', 'mysite.gallery.views.browse'),\n (r'^photo/$', 'mysite.gallery.views.photo'),\n)\n...
[ 17 ]
[]
[]
[ "django", "django_urls", "http_status_code_404", "python", "url_routing" ]
stackoverflow_0002910714_django_django_urls_http_status_code_404_python_url_routing.txt
Q: One single page to create a Parent object and its associated child objects This is my very first post on this awesome site, from which I have been finding answers to a handful of challenging questions. Kudos to the community! I am new to the Django world, so am hoping to find help from some Django experts here. Th...
One single page to create a Parent object and its associated child objects
This is my very first post on this awesome site, from which I have been finding answers to a handful of challenging questions. Kudos to the community! I am new to the Django world, so am hoping to find help from some Django experts here. Thanks in advance. Item model: class Item(models.Model): name = models.CharFi...
[ "Considering that you are using file upload fields, I'm not sure that it's a right approach for web application. What if Item name validation fails? If you re-display the form again all file upload fields become empty and user has to fill them again.\nRe technical side - ModelForm will do for the Item model but you...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002910708_django_python.txt
Q: Python 2.6 -> Python 3 (ProxyHandler) I wrote a script that works with a proxy (py2.6x): proxy_support = urllib2.ProxyHandler({'http' : 'http://127.0.0.1:80'}) But in py3.11x there is no urllib2 just a urllib... and that doesn't support the ProxyHandler How can I use a proxy with urllib? Isn't Python 3 newer then...
Python 2.6 -> Python 3 (ProxyHandler)
I wrote a script that works with a proxy (py2.6x): proxy_support = urllib2.ProxyHandler({'http' : 'http://127.0.0.1:80'}) But in py3.11x there is no urllib2 just a urllib... and that doesn't support the ProxyHandler How can I use a proxy with urllib? Isn't Python 3 newer then Python 2? Why did they remove urllib2 in a...
[ "In Python 3, urllib2.ProxyHandler is now urllib.request.ProxyHandler.\nimport urllib.request\nproxy_support = urllib.request.ProxyHandler({'http' : 'http://127.0.0.1:80'})\n\nMany of the old url*libs have been merged with theurllib package.\nHere is a great explanation.\n", "It became urllib.request.ProxyHandler...
[ 10, 3 ]
[]
[]
[ "python", "python_3.x", "urllib", "urllib2" ]
stackoverflow_0002911042_python_python_3.x_urllib_urllib2.txt
Q: create a gtk.window under a gtk.widget I wanna show a gtk.Window under a gtk.widget. But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window. Anyone knows ? Thanks. A: You can use the "window" attribute of the gtk.Widget to get the gtk.gdk.Window associated with it. Then look at the get_o...
create a gtk.window under a gtk.widget
I wanna show a gtk.Window under a gtk.widget. But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window. Anyone knows ? Thanks.
[ "You can use the \"window\" attribute of the gtk.Widget to get the gtk.gdk.Window associated with it. Then look at the get_origin() method to get the screen coordinates.\nThese coordinates are for the top-level window, I believe (I could be wrong about that, but my code below seems to support that). You can use the...
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002893323_pygtk_python.txt
Q: How to get the related_name of a many-to-many-field? I'm trying to get the related_name of a many-to-many-field. The m2m-field is located betweeen the models "Group" and "Lection" and is defined in the group-model as following: lections = models.ManyToManyField(Lection, blank=True) The field looks like this: ...
How to get the related_name of a many-to-many-field?
I'm trying to get the related_name of a many-to-many-field. The m2m-field is located betweeen the models "Group" and "Lection" and is defined in the group-model as following: lections = models.ManyToManyField(Lection, blank=True) The field looks like this: <django.db.models.fields.related.ManyToManyField object at...
[ "Try:\nfield.related_query_name()\n\n", "What you pasted is basically:\n>>> f = models.ManyToManyField(...)\n>>> dir(f)\n(...)\n\nWhat you probably need, is to get an actual model class containing that field:\nclass MyModel(models.Model):\n my_field = models.ManyToManyField(..., related_name='some_related_name...
[ 6, 3, 0 ]
[]
[]
[ "django", "django_models", "m2m", "many_to_many", "python" ]
stackoverflow_0002850376_django_django_models_m2m_many_to_many_python.txt
Q: What are some useful TextMate features? I noticed that many people here use TextMate for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for. So, what feature have you found most h...
What are some useful TextMate features?
I noticed that many people here use TextMate for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for. So, what feature have you found most helpful for coding (mainly in Python)? Are the...
[ "Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...\ndiff file1.py file2.py | mate\n\n...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.\nTextMate's SVN integration is g...
[ 29, 15, 11, 11, 7, 5, 5, 5, 4, 3, 3, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "macos", "python", "text_editor", "textmate" ]
stackoverflow_0000033813_macos_python_text_editor_textmate.txt
Q: Best way to handle timed events in PyGame I'm working on a Tetris-clone type game and I'm wondering what would be the best way to handle the logic that moves the blocks down every N seconds. I initially did it the easy way: pygame.time.set_timer(USEREVENT+1, 300) This will of course add a PyGame event to the queu...
Best way to handle timed events in PyGame
I'm working on a Tetris-clone type game and I'm wondering what would be the best way to handle the logic that moves the blocks down every N seconds. I initially did it the easy way: pygame.time.set_timer(USEREVENT+1, 300) This will of course add a PyGame event to the queue every 300 milliseconds. In the main loop I ca...
[ "Here's how a typical game loop works:\nrepeat forever:\n read all pending events\n if current time > last frame + frame time:\n last frame = last frame + frame time\n update game\n redraw screen\n\nA timer that is supposed to fire every 300 ms but doesn't work if the user floods the game wit...
[ 3, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002908397_pygame_python.txt
Q: wxPython formatting questions I have an app I was working on to learn more about wxPython( I have been primarily been a scripter ). I forgot about it now I am opening it back up. It's a screen scraper, and I have it working almost the way I want it, going to build a regex parser to strip out the links in every scr...
wxPython formatting questions
I have an app I was working on to learn more about wxPython( I have been primarily been a scripter ). I forgot about it now I am opening it back up. It's a screen scraper, and I have it working almost the way I want it, going to build a regex parser to strip out the links in every scrape that I don't need. The question...
[ "You could create a single answer panel or frame (start with a separate frame, like you are doing now - MyHtmlFrame is fine). Don't create a new panel or frame for every result.\nCreate a `wx.ComboBox(self, -1, choices=['google','so']) somewhere, and bind self.Bind(wx.EVT_COMBOBOX, myHtmlFrame.setFrame).\nNow you n...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002906561_python_wxpython.txt
Q: Generic unit test scheduling I'm (re)writing a program that does generic unit test scheduling. The current program is a mono-threaded Perl program, but I'm willing to modularize it and parallelize the tests. I'm also considering rewriting it in Python. Here is what I need to do: I have a list of tests, with the f...
Generic unit test scheduling
I'm (re)writing a program that does generic unit test scheduling. The current program is a mono-threaded Perl program, but I'm willing to modularize it and parallelize the tests. I'm also considering rewriting it in Python. Here is what I need to do: I have a list of tests, with the following attributes: uri: a URI ...
[ "This sort of testing is not unit testing.\nIf you decide not to follow rjh's advice in order to keep most of the code you've already written, then convert your tests to use the standard test toolchain.\n\nUse Test::Class and friends to emit TAP.\nUse prove's -j option or Test::Aggregate to run tests in parallel.\n...
[ 4 ]
[]
[]
[ "dependencies", "perl", "python", "tree", "unit_testing" ]
stackoverflow_0002911462_dependencies_perl_python_tree_unit_testing.txt
Q: Installing Python in Windows XP My work PC has restrictions that stop me from adding programs to the start menu so when I try to install Python using the Python 2.6.5 Windows installer it can't complete as it tries to add a shortcut to my start menu. Is there a way around this? I.e another way of installing witho...
Installing Python in Windows XP
My work PC has restrictions that stop me from adding programs to the start menu so when I try to install Python using the Python 2.6.5 Windows installer it can't complete as it tries to add a shortcut to my start menu. Is there a way around this? I.e another way of installing without the need for a shortcut? Edit: I'l...
[ "http://www.portablepython.com/\nOr get Ubuntu.\n" ]
[ 2 ]
[]
[]
[ "python", "windows_installer", "windows_xp" ]
stackoverflow_0002911946_python_windows_installer_windows_xp.txt
Q: How does py2exe actually -and simply explained- work? :) I have a c++ app that calls another python one (bundled into an exe with py2exe) So I have 2 apps. So I was wondering: What if my c++ did what py2exe does? i.e. embed the python app in the c++ one. This way I won't depend on py2exe and its configurations...
How does py2exe actually -and simply explained- work? :)
I have a c++ app that calls another python one (bundled into an exe with py2exe) So I have 2 apps. So I was wondering: What if my c++ did what py2exe does? i.e. embed the python app in the c++ one. This way I won't depend on py2exe and its configurations nighmares (yes, it has some) Hence my questions: how does ...
[ "http://www.py2exe.org/index.cgi/FAQ\nBasically, it packages up your python install and redistributes it. It still runs your Python as Python on a Python interpreter. The exe it creates just kicks everything off.\nThe Python website has some methods on integrating with C++.\n" ]
[ 3 ]
[]
[]
[ "c++", "embed", "py2exe", "python" ]
stackoverflow_0002912404_c++_embed_py2exe_python.txt
Q: traverse a binary decison tree using python? how to traverse a binary decision tree using python language. given a tree,i want know how can we travesre from root to required leaf the feature of the required leaf are given in an dictionary form assume and have to traverse from root to leaf answering the questions a...
traverse a binary decison tree using python?
how to traverse a binary decision tree using python language. given a tree,i want know how can we travesre from root to required leaf the feature of the required leaf are given in an dictionary form assume and have to traverse from root to leaf answering the questions at each node with the details given in feature list...
[ "def walk(node):\n answer = ask(node.question)\n if answer == left:\n walk(node.left_tree)\n else:\n walk(node.right_tree)\n\n\ndef ask(question):\n # get answer somehow\n # depending on the answer choose which subtree to traverse\n return answer\n\n", "@TheMachineCharmer ...
[ 2, 0 ]
[]
[]
[ "decision_tree", "python", "traversal" ]
stackoverflow_0002911706_decision_tree_python_traversal.txt
Q: Which Language to target on Ubuntu? I'm a c# programmer by trade and looking to move my wares over to Ubuntu as a business concern. I have some experience of Python and like it a lot. My question is, as a developer which would be the best language to use when targeting ubuntu Mono c# or python as a commercial conc...
Which Language to target on Ubuntu?
I'm a c# programmer by trade and looking to move my wares over to Ubuntu as a business concern. I have some experience of Python and like it a lot. My question is, as a developer which would be the best language to use when targeting ubuntu Mono c# or python as a commercial concern. please note that I am not interested...
[ "Both Python and Mono are installed by default on recent Ubuntu, and will likely continue to be for the foreseeable future.\nMono is removable since it is currently only used by a few desktop apps. Python is not reasonably removable as a lot of core scripts and GNOME tools depend on it. (The same is true of Perl.)\...
[ 4, 2 ]
[]
[]
[ "c#", "mono", "python", "ubuntu" ]
stackoverflow_0002912216_c#_mono_python_ubuntu.txt
Q: Login through twitter failiing as "unauthorized" in OSQA I have installed OSQA on a site hosted on hostgator. The login functionality is working for google, yahoo and facebook, but when I click on twitter's icon it's generating an exception. I have already added the twitter consumer key and the twitter consumer se...
Login through twitter failiing as "unauthorized" in OSQA
I have installed OSQA on a site hosted on hostgator. The login functionality is working for google, yahoo and facebook, but when I click on twitter's icon it's generating an exception. I have already added the twitter consumer key and the twitter consumer secret through the admin interface. The exception I am getting i...
[ "I removed the earlier application created in twitter and created a new one. Added the new keys through administration panel and it resolved my issue.But i am still unable to figure out what caused problem in my earlier application?\n" ]
[ 0 ]
[]
[]
[ "osqa", "python", "twitter" ]
stackoverflow_0002911495_osqa_python_twitter.txt
Q: Not getting the correct result back from inet_aton/struct.unpack Using python 2.6.5 on Windows XP, it seems I'm getting the wrong result when using the following code: import struct import socket struct.unpack('L', socket.inet_aton('192.168.1.1'))[0] This returns 16885952 while to my knowledge it should return 32...
Not getting the correct result back from inet_aton/struct.unpack
Using python 2.6.5 on Windows XP, it seems I'm getting the wrong result when using the following code: import struct import socket struct.unpack('L', socket.inet_aton('192.168.1.1'))[0] This returns 16885952 while to my knowledge it should return 3232235777. Am I doing something wrong here? How do I fix this?
[ "You need to specify the endianess. Its interpreting the number as litle-endian, however inet_aton returns the number as big-endian.\nstruct.unpack('>L', socket.inet_aton('192.168.1.1'))[0]\n\nThis should work fine, and return the number you expected.\nSee the python documentation on \"struct\" for reference.\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0002912551_python.txt
Q: Important packages and modules not compatible with py2exe? Are there major/common/important packages that py2exe cannot handle? I am currently studying the possibility of creating a .exe from a Python program that will use Tkinter, some Excel file reading module, NumPy, SciPy and matplotlib: is it realistic to try...
Important packages and modules not compatible with py2exe?
Are there major/common/important packages that py2exe cannot handle? I am currently studying the possibility of creating a .exe from a Python program that will use Tkinter, some Excel file reading module, NumPy, SciPy and matplotlib: is it realistic to try to achieve this with py2exe?
[ "I routinely build py2exe single file executables using Scipy, matplotlib, wxpython and win32com or the Machin's xlrd/xlwt modules. Never used Tkinter but should not be a problem, probably wxpython is more picky.\nI have found some problems with numpy/scipy, matplotlib and wxpython before and after building the exe...
[ 3, 2 ]
[]
[]
[ "excel", "executable", "matplotlib", "py2exe", "python" ]
stackoverflow_0002912295_excel_executable_matplotlib_py2exe_python.txt
Q: Interesting task using random numbers only Given any number of the random real numbers from the interval [0,1] is there exist any method to construct a floating point number with zero fractional part? Your algorithm can use only random() function calls and no variables or constants. No constants and variables are...
Interesting task using random numbers only
Given any number of the random real numbers from the interval [0,1] is there exist any method to construct a floating point number with zero fractional part? Your algorithm can use only random() function calls and no variables or constants. No constants and variables are allowed, no type casting is allowed. You can us...
[ "Best I've come up with so far: generate a list of N random numbers, multiply them all together, this will go to 0 (which has a 0 fractional part) when N is large enough. \nOK, I used a variable (N), but I'm not sure how to use for loops or if statements without a variable or constant.\nIf I had more time and the ...
[ 4, 4, 4, 4, 2, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "c", "math", "python", "random" ]
stackoverflow_0002912025_algorithm_c_math_python_random.txt
Q: Scipy.cluster.hierarchy.fclusterdata + distance measure 1) I am using scipy's hcluster module. so the variable that I have control over is the threshold variable. How do I know my performance per threshold? i.e. In Kmeans, this performance will be the sum of all the points to their centroids. Of course, this has ...
Scipy.cluster.hierarchy.fclusterdata + distance measure
1) I am using scipy's hcluster module. so the variable that I have control over is the threshold variable. How do I know my performance per threshold? i.e. In Kmeans, this performance will be the sum of all the points to their centroids. Of course, this has to be adjusted since more clusters = less distance generally....
[ "One can calculate average distances |x - cluster centre| for x in cluster, just as for K-means.\nThe following does this brute-force. (It must be a builtin\nin scipy.cluster or scipy.spatial.distance but I can't find it either.)\nOn your question 2, pass. Any links to good tutorials on hierarchical clustering woul...
[ 5 ]
[]
[]
[ "cluster_analysis", "python", "scipy" ]
stackoverflow_0002547391_cluster_analysis_python_scipy.txt
Q: How to iterate over function arguments I have a Python function accepting several string arguments def foo(a, b, c): and concatenating them in a string. I want to iterate over all function arguments to check they are not None. How it can be done? Is there a quick way to convert None to ""? Thanks. A: locals() ma...
How to iterate over function arguments
I have a Python function accepting several string arguments def foo(a, b, c): and concatenating them in a string. I want to iterate over all function arguments to check they are not None. How it can be done? Is there a quick way to convert None to ""? Thanks.
[ "locals() may be your friend here if you call it first thing in your function.\nExample 1:\n>>> def fun(a, b, c):\n... d = locals()\n... e = d\n... print e\n... print locals()\n... \n>>> fun(1, 2, 3)\n{'a': 1, 'c': 3, 'b': 2}\n{'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}}\n\nExample 2:\n>>> def n...
[ 66, 21, 4, 2 ]
[ "I would use sed s/None//g, but that's not in python, but you can probably use os.popen() to do that.\n" ]
[ -6 ]
[ "arguments", "python" ]
stackoverflow_0002912615_arguments_python.txt
Q: How to Return Variable for all tests to use Unittest I have a Python script and I am trying to set a variable so that if the first test fail's the rest of then will be set to fail. The script I have so far is: class Tests(unittest.TestCase): def result(self): ....This function does something[ignore].....
How to Return Variable for all tests to use Unittest
I have a Python script and I am trying to set a variable so that if the first test fail's the rest of then will be set to fail. The script I have so far is: class Tests(unittest.TestCase): def result(self): ....This function does something[ignore]...... someArg = 0 def testPass(self): ...
[ "I'm having a hard time understanding your code, so let's pinpoint a few bits that I do understand (as it look like you may believe things are different from how they are).\nThe call\nself.errorHandle() \n\nwhich you perform repeatedly works as a no-operation: the errorHandle method just does a return, the callers...
[ 1 ]
[]
[]
[ "inheritance", "python", "unit_testing" ]
stackoverflow_0002913053_inheritance_python_unit_testing.txt
Q: How should I correctly handle exceptions in Python3 I can't understand what sort of exceptions I should handle 'here and now', and what sort of exceptions I should re-raise or just don't handle here, and what to do with them later (on higher tier). For example: I wrote client/server application using python3 with ...
How should I correctly handle exceptions in Python3
I can't understand what sort of exceptions I should handle 'here and now', and what sort of exceptions I should re-raise or just don't handle here, and what to do with them later (on higher tier). For example: I wrote client/server application using python3 with ssl communication. Client is supposed to verify files on ...
[ "In general, you should \"catch\" the exceptions that you expect to happen (because they may be caused by user error, or other environmental problems outside of your program's control), especially if you know what your code might be able to do about them. Just giving more details in an error report is a marginal i...
[ 24, 3 ]
[]
[]
[ "exception", "logging", "python" ]
stackoverflow_0002913819_exception_logging_python.txt
Q: Django's Admin - Many-to-Many field confusion I'm teaching myself Django and creating a personal portfolio site. I've setup a model called FolioItem which makes use of a Many-To-Many relation to another model called FolioImage. The idea being each FolioItem can have numerous FolioImages. class FolioImage(models.Mo...
Django's Admin - Many-to-Many field confusion
I'm teaching myself Django and creating a personal portfolio site. I've setup a model called FolioItem which makes use of a Many-To-Many relation to another model called FolioImage. The idea being each FolioItem can have numerous FolioImages. class FolioImage(models.Model): image = models.FileField(upload_to='portf...
[ "\nIs there any way to force this\n selector to be blank when creating a\n new item?\n\nI think you are slightly confused about the interface to the default select multiple widget. It is showing you all the existing images, making them available to you as choices, but there is no relationship on a brand new item....
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002913095_django_python.txt
Q: Injecting raw TCP packets with Python What would be a suitable way to inject a raw TCP packet with Python? For example, I have the payload consisting of hexadecimal numbers and I want to send that sequence of hexadecimal numbers to a network daemon: so that if I choose to send 'abcdef', I see 'abcdef' on the wire ...
Injecting raw TCP packets with Python
What would be a suitable way to inject a raw TCP packet with Python? For example, I have the payload consisting of hexadecimal numbers and I want to send that sequence of hexadecimal numbers to a network daemon: so that if I choose to send 'abcdef', I see 'abcdef' on the wire too. But not '6162636566' as in the case of...
[ "Try scapy, a powerful interactive packet manipulation program.\nExample:\n%> sudo scapy\n\n>>> packet1 = IP(dst='127.0.0.1')/TCP(dport=9999)\n>>> packet1.payload = 'abcdef'\n>>> send(packet1)\n.\nSent 1 packets.\n>>> packet1.show()\n###[ IP ]###\n version= 4\n ihl= None\n tos= 0x0\n len= None\n id= 1\n flags...
[ 11, 1, 1, 1 ]
[]
[]
[ "python", "tcp" ]
stackoverflow_0002912123_python_tcp.txt
Q: Python : How to close a UDP socket while is waiting for data in recv? let's consider this code in python: import socket import threading import sys import select class UDPServer: def __init__(self): self.s=None self.t=None def start(self,port=8888): if not self.s: self....
Python : How to close a UDP socket while is waiting for data in recv?
let's consider this code in python: import socket import threading import sys import select class UDPServer: def __init__(self): self.s=None self.t=None def start(self,port=8888): if not self.s: self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.s.bind...
[ "The usual solution is to have a pipe tell the worker thread when to die.\n\nCreate a pipe using os.pipe. This gives you a socket with both the reading and writing ends in the same program. It returns raw file descriptors, which you can use as-is (os.read and os.write) or turn into Python file objects using os.fd...
[ 4, 1 ]
[]
[]
[ "multithreading", "python", "recv", "sockets" ]
stackoverflow_0002912245_multithreading_python_recv_sockets.txt
Q: ctypes DLL with optional dependencies Disclaimer: I'm new to windows programming so some of my assumptions may be wrong. Please correct me if so. I am developing a python wrapper for a C API using ctypes. The API ships with both 64 and 32 DLLs/LIBs. I can succesfully load the DLL using ctypes.WinDLL('TheLibName') ...
ctypes DLL with optional dependencies
Disclaimer: I'm new to windows programming so some of my assumptions may be wrong. Please correct me if so. I am developing a python wrapper for a C API using ctypes. The API ships with both 64 and 32 DLLs/LIBs. I can succesfully load the DLL using ctypes.WinDLL('TheLibName') and call functions etc etc. However some fu...
[ "I can load LibName64 when I use the 64 bit version of python. Should have tried that earlier!\n" ]
[ 0 ]
[]
[]
[ "ctypes", "dll", "python", "visual_studio", "windows" ]
stackoverflow_0002914585_ctypes_dll_python_visual_studio_windows.txt
Q: How can I share data (which is updated every minute) accoss modules in Python? I have read in many posts that global variables are bad, but I need them! My situation: I have few variables defined in a dedicated module which are updated every minute and are used by other modules in the application. (Implemented aft...
How can I share data (which is updated every minute) accoss modules in Python?
I have read in many posts that global variables are bad, but I need them! My situation: I have few variables defined in a dedicated module which are updated every minute and are used by other modules in the application. (Implemented after reading this), Do you think its a good approach or needs any improvement or any b...
[ "This sounds like a good place for the pub/sub technique, where you have objects watch for changes. This is useful in things like GUIs, when you need to update some widget whenever the value it displays changes.\nSomething very simple:\n>>> class Widget(object):\n def __init__(self, name, val):\n self.nam...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002914823_python.txt
Q: Saving a Django form to a csv file I have a Django form that is working fine. I'd like to save the data it submits to a CSV file. Is there a "best practice" way to do this? I need to include blank fields in the CSV file where the user has not filled in a "required=False" field A: You can find the document CSV F...
Saving a Django form to a csv file
I have a Django form that is working fine. I'd like to save the data it submits to a CSV file. Is there a "best practice" way to do this? I need to include blank fields in the CSV file where the user has not filled in a "required=False" field
[ "You can find the document CSV File Reading and Writing very helpful for your problem.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "forms", "python" ]
stackoverflow_0002915045_django_django_forms_forms_python.txt
Q: How to optimize this Python code? def maxVote(nLabels): count = {} maxList = [] maxCount = 0 for nLabel in nLabels: if nLabel in count: count[nLabel] += 1 else: count[nLabel] = 1 #Check if the count is max if count[nLabel] > maxCount: ...
How to optimize this Python code?
def maxVote(nLabels): count = {} maxList = [] maxCount = 0 for nLabel in nLabels: if nLabel in count: count[nLabel] += 1 else: count[nLabel] = 1 #Check if the count is max if count[nLabel] > maxCount: maxCount = count[nLabel] ma...
[ "import random\nimport collections\n\ndef maxvote(nlabels):\n cnt = collections.defaultdict(int)\n for i in nlabels:\n cnt[i] += 1\n maxv = max(cnt.itervalues())\n return random.choice([k for k,v in cnt.iteritems() if v == maxv])\n\nprint maxvote([1,3,4,5,5,5,3,3,11])\n\n", "In Python 3.1 or future 2.7 you...
[ 6, 5, 2, 1, 0, 0 ]
[]
[]
[ "algorithm", "data_structures", "python" ]
stackoverflow_0002915095_algorithm_data_structures_python.txt
Q: jEdit+JythonInterpreter: how to import java class? I'm running jEdit with the JythonInterprete and I have a .jar file called JavaTest.jar. JavaTest has a class called SampleJavaClass which has a method printerCount. From my .py file, I want to do: from javatest import SampleJavaClass class SampleClass(SampleJava...
jEdit+JythonInterpreter: how to import java class?
I'm running jEdit with the JythonInterprete and I have a .jar file called JavaTest.jar. JavaTest has a class called SampleJavaClass which has a method printerCount. From my .py file, I want to do: from javatest import SampleJavaClass class SampleClass(SampleJavaClass): def pymain(self): SampleJavaClass.printerCoun...
[ "You need to add the JavaTest.jar to the Java classpath used by jEdit. The Jython path is used to tell Jython where the Python modules are, the Java classpath is used to tell the JVM where the Java jars are. In order to access javatest.SampleJavaClass in Jython the JVM must first be able to find it. It will then...
[ 2 ]
[]
[]
[ "java", "jedit", "jython", "python" ]
stackoverflow_0002906074_java_jedit_jython_python.txt
Q: Python FTP grabbing and saving images issue EDIT: I got it working it just won't download anything... So here is my code simplified now: notions_ftp = ftplib.FTP(ftp_host, ftp_user, ftp_passwd) folder = "Leisure Arts - Images" notions_ftp.cwd(folder) image = open("015693PR-com.jpg","wb") notions_ftp.retrlines("RET...
Python FTP grabbing and saving images issue
EDIT: I got it working it just won't download anything... So here is my code simplified now: notions_ftp = ftplib.FTP(ftp_host, ftp_user, ftp_passwd) folder = "Leisure Arts - Images" notions_ftp.cwd(folder) image = open("015693PR-com.jpg","wb") notions_ftp.retrlines("RETR 015693PR-com.jpg", image.write) send_image = op...
[ "You're reading the file instead of writing it.\nSo instead of open(image_name_we_want, \"rb\") use open(image_name_we_want, \"wb\")\n[edit]\nIf you're simply fetching from an ftp server than you could also try this:\nimport urllib2\nfh = urllib2.urlopen('ftp://server/path/file.png')\nfile('file.png', 'wb').write(f...
[ 1 ]
[]
[]
[ "ftp", "image", "python" ]
stackoverflow_0002915597_ftp_image_python.txt
Q: Getting Unit Tests to work with Komodo IDE for Python I've tried to run the following code on Komodo IDE (for python): import unittest class MathLibraryTests(unittest.TestCase): def test1Plus1Equals2(self): self.assertEqual(1+1, 2) Then, I created a new test plan, pointing to this project(file) direc...
Getting Unit Tests to work with Komodo IDE for Python
I've tried to run the following code on Komodo IDE (for python): import unittest class MathLibraryTests(unittest.TestCase): def test1Plus1Equals2(self): self.assertEqual(1+1, 2) Then, I created a new test plan, pointing to this project(file) directory and tried to run it the test plan. It seems to run but...
[ "For the test file to be picked up the filename must start with test_. I tried using just test.py which failed, however test_.py works like a dream.\nAll you need to do is rename your file. This is not made very clear in the documentation - I worked it out via a bug report on Komodo's web site.\nIt would be nice if...
[ 6 ]
[]
[]
[ "ide", "komodo", "python", "unit_testing" ]
stackoverflow_0002870319_ide_komodo_python_unit_testing.txt
Q: Convert GeoTIFF to JPEG and Extract GeoTIFF Headers in Python I am making a Python script which will read in a GeoTIFF file, and will do both: convert the GeoTIFF into a static JPEG (that is much smaller in size), and create a separate text file which contains the GeoTIFF headers. Using the Python GDAL API, I am a...
Convert GeoTIFF to JPEG and Extract GeoTIFF Headers in Python
I am making a Python script which will read in a GeoTIFF file, and will do both: convert the GeoTIFF into a static JPEG (that is much smaller in size), and create a separate text file which contains the GeoTIFF headers. Using the Python GDAL API, I am able to get the script to open a GeoTIFF file, and print details, su...
[ "I figured it out myself with some Googling.\nTo save the .jpg file with varying level of quality, you need to use the following code:\n# Assume this retrieves the dataset from a GeoTIFF file.\ndataset = getDataSet(tiffFileLocation) \n\nsaveOptions = []\nsaveOptions.append(\"QUALITY=75\")\n\n# Obtains a JPEG G...
[ 8 ]
[]
[]
[ "gdal", "geospatial", "jpeg", "python", "tiff" ]
stackoverflow_0002913208_gdal_geospatial_jpeg_python_tiff.txt
Q: Reliable and fast way to convert a zillion ODT files in PDF? I need to pre-produce a million or two PDF files from a simple template (a few pages and tables) with embedded fonts. Usually, I would stay low level in a case like this, and compose everything with a library like ReportLab, but I joined late in the proj...
Reliable and fast way to convert a zillion ODT files in PDF?
I need to pre-produce a million or two PDF files from a simple template (a few pages and tables) with embedded fonts. Usually, I would stay low level in a case like this, and compose everything with a library like ReportLab, but I joined late in the project. Currently, I have a template.odt and use markers in the conte...
[ "For creating such large amount of PDF files OpenOffice seems me the wrong product. You should use a real reporting solution which is optimized for creating large amount of PDF files. There many different tools. I would recommended i-net Clear Reports (used to be called i-net Crystal-Clear).\n\nI would expect that ...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "openoffice.org", "pdf", "python", "reporting" ]
stackoverflow_0002903774_openoffice.org_pdf_python_reporting.txt
Q: Python - drag file into .exe to run script I have a Python script that takes the directory path of a text file and converts it into an excel file. Currently I have it running as a console application (compiled with py2exe) and prompts the user for the directory path through raw_input(). How do i make it such that...
Python - drag file into .exe to run script
I have a Python script that takes the directory path of a text file and converts it into an excel file. Currently I have it running as a console application (compiled with py2exe) and prompts the user for the directory path through raw_input(). How do i make it such that I can drag & drop my text file directly into th...
[ "The dropped file will be available as an element of sys.argv.\n" ]
[ 4 ]
[]
[]
[ "drag_and_drop", "executable", "python" ]
stackoverflow_0002915945_drag_and_drop_executable_python.txt
Q: Loading a wave from waveid I'm working on a small wave thingy where i need to load a wave based on an outside event. So i don't have a context to work with. I've been looking at the python api for a while but i can't figure out the correct way to get a wave object (that i can then call CreateBlip() on) when i just...
Loading a wave from waveid
I'm working on a small wave thingy where i need to load a wave based on an outside event. So i don't have a context to work with. I've been looking at the python api for a while but i can't figure out the correct way to get a wave object (that i can then call CreateBlip() on) when i just have the waveid. Is there somet...
[ "At Google I/O, the Wave Data API was announced which allows for pulling waves which haven't previously gotten a context as long as they're accessible to a @googlewave.com user authenticated through OAuth. However, this can not call CreateBlip()\n", "At the moment the answer is that i can't be done. Hopefully in ...
[ 1, 0 ]
[]
[]
[ "google_wave", "python" ]
stackoverflow_0001876908_google_wave_python.txt
Q: What is the Pythonic way to implement a simple FSM? Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 bytes and output the given amount of data from there. Repeat to the end of the file. My so...
What is the Pythonic way to implement a simple FSM?
Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 bytes and output the given amount of data from there. Repeat to the end of the file. My solution did work, and was very quick to put together (even...
[ "The coolest way I've seen to implement FSMs in Python has to be via generators and coroutines. See this Charming Python post for an example. Eli Bendersky also has an excellent treatment of the subject.\nIf coroutines aren't familiar territory, David Beazley's A Curious Course on Coroutines and Concurrency is a st...
[ 8, 7, 3, 1, 1, 1, 1 ]
[]
[]
[ "fsm", "python" ]
stackoverflow_0002916181_fsm_python.txt
Q: Unit Testing Interfaces in Python I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures. I began to write a unit test suite for the project but ran into difficulties into creating a generic unit ...
Unit Testing Interfaces in Python
I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures. I began to write a unit test suite for the project but ran into difficulties into creating a generic unit test that only tests the interface and ...
[ "I personally like nose test generation more for this sort of thing. I'd then write it like:\n# They happen to all be simple callable factories, if they weren't you could put\n# a function in here:\nmake_heaps = [BinaryHeap, BinomialHeap]\n\ndef test_heaps():\n for make_heap in make_heaps:\n for checker ...
[ 4, 2, 1 ]
[]
[]
[ "interface", "python", "test_suite", "unit_testing" ]
stackoverflow_0002915286_interface_python_test_suite_unit_testing.txt
Q: Reinterpret a CGImageRef using PyObjC in Python I'm doing something that's a little complicated to sum up in the title, so please bear with me. I'm writing a Python module that provides an interface to my C++ library, which provides some specialized image manipulation functionality. It would be most convenient to ...
Reinterpret a CGImageRef using PyObjC in Python
I'm doing something that's a little complicated to sum up in the title, so please bear with me. I'm writing a Python module that provides an interface to my C++ library, which provides some specialized image manipulation functionality. It would be most convenient to be able to access image buffers as CGImageRefs from P...
[ "I think a wrapper is your only option since it is an undefined struct and Boost::Python demands to know the interface. Here is a starting point:\nhttp://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/faq.html#xref\nI would add the necessary member functions you need into the wrapper. I am doing something somewha...
[ 0 ]
[]
[]
[ "boost_python", "core_graphics", "pyobjc", "python" ]
stackoverflow_0002822887_boost_python_core_graphics_pyobjc_python.txt
Q: Why is sys.path showing non-existent items (which cause import problems)? I'm seeing some additional items in sys.path which 1) don't exist and 2) cause problems with imports (specifically with Nose). Basically, I've created a package (lets call it foo) which I use in multiple projects. The project I'm working on ...
Why is sys.path showing non-existent items (which cause import problems)?
I'm seeing some additional items in sys.path which 1) don't exist and 2) cause problems with imports (specifically with Nose). Basically, I've created a package (lets call it foo) which I use in multiple projects. The project I'm working on at the moment can import everything from foo without issue, but when I run Nose...
[ "Do you have anything in $PYTHONPATH? This will put entries in sys.path even within a virtualenv enviroment.\nTry unset PYTHONPATH in bash (if you use bash) and then see what your sys.path contains.\n", "Look for .pth files anywhere on the path. These files (e.g., easy-install.pth) can contain additional sys.pat...
[ 0, 0 ]
[]
[]
[ "egg", "python" ]
stackoverflow_0002914516_egg_python.txt
Q: Python doctest error Hi I recently started experimenting with python currently reading "Think like a computer scientist: Learning python v2nd edition" I have been having some trouble with doctest. I use a windows 7 machine and Eclipse IDE with pydev. My question is when i run the script below i get the error belo...
Python doctest error
Hi I recently started experimenting with python currently reading "Think like a computer scientist: Learning python v2nd edition" I have been having some trouble with doctest. I use a windows 7 machine and Eclipse IDE with pydev. My question is when i run the script below i get the error below. Said script is below th...
[ "you shoud write:\n>>> compare(5, 4)\n\nas the error said: missing blank before compare\n" ]
[ 6 ]
[]
[]
[ "doctest", "python" ]
stackoverflow_0002916351_doctest_python.txt
Q: How do I sort a list of python Django objects? In Django, I have a model object in a list. [object, object, object] Each object has ".name" which is the title of the thing. How do I sort alphabetically by this title? This doesn't work: catlist.sort(key=lambda x.name: x.name.lower()) A: catlist.sort(key=lambda x...
How do I sort a list of python Django objects?
In Django, I have a model object in a list. [object, object, object] Each object has ".name" which is the title of the thing. How do I sort alphabetically by this title? This doesn't work: catlist.sort(key=lambda x.name: x.name.lower())
[ "catlist.sort(key=lambda x: x.name.lower())\n\n", "Without the call to lower(), the following could be considered slightly cleaner than using a lambda:\nimport operator\ncatlist.sort(key=operator.attrgetter('name'))\n\nAdd that call to lower(), and you enter into a world of function-composition pain. Using Ants ...
[ 12, 2 ]
[]
[]
[ "django", "list", "python", "sorting" ]
stackoverflow_0002916558_django_list_python_sorting.txt
Q: Distributing a Python library (single file) For my project I would be using the argparse library. My question is, how do I distribute it with my project. I am asking this because of the technicalities and legalities involved. Do I just: Put the argparse.py file along with my project. That is, in the tar file for...
Distributing a Python library (single file)
For my project I would be using the argparse library. My question is, how do I distribute it with my project. I am asking this because of the technicalities and legalities involved. Do I just: Put the argparse.py file along with my project. That is, in the tar file for my project. Create a package for it for my distr...
[ "It would be best for the user to install it so that only one copy is present on the system and so that it can be updated if there are any issues, but including it with your project is a viable option if you abide by all requirements specified in the license.\nTry to import it from the public location, and if that ...
[ 1, 1, 1 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0002916116_argparse_python.txt
Q: How to import * with __import__ What's the best approach to execute the following using __import__ so that I may dynamically specify the module? from module import * A: The only way I found: module = __import__(module, globals(), locals(), ['*']) for k in dir(module): locals()[k] = getattr(module, k) A: It...
How to import * with __import__
What's the best approach to execute the following using __import__ so that I may dynamically specify the module? from module import *
[ "The only way I found:\nmodule = __import__(module, globals(), locals(), ['*'])\nfor k in dir(module):\n locals()[k] = getattr(module, k)\n\n", "It's the same as a normal from-import call, you just pass it a list containing '*' for the fromlist:\nmoduleName = \"foo\"\n__import__(moduleName, globals(), locals()...
[ 17, 5, 4 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002916374_import_python.txt
Q: Hide script extension I have a html form that posts to a python script test.py. If someone tries to access the script directly, it redirects them to the form. I not using a web framework, just straight python cgi programming. My website is hosted on a shared hosting provider that allows me access to a .htaccess fi...
Hide script extension
I have a html form that posts to a python script test.py. If someone tries to access the script directly, it redirects them to the form. I not using a web framework, just straight python cgi programming. My website is hosted on a shared hosting provider that allows me access to a .htaccess file. I wanted to know if the...
[ "Try this:\nRewriteEngine On\nRewriteRule ^/test/$ /test.py \n\n", "Absolutely. Use mod_rewrite to rewrite the URL as desired.\n" ]
[ 3, 1 ]
[]
[]
[ "cgi", "python", "web_applications" ]
stackoverflow_0002917357_cgi_python_web_applications.txt
Q: Help a Python newbie with a Django model inheritance problem I'm working on my first real Django project after years of PHP programming, and I am running into a problem with my models. First, I noticed that I was copying and pasting code between the models, and being a diligent OO programmer I decided to make a p...
Help a Python newbie with a Django model inheritance problem
I'm working on my first real Django project after years of PHP programming, and I am running into a problem with my models. First, I noticed that I was copying and pasting code between the models, and being a diligent OO programmer I decided to make a parent class that the other models could inherit from: class Common...
[ "No, Django doesn't allow that. \nSee the docs: http://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permitted\nAlso answered in other questions like: In Django - Model Inheritance - Does it allow you to override a parent model's attribute?\n", "You have a small mistake in your Common c...
[ 2, 1, 1, 0 ]
[]
[]
[ "django", "django_inheritance", "django_models", "python" ]
stackoverflow_0002914380_django_django_inheritance_django_models_python.txt
Q: Recognition source of event in PyQT I`m starting with PyQt4 and right now I have a problem with events. I have one main class let say MainWindow. MainWindow has a list of buttons of type ButtonX (inherence form QPushButton). I would like to achieve one of 2 solutions (depends which is easier). 1) After click one o...
Recognition source of event in PyQT
I`m starting with PyQt4 and right now I have a problem with events. I have one main class let say MainWindow. MainWindow has a list of buttons of type ButtonX (inherence form QPushButton). I would like to achieve one of 2 solutions (depends which is easier). 1) After click one of the button from the list I would like t...
[ "\n1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)\n\nYou can access the source of an event using QObject.sender(). But, as the instructions indicate, it's often better to use QSignalMap...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "user_interface" ]
stackoverflow_0002917292_pyqt_pyqt4_python_qt_user_interface.txt
Q: django multiprocess problem I have django application, running under lighttpd via fastcgi. FCGI running script looks like: python manage.py runfcgi socket=<path>/main.socket method=prefork \ pidfile=<path>/s...
django multiprocess problem
I have django application, running under lighttpd via fastcgi. FCGI running script looks like: python manage.py runfcgi socket=<path>/main.socket method=prefork \ pidfile=<path>/server.pid \ ...
[ "SQLite is not good choice if you need such concurrent access to database.\nI suggest switching to some other rdbms, like MySQL or PostgreSQL,\nand also take into account get_or_create fragility:\nHow do I deal with this race condition in django?\nRegarding the above link, there is also second solution to that prob...
[ 1 ]
[]
[]
[ "django", "python", "sqlite", "transactions" ]
stackoverflow_0002915609_django_python_sqlite_transactions.txt
Q: memcache won't store key/value because the value is too big cache.set(key, Biglist, 3600) print cache.get(key) When my "Biglist" is a huge list of lots of content, it doesn't seem to store. But when I change it to small text like "abc", it stores. What do I have to configure so that I can set my memcache to accep...
memcache won't store key/value because the value is too big
cache.set(key, Biglist, 3600) print cache.get(key) When my "Biglist" is a huge list of lots of content, it doesn't seem to store. But when I change it to small text like "abc", it stores. What do I have to configure so that I can set my memcache to accept unlimited size of key/value?
[ "See What is the maximum data size you can store section in the FAQ.\n\nWhat is the maximum data size you can store? (1 megabyte)\nThe maximum size of a value you can store in memcached is 1 megabyte. If your data is larger, consider clientside compression or splitting the value up into multiple keys.\nWhy are item...
[ 5 ]
[]
[]
[ "django", "key_value", "memcached", "python" ]
stackoverflow_0002917484_django_key_value_memcached_python.txt
Q: Describe this feature of a programming language Is there a way to describe the feature of a programming language that allows you to do something like the following: $foo = return_an_array()[0]; I love this feature in python, and I hate that it's missing in PHP. Is there a name for this? A: Array indexing on arb...
Describe this feature of a programming language
Is there a way to describe the feature of a programming language that allows you to do something like the following: $foo = return_an_array()[0]; I love this feature in python, and I hate that it's missing in PHP. Is there a name for this?
[ "Array indexing on arbitrary expressions\n" ]
[ 4 ]
[]
[]
[ "arrays", "python", "return_value" ]
stackoverflow_0002917761_arrays_python_return_value.txt
Q: Self-contained python installation with executable tools included (pip, orbited, etc) I'm trying deploy a Python application on Windows as a folder that includes a full python 2.6 folder. I don't need/want a fancy solution like py2exe, I'm just trying to automate deployment of a web application. So long as I inclu...
Self-contained python installation with executable tools included (pip, orbited, etc)
I'm trying deploy a Python application on Windows as a folder that includes a full python 2.6 folder. I don't need/want a fancy solution like py2exe, I'm just trying to automate deployment of a web application. So long as I include python26.dll and set the PYTHONHOME correctly, things seem to work if I just include the...
[ "How about trying to use virtualenv?\n" ]
[ 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002916616_python_windows.txt
Q: I have a very long and repetitive python path, where do I look to correct this? I know it is probably not necessary to paste the whole path, but just for the record I have done so below. Whenever I run a python command, it takes a long time to load this path I suppose. I have checked in .bash_profile and only have...
I have a very long and repetitive python path, where do I look to correct this?
I know it is probably not necessary to paste the whole path, but just for the record I have done so below. Whenever I run a python command, it takes a long time to load this path I suppose. I have checked in .bash_profile and only have these two lines: export PATH=/Users/username/bin:/opt/local/Library/Frameworks/Pytho...
[ "There are probably some files with extension .pth presumably in site-packages that add things to sys.path. This would explain (and let you fix) everything except the repetitions, which your site.py should actually eliminate (did you perhaps change site.py? Nobody ever does or should, but ...\nIf site.py is unbro...
[ 1 ]
[]
[]
[ "development_environment", "path", "python", "pythonpath", "shell" ]
stackoverflow_0002917790_development_environment_path_python_pythonpath_shell.txt
Q: What is the hard recursion limit for Linux, Mac and Windows? Python's sys module provides a function setrecursionlimit that lets you change Python's maximum recursion limit. The docs say: The highest possible limit is platform-dependent. My question is: What is the highest possible limits for various platforms, ...
What is the hard recursion limit for Linux, Mac and Windows?
Python's sys module provides a function setrecursionlimit that lets you change Python's maximum recursion limit. The docs say: The highest possible limit is platform-dependent. My question is: What is the highest possible limits for various platforms, under CPython? I would like to know the values for Linux, Mac and ...
[ "On Windows (at least), sys.setrecursionlimit isn't the full story. The hard limit is on a per-thread basis and you need to call threading.stack_size and create a new thread once you reach a certain limit. (I think 1MB, but not sure) I've used this approach to increase it to a 64MB stack.\nimport sys\nimport thre...
[ 36, 3 ]
[]
[]
[ "platform", "python", "recursion" ]
stackoverflow_0002917210_platform_python_recursion.txt
Q: Python alternative to Adobe Real Time Messaging Protocol Is there a way to stream audio and video over the internet using Python Web Programming and not Flash? A: Python is a server-side language, Flash is a client-side language. They do completely different things. If you want to look at video streaming that do...
Python alternative to Adobe Real Time Messaging Protocol
Is there a way to stream audio and video over the internet using Python Web Programming and not Flash?
[ "Python is a server-side language, Flash is a client-side language. They do completely different things.\nIf you want to look at video streaming that doesn't require Flash, take a look at the HTML5 video element, which is a portion of the HTML5 standard being developed and is handled client-side by the browser.\n" ...
[ 0 ]
[]
[]
[ "audio_streaming", "python", "streaming", "video_streaming" ]
stackoverflow_0002918199_audio_streaming_python_streaming_video_streaming.txt
Q: Python encoding ISO to UTF8 I am trying to read my emails using a Python script (Python 2.5 and PyPy) Some of my results are not in ASCII and i get strings like this: =?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?=' Is there any way to decode it and convert to utf-8 so that i can process it? I tried .decode('I...
Python encoding ISO to UTF8
I am trying to read my emails using a Python script (Python 2.5 and PyPy) Some of my results are not in ASCII and i get strings like this: =?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?=' Is there any way to decode it and convert to utf-8 so that i can process it? I tried .decode('ISO-8859-7') but i got the same st...
[ "import email.header as eh\n\nunicode_data= u''.join(\n str_data.decode(codec or 'ascii')\n for str_data, codec\n in eh.decode_header('=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='))\n# unicode_data now is u'Πεζοπορία στον Κιθαιρώνα'\n\nYou should work with unicode_data here. However, if you (think yo...
[ 5, 1 ]
[]
[]
[ "encoding", "internationalization", "python" ]
stackoverflow_0002723212_encoding_internationalization_python.txt
Q: index error:list out of range from string import Template from string import Formatter import pickle f=open("C:/begpython/text2.txt",'r') p='C:/begpython/text2.txt' f1=open("C:/begpython/text3.txt",'w') m=[] i=0 k='a' while k is not '': k=f.readline() mi=k.split(' ') m=m+[mi] i=i+1 print m[1] f1...
index error:list out of range
from string import Template from string import Formatter import pickle f=open("C:/begpython/text2.txt",'r') p='C:/begpython/text2.txt' f1=open("C:/begpython/text3.txt",'w') m=[] i=0 k='a' while k is not '': k=f.readline() mi=k.split(' ') m=m+[mi] i=i+1 print m[1] f1.write(str(m[3])) f1.write(str(m[4]...
[ "Suppose i is 10 then on the last run of the while loop j is 9, now you have l = j + 1 so l will be 10 but your 10 lines in m are indexed 0..9 so m[l][2] will give an index error.\nAlso, you code would look a lot better if you just added the elements to your list in one go i.e:\nx = x + [j, m[j][2], m[k][2], m[l][2...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002918243_python.txt
Q: Emailing smtp with Python error I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half...
Emailing smtp with Python error
I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes. import smtplib FROMADDR = ...
[ "It's likely that your school's SMTP server does not permit outside access to port 587. Gmail does, and requires authentication to ensure that you are who you say you are (and so that spammers can't send email appearing to be from you unless they know your password). Your school may have chosen to set up their mail...
[ 3 ]
[]
[]
[ "email", "python", "smtp" ]
stackoverflow_0002918282_email_python_smtp.txt
Q: XML - python prints extra lines from xml import xpath from xml.dom import minidom xmldata = minidom.parse('model.xml').documentElement for maks in xpath.Evaluate('/cacti/results/maks/text()', xmldata): print maks.nodeValue And I get result: 85603399.14 398673062.66 95785523.81 But I needed to be: 85603399.1...
XML - python prints extra lines
from xml import xpath from xml.dom import minidom xmldata = minidom.parse('model.xml').documentElement for maks in xpath.Evaluate('/cacti/results/maks/text()', xmldata): print maks.nodeValue And I get result: 85603399.14 398673062.66 95785523.81 But I needed to be: 85603399.14 NO SPACE 398673062.66 NO SPACE 957...
[ "Use:\nprint maks.nodeValue,\n\nThe comma at the end doesn't insert the extra newline.\n" ]
[ 3 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0002918316_minidom_python_xml.txt
Q: Reason for socket.error I am a complete newbie when it comes to python, and programming in general. I've been working on a little webapp for the past few weeks trying to improve my coding chops. A few days ago my laptop was stolen so I went out and got a new MacBook Pro. Thank God I had everything under subvers...
Reason for socket.error
I am a complete newbie when it comes to python, and programming in general. I've been working on a little webapp for the past few weeks trying to improve my coding chops. A few days ago my laptop was stolen so I went out and got a new MacBook Pro. Thank God I had everything under subversion control. The problem is ...
[ "Works fine for me, though it doesn't ever return anything. (Linux 2.6.32)\n" ]
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002916910_python_sockets.txt
Q: how do simple SQLAlchemy relationships work? I'm no database expert -- I just know the basics, really. I've picked up SQLAlchemy for a small project, and I'm using the declarative base configuration rather than the "normal" way. This way seems a lot simpler. However, while setting up my database schema, I realized...
how do simple SQLAlchemy relationships work?
I'm no database expert -- I just know the basics, really. I've picked up SQLAlchemy for a small project, and I'm using the declarative base configuration rather than the "normal" way. This way seems a lot simpler. However, while setting up my database schema, I realized I don't understand some database relationship con...
[ "Yes, you need user_id = Column(Integer, ForeignKey('users.id')) or user_id = Column(Integer, ForeignKey('users.id'), nullable=False) if it's mandatory. This is directly translated to FOREIGN KEY in underlying database schema, no magic.\nThe simple way to declare relationship is user = relationship(Users) in OpenID...
[ 46 ]
[]
[]
[ "database_design", "python", "sqlalchemy" ]
stackoverflow_0002917866_database_design_python_sqlalchemy.txt
Q: Making GUI applications on Linux/Windows. What languages/tools to use? My student group and I are trying to continue working on a project we worked on this semester over the summer to become a professional, deployable app. We originally did it in Adobe AIR but it seems now that the computers this program will be r...
Making GUI applications on Linux/Windows. What languages/tools to use?
My student group and I are trying to continue working on a project we worked on this semester over the summer to become a professional, deployable app. We originally did it in Adobe AIR but it seems now that the computers this program will be running on will be very slow, maybe 600mhz and 128-256mb ram so flash just is...
[ "I see answers pushing wx and gtk, so I can't avoid pushing Qt, my favorite!-) With a major corporation standing behind it (Nokia), two excellent sets of Python bindings (PyQt and PySide), support for Python 3, the superb Qt Designer, great Mac and mobile support too... it's seriously hard to beat...!-)\n", "The...
[ 4, 3, 1, 1 ]
[]
[]
[ "glade", "monodevelop", "open_source", "python", "user_interface" ]
stackoverflow_0002918445_glade_monodevelop_open_source_python_user_interface.txt
Q: problem with f.readline()? I am reading one line at a time from a file, but at the end of each line it adds a '\n'. Example: The file has: 094 234 hii but my input is: 094 234 hii\n I want to read line by line but I don't need to keep the newlines... My goal is to read a list from every line: I need ['094','234'...
problem with f.readline()?
I am reading one line at a time from a file, but at the end of each line it adds a '\n'. Example: The file has: 094 234 hii but my input is: 094 234 hii\n I want to read line by line but I don't need to keep the newlines... My goal is to read a list from every line: I need ['094','234','hii'], not ['094','234','hii\...
[ "\nIt's not that it adds a '\\n' so much as that there's really one there. Use line = line.rstrip() to get the line sans newline (or something similar to it depending on exactly what you need).\nDon't use the readline method for reading a file line by line. Just use for line in f:. Files already iterate over their ...
[ 7, 5, 4 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002918572_file_io_python.txt
Q: Use a foreign key mapping to get data from the other table using Python and SQLAlchemy Hmm, the title was harder to formulate than I thought. Basically, I've got these simple classes mapped to tables, using SQLAlchemy. I know they're missing a few items but those aren't essential for highlighting the problem. clas...
Use a foreign key mapping to get data from the other table using Python and SQLAlchemy
Hmm, the title was harder to formulate than I thought. Basically, I've got these simple classes mapped to tables, using SQLAlchemy. I know they're missing a few items but those aren't essential for highlighting the problem. class Customer(object): def __init__(self, uid, name, email): self.uid = uid ...
[ "First of all, if you do pass customer to the Order constructur, then at least use it.\nI suggest, use a default value, but still allow assigning to a customer on creation as below:\nclass Order(object):\n def __init__(self, item_id, item_name, customer=None):\n self.item_id = item_id\n self.item_n...
[ 5 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002918454_python_sqlalchemy.txt
Q: What host do I have to bind a listening socket to? I used python's socket module and tried to open a listening socket using import socket import sys def getServerSocket(host, port): for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSI...
What host do I have to bind a listening socket to?
I used python's socket module and tried to open a listening socket using import socket import sys def getServerSocket(host, port): for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = r ...
[ "Try 0.0.0.0. That's what's mostly used.\n", "The first problem is that your except blocks are swallowing errors with no reports being made. The second problem is that you are trying to bind to a specific interface, rather than INADDR_ANY. You are probably binding to \"localhost\" which will only accept connectio...
[ 8, 5, 2 ]
[]
[]
[ "network_programming", "networking", "python", "sockets" ]
stackoverflow_0002919068_network_programming_networking_python_sockets.txt
Q: stumped by WSGI module import errors I'm writing a bare bones Python wsgi application and am getting stumped by module import errors. I have a .py file in the current directory which initially failed to import. By adding sys.path.insert(0, '/Users/guhar/Sites/acom') the import of the module worked. But I now try a...
stumped by WSGI module import errors
I'm writing a bare bones Python wsgi application and am getting stumped by module import errors. I have a .py file in the current directory which initially failed to import. By adding sys.path.insert(0, '/Users/guhar/Sites/acom') the import of the module worked. But I now try and import a module that I had installed vi...
[ "Read:\nhttp://code.google.com/p/modwsgi/wiki/VirtualEnvironments\nYou cant simply add Python module directories containing .pth files into sys.path. You must use site.addsitedir() or use other options of mod_wsgi to have it use the virtual environment.\nI think though perhaps, given that it looks like you are usin...
[ 5, 1 ]
[]
[]
[ "mod_wsgi", "python", "wsgi" ]
stackoverflow_0002917972_mod_wsgi_python_wsgi.txt
Q: Load image from string Given a string containing jpeg image data, is it possible to load this directly in pygame? I've tried using StringIO but failed and I don't completely understand the 'file-like' object concept. Currently, as a workaround, I'm saving to disk and then loading an image the standard way: # image...
Load image from string
Given a string containing jpeg image data, is it possible to load this directly in pygame? I've tried using StringIO but failed and I don't completely understand the 'file-like' object concept. Currently, as a workaround, I'm saving to disk and then loading an image the standard way: # imagestring contains a jpeg f=op...
[ "fstr = cStringIO.StringIO(simage)\npygame.image.load(fstr, namehint=\"somethinguseful\")\n\n" ]
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002919236_pygame_python.txt
Q: Get client ip with python I'm a newbie in python. I want to write a simple web that prints the client ip on screen my http.conf Handler: AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On The cgi.escape(os.environ["REMOTE_ADDR"]) return this error: KeyError: 'REMOTE_ADDR' and I...
Get client ip with python
I'm a newbie in python. I want to write a simple web that prints the client ip on screen my http.conf Handler: AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On The cgi.escape(os.environ["REMOTE_ADDR"]) return this error: KeyError: 'REMOTE_ADDR' and I just get lost with the BaseHTT...
[ "In case you're concerned about scalability, this might be a bit faster:\nfrom mod_python import apache\nreq.get_remote_host(apache.REMOTE_NOLOOKUP)\n\n", "OK, I found the answer:\nfrom mod_python import apache\ndef client_ip(req):\n req.add_common_vars()\n return req.subprocess_env['REMOTE_ADDR']\n\nIt's w...
[ 7, 0 ]
[]
[]
[ "apache", "mod_python", "python", "webserver" ]
stackoverflow_0002919329_apache_mod_python_python_webserver.txt
Q: Writing a post search algorithm I'm trying to write a free text search algorithm for finding specific posts on a wall (similar kind of wall as Facebook uses). A user is suppose to be able to write some words in a search field and get hits on posts that contain the words; with the best match on top and then other p...
Writing a post search algorithm
I'm trying to write a free text search algorithm for finding specific posts on a wall (similar kind of wall as Facebook uses). A user is suppose to be able to write some words in a search field and get hits on posts that contain the words; with the best match on top and then other posts in decreasing order according to...
[ "Yes. There are many normalization methods you could use. This is a well-researched field!\nTake a look at the vector space model . TDF/IDF could be relevant to what you're doing. It's not strictly related to the method you're using but could give you some normalization leads.\nAlso note that comparing each post wi...
[ 1 ]
[]
[]
[ "full_text_search", "levenshtein_distance", "python" ]
stackoverflow_0002919528_full_text_search_levenshtein_distance_python.txt
Q: GWT on Python App Engine I have a python app engine code (matured backend) - and we are now planning to have a front end for that code. I was wondering whether it is possible to implement GWT as the front end. Even though Alex Martelli in this post [1] mentions it is not possible, a comment to that post suggests...
GWT on Python App Engine
I have a python app engine code (matured backend) - and we are now planning to have a front end for that code. I was wondering whether it is possible to implement GWT as the front end. Even though Alex Martelli in this post [1] mentions it is not possible, a comment to that post suggests that it is indeed possible us...
[ "I use GWT with Python quite a bit - the JSON interface works perfectly well. Your GWT front-end is still written in a java-like syntax, and you still need the Java toolchain to actually compile it down to HTML/Javascript, but it doesn't care what language the backend is written in.\nAs for how this is accomplishe...
[ 7 ]
[]
[]
[ "google_app_engine", "gwt", "json", "python", "rpc" ]
stackoverflow_0002919608_google_app_engine_gwt_json_python_rpc.txt
Q: Sending file over socket I'm have a problem sending data as a file from one end of a socket to the other. What's happening is that both the server and client are trying to read the file so the file never gets sent. I was wondering how to have the client block until the server's completed reading the file sent from...
Sending file over socket
I'm have a problem sending data as a file from one end of a socket to the other. What's happening is that both the server and client are trying to read the file so the file never gets sent. I was wondering how to have the client block until the server's completed reading the file sent from the client. I have this worki...
[ "It sounds like you have the client sending the file and then waiting for the server response, but if you don't give the server an indication that it has completely read the file, recv() on the server side will hang waiting for more data. You can call shutdown(SHUT_WR) on the client-side once the client is done se...
[ 3, 1, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002915030_python_sockets.txt
Q: Calling a non python program from python? I am currently struggling to call a non python program from a python script. I have a ~1000 files that when passed through this C++ program will generate ~1000 outputs. Each output file must have a distinct name. The command I wish to run is of the form: program_name -inpu...
Calling a non python program from python?
I am currently struggling to call a non python program from a python script. I have a ~1000 files that when passed through this C++ program will generate ~1000 outputs. Each output file must have a distinct name. The command I wish to run is of the form: program_name -input -output -o1 -o2 -o3 To date I have tried: im...
[ "You can use subprocess for that purpose:\nimport os\nimport subprocess\n\ncwd = os.getcwd()\n\nfor i in os.listdir(cwd):\n if i.endswith('.ttp'):\n o = i + \"-out\"\n p = subprocess.call([\"program_name\", \"-input\", i, \"-output\", o])\n\n" ]
[ 11 ]
[]
[]
[ "python", "system_calls" ]
stackoverflow_0002919783_python_system_calls.txt
Q: problem with lists? j=0 x=[] for j in range(9): x=x+ [j] this will output [1,2,3,4,5,6,7,8,9] i wanted it as ['1','2','3'... how can I get it? A: convert to string: >>> [str(i) for i in range(9)] ['0', '1', '2', '3', '4', '5', '6', '7', '8'] if you want your list to start with 1 just change your range func...
problem with lists?
j=0 x=[] for j in range(9): x=x+ [j] this will output [1,2,3,4,5,6,7,8,9] i wanted it as ['1','2','3'... how can I get it?
[ "convert to string:\n>>> [str(i) for i in range(9)]\n['0', '1', '2', '3', '4', '5', '6', '7', '8']\n\nif you want your list to start with 1 just change your range function:\n>>> [str(i) for i in range(1, 9)]\n['1', '2', '3', '4', '5', '6', '7', '8']\n\nAlso, you don't need to initialise loop variable (j=0 is not re...
[ 12, 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002919757_python.txt
Q: RW - Primary/Secondary DNS Address In Python I want to read the primary and secondary dns addresses from the system and want to change it to any user given address. Is this possible through some library. An alternative approach is that I read the /etc/resolv.conf and do the changes, which is what I've done. BTW t...
RW - Primary/Secondary DNS Address In Python
I want to read the primary and secondary dns addresses from the system and want to change it to any user given address. Is this possible through some library. An alternative approach is that I read the /etc/resolv.conf and do the changes, which is what I've done. BTW the current solution I have is for Ubuntu OS, and f...
[ "/etc/resolv.conf IS the authoritative source of DNS servers, so you better check there. \nA bit off-topic, but note that it's being overriden by DHCP, so if you need to add own DNS server, you have to edit /etc/dhcp3/dhclient.conf and add there something like:\nappend domain-name-servers <DNS-ip>;\n\nor\nprepend d...
[ 1 ]
[]
[]
[ "dns", "python", "ubuntu" ]
stackoverflow_0002919794_dns_python_ubuntu.txt
Q: Python urllib2 multiple try statement on urlopen() So, simply I want to be able to run a for across a list of URLs, if one fails then I want to continue on to try the next. I've tried using the following but sadly it throws and exception if the first URL doesn't work. servers = ('http://www.google.com', 'http://ww...
Python urllib2 multiple try statement on urlopen()
So, simply I want to be able to run a for across a list of URLs, if one fails then I want to continue on to try the next. I've tried using the following but sadly it throws and exception if the first URL doesn't work. servers = ('http://www.google.com', 'http://www.stackoverflow.com') for server in servers: try: ...
[ "servers = ('http://www.google.com', 'http://www.stackoverflow.com')\nfor server in servers:\n try:\n u = urllib2.urlopen(server)\n except urllib2.URLError:\n continue\n else:\n break\nelse:\n raise\n\nThis code breaks out of the loop if the url connection doesn't raise an error (el...
[ 0, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002917127_python_urllib2.txt
Q: Strange (atleast for me) behavior in Django template The following code snippet in a Django template (v 1.1) doesn't work. {{ item.vendors.all.0 }} ==> returns "Test" but the following code snippet, doesn't hide the paragraph! {% ifnotequal item.vendors.all.0 "Test" %} <p class="view_vendor">Vendor(s): {{item...
Strange (atleast for me) behavior in Django template
The following code snippet in a Django template (v 1.1) doesn't work. {{ item.vendors.all.0 }} ==> returns "Test" but the following code snippet, doesn't hide the paragraph! {% ifnotequal item.vendors.all.0 "Test" %} <p class="view_vendor">Vendor(s): {{item.vendors.all.0}} </p><br /> {% endifnotequal %} Any tips ...
[ "item.vendors.all.0 doesn't return \"Test\": It returns a vendor object, which gives \"Test\" when converted to a string. If you just compare the object with \"Test\", it will never be equal.\nTry converting the object to a string before comparing:\n{% ifnotequal item.vendors.all.0|stringformat:\"s\" \"Test\" %}\n\...
[ 6 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002920469_django_django_templates_python.txt
Q: Django, how to create form for add/edit object with m2m links? Good afternoon! There are three essences. Product, Option and ProductOption. Product has link many to many to Option through ProductOption. Prompt how to create please for Product'a the form of addition/editing with these options (not on administration...
Django, how to create form for add/edit object with m2m links?
Good afternoon! There are three essences. Product, Option and ProductOption. Product has link many to many to Option through ProductOption. Prompt how to create please for Product'a the form of addition/editing with these options (not on administration page)? If simply to output {{product.options}} - will be SelectBox ...
[ "This is my models.py.\nclass Section(models.Model):\n title = models.CharField(max_length=250)\n\n def __unicode__(self):\n return self.title\n\n class Meta:\n pass\n\n\nclass Option(models.Model):\n title = models.CharField(blank=True, null=True, max_length=250)\n section = models.Man...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0002911886_django_django_forms_django_templates_python.txt
Q: How do I slice a python string programmatically? Very simple question, hopefully. So, in Python you can split up strings using indices as follows: >>> a="abcdefg" >>> print a[2:4] cd but how do you do this if the indices are based on variables? E.g. >>> j=2 >>> h=4 >>> print a[j,h] Traceback (most recent call las...
How do I slice a python string programmatically?
Very simple question, hopefully. So, in Python you can split up strings using indices as follows: >>> a="abcdefg" >>> print a[2:4] cd but how do you do this if the indices are based on variables? E.g. >>> j=2 >>> h=4 >>> print a[j,h] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: string i...
[ "It works you just have a typo in there, use a[j:h] instead of a[j,h] :\n>>> a=\"abcdefg\"\n>>> print a[2:4]\ncd\n>>> j=2\n>>> h=4\n>>> print a[j:h]\ncd\n>>> \n\n", "In addition to Bakkal's answer, here is how to manipulate slices programmatically, which is sometimes convenient:\na = 'abcdefg'\nj=2;h=4\nmy_slice...
[ 12, 5 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002920551_python_string.txt
Q: related to list and file handling? I have file with contents in list form such as [1,'ab','fgf','ssd'] [2,'eb','ghf','hhsd'] [3,'ag','rtf','ssfdd'] I want to read that file line by line using f.readline and assign each line to a list. I tried doing this: k=[ ] k=f.readline() print k[1] I expected a result to sh...
related to list and file handling?
I have file with contents in list form such as [1,'ab','fgf','ssd'] [2,'eb','ghf','hhsd'] [3,'ag','rtf','ssfdd'] I want to read that file line by line using f.readline and assign each line to a list. I tried doing this: k=[ ] k=f.readline() print k[1] I expected a result to show 2nd element in the list in first line...
[ "If all you want is to take the input format shown and store it as a list attempting to execute the input file (with eval()) is not a good idea. This leaves your program open to all sorts of accidentally and intentionally harmful input. You are better advised to just parse the input file:\ns=f.readline()[1:-1]\nk =...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002919865_python.txt
Q: Converting human readable date into integer values I am looking to do something really simple. Merely convert a string, such as 'december' into something I can use with MySQL (such as '12'). At the moment I use a dict, month_map = { 'december': '12', 'november': '11', 'october': '10', 'september': ...
Converting human readable date into integer values
I am looking to do something really simple. Merely convert a string, such as 'december' into something I can use with MySQL (such as '12'). At the moment I use a dict, month_map = { 'december': '12', 'november': '11', 'october': '10', 'september': '09', 'august': '08', 'july': '07', 'june': ...
[ "It's locale-dependent, but you can accomplish this with strptime:\n>>> import datetime\n>>> datetime.datetime.strptime('december', '%B').month\n12\n>>> datetime.datetime.strptime('january', '%B').month\n1\n\n", "Python dateutil\n", "One thing you could do is:\n>>> datetime.datetime.strptime('december', '%B').m...
[ 2, 1, 1, 1 ]
[]
[]
[ "datetime", "mysql", "python" ]
stackoverflow_0002920888_datetime_mysql_python.txt
Q: summer experiment: GWT & python for a trading game- arch question As a summer learning experiment, I'm thinking of coding up a web front end for a trading game i wrote in python, that generates share prices and random snippets of text. I am sort of struggling with how this should work on the back-end though. I'd ...
summer experiment: GWT & python for a trading game- arch question
As a summer learning experiment, I'm thinking of coding up a web front end for a trading game i wrote in python, that generates share prices and random snippets of text. I am sort of struggling with how this should work on the back-end though. I'd rather have my GWT client page interact with the python share price gen...
[ "Make no mistake, GWT is a Java technology. You could perhaps interoperate by using Jython to compile your Python code but your UI will basically need to be written in Java (wrappers are second class citizens here). The reason is that the RPC protocol is proprietary and even though GWT is open I believe the compile...
[ 0, 0, 0 ]
[]
[]
[ "gwt", "java", "python" ]
stackoverflow_0002917735_gwt_java_python.txt
Q: Python: Copying files with special characters in path Is there a way in Python 2.5 to copy files which have special chars (Japanese chars, cyrillic letters) in their path? shutil.copy cannot handle this. here is some example code: import copy, os,shutil,sys fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt" ...
Python: Copying files with special characters in path
Is there a way in Python 2.5 to copy files which have special chars (Japanese chars, cyrillic letters) in their path? shutil.copy cannot handle this. here is some example code: import copy, os,shutil,sys fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt" print fname print "type of fname: "+str(type(fname)) fname0...
[ "Try passing unicode arguments to shutil.copy(). That is, shutil.copy( fname0, u'c:\\\\')\nhttp://docs.python.org/howto/unicode.html#unicode-filenames\nhttp://www.amk.ca/python/howto/unicode#unicode-filenames\nhttp://www.python.org/dev/peps/pep-0277/\n", "As a workaround, you could os.chdir to the unicode-named ...
[ 2, 0, 0 ]
[]
[]
[ "copy", "file", "python", "shutil" ]
stackoverflow_0002919205_copy_file_python_shutil.txt
Q: Django context processor gets AnonymousUser instead of User. def myview(request): return render_to_response('tmpl.html', {'user': User.objects.get(id=1}) works fine and passes User to template. But def myview(request): return render_to_response('tmpl.html', {}, context_instance=RequestContext(reques...
Django context processor gets AnonymousUser
instead of User. def myview(request): return render_to_response('tmpl.html', {'user': User.objects.get(id=1}) works fine and passes User to template. But def myview(request): return render_to_response('tmpl.html', {}, context_instance=RequestContext(request)) with a context processor def user(request): ...
[ "Are you sure that your context processor is enabled in TEMPLATE_CONTEXT_PROCESSORS in settings.py?\nMore to the point, does it come before or after the built-in django.contrib.auth.context_processors.auth? If it's before, it will be overridden by that processor, which will redefine user as the actual logged-in use...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002921386_django_python.txt
Q: Difference between list, sequence and slice in Python? What are the differences between these built-in Python data types: list, sequence and slice? As I see it, all three essentially represent what C++ and Java call array. A: You're mixing very different things in your question, so I'll just answer a different ...
Difference between list, sequence and slice in Python?
What are the differences between these built-in Python data types: list, sequence and slice? As I see it, all three essentially represent what C++ and Java call array.
[ "You're mixing very different things in your question, so I'll just answer a different question\nYou are now asking about one of the most important interface in Python: iterable - it's basically anything you can use like for elem in iterable.\niterable has three descendants: sequence, generator and mapping.\n\nA se...
[ 81, 17, 9, 9, 2 ]
[]
[]
[ "definition", "list", "python", "sequence", "slice" ]
stackoverflow_0002920619_definition_list_python_sequence_slice.txt
Q: Fast matrix transposition in Python Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).? Say, if I have an array X=[ [1,2,3], [4,5,6] ] I need an array Y which should be a transposed version of X, so Y=[ [1,4], [2,5], [3,6] ] A...
Fast matrix transposition in Python
Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).? Say, if I have an array X=[ [1,2,3], [4,5,6] ] I need an array Y which should be a transposed version of X, so Y=[ [1,4], [2,5], [3,6] ]
[ "Simple: Y=zip(*X)\n>>> X=[[1,2,3], [4,5,6]]\n>>> Y=zip(*X)\n>>> Y\n[(1, 4), (2, 5), (3, 6)]\n\nEDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:\n>>> range(3, 6) # normal call with separate arguments\n[3, 4, 5]\n>>> args = [3, 6]\n>>> range(*...
[ 20, 6, 5 ]
[]
[]
[ "algorithm", "matrix", "python" ]
stackoverflow_0002921681_algorithm_matrix_python.txt
Q: What is faster when looking in lists of strings? "In" or "index"? I have a bunch of lists of strings and I need to know if an string is in any of them so I have to look for the string in the first list, if not found, in the second, if not found, in the third... and so on. My question is: What is faster? if (string...
What is faster when looking in lists of strings? "In" or "index"?
I have a bunch of lists of strings and I need to know if an string is in any of them so I have to look for the string in the first list, if not found, in the second, if not found, in the third... and so on. My question is: What is faster? if (string in stringList1): return True else: if (string in stringList2):...
[ "\nin is the correct way to determine whether something is or is not in a container. Don't worry about speed microoptimization until you have tested your app, found it to be slow, profiled, and found what's causing it. At that point, optimize by testing (the timeit module can be good for this), not by taking the wo...
[ 12 ]
[]
[]
[ "list", "performance", "python", "search", "string" ]
stackoverflow_0002922072_list_performance_python_search_string.txt
Q: Simple numpy question I can't get this snippet to work: #base code A = array([ [ 1, 2, 10 ], [ 1, 3, 20 ], [ 1, 4, 30 ], [ 2, 1, 15 ], [ 2, 3, 25 ], [ 2, 4, 35 ], [ 3, 1, 17 ], [ 3, 2, 27 ], [ 3, 4, 37 ], [...
Simple numpy question
I can't get this snippet to work: #base code A = array([ [ 1, 2, 10 ], [ 1, 3, 20 ], [ 1, 4, 30 ], [ 2, 1, 15 ], [ 2, 3, 25 ], [ 2, 4, 35 ], [ 3, 1, 17 ], [ 3, 2, 27 ], [ 3, 4, 37 ], [ 4, 1, 13 ], [ ...
[ "I'm practicing my Psychic debugging...\nYour are missing parentheses in the last line:\nA_ik = A[(A[:,0] == origin) & (A[:,1] == destination), 2]\n\nshould work.\n", "Try replacing the logical AND operator & (which is a bitwise AND) by &&?\n" ]
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002922123_numpy_python.txt
Q: Program structure in long running data processing python script For my current job I am writing some long-running (think hours to days) scripts that do CPU intensive data-processing. The program flow is very simple - it proceeds into the main loop, completes the main loop, saves output and terminates: The basic ...
Program structure in long running data processing python script
For my current job I am writing some long-running (think hours to days) scripts that do CPU intensive data-processing. The program flow is very simple - it proceeds into the main loop, completes the main loop, saves output and terminates: The basic structure of my programs tends to be like so: <import statements> <co...
[ "First off, if your program is going to be running for hours/days then the overhead of switching to using classes/methods instead of putting everything in a giant main is pretty much non-existent. \nAdditionally, refactoring (even if it does involve passing a lot of variables) should help you improve speed in the l...
[ 2, 2, 1 ]
[]
[]
[ "language_agnostic", "maintainability", "python", "refactoring" ]
stackoverflow_0002921368_language_agnostic_maintainability_python_refactoring.txt
Q: php/Symfony View Component analog in python/Django Symfony has very useful feature - view component, this is small action code and template that you could embed anywhere inside view template: <?php include_component('news') ?> for example in above code mews component executes query in db and display results as bl...
php/Symfony View Component analog in python/Django
Symfony has very useful feature - view component, this is small action code and template that you could embed anywhere inside view template: <?php include_component('news') ?> for example in above code mews component executes query in db and display results as block on a site page. http://www.symfony-project.org/book...
[ "I think you're looking for Django's template tags feature. Template tags can make database calls, render partial templates, or do pretty much anything else you need them to do. Your example, as a template tag, might look something like this in your templates:\n{% include_component 'news' %}\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "symfony1" ]
stackoverflow_0002922145_django_python_symfony1.txt
Q: Framework Similar to Pylons for Ruby I've been using Python for most of my web projects lately, and have come to really love the Pylons MVC framework. I like the incredible transparency (lack of magic), the built-in components they selected (sqlalchemy, formencode, routes), and the ability to easily change things...
Framework Similar to Pylons for Ruby
I've been using Python for most of my web projects lately, and have come to really love the Pylons MVC framework. I like the incredible transparency (lack of magic), the built-in components they selected (sqlalchemy, formencode, routes), and the ability to easily change things up (use a different ORM or templating eng...
[ "I have no experience with pylons so its tough for me to compare, but if you are looking for a lightweight alternative to Rails, definitely check out Sinatra. However, keep in mind its not an MVC framework.\nRamaze is another alternative which is ORM and templating engine agnostic.\n", "Python is to Django as Rub...
[ 5, 0, 0 ]
[]
[]
[ "frameworks", "model_view_controller", "pylons", "python", "ruby" ]
stackoverflow_0002916693_frameworks_model_view_controller_pylons_python_ruby.txt
Q: How to make form validation in Django dynamic? I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form. Basically, when a user wants to create a new domain, this form should fail if the entered domain exists. When a user wants t...
How to make form validation in Django dynamic?
I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form. Basically, when a user wants to create a new domain, this form should fail if the entered domain exists. When a user wants to move a domain, this form should fail if the entere...
[ "Overriding the __init__ is the way to go. In that method, you can simply set your value to an instance variable.\ndef __init__(self, *args, **kwargs):\n self.myvalue = kwargs.pop('myvalue')\n super(MyForm, self).__init__(*args, **kwargs)\n\nNow self.myvalue is available in any form method.\n", "Do you have...
[ 1, 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0002922230_django_forms_python.txt
Q: Execute a BASH command in Python-- in the same process I need to execute the command . /home/db2v95/sqllib/db2profile before I can import ibm_db_dbi in Python 2.6. Executing it before I enter Python works: baldurb@gigur:~$ . /home/db2v95/sqllib/db2profile baldurb@gigur:~$ python Python 2.6.4 (r264:75706, Dec 7 20...
Execute a BASH command in Python-- in the same process
I need to execute the command . /home/db2v95/sqllib/db2profile before I can import ibm_db_dbi in Python 2.6. Executing it before I enter Python works: baldurb@gigur:~$ . /home/db2v95/sqllib/db2profile baldurb@gigur:~$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright...
[ "You are calling a '.' shell command. This command means 'execute this shell file in current process'. You cannot execute shell file in Python process as Python is not a shell script interpreter.\nThe /home/b2v95/sqllib/db2profile probably sets some shell environment variables. If you read it using system() functio...
[ 10, 0 ]
[ "Maybe os.popen is what you're looking for (better yet, one of the popen[2-4] variants)? Example:\nimport os\np = os.popen(\". /home/b2v95/sqllib/db2profile\")\np.close() # this will wait for the command to finish\nimport ibm_db_dbi\n\n\nEdit: I see that your error says No such file or directory. Try running it wit...
[ -1, -1 ]
[ "bash", "db2", "python", "subprocess" ]
stackoverflow_0002858920_bash_db2_python_subprocess.txt
Q: Python : Convert from C-Char to Int I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n. Each byte in the string is a single integer (1-byte) representing 0-255. So for each character in the string I want to convert it to an integer. I can't figure out how to do...
Python : Convert from C-Char to Int
I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n. Each byte in the string is a single integer (1-byte) representing 0-255. So for each character in the string I want to convert it to an integer. I can't figure out how to do this. Using ord doesn't seem to be on t...
[ ">>> import struct\n>>> a = struct.pack(\"ccc\", \"a\", \"b\", \"c\")\n>>> a\nb'abc'\n>>> b = struct.unpack(\"ccc\", a)\n>>> b\n(b'a', b'b', b'c')\n>>> ord(b[0])\n97\n>>> c = struct.pack(\"BBB\", 1, 2, 3)\n>>> c\nb'\\x01\\x02\\x03'\n>>> d = struct.unpack(\"BBB\", c)\n>>> d\n(1, 2, 3)\n\nWorks for me.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002922461_python.txt