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 fetch content of XML root element in Python? I have an XML file, e.g.: <?xml version="1.0" encoding="UTF-8"?> <root> First line. <br/> Second line. </root> As an output I want to get: '\nFirst line. <br/> Second line.\n' I just want to notice, if the root element contains other nested elements, they sh...
How to fetch content of XML root element in Python?
I have an XML file, e.g.: <?xml version="1.0" encoding="UTF-8"?> <root> First line. <br/> Second line. </root> As an output I want to get: '\nFirst line. <br/> Second line.\n' I just want to notice, if the root element contains other nested elements, they should be returned as is.
[ "The first that I came up with:\nfrom xml.etree.ElementTree import fromstring, tostring\n\nsource = '''<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n First line.<br/>Second line.\n</root>\n'''\n\nxml = fromstring(source)\nresult = tostring(xml).lstrip('<%s>' % xml.tag).rstrip('</%s>' % xml.tag)\n\nprint re...
[ 3, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0006669420_python_xml.txt
Q: Python CGI Script (using XML & mindom) returns unexpected results I am trying to parse the XML returned by search engine APIs (Bing, Yahoo & Blekko). The returned XML (for sample search query 'sushi') from Blekko takes the form: <rss version="2.0"> <channel> <title>blekko | rss for &quot;sushi/rss /ps=100&quo...
Python CGI Script (using XML & mindom) returns unexpected results
I am trying to parse the XML returned by search engine APIs (Bing, Yahoo & Blekko). The returned XML (for sample search query 'sushi') from Blekko takes the form: <rss version="2.0"> <channel> <title>blekko | rss for &quot;sushi/rss /ps=100&quot;</title> <link>http://blekko.com/?q=sushi%2Frss+%2Fps%3D100</link...
[ "I guess that the .toxml() method returns the XML for the element, including its delimiting tags, and then you’re getting something like this:\n<h2><title>...</title></h2><br />\n<description>...</description><br />\n<guid>...</guid><br />\n\nThe title element is therefore interpreted as the page’s title, unless yo...
[ 1 ]
[]
[]
[ "blekko", "cgi", "minidom", "python", "xml" ]
stackoverflow_0006680643_blekko_cgi_minidom_python_xml.txt
Q: how to play avi or mpeg video with python cocos2d i'm using cocos2d game engine for python. And i read api document but i can't found video library. how to play avi or mpeg video with python cocos2d ? A: i'm found this solution. class VideoLayer (Layer): def __init__(self, video_name): super(VideoLay...
how to play avi or mpeg video with python cocos2d
i'm using cocos2d game engine for python. And i read api document but i can't found video library. how to play avi or mpeg video with python cocos2d ?
[ "i'm found this solution.\nclass VideoLayer (Layer):\n def __init__(self, video_name):\n super(VideoLayer, self).__init__()\n\n source = pyglet.media.load(video_name)\n format = source.video_format\n if not format:\n print 'No video track in this source.'\n retur...
[ 1 ]
[]
[]
[ "cocos2d_python", "python" ]
stackoverflow_0006680676_cocos2d_python_python.txt
Q: Visual Fox Pro and Python I'm working with a visual fox pro database (.dbf file) and I'm using the dbf python module. Heres an example: myDb = VfpTable('table.dbf'); Now I can exclude deleted items with this by doing the following: myDb._use_deleted = None; My question(s) is/are is there an easier way to do t...
Visual Fox Pro and Python
I'm working with a visual fox pro database (.dbf file) and I'm using the dbf python module. Heres an example: myDb = VfpTable('table.dbf'); Now I can exclude deleted items with this by doing the following: myDb._use_deleted = None; My question(s) is/are is there an easier way to do this? Maybe a function? I hate a...
[ "Using the dbf module referenced above what you want is:\nmyDB.use_deleted = False\n\nand for individual records:\nfor record in myDB:\n if record.has_been_deleted:\n print \"record %d is marked for deletion!\" % record.record_number\n\nTo physically remove the records from the table:\nmyDB.pack()\n\ndisc...
[ 4, 0 ]
[]
[]
[ "dbf", "foxpro", "python", "visual_foxpro" ]
stackoverflow_0005424106_dbf_foxpro_python_visual_foxpro.txt
Q: video and audio processing library in python Which video/audio libraries are available in Python to recognize a certain audio pattern within a video recording? I'm trying to exclude the beginning of the recording from the video file (skipping up to the particular audio pattern) and therefore I'd need a way to sc...
video and audio processing library in python
Which video/audio libraries are available in Python to recognize a certain audio pattern within a video recording? I'm trying to exclude the beginning of the recording from the video file (skipping up to the particular audio pattern) and therefore I'd need a way to scan the file from its beginning recognize the audio...
[ "AFAIK, speech recognition (that also expose lower level functionality as scoring the similitude between two sounds) is only supported in Python through windows libraries or the dragon naturally speaking API.\nOnce the marker is found, you could use an external library like this or this to cut the video as per requ...
[ 3 ]
[]
[]
[ "audio", "python", "video" ]
stackoverflow_0006681540_audio_python_video.txt
Q: os.path.exists not working properly on Python CLI I've Python 2.5.x on my Windows 7 machine. os.path.exists('C:') # returns True os.path.exists('C:\Users') # returns True os.path.exists('C:\Users\alpha') # returns False, when ALPHA is a user on my machine I've given read/write permissions to...
os.path.exists not working properly on Python CLI
I've Python 2.5.x on my Windows 7 machine. os.path.exists('C:') # returns True os.path.exists('C:\Users') # returns True os.path.exists('C:\Users\alpha') # returns False, when ALPHA is a user on my machine I've given read/write permissions to the CLI I'm using. What could be the possible reason f...
[ "Inside quotes, '\\' escapes the next character; see the reference on string literals. Either double your backslashes like:\nos.path.exists('C:\\\\Users\\\\ALPHA')\n\nto escape the backslashes themselves, use forward slashes as path separators as Michael suggests, or use \"raw strings\":\nos.path.exists(r'C:\\Users...
[ 5, 1 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0006681243_python_python_module.txt
Q: python xml validation with xsd file Every year or so someone seems to ask the same question. Is there a good Python library to validate xml files comparing them to an xsd schema? The closest I've found is suggestions involving lxml, which unfortunately is not pure python (based on a few C libraries) A: I would b...
python xml validation with xsd file
Every year or so someone seems to ask the same question. Is there a good Python library to validate xml files comparing them to an xsd schema? The closest I've found is suggestions involving lxml, which unfortunately is not pure python (based on a few C libraries)
[ "I would be surprised to find any pure Python XSD validation libraries. I am aware of the following alternatives for CPython, but they all depend on non-Python code:\n\nlxml (based on libxml2)\nlibxml2 Python bindings\nXSV\nMSXML with PyWin32\n\n", "I've used XSV for this. It's about four years since any active ...
[ 5, 1 ]
[]
[]
[ "python", "validation", "xml", "xsd" ]
stackoverflow_0006654709_python_validation_xml_xsd.txt
Q: Designing Testing Framework in Python! I want to design a framework in Python for testing Development Codes.. For e.g. I wrote a small program in python only to add to numbers. And now I would like to test this Python code in an automated way by storing the Inputs and expected Output at some place and now I just r...
Designing Testing Framework in Python!
I want to design a framework in Python for testing Development Codes.. For e.g. I wrote a small program in python only to add to numbers. And now I would like to test this Python code in an automated way by storing the Inputs and expected Output at some place and now I just run the python script to validate the Output....
[ "If you were thinking of writing your own unit testing library from scratch, that is rather unncessary. There are already many to choose from, including one in the standard library! (unittest)\nNose is a popular alternative to using the standard library's unittest.\nHere's a good tutorial on using it: http://ivory....
[ 3 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0006682296_python_unit_testing.txt
Q: google app engine sending a copy of email to my inbox Possible Duplicate: sending email with GAE copies sender — how to stop? Below is a code to send emails from google app engine in Python. I made a list (pythons) of email-ids to whom I desire to send email to and ran a loop, each time reassigning message.to an...
google app engine sending a copy of email to my inbox
Possible Duplicate: sending email with GAE copies sender — how to stop? Below is a code to send emails from google app engine in Python. I made a list (pythons) of email-ids to whom I desire to send email to and ran a loop, each time reassigning message.to and executing message.send(). Code below, when run on Google...
[ "This is by design. You cannot send email from a user in App Engine without the user getting a copy.\n" ]
[ 1 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0006682095_email_google_app_engine_python.txt
Q: Calling a C++ DLL in Python which returns an object reference After a long research i have decided to write a question. I have a C++ DLL which has one exported function : ObjectType* getInstance() With this instance, the function returns, i can get access to all the other public functions. My problem now is, that ...
Calling a C++ DLL in Python which returns an object reference
After a long research i have decided to write a question. I have a C++ DLL which has one exported function : ObjectType* getInstance() With this instance, the function returns, i can get access to all the other public functions. My problem now is, that i want to use this thing in Python. When i access getInstance with ...
[ "As far as I know, you can't access a C++ type directly from Python. You\nhave to wrap it with some (often a lot of) C or C++ code: it's not\ndifficult, but it does take time. See Extending and\nEmbedding the Python Interpreter.\n" ]
[ 0 ]
[]
[]
[ "c++", "ctypes", "dll", "python" ]
stackoverflow_0006678266_c++_ctypes_dll_python.txt
Q: Python: Fast querying in a big dbf (xbase) file I have a big DBF file (~700MB). I'd like to select only a few lines from it using a python script. I've seen that dbfpy is a nice module that allows to open this type of database, but for now I haven't found any querying capability. Iterating through all the elements...
Python: Fast querying in a big dbf (xbase) file
I have a big DBF file (~700MB). I'd like to select only a few lines from it using a python script. I've seen that dbfpy is a nice module that allows to open this type of database, but for now I haven't found any querying capability. Iterating through all the elements from python is simply too slow. Can I do what I want...
[ "Using my dbf module you can create temporary indexes and then search using those:\nimport dbf\n\ntable = dbf.Table('big.dbf')\nindex = table.create_index(lambda rec: rec.field) # field should be actual field name\n\nrecords = index.search(match=('value',))\n\nCreating the index may take a few seconds, but the sear...
[ 14, 2, 1 ]
[]
[]
[ "dbf", "performance", "python", "python_3.x", "xbase" ]
stackoverflow_0002373086_dbf_performance_python_python_3.x_xbase.txt
Q: How can python return the filename currently being processed under Windows I am new to python, and just want to make a simple change. We are generating a template file via mako under Windows 7 and I want to change the comments at the start of the output file from: /////////////////////////////////////////////////...
How can python return the filename currently being processed under Windows
I am new to python, and just want to make a simple change. We are generating a template file via mako under Windows 7 and I want to change the comments at the start of the output file from: ///////////////////////////////////////////////////////////////// // This file is automatically generated by Mako ///////////////...
[ "import os\n\nfilename = os.path.basename(__file__)\nprint ('this is generated by ' + filename)\n\n", "For the name of the python script itself, use __file__:\n$ echo \"print __file__\" > test.py \n$ python test.py \ntest.py\n\n" ]
[ 4, 1 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0006682372_mako_python.txt
Q: unexpected indent in ipython 0.10.1 I have a problem with ipython 0.10.1 in ubuntu 11.04 and python 2.7.1. In previous versions of ipython indentation did not matter when working interactively. Now instead any indented statement throws an exception: In [1]: a=3 ----------------------------------------------------...
unexpected indent in ipython 0.10.1
I have a problem with ipython 0.10.1 in ubuntu 11.04 and python 2.7.1. In previous versions of ipython indentation did not matter when working interactively. Now instead any indented statement throws an exception: In [1]: a=3 ------------------------------------------------------------ IndentationError: unexpected ind...
[ "This happens only when ipython is called with -wthread, I've just filed a bug about this.\n" ]
[ 2 ]
[]
[]
[ "indentation", "ipython", "python" ]
stackoverflow_0006682580_indentation_ipython_python.txt
Q: Handling Swing focus events with Jython Jython 2.5 I'm trying to bind a method to the focusGained event of a JText control, but all the examples that I found are Java samples, not Jython. Here's the code, I want to run a custom method when each text control gains focus (to select all the control's text, for instan...
Handling Swing focus events with Jython
Jython 2.5 I'm trying to bind a method to the focusGained event of a JText control, but all the examples that I found are Java samples, not Jython. Here's the code, I want to run a custom method when each text control gains focus (to select all the control's text, for instance) from javax.swing import * from java.awt i...
[ "I was just trying to figure this out yesterday myself...tested and works:\nfrom javax.swing import *\nfrom java.awt import *\n\nclass Test(JFrame):\n def __init__(self):\n JFrame.__init__(self,\n 'JDesktopPane and JInternalFrame Demo',\n size=(600, 300),\n ...
[ 1, 1 ]
[]
[]
[ "jython", "python", "swing" ]
stackoverflow_0001213295_jython_python_swing.txt
Q: Python dynamic function generation I am using PyQt and want to create a menu based on a list of strings. The problem is that when I want to call 'addAction', it requires a call-back function (for each string) that does not take any arguments. For simple menus, this would be fine: e.g. menu.addAction("Open", self....
Python dynamic function generation
I am using PyQt and want to create a menu based on a list of strings. The problem is that when I want to call 'addAction', it requires a call-back function (for each string) that does not take any arguments. For simple menus, this would be fine: e.g. menu.addAction("Open", self.open) menu.addAction("Exit", self.quit) ...
[ "functools.partial() allows you to supply some of the arguments ahead of time. It will allow you to make custom callbacks as you want.\n>>> from functools import partial\n>>> basetwo = partial(int, base=2)\n>>> basetwo.__doc__ = 'Convert base 2 string to an int.'\n>>> basetwo('10010')\n18\n\n", "You can use a clo...
[ 6, 4, 2, 1, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006682688_pyqt_python.txt
Q: How to fix Unicode encode error using the hashlib module? After multiple searches I have not been able to determine how to avoid an error stating: "Unicode-objects must be encoded before hashing" when using this code: pwdinput = input("Now enter a password:") pwd = hashlib.sha1() pwd.update(pwdinput) ...
How to fix Unicode encode error using the hashlib module?
After multiple searches I have not been able to determine how to avoid an error stating: "Unicode-objects must be encoded before hashing" when using this code: pwdinput = input("Now enter a password:") pwd = hashlib.sha1() pwd.update(pwdinput) pwd = pwd.hexdigest() How can I get past that error? How do...
[ "pwdinput = input(\"Now enter a password:\").encode('utf-8') # or whatever encoding you wish to use\n\nAssuming you're using Python 3, this will convert the Unicode string returned by input() into a bytes object encoded in UTF-8, or whatever encoding you wish to use. Previous versions of Python do have it as well, ...
[ 51 ]
[]
[]
[ "hashlib", "python", "unicode" ]
stackoverflow_0006683167_hashlib_python_unicode.txt
Q: How many line of code are in a program? (I know this is kind of vauge and depends but...) It seems when I try to research all I can find are how many lines are in Linux, call of duty, windows and other things that are massive applications with millions of lines of code. Does anyone have examples of code size of ap...
How many line of code are in a program? (I know this is kind of vauge and depends but...)
It seems when I try to research all I can find are how many lines are in Linux, call of duty, windows and other things that are massive applications with millions of lines of code. Does anyone have examples of code size of applications that don't take teams and teams of people? P.S. I'm 24 yrs old and just starting to ...
[ "Code length depends completely on the type of the application you want to design. It also depends on the language of choice. A program written in c will likely be significantly longer than say code in python. \nIt's never to late to learn!\n", "If you're new to programming, you might want to start with a great ...
[ 5, 1, 0, 0 ]
[]
[]
[ "c++", "java", "javascript", "php", "python" ]
stackoverflow_0006683248_c++_java_javascript_php_python.txt
Q: Relative import from current file Currently I have a "main" folder where all of the modules I write eventually go, but I usually place the modules I'm currently working on in a 'dev' folder just so I don't clutter up the other folder with stuff that aren't ready. The structure looks like this MyProg |-run.py |-\l...
Relative import from current file
Currently I have a "main" folder where all of the modules I write eventually go, but I usually place the modules I'm currently working on in a 'dev' folder just so I don't clutter up the other folder with stuff that aren't ready. The structure looks like this MyProg |-run.py |-\lib | |-someLibrary.py | ... | |-\main |...
[ "If you have your PYTHONPATH set to MyProg, what you can do is create an empty __init__.py file in each folder so python recognizes them as modules:\nMyProg\n|-run.py\n|-__init__.py\n|-\\lib\n| |-someLibrary.py\n| |-__init__.py\n| ...\n|\n|-\\main\n| |-readyScripts.py\n| |-__init__.py\n| ...\n|\n|-\\dev\n| |-inProg...
[ 3, 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006683165_import_python.txt
Q: How to set the variable inside a function scope? Could I set a variable inside a function scope, knowing that I sent this variable like a parameter.. See the example: def test(param): param = 3 var = 5 test(var) print var I want the value printed be 3, but it doesn't happen. How can I do that? Thanks.. A: ...
How to set the variable inside a function scope?
Could I set a variable inside a function scope, knowing that I sent this variable like a parameter.. See the example: def test(param): param = 3 var = 5 test(var) print var I want the value printed be 3, but it doesn't happen. How can I do that? Thanks..
[ "You can return the value of param like this:\ndef test(param)\n param = 3\n return param\n\nvar = 5\nvar = test(var)\n\nOr you can use a global variable.\n", "Better to use return than a global:\ndef test(param):\n param = 3\n return param\n\nvar = 5\nvar = test(var)\n\nprint var\n\n", "The global ...
[ 2, 2, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0006683306_python_syntax.txt
Q: why does this loop always return the original argument? I've a loop which checks a username. If the username exists I want to increment the counter for each loop. Then append that Id to the username. This loop always returns the original argument passed though and I don't know why. I have it going on a def save on...
why does this loop always return the original argument?
I've a loop which checks a username. If the username exists I want to increment the counter for each loop. Then append that Id to the username. This loop always returns the original argument passed though and I don't know why. I have it going on a def save on my form in forms.py. def check_username(self, username): ...
[ "You should probably use return self.check_username(username) within the if block, otherwise, your recursive call won't do much.\nThe counter is probably not used as you'd like here either. You'll keep adding '2' at the end of every username you try, e.g username -> username2 -> username22.\nThis being said, a whil...
[ 2, 0 ]
[]
[]
[ "django", "loops", "python" ]
stackoverflow_0006683343_django_loops_python.txt
Q: How does one create a method to add things in a list in Python? My background is in Java and I was only recently learning how to do some object oriented programming in it. I am currently learning python as well and I wondering how this Java code translates into python. Assuming I have a HockeyPlayer class that has...
How does one create a method to add things in a list in Python?
My background is in Java and I was only recently learning how to do some object oriented programming in it. I am currently learning python as well and I wondering how this Java code translates into python. Assuming I have a HockeyPlayer class that has a jerseyNumber instance variable: public void addPlayer(HockeyPlayer...
[ "You can use the append() method to append a single item to your list.\n>>> hockeyplayers = [\"Adam\", \"Ben\"]\n>>> hockeyplayers.append(\"Charlie\")\n>>> hockeyplayers\n['Adam', 'Ben', 'Charlie']\n\nTo concatenate two lists, use the extend() method:\n>>> moreplayers = [\"Dan\", \"Eddie\"]\n>>> hockeyplayers.exten...
[ 4 ]
[]
[]
[ "java", "python" ]
stackoverflow_0006683431_java_python.txt
Q: How to directly publish only child items of my Container type in Plone? I have a custom folderish Dexterity content-type in Plone. It can have only Documents as children. I want these documents to be directly published as they are created. I can achieve this easily by setting an appropriate workflow for the Docume...
How to directly publish only child items of my Container type in Plone?
I have a custom folderish Dexterity content-type in Plone. It can have only Documents as children. I want these documents to be directly published as they are created. I can achieve this easily by setting an appropriate workflow for the Document type, but that would affect every document in my site. I want only the one...
[ "You just want the \"Workflow Policy Support (CMFPlacefulWorkflow)\" product (it's a default part of Plone):\nAdd in Plone the capability to change workflow chains for types in every object.\n\nYou can set workflow on individual folders, or on that folder and all folders below it.\n", "Create a new automatic tran...
[ 11, 4, 2 ]
[]
[]
[ "plone", "python", "workflow" ]
stackoverflow_0006679530_plone_python_workflow.txt
Q: How can mako access the object name currently being rendered under Windows I am new to mako, and have a question about the object model. We are generating a template file via mako under Windows 7 through the render command, similar to out.write(self.objectname.render(...)) within the file being rendered, I want t...
How can mako access the object name currently being rendered under Windows
I am new to mako, and have a question about the object model. We are generating a template file via mako under Windows 7 through the render command, similar to out.write(self.objectname.render(...)) within the file being rendered, I want to access the objectname similar to the following pseudo code ... <%namespace nam...
[ "<%namespace name=\"mapping\" module=\"objtool.mapping\" />\n<%!\nimport os\nimport time\n%>\\\n======================================================\n== this file is being rendered from ${os.path.basename(self.name)}\n======================================================\n\nrenders\n=============================...
[ 0 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0006683538_mako_python.txt
Q: ftplib change file remotely I have some file remotely : ___________ [somevar] Test: 2 ___________ And i want to change var "Test" to 3 for example so i will have : ___________ [somevar] Test: 3 ___________ I'm using this function to upload file ftp = ftplib.FTP('') ftp.connect(HOSTNAME,PORT) ftp.logi...
ftplib change file remotely
I have some file remotely : ___________ [somevar] Test: 2 ___________ And i want to change var "Test" to 3 for example so i will have : ___________ [somevar] Test: 3 ___________ I'm using this function to upload file ftp = ftplib.FTP('') ftp.connect(HOSTNAME,PORT) ftp.login(FTP_NAME,FTP_PASS) file = o...
[ "You can't change the file remotely without RETR + STOR though you can edit it in the memory without saving if it is small.\n" ]
[ 0 ]
[]
[]
[ "file", "ftplib", "python" ]
stackoverflow_0006683730_file_ftplib_python.txt
Q: "Reading in" large text file into hdf5 via PyTables or PyHDF? I'm attempting some statistics using SciPy, but my input dataset is quite large (~1.9GB) and in dbf format. The file is large enough that Numpy returns an error message when I try to create an array with genfromtxt. (I've got 3GB ram, but running win32...
"Reading in" large text file into hdf5 via PyTables or PyHDF?
I'm attempting some statistics using SciPy, but my input dataset is quite large (~1.9GB) and in dbf format. The file is large enough that Numpy returns an error message when I try to create an array with genfromtxt. (I've got 3GB ram, but running win32). i.e.: Traceback (most recent call last): File "<pyshell#5>", ...
[ "If the data is too big to fit in memory, you can work with a memory-mapped file (it's like a numpy array but stored on disk - see docs here), though you may be able to get similar results using HDF5 depending on what operations you need to perform on the array. Obviously this will make many operations slower but ...
[ 4, 0 ]
[]
[]
[ "hdf5", "pytables", "python" ]
stackoverflow_0004629798_hdf5_pytables_python.txt
Q: Copy oldest file to another directory using Python There are some problems in my python program. I want to open a directory, choose the oldest file and then copy the file to another directory. I read the documents where "shutil" is mentioned, but I don't know how to choose the oldest one. Could someone help me sol...
Copy oldest file to another directory using Python
There are some problems in my python program. I want to open a directory, choose the oldest file and then copy the file to another directory. I read the documents where "shutil" is mentioned, but I don't know how to choose the oldest one. Could someone help me solve this problem?
[ "You can use os.path.getatime to get the last access time for a file (or directory), or ps.path.getmtime to get the time of the last modification.\n", "The following example compares modification date, but you can of course change it to get other file-related times by changing the definition of gt to os.path.getc...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006544391_python.txt
Q: Improving a fuzzy matching algorithm in Python Task: Take two text files and output 100% matches and 75% matches. Solution: import difflib import csv # Imports and parses the files fileA = open("H:/comm.names.txt", 'r') try: setA = fileA.readlines() finally: fileA.close() fileB = open("H:/aca...
Improving a fuzzy matching algorithm in Python
Task: Take two text files and output 100% matches and 75% matches. Solution: import difflib import csv # Imports and parses the files fileA = open("H:/comm.names.txt", 'r') try: setA = fileA.readlines() finally: fileA.close() fileB = open("H:/acad.names.txt", 'r') try: setB = fileB.readlin...
[ "I would try comparing strings with a tool such as pylevenshtein. It allows fuzzy string comparisons.\n", "I ended up writing a most common word script, and then I removed the most common words. This significantly improved my results as @e-satis suggested in his comment. However, difflib gave me better results th...
[ 0, 0 ]
[]
[]
[ "algorithm", "fuzzy_comparison", "python", "string_matching" ]
stackoverflow_0005043847_algorithm_fuzzy_comparison_python_string_matching.txt
Q: Speeding up iterating over Numpy Arrays I am working on performing image processing using Numpy, specifically a running standard deviation stretch. This reads in X number of columns, finds the Std. and performs a percentage linear stretch. It then iterates to the next "group" of columns and performs the same ope...
Speeding up iterating over Numpy Arrays
I am working on performing image processing using Numpy, specifically a running standard deviation stretch. This reads in X number of columns, finds the Std. and performs a percentage linear stretch. It then iterates to the next "group" of columns and performs the same operations. The input image is a 1GB, 32-bit, s...
[ "One way to speed up operations over numpy data is to use vectorize. Essentially, vectorize takes a function f and creates a new function g that maps f over an array a. g is then called like so: g(a). \n>>> sqrt_vec = numpy.vectorize(lambda x: x ** 0.5)\n>>> sqrt_vec(numpy.arange(10))\narray([ 0. , 1. ...
[ 7, 5, 2 ]
[]
[]
[ "for_loop", "gdal", "numpy", "python" ]
stackoverflow_0006654329_for_loop_gdal_numpy_python.txt
Q: Python - removing xml tag in an element I am using python 2.7.2. and dom parser to read the data on several xml files. And export .db file to use on sql server. I have learned how to export the files, but XML tags are also included on my data tables. Here is the basic code : from xml.dom import minidom import sqli...
Python - removing xml tag in an element
I am using python 2.7.2. and dom parser to read the data on several xml files. And export .db file to use on sql server. I have learned how to export the files, but XML tags are also included on my data tables. Here is the basic code : from xml.dom import minidom import sqlite3 xmldoc = minidom.parse('c:\dd\l2con\l2con...
[ "coId[0] is a DOM Element with one child (a Text node). Use \ncoId[0].firstChild.data\n\nto get the text content. \nThis works too:\ncoId[0].firstChild.nodeValue\n\n", "use coId[0].data instead, this gives the element content.\nSee mzjn answer, coId[0].firstChild.data is the correct way to do it.\n", "You could...
[ 3, 2, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0006680413_python_xml.txt
Q: INSERT INTO SELECT syntax error Python ODBC with Microsoft Access Had a long search through here and the web and can't seem to find any examples that explain why I am getting a syntax error on the following: import win32com.client ` PregCode = recordsetraw.Fields.Item("PregnancyCode").value SQL = "...
INSERT INTO SELECT syntax error Python ODBC with Microsoft Access
Had a long search through here and the web and can't seem to find any examples that explain why I am getting a syntax error on the following: import win32com.client ` PregCode = recordsetraw.Fields.Item("PregnancyCode").value SQL = "INSERT INTO UniqueData SELECT * FROM Rawdata WHERE PregnancyCode =%s" ...
[ "My Python is very rusty, and I don't recall what this type of substitution is called, but I think you're trying to accomplish something similar to this with your INSERT statement:\n>>> print \"Hello %s\" %(\"World\")\nHello World\n\nFrom your code:\nSQL = \"INSERT INTO UniqueData SELECT * FROM Rawdata WHERE Pregna...
[ 1, 0 ]
[]
[]
[ "insert", "ms_access", "python", "sql" ]
stackoverflow_0006683580_insert_ms_access_python_sql.txt
Q: SSH and SCP from windows with Python 3 I've Been stuck here for days. I want to copy a file from my windows to a remote linux server and run the script there. I've tool for ssh and scp. from which I can call the linux server through command line but when I call it through python it gets hanged. pro=subprocess.Pope...
SSH and SCP from windows with Python 3
I've Been stuck here for days. I want to copy a file from my windows to a remote linux server and run the script there. I've tool for ssh and scp. from which I can call the linux server through command line but when I call it through python it gets hanged. pro=subprocess.Popen('ssh user@server') pro.communicate() ther...
[ "http://docs.fabfile.org/en/1.0.1/index.html\nI'm not sure it can be converted by 2to3\nbut it's rather simple to use:\nfrom fabric.api import run, env\nfrom fabric.context_managers import hide\nfrom fabric.colors import green\n\nwith hide('status', 'running', 'output'):\n print('Apache ' + env.host + ': ' + gre...
[ 0 ]
[ "There was another question like this. Use netcat. 'man nc'. Use os.system() in python to spawn it on both client side and server side.\nFrom the netcat manual page:\n\nDESCRIPTION\nThe nc (or netcat) utility is used for just about anything under the sun\n involving TCP or UDP. It can open TCP connections, sen...
[ -1 ]
[ "python", "python_3.x", "scp", "ssh" ]
stackoverflow_0006097278_python_python_3.x_scp_ssh.txt
Q: OpenCV/C++ program slower than its numpy counterpart, what should I do? I implemented some time ago the Procrustes Analysis algorithm in Python and was told to port it to OpenCV/C++ recently. After finishing it I ran some tests and for the same input/instances, the C++ code is taking twice the time the Python code...
OpenCV/C++ program slower than its numpy counterpart, what should I do?
I implemented some time ago the Procrustes Analysis algorithm in Python and was told to port it to OpenCV/C++ recently. After finishing it I ran some tests and for the same input/instances, the C++ code is taking twice the time the Python code does (roughly 8 vs 4 seconds, respectively. I'm repeating the tests a thousa...
[ "for(int i = 0; i < 10; i++) {\n cv::Mat m3 = m1 * m2;\n}\n\nThis is totally pointless in c++, the m3 is destroyed on each iteration of the loop - that's why you get all those destructor calls.\nedit:\ncv::Mat m3 = m1 * m2;\n\nand \nm3 = np.dot(m1, m2)\n\naren't the same thing. Have you tried comparing a cro...
[ 1 ]
[]
[]
[ "c++", "image_processing", "numpy", "opencv", "python" ]
stackoverflow_0006674338_c++_image_processing_numpy_opencv_python.txt
Q: Any way to make dict passed to URL express in regexp in GAE? Say, I have a dict URLS = {'admin' : '/admin/(.*)'} and if I do so application = ([ (r(URLS['admin']), AdminPage) ], debug=True) google app engine will raise an error NameError: name 'r' is not defined I really really need to pass dictionary described...
Any way to make dict passed to URL express in regexp in GAE?
Say, I have a dict URLS = {'admin' : '/admin/(.*)'} and if I do so application = ([ (r(URLS['admin']), AdminPage) ], debug=True) google app engine will raise an error NameError: name 'r' is not defined I really really need to pass dictionary described in regexp to URL map for making my code more module. What should ...
[ "The 'r' is a string prefix to escape some sequences for regular expression. It is not a function.\nhttp://docs.python.org/reference/lexical_analysis.html#string-literals\nURLS = {'admin' : r'/admin/(.*)'}\n\napplication = webapp.WSGIApplication([\n(URLS['admin'], AdminPage)\n], debug=True)\n\nThe \"webapp.WSGIAppl...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006677555_google_app_engine_python.txt
Q: Blender 2.5 Python animated world texture setup I need to set up an animated (i.e. from video file) world texture in blender 2.58 using python. I make a texture like this: import bpy # create new clouds texture bpy.ops.texture.new() wtex = bpy.data.textures[-1] # set World texture wrld = bpy.data.worlds['World'] s...
Blender 2.5 Python animated world texture setup
I need to set up an animated (i.e. from video file) world texture in blender 2.58 using python. I make a texture like this: import bpy # create new clouds texture bpy.ops.texture.new() wtex = bpy.data.textures[-1] # set World texture wrld = bpy.data.worlds['World'] slot = wrld.texture_slots.add() slot.texture = wtex sl...
[ "For data addition/removal, its best not to use operators, we have api functions from bpy.data for this.\nimport bpy\n# create new clouds texture\nwtex = bpy.data.textures.new(name=\"MyTexture\", type='IMAGE')\n# set World texture\nwrld = bpy.context.scene.world\nif wrld:\n slot = wrld.texture_slots.add()\n s...
[ 0 ]
[]
[]
[ "blender", "blender_2.50", "bpython", "python" ]
stackoverflow_0006681039_blender_blender_2.50_bpython_python.txt
Q: Spynner programmatic python browser to download files from cgi file-server: jquery selector for browser.click()? I am trying to use spynner , the stateful programmatic web browser to download files from a cookie protected web / cgi file repository. Spynner uses jquery like selectors to tell the browser what to cli...
Spynner programmatic python browser to download files from cgi file-server: jquery selector for browser.click()?
I am trying to use spynner , the stateful programmatic web browser to download files from a cookie protected web / cgi file repository. Spynner uses jquery like selectors to tell the browser what to click. I have a link to the file <a href="index.cgi?page=download&amp;file=%2Fhome%2Fjdataserver%2Fpublic_html%2Fuser_da...
[ "I got this to work with the appropriate jquery selector and also using the spynner.browser.download() method.\nThe file links were nested in image tags\n\n\n\n\nOnce I used the appropriate tag for the href link that held the file a browser.click downloaded the file to a directory called www.servername.com .\nTo ta...
[ 1 ]
[]
[]
[ "jquery_selectors", "python", "wget" ]
stackoverflow_0006654784_jquery_selectors_python_wget.txt
Q: Create a terminate-button like eclipse Currently I program a GUI application with wxPython. Now I want create a STOP-Button which will stop the current python command/request/task. I already created a button: def StopButton(self, event): sys.exit(0) But it does not work. :( Because my program do not reali...
Create a terminate-button like eclipse
Currently I program a GUI application with wxPython. Now I want create a STOP-Button which will stop the current python command/request/task. I already created a button: def StopButton(self, event): sys.exit(0) But it does not work. :( Because my program do not realize the click on the button. It does not reac...
[ "With GUI applications, the UI runs on a single, often main, thread. This thread initializes the GUI elements, and waits for user input.\nWhen you do other things in that main thread, your GUI elements cannot accept user input, because you're busy doing those other things. Sometimes this is what you want to have ha...
[ 1, 0 ]
[]
[]
[ "button", "python", "terminate", "wxpython" ]
stackoverflow_0006684018_button_python_terminate_wxpython.txt
Q: Create list by repeated application of function I want this: [foo() for _ in xrange (100)] but beautifuller. ? A: You can write a generator repeat like this: def repeat(times, func, *args, **kwargs): for _ in xrange(times): yield func(*args, **kwargs) Then: list(repeat(100, foo)) It also accepts a...
Create list by repeated application of function
I want this: [foo() for _ in xrange (100)] but beautifuller. ?
[ "You can write a generator repeat like this:\ndef repeat(times, func, *args, **kwargs):\n for _ in xrange(times):\n yield func(*args, **kwargs)\n\nThen:\nlist(repeat(100, foo))\n\nIt also accepts arguments to be passed on to the function, so you can:\nfrom random import randint\nlist(repeat(100, randint, ...
[ 8, 5, 3, 2, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006683449_list_python.txt
Q: Feedparser Date parameter/Time-specific query Is there an Option in feedparser to query only the new entries newer then feed.updated? Or can you set a parameter to get only entries from a specific date/today/week etc.? (Safari´s RSS Reader provides this options...) A: I don't understand the question as written....
Feedparser Date parameter/Time-specific query
Is there an Option in feedparser to query only the new entries newer then feed.updated? Or can you set a parameter to get only entries from a specific date/today/week etc.? (Safari´s RSS Reader provides this options...)
[ "I don't understand the question as written. An RSS feed is an XML document. Feedparser retrieves and parses this entire document. It can't query just part of a document. It's up to you to write the code around feedparser to extract what you want (e.g., for each entry, you can look at d.entries[0].date and comp...
[ 2 ]
[]
[]
[ "feedparser", "python", "rss" ]
stackoverflow_0006642570_feedparser_python_rss.txt
Q: issuing dos commands from inside ruby on rails controller in the same dos session Here is my scenario. I have a ajax call in my web site to find the elevation at particular point. Once this point comes into an action of a controller in Ruby on rails, I have to use python on command line to find the elevation. The ...
issuing dos commands from inside ruby on rails controller in the same dos session
Here is my scenario. I have a ajax call in my web site to find the elevation at particular point. Once this point comes into an action of a controller in Ruby on rails, I have to use python on command line to find the elevation. The following sequence of commands in DOS does that for me. python (starts a python sessio...
[ "What you are proposing could be possible if Rails was friendlier about forked processes. A cleaner and better solution would be to write a python daemon that you could query so that you don't incur the startup penalty. (This could be a web-service or a daemon you communicate with standard network sockets or what...
[ 1 ]
[]
[]
[ "command_line", "dos", "python", "ruby_on_rails", "session" ]
stackoverflow_0006685530_command_line_dos_python_ruby_on_rails_session.txt
Q: "TypeError: argument of type 'NoneType' is not iterable"? Here is some Python code which I wrote to generate a random poker hand, just for the heck of it/for the challenge, but when I try to run it, I get the error above on the line "if card in hand". What's going on, and why is this happening, especially since th...
"TypeError: argument of type 'NoneType' is not iterable"?
Here is some Python code which I wrote to generate a random poker hand, just for the heck of it/for the challenge, but when I try to run it, I get the error above on the line "if card in hand". What's going on, and why is this happening, especially since that line is not iterating? import random def pokerHand(): ha...
[ "hand = hand.append(card)\nappend does not return anything. Change it to:\nhand.append(card)\n", "the append() method of a list does not return the list, it modifies it in place. thus, after you add the first card (with hand = hand.append(card)), hand is set to the return value of append(), which is None (the ret...
[ 7, 3, 0 ]
[]
[]
[ "if_statement", "iteration", "python", "typeerror" ]
stackoverflow_0006685752_if_statement_iteration_python_typeerror.txt
Q: What does this error message mean? It appears after I did some reconfigruation to my GAE / django project namely using appengine_config.py to select django 1.2 Does this error message mean I'm running the wrong version of python? If so, which version should I be running? I previously used to latest available prein...
What does this error message mean?
It appears after I did some reconfigruation to my GAE / django project namely using appengine_config.py to select django 1.2 Does this error message mean I'm running the wrong version of python? If so, which version should I be running? I previously used to latest available preinstalled python version at ubuntu 11. --...
[ "You are using python 2.7\nFile \"/usr/lib/python2.7/io.py\", line 60, in <module>\n\nThe Python runtime environment uses Python 2.5.2\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006685768_django_google_app_engine_python.txt
Q: Circular reference between modules? If have this module # mymodule.py import __main__ And I import it in the python interpreter: >>> import mymodule >>> dir(mymodule) ['__builtins__', '__doc__', '__file__', '__main__', '__name__', '__package__'] >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'my...
Circular reference between modules?
If have this module # mymodule.py import __main__ And I import it in the python interpreter: >>> import mymodule >>> dir(mymodule) ['__builtins__', '__doc__', '__file__', '__main__', '__name__', '__package__'] >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'mymodule'] >>> import sys >>> sys.modules['...
[ "No. Python has no problem with circular references like this. The only thing you must be sure of is that you don't use a name from the other module until it has been defined.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006685960_python.txt
Q: Friendly wrapper for Multiprocessing on Windows7 in Python 2.6 environment? For Python 2.6, is there a friendly wrapper for Multiprocessing that works in a Windows 7 environment? On another question people helped me with similar knowledge for only Unix environment. But for my current project, it's already too late...
Friendly wrapper for Multiprocessing on Windows7 in Python 2.6 environment?
For Python 2.6, is there a friendly wrapper for Multiprocessing that works in a Windows 7 environment? On another question people helped me with similar knowledge for only Unix environment. But for my current project, it's already too late to shift the environment.
[ "Author of jug here. I would still recommend it on Windows. If there is a reason it doesn't work, I can help you make the code platform-independent.\n", "Maybe have a look at the new concurrent.futures library from the python 3.2 standardlib? (there is a backport availabe for older python versions).\n" ]
[ 5, 2 ]
[]
[]
[ "multiprocessing", "python", "windows_7" ]
stackoverflow_0006596707_multiprocessing_python_windows_7.txt
Q: Implement text-autocompletion in python/tkinter based text editor I would like to use an autocompletion algorithm in the main text window (not the Tkinter.entry - examples for this can be found) of this simple Tkinter text editor provided in the code box below. I thought the autocompletion algorithm of beeing depe...
Implement text-autocompletion in python/tkinter based text editor
I would like to use an autocompletion algorithm in the main text window (not the Tkinter.entry - examples for this can be found) of this simple Tkinter text editor provided in the code box below. I thought the autocompletion algorithm of beeing dependent on a list of autocompleted words, i.e. as provided in the code ex...
[ "Well, after some trying I figured it out: \nI used the AutoComplete and AutocompleteWindow modules from IDLE and added the needed window parameters for the manually. AutoComplete is called each time a specific set of characters is hit on the keyboard. \n" ]
[ 0 ]
[]
[]
[ "autocomplete", "editor", "python", "text", "tkinter" ]
stackoverflow_0006482956_autocomplete_editor_python_text_tkinter.txt
Q: Django: want to sort comments by datetime I have in my view comments and I want to sort them with the latest comment at the top of the list. However it is not working. I get this error. Caught TypeError while rendering: 'Comment' object is not iterable I am not so sure what is causing this problem. Here is my view...
Django: want to sort comments by datetime
I have in my view comments and I want to sort them with the latest comment at the top of the list. However it is not working. I get this error. Caught TypeError while rendering: 'Comment' object is not iterable I am not so sure what is causing this problem. Here is my views and model which may help. Views def home(requ...
[ "The cleanest way is to add a class meta to your model and add the ordering parameter like this:\nclass Comment(models.Model):\n name = models.CharField(max_length = 40)\n datetime = models.DateTimeField(default=datetime.now)\n note = models.TextField()\n\n class Meta:\n ordering = ['-datetime']\...
[ 14, 11, 2 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0006685834_datetime_django_python.txt
Q: getting apache to run python on a mac So i have a new mac and i'm trying to get it to run apache with mod_python, mod_wsgi, and django. I have a test test.py that simply contains: #!/usr/bin/python print "Content-type: text/html" print print "<html><head>" print "" print "</head><body>" print "Test Page" print "...
getting apache to run python on a mac
So i have a new mac and i'm trying to get it to run apache with mod_python, mod_wsgi, and django. I have a test test.py that simply contains: #!/usr/bin/python print "Content-type: text/html" print print "<html><head>" print "" print "</head><body>" print "Test Page" print "</body></html>" I've just downloaded xcode4...
[ "As @ignatio-vazquez-abrams noted, mod_python is deprecated, but if you're set on using it, you may want to check out Homebrew. Once Homebrew is installed, you can run brew install mod_python in Terminal. After installation, you'll see a note about adding the compiled mod to your Apache config (as well as a depreca...
[ 0 ]
[]
[]
[ "apache", "apache_modules", "macos", "macports", "python" ]
stackoverflow_0006686379_apache_apache_modules_macos_macports_python.txt
Q: Python strange file read behaviour for long-running non-block thread reading I am writing a code for non-block reading file from standard output using threading. I use the online example to start. The file is created when the subprocess is started. However, after read file in ResultEvent, the file is cleared. I co...
Python strange file read behaviour for long-running non-block thread reading
I am writing a code for non-block reading file from standard output using threading. I use the online example to start. The file is created when the subprocess is started. However, after read file in ResultEvent, the file is cleared. I could not debug into thread and not sure what happend there. Anybody give me a clue?...
[ "There are several things wrong with your code:\n1) You are calling Popen but not waiting for it to finish - the rest of your code is probably executing before the pipe has finished being created. The next thing you do is close the file you are using for stdout, which is why it is always empty. Call p.wait() to wa...
[ 1, 0 ]
[]
[]
[ "file", "multithreading", "python", "readline" ]
stackoverflow_0006685539_file_multithreading_python_readline.txt
Q: MySQLPython is ignoring my my.cnf file. Where does it get its information? When I try to use MySQLPython (via SQLAlchemy) I get the error File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-x86_64.egg/MySQLdb/connections.py", line 18...
MySQLPython is ignoring my my.cnf file. Where does it get its information?
When I try to use MySQLPython (via SQLAlchemy) I get the error File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-x86_64.egg/MySQLdb/connections.py", line 188, in __init__ super(Connection, self).__init__(*args, **kwargs2) sqlalchemy...
[ "Have you tried adding the option read_default_file='~/.my.cnf' to your connect() call, to tell the Python database driver to read your configuration file? I think that otherwise it ignores the file by default.\n", "MysqlDBlib doesn't read /etc/my.cnf by default. Adding read_default_group=\"client\" to the MySQL...
[ 4, 3, 2, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002940399_mysql_python.txt
Q: Using Python to remove incomplete line from the end of a JSON formatted log file I have some JSON formatted log files that I am copying to S3 so I can run Hive queries on them using Elastic Map Reduce. The script I use to copy the log files to S3 is written in Python. Every once in a while I encounter a file with ...
Using Python to remove incomplete line from the end of a JSON formatted log file
I have some JSON formatted log files that I am copying to S3 so I can run Hive queries on them using Elastic Map Reduce. The script I use to copy the log files to S3 is written in Python. Every once in a while I encounter a file with an incomplete line, typically at the end of the file. This causes any Hive queries tha...
[ "Python has a json module in its standard library. It has a parser that will raise an exception if the input isn't valid JSON. To check the last line, you could do something like\nimport json\nwith open('log.txt') as file:\n lines = file.readlines()\ntry:\n json.loads(lines[-1])\nexcept ValueError:\n wit...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006685378_python.txt
Q: What version of Python should I be using to develop web applications? Currently I have Python 3.1.1 installed on my system, same version on my server with WSGI 3.0 running on Apache 2.2. I want to keep using Python 3.1, but I'm finding that lots of libraries/frameworks don't support it yet, namely Django, Pylons, ...
What version of Python should I be using to develop web applications?
Currently I have Python 3.1.1 installed on my system, same version on my server with WSGI 3.0 running on Apache 2.2. I want to keep using Python 3.1, but I'm finding that lots of libraries/frameworks don't support it yet, namely Django, Pylons, MySQLdb, etc. I also checked an account I have on a friend's server, and it...
[ "For now, Python 3 is not widely deployed in production. Depends on what you use Python for. If it's just for one off scripts, it will be ok either way, if the idea is to use third party modules, C modules and or deploy painlessly, then settle for any of the 2.4+ versions. Many projects strive to keep 2.3 compativi...
[ 4, 2, 1, 0 ]
[]
[]
[ "forward_compatibility", "portability", "python" ]
stackoverflow_0002322176_forward_compatibility_portability_python.txt
Q: How to iterate and execute scripts from the command line? I have a program that I run from the command line that takes two file arguments like this: $ my_program I would like to write a python script that can be used to run iterations of this program using different file arguments. For example: $ my_program <fil...
How to iterate and execute scripts from the command line?
I have a program that I run from the command line that takes two file arguments like this: $ my_program I would like to write a python script that can be used to run iterations of this program using different file arguments. For example: $ my_program <file_1> <file_4> $ my_program <file_2> <file_4> $ my_program <file...
[ "From what I gather, you want something like this:\ncmds = [path_to_program, arg1, arg2]\nsubprocess.Popen(cmds)\n\nthen if you want to iterate through many, something like:\ncmds = [('file1', 'file4'), ('file2', 'file4'), ('file3', 'file4')]\nfor arg1, arg2 in cmds:\n subprocess.Popen([path_to_program, arg1, ar...
[ 2, 0, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0006686791_python_subprocess.txt
Q: Python 3 subprocess.PIPE output error I have a simple script that I use to automate CLI calls to our software (the Moab Workload Manager) in testing, to avoid having to use the '--xml' flag to get xml output and then pipe it through tidy so it's easily readable. It uses a subprocess.Popen call to run the command, ...
Python 3 subprocess.PIPE output error
I have a simple script that I use to automate CLI calls to our software (the Moab Workload Manager) in testing, to avoid having to use the '--xml' flag to get xml output and then pipe it through tidy so it's easily readable. It uses a subprocess.Popen call to run the command, then uses str.strip() and str.replace() to ...
[ "bytes.replace() expects bytes as arguments:\ncrOut.strip().replace(b\"><\", b\">\\n<\").replace(b\"\\\" \", b\"\\\"\\n\")\n\nThough in general it could be preferable to decode the input to unicode text as early as possible. And the transformations to be performed on the text (not bytes).\n", "You need to use crO...
[ 3, 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004168809_python_python_3.x.txt
Q: Deleting repeats in a list python Possible Duplicates: How do you remove duplicates from a list in Python whilst preserving order? In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order? I was wondering if there was a function which doe...
Deleting repeats in a list python
Possible Duplicates: How do you remove duplicates from a list in Python whilst preserving order? In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order? I was wondering if there was a function which does the following: Take a list as an arg...
[ "Please see the Python documentation for three ways to accomplish this. The following is copied from that site. Replace the example 'mylist' with your variable name ('list').\nFirst Example: If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:\nif myl...
[ 7, 5, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006685710_list_python.txt
Q: pip not finding setup file I am getting an error when trying to install a python package with pip. It is looking in a certain directory for "setup.py" after untaring the package and it can't find it there. The setup.py file is actually one directory down. It's looking in: 'virtualenvs/pyling/build/nltk/setup.py'...
pip not finding setup file
I am getting an error when trying to install a python package with pip. It is looking in a certain directory for "setup.py" after untaring the package and it can't find it there. The setup.py file is actually one directory down. It's looking in: 'virtualenvs/pyling/build/nltk/setup.py' but it's actually in: virtuale...
[ "What I found was that pip runs a python command line script that looks like this:\n__file__ = '<path to package>/setup.py'\n\nfrom setuptools.command import egg_info\n\ndef replacement_run(self):\n self.mkpath(self.egg_info)\n\n installer = self.distribution.fetch_build_egg\n\n for ep in egg_info.iter_ent...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "pip", "python", "virtualenv" ]
stackoverflow_0005317672_pip_python_virtualenv.txt
Q: Sorting a list of dicts in python, using another list as a "filter"? b = [{'id': 'a'}, {'id': 'c'}, {'id': 'b'}, {'id': 'e'}] I need this to become: b = [{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}] This new order is defined by another list. my_filter = ['a', 'c', 'e', 'b'] ...as you can see, the list w...
Sorting a list of dicts in python, using another list as a "filter"?
b = [{'id': 'a'}, {'id': 'c'}, {'id': 'b'}, {'id': 'e'}] I need this to become: b = [{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}] This new order is defined by another list. my_filter = ['a', 'c', 'e', 'b'] ...as you can see, the list with dicts now have a sequence of ids that were presented on the my_filter ...
[ ">>> sorted(b, key=lambda x: filter.index(x['id']))\n[{'id': 'a'}, {'id': 'c'}, {'id': 'e'}, {'id': 'b'}]\n\n", "Keep in mind Ignacio's solution is equivalent to doing the nested for loops you wanted to avoid. i.e. it's n^2. A more efficient solution is as follows:\n>>> filterdict = dict((k,i) for i,k in enumerat...
[ 7, 5, 3, 3, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006686455_dictionary_python.txt
Q: getting apache to run python on a mac So i have a new mac and i'm trying to get it to run apache with mod_python, mod_wsgi, and django. I have a test test.py that simply contains: #!/usr/bin/python print "Content-type: text/html" print print "<html><head>" print "" print "</head><body>" print "Test Page" print "<...
getting apache to run python on a mac
So i have a new mac and i'm trying to get it to run apache with mod_python, mod_wsgi, and django. I have a test test.py that simply contains: #!/usr/bin/python print "Content-type: text/html" print print "<html><head>" print "" print "</head><body>" print "Test Page" print "</body></html>" I've just downloaded xcode4...
[ "I think you are expecting WSGI to work like PHP or CGI. It's somewhat different...\nProblem 1: That's a Python script, but it's not a WSGI script. A WSGI script will define an application object (\"object\" in the strict sense, you don't need a class) which is callable. See the WSGI PEP (link), especially \"The...
[ 0 ]
[]
[]
[ "apache2", "mod_wsgi", "python" ]
stackoverflow_0006686766_apache2_mod_wsgi_python.txt
Q: How do I know which versions of pickle a particular version of Python supports? I have a script that requires Python 2.6. I will be adding a large-ish pickled database to the next version, and I want to use the fastest version of pickling. How can I tell which versions of pickling are available in every version of...
How do I know which versions of pickle a particular version of Python supports?
I have a script that requires Python 2.6. I will be adding a large-ish pickled database to the next version, and I want to use the fastest version of pickling. How can I tell which versions of pickling are available in every version of Python 2.6 and later?
[ "Like so:\n>>> import pickle\n>>> pickle.compatible_formats\n['1.0', '1.1', '1.2', '1.3', '2.0']\n\nEdit\nI think it's safe to rely on the latest documentation. For example the pickle documentation for Python 3.2.1 states:\n\nThere are currently 4 different protocols which can be used for\n pickling.\n\nProtocol v...
[ 9 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0006687262_pickle_python.txt
Q: Print out a large list from file into multiple sublists with overlapping sequences in python currently I have a very long sequence in a file and I wish to split this sequence into smaller subsequences, but I would like each subsequence to have an overlap from the previous sequence, and place them into a list. here...
Print out a large list from file into multiple sublists with overlapping sequences in python
currently I have a very long sequence in a file and I wish to split this sequence into smaller subsequences, but I would like each subsequence to have an overlap from the previous sequence, and place them into a list. here is an example of what I mean: (apologies about the cryptic sequence, this is all on 1 line) file1...
[ "seq=\"abcdefessdfekgheithrfkopeifhghtryrhfbcvdfersdwtiyuyrterdhcbgjherytyekdnfiwytowihfiwoeirehjiwoqpft\"\n>>> n = 4\n>>> overlap = 5\n>>> division = len(seq)/n\n>>> [seq[i*division:(i+1)*division+overlap] for i in range(n)]\n['abcdefessdfekgheithrfkopeifhg', 'eifhghtryrhfbcvdfersdwtiyuyrt', 'yuyrterdhcbgjherytyek...
[ 1, 1 ]
[]
[]
[ "list", "overlap", "python", "sequences" ]
stackoverflow_0006687619_list_overlap_python_sequences.txt
Q: jQuery.ajax success callback not called although Pyramid did return response I have this simple jQuery ajax post to a Pyramid webapp. Ajax call: $.ajax({ type: 'POST', url: 'http://localhost:6543/test', dataType: 'json', data: JSON.stringify({"username":"demo","email":"demo@something.com","Pass...
jQuery.ajax success callback not called although Pyramid did return response
I have this simple jQuery ajax post to a Pyramid webapp. Ajax call: $.ajax({ type: 'POST', url: 'http://localhost:6543/test', dataType: 'json', data: JSON.stringify({"username":"demo","email":"demo@something.com","Password":"1234"}), success: function (response) { alert(response); ...
[ "For however is encountering the same issue as me, ie. not having enough sleep!!\nFor the sake of God make sure the html is on the same server, as this happens because of calling across domains of course, the html with jQuery is just a local file, the service is served on localhost.\nSo the server was rejecting the...
[ 2 ]
[]
[]
[ "jquery", "pyramid", "python" ]
stackoverflow_0006619148_jquery_pyramid_python.txt
Q: Failed to verify a dsawithSha1 signed message against a DSA public key in m2crypto I'm trying to verify a signed message using a x509 certificate holding a dsa public key. The x509 certificate was provided by an SAP System in PKCS7 encoding and after converting in PEM with openssl I'm able to read the contents (op...
Failed to verify a dsawithSha1 signed message against a DSA public key in m2crypto
I'm trying to verify a signed message using a x509 certificate holding a dsa public key. The x509 certificate was provided by an SAP System in PKCS7 encoding and after converting in PEM with openssl I'm able to read the contents (openssl x509 -in sapcert.pem -inform pem -text) It holds a public key in dsaEncryption, sh...
[ "What you named seckey64 in your sample code is actually a SignedData structure from CMS.\nIt contains two \"signed attributes\", signing-time and message-digest. In order to verify this as a signature you need to follow the rules of the RFC that apply when at least one signed attribute is present.\nIn your case th...
[ 0 ]
[]
[]
[ "m2crypto", "python" ]
stackoverflow_0006653689_m2crypto_python.txt
Q: Can I copy a Python interpreter and rename it without ill effect? Because of some asinine problem I'm having with multiple Python interpreters and Windows 7, could I simply copy an interpreter, rename it, and run scripts with it without any problems? My Python 2.6 install came with a python.exe and python26.exe ...
Can I copy a Python interpreter and rename it without ill effect?
Because of some asinine problem I'm having with multiple Python interpreters and Windows 7, could I simply copy an interpreter, rename it, and run scripts with it without any problems? My Python 2.6 install came with a python.exe and python26.exe which are identical according to fc. It seems a convenient arrangement...
[ "Yes, depending on what you are doing. You should also be able to move a whole installed interpreter (i.e. the libs and everything) but moving just the executable will probably cause you problems.\nYou might want to create a .bat file that you can use in place of your script that selects the correct interpreter. In...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006687997_python.txt
Q: Multiple Django template loaders I'd like to use Jinja2 with a Django project. I'm using this template loader from Django Snippets, but I still need to be able to render templates with Django for the admin pages. Whenever I try to use the admin pages, though, I get a TemplateSyntaxError because of the unknown tag ...
Multiple Django template loaders
I'd like to use Jinja2 with a Django project. I'm using this template loader from Django Snippets, but I still need to be able to render templates with Django for the admin pages. Whenever I try to use the admin pages, though, I get a TemplateSyntaxError because of the unknown tag "load". Is there a way to make the Jin...
[ "I would recommend using this fork of Coffin when using Jinja and Django templates at the same time: https://github.com/GaretJax/coffin/blame/master/README.rst I implemented this on http://umbel.com/ which uses a combination of Django and Jinja templates.\nIt has a setting that you can use to disable Jinja's templa...
[ 4 ]
[]
[]
[ "django", "jinja2", "python", "templates" ]
stackoverflow_0006687517_django_jinja2_python_templates.txt
Q: ValueError: need more than 1 value to unpack I have a code meant to strim a string within a large text file. When I run it an error message shows up "ValueError: need more than 1 value to unpack". So I changed the integer for 0, 1 and 2 in this line : _, k = line.split('\t',1) If I input 2 it says 'Too many ...
ValueError: need more than 1 value to unpack
I have a code meant to strim a string within a large text file. When I run it an error message shows up "ValueError: need more than 1 value to unpack". So I changed the integer for 0, 1 and 2 in this line : _, k = line.split('\t',1) If I input 2 it says 'Too many value to unpack'. I tried to define each variable ...
[ "You hit a line that doesn't contain \\t, hence the resultant list only has one element.\n", "Oh, that's the code I wrote on the other question. You could have asked there...\nSince the file you gave didn't had any non-empty lines without tab, i assumed there would be no problem.\nYou can check if there's any tab...
[ 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006687772_python_string.txt
Q: Python parsing query string to list I have a form that submits data to the server that looks like the following: videos[0][type]=Vimeo& videos[0][moments][0][time]=11& videos[0][moments][0][lng]=111& videos[0][moments][0][lat]=111& videos[0][moments][1][time]=222& videos[0][moments][1][lng]=222& videos...
Python parsing query string to list
I have a form that submits data to the server that looks like the following: videos[0][type]=Vimeo& videos[0][moments][0][time]=11& videos[0][moments][0][lng]=111& videos[0][moments][0][lat]=111& videos[0][moments][1][time]=222& videos[0][moments][1][lng]=222& videos[0][moments][1][lat]=222& videos[1][type]...
[ "You can use urlparse.parse_qsl to get the query parameters. However you'll need manually to construct the video objects.\nExample implementation can be:\ndef add(root, path, value):\n for part in path[:-1]:\n root = root.setdefault(part, {})\n root[path[-1]] = value\n\ndef parse(s):\n videos = {}\n...
[ 3, 2 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0006687698_flask_python.txt
Q: What's the equivalent of "has_key" in javascript? if dictionary.has_key('school'): How would you write this in javascript? A: hasOwnProperty: if(Object.prototype.hasOwnProperty.call(dictionary, key)) { // ... You can also use the in operator, but sometimes it gives undesirable results: console.log('watch' ...
What's the equivalent of "has_key" in javascript?
if dictionary.has_key('school'): How would you write this in javascript?
[ "hasOwnProperty:\nif(Object.prototype.hasOwnProperty.call(dictionary, key)) {\n // ...\n\nYou can also use the in operator, but sometimes it gives undesirable results:\nconsole.log('watch' in dictionary); // always true\n\n", "Either with the in operator:\nif('school' in dictionary) { …\n\nOr probably supporte...
[ 24, 12, 6, 5, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0006687740_javascript_python.txt
Q: Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified Why this is happening? I don't really understand: >>> P = [ [()]*3 ]*3 >>> P [[(), (), ()], [(), (), ()], [(), (), ()]] >>> P[0][0]=1 >>> P [[1, (), ()], [1, (), ()], [1, (), ()]] A: You've made 3 references to the same lis...
Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified
Why this is happening? I don't really understand: >>> P = [ [()]*3 ]*3 >>> P [[(), (), ()], [(), (), ()], [(), (), ()]] >>> P[0][0]=1 >>> P [[1, (), ()], [1, (), ()], [1, (), ()]]
[ "You've made 3 references to the same list.\n>>> a = b = []\n>>> a.append(42)\n>>> b\n[42]\n\nYou want to do this:\nP = [[()] * 3 for x in range(3)]\n\n", "Lists are mutable, and multiplying a list by a number doesn't copy its elements. You can try changing it to a list comprehension, so it will evaluate [()]*3 t...
[ 33, 9, 6, 6 ]
[]
[]
[ "list", "multiplication", "python" ]
stackoverflow_0006688223_list_multiplication_python.txt
Q: Python: if more than one of three things is true, return false I'm writing a django model that allows my site to have coupons. Coupons can have three types: lifetime account voucher, certain period of months voucher, certain number of dollars voucher. To keep things simple, I'm only allowing coupons to have on...
Python: if more than one of three things is true, return false
I'm writing a django model that allows my site to have coupons. Coupons can have three types: lifetime account voucher, certain period of months voucher, certain number of dollars voucher. To keep things simple, I'm only allowing coupons to have one of the three possible values (i.e. a voucher can't be for $10 and ...
[ "One thing I've done in similar situations is this:\ncoupon_types = (self.months, self.dollars, self.lifetime,)\n\ntrue_count = sum(1 for ct in coupon_types if ct)\nif true_count > 1:\n raise ValueError(\"Coupon can be valid for only one of: months, lifetime, or dollars\") \n\nIt's now much easier to add new c...
[ 12, 5, 2, 2, 2, 2, 1, 1, 0, 0 ]
[ "bool is a subclass of int because Python originally lacked bool, using int for Boolean, so:\nif self.months + self.dollars + self.lifetime > 1:\n ...\n\nThis works because False == 0 and True == 1 are both true.\n" ]
[ -2 ]
[ "django", "python" ]
stackoverflow_0006687557_django_python.txt
Q: whats the fastest way to find eigenvalues/vectors in python? Currently im using numpy which does the job. But, as i'm dealing with matrices with several thousands of rows/columns and later this figure will go up to tens of thousands, i was wondering if there was a package in existence that can perform this kind of...
whats the fastest way to find eigenvalues/vectors in python?
Currently im using numpy which does the job. But, as i'm dealing with matrices with several thousands of rows/columns and later this figure will go up to tens of thousands, i was wondering if there was a package in existence that can perform this kind of calculations faster ?
[ "\n**if your matrix is sparse, then instantiate your matrix using a constructor from scipy.sparse then use the analogous eigenvector/eigenvalue methods in spicy.sparse.linalg. From a performance point of view, this has two advantages:\n\nyour matrix, built from the spicy.sparse constructor, will be smaller in propo...
[ 62, 9 ]
[]
[]
[ "eigenvalue", "linear_algebra", "matrix", "numpy", "python" ]
stackoverflow_0006684238_eigenvalue_linear_algebra_matrix_numpy_python.txt
Q: Perfectly running python script gives error when run from web.py I have the following python script which runs perfectly if run separately: import arcpy val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "") print str(val) I want to expose this as a web se...
Perfectly running python script gives error when run from web.py
I have the following python script which runs perfectly if run separately: import arcpy val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "") print str(val) I want to expose this as a web service and so I installed web.py and wrote the following code for code....
[ "That looks like an error from the third party module. Try finding out what that error code (000582) actually means to the application. \n" ]
[ 0 ]
[]
[]
[ "arcgis", "python", "web.py" ]
stackoverflow_0006687819_arcgis_python_web.py.txt
Q: Replacing each match with a different word I have a regular expression like this: findthe = re.compile(r" the ") replacement = ["firstthe", "secondthe"] sentence = "This is the first sentence in the whole universe!" What I am trying to do is to replace each occurrence with an associated replacement word from a li...
Replacing each match with a different word
I have a regular expression like this: findthe = re.compile(r" the ") replacement = ["firstthe", "secondthe"] sentence = "This is the first sentence in the whole universe!" What I am trying to do is to replace each occurrence with an associated replacement word from a list so that the end sentence would look like this...
[ "If it is not required to use regEx than you can try to use the following code:\nreplacement = [\"firstthe\", \"secondthe\"]\nsentence = \"This is the first sentence in the whole universe!\"\n\nwords = sentence.split()\n\ncounter = 0\nfor i,word in enumerate(words):\n if word == 'the':\n words[i] = replac...
[ 6, 5, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006688581_python_regex.txt
Q: Single pass algorithm for finding the topX percent of items I'm looking for a single-pass algorithm for finding the topX percent of floats in a stream where I do not know the total number ahead of time ... but its on the order of 5-30 million floats. It needs to be single-pass since the data is generated on the fl...
Single pass algorithm for finding the topX percent of items
I'm looking for a single-pass algorithm for finding the topX percent of floats in a stream where I do not know the total number ahead of time ... but its on the order of 5-30 million floats. It needs to be single-pass since the data is generated on the fly and recreate the exact stream a second time. The algorithm I ha...
[ "I'm not sure there's any way to actually do that reliably, as the range denoted by the \"top X percent\" can grow unpredictably as you see more elements. Consider the following input:\n 101 102 103 104 105 106 107 108 109 110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...\n\nIf you wanted the top 25% of elements, you'd end up...
[ 5, 4, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006687145_algorithm_python.txt
Q: Suitability of deploying python 2.7 apps using external (PyPi) packages in major hosts I am writing a python program for processing files (no DJango involved). I need ZODB3 and Whoosh which are hosted on http://pypi.python.org. It needs to be deployed in a major host like Bluehost or Hostgator. My questions are: ...
Suitability of deploying python 2.7 apps using external (PyPi) packages in major hosts
I am writing a python program for processing files (no DJango involved). I need ZODB3 and Whoosh which are hosted on http://pypi.python.org. It needs to be deployed in a major host like Bluehost or Hostgator. My questions are: Can I depend on reliable Python 2.7 support from major hosts? Can they support other package...
[ "No you cannot depend on any kind of Python support from any hoster or any operating system. Build your own portable Python distro and include all the 3rd party modules that you will need. Then you have one tarball to install on any Linux VM and everything just works. You also avoid breaking OS tools that depend on...
[ 0 ]
[]
[]
[ "python", "web_hosting" ]
stackoverflow_0006689237_python_web_hosting.txt
Q: How to excute python script when pushing a button on excel I have several python scripts, test1,py, test2,py, test3.py and so on. I would like to have three buttons (using VBA) on the Excel screen. How do I associate a button to a specific python filename so that I can execute the file and capture the python respo...
How to excute python script when pushing a button on excel
I have several python scripts, test1,py, test2,py, test3.py and so on. I would like to have three buttons (using VBA) on the Excel screen. How do I associate a button to a specific python filename so that I can execute the file and capture the python response into a text box within excel (message response).
[ "You could try embedding Python in Excel with this http://code.google.com/p/pyinex/\nOr just have some VBA code that runs a Python shell script and captures the output into a file, then reads the file and fills the textbox.\nOr try writing a Python COM server in 20 lines https://web.archive.org/web/20111113152839/h...
[ 3 ]
[]
[]
[ "excel", "python", "vba" ]
stackoverflow_0006688115_excel_python_vba.txt
Q: Calling Python functions from C++ I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using boost.python to accomplish this. Say there is a function defined in Python: def callback(arg1, arg2): #do so...
Calling Python functions from C++
I am trying to achieve call Python functions from C++. I thought it could be achieved through function pointers, but it does not seem to be possible. I have been using boost.python to accomplish this. Say there is a function defined in Python: def callback(arg1, arg2): #do something return something Now I nee...
[ "If it might have any name:\nPass it to a function that takes a boost::python::object.\nbp::object pycb; //global variable. could also store it in a map, etc\nvoid register_callback(bp::object cb)\n{\n pycb = cb;\n}\n\nIf it is in a single known namespace with a consistent name: \nbp::object pycb = bp::scope(\...
[ 15, 4, 2, 1 ]
[]
[]
[ "boost_python", "c++", "callback", "python" ]
stackoverflow_0004331599_boost_python_c++_callback_python.txt
Q: python add time to a countdown already running I want to have an app where if I click a button I add X amount of time to my running countdown timer. I'm guessing I have to use threads for this but am not sure how to implement it.. Here is the code I have so far: def countdown_controller(add_time): end_it = Fa...
python add time to a countdown already running
I want to have an app where if I click a button I add X amount of time to my running countdown timer. I'm guessing I have to use threads for this but am not sure how to implement it.. Here is the code I have so far: def countdown_controller(add_time): end_it = False def timer(time_this): start = time.t...
[ "I would say that there is a flaw in the design of the code, because your screen output blocks down the entire program doing nothing (time.sleep(0.1)).\nTypically what you want to to do in these cases is having a main loop in your program that cycles through the various operations that make your program run. This g...
[ 1, 0 ]
[]
[]
[ "countdown", "multithreading", "python", "timer" ]
stackoverflow_0006688126_countdown_multithreading_python_timer.txt
Q: Python: would this leave me with a clean environment? I want to change directories in the python (not ipython) repl under certain circumstances. If I programmatically send the following text will I be likely to avoid any name pollution? import os as prefix_hide_os prefix_hide_os.chdir("/some/path) del prefix_hide_...
Python: would this leave me with a clean environment?
I want to change directories in the python (not ipython) repl under certain circumstances. If I programmatically send the following text will I be likely to avoid any name pollution? import os as prefix_hide_os prefix_hide_os.chdir("/some/path) del prefix_hide_os
[ "Just use this\n__import__(\"os\").chdir(\"/some/path\")\n\n" ]
[ 2 ]
[]
[]
[ "namespaces", "python", "read_eval_print_loop" ]
stackoverflow_0006689502_namespaces_python_read_eval_print_loop.txt
Q: Using global variable as default parameter a.py #!c:/Python27/python.exe -u from connection import Connection import globals globals.server_ip = '192.168.0.1' connection = Connection() globals.py #!c:/Python27/python.exe -u server_ip = '127.0.0.1' connection.py import globals class Connection: de...
Using global variable as default parameter
a.py #!c:/Python27/python.exe -u from connection import Connection import globals globals.server_ip = '192.168.0.1' connection = Connection() globals.py #!c:/Python27/python.exe -u server_ip = '127.0.0.1' connection.py import globals class Connection: def __init__(self, server_ip = globals.server_ip):...
[ "def __init__(self, server_ip=globals.server_ip):\n\nThe argument is bound when the method is created and not re-evaluated later.\nTo use whatever is the current value, use something like this:\ndef __init__(self, server_ip=None):\n if server_ip is None:\n server_ip = globals.server_ip\n\n\nBtw, for exact...
[ 14 ]
[]
[]
[ "python" ]
stackoverflow_0006689652_python.txt
Q: Get size of movie file in Python How would I get the size of a .mov file in Python. With other files, I can do: >>> f = open('<file>') >>> import os >>> os.path.getsize(f.read()) However, when I try and do this with a .mov file, I get the following error: >>> os.path.getsize(f.read()) Traceback (most recent call...
Get size of movie file in Python
How would I get the size of a .mov file in Python. With other files, I can do: >>> f = open('<file>') >>> import os >>> os.path.getsize(f.read()) However, when I try and do this with a .mov file, I get the following error: >>> os.path.getsize(f.read()) Traceback (most recent call last): File "<stdin>", line 1, in <...
[ "You are doing it wrong. os.path.getsize takes a file name, not file contents. I have no idea why your first code sample works.\nSo you need to call just os.path.getsize(<file>).\n", "Try the following:\nos.path.getsize(FILENAME_AS_STRING)\n\n" ]
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006689824_python.txt
Q: Raising events and object persistence in Django I have a tricky Django problem which didn't occur to me when I was developing it. My Django application allows a user to sign up and store his login credentials for a sites. The Django application basically allows the user to search this other site (by scraping conte...
Raising events and object persistence in Django
I have a tricky Django problem which didn't occur to me when I was developing it. My Django application allows a user to sign up and store his login credentials for a sites. The Django application basically allows the user to search this other site (by scraping content off it) and returns the result to the user. For ea...
[ "Something else to remember: You need to maintain a browser session with the remote site so that site knows which CAPTCHA you're trying to solve. Lots of webclients allow you to store your cookies and I'd suggest you dump them in the Django Session of the user you're doing the screen scraping for. Then load them ba...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003031483_django_python.txt
Q: Creating a follow button? How to maximize efficiency? I'm using django. I want to create a follow button that once clicked will include the current user in the group of followers and then display the number of followers. There is a unfollow button, too, which obviously does the opposite. My question is how I cou...
Creating a follow button? How to maximize efficiency?
I'm using django. I want to create a follow button that once clicked will include the current user in the group of followers and then display the number of followers. There is a unfollow button, too, which obviously does the opposite. My question is how I could do this with the least number of queries possible and as...
[ "IMHO: \n\nAnd retrieving the number of followers will take another query from the user_to_post table with count.\n\n\nYou don't need to retrieve anything if you inserting something than you have it. Take this data and use them... Or even path them to your other function, like unnecessary variables or so...\nfor e....
[ 0 ]
[]
[]
[ "django", "many_to_many", "python", "relational_database", "sql" ]
stackoverflow_0006671230_django_many_to_many_python_relational_database_sql.txt
Q: Hashing uncertain objects I need to design object that support some sort of uncertainty (or wild characters, if you wish) it its components. The work is done in Python. Consider the following class class C(): def __init__(self, p1): self.p1 = p1 The property p1 can be either "x", "y", "z", but someti...
Hashing uncertain objects
I need to design object that support some sort of uncertainty (or wild characters, if you wish) it its components. The work is done in Python. Consider the following class class C(): def __init__(self, p1): self.p1 = p1 The property p1 can be either "x", "y", "z", but sometimes "x or y", or any other comb...
[ "Your equality criterion is not transitive, and therefore invalid:\nC('x') == C('x or y') == C('y')\n\nbut\nC('x') != C('y')\n\nSince you can construct an element that equals all others C('x or y or z or a or ...'), the only hash function that fulfills c1 == c2 ⇒ hash(c1) == hash(c2) is a constant one, i.e.\ndef __...
[ 1, 0, 0, 0 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0006689935_hash_python.txt
Q: Don't understand algorithmic of string to list of words function This is a Python function. It's convert to a list of words from a string. But I don't understand the algorithmic the part of code: for c in ch: if c==" ": lista.append(ct) # add to list of temporary string ct="" ...
Don't understand algorithmic of string to list of words function
This is a Python function. It's convert to a list of words from a string. But I don't understand the algorithmic the part of code: for c in ch: if c==" ": lista.append(ct) # add to list of temporary string ct="" # the ch temporary string reinicialization I don't understand, h...
[ "else:\n ct=ct+c\n\nThese are the lines you are overlooking.\nct is set empty when a space if found, but after it was already added to the list.\nIf the current character is not a space, the character is appended to ct.\nSo when you encounter the next space, you have the last word in ct and can add it to the li...
[ 3, 2, 1 ]
[]
[]
[ "algorithm", "python", "string" ]
stackoverflow_0006690222_algorithm_python_string.txt
Q: Multiple while matches in python I have 5 different strings i am searching for in a text file. I am trying to get python to ask the user for a "room number" and if any of those numbers match, to continue, otherwise ask again until a correct number is entered. I can get it to work if try: roomNumber = input("Enter ...
Multiple while matches in python
I have 5 different strings i am searching for in a text file. I am trying to get python to ask the user for a "room number" and if any of those numbers match, to continue, otherwise ask again until a correct number is entered. I can get it to work if try: roomNumber = input("Enter the room number: ") while roomNumber !...
[ "Python has an in/not in operator that is useful for things like this:\nwhile roomNumber not in (\"L1\", \"L2\", \"L3\", \"L4\", \"L5\"):\n ...\n\nIt works for almost any container type in Python; all of the following are true:\n1 in [1, 2, 3]\n3 in range(50)\n\"foo\" in { \"foo\": \"bar\" }\n\"bar\" not in { \"...
[ 7, 2 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0006690377_python_while_loop.txt
Q: Parse/extract table data using python <html> <table border="1px"> <tr> <td>yes</td> <td>no</td> </tr> </table> </html> Is there any way to get the contents of the table (yes ,no) besides beautifulsoup?? A python beginner,any help or any kind of direction will be of great help. Thank you A: You can use the HTM...
Parse/extract table data using python
<html> <table border="1px"> <tr> <td>yes</td> <td>no</td> </tr> </table> </html> Is there any way to get the contents of the table (yes ,no) besides beautifulsoup?? A python beginner,any help or any kind of direction will be of great help. Thank you
[ "You can use the HTMLParser module that comes with the Python standard library.\n>>> import HTMLParser\n>>> data = '''\n... <html> \n... <table border=\"1px\"> \n... <tr>\n... <td>yes</td>\n... <td>no</td>\n... </tr>\n... </table>\n... </html>\n... '''\n>>> class TableParser(HTMLParser.HTMLParser):\n... def __i...
[ 12 ]
[]
[]
[ "html", "python" ]
stackoverflow_0006690367_html_python.txt
Q: How can I traverse directories named in Japanese in Python? I'm trying to build a simple helper utility that will look through my projects and find and return the open ones to me via command line. But my calls to os.listdir return gibberish (example: '\x82\xa9\x82\xcc\x96I') whenever the folder or filename is in J...
How can I traverse directories named in Japanese in Python?
I'm trying to build a simple helper utility that will look through my projects and find and return the open ones to me via command line. But my calls to os.listdir return gibberish (example: '\x82\xa9\x82\xcc\x96I') whenever the folder or filename is in Japanese, and said gibberish can't be passed to the call again to ...
[ "You may need to decode the string into Unicode, then re-encode it in UTF-8 before passing it to os.listdir. It looks like your Japanese string is encoded in shift-JIS:\n>>> '\\x82\\xa9\\x82\\xcc\\x96I'.decode('shift-jis').encode('utf-8')\n'\\xe3\\x81\\x8b\\xe3\\x81\\xae\\xe8\\x9c\\x82'\n>>> print '\\x82\\xa9\\x82\...
[ 6, 2 ]
[]
[]
[ "character_encoding", "internationalization", "ios", "python", "unicode" ]
stackoverflow_0006690702_character_encoding_internationalization_ios_python_unicode.txt
Q: What's wrong with this gzip format? I use the following python code to download web pages from servers with gzip compression: url = "http://www.v-gn.de/wbb/" import urllib2 request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) content = response.read() res...
What's wrong with this gzip format?
I use the following python code to download web pages from servers with gzip compression: url = "http://www.v-gn.de/wbb/" import urllib2 request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) content = response.read() response.close() import gzip from StringIO ...
[ "It appears you can call readline() on the gzip.GzipFile object, but\nread() raises a struct.error because the file ends abruptly. \nSince readline works (except at the very end), you could do something like this:\nimport urllib2\nimport StringIO\nimport gzip\nimport struct\n\nurl = \"http://www.v-gn.de/wbb/\"\nreq...
[ 4, 3, 3 ]
[]
[]
[ "gzip", "http", "python" ]
stackoverflow_0003652177_gzip_http_python.txt
Q: How can I sort out this data? http://img32.imageshack.us/img32/6649/workspace1001.png big version I have this product data in a csv file, but some of the fields are wrong. Look at the screenshot. Some of the images are like this: image.jpg#foobar When they need to be image.jpg Not all of them have this. They are a...
How can I sort out this data?
http://img32.imageshack.us/img32/6649/workspace1001.png big version I have this product data in a csv file, but some of the fields are wrong. Look at the screenshot. Some of the images are like this: image.jpg#foobar When they need to be image.jpg Not all of them have this. They are all .jpg Is there something I can do...
[ "sed -i.bk -e 's/jpg#[^,]*/jpg/g' filename\n\n", "So all you want to do is strip the #... from column S, the image column right?\nPerl can do this neatly. Handles quoted cols in CSV and only updates the columns you specifiy.\nmy $in = IO::File->new( \"<old.csv\" );\nmy $out = IO::File->new( \">new.csv\" );\nmy $c...
[ 3, 0 ]
[]
[]
[ "perl", "python", "regex", "sed" ]
stackoverflow_0006690995_perl_python_regex_sed.txt
Q: PyCurl alternative, a pythonic wrapper for libcurl? PycURL is a thin wrapper around the C libcurl API, I wonder if there's any more pythonic wrapper for libcurl which supports CurlMulti ? A: As with most bindings made for C libraries, it is clever to make a very thin layer on top of it to offer the most of it. ...
PyCurl alternative, a pythonic wrapper for libcurl?
PycURL is a thin wrapper around the C libcurl API, I wonder if there's any more pythonic wrapper for libcurl which supports CurlMulti ?
[ "As with most bindings made for C libraries, it is clever to make a very thin layer on top of it to offer the most of it.\nThis said, it generally makes sense to wrap that binding itself then to offer more higher level features and more language-specific ways to do things, rather than to write yet another binding.\...
[ 2 ]
[]
[]
[ "libcurl", "pycurl", "python" ]
stackoverflow_0006591238_libcurl_pycurl_python.txt
Q: Why do I get an import error for multiprocessing when my code is called from a unittest? (PyCharm Python 3) In one of my modules I do the following import: from multiprocessing import Pool This module works fine when called normally, but when I use this from a unittest, I get the following error: Error Traceback ...
Why do I get an import error for multiprocessing when my code is called from a unittest? (PyCharm Python 3)
In one of my modules I do the following import: from multiprocessing import Pool This module works fine when called normally, but when I use this from a unittest, I get the following error: Error Traceback (most recent call last): File "/share/work/peter/software/lib/python3.2/unittest/case.py", line 387, in _execut...
[ "It may be because you have the ...src/parallelize/backend/ directory on your Python path (perhaps it is the working directory), and Python is trying to import Pool from your own multiprocessing.py there, not from the standard library. I don’t know if it’s possible with PyCharm, but try changing the working directo...
[ 2 ]
[]
[]
[ "multiprocessing", "pycharm", "python", "python_3.x", "unit_testing" ]
stackoverflow_0006690220_multiprocessing_pycharm_python_python_3.x_unit_testing.txt
Q: How can we make a software which can be installed? I have no experience in making a program into an software. I want to mimic a software out there because the software is simple and yet not free. I want to use python as the language chosen. So what is the process/steps to make an software using python? The softwar...
How can we make a software which can be installed?
I have no experience in making a program into an software. I want to mimic a software out there because the software is simple and yet not free. I want to use python as the language chosen. So what is the process/steps to make an software using python? The software should be okay in Windows. I only have experience in m...
[ "Not sure I got what you are asking for either, but among the most typical ways to create installations or executables there are:\n\nDistutils (part of the standard library)\nPyInstaller (cross-platform)\nPy2Exe (windows only)\n\nHTH!\n", "I'm not quite certain I understand what you're asking, but I'm guessing yo...
[ 3, 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006691193_python_windows.txt
Q: Delete function picks up CSRF value as path Sorry for the massive code but I figured just put everything related out there. The fix might be easy. I'm using a filemanager app django-fileman and I'm trying to get it work. So the problems are the move to basket and delete functions. But I will show the delete functi...
Delete function picks up CSRF value as path
Sorry for the massive code but I figured just put everything related out there. The fix might be easy. I'm using a filemanager app django-fileman and I'm trying to get it work. So the problems are the move to basket and delete functions. But I will show the delete function here because they probably have the same probl...
[ "Perhaps unsurprisingly the following code is processing the csrf token cookie:\nif (!safeMethod(settings.type) && sameOrigin(settings.url)) {\n xhr.setRequestHeader(\"X-CSRFToken\", getCookie('csrftoken'));\n }\n});\n\nTry using your own cookie name, and if you need a request header, use your own name for th...
[ 1 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0006691613_ajax_django_jquery_python.txt
Q: string split in python I want to split string between a tab. Let's say I have some text in a file.txt Kern_County_Museum 1,000,000+ Fairplex_railway_exhibit Depot and rolling stock So I want to remove redundancy from left side and keep right side as it is. import re import string import urllib for line in o...
string split in python
I want to split string between a tab. Let's say I have some text in a file.txt Kern_County_Museum 1,000,000+ Fairplex_railway_exhibit Depot and rolling stock So I want to remove redundancy from left side and keep right side as it is. import re import string import urllib for line in open('file.txt', 'r').readlin...
[ "Restrain your split.\nleft, right = line.split(None, 1)\n\n", "By default split method splits string by any whitespace. To split string by a tab, pass extra parameter to this method:\nleft, right = line.split('\\t', 1)\n\n", "Use str.partition\nleft, delim, right = line.partition('\\t')\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0006691539_python_string_formatting.txt
Q: Python CGI Script (using XML & mindom) cannot extract null data This portion of code parses XML for output to the screen on a webpage. for counter in range(100): try: for item in BlekkoSearchResultsXML.getElementsByTagName('item'): Blekko_PageTitle = item.getElementsByTagName('title')[cou...
Python CGI Script (using XML & mindom) cannot extract null data
This portion of code parses XML for output to the screen on a webpage. for counter in range(100): try: for item in BlekkoSearchResultsXML.getElementsByTagName('item'): Blekko_PageTitle = item.getElementsByTagName('title')[counter].firstChild.toxml(encoding="utf-8") Blekko_PageDesc ...
[ "You're doing except wrong: it catches Exception objects that get raised. You want \nexcept AttributeError:\n\nAlternatively, use a conditional:\nif Blekko_PageTitle = None:\n ...\nelse:\n ...\n\n" ]
[ 0 ]
[]
[]
[ "blekko", "cgi", "minidom", "python", "xml" ]
stackoverflow_0006691666_blekko_cgi_minidom_python_xml.txt
Q: Mod_wsgi syntax error: "Invalid command import" i'm trying to setup mod_wsgi to serve my django media files (i want to use this also in a developement env) I followed this guide to correctly setup mod_wsgi. This is my wsgi file ("django.wsgi") import os, sys path = '/home/smau/Workspace/Maynard/tothego_frontend/'...
Mod_wsgi syntax error: "Invalid command import"
i'm trying to setup mod_wsgi to serve my django media files (i want to use this also in a developement env) I followed this guide to correctly setup mod_wsgi. This is my wsgi file ("django.wsgi") import os, sys path = '/home/smau/Workspace/Maynard/tothego_frontend/' if path not in sys.path: sys.path.append(path) ...
[ "You're supposed to include the configuration file (django.conf), not the WSGI script (django.wsgi).\n" ]
[ 2 ]
[]
[]
[ "django_wsgi", "mod_wsgi", "python" ]
stackoverflow_0006691838_django_wsgi_mod_wsgi_python.txt
Q: How to check if a remote file is writable using python Paramiko (SSHClient)? I am trying to check if a remote file is writable or not using paramiko. My current code is from paramiko.ssh_exception import SSHException, BadHostKeyException import paramiko import sys from optparse import OptionParser import os st...
How to check if a remote file is writable using python Paramiko (SSHClient)?
I am trying to check if a remote file is writable or not using paramiko. My current code is from paramiko.ssh_exception import SSHException, BadHostKeyException import paramiko import sys from optparse import OptionParser import os stdin, stdout, stderr = self.__econnection.exec_command('bash'); stdin.write('if [ -...
[ "assuming ssh is your paramiko SSHClient object, temp_path the path to the file under test, and the connection is already setup try the following:\n# prepare command\ncommand = 'if [ -w {filename} ]; then echo True; else echo False; fi;'\n# add filename\ncommand = command.format(filename=temp_path)\n# execute comma...
[ 2 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0005102702_paramiko_python.txt
Q: Python regexp for data of byte numbers How to make a regexp matching for a row of bytes? For example how to check with regexp that binary data consists of (0-10 byte) characters? data = 0x00 0x05 0x02 0x00 0x03 ... (not a string, binary data) A: If you want to check that the string contains only characters be...
Python regexp for data of byte numbers
How to make a regexp matching for a row of bytes? For example how to check with regexp that binary data consists of (0-10 byte) characters? data = 0x00 0x05 0x02 0x00 0x03 ... (not a string, binary data)
[ "If you want to check that the string contains only characters between chr(0) and chr(10), simply use\nre.match('^[\\0-\\x0A]*$',data)\n\nFor Python3, you can do the same with byte strings:\nre.match(b'^[\\0-\\x0A]*$',b'\\x01\\x02\\x03\\x04')\n\n", "This will match any code before space:\nif re.search('[\\0-\\037...
[ 5, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006691748_python_regex.txt
Q: python "r+" requires file to exist? I know that it doesn't make sense to open file for reading if it doesn't exist, unlike for writing. But I need to create a file object, write data to it and then read it later, that's why I want to use the "r+" mode. Of course I can just open the file for writing once and then o...
python "r+" requires file to exist?
I know that it doesn't make sense to open file for reading if it doesn't exist, unlike for writing. But I need to create a file object, write data to it and then read it later, that's why I want to use the "r+" mode. Of course I can just open the file for writing once and then open the saved file for reading, but the p...
[ "Maybe you should be using a StringIO then. It imitates file-like operations (such as writing to and reading from it).\n" ]
[ 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0006692166_file_python.txt
Q: How to resolve "Could not import django.contrib.syndication.views.feed" error in Django admin? I've updated my Django version to the latest nightly, and I'm getting the following error in the admin; Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndication....
How to resolve "Could not import django.contrib.syndication.views.feed" error in Django admin?
I've updated my Django version to the latest nightly, and I'm getting the following error in the admin; Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndication.views. I had this error in several views too because, indeed, django.contrib.syndication.views.feed...
[ "user643511 suggested that the error might be in my own code, not Django. However she didn't point out the real problem (which I understand since I didn't provide the right information). Only after days of digging I found that I had\nurl(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict'...
[ 11, 7 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006642829_django_django_admin_python.txt
Q: Excel file writing using xlwt+Google app engine - Getting IOError: invalid mode: wb In my application i'm trying to write the data to excel file using xlwt API. When i run the GAE app, i got following error . Please help me to fix this bug. Traceback (most recent call last): File "C:\Program Files\Google\google_...
Excel file writing using xlwt+Google app engine - Getting IOError: invalid mode: wb
In my application i'm trying to write the data to excel file using xlwt API. When i run the GAE app, i got following error . Please help me to fix this bug. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 700, in __call__ handler.get...
[ "You can't write files to the filesystem on App Engine. Instead, serialize it and save it to the datastore or blobstore.\n" ]
[ 3 ]
[]
[]
[ "file_writing", "google_app_engine", "python", "xlwt" ]
stackoverflow_0006692741_file_writing_google_app_engine_python_xlwt.txt
Q: Scapy BitField and type() question I'm writing an addon for scapy, and encountered a problem. I had to slightly modify the original scapy code (every class is inheriting from object) The modified code can be found here: http://pastebin.com/pjcL1KJv The code I wrote is the following: class Foo(): array=[ BitFiel...
Scapy BitField and type() question
I'm writing an addon for scapy, and encountered a problem. I had to slightly modify the original scapy code (every class is inheriting from object) The modified code can be found here: http://pastebin.com/pjcL1KJv The code I wrote is the following: class Foo(): array=[ BitField("foo",0x0,2), BitField("foo...
[ "The second parameter is called default, and it's stored as an attribute also called default.\nb = BitField(\"foo\",0x0,2)\nb.default # 0\n\n", "Try .default attribute for BitField instances.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "scapy" ]
stackoverflow_0006692411_python_scapy.txt