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: MongoDB: Limiting results from a $gt query (from pymongo) I'm gathering some statistics from a web service, and storing it in a collection. The data looks similar to this (but with more fields): {"downloads": 30, "dt": "2010-02-17T16:56:34.163000"} {"downloads": 30, "dt": "2010-02-17T17:56:34.163000"} {"downloads"...
MongoDB: Limiting results from a $gt query (from pymongo)
I'm gathering some statistics from a web service, and storing it in a collection. The data looks similar to this (but with more fields): {"downloads": 30, "dt": "2010-02-17T16:56:34.163000"} {"downloads": 30, "dt": "2010-02-17T17:56:34.163000"} {"downloads": 30, "dt": "2010-02-17T18:56:34.163000"} {"downloads": 30, "dt...
[ "You can do this using group. In your example you'd need to supply a javascript function to compute the key (as well the reduce function), because you want only the date component of the datetime field. This should work:\ndb.coll.group(\n key='function(doc) { return {\"dt\": doc.dt.toDateString()} }',\n con...
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0002291307_mongodb_pymongo_python.txt
Q: Python Lambda behaviour I'm trying to get my head around lambda expressions, closures and scoping in Python. Why does the program not crash on the first line here? >>> foo = lambda x: x + a >>> foo(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> Nam...
Python Lambda behaviour
I'm trying to get my head around lambda expressions, closures and scoping in Python. Why does the program not crash on the first line here? >>> foo = lambda x: x + a >>> foo(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> NameError: global name 'a' is no...
[ "Because that's just not how Python functions work; it's not special to lambdas:\n>>> def foo(x):\n... return x + a\n>>> foo\n<function foo at 0xb7dde454>\n>>> foo(2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in foo\nNameError: global name 'a' is not...
[ 6, 2, 2, 0, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0002294134_lambda_python.txt
Q: Django: Using django.contrib.auth for SAAS ( Users, permissions, etc. ) I'm making a SAAS and I've been asking a slew of questions on here related to the Auth system built in. I'm having trouble understanding the "why" and "how". Primarily I don't understand how it fits in with my SAAS. I (do) know the following: ...
Django: Using django.contrib.auth for SAAS ( Users, permissions, etc. )
I'm making a SAAS and I've been asking a slew of questions on here related to the Auth system built in. I'm having trouble understanding the "why" and "how". Primarily I don't understand how it fits in with my SAAS. I (do) know the following: You can do this: http://docs.djangoproject.com/en/dev/topics/auth/#storing-a...
[ "\nSomebody goes to a page and creates a UserProfile with a username and password, etc.\n\nUserProfile doesn't have an username or password field. So it should be somebody goes to a page and create an User. Then, it creates an UserProfile associated to that newly created User.\nThe question is, how and when do you ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002293924_django_python.txt
Q: How do I create a list or set object in a class in Python? For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects. Thus for the "...
How do I create a list or set object in a class in Python?
For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects. Thus for the "lecturers" dictionary (currently): lecturer[id] = Lecturer(lec...
[ "set is better since you don't care about order and have no duplicate.\nYou can parse the file easily with the csv module (with a delimiter of ' ').\nOnce you have the lec_name you must check if that lecturer's already know; for that purpose, keep a dictionary from lec_name to lecturer objects (that's just another ...
[ 4, 1, 0 ]
[]
[]
[ "class", "dictionary", "python" ]
stackoverflow_0002293968_class_dictionary_python.txt
Q: Beginner extending C with Python (specifically Numpy) I am working on a real time audio processing dynamically linked library where I have a 2 dimensional C array of floating point data which represents the audio buffer. One dimension is time (samples) and the other is channel. I would like to pass this to a pytho...
Beginner extending C with Python (specifically Numpy)
I am working on a real time audio processing dynamically linked library where I have a 2 dimensional C array of floating point data which represents the audio buffer. One dimension is time (samples) and the other is channel. I would like to pass this to a python script as a numpy array for the DSP processing and then I...
[ "You may be able to avoid dealing with the NumPy C API entirely. Python can call C code using the ctypes module, and you can access pointers into the numpy data using the array's ctypes attribute. \nHere's a minimal example showing the process for a 1d sum-of-squares function.\nctsquare.c\n#include <stdlib.h>\n\nfl...
[ 7 ]
[]
[]
[ "api", "c", "c++", "numpy", "python" ]
stackoverflow_0002290007_api_c_c++_numpy_python.txt
Q: Deferred evaluation in python I have heard of deferred evaluation in python (for example here), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many errors until runtime? O...
Deferred evaluation in python
I have heard of deferred evaluation in python (for example here), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many errors until runtime? Or am I missing something entirely?
[ "Deferred evaluation is when an expression isn't evaluated until it's needed. In most languages, you use something like lambda to make this work. Here's a contrived example that shows part of the concept:\ndef list_files():\n for fn in os.listdir('.'):\n yield fn, lambda: open(fn, 'r').read()\n\n\nfor f...
[ 17, 8 ]
[]
[]
[ "evaluation", "interpreter", "lambda", "python" ]
stackoverflow_0002294236_evaluation_interpreter_lambda_python.txt
Q: 'ASCII' to Unicode error in python when attempting to read a latin-1 encoded string I'm having a problem when trying to apply a regular expression to some strings encoded in latin-1 (ISO-8859-1). What I'm trying to do is send some data via HTTP POST from a page encoded in ISO-8859-1 to my python application and d...
'ASCII' to Unicode error in python when attempting to read a latin-1 encoded string
I'm having a problem when trying to apply a regular expression to some strings encoded in latin-1 (ISO-8859-1). What I'm trying to do is send some data via HTTP POST from a page encoded in ISO-8859-1 to my python application and do some parsing on the data using regular expressions in my python script. The web page us...
[ "Try this instead:\nprint(repr(unicode(data, 'iso-8859-1')))\n\nby printing a unicode object you're implicitly trying to convert it to the default encoding, which is ASCII. Using repr will escape it into an ASCII-safe form, plus it'll be easier for you to figure out what's going on for debugging.\n", "Are you usi...
[ 2, 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0002294509_encoding_python.txt
Q: how to write integer number in particular no of bytes in python ( file writing) assume i have to store few integer numbers like 1024 or 512 or 10240 or 900000 in a file, but the condition is that i can consume only 4 bytes (not less nor max).but while writing a python file using write method it stored as "1024" or...
how to write integer number in particular no of bytes in python ( file writing)
assume i have to store few integer numbers like 1024 or 512 or 10240 or 900000 in a file, but the condition is that i can consume only 4 bytes (not less nor max).but while writing a python file using write method it stored as "1024" or "512" or "10240" ie they written as ascii value but i want to store directly their b...
[ "use the struct module\n>>> import struct\n>>> struct.pack(\"i\",1024)\n'\\x00\\x04\\x00\\x00'\n>>> struct.pack(\"i\",10240)\n'\\x00(\\x00\\x00'\n>>> struct.pack(\"i\",900000)\n'\\xa0\\xbb\\r\\x00'\n\nIn Python3, it you can use the to_bytes method of int. The paren around 1024 are only necessary as 1024. parses as ...
[ 13, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002294608_python.txt
Q: How can I replace double and single quotations in a string efficiently? I'm parsing a xml file and inserting it into database. However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient. s = s.replace('"', ...
How can I replace double and single quotations in a string efficiently?
I'm parsing a xml file and inserting it into database. However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient. s = s.replace('"', ' ') s = s.replace("'", ' ') Is there any way I can insert text without repl...
[ "Why can't you insert strings containing quote marks into your database? Is there some weird data type that permits any character except a quote mark? Or are you building an insert statement with literal strings, rather than binding your strings to query parameters as you should be doing?\nIf you're doing\ncursor.e...
[ 12, 2, 1 ]
[]
[]
[ "database", "python", "string" ]
stackoverflow_0002293854_database_python_string.txt
Q: How do I define an array of custom types in WSDL? I'm very new to WSDL, but what I'm trying to do is very simple. I have gotten a web service working with python's ZSI library, but am stuck defining a service which returns an array of a custom type. In my WSDL I have the following: <xsd:element name="ArtPiece"> ...
How do I define an array of custom types in WSDL?
I'm very new to WSDL, but what I'm trying to do is very simple. I have gotten a web service working with python's ZSI library, but am stuck defining a service which returns an array of a custom type. In my WSDL I have the following: <xsd:element name="ArtPiece"> <xsd:complexType> <xsd:sequence> <xsd:...
[ "<xs:schema elementFormDefault=\"qualified\" \n targetNamespace=\"http://schemas.datacontract.org/2004/07/Foo\" \n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \n xmlns:tns=\"http://schemas.datacontract.org/2004/07/Foo\">\n <xs:complexType name=\"ArtPiece\">\n <xs:sequence>\...
[ 26 ]
[]
[]
[ "c#", "python", "soap", "web_services", "wsdl" ]
stackoverflow_0002293873_c#_python_soap_web_services_wsdl.txt
Q: Sudo equivalent for Django user profiles Is it possible to implement an equivalent of sudo for Django profiles ? I'm using the basic authentication system django.contrib.auth. Usecase: Sometimes, users report bugs which are only reproductible in their profile, so, each time, I change their password, log in, fix t...
Sudo equivalent for Django user profiles
Is it possible to implement an equivalent of sudo for Django profiles ? I'm using the basic authentication system django.contrib.auth. Usecase: Sometimes, users report bugs which are only reproductible in their profile, so, each time, I change their password, log in, fix the bug and replaces the password with the orig...
[ "Djangosnippets.org is your friend: http://www.djangosnippets.org/snippets/1590/\n", "I knocked up a user panel in the debug toolbar. It works well for flipping logged in users around . The fork is here. \nhttp://github.com/mjbrownie/django-debug-toolbar\nit also displays some basic user group permission info. I ...
[ 3, 2 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0002289917_authentication_django_python.txt
Q: Issue with python class hierarchy I have a class hierarchy: class ParentClass: def do_something(self): pass # child classes have their own implementation of this class ChildClass1(ParentClass): def do_something(self): <implementation here> class ChildClass2(ParentClass): def do_som...
Issue with python class hierarchy
I have a class hierarchy: class ParentClass: def do_something(self): pass # child classes have their own implementation of this class ChildClass1(ParentClass): def do_something(self): <implementation here> class ChildClass2(ParentClass): def do_something(self, argument_x): <impl...
[ "Methods with the same name and different arguments are a code smell.\n\"method do_something() has different interfaces in subclasses: it accepts an argument in child classes 2 and 3, but has no argument in child class 1\"\nYou don't say why. There are two good reasons why \n\nchild class 1 has a default value. \nc...
[ 13, 2, 1 ]
[ "You could do this, to make the signatures the same:\nclass ParentClass:\n pass\n\nclass ChildClass1(ParentClass):\n\n def do_something(self, **kwargs):\n <implementation here>\n\nclass ChildClass2(ParentClass):\n\n def do_something(self, **kwargs):\n argument_x = kwargs[argument_x]\n ...
[ -4 ]
[ "oop", "python" ]
stackoverflow_0002294200_oop_python.txt
Q: assign multiple instances of a class to variables Python. I need to assign multiple class instances to number of variables. First i tried this: a = b = c = [] but they all refer to the same object, which is not what I need. This works better: (a, b, c) = [[] for i in range(3)] but it seems a bit too verbose. Is ...
assign multiple instances of a class to variables
Python. I need to assign multiple class instances to number of variables. First i tried this: a = b = c = [] but they all refer to the same object, which is not what I need. This works better: (a, b, c) = [[] for i in range(3)] but it seems a bit too verbose. Is there a shorter way to do this? UPDATE: OK, so this is ...
[ "a, b, c = [], [], []\n\n", "simply:\na = []\nb = []\nc = []\n\n(python is not perl, there is no need for one-liners)\n", "a = []\nb = a[:]\nimport copy\nc = copy.copy(b)\n\nYou could use these if you want them all initialized to something other than []\n" ]
[ 9, 8, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002294823_python.txt
Q: python csv - export data and format color, text format, etc I'm exporting data from python with the csv library which works pretty good. After a web-search I can not find any information about how to format the exported data with python. For example. I export a csv row within python like this. for hour_record in o...
python csv - export data and format color, text format, etc
I'm exporting data from python with the csv library which works pretty good. After a web-search I can not find any information about how to format the exported data with python. For example. I export a csv row within python like this. for hour_record in object_list: row = list() for field in fie...
[ "CSV is used only for plain text. If you want formatting information to be contained then you must either embed HTML fragments, or you must add the attributes as separate fields. Either option will require a consumer that understands said formatting mechanism.\n", "Instead of csv, you should use numpy.genfromtxt ...
[ 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002295727_csv_python.txt
Q: join lists based on common head or tail What is the fastest way to solve the following I will to join several lists based on common head or tail input = ([5,6,7], [1,2,3], [3,4,5], [8, 9]) output = [1, 2, 3, 4, 5, 6, 7] A: >>> def chain(inp): d = {} for i in inp: d[i[0]] = i[:], i[-1] l, n = ...
join lists based on common head or tail
What is the fastest way to solve the following I will to join several lists based on common head or tail input = ([5,6,7], [1,2,3], [3,4,5], [8, 9]) output = [1, 2, 3, 4, 5, 6, 7]
[ ">>> def chain(inp):\n d = {}\n for i in inp:\n d[i[0]] = i[:], i[-1]\n l, n = d.pop(min(d))\n while True:\n lt, n = d.pop(n, [None, None])\n if n is None:\n if len(d) == len(inp) - 1:\n l, n = d.pop(min(d))\n continue\n break\n ...
[ 1 ]
[]
[]
[ "head", "join", "list", "python", "tail" ]
stackoverflow_0002296406_head_join_list_python_tail.txt
Q: How to open a Pyqt 3.3 ui file with QtDesigner 4? I've a PyQt 4 installed (I can't find PyQt 3 for Windows) and I would like to open a QtDesigner ui file which has been created with QtDesigner 3.3. When I open this file I've the following message: Please use uic3 -convert to convert to Qt4 Unfortunately, I don't s...
How to open a Pyqt 3.3 ui file with QtDesigner 4?
I've a PyQt 4 installed (I can't find PyQt 3 for Windows) and I would like to open a QtDesigner ui file which has been created with QtDesigner 3.3. When I open this file I've the following message: Please use uic3 -convert to convert to Qt4 Unfortunately, I don't see the uic3 tool in the bin folder of my install. Does ...
[ "Qt3 and Qt4 aren't fully compatible so you may need to make some manual tweaks after uic3 converts.\nThat said, the uic3 tool was installed on my system when I installed the Qt SDK, in C:\\Qt\\2010.01\\qt\\bin\nQt SDK: http://qt.nokia.com/downloads\n", "Try finding pyuic3 or rather pyuic4. Since you are using Py...
[ 2, 1 ]
[]
[]
[ "pyqt", "python", "qt", "qt_designer" ]
stackoverflow_0002294956_pyqt_python_qt_qt_designer.txt
Q: Generating recurring dates using python? How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express). A: im...
Generating recurring dates using python?
How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).
[ "import dateutil.rrule as dr\nimport dateutil.parser as dp\nimport dateutil.relativedelta as drel\n\nstart=dp.parse(\"19/02/2010\") # Third Friday in Feb 2010\n\nThis generates the third Friday of every month\nrr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)\n\nThis prints every third Friday...
[ 30, 0, 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0002295765_date_python.txt
Q: Change tab-label on gtk.noteBook I have a gtk.Notebook with some tabs on it. How can i change label on current tab when button clicked? I make: self.set_tab_label(self.scrolled_window,label) But label change on last tab, but not in current :( Thank you. A: I found the solution: self.set_tab_label_text(self.get_...
Change tab-label on gtk.noteBook
I have a gtk.Notebook with some tabs on it. How can i change label on current tab when button clicked? I make: self.set_tab_label(self.scrolled_window,label) But label change on last tab, but not in current :( Thank you.
[ "I found the solution:\nself.set_tab_label_text(self.get_nth_page(self.get_current_page()),\"LABEL_TEXT\")\n\n" ]
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002296722_gtk_pygtk_python.txt
Q: Python Regex Help (httplib2 cookies) Having the same problem as the poster of this question: httplib2, how to set more than one cookie? The cookie looks like this.. PHPSESSID=8527b5532b6018aec4159d81f69765bd; path=/; expires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578; expires=Mon, 22-Feb-2010 13:37:51 GMT, password=1...
Python Regex Help (httplib2 cookies)
Having the same problem as the poster of this question: httplib2, how to set more than one cookie? The cookie looks like this.. PHPSESSID=8527b5532b6018aec4159d81f69765bd; path=/; expires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578; expires=Mon, 22-Feb-2010 13:37:51 GMT, password=123456; expires=Mon, 22-Feb-2010 13:37:51 G...
[ "Have you tried cookielib / http.cookiejar?\n\nIf you interpret the cookie as this\nPHPSESSID=8527b5532b6018aec4159d81f69765bd;\npath=/;\nexpires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578;\nexpires=Mon, 22-Feb-2010 13:37:51 GMT, password=123456; \nexpires=Mon, 22-Feb-2010 13:37:51 GMT, sid=8527b5532b6018aec4159d81f697...
[ 1, 1 ]
[]
[]
[ "cookies", "httplib2", "python", "regex" ]
stackoverflow_0002296654_cookies_httplib2_python_regex.txt
Q: How to see possible combinations of a given number in python in Python I wanting see all the possible combination's of a number, but limiting to 0's and 1's... So for example the result of some loop would be: 0000 0001 0011 0111 1111 1000 and so on. What python algorithm would best suite this? A: Example is in ...
How to see possible combinations of a given number in python
in Python I wanting see all the possible combination's of a number, but limiting to 0's and 1's... So for example the result of some loop would be: 0000 0001 0011 0111 1111 1000 and so on. What python algorithm would best suite this?
[ "Example is in the itertools docs:\n>>> import itertools\n>>> for i in itertools.product(range(2), repeat=4):\n print(i)\n\n", "def f(n):\n if n==1:\n return ['0', '1']\n tmp = f(n-1)\n return ['0'+v for v in tmp] + ['1'+v for v in tmp]\n\n>>> f(4)\n['0000',\n'0001',\n'0010',\n'0011',\n'0100',\n'01...
[ 7, 1, 1, 0, 0 ]
[]
[]
[ "algorithm", "binary", "python" ]
stackoverflow_0002296505_algorithm_binary_python.txt
Q: Replace a whole line in a file I have a .txt file containing data like this: 0,Rent1,Expense,16/02/2010,1,4000,4000 0,Car Loan1,Expense,16/02/2010,2,4500,9000 0,Flat Loan1,Expense,16/02/2010,2,4000,8000 0,Rent2,Expense,16/02/2010,1,4000,4000 0,Car Loan2,Expense,16/02/2010,2,4500,9000 0,Flat Loan2,Expense...
Replace a whole line in a file
I have a .txt file containing data like this: 0,Rent1,Expense,16/02/2010,1,4000,4000 0,Car Loan1,Expense,16/02/2010,2,4500,9000 0,Flat Loan1,Expense,16/02/2010,2,4000,8000 0,Rent2,Expense,16/02/2010,1,4000,4000 0,Car Loan2,Expense,16/02/2010,2,4500,9000 0,Flat Loan2,Expense,16/02/2010,2,4000,8000 Now i want...
[ "Put a new line \nnewline='0,Loan,Expense,19/02/2010,2,5000,10000'\nlnum=1\nfor line in fileinput.FileInput(\"sample.txt\",inplace=1):\n if lnum==4:\n result = newline+\"\\n\"\n else:\n result=line\n lnum=lnum+1 \n sys.stdout.write(result)\n\nOr you can just declare newline variable as ...
[ 2, 1, 0, 0 ]
[]
[]
[ "file", "python", "replace" ]
stackoverflow_0002294848_file_python_replace.txt
Q: how to encode/decode escape sequence characters in python how to encode/decode escape sequence character '\x13' in python into a character that is valid in a RSS or XML. use case is, I am getting data from arbitrary sources and making a RSS feed for that data. The data source sometimes have escape sequence chara...
how to encode/decode escape sequence characters in python
how to encode/decode escape sequence character '\x13' in python into a character that is valid in a RSS or XML. use case is, I am getting data from arbitrary sources and making a RSS feed for that data. The data source sometimes have escape sequence character which is breaking my RSS feed. So how can I sanitize the i...
[ "\\x13 (ASCII 19, ‘DC3’) can't be escaped; it is invalid in XML 1.0, period. You can include one, encoded as &#19; or &#x13; in XML 1.1, but then you have to include the <?xml version=\"1.1\"?> declaration and many tools won't like it.\nI've no idea why that character would be included in your data, but the way for...
[ 2 ]
[]
[]
[ "character_encoding", "encoding", "python" ]
stackoverflow_0002296525_character_encoding_encoding_python.txt
Q: tkinter: Specifying arguments for a function that's called when you press a button button1 = tkinter.Button(frame, text="Say hi", command=print) button2 = tkinter.Button(frame, text="foo", command=print) button3 = tkinter.Button(frame, text="bar", command=print) You've probably spotted the hole in my program: pri...
tkinter: Specifying arguments for a function that's called when you press a button
button1 = tkinter.Button(frame, text="Say hi", command=print) button2 = tkinter.Button(frame, text="foo", command=print) button3 = tkinter.Button(frame, text="bar", command=print) You've probably spotted the hole in my program: print can't specify arguments. This renders the whole thing useless and faulty. Obviously, ...
[ "If you have at least python 2.6 (which I'm guessing you are since you use print in a function position) you can use functools.partial. It takes a function and any arguments to supply and returns a callable that will call the underlying function and add on any arguments passed to the final call. For example:\n>>> f...
[ 7, 2 ]
[]
[]
[ "arguments", "python", "tkinter" ]
stackoverflow_0002297336_arguments_python_tkinter.txt
Q: How to switch to a python subprocess created by IPython (on OS X)? When I use IPython along with the -wthread option, it spawns a python subprocess, which appears as a Mac OS X application. My problem is that when I send commands to that application (for example plotting with matplotlib), the window is updated beh...
How to switch to a python subprocess created by IPython (on OS X)?
When I use IPython along with the -wthread option, it spawns a python subprocess, which appears as a Mac OS X application. My problem is that when I send commands to that application (for example plotting with matplotlib), the window is updated behind all my other windows. I would like to be able to call a python comma...
[ "Could be either:\n\nMaking a new python script that tracks grandchild processes of another script might be tricky. The IPython documentation has an example to monitor spawned processes by pid; JobControl. JobControl only kills the processes but I imagine adding a command to change window focus would be fairly easy...
[ 1, 1 ]
[]
[]
[ "ipython", "macos", "python", "wxpython" ]
stackoverflow_0002260614_ipython_macos_python_wxpython.txt
Q: Assignment into Python 3.x Buffers with itemsize > 1 I am trying to expose a buffer of image pixel information (32 bit RGBA) through the Python 3.x buffer interface. After quite a bit of playing around, I was able to get this working like so: int Image_get_buffer(PyObject* self, Py_buffer* view, int flags) { i...
Assignment into Python 3.x Buffers with itemsize > 1
I am trying to expose a buffer of image pixel information (32 bit RGBA) through the Python 3.x buffer interface. After quite a bit of playing around, I was able to get this working like so: int Image_get_buffer(PyObject* self, Py_buffer* view, int flags) { int img_len; void* img_bytes; // Do my image fetch...
[ "I found this in the python code (in memoryobject.c in Objects) in the function memory_ass_sub:\n/* XXX should we allow assignment of different item sizes\n as long as the byte length is the same?\n (e.g. assign 2 shorts to a 4-byte slice) */\nif (srcview.itemsize != view->itemsize) {\n PyErr_Format(PyExc_Ty...
[ 1 ]
[]
[]
[ "pep3118", "pybuffer", "python", "python_3.x", "python_c_api" ]
stackoverflow_0002297026_pep3118_pybuffer_python_python_3.x_python_c_api.txt
Q: Searching a website import urllib import re import os search = (raw_input('[!]Search: ')) site = "http://www.exploit-db.com/list.php?description="+search+"&author=&platform=&type=&port=&osvdb=&cve=" print site source = urllib.urlopen(site).read() founds = re.findall("href='/exploits/\d+",source) print "\n[+]Sea...
Searching a website
import urllib import re import os search = (raw_input('[!]Search: ')) site = "http://www.exploit-db.com/list.php?description="+search+"&author=&platform=&type=&port=&osvdb=&cve=" print site source = urllib.urlopen(site).read() founds = re.findall("href='/exploits/\d+",source) print "\n[+]Search",len(founds),"Results...
[ "Easy to check by just visiting the site and looking at the URLs as you manually page: just put right after the ? in the URL page=1& to look at the second page of results, or page=2& to look at the third page, and so forth.\nHow is this a Python question? It's a (very elementary!) \"screen scraping\" question.\n",...
[ 0, 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0002297787_python_urllib.txt
Q: Production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django? Seems that Python lacks e-commerce solutions compared to PHP and C#. Any production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django? EDIT: http://github.com/johnboxall/django-paypal http://www.djangosnippets.org/snippets/9...
Production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django?
Seems that Python lacks e-commerce solutions compared to PHP and C#. Any production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django? EDIT: http://github.com/johnboxall/django-paypal http://www.djangosnippets.org/snippets/969/ E-commerce: http://www.satchmoproject.com/ http://code.activestate.com/recipe...
[ "You might look into Satchmo's source code. Satchmo is an open source e-commerce app for Django, and I'm pretty sure that it has support for a variety of payment gateways.\nTheir payment modules appear to work with at least PayPal and Authorize.Net from the list you gave, among others.\n" ]
[ 4 ]
[]
[]
[ "django", "e_commerce", "frameworks", "python" ]
stackoverflow_0002296542_django_e_commerce_frameworks_python.txt
Q: python basic while loop I have another newbie Python question. I have the following piece of code that I have a feeling is not written as pythonic as it should be: rowindex = 0 while params.getfirst('myfield'+rowindex): myid = params.getfirst('myfield'+rowindex) # do stuff with myid ...
python basic while loop
I have another newbie Python question. I have the following piece of code that I have a feeling is not written as pythonic as it should be: rowindex = 0 while params.getfirst('myfield'+rowindex): myid = params.getfirst('myfield'+rowindex) # do stuff with myid rowindex+=1 The input to t...
[ "The \"unbounded\" nature of a simple counter has some appeal. However, it's also an opportunity for someone to attempt a Denial of Service attack by spoofing a form with billions of fields. Simply counting through the fields could stall your web server as you attempt to process those billions of fields. \nSince...
[ 5, 2, 1 ]
[ "Try Doing this\nWhile 1:\n\n codehere\n\n" ]
[ -1 ]
[ "python", "while_loop" ]
stackoverflow_0002296803_python_while_loop.txt
Q: Looking for example GUI applications written in Python for the iPhone I have a little script I wrote in python and it actually works on the iPhone via the terminal. I am looking for code snippets or documentation for the GUI writing for the iPhone - Actually what I need is to implement an input and some output. ...
Looking for example GUI applications written in Python for the iPhone
I have a little script I wrote in python and it actually works on the iPhone via the terminal. I am looking for code snippets or documentation for the GUI writing for the iPhone - Actually what I need is to implement an input and some output. nothing fancy - for now. I have found this page: http://www.saurik.com/id/5...
[ "You cannot write an iPhone app in Python that will run on non-jailbroken phones. Apple's SDK license prohibits interpreted code on the iPhone, which definitely excludes Python. Although you can write OS X apps in Python using PyObjC, you still need to understand the Objective-C language both for documentation and ...
[ 1, 0 ]
[]
[]
[ "iphone", "objective_c", "python", "user_interface" ]
stackoverflow_0002296068_iphone_objective_c_python_user_interface.txt
Q: How to set pythonpath (python2.6) for tkinter on Ubuntu 9.04 (to use nltk)? I'd like to use the nltk toolkit on my machine which runs Ubuntu 9.04. I installed python 2.6.4 and several additional packages (numpy, scipy, matplotlib and of course nltk). I can import nltk, but calling a few methods gives various error...
How to set pythonpath (python2.6) for tkinter on Ubuntu 9.04 (to use nltk)?
I'd like to use the nltk toolkit on my machine which runs Ubuntu 9.04. I installed python 2.6.4 and several additional packages (numpy, scipy, matplotlib and of course nltk). I can import nltk, but calling a few methods gives various error masseges, all contain "please install Tkinter library". Googling around I discov...
[ "Sounds like you forgot to install the appropriate TkInter when you installed Python 2.6.4. Install it from the same source.\n", "Tkinter is usually included with the python standard libraries but Ubuntu left it out of the regular python package. You just need to install the python-tk package.\nsudo apt-get inst...
[ 3, 1 ]
[]
[]
[ "nltk", "python", "pythonpath", "tkinter" ]
stackoverflow_0002290375_nltk_python_pythonpath_tkinter.txt
Q: Updating a de-normalized attribute automatically with an AttributeExtension I am having some troubles with the AttributeExtension of SQLAlchemy. Actually I am storing a de-normalized sum attribute in the Partent table, because I need it quite often for sorting purposes. However, I would like the attribute to get u...
Updating a de-normalized attribute automatically with an AttributeExtension
I am having some troubles with the AttributeExtension of SQLAlchemy. Actually I am storing a de-normalized sum attribute in the Partent table, because I need it quite often for sorting purposes. However, I would like the attribute to get updated whenever the value of one of it's children is changed. Unfortunately, the ...
[ "As far as I can see, you are looking for events on child, but change child.value. Something like this should do the trick:\nclass ValueAttributeExtension(AttributeExtension):\n ...\n\nclass Child(Base):\n ...\n value = ColumnProperty(Column(Integer, nullable=False, default=0), \n extensi...
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002296502_python_sqlalchemy.txt
Q: Django(postgresql) + lighttpd. Any issues with threading and python's postgresql driver? I'd like to deploy my Django app (which uses postgresql as database) on lighttpd using FastCGI. For postgresql i see that Django has 2 backends available 'postgresql_psycopg2' and 'postgresql'. My question is that lighttpd bei...
Django(postgresql) + lighttpd. Any issues with threading and python's postgresql driver?
I'd like to deploy my Django app (which uses postgresql as database) on lighttpd using FastCGI. For postgresql i see that Django has 2 backends available 'postgresql_psycopg2' and 'postgresql'. My question is that lighttpd being a threaded server are there any issues with any of this backends? Are they thread safe? And...
[ "http://initd.org/psycopg/docs/usage.html#thread-safety\n" ]
[ 2 ]
[]
[]
[ "django", "lighttpd", "postgresql", "python", "thread_safety" ]
stackoverflow_0002297030_django_lighttpd_postgresql_python_thread_safety.txt
Q: how to have global variables among different modules in Python I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck. thanks in advance! A: You can access global v...
how to have global variables among different modules in Python
I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck. thanks in advance!
[ "You can access global variables from other modules by importing them explicitly.\nIn module foo:\n joe = 5\n\nIn module bar:\n from foo import joe\n print joe\n\nNote that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.\n", "Python does not support g...
[ 5, 3, 0 ]
[]
[]
[ "global_variables", "python", "scope" ]
stackoverflow_0002296550_global_variables_python_scope.txt
Q: Local App Engine datastore is slow once loaded up, any suggestions? I've loaded up a local datastore with 40,000+ entries. Unfortunately, recalling any data from it at all is very slow on my fairly new Macbook Pro. Any suggestions on speeding things up, short of buying a new piece of hardware? A: This ques...
Local App Engine datastore is slow once loaded up, any suggestions?
I've loaded up a local datastore with 40,000+ entries. Unfortunately, recalling any data from it at all is very slow on my fairly new Macbook Pro. Any suggestions on speeding things up, short of buying a new piece of hardware?
[ "This question addresses a few alternatives you could try.\nFor speeding up unit testing, you can set the datastore to stay in memory only, and not flush to disk. This may not help you if you need 40,000 entities to meaningfully test your system of course :)\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002298280_google_app_engine_google_cloud_datastore_python.txt
Q: PyQt4,How to add a batch of widget (QPushButton) at one time and lets them to execute on SLOT if i want to add 10 QPushButton at one time: NumCount=20 for i in range(NumCount): btn=QPushButton("%s %s" %("Button" i+1),self) btn.clicked.connect(self.btnclick) def btnclick(self): # here is my question # how...
PyQt4,How to add a batch of widget (QPushButton) at one time and lets them to execute on SLOT
if i want to add 10 QPushButton at one time: NumCount=20 for i in range(NumCount): btn=QPushButton("%s %s" %("Button" i+1),self) btn.clicked.connect(self.btnclick) def btnclick(self): # here is my question # how to define which button clicked? # how to print btn.text? as stated in the def(btnclick).
[ "When you are in a slot, you can use sender() method (just call self.sender()) and you will receive a reference to the object, from which signal was emitted. Here is documentation about it.\n", "I'd subclass QPushButton and define my own sender and slot. The QObject.sender() method is tempting, but it gives me t...
[ 3, 2, 1, 0 ]
[]
[]
[ "pyqt", "python", "sender", "signals" ]
stackoverflow_0002108049_pyqt_python_sender_signals.txt
Q: Garbage collection of object after exception I have observed that after an exception I have an object for which constructor is not called, which causes a lock to be held. What is the best way to improve the situation? Would calling del in an except block be the solution? b=BigHash(DB_DIR, url) meta = bdecode(b.get...
Garbage collection of object after exception
I have observed that after an exception I have an object for which constructor is not called, which causes a lock to be held. What is the best way to improve the situation? Would calling del in an except block be the solution? b=BigHash(DB_DIR, url) meta = bdecode(b.get()) return meta b holds a lock which is released ...
[ "No matter what, you want the lock to be released - whether or not an exception is thrown. In that case, it's probably best to release the lock/delete b in a finally: clause:\nb=BigHash(DB_DIR, url)\ntry:\n meta = bdecode(b.get())\nfinally:\n del b # or whatever you need to do to release the lock\nreturn meta...
[ 3, 1, 0 ]
[]
[]
[ "destructor", "exception_handling", "python" ]
stackoverflow_0002295978_destructor_exception_handling_python.txt
Q: disabling "joining" when process shuts down Is there a way to stop the multiprocessing Python module from trying to call & wait on join() on child processes of a parent process shutting down? 2010-02-18 10:58:34,750 INFO calling join() for process procRx1 I want the process to which I sent a SIGTERM to exit as qui...
disabling "joining" when process shuts down
Is there a way to stop the multiprocessing Python module from trying to call & wait on join() on child processes of a parent process shutting down? 2010-02-18 10:58:34,750 INFO calling join() for process procRx1 I want the process to which I sent a SIGTERM to exit as quickly as possible (i.e. "fail fast") instead of wa...
[ "Have you tried to explicitly using Process.terminate?\n", "You could try joining in a loop with a timeout (1 sec?) and checking if the thread is still alive, something like:\nwhile True:\n a_thread.join(1)\n if not a_thread.isAlive(): break\n\nTerminating the a_thread will trigger break clause.\n", "Sounds l...
[ 0, 0, 0 ]
[]
[]
[ "fail_fast", "multiprocessing", "python" ]
stackoverflow_0002290043_fail_fast_multiprocessing_python.txt
Q: PyQt4: Hide widget and resize window I'm working with several widgets but the solution just won't come out. What I have is a series of buttons in series of QHBoxLayouts. Some buttons are hidden by default, but they will appear when needed. To solve space issues, all buttons have a minimum and maximum size so they ...
PyQt4: Hide widget and resize window
I'm working with several widgets but the solution just won't come out. What I have is a series of buttons in series of QHBoxLayouts. Some buttons are hidden by default, but they will appear when needed. To solve space issues, all buttons have a minimum and maximum size so they always look well packed. Also I have a QTe...
[ "The answer was quite lame... Just needed to change the QVBoxLayout for a QGridLayout and use self.ui.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)\n" ]
[ 4 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0002293708_pyqt4_python_qt4.txt
Q: Most optimal way to programmatically check if site is running locally or on a server with Django? Currently I have this in my settings.py file: DEBUG = True LOCAL = True TEMPLATE_DEBUG = DEBUG SITE_TITLE = 'Stack Overflow Question' REMOTE_SITE_URL = "http://************:8080" LOCAL_SITE_URL = "http://********...
Most optimal way to programmatically check if site is running locally or on a server with Django?
Currently I have this in my settings.py file: DEBUG = True LOCAL = True TEMPLATE_DEBUG = DEBUG SITE_TITLE = 'Stack Overflow Question' REMOTE_SITE_URL = "http://************:8080" LOCAL_SITE_URL = "http://************:8000" ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS if LOCAL: ...
[ "Checking if a file exists will not occur every time a render occurs. It will actually only occur whenever you interpreter process is started, which all depends on your deployment configuration. This will depend on a variety on your webserver setup, but if you are using apache, chiefly MaxRequestPerChild and Star...
[ 5 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0002298657_database_django_python.txt
Q: pycurl install :( already have min. libcurl version I'm running python 2.6 on an Intel Mac OS X 10.5 I'm trying to install pycurl 7.16.2.1 (as recommended here http://curl.haxx.se/mail/curlpython-2009-03/0009.html), but for some reason, the installation sees my libcurl 7.16.3, yet it still insist I install 7.16.2 ...
pycurl install :( already have min. libcurl version
I'm running python 2.6 on an Intel Mac OS X 10.5 I'm trying to install pycurl 7.16.2.1 (as recommended here http://curl.haxx.se/mail/curlpython-2009-03/0009.html), but for some reason, the installation sees my libcurl 7.16.3, yet it still insist I install 7.16.2 or greater (doesn't 7.16.3 satisfy that?) Here's the erro...
[ "If you are using the python.org Python 2.6, it is built using the 10.4 SDK so as to be able to run on multiple versions of OS X. In that case, the pycurl build is likely trying to link against the 10.4 version of libcurl, which appears to be 7.13.1. The thread you link to is talking about using the 10.5 Apple-su...
[ 7, 0 ]
[]
[]
[ "libcurl", "macos", "pycurl", "python" ]
stackoverflow_0002279014_libcurl_macos_pycurl_python.txt
Q: Is nested dictionary in design ok? My data is structured in a way that I ended up creating a nested dictionary in my design like: my_dict = {"a": {"b": {"c":"I am c"}}} my_dict["a"]["b"]["c"] Is it usual! or we have some other better alternatives (using objects!)? A: You could use a tuple to store your value...
Is nested dictionary in design ok?
My data is structured in a way that I ended up creating a nested dictionary in my design like: my_dict = {"a": {"b": {"c":"I am c"}}} my_dict["a"]["b"]["c"] Is it usual! or we have some other better alternatives (using objects!)?
[ "You could use a tuple to store your values in a flat dictionary:\nd = {}\nd[a, b, c] = e\n\nIt all depends on what you are doing, but remember that The Zen of Python says that flat is better than nested :)\n", "There is nothing inherently wrong with nested dicts. Anything can be a dict value, and it can make sen...
[ 8, 7, 1, 0, 0 ]
[]
[]
[ "data_structures", "dictionary", "python" ]
stackoverflow_0002298723_data_structures_dictionary_python.txt
Q: How to upload all .html files to a remote server using FTP and preserving file structure? I have edited about 100 html files locally, and now I want to push them to my live server, which I can only access via ftp. The HTML files are in many different directories, but hte directory structure on the remote machine i...
How to upload all .html files to a remote server using FTP and preserving file structure?
I have edited about 100 html files locally, and now I want to push them to my live server, which I can only access via ftp. The HTML files are in many different directories, but hte directory structure on the remote machine is the same as on the local machine. How can I recursively descend from my top-level directory f...
[ "If you want to do it in Python (rather than using other pre-packaged existing tools), you can use os.walk to read everything in the local subtree, and ftplib to perform all the FTP operations. In particular, storbinary is the method you'll usually use to transfer entire files without line-end conversions (storlin...
[ 1, 0, 0, 0 ]
[]
[]
[ "ftp", "networking", "python", "scripting" ]
stackoverflow_0002263782_ftp_networking_python_scripting.txt
Q: Django: When using register.inclusion_tag() where/what order is the template searched for? When using the register.inclusion_tag() shortcut on a Custom Template Tag, assuming you define the template as 'some_fragment.html', in what directories/order does Django try to find that template? Assume as many 'defaults'...
Django: When using register.inclusion_tag() where/what order is the template searched for?
When using the register.inclusion_tag() shortcut on a Custom Template Tag, assuming you define the template as 'some_fragment.html', in what directories/order does Django try to find that template? Assume as many 'defaults' as is reasonable. The Custom Template Tag portion of the documentation doesn't list anything s...
[ "It follows exactly the same rules as for any other template. That is, it will use the directories specified in your TEMPLATE_DIRS setting in order - then, depending on the contents of your TEMPLATE_LOADERS setting, will also look in templates subdirectories under each of your apps. It won't ever look in the templa...
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002299779_django_django_templates_python.txt
Q: Building a wiki application? I'm building this app in Python with Django. I would like to give parts of the site wiki like functionality, but I don't know how to go on about reliability and security. Make sure that good content is not ruined Check for quality Prevent spam from invading the site The items requiri...
Building a wiki application?
I'm building this app in Python with Django. I would like to give parts of the site wiki like functionality, but I don't know how to go on about reliability and security. Make sure that good content is not ruined Check for quality Prevent spam from invading the site The items requiring wiki like functionality are jus...
[ "You could try using Django Wikiapp, which gives you most of the features you want in a wiki, including history and the ability to revert to older versions of an article. I have personally used this app and it's pretty self-explanatory; they also have a bit of documentation at http://code.google.com/p/django-wikiap...
[ 2, 1, 1 ]
[]
[]
[ "django", "django_models", "python", "wiki" ]
stackoverflow_0002299697_django_django_models_python_wiki.txt
Q: why python associative map member variable is shared between objects For class A, why is aMap member variable being shared between object and object b? >>> class A: ... aMap = {} >>> a = A() >>> a.aMap["hello"] = 1 >>> b = A() >>> b.aMap["world"] = 2 >>> c = [] >>> c.append(a) >>> c.append(b) >>> for i in ...
why python associative map member variable is shared between objects
For class A, why is aMap member variable being shared between object and object b? >>> class A: ... aMap = {} >>> a = A() >>> a.aMap["hello"] = 1 >>> b = A() >>> b.aMap["world"] = 2 >>> c = [] >>> c.append(a) >>> c.append(b) >>> for i in c: ... for j in i.aMap.items(): ... print j ('world', 2) ('h...
[ "Because you defined it as a class attribute, not instance attribute.\nIf you wish to have it as instance attribute and not be shared between instances, you have to define it like this:\nclass A(object):\n def __init__(self):\n self.aMap = {}\n\n", "Because its a class attribute, not an instance attribu...
[ 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002299801_python.txt
Q: Problem with asyn icmp ping I'm writing service in python that async ping domains. So it must be able to ping many ip's at the same time. I wrote it on epoll ioloop, but have problem with packets loss. When there are many simultaneous ICMP requests much part of replies on them didn't reach my servise. What may cau...
Problem with asyn icmp ping
I'm writing service in python that async ping domains. So it must be able to ping many ip's at the same time. I wrote it on epoll ioloop, but have problem with packets loss. When there are many simultaneous ICMP requests much part of replies on them didn't reach my servise. What may cause this situation and how i can m...
[ "A problem you might be having is due to the fact that ICMP is layer 3 of the OSI model and does not use a port for communication. In short, ICMP isn't really designed for this. The desired behavior is still possible but perhaps the IP Stack you are using is getting in the way and if this is on a Windows system th...
[ 0 ]
[]
[]
[ "icmp", "ping", "python" ]
stackoverflow_0002299751_icmp_ping_python.txt
Q: gdb python scripting: where has `parse_and_eval` gone? I had some scripts in Python to help me debugging with GDB that used the function gdb.parse_and_eval (still documented) to get the inferior values from the arguments passed to a scripted command, and now the module doesn't seem to have any trace of that functi...
gdb python scripting: where has `parse_and_eval` gone?
I had some scripts in Python to help me debugging with GDB that used the function gdb.parse_and_eval (still documented) to get the inferior values from the arguments passed to a scripted command, and now the module doesn't seem to have any trace of that function. Doing python import gdb; print dir(gdb) from GDB clearly...
[ "I don't know where it went or why, but Qt implemented this workaround in their code, which may be practically useful to you:\ndef parseAndEvaluate(exp):\n if gdb.VERSION.startswith(\"6.8.50.2009\"):\n return gdb.parse_and_eval(exp)\n # Work around non-existing gdb.parse_and_eval as in rele...
[ 4, 4 ]
[]
[]
[ "gdb", "python" ]
stackoverflow_0002290842_gdb_python.txt
Q: Combining words in Python (permutations?) Suppose I have 4 words, as a string. How do I join them all like this? s = orange apple grapes pear The result would be a String: "orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear" I am thinking: list_...
Combining words in Python (permutations?)
Suppose I have 4 words, as a string. How do I join them all like this? s = orange apple grapes pear The result would be a String: "orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear" I am thinking: list_words = s.split(' ') for l in list_words: And ...
[ "Maybe this is what you want?\ns = \"orange apple grapes pear\"\n\nfrom itertools import product\nl = s.split()\nr='/'.join(''.join(k*v for k,v in zip(l, x))\n for x in product(range(2), repeat=len(l))\n if sum(x) > 1)\nprint r\n\nIf run on 'a b c' (for clarity) the result is:\nbc/ac/ab/abc\n\n(...
[ 4, 4, 1, 1, 1 ]
[]
[]
[ "permutation", "python", "string" ]
stackoverflow_0002299671_permutation_python_string.txt
Q: Python Thread/Queue issue I'm creating a threaded python script that has a collection of files that is put into a queue and then an unknown amount of threads (default is 3) to start downloading. When each of the threads complete it updates the stdout with the queue status and a percentage. All the files are bein...
Python Thread/Queue issue
I'm creating a threaded python script that has a collection of files that is put into a queue and then an unknown amount of threads (default is 3) to start downloading. When each of the threads complete it updates the stdout with the queue status and a percentage. All the files are being downloaded but the status inf...
[ "You can't check the queue size in one statement, and then .get() from the queue in the next. In the meantime the whole world may have changed. The .get() method call is the single atomic operation you need to call. If it raises Empty or blocks, the queue is empty.\nYour threads can overwrite each other's output....
[ 4, 2 ]
[]
[]
[ "multithreading", "python", "queue" ]
stackoverflow_0002299478_multithreading_python_queue.txt
Q: Opinions on Unladen Swallow? What are your opinions and expectations on Google's Unladen Swallow? From their project plan: We want to make Python faster, but we also want to make it easy for large, well-established applications to switch to Unladen Swallow. Produce a version of Python at least 5x faster th...
Opinions on Unladen Swallow?
What are your opinions and expectations on Google's Unladen Swallow? From their project plan: We want to make Python faster, but we also want to make it easy for large, well-established applications to switch to Unladen Swallow. Produce a version of Python at least 5x faster than CPython. Python application per...
[ "I have high hopes for it.\n\nThis is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.\nOff the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.\nMo...
[ 17, 12, 4, 4, 1, 0, 0 ]
[]
[]
[ "llvm", "python", "unladen_swallow" ]
stackoverflow_0000714242_llvm_python_unladen_swallow.txt
Q: How to I extract floats from a file in Python? So, I have a file that looks like this: # 3e98.mtz MR_AUTO with model 200la_.pdb SPACegroup HALL P 2yb #P 1 21 1 SOLU SET RFZ=3.0 TFZ=4.7 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 321.997 124.066 234.744 FRAC -0.14681 0.50245 -0.05722 SOLU SET RFZ=3.3 TFZ=4.2 PAK=0 LLG...
How to I extract floats from a file in Python?
So, I have a file that looks like this: # 3e98.mtz MR_AUTO with model 200la_.pdb SPACegroup HALL P 2yb #P 1 21 1 SOLU SET RFZ=3.0 TFZ=4.7 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 321.997 124.066 234.744 FRAC -0.14681 0.50245 -0.05722 SOLU SET RFZ=3.3 TFZ=4.2 PAK=0 LLG=30 SOLU 6DIM ENSE 200la_ EULER 329.492 34.325 209.7...
[ "Here's one way.\ndef floats( aList ):\n for v in aList:\n try:\n yield float(v)\n except ValueError:\n pass\n\na = list( floats( [....] ) )\n\n", "floats = []\nall = ['#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb', '#P', '1', '21...
[ 11, 7, 3, 0 ]
[]
[]
[ "floating_point", "list", "loops", "python" ]
stackoverflow_0002299609_floating_point_list_loops_python.txt
Q: retrieving the keys of all variables on an object If I had: class A(object): varA = 1 inst = A() Then how would I retrieve the keys of all variables on inst? I'd want something like ["varA"] So far, I've gotten this: vars(inst.__class__).keys() #returns ['__dict__', '__weakref__', '__module__', 'varA', '__do...
retrieving the keys of all variables on an object
If I had: class A(object): varA = 1 inst = A() Then how would I retrieve the keys of all variables on inst? I'd want something like ["varA"] So far, I've gotten this: vars(inst.__class__).keys() #returns ['__dict__', '__weakref__', '__module__', 'varA', '__doc__'] I'm fine with that, I'd just ignore the double-u...
[ "There is a python module, called inspect for runtime introspection. Maybe inspect.getmembers can help you ...\n" ]
[ 1 ]
[]
[]
[ "class", "multiple_inheritance", "python" ]
stackoverflow_0002300383_class_multiple_inheritance_python.txt
Q: Installing Mercurial 1.4.3 - Python Requirement? Is it ok if I install Python 2.6.4 instead of the 2.4 requirement listed on the Mercurial website? I'm fairly new to Mercurial and Python. My general impression of Python is that newer versions break compatibility with older versions. If Python is currently at 2.6.4...
Installing Mercurial 1.4.3 - Python Requirement?
Is it ok if I install Python 2.6.4 instead of the 2.4 requirement listed on the Mercurial website? I'm fairly new to Mercurial and Python. My general impression of Python is that newer versions break compatibility with older versions. If Python is currently at 2.6.4 and Mercurial 1.4.3 lists Python 2.4 as a requirement...
[ "2.4 is a minimum requirement. 2.6.4 is fine.\n" ]
[ 4 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0002300636_mercurial_python.txt
Q: If you are really good at Python and Regex, please help fix function def boldword(text, needle): return mark_safe(re.compile(r"\b(%s)\b" % "|".join(map(re.escape, needle.split(' '))), re.I).sub(r'<strong>\1</strong>', text)) This is currently my function to bold a string text given a needle. (Like Google...th...
If you are really good at Python and Regex, please help fix function
def boldword(text, needle): return mark_safe(re.compile(r"\b(%s)\b" % "|".join(map(re.escape, needle.split(' '))), re.I).sub(r'<strong>\1</strong>', text)) This is currently my function to bold a string text given a needle. (Like Google...they bold the text for you when you do a search). When the needle is "the s...
[ "Your biggest problem seems to be the word boundaries. If the tokens you're searching for can begin or end with non-word characters (e.g., (video)), enclosing the regex in \\b prevents matching. They also prevent matching of two or more contiguous tokens (e.g., theshow in www.theshow.com). However, instead of lo...
[ 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002300563_python_regex.txt
Q: Problem in calculating checksum : casting int to signed int32 I need to convert the following c code (to calculate checksum for a file) to python. I had written, the corresponding code in python but the result didn't match the c version. The problem was that python autmatically promotes int to long whenever overfl...
Problem in calculating checksum : casting int to signed int32
I need to convert the following c code (to calculate checksum for a file) to python. I had written, the corresponding code in python but the result didn't match the c version. The problem was that python autmatically promotes int to long whenever overflow occurs and this results in wrong checksums. Any idea how to over...
[ "Use numpy.int32 or numpy.uint32 if you need to restrict the range. Or mod it by 1 << 32 after operations that could \"overflow\".\n" ]
[ 2 ]
[]
[]
[ "casting", "checksum", "python" ]
stackoverflow_0002300740_casting_checksum_python.txt
Q: Basic Django - Custom Managers I'm going through the Django book and I'm currently on chapter 10. I'm having a problem understanding the third line in this fragment of code: class DahlBookManager(models.Manager): def get_query_set(self): return super(DahlBookManager, self).get_query_set().filter(author...
Basic Django - Custom Managers
I'm going through the Django book and I'm currently on chapter 10. I'm having a problem understanding the third line in this fragment of code: class DahlBookManager(models.Manager): def get_query_set(self): return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl') I understand that th...
[ "No, self is an instance of DahlBookManager. super() uses the class to handle things like MRO, inheritance, etc.\n", "This is about the builtin Super() function in Python.\nYou can get a reference here: http://docs.python.org/library/functions.html\n\nIf the second argument is omitted, the\n super object returne...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002300737_django_python.txt
Q: Using list.reverse() on a subset of a list. "NoneType" object is not iterable So, I'm trying to append to one list the reverse of a subset of another list. For some reason, the interpreter doesn't seem to be liking it. Here's what I'm doing. list1.extend(list2[someInt:someOtherInt].reverse()) Why is this not le...
Using list.reverse() on a subset of a list. "NoneType" object is not iterable
So, I'm trying to append to one list the reverse of a subset of another list. For some reason, the interpreter doesn't seem to be liking it. Here's what I'm doing. list1.extend(list2[someInt:someOtherInt].reverse()) Why is this not legit? It seems reasonable to me..
[ "list methods operate in-place, which means that they return None.\n", "In addition to Ignacio's answer, here's a solution. Try:\nlist1.extend(reversed(list2[someInt:someOtherInt]))\n\nAlternatively, you can use a slice with reversed indexes, but be careful with off-by-one errors!\nlist1.extend(list2[someOtherInt...
[ 5, 3 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002300872_list_python.txt
Q: Maintaining session in an Eventlet page scraper? I'm trying to do some scraping of a site that requires authentication (not http auth). The script I'm using is based on this eventlet example. Basically, urls = ["https://mysecuresite.com/data.aspx?itemid=blah1", "https://mysecuresite.com/data.aspx?itemid=blah2...
Maintaining session in an Eventlet page scraper?
I'm trying to do some scraping of a site that requires authentication (not http auth). The script I'm using is based on this eventlet example. Basically, urls = ["https://mysecuresite.com/data.aspx?itemid=blah1", "https://mysecuresite.com/data.aspx?itemid=blah2", "https://mysecuresite.com/data.aspx?itemid=bla...
[ "I'm not an expert on this by any means, but it looks like the standard way to maintain session state with urllib2 is to create a custom opener instance for each session. That looks like this:\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor())\n\nThen you use that opener to do whatever authentication yo...
[ 4, 1, 0 ]
[]
[]
[ "parallel_processing", "python", "screen_scraping" ]
stackoverflow_0002294869_parallel_processing_python_screen_scraping.txt
Q: python - syntax error Hi:) I am not able to figure out what the error in the program is could you please help me out with it. Thank you..:) The input file contains the following: 3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है। 57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्...
python - syntax error
Hi:) I am not able to figure out what the error in the program is could you please help me out with it. Thank you..:) The input file contains the following: 3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है। 57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्देश्य से असम आए। ( its bas...
[ "What is posted here does not have the error. Note that what is posted has TWO space characters between the + and the u in output += word[-1] + u'(%d) ' % counter. What is probably happening is that you have a whitespace character other than a space in there. A possibility is NBSP (U+00A0) aka \"no-break space\". ...
[ 3, 0 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0002301214_nlp_python.txt
Q: Bash alias to Python script -- is it possible? The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of ...
Bash alias to Python script -- is it possible?
The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by taki...
[ "The relevant section from the Bash manual states:\n\nAliases allow a string to be\n substituted for a word when it is used\n as the first word of a simple command.\n\nSo, there should be nothing preventing you from doing e.g.\n$ alias geturl=\"python /some/cool/script.py\"\n\nThen you could use it like any other...
[ 18, 0 ]
[]
[]
[ "bash", "curl", "multiplatform", "python", "scripting" ]
stackoverflow_0002279749_bash_curl_multiplatform_python_scripting.txt
Q: Returning a list from a function in Python I'm creating a game for my sister, and I want a function to return a list variable, so I can pass it to another variable. The relevant code is as follows: def startNewGame(): while 1: #Introduction: print print """Hello, You will now be guided ...
Returning a list from a function in Python
I'm creating a game for my sister, and I want a function to return a list variable, so I can pass it to another variable. The relevant code is as follows: def startNewGame(): while 1: #Introduction: print print """Hello, You will now be guided through the setup process. There are 7 steps to ...
[ "First all, i must say you are writing good code for a beginner, though you can improve startNewGame by writing a function, for getting user input in a loop, instead of writing same code again and again.\nI copied your code and it runs without problem, though i did a small change\nyou are doing \nMCreatePH = startG...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002300963_python.txt
Q: Factor Analysis in python is there a module that contains a function that calculate Factor Analysis (not PCA) in python? A: Here is the direct link to the MDP Factor Analysis node. The MDP homepage is here. A: Yes there is http://pypi.python.org/pypi/MDP/2.3. First result in Google on query Factor Analysis py...
Factor Analysis in python
is there a module that contains a function that calculate Factor Analysis (not PCA) in python?
[ "Here is the direct link to the MDP Factor Analysis node.\nThe MDP homepage is here. \n", "Yes there is http://pypi.python.org/pypi/MDP/2.3. First result in Google on query Factor Analysis python ;-)\n" ]
[ 5, 0 ]
[]
[]
[ "analysis", "factor_analysis", "python" ]
stackoverflow_0002301993_analysis_factor_analysis_python.txt
Q: Would you use numpy if you were just manipulating a sequence of binary values? Is there any advantage to using numpy when you're doing a large number of operations on lists of binary values? How about integers within a small range (like just the numbers 1,2, and 3?) A: Eliminating the loops is the the source of...
Would you use numpy if you were just manipulating a sequence of binary values?
Is there any advantage to using numpy when you're doing a large number of operations on lists of binary values? How about integers within a small range (like just the numbers 1,2, and 3?)
[ "Eliminating the loops is the the source of the performance gain (10x):\nimport profile\nimport numpy as NP\n\ndef np_test(a2darray) :\n row_sums = NP.sum(a2darray, axis=1)\n return NP.sum(row_sums)\n\ndef stdlib_test2(a2dlist) :\n return sum([sum(row) for row in a2dlist])\n\nA = NP.random.randint(1, 6, 1e7).res...
[ 3, 1 ]
[]
[]
[ "bit_manipulation", "numpy", "python", "scipy" ]
stackoverflow_0002301018_bit_manipulation_numpy_python_scipy.txt
Q: Appending word position numbers to Unicode text in Python I have a code which appends word positions to the words from the source file but the output is not coming as desired: The input file contains the following: 3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है। 57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लो...
Appending word position numbers to Unicode text in Python
I have a code which appends word positions to the words from the source file but the output is not coming as desired: The input file contains the following: 3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है। 57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्देश्य से असम आए। The origi...
[ "I think your code should something like:\n# the input part is fine as is\nlines = text.split('\\n')\noutlines = []\nfor line in lines:\n lout = []\n counter = 1\n for i, word in enumerate(lines.split()):\n if i == 0: # leave 1st word of line alone, it's a marker:\n lout.append(word)\n ...
[ 2, 1, 0 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0002301918_nlp_python.txt
Q: skipping unknown items while Serializing using json I'm trying to serialize obj using json (Python). I wish to skip json's unknown type I know I can add my own encoder, but what I'm interested in is to just skip the unknown type. I don't want to use None instead. I have tried icon=QIcon() arr=["blablal",...
skipping unknown items while Serializing using json
I'm trying to serialize obj using json (Python). I wish to skip json's unknown type I know I can add my own encoder, but what I'm interested in is to just skip the unknown type. I don't want to use None instead. I have tried icon=QIcon() arr=["blablal",icon] str1=simplejson.dumps(arr,skipkeys=True) I use...
[ "Ok so i found the problem \nicon isn't a key but a value \nif icon was used as a key in a dict it would have been ignored\n" ]
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0002302252_json_python.txt
Q: cannot import name formats what does it mean? i ve googled but found nothing =/ ImportError at /admin/ cannot import name formats Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Exception Type: ImportError Exception Value: cannot import name formats Exception Location: /usr/lib/python2.6/si...
cannot import name formats
what does it mean? i ve googled but found nothing =/ ImportError at /admin/ cannot import name formats Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Exception Type: ImportError Exception Value: cannot import name formats Exception Location: /usr/lib/python2.6/site-packages/django/contrib/admin...
[ "What that line is trying to do (see the sources) is\n3 from django.utils import formats\n\nIf you don't have the parent directory of the django/ directory on your sys.path, or the __init__.py files at either levels somehow went missing, that would explain your issues.\nOn a side note, the .0 in 2.6.0 is worrisom...
[ 1 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0002301703_admin_django_python.txt
Q: Python multiple threads accessing same file I have two threads, one which writes to a file, and another which periodically moves the file to a different location. The writes always calls open before writing a message, and calls close after writing the message. The mover uses shutil.move to do the move. I see that ...
Python multiple threads accessing same file
I have two threads, one which writes to a file, and another which periodically moves the file to a different location. The writes always calls open before writing a message, and calls close after writing the message. The mover uses shutil.move to do the move. I see that after the first move is done, the writer cannot w...
[ "Locking is a possible solution, but I prefer the general architecture of having each external resource (including a file) dealt with by a single, separate thread. Other threads send work requests to the dedicated thread on a Queue.Queue instance (and provide a separate queue of their own as part of the work reque...
[ 29, 8, 4 ]
[]
[]
[ "file", "multithreading", "python" ]
stackoverflow_0002301458_file_multithreading_python.txt
Q: With multiple Python installs, how does MacPorts know which one to install MySQLdb for? I just upgraded the default Python 2.5 on Leopard to 2.6 via the installer on www.python.org. Upon doing so, the MySQLdb I had installed was no longer found. So I tried reinstalling it via port install py-mysql, and it succeede...
With multiple Python installs, how does MacPorts know which one to install MySQLdb for?
I just upgraded the default Python 2.5 on Leopard to 2.6 via the installer on www.python.org. Upon doing so, the MySQLdb I had installed was no longer found. So I tried reinstalling it via port install py-mysql, and it succeeded, but MySQLdb was still not importable. So then I tried to python install python26 with pyth...
[ "The MacPorts python ports generally follow a pattern: if the port name starts with just py-, it is configured to install into MacPorts python2.4. Likewise py25- requires python2.5. For the MacPorts python2.6, you want this port:\nsudo port install py26-mysql\n\n", "You also need python_select (or is it select_...
[ 2, 1 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0001499572_macos_mysql_python.txt
Q: Alternate row coloring in Scintilla I'm using wxStyledTextCtrl from wxPython, a wrapper around the Scintilla component. Is there any way to get alternate row coloring on it (odd rows in one background color and even rows in another color)? I'm using the builtin python styler to highlight keywords. A: The backgr...
Alternate row coloring in Scintilla
I'm using wxStyledTextCtrl from wxPython, a wrapper around the Scintilla component. Is there any way to get alternate row coloring on it (odd rows in one background color and even rows in another color)? I'm using the builtin python styler to highlight keywords.
[ "The background of lines can be changed, for example by markers (which is used for stuff like bookmarks or breakpoints, current execution point and the like in IDEs), but there is no built-in mode for changing the background colour of every other line.\nYou could simulate this by setting a special marker with a bac...
[ 6 ]
[]
[]
[ "python", "scintilla", "wxpython" ]
stackoverflow_0002302165_python_scintilla_wxpython.txt
Q: How can I fix the error on this Python code? I have this superclass: import wx class Plugin(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) self.colorOver = ((89,89,89)) self.colorLeave = ((110,110,110)) self.SetBackground...
How can I fix the error on this Python code?
I have this superclass: import wx class Plugin(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) self.colorOver = ((89,89,89)) self.colorLeave = ((110,110,110)) self.SetBackgroundColour(self.colorLeave) self.SetForeground...
[ "Make the subclass\nclass noisePlugin(plugin.Plugin):\n def __init__(self, *a, **k):\n plugin.Plugin.__init__(self, *a, **k)\n self.name = \"noise\"\n\nWhenever you want to use self.something you have to be within a method, not at class level outside of methods!\n", "What makes you think this wor...
[ 3, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002302360_python_wxpython.txt
Q: Manipulating dates in the datastore I've recently been playing around with Google's AppEngine and I seem to have gotten stuck. I'm trying to create a query that selects posts that are before a certain date (in this case, the date is now - 1 day). I've tried a few different methods in order to accomplish this, but ...
Manipulating dates in the datastore
I've recently been playing around with Google's AppEngine and I seem to have gotten stuck. I'm trying to create a query that selects posts that are before a certain date (in this case, the date is now - 1 day). I've tried a few different methods in order to accomplish this, but none have worked. One of which involved c...
[ "What happens if you build your query using methods?\nquery = Post.all()\nquery.filter('date < ', datetime.datetime - 84600)\nresults = query.fetch(limit=10)\n\n", "You need to move the math outside of the query:\ndb.GqlQuery(\"SELECT __key__ FROM Post WHERE date < :1 LIMIT 10, ORDER BY date DESC\", (time.time() ...
[ 1, 1 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0002300759_database_google_app_engine_python.txt
Q: What's the way to keep the dictionary parameter order in Python? def createNode(doc_, **param_): cache = {'p':'property','l':'label','td':'totalDelay','rd':'routeDelay','ld':'logicDelay'} for index in param_: newIndex = cache[index] value = param_[index] print newIndex, '=', value d...
What's the way to keep the dictionary parameter order in Python?
def createNode(doc_, **param_): cache = {'p':'property','l':'label','td':'totalDelay','rd':'routeDelay','ld':'logicDelay'} for index in param_: newIndex = cache[index] value = param_[index] print newIndex, '=', value doc = 10 createNode(doc, p='path', l='ifft4k_radix4_noUnolling_core.v...
[ "\nI need to keep the order of the\n parameter, I mean, property comes\n first, then label until I get\n reouteDelay last.\n\nThen you're simply doing things in the wrong order -- no need for ordered dictionaries! Try, instead, a tuple of pairs for cache, as follows:\ndef createNode(doc_, **param_):\n cache ...
[ 7, 6, 3 ]
[]
[]
[ "parameter_passing", "python" ]
stackoverflow_0002302663_parameter_passing_python.txt
Q: Pass error on socket I am writing a general Client-Server socket program where the client sends commands to the Server, which executes it and sends the result to the Client. However if there is an error while executing a command, I want to be able to inform the Client of an error. I know I could send the String "...
Pass error on socket
I am writing a general Client-Server socket program where the client sends commands to the Server, which executes it and sends the result to the Client. However if there is an error while executing a command, I want to be able to inform the Client of an error. I know I could send the String "ERROR" or maybe something ...
[ "Typically when doing client-server communication you need to establish some kind of protocol. One very simple protocol is to send the String \"COMMAND\" before you send any commands and the String \"ERROR\" before you send any errors. This doubles the number of Strings you have to send but gives more flexibility...
[ 0, 0 ]
[]
[]
[ "java", "python", "sockets" ]
stackoverflow_0002302761_java_python_sockets.txt
Q: How to test whether a variable has been initialized before using it? So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use if __name__ == '__main__'). Also, there is a method that is to be called for when a client imports t...
How to test whether a variable has been initialized before using it?
So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use if __name__ == '__main__'). Also, there is a method that is to be called for when a client imports the application for use within another application. This method will also ...
[ "It's an error to access a variable before it is initialized. An uninitialized variable's value isn't None; accessing it just raises an exception.\nYou can catch the exception if you like:\n>>> try:\n... foo = x\n... except NameError:\n... x = 5\n... foo = 1\n\nIn a class, you can provide a default value o...
[ 18, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002303005_python.txt
Q: how to use array in django I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using IntegerField but on save it is giving error int() argument must be a string or a number, not 'list How can I add this field to my model? I am using this field in my views.py ...
how to use array in django
I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using IntegerField but on save it is giving error int() argument must be a string or a number, not 'list How can I add this field to my model? I am using this field in my views.py so I need to add it in my model....
[ "You may be interested in using a CommaSeparatedIntegerField.\nIf you've got a list of integers like this:\nmy_ints = [1,2,3,4,5]\n\nand a model like this:\nclass MyModel(models.Model):\n values = CommaSeparatedIntegerField(max_length = 200)\n\nthen you can save my_ints into a MyModel like this:\nm = MyModel(val...
[ 7, 1, 1, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002197975_django_django_models_python.txt
Q: Dump django debug output to a file? I noticed in the django documentation that when DEBUG is False it will mail your configured ADMINS the full exception information. Is there an easy way to dump the full exception information this to a file? A: No, but you can find or write middleware to catch it.
Dump django debug output to a file?
I noticed in the django documentation that when DEBUG is False it will mail your configured ADMINS the full exception information. Is there an easy way to dump the full exception information this to a file?
[ "No, but you can find or write middleware to catch it.\n" ]
[ 1 ]
[]
[]
[ "debugging", "django", "python" ]
stackoverflow_0002302926_debugging_django_python.txt
Q: Python class methods In Python, which is the best way (style wise) to allow public access to an object's variables? There are lots of options I've seen from different languages, I was wondering which of these (if any) is the preferred Python method? These are the options I'm currently torn between: Allow direct a...
Python class methods
In Python, which is the best way (style wise) to allow public access to an object's variables? There are lots of options I've seen from different languages, I was wondering which of these (if any) is the preferred Python method? These are the options I'm currently torn between: Allow direct access to object variables ...
[ "Don't bother using accessors until they're necessary; converting a simple attribute to a property is quick and easy, and doesn't need modification of client code.\nWhen I write a property, I use _get_FOO() and _set_FOO() for the accessors, and _FOO for the attribute itself.\n", "There are no \"private\" variable...
[ 4, 3, 2 ]
[ "You can use\nGetters and setters (Java like)\nclass SomeClass(object):\n ...\n\n def get_x(self):\n return self._x\n def set_x(self, x):\n self._x = x\n\nc = SomeClass()\nprint c.get_x()\nc.set_x(10)\n\nProperties (C# like)\nclass SomeClass(object):\n ...\n\n def get_x(self):\n return self._x\n def ...
[ -1 ]
[ "class", "python" ]
stackoverflow_0002303414_class_python.txt
Q: How to install python module as a command line application under windows? I need to install a python module in the site packages that also will be used as a command line application. Suppose I have a module like: app.py def main(): print 'Dummy message' if __name__ == '__main__': main() setup.py import di...
How to install python module as a command line application under windows?
I need to install a python module in the site packages that also will be used as a command line application. Suppose I have a module like: app.py def main(): print 'Dummy message' if __name__ == '__main__': main() setup.py import distutils try: from setuptools import setup except ImportError: from dis...
[ "You can use the options in setup.py to declare command line scripts. Please refer to this article. On Windows, the script will be created in \"C:\\Python26\\Scripts\" (if you didn't change the path) - lots of tools store their scripts there (e.g. \"easy_install\", \"hg\", ...).\n", "Put the following in dummy.cm...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002303434_python.txt
Q: GAE Chat Data Persistance in Memcache I'm writing a chat feature (like the Faceboook.com one) for a Google App Engine site. I need a way to keep track of what users have new messages. I'm currently trying to use Memcache: class Message(): def __init__(self, from_user_key, message_text) self.from_user_k...
GAE Chat Data Persistance in Memcache
I'm writing a chat feature (like the Faceboook.com one) for a Google App Engine site. I need a way to keep track of what users have new messages. I'm currently trying to use Memcache: class Message(): def __init__(self, from_user_key, message_text) self.from_user_key = from_user_key self.message_tex...
[ "The problem isn't so much about how to share data between \"pages\" but how will the usability of the service will be impacted by using memcache.\nThere are no guarantees associated with data persistence in memcache: one moment its there, the other it might not.\n" ]
[ 3 ]
[]
[]
[ "chat", "google_app_engine", "python" ]
stackoverflow_0002303751_chat_google_app_engine_python.txt
Q: Is there any purpose for a python application use C other than performance? If Python was so fast as C, the latter would be present in python apps/libraries? Example: if Python was fast as C would PIL be written completely in Python? A: To access "legacy" C libraries and OS facilities. A: While you can of cour...
Is there any purpose for a python application use C other than performance?
If Python was so fast as C, the latter would be present in python apps/libraries? Example: if Python was fast as C would PIL be written completely in Python?
[ "To access \"legacy\" C libraries and OS facilities.\n", "While you can of course use ctypes to access existing C code, you might not necessarily want to, in sufficiently complex cases: when you're coding to an interface designed for (and implemented in) C, not doing compilation can mean that small errors on the ...
[ 7, 5, 2, 0 ]
[]
[]
[ "bytecode", "c", "performance", "python" ]
stackoverflow_0002303683_bytecode_c_performance_python.txt
Q: What is the easiest way to implement a Comet serverside backend? PHP as an Apache module or otherwise, would start one thread per pending request so it doesn't scale well. Are Java and Python my only other options? As a complete newbie to Python, is Twisted easy to use? A: Twisted is very powerful but not easy t...
What is the easiest way to implement a Comet serverside backend?
PHP as an Apache module or otherwise, would start one thread per pending request so it doesn't scale well. Are Java and Python my only other options? As a complete newbie to Python, is Twisted easy to use?
[ "Twisted is very powerful but not easy to use, especially for a newbie.\ntornado is another async server in Python, less general than Twisted (you would not use it for a network client for example) but simpler to use to implement servers, including Comet ones.\n", "Investigate node.js. It's an evented server-side...
[ 2, 1, 1 ]
[]
[]
[ "comet", "http", "php", "push", "python" ]
stackoverflow_0002302145_comet_http_php_push_python.txt
Q: Get zip code based on IP Address with Python Is it possible to find the zip code based on a users IP address using python / django (not geodjango)? I assume I would have to use a web service, but I would really like to just be able to query a database if possible. I am using geopy right now, so it would be cool...
Get zip code based on IP Address with Python
Is it possible to find the zip code based on a users IP address using python / django (not geodjango)? I assume I would have to use a web service, but I would really like to just be able to query a database if possible. I am using geopy right now, so it would be cool if I could integrate that somehow.
[ "http://www.ip2location.com/python.aspx\nimport IP2Location;\n\nIP2LocObj = IP2Location.IP2Location();\nIP2LocObj.open(\"data/IP-COUNTRY-SAMPLE.BIN\");\nrec = IP2LocObj.get_all(\"19.5.10.1\");\n\nprint rec.zipcode\n\nI don't have any experience with this package but it looks like it will do what you want.\nEDIT: Ac...
[ 1, -2 ]
[]
[]
[ "django", "geolocation", "python" ]
stackoverflow_0002303966_django_geolocation_python.txt
Q: django having multiple one many to many relations that references same model i have a model that is having multiple many to many relation to another model it is as follows: class Match(models.Model): """Model docstring""" Match_Id = models.AutoField(primary_key=True) Team_one = models.ManyToManyField('Team',...
django having multiple one many to many relations that references same model
i have a model that is having multiple many to many relation to another model it is as follows: class Match(models.Model): """Model docstring""" Match_Id = models.AutoField(primary_key=True) Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,) Team_two = models.ManyToManyField(...
[ "Are you sure Team_one and Team_two should be ManyToMany fields? Surely, a match only has a single team on each side - in which case these should both be ForeignKeys.\n", "Using spaces in related_name attribute makes me uneasy, but I think the real problem is connected to the use of to_field attribute on the winn...
[ 1, 1 ]
[]
[]
[ "database", "django", "django_models", "python" ]
stackoverflow_0002303778_database_django_django_models_python.txt
Q: Print out the output of os.popen() without buffering in python Let's say that I have a process that prints out some data something like this ruby code. 1.upto(10) { |i| puts i puts "\n" sleep 0.6 } I want to have a python code that spawns this process, and read data from it to print it out. import...
Print out the output of os.popen() without buffering in python
Let's say that I have a process that prints out some data something like this ruby code. 1.upto(10) { |i| puts i puts "\n" sleep 0.6 } I want to have a python code that spawns this process, and read data from it to print it out. import os import sys cmd = "ruby /Users/smcho/Desktop/testit.rb"; pinga...
[ "The data is being buffered by ruby. Use something like\n$stdout.flush\n\nto make it flush. I'm not sure if that's the correct ruby command to do that.\n\nObligatory:\nUse subprocess module. os.popen has been replaced by it.\nimport subprocess\nimport sys\n\ncmd = [\"ruby\", \"/Users/smcho/Desktop/testit.rb\"]\np =...
[ 5 ]
[]
[]
[ "flush", "popen", "python", "ruby" ]
stackoverflow_0002304072_flush_popen_python_ruby.txt
Q: _ElementInterface instance has no attribute 'tostring' The code below generates this error. I can't figure out why. If ElementTree has parse, why doesn't it have tostring? http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree from xml.etree.ElementTree import ElementTree ... ...
_ElementInterface instance has no attribute 'tostring'
The code below generates this error. I can't figure out why. If ElementTree has parse, why doesn't it have tostring? http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree from xml.etree.ElementTree import ElementTree ... tree = ElementTree() node = ElementTree() node = tree.pars...
[ "tostring is a method of the xml.etree.ElementTree module, not the confusingly similarly-named xml.etree.ElementTree.ElementTree class.\nfrom xml.etree.ElementTree import ElementTree\nfrom xml.etree.ElementTree import tostring\n\ntree = ElementTree()\nnode = tree.parse(open(\"my_xml.xml\"))\ntext = tostring(node)\n...
[ 8, 3 ]
[ "The docs you've linked to do not support the existence of a ElementTree.tostring() method.\nAlso, your call to tree.parse() rebinds node.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0002304082_python.txt
Q: django database many2many relationship errors hi i am using the following models to build a database from django.db import models from django.contrib import admin class Team(models.Model): """Model docstring""" slug = models.SlugField(max_length=200) Team_ID = models.AutoField(primary_key=True) T...
django database many2many relationship errors
hi i am using the following models to build a database from django.db import models from django.contrib import admin class Team(models.Model): """Model docstring""" slug = models.SlugField(max_length=200) Team_ID = models.AutoField(primary_key=True) Team_Name = models.CharField(max_length=100,) C...
[ "Mmh do you really have to use your own primary key fields? If you don't specify a primary key field, than Django automatically creates a field called id. I don't see a a benefit from naming the fields e.g. match_id, especially as you want to access this field later, it will look like match.match_id.\nSo maybe it w...
[ 1 ]
[]
[]
[ "database", "django", "django_models", "postgresql", "python" ]
stackoverflow_0002303498_database_django_django_models_postgresql_python.txt
Q: Automate conversion of Sybase .ADT files to SQL I am working with some data I obtained that is read with a program using an embedded Advantage Database Server. The program was not written by me and does not have all of the functionality that I need. I would like to convert this data to a different format so that...
Automate conversion of Sybase .ADT files to SQL
I am working with some data I obtained that is read with a program using an embedded Advantage Database Server. The program was not written by me and does not have all of the functionality that I need. I would like to convert this data to a different format so that I can work with it more freely, such as MySQL. I k...
[ "Advantage has a dbi (Perl) driver you could use to access the tables in their existing ADT format. Also has JDBC and OLE DB drivers. See all of them at http://devzone.advantagedatabase.com/dz/content.aspx?key=20&Release=13\nNote that link is to the version 9.1 drivers. You will want to grab a driver that is equal ...
[ 2, 2 ]
[]
[]
[ "advantage_database_server", "python", "ruby", "sybase" ]
stackoverflow_0002289519_advantage_database_server_python_ruby_sybase.txt
Q: Numeric data collection from an mp3 in python Anyone know how I can plot numeric data from an mp3 in real time? For example the script plays a mp3 and as its playing prints 3 sets of numeric data. A: You could use the Veusz python package that supports realtime plotting of data.
Numeric data collection from an mp3 in python
Anyone know how I can plot numeric data from an mp3 in real time? For example the script plays a mp3 and as its playing prints 3 sets of numeric data.
[ "You could use the Veusz python package that supports realtime plotting of data.\n" ]
[ 0 ]
[]
[]
[ "graphical_programming", "mp3", "numeric", "python" ]
stackoverflow_0002303958_graphical_programming_mp3_numeric_python.txt
Q: pycurl request exist in header function? in C do return -1 when i want to cancel the download in either the header or the write function. In pycurl i get this error pycurl.error: invalid return value for write callback -1 17 I dont know what the 17 means but what am i not doing correctly? A: from pycurl.c: els...
pycurl request exist in header function?
in C do return -1 when i want to cancel the download in either the header or the write function. In pycurl i get this error pycurl.error: invalid return value for write callback -1 17 I dont know what the 17 means but what am i not doing correctly?
[ "from pycurl.c: \nelse if (PyInt_Check(result)) {\n long obj_size = PyInt_AsLong(result);\n if (obj_size < 0 || obj_size > total_size) {\n PyErr_Format(ErrorObject, \"invalid return value for write callback %ld %ld\", (long)obj_size, (long)total_size);\n goto verbose_error;\n }\n\nthis would ...
[ 3, 1 ]
[]
[]
[ "libcurl", "pycurl", "python" ]
stackoverflow_0000525405_libcurl_pycurl_python.txt
Q: TinyMCE popup windows not working in Django development server TinyMCE is working just fine, all except for the popup windows. They come up blank, and after a little bit of Google searching, apparently it has something to do with cross domain errors with Firefox and Django. I tried using document.domain, but I hav...
TinyMCE popup windows not working in Django development server
TinyMCE is working just fine, all except for the popup windows. They come up blank, and after a little bit of Google searching, apparently it has something to do with cross domain errors with Firefox and Django. I tried using document.domain, but I have a feeling that it doesn't work when you're using the Django develo...
[ "There's nothing wrong with 127.0.0.1 as a domain. The problem is that it's different to your media domain localhost, although they both point to the same thing.\nTinyMCE doesn't like different domains for the media, which is why having a relative MEDIA_URL would work. Using the URL http://localhost:8000/ to access...
[ 1, 0 ]
[]
[]
[ "django", "django_tinymce", "python", "tinymce" ]
stackoverflow_0002260061_django_django_tinymce_python_tinymce.txt
Q: app-engine-patch is dead. Now what is the best way to use Django on Google App Engine? The app-engine-patch authors have officially marked this wonderful project as dead on their website. Over the last year a lot of people have asked what the best way to run Django on Google App Engine was, and time after time pe...
app-engine-patch is dead. Now what is the best way to use Django on Google App Engine?
The app-engine-patch authors have officially marked this wonderful project as dead on their website. Over the last year a lot of people have asked what the best way to run Django on Google App Engine was, and time after time people have pointed to app-engine-patch being the way to go. Now that this project is dead, I ...
[ "App engine patch is probably a safer bet for a given moment. Though not actively supported at the moment, it's still great, as it's been tested more thoroughly. If you're ready to take some risks - go and give the new djangoappengine+django-nonrel (native django support for non relational databases, primarily goog...
[ 4, 0 ]
[]
[]
[ "app_engine_patch", "django", "google_app_engine", "python" ]
stackoverflow_0002283414_app_engine_patch_django_google_app_engine_python.txt
Q: How to use Twitter API to check if a user/password is valid? I have a user and a password and I'd like to use Twitter API (I'm using python-twitter) to check if those are valid data. A: urllib2 will raise HTTPError if the credentials are wrong, and the message will be 'HTTP Error 401: Unauthorized'. You could us...
How to use Twitter API to check if a user/password is valid?
I have a user and a password and I'd like to use Twitter API (I'm using python-twitter) to check if those are valid data.
[ "urllib2 will raise HTTPError if the credentials are wrong, and the message will be 'HTTP Error 401: Unauthorized'. You could use a temporary instance of the API to make an authorized request (GetFriends(), for example) in a try/except block to determine if the credentials are valid.\nimport twitter, urllib2\ncheck...
[ 1, 0 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0002304712_python_twitter.txt
Q: Is there a way of checking for membership from the values of a dictionary? Once confirmed, can we do other things? I understand that it's quite easy to check if a key is available in a dictionary, but what about certain values? So, what I have here is a dictionary of lists where the key references a set of, for co...
Is there a way of checking for membership from the values of a dictionary? Once confirmed, can we do other things?
I understand that it's quite easy to check if a key is available in a dictionary, but what about certain values? So, what I have here is a dictionary of lists where the key references a set of, for consistency's sake, strings. It would look a bit like this: menu = {'breakfast':['soft-boiled eggs', 'hash brown', 'Earl...
[ "Membership in menu is easy:\n[k for k, v in menu.iteritems() if 'chips' in v]\n\nMembership with defaultdict works exactly the same way since containment checking doesn't mutate it.\n", "One obvious way is to just go thru whole dict and replace the values but IMO it is better to design it so that it is easy to r...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002304749_dictionary_python.txt
Q: Remove and insert lines in a text file I have a text file looks like: first line second line third line forth line fifth line sixth line I want to replace the third and forth lines with three new lines. The above contents would become: first line second line new line1 new line2 new line3 ...
Remove and insert lines in a text file
I have a text file looks like: first line second line third line forth line fifth line sixth line I want to replace the third and forth lines with three new lines. The above contents would become: first line second line new line1 new line2 new line3 fifth line sixth line How can I do this u...
[ "For python2.6\nwith open(\"file1\") as infile:\n with open(\"file2\",\"w\") as outfile:\n for i,line in enumerate(infile):\n if i==2:\n # 3rd line\n outfile.write(\"new line1\\n\")\n outfile.write(\"new line2\\n\")\n outfile.write(\"n...
[ 7, 4, 3, 2, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002305115_file_io_python.txt
Q: python 2.6.4 doesn't support mod_python? am looking for a way to run django by just using my xampp, and i bumped into this tutorial online http://jyotirmaya.blogspot.com/2008/11/xampp-python-django.html according to the author, mod_python 3.3.1 is not supported by python 2.6, but the blog post was created more the...
python 2.6.4 doesn't support mod_python?
am looking for a way to run django by just using my xampp, and i bumped into this tutorial online http://jyotirmaya.blogspot.com/2008/11/xampp-python-django.html according to the author, mod_python 3.3.1 is not supported by python 2.6, but the blog post was created more then a year ago i think. is this thing still true...
[ "mod_python must be compiled against the specific version of Python that the handler will be run in. At the time there was probably no Windows installer for mod_python built against 2.6.4, hence the hysteria.\nIn all fairness, you should probably be using mod_wsgi to run Django apps instead.\n" ]
[ 6 ]
[]
[]
[ "django", "mod_python", "python" ]
stackoverflow_0002305210_django_mod_python_python.txt
Q: How can I limit an SQL query to be nondestructive? I'm planning on building a Django log-viewing app with powerful filters. I'd like to enable the user to finely filter the results with some custom (possibly DB-specific) SELECT queries. However, I dislike giving the user write access to the database. Is there a wa...
How can I limit an SQL query to be nondestructive?
I'm planning on building a Django log-viewing app with powerful filters. I'd like to enable the user to finely filter the results with some custom (possibly DB-specific) SELECT queries. However, I dislike giving the user write access to the database. Is there a way to make sure a query doesn't change anything in the da...
[ "Connect with a user that has only been granted SELECT permissions. Situations like this is why permissions exist in the first place.\n", "Create and use non-modifiable views.\n" ]
[ 14, 1 ]
[]
[]
[ "django", "python", "security", "sql", "sql_injection" ]
stackoverflow_0002305353_django_python_security_sql_sql_injection.txt
Q: Installing bitarray in Python 2.6 on Windows I would like to install bitarray in Windows running python 2.6. I have mingw32 installed, and I have C:\Python26\Lib\distutils\distutils.cfg set to: [build] compiler = mingw32 If I type, in a cmd.exe window: C:\Documents and Settings\john\My Documents\bitarray-0.3.5>py...
Installing bitarray in Python 2.6 on Windows
I would like to install bitarray in Windows running python 2.6. I have mingw32 installed, and I have C:\Python26\Lib\distutils\distutils.cfg set to: [build] compiler = mingw32 If I type, in a cmd.exe window: C:\Documents and Settings\john\My Documents\bitarray-0.3.5>python setup.py install I get: [normal python messa...
[ "MingW cannot compile the bitarray sources, I tried with version 3.4.5 and get the same errors.\nHowever, it compiles fine with the Microsoft compiler.\nFor your convenience I've build msi and exe installers for Python 2.6:\nhttp://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.msi\nhttp://starship.pyt...
[ 3, 0 ]
[]
[]
[ "bitarray", "c", "mingw", "python" ]
stackoverflow_0000780127_bitarray_c_mingw_python.txt
Q: Sampling keys due to their values I have a dictionary in python with key->value as str->int. If I have to chose a key based on it's own value, then as the value gets larger the key has a lower possibility of being chosen. For example, if key1=2 and key2->1, then the attitude of key1 should be 2:1. How can I do th...
Sampling keys due to their values
I have a dictionary in python with key->value as str->int. If I have to chose a key based on it's own value, then as the value gets larger the key has a lower possibility of being chosen. For example, if key1=2 and key2->1, then the attitude of key1 should be 2:1. How can I do this?
[ "If the values are too large for gnibler's approach:\nBuild a list of tuples (key, index), where index is the sum of all values that come before key in the list (this would be the index of the first occurrence of key gnibler's list c. Also calculate the sum of all values (n).\nNow, generate a random number xbetween...
[ 2, 1, 1, 0 ]
[]
[]
[ "dictionary", "python", "sampling" ]
stackoverflow_0002305501_dictionary_python_sampling.txt
Q: How to output huge dependency relationships diagram of Plone with Graphviz? I wrote a tool for find dependency relationships behind a Python project. It is Gluttony. I run it on Plone, the result is impressive. I output the diagram with Networkx, and it looks like this: (source: googlecode.com) (Gee! It looks...
How to output huge dependency relationships diagram of Plone with Graphviz?
I wrote a tool for find dependency relationships behind a Python project. It is Gluttony. I run it on Plone, the result is impressive. I output the diagram with Networkx, and it looks like this: (source: googlecode.com) (Gee! It looks like World of Goo!) A mess! I didn't handle layout with Networkx. That's why it...
[ "The command dot plone.dot -Tsvg > plone.svg renders this scalable vecor graphic:\nalt text http://dl.dropbox.com/u/138632/plone.svg \nI can open the .svg file fine in Inkscape and zoom in till 100%.\n", "If you can produce an image: Graphviz tends to create huge files. Zoom in.\nFor me graphviz regularly crashes...
[ 2, 1 ]
[]
[]
[ "diagram", "graphviz", "plone", "python" ]
stackoverflow_0002303079_diagram_graphviz_plone_python.txt
Q: UnicodeDecodeError problem with mechanize I receive the following string from one website via mechanize: 'We\x92ve' I know that \x92 stands for ’ character. I'm trying to convert that string to Unicode: >> unicode('We\x92ve','utf-8') UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 2: unexpecte...
UnicodeDecodeError problem with mechanize
I receive the following string from one website via mechanize: 'We\x92ve' I know that \x92 stands for ’ character. I'm trying to convert that string to Unicode: >> unicode('We\x92ve','utf-8') UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 2: unexpected code byte What am I doing wrong? Edit: The r...
[ "\\x92 stands for ’ alright, but it does so in the Windows-1252 encoding, not in UTF-8:\n>>> print unicode('We\\x92ve','1252')\nWe’ve\n\nIf you don't know what encoding your source data is in, you can detect it using chardet (extremely easy to use).\n" ]
[ 4 ]
[]
[]
[ "mechanize", "python", "unicode" ]
stackoverflow_0002305997_mechanize_python_unicode.txt