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: Inserting a row in SQLAlchemy Been round the houses on this one, cant seem to get the right syntax. All I want to do is insert a row into a table in SQLAlchemy. The documentation doesnt make sense to me thought: class sqlalchemy.sql.expression.Insert(table, values=None, inline=False, bind=None, prefixes=None, retu...
Inserting a row in SQLAlchemy
Been round the houses on this one, cant seem to get the right syntax. All I want to do is insert a row into a table in SQLAlchemy. The documentation doesnt make sense to me thought: class sqlalchemy.sql.expression.Insert(table, values=None, inline=False, bind=None, prefixes=None, returning=None, **kwargs) The closest ...
[ "I'm not sure I understand what exactly you are trying to do, but adding a row is usually no harder than creating a model object and adding it to the session.\nuserChoices = model.CompUserChoices()\n# Do stuff on userChoices\nmeta.Session.add(userChoices)\nmeta.Session.commit() # if you have to commit manually\n\n...
[ 7 ]
[]
[]
[ "insert", "python", "sqlalchemy" ]
stackoverflow_0007753100_insert_python_sqlalchemy.txt
Q: Quirk in Python on multiple inheritance! At least I think so I have been working on a multiple inheritance code which looks similar to this: class Document(): def save(self, x): print "inside Document from " + x class Cdm(object): def save(self,x): print "inside Cdm from " + x su...
Quirk in Python on multiple inheritance! At least I think so
I have been working on a multiple inheritance code which looks similar to this: class Document(): def save(self, x): print "inside Document from " + x class Cdm(object): def save(self,x): print "inside Cdm from " + x super(Cdm,self).save('Cdm') class Contacts(Cdm, Document): def ...
[ "As Python documentation says:\n\nsuper(): Return a proxy object that delegates method calls to a parent or sibling class of type.\n\nIn that situation, super(Cdm,self).save('Cdm') will call the version of save() which is next in method resolution order. In that case it is the save() method in the Document class be...
[ 3, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0007753079_inheritance_python.txt
Q: Pytables vs. CSV for files that are not very large I recently came across Pytables and find it to be very cool. It is clear that they are superior to a csv format for very large data sets. I am running some simulations using python. The output is not so large, say 200 columns and 2000 rows. If someone has experie...
Pytables vs. CSV for files that are not very large
I recently came across Pytables and find it to be very cool. It is clear that they are superior to a csv format for very large data sets. I am running some simulations using python. The output is not so large, say 200 columns and 2000 rows. If someone has experience with both, can you suggest which format would be mor...
[ "Have you considered Numpy arrays?\nPyTables are wonderful when your data is too large to fit in memory, but a\n200x2000 matrix of 8 byte floats only requires about 3MB of memory. So I think\nPyTables may be overkill. \nYou can save numpy arrays to files using np.savetxt or np.savez (for compression), and can read ...
[ 6, 2, 2, 1, 1, 0 ]
[]
[]
[ "csv", "pytables", "python" ]
stackoverflow_0004022887_csv_pytables_python.txt
Q: Django: CreateView fail_url I've the following code and I want form_invalid method to return the same page as success_url. I've been considering sub-classing CreateView but I want to know public opinion. How to realize the thing described above? class ProgramNew(CreateView): form_class = ProgramForm templa...
Django: CreateView fail_url
I've the following code and I want form_invalid method to return the same page as success_url. I've been considering sub-classing CreateView but I want to know public opinion. How to realize the thing described above? class ProgramNew(CreateView): form_class = ProgramForm template_name = 'programs/program_list....
[ "def form_invalid(self, form): \n return HttpResponseRedirect(self.get_success_url())\n\nBut I don't know what's the use of this form.\n" ]
[ 1 ]
[]
[]
[ "django", "django_generic_views", "python" ]
stackoverflow_0007753357_django_django_generic_views_python.txt
Q: Python put multiple lines to array Using regexp I am searching through text file which contains data. I get output similar to this. Here's what I get for example: 36 37 36 36 36 76 39 36 68 36 56 36 36 36 ... I need all those 36 to be in array like this [ '36', '36', .... ] The sample code is below. #!/usr/bin/p...
Python put multiple lines to array
Using regexp I am searching through text file which contains data. I get output similar to this. Here's what I get for example: 36 37 36 36 36 76 39 36 68 36 56 36 36 36 ... I need all those 36 to be in array like this [ '36', '36', .... ] The sample code is below. #!/usr/bin/python import re log = re.compile('Dele...
[ "Your data is already in a list. If you want to print it out in array notation, replace this:\nfor result in List:\n print(result)\n\nwith this:\nprint List\n\nYou really shouldn't call your list List, though - list is a reserved word, and List is confusingly similar.\nIncidentally, this:\nList.append(str(first)...
[ 5, 1, 0 ]
[]
[]
[ "arrays", "line", "python" ]
stackoverflow_0007753226_arrays_line_python.txt
Q: python subprocess with timeout and large output (>64K) I want to execute a process, limit the execution-time by some timeout in seconds and grab the output produced by the process. And I want to do this on windows, linux and freebsd. I have tried implementing this in three different ways: cmd - Without timeout an...
python subprocess with timeout and large output (>64K)
I want to execute a process, limit the execution-time by some timeout in seconds and grab the output produced by the process. And I want to do this on windows, linux and freebsd. I have tried implementing this in three different ways: cmd - Without timeout and subprocess.PIPE for output capture. BEHAVIOUR: Operates as...
[ "As opposed to all the warnings in the subprocess documentation then directly reading from process.stdout and process.stderr has provided a better solution.\nBy better I mean that I can read output from a process that exceeds 2^16 bytes without having to temporarily store the output on disk.\nThe code follows:\nimp...
[ 5, 2 ]
[]
[]
[ "python", "subprocess", "timeout" ]
stackoverflow_0003575554_python_subprocess_timeout.txt
Q: Kill or terminate subprocess when timeout? I would like to repeatedly execute a subprocess as fast as possible. However, sometimes the process will take too long, so I want to kill it. I use signal.signal(...) like below: ppid=pipeexe.pid signal.signal(signal.SIGALRM, stop_handler) signal.alarm(1) ..... def stop...
Kill or terminate subprocess when timeout?
I would like to repeatedly execute a subprocess as fast as possible. However, sometimes the process will take too long, so I want to kill it. I use signal.signal(...) like below: ppid=pipeexe.pid signal.signal(signal.SIGALRM, stop_handler) signal.alarm(1) ..... def stop_handler(signal, frame): print 'Stop test'+t...
[ "You could do something like this:\nimport subprocess as sub\nimport threading\n\nclass RunCmd(threading.Thread):\n def __init__(self, cmd, timeout):\n threading.Thread.__init__(self)\n self.cmd = cmd\n self.timeout = timeout\n\n def run(self):\n self.p = sub.Popen(self.cmd)\n ...
[ 47, 2, 0, 0, 0 ]
[]
[]
[ "kill", "python", "signals", "subprocess", "timeout" ]
stackoverflow_0004158502_kill_python_signals_subprocess_timeout.txt
Q: PyDev: Fatal error Python32\lib\io.py, line 60, in I work in PyDev and quite suddenly, I cannot run my python programs from within Eclipse's PyDev (version 2.1.0) anymore. Any python program I have ran through Run As > Python Run fails wioth Fatal Python error: Py_Initialize: can't initialize sys standard stream...
PyDev: Fatal error Python32\lib\io.py, line 60, in
I work in PyDev and quite suddenly, I cannot run my python programs from within Eclipse's PyDev (version 2.1.0) anymore. Any python program I have ran through Run As > Python Run fails wioth Fatal Python error: Py_Initialize: can't initialize sys standard streams Traceback (most recent call last): File "C:\Python32\...
[ "I have finally found out where the problem came from: I had a file called stat.py and this is apparently creating a conflict with Lib/stat.py\nUnfortunately the error message was very obscure.\nAnd I just don't understand why pyDev behaves differently than python.exe\n" ]
[ 1 ]
[]
[]
[ "eclipse", "eclipse_3.5", "pydev", "python", "python_3.x" ]
stackoverflow_0007111025_eclipse_eclipse_3.5_pydev_python_python_3.x.txt
Q: How to read single values that contains commas in csv file using python I have a csv file that contains the following values "Spam2,pank",Spam3,Spam6,Spam7 Spam1,Spam5,Spam0,Spam9 And i am using the following python code to read a particular column for line in open('D:\eggs2.csv','rb'): columns = line.split("...
How to read single values that contains commas in csv file using python
I have a csv file that contains the following values "Spam2,pank",Spam3,Spam6,Spam7 Spam1,Spam5,Spam0,Spam9 And i am using the following python code to read a particular column for line in open('D:\eggs2.csv','rb'): columns = line.split(",") print columns[0] The output it gives is:- "Spam2 Spam1 while i am e...
[ "You don't have to reinvent the wheel, the python csv module does a perfect job.\nimport csv\n\ncsv_file = open('D:\\eggs2.csv','rb')\ncsv_reader = csv.reader(csv_file)\nfor row in csv_reader:\n print row[0]\n\ncsv_file.close()\n\n@see python csv\n", "It depends on what data structure you want to red the csv i...
[ 7, 0 ]
[ "You could split it twice. First, split it to get something like '''\"\\w\"''', ie all alphanumberic characters inside quotes. The result is a list for each split. Then you would split again, this time for ',', for each list that resulted in your first split. Then you flatten the lists.\n" ]
[ -1 ]
[ "csv", "python" ]
stackoverflow_0007750255_csv_python.txt
Q: how can i run a script containing shell escape from ipython? It's so convenient to use shell escape from interactive environment in ipython, but is it possible to call python script containing shell escape from ipython? A: If you give the script a .ipy extension, ipython's special syntax (like !ls) should work w...
how can i run a script containing shell escape from ipython?
It's so convenient to use shell escape from interactive environment in ipython, but is it possible to call python script containing shell escape from ipython?
[ "If you give the script a .ipy extension, ipython's special syntax (like !ls) should work when you do ipython myscript.ipy.\n" ]
[ 1 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0007752532_ipython_python.txt
Q: Sphinx automodule: how to reference classes in same module? I am trying to use the sphinx autodoc extension and specifically the automodule directive to automatically generate documentation for django app I am working on. The problem is that I want to create internal references to different classes within the modu...
Sphinx automodule: how to reference classes in same module?
I am trying to use the sphinx autodoc extension and specifically the automodule directive to automatically generate documentation for django app I am working on. The problem is that I want to create internal references to different classes within the module, without having to use autoclass and autofunction on every sin...
[ "You can reference a class like this:\nclass B(object):\n \"\"\"docs for B with reference to :class:`.A`\"\"\"\n pass\n\nSphinx will intelligently try and figure out what you're referencing. If there are multiple classes with the name A, you might get a warning, but it should pick up the one in the current mo...
[ 56, 14 ]
[]
[]
[ "autodoc", "django", "python", "python_sphinx" ]
stackoverflow_0007753805_autodoc_django_python_python_sphinx.txt
Q: Python - Best way to read a file and break out the lines by a delimeter What is the best way to read a file and break out the lines by a delimeter. Data returned should be a list of tuples. Can this method be beaten? Can this be done faster/using less memory? def readfile(filepath, delim): with open(filepath, ...
Python - Best way to read a file and break out the lines by a delimeter
What is the best way to read a file and break out the lines by a delimeter. Data returned should be a list of tuples. Can this method be beaten? Can this be done faster/using less memory? def readfile(filepath, delim): with open(filepath, 'r') as f: return [tuple(line.split(delim)) for line in f]
[ "Your posted code reads the entire file and builds a copy of the file in memory as a single list of all the file contents split into tuples, one tuple per line. Since you ask about how to use less memory, you may only need a generator function:\ndef readfile(filepath, delim): \n with open(filepath, 'r') as f: \n...
[ 15, 4 ]
[]
[]
[ "file_io", "generator", "python" ]
stackoverflow_0007753899_file_io_generator_python.txt
Q: How to save StringListProperty from input type text - Appengine Python I need to save the value of an input type text into a StringListProperty property in Google Appengine with Python. If I try: author.books = self.request.get('books') author.put() Then I get a 'Property books must be a list' error. I need it to...
How to save StringListProperty from input type text - Appengine Python
I need to save the value of an input type text into a StringListProperty property in Google Appengine with Python. If I try: author.books = self.request.get('books') author.put() Then I get a 'Property books must be a list' error. I need it to work with the following text in the input (2 or 1 books separated by commas...
[ "author.books = self.request.get('books').split(', ')\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "input", "python", "textinput" ]
stackoverflow_0007754140_google_app_engine_input_python_textinput.txt
Q: Listing inputs on Python by using XML and array I want to sort some kind of functions by Python and XML, but I'm really confused about it. I'll give you an example, There are 3 input options that contains in a config.xml file. <inputs> <input1 value='1- Sending Email' /> <input2 value='2- Extracting a Tar ...
Listing inputs on Python by using XML and array
I want to sort some kind of functions by Python and XML, but I'm really confused about it. I'll give you an example, There are 3 input options that contains in a config.xml file. <inputs> <input1 value='1- Sending Email' /> <input2 value='2- Extracting a Tar File' /> <input3 value='3- Rebooting Server' /> <...
[ "This involves a bit of mindreading, but I think I know what you're looking for... I built a file called inputs.xml that contains the xml you referenced above, then I read it and stored the inputs in a python dictionary called inputs\nfrom xml.etree import ElementTree\n\ninputs = dict()\ntree = ElementTree.parse( ...
[ 0, 0 ]
[]
[]
[ "arrays", "input", "list", "python", "xml" ]
stackoverflow_0007754257_arrays_input_list_python_xml.txt
Q: Python Regex pattern not being matched I'm trying to get some regex to parse some values stored in a set of lua files, each line looks something like one of these two lines ITEM.ID = 'item_clock';\r\n ITEM.Cost = 150;\r\n. when I run my regex pattern on the first line I get an expected result >>> re.search("ITE...
Python Regex pattern not being matched
I'm trying to get some regex to parse some values stored in a set of lua files, each line looks something like one of these two lines ITEM.ID = 'item_clock';\r\n ITEM.Cost = 150;\r\n. when I run my regex pattern on the first line I get an expected result >>> re.search("ITEM.(?P<key>[a-zA-Z]\w) = (?P<value>.*);", lin...
[ "The regex looks for ITEM. followed by a letter then followed by exactly one word character (the \\w in the regex).\nYou probably meant something like ITEM.(?P<key>[a-zA-Z]\\w*)... (note the added asterisk). This will look for ITEM. followed by a letter then followed by zero or more word characters.\nAlso, it's a g...
[ 7, 1 ]
[]
[]
[ "file", "python", "regex" ]
stackoverflow_0007754221_file_python_regex.txt
Q: Using a file to store optparse arguments I've been using optparse for a while now, and would like to add the ability to load the arguments from a config file. So far the best I can think of is a wrapper batch script with the arguments hardcoded... seems clunky. What is the most elegant way to do this? A: I agr...
Using a file to store optparse arguments
I've been using optparse for a while now, and would like to add the ability to load the arguments from a config file. So far the best I can think of is a wrapper batch script with the arguments hardcoded... seems clunky. What is the most elegant way to do this?
[ "I agree with S.Lott's idea of using a config file, but I'd recommend using the built-in ConfigParser (configparser in 3.0) module to parse it, rather than a home-brewed solution.\nHere's a brief script that illustrates ConfigParser and optparse in action.\nimport ConfigParser\nfrom optparse import OptionParser\n\n...
[ 23, 7, 4, 3, 2, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0001880404_optparse_python.txt
Q: Shortest Way to Assign "A or B" to a Variable in Python? Hello Python experts, I am wondering if there is any shorter way to assign a value "A" to a variable if "A" is True (i.e. exists) and "B" if not. Suppose I have: mydict = {'a': 'apple', 'b': 'banana', 'c': 'Cherry'} Then, as I understand, the shortest (well...
Shortest Way to Assign "A or B" to a Variable in Python?
Hello Python experts, I am wondering if there is any shorter way to assign a value "A" to a variable if "A" is True (i.e. exists) and "B" if not. Suppose I have: mydict = {'a': 'apple', 'b': 'banana', 'c': 'Cherry'} Then, as I understand, the shortest (well, one-line) way of assigning a value that does not exist as a ...
[ "In this particular case (getting an item from a dictionary), there's a shortcut available - the get method, which allows a default value.\nmyvar = mydict.get('m', 'Melon')\n\n", "I would consider the use of the get() method to be an improvement on the if/else version.\nmyvar = mydict.get('m', 'melon')\n\n", "Y...
[ 5, 4, 3 ]
[]
[]
[ "python", "ruby", "ternary_operator" ]
stackoverflow_0007755276_python_ruby_ternary_operator.txt
Q: Python model object validation I'm writing an interface to be used by two applications. This interface should use some DoSomethingRequest and DoSomethingResponse classes to do the communication. Is there any library that does some model validation, for example like Django's Model? I basically want to be able to sa...
Python model object validation
I'm writing an interface to be used by two applications. This interface should use some DoSomethingRequest and DoSomethingResponse classes to do the communication. Is there any library that does some model validation, for example like Django's Model? I basically want to be able to say something like: Object A must have...
[ "If you want to enforce interfaces, or use design-by-contract, then you probably want the zope.interface library. Despite the name, which reflects its origins in Zope, it's not actually tied to that framework at all and is quite usable outside.\n", "I think decorators could be used for this.\ncheck this link\nCo...
[ 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007754589_python.txt
Q: python help() function shortcuts What are shortcuts of Python help() function used in Python interpreter? I'm interested for help content that doesn't fit to window and shows "-- More --" at the bottom. I found q quits help(). What is a shortcut to show the whole article w/o pressing Enter many times? A: On my ...
python help() function shortcuts
What are shortcuts of Python help() function used in Python interpreter? I'm interested for help content that doesn't fit to window and shows "-- More --" at the bottom. I found q quits help(). What is a shortcut to show the whole article w/o pressing Enter many times?
[ "On my (Linux) machine help seems to be using \"less\". Press \"h\" when in help to see a complete list of shortcuts/commands. I'm not sure if this will work on Windows though.\n", "The help() function in Python interactive interpreter is based on the pydoc module. There's a function called getpager() in this mod...
[ 4, 3, 2 ]
[]
[]
[ "python", "shortcut" ]
stackoverflow_0007755325_python_shortcut.txt
Q: Monkey patching and dispatching I have the following situation, a module called enthought.chaco2 and I have many imports, like from enthought.chaco.api import .. so what's the quickest way to add chaco.api and make it dispatch to the correct one? I tried a few things, for example: import enthought.chaco2 as c2 imp...
Monkey patching and dispatching
I have the following situation, a module called enthought.chaco2 and I have many imports, like from enthought.chaco.api import .. so what's the quickest way to add chaco.api and make it dispatch to the correct one? I tried a few things, for example: import enthought.chaco2 as c2 import enthought enthought.chaco = c2 b...
[ "What is the behavior you're looking for?\nYou could use from enthought.chaco import api as ChacoApi and then address any content from the module through ChacoApi, like ChacoApi.foo() or chaco_class = ChacoApi.MyClass().\nYou could use (and that's not recommended) from enthought.chaco.api import * and have all the ...
[ 0 ]
[]
[]
[ "monkeypatching", "python" ]
stackoverflow_0007755504_monkeypatching_python.txt
Q: Flatten OpenCV/Numpy Array I've loaded an RGB image with PIL/OpenCV, and I'd like convert all its channels into a single 1x(3*width*height) sequence into order to feed it to an ANN. I found I can simply do: rlist = [] glist = [] blist = [] for i in xrange(im.width): for j in xrange(im.height): r,g,b = ...
Flatten OpenCV/Numpy Array
I've loaded an RGB image with PIL/OpenCV, and I'd like convert all its channels into a single 1x(3*width*height) sequence into order to feed it to an ANN. I found I can simply do: rlist = [] glist = [] blist = [] for i in xrange(im.width): for j in xrange(im.height): r,g,b = im[i,j] rlist.append(r) ...
[ "As a quick example:\nimport Image\nimport numpy as np\n\nim = Image.open('temp.png')\ndata = np.array(im)\nflattened = data.flatten()\n\nprint data.shape\nprint flattened.shape\n\nThis yields:\n(612, 812, 4)\n(1987776,)\n\nAlternately, instead of calling data.flatten(), you could call data.reshape(-1). -1 is used...
[ 8 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0007755684_numpy_opencv_python.txt
Q: is searching a python list for an empty list inaccurate? Why can b list be found in some_list even though it's not in some_list? >>> a = [] >>> b = [] >>> a is b False >>> some_list = [0, 1, 2, 3, a] >>> some_list.index(b) 4 A: .index returns 4th position because it compares a and b, two empty lists. They are eq...
is searching a python list for an empty list inaccurate?
Why can b list be found in some_list even though it's not in some_list? >>> a = [] >>> b = [] >>> a is b False >>> some_list = [0, 1, 2, 3, a] >>> some_list.index(b) 4
[ ".index returns 4th position because it compares a and b, two empty lists. They are equal. If you do a is b, it compares the memory addresses of objects, and they are different, that's why this expression evaluates to False.\nIn [1]: a = []\nIn [2]: b = []\nIn [3]: a == b\nOut[3]: True\n\n", "Python's list.index ...
[ 7, 6, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007755696_list_python.txt
Q: Python-Boto: Check the Array Position Availability I have try to get a specific list of AMI and store it in the array list. usubuntuamilist = {} for i, image in enumerate(conn.get_all_images()): if image.location.startswith("ubuntu-images-us/ubuntu-lucid-10.04-i386-serve"): print "%s - %s" % (i, image....
Python-Boto: Check the Array Position Availability
I have try to get a specific list of AMI and store it in the array list. usubuntuamilist = {} for i, image in enumerate(conn.get_all_images()): if image.location.startswith("ubuntu-images-us/ubuntu-lucid-10.04-i386-serve"): print "%s - %s" % (i, image.name) usubuntuamilist[i] = image.name How can c...
[ "Why not just:\nif image.location.startswith(\"ubuntu-images-us/ubuntu-lucid-10.04-i386-serve\"):\n # As before...\nelse:\n usubuntuamilist[i] = None\n\nThen, checking is the image name is None is simple, no?\n" ]
[ 1 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "arrays", "boto", "python" ]
stackoverflow_0007720920_amazon_ec2_amazon_web_services_arrays_boto_python.txt
Q: Post to Tornado server I am trying to post to my Tornado Web Server but keep getting a 405 Error. Not sure what is going wrong. I am fairly new to python but I have been searching up on this for about a month and finally decided to give it a go. Tornado Web Server: import tornado.httpserver import tornado.ioloop i...
Post to Tornado server
I am trying to post to my Tornado Web Server but keep getting a 405 Error. Not sure what is going wrong. I am fairly new to python but I have been searching up on this for about a month and finally decided to give it a go. Tornado Web Server: import tornado.httpserver import tornado.ioloop import tornado.options import...
[ "You will have to change the LoginHandler to accept a POST request.\nLike so:\nclass LoginHandler(tornado.web.RequestHandler):\n def post(self):\n email_address = self.get_argument('email', '')\n password = self.get_argument('password', '')\n\n if not email_address:\n login_respon...
[ 23 ]
[]
[]
[ "post", "python", "tornado", "web" ]
stackoverflow_0007754936_post_python_tornado_web.txt
Q: Is this a bug in os or can someone explain to me what's going on? >>> os.path.realpath("C:") 'C:\\PythonApp' >>> os.path.realpath("E:") 'E:\\' My current directory is C:\PythonApp. It seems os defaults to the current directory if I give it an unknown path name for something like os.listdir so why does it work for...
Is this a bug in os or can someone explain to me what's going on?
>>> os.path.realpath("C:") 'C:\\PythonApp' >>> os.path.realpath("E:") 'E:\\' My current directory is C:\PythonApp. It seems os defaults to the current directory if I give it an unknown path name for something like os.listdir so why does it work for E and not C?
[ "Compare what you get with:\n os.path.realpath(\"C:\\\\\")\n\nWindows saves a \"current directory\" for each drive, and C: (without the slash) refers to that, not the root of the drive.\nThe python docs for os.path.join mention this:\n\nNote that on Windows, since there is a current directory for each drive, os.pat...
[ 6 ]
[]
[]
[ "operating_system", "python" ]
stackoverflow_0007756072_operating_system_python.txt
Q: "List index out of range" error in Python I am making a simple Checkers again. And, in order to keep track of all the locations for the checkers to move to, I created a list to add all of the locations. Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), \ (370, 10), (430, 10), (1...
"List index out of range" error in Python
I am making a simple Checkers again. And, in order to keep track of all the locations for the checkers to move to, I created a list to add all of the locations. Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), \ (370, 10), (430, 10), (10, 70), (130, 70), (190, 70), (250, 70), \ ...
[ "You have a very basic understanding problem:\n>>> Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), (370, 10), (430, 10), (10, 70), (130, 70), (190, 70), (250, 70), (310, 70), (370, 70), (430, 70), (10, 130), (70, 130), (130, 130), (190, 130), (250, 130), (310, 130), (370, 130), (430, 13...
[ 6, 3, 2, 1, 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0007756069_pygame_python.txt
Q: Using SIgnals with variables PyQT Hello I am trying to figure out how to get data from my worker class. I have server code running as a threaded process and I want to send some data from my server to the pyQT GUI I have a variable in my gui code self.mytext = QTextEdit() and in my server code I send the data...
Using SIgnals with variables PyQT
Hello I am trying to figure out how to get data from my worker class. I have server code running as a threaded process and I want to send some data from my server to the pyQT GUI I have a variable in my gui code self.mytext = QTextEdit() and in my server code I send the data to the GUI. Only problem is I don't ...
[ "First, have look at how Signals/Slots concept works. Original Qt documentation for is a good start. Then if you are working with PyQt 4.5+, try to use the new style signals and slots. They are more Pythonic.\nHere is how a small example might work (omitting the obvious parts).\nclass myWorker(QtCore.QThread):\n ...
[ 3, 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007756336_pyqt_python.txt
Q: Python Filter/ compare every second value in a sequence Possible Duplicate: How to make a function that counts how many times each element is equal to 2 elements to its right I need help with the prompt below. For some reason I keep on getting a "'int' object is not subscriptable" errpr and don't really know ho...
Python Filter/ compare every second value in a sequence
Possible Duplicate: How to make a function that counts how many times each element is equal to 2 elements to its right I need help with the prompt below. For some reason I keep on getting a "'int' object is not subscriptable" errpr and don't really know how to fix it. I have a feeling that it has something to do w...
[ "In [4]: word = \"mississippi\" \nIn [5]: word_list = [w for w in xrange(len(word) - 2) if word[w] == word[w + 2]]\nIn [6]: print len(word_list)\n1\n\nIn [7]: word = \"evening\"\nIn [8]: word_list = [w for w in xrange(len(word) - 2) if word[w] == word[w + 2]]\nIn [9]: print len(word_list)\n2\n\n", "You can't d...
[ 0, 0 ]
[]
[]
[ "filter", "python" ]
stackoverflow_0007756310_filter_python.txt
Q: How do I parse HTML which includes named ISO-8859-1 entities with Python? I summarize: minidom appears not to like 8859 named entities; what's an appropriate resolution? Here's code which illustrates my situation: sample = """ <html> <body> <h1>Un ejemplo</h1> <p>Me llamo Juan Fulano y Hern&aacu...
How do I parse HTML which includes named ISO-8859-1 entities with Python?
I summarize: minidom appears not to like 8859 named entities; what's an appropriate resolution? Here's code which illustrates my situation: sample = """ <html> <body> <h1>Un ejemplo</h1> <p>Me llamo Juan Fulano y Hern&aacute;ndez.</p> </body> </html> """ sample2 = sample.replace("&aacute;", "&#...
[ "xml.dom.minidom is an XML parser, not an HTML parser. Therefore, it doesn't know any HTML entities (only those which are common to both XML and HTML: &quot;, &amp;, &lt;, &gt; and &apos;).\nTry BeautifulSoup.\n" ]
[ 10 ]
[]
[]
[ "html_parsing", "python", "xhtml" ]
stackoverflow_0007756817_html_parsing_python_xhtml.txt
Q: PyQt: QGraphicsItemAnimation with setPosAt I got a little problem since I'm unable to create a simple setPos animation by overriding the setPos method like this: def setPos(self, pos): ...
PyQt: QGraphicsItemAnimation with setPosAt
I got a little problem since I'm unable to create a simple setPos animation by overriding the setPos method like this: def setPos(self, pos): ...
[ "@robe: QPropertyAnimation requires the declaring class to be an QObject and I believe QGraphicsItem is not.\n", "Why not use QPropertyAnimation?. With this class you can create animations for any properties of objects.\n QPropertyAnimation * animationPos = new QPropertyAnimation(Object, propertyName);\n\n ani...
[ 1, 0 ]
[]
[]
[ "pyqt", "python", "qgraphicsitem" ]
stackoverflow_0006454663_pyqt_python_qgraphicsitem.txt
Q: account(s) management over multiple tenants i have an app with multiple tenants on GAE. over the 'master' (which is a tenant on its own) i let people register and create a subapp/tenant where the creator is the owner of the app. what is the best way to manage the user accounts? lets say USER_A creates APP_A and U...
account(s) management over multiple tenants
i have an app with multiple tenants on GAE. over the 'master' (which is a tenant on its own) i let people register and create a subapp/tenant where the creator is the owner of the app. what is the best way to manage the user accounts? lets say USER_A creates APP_A and USER_B creates APP_B. so there are 2 users and 2 ...
[ "If 'user identity' can span tenants (your apps), then keep user entities in a common namespace (the default namespace works fine for that, and that's the default when a request begins). Anything specific to a tenant (e.g., what authorization a user identity has for a specific tenant) can be stored where it is most...
[ 2 ]
[]
[]
[ "google_app_engine", "namespaces", "python", "user_accounts" ]
stackoverflow_0007756132_google_app_engine_namespaces_python_user_accounts.txt
Q: How to split a row into different collections with each store the _id of the first collection as reference Given the following row with four attributes: { att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"} I want to store this row into two collections in MongoDB. The _id of the collectionA will be used a...
How to split a row into different collections with each store the _id of the first collection as reference
Given the following row with four attributes: { att1 : "att1", att2 : "att2", att3 : "att3", att4 : "att4"} I want to store this row into two collections in MongoDB. The _id of the collectionA will be used as a foreign key in relational DB. How to efficiently implement this in MongoDB with pymongo? collectionA { "...
[ "The driver is actually responsible for generating the ObjectId value, so it's fairly straightforward (below I assume your database is stored in the python variable 'db'):\nimport bson\n\nmyrow = { att1 : \"att1\", att2 : \"att2\", att3 : \"att3\", att4 : \"att4\"}\n\nref_id = bson.ObjectId()\ndb.collectionA.insert...
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0007746232_mongodb_pymongo_python.txt
Q: open (and maintain) remote connection with python I'm using Python to transfer (via scp) and database a large number of files. One of the servers I transfer files to has odd ssh config rules to stop too many ssh requests from a single location. The upshot of this is that my python script, currently looping throu...
open (and maintain) remote connection with python
I'm using Python to transfer (via scp) and database a large number of files. One of the servers I transfer files to has odd ssh config rules to stop too many ssh requests from a single location. The upshot of this is that my python script, currently looping through files and copying via os.system, hangs after a few f...
[ "You probably want to look into the paramiko module.\nThere's a Copy files over SSH using paramiko recipe using it that might be helpful.\n", "Check out SFTP in the Python module Paramiko. You can do multiple file transfers in a single session.\n", "This is not really python specific, but it probably depends o...
[ 2, 1, 0 ]
[]
[]
[ "python", "scp", "sockets", "ssh" ]
stackoverflow_0007757059_python_scp_sockets_ssh.txt
Q: Refreshing panel contents in wxPython What is the approach to update widgets in a wxPanel based on events from other controls on same panel? Scenario 1 is updating the list of a comboBox based on what has been selected from another comboBox , where both are in same panel. Scenario 2 is showing a new control/widget...
Refreshing panel contents in wxPython
What is the approach to update widgets in a wxPanel based on events from other controls on same panel? Scenario 1 is updating the list of a comboBox based on what has been selected from another comboBox , where both are in same panel. Scenario 2 is showing a new control/widget in a panel based on an event. Basically cr...
[ "Scenario 1\nTo change the choices of a combobox self.cbx you can use any of the following methods: \nself.cbx.SetItems(choices) where choices is the full list of choices.\nself.cbx.SetString(n, string) that sets the string at position n.\nInsertItems(items, pos) Inserts the list of strings in the items argument in...
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007755607_python_wxpython.txt
Q: Why do I get "Too many indexed properties for entity" error just for 18 items in the list? (Python) I have a list property tag_list = db.StringListProperty() This has been working fine so far, but today when I tried to write a list with 18 items I got the Too many indexed properties for entity: error. I think thi...
Why do I get "Too many indexed properties for entity" error just for 18 items in the list? (Python)
I have a list property tag_list = db.StringListProperty() This has been working fine so far, but today when I tried to write a list with 18 items I got the Too many indexed properties for entity: error. I think this is a case of "exploding indexes." This is my query: query = Main.all() query.filter("url =", url) query...
[ "This is because of exploding indexes.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007757230_google_app_engine_python.txt
Q: Catch exception throw from inside of the with statement zip_file_name = "not_exist.py" try: with zipfile.ZipFile(zip_file_name) as f_handle: print("open it successfully") except (zipfile.BadZipfile, zipfile.LargeZipFile), e: print(e) Is this the correct way to handle exception throw by a with st...
Catch exception throw from inside of the with statement
zip_file_name = "not_exist.py" try: with zipfile.ZipFile(zip_file_name) as f_handle: print("open it successfully") except (zipfile.BadZipfile, zipfile.LargeZipFile), e: print(e) Is this the correct way to handle exception throw by a with statement?
[ "Yes, this is how you would want to handle exceptions from inside a with statement. ContextManagers (that implement the behavior behind the with statement) can handle exceptions but should only do so to properly clean up resources used by the object. \nHere's a snippet from the relevant documentation:\n\nIf BLOCK r...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007757317_python.txt
Q: How to make this page reload on login / logout? I tried to make the user variable available serveside and now I've noticed that my page behaves the way I want it if I reload: So how can I force the page to reload at facebook connect / disconnect? Any other idea about this code? I tried the obvious javascript but ...
How to make this page reload on login / logout?
I tried to make the user variable available serveside and now I've noticed that my page behaves the way I want it if I reload: So how can I force the page to reload at facebook connect / disconnect? Any other idea about this code? I tried the obvious javascript but that created a loop. Can you help me? Thanks {% load ...
[ "If your page content has dependencies on events that occur after the pageload (ie Facebook login/logout) your best bet may be to use jQuery + ajax to load and/or reload the dependent elements separately.\n" ]
[ 1 ]
[]
[]
[ "django", "facebook", "facebook_graph_api", "google_app_engine", "python" ]
stackoverflow_0007747687_django_facebook_facebook_graph_api_google_app_engine_python.txt
Q: numpy ndarrays: row-wise and column-wise operations If I wanted to apply a function row-wise (or column-wise) to an ndarray, do I look to ufuncs (doesn't seem like it) or some type of array broadcasting (not what I'm looking for either?) ? Edit I am looking for something like R's apply function. For instance, appl...
numpy ndarrays: row-wise and column-wise operations
If I wanted to apply a function row-wise (or column-wise) to an ndarray, do I look to ufuncs (doesn't seem like it) or some type of array broadcasting (not what I'm looking for either?) ? Edit I am looking for something like R's apply function. For instance, apply(X,1,function(x) x*2) would multiply 2 to each row of X...
[ "First off, many numpy functions take an axis argument. It's probably possible (and better) to do what you want with that sort of approach.\nHowever, a generic \"apply this function row-wise\" approach would look something like this:\nimport numpy as np\n\ndef rowwise(func):\n def new_func(array2d, **kwargs):\n ...
[ 16 ]
[]
[]
[ "arrays", "multidimensional_array", "numpy", "python" ]
stackoverflow_0007757313_arrays_multidimensional_array_numpy_python.txt
Q: Fitting a 3d points of an arc to a circle (regression in Python) I am relatively new to python. My problem is as follows I have a set of noisy data points (x,y,z) on an arbitrary plane that forms a 2d arc. I would like a best fit circle through these points and return: center (x,y,z), radius, and residue. How do ...
Fitting a 3d points of an arc to a circle (regression in Python)
I am relatively new to python. My problem is as follows I have a set of noisy data points (x,y,z) on an arbitrary plane that forms a 2d arc. I would like a best fit circle through these points and return: center (x,y,z), radius, and residue. How do I go about this problem using scipy in python. I could solve this usin...
[ "The scipy-cookbook has a long section on fitting circles:\nhttp://www.scipy.org/Cookbook/Least_Squares_Circle\n" ]
[ 5 ]
[]
[]
[ "geometry", "least_squares", "python", "regression", "scipy" ]
stackoverflow_0007747440_geometry_least_squares_python_regression_scipy.txt
Q: IronPython 3 compatibility I love the Python language and mainly use the standard CPython 3.+ version for simple scripting and as an algorithm sandbox. Sometimes I need .NET intergration, so I use IronPython which is now in 2.7 version. I like 3.+ better and am therefore reluctant to use the older 2.7. Is there a...
IronPython 3 compatibility
I love the Python language and mainly use the standard CPython 3.+ version for simple scripting and as an algorithm sandbox. Sometimes I need .NET intergration, so I use IronPython which is now in 2.7 version. I like 3.+ better and am therefore reluctant to use the older 2.7. Is there any info on when will it be relea...
[ "IronPython has one big step towards Py3k support - its strings are already unicode. Many of the native modules are already in place because they were backported to Python 2.7. The re-arranged standard library is free because it's just copied from CPython.\nThe time-consuming part are the parser changes such as fun...
[ 19, 6 ]
[]
[]
[ "ironpython", "python", "python_3.x" ]
stackoverflow_0007751767_ironpython_python_python_3.x.txt
Q: Python tempfile: broken or am I doing it wrong? For a small python script I would like to use a temporary file with the tempfile module. Somehow it does not give the expected behavior and I don't know what I am doing wrong or if this is a bug: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel...
Python tempfile: broken or am I doing it wrong?
For a small python script I would like to use a temporary file with the tempfile module. Somehow it does not give the expected behavior and I don't know what I am doing wrong or if this is a bug: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "l...
[ "I just reproduced this behavior in Python 2.7.1 on Windows XP.\nThis appears to be a bug that only occurs when you attempt to read without seeking first.\nThat is:\n>>> tmp.write('test')\n>>> tmp.seek(0)\n>>> tmp.read()\n'test'\n\nvs.\n>>> tmp.write('test')\n>>> tmp.read()\n'x\\x01\\x98\\x00pfile.pyR\\x05\\x00\\x0...
[ 8, 0 ]
[]
[]
[ "python", "temporary_files" ]
stackoverflow_0007757663_python_temporary_files.txt
Q: What is the difference between Python 3.2 and 3.1? newb coder here I have decided to dive headfirst into python and discovered there are different versions of python such as Python 3.2, 3.1 etc. Could someone please tell me if there is any difference? if I learn an older version would i have to re-learn a newer ve...
What is the difference between Python 3.2 and 3.1?
newb coder here I have decided to dive headfirst into python and discovered there are different versions of python such as Python 3.2, 3.1 etc. Could someone please tell me if there is any difference? if I learn an older version would i have to re-learn a newer version or is it just an update to the libraries and stuff...
[ "Check out the Python 3.2 release notes for specifics. You shouldn't notice any syntax differences or issues between 3.2 and 3.1, especially if you are just beginning. You shouldn't be worried about learning one then having to learn the other, they are basically the same. \nAlso, Python is very good about being bac...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007758011_python.txt
Q: Summing the number of instances a string is generated in iteration Working in python 2.7. I'm trying to work my way up to plotting a random walk. But first I'm having some trouble summing the number of results I get from a random generator. The first piece of code: def random_pick(some_list, probabilities): x = ra...
Summing the number of instances a string is generated in iteration
Working in python 2.7. I'm trying to work my way up to plotting a random walk. But first I'm having some trouble summing the number of results I get from a random generator. The first piece of code: def random_pick(some_list, probabilities): x = random.uniform(0,1) cumulative_probability = 0.0 for item, item_probabilit...
[ "num_hits = 0\nnum_outs = 0\nfor i in range(1, atBats):\n if random_pick(a,b) == 'Hit':\n num_hits += 1\n else:\n num_outs += 1\nprint num_hits, num_outs\n\n", "To be honest, I am struggling to follow the logic of your code (it's been a long day), but here are a couple of pointers:\n1) When yo...
[ 2, 2 ]
[]
[]
[ "iteration", "python", "random", "sum" ]
stackoverflow_0007758038_iteration_python_random_sum.txt
Q: How to compare two different files line by line and write the difference in third file? I would like to compare two text files which have three columns each. One file has 999 rows and another has 757 rows. I want the different 242 rows to be stored in a different file. I created the first file (999 rows) using a r...
How to compare two different files line by line and write the difference in third file?
I would like to compare two text files which have three columns each. One file has 999 rows and another has 757 rows. I want the different 242 rows to be stored in a different file. I created the first file (999 rows) using a random network generator (999 rows are edges with third column being weight between first, sec...
[ "The best general-purpose option if you're on a *nix system is just to use:\nsort filea fileb | uniq -u\n\nBut if you need to use Python:\nYour code reopens the inner file in every iteration of the outer file. Open it outside the loop.\nUsing a nested loop is less efficient than looping over the first storing the ...
[ 7 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007757626_file_python.txt
Q: Compiling with Py2Exe - Black Box Error When trying to compile a GUI program using Py2Exe, whenever I load the GUI, a black box appears behind it. Is there anyway to prevent this? A: In your py2exe script, specify windows=['myscript.py'], instead of console=['myscript.py'], Like so: setup( windows=['mysc...
Compiling with Py2Exe - Black Box Error
When trying to compile a GUI program using Py2Exe, whenever I load the GUI, a black box appears behind it. Is there anyway to prevent this?
[ "In your py2exe script, specify windows=['myscript.py'], instead of console=['myscript.py'],\nLike so:\nsetup(\n windows=['myscript.py'],\n options={\n \"py2exe\":{\n \"unbuffered\": True,\n \"optimize\": 2,\n }\n }\n)\...
[ 2, 2 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0007758260_py2exe_python.txt
Q: Connecting Maya 2011 with Mysqldb I am using Maya 2011(64bit) and MySQL 5.5 (64 bit) in Windows 7 (64 bit) machine. I tried to connect maya with Mysqldb through python. So i copied the connector files into maya\python\lib\site packages. I was able to import MYsqldb module without any error. But when i tried call ...
Connecting Maya 2011 with Mysqldb
I am using Maya 2011(64bit) and MySQL 5.5 (64 bit) in Windows 7 (64 bit) machine. I tried to connect maya with Mysqldb through python. So i copied the connector files into maya\python\lib\site packages. I was able to import MYsqldb module without any error. But when i tried call the cursor object (for querying), I fou...
[ "You are not returning anything from mysql_connect function. So it returns None. When you do:\ndb = mysql_connect(\"localhost\", “root”, “test”, “mydbt\")\n\ndb becomes None. Try changing:\ndb = mb.connect(host=hostname,user=username,passwd=password,db=dbname)\n\nwith\nreturn mb.connect(host=hostname,user=username,...
[ 1, 0 ]
[]
[]
[ "maya", "mysql", "python" ]
stackoverflow_0007758224_maya_mysql_python.txt
Q: "growing" (appending to) a sequence object In Matlab, this type of algorithm ("growing arrays") is advised against mine = [] for i=1:100, mine = [mine,randn(1)] end whereas it seems that many examples for Python show this kind of algorithm (this is a really bad example though): import numpy.random as rand mi...
"growing" (appending to) a sequence object
In Matlab, this type of algorithm ("growing arrays") is advised against mine = [] for i=1:100, mine = [mine,randn(1)] end whereas it seems that many examples for Python show this kind of algorithm (this is a really bad example though): import numpy.random as rand mine = [] for i in range(100): mine.append(ran...
[ "The difference is that:\n\nIn MATLAB, every iteration of your loop re-allocates the matrix to increase the size by one and copies the entire contents into the newly allocated space.\nPython lists don't work like that. More space is allocated than is needed at any given point and this allocated space grows in a man...
[ 7, 4, 2, 2 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0007757573_matlab_python.txt
Q: What else exception we should catch for ZipFile.open I am using Python 2.7. Based on the document ZipFile.open, I am not able to find which exception should be caught when we call the ZipFile.open. try: with zipfile.ZipFile(zip_file_name, "r") as f_handle: for data_file_name in f_handle.na...
What else exception we should catch for ZipFile.open
I am using Python 2.7. Based on the document ZipFile.open, I am not able to find which exception should be caught when we call the ZipFile.open. try: with zipfile.ZipFile(zip_file_name, "r") as f_handle: for data_file_name in f_handle.namelist(): try: with f_...
[ "Do you need to catch exceptions at all? Your code shows catching RuntimeError: what will you do if that exception is raised? Generally, the best thing is to not catch exceptions unless you know what you might do about them.\n" ]
[ 3 ]
[]
[]
[ "exception", "python", "zip" ]
stackoverflow_0007758608_exception_python_zip.txt
Q: Django : provide dynamically generated data as attachment on button press Problem Overview: I am creating a Django-based client with the intent of returning data from a web service. The goal of this project is to return data to the user from the web service based on the values selected by the user in a form. Upon ...
Django : provide dynamically generated data as attachment on button press
Problem Overview: I am creating a Django-based client with the intent of returning data from a web service. The goal of this project is to return data to the user from the web service based on the values selected by the user in a form. Upon the form submit, a query string is generated, sent to the web service and the p...
[ "Solution:\nAfter looking at the problem a little further and talking to a colleague about it, it seems as though my problem lies in trying to pass the response object to the javascript. For those interested, I solved the problem with a little careful re-routing of the data.\nviews.py\nIn my views.py I added a coup...
[ 4, 1 ]
[]
[]
[ "django", "httpresponse", "javascript", "python", "templates" ]
stackoverflow_0007732990_django_httpresponse_javascript_python_templates.txt
Q: Display number int in Python How to display numbers integer in python ? For example: number1 = raw_input('Write one number: ') number2 = raw_input('Write other number: ') result = number1 + number2 print "The sum of the numbers is: %d" % result # here, display the result of the operatio n. A: You want result ...
Display number int in Python
How to display numbers integer in python ? For example: number1 = raw_input('Write one number: ') number2 = raw_input('Write other number: ') result = number1 + number2 print "The sum of the numbers is: %d" % result # here, display the result of the operatio n.
[ "You want \nresult = int(number1) + int(number2)\n\nraw_input returns strings.\n", "raw_input returns strings. If you mean for them to be integers, then use int(x) to convert them to ints.\n", "You have to convert the inputted strings into numbers:\nresult = int(number1) + int(number2)\n\n", "Like this;\nIn ...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007758776_python.txt
Q: Shorten sequence of if statements I have this code. c = getch() if c == "r": return randrange(101, len(mylist) - 1) if c == "u": return 100 if c == "b": return -2 ...
Shorten sequence of if statements
I have this code. c = getch() if c == "r": return randrange(101, len(mylist) - 1) if c == "u": return 100 if c == "b": return -2 if c == "w": retur...
[ "You can use a dictionary:\n# Special case.\nif c == \"r\": \n return randrange(101, len(list) - 1) \n\n# This is constant. It could be generated once at program start.\nd = { 'u' : 100, ...., 'p' : -9 }\n\n# This covers the majority of the cases....
[ 8, 2, 1 ]
[]
[]
[ "coding_style", "if_statement", "python" ]
stackoverflow_0007757971_coding_style_if_statement_python.txt
Q: Issues converting python list for mongodb import I am new to python, mongodb and sql. I am working in Eclipse 3.7.1 on a Mac 10.7. I am using a pyodbc driver (and freeTDS) to connect to an mssql database. I am scripting in python 2.7. I want to query the mssql database and write it out to a mongo database. Where I...
Issues converting python list for mongodb import
I am new to python, mongodb and sql. I am working in Eclipse 3.7.1 on a Mac 10.7. I am using a pyodbc driver (and freeTDS) to connect to an mssql database. I am scripting in python 2.7. I want to query the mssql database and write it out to a mongo database. Where I stumble is that the query output is in a python list ...
[ "this is how i got it to work:\n\npyodbc to query mssql database\npython dict and zip to convert list of tuples into key-value dictionary pairs\npymongo to save it as collection\n#===============================================================================\n# 1. MSSQL QUERY WITH PYODBC\n#========================...
[ 2, 0 ]
[]
[]
[ "mongodb", "python", "sql_server" ]
stackoverflow_0007747192_mongodb_python_sql_server.txt
Q: Choosing format in pack() using struct module in python I am trying to convert a PHP code to python. All values are send in network byte order (big endian). Basically, the REQUEST in protocol specification is and response is Corresponding PHP Code (corresponding DOC) is: $transaction_id = mt_rand(0,65535); $c...
Choosing format in pack() using struct module in python
I am trying to convert a PHP code to python. All values are send in network byte order (big endian). Basically, the REQUEST in protocol specification is and response is Corresponding PHP Code (corresponding DOC) is: $transaction_id = mt_rand(0,65535); $current_connid = "\x00\x00\x04\x17\x27\x10\x19\x80"; $fp = fso...
[ "The php pack function format N means unsigned 32-bit big-endian integer.\nThe corresponding Python struct.pack format is >L.\nThe images you posted for the protocol show the connection_id should be 64-bit (unsigned) integer: Python struct.pack format Q.\nSo:\nclisocket = socket.socket(socket.AF_INET, socket.SOCK_D...
[ 3, 0 ]
[]
[]
[ "network_programming", "php", "python", "sockets" ]
stackoverflow_0007758448_network_programming_php_python_sockets.txt
Q: Trying to format returned _set I am trying to populate my form with a list of plans. Here is my unicode for the Plans model def __unicode__(self): label = "ID: %s, Member(s): %s, Plan Type: %s" % (self.id, self.get_owners(), self.plan_type) return unicode(label) Now I call get_owners which is shown belo...
Trying to format returned _set
I am trying to populate my form with a list of plans. Here is my unicode for the Plans model def __unicode__(self): label = "ID: %s, Member(s): %s, Plan Type: %s" % (self.id, self.get_owners(), self.plan_type) return unicode(label) Now I call get_owners which is shown below: def get_owners(self): owners ...
[ "You're just returning the raw queryset from get_owners, and Python is calling repr() on that to insert it into the string.\nThe best bet is to do the formatting within get_owners:\ndef get_owners(self):\n owners = ...\n return u\", \".join(unicode(o) for o in owners)\n\n", "Your get_owners method is doing ...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "python" ]
stackoverflow_0007758914_django_django_models_django_templates_python.txt
Q: Python - ssh with password to foreign computer without using non-built-in modules Before you down vote this, let me say that I've read ALOT of questions on this subject on SO and haven't found the answer. This one has the closest thing to what I need though on the answer by "Neil". What is the simplest way to SSH...
Python - ssh with password to foreign computer without using non-built-in modules
Before you down vote this, let me say that I've read ALOT of questions on this subject on SO and haven't found the answer. This one has the closest thing to what I need though on the answer by "Neil". What is the simplest way to SSH using Python? I would like to find a way to log into another host using ssh, providing...
[ "This code uses Popen.communicate() to run a command. As described in chapter 17 of the Python Library Reference, communicate() opens pipes for stdin, stdout, and stderr, starts up the subprocess, and waits for the process to terminate. FYI for other readers: startupinfo is the Windows-specific way of running th...
[ 2 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0007758870_python_ssh.txt
Q: Django or python manipulate email addresses and reason about domains I want to be able to parse email addresses to isolate the domain part, and test if an email address is part of a given domain. The email module doesn't, as far as I can tell, do that. Is there anything worth using to do this other than the usual ...
Django or python manipulate email addresses and reason about domains
I want to be able to parse email addresses to isolate the domain part, and test if an email address is part of a given domain. The email module doesn't, as far as I can tell, do that. Is there anything worth using to do this other than the usual string handling and regex routines? Note: I know how to deal with python ...
[ "As per @dm03514's comment, there is a python library that does exactly this: tldextract:\n>>> import tldextract\n>>> tldextract.extract('foo@bar.baz.org.uk')\nExtractResult(subdomain='bar', domain='baz', tld='org.uk')\n\n", "With this simple script, we replace @ with @. so that our domain is terminated and the e...
[ 1, 0 ]
[]
[]
[ "django", "email", "email_validation", "python" ]
stackoverflow_0007712762_django_email_email_validation_python.txt
Q: How can I implement multiple URL parameters in a Tornado route? I'm trying to figure out how to implement a URL with up to 3 (optional) url parameters. I figured out how to do this in ASP.NET MVC 3, but the constraints of the current project eliminated it. So, here's what I'm looking for: base/{param1}/{param2}/{p...
How can I implement multiple URL parameters in a Tornado route?
I'm trying to figure out how to implement a URL with up to 3 (optional) url parameters. I figured out how to do this in ASP.NET MVC 3, but the constraints of the current project eliminated it. So, here's what I'm looking for: base/{param1}/{param2}/{param3} where param2 and param3 are optional. Is this simply a regex p...
[ "I'm not sure if there is a nice way to do it, but this should work:\nimport tornado.web\nimport tornado.httpserver\n\nclass TestParamsHandler(tornado.web.RequestHandler):\n def get(self, param1, param2, param3):\n param2 = param2 if param2 else 'default2'\n param3 = param3 if param3 else 'default3...
[ 36 ]
[]
[]
[ "python", "routing", "tornado" ]
stackoverflow_0007744454_python_routing_tornado.txt
Q: Parsing the content of a 'Requests' call only shows some json data To start here is some code: import requests import json url = r'http:\\some.url' p = requests.post(url) print p.status_code data = json.load(p) for entry in data: print entry print data The output of this program is as follows (note values ...
Parsing the content of a 'Requests' call only shows some json data
To start here is some code: import requests import json url = r'http:\\some.url' p = requests.post(url) print p.status_code data = json.load(p) for entry in data: print entry print data The output of this program is as follows (note values are sanitized): 200 a {"a":"b"} Is there a way to get value "b" applie...
[ "Assuming Python 2.x:\n>>> x = {\"a\":\"b\"}\n>>> x.values()\n['b']\n>>> x.values()[0]\n'b'\n\n" ]
[ 2 ]
[]
[]
[ "json", "python", "python_requests" ]
stackoverflow_0007759691_json_python_python_requests.txt
Q: Using totient functions - undefined issues From Python ProblemSet I would like to test the following functions but it seems that mult and coprime could not be defined. I tried importing math but that did not help. Any recommendations? >>> import itertools >>> def prime_factors(value): if value > 3: for...
Using totient functions - undefined issues
From Python ProblemSet I would like to test the following functions but it seems that mult and coprime could not be defined. I tried importing math but that did not help. Any recommendations? >>> import itertools >>> def prime_factors(value): if value > 3: for this in itertools.chain(iter([2]), xrange(3,int...
[ "If you check the documentation for the operator module, you'll find that the multiplication operator is mul.\nAlso, I believe the definition of coprime relies on definitions from previous problems.\n" ]
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007759877_function_python.txt
Q: How to define a binary string in Python in a way that works with both py2 and py3? I am writing a module that is supposed to work in both Python 2 and 3 and I need to define a binary string. Usually this would be something like data = b'abc' but this code code fails on Python 2.5 with invalid syntax. How can I wri...
How to define a binary string in Python in a way that works with both py2 and py3?
I am writing a module that is supposed to work in both Python 2 and 3 and I need to define a binary string. Usually this would be something like data = b'abc' but this code code fails on Python 2.5 with invalid syntax. How can I write the above code in a way that will work in all versions of Python 2.5+ Note: this has ...
[ "I would recommend the following:\nfrom six import b\n\nThat requires the six module, of course.\nIf you don't want that, here's another version:\nimport sys\nif sys.version < '3':\n def b(x):\n return x\nelse:\n import codecs\n def b(x):\n return codecs.latin_1_encode(x)[0]\n\nMore info.\nTh...
[ 6, 2 ]
[ "You could store the data base64-encoded.\nFirst step would be to transform into base64:\n>>> import base64\n>>> base64.b64encode(b\"\\x80\\xFF\")\nb'gP8='\n\nThis is to be done once, and using the b or not depends on the version of Python you use for it.\nIn the second step, you put this byte string into a program...
[ -3 ]
[ "python", "python_2.5", "python_3.x" ]
stackoverflow_0007755082_python_python_2.5_python_3.x.txt
Q: I'm looking for gevent for Python 2.7 for windows However gevent depends upon greenlet and the .msi version I found fails to install and the egg for 2.6 refuses to install. The msi version fails as follows. C:\Windows\system32>easy_install greenlet install_dir C:\Python27\Lib\site-packages\ Searching for greenle...
I'm looking for gevent for Python 2.7 for windows
However gevent depends upon greenlet and the .msi version I found fails to install and the egg for 2.6 refuses to install. The msi version fails as follows. C:\Windows\system32>easy_install greenlet install_dir C:\Python27\Lib\site-packages\ Searching for greenlet Reading http://pypi.python.org/simple/greenlet/ Readi...
[ "This worked for me:\n\nGrab the gevent installer from the Unofficial Windows Binaries for Python Extension Packages\nInstall greenlet from that same site\n\nAnd if you're on a 64-bit Windows 7 machine and are having trouble installing, read this too.\n", "You should ask the maintainer of greenlet to build .msi f...
[ 9, 5, 2 ]
[]
[]
[ "gevent", "greenlets", "python" ]
stackoverflow_0004867750_gevent_greenlets_python.txt
Q: in python, is there a way to find the module that contains a variable or other object from the object itself? As an example, say I have a variable defined where there may be multiple from __ import * from ____ import * etc. Is there a way to figure out where one of the variables in the namespace is defined? edit...
in python, is there a way to find the module that contains a variable or other object from the object itself?
As an example, say I have a variable defined where there may be multiple from __ import * from ____ import * etc. Is there a way to figure out where one of the variables in the namespace is defined? edit Thanks, but I already understand that import * is often considered poor form. That wasn't the question though, an...
[ "This is why it is considered bad form to use from __ import * in python in most cases. Either use from __ import myFunc or else import __ as myLib. Then when you need something from myLib it doesn't over lap something else.\nFor help finding things in the current namespace, check out the pprint library, the dir bu...
[ 5, 3, 1, 0 ]
[]
[]
[ "definition", "namespaces", "python" ]
stackoverflow_0007759290_definition_namespaces_python.txt
Q: Can user activity be captured on a unix server with bash or Python I work off a server along with a number of other people, who, because of unexplained occurrences, change files, symlinks, etc. Unfortunately, all have the same level of file system rights. Is there a straightforward way to capture activity: login/l...
Can user activity be captured on a unix server with bash or Python
I work off a server along with a number of other people, who, because of unexplained occurrences, change files, symlinks, etc. Unfortunately, all have the same level of file system rights. Is there a straightforward way to capture activity: login/logout time (I know the 'last' command shows this), files changed (delete...
[ "First, you really should lock your user accounts down on your server. But if you really want to monitor activity within the file system, you've got a couple of options. \n\nWrite a script to parse their bash history on logout, and save the log out time (poor)\nInstall iwatch, then point it at the locations to moni...
[ 1 ]
[]
[]
[ "bash", "python", "ubuntu" ]
stackoverflow_0007760027_bash_python_ubuntu.txt
Q: Python milk library: object weights issue I'm trying to use one_vs_one composition of decision trees for multiclass classification. The problem is, when I pass different object weights to a classifier, the result stays the same. Do I misunderstand something with weights, or do they just work incorrectly? Thanks fo...
Python milk library: object weights issue
I'm trying to use one_vs_one composition of decision trees for multiclass classification. The problem is, when I pass different object weights to a classifier, the result stays the same. Do I misunderstand something with weights, or do they just work incorrectly? Thanks for your replies! Here is my code: class AdaLearn...
[ "The default tree criterion, namely information gain, does not take the weights into account. If you know of a formula which would do it, I'll implement it.\nIn the meanwhile, using neg_z1_loss will do it correctly. By the way, there was a slight bug in that implementation, so you will need to use the most current ...
[ 0 ]
[]
[]
[ "classification", "machine_learning", "python" ]
stackoverflow_0007711129_classification_machine_learning_python.txt
Q: Insert python list into Postgres database I am having trouble in formatting the list for insertion using psycopg. Here is a sample of code i am trying to do. Basically I am just reading data from one table and trying to insert it into another table. Code: cur.execute("""select data from \"Table1\" where lat=-20.00...
Insert python list into Postgres database
I am having trouble in formatting the list for insertion using psycopg. Here is a sample of code i am trying to do. Basically I am just reading data from one table and trying to insert it into another table. Code: cur.execute("""select data from \"Table1\" where lat=-20.004189 and lon=-63.848004""") rows = cur.fetchall...
[ "I don't think mogrify is needed here. Use executemany and pass rows as the second argument.\ncur.executemany(\n \"\"\"INSERT INTO \"%s\" (data) VALUES (%%s)\"\"\" % (args.tableName),rows)\n\nUsing parametrized arguments helps prevent SQL injection.\nThe table name can not be parametrized, so we do have to use s...
[ 7 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0007760052_postgresql_psycopg2_python.txt
Q: Why isn't the empty string being removed from list? I'm trying to format a tab delimited txt file that has rows and columns. I'm trying to simply ignore the rows that have any empty values in it when I write to the output file. I'm doing this by len(list) method where if the length of the list equals the number ...
Why isn't the empty string being removed from list?
I'm trying to format a tab delimited txt file that has rows and columns. I'm trying to simply ignore the rows that have any empty values in it when I write to the output file. I'm doing this by len(list) method where if the length of the list equals the number of columns, then that line gets written to output file. ...
[ "I think that one of your problems is that list.remove only removes the first occurrence of the element. There could still be more empty strings in your list. From the documentation:\n\nRemove the first item from the list whose value is x. It is an error if there is no such item.\n\nTo remove all the empty strings ...
[ 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007759480_list_python.txt
Q: How do I completely uninstall Python and all its packages? I installed some packages , but I think either some of the packages corrupted or are conflicting with versions Is there a good way to just uninstall every package and python itself? A: If you just want to remove all the packages you've installed (as opp...
How do I completely uninstall Python and all its packages?
I installed some packages , but I think either some of the packages corrupted or are conflicting with versions Is there a good way to just uninstall every package and python itself?
[ "If you just want to remove all the packages you've installed (as opposed to all of Python), you'd want to nuke your site-packages directory.\nTo find it, from Python run >>> import some_package (where some_package is a package you've installed; setuptools is one you're likely to have), then run some_package.__file...
[ 2 ]
[]
[]
[ "package", "python", "uninstallation" ]
stackoverflow_0007760382_package_python_uninstallation.txt
Q: how do I know which function need to be followed by a close resource operation I am new to Python and feel confused about when I should call close. For instance, consider this example from the csv documentation. import csv with open('some.csv', 'rb') as f: reader = csv.reader(f) for row in reader: ...
how do I know which function need to be followed by a close resource operation
I am new to Python and feel confused about when I should call close. For instance, consider this example from the csv documentation. import csv with open('some.csv', 'rb') as f: reader = csv.reader(f) for row in reader: print row There is no reader.close() in the end of this task. Q> How do I find out ...
[ "Functions that return resources that need to be cleaned up will have documentation that explains that. csv.reader doesn't open a file, or otherwise create a closable resource. The open call does, but the with statement takes care of closing it for you.\n", "The only time you need to call close is when you must...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007758796_python.txt
Q: Should I remove an index with a deleted property and how? (python) This is a follow up to my earlier question. This is my model: class Main(db.Model): url = db.StringProperty() tag_list = db.StringListProperty() #total_value = db.IntegerProperty(default=0) pitch = db.TextProperty() owner = ...
Should I remove an index with a deleted property and how? (python)
This is a follow up to my earlier question. This is my model: class Main(db.Model): url = db.StringProperty() tag_list = db.StringListProperty() #total_value = db.IntegerProperty(default=0) pitch = db.TextProperty() owner = db.UserProperty() title = db.StringProperty() date = db.DateTime...
[ "You need to call appcfg with vacuum_indexes in order to delete indexes that are no longer defined in index.yaml.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007758484_google_app_engine_python.txt
Q: best way to emulate a python ie compatible browser What would be the best way to emulate a IE browser with python for scraping? I've found this script http://www.mayukhbose.com/python/IEC/index.php and was wondering if there was anything more updated out there! (that's able to fill forms) Thanks! A: If you want...
best way to emulate a python ie compatible browser
What would be the best way to emulate a IE browser with python for scraping? I've found this script http://www.mayukhbose.com/python/IEC/index.php and was wondering if there was anything more updated out there! (that's able to fill forms) Thanks!
[ "If you want to scrape, you can use a scraper module like mechanize http://wwwsearch.sourceforge.net/mechanize/\n", "Python Mechanize does exactly that:\nhttp://wwwsearch.sourceforge.net/mechanize/\nIt acts as a browser (i.e. you can go foward and backward, search and fill out a form on a retrieved page, post etc...
[ 1, 0 ]
[]
[]
[ "internet_explorer", "python", "web_scraping" ]
stackoverflow_0007760627_internet_explorer_python_web_scraping.txt
Q: Why does the "engine" capitalize this variable. Can it be hidden? The view: def GRID_ServerDropDownSearch(request): if 'r' in request.GET and request.GET['r']: r = request.GET['r'] servers = SERVERS.objects.get(name=r) drives = servers.drives_set.all()[0:] memory = servers.memory_...
Why does the "engine" capitalize this variable. Can it be hidden?
The view: def GRID_ServerDropDownSearch(request): if 'r' in request.GET and request.GET['r']: r = request.GET['r'] servers = SERVERS.objects.get(name=r) drives = servers.drives_set.all()[0:] memory = servers.memory_set.all()[0:] return render_to_response('GRID_ServerDropDownSearchR...
[ "Django derives the label for a form field from the corresponding variable name, but \"humanizes\" it. For example, a field called my_variable would translate to \"My variable\".\nThe simplest way to fix this would be to give a more human-readable name to the field:\nserver = forms.ModelChoiceField(queryset = SERVE...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007760547_django_python.txt
Q: Sort a Dictionary in Python Based on its Keys (when all keys are ints) Basically, I have a dictionary where all the keys are ints where the highest keys are at the end of the list and the lower keys are at the start (sort of like a list). Note I can't use a list for reasons I won't go into. A: Python's ordered d...
Sort a Dictionary in Python Based on its Keys (when all keys are ints)
Basically, I have a dictionary where all the keys are ints where the highest keys are at the end of the list and the lower keys are at the start (sort of like a list). Note I can't use a list for reasons I won't go into.
[ "Python's ordered dictionary is what you are looking for. For example\n>>> from collections import OrderedDict\n>>> data = {4:'str1', 19:'str2', 1:'str3', 7:'str4'}\n>>> orderedData = OrderedDict(sorted(data.items()))\n>>> orderedData\nOrderedDict([(1, 'str3'), (4, 'str1'), (7, 'str4'), (19, 'str2')])\n\nYou can s...
[ 3 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0007760837_dictionary_python_sorting.txt
Q: Extend QGraphicsItem with pyqt How can I create a class that extend QGraphicsItem to define a new kind of Item? I'm trying to do that #!/usr/bin/python import sys from PyQt4 import QtGui class Node(QtGui.QGraphicsItem): def __init__(self, parent = 0): self.setFlag(QtGui.QGraphicsItem.ItemIsMovable) ...
Extend QGraphicsItem with pyqt
How can I create a class that extend QGraphicsItem to define a new kind of Item? I'm trying to do that #!/usr/bin/python import sys from PyQt4 import QtGui class Node(QtGui.QGraphicsItem): def __init__(self, parent = 0): self.setFlag(QtGui.QGraphicsItem.ItemIsMovable) app = QtGui.QApplication(sys.argv) ...
[ "The solution is this\n#!/usr/bin/python\n\nimport sys\nfrom PyQt4 import QtGui\n\nclass Node(QtGui.QGraphicsItem):\n def __init__(self, parent = None):\n QtGui.QGraphicsItem.__init__(self,parent)\n self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)\n\napp = QtGui.QApplication(sys.argv)\n\nscene = QtG...
[ 6, 0 ]
[]
[]
[ "pyqt", "python", "qgraphicsitem" ]
stackoverflow_0003131399_pyqt_python_qgraphicsitem.txt
Q: Schema migration with south (django) and MySQL I was just going through a tutorial on django, and I followed every step, but still I get this error every time I try to migrate: The initial migration works, but trying to migrate it, I get this: root@debian:/Sites/tumblog# ./manage.py migrate blog Traceback (m...
Schema migration with south (django) and MySQL
I was just going through a tutorial on django, and I followed every step, but still I get this error every time I try to migrate: The initial migration works, but trying to migrate it, I get this: root@debian:/Sites/tumblog# ./manage.py migrate blog Traceback (most recent call last): File "manage.py", line 11, ...
[ "Are you sure adding --fake doesnt change anything ? \nmanage.py migrate blog --fake \n... or drop table 'blog_blog' manually from mysql console ;)\n", "The problem is that the tables the migration is trying to create already exist in the database. They must have been created with a syncdb (you get this if you do...
[ 3, 3, 1 ]
[]
[]
[ "django", "django_south", "mysql", "python" ]
stackoverflow_0007759746_django_django_south_mysql_python.txt
Q: list printing in formatted string in python In python to print a formatted string with ints and strings, I'd usually do : print '%d %d - %s' %(x,y, mystr) Is there anything similar for printing out a list? I have: L= [1,0,0] name = 'V' and I want the output to be : v(1,0,0) Is there anything similar to %d for ...
list printing in formatted string in python
In python to print a formatted string with ints and strings, I'd usually do : print '%d %d - %s' %(x,y, mystr) Is there anything similar for printing out a list? I have: L= [1,0,0] name = 'V' and I want the output to be : v(1,0,0) Is there anything similar to %d for list objects?
[ "If you want complete control how the list gets rendered, you'll have to format it separately.\nIn your case, the code would be something like:\nitems = [1,0,0]\nname = 'V'\nformatted = '%s(%s)' % (\n name,\n ','.join(str(it) for it in items)\n)\n\n", "You can always subclass list, then overwrite the repr f...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007760869_python.txt
Q: Q_ENUMS in PyQt4 I would like to use facilities of enumeration of Qt. I saw in documentation of the module of QtCore there is a macros of Q_ENUMS, but I do not know and information how to use him. A: In python (and PyQt), the way to create an enum is like this: class MyEnum(object): One = 1 Two = 2 T...
Q_ENUMS in PyQt4
I would like to use facilities of enumeration of Qt. I saw in documentation of the module of QtCore there is a macros of Q_ENUMS, but I do not know and information how to use him.
[ "In python (and PyQt), the way to create an enum is like this:\nclass MyEnum(object):\n One = 1\n Two = 2\n Three = 3\n\nIf you need more functionality than that, please give more details of what you are trying to do.\nEDIT\nLooking at the documentation for QAbstractSocket.stateChanged I can see it refers ...
[ 5 ]
[]
[]
[ "enums", "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0007760842_enums_pyqt_pyqt4_python_qt.txt
Q: Issue converting Matlab sparse() code to numpy/scipy with csc_matrix() I'm a bit of a newbie to both Matlab and Python so, many apologies if this question is a bit dumb... I'm trying to convert some Matlab code over to Python using numpy and scipy and things were going fine until I reached the sparse matrix that s...
Issue converting Matlab sparse() code to numpy/scipy with csc_matrix()
I'm a bit of a newbie to both Matlab and Python so, many apologies if this question is a bit dumb... I'm trying to convert some Matlab code over to Python using numpy and scipy and things were going fine until I reached the sparse matrix that someone wrote. The Matlab code goes like: unwarpMatrix = sparse(phaseOrigin,...
[ "The problem is; Python indexes start from 0, whereas Matlab indexes start from 1. So for an array of size 57344, in Python first element would be arr[0] and last element would be arr[57343]. \nYou variable j has values from 1 to 57344. You probably see the problem. Creating your j like this would solve the problem...
[ 3 ]
[]
[]
[ "matlab", "python", "scipy", "sparse_matrix" ]
stackoverflow_0007760937_matlab_python_scipy_sparse_matrix.txt
Q: How can escape spaces in directory names in a MANIFEST.in files? I've inherited some code that has directory names with embedded spaces, and I don't have the option of renaming the directory. Let's say the name of the directory is "embedded spaces" Now I'm trying to access some files from this directory in a MANI...
How can escape spaces in directory names in a MANIFEST.in files?
I've inherited some code that has directory names with embedded spaces, and I don't have the option of renaming the directory. Let's say the name of the directory is "embedded spaces" Now I'm trying to access some files from this directory in a MANIFEST.in file I've tried the following: recursive-include 'embedded spa...
[ "No it would appear not. Inspecting the source of distutils.filelist, which does the work of parsing the MANIFEST.in shows that the line is split purely on whitespace to determine the action and its parameters\nHere is the source (in python 2,7)\ndef _parse_template_line(self, line):\n words = line.split()\n ...
[ 2, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0007761130_python_setuptools.txt
Q: Neo4j and django models So, I'm looking into the Django and Neo4j integration, but there's not much about it out there ... What I want to know is if I have a model like the one here: If I want to add a new property to a model, it would be as simple as doing: node.setProperty( "newProperty", "something" ); ?? Mor...
Neo4j and django models
So, I'm looking into the Django and Neo4j integration, but there's not much about it out there ... What I want to know is if I have a model like the one here: If I want to add a new property to a model, it would be as simple as doing: node.setProperty( "newProperty", "something" ); ?? Moreover, all the queries in dja...
[ "We've been working on updating the Neo4j/Django integration to work with neo4j-rest-client - the fruits of our labor are on GitHub, with some quick comments on my blog.\nThere are some pros and cons to our integration. The most obviously impacting is our use of a REST client- you get to use a remote database, whil...
[ 7, 1 ]
[]
[]
[ "django", "neo4j", "nosql", "python" ]
stackoverflow_0005866635_django_neo4j_nosql_python.txt
Q: How can I correct a corrupted $PYTHONPATH? When trying to launch Mercurial(hg) after a restart in my Ubuntu 9.10 Linux Box I got following message: abort: couldn't find mercurial libraries in [/usr/bin /usr/local/lib/python2.6/dist-packages/vipy-0.4-py2.6.egg /usr/local/lib/python2.6/dist-packages/nose-0.11....
How can I correct a corrupted $PYTHONPATH?
When trying to launch Mercurial(hg) after a restart in my Ubuntu 9.10 Linux Box I got following message: abort: couldn't find mercurial libraries in [/usr/bin /usr/local/lib/python2.6/dist-packages/vipy-0.4-py2.6.egg /usr/local/lib/python2.6/dist-packages/nose-0.11.1-py2.6.egg /usr/local/lib/python2.6/dist-packag...
[ "Try this:\nupdate-python-modules -p\n(might need to sudo that...)\nSource:\nhttp://hg.opensource.lshift.net/mercurial-server/rev/32dba1a70a54\n", "All of the sites I've googled for this say that your PYTHONPATHis set wrong. The code that you are hitting in mercurial appears to be this:\ntry:\n from mercurial ...
[ 8, 5, 1, 1, 0 ]
[]
[]
[ "mercurial", "python", "pythonpath", "ubuntu_9.10", "version_control" ]
stackoverflow_0001847249_mercurial_python_pythonpath_ubuntu_9.10_version_control.txt
Q: Developing a web application in python with neo4j I'm planning to implement a recommendation engine, of which details are given here. 'Python' is my preferred choice along with 'neo4j' Database. Can anyone please point out, how integration of 'neo4j' with any web framework like 'django' can be done?. Is it possibl...
Developing a web application in python with neo4j
I'm planning to implement a recommendation engine, of which details are given here. 'Python' is my preferred choice along with 'neo4j' Database. Can anyone please point out, how integration of 'neo4j' with any web framework like 'django' can be done?. Is it possible to integrate them just like 'PHP'integrates with 'MyS...
[ "I dont see why not. You can integrate this with Django & serve requests through it...\n\nModeling Categories in Graph Database\nNeo4J shop categories example\nNeo4j and django models\nDjango & Neo4j - domain modeling that kicks ass.\nSeamless Django & Neo4j integration\n\nHope this helps... I myself was able to in...
[ 13, 5, 4, 4 ]
[]
[]
[ "django", "neo4j", "python", "recommendation_engine" ]
stackoverflow_0007721737_django_neo4j_python_recommendation_engine.txt
Q: Does Python's open() read an unflushed buffer? My knowledge of how file buffers work is fairly weak, so forgive the simple mindedness of this question. I have a piece of code in Python that waits for a file to appear, then reads it. while 1: try: f = open('file.txt') f.close() print "Me...
Does Python's open() read an unflushed buffer?
My knowledge of how file buffers work is fairly weak, so forgive the simple mindedness of this question. I have a piece of code in Python that waits for a file to appear, then reads it. while 1: try: f = open('file.txt') f.close() print "Message received." break except: t...
[ "Don't use a while-loop for this purpose. There is a better way, though the details depend on your OS. \nLinux has inotify. You can write a simple pyinotify script to watch the directory and react to IN_CLOSE_WRITE events (which occur only after the file has been closed).\nOSX (FSEvents) and Windows have similar fa...
[ 3, 1, 1, 0 ]
[]
[]
[ "buffer", "file_io", "python" ]
stackoverflow_0007760670_buffer_file_io_python.txt
Q: Correct usage of a getter/setter for dictionary values I'm pretty new to Python, so if there's anything here that's flat-out bad, please point it out. I have an object with this dictionary: traits = {'happy': 0, 'worker': 0, 'honest': 0} The value for each trait should be an int in the range 1-10, and new traits ...
Correct usage of a getter/setter for dictionary values
I'm pretty new to Python, so if there's anything here that's flat-out bad, please point it out. I have an object with this dictionary: traits = {'happy': 0, 'worker': 0, 'honest': 0} The value for each trait should be an int in the range 1-10, and new traits should not be allowed to be added. I want getter/setters so ...
[ "If you are willing to use syntax like obj['happy'] = 14 then you could use __getitem__ and __setitem__:\ndef __getitem__(self, key):\n if key not in self.traits.keys():\n raise KeyError\n ... \n return traits[key]\n\ndef __setitem__(self, key, value):\n if key not in self.traits.keys():\n ...
[ 13, 3, 1 ]
[]
[]
[ "getter_setter", "python" ]
stackoverflow_0007760916_getter_setter_python.txt
Q: PyArg_ParseTuple SegFaults in CApi I am writing a code, trying to get used to the C API of NumPy arrays. #include <Python.h> #include "numpy/arrayobject.h" #include <stdio.h> #include <stdbool.h> static char doc[] = "Document"; static PyArrayObject * trace(PyObject *self, PyObject *args){ PyArrayObject...
PyArg_ParseTuple SegFaults in CApi
I am writing a code, trying to get used to the C API of NumPy arrays. #include <Python.h> #include "numpy/arrayobject.h" #include <stdio.h> #include <stdbool.h> static char doc[] = "Document"; static PyArrayObject * trace(PyObject *self, PyObject *args){ PyArrayObject *matin; if (!PyArg_ParseTuple(arg...
[ "From the docs:\n\nO (object) [PyObject *]\nStore a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object’s reference count is not increased. The pointer stored is not NULL.\nO! (object) [typeobject, PyObject *]\nStore a Python object...
[ 1 ]
[]
[]
[ "numpy", "python", "python_c_api" ]
stackoverflow_0007760658_numpy_python_python_c_api.txt
Q: Combine functions to reduce queries From Python Problem Set The three functions work correctly but they require executing one at a time before moving to the next in order to get the final result. Is there a way to obtain the result from all three without having to query each one individually? >>> import itertools ...
Combine functions to reduce queries
From Python Problem Set The three functions work correctly but they require executing one at a time before moving to the next in order to get the final result. Is there a way to obtain the result from all three without having to query each one individually? >>> import itertools >>> def prime_factors(value): if val...
[ "You can combine the second 2, but the generator should stay a generator:\nIn [1]: import itertools\nIn [2]: from operator import mul\n\nIn [3]: def prime_factors(value):\n if value > 3:\n for this in itertools.chain(iter([2]), xrange(3,int(value ** 0.5) + 1, 2)):\n if (...
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007761659_function_python.txt
Q: Django: how do I render an XML file, then use that xml in a simultaneously rendered view? What I'm trying to do is use a SIMILE timeline in my Django app. The timeline requires it's data in an XML file. Now, I know how to render a view in html. And I can probably figure out how to render a view into XML. But how w...
Django: how do I render an XML file, then use that xml in a simultaneously rendered view?
What I'm trying to do is use a SIMILE timeline in my Django app. The timeline requires it's data in an XML file. Now, I know how to render a view in html. And I can probably figure out how to render a view into XML. But how would one render both, then pull in the XML data to the HTML file if the XML file doesn't exist ...
[ "You seem to be trying to cram too many things into the same view.\nWhat I'd do is the following:\n\nCreate a view that generates the XML (every request to the view should generate the XML from scratch).\nCreate a view that uses the timeline widget and points it to the XML in 1)\nEnable Django's caching layer and a...
[ 1, 1 ]
[]
[]
[ "django", "python", "simile", "xml" ]
stackoverflow_0007750386_django_python_simile_xml.txt
Q: mod_wsgi python can't import from standard library I have created two python environments with virtualenv: /usr/local/pythonenv/BASELINE and /usr/local/pythonenv/django1. Both were created with --no-site-packages. I installed django to the django1 environment with easy_install. My wsgi.conf file has this line to s...
mod_wsgi python can't import from standard library
I have created two python environments with virtualenv: /usr/local/pythonenv/BASELINE and /usr/local/pythonenv/django1. Both were created with --no-site-packages. I installed django to the django1 environment with easy_install. My wsgi.conf file has this line to set the Python interpreter: WSGIPythonHome /usr/local/pyt...
[ "Your mod_wsgi is likely not compiled against Python 2.7. You cannot use a virtualenv for one Python version with mod_wsgi compiled against a different Python version.\nRead from:\nhttp://code.google.com/p/modwsgi/wiki/CheckingYourInstallation#Python_Shared_Library\nand do checks in that document.\n" ]
[ 4 ]
[]
[]
[ "mod_wsgi", "python", "virtualenv" ]
stackoverflow_0007760959_mod_wsgi_python_virtualenv.txt
Q: How do I search for an entity in Google App engine by user? I am attempting to lookup a user entity that is related to the current user, and I do not seem to be able to find the user after they get stored in the database. When I am creating the user for the first time, the call I make looks like the following: new...
How do I search for an entity in Google App engine by user?
I am attempting to lookup a user entity that is related to the current user, and I do not seem to be able to find the user after they get stored in the database. When I am creating the user for the first time, the call I make looks like the following: newPlayer = model.Player(parent=model.user_key(), user=users.GetCurr...
[ "User is not a class in datastore, so you can't make player a child of it. This should work:\nnewPlayer = model.Player(user=users.get_current_user(), publicName='john')\nnewPlayer.put()\n\nusr = users.get_current_user()\njohn = model.Player.all().filter('user =', usr).fetch(1)\nprint john.nickname\n>> 'john'\n\nNot...
[ 1 ]
[]
[]
[ "datamodel", "google_app_engine", "python" ]
stackoverflow_0007761530_datamodel_google_app_engine_python.txt
Q: Matplotlib - matching axes unit length (resolution) I need to match the resolution of x- and y-axes in matplotlib, so that the linear function y=x would plot as an exactly 45° line, and so that a mathematically plotted circle (r^2=x^2+y^2) would appear round. This because I'm plotting geographical data, and would ...
Matplotlib - matching axes unit length (resolution)
I need to match the resolution of x- and y-axes in matplotlib, so that the linear function y=x would plot as an exactly 45° line, and so that a mathematically plotted circle (r^2=x^2+y^2) would appear round. This because I'm plotting geographical data, and would like a given distance measured along the x-axis to equal ...
[ "You can do that with axes.set_aspect. For example:\nimport matplotlib.pyplot as plt\n\nf = plt.figure()\nx = f.gca()\nx.set_aspect(\"equal\")\nx.plot(range(10),range(10))\nplt.show()\n\n" ]
[ 4 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007761817_matplotlib_python.txt
Q: Python: Calling variables in one function from a seperate function but not using global variables I wrote the below code in order to check for three files and whichever files exist, run a "scan" on the file (if a file does not exist, don't worry about it just run a "scan" on the available files) and produce the pr...
Python: Calling variables in one function from a seperate function but not using global variables
I wrote the below code in order to check for three files and whichever files exist, run a "scan" on the file (if a file does not exist, don't worry about it just run a "scan" on the available files) and produce the proper output file on those available files. The program I'm working on includes the following code: def ...
[ "Inside chkifexists, you would return all three variables like so:\nreturn (filename, hashcolumn, filepathNum)\n\nYou would retrieve these by calling the function like so:\n(filename, hashcolumn, filepathNum) = chkifexists()\n\nYou now have them in your function scope without needing global variables!\nTechnically,...
[ 4 ]
[]
[]
[ "global_variables", "python" ]
stackoverflow_0007762082_global_variables_python.txt
Q: Override + operator in python for float + obj I have a class Vec3D (see http://pastebin.com/9Y7YbCZq) Currently, I allow Vec3D(1,0,0) + 1.2 but I'm wondering how I should proceed to overload the + operator in such a way that I get the following output: >>> 3.3 + Vec3D(1,0,0) [4.3, 3.3 , 3.3] Code is not required...
Override + operator in python for float + obj
I have a class Vec3D (see http://pastebin.com/9Y7YbCZq) Currently, I allow Vec3D(1,0,0) + 1.2 but I'm wondering how I should proceed to overload the + operator in such a way that I get the following output: >>> 3.3 + Vec3D(1,0,0) [4.3, 3.3 , 3.3] Code is not required, but just a hint in which direction I should look....
[ "You're looking for __radd__:\nclass MyClass(object):\n def __init__(self, value):\n self.value = value\n def __radd__(self, other):\n print other, \"radd\", self.value\n return self.value + other\n\n\nmy = MyClass(1)\n\nprint 1 + my\n# 1 radd 1\n# 2\n\nIf the object on the left of the ad...
[ 11, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007762108_python.txt
Q: Python - apache - windows 7 - wamp I tried millions of times to install python with apache on my windows 7 32 bit. But failed. Can anybody tell me the simplest way to get it work??? A: If you're looking to run a simple web app built in python, mod_wsgi is an Apache module that will enable the server to run pytho...
Python - apache - windows 7 - wamp
I tried millions of times to install python with apache on my windows 7 32 bit. But failed. Can anybody tell me the simplest way to get it work???
[ "If you're looking to run a simple web app built in python, mod_wsgi is an Apache module that will enable the server to run python code as either a daemon or as embedded code.\n", "Common problems with Apache/mod_wsgi installation, if that is what you are trying to install are:\n\nInstalling a mix of 32 and 64 bi...
[ 0, 0 ]
[]
[]
[ "apache", "python", "windows" ]
stackoverflow_0007758160_apache_python_windows.txt
Q: Python Pickle Yielding EOF Error on Read and Not Reading Correctly I am trying to pickle a patient object by using: theFile = open(str(location)+str(filename)+'.pkl','wb') pickle.dump(self,theFile) theFile.close() This works well and successfully writes to the file as desired. But! When I try to load the data fro...
Python Pickle Yielding EOF Error on Read and Not Reading Correctly
I am trying to pickle a patient object by using: theFile = open(str(location)+str(filename)+'.pkl','wb') pickle.dump(self,theFile) theFile.close() This works well and successfully writes to the file as desired. But! When I try to load the data from the thumb, I get an EOF error XOR it loads old data that is not presen...
[ "Assigning to self inside a method only updates what the variable self points to in that method; it doesn't update the object itself. To load it, instead return a newly loaded object from a classmethod or function. Try code like this:\nimport pickle\nclass Patient(object):\n def __init__(self, name):\n se...
[ 1, 0, 0 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0007748056_pickle_python.txt
Q: Python negative list indices wrapped as slicing I have nested lists that represents a table of sorts. I would like to access the element in n rows above. That it is easy, however, my problem is that I would like to catch anything that is outside the table and react to it. But afaics negative indices get interprete...
Python negative list indices wrapped as slicing
I have nested lists that represents a table of sorts. I would like to access the element in n rows above. That it is easy, however, my problem is that I would like to catch anything that is outside the table and react to it. But afaics negative indices get interpreted as slicing in this case and get "wrapped around". H...
[ "Since the slicing behavior is built in to the Python syntax, I'd recommend putting a simple 'if' statement in your loop:\nfor k in [-1, 0, 1]:\n idx = i+k\n if idx < 0: raise IndexError, 'list index is out of range'\n print lists[idx][0]\n\n", "This will throw an error when it tries to print an entire r...
[ 1, 0 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0007761955_list_python_slice.txt
Q: How can I sort a complicated dictionary key I have these really complicated data files that I have processed and as each file is processed I have used an orderedDictionary to capture the keys and values. Each orderedDictionary is appended to a list so my final result is a list of dictionaries. Because of the div...
How can I sort a complicated dictionary key
I have these really complicated data files that I have processed and as each file is processed I have used an orderedDictionary to capture the keys and values. Each orderedDictionary is appended to a list so my final result is a list of dictionaries. Because of the diversity in the data captured in these files, they ...
[ "Just supply a sufficiently clever function as the key when sorting.\n>>> (lambda x: tuple(y(z) for (y, z) \n in zip((int, str, str, int), \n x.split('_')[1::2])))('Q_122_SUB_A_COLUMN_C_NUMB_1')\n(122, 'A', 'C', 1)\n\n", "You could use a regular expression to extract...
[ 4, 2, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0007762101_dictionary_python_sorting.txt
Q: Extract business titles and time periods from string I am extracting information about certain companies from Reuters using Python. I have been able to get the officer/executive names, biographies, and compensation from this page Now, I want to extract previous position titles and companies from the biography sec...
Extract business titles and time periods from string
I am extracting information about certain companies from Reuters using Python. I have been able to get the officer/executive names, biographies, and compensation from this page Now, I want to extract previous position titles and companies from the biography section, which looks something like this: Mr. Donald T. Grim...
[ "The problem you are trying to solve is well known and researched, and you will find a large amount of research paper describing approaches and algorithms if you google for the terms \"Named Entity Extraction\" and \"Relationship Extraction\" Some good starting points are:\n\nChapter 7 of the book \"Natural Languag...
[ 2, 1 ]
[]
[]
[ "nlp", "python", "regex" ]
stackoverflow_0007757554_nlp_python_regex.txt
Q: html in do_GET() method of a simple Python webserver I am relatively new to Python but have been doing a lot of different things with it recently and I am liking it a lot. However, I ran into trouble/block with the following code. import http.server import socketserver import glob import random class Server(http.s...
html in do_GET() method of a simple Python webserver
I am relatively new to Python but have been doing a lot of different things with it recently and I am liking it a lot. However, I ran into trouble/block with the following code. import http.server import socketserver import glob import random class Server(http.server.SimpleHTTPRequestHandler): def do_GET(self): ...
[ "I changed the code to:\n#!usr/bin/python3.2\nimport http.server\nimport socketserver\nimport glob\nimport random\nimport sys\n\nclass Server(http.server.SimpleHTTPRequestHandler):\ndef do_GET(self):\n referer = self.headers.get('Referer')\n print(\"The referer is\", referer)\n if referer == None:\n ...
[ 5, 1, 0, 0 ]
[]
[]
[ "html", "image", "python", "webserver" ]
stackoverflow_0006530979_html_image_python_webserver.txt
Q: Javascript & CSS Obfuscation/Minimization in Django Website? I am serving CSS and javascripts in my django website, so how to obfuscate and minimize them. 1 solution is: To serve already obfuscated and minimized js and css. can I have a flag set in settings.py that to switch on and off the obfuscation? So, that I ...
Javascript & CSS Obfuscation/Minimization in Django Website?
I am serving CSS and javascripts in my django website, so how to obfuscate and minimize them. 1 solution is: To serve already obfuscated and minimized js and css. can I have a flag set in settings.py that to switch on and off the obfuscation? So, that I can develop on normal human readable code and serve the obfuscated...
[ "I would recommend django-compressor. It supports running your JS/CSS through a number of different compression algorithms (JSMin, Slim It, YUI, Closure Compiler).\n" ]
[ 3 ]
[]
[]
[ "css", "django", "javascript", "python" ]
stackoverflow_0007757589_css_django_javascript_python.txt
Q: Get an error <'NoneType' object has no attribute 'peer_certificate'> when clone code from google code by Mercurial Description There is no error when clone by http, the error only meet when clone by https. Env Install Mercurial by mercurial-1.9.1+20110801-py2.6-macosx10.6.mpkg from http://mercurial.berkwood.com/bi...
Get an error <'NoneType' object has no attribute 'peer_certificate'> when clone code from google code by Mercurial
Description There is no error when clone by http, the error only meet when clone by https. Env Install Mercurial by mercurial-1.9.1+20110801-py2.6-macosx10.6.mpkg from http://mercurial.berkwood.com/binaries/Mercurial-1.9.1-py2.6-macosx10.6.zip site-packages location: /Library/Python/2.6/site-packages Command: hg clone ...
[ "After I installed Mercurial (version 1.9.3), I encountered the same problem with Sailing, when I hg clone https://code.google.com/p/vim/\nAnd my solution is:\nhg clone http://code.google.com/p/vim/\nI guess Mercurial 1.9.3\nsslutil.py has bug in line 105:\npeercert = sock.getpeercert(True)\n" ]
[ 1 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0007043126_mercurial_python.txt
Q: HTTP method for files using python I have a website that has a form which accepts two input type="file". I would like to do these POST requests using python. How can I do that? A: If you want some Python code to POST to a website, then use either the included httplib web client or the 3rd party httplib2 web cli...
HTTP method for files using python
I have a website that has a form which accepts two input type="file". I would like to do these POST requests using python. How can I do that?
[ "If you want some Python code to POST to a website, then use either the included httplib web client or the 3rd party httplib2 web client. You could also consider using curl to do this.\nIn the POST transaction, you would typically send all the form fields including the file name as parameters, and then send bulk da...
[ 0 ]
[]
[]
[ "http", "post", "python" ]
stackoverflow_0007762841_http_post_python.txt