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: Need to turn all text into plain text/ASCII (I think?) I am trying to scrape a story from a website that I work for, when you put in the URL, which then posts to various news partners that we have. The problem is that, special characters seem to be giving it hiccups. I'm trying to do .replace on the string, but it...
Need to turn all text into plain text/ASCII (I think?)
I am trying to scrape a story from a website that I work for, when you put in the URL, which then posts to various news partners that we have. The problem is that, special characters seem to be giving it hiccups. I'm trying to do .replace on the string, but it doesn't seem to work particularly well. Is there anyway to ...
[ "Please take a look at this article and see if you are already familiar with the principles it discusses: http://www.joelonsoftware.com/articles/Unicode.html\nMy instinct is that your news partners are able to accept text beyond just what ASCII can encode. You just need to ensure that your application handles char...
[ 2, 1 ]
[]
[]
[ "encoding", "mechanize", "python" ]
stackoverflow_0006984030_encoding_mechanize_python.txt
Q: How can I create an executable with an executable inside? I want to make an executable with VNC windows client inside, and when the app is executed, it prompts something, a message or something, and then opens the VNC client and closes itself, leaving only the VNC open... How can I do that? A: What you want to d...
How can I create an executable with an executable inside?
I want to make an executable with VNC windows client inside, and when the app is executed, it prompts something, a message or something, and then opens the VNC client and closes itself, leaving only the VNC open... How can I do that?
[ "What you want to do is invoke a process [for the VNC windows client] from your application, not embed an executable within another (which doesn't make sense, by the way.) \nFor more information on how to do this, see Subprocess Management in the Python documentation.\n", "If you wish to download a single file bu...
[ 1, 1 ]
[]
[]
[ "executable", "python", "vnc", "windows" ]
stackoverflow_0006983021_executable_python_vnc_windows.txt
Q: Python: how to search a multi line string for specific content I have created a string from connectString = 'D:\Database\10.2.0\BIN\sqlplus.exe -L sys/PASSWORD' output = str(call(connectstring)) this results from print output stuff stuff stuff stuff even more stuff ORA-28009 stuff stuff stuff and stuff I do ...
Python: how to search a multi line string for specific content
I have created a string from connectString = 'D:\Database\10.2.0\BIN\sqlplus.exe -L sys/PASSWORD' output = str(call(connectstring)) this results from print output stuff stuff stuff stuff even more stuff ORA-28009 stuff stuff stuff and stuff I do output.find('ORA-28009') but it does not find the string sequence. ...
[ "try to normalise the string removing the special charachter.\ni use a function like this:\ndef trim (str):\n str = str.replace(' ', '')\n str = str.replace('\\s', '')\n str = str.replace('\\t', '')\n str = str.replace('\\r', '')\n str = str.replace('\\n', '')\n return str\n\nMaybe you can adapt i...
[ 2, 0, 0 ]
[]
[]
[ "find", "python", "string" ]
stackoverflow_0006958868_find_python_string.txt
Q: Error while pinging Pingomatic (XMLRPC) using python I'm trying to ping Pingomatic using python. I've written this: import xmlrpclib print "START" s = xmlrpclib.Server('http://rpc.pingomatic.com') reply = s.weblogUpdates.ping('Test','http://www.testblog.com') print "END" But when I run, i get: >>> START Trac...
Error while pinging Pingomatic (XMLRPC) using python
I'm trying to ping Pingomatic using python. I've written this: import xmlrpclib print "START" s = xmlrpclib.Server('http://rpc.pingomatic.com') reply = s.weblogUpdates.ping('Test','http://www.testblog.com') print "END" But when I run, i get: >>> START Traceback (most recent call last): File "C:/xxxxxxxxxxxxxxxx...
[ "It turns out this was an issue with Pingomatic's response format. I tried pinging Weblogs.com, and it worked fine.\nI emailed Automattic to let them know, and they've since fixed the issue -- everything should be working!\n" ]
[ 1 ]
[]
[]
[ "python", "xmlrpclib" ]
stackoverflow_0004431596_python_xmlrpclib.txt
Q: Accepting inputs from Tkinter I want to write a GUI in Tkinter that accepts a text inputs from the user and stores it in a variable Text; I also want to be able to use this variable later on... Here is something i tried that failed: from Tkinter import * def recieve(): text = E1.get() return text top = T...
Accepting inputs from Tkinter
I want to write a GUI in Tkinter that accepts a text inputs from the user and stores it in a variable Text; I also want to be able to use this variable later on... Here is something i tried that failed: from Tkinter import * def recieve(): text = E1.get() return text top = Tk() L1 = Label(top, text="User Nam...
[ "The problem lies here:\nprint text \ntop.mainloop()\n\nBefore top.mainloop() is called, text has not been defined. Only after the call to top.mainloop is the user presented with the GUI interface, and the mainloop probably loops many many times before the user gets around to typing in the Entry box and pressing...
[ 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0006985074_python_tkinter_user_interface.txt
Q: Word Net - Word Synonyms & related word constructs - Java or Python I am looking to use WordNet to look for a collection of like terms from a base set of terms. For example, the word 'discouraged' - potential synonyms could be: daunted, glum, deterred, pessimistic. I also wanted to identify potential bi-grams su...
Word Net - Word Synonyms & related word constructs - Java or Python
I am looking to use WordNet to look for a collection of like terms from a base set of terms. For example, the word 'discouraged' - potential synonyms could be: daunted, glum, deterred, pessimistic. I also wanted to identify potential bi-grams such as; beat down, put off, caved in etc. How do I go about extracting thi...
[ "These are two different problems.\n1) Wordnet and python. Use NLTK, it has a nice interface to wordnet. You could write something on your own, but honestly why make life difficult? Lingpipe probably also has something built in but NLTK is much easier to use. I think nltk just downloads an ntlk database, but I'm pr...
[ 3, 3, 2 ]
[]
[]
[ "java", "nlp", "python", "text_mining", "wordnet" ]
stackoverflow_0006984264_java_nlp_python_text_mining_wordnet.txt
Q: How can you emulate a mailing list in Django? I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions. The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, inst...
How can you emulate a mailing list in Django?
I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions. The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address. Now, we can work our way t...
[ "What about http://labs.freehackers.org/projects/colibri/wiki\nIt seems to do what you want: a mailing list manager with a django frontend.\n", "Did you take a look at majordomo, or mailman?\n", "RFC 2919 has some info and more references on this.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "django", "mailing_list", "python" ]
stackoverflow_0000268930_django_mailing_list_python.txt
Q: MessageBox case for Ok an Cancel? how can I make "cases" for the following code: win32api.MessageBox(None, "This Program Will do THIS:\n" "blablabla", "programtitler", win32con.MB_OKCANCEL | win32con.MB_ICONQUESTION) for example if se...
MessageBox case for Ok an Cancel?
how can I make "cases" for the following code: win32api.MessageBox(None, "This Program Will do THIS:\n" "blablabla", "programtitler", win32con.MB_OKCANCEL | win32con.MB_ICONQUESTION) for example if select ok, do THIS, if select cancel, do ...
[ "Should be something like this. (C#)\n int result = win32api.MessageBox(None,\n \"This Program Will do THIS:\\n\"\n \"blablabla\",\n \"programtitler\",\n win32con.MB_OKCANCEL | win32con.MB_ICONQUESTION)\n\n switch (res...
[ 4, 0 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0006985442_python_pywin32_windows.txt
Q: Hide console from Python script? Possible Duplicate: How to hide console window in python? I have a simple script with one messagedialog only... how can I hide the console from it when I execute the app? A: Execute the script using pythonw.exe rather than python.exe. You can set that up to happen automatically...
Hide console from Python script?
Possible Duplicate: How to hide console window in python? I have a simple script with one messagedialog only... how can I hide the console from it when I execute the app?
[ "Execute the script using pythonw.exe rather than python.exe. You can set that up to happen automatically by giving the script the extension .pyw rather than .py.\n" ]
[ 3 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0006985929_python_pywin32_windows.txt
Q: Use Python to remove lines in a files that start with an octothorpe? This seems like a straight-forward question but I can't seem to pinpoint my problem. I am trying to delete all lines in a file that start with an octothorpe (#) except the first line. Here is the loop I am working with: for i, line in enumerate(i...
Use Python to remove lines in a files that start with an octothorpe?
This seems like a straight-forward question but I can't seem to pinpoint my problem. I am trying to delete all lines in a file that start with an octothorpe (#) except the first line. Here is the loop I am working with: for i, line in enumerate(input_file): if i > 1: if not line.startswith('#'): ...
[ "You aren't writing out the first line:\nfor i, line in enumerate(input_file):\n if i == 0:\n output.write(line)\n else:\n if not line.startswith('#'):\n output.write(line)\n\nKeep in mind also that enumerate (like most things) starts at zero.\nA little more concisely (and not repeati...
[ 19, 10, 4 ]
[]
[]
[ "python", "startswith" ]
stackoverflow_0006985783_python_startswith.txt
Q: MySQL in Python 2.5 I would like to know how can I handle MySQL in python 2.5. Is there any build in library? Or any small external library? A: Try taking a look at http://sourceforge.net/projects/mysql-python/ it is a souerceforge project. A: If, as you suggest, you can't build C modules, try using one of the...
MySQL in Python 2.5
I would like to know how can I handle MySQL in python 2.5. Is there any build in library? Or any small external library?
[ "Try taking a look at http://sourceforge.net/projects/mysql-python/ it is a souerceforge project.\n", "If, as you suggest, you can't build C modules, try using one of the pure Python modules listed here. Use virtualenv to create your own site-packages directory and pip to install it. I have no idea how well any o...
[ 1, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006980827_mysql_python.txt
Q: timestamp from 3months ago I've a small script where I'm getting data from the last few months, based on the timestamp. Right now I'm using current day and a set date (currently May). Here's how I'm defining it: today_time = int(time.mktime(date.today().timetuple())*1000000) earlier_time = int(time.mktime(datetime...
timestamp from 3months ago
I've a small script where I'm getting data from the last few months, based on the timestamp. Right now I'm using current day and a set date (currently May). Here's how I'm defining it: today_time = int(time.mktime(date.today().timetuple())*1000000) earlier_time = int(time.mktime(datetime.date(2011,05,01).timetuple())*1...
[ "import datetime\n\nnow = datetime.datetime.now()\nthen = now - datetime.timedelta(days=90)\n\n" ]
[ 21 ]
[]
[]
[ "python", "timestamp" ]
stackoverflow_0006986067_python_timestamp.txt
Q: Client polling (reverse AJAX) for chat requests in Django? I want to make it that one user on the site can chat request another user on my Django site. I want the requestee to get a realtime box that say: "Do you want to chat?" How does the following client polling approach sound: user1 clicks on users2 nickname, ...
Client polling (reverse AJAX) for chat requests in Django?
I want to make it that one user on the site can chat request another user on my Django site. I want the requestee to get a realtime box that say: "Do you want to chat?" How does the following client polling approach sound: user1 clicks on users2 nickname, generating a POST request to some /message/requests, which creat...
[ "A database table for this would put a load on your server, as you said, but might be useful if you want to keep a record of these requests for whatever reason.\nUsing something like memcached or an AMQP server might give you better performance. If you like you could even use a higher-performance key-value-store su...
[ 2, 1 ]
[]
[]
[ "ajax", "django", "python", "reverse_ajax", "session" ]
stackoverflow_0002329627_ajax_django_python_reverse_ajax_session.txt
Q: python: how do you concatenate time to a string? I'm a py newbie and was wondering if there was a simpler way to concatenate time to a string in a write function? here is my code running windows xp with activepy 2.6: from time import clock filename = "c:\Python\\test.txt" try: tm = clock() print "fil...
python: how do you concatenate time to a string?
I'm a py newbie and was wondering if there was a simpler way to concatenate time to a string in a write function? here is my code running windows xp with activepy 2.6: from time import clock filename = "c:\Python\\test.txt" try: tm = clock() print "filename: " + filename fs...
[ "time.clock returns a machine-readable representation of the duration the system is running.\nTo get a human-readable representation (a string) of the current wall time, use time.strftime:\n>>> import time\n>>> tm = time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)')\n>>> tm\n'Mon, 08 Aug 2011 20:14:59 CEST(+0200)'\n\n",...
[ 9, 7, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006986547_python.txt
Q: Subclassing the Django ImageFileField I'm interested in subclassing django's ImageFileField to allow access to the image IPTC metadata, something like: >>> from myapp.models import SomeModel >>> obj = SomeModel.objects.all()[0] # or what have you >>> obj.image.iptc['keywords'] ('keyword','anotherkeyword','etc') ....
Subclassing the Django ImageFileField
I'm interested in subclassing django's ImageFileField to allow access to the image IPTC metadata, something like: >>> from myapp.models import SomeModel >>> obj = SomeModel.objects.all()[0] # or what have you >>> obj.image.iptc['keywords'] ('keyword','anotherkeyword','etc') ... the docs say to read over django's inter...
[ "It's not clear from your question: have you tried something like this?\nclass ImageMetadataMixin(object):\n \"\"\"Mixin can be added to any image file\"\"\"\n @property\n def iptc(self):\n \"\"\"Or something like this\"\"\"\n\nclass ImageWithMetadataFieldFile(ImageMetadataMixin, ImageFieldFile):\n ...
[ 6, 1 ]
[]
[]
[ "django", "django_models", "image", "metadata", "python" ]
stackoverflow_0003973586_django_django_models_image_metadata_python.txt
Q: Django - Abstract Base Class Model Breaking syncdb I have this in my models.py: class AuditableTable(models.Model): class Meta: abstract = True created_by = models.ForeignKey(User,blank=True, related_name="%(app_label)s_%(class)s_related1") last_updated_by = models.ForeignKey(Us...
Django - Abstract Base Class Model Breaking syncdb
I have this in my models.py: class AuditableTable(models.Model): class Meta: abstract = True created_by = models.ForeignKey(User,blank=True, related_name="%(app_label)s_%(class)s_related1") last_updated_by = models.ForeignKey(User,blank=True, related_name="%(app_label)s_%(cla...
[ "Your related_name for created_by and last_updated_by are the same and should not be.\nfor what I can see your class Meta is ok, just change the related_name :)\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006986761_django_django_models_python.txt
Q: How create a tempory file from base64 encoded string? How can I create a file into the temporary files from a encoded string and then execute it? A: You'll probably be interested in the tempfile module, as well as base64 and execfile. BTW, you may want to provide some more detail about what you're trying to acco...
How create a tempory file from base64 encoded string?
How can I create a file into the temporary files from a encoded string and then execute it?
[ "You'll probably be interested in the tempfile module, as well as base64 and execfile.\nBTW, you may want to provide some more detail about what you're trying to accomplish. This sounds like it has a good chance of being either a bad idea, unnecessary work, or both.\n", "Something like this:\nimport tempfile\nimp...
[ 3, 3, 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006986273_python_windows.txt
Q: How to set default value of integer field to id() in app engine? Is it possible to set default value of field in data model to id() of the data model? something like class MyModel(db.Model): myID = db.IntegerProperty(default=self.id()) desc = db.StringProperty() A: You can't. The default you're setting ...
How to set default value of integer field to id() in app engine?
Is it possible to set default value of field in data model to id() of the data model? something like class MyModel(db.Model): myID = db.IntegerProperty(default=self.id()) desc = db.StringProperty()
[ "You can't. The default you're setting there is in a class variable, and will be the same for all instances created after the class definition is read. If self.id() actually made sense in this context (it doesn't; self is undefined), you'd be getting something like the id of the class, and assigning it as the defau...
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006982349_google_app_engine_python.txt
Q: How to do nested comments in Flask/Jinja? Like the comments in Hacker News and Reddit. I've looked at Jinja's docs but I can't find anything about recursion (which I assume is how this sort of thing is done). Any ideas? Thanks in advance. EDIT: I already have the data (from an API), and the comments are objects w...
How to do nested comments in Flask/Jinja?
Like the comments in Hacker News and Reddit. I've looked at Jinja's docs but I can't find anything about recursion (which I assume is how this sort of thing is done). Any ideas? Thanks in advance. EDIT: I already have the data (from an API), and the comments are objects which have children. I just need to know how to ...
[ "Unless, you give an example how your comment data is laid out, I can only give a basic example how recursive for loops work:\n{%- for item in comments recursive %}\n <li>{{ item.text }}</li>\n {%- if item.children -%}\n <ul class=\"children\">{{ loop(item.children) }}</ul>\n {%- endif %}</li>\n{%- ...
[ 7, 5 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0006985404_flask_jinja2_python.txt
Q: How to compile .c code from Cython with gcc Now that I've successfully installed Cython on Windows 7, I try to compile some Cython code using Cython, but gcc makes my life hard. cdef void say_hello(name): print "Hello %s" % name Using gcc to compile the code throws dozens of undefined reference to -erros, and...
How to compile .c code from Cython with gcc
Now that I've successfully installed Cython on Windows 7, I try to compile some Cython code using Cython, but gcc makes my life hard. cdef void say_hello(name): print "Hello %s" % name Using gcc to compile the code throws dozens of undefined reference to -erros, and I'm pretty sure the libpython.a is available (as...
[ "Try: \ngcc -c -IC:\\Python27\\include -o ctest.o ctest.c\ngcc -shared -LC:\\Python27\\libs -o ctest.pyd ctest.o -lpython27\n\n-shared creates a shared library. -lpython27 links with the import library C:\\Python27\\libs\\libpython27.a.\n", "That is a linker (ld) error and not a compiler error. You should provide...
[ 21, 1 ]
[]
[]
[ "c", "compilation", "cython", "gcc", "python" ]
stackoverflow_0006985109_c_compilation_cython_gcc_python.txt
Q: Using methods of a class from another in python I'm working through 'Dive Into Python' on Google App Engine and came across this error while attempting to call one class's methods from another: ERROR __init__.py:463] create() takes exactly 1 argument (2 given) Traceback (most recent call last): File "main.py", l...
Using methods of a class from another in python
I'm working through 'Dive Into Python' on Google App Engine and came across this error while attempting to call one class's methods from another: ERROR __init__.py:463] create() takes exactly 1 argument (2 given) Traceback (most recent call last): File "main.py", line 35, in get dal.create("sample-data"); File ...
[ "In self.data_store.create(data_dictionary), the self.data_store refers to the object created by self.data_store = StandardDataStore() in the __init__ method.\nIt looks like the create method of a StandardDataStore object doesn't expect an additional argument.\n", "It should be self.data_store.create(data_diction...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "instance_methods", "python" ]
stackoverflow_0006987327_google_app_engine_instance_methods_python.txt
Q: Question about timeit module in python I have a question about the timeit module in python, which is used to determine the time it takes for a piece of code to execute. t = timeit.Timer("foo","from __main__ import foo") str(t.timeit(1000)) What is the meaning of the argument 1000 in the above code ? A: From the...
Question about timeit module in python
I have a question about the timeit module in python, which is used to determine the time it takes for a piece of code to execute. t = timeit.Timer("foo","from __main__ import foo") str(t.timeit(1000)) What is the meaning of the argument 1000 in the above code ?
[ "From the documentation:\n\nTimer.timeit([number=1000000])\n\nTime number executions of the main statement. This executes the\n setup statement once, and then returns the time it takes to execute\n the main statement a number of times, measured in seconds as a float.\n The argument is the number of times through...
[ 4, 1, 1 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0006987630_python_timeit.txt
Q: Packaging a Python Program with custom built libraries I am trying to find a solution for a problem I am working on. I have a python program which is is using a custom built sqlite3 install (which allows > 10 simultaneous connections) and in addition requires the use of Tix (which does not come as a stand install...
Packaging a Python Program with custom built libraries
I am trying to find a solution for a problem I am working on. I have a python program which is is using a custom built sqlite3 install (which allows > 10 simultaneous connections) and in addition requires the use of Tix (which does not come as a stand install with the python package for the group I am distributing to....
[ "One possible solution: Create a custom package for that program containing the custom sqlite3/etc. stuff and use relative imports to refer to those custom subpackages from a main module in your package, which you'd hook into with a simple importing script that would execute a your_package.run() function or somethi...
[ 3 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0006986925_distutils_python.txt
Q: ImportError: No module named PySide.QtCore I have trouble using PySide in Eclipse. I installed py26-pyside using macports and added /opt/local/var/macports/software/py26-pyside/1.0.4_0/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PySide to PYTHONPATH But I got the above im...
ImportError: No module named PySide.QtCore
I have trouble using PySide in Eclipse. I installed py26-pyside using macports and added /opt/local/var/macports/software/py26-pyside/1.0.4_0/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PySide to PYTHONPATH But I got the above import error. What am I missing? Thanks
[ "Add /opt/local/var/macports/software/py26-pyside/1.0.4_0/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages to PYTHONPATH instead of what you have added.\n", "Running Linux, I had the same problem and I don't use PYTHONPATH. Simpler to put /usr/local/lib/python2.6/site-package...
[ 1, 0 ]
[]
[]
[ "pyside", "python" ]
stackoverflow_0006721266_pyside_python.txt
Q: Django Auth , Login Question Question Clarification: I'm trying to test if the user is authenticated or not for each page request. I'm trying to use Authentication for the first time in Django and I am not grasping how the login view is supposed to handle authentications. When I use @login_required, I'm redirectin...
Django Auth , Login Question
Question Clarification: I'm trying to test if the user is authenticated or not for each page request. I'm trying to use Authentication for the first time in Django and I am not grasping how the login view is supposed to handle authentications. When I use @login_required, I'm redirecting to "/login" to check if the user...
[ "Well, as you say, obviously that's not going to work, because it's incomplete. So, until you complete it, you're going to get an infinite loop - because you haven't written the code that puts _auth_user_id into request.session.\nBut I don't really know why you're making that test in the first place. The auth docum...
[ 2, 0 ]
[]
[]
[ "authentication", "django", "python", "session" ]
stackoverflow_0006987987_authentication_django_python_session.txt
Q: Using Chinese to build a dictionary in Python so this is my first time here, and also I am new to the world of Python. I am studying Chinese also and I wanted to create a program to review Chinese vocabulary using a dictionary. Here is the code that I normally use: #!/usr/bin/python # -*- coding:utf-8-*- dictiona...
Using Chinese to build a dictionary in Python
so this is my first time here, and also I am new to the world of Python. I am studying Chinese also and I wanted to create a program to review Chinese vocabulary using a dictionary. Here is the code that I normally use: #!/usr/bin/python # -*- coding:utf-8-*- dictionary = {"Hello" : "你好"} # Simple example to save time...
[ "When printing a dict, (e.g. print(dictionary)), the reprs of the keys and values are displayed.\nInstead, try:\ndictionary = {u\"Hello\" : u\"你好\"} \nfor key,value in dictionary.iteritems():\n print(u'{k} --> {v}'.format(k=key,v=value))\n\nyields:\nHello --> 你好\n\n", "You can see the characters if you print ...
[ 8, 1 ]
[]
[]
[ "cjk", "dictionary", "python", "unicode", "utf_8" ]
stackoverflow_0006988213_cjk_dictionary_python_unicode_utf_8.txt
Q: Retrieving files from different paths in Python? I am building a Python wrapper for a command line program. The wrapper takes a series of files and sends them one-by-one to the command line program as arguments. My wrapper looks like this: for file_name in glob.iglob('A0*'): output_dir = ''.join(('my_output_...
Retrieving files from different paths in Python?
I am building a Python wrapper for a command line program. The wrapper takes a series of files and sends them one-by-one to the command line program as arguments. My wrapper looks like this: for file_name in glob.iglob('A0*'): output_dir = ''.join(('my_output_',file_name)) cmd = ['/Users/bunsen/src/my_program...
[ "It seems like what you want is the following: glob.iglob(os.getcwd()+'/A0*')\n", "You can use the os module to get at some useful (and platform independent) pathname functions. You might try something like:\nimport os\nCOMMAND_LINE_FILES_HOME = \"cmd_files\" # Set the name of the directory where the command line...
[ 0, 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0006988281_path_python.txt
Q: 'str' object is not callable Not quite understanding why I am getting this trace error: Traceback (most recent call last): File "S:/Personal Folders/Andy/Python Projects/Salesforce BZ API/Automated Reports.py", line 15, in <module> parse = br.soup("find('div')") File "build\bdist.win32\egg\spynner\browser....
'str' object is not callable
Not quite understanding why I am getting this trace error: Traceback (most recent call last): File "S:/Personal Folders/Andy/Python Projects/Salesforce BZ API/Automated Reports.py", line 15, in <module> parse = br.soup("find('div')") File "build\bdist.win32\egg\spynner\browser.py", line 409, in _get_soup re...
[ "It looks like you're setting the HTML parser to the string \"BeautifulSoup\", not to BeautifulSoup. I don't have it installed so I can't test whether it works, but it's worth a try.\n", "I took a quick look here, and it seems that soup is not a function but a property.\n" ]
[ 5, 0 ]
[]
[]
[ "beautifulsoup", "python", "spynner" ]
stackoverflow_0006988494_beautifulsoup_python_spynner.txt
Q: numpy.interp & masked arrays I am using a numpy masked array to perform some image processing. The mask is in place to handle NoData pixels which surround the image (a necessary border as these are map projected images with the origin in a no data pixel). Using the following code block, I am able to perform a g...
numpy.interp & masked arrays
I am using a numpy masked array to perform some image processing. The mask is in place to handle NoData pixels which surround the image (a necessary border as these are map projected images with the origin in a no data pixel). Using the following code block, I am able to perform a gaussian stretch on an image. def g...
[ "you can get the mask of input_array first, and apply it to the result array, and use scipy.stats.norm to calculate cdf of normal distribution, or you can use scipy.special.erf() to calculate cdf by using the cdf formula of normal distribution:\nimport scipy.stats as stats \ndef gaussian_stretch2(input_array, ar...
[ 3 ]
[]
[]
[ "arrays", "image_processing", "numpy", "python" ]
stackoverflow_0006987495_arrays_image_processing_numpy_python.txt
Q: Django template span relationships? In django, https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships, span relationships provide an easy way in django to do a JOIN. Is there a way in the template to do this (using template tags)? A: You could do that, I think, because when you...
Django template span relationships?
In django, https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships, span relationships provide an easy way in django to do a JOIN. Is there a way in the template to do this (using template tags)?
[ "You could do that, I think, because when you write a custom template tag you can import models and run queries on them just as you can anywhere else. But it violates the separation of business logic and presentation that Django's model-view-controller (or model-view-template) design works hard to preserve. Why not...
[ 1 ]
[]
[]
[ "django", "filter", "python", "tags", "templates" ]
stackoverflow_0006978544_django_filter_python_tags_templates.txt
Q: How to name my variable class dynamicly in python Possible Duplicates: Python: Why can't I modify the current scope within a function using locals()? How do you programmatically set an attribute in Python? i know nammed dynamicly an varial in python with: var = "my_var" locals()[var] = "coucou" print my_var >>co...
How to name my variable class dynamicly in python
Possible Duplicates: Python: Why can't I modify the current scope within a function using locals()? How do you programmatically set an attribute in Python? i know nammed dynamicly an varial in python with: var = "my_var" locals()[var] = "coucou" print my_var >>coucou But i don't know how to make it on a variable cl...
[ "User setattr:\nclass Controller(object):\n def __init__(self):\n var = 'ma_variable_dynamique'\n setattr(self, var, 'toto')\n\n", "This only explains why what you're doing doesn't work (not how to do it).\nDocumentation from http://docs.python.org/library/functions.html#locals (emphasis mine):\n...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006988709_python.txt
Q: Is it possible to make a contextually-sensitive python context manager that saves, modifies and restores state? I have a pair of python functions that currently flip a global variable between two values. I would like to turn them into context managers so I can use them as with blocks, setting the variable inside t...
Is it possible to make a contextually-sensitive python context manager that saves, modifies and restores state?
I have a pair of python functions that currently flip a global variable between two values. I would like to turn them into context managers so I can use them as with blocks, setting the variable inside the block, but restoring it after. Here's the desired behaviour: >>> MODE 'user' >>> mode_sudo() # Sets MODE to 'sudo...
[ "Do it like this:\nclass mod_user:\n\n def __init__(self):\n global MODE\n self._old_mode = MODE\n MODE = \"user\"\n\n def __enter__(self):\n pass\n\n def __exit__(self, *args, **kws):\n global MODE\n MODE = self._old_mode\n\nMODE = \"sudo\"\n\nwith mod_user():\n ...
[ 7, 2 ]
[]
[]
[ "contextmanager", "python", "state", "stateful" ]
stackoverflow_0006988541_contextmanager_python_state_stateful.txt
Q: Return list of words from a list of lines with regexp I'm running the following code on a list of strings to return a list of its words: words = [re.split('\\s+', line) for line in lines] However, I end up getting something like: [['import', 're', ''], ['', ''], ['def', 'word_count(filename):', ''], ...] As oppo...
Return list of words from a list of lines with regexp
I'm running the following code on a list of strings to return a list of its words: words = [re.split('\\s+', line) for line in lines] However, I end up getting something like: [['import', 're', ''], ['', ''], ['def', 'word_count(filename):', ''], ...] As opposed to the desired: ['import', 're', '', '', '', 'def', 'wo...
[ ">>> import re\n>>> from itertools import chain\n>>> lines = [\"hello world\", \"second line\", \"third line\"]\n>>> words = chain(*[re.split(r'\\s+', line) for line in lines])\n\nThis will give you an iterator that can be used for looping through all words:\n>>> for word in words:\n... print(word)\n... \nhello\...
[ 4, 1, 0, 0 ]
[]
[]
[ "list_comprehension", "python", "python_3.x", "regex" ]
stackoverflow_0002586326_list_comprehension_python_python_3.x_regex.txt
Q: MySQL-Python Installation Error: Possible Architecture Incompatibility? I am attempting to set up my Django virtualenv production environment on a Linux shared host server. Installing python packages using pip goes fine until I try to install Mysql-Python, which crashes. Does anyone know why this is failing? Looki...
MySQL-Python Installation Error: Possible Architecture Incompatibility?
I am attempting to set up my Django virtualenv production environment on a Linux shared host server. Installing python packages using pip goes fine until I try to install Mysql-Python, which crashes. Does anyone know why this is failing? Looking through the error log, I think it's an architecture incompatibility betwee...
[ "If you can't get the same architecture through pip or your package manager, you will probably need to either recompile Python (which you might consider anyway -- Python 2.4 is old), or MySQLdb. \nUnfortunately, a lot of Python libraries are not cross-compatible between i386 and x86_64 -- I've actually had exactly ...
[ 0 ]
[]
[]
[ "linux", "mysql_python", "python" ]
stackoverflow_0006987957_linux_mysql_python_python.txt
Q: Securing RESTapi in flask The app I'm deving uses a lot of ajax calls. Unfortunately I hit a snag when researching on how to restrict access to the api. For example: i have table that does an ajax call to http://site/api/tasks/bob i need to make sure that only bob, logged in, can read that table (otherwise somebo...
Securing RESTapi in flask
The app I'm deving uses a lot of ajax calls. Unfortunately I hit a snag when researching on how to restrict access to the api. For example: i have table that does an ajax call to http://site/api/tasks/bob i need to make sure that only bob, logged in, can read that table (otherwise somebody who knows the pattern might ...
[ "The thousand-foot view is you need to authenticate the user either with:\nA) HTTP-Auth (either basic or digest) on each request.\nB) Server-side sessions. (The user authenticates and receives a session key - their user information is stored in the session backend on the server, attached to that key Once they have ...
[ 14 ]
[]
[]
[ "flask", "python", "rest", "restful_authentication" ]
stackoverflow_0006988977_flask_python_rest_restful_authentication.txt
Q: Why is GCC ignoring ARCHFLAGS in Snow Leopard? I'm trying to install AMFAST in a virtual_env location based on a dependencies file. I have export ARCHFLAGS="-arch x86_64" in my local .profile, and have confirmed its presence by running env and seeing it listed. However, whenever I run PIP targeting the virtual env...
Why is GCC ignoring ARCHFLAGS in Snow Leopard?
I'm trying to install AMFAST in a virtual_env location based on a dependencies file. I have export ARCHFLAGS="-arch x86_64" in my local .profile, and have confirmed its presence by running env and seeing it listed. However, whenever I run PIP targeting the virtual environment, gcc is set to target i386 and ppc. I've a...
[ "Most likely the problem is that the ARCHFLAGS environment variable is not being passed through by sudo. By default, some versions of sudo filter out most env variables as a security measure (see man sudo). Try running it this way:\nsudo ARCHFLAGS=\"-arch x86_64\" pip install -E ~/Documents/project/project_env -r...
[ 14 ]
[]
[]
[ "gcc", "macos", "pip", "python", "virtualenv" ]
stackoverflow_0006988528_gcc_macos_pip_python_virtualenv.txt
Q: Python...Lambda not working? I was going through the Python tutorials and I decided to create a little exercise for myself with the "Lambda" tool. It's a basic square root calculator. However, when I try to run it, it doesn't return a number. Here's how it looks so far. x = int(raw_input("Enter number:")) def pow...
Python...Lambda not working?
I was going through the Python tutorials and I decided to create a little exercise for myself with the "Lambda" tool. It's a basic square root calculator. However, when I try to run it, it doesn't return a number. Here's how it looks so far. x = int(raw_input("Enter number:")) def power(n): return lambda x: x**n ...
[ "What do you mean by it doesn't work? Did you just forget to do:\nprint sqrt(x)\n\ninstead of just\nsqrt(x)\n\n?\n", "This is correct program. I think you forgot to print the result.\nChange last line to\nprint sqrt(x)\n\nand you should get what you want.\n" ]
[ 6, 3 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0006989214_lambda_python.txt
Q: Python unpack 2-dimensional list of named tuples I have a 2-dimensional list of named tuples (let's say that each tuple has N values), and I want to unpack them into N different 2-dimensional lists where each unpacked 2-D list is composed entirely of a single attribute from the original list. For example if I have...
Python unpack 2-dimensional list of named tuples
I have a 2-dimensional list of named tuples (let's say that each tuple has N values), and I want to unpack them into N different 2-dimensional lists where each unpacked 2-D list is composed entirely of a single attribute from the original list. For example if I have this 2-D list: >>> combo = namedtuple('combo', 'i, f,...
[ "Functional programming to the rescue? It's essentially a cleaner version of nesting the zips:\ndef fmap_element(f, el):\n return f(el)\n\ndef fmap_list(f, l):\n return [fmap_element(f, el) for el in l)]\n\ndef fmap_lol(f, lol):\n return [fmap_list(f,l) for l in lol]\n\ndef split_nt_lol(nt_lol):\n retur...
[ 3, 2, 1, 0 ]
[]
[]
[ "iterable_unpacking", "namedtuple", "nested_lists", "python", "tuples" ]
stackoverflow_0006989193_iterable_unpacking_namedtuple_nested_lists_python_tuples.txt
Q: Can't upload file to App Engine "list index out of range" I am trying to updload a picture from a Phonegap application to my Python App Engine project. The phone app trys to upload the file but App engine returns a "list index out of range" error. I have the following code on the App Engine side to handle the fil...
Can't upload file to App Engine "list index out of range"
I am trying to updload a picture from a Phonegap application to my Python App Engine project. The phone app trys to upload the file but App engine returns a "list index out of range" error. I have the following code on the App Engine side to handle the files, class UploadHandler(blobstore_handlers.BlobstoreUploadHandl...
[ "You need to generate the upload url via blobstore.create_upload_url('/upload'). Right now you are making a multi-part POST directly your upload handler url. The intermediate url is critical because it generates a Blobstore key and adds it to the MIME header before passing it to the handler.\n", "I don't know an...
[ 4, 0 ]
[]
[]
[ "cordova", "google_app_engine", "python" ]
stackoverflow_0006988557_cordova_google_app_engine_python.txt
Q: RegEx Tokenizer: split text into words, digits, punctuation, and spacing (do not delete anything) I almost found the answer to this question in this thread (samplebias's answer); however I need to split a phrase into words, digits, punctuation marks, and spaces/tabs. I also need this to preserve the order in which...
RegEx Tokenizer: split text into words, digits, punctuation, and spacing (do not delete anything)
I almost found the answer to this question in this thread (samplebias's answer); however I need to split a phrase into words, digits, punctuation marks, and spaces/tabs. I also need this to preserve the order in which each of these things occurs (which the code in that thread already does). So, what I've found is somet...
[ "I think that something like this should work for you. There is probably more in that regex than there needs to be, but your requirements are somewhat vague and don't exactly match up with the expected output you provided.\n>>> txt = \"Today it's \\t07.May 2011. Or 2.999.\"\n>>> p = re.compile(r\"\\d+|[-'a-z]+|[ ]...
[ 4, 0, 0 ]
[]
[]
[ "nltk", "python", "regex", "tokenize" ]
stackoverflow_0006987356_nltk_python_regex_tokenize.txt
Q: Named Entity Recognition from personal Gazetter using Python I try to do named entity recognition in python using NLTK. I want to extract personal list of skills. I have the list of skills and would like to search them in requisition and tag the skills. I noticed that NLTK has NER tag for predefine tags like Perso...
Named Entity Recognition from personal Gazetter using Python
I try to do named entity recognition in python using NLTK. I want to extract personal list of skills. I have the list of skills and would like to search them in requisition and tag the skills. I noticed that NLTK has NER tag for predefine tags like Person, Location etc. Is there a external gazetter tagger in Python I c...
[ "I haven't used NLTK enough recently, but if you have words that you know are skills, you don't need to do NER- just a text search.\nMaybe use Lucene or some other search library to find the text, and then annotate it? That's a lot of work but if you are working with a lot of data that might be ok. Alternatively, y...
[ 1, 1 ]
[]
[]
[ "named_entity_recognition", "nlp", "nltk", "python" ]
stackoverflow_0005084578_named_entity_recognition_nlp_nltk_python.txt
Q: cygwin hadoop map-reduce problem I am having problem getting map/reduce example to work on cygwin: http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/ Under cygwin, passing -mapper=mapper.py result in "CreateProcess error=193, %1 is not a valid Win32 application" I try to use -mapp...
cygwin hadoop map-reduce problem
I am having problem getting map/reduce example to work on cygwin: http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/ Under cygwin, passing -mapper=mapper.py result in "CreateProcess error=193, %1 is not a valid Win32 application" I try to use -mapper="python mapper.py", it give error: ...
[ "I have had success with that tutorial under Cygwin. I am using hadoop-0.20.2, under Cygwin 1.7.9-1 on WinXP. I haven't seen your exact message ... I'm answering, though, because I did have some trouble with the -mapper option and solved it by putting the python scripts in the /tmp directory. I saw some error ...
[ 1 ]
[]
[]
[ "cygwin", "hadoop", "mapreduce", "python" ]
stackoverflow_0006039961_cygwin_hadoop_mapreduce_python.txt
Q: urllib2 javascript redirect issue import urllib2,urllib data = urllib.urlencode({"username" : "usr", "password" : "pass", "lang" : "eng", "usertype" : "cashier", "submit" : "Enter"}) req = urllib2.Request("https://website/index.php", data) opener = urllib2.build_opener() response = opener.open(req) the_page = res...
urllib2 javascript redirect issue
import urllib2,urllib data = urllib.urlencode({"username" : "usr", "password" : "pass", "lang" : "eng", "usertype" : "cashier", "submit" : "Enter"}) req = urllib2.Request("https://website/index.php", data) opener = urllib2.build_opener() response = opener.open(req) the_page = response.read() print the_page OUTPUT: <s...
[ "First, try delivering a stern lecture to the webmaster about graceful degradation and web standards.\nIf that fails, then you ultimately have two options:\n\nExtract the redirection location using a regular expression. (Pro: This is easy. Cons: This won't work if the redirection URL is built using JavaScript, as...
[ 2 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0006989648_python_urllib_urllib2.txt
Q: Python packages for editing images I am wondering if there are any python packages out there for taking multiple graphs, saved in a png format, and editing their dimensions, and saving them in a new image? I want to have multiple graphs in a constant form, for when I have to manually add them to slides. A: The ...
Python packages for editing images
I am wondering if there are any python packages out there for taking multiple graphs, saved in a png format, and editing their dimensions, and saving them in a new image? I want to have multiple graphs in a constant form, for when I have to manually add them to slides.
[ "The standard Python imaging library for edits like these is...\nwell, the Python Imaging Library!\n", "As another poster said, I'd recommend using the PIL. You could do something like this:\nfrom PIL import Image\n\nin_filename = 'sample.png'\nout_filename = 'sample_small.png'\noutput_res = (320, 240)\n\nim = Im...
[ 7, 3 ]
[]
[]
[ "data_visualization", "photo", "python" ]
stackoverflow_0006989151_data_visualization_photo_python.txt
Q: GTK Named Icons: Load while running from source, during development I have written a GTK app in Python (using PyGObject). I'm confused about how to handle deployment, specifically icons. I understand that in most cases, I would be able to load my images from a specific path; however, the recommended way seems to b...
GTK Named Icons: Load while running from source, during development
I have written a GTK app in Python (using PyGObject). I'm confused about how to handle deployment, specifically icons. I understand that in most cases, I would be able to load my images from a specific path; however, the recommended way seems to be to register icons as named icons with the system, so they can be themed...
[ "If you're going to support running from the source directory, then your executable is already going to have to deal with a range of path-based issues. Fixing icon theme lookups is just another step in this process.\nIf you already have a subdirectory structured as required by the icon theme spec, then all you shou...
[ 3, 0 ]
[]
[]
[ "gtk", "icons", "python" ]
stackoverflow_0006973774_gtk_icons_python.txt
Q: What does test_func and view_func do in Python / Django? I'm trying to break-down the following code in Django to figure out what it's doing and edit it if necessary, but I can't quite figure out what a few of these functions are doing or where they're coming from. Are test_func and view_func Django specific or ar...
What does test_func and view_func do in Python / Django?
I'm trying to break-down the following code in Django to figure out what it's doing and edit it if necessary, but I can't quite figure out what a few of these functions are doing or where they're coming from. Are test_func and view_func Django specific or are these built-in python functions? Conclusion: I'm not sure ho...
[ "view_func is a Django view. test_func is a function \"that checks that the user passes the given test\". \nSo, you write a function that asks for something from the user, and returns True if they pass. Then you pass that function to user_passes_test and it creates a decorator you can use to first test a user befor...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006989762_django_python.txt
Q: How do I find the path with the biggest sum of weights in a weighted graph? I have a bunch of objects with level, weight and 0 or more connections to objects of the next levels. I want to know how do I get the "heaviest" path (with the biggest sum of weights). I'd also love to know of course, what books teach me h...
How do I find the path with the biggest sum of weights in a weighted graph?
I have a bunch of objects with level, weight and 0 or more connections to objects of the next levels. I want to know how do I get the "heaviest" path (with the biggest sum of weights). I'd also love to know of course, what books teach me how to deal with graphs in a practical way.
[ "Your graph is acyclic right? (I presume so, since a node always points to a node on the next level). If your graph can have arbritrary cycles, the problem of finding the largest path becomes NP-complete and brute force search becomes the only solution.\nBack to the problem - you can solve this by finding, for each...
[ 6, 2, 2, 0 ]
[]
[]
[ "algorithm", "graph", "python" ]
stackoverflow_0006989855_algorithm_graph_python.txt
Q: What limitations have closures in Python compared to language X closures? Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and...
What limitations have closures in Python compared to language X closures?
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more. Seeing a code example...
[ "The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:\n>>> def outer(x): \n... def inner_reads():\n... # Will return outer's 'x'.\n... return x\n... def inner_writes(y):\n... # Will assign to a local '...
[ 45, 6, 6, 5, 2, 2 ]
[ "The better workaround until 3.0 is to include the variable as a defaulted parameter in the enclosed function definition:\n\ndef f()\n x = 5\n def g(y, z, x=x):\n x = x + 1\n\n" ]
[ -2 ]
[ "closures", "python" ]
stackoverflow_0000141642_closures_python.txt
Q: Error on accessing iteritems() of an imported variable I'm using Jython if that's relevant. util.py: globals = {} #... globals["foo"] = "bar" globals["baz"] = "qux" main.py: import util for key, value in util.globals.iteritems(): print "Key: %s, Value: %s" % (key, value) My IDE (PyDev) underlines only 'iteri...
Error on accessing iteritems() of an imported variable
I'm using Jython if that's relevant. util.py: globals = {} #... globals["foo"] = "bar" globals["baz"] = "qux" main.py: import util for key, value in util.globals.iteritems(): print "Key: %s, Value: %s" % (key, value) My IDE (PyDev) underlines only 'iteritems' and tells me Undefined variable from import: iteritems...
[ "It thinks you're taking about org.python.util (or, a less likely possibility, distutils.util) because the modules have the same name, and it knows those imports don't exist there.\nYou also shouldn't ever use the name globals because there is a builtin called globals().\nRename the module and the variable and you...
[ 1 ]
[]
[]
[ "import", "jython", "pydev", "python" ]
stackoverflow_0006990224_import_jython_pydev_python.txt
Q: Float value in Tkinter canvas coordinates How I can use float coordinates when I create a canvas object? For example: from Tkinter import * import math main=Tk() w=Canvas(main, height=100, width=100) w.grid(row=0, column=0) for y in range(100): for x in range(100): if y...
Float value in Tkinter canvas coordinates
How I can use float coordinates when I create a canvas object? For example: from Tkinter import * import math main=Tk() w=Canvas(main, height=100, width=100) w.grid(row=0, column=0) for y in range(100): for x in range(100): if y==math.sin(x): w.create_oval(x,...
[ "You've got several problems.\n\nsin(x) will never be greater than 1 or less than -1, so it makes no sense to check y up to 100. Your whole loop structure is wrong.\nIf you want to match x to integer values of sin(x) (1, 0, and -1), you need to multiply x by math.pi/2\nBecause of the way floating point math works, ...
[ 0 ]
[]
[]
[ "canvas", "floating_point", "python", "tkinter" ]
stackoverflow_0006990293_canvas_floating_point_python_tkinter.txt
Q: Eliminating rows with a specific value in a column using Python How could I delete the rows which have '0' as a value on 5th column? Or even better, Can we choose the range (ie. remove the rows which have values between -50 and 30 on 5th column)? data looks like this: 0 4028.44 4544434.50 -6.76 -117.00 0....
Eliminating rows with a specific value in a column using Python
How could I delete the rows which have '0' as a value on 5th column? Or even better, Can we choose the range (ie. remove the rows which have values between -50 and 30 on 5th column)? data looks like this: 0 4028.44 4544434.50 -6.76 -117.00 0.0002 0.12 0 4028.50 3455014.50 -5.86 0 0.0003 0.39 ...
[ "goodrows = [row for row in data if row.split()[4] != '0']\n\nor \ngoodrows = [row for row in data if not (-50 <= float(row.split()[4]) <= 30)]\n\nEdit:\nIf your data is actually in a NumPy array, which your comment seems to indicate even if your post didn't:\ngoodrows = [row for row in data if row[4] != 0]\n\nor \...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006990141_python.txt
Q: Get socket for urllib2.urlopen return value for HTTP I'm trying to do asynchronous downloading of files using urllib2 but have no succeeded in finding out the socket (or its fileno) to wait for new data for for HTTP requests. Here's what I've already tried. >>> from urllib2 import urlopen >>> from select import se...
Get socket for urllib2.urlopen return value for HTTP
I'm trying to do asynchronous downloading of files using urllib2 but have no succeeded in finding out the socket (or its fileno) to wait for new data for for HTTP requests. Here's what I've already tried. >>> from urllib2 import urlopen >>> from select import select >>> r = urlopen('http://stackoverflow.com/') >>> sele...
[ "See http://www.velocityreviews.com/forums/t512553-re-urllib2-urlopen-broken.html.\n\nThe problem is that urlib2 was changed to wrap an HTTPResponse object\n in a socket._fileobject to get a few more file methods. Except (as\n reported above) HTTPResponse doesn't have a fileno() method, so when\n _fileobject tri...
[ 3 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0006990340_python_urllib_urllib2.txt
Q: Forwarding All Mail Sent to a Domain (Google App Engine) I've built a Python app on Google App Engine which primarily handles incoming mail and does interesting based upon the email address at which the email is received. I would like to use a custom domain for receiving emails as <some text>@<my app name>.appspot...
Forwarding All Mail Sent to a Domain (Google App Engine)
I've built a Python app on Google App Engine which primarily handles incoming mail and does interesting based upon the email address at which the email is received. I would like to use a custom domain for receiving emails as <some text>@<my app name>.appspotmail.com is rather cumbersome. Unfortunately I've been unable ...
[ "It's nothing to do with \"DNS trickery\". You simply have to use a regular mail service - Google Apps will do - that can be configured to forward all incoming mail to a specific address, namely any address your app can receive email on. Your app can determine the original 'To' address by examining the headers.\n" ...
[ 2 ]
[]
[]
[ "dns", "email_forwarding", "google_app_engine", "python" ]
stackoverflow_0006987882_dns_email_forwarding_google_app_engine_python.txt
Q: How can I override the keyboard interrupt? (Python) Is there anyway I can make my script execute one of my functions when Ctrl+c is hit when the script is running? A: Take a look at signal handlers. CTRL-C corresponds to SIGINT (signal #2 on posix systems). Example: #!/usr/bin/env python import signal import sys...
How can I override the keyboard interrupt? (Python)
Is there anyway I can make my script execute one of my functions when Ctrl+c is hit when the script is running?
[ "Take a look at signal handlers. CTRL-C corresponds to SIGINT (signal #2 on posix systems).\nExample:\n#!/usr/bin/env python\nimport signal\nimport sys\ndef signal_handler(signal, frame):\n print(\"You pressed Ctrl+C - or killed me with -2\")\n sys.exit(0)\nsignal.signal(signal.SIGINT, signal_handler)\nprint(...
[ 24, 9, 3 ]
[]
[]
[ "interrupt", "python", "signals" ]
stackoverflow_0006990474_interrupt_python_signals.txt
Q: Using Boost Python with Weak Ptrs? Trying to set up a dependency in C++ with a parent-child relationship. The parent contains the child and the child has a weak pointer to the parent. I would also like to be able to derive from the parent in Python. However, when I do this, I get a weak pointer error connecting up...
Using Boost Python with Weak Ptrs?
Trying to set up a dependency in C++ with a parent-child relationship. The parent contains the child and the child has a weak pointer to the parent. I would also like to be able to derive from the parent in Python. However, when I do this, I get a weak pointer error connecting up this parent-child relationship. C++ cod...
[ "I played with the code without the python stuff.\nThis reproduced the problem:\nParent* p(new Parent);\np->initialize();\n\nThe problem is nothing is holding on to the shared_ptr object.\nThis fixes it:\nboost::shared_ptr<Parent> p(new Parent);\np->initialize();\n\nBoost.Python FAQ : \"When a shared_ptr is convert...
[ 2, 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python", "weak_references" ]
stackoverflow_0001624905_boost_boost_python_c++_python_weak_references.txt
Q: revert/undo/redo/refresh, an `import` in interactive python session Possible Duplicate: How do I unload (reload) a Python module? Would it be possible to 'refresh' an imported module in python? The use case: interactively improving the module; up til now, I always completely restart the interactive session to r...
revert/undo/redo/refresh, an `import` in interactive python session
Possible Duplicate: How do I unload (reload) a Python module? Would it be possible to 'refresh' an imported module in python? The use case: interactively improving the module; up til now, I always completely restart the interactive session to reload my updated sources. Is there a better way?
[ "Supposing a module named foo is already present in the namespace, but you have made some changes in source and you want the new code to be imported, use:\nreload(foo)\n\nThere is a gotcha here: if you have used from foo import bar and you have made subsequent changes in your function bar, then the reload will not ...
[ 4 ]
[]
[]
[ "import", "interactive", "iteration", "python" ]
stackoverflow_0006987653_import_interactive_iteration_python.txt
Q: Python proper code formatting (PEP8) So I just learned about "List Comprehensions" in python. some of these are getting too long for a single line (PEP8) and I'm trying to figure out the best (most readable) way to break these out. I've come up with this questions = [ ( q, q.vote_set.filter(ch...
Python proper code formatting (PEP8)
So I just learned about "List Comprehensions" in python. some of these are getting too long for a single line (PEP8) and I'm trying to figure out the best (most readable) way to break these out. I've come up with this questions = [ ( q, q.vote_set.filter(choice__exact='Y'), q.vote_set.filte...
[ "I would probably do it like this:\nquestions = [(q, \n q.vote_set.filter(choice__exact='Y'), \n q.vote_set.filter(choice__exact='N'), \n request.session.get(str(q.id)))\n for q in questions]\n\nKeep in mind that PEP8 is intended to be used along with your bes...
[ 1, 0, 0, 0 ]
[]
[]
[ "code_formatting", "pep8", "python" ]
stackoverflow_0006990501_code_formatting_pep8_python.txt
Q: Python - How to print a specific text def handler_users_answ(coze, res, type, source): if res: if res.getType() == 'result': aa=res.getQueryChildren() if aa: print 'workz1' for x in aa: m=x.getAttr('jid') if...
Python - How to print a specific text
def handler_users_answ(coze, res, type, source): if res: if res.getType() == 'result': aa=res.getQueryChildren() if aa: print 'workz1' for x in aa: m=x.getAttr('jid') if m: print m so thi...
[ "You can use rpartition to get the part after the last \\ in the string.\n", "a = 'roomname@domain.com/nickname1'\n\nb=a.split('/');\nc=b[1];\n\n", "You can use rsplit which will do the splitting form the right:\na = 'roomname@domain.com/nickname1'\ntry:\n print a.rsplit('/')[1][1]\nexcept IndexError:\n p...
[ 2, 1, 1, 1 ]
[]
[]
[ "printing", "python", "split", "xmpp" ]
stackoverflow_0006987682_printing_python_split_xmpp.txt
Q: Django:Is there a way to use a tree control in my template‏ Hi i wanted to know is there a way through which i could use a tree control in my template I wanted to add something like Student |_Name |_Address |_Contact No I think you guys get the picture...How can i add something like that in my t...
Django:Is there a way to use a tree control in my template‏
Hi i wanted to know is there a way through which i could use a tree control in my template I wanted to add something like Student |_Name |_Address |_Contact No I think you guys get the picture...How can i add something like that in my template...Thanks
[ "This has nothing to do with Django. You can use any HTML/CSS/Javascript in your templates, so just use any script to create your tree control.\nHere is one of jQuery scripts: http://www.boarsoft.com/javascript/dtree/?jdfwkey=97rdf1\nOther examples: http://www.google.lv/search?sourceid=chrome&ie=UTF-8&q=jquery+tree...
[ 2, 1 ]
[]
[]
[ "django", "python", "treecontrol" ]
stackoverflow_0006987994_django_python_treecontrol.txt
Q: Simulating a Google App Engine File Upload in Python I have a Google App Engine app in Python that lets users upload files. After a file has been submitted, I get the file using self.request.get('uploaded_file') I get the filename using self.request.POST['uploaded_file'].filename I'm trying to write a unit te...
Simulating a Google App Engine File Upload in Python
I have a Google App Engine app in Python that lets users upload files. After a file has been submitted, I get the file using self.request.get('uploaded_file') I get the filename using self.request.POST['uploaded_file'].filename I'm trying to write a unit test for it by manually creating a webapp request with the f...
[ "If you're testing your handler, you're probably already creating a Webob request object and passing it to your handler, something like this:\nrequest = webapp.Request({\n \"wsgi.input\": StringIO.StringIO(),\n \"METHOD\": \"POST\",\n})\nresponse = webapp.Response()\nhandler = MyHandler()\nhandler.initialize(...
[ 4, 1 ]
[]
[]
[ "file_upload", "google_app_engine", "python", "unit_testing" ]
stackoverflow_0006990986_file_upload_google_app_engine_python_unit_testing.txt
Q: pyUnit unit testing for Magento a good idea? Today it was suggested to me to use PyUnit with our Magento modules because of its request and response objects. Is there any advantage to using an xUnit testing framework? We would be running Hudson as the CI with Maven along with some PHPUnit and Selenium Tests. I am ...
pyUnit unit testing for Magento a good idea?
Today it was suggested to me to use PyUnit with our Magento modules because of its request and response objects. Is there any advantage to using an xUnit testing framework? We would be running Hudson as the CI with Maven along with some PHPUnit and Selenium Tests. I am currently using the Request and Response controlle...
[ "Magento unit-testing framework: https://github.com/IvanChepurnyi/EcomDev_PHPUnit\n" ]
[ 3 ]
[]
[]
[ "continuous_integration", "magento", "python", "python_unittest", "unit_testing" ]
stackoverflow_0006990604_continuous_integration_magento_python_python_unittest_unit_testing.txt
Q: Find directory of a file in Python If I have the following file: file = '/Users/david542/Desktop/work.txt' I can use os.path.basename(file) to get the file name. What command would I use to get the directory of the file (i.e., to get "/Users/david542/Desktop") ? A: >>> os.path.dirname(os.path.realpath('/Users/d...
Find directory of a file in Python
If I have the following file: file = '/Users/david542/Desktop/work.txt' I can use os.path.basename(file) to get the file name. What command would I use to get the directory of the file (i.e., to get "/Users/david542/Desktop") ?
[ ">>> os.path.dirname(os.path.realpath('/Users/david542/Desktop/work.txt'))\n\n", "os.path.dirname(file) returns the directory of the passed file name. Alternatively, you can use os.path.split(file) which will give you a tuple containing the directory name and the file name in one call.\n", "os.path.dirname(file...
[ 4, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006991539_python.txt
Q: Localized date strftime in Django view I would like to send localized date in JSON from django view Normal text translation via ugettext is OK Following code in view has no effect: translation.activate("ru") print datetime.now().strtime("%B") Output is "August", instead of "Август" I read about python's "loca...
Localized date strftime in Django view
I would like to send localized date in JSON from django view Normal text translation via ugettext is OK Following code in view has no effect: translation.activate("ru") print datetime.now().strtime("%B") Output is "August", instead of "Август" I read about python's "locale" module, but it's named as thread unsafe ...
[ "Finally i used date filter from django templates:\nfrom django.template.defaultfilters import date as _date\nfrom datetime import datetime\n\n_date(datetime.now(), \"d b, D\")\n\n" ]
[ 97 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0006945251_django_localization_python.txt
Q: Need help converting python code to c code Is there any compiler which will help me convert my python code to proper C code? In my python code I am using the xml.dom.minidom module to parse an xml and process the results obtained by ElementsByTagName. I don't know of any such compiler which will help me convert th...
Need help converting python code to c code
Is there any compiler which will help me convert my python code to proper C code? In my python code I am using the xml.dom.minidom module to parse an xml and process the results obtained by ElementsByTagName. I don't know of any such compiler which will help me convert this kind of python code to C code. My intention i...
[ "There are no Python to C translators which would produce human-readable, editable, C source code.\n", "You are looking in the wrong direction. Instead of looking for a generic Python to C compiler to make xml.dom.minidom more efficient, replace the library with lxml which is already compiled C code. The lxml mod...
[ 4, 2 ]
[]
[]
[ "compiler_construction", "python" ]
stackoverflow_0006991923_compiler_construction_python.txt
Q: Django Querying Self-referential Many-To-Many relations I am trying to get a list of all manuscripts in my db, print out the shelfmarks for each of them and in case that they are linked to other manuscripts also print out the shelfmarks of those manuscripts. Here is what my models look like: class MSS(models.Model...
Django Querying Self-referential Many-To-Many relations
I am trying to get a list of all manuscripts in my db, print out the shelfmarks for each of them and in case that they are linked to other manuscripts also print out the shelfmarks of those manuscripts. Here is what my models look like: class MSS(models.Model): shelfmark = models.CharField(max_length=50) MSSLin...
[ "Your models are a bit complicated - you can probably get rid of MSSLink:\nclass MSS(models.Model):\n shelfmark = models.CharField(max_length=50)\n links = models.ManyToManyField('self', symmetrical=False, blank=True)\n\n def __unicode__(self):\n return self.shelfmark\n\nand add this to your templat...
[ 0 ]
[]
[]
[ "django", "many_to_many", "python", "self_reference" ]
stackoverflow_0006989856_django_many_to_many_python_self_reference.txt
Q: Is there any lower layer object manipulation function than "marshal" or "cPickle" in Python? For example, Marshal is still parsing the input data, according to Python source. ..... case TYPE_FALSE: Py_INCREF(Py_False); retval = Py_False; break; case TYPE_TRUE: Py_INCREF(Py_True); retval = Py_T...
Is there any lower layer object manipulation function than "marshal" or "cPickle" in Python?
For example, Marshal is still parsing the input data, according to Python source. ..... case TYPE_FALSE: Py_INCREF(Py_False); retval = Py_False; break; case TYPE_TRUE: Py_INCREF(Py_True); retval = Py_True; break; case TYPE_INT: retval = PyInt_FromLong(r_long(p)); break; case TYPE_INT6...
[ "If you do not really need to serialize Python objects in general, only encode and decode certain specific things, then you might look at the struct module. This module would be used to work directly with byte-strings that represent C structs (example: DNS protocol packets). Similar idea to pack and unpack in Per...
[ 1, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0006952109_c_python.txt
Q: Getting facebook OAuth access_token through Python SDK does not seem to be working, any ideas? According to http://github.com/facebook/python-sdk/blob/master/src/facebook.py , In my canvas application, i can do the following call to get my access_token, which will work because my user has used facebook to login: i...
Getting facebook OAuth access_token through Python SDK does not seem to be working, any ideas?
According to http://github.com/facebook/python-sdk/blob/master/src/facebook.py , In my canvas application, i can do the following call to get my access_token, which will work because my user has used facebook to login: import facebook myDict = facebook.get_user_from_cookie(cookies, app_id, app_secret) # my access_tok...
[ "For this to work, you need to use the Javascript SDK to init the session at which point the python-sdk is able to read the cookies as set by the javascript-sdk.\nSince you are using an IFrame canvas, the cookies set by facebook are not readable by you. In the python-sdk, there is a sample appengine oauth example ...
[ 2, 1, 0, 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0002727118_facebook_python.txt
Q: transferring real time data from a website in python I am programming in Python. I would like to extract real time data from a webpage without refreshing it: http://www.fxstreet.com/rates-charts/currency-rates/ I think the real time data webpage is written in AJAX but I am not quite sure.. I thought about opening ...
transferring real time data from a website in python
I am programming in Python. I would like to extract real time data from a webpage without refreshing it: http://www.fxstreet.com/rates-charts/currency-rates/ I think the real time data webpage is written in AJAX but I am not quite sure.. I thought about opening an internet browser with the program but I do not really k...
[ "To get the data, you'll need to look through the javascript and HTML source to find what URL it's hitting to get the data it's displaying. Then, you can call that URL with urllib or your favorite python library and parse it \nAlso, it may be easier if you use a plugin like Firebug that lets you watch the AJAX re...
[ 1 ]
[]
[]
[ "ajax", "python", "web_scraping" ]
stackoverflow_0006992421_ajax_python_web_scraping.txt
Q: How to install orbited on Mac 10.6 I have tried pypm install orbited but I still get sudo: orbited: command not found when running sudo orbited I downloaded orbited from http://pypi.python.org/pypi/orbited/0.7.10 Where do I put the files to install? Thanks A: Navigate to the directory of the files and then try r...
How to install orbited on Mac 10.6
I have tried pypm install orbited but I still get sudo: orbited: command not found when running sudo orbited I downloaded orbited from http://pypi.python.org/pypi/orbited/0.7.10 Where do I put the files to install? Thanks
[ "Navigate to the directory of the files and then try running the command.\n" ]
[ 0 ]
[]
[]
[ "macos", "orbited", "pypm", "python", "sudo" ]
stackoverflow_0006871470_macos_orbited_pypm_python_sudo.txt
Q: Setting default value for integer field in django models I'm trying to set a default value for the integer field in Django model using models.PositiveSmallIntegerField(default='0') Why isn't it working? A: The default value in your example is set to string ('0'), but it should be integer. Try this instead: mode...
Setting default value for integer field in django models
I'm trying to set a default value for the integer field in Django model using models.PositiveSmallIntegerField(default='0') Why isn't it working?
[ "The default value in your example is set to string ('0'), but it should be integer. Try this instead:\nmodels.PositiveSmallIntegerField(default=0)\n\n" ]
[ 31 ]
[]
[]
[ "django", "django_models", "integer", "python" ]
stackoverflow_0006992364_django_django_models_integer_python.txt
Q: What is the best way to do a find and replace of multiple queries on multiple files? I have a file that has over 200 lines in this format: name old_id new_id The name is useless for what I'm trying to do currently, but I still want it there because it may become useful for debugging later. Now I need to go throug...
What is the best way to do a find and replace of multiple queries on multiple files?
I have a file that has over 200 lines in this format: name old_id new_id The name is useless for what I'm trying to do currently, but I still want it there because it may become useful for debugging later. Now I need to go through every file in a folder and find all the instances of old_id and replace them with new_id...
[ "Use something like multiwordReplace (I've edited it for your situation) with mmap.\nimport os\nimport os.path\nimport re\nfrom mmap import mmap\nfrom contextlib import closing\n\n\nid_filename = 'path/to/id/file'\ndirectory_name = 'directory/to/replace/in'\n\n# read the ids into a dictionary mapping old to new\nwi...
[ 2 ]
[]
[]
[ "performance", "python", "regex", "replace", "search" ]
stackoverflow_0006992545_performance_python_regex_replace_search.txt
Q: Installation error in with byteflow-0.7 I am installing byteflow-0.7 on python 2.6.5 with django 1.3 on windows7(64-bits). Database used is MySQL 5.0.51b on wamp 2.0 server. I installed all the prerequisites well and have run the syncdb command. That run well and the database was created successfully. When I run t...
Installation error in with byteflow-0.7
I am installing byteflow-0.7 on python 2.6.5 with django 1.3 on windows7(64-bits). Database used is MySQL 5.0.51b on wamp 2.0 server. I installed all the prerequisites well and have run the syncdb command. That run well and the database was created successfully. When I run the server and hit the localhost:8000 on my br...
[ "It seems that AdminSite.root had been marked deprecated in Django 1.1 and apparently it is now removed in Django 1.3. So you either have to downgrade Django to 1.0 (as this is what ByteFlow website says in requirements) or use a newer Byteflow version that has this issue fixed.\nPS. Found a fix in a forked repo.\n...
[ 0 ]
[]
[]
[ "django", "django_1.3", "python", "python_2.6" ]
stackoverflow_0006921963_django_django_1.3_python_python_2.6.txt
Q: SQLAlchemy losing timezone information with SQLite I'm having an issue where SQLAlchemy (versions 0.6.4 & 0.6.8) is losing the timezone information from a datetime object when committed to an SQLite database with the column defined with SQLAlchemy's DateTime class. (I realise that SQLAlchemy is converting this to...
SQLAlchemy losing timezone information with SQLite
I'm having an issue where SQLAlchemy (versions 0.6.4 & 0.6.8) is losing the timezone information from a datetime object when committed to an SQLite database with the column defined with SQLAlchemy's DateTime class. (I realise that SQLAlchemy is converting this to a string and back, which is what I believe to be half t...
[ "Python's strptime methods don't support the %z formatting directive, so there would be no way to get the timezone back out of the string in the database. I assume this is why it isn't stored.\nYou have two options. You already mentioned one -- store the timezone in another column.\nThe generally recommended soluti...
[ 7, 1 ]
[]
[]
[ "database", "datetime", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0006991457_database_datetime_python_sqlalchemy_sqlite.txt
Q: Python enforce unicode escape how do I enforce unicode escape in python? I have the unicode string u'aä' or u'a\u00e4' and I want it to be represented as a\u00e4. The solution suggested here doesn't work for me: >>> repr(u'a\u00e4') "u'a\\xe4'" From my understanding the following attempt should be the correct sol...
Python enforce unicode escape
how do I enforce unicode escape in python? I have the unicode string u'aä' or u'a\u00e4' and I want it to be represented as a\u00e4. The solution suggested here doesn't work for me: >>> repr(u'a\u00e4') "u'a\\xe4'" From my understanding the following attempt should be the correct solution (but isn't): >>> u'a\u00e4'.e...
[ "Unicode characters below 256 are always encoded with \\x in their repr()esentation, as it is the least space-consuming.\nNevertheless, they are unicode because of the u' at the start. It is just a matter of representation.\nIf you want it nevertheless, you could do\nprint repr(u'a\\u00e4').replace('\\\\x','\\\\u00...
[ 3 ]
[]
[]
[ "character_encoding", "python", "unicode" ]
stackoverflow_0006992979_character_encoding_python_unicode.txt
Q: Cython with Visual C++ Compiler? Once I've used Cython to generate a C file, how do I use the Visual C++ 2010 compiler to make an EXE? I've tried cython.py Temp.py cl.exe /MD /I "%ProgramFiles%\Python 2.6\include" Temp.c /link /LibPath:"%ProgramFiles%\Python 2.6\libs" but it says LINK : fatal error LNK1561: ...
Cython with Visual C++ Compiler?
Once I've used Cython to generate a C file, how do I use the Visual C++ 2010 compiler to make an EXE? I've tried cython.py Temp.py cl.exe /MD /I "%ProgramFiles%\Python 2.6\include" Temp.c /link /LibPath:"%ProgramFiles%\Python 2.6\libs" but it says LINK : fatal error LNK1561: entry point must be defined and if I ...
[ "By default, Cython does not generate the code for an executable, but for a Python module. For example, it generates an init<modulename>() function, but no main(). This can be changed by supplying the --embed option, as explained in Embedding Cython.\nSee also: Can Cython compile to an EXE? -- one answer even giv...
[ 7 ]
[]
[]
[ "cython", "python", "python_2.6", "visual_studio", "visual_studio_2010" ]
stackoverflow_0006993095_cython_python_python_2.6_visual_studio_visual_studio_2010.txt
Q: Django list all authors by most recent rating Given the following simplified models from the Django docs, I would like to return a list of all of the authors grouped by the rating on their most recent entry, or the most recent prior to some date in the past. class Author(models.Model): name = models.CharFiel...
Django list all authors by most recent rating
Given the following simplified models from the Django docs, I would like to return a list of all of the authors grouped by the rating on their most recent entry, or the most recent prior to some date in the past. class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() ...
[ "Recent is hard to do in vanilla Django without a lot of work (max, average, etc. can all be done with annotations and aggregations).\nI do this with a custom manager something like:\nclass AuthorManager(models.Manager):\n def with_recent_rating(self):\n return super(AuthorManager, self).get_query_set().extra(\...
[ 2, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006976792_django_python.txt
Q: Calling C function from ctypes: class instance can be None I have a C library with several datatypes which I have wrapped with Python and ctypes - works very well! In C I have the following (schematic) code: typedef struct type1_struct type1_t; typedef struct type2_struct type2_t; void some_function( type1_t ...
Calling C function from ctypes: class instance can be None
I have a C library with several datatypes which I have wrapped with Python and ctypes - works very well! In C I have the following (schematic) code: typedef struct type1_struct type1_t; typedef struct type2_struct type2_t; void some_function( type1_t *t1 , type2_t *t2) { if (t2 == NULL) { // Do whatever...
[ "The from_param() method needs to be a class method, but you have defined it as an instance method. Change it to a classmethod and check whether the parameter is None.\nSomething like (untested):\nclass Type1:\n @classmethod\n def from_param(cls, obj):\n if obj is None:\n return c_void_p()\n ...
[ 3, 0 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0006992903_c_ctypes_python.txt
Q: Backspace with `raw_input` in Python I am using raw_input() like this: while True: print "MC ID (CTRL-D = done, 0 = sets, ? = lookup):", try: mcid=raw_input() except: print break # evaluate user input # ... Now if you type something, e.g. abc and hit backspace to correct something, as soon a...
Backspace with `raw_input` in Python
I am using raw_input() like this: while True: print "MC ID (CTRL-D = done, 0 = sets, ? = lookup):", try: mcid=raw_input() except: print break # evaluate user input # ... Now if you type something, e.g. abc and hit backspace to correct something, as soon as you remove the a, the output from print ...
[ "Try this:\nmcid = raw_input(\"MC ID (CTRL-D = done, 0 = sets, ? = lookup): \")\n\n", "I cannot reproduce it, but you can try this way:\nmcid=raw_input(\"MC ID (CTRL-D = done, 0 = sets, ? = lookup):\")\n\n" ]
[ 4, 1 ]
[]
[]
[ "backspace", "python", "raw_input" ]
stackoverflow_0006993564_backspace_python_raw_input.txt
Q: How do I see "print"s from a python tkinter app converted to a .exe? I built a tkinter app, then I converted it into a .exe. When I run the .exe, no console shows up. But in the script, I wrote several print "stuff" statements, how can I display them when I run the .exe? A: Run the .exe from the console. Easiest...
How do I see "print"s from a python tkinter app converted to a .exe?
I built a tkinter app, then I converted it into a .exe. When I run the .exe, no console shows up. But in the script, I wrote several print "stuff" statements, how can I display them when I run the .exe?
[ "Run the .exe from the console.\nEasiest way to start the console is Start -> Run -> cmd.exe\nThen cd to the directory where the .exe is, and run the .exe.\nEdit: If you used py2exe, you may need to pass your script to setup() as the console argument:\nsetup(console=['hello.py'])\n\nThis will tell it you want conso...
[ 2 ]
[]
[]
[ "console", "py2exe", "python", "tkinter" ]
stackoverflow_0006993690_console_py2exe_python_tkinter.txt
Q: TestSuite with testsuites and testcases I need to make a big python suitecase consisted of other suitcases and testcase which I have already made to execute together. How do I do this? For example, here there is a suitecase (suiteFilter.py) which I want to add: import testFilter1 import testFilter2 import unittes...
TestSuite with testsuites and testcases
I need to make a big python suitecase consisted of other suitcases and testcase which I have already made to execute together. How do I do this? For example, here there is a suitecase (suiteFilter.py) which I want to add: import testFilter1 import testFilter2 import unittest import sys def suite(): return unittes...
[ "You could give some additional information like the structure of your program / test cases and suites. The way I do it is define a suite() for each module. So I have say for UserServiceTest module:\ndef suite():\n \"\"\"\n Gather all the tests from this module in a test suite.\n \"\"\"\n test_suite...
[ 12 ]
[]
[]
[ "python", "selenium", "test_suite", "testcase", "unit_testing" ]
stackoverflow_0006993711_python_selenium_test_suite_testcase_unit_testing.txt
Q: copy list in python As I am trying to make a copy of a list and do some stuff with the copy of the list. Somehow my original list is modified as well. I already looked at different memory allocatinos and different ways of assigning the lists. So far no luck... Any ideas? row = 0 column = 0 table1 = cop...
copy list in python
As I am trying to make a copy of a list and do some stuff with the copy of the list. Somehow my original list is modified as well. I already looked at different memory allocatinos and different ways of assigning the lists. So far no luck... Any ideas? row = 0 column = 0 table1 = copy.copy(table[:]) tem...
[ "Your original list contains inner lists:\n[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0], \n ['BBB', 1, 1, 0, 26, 28, 0], ...\n]\n\nThe inner list are actually stored as references, i.e.:\n[ location-of-list-0, \n location-of-list-1, ...\n]\n\nWhen you copied the list, you actually copied a list of references to the same...
[ 12, 4, 2, 0 ]
[]
[]
[ "list", "memory", "multidimensional_array", "python" ]
stackoverflow_0006993531_list_memory_multidimensional_array_python.txt
Q: How to refer overriden class functions in python I know C++ and Java and I am unfamiliar with Pythonic programming. So maybe it is bad style what I am trying to do. Consider fallowing example: class foo: def a(): __class__.b() # gives: this is foo bar.b() # gives: this is ba...
How to refer overriden class functions in python
I know C++ and Java and I am unfamiliar with Pythonic programming. So maybe it is bad style what I am trying to do. Consider fallowing example: class foo: def a(): __class__.b() # gives: this is foo bar.b() # gives: this is bar foo.b() # gives: this is foo ...
[ "What you want is for a to be a classmethod.\nclass Foo(object):\n @classmethod\n def a(cls):\n Foo.b() # gives: this is foo\n Bar.b() # gives: this is bar\n cls.b() # gives: this is bar\n @staticmethod\n def b():\n print(\"this is foo\")\n\nclass Bar(Foo):\n @staticmethod...
[ 5, 0 ]
[]
[]
[ "class_method", "inheritance", "oop", "python", "static_functions" ]
stackoverflow_0006994093_class_method_inheritance_oop_python_static_functions.txt
Q: Bundling python(".py")files along with java class files for a web application We are having an java we application where flex is front end and we use Axis2 for web services.So what ever the java code for services we bundle java classes as an aar file ans supply to axis2 with which flex interacts. Recently we had a...
Bundling python(".py")files along with java class files for a web application
We are having an java we application where flex is front end and we use Axis2 for web services.So what ever the java code for services we bundle java classes as an aar file ans supply to axis2 with which flex interacts. Recently we had a req where we need to use some python code from java, So Eclipse, i setup by adding...
[ "Have a look at the maven-jython-compile-plugin and its demo project at http://mavenjython.sourceforge.net/ . It allows bundling jython with dependencies into a standalone jar.\n" ]
[ 0 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0006921809_java_jython_python.txt
Q: Add python module to JAR classpath in Eclipse I have a Java project that utilizes Jython to interface with a Python module. With my configuration, the program runs fine, however, when I export the project to a JAR file, I get the following error: Jar export finished with problems. See details for additional inform...
Add python module to JAR classpath in Eclipse
I have a Java project that utilizes Jython to interface with a Python module. With my configuration, the program runs fine, however, when I export the project to a JAR file, I get the following error: Jar export finished with problems. See details for additional information. Fat Jar Export: Could not find class-path ...
[ "Figured it out, had to add the source folder with the Python module in it as a class folder in the Build Path project properties. Not sure if this next part is necessary or not, but since the module is not compiled, I added the folder again as \"Attached Source\" after adding the class folder.\n", "Have a look a...
[ 1, 1 ]
[]
[]
[ "eclipse", "jar", "java", "jython", "python" ]
stackoverflow_0006652492_eclipse_jar_java_jython_python.txt
Q: Using map function instead of for loop I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23": Numb...
Using map function instead of for loop
I want to find number of lines and words in a file. My input file "testfile.txt' has 6 lines and 23 words. For finding number of words I am using map() function instead of the for loop. When I executed this code it shows the memory location of the object instead of "23": Number of words = What am I doing wrong here? d...
[ "after:\nnumwords = map(wordcount, lines)\n\nnumwords is a list of None the same length as lines as wordcount returns None\nfor line in lines:\n words = line.split()\n numwords += len(words)\n\nwould be better and more pythonic\n", "In Python 3, map is an iterator: (akin: itertools.imap)\nclass map(object)\...
[ 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "map", "python" ]
stackoverflow_0005633282_map_python.txt
Q: Get the Records which contains a word (Case insensitive) in Gql? Is it possible to write a single Gql Query for retrieving the record which contains a searching string? Data store Contains following Records: addax Crest Addrest Drest Armrest admix I need to get the Records which contains the word "Rest" (Case in...
Get the Records which contains a word (Case insensitive) in Gql?
Is it possible to write a single Gql Query for retrieving the record which contains a searching string? Data store Contains following Records: addax Crest Addrest Drest Armrest admix I need to get the Records which contains the word "Rest" (Case insensitive)
[ "Full-Text-Search is not supported in AE yet, it's on the roadmap so we can look forward to it.\nIf you are just trying to match single words in a case insensitive way, you could store all your words in a ListProperty, and ensure they are always stored in lowercase. That way you could easily query for them in a cas...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python" ]
stackoverflow_0006994266_google_app_engine_gql_gqlquery_python.txt
Q: Programmatically enter password on prompt within Python? I need functionality similar to the Unix expect from within a Python script, as an external executable is prompting for password. I am currently doing this: p = subprocess.Popen("execA",stdout=subprocess.PIPE,stderr=subprocess.STDOUT) where execA is prompti...
Programmatically enter password on prompt within Python?
I need functionality similar to the Unix expect from within a Python script, as an external executable is prompting for password. I am currently doing this: p = subprocess.Popen("execA",stdout=subprocess.PIPE,stderr=subprocess.STDOUT) where execA is prompting for password. I'd like to wrap it with "expect" to supply s...
[ "Pexpect is the one I've used in the past to do things like this.\nThough depending on the program it might be sufficient to just write to it's stdin?\n", "Those kind of programs typically access the tty directly and put it in \"raw\" mode. So the stdio pipes don't work. You need to spawn the subprocess in a pty....
[ 1, 0 ]
[]
[]
[ "expect", "macos", "python" ]
stackoverflow_0006992706_expect_macos_python.txt
Q: Need to make my python web application self-monitoring (keep-alive) like a daemon I wrote my python web application with BaseHTTPServer. It is intended to run in localhost and serve localhost requests. It is intended to be hosted in a major VPS. So I need some reliable way to keep it alive. Apache (and what's bein...
Need to make my python web application self-monitoring (keep-alive) like a daemon
I wrote my python web application with BaseHTTPServer. It is intended to run in localhost and serve localhost requests. It is intended to be hosted in a major VPS. So I need some reliable way to keep it alive. Apache (and what's being served under it) can easily re-spawn when it's stopped. Similarly, I can make CRON do...
[ "First approach would be using supervisor. Another option is to use python-daemon and create a system-wide init-script that is started when system boots.\nAlso, for a quick hack - you can run the app inside the detachable shell like screen or tmux.\n", "What you need is a process monitor, like the previously ment...
[ 4, 3, 0 ]
[]
[]
[ "daemon", "python" ]
stackoverflow_0006994236_daemon_python.txt
Q: How do I use the TarFile dereference flag in Python 2.4? I wrote a script that collects all our log files to one tar file. The problem is that it doesn't contain soft link's data. I tried to use the dereference flag but it is not recognized for python 2.4.3. I can't use the command line since there's a length lim...
How do I use the TarFile dereference flag in Python 2.4?
I wrote a script that collects all our log files to one tar file. The problem is that it doesn't contain soft link's data. I tried to use the dereference flag but it is not recognized for python 2.4.3. I can't use the command line since there's a length limit and I want to support many log files. user ~/Desktop]$pytho...
[ "According to the Python 2.4 docs dereference = True is supported. It appears to have been supported since tarfile was added in Python 2.3.\nUnless you're on a non-Posix system (Windows) you must be doing it wrong. Post your code and the error you get with dereference = True so we can tell you what that is.\nAlso, ...
[ 3, 0 ]
[]
[]
[ "python", "python_2.x", "tar" ]
stackoverflow_0006996224_python_python_2.x_tar.txt
Q: Can't execute mysql insert using pythons mysqldb This is my first question on stackoverflow! I'm currently programming a steamcommunity crawler, which crawls through the steam profiles and saves things like owned games, steamname, friends, ... But when I try to run the insert command it just does NOTHING. if not ...
Can't execute mysql insert using pythons mysqldb
This is my first question on stackoverflow! I'm currently programming a steamcommunity crawler, which crawls through the steam profiles and saves things like owned games, steamname, friends, ... But when I try to run the insert command it just does NOTHING. if not self.check_user('games', id): print "insert" self....
[ "\nadd \"COMMIT\" at the end of command\nfor example:\ncursor.execute(\"INSERT INTO games (userid) VALUES(%s);COMMIT;\" % id)\n\nset autocommit by add the second line\ndb = MySQLdb.connect(user='username', db=dbName,) # exmaple\ndb.autocommit(1) # enable auto commit\n\nadd commit() after transaction\ndb.commit()\n\...
[ 6, 5 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0006726521_mysql_mysql_python_python.txt
Q: Virtualenv virtualenvwrapper and _imaging So my Mac is correctly set up with _imaging but as soon as I create a new virtualenv with mkvirtualenv myproject and run the python interpreter import _imaging Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Python/2.7/...
Virtualenv virtualenvwrapper and _imaging
So my Mac is correctly set up with _imaging but as soon as I create a new virtualenv with mkvirtualenv myproject and run the python interpreter import _imaging Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Python/2.7/site-packages/PIL/_imaging.so, 2): Symbol not f...
[ "You will need to install it from source, see this google article. Do NOT use Mac Ports as that way lies madness.\n", "Do not believe the previous comment, Macports Python + PIL works just fine :)\nBased on error message you are probably somehow mixing OSX own Python and libraries with Macports ones (wrong versi...
[ 1, 1, 1, 0 ]
[]
[]
[ "django", "imaging", "python", "virtualenv", "virtualenvwrapper" ]
stackoverflow_0006960785_django_imaging_python_virtualenv_virtualenvwrapper.txt
Q: web2py Ajax search I'm trying to use an ajax search slice for my website that I found here: http://www.web2pyslices.com/slices/take_slice/51 But for some reason I keep getting the error: IndexError: list index out of range Here is my version of the code: default.py (controller) def index(): listings = db().select...
web2py Ajax search
I'm trying to use an ajax search slice for my website that I found here: http://www.web2pyslices.com/slices/take_slice/51 But for some reason I keep getting the error: IndexError: list index out of range Here is my version of the code: default.py (controller) def index(): listings = db().select(db.listing.ALL, orderby...
[ "If the following is your index() code:\ndef index():\n listings = db().select(db.listing.ALL, orderby=db.listing.first_name)\n return dict(listings=listings, livesearch=livesearch())\n\nthen, if you visit index.html page and livesearch() will be called, but at this time, request.vars.values() is empty, so In...
[ 1, 1 ]
[]
[]
[ "ajax", "python", "search", "web2py" ]
stackoverflow_0006990860_ajax_python_search_web2py.txt
Q: xmlrpclib: dictionary key must be string type error I would like some advice. I have encountered the following error in Python 2.6: Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> s.Search(query) File "/usr/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__sen...
xmlrpclib: dictionary key must be string type error
I would like some advice. I have encountered the following error in Python 2.6: Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> s.Search(query) File "/usr/lib/python2.6/xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.6/xmlrpclib...
[ "The doc of xmlrpclib state that for a python dictionary to be marshaled through XML the keys should be strings:\n\nA Python dictionary. Keys must be strings, values may be any\n conformable type. Objects of user-defined classes can be passed in;\n only their dict attribute is transmitted.\n\nSo you should change...
[ 6 ]
[]
[]
[ "dictionary", "python", "unicode", "xmlrpclib" ]
stackoverflow_0006996585_dictionary_python_unicode_xmlrpclib.txt
Q: How do you get default headers in a urllib2 Request? I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer. However, other "standard" HTTP headers get added to the...
How do you get default headers in a urllib2 Request?
I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer. However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. Whe...
[ "If you want to see the literal HTTP request that is sent out, and therefore see every last header exactly as it is represented on the wire, then you can tell urllib2 to use your own version of an HTTPHandler that prints out (or saves, or whatever) the outgoing HTTP request.\nimport httplib, urllib2\n\nclass MyHTTP...
[ 10, 5, 2, 2, 2, 0, 0 ]
[ "It should send the default http headers (as specified by w3.org) alongside the ones you specify. You can use a tool like WireShark if you would like to see them in their entirety.\nEdit:\nIf you would like to log them, you can use WinPcap to capture packets sent by specific applications (in your case, python). You...
[ -1 ]
[ "python", "urllib2" ]
stackoverflow_0000603856_python_urllib2.txt
Q: 500 errors on appengine and console I'm using Google Appengine in a production environment and we are currently getting 500 errors on both our website and console. Is there anything we can do to prevent these or handle them more gracefully? EDIT: We're using python with Webapp A: Setup error handlers: http://co...
500 errors on appengine and console
I'm using Google Appengine in a production environment and we are currently getting 500 errors on both our website and console. Is there anything we can do to prevent these or handle them more gracefully? EDIT: We're using python with Webapp
[ "\nSetup error handlers: http://code.google.com/appengine/docs/python/config/appconfig.html#Custom_Error_Responses\nWhen the error occurs in the app, error handlers can't help. One solution is to wrap the application to handle uncaught exceptions:\nimport logging\n\nfrom google.appengine.ext import webapp\nfrom goo...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006994594_google_app_engine_python.txt
Q: Python practices: arguments passed by "reference" Consider an instance of a class: class Car(object): def __init__(self): self.engine = None And a function that modifies that instance: def add_engine(car): car.engine = 'V6' Python has no implicit techniques of pointing out that an argument will b...
Python practices: arguments passed by "reference"
Consider an instance of a class: class Car(object): def __init__(self): self.engine = None And a function that modifies that instance: def add_engine(car): car.engine = 'V6' Python has no implicit techniques of pointing out that an argument will be modified. The best solution that I could think of is ...
[ "FWIW, I've noticed that in the Python universe, functions/methods that have side effects (such as the one you're asking about) always return None. (This is done implicitly, either by using a return statement without arguments, or simply leaving out the return altogether.)\nFor example compare the sorted built-in ...
[ 7, 5, 2, 2, 0 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0006996576_arguments_python.txt
Q: What's wrong in python script? What's wrong in python script? Code: import os import shutil import getpass os.mkdir("C:\\dtmp") shutil.copy("C:\\path\\to\\bb-freeze-script.py","C:\\dtmp") os.chdir("C:\\dtmp") shutil.copy("C:\\path\\to\\main.py","C:\\dtmp") os.system("python bb-freeze-script.py main.py") ...
What's wrong in python script?
What's wrong in python script? Code: import os import shutil import getpass os.mkdir("C:\\dtmp") shutil.copy("C:\\path\\to\\bb-freeze-script.py","C:\\dtmp") os.chdir("C:\\dtmp") shutil.copy("C:\\path\\to\\main.py","C:\\dtmp") os.system("python bb-freeze-script.py main.py") os.mkdir("C:\\Program Files\\Direct...
[ "Here's a quick walkthrough on how to read tracebacks. It's pretty easy.\n\nLooking through your code, all of it is calling Python builtin modules. It's safe to say they're not causing the error, so the only thing left is the os.system call. Sure enough, you're calling python through said call (why would you not ju...
[ 11 ]
[]
[]
[ "indentation", "program_entry_point", "python", "windows_xp" ]
stackoverflow_0006997138_indentation_program_entry_point_python_windows_xp.txt
Q: Reversing axis in Numpy array using C-API I am using the Python C-API to wrap some C++ code as a Python package. In the end, I have to reverse an axis in a numpy array, i.e. doing x = x[:, ::-1] Is there some way of doing this using the Numpy C-API? I know there are routines for transposing and swaping axes but I ...
Reversing axis in Numpy array using C-API
I am using the Python C-API to wrap some C++ code as a Python package. In the end, I have to reverse an axis in a numpy array, i.e. doing x = x[:, ::-1] Is there some way of doing this using the Numpy C-API? I know there are routines for transposing and swaping axes but I haven't found much about indexing. Any ideas? T...
[ "As indexing in Python is just syntactic sugar for calling an object's __getitem__() method (i.e. x[:, ::-1] is equivalent to x.__getitem__((slice(None), slice(None, None, -1)))), you just have to construct the required slice objects, store them in the correct order in a tuple, and then call the object's __getitem_...
[ 3 ]
[]
[]
[ "numpy", "python", "python_c_api" ]
stackoverflow_0006994725_numpy_python_python_c_api.txt
Q: BASIC to Python program I have created a small program to see if I'm as proficient in Python as I am in FreeBasic (and I'm not that good with FreeBasic). Obviously, I'm asking this question because the answer is no. So the this program is a small Dungeons and Dragons (2nd edition) combat generator. For some reason...
BASIC to Python program
I have created a small program to see if I'm as proficient in Python as I am in FreeBasic (and I'm not that good with FreeBasic). Obviously, I'm asking this question because the answer is no. So the this program is a small Dungeons and Dragons (2nd edition) combat generator. For some reason, many functions don't execut...
[ "attaque1() and attaque2() are called from calcInitiative() so if it doesn't get called they won't either.\nYour while loop executes while ((pv1 <= 0) or (pv2 <= 0))\nbut you've defined them to be \npv1 = random.randint(1,10)\npv1 = (pv1) # this line does nothing\npv2 = random.randint(1,10)\npv2 = str(pv2)\n\nSo ne...
[ 2, 1 ]
[]
[]
[ "freebasic", "python" ]
stackoverflow_0006997197_freebasic_python.txt
Q: How to create a loop to read several images in a python script? I use python to work with image processing. I'm used to cut, draw and other things, but for one image. Like in the script below, how can i aply a loop in the script to do for several images? import PIL import Image im=Image.open('test.tif') box=(50...
How to create a loop to read several images in a python script?
I use python to work with image processing. I'm used to cut, draw and other things, but for one image. Like in the script below, how can i aply a loop in the script to do for several images? import PIL import Image im=Image.open('test.tif') box=(50, 50, 200, 200) im_crop=im.crop(box) im_crop.show()
[ "You need to wrap it in a for loop, and give that loop a list of files.\nOne very easy way to get a list of all the TIF files in the current directory is with glob, like this:\nimport PIL\nimport Image\nimport glob\n\nfor filename in glob.glob(\"*.tif\"):\n im=Image.open(filename)\n box=(50, 50, 200, 200)\n ...
[ 9, 2, 0 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0006997419_image_processing_python_python_imaging_library.txt