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: Django: optimizing many to many query I have Post and Tag models: class Tag(models.Model): """ Tag for blog entry """ title = models.CharField(max_length=255, unique=True) class Post(models.Model): """ Blog entry """ tags = models.ManyToManyField(Tag) title = mod...
Django: optimizing many to many query
I have Post and Tag models: class Tag(models.Model): """ Tag for blog entry """ title = models.CharField(max_length=255, unique=True) class Post(models.Model): """ Blog entry """ tags = models.ManyToManyField(Tag) title = models.CharField(max_length=255) text ...
[ "Here's what I usually do in this situation: \nposts = Post.objects.filter(...)[:20]\n\npost_id_map = {}\nfor post in posts:\n post_id_map[post.id] = post\n # Iteration causes the queryset to be evaluated and cached.\n # We can therefore annotate instances, e.g. with a custom `tag_list`.\n # Note: Do...
[ 4, 1 ]
[]
[]
[ "django", "python", "query_optimization", "rails_postgresql" ]
stackoverflow_0005636482_django_python_query_optimization_rails_postgresql.txt
Q: django form widget rendering hey guys, i want to create a widget that renders a phone field in the following format box - box2 - box3 i have tried the different code snippets provided in this same site, however they dont overide the html rendering, which is what i want to do for example this: class USPhoneNumber...
django form widget rendering
hey guys, i want to create a widget that renders a phone field in the following format box - box2 - box3 i have tried the different code snippets provided in this same site, however they dont overide the html rendering, which is what i want to do for example this: class USPhoneNumberMultiWidget(forms.MultiWidget): ""...
[ "You can override the MultiWidget's format_output method:\ndef format_output(self, rendered_widgets):\n return u'%s - %s - %s' % \\\n (rendered_widgets[0], rendered_widgets[1], rendered_widgets[2])\n\nThere isn't a ton of documentation on custom form widgets. I've only made a couple, and they took...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005641463_django_django_forms_python.txt
Q: Pythonic way to avoid a mountain of if...else statements? This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary. If the value is different between them, I want to set the object.attr...
Pythonic way to avoid a mountain of if...else statements?
This has come up several times recently and I'd like to deal with it better than I have been: I have a series of attributes that I'm cross referencing between an object and a dictionary. If the value is different between them, I want to set the object.attribute to the dictionary['attribute'] value. I also want to kee...
[ "setattr() is what you're looking for:\nattributeList = (('Name', 'name', 'name'),\n ('Version', 'version', 'revision'))\n\nfor title, obj_attribute, dict_key in attributeList:\n obj_value = getattr(obj, obj_attribute)\n adict_value = adict[dict_key]\n\n if obj_value == adict_value:\n...
[ 6, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005640598_python.txt
Q: using a function changing my average from Fahrenheit to Celsius Hey guys. I got my average number of 32. I know that is freezing and it is 0 degrees in Celsius. What I have to do is use a function write a program to display it in Celsius. I know the Formula is C = (F - 32) * (5 / 9) def fahrenToCel(32): ret...
using a function changing my average from Fahrenheit to Celsius
Hey guys. I got my average number of 32. I know that is freezing and it is 0 degrees in Celsius. What I have to do is use a function write a program to display it in Celsius. I know the Formula is C = (F - 32) * (5 / 9) def fahrenToCel(32): return (this is the part where I am stumped.. I don't know if i'm miss...
[ "It's really simple:\ndef fahrenToCel(f):\n return (f - 32) * (5 / 9.0)\n\n", "First of all, the 32 should be in your call, not your definition:\ndef fahrenToCel(f):\n # Code to convert to Celcius here\n return c\n\nprint fahrenToCel(32)\n\n" ]
[ 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0005641991_python.txt
Q: Availability of IP Address - Python How to check the availability of an IP address in python? For example, I wan't to change my system's IP address to 192.168.112.226 statically overriding the dhcp provided address. The default gateway is 192.168.112.1. But I wan't to check before if anyone is using 192.168.112.22...
Availability of IP Address - Python
How to check the availability of an IP address in python? For example, I wan't to change my system's IP address to 192.168.112.226 statically overriding the dhcp provided address. The default gateway is 192.168.112.1. But I wan't to check before if anyone is using 192.168.112.226 before assigning to myself. Usually do ...
[ "This is so bad in so many ways I can't even explain how awfull this is.\nWhy do you want this? Could you please tell us that, and we could come up with a much better answer than this utterly uggly \"sollution\"?\nIf you have a Linux/Unix system, you can make your DHCP client to request the DHCP-server to give you...
[ 1, 0, 0 ]
[]
[]
[ "ip_address", "networking", "python", "static_ip_address" ]
stackoverflow_0005024478_ip_address_networking_python_static_ip_address.txt
Q: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python Inside my python scrip, I get some string back from a function which I didn't write. The encoding of it varies. I need to convert it to ascii format. Is there some fool-proof way of doing this? I don't mind replaci...
What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
Inside my python scrip, I get some string back from a function which I didn't write. The encoding of it varies. I need to convert it to ascii format. Is there some fool-proof way of doing this? I don't mind replacing the non-ascii chars with blanks or something else...
[ "If you want an ASCII string that unambiguously represents what you have got, without losing any information, the answer is simple:\nDon't muck about with encode/decode, use the repr() function (Python 2.X) or the ascii() function (Python 3.x).\n", "You say \"the encoding of it varies\". I guess that by \"it\" yo...
[ 10, 5, 4, 2, 1 ]
[]
[]
[ "ascii", "decode", "python", "utf_8" ]
stackoverflow_0001792602_ascii_decode_python_utf_8.txt
Q: How to select only certain tag and text using xpath? For example, html block: <p><b>text1</b> (<span><a href="#1">asdf</a>text2</span>)</p> I need to select all tags "a" and all the rest must be the plain text just like we see in browser: result = ["text1", " (", <tag_a>, "text2", ")"] or something like that. Tr...
How to select only certain tag and text using xpath?
For example, html block: <p><b>text1</b> (<span><a href="#1">asdf</a>text2</span>)</p> I need to select all tags "a" and all the rest must be the plain text just like we see in browser: result = ["text1", " (", <tag_a>, "text2", ")"] or something like that. Tried: hxs.select('.//a|text()') in this case it finds all ...
[ "It looks to me as if you are stepping beyond XPath territory. XPath is good at selecting things from the input but not at constructing output. It was designed, of course, for use with XSLT where XSLT instructions handle the output side. I'm not sure what the Python equivalent would be.\n", "Is this the kind of t...
[ 1, 1, 1 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0005629781_python_xpath.txt
Q: Unable to locate freeimage after install of mahotas in Python Hi I am new to Python and am following the Python Image Tutorial. The following executes with no errors after installing the packages described in the tutorial import numpy import scipy import pylab import pymorph import mahotas from scipy import ndimag...
Unable to locate freeimage after install of mahotas in Python
Hi I am new to Python and am following the Python Image Tutorial. The following executes with no errors after installing the packages described in the tutorial import numpy import scipy import pylab import pymorph import mahotas from scipy import ndimage However when I try reading an image image = mahotas.imread('pict...
[ "Answer for more recent versions of mahotas\nMahotas itself does not have the functionality to read in images. imread is just a wrapper around one of 3 backends:\n\nmahotas-imread (i.e., https://pypi.python.org/pypi/imread)\nFreeImage\nmatplotlib (which only supports PNG & JPEG)\n\nThus, you need to install one of ...
[ 2 ]
[]
[]
[ "installation", "mahotas", "package", "python" ]
stackoverflow_0005601410_installation_mahotas_package_python.txt
Q: How to monitor django-piston API Calls even bad ones i 'm heavily using django-piston for many of my projects, and i wanted to know if there was any way to monitor calls to a REST API creates using Django-Piston. Any Signals emitted ? or decorators ? and more importantly if anyone cares ? Because if some people ar...
How to monitor django-piston API Calls even bad ones
i 'm heavily using django-piston for many of my projects, and i wanted to know if there was any way to monitor calls to a REST API creates using Django-Piston. Any Signals emitted ? or decorators ? and more importantly if anyone cares ? Because if some people are dealing with creating REST API in Django, please tell me...
[ "You could easily modify one of your handlers to perform custom logging operations or otherwise anytime its called. For example:\nfrom piston import handler\nclass MyHandler(handler.BaseHandler):\n # blah blah blah\n\n def create(self, request):\n attrs = self.flatten_dict(request.POST)\n # log...
[ 3 ]
[]
[]
[ "django", "django_piston", "monitoring", "python", "rest" ]
stackoverflow_0005641959_django_django_piston_monitoring_python_rest.txt
Q: Only extract those words from a list that include no repeating letters, using regex I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets. INPUT: abducts abe abeam abel abele OUTPUT: abducts abe abel I'd like to do this using Regex (g...
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets. INPUT: abducts abe abeam abel abele OUTPUT: abducts abe abel I'd like to do this using Regex (grep or perl or python). Is that possible?
[ "It's much easier to write a regex that matches words that do have repeating letters, and then negate the match:\nmy @input = qw(abducts abe abeam abel abele);\nmy @output = grep { not /(\\w).*\\1/ } @input;\n\n(This code assumes that @input contains one word per entry.) But this problem isn't necessarily best solv...
[ 7, 5, 3, 3, 2, 2, 1, 1, 1 ]
[ "You can't do this with Regex. Regex is a Finite State Machine, and this would require a stack to store what letters have been seen.\nI would suggest doing this with a foreach and manually check each word with code.\nSomething like\nList chars\nforeach word in list\n foreach letter in word\n if chars.con...
[ -1 ]
[ "grep", "perl", "python", "regex" ]
stackoverflow_0005637963_grep_perl_python_regex.txt
Q: using functions to display numbers in a list I have a list of numbers and I have to use a function to display them in celsius, they are in fahrenheit now. nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,29,40,36,24,26,30,30,32,34,32,28,36,24,32] def fahrenToCel(c): c = (f - 32) * (5 / 9) return c print ...
using functions to display numbers in a list
I have a list of numbers and I have to use a function to display them in celsius, they are in fahrenheit now. nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,29,40,36,24,26,30,30,32,34,32,28,36,24,32] def fahrenToCel(c): c = (f - 32) * (5 / 9) return c print fahrenToCel(nums) this is what I have, can someon...
[ "If you have a list the_list and you want to apply a function f to each element, creating a new list of the results:\nnew_list = [f(x) for x in the_list]\n\n", "Your function seems to take as input a single number, yet you're giving it a list of numbers. If you want to generate a list of converted numbers using t...
[ 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005642263_python.txt
Q: is there a nice "python conventions and best practices" summary anywhere? I am fairly new to python, and I generally code as a means to an end, as opposed to being a "coder". I like all the power that python contains through libraries, and I enjoy the inherent but invisible strength in python. (E.g., object-orie...
is there a nice "python conventions and best practices" summary anywhere?
I am fairly new to python, and I generally code as a means to an end, as opposed to being a "coder". I like all the power that python contains through libraries, and I enjoy the inherent but invisible strength in python. (E.g., object-oriented, but still relatively scripter-friendly structure for making classes, etc....
[ "I don't know of any definitive source that covers everything but in addition to the links you already posted you should definitely check these links out for some best practices:\n\nGoogle Python Style Guide\nPythonStyleGuide\n\nThese cover style and also highlight some gotchas that can be avoided by using certain ...
[ 6, 3 ]
[]
[]
[ "conventions", "python" ]
stackoverflow_0005641755_conventions_python.txt
Q: Efficient vector selection in numpy Is there an efficient numpy mechanism to generate an array of values from a 2D array given a list of indexes into that array? Specifically, I have a list of 2D coordinates that represent interesting values in a 2D numpy array. I calculate those coordinates as follows: nonzeroVa...
Efficient vector selection in numpy
Is there an efficient numpy mechanism to generate an array of values from a 2D array given a list of indexes into that array? Specifically, I have a list of 2D coordinates that represent interesting values in a 2D numpy array. I calculate those coordinates as follows: nonzeroValidIndices = numpy.where((array2d != noDa...
[ "How about something like this:\na = np.arange(100).reshape((10,10))\nii = np.where(a > 27) # your nonzeroValidIndices\nb = np.zeros_like(a) # your map\nb[ii] = a[ii]\n\nYou can use the result of np.where to index an array as I show above. This should accomplish something similar to what you're doing without loopin...
[ 2, 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005642203_numpy_python.txt
Q: What is the proper way to insert an object with a foreign key in SQLAlchemy? When using SQLAlchemy, what is the ideal way to insert an object into a table with a column that is a foreign key and then commit it? Is there anything wrong with inserting objects with a foreign in the code below? def retrieve_objects()...
What is the proper way to insert an object with a foreign key in SQLAlchemy?
When using SQLAlchemy, what is the ideal way to insert an object into a table with a column that is a foreign key and then commit it? Is there anything wrong with inserting objects with a foreign in the code below? def retrieve_objects(): session = DBSession() return session.query(SomeClass).all() def insert_...
[ "If you aren't using SQLAlchemy relationships on your ORM objects you have to manually deal with foreign keys. This means you have to create the parent object first, get its primary key back from the database, and use that key in the child's foreign key:\ndef retrieve_objects():\n session = DBSession()\n retu...
[ 8 ]
[]
[]
[ "pyramid", "python", "sqlalchemy" ]
stackoverflow_0005610563_pyramid_python_sqlalchemy.txt
Q: displaying celsius in python- functions Possible Duplicate: using functions to display numbers in a list x = [30,34,40,36,36,28,29,32,34,44,36,35,28,33, 29,40,36,24,26,30,30,32,34,32,28,36,24,32] def fahrenToCel(x): return (x - 32) * (5 / 9) print fahrenToCel(x) I know I have asked a couple of times,...
displaying celsius in python- functions
Possible Duplicate: using functions to display numbers in a list x = [30,34,40,36,36,28,29,32,34,44,36,35,28,33, 29,40,36,24,26,30,30,32,34,32,28,36,24,32] def fahrenToCel(x): return (x - 32) * (5 / 9) print fahrenToCel(x) I know I have asked a couple of times, but I am still having issues. I just need...
[ "x = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,\n 29,40,36,24,26,30,30,32,34,32,28,36,24,32]\n\ndef fahrenToCel(x):\n return (x - 32) * (5.0 / 9) # 5.0 to make result float (you can explicitly convert to float as well)\n\n\nprint [fahrenToCel(item) for item in x]\n\n", "Unless x is a numpy array, python w...
[ 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005642771_python.txt
Q: ContentHandler is undefined I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why. The first file is handlers.py: class ArticleHandler(ContentHandler): """ A handler to deal with articles i...
ContentHandler is undefined
I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why. The first file is handlers.py: class ArticleHandler(ContentHandler): """ A handler to deal with articles in XML """ def startEleme...
[ "You have to import ContentHandler in handlers.py as follows:\nfrom xml.sax.handler import ContentHandler\n\nThis should do it.\n" ]
[ 3 ]
[]
[]
[ "python", "sax", "saxparser", "xml" ]
stackoverflow_0005642160_python_sax_saxparser_xml.txt
Q: Python: implementing feature vectors efficiently I'm implementing feature vectors as bit maps for documents in a corpus. I already have the vocabulary for the entire corpus (as a list/set) and a list of the terms in each document. For example, if the corpus vocabulary is ['a', 'b', 'c', 'd'] and the terms in docu...
Python: implementing feature vectors efficiently
I'm implementing feature vectors as bit maps for documents in a corpus. I already have the vocabulary for the entire corpus (as a list/set) and a list of the terms in each document. For example, if the corpus vocabulary is ['a', 'b', 'c', 'd'] and the terms in document d1 is ['a', 'b', 'd', 'd'], the feature vector fo...
[ "I think the most efficient way is to loop over each document's terms, get the position of the term in the (sorted) corpus and set the bit accordingly.\nThe sorted list of corpus terms can be stored as dictionary with term -> index mapping (basically an inverted index).\nYou can create it like so:\ncorpus = dict(((...
[ 2 ]
[]
[]
[ "dictionary", "hash", "python" ]
stackoverflow_0005642825_dictionary_hash_python.txt
Q: display new Django object with jQuery I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly? views.py: def add_post(request): error_msg = u"No POST data sent." post = Post() if r...
display new Django object with jQuery
I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly? views.py: def add_post(request): error_msg = u"No POST data sent." post = Post() if request.method == "POST": #do stuff ret...
[ "Why don't you just return the HTML for the post the in the success return, and use jQuery to append it to where it should go in your page. That's what I usually do in my code, it's quick and easy. For more complex solutions you'd want to return a list of JSON objects perhaps and use a javascript framework like bac...
[ 3, 1, 0 ]
[]
[]
[ "ajax", "django", "jquery", "python", "reload" ]
stackoverflow_0005631985_ajax_django_jquery_python_reload.txt
Q: What is the working directory for Python Windows services? I have successfully created a Python Windows service using pywin32. In testing my application I attempted to have it print (which didn't work as I expected) and I also had it write to a file. It was able to write to a file, but the file ended up in the p...
What is the working directory for Python Windows services?
I have successfully created a Python Windows service using pywin32. In testing my application I attempted to have it print (which didn't work as I expected) and I also had it write to a file. It was able to write to a file, but the file ended up in the python library site-packages folder. This appears to be where th...
[ "They both work, it's what your needs are. For various reasons, it's probably best to use absolute paths to the file names, this way you don't have to worry about 'where' your app is working, you just know where the output will be (which is most important). In *nix, apps generally work in '/' when they don't have a...
[ 2 ]
[]
[]
[ "python", "pywin32", "twisted", "windows_services" ]
stackoverflow_0005641182_python_pywin32_twisted_windows_services.txt
Q: Write to a file I have been trying to write to a file,but it kept writing them on a single line with commas, and square brackets at both ends. How do I write to a file without the square brackets, commas and newline for each rows or lines of the file. Column 6 must remained sorted in descending order. This is the...
Write to a file
I have been trying to write to a file,but it kept writing them on a single line with commas, and square brackets at both ends. How do I write to a file without the square brackets, commas and newline for each rows or lines of the file. Column 6 must remained sorted in descending order. This is the output from the code...
[ "Each element of lines is itself an array. Try:\nfor i in lines:\n outfile.write(\" \".join(i) + \"\\n\")\n\nThe .join() method takes an array i and concatenates all the elements together with a space \" \" between each element. Then a newline \"\\n\" is added to make sure your output is broken up into separate ...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005643206_python.txt
Q: python manage.py syncdb I am very new to python and Django, was actually thrown in to finish off some coding for my company since our coder left for overseas. When I run python manage.py syncdb I receive the following error psycopg2.OperationalError: FATAL: password authentication failed for user "winepad" I'm no...
python manage.py syncdb
I am very new to python and Django, was actually thrown in to finish off some coding for my company since our coder left for overseas. When I run python manage.py syncdb I receive the following error psycopg2.OperationalError: FATAL: password authentication failed for user "winepad" I'm not sure why I am being prompte...
[ "Once you start a Django project, you have to set your database settings in your_project/settings.py . The settings you want to check/change is (assuming you use Django 1.3) something like this:\nDATABASES = {\n 'default': {\n 'ENGINE': '',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD': ''...
[ 4, 1 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0005643201_django_postgresql_python.txt
Q: _tkinter.TclError: wrong # args : What's the matter? Still writing a game. This error's a little different, though. I get a trace back like this... Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 1...
_tkinter.TclError: wrong # args : What's the matter?
Still writing a game. This error's a little different, though. I get a trace back like this... Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 1399, in __call__ return self.func(*args) File "/Users/bl...
[ "Your hypothesis is almost certainly correct. You can easily test this hypothesis by printing out the value before calling find_withtag. \n" ]
[ 0 ]
[]
[]
[ "binding", "canvas", "events", "python", "tkinter" ]
stackoverflow_0005643117_binding_canvas_events_python_tkinter.txt
Q: Converting Tuple to Dictionary i'm parsing an XML file and getting a tuple in return. i converted the tuple to str and then to dictionary. i want to get the key and value for Lanestat. for eg: Lanestat, key 1 and get value 2. but the code is not elegant, appreciate any advice. tq xml: - <Test> - <Default_Config> ...
Converting Tuple to Dictionary
i'm parsing an XML file and getting a tuple in return. i converted the tuple to str and then to dictionary. i want to get the key and value for Lanestat. for eg: Lanestat, key 1 and get value 2. but the code is not elegant, appreciate any advice. tq xml: - <Test> - <Default_Config> <LINK>{1: 1, 2: 2, 3: 3, 4: 4, 5: 5...
[ "You can use ast.literal_eval() to parse the elem.text into a dict safely:\nimport ast\n\nfor elem in doc.findall('Default_Config/Lanestat'):\n if elem.tag == 'Lanestat':\n val = ast.literal_eval(elem.text)\n print type(val), val\n print elem.tag, val[1]\n\nOutput:\n<type 'dict'> {1: 2, 2: 4...
[ 4 ]
[]
[]
[ "dictionary", "python", "tuples", "xml" ]
stackoverflow_0005642987_dictionary_python_tuples_xml.txt
Q: How can I use django.auth.views.login? How can I use django.auth.views.login? I am trying to make a user login but I can't figure out how to use it. Is there a thing you add to urls.py. I have an intermediate understanding of django. Thanks in advance! A: For a quick and simple login view you just have to add th...
How can I use django.auth.views.login?
How can I use django.auth.views.login? I am trying to make a user login but I can't figure out how to use it. Is there a thing you add to urls.py. I have an intermediate understanding of django. Thanks in advance!
[ "For a quick and simple login view you just have to add the following to your urlpatterns in your urls.py file (You can change the regex to match whatever location you need it to match):\n(r'^login/$', 'django.contrib.auth.views.login'),\n\nNext, add a directory called \"registration\" in your main templates folder...
[ 8 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0005643358_authentication_django_python.txt
Q: Emacs ipython shell error message foreground color setting In my python shell with white background it looks like this: As you can see, when there is an error, it's white text on white background. In order to see them, I have to highlight the text. I haven't got any luck finding out what face controls those color...
Emacs ipython shell error message foreground color setting
In my python shell with white background it looks like this: As you can see, when there is an error, it's white text on white background. In order to see them, I have to highlight the text. I haven't got any luck finding out what face controls those colors. Anyone has any idea? Thanks
[ "in ~\\.ipython\\ipythonrc there is this section (About a 1/4 away from the top)\n# colors - Coloring option for prompts and traceback printouts.\n\n# Currently available schemes: NoColor, Linux, LightBG.\n\n# This option allows coloring the prompts and traceback printouts. This\n# requires a terminal which can pro...
[ 1 ]
[]
[]
[ "emacs", "foreground", "python" ]
stackoverflow_0005643490_emacs_foreground_python.txt
Q: python gdb and ctypes I'm trying to implement a debugging helper, which should stringify an xml node. I'm using gdb 7.2s python interface to do this. The idea is to get the nodes address, then pass it to the xml library using ctypes. I've managed to get the xml nodes address (a gdb.Value) and I can call functions ...
python gdb and ctypes
I'm trying to implement a debugging helper, which should stringify an xml node. I'm using gdb 7.2s python interface to do this. The idea is to get the nodes address, then pass it to the xml library using ctypes. I've managed to get the xml nodes address (a gdb.Value) and I can call functions in the xml library. But som...
[ "Think about what you are doing. It can't possibly work!\nYou get a gdb.Value, representing the address of xmlNodePtr in the inferior (being debugged) process.\nYou then pass that address into libxml2.so.2, loaded into GDB itself.\nBut the address in the inferior is very likely inaccessible within GDB. If by chance...
[ 3 ]
[]
[]
[ "ctypes", "gdb", "python" ]
stackoverflow_0005637718_ctypes_gdb_python.txt
Q: Facebook Python OAuth Desktop Application I have been trying to create a desktop application with Python for logging into Facebook, and then it would use the Facebook GraphAPI. However I cannot figure out how to get the access token that I need. Can anyone help? A: Here's a guide that explains the steps to get a...
Facebook Python OAuth Desktop Application
I have been trying to create a desktop application with Python for logging into Facebook, and then it would use the Facebook GraphAPI. However I cannot figure out how to get the access token that I need. Can anyone help?
[ "Here's a guide that explains the steps to get a Facebook OAuth token: http://benbiddington.wordpress.com/2010/04/23/facebook-graph-api-getting-access-tokens/\n" ]
[ 1 ]
[]
[]
[ "facebook", "facebook_graph_api", "oauth", "python" ]
stackoverflow_0005642978_facebook_facebook_graph_api_oauth_python.txt
Q: Why does my function call not print out what it's supposed to? class A: def __init__(self, blocking, b = None): self.blocking = blocking def printerthing(self): print "hi this is a test" a = A(True) a.printerthing print("5") A: You're not actually calling the function, you're ju...
Why does my function call not print out what it's supposed to?
class A: def __init__(self, blocking, b = None): self.blocking = blocking def printerthing(self): print "hi this is a test" a = A(True) a.printerthing print("5")
[ "You're not actually calling the function, you're just accessing a reference to it (and then doing nothing with it). You probably want:\na.printerthing()\n\n", "try a.printerthing()?\nEach method call has to have a ()\n", "print in python3.x is different from print in python2.x\n#!/usr/local/bin/python3\n\nclas...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005643769_python.txt
Q: Python 2.6 in mac corrupted because of failled update I'm a mac newbie and I tried to update my python version from 2.6 to 2.7. Unsuccessful, I changed my mind and uninstalled the python2.7 I had. I had a previous issue that if I typed something like: python setup.py install It would not install the package for p...
Python 2.6 in mac corrupted because of failled update
I'm a mac newbie and I tried to update my python version from 2.6 to 2.7. Unsuccessful, I changed my mind and uninstalled the python2.7 I had. I had a previous issue that if I typed something like: python setup.py install It would not install the package for python2.6, installing to the removed 2.7 version instead, to...
[ "Since you were trying to install MySQLdb, how about you give ActivePython a try? \n\nInstall ActivePython 2.7 (it co-exists with Apple's System Python 2.6)\nOpen Terminal and type pypm install mysql-python (see PyPM Index) .. no compilation required\n\nMake sure that /usr/local/bin/ is in front of your $PATH. \nTo...
[ 0 ]
[]
[]
[ "macos", "python", "python_2.6" ]
stackoverflow_0005643278_macos_python_python_2.6.txt
Q: PyCUDA: C/C++ includes? Something that isn't really mentioned anywhere (at least that I can see) is what library functions are exposed to inline CUDA kernels. Specifically I'm doing small / stupid matrix multiplications that don't deserve to be individually offloaded to the GPU but am offloading a larger section o...
PyCUDA: C/C++ includes?
Something that isn't really mentioned anywhere (at least that I can see) is what library functions are exposed to inline CUDA kernels. Specifically I'm doing small / stupid matrix multiplications that don't deserve to be individually offloaded to the GPU but am offloading a larger section of the algorithm which include...
[ "I don't know of any, and I always thought it would be useful to have.\nFor the size of problems that I usually work with (small matrices and tensors that arise in the finite element method), I just wrote C++ templates to do the operations. Templating the functions allows the compiler to know the trip counts at com...
[ 1 ]
[]
[]
[ "cuda", "gpgpu", "inline_code", "pycuda", "python" ]
stackoverflow_0005641299_cuda_gpgpu_inline_code_pycuda_python.txt
Q: module not being imported correctly in python when i attempt to import the following module (ex25.py): def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words all i get back is this: >>>import ex25 and nothing back...no prompt as to what i did wr...
module not being imported correctly in python
when i attempt to import the following module (ex25.py): def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words all i get back is this: >>>import ex25 and nothing back...no prompt as to what i did wrong...its almost like it is not even reading the mo...
[ "I don't think you've actually done anything wrong; the import statement normally does not produce any output (it only complains if there is something wrong). Try:\n>>> dir(ex25)\n\nThat should give a list of the names exported from the ex25 module.\n", "I think you are supposed to type all the lines that start w...
[ 2, 2, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0005643994_import_module_python.txt
Q: Help with MySQLdb module: corrupted installation and connecting to remote servers I am new to Python and having some rudimentary problems getting MySQLdb up and running. I'm hoping somebody out there can help me. When I first tried to install the module using setup.py, the setup terminated because it was unable t...
Help with MySQLdb module: corrupted installation and connecting to remote servers
I am new to Python and having some rudimentary problems getting MySQLdb up and running. I'm hoping somebody out there can help me. When I first tried to install the module using setup.py, the setup terminated because it was unable to find mysql_config. This is because I didn't realize the module expected MySQL to be ...
[ "\nInstall the MySQL client libraries.\nInstall the MySQL client library development files, and build again.\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_python", "python", "python_module", "setup.py" ]
stackoverflow_0005644374_mysql_mysql_python_python_python_module_setup.py.txt
Q: facebook connect: redirect to white page with only the facebook logo on it (amazon ec2) I've got a godaddy .com domain and I am forwarding it to an elastic amazon ec2 instance IP. I've recently added Facebook connect to my website, but when a user presses the 'Facebook connect' button, the button just redirects to...
facebook connect: redirect to white page with only the facebook logo on it (amazon ec2)
I've got a godaddy .com domain and I am forwarding it to an elastic amazon ec2 instance IP. I've recently added Facebook connect to my website, but when a user presses the 'Facebook connect' button, the button just redirects to a blank page with only the Facebook logo on it. When I click the Facebook logo, it redirects...
[ "Don't forward the domain. Depending on how you're doing your auth, you'll generally be passing/using an oauth callback url to facebook.\nGet your \"dynamic IP\" on your ec2 machine:\ncurl www.whatismyip.com/automation/n09230945.asp\n\nThen setup an A record in DNS for your domain to point to the IP you get from th...
[ 0 ]
[]
[]
[ "dns", "facebook", "python", "tornado" ]
stackoverflow_0005153680_dns_facebook_python_tornado.txt
Q: Python variable is evaluated differently in pdb and print statements I am using threads in a python program and recently found a problem where a float is not being interpreted correctly and whenever I go to print it out in pdb or in a logging statement, it shows up correctly most of the time. Oddly, it takes a d...
Python variable is evaluated differently in pdb and print statements
I am using threads in a python program and recently found a problem where a float is not being interpreted correctly and whenever I go to print it out in pdb or in a logging statement, it shows up correctly most of the time. Oddly, it takes a different amounts of prints to show up in these two threads I just ran. Als...
[ "Its pretty impossible to tell from what you've posted. Floats don't switch from 0.0 to ~0.05 randomly, something is changing the value stored in that memory location (variable). Are you setting the value from other thread?\nAlso, be aware that in your demo code, if you're looking for x.prob to have the value of ...
[ 0 ]
[]
[]
[ "debugging", "pdb", "python" ]
stackoverflow_0005644521_debugging_pdb_python.txt
Q: Python - Python 3.1 can't seem to handle UTF-16 encoded files? I'm trying to run some code to simply go through a bunch of files and write those that happen to be .txt files into the same file, removing all the spaces. Here's some simple code that should do the trick: for subdir, dirs, files in os.walk(rootdir): f...
Python - Python 3.1 can't seem to handle UTF-16 encoded files?
I'm trying to run some code to simply go through a bunch of files and write those that happen to be .txt files into the same file, removing all the spaces. Here's some simple code that should do the trick: for subdir, dirs, files in os.walk(rootdir): for file in files: if '.txt' in file: f = open(subdir+'/'...
[ "Use open(bla, 'r', encoding=\"utf-16\").\n", "There are various utf-16 encodings.\n\nutf-16-be big endian no BOM\nutf-16-le little endian no BOM\nutf-16 little endian + BOM\n\nExamples:\nPython 3.2 (r32:88452, Feb 20 2011, 11:12:31) \n[GCC 4.2.1 (Apple Inc. build 5664)] on darwin\nType \"help\", \"copyright\", \...
[ 8, 6 ]
[]
[]
[ "character_encoding", "python", "utf_16", "utf_8" ]
stackoverflow_0005644833_character_encoding_python_utf_16_utf_8.txt
Q: How to run python script on my server? I have a server hosting by Blueshot. I have been using php to get post variables from iPhone... But now I have to use python to get post variable from iPhone. I wrote something like this import cgi import cgitb; cgitb.enable() # for troubleshooting print "Content-type: tex...
How to run python script on my server?
I have a server hosting by Blueshot. I have been using php to get post variables from iPhone... But now I have to use python to get post variable from iPhone. I wrote something like this import cgi import cgitb; cgitb.enable() # for troubleshooting print "Content-type: text/html" print print """ <html> <head><titl...
[ "Here's a small checklist of things to check when CGI scripts aren't working:\n\nIs it in a cgi-bin (or equivalent) folder?\nIs it executable?\nIs it readable?\nDoes it have a hashbang?\nIs your server set up to process CGI scripts?\n\nHere's a sample CGI script you can use for testing:\n#!/usr/bin/env python\nimpo...
[ 10, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005645384_python.txt
Q: Converting String to List Possible Duplicate: Converting a string that represents a list, into an actual list object. hi, i have a string in this format: >>> x="(174,185)" >>> x '(174,185)' how can i convert this string to list so that i can access the index 0 as 174 and index 1 as 185? i'm using Python 2.5 & W...
Converting String to List
Possible Duplicate: Converting a string that represents a list, into an actual list object. hi, i have a string in this format: >>> x="(174,185)" >>> x '(174,185)' how can i convert this string to list so that i can access the index 0 as 174 and index 1 as 185? i'm using Python 2.5 & Win XP. i tried a few ways but ...
[ "You could try this\ny=x[1:-1].split(\",\")\n\nthat strips off the parens before splitting\n>>> x=\"(174,185)\"\n>>> map(int, x[1:-1].split(','))\n[174, 185]\n\nYou could also use literal_eval if you have python2.6+\n>>> from ast import literal_eval\n>>> literal_eval(x)\n(174, 185)\n>>> \n\n" ]
[ 3 ]
[]
[]
[ "list", "python", "python_2.5", "string" ]
stackoverflow_0005645463_list_python_python_2.5_string.txt
Q: Strategies for solving inequality sudoku? A twist on the classic sudoku solver that I've recently run into is the (rather crazy) inequality sudoku, which is your classic sudoku puzzle with the added twist that there are inequality conditions added to each box. Now, I've managed to scratch out a regular sudoku so...
Strategies for solving inequality sudoku?
A twist on the classic sudoku solver that I've recently run into is the (rather crazy) inequality sudoku, which is your classic sudoku puzzle with the added twist that there are inequality conditions added to each box. Now, I've managed to scratch out a regular sudoku solver in Python (using a brute-force method), bu...
[ "This is just constraint solving.\nIf you have a sudoku board, then, for each cell (i, j) you have these constraints:\nboard[i, j] in [1, 2, 3, 4, 5, 6, 7, 8, 9]\nfor each cell (a, j) where i != a: board[a, j] != board[i, j]\nfor each cell (i, b) where j != b: board[i, b] != board[i, j]\n\nFor particular cells, you...
[ 2, 0 ]
[]
[]
[ "math", "python", "sudoku" ]
stackoverflow_0005642580_math_python_sudoku.txt
Q: HTML parsing using lxml code i have following HTML code:- <table class="results"> <tr> <td> <a href="..">link</a><span>2nd Mar 2011</span><br>XYZ Consultancy Ltd<br> <div>....</div> </td> </tr> </table> I am using lxml+python code to parse above HTML file. I want to retrieve "XYZ Consult...
HTML parsing using lxml code
i have following HTML code:- <table class="results"> <tr> <td> <a href="..">link</a><span>2nd Mar 2011</span><br>XYZ Consultancy Ltd<br> <div>....</div> </td> </tr> </table> I am using lxml+python code to parse above HTML file. I want to retrieve "XYZ Consultancy Ltd" but I am not able to fin...
[ "You can use the CSS Selector +, a direct adjacent combinator, to get at the <br> preceding the text. Then, the target text is contained in its tail attribute.\nimport lxml.html\nroot = lxml.html.fromstring('''\n<table class=\"results\">\n <tr>\n <td>\n <a href=\"..\">link</a><span>2nd Mar 2011</span><br>X...
[ 2, 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0005646032_lxml_python.txt
Q: What is the easiest way to print 10 characters in Python? In Perl it's as easy as print "A"x10 What about in python? A: Before python3+: print "A" * 10 In python 3+: print("A"*10)
What is the easiest way to print 10 characters in Python?
In Perl it's as easy as print "A"x10 What about in python?
[ "Before python3+:\nprint \"A\" * 10\n\nIn python 3+:\nprint(\"A\"*10)\n\n" ]
[ 11 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0005646586_perl_python.txt
Q: How does the Django LazyUser code work? I'm curious how this code actually works. In particular what does request.__class__.user = LazyUser() do as opposed to setattr(request, user, LazyUser()). Sorry if this is an ignorant question, I want to know because I'm going to implement a similar piece of middleware that ...
How does the Django LazyUser code work?
I'm curious how this code actually works. In particular what does request.__class__.user = LazyUser() do as opposed to setattr(request, user, LazyUser()). Sorry if this is an ignorant question, I want to know because I'm going to implement a similar piece of middleware that adds an attribute to the request. Here's the ...
[ "In this case, since LazyUser() is a class that figures out if the request object already has checked to make sure the user has been queried for, this is the real magic, it only needs to query the db for the user once per session. Being a property, it is a universal action that will be applied to all instances of t...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005644527_django_python.txt
Q: Modules paths in Python I have created a folder with all my modules for my GAE application and with external libraries like Jinja2 to keep everything sorted in one place. I have folders structure like this: lib\ \utils\ \__init__.py \firepython \jinja2 \jsonpickle __init__.py sessions.py...
Modules paths in Python
I have created a folder with all my modules for my GAE application and with external libraries like Jinja2 to keep everything sorted in one place. I have folders structure like this: lib\ \utils\ \__init__.py \firepython \jinja2 \jsonpickle __init__.py sessions.py When I try to load Jinja fr...
[ "Indeed you should not have to change imports in external libraries - though depending on your environment, you might even have too.\nPYTHONPATH\nModifying your PYTHONPATH should suffice; PYTHONPATH should contain a 'lib' path that is either absolute or relative to your home, eg. \nThen you could simply do \nfrom j...
[ 6, 1 ]
[]
[]
[ "google_app_engine", "jinja2", "python", "pythonpath" ]
stackoverflow_0005646614_google_app_engine_jinja2_python_pythonpath.txt
Q: Why isn't IDLE creating a new log file with logging module when being run again? I was testing out some simple logging examples for Python's logging module in IDLE: import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='TESTLOG.log') logging.debug('A...
Why isn't IDLE creating a new log file with logging module when being run again?
I was testing out some simple logging examples for Python's logging module in IDLE: import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='TESTLOG.log') logging.debug('A debug message') And it works as expected: A file called TESTLOG.log is created with ...
[ "The first time basicConfig is called it adds a Handler to the root logger in the logging module. Subsequent calls to basicConfig check to see if there is already a Handler in the root logger, and if there is then the call to basicConfig has no effect (i.e. it will not re-create the log file).\nIf you open an IDLE ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005644789_python.txt
Q: Improving pure Python prime sieve by recurrence formula I am trying to optimize further the champion solution in prime number thread by taking out the complex formula for sub-list length. len() of the same subsequence is too slow as len is expensive and generating the subsequence is expensive. This looks to slight...
Improving pure Python prime sieve by recurrence formula
I am trying to optimize further the champion solution in prime number thread by taking out the complex formula for sub-list length. len() of the same subsequence is too slow as len is expensive and generating the subsequence is expensive. This looks to slightly speed up the function but I could not yet take away the di...
[ "You could do a wheel optimisation. Multiples of 2 and 3 aren't primes, so dont store them at all. You could then start from 5 and skip multiples of 2 and 3 by incrementing in steps of 2,4,2,4,2,4 etc..\nBelow is a C++ code for it. Hope this helps.\nvoid sieve23()\n{\n int lim=sqrt(MAX);\n for(int i=5,bit1=0;...
[ 1, 0 ]
[]
[]
[ "list", "primes", "python", "slice" ]
stackoverflow_0003285443_list_primes_python_slice.txt
Q: "No module named _scproxy" on OSX I'm on OSX 10.6 with pre-installed python 2.6 and would like to install python packages via easy_install or setup.py (in a downloaded package). In my case I'm trying to install MySQLdb. In both cases I get a stack trace which ends like so: ... File "/System/Library/Frameworks/Pyt...
"No module named _scproxy" on OSX
I'm on OSX 10.6 with pre-installed python 2.6 and would like to install python packages via easy_install or setup.py (in a downloaded package). In my case I'm trying to install MySQLdb. In both cases I get a stack trace which ends like so: ... File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/p...
[ "Background\n_scproxy is a Mac-specific urllib helper interfacing with OS-specific libraries to do HTTP requests. It seems to be missing on my system too (10.6.7). Preliminary, I think it looks like a problem with the system Python build (I can't find anything that looks like it under /System/Libraries).\nHack-o-ra...
[ 8 ]
[]
[]
[ "macos", "osx_snow_leopard", "python" ]
stackoverflow_0005647023_macos_osx_snow_leopard_python.txt
Q: Python: error IOError: [Errno2] bad interpretation of file or directory I'm try trying to read an csv file and the interpreter return a bad directory by duplicating the \ > result = [[urlparse(u).netloc] for u in file ('S:\Dev\Python\BDDtest.csv')] >>IOError: [Errno 2] No such file or directory: 'S:\\\Dev\\\Pytho...
Python: error IOError: [Errno2] bad interpretation of file or directory
I'm try trying to read an csv file and the interpreter return a bad directory by duplicating the \ > result = [[urlparse(u).netloc] for u in file ('S:\Dev\Python\BDDtest.csv')] >>IOError: [Errno 2] No such file or directory: 'S:\\\Dev\\\Python\\\BDDtest.csv' When I put it in a ufile ='S:\Dev\Python\BDDtest.csv' and p...
[ "Maybe a hack with os.path.abspath will help? \nimport os\nresult = [[urlparse(u).netloc] for u in \n file(os.path.abspath('S:\\Dev\\Python\\BDDtest.csv'))]\n\nYou can also try using ntpath explicitly:\nimport ntpath\nresult = [[urlparse(u).netloc] for u in \n file(ntpath.abspath('S:\\Dev\\Python\...
[ 1, 0 ]
[]
[]
[ "directory", "file", "python" ]
stackoverflow_0005646729_directory_file_python.txt
Q: Celery - collision of task_ids I'm getting HardTimeLimit exception for my tasks. After log examination i found - task is not being received by celery ( No "Got task from broker:" message for task id) task with the same id was executed couple a days ago. Task ids are assigned automatically by @task decorator, t...
Celery - collision of task_ids
I'm getting HardTimeLimit exception for my tasks. After log examination i found - task is not being received by celery ( No "Got task from broker:" message for task id) task with the same id was executed couple a days ago. Task ids are assigned automatically by @task decorator, tasks are started by django, there ar...
[ "It shouldn't be possible and even if, it should be very rare. My guess would be that the same task is executed a second time after your exception. Maybe there is a problem with your routing keys as the worker doesn't get the task? Or the broker has a problem, I've seen funny problems with RabbitMQ. Deleting it's d...
[ 0 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0005646679_celery_django_python.txt
Q: Qt Programming with Python, Installation and Environment I have been using the Qt C++ framework and now I need to switch to PyQt to use the Python programming language instead. However I am having some trouble installing PyQt on Windows. I have tried to follow this link: http://blog.oak-tree.us/index.php/2009/05/...
Qt Programming with Python, Installation and Environment
I have been using the Qt C++ framework and now I need to switch to PyQt to use the Python programming language instead. However I am having some trouble installing PyQt on Windows. I have tried to follow this link: http://blog.oak-tree.us/index.php/2009/05/12/pyqt-windows ANd when I get to the point where I have to en...
[ "Well, you're in luck of sorts. PyQt distributes binaries that include everything but the docs and source. You will also need/want the sip packages also. Get the PyQt installer for the for the python version you want, in this case 2.6, but I would advise an upgrade to 2.7 if you can (barring and spec related issues...
[ 2, 1, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "windows" ]
stackoverflow_0005642637_pyqt_pyqt4_python_windows.txt
Q: Which types of files can images.get_serving_url() serve? I'm interested to know which types of files can be served by GAE's image server. Or better yet, the location of a list/tuple of these types stored in the library somewhere (to automatically support future formats). A: While Java library offers Enum Image.F...
Which types of files can images.get_serving_url() serve?
I'm interested to know which types of files can be served by GAE's image server. Or better yet, the location of a list/tuple of these types stored in the library somewhere (to automatically support future formats).
[ "While Java library offers Enum Image.Format listing all the Image formats usable by the images api, Python does not seem to offer this kind of information.\nLooking at the source code, the list of supported image format is hardcoded as for example:\nif img_format not in (\"BMP\", \"GIF\", \"ICO\", \"JPEG\", \"PNG\...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005646537_google_app_engine_python.txt
Q: Django Model object creation Look at my django model (I'm pasting here only a part of it): from django.contrib.auth.models import User as DjangoUser from django.db import models class Client(DjangoUser): address = models.ForeignKey(Address, blank=True, null=True) I know how to create fresh Client and User: c...
Django Model object creation
Look at my django model (I'm pasting here only a part of it): from django.contrib.auth.models import User as DjangoUser from django.db import models class Client(DjangoUser): address = models.ForeignKey(Address, blank=True, null=True) I know how to create fresh Client and User: client = Client(username=name, pass...
[ "User is a special case in the Django framework. You should not use inheritance.\nThe best practice to add data to it is to create a model and define it as user profile:\nCreate a model for this:\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass UserProfile(models.Model):\n user...
[ 5, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005647669_django_python.txt
Q: Parenthesis folding in Eclipse PyDev Is there any way to customize Eclipse PyDev line folding? When a function call gets a lot of arguments, I prefer to fold my code like this: def some_function(): function_call( first_argument=first_value, second_argument=second_value, third_argument=t...
Parenthesis folding in Eclipse PyDev
Is there any way to customize Eclipse PyDev line folding? When a function call gets a lot of arguments, I prefer to fold my code like this: def some_function(): function_call( first_argument=first_value, second_argument=second_value, third_argument=third_value, ... ) However wit...
[ "Under window > preferences > pydev > editor > typing, uncheck the \"after '(' indents to its level (indents by tabs if unchecked)\".\n" ]
[ 4 ]
[]
[]
[ "eclipse", "editor", "pydev", "python", "word_wrap" ]
stackoverflow_0005643115_eclipse_editor_pydev_python_word_wrap.txt
Q: How to get unit test coverage results in Eclipse + Pydev? I know Eclipse + PyDev has an option Run As => 3 Python Coverage. But all it reports is: Ran 6 tests in 0.001s OK And it says nothing about code coverage. How to get a code coverage report in Pydev? A: Run a file with "Python Coverage" Window > Show Vie...
How to get unit test coverage results in Eclipse + Pydev?
I know Eclipse + PyDev has an option Run As => 3 Python Coverage. But all it reports is: Ran 6 tests in 0.001s OK And it says nothing about code coverage. How to get a code coverage report in Pydev?
[ "\nRun a file with \"Python Coverage\"\nWindow > Show View > Code Coverage Results View\nSelect the directory in which the executed file is\nDouble-click on the executed file in the file list\nStatistics are now at the right, not executed lines are marked red in the code view\n\nActually this is a really nice featu...
[ 14, 8, 0 ]
[]
[]
[ "code_coverage", "eclipse", "pydev", "python" ]
stackoverflow_0002262777_code_coverage_eclipse_pydev_python.txt
Q: Scope in a python class surprising behaviour The following code will result in the print statement being executed class C1(object): print 'I am some code executing in C1' def method1(self): print 'I am method1' def method2(self): print 'I am method2' pass I am surprised by t...
Scope in a python class surprising behaviour
The following code will result in the print statement being executed class C1(object): print 'I am some code executing in C1' def method1(self): print 'I am method1' def method2(self): print 'I am method2' pass I am surprised by this as I would have thought it would only execute ...
[ "I guess you mean that it prints 'I am some code executing in C1'? \nIt's printed when the class object is created, and in this case that happens when you load the file it's declared in. This is also the place where you put class variables (which can be used as Python's equivalent of static variables in other langu...
[ 8, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005648070_oop_python.txt
Q: python.exe output I've got an application that uses python as a script language. When somebody modifies a python script i want to known if it has syntax errors. I am using the python.exe (windows 2003, python 2.5) to check the script so i execute something like python script.py > errors.txt but errors.txt remains...
python.exe output
I've got an application that uses python as a script language. When somebody modifies a python script i want to known if it has syntax errors. I am using the python.exe (windows 2003, python 2.5) to check the script so i execute something like python script.py > errors.txt but errors.txt remains 0kb despite script.py ...
[ "If python uses the STDERR output stream for errors (I admit I do not know if it does), you must insted redirect the error strem by using:\npython script.py 2> errors.txt\n\n" ]
[ 0 ]
[]
[]
[ "python", "redirect", "syntax_error" ]
stackoverflow_0005648084_python_redirect_syntax_error.txt
Q: Python metaclasses tutorial Sorry if I have to use you as Google, but Google does not help. I was looking for a very good tutorial about metaclasses in Python. One feature I remember about it was a three-paned image where you had metaclasses, classes and instances, one for each column of the image. The author prog...
Python metaclasses tutorial
Sorry if I have to use you as Google, but Google does not help. I was looking for a very good tutorial about metaclasses in Python. One feature I remember about it was a three-paned image where you had metaclasses, classes and instances, one for each column of the image. The author progressively added blocks for each o...
[ "You may be referring to Python Types and Objects.\n" ]
[ 2 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0005648462_metaclass_python.txt
Q: Arbitrary joins in Django Models Let's say model X has a field n (an integer). Now I also have a model Y which has fields n and m (integers). Is it possible using Django ORM to select x (model X) such that there exists y (model Y) such that x.n = y.n and y.m = m for a given value of m? Please don't advise me to in...
Arbitrary joins in Django Models
Let's say model X has a field n (an integer). Now I also have a model Y which has fields n and m (integers). Is it possible using Django ORM to select x (model X) such that there exists y (model Y) such that x.n = y.n and y.m = m for a given value of m? Please don't advise me to introduce a ForeignKey relationship betw...
[ "i suppose this could be achieved using extra QuerySet method.\n(i didn't tested it)\nX.objects.extra(where=[\"x.n in (select y.n from y where y.m = '%s')\"], params=['m_value'])\n\n", "You can do this using raw sql:\ndef my_custom_sql(m):\n from django.db import connection, transaction\n cursor = connectio...
[ 6, 1 ]
[]
[]
[ "django", "django_models", "django_orm", "join", "python" ]
stackoverflow_0005648279_django_django_models_django_orm_join_python.txt
Q: Is it possible to do partial inheritance with Python? I'm creating a class (class0) in Python that is a currently based off of one class (class1); however, I'd like to inherit from another class as well (class2). The thing about class2 is that I don't want all of it's methods and attributes, I just need one single...
Is it possible to do partial inheritance with Python?
I'm creating a class (class0) in Python that is a currently based off of one class (class1); however, I'd like to inherit from another class as well (class2). The thing about class2 is that I don't want all of it's methods and attributes, I just need one single method. Is it possible for class0 to only inherit a single...
[ "The \"mixin\" method of having another class that just implemetns the method you want is the correct thing to do in this case.\nBut for sake of completeness, as it answers exactly what you are asking, I add that yes, it is possible to have a behavior just like the \"partial inheritance\" you want (but note that su...
[ 26, 15, 6, 4 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0005647118_class_inheritance_python.txt
Q: loop through python months since start time I want to loop through the months since a given start time, and print the first and last day. I can manually keep track of which month and year it is, and use the calendar.monthrange(year, month) to get the number of days...but is that the best way? from datetime import...
loop through python months since start time
I want to loop through the months since a given start time, and print the first and last day. I can manually keep track of which month and year it is, and use the calendar.monthrange(year, month) to get the number of days...but is that the best way? from datetime import date start_date = date(2010, 8, 1) end_date = da...
[ "To find the last day of a month, you can use first_of_next_month - datetime.timedelta(1). For instance:\ndef enumerate_month_dates(start_date, end_date):\n current = start_date\n while current <= end_date:\n if current.month >= 12:\n next = datetime.date(current.year + 1, 1, 1)\n el...
[ 3, 0, 0, 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0005641685_date_python.txt
Q: Unicode - String - list Manipulation I have a data s = u"[u'38', u'36', u'34', u'32']" which has data type unicode i want to make this data as simple list of element like s= ['38','36','32'], i try to use simplejson.loads but its not working simple json work with the ('["s"]') this type of string not ("['s']") so ...
Unicode - String - list Manipulation
I have a data s = u"[u'38', u'36', u'34', u'32']" which has data type unicode i want to make this data as simple list of element like s= ['38','36','32'], i try to use simplejson.loads but its not working simple json work with the ('["s"]') this type of string not ("['s']") so any buddy please guide me to get of this p...
[ ">>> import ast\n>>> s = u\"[u'38', u'36', u'34', u'32']\"\n>>> [ item.encode('ascii') for item in ast.literal_eval(s) ]\n['38', '36', '34', '32']\n\n", "If ast is available, you can use ast.literal_eval.\n", "Well the problem is that that string is not valid JSON syntax. It is valid Python syntax, but not JSON...
[ 9, 1, 1, 0 ]
[]
[]
[ "operation", "python", "string", "unicode" ]
stackoverflow_0005648532_operation_python_string_unicode.txt
Q: how to integrate two apps (mainloop) together in python hi i am working on a VR engine "vizard" it has (like any other game engine) its mainloop, i want to integrate it with a multi-touch framework "kivy" which has its own mainloop , is it possible to do so? and if you can help me finding references about this top...
how to integrate two apps (mainloop) together in python
hi i am working on a VR engine "vizard" it has (like any other game engine) its mainloop, i want to integrate it with a multi-touch framework "kivy" which has its own mainloop , is it possible to do so? and if you can help me finding references about this topic thank you in advance :D
[ "The other thing to do is check each library you want to use, and see if it is possible to go without using their native mainloop - you will have to build a mainloop yourself which takes care of calling an \"execute pending events\" in each of then. Since you are writting your mainloop yourself, this is the way to ...
[ 2, 0 ]
[]
[]
[ "kivy", "multi_touch", "python" ]
stackoverflow_0005646943_kivy_multi_touch_python.txt
Q: Is there a python builtin to create tuples from multiple lists? Is there a python builtin that does the same as tupler for a set of lists, or something similar: def tupler(arg1, *args): length = min([len(arg1)]+[len(x) for x in args]) out = [] for i in range(length): out.append(tuple([x[i] for ...
Is there a python builtin to create tuples from multiple lists?
Is there a python builtin that does the same as tupler for a set of lists, or something similar: def tupler(arg1, *args): length = min([len(arg1)]+[len(x) for x in args]) out = [] for i in range(length): out.append(tuple([x[i] for x in [arg1]+args])) return out so, for example: tupler([1,2,3,4]...
[ "I think you're looking for zip():\n\n>>> zip([1,2,3,4],[5,6,7])\n[(1, 5), (2, 6), (3, 7)]\n\n", "have a look at the built-in zip function http://docs.python.org/library/functions.html#zip\nit can also handle more than two lists, say n, and then creates n-tuples.\n>>> zip([1,2,3,4], [5,6,7,8], [9,10,11,12], [13,1...
[ 15, 5, 2, 0 ]
[]
[]
[ "built_in", "list_manipulation", "python", "transpose" ]
stackoverflow_0005648794_built_in_list_manipulation_python_transpose.txt
Q: Why is Cairo messing with my Colors? import cairo from PIL import Image as im orig_image = im.open('Camilla_Belle_photo_3.jpg') #http://i56.tinypic.com/261i5cn.jpg surface = cairo.ImageSurface.create_from_png('Camilla_Belle_photo_3.png') #http://i52.tinypic.com/20gmypv.png context = cairo.Context(surface) #draw s...
Why is Cairo messing with my Colors?
import cairo from PIL import Image as im orig_image = im.open('Camilla_Belle_photo_3.jpg') #http://i56.tinypic.com/261i5cn.jpg surface = cairo.ImageSurface.create_from_png('Camilla_Belle_photo_3.png') #http://i52.tinypic.com/20gmypv.png context = cairo.Context(surface) #draw stuff other_image = im.frombuffer('RGBA', o...
[ "The nature of the change shows us that the blue and red channels on the image have been swapped. In this case, it means that cairo maintains the pixel data in memory in a Blue Green Red Alpha\" order , rather than \"Red Green Blue Alpha\".\nLuckily Python's PIL offer support for that inversion: just pass \"BGRA\" ...
[ 2 ]
[]
[]
[ "cairo", "image", "image_processing", "pycairo", "python" ]
stackoverflow_0005640030_cairo_image_image_processing_pycairo_python.txt
Q: Where can I find a browser based editor for python that works with IE7? I'd like to get some code editing for a free software project done during some free time that I will have today at my university. There's just one small problem: We're almost entirely a windows environment (mostly thin clients at that) and the...
Where can I find a browser based editor for python that works with IE7?
I'd like to get some code editing for a free software project done during some free time that I will have today at my university. There's just one small problem: We're almost entirely a windows environment (mostly thin clients at that) and the only source code editor installed is jGRASP. So, I need a source code edito...
[ "The best webbased editor I know is Ace.\nIf you can't execute downloaded exes, this maybe mute, but SciTe is reasonably useable and does not require you to install anything - just download and run.\n", "Putty and vim would be my solution (Requires a remote host running 'nix)\nPutty is obviously a 3rd party binar...
[ 2, 1 ]
[]
[]
[ "browser", "editor", "internet_explorer_7", "python" ]
stackoverflow_0005648638_browser_editor_internet_explorer_7_python.txt
Q: Simple regular expression, why this not works? re.compile("a[b|c]d").findall("akjh adc abc abbd acd") why this returns only ['acd'] not ['abd', 'acd'] ? EDIT: I gave wrong example... thats why. Post can be deleted.. A: The regular expression will match a string starting with a, followed by b or c and then ...
Simple regular expression, why this not works?
re.compile("a[b|c]d").findall("akjh adc abc abbd acd") why this returns only ['acd'] not ['abd', 'acd'] ? EDIT: I gave wrong example... thats why. Post can be deleted..
[ "The regular expression will match a string starting with a, followed by b or c and then d. That is:\n'abd'\nor\n'acd'\n", "you don't need the pipe in the character class\nre.compile(\"a[bc]d\").findall(\"akjh adc abc abbd acd\") \n\nthe pattern says, search for a, then b or c (ie, anything in the character class...
[ 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005649514_python_regex.txt
Q: How to launch a program with many arguments in Python/Linux The following code works fine in Windows: subprocess.Popen([PATH_TO_G++]/g++ file.cpp -o file.exe) However in Linux I get the following error: OSError: [Errno 2] No such file or directory After reading the documentation and several SO threads, I found ...
How to launch a program with many arguments in Python/Linux
The following code works fine in Windows: subprocess.Popen([PATH_TO_G++]/g++ file.cpp -o file.exe) However in Linux I get the following error: OSError: [Errno 2] No such file or directory After reading the documentation and several SO threads, I found out that subprocess.Popen works differently in Windows and nix sy...
[ "Based on your example you'll need to make sure the command is properly quoted:\nsubprocess.Popen([PATH_TO_G++ + \"/g++\", \"file.cpp\", \"-o\", \"file.exe\"])\n\nThere is no way PATH_TO_G++ is a valid variable name, so I'm just going to assume that you provided that as an example.\nNow, more importantly, what are ...
[ 4 ]
[]
[]
[ "attributes", "linux", "process", "python", "windows" ]
stackoverflow_0005649701_attributes_linux_process_python_windows.txt
Q: Capturing/Return the output message of python logging Is there a way of obtaining/returning the message from a call to logging.debug()? Thanks A: Yes, providing a mechanism to easily capture and redirect event details without requiring any modification to the code emitting the events is the entire purpose of the...
Capturing/Return the output message of python logging
Is there a way of obtaining/returning the message from a call to logging.debug()? Thanks
[ "Yes, providing a mechanism to easily capture and redirect event details without requiring any modification to the code emitting the events is the entire purpose of the logging module.\nAll you need to do is include an appropriate call to logging.basicConfig() as your application starts up and you can send logged e...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005649540_python.txt
Q: SciPy global minimum curve fit I'm using scipy.optimize.curve_fit, but I suspect it is converging to a local minimum and not the global minimum. I tried using simulated annealing in the following way: def fit(params): return np.sum((ydata - specf(xdata,*params))**2) p = scipy.optimize.anneal(fit,[1000,1E-10]) ...
SciPy global minimum curve fit
I'm using scipy.optimize.curve_fit, but I suspect it is converging to a local minimum and not the global minimum. I tried using simulated annealing in the following way: def fit(params): return np.sum((ydata - specf(xdata,*params))**2) p = scipy.optimize.anneal(fit,[1000,1E-10]) where specf is the curve I am trying...
[ "You're right, it only converges towards a local minimum (when it converges) since it uses the Levenburg-Marquardt algorithm. There is no global curve fitter in SciPy, you have to write you own using the existing global optimizers . But be aware, that this still don't have to converge to the value you want. That's ...
[ 7, 3, 1 ]
[]
[]
[ "curve_fitting", "python", "scientific_computing", "scipy", "simulated_annealing" ]
stackoverflow_0005387464_curve_fitting_python_scientific_computing_scipy_simulated_annealing.txt
Q: Continuous unit testing with Pydev (Python and Eclipse) Is there a way to integrate background unit tests with the Pydev Eclipse environment? My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse...
Continuous unit testing with Pydev (Python and Eclipse)
Is there a way to integrate background unit tests with the Pydev Eclipse environment? My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and t...
[ "This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pas...
[ 36, 9, 5, 1, 0, 0 ]
[]
[]
[ "pydev", "python", "unit_testing" ]
stackoverflow_0001015581_pydev_python_unit_testing.txt
Q: A possible bug in odeint <-> interp1d interplay? I'm relatively new to python and scipy, being a convert from MATLAB. I was doing a quick test of the odeint function in scipy.integrate, and came across this potential bug. Consider the following snippet: from scipy import * from scipy.integrate import odeint from s...
A possible bug in odeint <-> interp1d interplay?
I'm relatively new to python and scipy, being a convert from MATLAB. I was doing a quick test of the odeint function in scipy.integrate, and came across this potential bug. Consider the following snippet: from scipy import * from scipy.integrate import odeint from scipy.interpolate import interp1d from pylab import * ...
[ "This isn't a bug. The issue is with the fact that you've turned bound_error to False and filled those values with zeros. If you set bound_error to True in your original code, you can see that you are exceeding the bounds of your interpolation and thus are putting in zeros in the integration (and thus producing a d...
[ 3 ]
[]
[]
[ "interpolation", "numerical_integration", "ode", "python", "scipy" ]
stackoverflow_0005649313_interpolation_numerical_integration_ode_python_scipy.txt
Q: Using classes to keep predefined strings Is that a good way to define a class like this: class states: INACTIVE = 'Inactive' ACTIVE = 'Active' PENDING = 'Pending' BANNED = 'Banned' to keep a list of possible values and then get them as, e.g. states.INACTIVE, so when I want to change user's status,...
Using classes to keep predefined strings
Is that a good way to define a class like this: class states: INACTIVE = 'Inactive' ACTIVE = 'Active' PENDING = 'Pending' BANNED = 'Banned' to keep a list of possible values and then get them as, e.g. states.INACTIVE, so when I want to change user's status, I do something like this: user.status=states....
[ "I think this solution is OK. But maybe I would add those constants to the user class:\nclass User:\n STATUS_INACTIVE = 'Inactive'\n STATUS_ACTIVE = 'Active'\n STATUS_PENDING = 'Pending'\n STATUS_BANNED = 'Banned'\n\n def __init__(self):\n self.status = User.STATUS_ACTIVE\n\n", "It seems lik...
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005650557_python.txt
Q: Setting Network settings from Python/Django on a Linux/Ubuntu machine I'm working on a simple web interface for an embedded computer. The computer will ship with a static default ip that will then need to be updated by the install tech who may not be tech/linux savvy. Basicly I need to change the following system...
Setting Network settings from Python/Django on a Linux/Ubuntu machine
I'm working on a simple web interface for an embedded computer. The computer will ship with a static default ip that will then need to be updated by the install tech who may not be tech/linux savvy. Basicly I need to change the following system settings from a Django app. IP Addres Subnet Default Gateway DNS Servers ...
[ "Have a look at pynetlinux on Github:\nhttps://github.com/rlisagor/pynetlinux\nIt is a good starting point and you can add the remaining functionality yourself quite easily I would imagine.\n" ]
[ 9 ]
[]
[]
[ "django", "ip", "networking", "python", "ubuntu" ]
stackoverflow_0005650965_django_ip_networking_python_ubuntu.txt
Q: Python: NameError while using nested classes I encountered with the following error: NameError: name 'JsonCleaner' is not defined The line, causing the error is the first pair in dictionary ERROR_CODES_MAPPING_DICT (see code below): from sshop.engine.models import WrongJsonError class JsonCleaner: class Nor...
Python: NameError while using nested classes
I encountered with the following error: NameError: name 'JsonCleaner' is not defined The line, causing the error is the first pair in dictionary ERROR_CODES_MAPPING_DICT (see code below): from sshop.engine.models import WrongJsonError class JsonCleaner: class NormalizeError(Exception): ERROR_NO_CODE = ...
[ "The class name cannot be used within the class scope since the name isn't actually bound until the class is completely defined. Move the dict literal outside the class scope.\nJsonCleaner.ERROR_CODES_MAPPING_DICT = ...\n\n", "JsonCleaner ist not completely defined at that point and therefor unknown. Just remove ...
[ 5, 3 ]
[ "Try replacing \"JsonCleaner\" with \"self\".\n ERROR_CODES_MAPPING_DICT = {\n # Line where exception is raised:\n self.NormalizeError.ERROR_NO_CODE: WrongJsonError.NO_ERROR, \n self.NormalizeError.ERROR_LACK_OF_FIELD: WrongJsonError.ERROR_LACK_OF_FIELD,\n self.NormalizeError.ERROR_TYPE_MISMATCH: ...
[ -1 ]
[ "python" ]
stackoverflow_0005651376_python.txt
Q: Mechanize not working for automating gmail login in Google Appengine I have used mechanize and deployed an app on GAE and it works fine. But, for an app that I am making, I am trying to automate login to gmail through mechanize. It doesn't work in the development environment on local machine as well as after deplo...
Mechanize not working for automating gmail login in Google Appengine
I have used mechanize and deployed an app on GAE and it works fine. But, for an app that I am making, I am trying to automate login to gmail through mechanize. It doesn't work in the development environment on local machine as well as after deploying on appengine. I have been able to use the same script to run it on my...
[ "The problem is most likely due to how Google crippled the urllib2 module on GAE.\nInternally it now uses the urlfetch module (which is something that Google wrote) and they have completely removed the HTTPCookieProcessor() functionality - meaning, cookies are NOT persisted from request to request which is the crit...
[ 7 ]
[]
[]
[ "gmail", "google_app_engine", "mechanize", "python" ]
stackoverflow_0005633702_gmail_google_app_engine_mechanize_python.txt
Q: OpenCV zero padding I'm using cvFilter2D to filter images. Its documentation says: When the aperture is partially outside the image, the function interpolates outlier pixel values from the nearest pixels that are inside the image. While such extrapolation is fine in a majority of cases, I want to handle s...
OpenCV zero padding
I'm using cvFilter2D to filter images. Its documentation says: When the aperture is partially outside the image, the function interpolates outlier pixel values from the nearest pixels that are inside the image. While such extrapolation is fine in a majority of cases, I want to handle such outlier pixel values ...
[ "If you don't mind losing a the external 1-pixel thick edge of your image, you can set it to 0, and then the \"interpolation\" will give you what you want.\n", "I'm not sure about Python, but the in C/C++, you can specify that you want a certain constant to be used for the \"undefined\" pixels. Set this constant ...
[ 2, 1 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0005311710_image_processing_opencv_python.txt
Q: python exceptions: how to print all debug info for nested try? I have code: try: print test.qwerq] try: print test.sdqwe] except: pass except: pass How to print debug info for all errors in nested try ? A: Re-raise exceptions. try: print test[qwerq] try: print tes...
python exceptions: how to print all debug info for nested try?
I have code: try: print test.qwerq] try: print test.sdqwe] except: pass except: pass How to print debug info for all errors in nested try ?
[ "Re-raise exceptions.\ntry:\n print test[qwerq]\n try:\n print test[qwe]\n except:\n # Do something with the exception.\n raise\nexcept:\n # Do something here too, just for fun.\n raise\n\nIt should be noted that in general you don't want to do this. You're better off not catching ...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0005651794_python.txt
Q: Receiving TypeError while trying to write to file in Python When I run this code: tickers = re.findall(r'Process Name: (\w+)', s) file = open("C:\Documents and Settings\jppavan\My Documents\My Dropbox\Python Scripts\Processes\GoodProcesses.txt","w") file.write(tickers) file.close() It returns the common error: ...
Receiving TypeError while trying to write to file in Python
When I run this code: tickers = re.findall(r'Process Name: (\w+)', s) file = open("C:\Documents and Settings\jppavan\My Documents\My Dropbox\Python Scripts\Processes\GoodProcesses.txt","w") file.write(tickers) file.close() It returns the common error: TypeError: expected a character buffer object Any ideas?
[ "findall() as the name indicates returns a Python list and not a string/buffer.\nYou can not write a list to file handle - how should that work? \nWhat do you expect?\nfile.write(str(tickers))\n\nfor the string representation of the list?\nOr \nfile.write(', '.join(tickers))\n\nfor a comma-separated concatenation o...
[ 17 ]
[]
[]
[ "file_io", "python", "typeerror" ]
stackoverflow_0005651784_file_io_python_typeerror.txt
Q: Doing column math with numpy in python I am looking for coding examples to learn Numpy. Usage would be dtype ='object'. To construnct array the code used would a= np.asarray(d, dtype ='object') not np.asarray(d) or np.asarray(d, dtype='float32') Is sorting any different than float32/64? Coming from excel "cel...
Doing column math with numpy in python
I am looking for coding examples to learn Numpy. Usage would be dtype ='object'. To construnct array the code used would a= np.asarray(d, dtype ='object') not np.asarray(d) or np.asarray(d, dtype='float32') Is sorting any different than float32/64? Coming from excel "cell" equations, wrapping my head around Row Co...
[ "Despite the fact that I still cannot understand exactly what you are asking, here is my best guess. Let's say you want to sort A by the values in 3rd column:\nA = array([['a',2,3,4],['b',5,6,2],['c',5,1,5]], dtype ='object')\n\nii = np.argsort(A[:,2])\nprint A[ii,:]\n\nHere the rows have been sorted according to t...
[ 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005640761_arrays_numpy_python.txt
Q: Any alternative for waitForPageToLoad I am developing automated test cases for my app using selenium RC in python 2.7. When I am using wait_for_time_to_load(time) is throwing error as the timeout is variable in my app. Can anyone suggest me any other alternative for the function "wait_for_page_to_load" which does ...
Any alternative for waitForPageToLoad
I am developing automated test cases for my app using selenium RC in python 2.7. When I am using wait_for_time_to_load(time) is throwing error as the timeout is variable in my app. Can anyone suggest me any other alternative for the function "wait_for_page_to_load" which does not take time as a parameter. Thanks
[ "Just to add to @rs79's code\n int iteration = 0;\n //checks the presence of element till a given no of iterations(say 20) to avoid infinite loop\n while(!(selenium.isElementPresent(\"yourelement\")) && iteration < 20){\n Thread.sleep(1000);\n iteration++;\n }\n\nagain this is in java, hop...
[ 1, 0 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0005648709_python_selenium_rc.txt
Q: Reading in a CSV file AND sorting it in Python I am trying to read in a CSV file that looks like this: ruby,2,100 diamond,1,400 emerald,3,250 amethyst,2,50 opal,1,300 sapphire,2,500 malachite,1,60 Here is some code I have been experimenting with. class jewel: def __init__(gem, name, carat, value): ...
Reading in a CSV file AND sorting it in Python
I am trying to read in a CSV file that looks like this: ruby,2,100 diamond,1,400 emerald,3,250 amethyst,2,50 opal,1,300 sapphire,2,500 malachite,1,60 Here is some code I have been experimenting with. class jewel: def __init__(gem, name, carat, value): gem.name = name gem.carot = carat ...
[ "You need to do two things here, the first is actually loading the data into the objects. I recommend you look at the 'csv' module in the standard python library for this. It's very complete and will read each row and make it easily accessable\nCSV docs: http://docs.python.org/library/csv.html\nI would create a ...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "csv", "file", "python", "sorting" ]
stackoverflow_0005643281_csv_file_python_sorting.txt
Q: Django Want to print the date & time for today I want to print some sort of time stamp or some sort of function to tell what day and time it is in a template. In my views I have time = datetime.now() and in my template I have {{time}} All this does is prints out a <type 'datetime.date'> object. A: if its ju...
Django Want to print the date & time for today
I want to print some sort of time stamp or some sort of function to tell what day and time it is in a template. In my views I have time = datetime.now() and in my template I have {{time}} All this does is prints out a <type 'datetime.date'> object.
[ "if its just in the template, use now\nIt is {% now \"f\" %}\n\n", "Normally, this should work:\nfrom datetime import datetime\n\ndef a_view(request):\n return render_to_response(\"a_template.html\", {\n 'time':datetime.now(),\n }, context_instance=RequestContext(request))\n\nThen render the date...
[ 84, 5 ]
[]
[]
[ "date", "datetime", "django", "python", "views" ]
stackoverflow_0005651763_date_datetime_django_python_views.txt
Q: How to copy raw data to ctypes.Structure from Python C extension? Is it possible to get the value of pointer to raw data of ctypes.Structure instance in Python C extension? I would like to access and copy data from/to the instance of this class without bothering the interpreter by importing and using ctypes.memmov...
How to copy raw data to ctypes.Structure from Python C extension?
Is it possible to get the value of pointer to raw data of ctypes.Structure instance in Python C extension? I would like to access and copy data from/to the instance of this class without bothering the interpreter by importing and using ctypes.memmove or ctypes.addressof. In other words, does ctypes provide any C API wh...
[ "It doesn't appear that ctypes exposes a C API.\nThis is how it's done in >= 2.7: http://docs.python.org/extending/extending.html#providing-a-c-api-for-an-extension-module\nctypes source tagged at 2.7.1: http://svn.python.org/view/python/tags/r271/Modules/_ctypes/\nI don't see anywhere in the source where an API ca...
[ 0 ]
[]
[]
[ "ctypes", "python", "structure" ]
stackoverflow_0005650942_ctypes_python_structure.txt
Q: python == syntax error i am getting a syntax error with the following code via a windmill test. it looks like it does not like the == any thoughts on what I am doing wrong counter = 0 while True: try: # some code goes here except: counter += 1 # some code goes here if c...
python == syntax error
i am getting a syntax error with the following code via a windmill test. it looks like it does not like the == any thoughts on what I am doing wrong counter = 0 while True: try: # some code goes here except: counter += 1 # some code goes here if counter == 3 coun...
[ "You need a colon after your if-statement.\nedit: fix the formatting of your code.\nI also see you're using C-style comments, which Python doesn't support. All comments in Python start with #.\nAlso, Python dellimits blocks by their indentation. Make sure you indent blocks consistently.\n", "You have a syntax err...
[ 7, 0 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0005651974_operators_python.txt
Q: cgi URL forwarding with "Location" header - only partial forwarding? Greetings all, I have a python CGI script which using print "Location: [nextfilename]" print After "forwarding" (the reason for the quotes there is apparent in a second), I see the HTML of the page to which it has forwarded fine, but all images...
cgi URL forwarding with "Location" header - only partial forwarding?
Greetings all, I have a python CGI script which using print "Location: [nextfilename]" print After "forwarding" (the reason for the quotes there is apparent in a second), I see the HTML of the page to which it has forwarded fine, but all images, etc. are not showing. The address bar still shows the cgi script as the ...
[ "You need to send a 30X Status header as well. See RFC 2616 for details.\n" ]
[ 2 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0005652078_cgi_python.txt
Q: SQLAlchemy Many-to-Many Relationship on a Single Table I have a SQLAlchemy model set up in my application that should mimic the functionality of "followers" on Twitter, ie. users have have a many-to-many relationship with eachother (both followers and following). The tables are structured as follows (sa is the sq...
SQLAlchemy Many-to-Many Relationship on a Single Table
I have a SQLAlchemy model set up in my application that should mimic the functionality of "followers" on Twitter, ie. users have have a many-to-many relationship with eachother (both followers and following). The tables are structured as follows (sa is the sqlalchemy module): t_users = sa.Table("users", meta.metadata,...
[ "You can also do this declaratively.\nHere is a similar example based on the above code, I do use the backref.\nVolumeRelationship = Table(\n 'VolumeRelationship', Base.metadata,\n Column('ParentID', Integer, ForeignKey('Volumes.ID')),\n Column('VolumeID', Integer, ForeignKey('Volumes.ID'))\n )\n\nclass...
[ 24, 9 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0001889251_orm_python_sqlalchemy.txt
Q: how to insert values into a list in python.. with a few extra conditions hi i have a list of tuples like this: bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ] and i wish to append each individual tuple to a dictionary as the dictionarys key. i want the format to look like ...
how to insert values into a list in python.. with a few extra conditions
hi i have a list of tuples like this: bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ] and i wish to append each individual tuple to a dictionary as the dictionarys key. i want the format to look like this. dict = {"wealth-gain": value, "gain-burnt": value ......} how would i ...
[ "You can use the join method:\nbigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]\ndict_ = {}\nfor tup in bigrams:\n k = '-'.join(tup)\n dict_[k] = data.setdefault(k,0) + 1\n\nor express the initialization with a generator:\nbigrams = [ ('wealth', 'gain'), ('gain', 'burnt...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "nltk", "python" ]
stackoverflow_0005651998_dictionary_nltk_python.txt
Q: Python 2.5 Windows Binaries? I need to test an issue that occurs on Windows with Python 2.5, but the releases page doesn't link to a binary for 2.5. Is there anywhere I could find a copy? A: It's on their FTP server still, it's just the link that's gone: http://www.python.org/ftp/python/2.5/ You'll want one of t...
Python 2.5 Windows Binaries?
I need to test an issue that occurs on Windows with Python 2.5, but the releases page doesn't link to a binary for 2.5. Is there anywhere I could find a copy?
[ "It's on their FTP server still, it's just the link that's gone:\nhttp://www.python.org/ftp/python/2.5/\nYou'll want one of the MSI files, depending on your Windows version (32-bits or 64-bits).\n", "ActiveState keeps old binaries for ActivePython available on its site. The oldest version there is 2.5.5.7.\n", ...
[ 8, 3, 2, 2, 1 ]
[]
[]
[ "python", "python_2.5", "windows" ]
stackoverflow_0003408847_python_python_2.5_windows.txt
Q: BeautifulSoup - Help me pick out divs and classes Heres my HMTL code: <div class="BlockA"> <h4>BlockA</h4> <div class="name">John Smith</div> <div class="number">2</div> <div class="name">Paul Peterson</div> <div class="number">14</div> </div> <div class="BlockB"> <h4>BlockB</h4> <div ...
BeautifulSoup - Help me pick out divs and classes
Heres my HMTL code: <div class="BlockA"> <h4>BlockA</h4> <div class="name">John Smith</div> <div class="number">2</div> <div class="name">Paul Peterson</div> <div class="number">14</div> </div> <div class="BlockB"> <h4>BlockB</h4> <div class="name">Steve Jones</div> <div class="number">...
[ "You want to find divs that contain a class attribute of \"name\" or \"number\"?\n>>> import re\n>>> soup.findAll(\"div\", {\"class\":re.compile(\"name|number\")})\n\n[<div class=\"name\">John Smith</div>, <div class=\"number\">2</div>, <div class=\"name\">Paul Peterson</div>, <div class=\"number\">14</div>, <div c...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "json", "python" ]
stackoverflow_0005652033_beautifulsoup_html_json_python.txt
Q: Apply opencv threshold to a numpy array I'm trying to apply opencv's Threshold function to a numpy array. I'm using the python bindings for opencv 2.1. It goes like this: import cv import numpy as np a = np.random.rand(1024,768) cv.Threshold(a,a,0.5,1,cv.CV_THRESH_BINARY) and this throws an error: OpenCV Error: U...
Apply opencv threshold to a numpy array
I'm trying to apply opencv's Threshold function to a numpy array. I'm using the python bindings for opencv 2.1. It goes like this: import cv import numpy as np a = np.random.rand(1024,768) cv.Threshold(a,a,0.5,1,cv.CV_THRESH_BINARY) and this throws an error: OpenCV Error: Unsupported format or combination of formats (...
[ "Apparently the Threshold method is more fussy than Smooth - it only works on 8 bit integer / 32 bit floating point arrays (see here) so your code snippet above won’t work because numpy arrays default to float64.\nSo if you change the line where you create the array to force the precision to 32 bit float\n>>> a = n...
[ 12 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0003903432_numpy_opencv_python.txt
Q: hash tables in python I started learning hash tables, so could anybody explain how the programm works. Although, where should I write a list with values? The code is here: http://www.daniweb.com/software-development/python/threads/342511 A: What you are looking at is an implementation of Hash Tables with chainin...
hash tables in python
I started learning hash tables, so could anybody explain how the programm works. Although, where should I write a list with values? The code is here: http://www.daniweb.com/software-development/python/threads/342511
[ "What you are looking at is an implementation of Hash Tables with chaining.\nThe purpose of this is to avoid hash collisions by creating a chain of values in which their hash values are the same.\nThe general implementation is that the key contains a pointer to a linked list. When you want to insert a value, you ad...
[ 2 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0005652936_hash_python.txt
Q: Using python how to find elements in a list of lists based on a key that is an element of the inner list? Suppose I have a list of lists or a list of tuples, whichever can solve my problem more efficiently. Eg: student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] The task is t...
Using python how to find elements in a list of lists based on a key that is an element of the inner list?
Suppose I have a list of lists or a list of tuples, whichever can solve my problem more efficiently. Eg: student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] The task is to find an element in the main list based on a key that is any element of the inner list or tuple. Eg: Using the...
[ "I would use filter() or a list comprehension.\ndef find_listcomp(students, value):\n return [student for student in students if student[1] == value or student[2] == value]\n\ndef find_filter(students, value):\n return filter(lambda s: s[1] == value or s[2] == value, students) \n\n", "To find the first matc...
[ 16, 8, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005652943_python.txt
Q: Shell to Python troubles if ! ps ax | grep -v grep | grep -v -i tmux | grep "theserver.jar" > /dev/null; then echo "Server failed to start!" else echo "Server successfully started!" fi How can i make this with python, please? I can't figure out how to do it. Please, help :( Can i use o...
Shell to Python troubles
if ! ps ax | grep -v grep | grep -v -i tmux | grep "theserver.jar" > /dev/null; then echo "Server failed to start!" else echo "Server successfully started!" fi How can i make this with python, please? I can't figure out how to do it. Please, help :( Can i use os.system? Thanks in advance.
[ "You can shell out with the subprocess module and run arbitrary shell commands, but you may want to consider using something like the PSI or psutil modules.\nThey are non-standard so you will have to download and install them, but they will be much more robust and resistant to errors. (Remember that ps output form...
[ 2, 1 ]
[]
[]
[ "python", "shell", "ubuntu_10.10" ]
stackoverflow_0005652758_python_shell_ubuntu_10.10.txt
Q: Running Commands in Python I am new to python. Any ideas why this does not work: C:\Python27>python Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> cmdBuilder = os.path.join("C:\\","Progr...
Running Commands in Python
I am new to python. Any ideas why this does not work: C:\Python27>python Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> cmdBuilder = os.path.join("C:\\","Program Files","InstallShield","2011...
[ "Try wrapping the executable in quotes:\n>>> os.system('\"'+cmdBuilder+'\"')\n\n", "Because parts of the path contain whitespaces.\nSee also \nhttp://help.wugnet.com/windows2/Program-space-batch-file-ftopict489742.html\n" ]
[ 3, 1 ]
[]
[]
[ "command", "python" ]
stackoverflow_0005653106_command_python.txt
Q: Adding assignees to tickets via API call I'm working with an API to integrate with the ActiveCollab system. I'm trying to add some assignees to a ticket that I have created everytime a new project is created. It is completely ignoring my request to add assignees, which makes me believe that I'm not doing it righ...
Adding assignees to tickets via API call
I'm working with an API to integrate with the ActiveCollab system. I'm trying to add some assignees to a ticket that I have created everytime a new project is created. It is completely ignoring my request to add assignees, which makes me believe that I'm not doing it right. Here is the link to the API instructions an...
[ "Here is the answer, if anyone runs into the same problem.\n'ticket[assignees][0][]': project.estimator_id\n'ticket[assignees][0][]': another assignee ID\n'ticket[assignees][0][]': and another assignee ID\n'ticket[assignees][0][]': ...\n'ticket[assignees][1]': project.estimator_id\n\n" ]
[ 0 ]
[]
[]
[ "activecollab", "api", "django", "django_views", "python" ]
stackoverflow_0005637365_activecollab_api_django_django_views_python.txt
Q: Python immutable types in function calls I have an sqlalchemy query that returns a tuple. I pass this tuple to a function, and since it's an immutable type, a new instance of the tuple is created in the called function. How does python deal with this in terms of memory management? Is a complete copy of the tuple ...
Python immutable types in function calls
I have an sqlalchemy query that returns a tuple. I pass this tuple to a function, and since it's an immutable type, a new instance of the tuple is created in the called function. How does python deal with this in terms of memory management? Is a complete copy of the tuple created, or is it using some clever 'copy on w...
[ "When you call a function, just a reference to the tuple gets passed, not a copy. The fact that it's immutable doesn't mean that it will be copied on a function call, just that you can't modify it.\n", "Python passes references to objects by value. So you dont need to worry about it.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005653150_python_sqlalchemy.txt
Q: How to identify type of draggable item? I need to drop an object dragged from a third party application to a wxpython application. I know the content of the object is basically a string but I dont know how to specify the type so that the drop is accepted by the wxpython application. By "type", I refer to this doc...
How to identify type of draggable item?
I need to drop an object dragged from a third party application to a wxpython application. I know the content of the object is basically a string but I dont know how to specify the type so that the drop is accepted by the wxpython application. By "type", I refer to this documentation: http://wiki.wxpython.org/DragAndD...
[ "It looks like your best bet is to use wx.PyDropTarget and wx.DataObjectComposite, from which you can call .GetReceivedFormat().GetType().\nThere's an example app on the wxPython wiki:\nhttp://wiki.wxpython.org/DragAndDrop#wxDataObjectComposite\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0005653189_python_wxpython_wxwidgets.txt
Q: python remove text inside I want to remove text inside <p> tags for a block of html text. I am trying to standardize some text and remove all class, align, and other information. Every example I can find seems to deal with stripping html, and I don't want to strip the tags. I just want to make them all plain. ...
python remove text inside
I want to remove text inside <p> tags for a block of html text. I am trying to standardize some text and remove all class, align, and other information. Every example I can find seems to deal with stripping html, and I don't want to strip the tags. I just want to make them all plain. So if I have something like this...
[ "Use a library for parsing HTML such as Beautiful Soup or a similar alternative. Regex is not powerful enough to correctly parse HTML.\n@Mark made a valid point that in this particular case a simple regex should work because you are not doing full parsing with tag matching etc. I still think it's a good practice ...
[ 6, 3, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0005652999_python_regex_string.txt
Q: different results in IDLE and Windows console I write this simple bit of code (Python 3.2 on Win32): def main(): decision = input('¿Send mail? (y/n): ') if decision == "y": sender() print("Mail sent.") else: print("Cancelled.") input() def sender(): print("In sender ......
different results in IDLE and Windows console
I write this simple bit of code (Python 3.2 on Win32): def main(): decision = input('¿Send mail? (y/n): ') if decision == "y": sender() print("Mail sent.") else: print("Cancelled.") input() def sender(): print("In sender ... ") pass main() and it works as expected in I...
[ "I suggest you read the definition of input(). It is not recommended for general user input as it expects syntactically valid Python code and eval()s it.\n" ]
[ 1 ]
[]
[]
[ "console_application", "python" ]
stackoverflow_0005652257_console_application_python.txt
Q: Sorting dictionary by values in python I have a dictionary with key as words and values as ints. Is it possible to sort the dictionary by values? I want to be able to take the top 10 most occurring words in my dictionary. The values represent the word counts and the keys represent the word. counter = 9 for a,b in ...
Sorting dictionary by values in python
I have a dictionary with key as words and values as ints. Is it possible to sort the dictionary by values? I want to be able to take the top 10 most occurring words in my dictionary. The values represent the word counts and the keys represent the word. counter = 9 for a,b in sorted(dict_.iteritems()): if counte...
[ "Python dictionaries are unordered, but you can convert it to a list of tuples using items() and pass an appropriate comparison function to sort's key parameter.\nsorted() has an analogous key parameter. You'd want to sort by lambda item: item[1] to get the value out of items() and iteritems(). Then you can just sl...
[ 2, 2, 2, 1, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0005653573_dictionary_python_sorting.txt
Q: port scanner in python if data.find('!scan') != -1: nick = data.split('!')[ 0 ].replace(':','') targetip = gethostbyname(arg) sck.send('PRIVMSG ' + chan + " :" ' scanning host' + targetip + '\r\n') for i in range(20, 1025): s = socket(AF_INET, SOCK_STREAM) result = s.connect...
port scanner in python
if data.find('!scan') != -1: nick = data.split('!')[ 0 ].replace(':','') targetip = gethostbyname(arg) sck.send('PRIVMSG ' + chan + " :" ' scanning host' + targetip + '\r\n') for i in range(20, 1025): s = socket(AF_INET, SOCK_STREAM) result = s.connect_ex((targetip, i)) ...
[ ">>> import socket\n>>> socket.gethostbyname('localhost')\n'127.0.0.1'\n\nAs mentioned make sure you imported the socket module, and depending on how you did that you can call gethostbyname().\n", "At the top of your script, it's looks like you performed:\nfrom socket import *\n\nOr something \"relatively\" large...
[ 3, 1, 0, 0 ]
[]
[]
[ "irc", "python", "sockets" ]
stackoverflow_0005653613_irc_python_sockets.txt
Q: Tracing windows API calls I am currently working on a tool in .NET/Python that monitors certain events on a system, like writing specific registry keys or creating files with a special name. I evaluated many possibilities, and as I don't have to care about WinXP support, I am using Event Tracing for Windows to get...
Tracing windows API calls
I am currently working on a tool in .NET/Python that monitors certain events on a system, like writing specific registry keys or creating files with a special name. I evaluated many possibilities, and as I don't have to care about WinXP support, I am using Event Tracing for Windows to get a real-time stream of all file...
[ "Generally speaking, there are two approaches to intercepting system API calls; either user mode or kernel mode interception. For user mode API interception, you will have to hook every process to accurately capture/redirect every call to your desired API function. Kernel mode interception circumvents the need to h...
[ 3 ]
[]
[]
[ ".net", "etw", "python", "trace", "winapi" ]
stackoverflow_0005652908_.net_etw_python_trace_winapi.txt