content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: how to encode string with unicode characters python I have a sql statement: select 'ó' from dual; after running fetchall for this statement I get the following string.'\xc2\xbf' in python. How do I get the original text based on the string returned? any ideas? thanks! Update: It turns out that the fetchall might ...
how to encode string with unicode characters python
I have a sql statement: select 'ó' from dual; after running fetchall for this statement I get the following string.'\xc2\xbf' in python. How do I get the original text based on the string returned? any ideas? thanks! Update: It turns out that the fetchall might be converting the 'ó' to an inverted questionmark(the \x...
[ "http://docs.python.org/library/stdtypes.html#str.decode is what you're looking for.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006075285_python.txt
Q: What is the lowest version of Python that has the shutil module? I am trying to use shutil.make_archive, but I get a "module not found" error. Then I tried using Python 2.7 and it worked. What is the lowest Python version that contains that module and function? A: From shutil doc, make_archive is new in version ...
What is the lowest version of Python that has the shutil module?
I am trying to use shutil.make_archive, but I get a "module not found" error. Then I tried using Python 2.7 and it worked. What is the lowest Python version that contains that module and function?
[ "From shutil doc, make_archive is new in version 2.7.\n", "shutil is at least as early as 2.3. make_archive is new in 2.7. shutil doc\n", "Python 2.7 is the earliest release to include make_archive in shutils. shutils in general existed since at least 2.0.\n" ]
[ 4, 3, 2 ]
[]
[]
[ "linux", "python", "shutil" ]
stackoverflow_0006075361_linux_python_shutil.txt
Q: Need help understanding this python error return (Google search doesn't help) In python code. When you see a negative in front of a Error Flag, what does it mean? return -errno.EACCES A: That's a C style error return. A practice that is popular is to return a meaningful non-negative result of the function on suc...
Need help understanding this python error return (Google search doesn't help)
In python code. When you see a negative in front of a Error Flag, what does it mean? return -errno.EACCES
[ "That's a C style error return. A practice that is popular is to return a meaningful non-negative result of the function on success or a negative error code on failure.\nIn this case, the error EACCES means that permision was denied.\n(See also this question)\n", "The author may has restricted error code to negat...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006075774_python.txt
Q: Dynamic columns using Mako for tabular data The mako documentation seems to hint a being able to have dynamic, optional layout just before "Using Blocks" but I am having a difficult time noodling it out.cle people = dict_cursor.fetchall() all_possible_cols = ('Name','Birth','Gender', 'Address','City','State', ......
Dynamic columns using Mako for tabular data
The mako documentation seems to hint a being able to have dynamic, optional layout just before "Using Blocks" but I am having a difficult time noodling it out.cle people = dict_cursor.fetchall() all_possible_cols = ('Name','Birth','Gender', 'Address','City','State', ...] user_cols = user_wants(user_id) # ('State','Gen...
[ "If I understand your question, something like this should work:\n<tr>\n % for col in user_cols:\n ${getattr(self, col)()}\n % endfor\n</tr>\n\n" ]
[ 0 ]
[]
[]
[ "dynamic", "mako", "python", "templates" ]
stackoverflow_0006075565_dynamic_mako_python_templates.txt
Q: Python pefile member question Gang, I apologize if this is a really dumb question... I am wanting to use the super convenient python script pefile (http://code.google.com/p/pefile/) that parses an executable and lists particular information about the PE structure. My question is where can I find information abou...
Python pefile member question
Gang, I apologize if this is a really dumb question... I am wanting to use the super convenient python script pefile (http://code.google.com/p/pefile/) that parses an executable and lists particular information about the PE structure. My question is where can I find information about how to access particular members ...
[ "From the PE docstring:\n\nBasic headers information will be available in the attributes:\n\nDOS_HEADER \nNT_HEADERS \nFILE_HEADER \nOPTIONAL_HEADER\n\nAll of them will contain among their attributes the members of the \ncorresponding structures as defined in WINNT.H\n\n\nSo, look at winnt.h and you'll see whic...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006075973_python.txt
Q: Python 3 does not give a clean exit This code does not give a clean exit when the Exit button is clicked. Instead, it hangs, leaaving the dead GUI. Hw can we fix this? A similar program in Python 2 behaves nicely. from tkinter import * import sys root=Tk() def quit(): sys.exit("quitting") frame=Frame() ...
Python 3 does not give a clean exit
This code does not give a clean exit when the Exit button is clicked. Instead, it hangs, leaaving the dead GUI. Hw can we fix this? A similar program in Python 2 behaves nicely. from tkinter import * import sys root=Tk() def quit(): sys.exit("quitting") frame=Frame() frame.pack() x=Label(root,text='Label') ...
[ "def quit():\n root.destroy()\n\nShould work...?\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x", "tkinter", "user_interface" ]
stackoverflow_0006076164_python_python_3.x_tkinter_user_interface.txt
Q: Python SWIG arrays I am wrapping a C module with SWIG for Python. Is there any way to turn all Python lists/tuples whose members are all of the same type (same kind of Swig object) to C arrays? A: Typemaps. What you are most likely looking for is an "in" typemap, which maps Python types to C types. The declara...
Python SWIG arrays
I am wrapping a C module with SWIG for Python. Is there any way to turn all Python lists/tuples whose members are all of the same type (same kind of Swig object) to C arrays?
[ "Typemaps. What you are most likely looking for is an \"in\" typemap, which maps Python types to C types. The declaration looks something like this:\n%typemap(in) {\n /* C code to convert Python tuple object to C array */\n}\nInside the typemap code you can use the variable $input to reference the PyObject* t...
[ 2 ]
[]
[]
[ "arrays", "list", "python", "swig", "types" ]
stackoverflow_0004074611_arrays_list_python_swig_types.txt
Q: Uploading to BlobStore in Google App Engine from a Command Line Java Application Here is my server side code for my blobstore uploading command line application: public class UploadServlet extends HttpServlet { private static final Logger log = Logger.getLogger(UploadServlet.class.getName()); private fina...
Uploading to BlobStore in Google App Engine from a Command Line Java Application
Here is my server side code for my blobstore uploading command line application: public class UploadServlet extends HttpServlet { private static final Logger log = Logger.getLogger(UploadServlet.class.getName()); private final BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService(); protected ...
[ "Since version 1.4.3 There is an experimental API to write directly to the blobstore.\nIt saves you from the need to upload to the blobstore using POSTs.\n" ]
[ 1 ]
[]
[]
[ "blobstore", "command_line", "google_app_engine", "java", "python" ]
stackoverflow_0005042871_blobstore_command_line_google_app_engine_java_python.txt
Q: Implementing a multi-process server in Python, with Twisted I have to write a CPU-bound server in Python, to distribute workloads for many cores. I want to use Twisted as the server (requests coming in via TCP). Are there any better options - using Ampoule, perhaps? I also saw an article using Twisted's pb for co...
Implementing a multi-process server in Python, with Twisted
I have to write a CPU-bound server in Python, to distribute workloads for many cores. I want to use Twisted as the server (requests coming in via TCP). Are there any better options - using Ampoule, perhaps? I also saw an article using Twisted's pb for communication, in conjunction with Popen - or perhaps combine it wi...
[ "Ampoule is a good building block for a multiprocess CPU-bound server. It uses the simpler AMP protocol, rather than PB (the complexity of which is usually not needed just to move job data into another process and then retrieve the results). It handles process creation, lifetime management, restarting, etc.\nYou ...
[ 10 ]
[]
[]
[ "parallel_processing", "python", "twisted" ]
stackoverflow_0006076161_parallel_processing_python_twisted.txt
Q: How do I run cleanup code in a Python multiprocessing Pool? I have some Python code (on Windows) that uses the multiprocessing module to run a pool of worker processes. Each worker process needs to do some cleanup at the end of the map_async method. Does anyone know how to do that? A: Do you really want to run a...
How do I run cleanup code in a Python multiprocessing Pool?
I have some Python code (on Windows) that uses the multiprocessing module to run a pool of worker processes. Each worker process needs to do some cleanup at the end of the map_async method. Does anyone know how to do that?
[ "Do you really want to run a cleanup function once for each worker process rather than once for every task created by the map_async call?\nmultiprocess.pool.Pool creates a pool of, say, 8 worker processes. map_async might submit 40 tasks to be distributed among the 8 workers.\nI can imagine why you might want to ru...
[ 4, 2 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0006075451_multiprocessing_python.txt
Q: Python: Efficient way to put multiple variables through a function I have a bunch of variables that are equal to values pulled from a database. Sometimes, the database doesn't have a value and returns "NoneType". I'm taking these variables and using them to build an XML file. When the variable is NoneType, it c...
Python: Efficient way to put multiple variables through a function
I have a bunch of variables that are equal to values pulled from a database. Sometimes, the database doesn't have a value and returns "NoneType". I'm taking these variables and using them to build an XML file. When the variable is NoneType, it causes the XML value to read "None" rather than blank as I'd prefer. My q...
[ "All the solutions given here will make your code shorter and less tedious, but if you really have a lot of variables I think you will appreciate this, since it won't make you add even a single extra character of code for each variable:\nclass NoneWrapper(object):\n def __init__(self, wrapped):\n self.wra...
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006076475_python.txt
Q: When should I use Popen() and when should I use call()? Caveat: new to Python. Wanting to hear from professionals who actually use it: What are the main differences between subprocess.Popen() and subprocess.call() and when is it best to use each one? Unless you want to read why I was thinking about this question o...
When should I use Popen() and when should I use call()?
Caveat: new to Python. Wanting to hear from professionals who actually use it: What are the main differences between subprocess.Popen() and subprocess.call() and when is it best to use each one? Unless you want to read why I was thinking about this question or what to center your answer around, you may stop reading now...
[ "\nsubprocess.call(*popenargs, **kwargs)\n Run command with arguments. Wait for\n command to complete, then return the\n returncode attribute.\n\nIf you create a Popen object, you must call the sp.wait() yourself.\nIf you use call, that's done for you.\n" ]
[ 7 ]
[]
[]
[ "call", "popen", "python", "subprocess" ]
stackoverflow_0006076723_call_popen_python_subprocess.txt
Q: Most elegant way for SWIG wrapped C library to raise exceptions I have recently converted a library, I originally wrote in C++ with Boost Python wrapping, to C with SWIG wrapping to support more languages. I switched from C++ to C because the library consists only of a set of functions and I also want the library ...
Most elegant way for SWIG wrapped C library to raise exceptions
I have recently converted a library, I originally wrote in C++ with Boost Python wrapping, to C with SWIG wrapping to support more languages. I switched from C++ to C because the library consists only of a set of functions and I also want the library to be callable from C (without having to compile the whole program wi...
[ "This is how I do it. the %{...%} block inserts it's contents to the wrapper file. The %exception block is SWIG's exception handling, and runs after each function call to check if there was an error and throw an exception with PyErr_SetString if there was. Then, simply call \"set_err(\"Error msg\"); from your C ...
[ 5, 0 ]
[]
[]
[ "c", "python", "swig" ]
stackoverflow_0005448257_c_python_swig.txt
Q: pyqt4: less round-about way of removing item from QListWidget? I want to remove an item whose name I know. I came up with: item = lw.findItems(name, QtCore.Qt.MatchExactly)[0] lw.takeItem(lw.indexFromItem(item).row()) Is there any more direct way of doing this? Something closer to lw.removeItem(name)? A: This l...
pyqt4: less round-about way of removing item from QListWidget?
I want to remove an item whose name I know. I came up with: item = lw.findItems(name, QtCore.Qt.MatchExactly)[0] lw.takeItem(lw.indexFromItem(item).row()) Is there any more direct way of doing this? Something closer to lw.removeItem(name)?
[ "This leaves a bit of ambiguity for multiple entries with the same text. I would lean more toward something like\n[ lw.takeItem( i ) for i in range( lw.count ) if lw.item( i ).text() == name ]\n\nThis will remove all items matching name from the list. If you only want to remove the first instance, you need to exp...
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0006074198_pyqt_pyqt4_python_qt_qt4.txt
Q: Merge csv files to excel in Python Possible Duplicate: python: creating excel workbook and dumping csv files as worksheets How would you automate the task of taking several CSV files and placing them in a single excel (XLS\XLSX) file so that each CSV is a different sheet, optimally with the same name as the CSV ...
Merge csv files to excel in Python
Possible Duplicate: python: creating excel workbook and dumping csv files as worksheets How would you automate the task of taking several CSV files and placing them in a single excel (XLS\XLSX) file so that each CSV is a different sheet, optimally with the same name as the CSV file?
[ "Here is a page that has several python excel libraries. Pick one that suites your needs. The library will provide ways of creating tabs and populating each tab. After doing so, if you still have questions, come back and update your post. Good luck! \n" ]
[ 2 ]
[]
[]
[ "automation", "csv", "excel", "merge", "python" ]
stackoverflow_0006077061_automation_csv_excel_merge_python.txt
Q: Ignore ImportError when exec source code I have an application that reads test scripts in python and sends them across the network for execution on a remote python instance. As the controlling program does not need to run these scripts I do not want to have all the modules the test scripts use installed on the co...
Ignore ImportError when exec source code
I have an application that reads test scripts in python and sends them across the network for execution on a remote python instance. As the controlling program does not need to run these scripts I do not want to have all the modules the test scripts use installed on the controller's python environment. However the co...
[ "Write an import hook that catches the exception and returns a dummy module if the module doesn't exist.\nimport __builtin__\nfrom types import ModuleType\n\nclass DummyModule(ModuleType):\n def __getattr__(self, key):\n return None\n __all__ = [] # support wildcard imports\n\ndef tryimport(name, glo...
[ 17, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006076770_python.txt
Q: How do I fix my "self-deleting" .exe from deleting itself early? For the sake of testing and personal proof of concept, I have a .exe file that only outputs a simple string and then calls a system pause (literally system("pause") in C++). I have a simple Python script I'm testing on a Windows XP VM that does these...
How do I fix my "self-deleting" .exe from deleting itself early?
For the sake of testing and personal proof of concept, I have a .exe file that only outputs a simple string and then calls a system pause (literally system("pause") in C++). I have a simple Python script I'm testing on a Windows XP VM that does these operations when messing up: subprocess.call(r'echo Nothing special. >...
[ "What happens is that each subprocess.call(..., shell=True) is immediately returning because they're just telling the shell to execute a command. On the commandline, calling an exe to run using the start command will still immediately return even though the exe has not terminated. The start immediately returned and...
[ 1, 1, 0 ]
[]
[]
[ "alternate_data_stream", "c++", "python", "windows_xp" ]
stackoverflow_0006076941_alternate_data_stream_c++_python_windows_xp.txt
Q: Is there a standard way of Watermarking videos in Python? Is there any standard method of watermarking videos of some format in Python? And how about still images? A: I'd suggest checking out pyffmpeg or pymedia, but that's about as good as it gets. Try to find a way to leverage ffmpeg proper if you can. For st...
Is there a standard way of Watermarking videos in Python?
Is there any standard method of watermarking videos of some format in Python? And how about still images?
[ "I'd suggest checking out pyffmpeg or pymedia, but that's about as good as it gets. Try to find a way to leverage ffmpeg proper if you can.\nFor still images, simply use PIL, the Python Imaging Library.\n", "Transloadit provides image & video conversion via web services, works well, and very cheap. If you need ...
[ 4, 0, 0 ]
[]
[]
[ "python", "video_processing", "video_watermarking", "watermark" ]
stackoverflow_0006066396_python_video_processing_video_watermarking_watermark.txt
Q: Separating comma delimited text within a field using Python I'm currently trying to convert a table into RDF using Python and attach the values from each cell to the end of a URL (eg E00 becomes statistics.data.gov.uk/id/statistical-geography/E00). I can do this for cells containing a single value using the script...
Separating comma delimited text within a field using Python
I'm currently trying to convert a table into RDF using Python and attach the values from each cell to the end of a URL (eg E00 becomes statistics.data.gov.uk/id/statistical-geography/E00). I can do this for cells containing a single value using the script. FirstCode = row[11] if row[11] != '': RDF = RDF + '<http://st...
[ "Yes, there is the split method.\nFirstCode.split(\",\")\n\nwill return a list like (E00, W00, S00)\nYou can than iterate over the items in the list:\n for i in FirstCode.split(\",\"):\n print i\n\nWill print out:\nE00\nW00\nS00\nThis page has some other useful string functions\n", "for i in FirstCode.split(...
[ 4, 2 ]
[]
[]
[ "csv", "linked_data", "python", "rdf" ]
stackoverflow_0006077429_csv_linked_data_python_rdf.txt
Q: Problem using easy_install.exe to install pyMySQL for Django I'm trying to install the pyMySQL module for python so that I can setup Django (see this previous question). I can't get easy_install.exe PyMySQL-0.3-py2.6.egg to run for the life of me. Every time I get the error easy_install.exe not recognized as an i...
Problem using easy_install.exe to install pyMySQL for Django
I'm trying to install the pyMySQL module for python so that I can setup Django (see this previous question). I can't get easy_install.exe PyMySQL-0.3-py2.6.egg to run for the life of me. Every time I get the error easy_install.exe not recognized as an internal or external command... I've tried adding various director...
[ "You have to install setuptools first\n[edit]\nUh,\nC:\\Users\\Robus>easy_install\nYada yada, not found\nC:\\Python26\\Scripts>easy_install\nerror: No urls, filenames, or requirements specified (see --help)\nC:\\Python26>\n\nThe next best thing I can think of is - do you, by any chance, have more than one version o...
[ 2 ]
[]
[]
[ "django", "easy_install", "path", "python" ]
stackoverflow_0006077494_django_easy_install_path_python.txt
Q: How does the "magic lines(s)" in python work, when specifying encoding in python file? At the start of a python file (first line) sometimes I read # -*- coding: utf-8 -*- and sometimes I read # encoding: utf-8 Both lines seem to do the same thing: specifying utf8 as encoding for all the text put in the file. I h...
How does the "magic lines(s)" in python work, when specifying encoding in python file?
At the start of a python file (first line) sometimes I read # -*- coding: utf-8 -*- and sometimes I read # encoding: utf-8 Both lines seem to do the same thing: specifying utf8 as encoding for all the text put in the file. I have to questions: Why does this even work? I thought the interpreter ignores everything aft...
[ "The two forms are equivalent. The -*- version is a special kind of comment that Emacs understands. See PEP 263 for more information.\nIf a comment like in either of these forms is one of the first two lines of a file, the interpreter will use the specified encoding to read the file.\n", "It works because the i...
[ 11, 3 ]
[]
[]
[ "comments", "encoding", "interpreter", "python" ]
stackoverflow_0006077479_comments_encoding_interpreter_python.txt
Q: Problem with Python nested objects being stored in a dictionary I'm having some trouble with changing the value of a class at runtime and then instantiating it into an object, then storing that object inside of another class and putting that into python dictionary. Here is a small code snippet I wrote to illustra...
Problem with Python nested objects being stored in a dictionary
I'm having some trouble with changing the value of a class at runtime and then instantiating it into an object, then storing that object inside of another class and putting that into python dictionary. Here is a small code snippet I wrote to illustrate the problem: import unittest class cls1(object): def __init_...
[ "What you're showing can't work. Ever.\nclass Cls2(object):\n def __init__(self):\n self.var = 1\n\nThat's an instance variable. It's not a class variable. You can't access that .var with Cls2.var That variable only exists within each unique instance of the class.\n Cls2.var = 2\n\nDoes not cha...
[ 1, 0 ]
[]
[]
[ "class", "dictionary", "object", "python" ]
stackoverflow_0006077742_class_dictionary_object_python.txt
Q: python pack 4 byte integer with bytes in bytearray struct.pack I am attempting to pack the contents of a python bytearray into a 4byte signed integer using struct.pack. Unfortunately, pack wants a string, so after some googling I figured I needed to decode my bytearray to a string. I figured ascii meant since be...
python pack 4 byte integer with bytes in bytearray struct.pack
I am attempting to pack the contents of a python bytearray into a 4byte signed integer using struct.pack. Unfortunately, pack wants a string, so after some googling I figured I needed to decode my bytearray to a string. I figured ascii meant since because an ascii character is a byte long. Unfortunately, ascii did n...
[ "All you need is to cast inBytes back to str:\n>>> inint = struct.unpack('<i', str(inBytes))\n>>> inint\n(-5,)\n\n", "When you read from a file in binary mode, you get an object that can be used immediately with struct.unpack. \nCreating the input data:\n>>> import struct\n>>> f = open('foo.bin', 'wb')\n>>> f.wri...
[ 1, 1 ]
[]
[]
[ "ascii", "bytearray", "python", "struct" ]
stackoverflow_0006076300_ascii_bytearray_python_struct.txt
Q: Inserts don't appear to be happening I'm using gevent with gevent-mysql (I also used pymysql to the same effect). It does selects just fine but no matter what I do I can't get it to run an insert. I'm out of ideas. conn = geventmysql.connect(host='localhost', port=3306, user='root', db='content') cur = conn.cursor...
Inserts don't appear to be happening
I'm using gevent with gevent-mysql (I also used pymysql to the same effect). It does selects just fine but no matter what I do I can't get it to run an insert. I'm out of ideas. conn = geventmysql.connect(host='localhost', port=3306, user='root', db='content') cur = conn.cursor() cur.execute("insert into placement (pla...
[ "If you are using a transactional storage engine (like InnoDB), you should check the value of the autocommit variable: http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_autocommit\nIf it is 0, you need to commit your transactions, either using a built in commit() method or an execute(\"COMM...
[ 3, 2, 1 ]
[]
[]
[ "gevent", "mysql", "python" ]
stackoverflow_0006078421_gevent_mysql_python.txt
Q: Can't unzip archive built with zipfile (Python) I'm having problems with an archive that I built using zipfile in Python. I'm iterating over all the files in a directory and writing them to an archive. When I attempt to extract them afterward I get an exception related to the path separator. the_path= "C:\\path\\t...
Can't unzip archive built with zipfile (Python)
I'm having problems with an archive that I built using zipfile in Python. I'm iterating over all the files in a directory and writing them to an archive. When I attempt to extract them afterward I get an exception related to the path separator. the_path= "C:\\path\\to\\folder" zipped= cStringIO.StringIO() zf = zipfile....
[ "You should consider adding an r before the string to indicate it is a raw string -- the backslashes in the path are being interpreted as escape characters.\nThe following code:\n#!/bin/env python \nprint(r\"C:\\destination\\path\")\nprint(r\"C:\\path\\to\\folder\")\nprint(\"C:\\destination\\path\")\nprint(\"C:...
[ 5, 4, 1, 1 ]
[]
[]
[ "archive", "python", "python_zipfile", "zip" ]
stackoverflow_0006063910_archive_python_python_zipfile_zip.txt
Q: What are some Python libraries that support DCC file transfer? Are there any Python libraries that support DCC file transfers? If so, what are they, if not would it be within my ability as a novice python programmer to write my own? A: irclib.py supports DCC connections.
What are some Python libraries that support DCC file transfer?
Are there any Python libraries that support DCC file transfers? If so, what are they, if not would it be within my ability as a novice python programmer to write my own?
[ "irclib.py supports DCC connections.\n" ]
[ 1 ]
[]
[]
[ "irc", "python" ]
stackoverflow_0006078540_irc_python.txt
Q: python - open() not working with path names Python 2.7.1, using open(), and having trouble with append mode and pathname instead of filename. It says open() works as stdio fopen(), and that func when put into append ("a") says it's supposed to create the file if it doesn't exist. # this works in python, creating f...
python - open() not working with path names
Python 2.7.1, using open(), and having trouble with append mode and pathname instead of filename. It says open() works as stdio fopen(), and that func when put into append ("a") says it's supposed to create the file if it doesn't exist. # this works in python, creating file.txt if it doesnt exist >>> fp = open ("file.t...
[ "Check out os.path.expanduser():\n\nos.path.expanduser(path)\nOn Unix and Windows, return the argument with an initial component of\n ~ or ~user replaced by that user‘s\n home directory.\n\nA lot of things don't like ~ in paths and this will fix it.\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0006078759_python.txt
Q: Python/Matplotlib - Quickly Updating Text on Axes I have a matplotlib figure/canvas in a wxpython window. I want to update some information on the plot as the mouse moves around. I've connected to 'motion_notify_event' to get this information. In the code below, a lot of random data is plotted and then the x,y l...
Python/Matplotlib - Quickly Updating Text on Axes
I have a matplotlib figure/canvas in a wxpython window. I want to update some information on the plot as the mouse moves around. I've connected to 'motion_notify_event' to get this information. In the code below, a lot of random data is plotted and then the x,y location of the cursor is displayed in the statusbar of ...
[ "You could use blitting, similar to the animation examples here.\nThis make a very large performance difference in this case, as only a small portion of the window needs to be redrawn. \nUnfortunately, I can't figure out how to get a gray background behind the text when it's redrawn, to match the default figure ba...
[ 5, 0 ]
[]
[]
[ "matplotlib", "python", "text" ]
stackoverflow_0006077017_matplotlib_python_text.txt
Q: How can I override Django filter I want to override timesince Django's template filter for creating a more efficient filter for getting relative times. How can I do it? A: Monkeypatch django.utils.timesince.timesince with your desired function. A: You can also create your own filter to do what you want: http:/...
How can I override Django filter
I want to override timesince Django's template filter for creating a more efficient filter for getting relative times. How can I do it?
[ "Monkeypatch django.utils.timesince.timesince with your desired function.\n", "You can also create your own filter to do what you want: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006078990_django_python.txt
Q: Python/mod_wsgi server global data I have been looking into different systems for creating a fast cache in a web-farm running Python/mod_wsgi. Memcache and others are options ... But I was wondering: Because I don't need to share data across machines, wanting each machine to maintain a local cache ... Does Python ...
Python/mod_wsgi server global data
I have been looking into different systems for creating a fast cache in a web-farm running Python/mod_wsgi. Memcache and others are options ... But I was wondering: Because I don't need to share data across machines, wanting each machine to maintain a local cache ... Does Python or WSGI provide a mechanism for Python n...
[ "This is thoroughly covered by the Sharing and Global Data section of the mod_wsgi documentation. The short answer is: No, not unless you run everything in one process, but that's not an ideal solution.\nIt should be noted that caching is ridiculously easy to do with Beaker middleware, which supports multiple backe...
[ 2, 1, 0 ]
[]
[]
[ "apache", "caching", "mod_wsgi", "python" ]
stackoverflow_0001113736_apache_caching_mod_wsgi_python.txt
Q: did you know a method to show this value using python i know floor in python : floor(0.2) #---> 0 but i want to get : 1 2 3 4 5 6 7 8 9 10 #---> 1 11 12 13 ... 20 # --->2 21 22 23 ... 30 #--->3 has a method to get this value , thanks A: >>> (21 + 9) // 10 3 >>> (30 + 9) // 10 3 A: The easiest solution (w...
did you know a method to show this value using python
i know floor in python : floor(0.2) #---> 0 but i want to get : 1 2 3 4 5 6 7 8 9 10 #---> 1 11 12 13 ... 20 # --->2 21 22 23 ... 30 #--->3 has a method to get this value , thanks
[ ">>> (21 + 9) // 10\n3\n>>> (30 + 9) // 10\n3\n\n", "The easiest solution (without the need to import math module) is:\n\n(x-1) // 10 + 1\n\nwhich will make sure you get an integer (thanks to //). But if you insist on using floor(), then here you go:\nimport math\nmath.floor ( (x - 1) / 10. ) + 1\n\nFor example:\...
[ 3, 1 ]
[]
[]
[ "numbers", "python" ]
stackoverflow_0006079395_numbers_python.txt
Q: Why is this sending so many variables? I have created a function timeout_func that will run an another function normally and return its output, but if the function exceeds 'secs' it will return a string 'failed'. Basically, it's a workaround to timeout a function which could run infinitely. (python 2.7 on windows)...
Why is this sending so many variables?
I have created a function timeout_func that will run an another function normally and return its output, but if the function exceeds 'secs' it will return a string 'failed'. Basically, it's a workaround to timeout a function which could run infinitely. (python 2.7 on windows) (Why do I need a workaround, why can't I ju...
[ "('i was returned') is not a tuple. It evaluates to a string, just like (3+2) evaluated to an integer..\nCalling do_this(*('i was returned')) passes each letter of the sequence 'i was returned' as a separate argument - the equivalent of:\ndo_this('i', ' ', 'w', 'a', 's', ' ', 'r', 'e', 't', 'u', 'r', 'n', 'e', 'd')...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0006079414_python.txt
Q: Equal sized Dock Widgets in PyQt4 How can I ensure that all dock widgets have the same size irrespective of their content? A: You have to set a layout in Qt4. Check this out.
Equal sized Dock Widgets in PyQt4
How can I ensure that all dock widgets have the same size irrespective of their content?
[ "You have to set a layout in Qt4. \nCheck this out.\n" ]
[ 0 ]
[]
[]
[ "dock", "pyqt", "python", "size", "widget" ]
stackoverflow_0006074564_dock_pyqt_python_size_widget.txt
Q: Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found pyPdf throws this exception: pyPdf.utils.PdfReadError: EOF marker not found I don't need to fix pyPdf, I just need to get the EOF error to cause an "except" block to execute and skip over the file, but it doesn't work. It still causes the pro...
Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found
pyPdf throws this exception: pyPdf.utils.PdfReadError: EOF marker not found I don't need to fix pyPdf, I just need to get the EOF error to cause an "except" block to execute and skip over the file, but it doesn't work. It still causes the program to stop running. Background: Batch OCR Program for PDFs Python, pyPdf, A...
[ "put your pyPdf call(s) inside the try/except block also.\n" ]
[ 2 ]
[]
[]
[ "eof", "exception", "pypdf", "python" ]
stackoverflow_0006079593_eof_exception_pypdf_python.txt
Q: Detect if .swf has transparent background Is there a way to do this programmatically in PHP, Python or Java? Use case: User uploads .swf through an upload form. Detect if it has a transparent background. If it does, change it to something else, e.g. white. A: This is very difficult to determine, because all SWF...
Detect if .swf has transparent background
Is there a way to do this programmatically in PHP, Python or Java? Use case: User uploads .swf through an upload form. Detect if it has a transparent background. If it does, change it to something else, e.g. white.
[ "This is very difficult to determine, because all SWFs are actually transparent (or they all can be) - it's just that they can contain shapes which cover the entire stage, which make them appear non-transparent.\nTo determine this programmatically, you'd need to loop over every shape in the SWF and look at it's bou...
[ 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "flash", "java", "php", "python" ]
stackoverflow_0005988172_flash_java_php_python.txt
Q: Bitbucket API authentication with Python's HTTPBasicAuthHandler I'm trying to get the list of issues on a private repository using bitbucket's API. I have confirmed that HTTP Basic authentication works with hurl, but I am unable to authenticate in Python. Adapting the code from this tutorial, I have written the fo...
Bitbucket API authentication with Python's HTTPBasicAuthHandler
I'm trying to get the list of issues on a private repository using bitbucket's API. I have confirmed that HTTP Basic authentication works with hurl, but I am unable to authenticate in Python. Adapting the code from this tutorial, I have written the following script. import cookielib import urllib2 class API(): api...
[ "It looks like there is an issue with HTTPBasicAuthHandler. This works:\nclass API():\n api_url = 'http://api.bitbucket.org/1.0/'\n\n def __init__(self, username, password, proxy=None):\n encodedstring = base64.encodestring(\"%s:%s\" % (username, password))[:-1]\n self._auth = \"Basic %s\" % enc...
[ 5, 2, 1, 0 ]
[]
[]
[ "bitbucket", "bitbucket_api", "python", "urllib2" ]
stackoverflow_0002669147_bitbucket_bitbucket_api_python_urllib2.txt
Q: django Error (EXTERNAL IP) I am receiving notifications every time, when enter an address that does not exist. Traceback (most recent call last): File "/home/user/opt/local/django/core/handlers/base.py", line 100, in get_response File "/web/blog/views.py", line 33, in post File "/home/user/local/djang...
django Error (EXTERNAL IP)
I am receiving notifications every time, when enter an address that does not exist. Traceback (most recent call last): File "/home/user/opt/local/django/core/handlers/base.py", line 100, in get_response File "/web/blog/views.py", line 33, in post File "/home/user/local/django/db/models/manager.py", line 13...
[ "Modify your query to use get_object_or_404, or catch the YourModel.DoesNotExist (3rd paragraph) exception when you're doing the lookup, and raise a Http404 exception. When you don't catch the DoesNotExist exception the view raises a 500 error. As a side effect, this sends an exception email to the the ADMINS def...
[ 6, 1, 1, 0 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0006080024_django_python_url.txt
Q: Python - Logging and levels I use python module logging to generate log files and console print. I set up my script to log all errors levels, without DEBUG to file. But i have trouble with set up handler for console printing. On console i want to display level INFO and below, not up like setLevel doing. Is any way...
Python - Logging and levels
I use python module logging to generate log files and console print. I set up my script to log all errors levels, without DEBUG to file. But i have trouble with set up handler for console printing. On console i want to display level INFO and below, not up like setLevel doing. Is any way to do this with inline code?
[ "I'm not sure exactly what you mean by \"inline code\", but you can achieve this using Filters.\nclass InfoAndLower(logging.Filter):\n def filter(self, record):\n return record.levelno <= logging.INFO\n\nand then attach a filter instance to your console handler.\nh = logging.StreamHandler(sys.stdout)\nh.a...
[ 4 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0006080293_logging_python.txt
Q: Error: child pid 6695 exit signal Segmentation fault (11) I use django + mod-wsgi + apache to develop a website. and it is strange that when i launch the website it's ok for all other function expect for login in function. when i try logging in, it gives me a 500 error. This is the error form error_log: [Sat May ...
Error: child pid 6695 exit signal Segmentation fault (11)
I use django + mod-wsgi + apache to develop a website. and it is strange that when i launch the website it's ok for all other function expect for login in function. when i try logging in, it gives me a 500 error. This is the error form error_log: [Sat May 21 13:00:39 2011] [error] /usr/local/lib64/python2.6/site-packa...
[ "Read the documentation for common causes:\nhttp://code.google.com/p/modwsgi/wiki/FrequentlyAskedQuestions#Apache_Process_Crashes\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues\nTry and track it down by using a debugger:\nhttp://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Debugging_Crashes_With_GDB...
[ 2 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0006079726_apache_django_mod_wsgi_python.txt
Q: Searching CSV Files (Python) I've made this CSV file up to play with.. From what I've been told before, I'm pretty sure this CSV file is valid and can be used in this example. Basically I have this CSV file 'book_list.csv': name,author,year Lord of the Rings: The Fellowship of the Ring,J. R. R. Tolkien,1954 ...
Searching CSV Files (Python)
I've made this CSV file up to play with.. From what I've been told before, I'm pretty sure this CSV file is valid and can be used in this example. Basically I have this CSV file 'book_list.csv': name,author,year Lord of the Rings: The Fellowship of the Ring,J. R. R. Tolkien,1954 Nineteen Eighty-Four,George Orwell...
[ "\nThrow away the query file and get your search terms from sys.argv[1:] instead.\nThrow away your output file and use sys.stdout instead.\nAppend matched booklist titles to a result_list. The result_row that you currently have has a rather misleading name. The count that you want is len(result_list). Print that. T...
[ 1, 0 ]
[]
[]
[ "csv", "python", "search" ]
stackoverflow_0006080490_csv_python_search.txt
Q: Python- Code Optimization Help- Find all dictionary-valid anagrams of a word I solved the problem using this (horribly inefficient method): def createList(word, wordList): #Made a set, because for some reason permutations was returning duplicates. #Returns all permutations if they're in the wordList ...
Python- Code Optimization Help- Find all dictionary-valid anagrams of a word
I solved the problem using this (horribly inefficient method): def createList(word, wordList): #Made a set, because for some reason permutations was returning duplicates. #Returns all permutations if they're in the wordList return set([''.join(item) for item in itertools.permutations(word) if ''.join(ite...
[ "This following seems to work OK on a smallish dictionary. By sorting the letters in the word, it becomes easy to test if two words are an anagram. From that starting point, it's just a matter of accumulating the words in some way. It wouldn't be hard to modify this to report all matches, rather than just the first...
[ 3, 2, 1 ]
[]
[]
[ "anagram", "memory_management", "performance", "python" ]
stackoverflow_0006080511_anagram_memory_management_performance_python.txt
Q: which is the best way to insert values in mysql via python scripts in a loop I have the backup script like below for f in os.listdir(path) // do backup Now i want to insert in mysql values like foldername , date , size etc This is mysql script sql = "INSERT INTO pythontest(name, \ name2, name3) \ ...
which is the best way to insert values in mysql via python scripts in a loop
I have the backup script like below for f in os.listdir(path) // do backup Now i want to insert in mysql values like foldername , date , size etc This is mysql script sql = "INSERT INTO pythontest(name, \ name2, name3) \ VALUES ('%s', '%s', '%s')" % \ ('Mac', 'Mohan', '') try: # Execute the S...
[ "\"insert full code in for loop or make a function\" - nothing we must decide for you. It is your snippet taken out of the context and only you can make a decision if encapsulating your code into a method is making or sense or not....this is really up to you .\n" ]
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006080416_mysql_python.txt
Q: getting error with execute many in python I am learning python and i am new bie. I am trying to use functions with mysql and python and i ma getting errors This is my script import MySQLdb def insert_values(cursor, values): #cursor = self.connection.cursor() cursor.executemany(""" insert into pytho...
getting error with execute many in python
I am learning python and i am new bie. I am trying to use functions with mysql and python and i ma getting errors This is my script import MySQLdb def insert_values(cursor, values): #cursor = self.connection.cursor() cursor.executemany(""" insert into pythontest (name1,name2,name3) values (%s, %...
[ "cursor.executemany(\"\"\"\n insert into pythontest (name1,name2,name3)\n values (%s, %s, %s)\"\"\", *values)\n\n", "Here's how I would write that (But untested):\nimport MySQLdb\n\ndef insert_values(db, values):\n cursor = db.cursor()\n try:\n try:\n cursor.execute(\"\"\"\n ...
[ 2, 1 ]
[]
[]
[ "linux", "mysql", "python" ]
stackoverflow_0006080650_linux_mysql_python.txt
Q: problem with pyglet playing video I'm new to pyglet and i have a problem with video.. I'm trying to play a video using pyglet .. but instead of playing the video in the window it just exits immediately and terminates .. do you guys have any solution for this problem how can i hold the window to play vedio?? i us...
problem with pyglet playing video
I'm new to pyglet and i have a problem with video.. I'm trying to play a video using pyglet .. but instead of playing the video in the window it just exits immediately and terminates .. do you guys have any solution for this problem how can i hold the window to play vedio?? i use windows vista 64x with python 2.5 ple...
[ "This might be a tad bit late and ironically if you dig around enough in the media_player.py piglet documentation you can piece this all together, but for those of us that spent hours trying to get pygame to play a movie on windows, and hopelessly tried to get pymedia to interface with pygame correctly and get the ...
[ 7, 0 ]
[]
[]
[ "pyglet", "python", "video" ]
stackoverflow_0001859195_pyglet_python_video.txt
Q: install_requires in setup.py depending on installed Python version My setup.py looks something like this: from distutils.core import setup setup( [...] install_requires=['gevent', 'ssl', 'configobj', 'simplejson', 'mechanize'], [...] ) Under Python 2.6 (or higher) the installation of the ssl module f...
install_requires in setup.py depending on installed Python version
My setup.py looks something like this: from distutils.core import setup setup( [...] install_requires=['gevent', 'ssl', 'configobj', 'simplejson', 'mechanize'], [...] ) Under Python 2.6 (or higher) the installation of the ssl module fails with: ValueError: This extension should not be used with Python 2.6...
[ "It's just a list, so somewhere above you have to conditionally build a list.\nSomething like to following is commonly done.\nimport sys\n\nif sys.version_info < (2 , 6):\n REQUIRES = ['gevent', 'ssl', 'configobj', 'simplejson', 'mechanize'],\nelse:\n REQUIRES = ['gevent', 'configobj', 'simplejson', 'mechaniz...
[ 13 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0006080646_python_setuptools.txt
Q: How to store variables in arraylist in python I want to have something like var1 = ('a','b','c') var2 = ('a1','b1','c1') var3 = ('a2','b2','c2') var4 = ('a3','b4','c5') var5 = ('a6','b6','c6') How can i have all those in one variable var I have a loop which will be saving each array but i want to have only one va...
How to store variables in arraylist in python
I want to have something like var1 = ('a','b','c') var2 = ('a1','b1','c1') var3 = ('a2','b2','c2') var4 = ('a3','b4','c5') var5 = ('a6','b6','c6') How can i have all those in one variable var I have a loop which will be saving each array but i want to have only one variable
[ "var = [var1, var2, var3, ('a3', 'b4', 'c5'), var5]\n\nYou could also copy vari in a loop, but that's very bad programming practice. Basically, you should construct a list upfront and not later from variable names. If you must do it, here's how:\nvar = [locals()['var' + str(i)] for i in range(6)]\n\nThis is the lon...
[ 7 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0006081174_linux_python.txt
Q: Question about Django and User Auth Django's noob question: I use dango.contrib.auth for managing users of my site. But now, I'm developing the 'settings page', where an user can edit his first name, last name, and email address. But in the settings page I want also a checkbox for "newsletter". Questions are: 1) W...
Question about Django and User Auth
Django's noob question: I use dango.contrib.auth for managing users of my site. But now, I'm developing the 'settings page', where an user can edit his first name, last name, and email address. But in the settings page I want also a checkbox for "newsletter". Questions are: 1) Where should I put newsletter field in the...
[ "You want to look at user profiles.\nEDIT: Regarding the forms, is there anything stopping you from using two forms? I think Django ignores fields in the HTTP request that don't match up to a form, so you could feed the request to two forms. When rendering a template, Django doesn't generate the <form> tags or the ...
[ 6, 0, 0, 0, 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0005825560_django_django_authentication_python.txt
Q: In what scenarios might a web crawler be CPU limited as opposed to IO limited? It seems like typical crawlers that just download a small number of pages or do very little processing to decide what pages to download are IO limited. I am curious as to what order of magnitude estimates of sizes relevant data structur...
In what scenarios might a web crawler be CPU limited as opposed to IO limited?
It seems like typical crawlers that just download a small number of pages or do very little processing to decide what pages to download are IO limited. I am curious as to what order of magnitude estimates of sizes relevant data structures, number of stored pages, indexing requirements etc that might actually make CPU t...
[ "Only when you are doing extensive processing on each page. eg if you are running some sort of AI to try to guess the semantics of the page.\nEven if your crawler is running on a really fast connection, there is still overhead creating connections, and you may also be limited by the bandwidth of the target machines...
[ 2, 1, 0, 0 ]
[]
[]
[ "c++", "java", "performance", "python", "web_crawler" ]
stackoverflow_0006079020_c++_java_performance_python_web_crawler.txt
Q: Mercurial API: hg.repository with https I'm trying to write a simple script that clones an existing Mercurial kiln repository that uses https authentications. I have this snippet: from mercurial import hg, ui repo = hg.repository(ui.ui(), "https://something.kilnhg.com/...") Normally, whenever I would clone this ...
Mercurial API: hg.repository with https
I'm trying to write a simple script that clones an existing Mercurial kiln repository that uses https authentications. I have this snippet: from mercurial import hg, ui repo = hg.repository(ui.ui(), "https://something.kilnhg.com/...") Normally, whenever I would clone this repo or something, Mercurial would ask me to ...
[ "You could try setting those directly to the url.\n\nhttps://username:password@something.kilnhg.com/...\n\n" ]
[ 4 ]
[]
[]
[ "api", "https", "mercurial", "python" ]
stackoverflow_0006081795_api_https_mercurial_python.txt
Q: python writing a list to a file incorrectly I am having an issue with writing a list to a file. I am annotating certain files to change them into a certain format, so I read sequence alignment files, store them in lists, do necessary formatting, and then write them to a new file. The problem is that while my list,...
python writing a list to a file incorrectly
I am having an issue with writing a list to a file. I am annotating certain files to change them into a certain format, so I read sequence alignment files, store them in lists, do necessary formatting, and then write them to a new file. The problem is that while my list, containing sequence alignments is structured cor...
[ "new.append(line.strip('*\\n'))\nnew.append('*')\n\nYou have a list of lines (with newline terminators each), so you need to include \\n for these two lines, too:\nnew.append(line[:-2] + \"\\n\") # slice as you just checked line.endswith(\"*\\n\")\nnew.append(\"*\\n\")\n\nRemember the strip (or slice, as I've chan...
[ 3 ]
[]
[]
[ "bioinformatics", "python", "text_processing" ]
stackoverflow_0006081805_bioinformatics_python_text_processing.txt
Q: Regex for tree structures? Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for. Here is an example that might clarify what I am looking for. <root> <node name="1"> subtrees .... </node> <node name="2"> ...
Regex for tree structures?
Are there regular expression equivalents for searching and modifying tree structures? Concise mini-languages (like perl regex) are what I am looking for. Here is an example that might clarify what I am looking for. <root> <node name="1"> subtrees .... </node> <node name="2"> <node name="2.1"> data ...
[ "TSurgeon and Tregex from Stanford is capable of doing that. You can download the library from http://nlp.stanford.edu/software/tregex.shtml\n", "I don't know a general purpose langugae that can do that, but it seems to me that you are looking for something like XPath.\n", "There is TXL for pattern based tree r...
[ 8, 5, 5, 1, 1, 1, 1 ]
[]
[]
[ "c", "java", "python", "regex", "tree_structure" ]
stackoverflow_0000875100_c_java_python_regex_tree_structure.txt
Q: python not correctly uploading to php I have a python script using mechanize to upload an image to a php script. The problem is that the image is 3,000kb yet only 52kb is showing on the server. HERE IS THE PYTHON: from mechanize import Browser br = Browser() br.open("http://www.mattyc.com/up") br.select_form(name=...
python not correctly uploading to php
I have a python script using mechanize to upload an image to a php script. The problem is that the image is 3,000kb yet only 52kb is showing on the server. HERE IS THE PYTHON: from mechanize import Browser br = Browser() br.open("http://www.mattyc.com/up") br.select_form(name="upper") br.form.add_file(open("tester.jpg"...
[ "Most likely, it's the PHP ini setting limiting the file upload size (upload_max_filesize).\nEdit: to check this setting, you can use: echo ini_get('upload_max_filesize');. If the size in there is 52KB, then you have your answer. Actually, if it's anything less than the size of the file you want to upload, then rai...
[ 1, 1 ]
[]
[]
[ "html", "mechanize", "php", "python" ]
stackoverflow_0004874702_html_mechanize_php_python.txt
Q: TeX in matplotlib on Mac OS X and TeX Live I have the following Hello World code to try out TeX rendering with matplotlib on my Mac. import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', family='serif') plt.text(2,2,r"Hello World!") plt.show() With that code, I'd get the f...
TeX in matplotlib on Mac OS X and TeX Live
I have the following Hello World code to try out TeX rendering with matplotlib on my Mac. import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', family='serif') plt.text(2,2,r"Hello World!") plt.show() With that code, I'd get the following error: sh: latex: command not found Exc...
[ "In future you might want to mention that you're running the code from NetBeans. The Python path is not $PATH, instead it's sys.path, the path from which Python code is loaded. You need to set os.environ['PATH'] in your Python code; with TeX Live the preferred way to reference the current TeX installation is /usr...
[ 13 ]
[]
[]
[ "macos", "matplotlib", "python", "tex" ]
stackoverflow_0006082126_macos_matplotlib_python_tex.txt
Q: Django produces blank pages when POST data is sent and Models are accessed I am pulling my hair out over this. I'm developing a webapp in Django 1.3 (recently upgraded from 1.2.5 in a feeble hope that this might solve my error) and I've come across a bizzare bug in one of my views. The view is called as an AJAX re...
Django produces blank pages when POST data is sent and Models are accessed
I am pulling my hair out over this. I'm developing a webapp in Django 1.3 (recently upgraded from 1.2.5 in a feeble hope that this might solve my error) and I've come across a bizzare bug in one of my views. The view is called as an AJAX request from the client. If I call the view as a GET request, all is fine and dand...
[ "This is going to be sort of an answer. It is rather a methodology so that you don't have this problem in the first place, but you can also use it to debug a problem if it happens.\n\nstart out by creating your requests using curl or with the firefox REST client plugin: \nThen you write your response code returning...
[ 1, 1 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0006081573_ajax_django_jquery_python.txt
Q: Color list to gtk Image How can i make a gtk.Image that is made from an list of gtk.gdk.Color. color_list = [gtk.gdk.Color(100*i,100*i,100*i) for i in range(10)] image = gtk.Image() draw_image_from_list(color_list, image) I need that procedure and the image would be just one column of pixels: |color1| |color2| |...
Color list to gtk Image
How can i make a gtk.Image that is made from an list of gtk.gdk.Color. color_list = [gtk.gdk.Color(100*i,100*i,100*i) for i in range(10)] image = gtk.Image() draw_image_from_list(color_list, image) I need that procedure and the image would be just one column of pixels: |color1| |color2| |color3| ...
[ "Here's a widget that almost does what you want: https://github.com/ptomato/LaserCam/blob/master/src/ColorMapIndicator.py\nIt's a gtk.DrawingArea instead of a gtk.Image, but I decided against using an image since they are more meant for displaying image files, not for drawing on. It displays the colors in a horizon...
[ 1 ]
[]
[]
[ "gtk", "image", "pixels", "pygtk", "python" ]
stackoverflow_0006080722_gtk_image_pixels_pygtk_python.txt
Q: raw_input or input does not complete by new line I am using Python language to program Cedrat Flux (a finite element software). Whatever Python commands I tried yet was O.K. But now I am trying to receive user information from command line using raw_input() or input(). Unfortunately despite normal Python it does n...
raw_input or input does not complete by new line
I am using Python language to program Cedrat Flux (a finite element software). Whatever Python commands I tried yet was O.K. But now I am trying to receive user information from command line using raw_input() or input(). Unfortunately despite normal Python it does not stop receiving characters by pressing New Line or E...
[ "raw_input(and input, but that distinction seems not relevant here) is just reading from stdin. You can do that manually by reading from sys.stdin:\nimport sys\nsys.stdin.read(1) # Read one character. '\\n' means newline\nsys.stdin.readline() # Read a single line, should be the same as raw_input()\n\nIf that does n...
[ 0, 0 ]
[]
[]
[ "input", "python" ]
stackoverflow_0006082468_input_python.txt
Q: how to get IP adress of a Host if its Mac address is known using python / scapy How can i get the IP address of a computer if its mac address is known , using python and scapy may be A: You might use the information from the arp cache: > arp -a localhost (10.37.129.2) at 0:1c:42:0:0:9 on vnic1 ifscope permanen...
how to get IP adress of a Host if its Mac address is known using python / scapy
How can i get the IP address of a computer if its mac address is known , using python and scapy may be
[ "You might use the information from the arp cache:\n> arp -a \nlocalhost (10.37.129.2) at 0:1c:42:0:0:9 on vnic1 ifscope permanent [ethernet]\nlocalhost (10.37.129.255) at ff:ff:ff:ff:ff:ff on vnic1 ifscope [ethernet]\nlocalhost (10.211.55.2) at 0:1c:42:0:0:8 on vnic0 ifscope permanent [ethernet]\nlocalhost (10.211...
[ 2, 1 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0006081729_networking_python.txt
Q: pythone ugettext hi: i have some code like this: from django.utils.translation import ugettext as _ def desc(): return _("%(user)s add this site") % { 'user': self.friendly_username(viewer, self.user)} ) if self.friendly_username(viewer, self.user) return a English name , this code will have ...
pythone ugettext
hi: i have some code like this: from django.utils.translation import ugettext as _ def desc(): return _("%(user)s add this site") % { 'user': self.friendly_username(viewer, self.user)} ) if self.friendly_username(viewer, self.user) return a English name , this code will have no problem , but if wh...
[ "I am not sure about the problem, as your code is not syntactically valid. In any case, I believe you want to do instead:\ndef desc():\n return _(\"%(user)s add this site\") % {\n 'user': self.friendly_username(viewer, self.user)}\n\nSo that your string does not depend on the user's name.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006081718_python.txt
Q: Python/Etree: Get text from element and its children I've got to use some HTML like this: <li><a href="#">S:</a><a class="#"> (n) </a><a href="#">trial</a>, <a href="#">trial run</a>, <b>test</b>, <a href="#">tryout</a> (trying something to find out about it) <i>"a sample for ten days free trial"; "a trial of prog...
Python/Etree: Get text from element and its children
I've got to use some HTML like this: <li><a href="#">S:</a><a class="#"> (n) </a><a href="#">trial</a>, <a href="#">trial run</a>, <b>test</b>, <a href="#">tryout</a> (trying something to find out about it) <i>"a sample for ten days free trial"; "a trial of progesterone failed to relieve the pain"</i></li> The problem...
[ "The lxml changelog shows lxml v2.3 is compatible with python 3.1.2 and newer. \nAlso you could use regexp re.sub(r'<[^>]*?>', '', val) as Python's equivalent to PHP's strip_tags said.\n", "You can do this using lxml.html.\nIn [1]: import lxml.html\n\nIn [2]: el = lxml.html.fromstring('<li><a href=\"#\">S:</a><a ...
[ 1, 0 ]
[]
[]
[ "elementtree", "html", "parsing", "python", "xml" ]
stackoverflow_0006082501_elementtree_html_parsing_python_xml.txt
Q: In Python, what's difference between some_string.lower() and str.lower(some_string) I am confused with built-in method in Python. For instance, what is the some_string.lower() and str.lower(some_string) and how are they different? A: str is the name of the class of all strings in Python. str.lower is one of its ...
In Python, what's difference between some_string.lower() and str.lower(some_string)
I am confused with built-in method in Python. For instance, what is the some_string.lower() and str.lower(some_string) and how are they different?
[ "str is the name of the class of all strings in Python. str.lower is one of its methods.\nIf you call lower on one of its instances (e.g. 'ABC'.lower()), you call a bound method, which automatically sends the called object as the first argument (usually called self).\nIf you call lower on the class itself (i.e. you...
[ 10, 3 ]
[]
[]
[ "built_in", "methods", "python" ]
stackoverflow_0006083090_built_in_methods_python.txt
Q: for python how can i use my application's console to execute one of my commands I apologize if I didn't explain this well enough but I want to know how I could use my console in my app to take an input like "add 5 4" so it would actually add 5+4 instead of just printing it out. I really just need a function that c...
for python how can i use my application's console to execute one of my commands
I apologize if I didn't explain this well enough but I want to know how I could use my console in my app to take an input like "add 5 4" so it would actually add 5+4 instead of just printing it out. I really just need a function that could take the string "add 5 4" and recognize i started with the word add.
[ "If you want to make a fully-fledged interpreter, I would say learn pyParsing.\nOtherwise,\ndef parse(string):\n words = string.rsplit()\n if words[0] == \"add\":\n print int(word[1]) + int(word[2])\n\nparse(raw_input());\n\nNotice that I'm doing absolutely no error checking, you should have that in yo...
[ 1 ]
[]
[]
[ "console", "function", "python", "string" ]
stackoverflow_0006083243_console_function_python_string.txt
Q: Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant Trying to learn Regex in Python to find words that have consecutive vowel-consonant or consonant-vowel combinations. How would I do this in regex? If it can't be done in Regex, is there an efficient way of doing this in Python?...
Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant
Trying to learn Regex in Python to find words that have consecutive vowel-consonant or consonant-vowel combinations. How would I do this in regex? If it can't be done in Regex, is there an efficient way of doing this in Python?
[ "I believe you should be able to use a regular expression like this:\nr\"([aeiou][bcdfghjklmnpqrstvwxz])+\"\n\nfor matching vowel followed by consonant and:\nr\"([bcdfghjklmnpqrstvwxz][aeiou])+\"\n\nfor matching consonant followed by vowel. For reference, the + means it will match the largest repetition of this pa...
[ 11, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006080008_python_regex.txt
Q: Horizontally oriented listbox using Python and Tkinter I want to provide a listbox where the user can select (multiple) characters (usually close to 15). Quite often some of these will be sequenced, so a listbox is easier than a validated text entry field. Since the character combination has a meaning to the user,...
Horizontally oriented listbox using Python and Tkinter
I want to provide a listbox where the user can select (multiple) characters (usually close to 15). Quite often some of these will be sequenced, so a listbox is easier than a validated text entry field. Since the character combination has a meaning to the user, it is user friendly to orient the listbox horizontally. Is ...
[ "No, there is no setting, subclass or theme that will let you do that with a listbox.\nWhat you might want to use instead is a set of check buttons with the indicator turned off so they each appear as a button with a single letter. You can then pack them all horizontally in a frame. With the indicator off, the butt...
[ 2 ]
[]
[]
[ "listbox", "python", "tkinter" ]
stackoverflow_0006082723_listbox_python_tkinter.txt
Q: Order of keys in dictionary I have a dictionary {'a': 'first', 'b': 'second'} However, I need the dictionary in a different order: {'b': 'second', 'a': 'first'} What is the best way to do this? A: Dictionaries are not ordered. So there is no way to do it. If you have python2.7+, you can use collections.Ordered...
Order of keys in dictionary
I have a dictionary {'a': 'first', 'b': 'second'} However, I need the dictionary in a different order: {'b': 'second', 'a': 'first'} What is the best way to do this?
[ "Dictionaries are not ordered. So there is no way to do it.\nIf you have python2.7+, you can use collections.OrderedDict - in this case you could retrieve the item list using .items() and then reverse it and create a new OrderedDict from the reversed list:\n>>> od = OrderedDict((('a', 'first'), ('b', 'second')))\n>...
[ 41, 8, 4 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006083531_dictionary_python.txt
Q: How to pass Selenium object to another class? Im having trouble calling my original selenium instance in my 2nd class which has a function GetRows(). What are the ways i can get the selenium object in my Functions Class? Class test(unittest.TestCase): def setUp(self): self.verificationerrors=[] ...
How to pass Selenium object to another class?
Im having trouble calling my original selenium instance in my 2nd class which has a function GetRows(). What are the ways i can get the selenium object in my Functions Class? Class test(unittest.TestCase): def setUp(self): self.verificationerrors=[] self.selenium = selenium("localhost",4444,"","http...
[ "Your second class either extend or instantiate your \"test\" class, which is responsible for creation of Selenium object\n", "The way that I would do it is to abstract all that you need to do to your second class and have your test just calling that.\nSo your test class would look like this\nclass SearchTests(un...
[ 0, 0 ]
[]
[]
[ "class", "python", "selenium" ]
stackoverflow_0006066782_class_python_selenium.txt
Q: Why would connection refused when client and server is running on the same process? I'm having a problem running a client and server in the same process. Every time I try to connect my client to the server, it would give me this error: Traceback (most recent call last): File "dirWatch.py", line 78, in <module> sta...
Why would connection refused when client and server is running on the same process?
I'm having a problem running a client and server in the same process. Every time I try to connect my client to the server, it would give me this error: Traceback (most recent call last): File "dirWatch.py", line 78, in <module> startDirWatch(sLink) File "dirWatch.py", line 68, in startDirWatch sC.client('/home/homer/Do...
[ "My first guess would simply be that when the client tries to connect, the server thread hasn't really gotten going yet; the client is connecting but nothing is listening. It takes substantial time to create a thread and transfer control to it. You could either sleep before the client connect, or retry it a few tim...
[ 1, 1 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0006083999_networking_python_sockets.txt
Q: django: exclude certain form elements based on a condition I have some form fields that I want to include/exclude based on whether or not a certain condition is met. I know how to include and exclude form elements, but I am having difficulty doing it when I want it elements to show based on the outcome of a functi...
django: exclude certain form elements based on a condition
I have some form fields that I want to include/exclude based on whether or not a certain condition is met. I know how to include and exclude form elements, but I am having difficulty doing it when I want it elements to show based on the outcome of a function. Here is my form: class ProfileForm(ModelForm): # this_te...
[ "This is actually fairly straightforward (conditional field settings) - here's a quick example:\nfrom django.forms import Modelform\nfrom django.forms.widgets import HiddenInput\n\nclass SomeForm(ModelForm):\n\n def __init__(self, *args, **kwargs):\n # call constructor to set up the fields. If you don't d...
[ 7, 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0006083104_django_forms_python.txt
Q: Python: Code for VHDL Code Generator I am trying to make a ROM in VHDL language, I am using this template I found on http://www.edaboard.com/thread38052.html : library ieee; use ieee.std_logic_1164.all; entity ROM is port ( address : in std_logic_vector(3 downto 0); data : out std_logic_vector(7 downto 0) );...
Python: Code for VHDL Code Generator
I am trying to make a ROM in VHDL language, I am using this template I found on http://www.edaboard.com/thread38052.html : library ieee; use ieee.std_logic_1164.all; entity ROM is port ( address : in std_logic_vector(3 downto 0); data : out std_logic_vector(7 downto 0) ); end entity ROM; architecture behavioral ...
[ "As an alternative to the other answers, make your ROM store naturals or integers (as appropriate). Then your constant can be of the form:\n0 => 45,\n1 => 56, ...\n\netc.\nIf you have all the values already, you could just put them all in a big comma separator series without doing the n => positional mapping.\n(45,...
[ 5, 5, 4, 2 ]
[]
[]
[ "code_generation", "python", "rom", "vhdl" ]
stackoverflow_0004967091_code_generation_python_rom_vhdl.txt
Q: Are there drawbacks to inheriting from the db.Expando class in AppEngine? I'm thinking about making all my models inherit from the db.Expando class in order to support a loose denormalization protocol whereby selected attributes of models referenced by db.ReferenceProperty would be set on the owning class also. cl...
Are there drawbacks to inheriting from the db.Expando class in AppEngine?
I'm thinking about making all my models inherit from the db.Expando class in order to support a loose denormalization protocol whereby selected attributes of models referenced by db.ReferenceProperty would be set on the owning class also. class ImgModel(db.Expando): height = db.IntegerProperty() width = db.Inte...
[ "To answer the title, most of the drawbacks of using dynamic properties are just about losing the benefits of property definitions: having to test for existence of some_attribute on object, not being able to query for entities with some_attribute unset, missing results from queries where the value on the entity has...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006084072_google_app_engine_python.txt
Q: Python subprocess that asks for password I'd like to call scp from Python script. subprocess.call doesn't work because scp asks for password. Someone asked same question last year and the answer was to use Pexpect. Is there some quick hack for this that doesn't involve installing Pexpect library? I tried echo pass...
Python subprocess that asks for password
I'd like to call scp from Python script. subprocess.call doesn't work because scp asks for password. Someone asked same question last year and the answer was to use Pexpect. Is there some quick hack for this that doesn't involve installing Pexpect library? I tried echo password | scp ... and it still asks for password ...
[ "Given that you don't want to use Pexpect, why not use a key pair?\n" ]
[ 2 ]
[]
[]
[ "python", "scp" ]
stackoverflow_0006084471_python_scp.txt
Q: Preserve POST variables during login redirect in GAE? in a form, I submit data to a python webapp handler (all Google App Engine based) using a HTTP POST request. In this script, I first check if the user is logged in and if not, I use users.create_login_url(...) to redirect the user first to the login page. How c...
Preserve POST variables during login redirect in GAE?
in a form, I submit data to a python webapp handler (all Google App Engine based) using a HTTP POST request. In this script, I first check if the user is logged in and if not, I use users.create_login_url(...) to redirect the user first to the login page. How can I ensure that after login the user is not just forwarded...
[ "Normally, I'd store it in session variables. I've used gae-sessions before and found it easy. It persists to the datastore and memcaches behind the scenes for speed. Looks like this:\nfrom gaesessions import get_current_session\nsession = get_current_session()\nif session.is_active():\n c = session.get('coun...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "http_post", "python" ]
stackoverflow_0006084123_google_app_engine_http_post_python.txt
Q: Google AppEngine complex WHERE condition I want to have a condition something like start_time <= start_time_input <= end_time OR start_time <= end_time_input <= end_time OR (start_time_input <= start_time AND end_time <= end_time_input ) The 2 ways as identified in the docs ( http://code.google.com/appengine/do...
Google AppEngine complex WHERE condition
I want to have a condition something like start_time <= start_time_input <= end_time OR start_time <= end_time_input <= end_time OR (start_time_input <= start_time AND end_time <= end_time_input ) The 2 ways as identified in the docs ( http://code.google.com/appengine/docs/python/datastore/queries.html and http://co...
[ "GQL doesn't have an OR. See http://code.google.com/appengine/docs/python/datastore/gqlreference.html\nYou'll need to do this as multiple queries.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python", "where_clause" ]
stackoverflow_0006084622_google_app_engine_gql_gqlquery_python_where_clause.txt
Q: Changing python math module behaviour for non-positive numbers division Non-positive number division is quite different in c++ and python programming langugages: //c++: 11 / 3 = 3 11 % 3 = 2 (-11) / 3 = -3 (-11) % 3 = -2 11 / (-3) = -3 11 % (-3) = 2 (-11) / (-3) = 3 (-11) % (-3) = -2 So, as you can see, c++ is mi...
Changing python math module behaviour for non-positive numbers division
Non-positive number division is quite different in c++ and python programming langugages: //c++: 11 / 3 = 3 11 % 3 = 2 (-11) / 3 = -3 (-11) % 3 = -2 11 / (-3) = -3 11 % (-3) = 2 (-11) / (-3) = 3 (-11) % (-3) = -2 So, as you can see, c++ is minimizing quotient. However, python behaves like that: #python 11 / 3 = 3 11 %...
[ "As Thomas K said, use math.fmod for modulo, or if you really want you can define it yourself:\ndef cmod(x, y):\n return abs(x) % abs(y) * (1 if x > 0 else -1)\n\nAnd this function should emulate C-style division:\ndef cdiv(x, y):\n return abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)\n\n\nYou said that you must us...
[ 3, 2, 0 ]
[]
[]
[ "c++", "integer_division", "python" ]
stackoverflow_0006084438_c++_integer_division_python.txt
Q: How to set a file's ctime with Python? How can I set a Unix file's ctime? (I'd much prefer an answer in terms of Python. If there's no way to do it with standard Python, then I suppose C is OK too.) (Note: I know that one can use os.utime to set a file's atime and mtime. I am interested in setting ctime.) (Note2...
How to set a file's ctime with Python?
How can I set a Unix file's ctime? (I'd much prefer an answer in terms of Python. If there's no way to do it with standard Python, then I suppose C is OK too.) (Note: I know that one can use os.utime to set a file's atime and mtime. I am interested in setting ctime.) (Note2: I hope that there's an answer that works f...
[ "It is relatively trivial to set a files ctime to the current time. Just modify its mtime, flip a permission bit or even make a hardlink to it. It is, AFAIK, impossible to set a file's ctime to an arbitrary value using the system call API in any direct sort of way.\nIf you had root access you could set the system t...
[ 9 ]
[]
[]
[ "ctime", "python", "stat", "unix" ]
stackoverflow_0006084985_ctime_python_stat_unix.txt
Q: psycopg2 install mutliple versions of python I have two version of python. I would like to install psycopg2 for python2.5 How can I run sudo apt-get install python-psycopg2 so it installs it for python2.5 and not python2.6 ? Thanks A: The ubuntu-10.04 package python-psycopg2 is designed to work with the default ...
psycopg2 install mutliple versions of python
I have two version of python. I would like to install psycopg2 for python2.5 How can I run sudo apt-get install python-psycopg2 so it installs it for python2.5 and not python2.6 ? Thanks
[ "The ubuntu-10.04 package python-psycopg2 is designed to work with the default python2.6 installation. \nTo install psycopg2 for python2.5, download the psycopg source and use \npython2.5 setup.py install\n\nto install it. (Note the call to python2.5).\n" ]
[ 3 ]
[]
[]
[ "linux", "python", "ubuntu_10.04" ]
stackoverflow_0006085000_linux_python_ubuntu_10.04.txt
Q: how to upload files to PHP server with use of Python? I was wondering is there any tutorial out there that can teach you how to push multiple files from desktop to a PHP based web server with use of Python application? Edited I am going to be writing this so I am wondering in general what would be the best method ...
how to upload files to PHP server with use of Python?
I was wondering is there any tutorial out there that can teach you how to push multiple files from desktop to a PHP based web server with use of Python application? Edited I am going to be writing this so I am wondering in general what would be the best method to push files from my desktop to web server. As read from s...
[ "I'm assuming you own the PHP server.\n\nUse FTP. See here and here.\nMake a file upload form with PHP, and use python to fill out the form. See this and this.\n(Usually a bad idea) Use PHP to write small server that listens for data and then writes it to a file. \n\n", "I think you're referring to a application ...
[ 2, 1 ]
[]
[]
[ "file_upload", "php", "python" ]
stackoverflow_0006085280_file_upload_php_python.txt
Q: How to render file-based template with arguments? from mako.template import Template stext = "hi" mytemplate = Template(filename='./t.txt') print mytemplate.render() t.txt: ${hi} , i am here A: Replace the last line with: mytemplate.render(hi = "world") Now, hi can equal anything you like, not just "world"....
How to render file-based template with arguments?
from mako.template import Template stext = "hi" mytemplate = Template(filename='./t.txt') print mytemplate.render() t.txt: ${hi} , i am here
[ "Replace the last line with:\nmytemplate.render(hi = \"world\")\n\nNow, hi can equal anything you like, not just \"world\". \n" ]
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0006085282_mako_python.txt
Q: How do you control the Python prompt with a middle-man application? How do you get a new application to stand between , like an I/O filter, the python prompt and the Python software? So that it would pass most stuff through to Python , unchanged , but some domain-specific paragraphs that the end-user types in , wo...
How do you control the Python prompt with a middle-man application?
How do you get a new application to stand between , like an I/O filter, the python prompt and the Python software? So that it would pass most stuff through to Python , unchanged , but some domain-specific paragraphs that the end-user types in , would be handled by a pre-parser, translated to python-legal syntax, and th...
[ "I would recommend you look at this, this and if your DSL is going to really differ from Python, this and this.\nAlso, I would also recommend you look into Ruby as it is very easy to write domain specific languages in it. And, despite what a lot of people say, its not just for web development and ruby 1.9 speeds ar...
[ 1 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0006085019_python_statistics.txt
Q: Python doesn't see submodules when running under coverage and nose I get an import error when I use coverage.py to run a suite of tests where nose is the underlying test runner. The tests run fine if I just run under Python instead. coverage run run_tests.py ERROR ================================================...
Python doesn't see submodules when running under coverage and nose
I get an import error when I use coverage.py to run a suite of tests where nose is the underlying test runner. The tests run fine if I just run under Python instead. coverage run run_tests.py ERROR ====================================================================== ERROR: <nose.suite.ContextSuite context=nova.test...
[ "This was a problem with coverage.py. When it inserted the current directory into the sys.path list, it didn't use an absolute path, which somehow caused this problem. Coverage.py is now fixed: https://bitbucket.org/ned/coveragepy/changeset/811ed58de8a3\n" ]
[ 2 ]
[]
[]
[ "coverage.py", "nose", "python", "python_coverage" ]
stackoverflow_0006076295_coverage.py_nose_python_python_coverage.txt
Q: Loading DLC files in Python or C++ or Java Is there any Libraries that allow for loading of DLC files in Python Java or C++? FYI link A: jDownloader is written in java and handles DLC files. Its open source. http://jdownloader.org/knowledge/wiki/development/get-started svn://svn.jdownloader.org/jdownloader/tru...
Loading DLC files in Python or C++ or Java
Is there any Libraries that allow for loading of DLC files in Python Java or C++? FYI link
[ "jDownloader is written in java and handles DLC files. Its open source.\nhttp://jdownloader.org/knowledge/wiki/development/get-started\nsvn://svn.jdownloader.org/jdownloader/trunk\n" ]
[ 0 ]
[]
[]
[ "c++", "java", "python" ]
stackoverflow_0006085494_c++_java_python.txt
Q: How to use list comprehension in python? How do I use list comprehension for doing this: MCs= [['foo', 180.9], ['bar', 163.5], ['noo', 140.3]] Want [['foo'], ['bar'], ['noo']] using MCs = [list(x[0]) for x in MCs] I get this: [['f', 'o', 'o'], ['b', 'a', 'r'], ['n', 'o', 'o']] A: You only need this:...
How to use list comprehension in python?
How do I use list comprehension for doing this: MCs= [['foo', 180.9], ['bar', 163.5], ['noo', 140.3]] Want [['foo'], ['bar'], ['noo']] using MCs = [list(x[0]) for x in MCs] I get this: [['f', 'o', 'o'], ['b', 'a', 'r'], ['n', 'o', 'o']]
[ "You only need this:\nMCs = [[x[0]] for x in MCs]\n\nStrings are iterable, and list(iterable) returns a list of elements yielded by the argument (i.e. characters, in this case).\n", "That's because x[0] is e.g. 'foo' and list turns an iterable into a list containing the items of the iterable - iterating a string ...
[ 6, 5, 3, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006084656_list_python.txt
Q: Redis Crash Windows Server 2003 R2 I’m running redis, 32bit, 2.0.2 from the cygwin compilation here: http://code.google.com/p/servicestack/wiki/RedisWindowsDownload I am running it from the terminal. It works great for about 24 hours and then it crashes, no errors, it just closes. My config file I have defaults...
Redis Crash Windows Server 2003 R2
I’m running redis, 32bit, 2.0.2 from the cygwin compilation here: http://code.google.com/p/servicestack/wiki/RedisWindowsDownload I am running it from the terminal. It works great for about 24 hours and then it crashes, no errors, it just closes. My config file I have defaults except: # save 900 1 # save 300 10 # sa...
[ "Redis does is not supposed to work with Windows, and the projects that try to make it work with windows all have numerous bugs that make them unstable.\n" ]
[ 0 ]
[]
[]
[ "celery", "python", "redis", "twisted" ]
stackoverflow_0006077138_celery_python_redis_twisted.txt
Q: Handling of ConnectionLost exception in twisted I can not handle a ConnectionLost exception. Brief example of what I have. First of all iIset up connection to jabber server and ping it. I use wokkel library for that. Then I add errback to the method that is sending ping. In the errback I handle the ConnectionLost ...
Handling of ConnectionLost exception in twisted
I can not handle a ConnectionLost exception. Brief example of what I have. First of all iIset up connection to jabber server and ping it. I use wokkel library for that. Then I add errback to the method that is sending ping. In the errback I handle the ConnectionLost error. After that, I close the internet connection. B...
[ "Protocol has:\nclientConnectionFailed(self, connector, reason)\nclientConnectionLost(self, connector, reason)\n\nyou can override both and call\nPingClientProtocol.clientConnectionFailed\nand PingClientProtocol.clientConnectionLost\nassuming that PingClientProtocol inherit somehow from Protocol\n" ]
[ 2 ]
[]
[]
[ "error_handling", "python", "twisted" ]
stackoverflow_0004855720_error_handling_python_twisted.txt
Q: Silencing OSX crash report window I have a python application which uses a compiled shared library. This library for some reason crashes with a segfault every time the app throws an exception. OSX catches the segfault somehow and shows a report crash window. How can I shut off this window once and for all ? A: Y...
Silencing OSX crash report window
I have a python application which uses a compiled shared library. This library for some reason crashes with a segfault every time the app throws an exception. OSX catches the segfault somehow and shows a report crash window. How can I shut off this window once and for all ?
[ "You can disable the crash reporter globally, but I don't think there is a way to disable it locally. This web site has details: http://hints.macworld.com/article.php?story=20091230100541242. Basically, you can use /Developer/Applications/Utilities/CrashReporterPrefs if you have XCode installed. Otherwise, you c...
[ 3 ]
[]
[]
[ "crash_reports", "macos", "python" ]
stackoverflow_0006084497_crash_reports_macos_python.txt
Q: Sum of values in a dict I want to have sum of values in a dict. Below is the code which I have written. results = collections.defaultdict(dict) for main, month, tot in list_data: d = results[main] d[month] = tot d.setdefault('total', 0) d['total'] += tot result_output = dict(results) Above code ...
Sum of values in a dict
I want to have sum of values in a dict. Below is the code which I have written. results = collections.defaultdict(dict) for main, month, tot in list_data: d = results[main] d[month] = tot d.setdefault('total', 0) d['total'] += tot result_output = dict(results) Above code gives below ouput: {u'Apple':...
[ "How about this? (Untested)\nfrom collections import defaultdict\nfrom functools import partial\n\nresults = defaultdict(partial(defaultdict, int))\nfor main, month, tot in list_data:\n results[main][month] += tot\n results[main][\"total\"] += tot\n results[u\"grandtotal\"][month] += tot\nresult_output = d...
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006084444_python.txt
Q: Address of Dragged File in Windows How can I know what is the address of dragged file or folder in windows explorer with Python? A: I think the filename path, the function that handles a 'drop' normally has a struct with the data you need, but python itself does not provides a gui to drop files, what widget fram...
Address of Dragged File in Windows
How can I know what is the address of dragged file or folder in windows explorer with Python?
[ "I think the filename path, the function that handles a 'drop' normally has a struct with the data you need, but python itself does not provides a gui to drop files, what widget framework are you using?\n" ]
[ 0 ]
[]
[]
[ "drag", "path", "python", "windows" ]
stackoverflow_0005961379_drag_path_python_windows.txt
Q: How to calculate numerical trend lines in python I have a monitoring application in python 2.6 that calculates the number of entries in a queue (queue_len). I want to create a simple function that can use these queue_len rate of change values over time and extract a trend from them. The goal is to start up or shut...
How to calculate numerical trend lines in python
I have a monitoring application in python 2.6 that calculates the number of entries in a queue (queue_len). I want to create a simple function that can use these queue_len rate of change values over time and extract a trend from them. The goal is to start up or shut down queue processing nodes depending of the +ive or ...
[ "Isn't that just a simple derivative?\ndef derivs(l):\n return [l[i + 1] - l[i] for i in range(len(l) - 1)]\n\n" ]
[ 1 ]
[]
[]
[ "algorithmic_trading", "graph_algorithm", "math", "python", "trending" ]
stackoverflow_0006085713_algorithmic_trading_graph_algorithm_math_python_trending.txt
Q: Memory leak while looping web.client.getPage function I have a page what refresh periodically using this script: from twisted.web.client import getPage from twisted.internet import reactor, task def getData(): dgp = getPage('http://www.google.com/') dgp.addCallback(dataLoadOK) dgp.addErrback(dataLoadE...
Memory leak while looping web.client.getPage function
I have a page what refresh periodically using this script: from twisted.web.client import getPage from twisted.internet import reactor, task def getData(): dgp = getPage('http://www.google.com/') dgp.addCallback(dataLoadOK) dgp.addErrback(dataLoadError) def dataLoadOK(value): print value def dataLoad...
[ "Try some strategies recommended in related questions. However, it is likely that you don't have a memory leak, you just have memory fragmentation.\nIt looks like the \"Python memory leak detector\" has a pretty severe bug. It enables DEBUG_LEAK which prevents all cycles from being collected. Put another way, it...
[ 3, 2 ]
[]
[]
[ "memory_leaks", "python", "twisted" ]
stackoverflow_0006084200_memory_leaks_python_twisted.txt
Q: add field first_name and last_name in django-profile I need add the first_name and last_name fields associated with that User model and display it in the profile form. fields: >>> user = User.objects.get(pk=1) >>> user.first_name u'Some' >>> user.last_name u'User' My model is something li...
add field first_name and last_name in django-profile
I need add the first_name and last_name fields associated with that User model and display it in the profile form. fields: >>> user = User.objects.get(pk=1) >>> user.first_name u'Some' >>> user.last_name u'User' My model is something like this : class UserProfile(models.Model): user = models...
[ "Assuming you are using a ModelForm you could do the following:\nclass profileForm(ModelForm):\n first_name = forms.CharField(max_length=30, required=False)\n last_name = forms.CharField(max_length=30, required=False)\n class Meta:\n model = UserProfile\n\n def save(self, commit=True):\n ...
[ 4 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0006085452_django_django_forms_django_models_python.txt
Q: Calculate web page size in python How would I go about calculating the size of a web page (url) using Python. I tried urllib2 and grabbing the content-length header but it wasn't present. import urllib2 url = 'http://www.google.com/' r = urllib2.urlopen(url) #Not sure what to do from here A: When you use urlope...
Calculate web page size in python
How would I go about calculating the size of a web page (url) using Python. I tried urllib2 and grabbing the content-length header but it wasn't present. import urllib2 url = 'http://www.google.com/' r = urllib2.urlopen(url) #Not sure what to do from here
[ "When you use urlopen, you are going requesting the whole contents (an HTTP GET request) so looking for the optional content-length header is not all that useful, once you've gone that way (it's OK, saves you some time and memory, but you have imposed avoidable load on the server and network). Still, as the existi...
[ 5, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001611376_python.txt
Q: How to crawl a web page for files of certain size I need to crawl a list of several thousand hosts and find at least two files rooted there that are larger than some value, given as an argument. Can any popular (python based?) tool possibly help? A: Here is an example of how you can get the filesize of an file o...
How to crawl a web page for files of certain size
I need to crawl a list of several thousand hosts and find at least two files rooted there that are larger than some value, given as an argument. Can any popular (python based?) tool possibly help?
[ "Here is an example of how you can get the filesize of an file on a HTTP server.\nimport urllib2\n\ndef sizeofURLResource(url):\n \"\"\"\n Return the size of an resource at 'url' in bytes\n \"\"\"\n info = urllib2.urlopen(url).info()\n return info.getheaders(\"Content-Length\")[0]\n\nThere is also an...
[ 2, 1 ]
[]
[]
[ "filesize", "python", "web_crawler" ]
stackoverflow_0005518927_filesize_python_web_crawler.txt
Q: Threading question so i have the code : from Tkinter import * from urllib2 import * import thread Admin = Tk() def download(): def dwnload(): def Listen(): os.startfile(filepath) chunks = 100000 dat = '' runum = runums.replace(' ', '%20') song = '3 roun...
Threading question
so i have the code : from Tkinter import * from urllib2 import * import thread Admin = Tk() def download(): def dwnload(): def Listen(): os.startfile(filepath) chunks = 100000 dat = '' runum = runums.replace(' ', '%20') song = '3 rounds and a sound' ...
[ "thread is a low-level interface to threads, I would suggest using threading, which actually has meaningful exceptions. And, make sure there is absolutely no convergence between Tkinter and your second thread, because locking is a very, very, painful thing.\nI thing you may need locking in the download function.\n"...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006085941_python_tkinter.txt
Q: Get 20 Random Records using AppEngine (Python) Possible Duplicate: How to get something random in datastore (AppEngine)? I'm trying to get 20 random records from a current set of 200, which I'm assuming will grow to 20,000+ within the month. Using Python in Google AppEngine. It's for a iPhone API where a User c...
Get 20 Random Records using AppEngine (Python)
Possible Duplicate: How to get something random in datastore (AppEngine)? I'm trying to get 20 random records from a current set of 200, which I'm assuming will grow to 20,000+ within the month. Using Python in Google AppEngine. It's for a iPhone API where a User can click "refresh" to get another random 20. I've ...
[ "App engine doesn't support queries on an arbirary selection of entities. The best bet you might have is to add a property to the entity in question and give it a random integer value(in the range of, say 0 .. 2**64-1, at the time it's created. \nthen you'll just be fetching one entity at a time based on that va...
[ 2, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006079555_google_app_engine_python.txt
Q: Manipulate a number algorithm How can I fix this algo? def change_num(n, direc, numMove): if direc == 'back': nums = range(10) return nums[n-numMove] elif direc == 'forward': nums = range(10) nums.reverse() return nums[n-numMove]-1 This doesn't work for direc == 'b...
Manipulate a number algorithm
How can I fix this algo? def change_num(n, direc, numMove): if direc == 'back': nums = range(10) return nums[n-numMove] elif direc == 'forward': nums = range(10) nums.reverse() return nums[n-numMove]-1 This doesn't work for direc == 'back' here are some sample expected ...
[ "Instead of 'back' and 'forward', it will be easier to pass +1 for forward and -1 for back. Then your function simplifies to\ndef change_num(n, direc, num_move):\n return (n + direc * num_move) % 10\n\n", "def change_num(n, direc, numMove):\n d = {'back' : -1, 'forward' : 1}\n return (n + d[direc]*numMove...
[ 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006064462_python.txt
Q: What are some techniques I could use to help gain a better understanding of how the concepts in discrete math are used in programming? I am trying to gain a better understanding of how discrete math concepts (e.g. set theory) are used in programming. I am familiar with high-school mathematics and have basic under...
What are some techniques I could use to help gain a better understanding of how the concepts in discrete math are used in programming?
I am trying to gain a better understanding of how discrete math concepts (e.g. set theory) are used in programming. I am familiar with high-school mathematics and have basic understanding of the terms and concepts used in discrete mathematics I understand languages like Haskell, Lisp, Ruby, Perl, and all C-based langu...
[ "If I were you I wouldn't buy any book. \nI would write a small program for each topic in discrete math. For the topic of set theory I would write a program that perform set operations like unions, intersections, difference etc. \nA simple example, take a list of customers that have bought product p1, then a list ...
[ 5 ]
[]
[]
[ "discrete_mathematics", "java", "python" ]
stackoverflow_0006012641_discrete_mathematics_java_python.txt
Q: py2exe: why are some standard modules NOT included? My python program uses plugins (python files) which I import dynamically using __import__. I bundle my python program into a Windows exe using py2exe. I've just spend searching 2 hours why my plugin python file couldn't be loaded properly from the .exe version. ...
py2exe: why are some standard modules NOT included?
My python program uses plugins (python files) which I import dynamically using __import__. I bundle my python program into a Windows exe using py2exe. I've just spend searching 2 hours why my plugin python file couldn't be loaded properly from the .exe version. I got an ImportError: "no module named urllib2" It appear...
[ "To see which modules are included look inside the library.zip (if there is no library.zip file - then try opening the EXE in any ZIP application - or rename it to .ZIP and try and open it).\nYou will be able to see a list of *.pyc. You can look at the list of files and directories to get an impression of which mo...
[ 4 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0006084632_py2exe_python_windows.txt
Q: Pagination with google app engine I have several questions regarding how to do pagination with gae. test code: for i in range(0, 6): MyClass(myProperty=unicode(i)).put() q = MyClass.all() cursor = None print haveMore = True batchSize = 2 i = 1 while haveMore: print '...
Pagination with google app engine
I have several questions regarding how to do pagination with gae. test code: for i in range(0, 6): MyClass(myProperty=unicode(i)).put() q = MyClass.all() cursor = None print haveMore = True batchSize = 2 i = 1 while haveMore: print 'Batch', i i = i + 1 res...
[ "Have a look here Query with paging by cursor causes error because of limitations for \"IN filter\" in cursor() method... What should be the alternative?\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006085257_google_app_engine_python.txt
Q: Django database connection error: "sqlite3.OperationalError: unable to open database file" So I just created a new project and app for the blog. When I try and syncdb it says: "sqlite3.OperationalError: unable to open database file" I saw the noob FAQ and it says the possible errors are having an incorrect path or...
Django database connection error: "sqlite3.OperationalError: unable to open database file"
So I just created a new project and app for the blog. When I try and syncdb it says: "sqlite3.OperationalError: unable to open database file" I saw the noob FAQ and it says the possible errors are having an incorrect path or not giving apache permission to write to the folder. Here is a dpaste with my settings.py and ...
[ "You need to give the path to the database file, look at your database settings:\n'NAME': '/home/vmplanet/code/blog', # Or path to database file if using sqlite3.\n\n...which is presumably the project directory. Try /home/vmplanet/code/blog/blog.db.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006086268_django_python.txt
Q: What is the difference between python string concatenation and string insertion I want to know what is the diff between two string operations in python filestamp = time.strftime('%Y-%m-%d') database = "mysql"; Between this filename = "/home/vmware/%s-%s.sql" % (database, filestamp) and filename = "/home/vmware/...
What is the difference between python string concatenation and string insertion
I want to know what is the diff between two string operations in python filestamp = time.strftime('%Y-%m-%d') database = "mysql"; Between this filename = "/home/vmware/%s-%s.sql" % (database, filestamp) and filename = "/home/vmware/"+database+"-"+filestamp+".sql"
[ "String interpolation using the '%' operators take the types of the interpolated values into account. String concatentation using the '+' will only work for strings. So you can't mix strings with numbers using the '+' operator. In general: string interpolation is what you want - at least for building strings from o...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006086466_python.txt
Q: Python- What word can have the most consecutive letters removed and still be a dictionary-valid word? I used this hideous and inefficient implementation to find the word that can have the most consecutive last letters removed and still be a word. Rodeo, for example, is a well-known one: Rodeo, Rode, Rod, Ro. The p...
Python- What word can have the most consecutive letters removed and still be a dictionary-valid word?
I used this hideous and inefficient implementation to find the word that can have the most consecutive last letters removed and still be a word. Rodeo, for example, is a well-known one: Rodeo, Rode, Rod, Ro. The program found 'composers': Composers, Composer, Compose, Compos, Comp I was wondering how I should go about ...
[ "for each english word W:\n for each letter you can remove:\n remove the letter\n if the result W' is also word:\n draw a line W->W'\nfor each english word W:\n connect ROOT-> each english word W\nuse a graph search algorithm to find the longest path starting at ROOT\n (specificall...
[ 10, 8, 1 ]
[]
[]
[ "algorithm", "performance", "python", "word" ]
stackoverflow_0006084795_algorithm_performance_python_word.txt