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:
Rename method in class body
Is it possible to rename method in Python?
Something like this
class Validation(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(Validation, self).__init__(methodName)
#Doesn't work
setattr(self,'do_folders_equal','test_do_folders_equal')... | Rename method in class body | Is it possible to rename method in Python?
Something like this
class Validation(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(Validation, self).__init__(methodName)
#Doesn't work
setattr(self,'do_folders_equal','test_do_folders_equal')
Rename method 'do_folders_equal... | [
"You wouldn't rename it, you'd just assign it to another variable:\n\nclass Validation(unittest.TestCase):\ndef __init__(self, methodName='runTest'):\n super(Validation, self).__init__(methodName)\n self.test_do_folders_equal = self.do_folders_equal\n\n\nHowever there can sometimes be some weird interplay wit... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004314750_python.txt |
Q:
Python: Find URLs and add querystring pair
I'm trying to affilliateize some legacy text in a Django webapp. It's a pretty simple scope. The text has some amazon URLs in and I want to munge my ?tag=xxx identifier onto the end of them.
I've written a template filter that I can quickly pass my text through but I'm sl... | Python: Find URLs and add querystring pair | I'm trying to affilliateize some legacy text in a Django webapp. It's a pretty simple scope. The text has some amazon URLs in and I want to munge my ?tag=xxx identifier onto the end of them.
I've written a template filter that I can quickly pass my text through but I'm slightly stuck on writing the regex logic.
t = tex... | [
"Yes, the second parameter to re.sub can be a function, which takes a match object and returns a string. See the documentation.\n",
"\nThere might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.\n\nthis will get the 2 question marks.\n(\\?|(\\?\\?))\n\nI believe th... | [
2,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004315033_python_regex.txt |
Q:
Is it possible to make eggs with a None zip-safe flag default to being instaleld zipped with Distribute?
Our large python project is being upgraded from using the legacy "setuptools" project to use "distribute" as a drop-in replacement.
We've noticed one problematic difference between the two applications: In set... | Is it possible to make eggs with a None zip-safe flag default to being instaleld zipped with Distribute? | Our large python project is being upgraded from using the legacy "setuptools" project to use "distribute" as a drop-in replacement.
We've noticed one problematic difference between the two applications: In setuptools an egg which had an undefined zip-safe flag was assumed to be zip-safe and would install as a zipped f... | [
"If you're using Python 2.4 on Windows, there aren't any advantages to using Distribute over Setuptools. Distribute only offers a comparative advantage on Python 2.6 (where it supports the new \"home\" directory layout) and Python 3.x (which setuptools hasn't been ported to).\nApart from that, there aren't really ... | [
1
] | [] | [] | [
"distribute",
"python",
"setuptools"
] | stackoverflow_0004305512_distribute_python_setuptools.txt |
Q:
How can I send a JSON object from a Python script to jQuery?
I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.
First, in a python script on my server, I ge... | How can I send a JSON object from a Python script to jQuery? | I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.
First, in a python script on my server, I generate and print a JSON array
import json
print "Content-type: app... | [
"In your case you have enclosed the JSON response in an array. To access price you need to access data[0]. You need to structure your JSON data properly.\nThe following changes in your Python script should allow you to access data.Price. Let me know in case you still face any issues.\n import json\n print \"Con... | [
9,
1
] | [] | [] | [
"ajax",
"getjson",
"jquery",
"json",
"python"
] | stackoverflow_0004315900_ajax_getjson_jquery_json_python.txt |
Q:
Redirecting stdout from multiple processes to python Logging module
I have a python script that launches a number of user processes using subprocess.Popen. Each process stdout is redirected to a unique file. For example the I launch each process as follows
proc = my_proc
for p in range(1, max_p, 1):
log_... | Redirecting stdout from multiple processes to python Logging module | I have a python script that launches a number of user processes using subprocess.Popen. Each process stdout is redirected to a unique file. For example the I launch each process as follows
proc = my_proc
for p in range(1, max_p, 1):
log_file = proc + "_" + str(p) + ".log"
log = open(log_file, "w+")
... | [
"Not a pythonic solution; but on linux systems I prefer using logrotate to automatically rotate my logs. Check to see if its installed on your system (On ubuntu say there is a directory called /etc/logrotate.d/ with files automatically run via cron). This may or may not be preferred to having log rotation run fro... | [
1,
0
] | [] | [] | [
"popen",
"python",
"redirect",
"stdout",
"subprocess"
] | stackoverflow_0004316117_popen_python_redirect_stdout_subprocess.txt |
Q:
How to access items in a model with ReferenceProperty?
This is a follow up on my previous question.
I set up the models with ReferenceProperty:
class User(db.Model):
userEmail = db.StringProperty()
class Comment(db.Model):
user = db.ReferenceProperty(User, collection_name="comments")
comment = db.Stri... | How to access items in a model with ReferenceProperty? | This is a follow up on my previous question.
I set up the models with ReferenceProperty:
class User(db.Model):
userEmail = db.StringProperty()
class Comment(db.Model):
user = db.ReferenceProperty(User, collection_name="comments")
comment = db.StringProperty(multiline=True)
class Venue(db.Model):
user ... | [
"venues is actually a query object. So you'll need to fetch or iterate over it.\nTry replacing the self.response.out.write(result.venues) line with a loop:\nquery = User.all()\nusers = query.fetch(10)\nself.response.out.write(\"<html><body><ol>\")\nfor user in users:\n self.response.out.write(\"<li>\")\n sel... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"referenceproperty"
] | stackoverflow_0004316276_google_app_engine_google_cloud_datastore_python_referenceproperty.txt |
Q:
How to run the same test-case for different classes?
I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.
As an example, suppose I have several classes that implement different approaches for partitioning a data-set. T... | How to run the same test-case for different classes? | I have several classes that share some invariants and have a common interface, and I would like to run automatically the same test for each of them.
As an example, suppose I have several classes that implement different approaches for partitioning a data-set. The common invariant here would be, that for all of these c... | [
"You could use multiple inheritance.\nclass PartitionerInvariantsFixture(object):\n def setUp(self):\n self.testDataSet = range(100) # create test-data-set\n super(PartitionInvariantsFixture, self).setUp()\n\n def test_partitioner(self):\n TestCase.assertEqual(self.testDataSet, \n ... | [
13,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0004316294_python_unit_testing.txt |
Q:
Working with subdomain in google app engine
How can I work with sub domain in google app engine (python).
I wanna get first domain part and take some action (handler).
Example:
product.example.com -> send it to products handler
user.example.com -> send it to users handler
Actually, using virtual pat... | Working with subdomain in google app engine | How can I work with sub domain in google app engine (python).
I wanna get first domain part and take some action (handler).
Example:
product.example.com -> send it to products handler
user.example.com -> send it to users handler
Actually, using virtual path I have this code:
application = webapp.WSGIAp... | [
"WSGIApplication isn't capable of routing based on domain. Instead, you need to create a separate application for each subdomain, like this:\napplications = {\n 'product.example.com': webapp.WSGIApplication([\n ('/', IndexHandler),\n ('/(.*)', ProductHandler)]),\n 'user.example.com': webapp.WSGIApplication(... | [
26,
2
] | [] | [] | [
"google_app_engine",
"python",
"subdomain"
] | stackoverflow_0000838078_google_app_engine_python_subdomain.txt |
Q:
Can I take a snapshot of a website from the command line?
I am writing documentation for a website database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?
note: I am using the tags ruby, bash, and python since those are... | Can I take a snapshot of a website from the command line? | I am writing documentation for a website database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?
note: I am using the tags ruby, bash, and python since those are the languages used in our group (along with R and FORTRAN; for... | [
"WkHTMLtoPDF has binaries which also convert web pages to images using webkit's renderer.\n",
"You might find this useful -- an interesting Python project which processes a queue of URLs and exports the browser screenshots to your server. \n",
"Would it be okay to take a snapshot of a web page and save it as an... | [
3,
2,
2,
2,
2
] | [] | [] | [
"bash",
"fortran",
"image",
"python",
"ruby_on_rails"
] | stackoverflow_0004315605_bash_fortran_image_python_ruby_on_rails.txt |
Q:
Program's execution does not end after clicking the close button python (using wxpython-GUI)
I've made a cpu scheduler application using python , i used wxpython to make a frame containing merely a big text area that is updated continously , the problem is that clicking the close button (x) would close the frame b... | Program's execution does not end after clicking the close button python (using wxpython-GUI) | I've made a cpu scheduler application using python , i used wxpython to make a frame containing merely a big text area that is updated continously , the problem is that clicking the close button (x) would close the frame but another or multiple frames would appear again and the program continues execution , below is th... | [
"You have to bind the close event in your wxFrame:\nself.Bind(wx.EVT_CLOSE, self.on_close)\nthen add an on_close method:\ndef on_close(self, event):\n self.Destroy()\n sys.exit(0)\n\n"
] | [
1
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0004316440_python_user_interface_wxpython.txt |
Q:
.py files opens up in a text editor when run from cmd
Whenever I try to run a .py file from cmd it opens up in a text editor(np++). I'm trying to run the following:
django-admin.py startproject testprj
Even if I run 'setup.py install'
A:
You need to change the file association so that .py files open with Pytho... | .py files opens up in a text editor when run from cmd | Whenever I try to run a .py file from cmd it opens up in a text editor(np++). I'm trying to run the following:
django-admin.py startproject testprj
Even if I run 'setup.py install'
| [
"You need to change the file association so that .py files open with Python executable, typically located in C:\\Python<version>\\ and not Notepad++\nChanging this should be easy, but here is how to do it.\nAlso, read here on to set the environment path so that the Python executable is found without you having to n... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0004316883_python.txt |
Q:
How can I protect a logging object from the garbage collector in a multiprocessing process?
I create a couple of worker processes using Python's Multiprocessing module 2.6.
In each worker I use the standard logging module (with log rotation and file per worker)
to keep an eye on the worker. I've noticed that afte... | How can I protect a logging object from the garbage collector in a multiprocessing process? | I create a couple of worker processes using Python's Multiprocessing module 2.6.
In each worker I use the standard logging module (with log rotation and file per worker)
to keep an eye on the worker. I've noticed that after a couple of hours that no more
events are written to the log. The process doesn't appear to cr... | [
"I agree with @THC4k. This doesn't seem like a GC issue. I'll give you my reasons why, and I'm sure somebody will vote me down if I'm wrong (if so, please leave a comment pointing out my error!).\nIf you're using CPython, it primarily uses reference counting, and objects are destroyed immediately when the ref count... | [
1,
0,
0
] | [] | [] | [
"garbage_collection",
"logging",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0004314912_garbage_collection_logging_multiprocessing_multithreading_python.txt |
Q:
pyodbc connection to Oracle database on Linux
Can anyone point me to a "free" resource that allows one to connect via pyodbc to an Oracle database? We have a multi db environment we support. I have DB2 and MSSQL ODBC drivers working but I cannot seem to find any information on connecting via ODBC/pyodbc to an Or... | pyodbc connection to Oracle database on Linux | Can anyone point me to a "free" resource that allows one to connect via pyodbc to an Oracle database? We have a multi db environment we support. I have DB2 and MSSQL ODBC drivers working but I cannot seem to find any information on connecting via ODBC/pyodbc to an Oracle server running on Linux.
Linux: cat /etc/redh... | [
"Not knowing thing one about pyodbc, I have to ask: would the oracle ODBC driver in the instant client software help you out? That's free.\n"
] | [
1
] | [] | [] | [
"oracle",
"pyodbc",
"python"
] | stackoverflow_0004316482_oracle_pyodbc_python.txt |
Q:
How to make "gtk.gdk.pixbuf_new_from_file()" use a relative path?
In gtk.gdk.pixbuf_new_from_file(image), if "image" is not an absolute path, I get:
glib.GError: Failed to open file 'image.png': No such file or directory
That's unless I'm in the directory where the image lives.
note1: I'm running Debian Squeeze, ... | How to make "gtk.gdk.pixbuf_new_from_file()" use a relative path? | In gtk.gdk.pixbuf_new_from_file(image), if "image" is not an absolute path, I get:
glib.GError: Failed to open file 'image.png': No such file or directory
That's unless I'm in the directory where the image lives.
note1: I'm running Debian Squeeze, which uses Python 2.6 by default.
note2: The image and the script live ... | [
"This is not specific to pixbuf_new_from_file, relative paths are always resolved relative to the current directory, which initially is the directory the script is started from.\nYou can get the directory the script is actually in with os.path.dirname(__file__). Then you can either make it your script's current dir... | [
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0004309187_pygtk_python.txt |
Q:
How to programmatically enable/disable network interfaces? (Windows XP)
I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.
A:
... | How to programmatically enable/disable network interfaces? (Windows XP) | I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.
| [
"Using the netsh interface \nUsage set interface [name = ] IfName\n [ [admin = ] ENABLED|DISABLED\n [connect = ] CONNECTED|DISCONNECTED\n [newname = ] NewName ]\nTry including everything inside the outer brackets:\nnetsh interface set interface name=\"thename\" admin=disabled co... | [
11,
6,
2,
1,
0,
0,
0
] | [] | [] | [
"networking",
"python",
"windows_xp"
] | stackoverflow_0000083756_networking_python_windows_xp.txt |
Q:
os.popen() variables
So i have this application thats rather complicated...
To keep it short this is the main things you should know:
file_name = raw_input("Name your file:").lower()
os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)
but this doesn't seem to work. Can i get a fix?
Thanks,
Pas... | os.popen() variables | So i have this application thats rather complicated...
To keep it short this is the main things you should know:
file_name = raw_input("Name your file:").lower()
os.popen(sudo tcpdump -c5 -vvv -w "file_name" host wiki or host wiki2)
but this doesn't seem to work. Can i get a fix?
Thanks,
Pastelinux
edit1:
Alright thi... | [
"Don't use `os.popen', you should use the subprocess module.\nI am assuming this (a string): \nsudo tcpdump -c5 -vvv -w \"file_name\" host wiki or host wiki2\n\nis your command.\nSince we just need to call tcpdump and not get any output from it, we use subprocess.call\n>>> subprocess.call(your_command.split())\n\nO... | [
3,
3,
0
] | [] | [] | [
"os.system",
"popen",
"python"
] | stackoverflow_0004317292_os.system_popen_python.txt |
Q:
How to unpack a list?
When extracting data from a list this way
line[0:3], line[3][:2], line[3][2:]
I receive an array and two variables after it, as should be expected:
(['a', 'b', 'c'], 'd', 'e')
I need to manipulate the list so the end result is
('a', 'b', 'c', 'd', 'e')
How? Thank you.
P.S. Yes, I know that... | How to unpack a list? | When extracting data from a list this way
line[0:3], line[3][:2], line[3][2:]
I receive an array and two variables after it, as should be expected:
(['a', 'b', 'c'], 'd', 'e')
I need to manipulate the list so the end result is
('a', 'b', 'c', 'd', 'e')
How? Thank you.
P.S. Yes, I know that I can write down the first... | [
"from itertools import chain\nprint tuple(chain(['a', 'b', 'c'], 'd', 'e'))\n\nOutput:\n('a', 'b', 'c', 'd','e')\n\n",
"Try this.\nline = ['a', 'b', 'c', 'de']\ntuple(line[0:3] + [line[3][:1]] + [line[3][1:]])\n('a', 'b', 'c', 'd', 'e')\n\nNOTE:\nI think there is some funny business in your slicing logic.\nIf [2:... | [
4,
1,
1,
0,
0
] | [] | [] | [
"iterable_unpacking",
"list",
"python"
] | stackoverflow_0004316993_iterable_unpacking_list_python.txt |
Q:
Python subprocess; Can't read stdout
I have about 500,000+ txt file for about 7+ gigs of data total. I am using python to put them into a sqlite database. I am creating 2 tables, 1. is the pK and the hyperlink to the file.
For the other table I am using an entity extractor that was devloped in perl by a coworker.... | Python subprocess; Can't read stdout | I have about 500,000+ txt file for about 7+ gigs of data total. I am using python to put them into a sqlite database. I am creating 2 tables, 1. is the pK and the hyperlink to the file.
For the other table I am using an entity extractor that was devloped in perl by a coworker.
To accomplish this I am using subprocess.... | [
"Consider using the shell. Life is simpler.\nperl extractSerialNumbers.pl *.txt | python load_database.py\n\nDon't mess around with having Python start perl and all that. Just read the results from perl and process those results in Python.\nSince both processes run concurrently, this tends to be pretty fast and u... | [
2
] | [] | [] | [
"python",
"stdout",
"subprocess"
] | stackoverflow_0004316644_python_stdout_subprocess.txt |
Q:
Jython - using Pygments in Java project
I'm trying to use Pygments in Java project by including Jython.jar. In my Java project I have src/main/python source directory where I placed pygments files into pygments folder so they end up on the classpath. Now I created highlighter.py file in the src/main/python with th... | Jython - using Pygments in Java project | I'm trying to use Pygments in Java project by including Jython.jar. In my Java project I have src/main/python source directory where I placed pygments files into pygments folder so they end up on the classpath. Now I created highlighter.py file in the src/main/python with the following content:
import sys
sys.path.appe... | [
"All right. I figured it out. Made few beginner errors but if you are wondering how to make Pygments work in your Java project here's full tutorial link\nHighlights:\n\nUsing bare jython.jar is insufficient. \nAdding Jython/Lib to your classpath doesn't work. I ended up unjarring jython.jar and adding Lib directory... | [
1
] | [] | [] | [
"java",
"jython",
"pygments",
"python"
] | stackoverflow_0004308434_java_jython_pygments_python.txt |
Q:
Python print adds new line and 0
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:
C:\Python30>python PLINKSS... | Python print adds new line and 0 | Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:
C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Pas... | [
"cur_dev is getting the result code returned by the plink command, which is 0. Your read_dev function returns this code, so print(read_dev()) prints the 0.\nJust say read_dev() instead of print(read_dev()).\n",
"It doesn't \"print zero\". It prints cur_dev which is returned by read_dev function, which happens to... | [
4,
4,
0
] | [] | [] | [
"printing",
"python"
] | stackoverflow_0004317297_printing_python.txt |
Q:
How to delay input
First i got a menu asking what i want to do, the problem is even if i select exit i still have to input the variables from the addEntry function. How do i make it so that only when i call the addEntry function i need to input those variables?
date=raw_input('date')
amount=raw_input('amount')
des... | How to delay input | First i got a menu asking what i want to do, the problem is even if i select exit i still have to input the variables from the addEntry function. How do i make it so that only when i call the addEntry function i need to input those variables?
date=raw_input('date')
amount=raw_input('amount')
desc=raw_input('desc')
acco... | [
"If I understand you correctly, you just want to move the calls to raw_input into addEntry, instead of making them arguments; then they only execute and prompt the user for input when addEntry is called:\ndef addEntry():\n date=raw_input('date')\n amount=raw_input('amount')\n desc=raw_input('desc')\n ac... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004317782_python.txt |
Q:
A quickie: python, terminal "print command not found"
Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either fro... | A quickie: python, terminal "print command not found" | Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either from BBedit or Textwrangler. The following code:
print "Please... | [
"Try putting \n#!/usr/bin/env python\n\nat the top of the script. The program is trying to execute it like a shell script instead of running it through python.\n",
"It's running the script as a shell script, not a Python script.\n",
"Also, be aware that this form of print (print-as-command) is changing to print... | [
25,
1,
0
] | [] | [] | [
"bbedit",
"macos",
"python",
"terminal",
"textwrangler"
] | stackoverflow_0004315131_bbedit_macos_python_terminal_textwrangler.txt |
Q:
Best way to support multi-login on AppEngine
I'm refactoring for a client an app that should support OpenID, Facebook Connect and custom authentication (email+password).
Suppose that i have:
class MyUser(db.Model):
pass
class Item(db.Model):
owner = db.ReferenceProperty(MyUser)
I was thinking to implement... | Best way to support multi-login on AppEngine | I'm refactoring for a client an app that should support OpenID, Facebook Connect and custom authentication (email+password).
Suppose that i have:
class MyUser(db.Model):
pass
class Item(db.Model):
owner = db.ReferenceProperty(MyUser)
I was thinking to implement different authentication systems this way:
class ... | [
"I would take a close look at tipfy and its Authentication extension.*\nThey have implemented a Universal User model that can be used with App Engine's default users API, own auth or third party authentication methods (OpenId, OAuth etc).\nHere is the documentation, look for MultiAuthMixin section.\n*good progra... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004200531_google_app_engine_python.txt |
Q:
Python: Frequency Analysis of Sound Files
I am generating some sound files that play tones at various frequencies with a certain number of harmonics.
Ultimately, these sounds will be played on a device with a small speaker.
I have the frequency response curve of the speaker and want to do the following in Python... | Python: Frequency Analysis of Sound Files | I am generating some sound files that play tones at various frequencies with a certain number of harmonics.
Ultimately, these sounds will be played on a device with a small speaker.
I have the frequency response curve of the speaker and want to do the following in Python:
Plot the frequency spectrum of sound file. I... | [
"I know you didn't mention Pylab/Matplotlib, but it works. Here is an example (assumes single-channel signal):\nx, fs, nbits = audiolab.wavread('schubert.wav')\naudiolab.play(x, fs)\nN = 4*fs # four seconds of audio\nX = scipy.fft(x[:N])\nXdb = 20*scipy.log10(scipy.absolute(X))\nf = scipy.linspace(0, fs, N, endp... | [
10,
4,
0
] | [] | [] | [
"audio",
"fft",
"gnuplot",
"python",
"wav"
] | stackoverflow_0004315989_audio_fft_gnuplot_python_wav.txt |
Q:
How to reverse a transformation by matrix in Blender?
I have a selected mesh (creatively called 'selected') which I want to work with in its local space so I use the following:
tmesh = NMesh.GetRawFromObject(selected.name)
tmesh.transform(selected.matrix)
I then do a bunch of calculations on its verticies... | How to reverse a transformation by matrix in Blender? | I have a selected mesh (creatively called 'selected') which I want to work with in its local space so I use the following:
tmesh = NMesh.GetRawFromObject(selected.name)
tmesh.transform(selected.matrix)
I then do a bunch of calculations on its verticies and remove them by index, which works great.
What doesn't ... | [
"I'm not familiar with Blender specfically, but after a quick peek at the documentation, in principle it seems like you ought to be able to use the invert() Matrix method to obtain the inverse transformation of the selected.matrix (perhaps after first making a copy() of it).\n"
] | [
1
] | [] | [] | [
"blender",
"python",
"scripting"
] | stackoverflow_0004316642_blender_python_scripting.txt |
Q:
ordering a list of string according to name (month)
I have a list of figures and I want to create a text file (using python) with their names listed in a specific order (for a movie creation with mencoder). In particular here, the figure names include months (April, August...). I want the one for Januray first, th... | ordering a list of string according to name (month) | I have a list of figures and I want to create a text file (using python) with their names listed in a specific order (for a movie creation with mencoder). In particular here, the figure names include months (April, August...). I want the one for Januray first, then February and so on.
I know I could do it in an ugly wa... | [
"As the key for the sort, split by _ and map the third element.\nsorted(filenames, key=lambda x: monthdict[x.split('_')[2]])\n\n",
"Longer, but more flexible answer for ordering sequences:\nimport collections\n\ndef rearrange(seq, order, keyfunc):\n if not isinstance(order, collections.Mapping):\n order... | [
6,
1,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0004310450_list_python_string.txt |
Q:
Weird python error - I/O error No such file of directory
I am trying to open python prompt and run the below code:
>>> a=open("Andrew_Smith_(author/education_professional)_0",'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory:
'Andrew_Smith_(au... | Weird python error - I/O error No such file of directory | I am trying to open python prompt and run the below code:
>>> a=open("Andrew_Smith_(author/education_professional)_0",'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory:
'Andrew_Smith_(author/education_professional)_0'
I am not sure why I am gettin... | [
"As others have said the issue is the /, it is looking for a directory named Andrew_Smith_(author to create the new file education_professional)_0 in.\nbash-3.2# mkdir \"Andrew_Smith_(author\"\nbash-3.2# python\n>>> a=open(\"Andrew_Smith_(author/education_professional)_0\", 'w')\n>>> \n\n",
"Because you have a / ... | [
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004318485_python.txt |
Q:
homogenization the functions can be compiled into a calculate networks?
Inside of a network, information (package) can be passed to different node(hosts), by modify it's content it can carry different meaning. The final package depends on hosts input via it's given route of network.
Now I want to implement a calcu... | homogenization the functions can be compiled into a calculate networks? | Inside of a network, information (package) can be passed to different node(hosts), by modify it's content it can carry different meaning. The final package depends on hosts input via it's given route of network.
Now I want to implement a calculating network model can do small jobs by give different calculate path.
Prot... | [
"You could test each function first with a set of sample data; any function which returns consistently unusable values might then be discarded.\ndef isGoodFn(f):\n testData = [1,2,3,8,38,73,159] # random test input\n goodEnough = 0.8 * len(testData) # need 80% pass rate\n\n try:\n good = 0\n ... | [
1,
0,
0
] | [] | [] | [
"chaining",
"function",
"python"
] | stackoverflow_0004313205_chaining_function_python.txt |
Q:
Offline python plugin installation for Netbeans?
I have a latest windows netbeans version (6.9.1) and i want to instal a python plugin for it. I have no problems on a computer that has internet connection, it's just tools->plugins->Available. But i have another computer that don't have internet connection availabl... | Offline python plugin installation for Netbeans? | I have a latest windows netbeans version (6.9.1) and i want to instal a python plugin for it. I have no problems on a computer that has internet connection, it's just tools->plugins->Available. But i have another computer that don't have internet connection available :(. Is it possible to install python addin for it? W... | [
"Check:\n\n/home/username/netbeans-6.9.1/php/update/download\n\nI tested it with the php plugin so you should check the python directory. Or if you are using windows you may find somewhere similar.\nIf no .nbm file there, you may try:\n\nUninstall python plugin from the other computer, and reinstall it. Don't resta... | [
2,
1
] | [] | [] | [
"netbeans",
"python"
] | stackoverflow_0004246939_netbeans_python.txt |
Q:
How to display an icon in a menu item?
I know how to create a plain text menu item:
item = gtk.MenuItem('text')
but how can I display an icon?
Like this:
A:
Simply use ImageMenuItem instead of MenuItem.
Here's an example: http://zetcode.com/tutorials/pygtktutorial/menus/
| How to display an icon in a menu item? | I know how to create a plain text menu item:
item = gtk.MenuItem('text')
but how can I display an icon?
Like this:
| [
"Simply use ImageMenuItem instead of MenuItem.\nHere's an example: http://zetcode.com/tutorials/pygtktutorial/menus/\n"
] | [
3
] | [] | [] | [
"gtk",
"menu",
"menuitem",
"pygtk",
"python"
] | stackoverflow_0004318703_gtk_menu_menuitem_pygtk_python.txt |
Q:
Single precision big endian float values to Python's float (double precision, big endian)
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?
The Arduino send so... | Single precision big endian float values to Python's float (double precision, big endian) | I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?
The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to fl... | [
"Building on Ignacio Vazquez-Abrams's answer,\nimport binascii\nimport struct\n\ntext='8192323E'\nprint(struct.unpack('<f',binascii.unhexlify(text))[0])\n# 0.17438699305057526\n\n",
">>> struct.unpack('<f', '\\x81\\x92\\x32\\x3e')\n(0.17438699305057526,)\n\n",
"Indeed, you need to invert the byte order. Look:\n... | [
5,
4,
0,
0
] | [] | [] | [
"arduino",
"python"
] | stackoverflow_0004315190_arduino_python.txt |
Q:
Python regex: Fix one html close tag
<div>random contents without < or > , but has ( ) <div>
Just need to fix the closing div tag
so it looks like <div>random contents</div>
I need to do it in Python by regex.
The input is exact like the first line, there will no any < or > in random contents
A:
I wouldn't rec... | Python regex: Fix one html close tag | <div>random contents without < or > , but has ( ) <div>
Just need to fix the closing div tag
so it looks like <div>random contents</div>
I need to do it in Python by regex.
The input is exact like the first line, there will no any < or > in random contents
| [
"I wouldn't recommend a regex - use something like tidy (which is a Python wrapper around HTML Tidy).\n",
"Avoid using regular expressions for dealing with HTML.\nThis is how it would be parsed in a DOM tree as it currently is:\n>>> from BeautifulSoup import BeautifulSoup\n>>> BeautifulSoup('<div>random contents<... | [
2,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004318759_python_regex.txt |
Q:
how to return message to ajax?
my ajax code:
$.ajax({
type: 'POST',
url: URL + "xyz/" ,
data: {"email": email},
success: function(data) {
alert('hello')
},
dataType: "json",
});
my handler in python + bottle framework:
def index():
if request.POST == XMLHttpRequest:
ema... | how to return message to ajax? | my ajax code:
$.ajax({
type: 'POST',
url: URL + "xyz/" ,
data: {"email": email},
success: function(data) {
alert('hello')
},
dataType: "json",
});
my handler in python + bottle framework:
def index():
if request.POST == XMLHttpRequest:
email = request.GET.get('email')
... | [
"2 things. First, I don't see why you're trying to check to see if it's an XMLHTTPRequest? I would just check to see if data has been sent via POST. Also it looks like you're sending through POST but trying to retrieve through GET. Try:\ndef index():\n if request.method == \"POST\":\n email = request.... | [
2,
0,
0
] | [] | [] | [
"ajax",
"bottle",
"python"
] | stackoverflow_0004318353_ajax_bottle_python.txt |
Q:
Is there a good Python library that lets me generate a temporary S3 token, so that other people can upload to my S3 bucket?
This is a temporary authentication token that can allow my mobile app to upload directly to S3.
The library should take the details of my Amazon account...and return a token.
I want the simp... | Is there a good Python library that lets me generate a temporary S3 token, so that other people can upload to my S3 bucket? | This is a temporary authentication token that can allow my mobile app to upload directly to S3.
The library should take the details of my Amazon account...and return a token.
I want the simplest library possible :)
| [
"I don't see any reason you can't just use boto\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"python"
] | stackoverflow_0004319066_amazon_s3_amazon_web_services_python.txt |
Q:
How to install Python using source files to a custom directory
I want to build Python 2.7.1 additionally to the one the redhat server already has pre-installed.
What options do I need to modify/use so that Python can be built under i.e. /opt/Python27
I would appreciate any help!
A:
Configure with:
./configure --... | How to install Python using source files to a custom directory | I want to build Python 2.7.1 additionally to the one the redhat server already has pre-installed.
What options do I need to modify/use so that Python can be built under i.e. /opt/Python27
I would appreciate any help!
| [
"Configure with:\n./configure --prefix=/opt/Python27\nIn general, you can just do ./configure --help to get a list of all the options you're allowed to set for that configure script.\n",
"You also want to pass --enable-shared to configure since it is an additional installation of Python.\n"
] | [
5,
1
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0004315657_installation_python.txt |
Q:
generating compiled Tkinter python code
I've noticed that when creating a GUI using Tkinter in python, when running the final .py/.pyw file, I'm not presented with a .pyc file.
I'd like to give my application to someone for personal usage, without giving him the full source code.
Is there anyway of forcing the int... | generating compiled Tkinter python code | I've noticed that when creating a GUI using Tkinter in python, when running the final .py/.pyw file, I'm not presented with a .pyc file.
I'd like to give my application to someone for personal usage, without giving him the full source code.
Is there anyway of forcing the interpreter to generate a pyc file, or any other... | [
"Try:\nimport py_compile\npy_compile.compile(r'/path/to/your/file.py')\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004319206_python_tkinter.txt |
Q:
How to avoid NotImplementedError "Only tempfile.TemporaryFile is available for use" in django on Google App Engine?
I'm using Django 1.1 on Google App Engine through use_library. No Django GAE helper, Django non-rel or similar tools are used here. Django handles URLs routing, forms validation etc., but I'm using p... | How to avoid NotImplementedError "Only tempfile.TemporaryFile is available for use" in django on Google App Engine? | I'm using Django 1.1 on Google App Engine through use_library. No Django GAE helper, Django non-rel or similar tools are used here. Django handles URLs routing, forms validation etc., but I'm using pure App Engine models.
In one of my Django forms there is a FileField, which from time to time, seems to call django.core... | [
"You need to update the settings.py file with the following to change the default Django behaviour:\n# only use the memory file uploader, do not use the file system - not able to do so on\n# google app engine\nFILE_UPLOAD_HANDLERS = ('django.core.files.uploadhandler.MemoryFileUploadHandler',)\nFILE_UPLOAD_MAX_MEMOR... | [
11
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0003586134_django_django_forms_google_app_engine_python.txt |
Q:
'hg strip' created patch is corrupt
I used hg strip to remove some commits from my history.
Now I want to reapply the patch that was made as backup during the strip command: .hg/strip-backup/68a8f24f62d0-backup.hg
Unfortunately when I try to push the patch, it seems that the patch is corrupted:
$:~/sc2$ hg init -... | 'hg strip' created patch is corrupt | I used hg strip to remove some commits from my history.
Now I want to reapply the patch that was made as backup during the strip command: .hg/strip-backup/68a8f24f62d0-backup.hg
Unfortunately when I try to push the patch, it seems that the patch is corrupted:
$:~/sc2$ hg init --mq
adding .hg/patches/68a8f24f62d0-backu... | [
"From the output of hg help strip:\n\nAny stripped changesets are stored in \".hg/strip-backup\" ... They can be restored by running \"hg unbundle .hg /strip-backup/BUNDLE\", where BUNDLE is the bundle file created by the strip.\n\nThis simple demo session illustrates the use of the strip and unbundle commands:\n# ... | [
5,
2
] | [] | [] | [
"mercurial",
"python",
"tortoisehg",
"utf_8"
] | stackoverflow_0004304055_mercurial_python_tortoisehg_utf_8.txt |
Q:
Python urllib2, how to avoid errors - need help
I am using python urllib2 to download pages from the web. I am not using any kind of user_agent etc. I am getting below sample errors. Can someone tell me a easy way to avoid them.
http://www.rottentomatoes.com/m/foxy_brown/
The server couldn't fulfill the request.
E... | Python urllib2, how to avoid errors - need help | I am using python urllib2 to download pages from the web. I am not using any kind of user_agent etc. I am getting below sample errors. Can someone tell me a easy way to avoid them.
http://www.rottentomatoes.com/m/foxy_brown/
The server couldn't fulfill the request.
Error code: 403
http://www.spiritus-temporis.com/ma... | [
"Many web resources require some kind of cookie or other authentication to access, your 403 status codes are most likely the result of this.\n503 errors tend to mean you're rapidly accessing resources from a server in a loop and you need to wait briefly before attempting another access.\nThe 500 example doesn't eve... | [
0,
0
] | [] | [] | [
"http",
"python",
"web_crawler",
"web_scraping"
] | stackoverflow_0004319045_http_python_web_crawler_web_scraping.txt |
Q:
Problem with Arduino and pySerial
I got a problem. I recently bought an Arduino Uno board. I tried to make something funny like controlling an input from my computer. I used Python with pySerial and the program is the following:
arduino = serial.Serial(portaCOM, 9600, timeout = 1)
... in loop ->
arduino.write(valu... | Problem with Arduino and pySerial | I got a problem. I recently bought an Arduino Uno board. I tried to make something funny like controlling an input from my computer. I used Python with pySerial and the program is the following:
arduino = serial.Serial(portaCOM, 9600, timeout = 1)
... in loop ->
arduino.write(value)
def sliderUpdate(self, event):
... | [
"\nFirst of all, make sure your LED is properly connected. Anode (longer pin) to PWM 11 port and cathode (shorter pin) to ground, also you may need to add a resistor between cathode and ground depending on LED.\nMake sure you're writing to the right port from python (that FTDI cable is associated with in your OS).\... | [
2,
1,
1,
0
] | [
"\"the write value should send the value to my board through USB\"\nIf this is not a typo, then you can not use PySerial to access USB ports. There is pyUSB instead, and probably others.\n"
] | [
-1
] | [
"arduino",
"c",
"pyserial",
"python"
] | stackoverflow_0004319121_arduino_c_pyserial_python.txt |
Q:
Python/Numpy MemoryError
Basically, I am getting a memory error in python when trying to perform an algebraic operation on a numpy matrix. The variable u, is a large matrix of double (in the failing case its a 288x288x156 matrix of doubles. I only get this error in this huge case, but I am able to do this on other... | Python/Numpy MemoryError | Basically, I am getting a memory error in python when trying to perform an algebraic operation on a numpy matrix. The variable u, is a large matrix of double (in the failing case its a 288x288x156 matrix of doubles. I only get this error in this huge case, but I am able to do this on other large matrices, just not this... | [
"Rewrite to\np *= alpha\nu += p\n\nand this will use much less memory. Whereas p = p*alpha allocates a whole new matrix for the result of p*alpha and then discards the old p; p*= alpha does the same thing in place.\nIn general, with big matrices, try to use op= assignment. \n",
"Another tip I have found to avoid ... | [
52,
12,
7
] | [] | [] | [
"memory",
"numpy",
"python",
"scipy"
] | stackoverflow_0004318615_memory_numpy_python_scipy.txt |
Q:
How do I modify my Python image resizer code to do this?
When I resize a picture that is smaller than desired, I want the image to NOT get resized...but instead be in the center, with white padding around it.
So, let's say I have an icon that's 50x50. But I want to resize it to 100x100. If I pass it to this func... | How do I modify my Python image resizer code to do this? | When I resize a picture that is smaller than desired, I want the image to NOT get resized...but instead be in the center, with white padding around it.
So, let's say I have an icon that's 50x50. But I want to resize it to 100x100. If I pass it to this function, I would like it to return me the same icon that is cente... | [
"One option is to create a blank white image of the size you want, then draw the existing image in the center.\n"
] | [
3
] | [] | [] | [
"image",
"python",
"python_imaging_library",
"resize"
] | stackoverflow_0004319578_image_python_python_imaging_library_resize.txt |
Q:
python truncate text around keyword
I have a string and I want to search it for a keyword or phrase and return only a portion of the text before and after the keyword or phrase. Google does exactly what I am talking about.
Here is a string I grabbed from the web:
"This filter truncates words like the original tru... | python truncate text around keyword | I have a string and I want to search it for a keyword or phrase and return only a portion of the text before and after the keyword or phrase. Google does exactly what I am talking about.
Here is a string I grabbed from the web:
"This filter truncates words like the original truncate words Django filter, but instead of... | [
"Use a method that gets the index of the phrase you want, then slice the string up to N characters before and after that index. You could get fancy by looking for the whitespace closest to N characters away from that index on each side, so you get whole words.\nPython string functions to find the exact ones you nee... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004319473_python.txt |
Q:
How to differentiate model classes between webapp and unittest
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.
I've written an abstract class to emulate a datastore model c... | How to differentiate model classes between webapp and unittest | I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.
I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, a... | [
"Instead of messing your models.py I would go with gaeunit.\nI've used it with success in a couple of projects and the features I like are:\n\nJust one file to add to your project (gaeunit.py) and you are almost done\nGaeunit isolates the test datastore from the development store (i.e. tests don't pollute your deve... | [
2,
2,
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004313280_google_app_engine_python.txt |
Q:
App Engine, How to check if all values in a list are in a string list in the datastore
If you have a string list in the datastore that has the values:
a,b,c
How can you compare it against a list so that it only returns true if every value in the string list is present in the list?
['a', 'b'] would return false
['a... | App Engine, How to check if all values in a list are in a string list in the datastore | If you have a string list in the datastore that has the values:
a,b,c
How can you compare it against a list so that it only returns true if every value in the string list is present in the list?
['a', 'b'] would return false
['a', 'b', 'c'] would return true
['a', 'b', 'c', 'd', 'e'] would return true
Is this possible ... | [
"From the documentation:\n\nA query cannot compare two list values. There is no way to test two lists for equality without testing each element for membership separately.\n\nSo I would guess that your comparison is also not possible directly.\nIt may be more efficient to use sets to compare, rather than looping ove... | [
2,
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004314059_google_app_engine_python.txt |
Q:
Remove the newline character in a list read from a file
I have a simple program that takes an ID number and prints information for the person matching the ID. The information is stored in a .dat file, with one ID number per line.
The problem is that my program is also reading the newline character \n from the file... | Remove the newline character in a list read from a file | I have a simple program that takes an ID number and prints information for the person matching the ID. The information is stored in a .dat file, with one ID number per line.
The problem is that my program is also reading the newline character \n from the file. I have tried the 'name'.split() method, but this doesn't se... | [
"str.strip() returns a string with leading+trailing whitespace removed, .lstrip and .rstrip for only leading and trailing respectively.\ngrades.append(lists[i].rstrip('\\n').split(','))\n\n",
"You can use the strip() function to remove trailing (and leading) whitespace; passing it an argument will let you specify... | [
106,
25,
7,
2,
0
] | [] | [] | [
"list",
"newline",
"python"
] | stackoverflow_0004319236_list_newline_python.txt |
Q:
How to use threads in python
I want to use it for reading values in 17770 files and to add all of them at the end to one dictionary object. I have a machine with 8 cores.
This is the code
def run_item_preprocess ():
scores = {};
for i in range(1,17771):
filename1 = "x_" + str(i) + ".txt";
l... | How to use threads in python | I want to use it for reading values in 17770 files and to add all of them at the end to one dictionary object. I have a machine with 8 cores.
This is the code
def run_item_preprocess ():
scores = {};
for i in range(1,17771):
filename1 = "x_" + str(i) + ".txt";
lines1 = open(filename1).readlines(... | [
"Here is the wonderful multiprocessing module. It lets you parallelise code, using processes not threads. This will use all cores.\nAn important difference is that processes don't share memory; a queue will help with the reduce step.\n",
"Here's some good parts of the python library reference to start with.\nhttp... | [
4,
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004319943_multithreading_python.txt |
Q:
How do I assign incremental names to elements of a list?
How do I assign incremental names in a list?
>>> ccList
['az <az@example.com>', 'cc777 <cc777@example.com>', 'user11 <user11@example.com>']
>>> for i in range(len(ccList)):
mailTuple = parseaddr(ccList[i])
cc = mailTuple[0]
print cc
az
cc777
use... | How do I assign incremental names to elements of a list? | How do I assign incremental names in a list?
>>> ccList
['az <az@example.com>', 'cc777 <cc777@example.com>', 'user11 <user11@example.com>']
>>> for i in range(len(ccList)):
mailTuple = parseaddr(ccList[i])
cc = mailTuple[0]
print cc
az
cc777
user11
>>>
>>> for i in range(3):
name = "name"+str(i)
p... | [
"If you really want to refer to the names as name0, name1, etc. I would suggest using a dictionary:\nnames = {}\nfor i in range(len(ccList)):\n mailTuple = parseaddr(ccList[i])\n cc = mailTuple[0]\n names[\"name\"+str(i)] = cc\n\nThen you can access name0 with names[\"name0\"], names[\"name1\"], etc. This is a m... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004320163_python.txt |
Q:
using BeautifulSoup to insert an element before closing body
What is the most efficient way to insert an element as last one in the body of an HTML page?
A:
See my answer to a previous question along the same lines:
Extract all <script> tags in an HTML page and append to the bottom of the document
The followin... | using BeautifulSoup to insert an element before closing body | What is the most efficient way to insert an element as last one in the body of an HTML page?
| [
"See my answer to a previous question along the same lines:\n\nExtract all <script> tags in an HTML page and append to the bottom of the document\n\nThe following should insert just fine:\nsoup.body.insert(len(soup.body.contents), yourelement)\n\n"
] | [
17
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004320300_beautifulsoup_python.txt |
Q:
how do I insert a cookie into a urllib2 openerdirector object?
Is there a way to append a cookie into an already made and used openerdirector object?
A:
Try this:
import urllib2
import cookielib
# load cookies from file
saved_cookies = cookielib.MozillaCookieJar('cookie_file_name')
saved_cookies.load()
opener ... | how do I insert a cookie into a urllib2 openerdirector object? | Is there a way to append a cookie into an already made and used openerdirector object?
| [
"Try this:\nimport urllib2\nimport cookielib\n\n# load cookies from file\nsaved_cookies = cookielib.MozillaCookieJar('cookie_file_name')\nsaved_cookies.load()\n\nopener = urllib2.build_opener() # your opener director\n\n# do something...\nopener.add_handler(urllib2.HTTPCookieProcessor(saved_cookies))\n\nEDIT: Accor... | [
0
] | [] | [] | [
"cookies",
"python",
"urllib2"
] | stackoverflow_0004320296_cookies_python_urllib2.txt |
Q:
String Matching with regular expressions
I am trying to write a regular expression in Python which takes a string and checks if:
The last character is a vowel.
The last 2 characters are not the same.
This is what I came up with:
[aeiou]$
Can anybody help me with point number 2: last 2 characters are not the sam... | String Matching with regular expressions | I am trying to write a regular expression in Python which takes a string and checks if:
The last character is a vowel.
The last 2 characters are not the same.
This is what I came up with:
[aeiou]$
Can anybody help me with point number 2: last 2 characters are not the same. For example, expresso is valid and expresso... | [
"It might be easier to do this without a regular expression.\ne.g if s[-2]!=s[-1] and s[-1] in 'aeiou'\n",
"(?i)([aeiouy])(?!\\1)[aeiouy]$\n\nEDIT:\nThis is also appealing for not having a repeat:\n(?i)(?=[aeiouy]{2}$)(.)(?!\\1).\n\n",
"Best I can do:\nr\"\\w*(?:[^a\\W]a|[^e\\W]e|[^i\\W]i|[^u\\W]u|[^o\\W]o)\\b\... | [
5,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004320379_python_regex.txt |
Q:
python mysqldb problem interfacing with python 2.6 & or mysql
I have MYSQL & MYSQLdb installed with Python 2.6 & Django 1.2.3. I can open & log on to mysql no problem but it's not interfacing with python when I check to see if it's working properly in the python interpreter. This is the error msg I am getting when... | python mysqldb problem interfacing with python 2.6 & or mysql | I have MYSQL & MYSQLdb installed with Python 2.6 & Django 1.2.3. I can open & log on to mysql no problem but it's not interfacing with python when I check to see if it's working properly in the python interpreter. This is the error msg I am getting when I invoke it in the interpreter....
import MySQLdb
Traceback (most... | [
"Python can not find the 'libmysqlclient_r.15.dylib' file. You might have mismatched versions of MySQL and MYSQLdb, or that file is not in a standard place. Try reinstalling MYSQLdb.\n",
"Looks like you are using a MacPorts Python installation on MacOS X. If you use MacPorts properly to upgrade, you should not r... | [
0,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0004320056_django_mysql_python.txt |
Q:
How to send zip file in http response in django?
Possible Duplicate:
Generating file to download with Django
I have a zip folder which has some file. I want to send those zip folder for some response in django. How can I do It?
A:
The others are right, this has been asked.
However, basically you should be able... | How to send zip file in http response in django? |
Possible Duplicate:
Generating file to download with Django
I have a zip folder which has some file. I want to send those zip folder for some response in django. How can I do It?
| [
"The others are right, this has been asked.\nHowever, basically you should be able to se\nYou can use the Python module 'zipfile' to generate the actual archive, but you mentioned you have the zipfile already?\nfrom django.http import HttpResponse\n...\n response = HttpResponse(wrapper, content_type='application... | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004312723_django_python.txt |
Q:
[Python]How to convert/record the output from subprocess into a file
I am using subprocess module, which Popen class output some results like:
063.245.209.093.00080-128.192.076.180.01039:HTTP/1.1 302 Found
063.245.209.093.00080-128.192.076.180.01040:HTTP/1.1 302 Found
and here is the script I wrote:
import subproc... | [Python]How to convert/record the output from subprocess into a file | I am using subprocess module, which Popen class output some results like:
063.245.209.093.00080-128.192.076.180.01039:HTTP/1.1 302 Found
063.245.209.093.00080-128.192.076.180.01040:HTTP/1.1 302 Found
and here is the script I wrote:
import subprocess, shlex, fileinput,filecmp
proc = subprocess.Popen('egrep \'^HTTP/\' *'... | [
"import subprocess\nimport glob\n\ndef egrep(pattern, *files):\n \"\"\" runs egrep on the files and returns the entire result as a string \"\"\"\n cmd = ['egrep', pattern]\n for filespec in files:\n cmd.extend(glob.glob(filespec))\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)\n return... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004320329_python.txt |
Q:
How do I write a decorator for my Django/Python view?
Here's my view. Basically, it returns different Responses based on whether it's logged in or not.
@check_login()
def home(request):
if is_logged_in(request):
return x
else:
return y
Here's my decorator code. I just want to check if the... | How do I write a decorator for my Django/Python view? | Here's my view. Basically, it returns different Responses based on whether it's logged in or not.
@check_login()
def home(request):
if is_logged_in(request):
return x
else:
return y
Here's my decorator code. I just want to check if the request has headers, and if so, log him in.
#decorator to ... | [
"Use only @check_login instead of check_login() - otherwise your decorator has to return a decorate as you are doing home = check_login()(home)\nHere's an example decorator:\ndef check_login(method):\n @functools.wraps(method)\n def wrapper(request, *args, **kwargs):\n if request.META['username'] == \"... | [
12,
4,
2
] | [] | [] | [
"decorator",
"django",
"http",
"python",
"request"
] | stackoverflow_0004320703_decorator_django_http_python_request.txt |
Q:
Vista User Access Controls with cx-freeze/python script
I'm trying to build a python script and freeze it with cx-freeze but with Vista User Access Control support.
As it stands my script runs fine under Server 2003/Win XP, however I need to be able to write files into the root of a drive which requires elevated p... | Vista User Access Controls with cx-freeze/python script | I'm trying to build a python script and freeze it with cx-freeze but with Vista User Access Control support.
As it stands my script runs fine under Server 2003/Win XP, however I need to be able to write files into the root of a drive which requires elevated privileges under UAC.
My compiled script is then executed by a... | [
"According to Python documentation UAC is automatically supported from version 2.6.\nSee http://docs.python.org/distutils/builtdist.html.\n"
] | [
1
] | [] | [] | [
"cx_freeze",
"python",
"python_3.x",
"uac",
"windows_vista"
] | stackoverflow_0003491064_cx_freeze_python_python_3.x_uac_windows_vista.txt |
Q:
How to order descending by a field in a different model in django models?
Here is an example how to order descending:
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
So we can use: '-pub_date'.
And another example how to order by a field in another model:
Entry.objects.order_by('blog__... | How to order descending by a field in a different model in django models? | Here is an example how to order descending:
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
So we can use: '-pub_date'.
And another example how to order by a field in another model:
Entry.objects.order_by('blog__name', 'headline')
So we can use: 'blog__name'.
How i can do both in one query... | [
"You want '-blog__name'.\n"
] | [
12
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004320881_django_django_models_python.txt |
Q:
google app engine python log level noise reduction
Does anyone know how to reduce the verbosity of logging output from dev_appserver.py?
The noise level of these logs is just driving me crazy. I know how to do this kind of config in Java with log4j, but am really lost here on google app engine python.
A:
Soluti... | google app engine python log level noise reduction | Does anyone know how to reduce the verbosity of logging output from dev_appserver.py?
The noise level of these logs is just driving me crazy. I know how to do this kind of config in Java with log4j, but am really lost here on google app engine python.
| [
"Solution 1.\nYou can instruct the logging library to only log statements at or above a given level with logging.setLevel(). If you set this level threshold higher than the level which contains the messages you don't want then you'll filter out the unwanted messages from dev_appserver.\nTo make your log messages s... | [
1
] | [] | [] | [
"google_app_engine",
"logging",
"noise_reduction",
"python"
] | stackoverflow_0004320882_google_app_engine_logging_noise_reduction_python.txt |
Q:
Can someone help me with my PIL function?
def pad_image(f, width=500, height=None):
if height==None:
height = width
image = Image.new("RGB", (800, 600), (0, 0, 0, 0))
image.paste(StringIO(f), (0,0, 50, 50))
res = StringIO()
image.save(res, 'JPEG')
res.seek(0)
return res
I am t... | Can someone help me with my PIL function? | def pad_image(f, width=500, height=None):
if height==None:
height = width
image = Image.new("RGB", (800, 600), (0, 0, 0, 0))
image.paste(StringIO(f), (0,0, 50, 50))
res = StringIO()
image.save(res, 'JPEG')
res.seek(0)
return res
I am trying to paste my image, f, in a 500x500 white ... | [
"the first argument to paste should be a Image not a StringIO so\nuse image.paste(Image.open(StringIO(f)), (0,0, 50, 50)) instead\nbut you should probably check the size of f before pasting it it will only paste the upper left corner if it's bigger than 50x50\n"
] | [
1
] | [] | [] | [
"debugging",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0004321024_debugging_image_python_python_imaging_library.txt |
Q:
How can I change what python interprets as a integer?
How can I change what python interprets as a integer? For example: 94*n would be a valid integer.
A:
Anything is possible when you smell like Old Spice and use Python's language services to generate a AST.
A:
On the off chance that you're not trying to modi... | How can I change what python interprets as a integer? | How can I change what python interprets as a integer? For example: 94*n would be a valid integer.
| [
"Anything is possible when you smell like Old Spice and use Python's language services to generate a AST.\n",
"On the off chance that you're not trying to modify Python's grammar, you could use int():\n>>> n = 1.2\n>>> x = 94*n\n>>> type(x)\n<type 'float'>\n>>> y = int(94*n) # use int()\n>>> type(y)\n<type 'int'>... | [
3,
2,
1
] | [] | [] | [
"integer",
"python"
] | stackoverflow_0004320534_integer_python.txt |
Q:
Why not python implicit line continuation on period?
Is there any reason Python does not allow implicit line continuations after (or before) periods? That is
data.where(lambda d: e.name == 'Obama').
count()
data.where(lambda d: e.name == 'Obama')
.count()
Does this conflict with some feature of Python? ... | Why not python implicit line continuation on period? | Is there any reason Python does not allow implicit line continuations after (or before) periods? That is
data.where(lambda d: e.name == 'Obama').
count()
data.where(lambda d: e.name == 'Obama')
.count()
Does this conflict with some feature of Python? With the rise of method chaining APIs this seems like a ... | [
"Both of those situations can lead to valid, complete constructs, so continuing on them would complicate the parser.\nprint 3.\n 1415926\n\nprint 'Hello, world'\n .lower()\n\n",
"Python allow line continuations within parentheticals (), so you might try:\n(data.where(lambda d: e.name == 'Obama').\n count())\... | [
6,
3,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004321122_python.txt |
Q:
How do I make PIL take into account the shortest side when creating a thumbnail?
Currently, for my function below...the image will be resized based on the longest side.
Basically the image has a larger height, the height will be 200px. The width will be just...whatever...
If the image has a larger width, the width... | How do I make PIL take into account the shortest side when creating a thumbnail? | Currently, for my function below...the image will be resized based on the longest side.
Basically the image has a larger height, the height will be 200px. The width will be just...whatever...
If the image has a larger width, the width will be 200px, and the height will adjust accordingly.
How do I flip this around!? ... | [
"Use resize instead of thumbnail.\nThe point behind thumbnail is to make it easy to scale an image down to fit within a particular bounding box preserving aspect ratio. That means that if your bounding box is a square, the longer side of the image determines the scale used.\nresize gives you more direct control -- ... | [
2,
0
] | [] | [] | [
"image",
"math",
"python",
"python_imaging_library",
"resize"
] | stackoverflow_0004321290_image_math_python_python_imaging_library_resize.txt |
Q:
Multi-language website - unique URLs required for different languages (to prevent caching)?
I have developed an AppEngine/Python/Django application that currently works in Spanish, and I am in the process of internationalizing with multi-language support. It is basically a dating website, in which people can brows... | Multi-language website - unique URLs required for different languages (to prevent caching)? | I have developed an AppEngine/Python/Django application that currently works in Spanish, and I am in the process of internationalizing with multi-language support. It is basically a dating website, in which people can browse other profiles and send messages. Viewing a profile in different languages will result in some ... | [
"In principle, you can use the Content-Language and Vary response headers and the Accept-Language request header to control how caches behave and to prevent them serving up the wrong language to users.\nIn practice, however, Accept-Language is frequently set incorrectly in browsers, which is why most sites don't re... | [
4,
3
] | [] | [] | [
"caching",
"django",
"google_app_engine",
"internationalization",
"python"
] | stackoverflow_0004321173_caching_django_google_app_engine_internationalization_python.txt |
Q:
What's the preferred way to implement a hook or callback in Python?
I'd like to provide the capability for users of one of my modules to extend its capabilities by providing an interface to call a user's function. For example, I want to give users the capability to be notified when an instance of a class is create... | What's the preferred way to implement a hook or callback in Python? | I'd like to provide the capability for users of one of my modules to extend its capabilities by providing an interface to call a user's function. For example, I want to give users the capability to be notified when an instance of a class is created and given the opportunity to modify the instance before it is used.
The... | [
"Taking aaronsterling's idea a bit further:\nclass C(object):\n _oncreate = []\n\n def __new__(cls):\n return reduce(lambda x, y: y(x), cls._oncreate, super(C, cls).__new__(cls))\n\n @classmethod\n def oncreate(cls, func):\n cls._oncreate.append(func)\n\nc = C()\nprint hasattr(c, 'spew')\n\n@C.oncreate\nd... | [
14,
12,
6
] | [] | [] | [
"callback",
"factory",
"hook",
"python"
] | stackoverflow_0004309607_callback_factory_hook_python.txt |
Q:
Python: Perform ations repeatedly over a time interval, as long as a condition is true
So I'm trying to do this (access a file on a website, read its contents and perform actions until the content says to exit. The precondition being it has to wait x seconds before accessing the website again; to recheck the conte... | Python: Perform ations repeatedly over a time interval, as long as a condition is true | So I'm trying to do this (access a file on a website, read its contents and perform actions until the content says to exit. The precondition being it has to wait x seconds before accessing the website again; to recheck the contents):
perform = True
while(perform):
data = urllib.urlopen('someurl')
data = data.read()
... | [
"this:\nimport time\nwhile True:\n print \"fetching\"\n time.sleep(10)\n\nis the minimal test case and as this always works it can't be a problem with the time.sleep function\n",
"1) Have you tried actually checking what data you get back from reading the URL? Like, printing it out or something?\n2) If the ... | [
3,
1
] | [] | [] | [
"python",
"sleep",
"while_loop"
] | stackoverflow_0004321859_python_sleep_while_loop.txt |
Q:
Python - Find longest (most words) key in dictionary
Is there a way to quickly query a dictionary object in order to find the key (all keys are of string type) with the most words?
I.e., if the item with the largest key had five words {'this is the largest key': 3}, how could I quickly query the dict and have the ... | Python - Find longest (most words) key in dictionary | Is there a way to quickly query a dictionary object in order to find the key (all keys are of string type) with the most words?
I.e., if the item with the largest key had five words {'this is the largest key': 3}, how could I quickly query the dict and have the int '5' returned?
Best,
Georgina
| [
"This will give you the key:\nmax(d, key=lambda x: len(x.split()))\n\nAnd if you want the size:\nmax(len(x.split()) for x in d)\n\n",
"max of - count of words per key:\nmax(len(k.split()) for k in d.keys())\n\n",
"longest=max(d.keys(), key=lambda s:len(s.split()))\nlen(longest.split())\n\n",
"max(len(i.split(... | [
3,
1,
1,
0,
0,
0
] | [
"No shortcut. Simple way:\nimport re\nmax([len(re.split('\\s+', k)) for k in d.keys()])\n\n"
] | [
-1
] | [
"dictionary",
"key",
"python"
] | stackoverflow_0004321160_dictionary_key_python.txt |
Q:
Concurent Access to datastore in app engine
i want to know if db.run_in_transaction() acts as a lock for Data store operations
and helps in case of concurrent access on same entity.
Does in following code it is guarantied that a concurrent access will not cause a race and instead of creating new entity it will not... | Concurent Access to datastore in app engine | i want to know if db.run_in_transaction() acts as a lock for Data store operations
and helps in case of concurrent access on same entity.
Does in following code it is guarantied that a concurrent access will not cause a race and instead of creating new entity it will not do a over-write
Is db.run_in_transaction() corr... | [
"That is a safe method. Should the same name get generated twice, only one entity would be created.\nIt sounds like you have already looked at the transactions documentation. There is also a more detailed description.\nCheck out the docs (specifically the equivalent code) on Model.get_or_insert, it answers exactl... | [
4,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"transactions"
] | stackoverflow_0004321876_google_app_engine_google_cloud_datastore_python_transactions.txt |
Q:
What's the best way to process HTML in Python?
I'm trying to write some tests with Lettuce, started using lxml but found kinda complicated to integrate it with Django in the same way that Webrat integrates with Rails.
A:
I use beautiful soup with django and no problems.
http://www.crummy.com/software/BeautifulSo... | What's the best way to process HTML in Python? | I'm trying to write some tests with Lettuce, started using lxml but found kinda complicated to integrate it with Django in the same way that Webrat integrates with Rails.
| [
"I use beautiful soup with django and no problems.\nhttp://www.crummy.com/software/BeautifulSoup/\n",
"Not sure what your problem with lxml being complicated is (parsing html will be complicated!) but I've always used Beautiful Soup for handling html, finding elements, constructing trees etc etc.\n"
] | [
3,
2
] | [] | [] | [
"bdd",
"html",
"lettuce",
"python"
] | stackoverflow_0004233554_bdd_html_lettuce_python.txt |
Q:
python executable
is it possible to create python executable targeted for linux, from mac os x?
PyInstaller seems to be at an early stage, and I don't know much else.
Thanks
A:
Do you really need a standalone executable? For most Linux distributions, the easier and more common way to distribute Python software i... | python executable | is it possible to create python executable targeted for linux, from mac os x?
PyInstaller seems to be at an early stage, and I don't know much else.
Thanks
| [
"Do you really need a standalone executable? For most Linux distributions, the easier and more common way to distribute Python software is to just distribute the source.\nEvery major Linux distribution already has Python installed, and some have it installed by default.\n",
"Dont know if available for OS X but ... | [
5,
0,
0
] | [] | [] | [
"executable",
"linux",
"macos",
"python"
] | stackoverflow_0004322250_executable_linux_macos_python.txt |
Q:
How to make this naive python implement of Quicksort more pythonic?
I'm 2 hours into my reading of diveintopython and I implemented a naive version of quicksort.
import operator
def even(num):
return operator.mod(num,2) == 0
def last(list):
return len(list)-1
def median(list):
if even(len(list)):
... | How to make this naive python implement of Quicksort more pythonic? | I'm 2 hours into my reading of diveintopython and I implemented a naive version of quicksort.
import operator
def even(num):
return operator.mod(num,2) == 0
def last(list):
return len(list)-1
def median(list):
if even(len(list)):
return len(list)/2 - 1
else:
return len(list)/2
def s... | [
"\n1 - This code resides in a file called quicksort.py. How does one hide the method even from being exported to the public.\n\nThe convention is to name functions private to your module with an underscore at the beginning.\n\n2 - Is it pythonic to pass in a *pivot_selector* as a parameter ?\n\nSince Python has fir... | [
5,
4,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"quicksort"
] | stackoverflow_0004322823_python_quicksort.txt |
Q:
In Django's template system, how do I make it to do different things sometimes?
{% for p in posts %}
<div style="width:50px;">
blah
</div>
{% endfor %}
However, what if I want the div to be 100px 75% of the time? 25% of the time? Randomized.
A:
random filter should do the thing
A:
Logic does not g... | In Django's template system, how do I make it to do different things sometimes? | {% for p in posts %}
<div style="width:50px;">
blah
</div>
{% endfor %}
However, what if I want the div to be 100px 75% of the time? 25% of the time? Randomized.
| [
"random filter should do the thing\n",
"Logic does not go into templates.\nSolution: write a new template tag that returns a random number, and use that for the width.\nhttp://docs.djangoproject.com/en/1.2/howto/custom-template-tags/\nYour template would then look like:\n{% for p in posts %}\n <div style=\"wid... | [
2,
2,
0
] | [] | [] | [
"css",
"django",
"html",
"python",
"templates"
] | stackoverflow_0004322966_css_django_html_python_templates.txt |
Q:
How to program to have all processors on your machine used?
I am running a single-threaded python program that performs massive data processing on my windows box. My machine has 8 processors. When I monitor the CPU usage in performance tab under Windows Task Manager, it shows that I am using only a very small frac... | How to program to have all processors on your machine used? | I am running a single-threaded python program that performs massive data processing on my windows box. My machine has 8 processors. When I monitor the CPU usage in performance tab under Windows Task Manager, it shows that I am using only a very small fraction of the processing power available to me. Only one processor ... | [
"multithreading cannot make use of extra processors or cores.\nYou should spawn new processes instead of new threads.\nThis tool is by far the simplest among all that I have come across:\nparallel python\n\nOverview: \nPP is a python module which provides mechanism for parallel\n execution of python code on SMP\n ... | [
6,
2,
2,
2,
1,
1
] | [] | [] | [
"processor",
"python",
"windows"
] | stackoverflow_0004321993_processor_python_windows.txt |
Q:
Loop with conditions in python
Consider the following code in C:
for(int i=0; i<10 && some_condition; ++i){
do_something();
}
I would like to write something similar in Python. The best version I can think of is:
i = 0
while some_condition and i<10:
do_something()
i+=1
Frankly, I don't like while loo... | Loop with conditions in python | Consider the following code in C:
for(int i=0; i<10 && some_condition; ++i){
do_something();
}
I would like to write something similar in Python. The best version I can think of is:
i = 0
while some_condition and i<10:
do_something()
i+=1
Frankly, I don't like while loops that imitate for loops. This is d... | [
"This might not be related, but there's what I'm used to do... If some_condition is simple enough, put it in a function and filter items you iterate over:\ndef some_condition(element):\n return True#False\n\nfor i in filter(some_condition, xrange(10)):\n pass\n\nYou can use this approach also when you iterate... | [
10,
8,
4
] | [] | [] | [
"coding_style",
"idioms",
"python"
] | stackoverflow_0004323946_coding_style_idioms_python.txt |
Q:
__init__.py seemingly not working
New to Python. I'm on Windows and Python2.7.
I have confirmed that my directory is setup in PYTHONPATH by looking in sys.path from IDLE.
import sys
print(sys.path)
This shows me that c:\users\owner\documents\PythonProjects is definitely in the path. Furthermore in that director... | __init__.py seemingly not working | New to Python. I'm on Windows and Python2.7.
I have confirmed that my directory is setup in PYTHONPATH by looking in sys.path from IDLE.
import sys
print(sys.path)
This shows me that c:\users\owner\documents\PythonProjects is definitely in the path. Furthermore in that directory I have a .py file which can be import... | [
"Because it should be in testPackage\\.\n",
"There must be an __init__.py file in every directory, so if your structure is:\nprojects/\n TestProject/\n __init__.py\n test.py\n\nAnd the path to projects is on your PYTHONPATH, then you should be able to import the test module.\n"
] | [
2,
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0004324159_package_python.txt |
Q:
Meaning of curly brackets and colons?
Homework question:
Write a function which is called like: replace_all({'a':'123', 'b':'Zab'}, 'acb')
What does the function declaration look like?
What kind of variable is 'a':'123' and {}?
A:
It's a dictionary (mapping).
See http://docs.python.org/library/stdtypes.html#dict... | Meaning of curly brackets and colons? | Homework question:
Write a function which is called like: replace_all({'a':'123', 'b':'Zab'}, 'acb')
What does the function declaration look like?
What kind of variable is 'a':'123' and {}?
| [
"It's a dictionary (mapping).\nSee http://docs.python.org/library/stdtypes.html#dict.\nGenerally, when you define function in python, you don't need types. Python is dynamically typed language.\n",
"{} is the empty dictionary, {'a':'123'} is a dictionary with a key 'a' that has the associated value '123'\nthe fun... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004321836_python.txt |
Q:
Python text validation: a-z and comma (",")
I need to check that some text only contains lower-case letters a-z and a comma (",").
What is the best way to do this in Python?
A:
import re
def matches(s):
return re.match("^[a-z,]*$", s) is not None
Which gives you:
>>> matches("tea and cakes")
False
>>> match... | Python text validation: a-z and comma (",") | I need to check that some text only contains lower-case letters a-z and a comma (",").
What is the best way to do this in Python?
| [
"import re\ndef matches(s):\n return re.match(\"^[a-z,]*$\", s) is not None\n\nWhich gives you:\n>>> matches(\"tea and cakes\")\nFalse\n>>> matches(\"twiddledee,twiddledum\")\nTrue\n\nYou can optimise a bit with re.compile:\nimport re\nmatcher = re.compile(\"^[a-z,]*$\")\ndef matches(s):\n return matcher.matc... | [
16,
14,
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"validation"
] | stackoverflow_0003767210_python_regex_validation.txt |
Q:
Python: NameError for no apparent reason?
from random import random
def computer():
computer = 0
while computer < 21:
val = int(random()*10)+1
if (computer + val) > 21:
break
else:
computer += val
print "Ich habe ", computer, "!"
return computer
def player():
player = 0
loss = 0
while pl... | Python: NameError for no apparent reason? | from random import random
def computer():
computer = 0
while computer < 21:
val = int(random()*10)+1
if (computer + val) > 21:
break
else:
computer += val
print "Ich habe ", computer, "!"
return computer
def player():
player = 0
loss = 0
while player < 21:
hval = int(random()... | [
"Let's clean that mess up and see what all the errors are:\nfrom random import random # tip, check out randint (the function in the random module)\n\ndef computer():\n computer = 0\n while computer < 21:\n val = int(random()*10)+1 # please use some whitespace around operators\n\n if (computer + ... | [
3,
1,
0,
0
] | [] | [] | [
"nameerror",
"python"
] | stackoverflow_0004324434_nameerror_python.txt |
Q:
python's trackback error - using pymssql
am trying to execute the below code using python 2.5.2. The script is establishing the connection and creating the table, but then its failing with the below error.
The script
import pymssql
conn = pymssql.connect(host='10.103.8.75', user='mo', password='the_password', data... | python's trackback error - using pymssql | am trying to execute the below code using python 2.5.2. The script is establishing the connection and creating the table, but then its failing with the below error.
The script
import pymssql
conn = pymssql.connect(host='10.103.8.75', user='mo', password='the_password', database='SR_WF_MODEL')
cur = conn.cursor()
cur.ex... | [
"I think you are assuming the regular python string interpolation behavior, ie:\n>>> a = \"we should never do '%s' when working with dbs\"\n>>> a % 'this'\n\"we should never do 'this' when working with dbs\"\n\nThe % operator within the execute method looks like the normal string formatting operator but that is mor... | [
1
] | [] | [] | [
"pymssql",
"python"
] | stackoverflow_0004324049_pymssql_python.txt |
Q:
webbrowser modules only opens url in mozilla?
import webbrowser
webbrowser.open(url)
I am using this to open url in browser. But it opens only in 'Mozilla' why?
A:
Just look at the docs. It uses the default browser. Look at webbrowser.get() for instructions on using a different browser.
| webbrowser modules only opens url in mozilla? | import webbrowser
webbrowser.open(url)
I am using this to open url in browser. But it opens only in 'Mozilla' why?
| [
"Just look at the docs. It uses the default browser. Look at webbrowser.get() for instructions on using a different browser.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004324922_python.txt |
Q:
Is there any library popular in Python to monitor Linux/Unix system?
In erlang, thare is a os_mon module responsible for monitoring system, but I haven't found the library like that for python,is there any?
thank you very much!
A:
Two ways of doing this:
Use subprocess to call another process that can get this ... | Is there any library popular in Python to monitor Linux/Unix system? | In erlang, thare is a os_mon module responsible for monitoring system, but I haven't found the library like that for python,is there any?
thank you very much!
| [
"Two ways of doing this:\n\nUse subprocess to call another process that can get this information for you. \nUse PyMeter. Does what you want easily. \n\n",
"Like Sukhbir suggested earlier, you can look beyond python by using subprocess to invoke another tool that can do this for you. Look at Dstat. It returns a ve... | [
2,
1
] | [] | [] | [
"linux",
"monitor",
"monitoring",
"python"
] | stackoverflow_0004324236_linux_monitor_monitoring_python.txt |
Q:
How do I get the username in Python?
Possible Duplicate:
Is there a portable way to get the current username in Python?
How can I get the username of the account by which the given script is being executed?
A:
import getpass
print getpass.getuser()
| How do I get the username in Python? |
Possible Duplicate:
Is there a portable way to get the current username in Python?
How can I get the username of the account by which the given script is being executed?
| [
"import getpass\nprint getpass.getuser()\n\n"
] | [
78
] | [] | [] | [
"python"
] | stackoverflow_0004325416_python.txt |
Q:
Error after creating exe with Py2exe
Py2exe seems to run fine although it does mention that a few modules maybe missing.
I had been using the windows option (in my py2exe script) to remove the console window but realized that the process still remained open even after I closed down the gui window i.e. I could sti... | Error after creating exe with Py2exe | Py2exe seems to run fine although it does mention that a few modules maybe missing.
I had been using the windows option (in my py2exe script) to remove the console window but realized that the process still remained open even after I closed down the gui window i.e. I could still see the process still in task manager..... | [
"I've had very little trouble getting wxPython code to compile to an exe using py2exe. I have a tutorial that you can try here:\nhttp://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/\nI have had some issues with the new version of pubsub that is included with 2.8.11.0. You can read t... | [
2
] | [] | [] | [
"py2exe",
"python",
"wxpython"
] | stackoverflow_0004321893_py2exe_python_wxpython.txt |
Q:
Python: Delete a character from a string
I want to delete i.e. character number 5 in a string. So I did:
del line[5]
and got:
TypeError: 'str' object doesn't support item deletion
So no I wonder whether there is a different efficient solution to the problem.
A:
Strings are immutable in Python, so you can't chang... | Python: Delete a character from a string | I want to delete i.e. character number 5 in a string. So I did:
del line[5]
and got:
TypeError: 'str' object doesn't support item deletion
So no I wonder whether there is a different efficient solution to the problem.
| [
"Strings are immutable in Python, so you can't change them in-place.\nBut of course you can assign a combination of string slices back to the same identifier:\nmystr = mystr[:5] + mystr[6:]\n\n",
"I use a function similar to :\ndef delstring(mystring, indexes):\n return ''.join([let for ind, let in enumerate(mys... | [
7,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004324700_python_string.txt |
Q:
serving mp3 files from cherrypy
I am using cherrypy as a server. This server gives you ability to download .mp3 files. I am using the following code to make the .mp3 files downloadable. The problem is that the mp3 file that I get after downloading it is a data file which should actually be an mp3 file.
import glob... | serving mp3 files from cherrypy | I am using cherrypy as a server. This server gives you ability to download .mp3 files. I am using the following code to make the .mp3 files downloadable. The problem is that the mp3 file that I get after downloading it is a data file which should actually be an mp3 file.
import glob
import os.path
import cherrypy
from ... | [
"Try setting up the directory that contains the mp3 files as a static directory. Your cherrypy conf should contain something like this:\n '/directory_with_mp3s': {\n 'tools.staticdir.on': True, \n 'tools.staticdir.dir': 'directory_with_mp3s'\n}\n\nThis will allow you to get rid of the Download cla... | [
3
] | [] | [] | [
"cherrypy",
"mp3",
"python"
] | stackoverflow_0004283890_cherrypy_mp3_python.txt |
Q:
using list with python multiprocessing
can anyone help me out with sharing a list between multiple python processes. The problem is to get self.ID_List and self.mps_in_process working in the following code.
import time, random
from multiprocessing import Process #, Manager, Array, Queue
class MP_Stuff():
def ... | using list with python multiprocessing | can anyone help me out with sharing a list between multiple python processes. The problem is to get self.ID_List and self.mps_in_process working in the following code.
import time, random
from multiprocessing import Process #, Manager, Array, Queue
class MP_Stuff():
def __init__(self, parent, id):
time.sle... | [
"The Manager is working fine (including len()). The issue with your code is that in your main process, you don't wait until the processing ends, so the main process ends and the manager is no longer accessible. Also I don't know about atomicity of ListProxy's pop, so maybe a lock would be handy.\nThe solution is p.... | [
3,
0
] | [] | [] | [
"list",
"multiprocessing",
"python"
] | stackoverflow_0004325372_list_multiprocessing_python.txt |
Q:
Solve this equation with fixed point iteration
How can I solve this equation
x3 + x - 1 = 0
using fixed point iteration?
Is there any fixed-point iteration code (especially in Python) I can find online?
A:
Using scipy.optimize.fixed_point:
import scipy.optimize as optimize
def func(x):
return -x**3+1
# ... | Solve this equation with fixed point iteration | How can I solve this equation
x3 + x - 1 = 0
using fixed point iteration?
Is there any fixed-point iteration code (especially in Python) I can find online?
| [
"Using scipy.optimize.fixed_point:\nimport scipy.optimize as optimize\n\ndef func(x):\n return -x**3+1\n\n# This finds the value of x such that func(x) = x, that is, where\n# -x**3 + 1 = x\nprint(optimize.fixed_point(func,0))\n# 0.682327803828\n\nThe Python code defining fixed_point is in scipy/optimize/minpack.... | [
12,
2
] | [] | [] | [
"equation",
"fixed_point_iteration",
"nonlinear_functions",
"numerical_analysis",
"python"
] | stackoverflow_0004326419_equation_fixed_point_iteration_nonlinear_functions_numerical_analysis_python.txt |
Q:
Integrating activeCollab with my Django project
I have tried looking all over the net for some help, and couldn't find anything. I'm posting here because I am out of all other ideas. I want to integrate activeCollab with my django project but I am having trouble finding tutorials or instructions on how to use th... | Integrating activeCollab with my Django project | I have tried looking all over the net for some help, and couldn't find anything. I'm posting here because I am out of all other ideas. I want to integrate activeCollab with my django project but I am having trouble finding tutorials or instructions on how to use their API with django. All of the aC documentation is ... | [
"Does \"all over the net\" include the activeCollab marketplace forum? Try \"I will pay $300 for someone to convert the PHP API wrapper to Python\" or something more specific describing exactly what you want to accomplish through Django.\nIf you haven't already purchased an activeCollab license, you might look at T... | [
0,
0
] | [] | [] | [
"api",
"django",
"python"
] | stackoverflow_0004126767_api_django_python.txt |
Q:
Most efficient way to open a file and read the lines?
I've got this:
vlgaStream = open('vlgaChcWaves.txt', 'r+')
vlgaBuffer = vlgaStream.readlines()
vlgaStream.close()
But need a way to directly and efficiently read all of the lines from a file into a buffer?
A:
Iterating over a file yields lines.
with open('vl... | Most efficient way to open a file and read the lines? | I've got this:
vlgaStream = open('vlgaChcWaves.txt', 'r+')
vlgaBuffer = vlgaStream.readlines()
vlgaStream.close()
But need a way to directly and efficiently read all of the lines from a file into a buffer?
| [
"Iterating over a file yields lines.\nwith open('vlgaChcWaves.txt', 'r+') as vlgaStream:\n for line in vlgaStream:\n dosomethingwith(line)\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004326641_python.txt |
Q:
How do I parse a text file in dictionary form and put it into a dictionary in python?
I want to take a text file that contains something of the form:
{('q0','a'):('q0','a','R'),
('q0','b'):('q0','a','R'),
('q1',' '):('q1',' ','L')}
and place it into a real dictionary.
I've been hacking away at this for hours and ... | How do I parse a text file in dictionary form and put it into a dictionary in python? | I want to take a text file that contains something of the form:
{('q0','a'):('q0','a','R'),
('q0','b'):('q0','a','R'),
('q1',' '):('q1',' ','L')}
and place it into a real dictionary.
I've been hacking away at this for hours and have gotten very far.
I think the solution is simple but I have found nothing useful on the... | [
">>> ast.literal_eval('''{('q0','a'):('q0','a','R'),\n... ('q0','b'):('q0','a','R'),\n... ('q1',' '):('q1',' ','L')}\n... ''')\n{('q1', ' '): ('q1', ' ', 'L'), ('q0', 'a'): ('q0', 'a', 'R'), ('q0', 'b'):\n ('q0', 'a', 'R')}\n\n",
"If the file contains valid Python code describing a dictionary, just use eval:\n>>... | [
3,
0,
0,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0004326492_parsing_python.txt |
Q:
GAE verify appspotmail.com forwarding
I am trying to setup email forwarding from my-domain.com to myappid.appspot.com. When I sign in to the email account and enter the email for forwarding messages, it says that a confirmation message with a code had been sent there. How can I access that code?
A:
I created thi... | GAE verify appspotmail.com forwarding | I am trying to setup email forwarding from my-domain.com to myappid.appspot.com. When I sign in to the email account and enter the email for forwarding messages, it says that a confirmation message with a code had been sent there. How can I access that code?
| [
"I created this and made it forward a confirmation message to my email. From there I got the link, clicked it and it worked just perfectly!\nclass LogSenderHandler(InboundMailHandler):\n def receive(self, mail_message):\n logging.info(\"Received a message from: \" + mail_message.sender)\n sender_ad... | [
2
] | [] | [] | [
"email",
"forwarding",
"gmail",
"google_app_engine",
"python"
] | stackoverflow_0004326790_email_forwarding_gmail_google_app_engine_python.txt |
Q:
Twisted + Gtk - shutdown not working properly
Using Python 2.6, Twisted 10.1, and GTK+ 2.22, with latest pygtk installed, I'm having problems on shutdown. When I close my application and shut down the reactor (using the gtk2reactor of course), the application simply freezes.
I've poked around the twisted source a... | Twisted + Gtk - shutdown not working properly | Using Python 2.6, Twisted 10.1, and GTK+ 2.22, with latest pygtk installed, I'm having problems on shutdown. When I close my application and shut down the reactor (using the gtk2reactor of course), the application simply freezes.
I've poked around the twisted source and added debug messages. What ends up happening is,... | [
"As from this question it seems to come from importing the win32ui module. But I think the underlying problem is deeper..\nEDIT: Seems to be a problem with my particular install of Windows 7 and whatever else is here.\n",
"Threads, perhaps? The Twisted reactor joins all threads on shutdown, and if you're doing s... | [
1,
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"twisted"
] | stackoverflow_0004308346_gtk_pygtk_python_twisted.txt |
Q:
python count down to event (in days and hours)
Please can someone advise on this, I've tried various methods but don't seem to be able to get it to work.
I just need a countdown from
datetime.now()
to
datetime(2011,05,05)
in days hours
A:
You can use
delta = datetime.datetime(2011, 5, 5) - datetime.datetime.n... | python count down to event (in days and hours) | Please can someone advise on this, I've tried various methods but don't seem to be able to get it to work.
I just need a countdown from
datetime.now()
to
datetime(2011,05,05)
in days hours
| [
"You can use\ndelta = datetime.datetime(2011, 5, 5) - datetime.datetime.now()\n\nto get a datetime.timedelta object describing the remaining time. The number of remaining days is delta.days, the remaining hours delta.seconds/3600. or delta.seconds//3600.\n",
"You could try this - \nimport datetime\n\ndt = datet... | [
12,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004327021_datetime_python.txt |
Q:
'To' field when parsing email in Python
I'm using the python standard library's email module to parse email. Something like this allows me to determine sender:
msg = email.message_from_string(data)
sender = msg.get_unixfrom()
But I'm having trouble determining who the mail is for.
Thoughts?
A:
You can access a... | 'To' field when parsing email in Python | I'm using the python standard library's email module to parse email. Something like this allows me to determine sender:
msg = email.message_from_string(data)
sender = msg.get_unixfrom()
But I'm having trouble determining who the mail is for.
Thoughts?
| [
"You can access all headers of the message by index, e.g. msg[\"From\"]. In the case of the recipient, use msg.get_all(\"To\") because there might be multiple values.\nAlso note the following:\n\nHeaders are stored and returned in case-preserving form but are matched case-insensitively.\n\n",
"Example interactive... | [
6,
1,
0,
0
] | [] | [] | [
"email",
"parsing",
"python"
] | stackoverflow_0004327430_email_parsing_python.txt |
Q:
measuring WLAN using python for S60
I'm using python for S60. is there a module that enable you to measure WLAN intensity in your area?
In the end I want to get a list with all the networks available in the point and their intensity.
thanks
A:
Yes, there is: http://chris.berger.cx/PyS60/PyS60
| measuring WLAN using python for S60 | I'm using python for S60. is there a module that enable you to measure WLAN intensity in your area?
In the end I want to get a list with all the networks available in the point and their intensity.
thanks
| [
"Yes, there is: http://chris.berger.cx/PyS60/PyS60\n"
] | [
0
] | [] | [] | [
"pys60",
"python",
"wifi"
] | stackoverflow_0003377338_pys60_python_wifi.txt |
Q:
How can I speed-up the build/install of lxml?
We use Hudson-CI for out Continuous Integration server for Python projects, all of which use Buildout to manage dependencies. Almost all our projects use lxml which, because of Buildout, must be built/installed during each test-run and because it takes so long it reduc... | How can I speed-up the build/install of lxml? | We use Hudson-CI for out Continuous Integration server for Python projects, all of which use Buildout to manage dependencies. Almost all our projects use lxml which, because of Buildout, must be built/installed during each test-run and because it takes so long it reduces the number of builds we can run per day.
Is ther... | [
"My solution is to create an egg myself and keep that egg version-controlled with my buildout. I recreate the egg each time I need to upgrade lxml. You can almost always create a binary egg of any Python project by throwing an import setuptools into the top of its setup.py and then saying python setup.py bdist_egg... | [
1
] | [
"You can create a buildout defaults file and define an eggs-directory to share eggs between multiple builds.\nThis post sums it up nicely: http://plone.org/documentation/manual/developer-manual/managing-projects-with-buildout/creating-a-buildout-defaults-file\n"
] | [
-1
] | [
"compilation",
"lxml",
"python"
] | stackoverflow_0004313782_compilation_lxml_python.txt |
Q:
Create default values for dictionary in python
Let's have a method that would cache results it calculates.
"If" approach:
def calculate1(input_values):
if input_values not in calculate1.cache.keys():
# do some calculation
result = input_values
calculate1.cache[input_values] = result
... | Create default values for dictionary in python | Let's have a method that would cache results it calculates.
"If" approach:
def calculate1(input_values):
if input_values not in calculate1.cache.keys():
# do some calculation
result = input_values
calculate1.cache[input_values] = result
return calculate1.cache[input_values]
calculate1.ca... | [
"Use a collections.defaultdict. It's designed precisely for this purpose.\n",
"Of course; this is Python after all: Just use a defaultdict.\n",
"Well if you are trying to memoize something, its best to use a Memoize class and decorators.\nclass Memoize(object):\n def __init__(self, func):\n self.func ... | [
25,
5,
3
] | [] | [] | [
"coding_style",
"performance",
"python"
] | stackoverflow_0004326119_coding_style_performance_python.txt |
Q:
Can I count on order being preserved in a Python tuple?
I've got a list of datetimes from which I want to construct time segments. In other words, turn [t0, t1, ... tn] into [(t0,t1),(t1,t2),...,(tn-1, tn)]. I've done it this way:
# start by sorting list of datetimes
mdtimes.sort()
# construct tuples which repre... | Can I count on order being preserved in a Python tuple? | I've got a list of datetimes from which I want to construct time segments. In other words, turn [t0, t1, ... tn] into [(t0,t1),(t1,t2),...,(tn-1, tn)]. I've done it this way:
# start by sorting list of datetimes
mdtimes.sort()
# construct tuples which represent possible start and end dates
# left edges
dtg0 = [x for... | [
"Both list and tuple are ordered.\ndtg0, dtg1 = itertools.tee(mdtimes)\nnext(dtg0)\ndtsegs = zip(dtg0, dtg1)\n\n",
"\nTuple order is as you insert values into the tuple. They're not going to be sorted as I think you're asking. zip will again, retain the order you inserted the values in.\nIt's an acceptable method... | [
22,
21,
6,
4,
3,
3,
1
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0004326553_list_python_tuples.txt |
Q:
How to merge notifications with a common title in pynotify?
How can I tell a pynotify.Notification object to merge with another that has the same title?
A:
(Per discussion:)
Setting the append hint on your notifications (set_hint_string('append', '')) tells the notification daemon that it should merge notificati... | How to merge notifications with a common title in pynotify? | How can I tell a pynotify.Notification object to merge with another that has the same title?
| [
"(Per discussion:)\nSetting the append hint on your notifications (set_hint_string('append', '')) tells the notification daemon that it should merge notifications from your app when they have the same titles.\n"
] | [
4
] | [] | [] | [
"notifications",
"pynotify",
"python"
] | stackoverflow_0004319040_notifications_pynotify_python.txt |
Q:
How to retrieve these elements from a webpage?
I have a webpage in HTML with these elements:
<div class="content_page">
<a href="/earth" class="nametessera" >earth</a>
</div>
<div class="content_page">
<a href="/world" class="nametessera" >world</a>
</div>
<div class="content_page">
<a href="/planet" c... | How to retrieve these elements from a webpage? | I have a webpage in HTML with these elements:
<div class="content_page">
<a href="/earth" class="nametessera" >earth</a>
</div>
<div class="content_page">
<a href="/world" class="nametessera" >world</a>
</div>
<div class="content_page">
<a href="/planet" class="nametessera">planet</a>
</div>
...
I need to ... | [
"Short answer: \nUse beautifulSoup to parse the page, get the urls and then use urlib2 or pycurl to download the mentioned urls.\n[Edit:]\nAdding on to the examples below but to only use the the href contained in the div\n>>> alldiv = soup.findAll('div', { \"class\" : \"content_page\" })\n>>> for div in alldiv: pri... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0004328167_python.txt |
Q:
Creating sets of default values for Matplotlib
I am frequently making plots for my own research and all of the default settings are fine, but often have to switch over to making plots designed for talks/presentations; I manually set all of the font sizes a bit bigger for easier reading:
plot(xdata, ydata)
xlabel("... | Creating sets of default values for Matplotlib | I am frequently making plots for my own research and all of the default settings are fine, but often have to switch over to making plots designed for talks/presentations; I manually set all of the font sizes a bit bigger for easier reading:
plot(xdata, ydata)
xlabel("x-axis data", fontsize=20)
ax = gca()
for labeltick ... | [
"Try this:\nimport matplotlib as mpl \nmpl.rc('figure.subplot', left=.2, right=.8, bottom=.2, top=.8)\n\nAnd there should be a \"site-packages/matplotlib/mpl-data/matplotlibrc\" file, described in doc 5.1.\nUse mpl.matplotlib_fname() to get your rc file path, and modify it so the setting will be permanent.\n",
... | [
4,
4
] | [] | [] | [
"default",
"matplotlib",
"presentation",
"python"
] | stackoverflow_0004301140_default_matplotlib_presentation_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.