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: Passing dictionaries to a Python script through the command line How can I pass a dictionary to a python script from another python script over the command line? I use subprocess to call the second script. The options I've come to are: I) Build a module to parse a dictionary from a string (more in-depth than I h...
Passing dictionaries to a Python script through the command line
How can I pass a dictionary to a python script from another python script over the command line? I use subprocess to call the second script. The options I've come to are: I) Build a module to parse a dictionary from a string (more in-depth than I had hoped to go). II) Use a temporary file to write a pickle, and pass ...
[ "Have you looked at the pickle module to pass the data over stdout/stdin? \nExample:\nknights.py:\nimport pickle\nimport sys\n\ndesires = {'say': 'ni', 'obtain': 'shrubbery'}\npickle.dump(desires, sys.stdout)\n\nroundtable.py:\nimport pickle\nimport sys\n\nknightsRequest = pickle.load(sys.stdin)\nfor req in knights...
[ 9, 6, 6, 2, 0, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0003780468_command_line_python.txt
Q: Integrating a script language into a C++ application I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations. I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python. I'm not looking for something like...
Integrating a script language into a C++ application
I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations. I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python. I'm not looking for something like Boost.Python / swig, something that is able to wrap my c+...
[ "The Python documentation has a page on embedding Python in a C or C++ application.\n", "Why not use Boost.Python? You can expose your data classes to Python and execute a script/function as described here.\n", "If you want to simply run Python scripts from C/C++, then use the Python C API. In your C/C++ code:...
[ 8, 8, 6, 2, 1, 1, 1, 1, 1 ]
[]
[]
[ "c++", "embedding", "python", "scripting" ]
stackoverflow_0003780398_c++_embedding_python_scripting.txt
Q: Creating lists using yield in Ruby and Python I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby. In Python: def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) In Ruby: def foo(x) x.times {|i| yield i if bar...
Creating lists using yield in Ruby and Python
I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby. In Python: def foo(x): for i in range(x): if bar(i): yield i result = list(foo(100)) In Ruby: def foo(x) x.times {|i| yield i if bar(i)} end result = [] foo(100) {|x| result << x} Al...
[ "So, for your new example, try this:\ndef foo(x)\n (0..x).select { |i| bar(i) }\nend\n\nBasically, unless you're writing an iterator of your own, you don't need yield very often in Ruby. You'll probably do a lot better if you stop trying to write Python idioms using Ruby syntax.\n", "For the Python version I wo...
[ 10, 7, 5, 1, 1, 1, 1 ]
[]
[]
[ "list", "python", "ruby", "yield" ]
stackoverflow_0000608951_list_python_ruby_yield.txt
Q: How can I replace the class by monkey patching? How can I replace the ORM class - so it should not cause recursion !!! Problem: original class has the super call, when its got replaced - it causes self inheritance and causes maximum recursion depth exceed exception. i.e. class orm is calling super(orm, self).... a...
How can I replace the class by monkey patching?
How can I replace the ORM class - so it should not cause recursion !!! Problem: original class has the super call, when its got replaced - it causes self inheritance and causes maximum recursion depth exceed exception. i.e. class orm is calling super(orm, self).... and orm has been replaced by another class which inher...
[ "Your addons/test.py needs to get and keep a reference to the original orm.orm and use that instead of the replaced version. I.e.:\nfrom osv import orm\nimport osv\noriginal_orm = osv.orm\nclass orm(original_orm):\n def __init__(self, *args, **kw):\n super(orm, self).__init__(*args, **kw) \n def fi...
[ 5 ]
[]
[]
[ "class", "monkeypatching", "python" ]
stackoverflow_0003781280_class_monkeypatching_python.txt
Q: Sort distributed couples from two lists Having two lists, I want to get all the possible couples. (a couple can be only one element from list 1 and another from list 2) If I do a double "foreach" statement, I get it immediately (I am using python): couples = [] for e1 in list_1: for e2 in list_2: coupl...
Sort distributed couples from two lists
Having two lists, I want to get all the possible couples. (a couple can be only one element from list 1 and another from list 2) If I do a double "foreach" statement, I get it immediately (I am using python): couples = [] for e1 in list_1: for e2 in list_2: couples.append([l1, l2]) How can I sort couples l...
[ "You should check out itertools.product() from the stdlib.\nEdit: I meant product(), not permutations().\nimport itertools\n\nlist_1 = ['a','b','c']\nlist_2 = [1,2]\n\n# To pair list_1 with list_2 \npaired = list(itertools.product(list_1, list_2))\n# => [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)]\n...
[ 3, 3, 0, 0 ]
[]
[]
[ "algorithm", "python", "sorting" ]
stackoverflow_0003781342_algorithm_python_sorting.txt
Q: Are my permissions set correctly? (python) In python I'm doing a os.system('chmod o+w filename.png') command so I can overwrite the file with pngcrush. These are the permissions after I set them in python: -rw-rw-rw- 1 me users 925 Sep 20 11:25 filename.png Then I attempt: os.system('pngcrush filename.png filenam...
Are my permissions set correctly? (python)
In python I'm doing a os.system('chmod o+w filename.png') command so I can overwrite the file with pngcrush. These are the permissions after I set them in python: -rw-rw-rw- 1 me users 925 Sep 20 11:25 filename.png Then I attempt: os.system('pngcrush filename.png filename.png') which is supposed to overwrite the file...
[ "The problem is with the way you execute the pngcrush program, not with permissions of filename.png or Python. It simply attempts to open filename.png both for input and output, which is of course invalid.\nGive pngcrush either the -e or the -d option to tell it how to write output. Read its man for more informatio...
[ 3, 2, 2, 0 ]
[]
[]
[ "file_permissions", "python" ]
stackoverflow_0003781302_file_permissions_python.txt
Q: why python doesn't need type declaration for python, other way what are the adv. of not declaring type? If we know the type of variable or parameter very well, why not to declare them? I'd like to know why it's bad or not necessary. Sorry, I'm new on Python (from about 1 year) and before I was on C, VB, VB.NET and...
why python doesn't need type declaration for python, other way what are the adv. of not declaring type?
If we know the type of variable or parameter very well, why not to declare them? I'd like to know why it's bad or not necessary. Sorry, I'm new on Python (from about 1 year) and before I was on C, VB, VB.NET and C# programming languages. With Python, I hope to have bad parameter types to be catched at compilation tim...
[ "I'm sure you know the + function. So, what is it's type? Numbers? Well, it works for lists and strings too. It even works for every object that defines __add__. Or in some cases when one object defines __radd__. \nSo it's hard to tell the type of this function already. But Python makes it even possible to define t...
[ 10, 4, 3, 2 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0003781454_programming_languages_python.txt
Q: How to create new list of dicts in python by consolidating dicts in another list? In Python, I have a list of dicts as follows: orig_list = [ {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'Team...
How to create new list of dicts in python by consolidating dicts in another list?
In Python, I have a list of dicts as follows: orig_list = [ {'first_name': u'Jake', 'last_name': u'Sarson', 'team': u'TeamOne', 'display_name': u'AVG', 'value': 7.0}, {'first_name': u'Mike', 'last_name': u'Walsh', 'team': u'TeamTwo', 'display_name': u'AVG', 'value': 12.0}, {'first_name': u'Jake', 'last_name': u...
[ "temp = {}\nfor rec in orig_list:\n temp.setdefault((rec['first_name'], rec['last_name'], rec['team']), {}).setdefault(rec['display_name'], rec['value'])\n\npersons = []\nfor key, person in temp.iteritems():\n person.update(dict(zip(('first_name', 'last_name', 'team'), key)))\n persons.append(person)\n\n",...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003770022_python.txt
Q: sqlalchemy REST serialization Reading the doc of sqlalchemy, i saw the serialization part. I'm wondering about a possibility to use an xml serializer for matching sa models with Rest webservices like Jax-RS There is a django extension which deal with that : django_roa Do you know if that kind of thing has already ...
sqlalchemy REST serialization
Reading the doc of sqlalchemy, i saw the serialization part. I'm wondering about a possibility to use an xml serializer for matching sa models with Rest webservices like Jax-RS There is a django extension which deal with that : django_roa Do you know if that kind of thing has already been developped for sqlalchemy or i...
[ "Its a long way till full RFC2616 compliance, but for a prototype, I do something like this:\nfrom sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, UniqueConstraint\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relation, backref, sessionmaker\nfrom ...
[ 2, 1 ]
[]
[]
[ "python", "rest", "sqlalchemy", "xml_serialization" ]
stackoverflow_0001740817_python_rest_sqlalchemy_xml_serialization.txt
Q: python+win32: detect window drag Is there a way to detect when a window that doesn't belong to my application is being dragged in windows using python/pywin32? I want to set it up so that when I drag a window whose title matches a pattern near the desktop edge, it snaps to the edge when the mouse is let go. I coul...
python+win32: detect window drag
Is there a way to detect when a window that doesn't belong to my application is being dragged in windows using python/pywin32? I want to set it up so that when I drag a window whose title matches a pattern near the desktop edge, it snaps to the edge when the mouse is let go. I could write code to snap all windows with ...
[ "So far the only possible solution I see is to use SetWindowsHookEx. Pywin32 doesn't interface this, so I think I'll have to do something like this:\n\nWrite a C extension module. It has a function like setCallback which takes a python function to be called when the drag event happens. \nWrite a C DLL that contains...
[ 2, 2 ]
[]
[]
[ "python", "pywin32", "winapi", "windows" ]
stackoverflow_0003753612_python_pywin32_winapi_windows.txt
Q: Properties in Python whats the reason to use the variable the self._age? A similar name that doesn't link to the already used self.age? class newprops(object): def getage(self): return 40 def setage(self, value): self._age = value age = property(getage, setage, None, None) A: self.ag...
Properties in Python
whats the reason to use the variable the self._age? A similar name that doesn't link to the already used self.age? class newprops(object): def getage(self): return 40 def setage(self, value): self._age = value age = property(getage, setage, None, None)
[ "self.age is already occupied by the property, you need to give another name to the actual variable, which is _age here.\nBTW, since Python 2.6, you could write this with decorators:\ndef newprops(object):\n\n @property\n def age(self):\n return 40\n\n @age.setter\n def age(self, value):\n ...
[ 12, 7, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003781834_python.txt
Q: pywin32 captive installation (avoid py*.dll getting installed in system32 directory) I have python as an embedded scripting environment in my application. I supply the python bits (python26.dll, DLLs & Lib folders) with my application. All this to avoid asking users to install python (you know how it goes in big c...
pywin32 captive installation (avoid py*.dll getting installed in system32 directory)
I have python as an embedded scripting environment in my application. I supply the python bits (python26.dll, DLLs & Lib folders) with my application. All this to avoid asking users to install python (you know how it goes in big corporations). All works nice except pywin32. It installs pythoncom26.dll and pywintypes26....
[ "I previously used py2exe to freeze the application and all the DLLs. Then use Innosetup to create an installer. Work like a charm.\n" ]
[ 0 ]
[]
[]
[ "python", "python_embedding", "pywin32" ]
stackoverflow_0003781873_python_python_embedding_pywin32.txt
Q: Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class (the decorator will access cl...
Python decorators that are part of a base class cannot be used to decorate member functions in inherited classes
Python decorators are fun to use, but I appear to have hit a wall due to the way arguments are passed to decorators. Here I have a decorator defined as part of a base class (the decorator will access class members hence it will require the self parameter). class SubSystem(object): def UpdateGUI(self, fun): #functio...
[ "You need to make UpdateGUI a @classmethod, and make your wrapper aware of self. A working example:\nclass X(object):\n @classmethod\n def foo(cls, fun):\n def wrapper(self, *args, **kwargs):\n self.write(*args, **kwargs)\n return fun(self, *args, **kwargs)\n return wrapper...
[ 28, 3, 3, 2 ]
[]
[]
[ "decorator", "inheritance", "ironpython", "python" ]
stackoverflow_0003782040_decorator_inheritance_ironpython_python.txt
Q: Python Sort Two Dimensional Dictionary By First Key I have a 2D dictionary in python indexed by two IPs. I want to group the dictionary by the first key. For example, the before would look like this: myDict["182.12.17.50"]["175.12.13.14"] = 14 myDict["182.15.12.30"]["175.12.13.15"] = 10 myDict["182.12.17.50"]["185...
Python Sort Two Dimensional Dictionary By First Key
I have a 2D dictionary in python indexed by two IPs. I want to group the dictionary by the first key. For example, the before would look like this: myDict["182.12.17.50"]["175.12.13.14"] = 14 myDict["182.15.12.30"]["175.12.13.15"] = 10 myDict["182.12.17.50"]["185.23.15.69"] = 30 myDict["182.15.12.30"]["145.33.34.56"] =...
[ "Well, there are a variety of options. One of them would be to sort the keys before printing, something like this:\nfor key1 in sorted(myDict):\n for key2 in myDict[key1]:\n print key1 +\" \" +key2 +\" \" +myDict[key1][key2]\n\nAnother option would be to use the sorteddict class from the blist module...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0003781527_dictionary_python_sorting.txt
Q: How do I get the request parameters from urls.py? Hi I have an application that works fine when I type the url from the browser. it works something like http://mysite/service?id=1234, if I type that on the browser it works fine, however we have another service that accepts parameters from a mobile phone, this serv...
How do I get the request parameters from urls.py?
Hi I have an application that works fine when I type the url from the browser. it works something like http://mysite/service?id=1234, if I type that on the browser it works fine, however we have another service that accepts parameters from a mobile phone, this service would then call the same url, and post the paramete...
[ "When you say post, do you mean post, or are you using this crucial, extremely specific verb randomly? Because if the request is indeed a post, there will most likely be no ?id=1234 as part of the URL -- the parameters will instead go in the body of the post; the query-string part of the URL is normally used only ...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003775365_django_python.txt
Q: wxPython GUI BoxSizers Ok I have an application I am coding and am trying to get a layout simpler to this: Notice how the text is left justified and the input boxes are all aligned, I see this in the wxPython demo code, but they all use the flexgrid sizer and I am trying to only use BoxSizers (due to them being s...
wxPython GUI BoxSizers
Ok I have an application I am coding and am trying to get a layout simpler to this: Notice how the text is left justified and the input boxes are all aligned, I see this in the wxPython demo code, but they all use the flexgrid sizer and I am trying to only use BoxSizers (due to them being simpler and because I only un...
[ "Here's a simple example using just BoxSizers:\nimport wx\n\nclass MyForm(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, wx.ID_ANY, \"Tutorial\")\n\n # Add a panel so it looks the correct on all platforms\n panel = wx.Panel(self, wx.ID_ANY)\n\n # create the labels\...
[ 3, 1 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003775071_python_user_interface_wxpython.txt
Q: Python: interact with complex data warehouse We've worked hard to work up a full dimensional database model of our problem, and now it's time to start coding. Our previous projects have used hand-crafted queries constructed by string manipulation. Is there any best/standard practice for interfacing between python ...
Python: interact with complex data warehouse
We've worked hard to work up a full dimensional database model of our problem, and now it's time to start coding. Our previous projects have used hand-crafted queries constructed by string manipulation. Is there any best/standard practice for interfacing between python and a complex database layout? I've briefly evalua...
[ "Don't get confused by your requirements. One size does not fit all.\n\nload large amounts of data relatively quickly\n\nWhy not use the databases's native loaders for this? Use Python to prepare files, but use database tools to load. You'll find that this is amazingly fast. \n\nupdate/insert small amounts of d...
[ 6, 3, 2 ]
[]
[]
[ "data_warehouse", "django_models", "olap", "python", "sqlalchemy" ]
stackoverflow_0003782386_data_warehouse_django_models_olap_python_sqlalchemy.txt
Q: Character encoding is violated I am trying to parse a file encoded in utf-8. No operation has problem apart from write to file (or at least I think so). A minimum working example follows: from lxml import etree parser = etree.HTMLParser() tree = etree.parse('example.txt', parser) tree.write('aaaaaaaaaaaaaaaaa.html...
Character encoding is violated
I am trying to parse a file encoded in utf-8. No operation has problem apart from write to file (or at least I think so). A minimum working example follows: from lxml import etree parser = etree.HTMLParser() tree = etree.parse('example.txt', parser) tree.write('aaaaaaaaaaaaaaaaa.html') example.txt: <html> <body> ...
[ "The obvious problem is that HTMLParser treats the input file as ANSI by default, i.e. the UTF-8 bytes are misinterpreted as 8-bit character codes. You can simply pass the encoding to fix this:\nparser = etree.HTMLParser(encoding = \"utf-8\")\n\nIf you want to check what I meant with the misinterpretation, let Pyth...
[ 1 ]
[]
[]
[ "encoding", "lxml", "python" ]
stackoverflow_0003780829_encoding_lxml_python.txt
Q: Can not get the Auth Token for GData After Authentication on App Engine I would like to pull the Auth Token for the Gdata auth so that I can write to a google calendar. I am having issues getting the token after authentication so that I can send the token to the calendar service. I am using the default login scree...
Can not get the Auth Token for GData After Authentication on App Engine
I would like to pull the Auth Token for the Gdata auth so that I can write to a google calendar. I am having issues getting the token after authentication so that I can send the token to the calendar service. I am using the default login screen provided by appengine (/_ah/login) and I am able to login and authenticate,...
[ "The login screen only authenticates the user to your application, it does not give you authorization to the user's gdata. \nYou will need to have the user authorize your use of the calendar api - I suggest through oauth here: http://code.google.com/apis/gdata/docs/auth/overview.html#OAuth. \nYou only need to do ...
[ 3, 0 ]
[]
[]
[ "gdata", "gdata_api", "google_app_engine", "google_data_api", "python" ]
stackoverflow_0002100699_gdata_gdata_api_google_app_engine_google_data_api_python.txt
Q: Django Form validation including the use of session data The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process. In order to achieve this, I have a Django Form to capture the user's general information which POSTS...
Django Form validation including the use of session data
The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process. In order to achieve this, I have a Django Form to capture the user's general information which POSTS to Django view 'A'. The Form is displayed using a template wh...
[ "You could override the __init__ method for your form so that it takes request as an argument.\nclass MyForm(forms.Form):\n def __init__(self, request, *args, **kwargs)\n self.request = request\n super(MyForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n if not self.request.sess...
[ 13, 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003778148_django_django_forms_python.txt
Q: How do I stop 'print' from outputting to the browser with Google App Engine? I'm new to GAE, and have not been able to figure out how to configure 'print' statements to the logging console rather than the browser. For example: class Feed(webapp.RequestHandler): def post(self): feeditem = Feeditem() ...
How do I stop 'print' from outputting to the browser with Google App Engine?
I'm new to GAE, and have not been able to figure out how to configure 'print' statements to the logging console rather than the browser. For example: class Feed(webapp.RequestHandler): def post(self): feeditem = Feeditem() feeditem.author = self.request.get('from') feeditem.content = self.re...
[ "You should instead use the logging module, like so:\nimport logging\ndef notify_friends(feeditem):\n \"\"\"Alerts friends of a new feeditem\"\"\" \n logging.info('Feeditem = %s', feeditem)\n\nThere are a variety of logging levels you can use, from debug to critical. By default, though, the App Engine SDK...
[ 3, 2 ]
[]
[]
[ "debugging", "logging", "python" ]
stackoverflow_0003782966_debugging_logging_python.txt
Q: Basic GUI for Python? Possible Duplicate: Practical GUI toolkit? Hi, I'm just getting my head around Python, and have been building some stuff from tutorials, examples, etc. As my programs are getting more complex after a few weeks' tinkering, I'm getting overwhelmed by the pile of data my console is serving me ...
Basic GUI for Python?
Possible Duplicate: Practical GUI toolkit? Hi, I'm just getting my head around Python, and have been building some stuff from tutorials, examples, etc. As my programs are getting more complex after a few weeks' tinkering, I'm getting overwhelmed by the pile of data my console is serving me (working on an app with lo...
[ "If you are working with scientifical data you should check Traits and Traits UI\n\nThe Traits UI package is a set of user\n interface tools designed to complement\n Traits. In the simplest case, it can\n automatically generate a user\n interface for editing a Traits-based\n object, with no additional coding o...
[ 0, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0003782832_python_user_interface.txt
Q: Why does python gstreamer crash without "gobject.threads_init()" at the top of my script? I have written a python script to use gstreamer (pygst and gst modules) to calculate replaygain tags, and it was crashing inconsistently with various gobject errors. I found somewhere that you could fix this by putting the fo...
Why does python gstreamer crash without "gobject.threads_init()" at the top of my script?
I have written a python script to use gstreamer (pygst and gst modules) to calculate replaygain tags, and it was crashing inconsistently with various gobject errors. I found somewhere that you could fix this by putting the following boilerplate at the top of your script: import gobject gobject.threads_init() I tried i...
[ "Because, you can use gobject in a non threading environment. This is not unusual.\nWhen you use gobject in a threading environment, you need to explicitly initialize by calling gobject.threads_init(). This will also ensure that the when \"C\" functions are called, the GIL is freed.\n\nPython, Threads, the GIL, and...
[ 14 ]
[]
[]
[ "gobject", "gstreamer", "python", "thread_safety" ]
stackoverflow_0003782962_gobject_gstreamer_python_thread_safety.txt
Q: Calling a Java program from a CGI script fails I have a Python CGI script from which I am trying to call a Java program to perform a task. The Java program uses JExcelAPI. When I run the Python script from the browser, it fails with error messages that it can't find the class definitions for the classes from JExce...
Calling a Java program from a CGI script fails
I have a Python CGI script from which I am trying to call a Java program to perform a task. The Java program uses JExcelAPI. When I run the Python script from the browser, it fails with error messages that it can't find the class definitions for the classes from JExcelAPI. I suppose this happens because the Python CGI ...
[ "Several solutions come to mind :\n\nCreate a bash script which calls the java program. You can set all the variables you like and debug on the commandline, e.g. sudo -u apache /usr/local/bin/java-task-wrapper. This simplifies calling it from a cgi considerably and the overhead of bash is negligeable compared to sp...
[ 2 ]
[]
[]
[ "apache", "cgi", "java", "linux", "python" ]
stackoverflow_0003783121_apache_cgi_java_linux_python.txt
Q: Parameter names in Python functions that take single object or iterable I have some functions in my code that accept either an object or an iterable of objects as input. I was taught to use meaningful names for everything, but I am not sure how to comply here. What should I call a parameter that can a sinlge objec...
Parameter names in Python functions that take single object or iterable
I have some functions in my code that accept either an object or an iterable of objects as input. I was taught to use meaningful names for everything, but I am not sure how to comply here. What should I call a parameter that can a sinlge object or an iterable of objects? I have come up with two ideas, but I don't like ...
[ "\nI have some functions in my code that accept either an object or an iterable of objects as input.\n\nThis is a very exceptional and often very bad thing to do. It's trivially avoidable.\ni.e., pass [foo] instead of foo when calling this function.\nThe only time you can justify doing this is when (1) you have an...
[ 7, 4, 3, 2, 1, 1, 1, 0 ]
[ "I'm working on a fairly big project now and we're passing maps around and just calling our parameter map. The map contents vary depending on the function that's being called. This probably isn't the best situation, but we reuse a lot of the same code on the maps, so copying and pasting is easier.\nI would say inst...
[ -1 ]
[ "naming_conventions", "python" ]
stackoverflow_0003683116_naming_conventions_python.txt
Q: How do I make a Python script (installed as a service) survive a logout? I followed the instructions in this answer about writing a Python script to be used as a service. I placed my looping code in def main(). I installed the service with python my_script.py install. I was able to Start and Stop the service throu...
How do I make a Python script (installed as a service) survive a logout?
I followed the instructions in this answer about writing a Python script to be used as a service. I placed my looping code in def main(). I installed the service with python my_script.py install. I was able to Start and Stop the service through services.msc in Windows XP. It's a logging program that is intended to writ...
[ "The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination. To ensure that you detach your service from all this, you will need to use the contro...
[ 2 ]
[]
[]
[ "logout", "python", "service", "windows_xp" ]
stackoverflow_0003783269_logout_python_service_windows_xp.txt
Q: How to submit web forms using Python? First of all, sorry if this question is a little vague and rambling! I'm ok with Python, but I've never done anything HTTP related before. I'm trying to automate submitting a web form, and from reading some of this page I understand that I need to do a POST request. I also fou...
How to submit web forms using Python?
First of all, sorry if this question is a little vague and rambling! I'm ok with Python, but I've never done anything HTTP related before. I'm trying to automate submitting a web form, and from reading some of this page I understand that I need to do a POST request. I also found a code snippet demonstrating the urllib ...
[ "The code there should do what you want.\nWhatever data you want to use should go into the params as you have in your example. When the params are included as an argument to urlopen a POST request will be used (instead of a GET).\nBy just calling urlopen I believe the POST request will be submitted. If you want the...
[ 0 ]
[]
[]
[ "form_submit", "python", "webforms" ]
stackoverflow_0003783260_form_submit_python_webforms.txt
Q: What is the fastest way to read in a large data file of text columns? I have a data file of almost 9 million lines (soon to be more than 500 million lines) and I'm looking for the fastest way to read it in. The five aligned columns are padded and separated by spaces, so I know where on each line to look for the tw...
What is the fastest way to read in a large data file of text columns?
I have a data file of almost 9 million lines (soon to be more than 500 million lines) and I'm looking for the fastest way to read it in. The five aligned columns are padded and separated by spaces, so I know where on each line to look for the two fields that I want. My Python routine takes 45 secs: import sys,time sta...
[ "Some points:\n\nYour C routine is cheating; it is being tipped off with the filesize, and is pre-allocating ...\nPython: consider using array.array('d') ... one each for S and nu. Then try pre-allocation.\nPython: write your routine as a function and call it -- accessing function-local variables is rather faster t...
[ 4, 3, 3, 1 ]
[ "Another possible speed-up, given the number of times you need to do it, is to use pointers to S and nu instead of indexing into arrays, e.g.,\ndouble *pS = S, *pnu = nu;\n...\n*pS++ = atof(sp);\n*pnu = atof(sp);\n...\n\nAlso, since you are always converting from char to double at the same locations in buf, pre-com...
[ -1 ]
[ "c", "dataset", "io", "python" ]
stackoverflow_0003779073_c_dataset_io_python.txt
Q: How do I use Avro to process a stream that I cannot seek? I am using Avro 1.4.0 to read some data out of S3 via the Python avro bindings and the boto S3 library. When I open an avro.datafile.DataFileReader on the file like objects returned by boto it immediately fails when it tries to seek(). For now I am working ...
How do I use Avro to process a stream that I cannot seek?
I am using Avro 1.4.0 to read some data out of S3 via the Python avro bindings and the boto S3 library. When I open an avro.datafile.DataFileReader on the file like objects returned by boto it immediately fails when it tries to seek(). For now I am working around this by reading the S3 objects into temporary files. I ...
[ "I am not very clear on this and this may not be the answer.\nI was of the impression that \nditer = datafile.DataFileReader(..) \n\nreturns an iterator so that you could do the following\nfor data in diter:\n ....\n\nCorrect me, if I am wrong here.\nRevisiting my answer:\nYou are right, datafile.DataFileReader ...
[ 2 ]
[]
[]
[ "avro", "boto", "hadoop", "python" ]
stackoverflow_0003783453_avro_boto_hadoop_python.txt
Q: 'else' statement in list comprehensions I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list. Essentially, I want to transform the following into a list comprehension. variable = 'id' final = [] if isinstance(variable, str): final.append...
'else' statement in list comprehensions
I've got a variable that could either be a string or a tuple (I don't know ahead of time) and I need to work with it as a list. Essentially, I want to transform the following into a list comprehension. variable = 'id' final = [] if isinstance(variable, str): final.append(variable) elif isinstance(variable, tuple): ...
[ "I think you want:\nfinal = [variable] if isinstance(variable, str) else list(variable)\n\n", "You just need to rearrange it a bit.\nfinal = [var if isinstance(variable, tuple) else variable for var in variable]\n\nOr maybe I misunderstood and you really want\nfinal = variable if not isinstance(variable, tuple) e...
[ 5, 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003783579_list_comprehension_python.txt
Q: Selecting a Python Web Framework This may seem like a subjective question. But it is not (that's not the idea, at least). I'm developing an Advertising software (like AdWords, AdBrite, etc) and i've decide to use Python. And would like to use one of those well known web frameworks (Django, Cherrypy, pylons, etc). ...
Selecting a Python Web Framework
This may seem like a subjective question. But it is not (that's not the idea, at least). I'm developing an Advertising software (like AdWords, AdBrite, etc) and i've decide to use Python. And would like to use one of those well known web frameworks (Django, Cherrypy, pylons, etc). The question is: Given that it will ha...
[ "check out Flask. Its easy, its fast, works on top of Werkzeug, uses Jinja2 templating and SQLAlchemy for the model domain. http://flask.pocoo.org/\n", "Performance should be more or less equal. If you want to keep it simple look at cherrypy, pylons and other lightweight frameworks.\n-> http://wiki.python.org/moi...
[ 7, 2, 1, 1, 0 ]
[]
[]
[ "cherrypy", "django", "mysql", "pylons", "python" ]
stackoverflow_0003781802_cherrypy_django_mysql_pylons_python.txt
Q: Python Exception handling in Google App Engine I have exception handling in my app engine app. The code work perfectly fine on the dev server. But when I upload the file on the app engine server, I get a syntax error. Here is the traceback: Exception in request: Traceback (most recent call last): File "/base/pyt...
Python Exception handling in Google App Engine
I have exception handling in my app engine app. The code work perfectly fine on the dev server. But when I upload the file on the app engine server, I get a syntax error. Here is the traceback: Exception in request: Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/third_party/django-0...
[ "You're running python 2.6+ on your dev server. App Engine runs on python 2.5.2, which doesn't have the except Exception as foo: syntax. Replace as with a ,, and while you're at it, install Python 2.5 on your dev machine.\n" ]
[ 5 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003783758_django_google_app_engine_python.txt
Q: Is there a Pythonic way to make this logic more elegant? I'm new to Python, and I've been playing around with it for simple tasks. I have a bunch of CSVs which I need to manipulate in complex ways, but I'm breaking this up into smaller tasks for the sake of learning Python. For now, given a list of strings, I wan...
Is there a Pythonic way to make this logic more elegant?
I'm new to Python, and I've been playing around with it for simple tasks. I have a bunch of CSVs which I need to manipulate in complex ways, but I'm breaking this up into smaller tasks for the sake of learning Python. For now, given a list of strings, I want to remove user-defined title prefixes of any names in the st...
[ "[re.sub(r'^(Mr|Ms|Mrs)\\.\\s+', '', s) for s in test_csv_line]\n\n", "Assuming that prefixes is variable, perhaps as an aspect of localization, or you prefer not to use a regular expression for some other reason, you could do something like this (untested code):\ndef strip_title(string, prefixes):\n for prefi...
[ 9, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003783728_python.txt
Q: How do I generate a connection reset programatically? I'm sure you've seen the "the connection was reset" message displayed when trying to browse web pages. (The text is from Firefox, other browsers differ.) I need to generate that message/error/condition on demand, to test workarounds. So, how do I generate that...
How do I generate a connection reset programatically?
I'm sure you've seen the "the connection was reset" message displayed when trying to browse web pages. (The text is from Firefox, other browsers differ.) I need to generate that message/error/condition on demand, to test workarounds. So, how do I generate that condition programmatically? (How to generate a TCP RST fr...
[ "I would recommend doing this via a custom socket via CLI as messing with the apache process could be messy:\n#!/usr/bin/php -q\n<?php\n\nset_time_limit (0);\n\n$sock = socket_create(AF_INET, SOCK_STREAM, 0);\n\nsocket_bind($sock, '1.1.1.1', 8081) or die('Could not bind to address');\n\nsocket_listen($sock);\n\n$cl...
[ 2, 1, 1 ]
[]
[]
[ "php", "python", "sockets", "tcp", "web_applications" ]
stackoverflow_0003773566_php_python_sockets_tcp_web_applications.txt
Q: django/python imports performance Can somebody please proof why it's a bad practice to use solution like this: In django views in 98% cases you need to use from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ anyway in m...
django/python imports performance
Can somebody please proof why it's a bad practice to use solution like this: In django views in 98% cases you need to use from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ anyway in my project my every view has these impor...
[ "1) it's nothing but laziness to not prefix your imported names with the module it came from. It's nothing but laziness to not be willing to scroll past the imports to the code. How exactly does having that mess of imports in another file make it any easier to read through? I would leave it in the original file whe...
[ 5, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003782945_django_python.txt
Q: Python "switch statement" and string formatting I'm trying to do switch statement (with dictionary) and the answer needs to be a formatted string, so for example: descriptions = { 'player_joined_clan': "%(player)s joined clan %(clan)s." % {"player": token1, "clan": token2}, #etc... } Now, this would work ...
Python "switch statement" and string formatting
I'm trying to do switch statement (with dictionary) and the answer needs to be a formatted string, so for example: descriptions = { 'player_joined_clan': "%(player)s joined clan %(clan)s." % {"player": token1, "clan": token2}, #etc... } Now, this would work if those both tokens were always defined, which is no...
[ "If I'm understanding correctly, I'd recommend a collections.defaultdict.\nThis isn't really what I'd call a \"switch\" statement, but I think the end result is close to what you're looking for.\nI can best explain with full code, data, and application.\nObviously, the key line is the defualtdict line.\n>>> import ...
[ 3, 1, 1 ]
[]
[]
[ "lambda", "python", "switch_statement" ]
stackoverflow_0003783585_lambda_python_switch_statement.txt
Q: Calling PHP from Python Is it possible to run a PHP script using python? A: You can look into the subprocess class, more specifically, subprocess.call() subprocess.call(*popenargs, **kwargs) subprocess.call(["php", "path/to/script.php"]); A: You can use the Python OS module. You can run any script by calling ...
Calling PHP from Python
Is it possible to run a PHP script using python?
[ "You can look into the subprocess class, more specifically, subprocess.call()\nsubprocess.call(*popenargs, **kwargs)\n\nsubprocess.call([\"php\", \"path/to/script.php\"]);\n\n", "You can use the Python OS module. You can run any script by calling \nos.system('php -f file.php')\n\nThe issue would be getting return...
[ 14, 4 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003784138_php_python.txt
Q: Python3 int, long unification implementation I just read through a PEP concerning the unification of ints and longs in Python3k in PEP 237. The approach used in this seems very interesting. The approach is to create a new type "integer" which is the abstract base class of int and long. Also, performing operations ...
Python3 int, long unification implementation
I just read through a PEP concerning the unification of ints and longs in Python3k in PEP 237. The approach used in this seems very interesting. The approach is to create a new type "integer" which is the abstract base class of int and long. Also, performing operations on ints which result in very large numbers will no...
[ "Start with Include/longobject.h and Objects/longobject.h These paths are relative to the root of a Python source tree. Make sure to arm yourself with an editor suitable for browsing C code conveniently, or generate a HTML interlinked reference with GNU global.\nAlso, it would surely help to read this article on in...
[ 3 ]
[]
[]
[ "c", "python", "python_3.x" ]
stackoverflow_0003784273_c_python_python_3.x.txt
Q: Python, print names and values of all bound variables Is there a way to have Python print the names and values of all bound variables? (without redesigning the program to store them all in a single list) A: globals() and locals() should give you what you're looking for. A: Yes you can, it is a rather dirty way...
Python, print names and values of all bound variables
Is there a way to have Python print the names and values of all bound variables? (without redesigning the program to store them all in a single list)
[ "globals() and locals() should give you what you're looking for.\n", "Yes you can, it is a rather dirty way to do it, but it is good for debugging etc\nfrom pprint import pprint\n\ndef getCurrentVariableState():\n pprint(locals())\n pprint(globals())\n\n", "dir(...)\n dir([object]) -> list of strings\n...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003784353_python.txt
Q: Division by Zero Errors I have a problem with this question from my professor. Here is the question: Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The s...
Division by Zero Errors
I have a problem with this question from my professor. Here is the question: Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the ti...
[ "When you call float on the division result, it's after the fact the division was treated as an integer division (note: this is Python 2, I assume). It doesn't help, what does help is initially specify the division as a floating-point division, for example by saying 60.0 (the float version of 60):\nfactor = 60.0 / ...
[ 11, 4 ]
[]
[]
[ "decimal", "division", "floating_point", "python" ]
stackoverflow_0003784467_decimal_division_floating_point_python.txt
Q: Online file comparison tool I want to a visualize web file compare tool,that can embed into my app,I know there some software like beyond compare,it has done great job,but it on windows & need buy licence,if someone has develop a web version,then it can cross platform, does some already achieve this? if it is pyth...
Online file comparison tool
I want to a visualize web file compare tool,that can embed into my app,I know there some software like beyond compare,it has done great job,but it on windows & need buy licence,if someone has develop a web version,then it can cross platform, does some already achieve this? if it is python - friendly is great appreciate...
[ "There is Trac: Trac is an enhanced wiki and issue tracking system for software development projects. ... It provides an interface to Subversion (or other version control systems)...\nIt is written in python, and can compare source files. This looks like:\nhttp://trac.edgewall.org/changeset?old_path=%2Ftrunk%2Ftra...
[ 1, 1 ]
[]
[]
[ "compare", "diff", "python" ]
stackoverflow_0003784622_compare_diff_python.txt
Q: Can't do an AJAX call with Python and Django I am still learning to do javascript and django and yesterday I tried to do a simple hello world ajax exercise. Server logs show that python code is being called but somehow django/python does not return anything when I check the xmlhttp.responseText and responseXML in...
Can't do an AJAX call with Python and Django
I am still learning to do javascript and django and yesterday I tried to do a simple hello world ajax exercise. Server logs show that python code is being called but somehow django/python does not return anything when I check the xmlhttp.responseText and responseXML in firebug. UPDATE: I removed the checking of the h...
[ "I just tested your code. When I clicked the \"click me\" button, a request was indeed made to the test view. I was able to confirm this. However, unlike what you said the view is returning the HttpResponse. To verify this yourself, access the http://localhost:8000/test/ url using your web browser. See what happens...
[ 2, 1 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0003783839_django_javascript_python.txt
Q: python backports for some methods Is there any backport for the following methods to work with python 2.4: any, all, collections.defaultdict, collections.deque A: Well, at least for any and all it's easy: def any(iterable): for element in iterable: if element: return True return False...
python backports for some methods
Is there any backport for the following methods to work with python 2.4: any, all, collections.defaultdict, collections.deque
[ "Well, at least for any and all it's easy:\ndef any(iterable):\n for element in iterable:\n if element:\n return True\n return False\n\ndef all(iterable):\n for element in iterable:\n if not element:\n return False\n return True\n\ndeque is already in 2.4.\nAs for def...
[ 5, 5 ]
[]
[]
[ "backport", "methods", "python" ]
stackoverflow_0003785433_backport_methods_python.txt
Q: How do I find out in which file or module is my function called? Python 2.5 to 2.7: #a.py: def foo(): pass #b.py from a import foo foo() From foo(), I'd like to know that it has benn called in the "b" module. The only way I can think of right now is raising an exception, catching it and inspecting the traceb...
How do I find out in which file or module is my function called?
Python 2.5 to 2.7: #a.py: def foo(): pass #b.py from a import foo foo() From foo(), I'd like to know that it has benn called in the "b" module. The only way I can think of right now is raising an exception, catching it and inspecting the traceback (going one level up). Is there a mare natural way of doing this?
[ "You can do this with the inspect module.\nE.g.\n#!/usr/bin/env python\n# a.py\nimport inspect\n\ndef foo():\n for item in inspect.stack():\n print item\n\n-\n#!/usr/bin/env python\n# b.py\n\nfrom a import foo\n\nfoo()\n\n-\n$ python b.py\n(<frame object at 0x2026fb0>, '/home/tdb/a.py', 6, 'foo', [' fo...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003785479_python.txt
Q: Detecting Similar images Possible Duplicate: Image comparison algorithm So basically i need to write a program that checks whether 2 images are the same or not. Consider the following 2 images: http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night.jpg http://i221.photobucket.com/albums/dd298/ramdeen32/...
Detecting Similar images
Possible Duplicate: Image comparison algorithm So basically i need to write a program that checks whether 2 images are the same or not. Consider the following 2 images: http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night.jpg http://i221.photobucket.com/albums/dd298/ramdeen32/starry_night2.jpg Well they a...
[ "Wow - that is a massive question, and one that has a vast number of possible solutions. I'm afraid I'm not a python expert, but I thought your question was interesting - so I wanted to propose a method that I would implement if I were posed with this problem.\nObviously, the two images you posted are actually very...
[ 5, 1, 0 ]
[]
[]
[ "comparison", "image", "media", "python" ]
stackoverflow_0003783398_comparison_image_media_python.txt
Q: How to properly use and cancel subprocess in python using Django? I have a view that gets data from a form and executes a subprocess: def sync_job(request, job_id, src, dest): form = SyncJobForm() check = SyncJob.objects.get(id=job_id) check.status = True check.save() pre_sync = SyncJobCMD.objects.get(id...
How to properly use and cancel subprocess in python using Django?
I have a view that gets data from a form and executes a subprocess: def sync_job(request, job_id, src, dest): form = SyncJobForm() check = SyncJob.objects.get(id=job_id) check.status = True check.save() pre_sync = SyncJobCMD.objects.get(id=1) p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PI...
[ "Starting from Python 2.6 you can use Popen.terminate() to kill your processes:\np.terminate()\n\nIn earlier versions of Python you can use os.kill().\nos.kill(p.pid, signal.SIGTERM)\n\nAlso, Popen.communicate() will block until your child process has terminated. This means that the response will not get sent to th...
[ 0, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0003784052_django_django_views_python.txt
Q: Linux / Bash using PS -f for specific PID returns in different format than PS -f, also queston about using Grep to parse this I have a need, for a python script I'm creating, to first get just the PID of a process (based on its name) and then to get from that process, usings its PID, its time duration, which, from...
Linux / Bash using PS -f for specific PID returns in different format than PS -f, also queston about using Grep to parse this
I have a need, for a python script I'm creating, to first get just the PID of a process (based on its name) and then to get from that process, usings its PID, its time duration, which, from the printout below, would be "00:00:00" root 5686 1 0 Sep23 ? 00:00:00 process-name I am using this to get just ...
[ "Use the -o option to control what data is output and in what order.\ne.g.\n$ ps -o pid,time,comm\n PID TIME COMMAND\n 3029 00:00:01 zsh\n22046 00:00:00 ps\n\nor\n$ ps -o pid,time,comm --no-headers\n 3029 00:00:01 zsh\n22046 00:00:00 ps\n\nThis will make it easier to parse. I would suggest parsing the output ...
[ 3, 0, 0 ]
[]
[]
[ "bash", "command_line", "linux", "pid", "python" ]
stackoverflow_0003785768_bash_command_line_linux_pid_python.txt
Q: Send file using POST from a Python script This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing ...
Send file using POST from a Python script
This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most o...
[ "Best thing I can think of is to encode it yourself. How about this subroutine?\nfrom urllib2 import Request, urlopen\nfrom binascii import b2a_base64\n\ndef b64open(url, postdata):\n req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})\n return urlopen(req)\n\nconn = b64open...
[ 5, 1, 1 ]
[]
[]
[ "encoding", "post", "python" ]
stackoverflow_0000150517_encoding_post_python.txt
Q: SQLite error when loading two python scripts simultaneously I have two python scripts that have to run simultaneously because they interact with each other. One script is a 'server' script running locally and the other is client script that connects to it via a socket. Normally I just open a couple terminal tabs a...
SQLite error when loading two python scripts simultaneously
I have two python scripts that have to run simultaneously because they interact with each other. One script is a 'server' script running locally and the other is client script that connects to it via a socket. Normally I just open a couple terminal tabs and run the server script in one and the client in the other. Afte...
[ "Try combining the two commands into one:\ngnome-terminal --tab -x bash -c \"python server.py & sleep 5; python client.py\"\n\nI think it is better to put the sleep command (if needed) outside client since there may be situations where the server is already started and the client does not have to sleep.\n\nThe -x f...
[ 0 ]
[]
[]
[ "gnome_terminal", "python", "sqlite" ]
stackoverflow_0003786194_gnome_terminal_python_sqlite.txt
Q: Good python XML parser to work with namespace heavy documents Python elementTree seems unusable with namespaces. What are my alternatives? BeautifulSoup is pretty rubbish with namespaces too. I don't want to strip them out. Examples of how a particular python library gets namespaced elements and their collections ...
Good python XML parser to work with namespace heavy documents
Python elementTree seems unusable with namespaces. What are my alternatives? BeautifulSoup is pretty rubbish with namespaces too. I don't want to strip them out. Examples of how a particular python library gets namespaced elements and their collections are all +1. Edit: Could you provide code to deal with this real wor...
[ "lxml is namespace-aware.\n>>> from lxml import etree\n>>> et = etree.XML(\"\"\"<root xmlns=\"foo\" xmlns:stuff=\"bar\"><bar><stuff:baz /></bar></root>\"\"\")\n>>> etree.tostring(et, encoding=str) # encoding=str only needed in Python 3, to avoid getting bytes\n'<root xmlns=\"foo\" xmlns:stuff=\"bar\"><bar><stuff:ba...
[ 13, 1, 0 ]
[]
[]
[ "namespaces", "python", "xml", "xml_namespaces" ]
stackoverflow_0003785629_namespaces_python_xml_xml_namespaces.txt
Q: Windows Live Web Authentication on Google App Engine (GAE) using Python I'm struggling to get Windows Live Web Authentication running on Google App Engine (GAE) using Python, as I'm quite new to the language. However there are lots of examples for Facebook and Twitter, I was wondering if anyone had come up with a ...
Windows Live Web Authentication on Google App Engine (GAE) using Python
I'm struggling to get Windows Live Web Authentication running on Google App Engine (GAE) using Python, as I'm quite new to the language. However there are lots of examples for Facebook and Twitter, I was wondering if anyone had come up with a solution for Windows Live yet?
[ "From what I can tell, the SDK you're referring to is just used for authentication, not authorization. That is, it allows you to uniquely identify a user by their Windows Live ID, but not, say, programmatically import their Hotmail contacts.\nIf this is the case, it would be easier to use the built-in OpenID suppor...
[ 0, 0 ]
[]
[]
[ "authentication", "google_app_engine", "python", "windows_live" ]
stackoverflow_0003567012_authentication_google_app_engine_python_windows_live.txt
Q: Dynamic base class and factories I have following code: class EntityBase (object) : __entity__ = None def __init__ (self) : pass def entity (name) : class Entity (EntityBase) : __entity__ = name def __init__ (self) : pass return Entity class Smth (entity ("...
Dynamic base class and factories
I have following code: class EntityBase (object) : __entity__ = None def __init__ (self) : pass def entity (name) : class Entity (EntityBase) : __entity__ = name def __init__ (self) : pass return Entity class Smth (entity ("SMTH")) : def __init__ (self, a, b...
[ "I would do this with a decorator. Also, storing the entity -> subclass map in a dictionary lets you replace a linear scan with a dict lookup.\nclass EntityBase(object):\n _entity_ = None\n _entities_ = {}\n\n @classmethod\n def factory(cls, entity):\n try:\n return cls._entities_[enti...
[ 9, 5, 3 ]
[ "\nthis valid approach or maybe I something misunderstood and doing wrong?\n\nIt works. So in one sense it's \"valid\".\nIt's a complete waste of code. So in one sense it's not \"valid\".\nThere aren't any use cases for this kind of construct. Now that you've built it, you can move on to solving practical proble...
[ -2 ]
[ "factory", "factory_pattern", "python" ]
stackoverflow_0003786762_factory_factory_pattern_python.txt
Q: Determine Declaring Order of Python/IronPython Functions I'm trying to take a python class (in IronPython), apply it to some data and display it in a grid. The results of the functions become columns on the grid, and I would like the order of the functions to be the order of the columns. Is there a way to determ...
Determine Declaring Order of Python/IronPython Functions
I'm trying to take a python class (in IronPython), apply it to some data and display it in a grid. The results of the functions become columns on the grid, and I would like the order of the functions to be the order of the columns. Is there a way to determine the order of python functions of a class in the order they...
[ "In Python 2.X (IronPython is currently on Python 2) the answer is unfortunately no. Python builds a dictionary of the class members before creating the class object. Once the class is created there is no 'record' of the order.\nIn Python 3 metaclasses (which are used to create classes) are improved and you can use...
[ 2, 2, 1 ]
[]
[]
[ ".net_4.0", "c#", "ironpython", "python" ]
stackoverflow_0003786984_.net_4.0_c#_ironpython_python.txt
Q: Django to do its own NTLM Authentication (HTTP Headers & all) I'm considering moving from Apache to Lighttpd for an internal web application, written with python. The problem is that I'm relying on libapache2-mod-auth-ntlm-winbind ... which doesn't actually seem to be a well support & updated package (though that...
Django to do its own NTLM Authentication (HTTP Headers & all)
I'm considering moving from Apache to Lighttpd for an internal web application, written with python. The problem is that I'm relying on libapache2-mod-auth-ntlm-winbind ... which doesn't actually seem to be a well support & updated package (though that could be because it really does work well). I'm looking for sugges...
[ "Partial answer:\nYou can (and should) pass the NTLM auth off to an external helper. Basically, install Samba on the machine, configure it, join the domain, enable winbind, then use the \"ntlm_auth\" helper binary, probably in \"pipe\" mode.\nAuthenticating an NTLM session requires a secure pipe to the domain contr...
[ 1 ]
[]
[]
[ "active_directory", "django", "ldap", "ntlm", "python" ]
stackoverflow_0003120956_active_directory_django_ldap_ntlm_python.txt
Q: Python GUI for portable app I am developing a python app, using python and sqlite and GUI to re-create a Access 2007 report generating app. Since the app is portable, I'm looking for GUI solution for python that user doesn't need to install addition things before using the app. Is there any GUI solution suits my n...
Python GUI for portable app
I am developing a python app, using python and sqlite and GUI to re-create a Access 2007 report generating app. Since the app is portable, I'm looking for GUI solution for python that user doesn't need to install addition things before using the app. Is there any GUI solution suits my need? Thanks!
[ "The only fully portable GUI for Python is the standard TkInter, if you don't want any additional install beside Python. The Themed Tk version is quite nice looking, compared to the older Tk version (the themed version is available through the ttk module).\nA few weeks ago, I had to answer the same question as you...
[ 8, 5 ]
[]
[]
[ "portable_applications", "python", "user_interface" ]
stackoverflow_0003787065_portable_applications_python_user_interface.txt
Q: Python comparison functions I have some data that lends itself to representation as a value and a comparison function, (val, f), so another value can be checked against it by seeing if f(val, another) is True. That's easy. Some of them just need >, <, or == as f, however, and I can't find a clean way of using t...
Python comparison functions
I have some data that lends itself to representation as a value and a comparison function, (val, f), so another value can be checked against it by seeing if f(val, another) is True. That's easy. Some of them just need >, <, or == as f, however, and I can't find a clean way of using them; I end up writing things like...
[ "The operator module is your friend:\nimport operator\nScorePoint(60, operator.le)\n\nSee http://docs.python.org/library/operator.html\n" ]
[ 11 ]
[ "Yes:\n LessEqual = lambda a, b: a <= b\n ScorePoint(60, LessEqual)\n\nor more concise (but less readable):\n LE = lambda a, b: a <= b\n ScorePoint(60, LE)\n\n" ]
[ -4 ]
[ "comparison", "functional_programming", "python" ]
stackoverflow_0003787633_comparison_functional_programming_python.txt
Q: Prepopulating a Django FileField I wanted to know how is it possible in django to bind an already uploaded file (stored in the file system of server) to a Model FileField. This way I want to have my edit page of that model to prepopulate the FileField with this file. Thanks A: Well I found the answer. It was qui...
Prepopulating a Django FileField
I wanted to know how is it possible in django to bind an already uploaded file (stored in the file system of server) to a Model FileField. This way I want to have my edit page of that model to prepopulate the FileField with this file. Thanks
[ "Well I found the answer. It was quite easy actually. you just need to set the FileField value to some string and it will point to that file.\nThe point is that the path specified should be correct otherwise you get a 404 error when trying to access it.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003785502_django_python.txt
Q: simple python lxml CRUD? I have been looking for a while a python module/API that does something I believe is quite simple: Read an XML file Add/Edit/Remove entries So far I've found several snippets that interface with complicated object oriented databases, but nothing dead simple as: xml = etree.parse ('file.x...
simple python lxml CRUD?
I have been looking for a while a python module/API that does something I believe is quite simple: Read an XML file Add/Edit/Remove entries So far I've found several snippets that interface with complicated object oriented databases, but nothing dead simple as: xml = etree.parse ('file.xml') xml.add(xpath, new_node(...
[ "Did you checkout the lxml.etree tutorial? It has enough examples to show you how to do most of what you want. \n", "There are solutions from the standard library too. I think clear() from xml.etree.ElementTree should work as desired. On the other hand, if you have no problem with external dependencies, I think, ...
[ 2, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003785921_lxml_python.txt
Q: Problem with Python relative imports I am using Python 2.6 and have the Facebook API installed as a python package (under /usr/lib64/python2.6/site-packages/facebook/...) which means, it is available with a plain import facebook or from facebook import .... This works well, as long as there is no name clash. For e...
Problem with Python relative imports
I am using Python 2.6 and have the Facebook API installed as a python package (under /usr/lib64/python2.6/site-packages/facebook/...) which means, it is available with a plain import facebook or from facebook import .... This works well, as long as there is no name clash. For example, in my project, I try to import the...
[ "Apparently (according to http://docs.python.org/whatsnew/2.5.html#pep-328), there is not way around from __future__ import absolute_import, so I guess I'll just have to be happy with that __future__ import to resolve my name shadowing problem.\n" ]
[ 0 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0003783538_django_import_python.txt
Q: Designing a scalable product database on Google App Engine I've built a product database that is divided in 3 parts. And each part has a "sub" part containing labels. But the more I work with it the more unstable it feels. And each addition I make it takes more and more code to get it to work. A product is built ...
Designing a scalable product database on Google App Engine
I've built a product database that is divided in 3 parts. And each part has a "sub" part containing labels. But the more I work with it the more unstable it feels. And each addition I make it takes more and more code to get it to work. A product is built of parts, and each part is of a type. Each product, part and typ...
[ "You need to keep in mind that App Engine's datastore requires you to rethink your usual way of designing databases. It goes against intuition at first but you must denormalize your data as much as possible if you want your application to be scalable. The datastore has been designed this way.\nThe approach I usuall...
[ 3, 1 ]
[]
[]
[ "architecture", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003785802_architecture_google_app_engine_google_cloud_datastore_python.txt
Q: How to draw same nodes with different edge colours correspond to two different graphs? Hope my question has not asked before. I have two graphs, which nodes are the same in both of them but edges are different. I want to draw both of graphs in one plot. Which means I have the same nodes, but with two different edg...
How to draw same nodes with different edge colours correspond to two different graphs?
Hope my question has not asked before. I have two graphs, which nodes are the same in both of them but edges are different. I want to draw both of graphs in one plot. Which means I have the same nodes, but with two different edge colours. But it gives me two different graphs. How could I have them in one graph but wit...
[ "If you are using Python, NetworkX and Matplotlib then you can do something like this, where you have two graphs with the same set of nodes and so you draw first the nodes and then the two set of edges in different colors.\nimport networkx as nx \n\nG=nx.gnm_random_graph(10,20) \nG2=nx.gnm_random_graph(10,20) \n...
[ 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0003519845_networkx_python.txt
Q: Concatenate strings read from file with python? Emacs's auto-fill mode splits the line to make the document look nice. I need to join the strings read from the document. For example, (CR is the carriage return, not the real character) - Blah, Blah, and (CR) Blah, Blah, Blah, (CR) Blah, Blah (CR) - A, ...
Concatenate strings read from file with python?
Emacs's auto-fill mode splits the line to make the document look nice. I need to join the strings read from the document. For example, (CR is the carriage return, not the real character) - Blah, Blah, and (CR) Blah, Blah, Blah, (CR) Blah, Blah (CR) - A, B, C (CR) Blah, Blah, Blah, (CR) Blah, Blah ...
[ "As I read it, your problem is to undo hard-wrapping and restore each set of indented lines to a single soft-wrapped line. This is one way to do it:\n# hard-coded input, could also readlines() from a file\nlines = [\"- Blah, Blah, and\", \n \" Blah, Blah, Blah,\",\n \" Blah, Blah\",\n \"- ...
[ 4, 3, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003788426_python_string.txt
Q: Determine if an XMPP user is online or not I'm using the xmpppy library to write an XMPP client that can chat with users. It has its own XMPP user account and needs to know if a given user is online. However, the documentation is a bit sparse on how to do this. What would you recommend? The only solution I've seen...
Determine if an XMPP user is online or not
I'm using the xmpppy library to write an XMPP client that can chat with users. It has its own XMPP user account and needs to know if a given user is online. However, the documentation is a bit sparse on how to do this. What would you recommend? The only solution I've seen thus far is to start up a daemon before the XMP...
[ "The simple way is to support \"subscribe\" presence message -- this lets another user check if you're currently present (if they don't already know) by a \"subscribe\" attempt. Check this useful guide to get started, and the standard for many more important details (esp. on protecting your privacy, if needed, fro...
[ 2, 1 ]
[]
[]
[ "python", "xmpp", "xmpppy" ]
stackoverflow_0003737779_python_xmpp_xmpppy.txt
Q: Python socket send EOF I have a simple file transfer socket program where one socket sends file data and another socket receives the data and writes to a file I need to send an acknowledgment once transfer is finished from the destination to the source Code for destination s.accept() f = s.makefile() f.read(1024)...
Python socket send EOF
I have a simple file transfer socket program where one socket sends file data and another socket receives the data and writes to a file I need to send an acknowledgment once transfer is finished from the destination to the source Code for destination s.accept() f = s.makefile() f.read(1024) Code for source s.connect(...
[ "Design a protocol (an agreement between client and server) on how to send messages. One simple way is \"the first byte is the length of the message, followed by the message\". Rough example:\nClient\nPython 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\...
[ 7, 4, 3 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003788439_python_sockets.txt
Q: Reusing Generators in Different Unit Tests I'm running into an issue while unit-testing a Python project that I'm working on which uses generators. Simplified, the project/unit-test looks like this: I have a setUp() function which creates a Person instance. Person is a class that has a generator, next_task(), whic...
Reusing Generators in Different Unit Tests
I'm running into an issue while unit-testing a Python project that I'm working on which uses generators. Simplified, the project/unit-test looks like this: I have a setUp() function which creates a Person instance. Person is a class that has a generator, next_task(), which yields the next task that a Person has. I now ...
[ "If you are really creating a new Person object in setUp then it should work as you expect. There are several reasons why it may not be working:\n1) you are initialising the Person's tasks from another iterator, and that is exhausted by the second time you create Person.\n2) You are creating a new Person object ea...
[ 3, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003788878_python_unit_testing.txt
Q: Why am I getting this UnicodeEncodeError when I am inserting into the MySQL database? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 2: ordinal not in range(128) I changed my database default to be utf-8, and not "latin"....but this error still occurs. why? This is in my.cnf. Am I do...
Why am I getting this UnicodeEncodeError when I am inserting into the MySQL database?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 2: ordinal not in range(128) I changed my database default to be utf-8, and not "latin"....but this error still occurs. why? This is in my.cnf. Am I doing this wrong? I just want EVERYTHING TO BE UTF-8. init_connect='SET collation_connection ...
[ "MySQLdb.connect(read_default_*) options won't set the character set from default-character-set. You will need to set this explicitly:\nMySQLdb.connect(..., charset='utf8')\n\nOr the equivalent setting in your django databases settings.\n", "If you get an exception from Python then it's nothing to do with MySQL ...
[ 2, 0 ]
[]
[]
[ "database", "django", "encoding", "mysql", "python" ]
stackoverflow_0002761378_database_django_encoding_mysql_python.txt
Q: Python copy MySQL table to SQLite3 I've got a MySQL table with about ~10m rows. I created a parallel schema in SQLite3, and I'd like to copy the table somehow. Using Python seems like an acceptable solution, but this way -- # ... mysqlcursor.execute('SELECT * FROM tbl') rows = mysqlcursor.fetchall() # or mysqlcurs...
Python copy MySQL table to SQLite3
I've got a MySQL table with about ~10m rows. I created a parallel schema in SQLite3, and I'd like to copy the table somehow. Using Python seems like an acceptable solution, but this way -- # ... mysqlcursor.execute('SELECT * FROM tbl') rows = mysqlcursor.fetchall() # or mysqlcursor.fetchone() for row in rows: # ....
[ "The simplest way might be to use mysqldump to get a SQL file of the whole db, then use the SQLite command-line tool to execute the file.\n", "You don't show exactly how you insert rows, but you mention execute().\nYou might try executemany()* instead.\nFor example:\nimport sqlite3\nconn = sqlite3.connect('mydb')...
[ 3, 3, 0 ]
[]
[]
[ "database", "mysql", "python", "sqlite" ]
stackoverflow_0003124162_database_mysql_python_sqlite.txt
Q: Please point to the right webdev tools I'm making a simple web app where I have some simple python scripts that do the text crunchin g I need - but I'm not quite sure how to interface it with a client who'd only want to see some HTML forms. There's so many different server side frameworks out there - but I don't t...
Please point to the right webdev tools
I'm making a simple web app where I have some simple python scripts that do the text crunchin g I need - but I'm not quite sure how to interface it with a client who'd only want to see some HTML forms. There's so many different server side frameworks out there - but I don't think I need anything too heavy duty - just a...
[ "At the moment, the best lightweight and yet very powerful framework for python IMO is Flask. If you want form abstraction there is a WTFlask plugin for it which is WTForms adapted for flask - http://flask.pocoo.org/.\nWeb2py is also a very good framework for starters because it has helpers and wizards for creating...
[ 3, 1, 0 ]
[]
[]
[ "forms", "html", "python" ]
stackoverflow_0003790043_forms_html_python.txt
Q: How can I package a scrapy project using cxfreeze? I have a scrapy project that I would like to package all together for a customer using windows without having to manually install dependencies for them. I came across cxfreeze, but I'm not quite sure how it would work with a scrapy project. I'm thinking I would ma...
How can I package a scrapy project using cxfreeze?
I have a scrapy project that I would like to package all together for a customer using windows without having to manually install dependencies for them. I came across cxfreeze, but I'm not quite sure how it would work with a scrapy project. I'm thinking I would make some sort of interface and run the scrapy crawler wit...
[ "Try out py2exe. It works well, you can bundle all the code in one exe.\nI suggest you to exclude unused packages to reduce exe size (see py2exe examples on its site)\nUDATE\n As suggested try also\n\nGUI2Exe is a Graphical User\n Interface frontend to all the\n \"executable builders\" available for\n the Python...
[ 1 ]
[]
[]
[ "py2exe", "python", "scrapy", "screen_scraping" ]
stackoverflow_0003790563_py2exe_python_scrapy_screen_scraping.txt
Q: Python os.walk and japanese filename crash Possible Duplicate: Python, Unicode, and the Windows console I have a folder with a filename "01 - ナナナン塊.txt" I open python at the interactive prompt in the same folder as the file and attempt to walk the folder hierachy: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52)...
Python os.walk and japanese filename crash
Possible Duplicate: Python, Unicode, and the Windows console I have a folder with a filename "01 - ナナナン塊.txt" I open python at the interactive prompt in the same folder as the file and attempt to walk the folder hierachy: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "hel...
[ "It seems like all answers so far are from Unix people who assume the Windows console is like a Unix terminal, which it is not.\nThe problem is that you can't write Unicode output to the Windows console using the normal underlying file I/O functions. The Windows API WriteConsole needs to be used. Python should pr...
[ 7 ]
[ "For hard-coded strings, you'll need to specify the encoding at the top of source files. For bytestrings input from some other source - such as os.walk -, you need to specify the byte string's encoding (see unutbu's answer).\n" ]
[ -2 ]
[ "filesystems", "python", "unicode", "windows" ]
stackoverflow_0003789924_filesystems_python_unicode_windows.txt
Q: Piecewise list comprehensions in python What is the easiest/most elegant way to do the following in python: def piecewiseProperty(aList): result = [] valueTrue = 50 valueFalse = 10 for x in aList: if hasProperty(x): result.append(valueTrue) else result.appen...
Piecewise list comprehensions in python
What is the easiest/most elegant way to do the following in python: def piecewiseProperty(aList): result = [] valueTrue = 50 valueFalse = 10 for x in aList: if hasProperty(x): result.append(valueTrue) else result.append(valueFalse) return result where hasPr...
[ "Use a conditional expression (pep-308):\n[50 if hasProperty(x) else 10 for x in alist]\n\n", "How about:\n[50 if hasProperty(x) else 10 for x in aList]\n\n?\n" ]
[ 4, 3 ]
[]
[]
[ "list", "list_comprehension", "piecewise", "python" ]
stackoverflow_0003791245_list_list_comprehension_piecewise_python.txt
Q: Saving a StackedInline foreign keyed model before primary model in Django Admin I have four models with the relationships Model PagetTemplate(models.Model): pass Model TextKey(models.Model): page_template = models.ForeignKey(PageTemplate, related_name='text_keys') Model Page(models.Model): page_templ...
Saving a StackedInline foreign keyed model before primary model in Django Admin
I have four models with the relationships Model PagetTemplate(models.Model): pass Model TextKey(models.Model): page_template = models.ForeignKey(PageTemplate, related_name='text_keys') Model Page(models.Model): page_template = models.ForeignKey(Pagetemplate, related_name='pages') Model Text(models.Model...
[ "Looking at S. Lott's sagacious advice on various django related threads, I decided to write an app to do this myself instead of forcing the django admin to do something that it wasn't meant to do. I would honestly just download a decent CMS for django but the ones that I can find either suck (their code is riddled...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003755058_django_django_admin_django_models_python.txt
Q: Python number wrapping? Consider this Python code: assert(a > 0) assert(b > 0) assert(a + b > 0) Can the third assert ever fail? In C/C++, it can if the sum overflows the maximum integer value. How is this handled in Python? A: Depends on which version of Python you're using. Prior to 2.2 or so, you could get...
Python number wrapping?
Consider this Python code: assert(a > 0) assert(b > 0) assert(a + b > 0) Can the third assert ever fail? In C/C++, it can if the sum overflows the maximum integer value. How is this handled in Python?
[ "Depends on which version of Python you're using.\nPrior to 2.2 or so, you could get an OverflowError.\nVersion 2.2-2.7 promote the sum to a long (arbitrary precision) if it's too large to fit in an int.\n3.0+ has only one integer type, which is arbitrary precision.\n", "Python will automatically promote integers...
[ 9, 3, 1 ]
[ "Ok the answer to your question is generally no, however if you deal with large numbers you can have some problems, below are details on python's big numbers.\nAlso see this post for info on inf (infinity) NaN (not a number (i.e infinity / infinity = NaN) )\n\nPlease Note: This is on a 32 bit AMD machine (Though py...
[ -1 ]
[ "python" ]
stackoverflow_0003791312_python.txt
Q: Is there any other way besides browser extensions that one could have a GUI bar hover over any website a user visits? Goal I want to create a web app with a horizontal GUI bar that floats with the user as they move from site to site. e.g. A user will sign into the web at the home page and then proceed to say Googl...
Is there any other way besides browser extensions that one could have a GUI bar hover over any website a user visits?
Goal I want to create a web app with a horizontal GUI bar that floats with the user as they move from site to site. e.g. A user will sign into the web at the home page and then proceed to say Google to start searching for their topic. Once they are signed in and leave the web app homepage a horizontal GUI bar will appe...
[ "The closest you can get is using (ick) frames, with one frame for your bar and one for the page. That's what Google Image Search does. It can easily get broken by frame-busting scripts though.\n", "\nIs my idea possible with technologies\n like AJAX and Python?\n\nIf the pages you want floating under the bar be...
[ 1, 0 ]
[]
[]
[ "ajax", "browser", "python", "user_interface" ]
stackoverflow_0003791527_ajax_browser_python_user_interface.txt
Q: Building Python libraries on a Mac and experiencing flat namespace errors As a general rule, I rue the days whenever I have to build Python libraries on a Mac. I've generally had fairly good success using Boost::Python, and if I use distutils, most of the time everything works correctly. However, I've never been a...
Building Python libraries on a Mac and experiencing flat namespace errors
As a general rule, I rue the days whenever I have to build Python libraries on a Mac. I've generally had fairly good success using Boost::Python, and if I use distutils, most of the time everything works correctly. However, I've never been able figure out the exact combination of what works/what doesn't work. Specifica...
[ "I have seen this issue when I compile the \"C\" python bindings with the option \n-fvisibility=hidden parameter\n\non mac osx\nI am of understanding is that, this is similar to flat namespace issue.\n" ]
[ 0 ]
[]
[]
[ "boost_python", "flat", "macos", "namespaces", "python" ]
stackoverflow_0003791289_boost_python_flat_macos_namespaces_python.txt
Q: How do I get all instances of VLC on dbus quickly? basically the problem is, that the only way to get all instances of VLC is to search all non-named instances for the org.freedesktop.MediaPlayer identity function and call it. (alternatively I could use the introspection API, but this wouldn't seem to solve my pro...
How do I get all instances of VLC on dbus quickly?
basically the problem is, that the only way to get all instances of VLC is to search all non-named instances for the org.freedesktop.MediaPlayer identity function and call it. (alternatively I could use the introspection API, but this wouldn't seem to solve my problem) Unfortunately many programs upon having sent a dbu...
[ "Easier than spawning a bunch of threads would be to make the calls to the different services asynchronously, providing a callback handler for when a result comes back or a D-Bus error occurs. All of the calls effectively happen in parallel, and your program can proceed as soon as it gets some positive results.\nH...
[ 1 ]
[]
[]
[ "dbus", "linux", "multithreading", "python" ]
stackoverflow_0003791697_dbus_linux_multithreading_python.txt
Q: what constitutes a member of a class? What constitutes a method? It seems that an acceptable answer to the question What is a method? is A method is a function that's a member of a class. I disagree with this. class Foo(object): pass def func(): pass Foo.func = func f = Foo() print "fine so far"...
what constitutes a member of a class? What constitutes a method?
It seems that an acceptable answer to the question What is a method? is A method is a function that's a member of a class. I disagree with this. class Foo(object): pass def func(): pass Foo.func = func f = Foo() print "fine so far" try: f.func() except TypeError: print "whoops! func must not ...
[ "You're just testing it wrong:\n>>> class Foo(object): pass\n... \n>>> def func(self): pass\n... \n>>> Foo.func = func\n>>> f = Foo()\n>>> f.func()\n>>> \n\nYou error of forgetting to have in the def the self argument has absolutely nothing to do with f.func \"not being a method\", of course. The peculiar conceit ...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003791651_python.txt
Q: Output a python script to text file I'm using a script that someone else wrote in python. It's executed from the command line with 3 arguments. example: "python script.py 1111 2222 3333" It does it's thing and works perfectly. The results are NOT saved though, and I would really like to pipe the output to a text...
Output a python script to text file
I'm using a script that someone else wrote in python. It's executed from the command line with 3 arguments. example: "python script.py 1111 2222 3333" It does it's thing and works perfectly. The results are NOT saved though, and I would really like to pipe the output to a text file. Can I simply use similar dos comm...
[ "Redirection works fine both in unix-y shells and in Windows' cmd.exe (which I suspect is what you're calling \"the DOS window\"... unless you're managing to run Python on Windows '95 or something!-).\n$ python script.py 1111 2222 3333 >output.txt\n\nwhere the $ is not something you type, but rather stands for \"wh...
[ 10, 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003791905_python.txt
Q: How do you stream data into the STDIN of a program from different local/remote processes in Python? Standard streams are associated with a program. So, suppose there is a program already running in some way (I don't care how or in what way). The goal is to create pipes to the STDIN of the program from different pr...
How do you stream data into the STDIN of a program from different local/remote processes in Python?
Standard streams are associated with a program. So, suppose there is a program already running in some way (I don't care how or in what way). The goal is to create pipes to the STDIN of the program from different processes (or programs) that run either locally or remotely and stream data into it asynchronously. Availab...
[ "This isn't portable, but on many Linux systems, you can write to\n/proc/$PID/fd/0\n\nI think this may be one of a very limited number of potentially complicated options if you don't have any other control over the remote process.\n", "In most platforms (i.e., operating systems), an existing process's existing fi...
[ 2, 1 ]
[]
[]
[ "ipc", "process", "python", "stdin", "stdout" ]
stackoverflow_0003792054_ipc_process_python_stdin_stdout.txt
Q: Storing dynamic form in a model I want to build a system using Django that will allow users to build forms, store them and have their customers use them. I know how I can go about creating the forms dynamically but I'm looking for a good way to still use the form classes and handle many different user's dynamic fo...
Storing dynamic form in a model
I want to build a system using Django that will allow users to build forms, store them and have their customers use them. I know how I can go about creating the forms dynamically but I'm looking for a good way to still use the form classes and handle many different user's dynamic forms in an elegant way. I'm thinking ...
[ "This is a Python question more than a Django question, whence my tag edit.\nTo reproduce the equivalent of, say:\nclass MyForm(forms.Form):\n foo = forms.CharField(max_length=100)\n\nyou need something like:\nf = type(forms.Form)('MyForm', forms.Form, d)\n\nwhere d is a dictionary like:\nd = { 'foo': forms.Char...
[ 3 ]
[]
[]
[ "django_forms", "python" ]
stackoverflow_0003792083_django_forms_python.txt
Q: Will reloading supervisord cause the process under its to stop? I try to figure out when I used reload command to supervisord. Will it stop the processing currently executing under it? I used below steps: mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) mlzboy@mlzboy-mac:~/my/ide/t...
Will reloading supervisord cause the process under its to stop?
I try to figure out when I used reload command to supervisord. Will it stop the processing currently executing under it? I used below steps: mlzboy@mlzboy-mac:~/my/ide/test$ pstree -p|grep super |-supervisord(6763) mlzboy@mlzboy-mac:~/my/ide/test$ supervisorctl daemon STARTING supe...
[ "It doesn't kill the supervisord process, it just stops all processes, reload the configuration file, and restart processes again.\nIf you just want to apply the new configurations use reread command. It'd just reload the configuration without stopping, and respawning processes.\nAnd running update will restart the...
[ 50 ]
[]
[]
[ "python", "reload", "supervisord" ]
stackoverflow_0003792081_python_reload_supervisord.txt
Q: Which python version needs from __future__ import with_statement? Using python 2.6.5, I can use the with statement without calling from __future__ import with_statement. How can I tell which version of Python supports with without specifically importing it from __future__? A: __future__ features are self-documen...
Which python version needs from __future__ import with_statement?
Using python 2.6.5, I can use the with statement without calling from __future__ import with_statement. How can I tell which version of Python supports with without specifically importing it from __future__?
[ "__future__ features are self-documenting. Try this:\n>>> from __future__ import with_statement\n>>> with_statement.getOptionalRelease()\n(2, 5, 0, 'alpha', 1)\n>>> with_statement.getMandatoryRelease()\n(2, 6, 0, 'alpha', 0)\n\nThese respectively indicate the first release supporting from __future__ import with_st...
[ 51, 17, 2 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0003791903_python_python_import.txt
Q: python socket.PF_PACKET I am trying to send out an ARP request with python, working with dpkt, and I found some sample code that uses: socket.socket(socket.PF_PACKET, socket.SOCK_RAW) I understand that you need to use raw sockets to send this, but it says that socket.PF_PACKET doesn't exist. And there is nothing ...
python socket.PF_PACKET
I am trying to send out an ARP request with python, working with dpkt, and I found some sample code that uses: socket.socket(socket.PF_PACKET, socket.SOCK_RAW) I understand that you need to use raw sockets to send this, but it says that socket.PF_PACKET doesn't exist. And there is nothing in the python docs about it t...
[ "Edited my reply:\nPF_PACKET was introduced in Linux versions 2.0 and above. Python only wraps the socket interface of the operating system. AaronMcSmooth comment verifies that it is available on Linux. It is not available on mac though.\nAlso it looks like AF_PACKET may get preferred in 3.2 \n\nhttp://bugs.python....
[ 2 ]
[]
[]
[ "networking", "python", "raw_sockets" ]
stackoverflow_0003792407_networking_python_raw_sockets.txt
Q: How to require implementation of method in Python? I'm using duck typing in Python. def flagItem(object_to_flag, account_flagging, flag_type, is_flagged): if flag_type == Flags.OFFENSIVE: object_to_flag.is_offensive=is_flagged elif flag_type == Flags.SPAM: object_to_flag.is_spam=is_flagged...
How to require implementation of method in Python?
I'm using duck typing in Python. def flagItem(object_to_flag, account_flagging, flag_type, is_flagged): if flag_type == Flags.OFFENSIVE: object_to_flag.is_offensive=is_flagged elif flag_type == Flags.SPAM: object_to_flag.is_spam=is_flagged object_to_flag.is_active=(not is_flagged) objec...
[ "Use the abc module. Specifically, set your base class's metaclass to ABCMeta and use the @abstractmethod decorator on your cleanup method.\nThe debate on whether this is \"pythonic\" is split. PEP 3119, which describes the standard, lists some of the pros and cons (but obviously favors ABCs). It made it into the s...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "abstract_methods", "duck_typing", "python" ]
stackoverflow_0003783596_abstract_methods_duck_typing_python.txt
Q: How to Build a 32-bit Python Module Distribution w/ Setup.py on x86_64 Host I need to compile a 32-bit distribution of PyEphem. It does not seem like this should be difficult, however, I'm running into some compiler issues. $ CFLAGS=-m32 python setup.py bdist -p i386 running bdist running bdist_dumb running build ...
How to Build a 32-bit Python Module Distribution w/ Setup.py on x86_64 Host
I need to compile a 32-bit distribution of PyEphem. It does not seem like this should be difficult, however, I'm running into some compiler issues. $ CFLAGS=-m32 python setup.py bdist -p i386 running bdist running bdist_dumb running build running build_py running build_ext building 'ephem._libastro' extension gcc -pthr...
[ "Have you installed a 32-bit python on your machine? I think that it should be OK if you run it from 32-bit python, and make sure you're linking to the right python.h.\nI've never tried to cross-compile on Linux, but I have compiled against different pythons installed side by side on 64-bit Windows.\nThen of course...
[ 1 ]
[]
[]
[ "cross_compiling", "gcc", "python", "setup.py" ]
stackoverflow_0003792285_cross_compiling_gcc_python_setup.py.txt
Q: How to Install rpy2 on Mac OS X I am trying, so far unsuccessfully, at installing the rpy2 for python on my Mac OSX. I have tried Macports and DarwinPorts but have had no luck with import rpy2 within the python shell environment. I don't know much about programming in Mac and I am a wiz at installing modules on ...
How to Install rpy2 on Mac OS X
I am trying, so far unsuccessfully, at installing the rpy2 for python on my Mac OSX. I have tried Macports and DarwinPorts but have had no luck with import rpy2 within the python shell environment. I don't know much about programming in Mac and I am a wiz at installing modules on a Windoze based system, but for the l...
[ "easy_install and rpy2 work fine together (just did it) but you need to have easy_install in sync with your specific python version. This comes down to controlling your $PATH and $PYTHONPATH environment variables so that the first Python directory that appears is the version you want and also has the easy_install v...
[ 2, 1 ]
[]
[]
[ "macos", "osx_snow_leopard", "python", "rpy2" ]
stackoverflow_0003687939_macos_osx_snow_leopard_python_rpy2.txt
Q: Python regular expression slicing I am trying to get a web page using the following sample code: from urllib import urlopen print urlopen("http://www.php.net/manual/en/function.gettext.php").read() Now I can get the whole web page in a variable. I wanna get a part of the page containing something like this <div c...
Python regular expression slicing
I am trying to get a web page using the following sample code: from urllib import urlopen print urlopen("http://www.php.net/manual/en/function.gettext.php").read() Now I can get the whole web page in a variable. I wanna get a part of the page containing something like this <div class="methodsynopsis dc-description"> ...
[ "Why don't you try using BeautifulSoup\n\nhttp://www.crummy.com/software/BeautifulSoup/\n\nExample code :\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(htmldoc)\nallSpans = soup.findAll('span', class=\"type\")\nfor element in allSpans:\n ....\n\n", "When extracting information from HTML, it is...
[ 2, 1 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003792645_html_python_regex.txt
Q: What to do if collections.defaultdict is not available? Solaris python 2.4.3: from collections import defaultdict does not exist.. Please advise what could be an alternative to use multi-level dictionaries: dictOut['1']['exec'] = 'shell1.sh' dictOut['1']['onfailure'] = 'continue' ... dictOut['2']['exec'] = 'she...
What to do if collections.defaultdict is not available?
Solaris python 2.4.3: from collections import defaultdict does not exist.. Please advise what could be an alternative to use multi-level dictionaries: dictOut['1']['exec'] = 'shell1.sh' dictOut['1']['onfailure'] = 'continue' ... dictOut['2']['exec'] = 'shell2.sh' dictOut['2']['onfailure'] = stop' many thanks applom...
[ "setdefault?\ndictOut.setdefault('1', {})['exec'] = 'shell1.sh'\n\n", "Answered with looks-like-it-works code within the last 24 hours (found by searching for \"defaultdict\", choose \"newest\" or \"active\" order)\n", "As an alternative to setdefault, if you want extra level of dictionary goodness, try\nclass ...
[ 2, 2, 2, 0 ]
[]
[]
[ "collections", "python" ]
stackoverflow_0003792258_collections_python.txt
Q: Accessing names defined in a package's `__init__.py` when running setuptools tests I've taken to putting module code directly in a packages __init__.py, even for simple packages where this ends up being the only file. So I have a bunch of packages that look like this (though they're not all called pants:) + pants/...
Accessing names defined in a package's `__init__.py` when running setuptools tests
I've taken to putting module code directly in a packages __init__.py, even for simple packages where this ends up being the only file. So I have a bunch of packages that look like this (though they're not all called pants:) + pants/ \-- __init__.py \-- setup.py \-- README.txt \--+ test/ \-- __init__.py I started do...
[ "I think the standard way to package python programs would be more like this:\n\\-- setup.py\n\\-- README.txt\n\\--+ pants/\n \\-- __init__.py\n \\-- __main__.py\n ...\n\\--+ tests/\n \\-- __init__.py\n ...\n\\--+ some_dependency_you_need/\n ...\n\nThen you avoid the problem.\n" ]
[ 1 ]
[]
[]
[ "module", "package", "python", "setuptools", "testing" ]
stackoverflow_0003792813_module_package_python_setuptools_testing.txt
Q: wxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times? I am working on a chatroom client and am using an HTML window to process things like images and html tags and formatting. I am having trouble finding out how to make the scrollbar stay at the bottom as messages are added to the win...
wxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times?
I am working on a chatroom client and am using an HTML window to process things like images and html tags and formatting. I am having trouble finding out how to make the scrollbar stay at the bottom as messages are added to the window (every message sends the bar to the top) would anyone know how I would go about doing...
[ "After you add a new message, you can call Scroll on your htmlWindow to set its scrollBar position to the end.\nyourHtmlWindow.Scroll(-1, self.GetClientSize()[0])\n\nIf you want your scrollBar to stay at the bottom when the window is resized then you will need to Bind to wx.EVT_SIZE so that you can call Scroll on ...
[ 1 ]
[]
[]
[ "python", "wxhtmlwindow", "wxpython" ]
stackoverflow_0003791713_python_wxhtmlwindow_wxpython.txt
Q: How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python? Yesterday, I asked this question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extr...
How do I write this in Ruby/Python? Or, can you translate my LINQ to Ruby/Python?
Yesterday, I asked this question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style. Since I didn't see anything I really liked, I've written the...
[ ">>> import random\n>>> print random.sample(xrange(100), 5)\n[61, 54, 91, 72, 85]\n\nThis should yield 5 unique values in the range 0 — 99. The xrange object generates values as requested so no memory is used for values that aren't sampled.\n", "In Ruby:\na = (0..100).entries.sort_by {rand}.slice! 0, 5\n\nUpdate:...
[ 13, 5, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[ "I can't really read your LINQ, but I think you're trying to get 5 random numbers up to 100 and then remove duplicates.\nHere's a solution for that:\ndef random(max)\n (rand * max).to_i\nend\n\n# Get 5 random numbers between 0 and 100\na = (1..5).inject([]){|acc,i| acc << random( 100)}\n# Remove Duplicates\na = ...
[ -1 ]
[ "functional_programming", "linq", "python", "ruby" ]
stackoverflow_0000122033_functional_programming_linq_python_ruby.txt
Q: How to install a Python Recipe File (.py)? I'm new to Python. I'm currently on Py3k (Win). I'm having trouble installing a .py file. Basically, i want to use the recipes provided at the bottom of this page. So i want to put them inside a .py and import them in any of my source codes. So i copied all the recipes in...
How to install a Python Recipe File (.py)?
I'm new to Python. I'm currently on Py3k (Win). I'm having trouble installing a .py file. Basically, i want to use the recipes provided at the bottom of this page. So i want to put them inside a .py and import them in any of my source codes. So i copied all the recipes into a recipes.py file and copied them to C:\Pytho...
[ "There are two closely-related issues.\nFirst, within recipes.py, you need access to all of itertools. \nAt the very least, this means you need \nimport itertools\n\nat the top. But in this case you would need to qualify all of the itertools functions as itertools.<funcname>, as you say. (You could also use import ...
[ 7 ]
[]
[]
[ "installation", "python", "python_3.x", "recipe" ]
stackoverflow_0003793123_installation_python_python_3.x_recipe.txt
Q: Among MATLAB and Python, which one is good for statistical analysis? Which one among the two languages is good for statistical analysis? What are the pros and cons, other than accessibility, for each? A: MATLAB Good for beginners Good for interactive sessions Python (with SciPy) Good for slightly experienced ...
Among MATLAB and Python, which one is good for statistical analysis?
Which one among the two languages is good for statistical analysis? What are the pros and cons, other than accessibility, for each?
[ "MATLAB\n\nGood for beginners\nGood for interactive sessions\n\nPython (with SciPy)\n\nGood for slightly experienced programmers\nGood for creating reusable applications\nGood for reading and exporting data files\nFree of cost\n\nIf SciPy doesn't provide all the functionality out of the box, then you may have to go...
[ 8, 6, 3, 3, 2 ]
[]
[]
[ "analysis", "matlab", "python", "statistics" ]
stackoverflow_0003792465_analysis_matlab_python_statistics.txt
Q: How to make a .exe for Python with good graphics? I have a Python application and I decided to do a .exe to execute it. This is the code that I use to do the .exe: # -*- coding: cp1252 -*- from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_f...
How to make a .exe for Python with good graphics?
I have a Python application and I decided to do a .exe to execute it. This is the code that I use to do the .exe: # -*- coding: cp1252 -*- from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, windows = [{'script': "SoundLog.py"}],...
[ "I assume you mean the visual style of the toolbar and buttons. You need to add a manifest file to the EXE file or as a separate file so that Windows applies the modern style of recent comctl32.dll versions.\nCheck out Using Windows XP Visual Styles With Controls on Windows Forms on MSDN. Read the relevant part abo...
[ 7, 1, 0 ]
[]
[]
[ "graphics", "py2exe", "python", "wxpython" ]
stackoverflow_0003764410_graphics_py2exe_python_wxpython.txt
Q: How to open SQL Compact database read only There is a SQL Compact v3.1 database that I want to quickly read. I'm doing this in python so I don't have access to managed code. I've noticed that if I use adodbapi the database file actually gets modified just by opening it. And sadly when I add 'File mode=Read Only'...
How to open SQL Compact database read only
There is a SQL Compact v3.1 database that I want to quickly read. I'm doing this in python so I don't have access to managed code. I've noticed that if I use adodbapi the database file actually gets modified just by opening it. And sadly when I add 'File mode=Read Only' to the connection string I get a weird error. H...
[ "Look here: http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/bf70c615-b279-4a91-b964-0ff99adc7ab8/#674f6a79-a3b4-4601-a952-860a7e8f3169\ncn.Mode = adModeRead\n" ]
[ 3 ]
[]
[]
[ "ado", "python", "sql_server_ce" ]
stackoverflow_0003790090_ado_python_sql_server_ce.txt
Q: Using a java library from python I have a python app and java app. The python app generates input for the java app and invokes it on the command line. I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java. Any pointers? (FYI I'm v. new to Python) Clarification (at...
Using a java library from python
I have a python app and java app. The python app generates input for the java app and invokes it on the command line. I'm sure there must be a more elegant solution to this; just like using JNI to invoke C code from Java. Any pointers? (FYI I'm v. new to Python) Clarification (at the cost of a long question: apologie...
[ "Sorry to ressurect the thread, but there was no accepted answer...\nYou could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:\n>>> from py4j.java_gateway import JavaGateway\n>>> gateway ...
[ 70, 11, 6, 5, 4, 2 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0000476968_java_jython_python.txt
Q: error when plotting log'd array in matplotlib/scipy/numpy I have two arrays and I take their logs. When I do that and try to plot their scatter plot, I get this error: File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/pyplot.py", line 2192, in scatter ...
error when plotting log'd array in matplotlib/scipy/numpy
I have two arrays and I take their logs. When I do that and try to plot their scatter plot, I get this error: File "/Library/Python/2.6/site-packages/matplotlib-1.0.svn_r7892-py2.6-macosx-10.6-universal.egg/matplotlib/pyplot.py", line 2192, in scatter ret = ax.scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, a...
[ "I had the same problem which I fixed recently:\nThe problem for me was that my X and Y (numpy) arrays were made up of 128 bit floats.\nThe solution in this case was to recast the arrays to a lower precision float i.e. \narray = numpy.float64(array)\nHope this helps :~)\n", "New Answer:\nFrom looking at the sourc...
[ 7, 5, 4 ]
[]
[]
[ "matplotlib", "numpy", "python", "scipy" ]
stackoverflow_0002693399_matplotlib_numpy_python_scipy.txt
Q: How to get random slice of python list of constant size. (smallest code) Hi I have a List say 100 items, now i want a slice of say 6 items which should be randomly selected. Any way to do it in very simple simple concise statement??? This is what i came up with (but it will fetch in sequence) mylist #100 items ...
How to get random slice of python list of constant size. (smallest code)
Hi I have a List say 100 items, now i want a slice of say 6 items which should be randomly selected. Any way to do it in very simple simple concise statement??? This is what i came up with (but it will fetch in sequence) mylist #100 items N=100 L=6 start=random.randint(0,N-L); mylist[start:start+L]
[ "You could use the shuffle() method on the list before you slice.\nIf the order of the list matters, just make a copy of it first and slice out of the copy.\n\nmylist #100 items\nshuffleList = mylist\nL=6\nshuffle(shuffleList) \nstart=random.randint(0,len(shuffleList)-L);\nshuffleList[start:start+L]\n\nAs above, yo...
[ 13 ]
[]
[]
[ "python" ]
stackoverflow_0003793786_python.txt
Q: How can you select a random element from a list, and have it be removed? Let's say I have a list of colours, colours = ['red', 'blue', 'green', 'purple']. I then wish to call this python function that I hope exists, random_object = random_choice(colours). Now, if random_object holds 'blue', I hope colours = ['re...
How can you select a random element from a list, and have it be removed?
Let's say I have a list of colours, colours = ['red', 'blue', 'green', 'purple']. I then wish to call this python function that I hope exists, random_object = random_choice(colours). Now, if random_object holds 'blue', I hope colours = ['red', 'green', 'purple']. Does such a function exist in python?
[ "Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle() in the random module. \nrandom.choice() picks one, but does not remove it.\nOtherwise, try:\nimport random\n\n# this will choose one and remove it\ndef choose_and_remove( items ):\n # pick an item...
[ 8, 7 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003791400_python_random.txt
Q: Managing subdomains What are the best practices and solutions for managing dynamic subdomains in different technologies and frameworks? I am searching for something to implement in my Django project but those solutions that I saw, don't work. I also tried to use Apache rewrite mod to send requests from subdomain.d...
Managing subdomains
What are the best practices and solutions for managing dynamic subdomains in different technologies and frameworks? I am searching for something to implement in my Django project but those solutions that I saw, don't work. I also tried to use Apache rewrite mod to send requests from subdomain.domain.com to domain.com/s...
[ "You may be able to do what you need with apache mod_rewrite.\nObviously I didn't read the question clearly enough.\nAs for how to do it in django: you could have some middleware that looks at the server name, and redirects according to that (or even sets a variable). You can't do it with the bare url routing syste...
[ 1 ]
[]
[]
[ "django", "python", "subdomain" ]
stackoverflow_0003793424_django_python_subdomain.txt