content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to get item list from wxpython ListBox Is there a single method that returns the list of items contained in a wxPython listBox? I cant seem to find anything anywhere in the documentation or anywhere for that matter. All that I can think to do is to set the selection to all of the items and then get the select...
How to get item list from wxpython ListBox
Is there a single method that returns the list of items contained in a wxPython listBox? I cant seem to find anything anywhere in the documentation or anywhere for that matter. All that I can think to do is to set the selection to all of the items and then get the selected items, though seems like an ugly roundabout...
[ "wx.ListBox is derived from wx.ControlWithitems. I think GetStrings() is what you need.\n", "You can get a list of the strings in the listbox like:\n[listBox.GetString(i) for i in range(listBox.GetCount())]\n\n" ]
[ 10, 1 ]
[]
[]
[ "listbox", "listboxitems", "python", "wxpython" ]
stackoverflow_0003229749_listbox_listboxitems_python_wxpython.txt
Q: Initialize a django.forms.ModelChoiceField, bound with a foreign key and a default value I have a model that contains a foreign key value, then in the form generated from this model as a ModelChoiceField. I want to auto select the user's (update_author). I've tried the below code, using the initial property. The v...
Initialize a django.forms.ModelChoiceField, bound with a foreign key and a default value
I have a model that contains a foreign key value, then in the form generated from this model as a ModelChoiceField. I want to auto select the user's (update_author). I've tried the below code, using the initial property. The view creates a formset with the the dates initialized to now() for the empty form. But, I want ...
[ "For the core of your question is, as to how to set initial value for ForeignKey field, check the code snippet below. \nNote that when you provide initial value to a ForeignKey field, you don't need to pass the object. Pass it the id/pk of that object, and your problem will be solved.\ninitial = {\n 'upda...
[ 2 ]
[]
[]
[ "django", "field", "forms", "python" ]
stackoverflow_0003223936_django_field_forms_python.txt
Q: Is there a way to have parallel for-each loops? Let's say I have 2 lists in Python and I want to loop through each one in parallel - e.g. do something with element 1 for both lists, do something with element 2 for both lists... I know that I can do this by using an index: for listIndex in range(len(list1)): doS...
Is there a way to have parallel for-each loops?
Let's say I have 2 lists in Python and I want to loop through each one in parallel - e.g. do something with element 1 for both lists, do something with element 2 for both lists... I know that I can do this by using an index: for listIndex in range(len(list1)): doSomething(list1[listIndex]) doSomething(list2[listI...
[ "Something like this?\nfor (a,b) in zip(list1, list2):\n doSomething(a)\n doSomething(b)\n\nThough if doSomething() isn't doing I/O or updating global state, and it just works on one of the elements at a time, the order doesn't matter so you could just use chain() (from itertools):\nfor x in chain(list1, list2):\...
[ 14, 5, 4 ]
[]
[]
[ "foreach", "iteration", "parallel_processing", "python" ]
stackoverflow_0003229458_foreach_iteration_parallel_processing_python.txt
Q: Popular Django App Libraries I know there is some really good django app libraries out there (other than the builtin django.contrib.*) but for some reason, my google search abilities are failing me. I am thinking of one in particular that I cannot remeber the name of for the life of me. I keep wanting to call it p...
Popular Django App Libraries
I know there is some really good django app libraries out there (other than the builtin django.contrib.*) but for some reason, my google search abilities are failing me. I am thinking of one in particular that I cannot remeber the name of for the life of me. I keep wanting to call it pyrex or pixar or something. Obvio...
[ "http://code.google.com/p/django-basic-apps/ ?\nalso:\nhttp://code.google.com/p/django-profile/\nand\nhttp://code.google.com/p/django-registration/\nI have found useful.\n", "I've found the Python Package Index to be a great place to start searching for Django apps and libraries.\n\nsearch: django-pi\nsearch: dja...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003229675_django_python.txt
Q: Filter foreignkey field from the selection of another foreignkey in django-admin? i have the next models class Region(models.Model): nombre = models.CharField(max_length=25) class Departamento(models.Model): nombre = models.CharField(max_length=25) region = models.ForeignKey(Region) class Municipio(m...
Filter foreignkey field from the selection of another foreignkey in django-admin?
i have the next models class Region(models.Model): nombre = models.CharField(max_length=25) class Departamento(models.Model): nombre = models.CharField(max_length=25) region = models.ForeignKey(Region) class Municipio(models.Model): nombre = models.CharField(max_length=35) departamento = models.Fo...
[ "Assuming you are talking about doing this in a series of select boxes:\nCreate two views, one which returns a response containing the Departamentos for a given Region. The other does the same but for Municipios in a Departamento\n# views.py\nfrom django.core import serializers\n\ndef departamentos_por_region(reque...
[ 2 ]
[]
[]
[ "django", "django_models", "foreign_keys", "python" ]
stackoverflow_0003217556_django_django_models_foreign_keys_python.txt
Q: Slicing python lists If I have a list of say 'n' elements (each element is a single byte ) which represents a rectangular 2d matrix, how can I split this into rectangles of say w * h, starting from the first element of the list , just using the python standard functions for example l = [ 1,2,3,4,5,6,7,8,9,10, ...
Slicing python lists
If I have a list of say 'n' elements (each element is a single byte ) which represents a rectangular 2d matrix, how can I split this into rectangles of say w * h, starting from the first element of the list , just using the python standard functions for example l = [ 1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15....20....
[ "Note that your question specifies that the input list is 1D, but gives no indication into how many items to each logical row; you seem to magically imply it should be 10 items per row.\nSo, given a 1D list, the count of logical items per row, the width and height of the tiles requested, you can do:\ndef gettiles(l...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0003229677_list_python_slice.txt
Q: No module named preview, FormPreview Django Module I am trying to get the form preview django module example to work. In polls_app/mysite/urls.py: from django.conf.urls.defaults import * from mysite.preview import SomeModelFormPreview from mysite.forms import SomeModelForm from django import forms In polls_app/m...
No module named preview, FormPreview Django Module
I am trying to get the form preview django module example to work. In polls_app/mysite/urls.py: from django.conf.urls.defaults import * from mysite.preview import SomeModelFormPreview from mysite.forms import SomeModelForm from django import forms In polls_app/mysite/SomeModelFormPreview.py: from django.contrib.formt...
[ "It would appear that mysite.preview does not exist. That is the error you're seeing. This may be the result of circular includes, or an incorrect name.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003230194_django_python.txt
Q: Python: how does inspect.ismethod work? I'm trying to get the name of all methods in my class. When testing how the inspect module works, i extraced one of my methods by obj = MyClass.__dict__['mymethodname']. But now inspect.ismethod(obj) returns False while inspect.isfunction(obj) returns True, and i don't unde...
Python: how does inspect.ismethod work?
I'm trying to get the name of all methods in my class. When testing how the inspect module works, i extraced one of my methods by obj = MyClass.__dict__['mymethodname']. But now inspect.ismethod(obj) returns False while inspect.isfunction(obj) returns True, and i don't understand why. Is there some strange way of mark...
[ "You are seeing some effects of the behind-the-scenes machinery of Python.\nWhen you write f = MyClass.__dict__['mymethodname'], you get the raw implementation of \"mymethodname\", which is a plain function. To call it, you need to pass in an additional parameter, class instance.\nWhen you write f = MyClass.mymetho...
[ 11, 4, 1, 1, 0 ]
[]
[]
[ "inspect", "python" ]
stackoverflow_0003228680_inspect_python.txt
Q: Typogrify equivalent for .NET Does anyone know of, or use a library that has similar functionality to Typogrify (http://code.google.com/p/typogrify/) in a .NET project. Typogrify is a Python/Django library and I am looking for an equivalent that I could use in a .NET project. Edit: Now I'm just looking for any typ...
Typogrify equivalent for .NET
Does anyone know of, or use a library that has similar functionality to Typogrify (http://code.google.com/p/typogrify/) in a .NET project. Typogrify is a Python/Django library and I am looking for an equivalent that I could use in a .NET project. Edit: Now I'm just looking for any typography processing library for .NET...
[ "Textile has some of the same function\n\nTextile.NET is, surprisingly, a textile formatter for .NET projects.\n Textile is a \"human web text generator\"\n (http://www.textism.com/tools/textile/) that is useful for rapid web\n writings such as Wiki syntax or blog articles. From a simple and\n intuitive syntax ...
[ 0 ]
[]
[]
[ ".net", "assemblies", "django", "python", "typography" ]
stackoverflow_0003230333_.net_assemblies_django_python_typography.txt
Q: Python in Plone: trying to append a variable to RESPONSE.redirect I have a python script in Plone, I'm having trouble appending a variable to RESPONSE.redirect. I get a invalid syntax error. test = '1000' RESPONSE.redirect(("/Plone/user_blast/public_blast_results/%s" % (test)) A: Its me being stupid, theres an ...
Python in Plone: trying to append a variable to RESPONSE.redirect
I have a python script in Plone, I'm having trouble appending a variable to RESPONSE.redirect. I get a invalid syntax error. test = '1000' RESPONSE.redirect(("/Plone/user_blast/public_blast_results/%s" % (test))
[ "Its me being stupid, theres an extra bracket by redirect.\n" ]
[ 1 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0003230605_plone_python.txt
Q: Switching files to read from in python's .csv reader I am reading a csv file several times, but cutting its size every time I go through it. So, once I've reached the bottom, I am writing a new csv file which is, say, the bottom half of the .csv file. I then wish to change the csv reader to use this new file ins...
Switching files to read from in python's .csv reader
I am reading a csv file several times, but cutting its size every time I go through it. So, once I've reached the bottom, I am writing a new csv file which is, say, the bottom half of the .csv file. I then wish to change the csv reader to use this new file instead, but it doesn't seem to be working... Here's what I'v...
[ "\nIs something = r_send.next() in some kind of loop? The way you wrote it, it's only going to read one line. \nWhy do you need \",\".join(line)? You can simply print line itself, and it should work.\nPlus, there really is no need to seek(0) before closing a file.\n\n", "I suggest the following:\nUse for somethi...
[ 1, 0 ]
[]
[]
[ "csv", "file_io", "python" ]
stackoverflow_0003230554_csv_file_io_python.txt
Q: Passing list elements to a for loop I'm trying to pass elements from a list to a for loop and of course am getting the classic error 'argument 1 must be a string not list' - for the os.chdir() function. Here is a my code, any suggestions as to how I can get around the above error and still pass the elements of my ...
Passing list elements to a for loop
I'm trying to pass elements from a list to a for loop and of course am getting the classic error 'argument 1 must be a string not list' - for the os.chdir() function. Here is a my code, any suggestions as to how I can get around the above error and still pass the elements of my list on to the rest of the script so it l...
[ "You want os.chdir(x) instead of os.chdir(path).\npath is the list containing all the paths (and should thus probably be named paths), so you can't use it as an argument to chdir.\n", "First of all, double your backslashes if you want to hardcode the Windows paths this way (otherwise you'll have unexpected behavi...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003230728_python.txt
Q: Determine height of Coffee in the pot using Python imaging We have a web-cam in our office kitchenette focused at our coffee maker. The coffee pot is clearly visible. Both the location of the coffee pot and the camera are static. Is it possible to calculate the height of coffee in the pot using image recognition? ...
Determine height of Coffee in the pot using Python imaging
We have a web-cam in our office kitchenette focused at our coffee maker. The coffee pot is clearly visible. Both the location of the coffee pot and the camera are static. Is it possible to calculate the height of coffee in the pot using image recognition? I've seen image recognition used for quite complex stuff like fa...
[ "Since the coffee pot position is stationary, get a sample frame and locate a single column of pixels where the minimum and maximum coffee quantities can easily be seen, in a spot where there are no reflections. Check the green vertical line segment in the following picture:\n\n(source: nullnetwork.net)\nThe easies...
[ 11, 4, 2, 1, 0 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0003227843_image_processing_python.txt
Q: Python: appending a variable to Popen When i try to carry out the code below i get the error "unsupported operand type(s) for %: 'list' and 'str'" from subprocess import Popen z = '10000' Popen(["formatdb", "-p", "T", "-i", "%s.txt"] % (z)).wait() How would I insert my variable z into the name of my text file? A...
Python: appending a variable to Popen
When i try to carry out the code below i get the error "unsupported operand type(s) for %: 'list' and 'str'" from subprocess import Popen z = '10000' Popen(["formatdb", "-p", "T", "-i", "%s.txt"] % (z)).wait() How would I insert my variable z into the name of my text file?
[ "% should immediately follow the string that's being formatted, and you don't need parens around the z. Like so:\nPopen([\"formatdb\", \"-p\", \"T\", \"-i\", \"%s.txt\" % z]).wait()\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003231239_python.txt
Q: Sorting dicts (contained in lists) alphanumerically in Python I'm having an issue with sorting a list that contains a dict. Currently I am sorting it by a key called 'title' with the following line: list.sort(key=operator.itemgetter('title')) The problem with this is that some of my data gets sorted looking like ...
Sorting dicts (contained in lists) alphanumerically in Python
I'm having an issue with sorting a list that contains a dict. Currently I am sorting it by a key called 'title' with the following line: list.sort(key=operator.itemgetter('title')) The problem with this is that some of my data gets sorted looking like this: title_text #49 title_text #5 title_text #50 How would I go a...
[ "You are looking for human sorting.\nimport re\n# Source: http://nedbatchelder.com/blog/200712/human_sorting.html\n# Author: Ned Batchelder\ndef tryint(s):\n try:\n return int(s)\n except:\n return s\n\ndef alphanum_key(s):\n \"\"\" Turn a string into a list of string and number chunks.\n ...
[ 4, 2, 0 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0003231352_dictionary_list_python_sorting.txt
Q: Python 2.6: containment hierarchy issue: Same Values :S Hey Everyone, If you've seen my previous post you'll know im working on an airline program using Python. Another issue that poped up was that after I launch one flight, it calculates the duration of the flight and replaces the button which is used to launch t...
Python 2.6: containment hierarchy issue: Same Values :S
Hey Everyone, If you've seen my previous post you'll know im working on an airline program using Python. Another issue that poped up was that after I launch one flight, it calculates the duration of the flight and replaces the button which is used to launch the flight. But when I buy another aircraft, it changes both f...
[ "Your __init__ code is defaulting an argument to an object:\nclass Airplane (object): \n'''Airplane Class'''\n def __init__(self, ..., Flight = Flight(departure_time = datetime(1,1,1), ...):\n\nDefault arguments are only evaluated once, when the class is defined, so every Airplane object will get the same Fli...
[ 1 ]
[]
[]
[ "class", "function", "methods", "python", "python_2.6" ]
stackoverflow_0003231509_class_function_methods_python_python_2.6.txt
Q: Weird Python behaviour - or am I missing something The following code: class House: links = [] class Link: pass class Villa(House): pass if __name__ == '__main__': house = House() villa = Villa() link = Link() house.links.append(link) print house.links print villa.links res...
Weird Python behaviour - or am I missing something
The following code: class House: links = [] class Link: pass class Villa(House): pass if __name__ == '__main__': house = House() villa = Villa() link = Link() house.links.append(link) print house.links print villa.links results in this output: [<__main__.Link instance at 0xb65a4...
[ "It is another instance, but you have defined links as a class variable rather than an instance variable.\nAn instance variable would be defined as such:\nclass House(object): # Always use new-style classes except for backward compatibility\n def __init__(self):\n self.links = []\n\nNote that in Python, unlike...
[ 19, 3 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003231832_oop_python.txt
Q: How do you pass a Queue reference to a function managed by pool.map_async()? I want a long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queu...
How do you pass a Queue reference to a function managed by pool.map_async()?
I want a long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queue objects should only be shared between processes through inheritance. import mult...
[ "The following code seems to work:\nimport multiprocessing, time\n\ndef task(args):\n count = args[0]\n queue = args[1]\n for i in xrange(count):\n queue.put(\"%d mississippi\" % i)\n return \"Done\"\n\n\ndef main():\n manager = multiprocessing.Manager()\n q = manager.Queue()\n pool = mu...
[ 57, 8 ]
[]
[]
[ "multiprocessing", "pool", "python", "queue" ]
stackoverflow_0003217002_multiprocessing_pool_python_queue.txt
Q: Dial into FTP server (Data logger) using python (OS independent) I have a few data loggers in the field. The manufacturer set them up as dial up ftp servers. I'm writing a python program that automagically downloads all the latest files from the server into a specified folder on my computer. Which OS independent ...
Dial into FTP server (Data logger) using python (OS independent)
I have a few data loggers in the field. The manufacturer set them up as dial up ftp servers. I'm writing a python program that automagically downloads all the latest files from the server into a specified folder on my computer. Which OS independent library do you recommend for dial up? Do you have any suggestions, com...
[ "Why not use Python's built-in ftplib? Looks pretty straightforward, unless I'm missing something?\nFor using a modem with Python, this thread talks about using the pyserial module.\nI've never used pyserial with a modem, but I have with a USB port and an arduino. It was pretty straight forward, so I'm sure with so...
[ 1 ]
[]
[]
[ "dial_up", "ftp", "modem", "python" ]
stackoverflow_0003229407_dial_up_ftp_modem_python.txt
Q: a list > a list of lists In python, how can I split a long list into a list of lists wherever I come across '-'. For example, how can I convert: ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] to [['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']] Many thanks in advance. A: In [17]: import ...
a list > a list of lists
In python, how can I split a long list into a list of lists wherever I come across '-'. For example, how can I convert: ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] to [['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']] Many thanks in advance.
[ "In [17]: import itertools\n# putter around 22 times\nIn [39]: l=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']\n\nIn [40]: [list(g) for k,g in itertools.groupby(l,'---'.__ne__) if k]\nOut[40]: [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]\n\n", "import itertools\n\nl = ['1', 'a',...
[ 17, 4, 1, 1, 0 ]
[ "It's been a while since I've done any python so my syntax is going to be way off, but a simple loop should suffice.\nKeep track of the indexes in two numbers\nfirstList = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']\nlistIndex = 0\nitemIndex = 0\nii = 0\nforeach item in firstList\n if(firstLis...
[ -1 ]
[ "python" ]
stackoverflow_0003231894_python.txt
Q: numpy join entries intersecting at a cell In numpy, how can I join the entries that intersects at a cell? For example: Example http://img153.imageshack.us/img153/5162/matd.png In the example, I want to join rows/columns B and F into one row/column BF, where each element is the average of the ones with the same col...
numpy join entries intersecting at a cell
In numpy, how can I join the entries that intersects at a cell? For example: Example http://img153.imageshack.us/img153/5162/matd.png In the example, I want to join rows/columns B and F into one row/column BF, where each element is the average of the ones with the same color.
[ "What you want to do doesn't seem straightforward from a matrix point of view so doing in a \"pure numpy\" manner is likely unfeasible.\nI'd probably break it up into 2 or 3 operations:\n\nPull out row F, transpose it and average it with column B.\nTake the first value of the row F you pulled out and average it wit...
[ 1 ]
[]
[]
[ "intersection", "numpy", "python" ]
stackoverflow_0003230774_intersection_numpy_python.txt
Q: lxml removing tags when parsing? I'm currently working with parsing XML documents (adding elements, adding attributes, etc). So I first need to parse the XML in before working on it. However, lxml seems to be removing the element <?xml ...>. For example from lxml import etree tree = etree.fromstring('<?xml vers...
lxml removing tags when parsing?
I'm currently working with parsing XML documents (adding elements, adding attributes, etc). So I first need to parse the XML in before working on it. However, lxml seems to be removing the element <?xml ...>. For example from lxml import etree tree = etree.fromstring('<?xml version="1.0" encoding="utf-8"?><dmodule>te...
[ "The <?xml> element is an XML declaration, so it's not strictly an element. It just gives info about the XML tree below it.\nIf you need to print it out with lxml, there is some info here about the xmlDeclaration=TRUE flag you can use.\nhttp://lxml.de/api.html#serialisation\netree.tostring(tree, xml_declaration=Tru...
[ 7, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003232252_lxml_python_xml.txt
Q: How do I search from the bottom up using a regular expression? Here is an example of the type of text file I am trying to search (named usefile): DOCK onomatopoeia DOCK blah blah blah DOCK blah DOCK blah blah blah onomatopoeia blah blah blah blah blah DOCK DOCK blah blah DOCK blah onomatopoeia I am using a findite...
How do I search from the bottom up using a regular expression?
Here is an example of the type of text file I am trying to search (named usefile): DOCK onomatopoeia DOCK blah blah blah DOCK blah DOCK blah blah blah onomatopoeia blah blah blah blah blah DOCK DOCK blah blah DOCK blah onomatopoeia I am using a finditer statement to find everything between DOCK and onomatopoeia as foll...
[ "A negative lookahead assertion will do the trick.\nDOCK((?!DOCK).)+?onomatopoeia\n\n", "Here's an algorithmic approach:\n\nset pushing==false.\nBreak your text apart into words (e.g. spans of letters) and loop over those.\nupon hitting a DOCK and pushing==false, push it onto a stack and set pushing = true\nif yo...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003232659_python_regex.txt
Q: How do I convert a padded string to an integer while preserving padding? I followed the great example at Python: Nicest way to pad zeroes to string (4) but now I need to turn that padded string to a padded integer. I tried: list_padded=['0001101', '1100101', '0011011', '0011011', '1101111', '0000001', ...
How do I convert a padded string to an integer while preserving padding?
I followed the great example at Python: Nicest way to pad zeroes to string (4) but now I need to turn that padded string to a padded integer. I tried: list_padded=['0001101', '1100101', '0011011', '0011011', '1101111', '0000001', '1110111', 1101111', '0111001', '0011011', '0011001'] # My padded sting...
[ "Applying idea of padding to integers is meaningless. If you want to print/represent them you need strings, integers just don't have padding.\n", "Integers don't have a concept of padding, but if you want then you can store both the value and the original length instead of just the value:\nint_list = [(int(x), le...
[ 9, 4, 0 ]
[ "Since the INT type is a number it will be stored without leading zeros. Why would you want to store 675 as 00675? That's meaningless in the realm of integers. I would suggest storing the integers as integers and then only apply the padding when you access them and print them out (or whatever you are doing with the...
[ -1 ]
[ "integer", "padding", "python", "string" ]
stackoverflow_0003232256_integer_padding_python_string.txt
Q: Adding attributes to existing elements, removing elements, etc with lxml I parse in the XML using from lxml import etree tree = etree.parse('test.xml', etree.XMLParser()) Now I want to work on the parsed XML. I'm having trouble removing elements with namespaces or just elements in general such as <rdf:descriptio...
Adding attributes to existing elements, removing elements, etc with lxml
I parse in the XML using from lxml import etree tree = etree.parse('test.xml', etree.XMLParser()) Now I want to work on the parsed XML. I'm having trouble removing elements with namespaces or just elements in general such as <rdf:description><dc:title>Example</dc:title></rdf:description> and I want to remove that en...
[ "You can get to the root element via this call: root=tree.getroot()\nUsing that root element, you can use findall() and remove elements that match your criteria:\ndeleteThese = root.findall(\"title\")\nfor element in deleteThese: root.remove(element)\n\nFinally, you can see what your new tree looks like with this: ...
[ 24, 1 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003232618_lxml_python_xml.txt
Q: Class attributes reset when imported from package I have a project that is organized something like project/ __init__.py builder.py component/ __init__.py Within builder.py, I have a class called Builder that has several class attributes in order to implement the Borg pattern. The trouble aris...
Class attributes reset when imported from package
I have a project that is organized something like project/ __init__.py builder.py component/ __init__.py Within builder.py, I have a class called Builder that has several class attributes in order to implement the Borg pattern. The trouble arises when I try to import Builder in component/__init__.p...
[ "What you have is a circular import: builder imports component, component imports builder. \nAt the time builder imports component, builder is not yet fully constructed. Then component imports builder, which executes the rest of builder module (all after import component). Later, when component is loaded, builder c...
[ 1, 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0003216908_package_python.txt
Q: Assist with Python script I have written a code in Python, and I want to change it. I use it when I am performing a penetration tests in my organization and I want to make my script better. The script gets a username that I entering and it connect to the SMTP server over port 25 and check if the user exists or not...
Assist with Python script
I have written a code in Python, and I want to change it. I use it when I am performing a penetration tests in my organization and I want to make my script better. The script gets a username that I entering and it connect to the SMTP server over port 25 and check if the user exists or not. Here is the script: #!/usr/bi...
[ "You're not really supposed to use the low-level socket send() and recv() directly like that. They're not guaranteed to send/receive any particular amount of data. It might just happen to work the way you want talking to one particular mail server, but as soon as commands/responses don't fit one-to-one into IP pack...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003232648_python.txt
Q: How can I read an xml document/file into a DOM in python? I need to do screen scraping and for that I need to read some xml from python. I want to get a proper DOM tree out of it. How can I do that? A: Check out the minidom package which also has examples. BTW if your screen scraping is HTML don't use XML parsin...
How can I read an xml document/file into a DOM in python?
I need to do screen scraping and for that I need to read some xml from python. I want to get a proper DOM tree out of it. How can I do that?
[ "Check out the minidom package which also has examples.\nBTW if your screen scraping is HTML don't use XML parsing. There's other stuff for that.\n(Question about screen scraping, Question about python HTML screen scraping).\n", "The lxml library works well for scraping HTML. Here are some links to get you start...
[ 1, 0 ]
[]
[]
[ "dom", "python", "screen", "screen_scraping", "xml" ]
stackoverflow_0003231155_dom_python_screen_screen_scraping_xml.txt
Q: Python variable assignment confusion Why is it that when I do the following: x = y = {} Everytime I modify, x like x[1] = 5, I also end up modifying y and vice versa? A: You assign the names x and y to be pointing to one and the same dictionary, what behaviour would you expect? If you want them to point to diff...
Python variable assignment confusion
Why is it that when I do the following: x = y = {} Everytime I modify, x like x[1] = 5, I also end up modifying y and vice versa?
[ "You assign the names x and y to be pointing to one and the same dictionary, what behaviour would you expect?\nIf you want them to point to different dictionaries, use\nx = {}\ny = {}\n\nor\nx,y = {},{}\n\n", "Because x and y references the same dictionary.\nWhat happens under the hood:\n----- ------- \n| x | =...
[ 7, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003232376_python.txt
Q: App Engine Unique Non Numeric Code Using an alphabet like "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ" I'd like to generate 2 to 4 letter codes to identify unique datastore entries. I have a python function capable of doing this when passed an list indicating the letter positions of the last code [7,17,11] -> "7GA". the...
App Engine Unique Non Numeric Code
Using an alphabet like "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ" I'd like to generate 2 to 4 letter codes to identify unique datastore entries. I have a python function capable of doing this when passed an list indicating the letter positions of the last code [7,17,11] -> "7GA". the next code can be made by incrementing t...
[ "If you're attached to having the codes be sequential, you'll need to have a single counter object that is transactionally locked and incremented each time a new entity is created. The argument against this is that you're defeating one of the major advantages of App Engine: concurrency. Unless your application has ...
[ 5, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003232833_google_app_engine_python.txt
Q: Should I place custom registration code in Views, Models or Managers? I'm rolling my own custom registration module in Django based on django.contrib.auth. My registration module will have some extra functionality and help me reduce my dependency on other django modules that I'm currently using like django-registr...
Should I place custom registration code in Views, Models or Managers?
I'm rolling my own custom registration module in Django based on django.contrib.auth. My registration module will have some extra functionality and help me reduce my dependency on other django modules that I'm currently using like django-registration and django-emailchange. I've run into a what-the-best-way-to-do-it pr...
[ "Different from Chris, I believe on the philosophy of fat models, thin views.\nThe more code you can factor inside models, the more reusable your codebase is. Views concerns should be simply managing the request/response cycle and dealing with GET/POST parameters.\nIn this case, sending activation emails is related...
[ 2, 0 ]
[]
[]
[ "django", "django_authentication", "django_contrib", "python" ]
stackoverflow_0003226529_django_django_authentication_django_contrib_python.txt
Q: Which of `if x:` or `if x != 0:` is preferred in Python? Assuming that x is an integer, the construct if x: is functionally the same as if x != 0: in Python. Some languages' style guides explicitly forbid against the former -- for example, ActionScript/Flex's style guide states that you should never implicitly cas...
Which of `if x:` or `if x != 0:` is preferred in Python?
Assuming that x is an integer, the construct if x: is functionally the same as if x != 0: in Python. Some languages' style guides explicitly forbid against the former -- for example, ActionScript/Flex's style guide states that you should never implicitly cast an int to bool for this sort of thing. Does Python have a pr...
[ "The construct: if x: is generally used to check against boolean values.\nFor ints the use of the explicit x != 0 is preferred - along the lines of explicit is better than implicit (PEP 20 - Zen of Python).\n", "There's no hard and fast rule here. Here are some examples where I would use each:\nSuppose that I'm ...
[ 8, 4, 2, 1, 1, 0 ]
[ "Wouldn't if x is not 0: be the preferred method in Python, compared to if x != 0:?\nYes, the former is a bit longer to write, but I was under the impression that is and is not are preferred over == and !=. This makes Python easier to read as a natural language than as a programming language.\n" ]
[ -2 ]
[ "coding_style", "conditional", "python" ]
stackoverflow_0003216681_coding_style_conditional_python.txt
Q: SOAP Client for Python 3 Although this question is very popular here in StackOverflow, after spending some time here and in the Google, I still haven't find a concrete answer on what is the most appropriate way to do SOAP consuming in Python 3. I took a look at Does a Python 3 SOAP client module exist?, and I hop...
SOAP Client for Python 3
Although this question is very popular here in StackOverflow, after spending some time here and in the Google, I still haven't find a concrete answer on what is the most appropriate way to do SOAP consuming in Python 3. I took a look at Does a Python 3 SOAP client module exist?, and I hope it is outdated and today som...
[ "I would probably start by trying your suggested 2to3 port. For many things, it works pretty well. It would still be a day or two worth of work to convert something like suds, I imagine.\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x", "soap", "web_services", "wsdl" ]
stackoverflow_0003233298_python_python_3.x_soap_web_services_wsdl.txt
Q: Python: dynamic list parsing and processing I have popened a process which is producing a list of dictionaries, something like: [{'foo': '1'},{'bar':2},...] The list takes a long time to create and could be many gigabytes, so I don't want to reconstitute it in memory and then iterate over it. How can I parse the ...
Python: dynamic list parsing and processing
I have popened a process which is producing a list of dictionaries, something like: [{'foo': '1'},{'bar':2},...] The list takes a long time to create and could be many gigabytes, so I don't want to reconstitute it in memory and then iterate over it. How can I parse the partially completed list such that I can process ...
[ "The Python tokenizer is available as part of the Python standard library, module tokenize. It relies for its input on receiving at the start a readline function (which must supply to it a \"line\" of input), so it can operate incrementally -- if there are no newlines in your input, you can simulate that as long a...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003233043_python.txt
Q: How to use decorator? In SharpDevelop, I want to create a dll which contains a static methon, void Main(string[] args). Some one said I should use decorator to restrict the function in IronPython. I found "@staticmethod", but others, "void", "string[] args", how to restrict them? class MyClass: def __init__(se...
How to use decorator?
In SharpDevelop, I want to create a dll which contains a static methon, void Main(string[] args). Some one said I should use decorator to restrict the function in IronPython. I found "@staticmethod", but others, "void", "string[] args", how to restrict them? class MyClass: def __init__(self): pass @stat...
[ "Python doesn't have return types. Just don't return anything. You can do this either by using an empty return statement or by not using a return statement at all\n" ]
[ 0 ]
[]
[]
[ "decorator", "ironpython", "python" ]
stackoverflow_0003233710_decorator_ironpython_python.txt
Q: Map network drive with a Python service (There are other questions along these lines but none of them have any real answers, let alone answers dealing with python...) I have a Windows Service (XP SP3) written in Python that needs to be able to mount a network drive for ALL users. I tried using net use with subpro...
Map network drive with a Python service
(There are other questions along these lines but none of them have any real answers, let alone answers dealing with python...) I have a Windows Service (XP SP3) written in Python that needs to be able to mount a network drive for ALL users. I tried using net use with subprocess (even with the full path to net.exe), bu...
[ "Er... sadly, the short answer is no. If the Python program is running as a Windows service, there are multiple complications here... so let me explain.\nFirst, in order to even allow the service program itself to access the network, it'll have to be running under a user account that is allowed network access. The ...
[ 1 ]
[]
[]
[ "python", "service", "wmi" ]
stackoverflow_0003233756_python_service_wmi.txt
Q: wxPython on Mac OS X: creating a wx.Frame without stealing focus I managed to get it working on Win32 (inheriting from wx.MiniFrame does the trick), on wxGTK (wx.PopupWindow) but whatever I try, when I create a frame on wxMac, my main window loses focus and the new frame gets it. wxMac does not seem to have a way ...
wxPython on Mac OS X: creating a wx.Frame without stealing focus
I managed to get it working on Win32 (inheriting from wx.MiniFrame does the trick), on wxGTK (wx.PopupWindow) but whatever I try, when I create a frame on wxMac, my main window loses focus and the new frame gets it. wxMac does not seem to have a way to interact with the native platform (something like GetHandle() on Wi...
[ "If you want to get native handle to window in Mac you can do\nframe.MacGetTopLevelWindowRef()\n\nand may be you can use pyobjc to interact with windows natively, but why don't you set focus on the window you want to after opening mini-frame?\n" ]
[ 0 ]
[]
[]
[ "macos", "pyobjc", "python", "wxpython" ]
stackoverflow_0003222927_macos_pyobjc_python_wxpython.txt
Q: How to regex in python? I am trying to parse the keywords from google suggest, this is the url: http://google.com/complete/search?output=toolbar&q=test I've done it with php using: '|<CompleteSuggestion><suggestion data="(.*?)"/><num_queries int="(.*?)"/></CompleteSuggestion>|is' But that wont work with python re...
How to regex in python?
I am trying to parse the keywords from google suggest, this is the url: http://google.com/complete/search?output=toolbar&q=test I've done it with php using: '|<CompleteSuggestion><suggestion data="(.*?)"/><num_queries int="(.*?)"/></CompleteSuggestion>|is' But that wont work with python re.match(pattern, string), I tr...
[ "You could use etree:\n>>> from xml.etree.ElementTree import XMLParser\n>>> x = XMLParser()\n>>> x.feed('<toplevel><CompleteSuggestion><suggestion data=...')\n>>> tree = x.close()\n>>> [(e.find('suggestion').get('data'), int(e.find('num_queries').get('int')))\n for e in tree.findall('CompleteSuggestion')]\n[('t...
[ 5, 2 ]
[]
[]
[ "parsing", "python", "regex", "xml" ]
stackoverflow_0003234194_parsing_python_regex_xml.txt
Q: python, regex split and special character How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result. Example code: # -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything...
python, regex split and special character
How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result. Example code: # -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").split(s) pr...
[ "Your regex should be (\\s) instead of (\\W) like this:\nl = re.compile(\"(\\s)\").split(s)\n\nThe code above will give you the exact output you requested. However the following line makes more sense:\nl = re.compile(\"\\s\").split(s)\n\nwhich splits on whitespace characters and doesn't give you all the spaces as...
[ 16, 4, 3, 3, 0 ]
[]
[]
[ "python", "regex", "split", "unicode" ]
stackoverflow_0000647655_python_regex_split_unicode.txt
Q: How to parse command line arguments in Python? Possible Duplicate: What's the best way to grab/parse command line arguments passed to a Python script? I would like to be able to parse command line arguments in my Python 2.6 program. Ideally, I want to be able to handle these cases: # Show some help ./myprogram -...
How to parse command line arguments in Python?
Possible Duplicate: What's the best way to grab/parse command line arguments passed to a Python script? I would like to be able to parse command line arguments in my Python 2.6 program. Ideally, I want to be able to handle these cases: # Show some help ./myprogram --help # These are equivalent ./myprogram --block=1...
[ "Check out the argparse module (or optparse for older Python versions).\nNote that argparse/optparse are newer, better replacements for getopt, so if you're new to this they're the recommended option. From the getopt docs:\n\nNote The getopt module is a parser for command line options whose API is designed to be fa...
[ 33, 3, 1, 1 ]
[ "There might be a better way but I would just uses sys.argv and put in conditionals wherever needed i.e.\nif '--v' or '--vv' in sys.argv :\n print 'verbose message'\n\n" ]
[ -5 ]
[ "arguments", "command_line", "python" ]
stackoverflow_0003234216_arguments_command_line_python.txt
Q: What is the best way to publish RSS Feed on Facebook? What is the best way to publish an rss feed or a sitemap to facebook? I am using google app engine as the platform and the python language A: I don't know of a library that can do the feed to Facebook publication. There are a few apps that do this, like this...
What is the best way to publish RSS Feed on Facebook?
What is the best way to publish an rss feed or a sitemap to facebook? I am using google app engine as the platform and the python language
[ "I don't know of a library that can do the feed to Facebook publication. There are a few apps that do this, like this one.\nOne an Application is granted the publish_stream extended permission it can post on behalf of the User (or Page) using the api. There is a Python SDK which should work on AppEngine.\n" ]
[ 1 ]
[]
[]
[ "facebook", "google_app_engine", "publish", "python", "rss" ]
stackoverflow_0003227630_facebook_google_app_engine_publish_python_rss.txt
Q: view other computers on the network programatically in Python Is it possible to view other devices that are on the same network in Python (or any programming language for that matter)? Edit: For clarification, what I'd like to do (just to start out) is to display a list of devices connected and their local IP addr...
view other computers on the network programatically in Python
Is it possible to view other devices that are on the same network in Python (or any programming language for that matter)? Edit: For clarification, what I'd like to do (just to start out) is to display a list of devices connected and their local IP addresses. So on my router, it'll show the info: family_pc, 192.168.1.2...
[ "What are you trying to do exactly?\nnmap is a pretty common tool for scanning networks, which seems like you want to do. There is also a python-nmap package which lets you use nmap directly from within Python with ease.\nPlease be more detailed so we can give you a better answer, cheers.\n", "You have a couple o...
[ 8, 3 ]
[ "If you don't mind using a little third party software you could use Netresview which works nicely on windows systems, avoid reinventing the wheel and all that. You could this kind of thing.\nos.system('NetResView.exe /DisplayComputers 1 /RetrieveIPAddresses /stext ipfile')\nmy_file = open('ipfile')\nfor line in my...
[ -2 ]
[ "device", "networking", "python" ]
stackoverflow_0003233065_device_networking_python.txt
Q: help me understand python Initialize an array of arrays: M = [[]]*(24*60/5) Append the number 2 to the 51st array in M M[50].append(2) What is in M? ... [2] [2] [2] [2] [2] [2] [2] [2] ... Every element in M is the array [2] What am I missing? I suspect that every [] that I initially initialize is a reference t...
help me understand python
Initialize an array of arrays: M = [[]]*(24*60/5) Append the number 2 to the 51st array in M M[50].append(2) What is in M? ... [2] [2] [2] [2] [2] [2] [2] [2] ... Every element in M is the array [2] What am I missing? I suspect that every [] that I initially initialize is a reference to the same space in memory.
[ "You did create an array of arrays. But you then assigned the same [] to every one of its entries.\nIt's not that every time you call [] it gives you the same array - it's that you only called [] once.\nGet it?\n", "Yes, you got it, as Borealid pointed out.\nIf you want many times a different list, you can do:\n...
[ 5, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003234559_python.txt
Q: Python : match string inside double quotes and bracket I want to match text inside double quotes and bracket as two groups by use regex, How can I do that? from “作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為; “行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補) “成人”、“成年人”(adu...
Python : match string inside double quotes and bracket
I want to match text inside double quotes and bracket as two groups by use regex, How can I do that? from “作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為; “行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補) “成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂) “飛機”、“航空器”(aircraft) 指任何可憑空...
[ ">>> import re\n>>> s = u\"\"\"“作為”(act) ,用於罪行或民事過失時,包括一連串作為、任何違法的不作為和一連串違法的不作為;\n “行政上訴委員會”(Administrative Appeals Board) 指根據《行政上訴委員會條例》(第442章)設立的行政上訴委員會;(由1994年第6號第32條增補)\n “成人”、“成年人”(adult)* 指年滿18歲的人; (由1990年第32號第6條修訂)\n “飛機”、“航空器”(aircraft) 指任何可憑空氣的反作用而在大氣中獲得支承力的機器;\n “外籍人士”(alien) 指並非中國公民的人; (由19...
[ 1, 0, 0, 0 ]
[]
[]
[ "match", "python", "regex", "regex_group" ]
stackoverflow_0003234114_match_python_regex_regex_group.txt
Q: how can we run python script(which uses nltk and scrapy) from java I have written python scripts that use scrapy,nltk and simplejson in my project but i need to run them from java as my mentor wants to deploy them on a server and i have very less time to do this.I took a glance at runtime.exec() in java and jython...
how can we run python script(which uses nltk and scrapy) from java
I have written python scripts that use scrapy,nltk and simplejson in my project but i need to run them from java as my mentor wants to deploy them on a server and i have very less time to do this.I took a glance at runtime.exec() in java and jython, needless to say that running system commands from java doesn't look si...
[ "The Jepp project lets you call python scripts from Java. It provides an easy mechanism to pass variables into a script and extract values back. I've used on a few projects with good success\n" ]
[ 3 ]
[]
[]
[ "java", "jython", "nltk", "python", "scrapy" ]
stackoverflow_0003234965_java_jython_nltk_python_scrapy.txt
Q: What are the differences between struct_time and datetime? Is one preferred over the other? If so, in all cases or just a few? I am intending to use some form of date class for keeping long lists of date and time data, e.g. '2009-01-01 10:12:00'. A: struct_time is the old way of representing times, modeled after...
What are the differences between struct_time and datetime?
Is one preferred over the other? If so, in all cases or just a few? I am intending to use some form of date class for keeping long lists of date and time data, e.g. '2009-01-01 10:12:00'.
[ "struct_time is the old way of representing times, modeled after the C standard library. datetime came later, is more pythonic, is more featureful, and has more predictable behavior in edge cases than the struct_time functions. I would use datetime except in the rare cases where a measured performance difference ...
[ 5, 2 ]
[]
[]
[ "date_format", "python" ]
stackoverflow_0003235133_date_format_python.txt
Q: Backend processing for Django I'm working on a turn-based web game that will perform all world updates (player orders, physics, scripted events, etc.) on the server. For now, I could simply update the world in a web request callback. Unfortunately, that naive approach is not at all scalable. I don't want to bog...
Backend processing for Django
I'm working on a turn-based web game that will perform all world updates (player orders, physics, scripted events, etc.) on the server. For now, I could simply update the world in a web request callback. Unfortunately, that naive approach is not at all scalable. I don't want to bog down my web server when I start ru...
[ "I think Celery, which you mention in your question, is the way to go here. It will interface nicely with the rest of your setup, support your eventual aim of separating out the systems, and is compatible with Django.\n", "I'd just write the backend to just use the Django database interface (look at the setup cod...
[ 6, 0 ]
[]
[]
[ "distributed", "django", "python", "service" ]
stackoverflow_0003233844_distributed_django_python_service.txt
Q: Why do Selenium Python tests look so weird? I've used the Selenium IDE to generate some test code for my application. The generated Python code for an assertion looks like this. try: self.failUnless(sel.is_text_present("Path")) except AssertionError, e: self.verificationErrors.append(str(e)) Instead of fa...
Why do Selenium Python tests look so weird?
I've used the Selenium IDE to generate some test code for my application. The generated Python code for an assertion looks like this. try: self.failUnless(sel.is_text_present("Path")) except AssertionError, e: self.verificationErrors.append(str(e)) Instead of failing fast, the error is added to a list, and the...
[ "This is the difference between a verify and an assert in Selenium. When using verify any failures will be logged but the test will continue, they are in effect a 'soft assertion'. If you want to stop executing your test on a failure try using assert instead.\n//verifyTextPresent\ntry: self.failUnless(sel.is_text_p...
[ 6 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0003234869_python_selenium.txt
Q: Why am I encountering an ImportError when I try to 're-import' a module? I have a series of python modules written which are held in the same directory and I am having trouble with an ImportError. The three modules I am using are draw_menu.py, errors.py and file_operations.py. In errors.py I requires a list of err...
Why am I encountering an ImportError when I try to 're-import' a module?
I have a series of python modules written which are held in the same directory and I am having trouble with an ImportError. The three modules I am using are draw_menu.py, errors.py and file_operations.py. In errors.py I requires a list of error codes, I am using a custom method defined in file_operations.py to open a f...
[ "Circular imports can cause issues in Python (as you might expect). It's probably worth checking if:\nA) errors.py and file_operation.py should be single module (if they both rely so heavily on each other, do they need to be separate?)\nB) you can delay the import in one or the other module. An import statement in ...
[ 2, 1, 0 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0003235684_import_importerror_python.txt
Q: storing the output of a cursor object in csv format i've accessed a database and have the result in a cursor object. but i couldn't save it :( cur_deviceauth.execute('select * from device_auth') for row in cur_deviceauth: print row writer = csv.writer(open("out.csv", "w")) writer.writerows(cur_deviceau...
storing the output of a cursor object in csv format
i've accessed a database and have the result in a cursor object. but i couldn't save it :( cur_deviceauth.execute('select * from device_auth') for row in cur_deviceauth: print row writer = csv.writer(open("out.csv", "w")) writer.writerows(cur_deviceauth) i don't get an error msg and i couldn't write it. ...
[ "When you're printing rows before writing to a file, you're exhausting cursor object that works as a generator. Just write to file without any intermediate steps.\n" ]
[ 2 ]
[]
[]
[ "csv", "file_io", "python", "sqlite" ]
stackoverflow_0003235887_csv_file_io_python_sqlite.txt
Q: Dumping Collection to YAML file with PyYaml I am writing a python application. I am trying to dump my python object into yaml using PyYaml. I am using Python 2.6 and running Ubuntu Lucid 10.04. I am using the PyYAML package in Ubuntu Package: http://packages.ubuntu.com/lucid/python/python-yaml My object has 3 text...
Dumping Collection to YAML file with PyYaml
I am writing a python application. I am trying to dump my python object into yaml using PyYaml. I am using Python 2.6 and running Ubuntu Lucid 10.04. I am using the PyYAML package in Ubuntu Package: http://packages.ubuntu.com/lucid/python/python-yaml My object has 3 text variables and a list of objects. Roughly it is s...
[ "The PyYaml module takes care of the details for you, hopefully the following snippet will help \nimport sys\nimport yaml\n\nclass AnotherClass:\n def __init__(self):\n pass\n\nclass MyClass:\n def __init__(self):\n self.text_variable_1 = 'hello'\n self.text_variable_2 = 'world'\n ...
[ 2 ]
[]
[]
[ "python", "pyyaml", "ubuntu_10.04" ]
stackoverflow_0003233921_python_pyyaml_ubuntu_10.04.txt
Q: Ordered ManyToManyField that can be used in fieldsets I've been working through an ordered ManyToManyField widget, and have the front-end aspect of it working nicely: Unfortunately, I'm having a great deal of trouble getting the backend working. The obvious way to hook up the backend is to use a through table key...
Ordered ManyToManyField that can be used in fieldsets
I've been working through an ordered ManyToManyField widget, and have the front-end aspect of it working nicely: Unfortunately, I'm having a great deal of trouble getting the backend working. The obvious way to hook up the backend is to use a through table keyed off a model with ForeignKeys to both sides of the relat...
[ "In regard to how to set up the models, you're right in that a through table with an \"order\" column is the ideal way to represent it. You're also right in that Django will not let you refer to that relationship in a fieldset. The trick to cracking this problem is to remember that the field names you specify in th...
[ 9 ]
[]
[]
[ "django", "django_admin", "manytomanyfield", "python" ]
stackoverflow_0003190735_django_django_admin_manytomanyfield_python.txt
Q: Parsing Python HTML POST data from BaseHTTPServer I'm sending a couple of files from an HTML form to my server which is based on BaseHTTPServer. Within my do_POST I'm getting a string from rfile.read(length) which looks like some sort of multipart MIME string. Google is not being helpful on how I can decode this ...
Parsing Python HTML POST data from BaseHTTPServer
I'm sending a couple of files from an HTML form to my server which is based on BaseHTTPServer. Within my do_POST I'm getting a string from rfile.read(length) which looks like some sort of multipart MIME string. Google is not being helpful on how I can decode this into something usable. The output looks like this : --...
[ "Would cgi.parse_multipart meet your need? Also see a relevant discussion on comp.lang.python.\n" ]
[ 6 ]
[]
[]
[ "basehttpserver", "http", "post", "python" ]
stackoverflow_0003236597_basehttpserver_http_post_python.txt
Q: Google app engine: reverse reference lookups Is reverse referencing possible in Google app engine? I am using app engine patch to develope an application and my model is something like: class Portfolio(db.Model): user = db.ReferenceProperty(User) pic = db.BlobProperty() Now, If I have the user object, is it...
Google app engine: reverse reference lookups
Is reverse referencing possible in Google app engine? I am using app engine patch to develope an application and my model is something like: class Portfolio(db.Model): user = db.ReferenceProperty(User) pic = db.BlobProperty() Now, If I have the user object, is it possible to retrieve the pic associated with the ...
[ "Yes. You can access the pics, via:\nuser = User()\npics = user.portfolio_set\n\nYou can change the default name (which is modelname_set) by passing the collection_name argument to the ReferenceProperty constructor. For example:\nclass Portfolio(db.Model):\n user = db.ReferenceProperty(User, collection_name=\"Port...
[ 1, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003236890_django_google_app_engine_python.txt
Q: Term-Topic Matrix for a huge file I have a list of 17 million sentences in a text file. Each sentence contains at max 200 characters. Each sentence is also accompanied by one or more annotation(s) with it. I have a list of unique annotations and a list of unique words obtained from the 17 million sentences. I have...
Term-Topic Matrix for a huge file
I have a list of 17 million sentences in a text file. Each sentence contains at max 200 characters. Each sentence is also accompanied by one or more annotation(s) with it. I have a list of unique annotations and a list of unique words obtained from the 17 million sentences. I have to create a sparse matrix with the row...
[ "For sparse matrices, do not use an actual matrix or list.\nUse a dictionary, keyed, by word and annotation. Much simpler.\nmatrix[ (word,annotation) ] += 1\n\n", "In python2.7+ you can use a Counter\n>>> from collections import Counter\n>>> matrix = Counter()\n>>> matrix[(word,annotation)]+=1\n\nfor older pytho...
[ 3, 0 ]
[]
[]
[ "java", "lucene", "mysql", "python", "search" ]
stackoverflow_0003236181_java_lucene_mysql_python_search.txt
Q: Inserting utf8 characters in DB using Django In Django how to use unicode when inserting into DB Example: name =request.POST["name"] //This may be in Chinese or any other lanuages usr = Users(name=name) usr.save() The Python version that is used in Cent os is python 2.4.3 and mod python versi...
Inserting utf8 characters in DB using Django
In Django how to use unicode when inserting into DB Example: name =request.POST["name"] //This may be in Chinese or any other lanuages usr = Users(name=name) usr.save() The Python version that is used in Cent os is python 2.4.3 and mod python version is 1.2.1_p2-1
[ "you should check if your database has utf8 charset on table in which you are trying to insert.\nfor mysql \nshow create table TableName;\n\nto change encoding\n alter table TableName DEFAULT CHARACTER SET utf8;\n\n", "What database are you using? If it's MySQL, make sure you follow the Django documentation on ...
[ 5, 1, 0 ]
[]
[]
[ "django", "django_views", "python", "utf_8" ]
stackoverflow_0003237326_django_django_views_python_utf_8.txt
Q: Is there a direct equivalent in Java for Python's str.join? Possible Duplicates: What’s the best way to build a string of delimited items in Java? Java: convert List<String> to a join()d string In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the res...
Is there a direct equivalent in Java for Python's str.join?
Possible Duplicates: What’s the best way to build a string of delimited items in Java? Java: convert List<String> to a join()d string In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there som...
[ "Nope there is not. Here is my attempt:\n/**\n * Join a collection of strings and add commas as delimiters.\n * @require words.size() > 0 && words != null\n */\npublic static String concatWithCommas(Collection<String> words) {\n StringBuilder wordList = new StringBuilder();\n for (String word : words) {\n ...
[ 15, 14, 8, 3, 0 ]
[]
[]
[ "java", "python", "string" ]
stackoverflow_0003236213_java_python_string.txt
Q: How to install python on Samsung S5600 halley EVO I would like to know how to install python on Samsung S5600 Halley Evo. Do I have to do something like a jailbreak? Is it possible? and, if yes, how? A: What you actually need is to download Android Scripting Environment, since I guess your Samsung is an Android ...
How to install python on Samsung S5600 halley EVO
I would like to know how to install python on Samsung S5600 Halley Evo. Do I have to do something like a jailbreak? Is it possible? and, if yes, how?
[ "What you actually need is to download Android Scripting Environment, since I guess your Samsung is an Android phone. Within the ASE, you can determine which programming languages to use, weather its plain unix Shell, Python or Perl. Up to 10 different scripting languages are supported.\nJailbreaking is something y...
[ 0 ]
[]
[]
[ "jailbreak", "mobile", "python" ]
stackoverflow_0003235837_jailbreak_mobile_python.txt
Q: Can we learn Django for a python beginner? Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ? A: Yes, you can. I started learning Django with very little Python knowledge too. As long as you have...
Can we learn Django for a python beginner?
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
[ "Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.\nPython's a pretty easy language to pick up too. Just have to get used to the significant w...
[ 9, 6, 2, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003234402_django_python.txt
Q: Python Plugin for XCode I'm searching for a Xcode plugin to develop Python applications on Mac OS X platform. Can you give me some links please ? That will be very kind of you. Cordially, Vynile. A: XCode can create Cocoa-Python application projects by default. Why do you want a plugin? EDIT It seems Apple remo...
Python Plugin for XCode
I'm searching for a Xcode plugin to develop Python applications on Mac OS X platform. Can you give me some links please ? That will be very kind of you. Cordially, Vynile.
[ "XCode can create Cocoa-Python application projects by default.\nWhy do you want a plugin?\nEDIT\nIt seems Apple removed (since XCode 3.2) the project templates for third-party languages, like Python.\nSo on a fresh XCode installation, they are not available.\nYou can still get them from here: http://svn.red-bean.c...
[ 3 ]
[]
[]
[ "python", "xcode" ]
stackoverflow_0003237674_python_xcode.txt
Q: How to create decorator for lazy initialization of a property I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example: def SomeClass(object): @LazilyInitializedProperty def foo(se...
How to create decorator for lazy initialization of a property
I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example: def SomeClass(object): @LazilyInitializedProperty def foo(self): print "Now initializing" return 5 >>> x = Som...
[ "Denis Otkidach's CachedAttribute is a method decorator which makes attributes lazy (computed once, accessible many). To make it also read-only, I added a __set__ method. To retain the ability to recalculate (see below) I added a __delete__ method:\nclass ReadOnlyCachedAttribute(object): \n '''Computes attrib...
[ 15 ]
[]
[]
[ "decorator", "descriptor", "lazy_initialization", "python" ]
stackoverflow_0003237678_decorator_descriptor_lazy_initialization_python.txt
Q: How to update document's metadata in Sharepoint? (Linux -> WebServices -> Sharepoint) I managed to upload a file (crud PUT khe khe :) from Linux to Sharepoint. The absolute path of the file is: http://myhost/mysite/reports/2010-04-13/file.txt Now, I'm trying to add some metadata to the file: from suds.transport.h...
How to update document's metadata in Sharepoint? (Linux -> WebServices -> Sharepoint)
I managed to upload a file (crud PUT khe khe :) from Linux to Sharepoint. The absolute path of the file is: http://myhost/mysite/reports/2010-04-13/file.txt Now, I'm trying to add some metadata to the file: from suds.transport.https import WindowsHttpAuthenticated url='http://myhost/mysite/_vti_bin/lists.asmx?WSDL' n=...
[ "Found it! :)\nInstead of a plain text XML one must use DOM objects, something like this:\nb = Element(\"Batch\")\nb.append(Attribute(\"OnError\",\"Continue\")).append(Attribute(\"ListVersion\",\"3\"))\nbm= Element(\"Method\")\nbm.append(Attribute(\"ID\",\"1\")).append(Attribute(\"Cmd\",\"Update\"))\nbm.append(Elem...
[ 4, 3 ]
[]
[]
[ "linux", "python", "sharepoint", "web_services" ]
stackoverflow_0002629918_linux_python_sharepoint_web_services.txt
Q: How can I freeze a dual-mode (GUI and console) application using cx_Freeze? I've developed a Python application that runs both in the GUI mode and the console mode. If any arguments are specified, it runs in a console mode else it runs in the GUI mode. I've managed to freeze this using cx_Freeze. I had some proble...
How can I freeze a dual-mode (GUI and console) application using cx_Freeze?
I've developed a Python application that runs both in the GUI mode and the console mode. If any arguments are specified, it runs in a console mode else it runs in the GUI mode. I've managed to freeze this using cx_Freeze. I had some problems hiding the black console window that would pop up with wxPython and so I modif...
[ "I found this bit on this page:\n\nTip for the console-less version: If\n you try to print anything, you will\n get a nasty error window, because\n stdout and stderr do not exist (and\n the cx_freeze Win32gui.exe stub will\n display an error Window). This is a\n pain when you want your program to be\n able t...
[ 14, 2 ]
[]
[]
[ "cx_freeze", "python", "wxpython" ]
stackoverflow_0002883205_cx_freeze_python_wxpython.txt
Q: Python webservice client Can anyone make a webservice client in python from the following JAX-WS API? https://109.231.73.12:8090/API?wsdl As I'm running this of a virtual server it's self signed. Both the username and password are 'querty123' We can get it to work in php just fine not python. So a working example ...
Python webservice client
Can anyone make a webservice client in python from the following JAX-WS API? https://109.231.73.12:8090/API?wsdl As I'm running this of a virtual server it's self signed. Both the username and password are 'querty123' We can get it to work in php just fine not python. So a working example explaining how you managed to ...
[ "The suds library makes this a snap in Python:\n>>> from suds.client import Client\n>>> url = 'https://109.231.73.12:8090/API?wsdl'\n>>> client = Client(url, username='qwerty123', password='qwerty123')\n>>> client.service.addition(1, 2)\n3\n>>> client.service.hello('John')\nHelloJohn\n>>> client.service.xToThePower...
[ 5 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0003237985_python_web_services.txt
Q: lazy event publish subscribe in python I need an event messaging system in my google app engine application. and i was referring to following python library. http://pubsub.sourceforge.net/apidocs/concepts.html my question is , is it must that the listener function i want to execute must be imported ( or exist othe...
lazy event publish subscribe in python
I need an event messaging system in my google app engine application. and i was referring to following python library. http://pubsub.sourceforge.net/apidocs/concepts.html my question is , is it must that the listener function i want to execute must be imported ( or exist otherwise) somewhere in to the execution path in...
[ "tipfy (an App-Engine specific micro framework) has lazy loading, but only for the specific \"events\" that are web requests your code is serving. Other web frameworks have it too, but tipfy is small and simple enough to easily study and imitate its sources for the purpose.\nSo, if you can't find a richer event fr...
[ 1 ]
[]
[]
[ "events", "lazy_loading", "publish_subscribe", "python" ]
stackoverflow_0003237859_events_lazy_loading_publish_subscribe_python.txt
Q: Is it possible to repeat an iteration of a loop? I have defined a for loop as follows which scans through a file made up of two columns, when it finds the keyword DEFINE_MENU the second column on this line refers to the title for a screen. The next instance of the keyword will define a title for a seperate screen ...
Is it possible to repeat an iteration of a loop?
I have defined a for loop as follows which scans through a file made up of two columns, when it finds the keyword DEFINE_MENU the second column on this line refers to the title for a screen. The next instance of the keyword will define a title for a seperate screen and so on to the nth screen. At the moment the code is...
[ "If I understand your problem description correctly, you want to repeat the loop body (in certain cases) rather than \"the iteration\". If that's the case, one workable approach is to make the loop body into a possibly-recursive function, returning True if the loop is to break, False if it is to continue, as well ...
[ 2, 0, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0003238080_for_loop_python.txt
Q: Using Django's memcache API on Dynamically created models So I have a function which creates a dynamic model. I accomplish this in a way very similar to AuditTrail (see django wiki). Sample of code is here: https://gist.github.com/0212845ae00891efe555 Is there any way I can make a dynamically-generated class pick...
Using Django's memcache API on Dynamically created models
So I have a function which creates a dynamic model. I accomplish this in a way very similar to AuditTrail (see django wiki). Sample of code is here: https://gist.github.com/0212845ae00891efe555 Is there any way I can make a dynamically-generated class pickle-able? Ideally something thats not a crazy monkeypatch/hack?
[ "I am aware of the problem where pickle can't store a generated or dynamic class. I solved this by rigging in my dynamic type into the modules dict like so:\nnew_class = type(name, (models.Model,), attrs)\nmod = sys.modules[new_class.__module__]\nmod.__dict__[new_class.__name__] = new_class\n\nIt's FAR from a clean...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "memcached", "pickle", "python" ]
stackoverflow_0002966957_django_django_models_memcached_pickle_python.txt
Q: Basic SSL Server Using Twisted Not Responding I am currently trying to pull together a basic SSL server in twisted. I pulled the following example right off their website: from twisted.internet import ssl, reactor from twisted.internet.protocol import Factory, Protocol class Echo(Protocol): def dataReceived(s...
Basic SSL Server Using Twisted Not Responding
I am currently trying to pull together a basic SSL server in twisted. I pulled the following example right off their website: from twisted.internet import ssl, reactor from twisted.internet.protocol import Factory, Protocol class Echo(Protocol): def dataReceived(self, data): """As soon as any data is recei...
[ "You're not sending an http header back to the browser, and you're not closing the connection\n", "You've implemented an SSL echo server here, not an HTTPS server. Use the openssl s_client command to test it interactively, not firefox (or any other HTTP client, for that matter).\n" ]
[ 2, 1 ]
[]
[]
[ "python", "ssl", "twisted" ]
stackoverflow_0003237675_python_ssl_twisted.txt
Q: python introspection - how to detect the object i am in Suppose I have a free function which has been called from a class method. Is there a way for me to introspect the call stack in the free function and determine what object called me? def foo(arg1) : s = ? #Introspect call stack and determine what object cal...
python introspection - how to detect the object i am in
Suppose I have a free function which has been called from a class method. Is there a way for me to introspect the call stack in the free function and determine what object called me? def foo(arg1) : s = ? #Introspect call stack and determine what object called me # Do something with s Thanks!
[ "There isn't really the concept of \"a calling object\". You can introspect the stack and find if your calling function has a first argument named self, I guess -- if you're called directly from a normally-coded instance method (absolutely not a class method as you say... I imagine you're just horribly mis-speakin...
[ 2 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0003238673_introspection_python.txt
Q: Documenting public global functions with epydoc I have a module containing multiple global functions, and a global variable. The variable and some of the functions follow the 'private' naming convention for Python, with a leading underscore for the name. The other functions are intended to be public, and do not ha...
Documenting public global functions with epydoc
I have a module containing multiple global functions, and a global variable. The variable and some of the functions follow the 'private' naming convention for Python, with a leading underscore for the name. The other functions are intended to be public, and do not have a leading underscore. I have declared __all__, wit...
[ "This problem disappears when using epydoc to document more than one file. It seems to be a bug in epydoc, but it's easily worked around, so long as you have an actual package to document, rather than a single module.\n" ]
[ 3 ]
[]
[]
[ "documentation_generation", "epydoc", "python" ]
stackoverflow_0003231938_documentation_generation_epydoc_python.txt
Q: Making QProgressDialog update, also value does not change I have a progress which I "mintor" with a QProgessDialog in PyQt4. Basicly, I have a loop like this: while progressThread.isRunning(): self.progressDialog.setRange(0, self.progressTotal_) self.progressDialog.setValue(self.progress_) del self.progres...
Making QProgressDialog update, also value does not change
I have a progress which I "mintor" with a QProgessDialog in PyQt4. Basicly, I have a loop like this: while progressThread.isRunning(): self.progressDialog.setRange(0, self.progressTotal_) self.progressDialog.setValue(self.progress_) del self.progressDialog The progressThread upades the variables self.progessTo...
[ "You should connect an update signal from your thread to the progress dialog. You're blocking the UI thread with your loop. You could add a QApplication::processEvents call in the loop, but just don't block the UI thread and you'll be fine.\n" ]
[ 0 ]
[]
[]
[ "progressdialog", "pyqt4", "python" ]
stackoverflow_0003238927_progressdialog_pyqt4_python.txt
Q: Urllib quoting problem: dealing with â characters from a latin-1 database I need to get an â character into a format that can be passed to a URL. I'm obtaining some names as a json list, and then passing them elsewhere. result = json.load(urllib2.urlopen(LIST_URL), encoding='latin-1') for item in result: name ...
Urllib quoting problem: dealing with â characters from a latin-1 database
I need to get an â character into a format that can be passed to a URL. I'm obtaining some names as a json list, and then passing them elsewhere. result = json.load(urllib2.urlopen(LIST_URL), encoding='latin-1') for item in result: name = item["name"] print name print urllib2.quote(name.lower()) This produ...
[ "quote() function requires str argument, not unicode. Use urllib2.quote(name.lower().encode('latin1')) (assuming your site accepts latin1 encoding).\n" ]
[ 2 ]
[]
[]
[ "encoding", "python", "urllib" ]
stackoverflow_0003238913_encoding_python_urllib.txt
Q: Python URLLib / URLLib2 POST I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data: data = urllib.urlencode({'q': 'Status'}) u = urllib2.urlopen('http://myserver/inout-tracker', data)...
Python URLLib / URLLib2 POST
I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data: data = urllib.urlencode({'q': 'Status'}) u = urllib2.urlopen('http://myserver/inout-tracker', data) for line in u.readlines(): prin...
[ "u = urllib2.urlopen('http://myserver/inout-tracker', data)\nh.request('POST', '/inout-tracker/index.php', data, headers)\n\nUsing the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.\nDoing a 302 will typically cause ...
[ 47 ]
[]
[]
[ "post", "python", "urllib", "urllib2" ]
stackoverflow_0003238925_post_python_urllib_urllib2.txt
Q: Can Ironpython be used to run multiple Python Virtual Machine Instances in parallel? Inspired from the game GunTactyx, where you write programs controlling fighting robots. Guntactyx used the Small language, that later is called Pawn. I am looking into using Python as the scripting language. My concerns are: Int...
Can Ironpython be used to run multiple Python Virtual Machine Instances in parallel?
Inspired from the game GunTactyx, where you write programs controlling fighting robots. Guntactyx used the Small language, that later is called Pawn. I am looking into using Python as the scripting language. My concerns are: Interfacing to C# The scripts should interface into C# through simple functions, doing stuff ...
[ "The answer to your subject question is yes, you can run multiple interpreters in parallel. Generally each script will run in its own ScriptScope, but you can also use isolated ScriptEngines if necessary.\n\nYou can inject variables/functions into a script's scope before running it using scope.SetVariable.\nYour be...
[ 1 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0003237909_ironpython_python.txt
Q: How to suppress carriage return after a variable? Don't flame but I'm still a python newbie. I need to suppress the carriage return after I display a variable. data = """ [virtual_machines: %s] \taddress %s.domain.com """ % (line, line) fg = file('munin.txt', 'a') fg.write(stuff) When printing this out, it c...
How to suppress carriage return after a variable?
Don't flame but I'm still a python newbie. I need to suppress the carriage return after I display a variable. data = """ [virtual_machines: %s] \taddress %s.domain.com """ % (line, line) fg = file('munin.txt', 'a') fg.write(stuff) When printing this out, it creates a new line after the variable gets printed. I tr...
[ "If I understand your question correctly, you are seeing a new-line after the %s. It looks like line may have a newline in it, in which case you can do line.strip() to remove all whitespace around it:\n... \" % (line.strip(), line.strip())\n\nor\n ... \" % (line.strip(), ) * 2\n\nIf you are seeing an unwanted newl...
[ 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003240017_python.txt
Q: IOError: [Errno 22] Invalid Argument with clock() being passed in I have not had much luck hunting for finding a good explanation of what invalid argument errors are and what would cause them. My current sample I am working with is import sys mylog="mylog.log" sys.stdout = open(mylog,'w') #lots of code #. #. #. ...
IOError: [Errno 22] Invalid Argument with clock() being passed in
I have not had much luck hunting for finding a good explanation of what invalid argument errors are and what would cause them. My current sample I am working with is import sys mylog="mylog.log" sys.stdout = open(mylog,'w') #lots of code #. #. #. #End of lots of code from time import clock print "blablabla",clock() ...
[ "I can't reproduce this exact problem on my own computer, so I can't give specific advice, but here is some general commentary on how to debug this sort of thing.\nWhen you see \"Invalid argument\" in an IOError or OSError exception from python, that means the interpreter tried to make a system call, which failed a...
[ 3 ]
[]
[]
[ "invalid_argument", "ioerror", "python", "stdout" ]
stackoverflow_0003239883_invalid_argument_ioerror_python_stdout.txt
Q: multiple instances of django on a single domain I'm looking for a good way to install multiple completely different Django projects on the same server using only a single domain name. The point is that I want to browse to something like: http://192.168.0.1/gallery/ # a Django photo gallery project http://192....
multiple instances of django on a single domain
I'm looking for a good way to install multiple completely different Django projects on the same server using only a single domain name. The point is that I want to browse to something like: http://192.168.0.1/gallery/ # a Django photo gallery project http://192.168.0.1/blog/ # a blogging project This way, I ...
[ "I've been in situations where I couldn't use subdomains, and the way to handle this with Django is pretty simple actually.\nPretty much everything in your settings file will be just like a regular Django app, with the exception of making sure these settings include your project path:\nMEDIA_URL = 'http://192.168.0...
[ 16, 6, 3, 2, 1, 1 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0003232349_apache_django_python.txt
Q: Python and HTML: Assign a variable to a submit button I'm writing this to a text file which is then read in by my browser. How do I assign the variable "i[0]" to the to the "submit" button so it is passed to my edit_python script? k.write('<table>') for i in row: k.write('<tr>') k.write('<td><f...
Python and HTML: Assign a variable to a submit button
I'm writing this to a text file which is then read in by my browser. How do I assign the variable "i[0]" to the to the "submit" button so it is passed to my edit_python script? k.write('<table>') for i in row: k.write('<tr>') k.write('<td><form action="edit_python" method="post" name="edit_python"><...
[ "Put it in a hidden input element. In this case, it will be assigned to the ivalue post request variable.\nk.write('<table>')\n for i in row:\n k.write('<tr>')\n k.write('<td><form action=\"edit_python\" method=\"post\" name=\"edit_python\"><input type=\"hidden\" name=\"ivalue\" value=\"' + i[0] + ...
[ 2, 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003240271_html_python.txt
Q: Recompiling Python to fix arrow keys in interactive mode issue I am working in python 2.6 (installed alongside Python2.4.3 required for CentOS) and I am having issues with the arrow keys and backspace etc. I compiled from source and I imagine the solution is to recompile after installing readline-devel as outlined...
Recompiling Python to fix arrow keys in interactive mode issue
I am working in python 2.6 (installed alongside Python2.4.3 required for CentOS) and I am having issues with the arrow keys and backspace etc. I compiled from source and I imagine the solution is to recompile after installing readline-devel as outlined in: Seeing escape characters when pressing the arrow keys in python...
[ "As long as you use the same compiler that was originally used, you should be fine, I think. Especially if you don't have any extensions to recompile, because those are what would be affected.\nhttp://docs.python.org/release/2.6.5/install/index.html#building-extensions-tips-and-tricks\n\nthe same compiler and linke...
[ 2 ]
[]
[]
[ "python", "python_module", "readline" ]
stackoverflow_0003240516_python_python_module_readline.txt
Q: How to specify python interpreter on Windows My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix #!/usr/bin/python2.6. But what if I use Windows? Does any way to...
How to specify python interpreter on Windows
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix #!/usr/bin/python2.6. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I...
[ "the shebang line: \n#!/usr/bin/python2.6\n\n... will be ignored in Windows.\nIn Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\\Python26) to their PATH (environment variable) so you can just type \"python\" at any command l...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003236983_python.txt
Q: Issues with BeautifulSoup parsing I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? i...
Issues with BeautifulSoup parsing
I am trying to parse an html page with BeautifulSoup, but it appears that BeautifulSoup doesn't like the html or that page at all. When I run the code below, the method prettify() returns me only the script block of the page (see below). Does anybody has an idea why it happens? import urllib2 from BeautifulSoup import...
[ "Try with version 3.0.7a as Łukasz suggested. BeautifulSoup 3.1 was designed to be compatible with Python 3.0 so they had to change the parser from SGMLParser to HTMLParser which seems more vulnerable to bad HTML.\nFrom the changelog for BeautifulSoup 3.1:\n\"Beautiful Soup is now based on HTMLParser rather than SG...
[ 6, 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0000601166_beautifulsoup_python.txt
Q: Authentication in Google App Engine: app.yaml vs. python code I am writing a small app that uses the GAE. I have parts of my app that are for administrative use only. I have two options using login: admin option in the app.yaml or google.appengine.api.users.is_current_user_admin() in python code. The basic authent...
Authentication in Google App Engine: app.yaml vs. python code
I am writing a small app that uses the GAE. I have parts of my app that are for administrative use only. I have two options using login: admin option in the app.yaml or google.appengine.api.users.is_current_user_admin() in python code. The basic authentication is sufficient for my case. Which solution is better? The ad...
[ "I would say your assertions are correct. Let's say you have the following in your app.yaml:\n- url: /admin/.*\n script: admin.py\n login: admin\n\nIf you want everything in admin.py to be restricted to administrators, the configuration above ought to be more performant: you can fail unauthorized requests without...
[ 13, 2 ]
[]
[]
[ "authentication", "google_app_engine", "python" ]
stackoverflow_0003240990_authentication_google_app_engine_python.txt
Q: set process name in mod_wsgi I'm running a site by apache2.x with mod_wsgi 2.5, and python2.5. It is configured to run in multi-processes and each process only contains one thread. When I read this post, I try to set the process name to PATH_INFO, but it doesn't work. My code is like: import ctypes libc = ctypes....
set process name in mod_wsgi
I'm running a site by apache2.x with mod_wsgi 2.5, and python2.5. It is configured to run in multi-processes and each process only contains one thread. When I read this post, I try to set the process name to PATH_INFO, but it doesn't work. My code is like: import ctypes libc = ctypes.CDLL('/lib/libc.so.6') def applica...
[ "If you are using mod_wsgi daemon mode, is there anything wrong with the display-name option to WSGIDaemonProcess. That option is precisely for changing the name of the process to a fixed value using setproctitle() or argv[0] assignment as believed works for specific platforms. See:\nhttp://code.google.com/p/modwsg...
[ 3 ]
[]
[]
[ "mod_wsgi", "python" ]
stackoverflow_0003238010_mod_wsgi_python.txt
Q: Programmatically Uncheck a Checkbox in a wx.CheckListBox Is there a method to uncheck a checkbox in a wx.CheckListBox as I need to implement an "uncheck all" button, can't seem to find anything... although there is number of methods for setting a checkbox/s. A: Try this: for cb in mycblist.Checked: mycblist.C...
Programmatically Uncheck a Checkbox in a wx.CheckListBox
Is there a method to uncheck a checkbox in a wx.CheckListBox as I need to implement an "uncheck all" button, can't seem to find anything... although there is number of methods for setting a checkbox/s.
[ "Try this:\nfor cb in mycblist.Checked:\n mycblist.Check(cb, False)\n\n", "There is an optional \"check\" argument for Check() - see http://docs.wxwidgets.org/stable/wx_wxchecklistbox.html#wxchecklistboxcheck\nExample: clb.Check(itemnum, check=False)\n", "Use void wxCheckListBox::Check Check(int item, bool ch...
[ 2, 1, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003241273_python_user_interface_wxpython.txt
Q: Change package import name in python I was wondering if it was possible to import a library in python, and completely change its name. say i need to do : import plop.blah.wii but I want it to be recognized as foo.bar.yeah something like import plop.blah.wii as foo.bar.yeah Any idea how can this be done ? When ...
Change package import name in python
I was wondering if it was possible to import a library in python, and completely change its name. say i need to do : import plop.blah.wii but I want it to be recognized as foo.bar.yeah something like import plop.blah.wii as foo.bar.yeah Any idea how can this be done ? When unpickling an object, Python expects a lib...
[ "Rather than aliasing the module, there's a way to more directly solve your problem. You can override the method used by the pickler to resolve globals to map the old module name to the new module name. The details are here.\n" ]
[ 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003241379_import_python.txt
Q: How do i extract specific lines of data from a huge Excel sheet using Python? I need to get specific lines of data that have certain key words in them (names) and write them to another file. The starting file is a 1.5 GB Excel file. I can't just open it up and save it as a different format. How should I handle thi...
How do i extract specific lines of data from a huge Excel sheet using Python?
I need to get specific lines of data that have certain key words in them (names) and write them to another file. The starting file is a 1.5 GB Excel file. I can't just open it up and save it as a different format. How should I handle this using python?
[ "I'm the author and maintainer of xlrd. Please edit your question to provide answers to the following questions. [Such stuff in SO comments is VERY hard to read]\n\nHow big is the file in MB? [\"Huge\" is not a useful answer]\nWhat software created the file?\nHow much memory do you have on your computer?\nExactly w...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003241039_python.txt
Q: ValueError: need more than 1 value to unpack Here's the line that throws this error (x,neighbor) = random.sample(out_edge_list,1) A: You're asking for 1 unique random element. So you're getting back something like [5]. If the 5 goes into x, what goes into neighbor? Perhaps you meant to ask for 2 elements? (x, ne...
ValueError: need more than 1 value to unpack
Here's the line that throws this error (x,neighbor) = random.sample(out_edge_list,1)
[ "You're asking for 1 unique random element. So you're getting back something like [5]. If the 5 goes into x, what goes into neighbor?\nPerhaps you meant to ask for 2 elements?\n(x, neighbor) = random.sample(out_edge_list, 2)\n\n", "Here the solution. I changed the line to \n(x,neighbor) = random.sample(out_edge_l...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003241409_python.txt
Q: Send Raw hex data in jython udp packet I'm experience with Java, but I have to integrate a java library into a co-workers python code. Enter jython, yay! We are trying to send a UDP packet with a very specific data section. We are building up the packet like so: version = 0x0001 referenceNumber = 0x2323 bookID = b...
Send Raw hex data in jython udp packet
I'm experience with Java, but I have to integrate a java library into a co-workers python code. Enter jython, yay! We are trying to send a UDP packet with a very specific data section. We are building up the packet like so: version = 0x0001 referenceNumber = 0x2323 bookID = byteArray('df82818293819dbafde818ef') For ea...
[ "Check out the binascii module.\n" ]
[ 1 ]
[]
[]
[ "java", "jython", "python", "sockets" ]
stackoverflow_0003241612_java_jython_python_sockets.txt
Q: Is there a reason that a ReferenceProperty might not generate a back-reference? In my current project, I have two models, Version and Comment. There is a one-to-many relationship between the two; each Version can have many Comment and the Comment model has a ReferenceProperty to record which Version it belongs to:...
Is there a reason that a ReferenceProperty might not generate a back-reference?
In my current project, I have two models, Version and Comment. There is a one-to-many relationship between the two; each Version can have many Comment and the Comment model has a ReferenceProperty to record which Version it belongs to: class Comment(db.Model): version = db.ReferenceProperty(version.Version, collect...
[ "It looks like you are overwriting the automagical property called comments with your own property comments, in this line: \ncomments = self.comments.order('-added_on').fetch(500)\n\nWhat happens if you change the collection_name argument in your Comment model to be \"comments_set\", then change the above line to:\...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003240505_google_app_engine_python.txt
Q: Problems adding path and calling external program from Python I have an executable called "foo" in "/home/myname/mydir/" and am trying to call it from Python, but I am doing something basic and wrong here. Can you help me? import os, sys sys.path.append("/home/myname/mydir/") os.system("foo") # os.system("./foo") ...
Problems adding path and calling external program from Python
I have an executable called "foo" in "/home/myname/mydir/" and am trying to call it from Python, but I am doing something basic and wrong here. Can you help me? import os, sys sys.path.append("/home/myname/mydir/") os.system("foo") # os.system("./foo") doesn't work either Thanks
[ "sys.path is the path to Python libraries, not the system PATH to search for binaries. Try changing os.environ['PATH'] instead.\n>>> sys.path.append(\"/opt/local/bin\")\n>>> os.system(\"wget\")\nsh: wget: command not found\n32512\n>>> os.environ['PATH'] += os.pathsep + '/opt/local/bin'\n>>> os.system(\"wget\")\nwge...
[ 16, 3 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003241735_linux_python.txt
Q: Can python3.1 scripts be freezed in mac os x using cxfreeze? I m new to this and i need to freeze python3.1 scripts so that it can be run in other machines which does'nt have python3.1. CXFREEZE is the one which supports python 3.1 as far as i know. But i could not find any thread saying that freeze is successful...
Can python3.1 scripts be freezed in mac os x using cxfreeze?
I m new to this and i need to freeze python3.1 scripts so that it can be run in other machines which does'nt have python3.1. CXFREEZE is the one which supports python 3.1 as far as i know. But i could not find any thread saying that freeze is successful for python3.x. So can anybody tell me will it be done with cxfree...
[ "It sounds like you should be able to using cx_Freeze from SVN trunk according to this: http://www.mail-archive.com/cx-freeze-users@lists.sourceforge.net/msg00522.html\nNot many other executable builders for Python support 3.0 yet. cx_Freeze sounds like your best shot.\n" ]
[ 1 ]
[]
[]
[ "cx_freeze", "macos", "python", "python_3.x" ]
stackoverflow_0003210812_cx_freeze_macos_python_python_3.x.txt
Q: Only allow 1 instance of a python script Possible Duplicate: Python: single instance of program What is the best way to insure that only 1 copy of a python script is running? I am having trouble with python zombies. I tired creating a write lock using open("lock","w"), but python doesn't notify me if the fil...
Only allow 1 instance of a python script
Possible Duplicate: Python: single instance of program What is the best way to insure that only 1 copy of a python script is running? I am having trouble with python zombies. I tired creating a write lock using open("lock","w"), but python doesn't notify me if the file already has a write lock, it just seems to ...
[ "Try:\nimport os\nos.open(\"lock\", os.O_CREAT|os.O_EXCL)\n\nThe documentation for os.open and its flags.\n", "Your question is similar to this one: What is the best way to open a file for exclusive access in Python?. The answers given there should help you with your issue.\n(Use the flag combination portalocker...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003241754_python.txt
Q: python and search? am looking for method and function watch i can search in web page ! ok I'll explain it : i tell my python file .. go to www.example.com and search for that world "Hello guest" and if my python file found that world "Hello guest" my python file print "the world found!" and if he don't found he pr...
python and search?
am looking for method and function watch i can search in web page ! ok I'll explain it : i tell my python file .. go to www.example.com and search for that world "Hello guest" and if my python file found that world "Hello guest" my python file print "the world found!" and if he don't found he print "the world not found...
[ "Use Python's urllib module to fetch the content, and its re module to look for the word (make sure you use search instead of match; it's a common noob slip-up).\n", "The other answers here I believe are searching the html rather than the rendered content. If that's what you want that's fine, but if you want to ...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003242114_python.txt
Q: Pythonic syntax for appending an arbitrary class object list property Is there an analog of setattr() that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so? This is a trivialized version of what I'm doing currently: foo = SomeClass() .....
Pythonic syntax for appending an arbitrary class object list property
Is there an analog of setattr() that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so? This is a trivialized version of what I'm doing currently: foo = SomeClass() ... attr = "names" value = "Eric" values = getattr(foo, attr) values.append(v...
[ "The setattr call is redundant, if foo.names is indeed a list (if it's something else, could you please clarify?). getattr(foo, attr).append(value) is all you need.\n" ]
[ 15 ]
[]
[]
[ "python" ]
stackoverflow_0003242391_python.txt
Q: the best search engine written with python i want to build an information support system which is an web app. and we gonna use Django as the frame,but i don't know which search engine to use ? can you give me some suggestions on the search engine which we can use in our project,it must be written with python. than...
the best search engine written with python
i want to build an information support system which is an web app. and we gonna use Django as the frame,but i don't know which search engine to use ? can you give me some suggestions on the search engine which we can use in our project,it must be written with python. thanks
[ "I believe you'd be happy with whoosh, possibly \"fronted\" by Haystack which is a neat way to support any of several search engines in Django (but the other underlying engines it supports are not \"pure Python\"... whoosh is).\nI believe both whoosh and haystack support Unicode, so, in particular, Chinese too.\n",...
[ 12, 1, 0 ]
[]
[]
[ "django", "python", "search_engine" ]
stackoverflow_0003239576_django_python_search_engine.txt
Q: Python Popen.waitpid returns "[Errno 10] No child processes" I have a working Python script that executes an external command and calls Popen.communicate(). However when I call this script from a C process, it fails in os.waitpid() with "[Errno 10] No child processes". Why? This looks like a certain bug in Python,...
Python Popen.waitpid returns "[Errno 10] No child processes"
I have a working Python script that executes an external command and calls Popen.communicate(). However when I call this script from a C process, it fails in os.waitpid() with "[Errno 10] No child processes". Why? This looks like a certain bug in Python, but I'm not using threads. The C process forks, changes its UID, ...
[ "The problem in my case was that the C process was ignoring SIGCHLD. Since ignored signals are inherited by a forked process, Python process was ignoring it as well, which made waitpid() fail.\nSolution: set signal handlers in the C process after forking to SIG_DFL, if you've ignored any.\n" ]
[ 1 ]
[]
[]
[ "fork", "linux", "process", "python" ]
stackoverflow_0003234569_fork_linux_process_python.txt
Q: make data struct iterable in python So I've done some looking online and throught the documentation, but I'm having troubling finding out how to do this. I am working on creating an adventure game. I have a level class (which contains a bunch of rooms) and a Room class. I would like to be able to do something like...
make data struct iterable in python
So I've done some looking online and throught the documentation, but I'm having troubling finding out how to do this. I am working on creating an adventure game. I have a level class (which contains a bunch of rooms) and a Room class. I would like to be able to do something like the following. l = Level() for room in l...
[ "Use __iter__ with an iterator-generator. E.g.\ndef __iter__(self):\n for r in rooms:\n yield r\n\nAn iterator-generator is basically a psuedo-method used to implement an iterator. Note that there is no requirement that the generator use a for loop. It can use any combination of constructs (if, for, while, e...
[ 3, 3, 1 ]
[ "Why not use generator.\n>>> import timeit\n>>> class Test:\n def __iter__(self):\n for i in range(10):\n yield i\n\n>>> t1 = lambda: [k for k in Test()]\n>>> timeit.timeit(t1)\n3.529460948082189\n\n\n>>> def test2():\n for i in range(10):\n yield i\n\n>>> t2 = lambda: [k for k in tes...
[ -1 ]
[ "for_loop", "iterator", "loops", "python" ]
stackoverflow_0003240643_for_loop_iterator_loops_python.txt
Q: Using random.choice in conjuction with if statements So I'm really new to programming, I just started learning Python yesterday and I'm having a little trouble. I've looked through a few tutorials and haven't come up with how to answer my question on my own, so I'm coming to you guys. quickList = ["string1", "str...
Using random.choice in conjuction with if statements
So I'm really new to programming, I just started learning Python yesterday and I'm having a little trouble. I've looked through a few tutorials and haven't come up with how to answer my question on my own, so I'm coming to you guys. quickList = ["string1", "string2"] anotherList1 = ["another1a", "another1b"] anotherLi...
[ "Try storing them in a dictionary:\nd = {\n 'string1': ['another1a', 'another1b'],\n 'string2': ['another2a', 'another2b'],\n}\nchoice = random.choice(d.keys())\nprint choice, random.choice(d[choice])\n\n", "Try to think that logic through. I have formatted your exact words for you:\nif (quick turns up stri...
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003242637_python.txt
Q: Shared pointers and building in SIP4 (was: Dynamic casting in SWIG/python?) So I'm playing about with Python, C++0x, and SWIG 2.0. I've got a header that looks like this: #include <string> #include <iostream> #include <memory> using namespace std; struct Base { virtual string name(); int foo; shared_ptr<Bas...
Shared pointers and building in SIP4 (was: Dynamic casting in SWIG/python?)
So I'm playing about with Python, C++0x, and SWIG 2.0. I've got a header that looks like this: #include <string> #include <iostream> #include <memory> using namespace std; struct Base { virtual string name(); int foo; shared_ptr<Base> mine; Base(int); virtual ~Base() {} virtual void doit(shared_ptr<Base>...
[ "To (partially) answer my own question, SIP appears to do the right thing, both for the C++ \"Derived\" class as well as for a Python-level subclass — at least, when I use raw pointers. \nLooks like I'll need to figure out how to get it to work with shared_ptrs (looks not quite as easy as %include <std_shared_ptr.i...
[ 0 ]
[]
[]
[ "c++", "c++11", "python", "swig" ]
stackoverflow_0003217004_c++_c++11_python_swig.txt
Q: Edit .RAR file comments from python Ok, I need to be able to edit the file comments in .rar files from python. I can already view the comments using UnRAR. However, I need to embed metadata in the files in a way that is preserved over multiple file systems (e.g. alternate datastreams are out), so I can't really th...
Edit .RAR file comments from python
Ok, I need to be able to edit the file comments in .rar files from python. I can already view the comments using UnRAR. However, I need to embed metadata in the files in a way that is preserved over multiple file systems (e.g. alternate datastreams are out), so I can't really think of any other alternatives. rarfile se...
[ "I think you are out of luck. Unfortunately the RAR format is closed source and not documented, and there is no Python module that does what you want to do.\nThe only open-source tool I know that uncompress RAR files is The Unarchiver. I think that your best bet is check their sources and write your own Python tool...
[ 1 ]
[]
[]
[ "archive", "python", "python_2.6", "windows" ]
stackoverflow_0003201409_archive_python_python_2.6_windows.txt