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:
Commiting data from Tweepy to a sqlite3 database, no matter what I do, db remains empty
Code:
import time
import tweepy
import sqlite3
class Listener(tweepy.StreamListener):
conn = sqlite3.connect('/home/daniel/Desktop/activeSites/djeep/djeep.db')
def on_status(self, status):
try:
c ... | Commiting data from Tweepy to a sqlite3 database, no matter what I do, db remains empty | Code:
import time
import tweepy
import sqlite3
class Listener(tweepy.StreamListener):
conn = sqlite3.connect('/home/daniel/Desktop/activeSites/djeep/djeep.db')
def on_status(self, status):
try:
c = self.conn.cursor()
c.execute("""insert into feed_post values (%r,'%s','%s',%d)"... | [
"The path to the database should be an argument to your script, not hardcoded. It should be supplied to your class each time the class is instantiated, NOT when your class is created. However it's not apparent that that is the cause of your problem, not yet exactly what the problem is:\nYour title indicates that yo... | [
2,
0
] | [] | [] | [
"python",
"sqlite",
"tweepy"
] | stackoverflow_0008408228_python_sqlite_tweepy.txt |
Q:
Complex foreign key constraint in SQLAlchemy
I have two tables, SystemVariables and VariableOptions. SystemVariables should be self-explanatory, and VariableOptions contains all of the possible choices for all of the variables.
VariableOptions has a foreign key, variable_id, which states which variable it is an op... | Complex foreign key constraint in SQLAlchemy | I have two tables, SystemVariables and VariableOptions. SystemVariables should be self-explanatory, and VariableOptions contains all of the possible choices for all of the variables.
VariableOptions has a foreign key, variable_id, which states which variable it is an option for. SystemVariables has a foreign key, choic... | [
"You can implement that without dirty tricks. Just extend the foreign key referencing the chosen option to include variable_id in addition to choice_id.\nHere is a working demo. Temporary tables, so you can easily play with it:\nCREATE TABLE systemvariables (\n variable_id int PRIMARY KEY\n, choice_id int\n, var... | [
13,
4,
2
] | [] | [] | [
"database_design",
"postgresql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0008394177_database_design_postgresql_python_sql_sqlalchemy.txt |
Q:
ipython -c broken in 0.11?
I used to be able to start ipython from the command line like so:
ipython -c 'print "Hi"'
or more usefully
ipython -i -pdb -c "%run my_program.py"
Now I get the error: [TerminalIPythonApp] Unrecognized flag: '-c'.
Is this an ipython-0.11 bug or is the capability being 'phased out'? O... | ipython -c broken in 0.11? | I used to be able to start ipython from the command line like so:
ipython -c 'print "Hi"'
or more usefully
ipython -i -pdb -c "%run my_program.py"
Now I get the error: [TerminalIPythonApp] Unrecognized flag: '-c'.
Is this an ipython-0.11 bug or is the capability being 'phased out'? Or, better yet, am I just doing s... | [
"Yes, this an issue in the argument parsing in 0.11. It requires that you specify anything that takes a value with '=', so it must be:\nipython --c='print \"Hi\"'\n\nThis requirement has been relaxed in git master, and your command as-written* will work in 0.12, out later this month.\n* only one-character flags al... | [
3,
0
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0008408772_ipython_python.txt |
Q:
from . import x using __import__?
How do I achieve from . import x (import module x from the current package), using __import__?
Here are some attempts that failed:
>>> __import__('.', fromlist=['x'])
ValueError: Empty module name
>>> __import__('.x')
ValueError: Empty module name
How is this done using __import... | from . import x using __import__? | How do I achieve from . import x (import module x from the current package), using __import__?
Here are some attempts that failed:
>>> __import__('.', fromlist=['x'])
ValueError: Empty module name
>>> __import__('.x')
ValueError: Empty module name
How is this done using __import__?
| [
"The __import__ built-in's semantics are dovetailed with the bytecode that the interpreter generates from import statements, and are not especially convenient for manual use. If I understand what you are going for correctly, this does what you want:\nname = 'x'\nmod = getattr(__import__('', fromlist=[name], level=... | [
3,
2
] | [] | [] | [
"import",
"module",
"python",
"python_3.x"
] | stackoverflow_0008408373_import_module_python_python_3.x.txt |
Q:
python dictionary value begins by 0
Possible Duplicate:
Not getting exact result in python with the values leading zero. Please tell me what is going on there
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
>>> sample={'first_value':01... | python dictionary value begins by 0 |
Possible Duplicate:
Not getting exact result in python with the values leading zero. Please tell me what is going on there
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}... | [
"The leading zero is telling Python to interpret it as an octal number.\n",
"Numbers starting with 0 are considered octal. You'll either need to wrap the number temporarily in a string or format 123456 with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).\n... | [
7,
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008408970_dictionary_python.txt |
Q:
How do I write a form in django
I am writing a forums app for my final project in class and I am trying to write a form for creating a new thread, Basically all I need it to do is
username: text box here
Name of thread: Text box here
Post: text box here
I want to do this in forms.py instead of making a template ... | How do I write a form in django | I am writing a forums app for my final project in class and I am trying to write a form for creating a new thread, Basically all I need it to do is
username: text box here
Name of thread: Text box here
Post: text box here
I want to do this in forms.py instead of making a template for it.
url(r"^(.+)/new_thread/$", ne... | [
"Read the documentation:\nhttps://docs.djangoproject.com/en/dev/topics/forms/modelforms/\nI guess that the Thread has a model.\nclass ThreadForm(ModelForm):\n\n def __init__(self, forum, user, *args, **kwargs):\n super(ThreadForm, self).__init__(*args, **kwargs)\n self.forum = forum\n self.u... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008409014_django_python.txt |
Q:
How can I delete files or folders on github?
I have a python project I'm working on, and I'm keeping it on github. I recently updated it, trying to change the name of a folder. However, it actually just added the folder again without changing the other one. Is there a way I can delete the old folder? In the future... | How can I delete files or folders on github? | I have a python project I'm working on, and I'm keeping it on github. I recently updated it, trying to change the name of a folder. However, it actually just added the folder again without changing the other one. Is there a way I can delete the old folder? In the future, is there a better way to change the name of a fi... | [
"when you move the folder or rename it\ngit add -A\n\nthis will stage all changes - including deletions. Committing this, you will see that you now have a move.\nIn the future you can\nmv somefile someotherfile\n\nand git add -A will see this as a move.\n",
"Adam's answer will get your project from it's current s... | [
3,
1
] | [] | [] | [
"delete_file",
"git",
"github",
"python",
"repository"
] | stackoverflow_0008409035_delete_file_git_github_python_repository.txt |
Q:
Implementing sizeHint on a QItemDelegate subclass
I'm trying to create a table where each item contains a pair of rows, like this:
Ideally, the font of the top row would be different (rather than just bolded.)
My solution is to subclass QItemDelegate and overload paint and sizeHint. The above diagram show paint ... | Implementing sizeHint on a QItemDelegate subclass | I'm trying to create a table where each item contains a pair of rows, like this:
Ideally, the font of the top row would be different (rather than just bolded.)
My solution is to subclass QItemDelegate and overload paint and sizeHint. The above diagram show paint working properly, but I haven't been able to figure out... | [
"I don't have a complete solution to your question. However, for computing text rectangles you could take a look at QFontMetrics.boundingRect. Also, you might be interested in the rich-text item delegate given in this answer.\n"
] | [
0
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0008393793_pyqt4_python_qt.txt |
Q:
Python 2.6 and unicode
So I am working for a web browser type of application for my client and I just implemented bookmarking functionality, but it doesn't work as expected. When user click "Bookmark page" a little form pops up, which takes title of a webpage and puts it in a line edit. The thing is, that if the w... | Python 2.6 and unicode | So I am working for a web browser type of application for my client and I just implemented bookmarking functionality, but it doesn't work as expected. When user click "Bookmark page" a little form pops up, which takes title of a webpage and puts it in a line edit. The thing is, that if the website has some foreign or u... | [
"If you're using QWebView.title to get the title of the current web-page, then it will either return a QString or a python unicode string. Which one you get depends on the PyQt API version in use. For version 1 (which is the default for Python2), it will be a QString; for version 2 (which is the default for Python3... | [
1,
0
] | [] | [] | [
"browser",
"encoding",
"pyqt",
"python",
"unicode"
] | stackoverflow_0008407332_browser_encoding_pyqt_python_unicode.txt |
Q:
How does http://qwebirc.org/ work?
I think it's a really cool script. But when you're in a chat I'd like to know how it requests new chat content.
I'm interested because the chats I've made in the past have been inefficient and consumed a lot of bandwidth. I tried inspecting element in Chrome and going to Network ... | How does http://qwebirc.org/ work? | I think it's a really cool script. But when you're in a chat I'd like to know how it requests new chat content.
I'm interested because the chats I've made in the past have been inefficient and consumed a lot of bandwidth. I tried inspecting element in Chrome and going to Network but it never shows any requests for me. ... | [
"You can download the code powering the site.\nYou can also browse the code\nTo answer your question, you should install it, and use firebug to look at network traffic.\nSo... you've tagged this as PHP, but you might want to edit it and tag python.\nWhat do I need to run qwebirc?\nYou need Python (at least version ... | [
1
] | [] | [] | [
"chat",
"comet",
"pull",
"push",
"python"
] | stackoverflow_0008409412_chat_comet_pull_push_python.txt |
Q:
Unable to deserialize PyMongo ObjectId from JSON
I'm seemingly unable to deserialize my MongoDB JSON document with the BSON json_util.
The json.loads function is choking on the ObjectId() string. I had understood json_util capable of handling MongoDB's ObjectId format and transforming into usable JSON.
Python co... | Unable to deserialize PyMongo ObjectId from JSON | I'm seemingly unable to deserialize my MongoDB JSON document with the BSON json_util.
The json.loads function is choking on the ObjectId() string. I had understood json_util capable of handling MongoDB's ObjectId format and transforming into usable JSON.
Python code:
import json
from bson import json_util
s = "{... | [
"I think your string form actually looks like the python representation...\ns = '{\"_id\": {\"$oid\": \"4edebd262ae5e93b41000000\"}}'\nu = json.loads(s, object_hook=json_util.object_hook)\n\nprint u # Result: {u'_id': ObjectId('4edebd262ae5e93b41000000')}\n\ns = json.dumps(u, default=json_util.default)\n\nprint s... | [
20,
4
] | [] | [] | [
"bson",
"json",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0008409194_bson_json_mongodb_pymongo_python.txt |
Q:
Is there a way to use urllib to open one site until a specified object in it?
I'm using urllib to open one site and get some information on it.
Is there a way to "open" this site only to the part I need and discard the rest (discard I mean don't open/load the rest)?
A:
I'm not sure what you are trying to do. If ... | Is there a way to use urllib to open one site until a specified object in it? | I'm using urllib to open one site and get some information on it.
Is there a way to "open" this site only to the part I need and discard the rest (discard I mean don't open/load the rest)?
| [
"I'm not sure what you are trying to do. If you are simply trying to parse the site to find the useful \"information\", then I recommend using the library BeautifulSoup. That library makes it easy to keep certain parts of the site while discarding the rest.\nIf however you trying to save download bandwidth by down... | [
0,
0
] | [] | [] | [
"python",
"urllib",
"windows"
] | stackoverflow_0008409372_python_urllib_windows.txt |
Q:
Refactoring Synchronous Client to Use Asynchronous Twisted Calls
I discovered twisted half-way through developing a network application. I had a working Client and Server using raw socket communication, but have opted to use Twisted in order to handle multiple connections asynchronously on the Server side. The t... | Refactoring Synchronous Client to Use Asynchronous Twisted Calls | I discovered twisted half-way through developing a network application. I had a working Client and Server using raw socket communication, but have opted to use Twisted in order to handle multiple connections asynchronously on the Server side. The twisted server works fine with the following raw-socket client class co... | [
"Your best bet for quick Twisted client and server info is to look at the Twisted How To docs:\nhttp://twistedmatrix.com/documents/current/core/howto/index.html\nIn particular: Writing a TCP Server (which you seem to have working)\nand: Writing a TCP Client\nAfter you have your head wrapped around that, get the thi... | [
2
] | [] | [] | [
"network_programming",
"python",
"refactoring",
"twisted"
] | stackoverflow_0008408004_network_programming_python_refactoring_twisted.txt |
Q:
Passing form parameters between views in Pyramid
I am creating a form that requires user confirmation before submitting the data. I would like a seperate confirmation page because I need to display quite a bit information about how the form data will be processed. I was wondering if there was a pythonic way to pas... | Passing form parameters between views in Pyramid | I am creating a form that requires user confirmation before submitting the data. I would like a seperate confirmation page because I need to display quite a bit information about how the form data will be processed. I was wondering if there was a pythonic way to pass data between forms in Pyramid.
Submitting the form ... | [
"This is not a Pyramid-specific answer, but two common approaches to this problem are:\n\nStore the data in a session.\nStore the data as a hidden form on the confirmation page, and resubmit with \"confirmed\"\n\nI like 2 much better because it's a stateless method. You can also use the exact same form processing ... | [
5
] | [] | [] | [
"forms",
"pyramid",
"python"
] | stackoverflow_0008409521_forms_pyramid_python.txt |
Q:
Elegant way of chunking data
Let's say I'd like to split some data into 60-character parts and store them in a hash. I've got the following solution, but it seems a bit dirty to me: (because of iteration and constant reassigning)
i = 0
while signature != '':
header_hash['Some-Authorization-' + i] = signature[:6... | Elegant way of chunking data | Let's say I'd like to split some data into 60-character parts and store them in a hash. I've got the following solution, but it seems a bit dirty to me: (because of iteration and constant reassigning)
i = 0
while signature != '':
header_hash['Some-Authorization-' + i] = signature[:60]
signature = signature[60:]
... | [
"Although fairly similar to how to evenly split a list into chunks I believe this to still be a valid problem, but will contain part of the answer to that previous question:\ndef hashing(header_hash, signature, hash_size):\n for index, i in enumerate(xrange(len(signature), hash_size)):\n header_hash['S... | [
3
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008409782_python_string.txt |
Q:
? not being seen in SQLite query via Python
I am currently using Python 2.7's SQLite 3 database API. When I go to execute a query like such:
c.execute('''select ? from music where ? like "%?%"''', (attr, attr, query))
I get the following error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The... | ? not being seen in SQLite query via Python | I am currently using Python 2.7's SQLite 3 database API. When I go to execute a query like such:
c.execute('''select ? from music where ? like "%?%"''', (attr, attr, query))
I get the following error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 3 suppli... | [
"You misunderstand the use of parameter substitution. You can use ? in place a whole, single variable value in the SQL statement. You cannot use it in place of column or table names, nor can you use it as part of a larger string value.\nIn this case you could do this:\nc.execute('SELECT colname FROM music WHERE o... | [
3
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0008409803_database_python_sqlite.txt |
Q:
(Iron)Python - defining a variable of specific type
yes I know, this seems to be the same question as asked thousands of times before.
But no, it's not really - at least I think so.
I use IronPython and want to call a C# method:
bool GetClassInstance<T>(out T myClassInstance)
Calling this function via python woul... | (Iron)Python - defining a variable of specific type | yes I know, this seems to be the same question as asked thousands of times before.
But no, it's not really - at least I think so.
I use IronPython and want to call a C# method:
bool GetClassInstance<T>(out T myClassInstance)
Calling this function via python would look like:
myClassInstance = None
myInstance.GetClassIn... | [
"To call methods that have out parameters, just omit the argument (as you're not really passing a value) and its return value will be a tuple with the result of the function (if it was non-void) and the out values in the order they are defined.\nIn the case of ref parameters, pass in the argument and it will still ... | [
8,
3
] | [] | [] | [
"ironpython",
"python",
"types"
] | stackoverflow_0008397421_ironpython_python_types.txt |
Q:
randomly select a 200x200 square inside an image in python
I am using python to work on my project in image processing. Suppose I got a very large image ( 100000 x 100000), and I need to randomly select a 200 x 200 square from this large image. Are there any easy way to do this job? Please share some light with me... | randomly select a 200x200 square inside an image in python | I am using python to work on my project in image processing. Suppose I got a very large image ( 100000 x 100000), and I need to randomly select a 200 x 200 square from this large image. Are there any easy way to do this job? Please share some light with me. Thank you
----------------------------- EDIT -----------------... | [
"If you convert to binary PPM format, then there should be an easy way to seek to the appropriate offsets - it's not compressed, so there should be simple relationships.\nSo pick two random numbers between 0 and 100000-200-1, and go to town.\n(I'm assuming you don't have a system with 10's of gigabytes of RAM)\n"
] | [
4
] | [] | [] | [
"image_processing",
"matplotlib",
"python",
"python_imaging_library"
] | stackoverflow_0008410260_image_processing_matplotlib_python_python_imaging_library.txt |
Q:
How to escape a subpath inside a url with Pyramid
I need to pass a subpath as a param in a route generated by Pyramid. I tried using urllib.encode and urllib.quote but get a "resource could not be found error" either way.
route generation:
mypath='a/b/c'
new_route = route_url('new_model_route', self.request, subpa... | How to escape a subpath inside a url with Pyramid | I need to pass a subpath as a param in a route generated by Pyramid. I tried using urllib.encode and urllib.quote but get a "resource could not be found error" either way.
route generation:
mypath='a/b/c'
new_route = route_url('new_model_route', self.request, subpath=urllib.encode(mypath))
my route:
config.add_route('... | [
"The route pattern /model/new/{subpath} would never match /model/new/a/b/c so I don't understand why you would be able to generate a URL for that pattern?\nIt is possible to pass the rest of the url as elements, however.\nconfig.add_route('new_model_route', '/model/new/{subpath}')\nrequest.route_url('new_model_rout... | [
2
] | [] | [] | [
"pyramid",
"python",
"routes",
"url"
] | stackoverflow_0008409282_pyramid_python_routes_url.txt |
Q:
how to return a 400 errro_message in pyramid
I want to return the format:
res['result'] == False and res['error_message'] == 'Unknown User'
How to do it in views.py?
A:
Are you trying to return a JSON response? In that case set your renderer as json and return a dict containing the values you want.
def myview(re... | how to return a 400 errro_message in pyramid | I want to return the format:
res['result'] == False and res['error_message'] == 'Unknown User'
How to do it in views.py?
| [
"Are you trying to return a JSON response? In that case set your renderer as json and return a dict containing the values you want.\ndef myview(request):\n return {'result': False, 'error_message': 'Unknown User'}\n\nconfig.add_view(myview, renderer='json')\n\nObviously you'll need to add other stuff for your sp... | [
2
] | [] | [] | [
"pyramid",
"python"
] | stackoverflow_0008410137_pyramid_python.txt |
Q:
Getting Started with Facebook API
I have a friend that owns a small business and has a Page on Facebook. I want to help her manage it from a marketing perspective, and figure that it may be best to do so through their API.
I have skimmed their API documentation, and have a basic working knowledge of Python. W... | Getting Started with Facebook API | I have a friend that owns a small business and has a Page on Facebook. I want to help her manage it from a marketing perspective, and figure that it may be best to do so through their API.
I have skimmed their API documentation, and have a basic working knowledge of Python. What I can't figure out is if I can acce... | [
"You could try Pyjamas Desktop.\nhttp://pyjs.org/\nIt runs python in an embedded web browser and gives you access to the html DOM.\nThis potentially means that you can use the JS api directly from python.\nYou will need to be running a server locally though.\n",
"Basically to automate posting stuff to the persons... | [
1,
0
] | [] | [] | [
"api",
"facebook",
"python"
] | stackoverflow_0004697388_api_facebook_python.txt |
Q:
Python MongoDB Dict Results?
Is there away to retrieve results from MongoDB in Python using PyMongo and have them in dict style? For example
clogin = self.mdb.database.users.find_one( {"$and": [{"username" : str(username)}, {"password" : newpass}]})
fname = clogin['First_name']
A:
According to pymongo 2... | Python MongoDB Dict Results? | Is there away to retrieve results from MongoDB in Python using PyMongo and have them in dict style? For example
clogin = self.mdb.database.users.find_one( {"$and": [{"username" : str(username)}, {"password" : newpass}]})
fname = clogin['First_name']
| [
"According to pymongo 2.0 documentation:\n\nThe most basic type of query that can be performed in MongoDB is\n find_one(). This method returns a single document matching a query (or\n None if there are no matches). It is useful when you know there is\n only one matching document, or are only interested in the fi... | [
2,
1
] | [] | [] | [
"dictionary",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0008410249_dictionary_mongodb_pymongo_python.txt |
Q:
How to plot a simple function in python?
I have to implement a perceptron neural network in python.
For each training epoch (iterations over the training set), I record the number of errors in the predictions. I have to plot the errors as a function of epochs:
i.e.:
1 epoch -> 40 errors
2 epoch -> 30 errors
3 ep... | How to plot a simple function in python? | I have to implement a perceptron neural network in python.
For each training epoch (iterations over the training set), I record the number of errors in the predictions. I have to plot the errors as a function of epochs:
i.e.:
1 epoch -> 40 errors
2 epoch -> 30 errors
3 epoch -> 22 errors
...
I was thinking of making... | [
"import pylab\npylab.plot(epochs, errors)\npylab.show()\n\n"
] | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"plot",
"python"
] | stackoverflow_0008408893_matplotlib_numpy_plot_python.txt |
Q:
Can descriptors be used on properties to provide some declarative information?
I'm new to Python so forgive me if I'm not even using the right terminology... I'm using Python 3.2 and I'm trying to figure out whether I can decorate a class property with some declarative-style information.
In my mind it would look ... | Can descriptors be used on properties to provide some declarative information? | I'm new to Python so forgive me if I'm not even using the right terminology... I'm using Python 3.2 and I'm trying to figure out whether I can decorate a class property with some declarative-style information.
In my mind it would look like this:
class MyTestClass:
def __init__(self, foo):
self.foo = foo
... | [
"There is no simple way to do what you want with properties. You can't simply set attributes on or get attributes from items protected by a property.\ndef declarativeInfo(*args, **kwargs):\n def wrapper(obj):\n for arg in args:\n setattr(obj, arg, arg)\n for k, v in kwargs:\n ... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0007034498_python_python_3.x.txt |
Q:
Set Timeout for Pika ioloop async (RabbitMQ)
I need to be able to gracefully stop a consumer (worker) who works in a Pika ioloop. The worker should stop after 60 seconds. Currently processed messages should be finished.
I tried to put a connection.close() inside the callback function but that only stopped the cu... | Set Timeout for Pika ioloop async (RabbitMQ) | I need to be able to gracefully stop a consumer (worker) who works in a Pika ioloop. The worker should stop after 60 seconds. Currently processed messages should be finished.
I tried to put a connection.close() inside the callback function but that only stopped the current thread and not the complete ioloop. And it g... | [
"You can attach a timeout call-back function on the opened connection.\nHere is the extra code for your example.\ntimeout = 60\n\ndef on_timeout():\n global connection\n connection.close()\n\nconnection.add_timeout(timeout, on_timeout)\n\n"
] | [
10
] | [
"You can try to use:\nconnection.ioloop.stop()\n\n"
] | [
-4
] | [
"pika",
"python",
"rabbitmq"
] | stackoverflow_0008180596_pika_python_rabbitmq.txt |
Q:
Disable the Pygame console Output
Possible Duplicate:
How to suppress console output in Python?
Currently I am using pygame to read joystick input and I have the following issue that I need to solve.
When calling functions in the joystick module such as get_axis() or get_button() the function prints out lines su... | Disable the Pygame console Output |
Possible Duplicate:
How to suppress console output in Python?
Currently I am using pygame to read joystick input and I have the following issue that I need to solve.
When calling functions in the joystick module such as get_axis() or get_button() the function prints out lines such as SDL_JoystickGetButton value:0: I... | [
"This thread should resolve this:\nprintf statements 1.9.1\nI had this same issue except when running under PyScripter it causes a huge memory leak in PyScripter itself. So it was eating up all my memory on my machine. Nasty interaction.\n"
] | [
1
] | [] | [] | [
"console",
"python",
"sdl"
] | stackoverflow_0007012444_console_python_sdl.txt |
Q:
Get list of objects with related object
I've created two objects outside the database. One is SERVICES and one is MODULES.
I'd like to be able to get all MODULES related to a certain service. For instance, for the below example, I'd like to issue a command that basically says "Get list of Module Objects related t... | Get list of objects with related object | I've created two objects outside the database. One is SERVICES and one is MODULES.
I'd like to be able to get all MODULES related to a certain service. For instance, for the below example, I'd like to issue a command that basically says "Get list of Module Objects related to Service with key FACEBOOK" and have it retu... | [
"I assume that SERVICES returns a Service-class having an name-attribute. If this is true, then you can get all modules related to a service (FACEBOOK for example) like this:\nserviceModules = [m for m in ALL_MODULES if m.service.name == 'FACEBOOK']\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0008411096_python.txt |
Q:
Calculating moving average for values in a dictionary with keys in a specific range
So far this is my solution. I wonder if there is some more elegant/efficient way?
import datetime as dt
example = {dt.datetime(2008, 1, 1) : 5, dt.datetime(2008, 1, 2) : 6, dt.datetime(2008, 1, 3) : 7, dt.datetime(2008, 1, 4) : 9,... | Calculating moving average for values in a dictionary with keys in a specific range | So far this is my solution. I wonder if there is some more elegant/efficient way?
import datetime as dt
example = {dt.datetime(2008, 1, 1) : 5, dt.datetime(2008, 1, 2) : 6, dt.datetime(2008, 1, 3) : 7, dt.datetime(2008, 1, 4) : 9, dt.datetime(2008, 1, 5) : 12,
dt.datetime(2008, 1, 6) : 15, dt.datetime(2008, 1, 7) : 2... | [
"If you're looking for other interesting ways to solve the problem, here is an answer using itertools:\nimport datetime as dt\nfrom collections import deque\nfrom itertools import tee, islice, izip\n\ndef dayiter(start, end):\n one = dt.timedelta(days=1)\n day = start\n while day <= end:\n yield day... | [
2,
1
] | [] | [] | [
"dictionary",
"list_comprehension",
"moving_average",
"python"
] | stackoverflow_0008409225_dictionary_list_comprehension_moving_average_python.txt |
Q:
Can argparse in python 2.7 be told to require a minimum of TWO arguments?
My application is a specialized file comparison utility and obviously it does not make sense to compare only one file, so nargs='+' is not quite appropriate.
nargs=N only excepts a maximum of N arguments, but I need to accept an infinite num... | Can argparse in python 2.7 be told to require a minimum of TWO arguments? | My application is a specialized file comparison utility and obviously it does not make sense to compare only one file, so nargs='+' is not quite appropriate.
nargs=N only excepts a maximum of N arguments, but I need to accept an infinite number of arguments as long as there are at least two of them.
| [
"Short answer is you can't do that because nargs doesn't support something like '2+'.\nLong answer is you can workaround that using something like this:\nparser = argparse.ArgumentParser(usage='%(prog)s [-h] file file [file ...]')\nparser.add_argument('file1', nargs=1, metavar='file')\nparser.add_argument('file2', ... | [
19,
6
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0008411218_argparse_python.txt |
Q:
Running Selenium Tests Against Server Farm using Python
I want to run a selenium tests using python against a server farm that has about 50 web servers. What I have been doing is changing my host file (@ /etc/hosts) to switch to the desired server and run my selenium tests. This manual process can be tedious. Is t... | Running Selenium Tests Against Server Farm using Python | I want to run a selenium tests using python against a server farm that has about 50 web servers. What I have been doing is changing my host file (@ /etc/hosts) to switch to the desired server and run my selenium tests. This manual process can be tedious. Is there a better way to test these individual servers faster?
I... | [
"use selenium2(webdriver) python binding ,does it make sense than change the server address in for loop ?\nthen it run in sequence way.\n",
"As per my understanding, you are hitting a farm with same domain name but different IP addresses in it. Thats why changing the web address in selenium is not feasible and yo... | [
0,
0
] | [] | [] | [
"grid",
"python",
"selenium",
"testing"
] | stackoverflow_0008411129_grid_python_selenium_testing.txt |
Q:
Threading in Python : Python 'args' is an invalid keyword argument for this function, why?
I have written code for threading in Python.
It throws the error below.
How should I fix that error?
from django.core.management import setup_environ
import settings
setup_environ(settings)
from threading i... | Threading in Python : Python 'args' is an invalid keyword argument for this function, why? | I have written code for threading in Python.
It throws the error below.
How should I fix that error?
from django.core.management import setup_environ
import settings
setup_environ(settings)
from threading import Thread
import urllib2
from django.db import transaction
from Uzvy.models impor... | [
"I think (edited: I'm sure) you have model with name Thread. So you try to instantiate Uzvy.models.Thread, not threading.Thread\n\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python",
"python_module",
"python_multithreading"
] | stackoverflow_0008411641_django_django_models_python_python_module_python_multithreading.txt |
Q:
Warning message should contain a LINK to a next page
If the user has no username I am displaying an warning message on their profile page. In it I want to set a link to a page where the user can set their username. I have done this like this but the a href is displayed as a string. What is the problem?
messages.wa... | Warning message should contain a LINK to a next page | If the user has no username I am displaying an warning message on their profile page. In it I want to set a link to a page where the user can set their username. I have done this like this but the a href is displayed as a string. What is the problem?
messages.warning(request, 'WARNING! You have not set your custom URL ... | [
"Messages are just strings, not template instructions. To get your url you should use reverse:\nfrom django.core.urlresolvers import reverse \n\nmessages.warning(request, 'WARNING! You have not set your custom URL for this profile. You can set this <a href=\"%s\">HERE.</a>' % reverse('change_url'))\n\nTo turn of... | [
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0008411412_django_django_templates_python.txt |
Q:
python 2.7 can't find a module in the Lib directory
I'm running some code that is trying to import this module but failing with the error code
File "X:\python_2_7\lib\distutils\tests\__init__.py", line 18, in <module>
from test.test_support import run_unittest
ImportError: No module named test_support
The t... | python 2.7 can't find a module in the Lib directory | I'm running some code that is trying to import this module but failing with the error code
File "X:\python_2_7\lib\distutils\tests\__init__.py", line 18, in <module>
from test.test_support import run_unittest
ImportError: No module named test_support
The test_support.py file is located in the directory:
X:\pyth... | [
"\"python -v\" is your friend. It should report where modules are sought and where they are found.\n",
"You should fix the path by adding a file like pathfix.py, the content is below\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))\nsys.path.app... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0008411448_python.txt |
Q:
decoding json from ustream api with python
I'm trying to use simplejson to parse a request from the ustream data api, and I get this error when decoding. I'm new to the json library in python, so i'm not sure where to begin working towards a solution.
>>> import simplejson as json
>>> import requests as requests
>... | decoding json from ustream api with python | I'm trying to use simplejson to parse a request from the ustream data api, and I get this error when decoding. I'm new to the json library in python, so i'm not sure where to begin working towards a solution.
>>> import simplejson as json
>>> import requests as requests
>>> r = requests.get("http://api.ustream.tv/json/... | [
"When doing this :\n>>> in_json = None\n>>> json.loads(in_json)\n\nyou ask json to parse None... and None is not a JSon object, that's the cause of your problem.\nI think it would be better to do something like this\n>>> r = requests.get(\"http://api.ustream.tv/json/stream/popular/search/all?key=y\nourDevKey\")\n>>... | [
4
] | [] | [] | [
"api",
"decode",
"json",
"python",
"simplejson"
] | stackoverflow_0008412175_api_decode_json_python_simplejson.txt |
Q:
Is there a way to convert nltk featuresets into a scipy.sparse array?
I'm trying to use scikit.learn which needs numpy/scipy arrays for input.
The featureset generated in nltk consists of unigram and bigram frequencies. I could do it manually, but that'll be a lot of effort. So wondering if there's a solution i've... | Is there a way to convert nltk featuresets into a scipy.sparse array? | I'm trying to use scikit.learn which needs numpy/scipy arrays for input.
The featureset generated in nltk consists of unigram and bigram frequencies. I could do it manually, but that'll be a lot of effort. So wondering if there's a solution i've overlooked.
| [
"Jacob Perkins did a a bridge for training NLTK classifiers using scikit-learn classifiers that does exactly that here is the source:\nhttps://github.com/japerk/nltk-trainer/blob/master/nltk_trainer/classification/sci.py\nThe package import lines should be updated if you are using version 0.9+.\n",
"Not that I kn... | [
1,
0
] | [] | [] | [
"nlp",
"nltk",
"python",
"scikits"
] | stackoverflow_0008394257_nlp_nltk_python_scikits.txt |
Q:
Python Image Library (PIL) error with floating point tiff
I am writing a script that changes the resolution of a floating point 2K (2048x2048) tiff image to 1024x1024.
But I get the following error:
File "C:\Python26\lib\site-packages\PIL\Image.py", line 1916, in open
IOError: cannot identify image file
My Code:
i... | Python Image Library (PIL) error with floating point tiff | I am writing a script that changes the resolution of a floating point 2K (2048x2048) tiff image to 1024x1024.
But I get the following error:
File "C:\Python26\lib\site-packages\PIL\Image.py", line 1916, in open
IOError: cannot identify image file
My Code:
import Image
im = Image.open( inPath )
im = im.resize( (1024, ... | [
"Try one of these two:\n\nopen the file in binary mode,\ngive the full path to the file.\n\nHTH!\nEDIT after testing the OP's image:\nIt definitively seems like is the image having some problem. I'm on GNU/Linux and couldn't find a single program being able to handle it. Among the most informative about what the pr... | [
2
] | [] | [] | [
"floating_point",
"image",
"python",
"python_imaging_library",
"tiff"
] | stackoverflow_0008412261_floating_point_image_python_python_imaging_library_tiff.txt |
Q:
Syntax sugar for querying a Python list which element occurs first
I have a list of many elements.
I care about two of its elements, a and b.
I don't know the order of the list, nor do I want to sort it.
Is there a nice one-liner that will return True if a occurs before b and false otherwise?
A:
In the interests... | Syntax sugar for querying a Python list which element occurs first | I have a list of many elements.
I care about two of its elements, a and b.
I don't know the order of the list, nor do I want to sort it.
Is there a nice one-liner that will return True if a occurs before b and false otherwise?
| [
"In the interests of diversity, you could also:\nb in l[l.index(a):]\n\nThis will be True if a == b. If you know that a != b,\nb in l[l.index(a) + 1:]\n\n",
"Edit: Rewritten to check more cases\nOK, so this problem needs a bit more work. Mark Byers is completely right in that my first test only covered cases wher... | [
9,
8,
7,
5
] | [] | [] | [
"list",
"python",
"syntactic_sugar"
] | stackoverflow_0008412223_list_python_syntactic_sugar.txt |
Q:
Cant able to run the appliaction on appnegine SDK
I just tried to run the sample application(gustbook) on google app engine SDK. But it showing warning symbol for that apps.
I have re-insalled both python2.5 & GAE. Still app is not running.
Here is the Log:-
2011-12-07 11:15:51 Running command: "['C:\\Python25\\py... | Cant able to run the appliaction on appnegine SDK | I just tried to run the sample application(gustbook) on google app engine SDK. But it showing warning symbol for that apps.
I have re-insalled both python2.5 & GAE. Still app is not running.
Here is the Log:-
2011-12-07 11:15:51 Running command: "['C:\\Python25\\pythonw.exe', 'C:\\Program Files\\Google\\google_appengin... | [
"I'm guessing you got invalid characters in one of your strings,\ncould you give us some code to work with and perhaps some working data?\nI'm also guessing you're using the proper urlfetch function and not some home-brew socket solution because that wont work.\nhttp://code.google.com/appengine/docs/python/urlfetch... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008411019_google_app_engine_python.txt |
Q:
Python - VMWare vSphere (WEB SDK) - SUDS
How do i contact the vSphere (or VMWare) form Python either with some form of library or via SUDS to get the number of number of vCPU or a specific host/guest/virtual-machine?
Currently i'm trying:
from suds.client import Client
from suds.sudsobject import Property
client ... | Python - VMWare vSphere (WEB SDK) - SUDS | How do i contact the vSphere (or VMWare) form Python either with some form of library or via SUDS to get the number of number of vCPU or a specific host/guest/virtual-machine?
Currently i'm trying:
from suds.client import Client
from suds.sudsobject import Property
client = Client("https://<server>/sdk/vimService?wsdl... | [
"You might want to try psphere, a Python library (based on suds) which will give you access the entire vSphere Web Services SDK.\nInstall it:\n$ pip install psphere\n\nFind a virtual machine and print the number of CPUs it has:\n>>> from psphere.client import Client\n>>> from psphere.managedobjects import VirtualMa... | [
3,
2
] | [] | [] | [
"python",
"suds",
"vmware"
] | stackoverflow_0007889762_python_suds_vmware.txt |
Q:
How to search a file for all positions within a range in perl or python?
Ok, so I'm new to this, here's my problem:
I have two files, one contains gene ids and a range indicted with start and stop positions: for example:
gene_id start stop
grf4 1245 1365
fgt89 3089 4524
tig3 45600 46800
The other... | How to search a file for all positions within a range in perl or python? | Ok, so I'm new to this, here's my problem:
I have two files, one contains gene ids and a range indicted with start and stop positions: for example:
gene_id start stop
grf4 1245 1365
fgt89 3089 4524
tig3 45600 46800
The other contains positions and information about those positions, for example:
positi... | [
"Change text into data\nFirst I would suggest processing your files and saving them as database for easier further processing. You can extract data from these files eg. in the following ways:\nfile1 = open('some_filename.txt')\nfile1_lines = [filter(len, line.split(' ')) for line in file1.readlines()]\n\nand the fi... | [
3,
1,
0
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0008410347_perl_python.txt |
Q:
Python/Javascript: WYSIWYG html editor - Handle large documents fast and/or design theory
Background:
I am writing an ebook editing program in python. Currently it utilizes a source-code view for editing, and I would like to port it over to a wysiwyg view for editing. The best (only?) html renderer I could find fo... | Python/Javascript: WYSIWYG html editor - Handle large documents fast and/or design theory | Background:
I am writing an ebook editing program in python. Currently it utilizes a source-code view for editing, and I would like to port it over to a wysiwyg view for editing. The best (only?) html renderer I could find for python was webkit (I am using the PyQt version).
Question:
How do I accomplish wysiwyg editin... | [
"Can i suggest a complete another approach ? Since your ebook is only <p></p>:\n\nSplit the text on <p></p> to get an indexed array of all your paragraphs\nMake your own pagination system, and fill the screen with N paragraphs, that automatically get enough text to show from the indexed array\nWhen you are doing se... | [
1
] | [] | [] | [
"html",
"python",
"wysiwyg"
] | stackoverflow_0008412215_html_python_wysiwyg.txt |
Q:
Python : method resolution order of old-style (or classic) and new-style objects
I have read a lot about Objects in Python Documentation which differentiates these two at some point like:
Old-style instances, independently of their class, are implemented with a single built-in type, called instance.
A new-style ... | Python : method resolution order of old-style (or classic) and new-style objects | I have read a lot about Objects in Python Documentation which differentiates these two at some point like:
Old-style instances, independently of their class, are implemented with a single built-in type, called instance.
A new-style class is neither more nor less than a user-defined type.
Could anyone explain to me ... | [
"Old class style:\nclass BaseClass:\n def m1(self):\n return 1\n\nclass MyClass(BaseClass):\n def m1(self):\n return BaseClass.m1(self)\n\nNew class style:\nclass BaseClass(object):\n def m1(self):\n return 1\n\nclass MyClass(BaseClass):\n def m1(self):\n return super(MyClass... | [
6
] | [] | [] | [
"class",
"object",
"oop",
"python"
] | stackoverflow_0008411465_class_object_oop_python.txt |
Q:
mysql takes 50+ times longer to return 20% more records, why?
I am using a program that I downloaded and don't have all the details. This is a web app (Python CGI) that takes user input and queries the mysql database. What I do know is that when I limit the recordset to 100 results (in the app setting), the resu... | mysql takes 50+ times longer to return 20% more records, why? | I am using a program that I downloaded and don't have all the details. This is a web app (Python CGI) that takes user input and queries the mysql database. What I do know is that when I limit the recordset to 100 results (in the app setting), the results are returned within 2 seconds. But if I increase the limit jus... | [
"More than likely the query contains some sort of logic which results in an exponential execution time.\nFor example, if I had a list of locations and want to calculate the distances between them:\nFor 2 rows, using no optimisation:\n1 => 2\n2 => 1\n\nFor 4 rows, using no optimisation\n1 => 2\n1 => 3\n1 => 4\n2 => ... | [
3
] | [] | [] | [
"cgi",
"mysql",
"python"
] | stackoverflow_0008413137_cgi_mysql_python.txt |
Q:
Printing a word Document within Python
I have a simple batch file here which will print a word document from the command line.
"C:\Program Files\Microsoft Office\Office12\winword.exe" "p:\docs\daily checks.doc" /mFilePrintDefault /mFileExit
I am trying to place this into a python script, I have managed to get the... | Printing a word Document within Python | I have a simple batch file here which will print a word document from the command line.
"C:\Program Files\Microsoft Office\Office12\winword.exe" "p:\docs\daily checks.doc" /mFilePrintDefault /mFileExit
I am trying to place this into a python script, I have managed to get the document to open by using
subprocess.Popen(... | [
"This should work:\nsubprocess.Popen([\"C:\\\\Program Files\\Microsoft Office\\Office12\\winword.exe\", \"P:\\\\docs\\\\daily checks.doc\", \"/mFilePrintDefault\", \"/mFileExit\"]).communicate()\n\nOr, altenatively,\nsubprocess.Popen(\"'C:\\\\Program Files\\Microsoft Office\\Office12\\winword.exe' 'P:\\\\docs\\\\da... | [
9,
0
] | [] | [] | [
"python"
] | stackoverflow_0008413207_python.txt |
Q:
Error installing psycopg2 on Mac OS 10.6
Hi i am trying to install psycopg2 on Mac 10.6. After i install i get this error when i try to import
import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 69, in <module>
f... | Error installing psycopg2 on Mac OS 10.6 | Hi i am trying to install psycopg2 on Mac 10.6. After i install i get this error when i try to import
import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 69, in <module>
from psycopg2._psycopg import BINARY, NUMBER, S... | [
"According to this link, psycopg2 seems must work in 32bit mode on MacOSX\n"
] | [
0
] | [] | [] | [
"osx_snow_leopard",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0008406003_osx_snow_leopard_postgresql_psycopg2_python.txt |
Q:
Is there a way how to add title to Gtk.TextTag?
I'm developing Gtk based application with GtkTextView.
I created a GtkTextBuffer and set few tags there.
Here's my code
def tag(self, line, msg, bc_color="red"):
start = self.buff.get_iter_at_line(line)
end = self.buff.get_iter_at_line(line)
end.forward_... | Is there a way how to add title to Gtk.TextTag? | I'm developing Gtk based application with GtkTextView.
I created a GtkTextBuffer and set few tags there.
Here's my code
def tag(self, line, msg, bc_color="red"):
start = self.buff.get_iter_at_line(line)
end = self.buff.get_iter_at_line(line)
end.forward_line()
tag = Gtk.TextTag()
tag.set_property(... | [
"You need to combine text tags with a tooltip. See this tutorial for an example which I believe does just what you want.\n",
"Try Tooltips or Tooltip(if using Gtk 2.12+).\n"
] | [
2,
0
] | [] | [] | [
"glade",
"gtk",
"python",
"user_interface"
] | stackoverflow_0008302498_glade_gtk_python_user_interface.txt |
Q:
Error occurs when linking libboost_python
I want to build this openNERO for myself. According to its building tutorial, I also build Boost 1.48 with python 2.7.2. With Boost, openNERO is compiled successfully. But when it try to link, ld complains that
CMakeFiles/OpenNERO.dir/scripting/scripting.cpp.o: In function... | Error occurs when linking libboost_python | I want to build this openNERO for myself. According to its building tutorial, I also build Boost 1.48 with python 2.7.2. With Boost, openNERO is compiled successfully. But when it try to link, ld complains that
CMakeFiles/OpenNERO.dir/scripting/scripting.cpp.o: In function `initOpenNero':
~/svn/opennero/trunk/source/sc... | [
"I remember I first built boost with python 3.2, so I deleted all the files generated and rebuilt boost again. This time everything is correct. It seems that the older files will not be overwritten.\n"
] | [
1
] | [] | [] | [
"boost",
"ld",
"python"
] | stackoverflow_0008394207_boost_ld_python.txt |
Q:
How do I pass the contents of an Entry box to a Label?
I have an entry box and when I enter some text into it and click a button the text should appear in the label.
I have written the following but I am unable to bind the contents of the entry box to the label.
from Tkinter import *
root = Tk()
e = Entry(root)... | How do I pass the contents of an Entry box to a Label? | I have an entry box and when I enter some text into it and click a button the text should appear in the label.
I have written the following but I am unable to bind the contents of the entry box to the label.
from Tkinter import *
root = Tk()
e = Entry(root)
e.pack()
def get_me():
e.get()
print e.get()
#... | [
"Tkinter widget parameters can be modified with a dictionary like syntax, after they are\ninstantiated. In the case of text, the property to be changed is \"text\" -\nSo, just add this line to your button callback on your example:\nla[\"text\"] = e.get()\n\nOn a larger program, be sure to manage better variable nam... | [
3,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008411030_python_tkinter.txt |
Q:
Why does this work in Python 3 IDLE on Windows and not in the terminal on Ubuntu?
I have a program where I use input() to take input from STDIN.
I use the input to read the first word from a line and use it as a dictionary key, with every subsequent word added to a list which is the value of the aformentioned key.... | Why does this work in Python 3 IDLE on Windows and not in the terminal on Ubuntu? | I have a program where I use input() to take input from STDIN.
I use the input to read the first word from a line and use it as a dictionary key, with every subsequent word added to a list which is the value of the aformentioned key.
The input is in a file names.txt:
Victor Bertha Amy Diane Erika Clare
Wyatt Diane Bert... | [
"The meaning of input() has changed.\nIn Python 3.2: http://docs.python.org/py3k/library/functions.html#input\nIn Python 2.7.2: http://docs.python.org/library/functions.html#input\nYou can see this far easier with two small testing programs. The only difference is one uses the Python 2.7 interpreter and the other u... | [
3
] | [] | [] | [
"io",
"python",
"python_idle",
"ubuntu"
] | stackoverflow_0008413200_io_python_python_idle_ubuntu.txt |
Q:
Long integer shape of Numpy arrays
If I construct a numpy matrix like this:
A = array([[1,2,3],[4,5,6]])
and then type A.shape I get the result:
(2L, 3L)
Why am I getting a shape with the format long?
I can restart everything and I still have the same problem. And as far as I can see, it is only when I construct... | Long integer shape of Numpy arrays | If I construct a numpy matrix like this:
A = array([[1,2,3],[4,5,6]])
and then type A.shape I get the result:
(2L, 3L)
Why am I getting a shape with the format long?
I can restart everything and I still have the same problem. And as far as I can see, it is only when I construct arrays I have this problem, otherwise I... | [
"As @CédricJulien puts it on the comment, there is no problem with long numbers in this case - this should be treated as an implementation detail.\nThe real answer for your question can, of course, only be found inside numpy's source code, but the fact that the dimensions are long in this case should not matter for... | [
3
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0008412946_arrays_numpy_python.txt |
Q:
Parsing tag and getting data with python
I'm new on stackoverflow and this is my first question.
I'm writing script in Python for parsing HTML page.
Page looks like this:
<TABLE style="border: 1px solid black">
<TR>
<TD colspan="2"><span id="text1" style="color: white">DATA1</span></TD>
</TR>
<TR>
<T... | Parsing tag and getting data with python | I'm new on stackoverflow and this is my first question.
I'm writing script in Python for parsing HTML page.
Page looks like this:
<TABLE style="border: 1px solid black">
<TR>
<TD colspan="2"><span id="text1" style="color: white">DATA1</span></TD>
</TR>
<TR>
<TD class="rowLabel" valign="top">Data name</TD>
... | [
"I find that using BeautifulSoup with any sort of HTML is much easier.\nfrom BeautifulSoup import BeautifulSoup as bs\nfrom urllib2 import urlopen\n\ndata = urlopen('wherever').read()\n\nsoup = bs(data)\n\nfor span in soup.findAll('span'):\n print span['id'], span.text\n\nYou may have to refine some parts of it,... | [
2,
0
] | [] | [] | [
"html",
"parsing",
"python"
] | stackoverflow_0008413581_html_parsing_python.txt |
Q:
ActiveMQ : Use Django Auth with Stomp
I am working on power monitoring and want to send live power data to authorised users only. Some users have opted to install power sensors in their houses, others are viewing those sensors. Each sensor sends samples to a Twisted backend - the goal is to have this backend forwa... | ActiveMQ : Use Django Auth with Stomp | I am working on power monitoring and want to send live power data to authorised users only. Some users have opted to install power sensors in their houses, others are viewing those sensors. Each sensor sends samples to a Twisted backend - the goal is to have this backend forward the data to Javascript running in the br... | [
"If you use the restq extensions for morbidq, you can have it send an http callback to your application every time the user attempts to connect. (See http://www.morbidq.com/trac/wiki/RestQ ). Your django app can then just return yes or no to the connect attempt (after it runs though some auth procedure.)\n",
"Rev... | [
1,
1
] | [] | [] | [
"django",
"orbited",
"python",
"stomp"
] | stackoverflow_0001571224_django_orbited_python_stomp.txt |
Q:
faster redraw of pygtk drawing area?
I'm creating a paint program based on this program. Dragging the mouse faster results in spotty brush strokes, so I'm wondering if there is a faster way to redraw the drawing area.
This is the current redraw function. It is already utilizing widget.queue_draw_area and the scree... | faster redraw of pygtk drawing area? | I'm creating a paint program based on this program. Dragging the mouse faster results in spotty brush strokes, so I'm wondering if there is a faster way to redraw the drawing area.
This is the current redraw function. It is already utilizing widget.queue_draw_area and the screen is redrawn from a pixmap.
def expose_ev... | [
"I would suggest keeping track of the last position of the mouse and then drawing a continuous line from the last position to the current position, instead of drawing one brush shape at the current position.\n"
] | [
0
] | [] | [] | [
"drawable",
"pixmap",
"pygtk",
"python",
"redraw"
] | stackoverflow_0008370082_drawable_pixmap_pygtk_python_redraw.txt |
Q:
Application-shipped python does not autoset site-dirs correctly
The team I work in is developping an application (for now, on Windows) which is scriptable with python. A python 2.6 is installed alongside Application.exe, so as end users won't have to install python on their workstations.
I have not personnaly chos... | Application-shipped python does not autoset site-dirs correctly | The team I work in is developping an application (for now, on Windows) which is scriptable with python. A python 2.6 is installed alongside Application.exe, so as end users won't have to install python on their workstations.
I have not personnaly chosen the said distribution of python, and I find it quite strange, and ... | [
"You can add the ApplicationDir/lib/site-packages in your sys.path:\nimport sys, os\nsys.path += [os.path.join(os.path.dirname(__file__), 'lib', 'site-packages')]\n\nOr using environment variables:\nPYTHONPATH=/path/to/lib/site-packages\n\nOr check sysconfig module:\nimport sysconfig\nprint sysconfig.get_config_var... | [
0
] | [] | [] | [
"distribution",
"python"
] | stackoverflow_0008414136_distribution_python.txt |
Q:
Map multiple lists of values to a list of keys in a python dictionary?
I want to map some values(a list of lists) to some keys(a list) in a python dictionary.
I read Map two lists into a dictionary in Python
and figured I could do that this way :
headers = ['name', 'surname', 'city']
values = [
['charles', 'ro... | Map multiple lists of values to a list of keys in a python dictionary? | I want to map some values(a list of lists) to some keys(a list) in a python dictionary.
I read Map two lists into a dictionary in Python
and figured I could do that this way :
headers = ['name', 'surname', 'city']
values = [
['charles', 'rooth', 'kentucky'],
['william', 'jones', 'texas'],
['john', 'frith'... | [
"You could use a list comprehension:\ndata = [dict(itertools.izip(headers, entries)) for entries in values]\n\n",
"from functools import partial\nfrom itertools import izip, imap\ndata = map(dict, imap(partial(izip, headers), values))\n\n",
"It's already really nice...\ndata = [dict(itertools.izip(headers, entr... | [
2,
2,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0008414090_dictionary_list_python.txt |
Q:
How to define variable with two zeros
I making MAC addr generator and currently I have this problem.
mac1="001122334455"
mac2="001122334695"
mac1 = [mac1[x:x+2] for x in xrange(0,len(mac1),2)]
mac2 = [mac2[x:x+2] for x in xrange(0,len(mac2),2)]
k=0
for item in mac1:
mac1[k] = "%d" % int(mac1[k], 16)
mac2[... | How to define variable with two zeros | I making MAC addr generator and currently I have this problem.
mac1="001122334455"
mac2="001122334695"
mac1 = [mac1[x:x+2] for x in xrange(0,len(mac1),2)]
mac2 = [mac2[x:x+2] for x in xrange(0,len(mac2),2)]
k=0
for item in mac1:
mac1[k] = "%d" % int(mac1[k], 16)
mac2[k] = "%d" % int(mac2[k], 16)
mac1[k]=in... | [
"You cannot set an integer as 00 it will always degrade to 0, added to that fact, in python 2.x putting a 0 in front of an integer (for example 0123) will tell python you want that number evaluated as an octal! defiantly not what you want. In python 3.x, 0integer is not allowed at all!\nyou need to use strings if y... | [
0,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0008414031_python_variables.txt |
Q:
Python 3 xmlrpc for remote objects
I am trying to implement a remote object implementation using xmlrpc, and python 3.
I have tried the example at http://docs.python.org/3.1/library/xmlrpc.server.html?highlight=xmlrpc#simplexmlrpcserver-example, but it only works to and from localhost, how can I get it to work to ... | Python 3 xmlrpc for remote objects | I am trying to implement a remote object implementation using xmlrpc, and python 3.
I have tried the example at http://docs.python.org/3.1/library/xmlrpc.server.html?highlight=xmlrpc#simplexmlrpcserver-example, but it only works to and from localhost, how can I get it to work to and from internal IPs?
| [
"Update the localhost value to the following:\nFor the server : s = SimpleXMLRPCServer((\"ServerIp\", 8000))\nFor the client : s = xmlrpc.client.ServerProxy(\"http://ServerIp:8000/\")\n",
"Perhaps I'm misunderstanding your question, but... Have you tried running the server code on another machine, and the client ... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"remoteobject"
] | stackoverflow_0001609749_python_python_3.x_remoteobject.txt |
Q:
How to select only certain Substrings
from a string say dna = 'ATAGGGATAGGGAGAGAGCGATCGAGCTAG'
i got substring say dna.format = 'ATAGGGATAG','GGGAGAGAG'
i only want to print substring whose length is divisible by 3
how to do that? im using modulo but its not working !
import re
if mydna = 'ATAGGGATAGGGAGAGAGCAGAT... | How to select only certain Substrings | from a string say dna = 'ATAGGGATAGGGAGAGAGCGATCGAGCTAG'
i got substring say dna.format = 'ATAGGGATAG','GGGAGAGAG'
i only want to print substring whose length is divisible by 3
how to do that? im using modulo but its not working !
import re
if mydna = 'ATAGGGATAGGGAGAGAGCAGATCGAGCTAG'
print re.findall("ATA"(.*?)"AGA" ... | [
"For including overlap substrings, I have the following lengthy version. The idea is to find all starting and ending marks and calculate the distance between them.\nmydna = 'ATAGGGATAGGGAGAGAGCAGATCGAGCTAG'\n[mydna[start.start():end.start()+3] for start in re.finditer('(?=ATA)',mydna) for end in re.finditer('(?=AGA... | [
1,
0,
0,
0
] | [] | [] | [
"biopython",
"python"
] | stackoverflow_0008390913_biopython_python.txt |
Q:
backup msSQL stored proc or UDF code via Python
The idea is to make a script that would get stored procedure and udf contents (code) every hour (for example) and add it to SVN repo. As a result we have sql versioning control system.
Does anyone know how to backup stored procedure code using Python (sqlAlchemy, pyo... | backup msSQL stored proc or UDF code via Python | The idea is to make a script that would get stored procedure and udf contents (code) every hour (for example) and add it to SVN repo. As a result we have sql versioning control system.
Does anyone know how to backup stored procedure code using Python (sqlAlchemy, pyodbc or smth).
I'v done this via C# before using SQL ... | [
"There is no easy way to access SMO from Python (because there is no generic solution for accessing .NET from Python), so I would write a command-line tool in C# and call it from Python using the subprocess module. Perhaps you could do something with ctypes but I have no idea if that's feasible.\nBut, perhaps a mor... | [
1
] | [] | [] | [
"c#",
"python",
"smo",
"sql_server",
"stored_procedures"
] | stackoverflow_0008412636_c#_python_smo_sql_server_stored_procedures.txt |
Q:
Caching disk operations
I might need to do multiple reads over a big code-base, and with different tools.
I then thought that is a real waste to read on disk so many times while the text won't change, so I wrote the following.
class Module(object):
def __init__(self, module_path):
self.module_path = mo... | Caching disk operations | I might need to do multiple reads over a big code-base, and with different tools.
I then thought that is a real waste to read on disk so many times while the text won't change, so I wrote the following.
class Module(object):
def __init__(self, module_path):
self.module_path = module_path
self._text ... | [
"Replacing the system open() call is potentially a bad thing. It requires that everything which uses open() uses it as you expect.\nWhy do you want to avoid changing the code?\nYes, measure the performance and see if it's worthwhile. For example, put in your above code and see how much faster things are. If it's on... | [
2,
2,
1
] | [] | [] | [
"built_in",
"caching",
"python",
"regex"
] | stackoverflow_0008414231_built_in_caching_python_regex.txt |
Q:
Python: large number of dict like objects memory use
I am using csv.DictReader to read some large files into memory to then do some analysis, so all objects from multiple CSV files need to be kept in memory. I need to read them as Dictionary to make analysis easier, and because the CSV files may be altered by add... | Python: large number of dict like objects memory use | I am using csv.DictReader to read some large files into memory to then do some analysis, so all objects from multiple CSV files need to be kept in memory. I need to read them as Dictionary to make analysis easier, and because the CSV files may be altered by adding new columns.
Yes SQL can be used, but I'd rather avoid... | [
"If you are on Python 2.6 or later, collections.namedtuple is what you are asking for.\nSee http://docs.python.org/library/collections.html#collections.namedtuple\n(there is even an example of using it with csv).\nEDIT: It requires the field names to be valid as Python identifiers, so perhaps it is not suitable in ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"memory",
"python"
] | stackoverflow_0008411476_dictionary_memory_python.txt |
Q:
Complex comparisons on yesno filter?
I'm quite new at python/django.
I love django's templates, but there is one recurrent thing I cannot find
It's very common for me to have one conditional attribute on a (probably long) HTML tag. Most of the times that's an extra CSS class.
For example, let's say you have two li... | Complex comparisons on yesno filter? | I'm quite new at python/django.
I love django's templates, but there is one recurrent thing I cannot find
It's very common for me to have one conditional attribute on a (probably long) HTML tag. Most of the times that's an extra CSS class.
For example, let's say you have two links to switch languages, and you want to e... | [
"The problem is simply with your syntax in the code you posted:\n{{l.code==\"es\"|yesno:\"disabled,\"}}\n\nIt's actually processed like:\n{{ l.code=={{\"es\"|yesno:\"disabled,\"}} }}\n\n(Note: that code doesn't work, it's just meant to illustrate how Django reads it)\nWhat you want is a custom template tag that wor... | [
4,
0
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0008404782_django_python_templates.txt |
Q:
Overriding eval globals with __getattr__ problems
I'm trying to override globals so that any attribute name
that doesn't exists returns itself(the name string).
The reason for this is to use it in eval to do some quick/hacky parsing of a c initilizer list, (and just because of course).
My Code:
class EvalGlobalsD... | Overriding eval globals with __getattr__ problems | I'm trying to override globals so that any attribute name
that doesn't exists returns itself(the name string).
The reason for this is to use it in eval to do some quick/hacky parsing of a c initilizer list, (and just because of course).
My Code:
class EvalGlobalsDict(dict):
def __getattr__(self, name):
if ... | [
"Since you're subclassing a dict, you'll want to override __getitem__ (the indexing accessor).\nclass EvalGlobalsDict(dict):\n def __getitem__(self, name):\n return self.get(name, name)\n\nfoo = 1337\neval_globals = EvalGlobalsDict(globals())\nprint repr(eval(\"aaa\", eval_globals))\nprint repr(eval(\"foo... | [
4
] | [] | [] | [
"getattr",
"metaprogramming",
"python"
] | stackoverflow_0008414800_getattr_metaprogramming_python.txt |
Q:
connection refused from server unit I reset client machine
Below is the code I am running within a service. For the most part the script runs fine for days/weeks until the script hiccups and crashes. I am not so worried about the crashing part as I can resolve the cause from the error logs an patch appropriately. ... | connection refused from server unit I reset client machine | Below is the code I am running within a service. For the most part the script runs fine for days/weeks until the script hiccups and crashes. I am not so worried about the crashing part as I can resolve the cause from the error logs an patch appropriately. The issue I am facing is that sometimes when the service restart... | [
"Connection refused is an error meaning that the program on the other side of the connection is not accepting your connection attempt. Most probably it hasn't noticed you crashing, and hasn't closed its connection.\nWhat you can do is simply sleep a little while (30-60 seconds) and try again, and do this in a loop ... | [
1,
0
] | [] | [] | [
"client",
"python",
"tcp"
] | stackoverflow_0007954016_client_python_tcp.txt |
Q:
Python/Sqlite3 - is there a way to programmatically set .nullvalue?
Currently, Python is storing the string "None" for nulls returned by sqlite3. I read that you can change the default value for nulls in sqlite3 at the command line, but can you set this within the Python code?
I'd like all of my blank results to ... | Python/Sqlite3 - is there a way to programmatically set .nullvalue? | Currently, Python is storing the string "None" for nulls returned by sqlite3. I read that you can change the default value for nulls in sqlite3 at the command line, but can you set this within the Python code?
I'd like all of my blank results to look the same without having to loop through and check each value. So I ... | [
"Uses the SQL-Function COALESCE for each column of your left join.\nSELECT \n a.id, a.value, \n COALESCE(b.id, ''), COALESCE(b.value, '')\nFROM \n a \n LEFT OUTER JOIN b ON b.a_id = a.id \n\n",
"In docs there is an explanation with examples of how to make use of converters and adapters.\n"
] | [
1,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003320089_python_sqlite.txt |
Q:
How do I deploy web2py on PythonAnywhere but from Dropbox shared folder?
I have tried to use this link
How do I deploy web2py on PythonAnywhere?
to deploy Web2py on Pythonanywhere but from Dropbox's shared folder.
path = '/home/my_username/Dropbox/web2py'
The result is ...
Internal Server Error
The server enco... | How do I deploy web2py on PythonAnywhere but from Dropbox shared folder? | I have tried to use this link
How do I deploy web2py on PythonAnywhere?
to deploy Web2py on Pythonanywhere but from Dropbox's shared folder.
path = '/home/my_username/Dropbox/web2py'
The result is ...
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your ... | [
"Have you taken a look at your error logs? (in /var/log/apache/error.log, you can access these via the Web tab). You may find you have an ImportError, because a package you depend on isn't available on PythonAnywhere.\nMost packages can be installed by doing a \npip install --user package_name\n\nYou then also ne... | [
2
] | [] | [] | [
"dropbox",
"python",
"pythonanywhere",
"web2py"
] | stackoverflow_0008405289_dropbox_python_pythonanywhere_web2py.txt |
Q:
Get "flat" member output for sphinx automodule
I'm using the Sphinx autodoc extension to document a module, and I'd like to get a flat list of the module's members in the documentation output.
I tried using the following:
.. automodule:: modname
:members:
However, there are two problems with this:
It includes... | Get "flat" member output for sphinx automodule | I'm using the Sphinx autodoc extension to document a module, and I'd like to get a flat list of the module's members in the documentation output.
I tried using the following:
.. automodule:: modname
:members:
However, there are two problems with this:
It includes the module's docstring, which I don't want here.
Th... | [
"Looking at this answer to a similar question, I've found that you can use the autodoc-process-docstring event to remove the docstrings from modules appending the following code to your conf.py:\ndef skip_modules_docstring(app, what, name, obj, options, lines):\n if what == 'module':\n del lines[:]\n\ndef... | [
4
] | [] | [] | [
"autodoc",
"python",
"python_sphinx"
] | stackoverflow_0008110444_autodoc_python_python_sphinx.txt |
Q:
Comparing instances of a dict subclass
I have subclassed dict to add an extra method (so no overriding).
Now, I try to compare two of those subclasses, and I get something weird :
>>> d1.items() == d2.items()
True
>>> d1.values() == d2.values()
True
>>> d1.keys() == d2.keys()
True
>>> d1 == d2
False
EDIT
That's ... | Comparing instances of a dict subclass | I have subclassed dict to add an extra method (so no overriding).
Now, I try to compare two of those subclasses, and I get something weird :
>>> d1.items() == d2.items()
True
>>> d1.values() == d2.values()
True
>>> d1.keys() == d2.keys()
True
>>> d1 == d2
False
EDIT
That's damn weird ... I don't understand at all ! A... | [
"the problem you're seing has nothing at all to do with subclassing dict. in fact this behavior can be seen using a regular dict. The problem is how you have defined the keys you're using. A simple class like:\n>>> class Foo(object):\n... def __init__(self, value):\n... self.value = value\n... \n... ... | [
9,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008415555_python.txt |
Q:
parse youtube video likes dislikes using gadata API
I am using python and the gdata library to parse the info of a youtube video.
My code is this:
yt_service = gdata.youtube.service.YouTubeService()
entry = yt_service.GetYouTubeVideoEntry(video_id='someid')
but in the entry.rating or entry.statistics there is no ... | parse youtube video likes dislikes using gadata API | I am using python and the gdata library to parse the info of a youtube video.
My code is this:
yt_service = gdata.youtube.service.YouTubeService()
entry = yt_service.GetYouTubeVideoEntry(video_id='someid')
but in the entry.rating or entry.statistics there is no likes/dislikes
Where can I get that info from?
| [
"Once I use Python 3 and the gdata library doesn't have support for it I couldn't reproduce the results. \nBut as far as I know, the entry.rating returns a xml code with the whole statistic content of the video.\nFor a more specific result you should try entry.rating.average or entry.rating.num_raters\n",
"Lookin... | [
1,
1
] | [] | [] | [
"python",
"social_media_like",
"youtube_api"
] | stackoverflow_0008415148_python_social_media_like_youtube_api.txt |
Q:
Selecting a file from a stated directory in Python
I want to select a file by numbers at left side of listing but I can't go more than this:
import os
path="/root/Desktop"
dirList=os.listdir(path)
for fname in dirList:
print fname
selected = raw_input("Select a file above: ")
What should I do?
Example:
http:... | Selecting a file from a stated directory in Python | I want to select a file by numbers at left side of listing but I can't go more than this:
import os
path="/root/Desktop"
dirList=os.listdir(path)
for fname in dirList:
print fname
selected = raw_input("Select a file above: ")
What should I do?
Example:
http://img502.imageshack.us/img502/4407/listingy.png
Thank yo... | [
"You should use enumerate for the list and then handle input errors. Ideally this would be a function and instead of doing a break you would just return the selected file.\nimport os\n\npath=\"/root/Desktop\"\ndirList=os.listdir(path)\n\nfor i, fname in enumerate(dirList):\n print \"%d) %s\" % (i + 1, fname)\n\... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"directory_listing",
"file",
"python",
"select"
] | stackoverflow_0008416333_directory_listing_file_python_select.txt |
Q:
Playing music with Pygame unreliable
I'm trying to write a simple program to play music files with Pygame. My script is below.
import pygame
import sys
import time
FRAMERATE = 30
if len(sys.argv) < 2:
sys.exit(2)
filename = sys.argv[1]
clock = pygame.time.Clock()
pygame.init()
pygame.mixer.init(frequency... | Playing music with Pygame unreliable | I'm trying to write a simple program to play music files with Pygame. My script is below.
import pygame
import sys
import time
FRAMERATE = 30
if len(sys.argv) < 2:
sys.exit(2)
filename = sys.argv[1]
clock = pygame.time.Clock()
pygame.init()
pygame.mixer.init(frequency=44100)
pygame.mixer.music.load(filename)
... | [
"I imagine this is because the actual music playback is happening on another thread, so it sometimes hasn't finished starting at the point you first call get_busy().\nIf that's the case, it seems like a bug in either pygame or SDL_mixer (which pygame uses.)\nAs an alternative way of checking for music completion, y... | [
4
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0008205844_pygame_python.txt |
Q:
PyGTK and Tree View
I'm trying to add Tree View to my PyGTK app.
Here is how it looks in Glade:
And there is the main window code where I'm trying to add append some data to my Tree View:
import gettext
from gettext import gettext as _
gettext.textdomain('repository-notifier')
import gtk
import logging
logger = ... | PyGTK and Tree View | I'm trying to add Tree View to my PyGTK app.
Here is how it looks in Glade:
And there is the main window code where I'm trying to add append some data to my Tree View:
import gettext
from gettext import gettext as _
gettext.textdomain('repository-notifier')
import gtk
import logging
logger = logging.getLogger('repos... | [
"I think you need to add a TreeViewColumn under your ListStore with some CellRenderer to display the column you already have in the model.\nTo do that, select the TreeView widget and click on the Edit button. A dialog will be opened (similar to the one used to edit menus) so that you can add columns and renderers t... | [
2
] | [] | [] | [
"glade",
"pygtk",
"python"
] | stackoverflow_0008416992_glade_pygtk_python.txt |
Q:
generating bi-gram from a sentence in the list
i have a list which contains sentences split up from a test paragraph. I'm trying to generate bi-grams from this list of sentences. but i'm getting :
<itertools.izip object at 0x029E5080>
My code:
.....
print (words3)
print (words4)
A:
<itertools.izip obj... | generating bi-gram from a sentence in the list | i have a list which contains sentences split up from a test paragraph. I'm trying to generate bi-grams from this list of sentences. but i'm getting :
<itertools.izip object at 0x029E5080>
My code:
.....
print (words3)
print (words4)
| [
"<itertools.izip object at 0x029E5080> is not an error, it is the iterator object, if you want to print your bigrams, try this : \nprint([word for word in words3]) # or replace the list comprehension by list(words3) as pointed out by @larsmans\nprint([word for word in words4])\n\ninstead of your \nprint(words3)... | [
2,
2,
1
] | [] | [] | [
"list",
"n_gram",
"python"
] | stackoverflow_0008417082_list_n_gram_python.txt |
Q:
Why are some of my files being replicated?
I'm running a django framework and notice that when I'm editing a file I will get another file in the form "filename.extension~". What exactly is that "~" doing there and why am I generating another file?
If it's a temp file, when does it go away?
A:
Sounds like a temp ... | Why are some of my files being replicated? | I'm running a django framework and notice that when I'm editing a file I will get another file in the form "filename.extension~". What exactly is that "~" doing there and why am I generating another file?
If it's a temp file, when does it go away?
| [
"Sounds like a temp file created by your editor to support restoring if you crash/forget to save/etc. I'm sure if I googled a bit I'd even be able to figure out which editor(s) use that format for their temp files.\nHas nothing to do with django.\n",
"I'm not familiar with django, but I'm sure it's a temporary/b... | [
2,
1,
0
] | [] | [] | [
"css",
"django",
"html",
"python"
] | stackoverflow_0007112315_css_django_html_python.txt |
Q:
Using a list to synthesize a stack for recursion in Python? Examples?
For instance, this is my factorial function:
def fact(n):
if n<=1: return 1
else: return n*fact(n-1)
But it crashes when n is too high. I'd like to emulate this exact same function using a stack emulation. How would I do something lik... | Using a list to synthesize a stack for recursion in Python? Examples? | For instance, this is my factorial function:
def fact(n):
if n<=1: return 1
else: return n*fact(n-1)
But it crashes when n is too high. I'd like to emulate this exact same function using a stack emulation. How would I do something like this? What if it's not tail-recursive? Having a hard time finding explana... | [
"First off, you could make it tail recursive:\ndef tfact(n,acc=1):\n if n<=1: return acc\n else: return tfact(n-1,acc*n)\n\nBut for a more direct translation:\ndef ifact(n):\n stack = []\n while True:\n if n==1:\n while stack:\n n *= stack.pop()\n break\n ... | [
4
] | [] | [] | [
"factorial",
"python"
] | stackoverflow_0008417316_factorial_python.txt |
Q:
Checking whether a string contains some characters in python
I want to check if a string only contains A-Z and a-z and 0-9 and underscore and dash (_ -)
Any other special signs like !"#\% should not be contained
How can I write the regular expression?
and use match or ?
My strings look like these: QOIWU_W QWLJ2-1... | Checking whether a string contains some characters in python | I want to check if a string only contains A-Z and a-z and 0-9 and underscore and dash (_ -)
Any other special signs like !"#\% should not be contained
How can I write the regular expression?
and use match or ?
My strings look like these: QOIWU_W QWLJ2-1
| [
"Yes, re.match seems like a good match (pardon the pun). As for the regular expression, how about something like this: '[A-Za-z0-9-_]*'?\n",
"Using re doesn't harm in any way, but just for scientific curiosity, another approach that doesn't require you to pass through re is using sets:\n>>> valid = set('ABCDEFGHI... | [
9,
9,
1,
0
] | [
"import re\nre.search('[^a-zA-Z0-9-_]+', your_string) == None\n\nre.search() will return a match object if it comes across any instances of one or more non-alphanumeric characters and None otherwise. So you'd be checking if the string is safe.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0008417488_python.txt |
Q:
I get HTTP 500 error when use python urllib2.open
The code is like. The url is my blog and I'd like to fetch and backup my blog posts. Things goes well with my other blog posts but return 500 error with this one.
usock = urlopen("http://xiaoshuaistudio.ycool.com/post.4606754.html")
htmlSource = usock.read()
usock.... | I get HTTP 500 error when use python urllib2.open | The code is like. The url is my blog and I'd like to fetch and backup my blog posts. Things goes well with my other blog posts but return 500 error with this one.
usock = urlopen("http://xiaoshuaistudio.ycool.com/post.4606754.html")
htmlSource = usock.read()
usock.close()
Can you help me figure out how to debug a HTTP... | [
"A page content is loaded, and a 500 error is returned. But I myself can't read whether the page content is relevant.\nTo avoid error on this specific page or website you could do (WARNING this is not very pretty)\ntry:\n response = urlopen(url)\n content = response.read()\nexcept HTTPError, e:\n if e.getcode() ... | [
3,
0,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0008404938_python_urllib2.txt |
Q:
os.walk not parsing a few directories
I am kinda new to python and right now I am trying out some stuff, specifically :
recurse through all the directories and files and print the file sizes using os.walk.
My problem is, that the program does not recurse through a few directories although files are present in thos... | os.walk not parsing a few directories | I am kinda new to python and right now I am trying out some stuff, specifically :
recurse through all the directories and files and print the file sizes using os.walk.
My problem is, that the program does not recurse through a few directories although files are present in those directories. An example in my machine wou... | [
"Is it a symbolic link?\n\nos.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])\nBy default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.\nNote: Be aware that setting followl... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008417669_python.txt |
Q:
Trouble installing pyserial with macports python (python27) on Mac
I installed py-serial using macports (on my mac) but it installed python24 instead of using my existing python27.
So if use the python24 that macports py-serial installed then I can import py-serial
# /opt/local/bin/python2.4 -c 'import serial'
B... | Trouble installing pyserial with macports python (python27) on Mac | I installed py-serial using macports (on my mac) but it installed python24 instead of using my existing python27.
So if use the python24 that macports py-serial installed then I can import py-serial
# /opt/local/bin/python2.4 -c 'import serial'
But I cannot import it into python27 using either of these
# /opt/local/b... | [
"py-serial is the port for python2.4 for later versions of python use the numbered version e.g. \nsudo port install py27-serial\n\nIt is an historical error - originally they thought they should just have one version of python packages then it was realised that you could have multiple versions of python and that m... | [
5
] | [] | [] | [
"macos",
"macports",
"pyserial",
"python"
] | stackoverflow_0008417940_macos_macports_pyserial_python.txt |
Q:
Filter POST data in Django
I have a view in django that is going to save HTML data to a model, and I'm wondering how I might go about filtering it before saving it to the model? Are there built in functions for it? I know there are template filters, but I don't think those help me in this case.
What I'll be doing ... | Filter POST data in Django | I have a view in django that is going to save HTML data to a model, and I'm wondering how I might go about filtering it before saving it to the model? Are there built in functions for it? I know there are template filters, but I don't think those help me in this case.
What I'll be doing is getting the content of a div ... | [
"django takes care of safely storing strings in the database. html is a worry when displaying to the user, and django provides some help there as well, escaping html unless explicitly told not to\n",
"You can use urllib module and these functions : http://docs.python.org/library/urllib.html#utility-functions\n"
] | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008417971_django_django_models_python.txt |
Q:
Executing su user (without password) on paramiko ssh connection
I need to login in ssh to a server, do "su username" (without password) to execute some commands as that user (that have no direct login in ssh).
From the terminal it would be something like this:
root@cs01:~# su foo
foo@cs01:/root$ cd
foo@cs01:~$ ls
... | Executing su user (without password) on paramiko ssh connection | I need to login in ssh to a server, do "su username" (without password) to execute some commands as that user (that have no direct login in ssh).
From the terminal it would be something like this:
root@cs01:~# su foo
foo@cs01:/root$ cd
foo@cs01:~$ ls
I've tried to do this with paramiko (python):
import paramiko
ssh = ... | [
"Each exec_command() call happens in a new shell, so there is no state carried over from previous commands. If commands rely on a previous command to execute, you have to send them in a single statement, or as a script. If you want an interactive shell, there is the invoke_shell command, but then you need to parse ... | [
8
] | [] | [] | [
"paramiko",
"python",
"shell",
"ssh",
"su"
] | stackoverflow_0008418026_paramiko_python_shell_ssh_su.txt |
Q:
Python: what is the proper way to pass arguments to threading.Thread instance
I have extended threading.Thread - my idea is to do something like this:
class StateManager(threading.Thread):
def run(self, lock, state):
while True:
lock.acquire()
self.updateState(state)
... | Python: what is the proper way to pass arguments to threading.Thread instance | I have extended threading.Thread - my idea is to do something like this:
class StateManager(threading.Thread):
def run(self, lock, state):
while True:
lock.acquire()
self.updateState(state)
lock.release()
time.sleep(60)
I need to be able to pass reference to... | [
"pass them in the constructor, e.g.\nclass StateManager(threading.Thread):\n def __init__(self, lock, state):\n threading.Thread.__init__(self)\n self.lock = lock\n self.state = state \n\n def run(self):\n lock = self.lock\n state = self.state\n while True:... | [
8,
8
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0008418067_multithreading_python.txt |
Q:
scripting language to remove license preamble on files
I want to recursively replace the "blah blah blah"
in my License region with nothing:
#region License
blah blah blah
blah blah blah
#endregion
should be replaced with
#region License
#endregion
This should apply to all of of my .cs files in a certain directo... | scripting language to remove license preamble on files | I want to recursively replace the "blah blah blah"
in my License region with nothing:
#region License
blah blah blah
blah blah blah
#endregion
should be replaced with
#region License
#endregion
This should apply to all of of my .cs files in a certain directory (recursive). I tried this with sed, but since I am on win... | [
"Something like this?\nperl -i~ -pe 'undef $_ if /^#region License$/ .. /^#endregion$/'\n\n",
"#!/usr/bin/env python\n\nwith open('input') as fd:\n text=fd.read()\n\nold=\"\"\"#region License\nblah blah blah\nblah blah blah\n#endregion\n\n\"\"\"\n\nnew=\"\"\"#region License\n#endregion\n\n\"\"\"\n\nprint text.... | [
6,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"perl",
"python",
"regex"
] | stackoverflow_0008417869_perl_python_regex.txt |
Q:
How to draw a round pie in non square figure size in matplotlib
I would like to draw a round pie in a rectangle figure. At the moment I'm using something like:
fig = plt.figure(figsize=figsize, dpi=inch)
# plot actually
ax = fig.add_subplot(1, 1, 1)
ax.pie(value_list, labels=labels_list, **kwargs)
plt.savefig(pl... | How to draw a round pie in non square figure size in matplotlib | I would like to draw a round pie in a rectangle figure. At the moment I'm using something like:
fig = plt.figure(figsize=figsize, dpi=inch)
# plot actually
ax = fig.add_subplot(1, 1, 1)
ax.pie(value_list, labels=labels_list, **kwargs)
plt.savefig(plt_pathname)
plt.close()
If the figsize is not square ( eg. [4, 4]) t... | [
"Just use ax.set_aspect(1) or ax.axis('equal'). (Or plt.axis('equal'))\nax.axis('equal') will also set the x and y limits to be the same, as well as setting the aspect of the plot to 1. In your case, that's probably the best option.\n"
] | [
16
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008418566_matplotlib_python.txt |
Q:
Can distutils perform a dependency check without installing?
Is it possible to have distutils just run the python module dependency analysis (and possibly install missing modules) without actually installing the python module in question? I imagine a command as follows:
./setup.py check-dependencies
that would re... | Can distutils perform a dependency check without installing? | Is it possible to have distutils just run the python module dependency analysis (and possibly install missing modules) without actually installing the python module in question? I imagine a command as follows:
./setup.py check-dependencies
that would report if any dependent modules are missing on the target system.
| [
"Dependencies in Python packaging are a confusing subject. For a long time, the only standard was PEP 314, which defines the requires, provides and obsoletes parameter to the distutils.core.setup function. The elements used for these arguments are Python module name, for example provides=['xml', 'xml.utils']. Th... | [
5,
4,
0
] | [] | [] | [
"distutils",
"python",
"setup.py"
] | stackoverflow_0008405271_distutils_python_setup.py.txt |
Q:
SQLAlchemy, threads, and table not such table errors
I have a object that wraps all access to SQLAlchemy, let's called it Wrapper. I use sqlalchemy.orm.scoped_session so that any session is local to the thread this class is in as per the documentation. Now, I have a Master thread that creates an instance of Wrap... | SQLAlchemy, threads, and table not such table errors | I have a object that wraps all access to SQLAlchemy, let's called it Wrapper. I use sqlalchemy.orm.scoped_session so that any session is local to the thread this class is in as per the documentation. Now, I have a Master thread that creates an instance of Wrapper. A few Slave threads are created by the Mater and pas... | [
"Yes, either create a Wrapper in each thread, or have the Wrapper maintain a pool of sessions.\n"
] | [
1
] | [] | [] | [
"multithreading",
"python",
"sqlalchemy"
] | stackoverflow_0008418946_multithreading_python_sqlalchemy.txt |
Q:
Value Error: No back-end
trying to use pyusb 1.0 on windows 7 with python 2.7 and libusb 1.2.5
Have installed everything fine, libusb is working as I am getting endpoint information from the test program but when I run this code from the pyusb tutorial -
import usb.core
import usb.util
import sys
dev = usb.core.... | Value Error: No back-end | trying to use pyusb 1.0 on windows 7 with python 2.7 and libusb 1.2.5
Have installed everything fine, libusb is working as I am getting endpoint information from the test program but when I run this code from the pyusb tutorial -
import usb.core
import usb.util
import sys
dev = usb.core.find(idVendor=0x20A4, idProduc... | [
"The latest pyusb trunk is supporting libusb 0.x and libusb 1.0. Look like it's not supporting 1.2, and you can see it in the usb/backend/libusb10.py in the get_backend() method.\nMaybe you can use an older version of libusb, or contribute to the 1.0 backend :)\n"
] | [
0
] | [] | [] | [
"python",
"pyusb",
"usb"
] | stackoverflow_0008418947_python_pyusb_usb.txt |
Q:
Why this error from urllib?
I get a strange error when using urllib:
INFO 2011-12-07 07:02:45,101 main.py:884] urlhttp://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false
WARNING 2011-12-07 07:02:45,103 urlfetch_stub.py:428] Stripped prohibited headers from URLFetch request: ['Host']... | Why this error from urllib? | I get a strange error when using urllib:
INFO 2011-12-07 07:02:45,101 main.py:884] urlhttp://maps.googleapis.com/maps/api/geocode/json?latlng=59.3333,18.05&sensor=false
WARNING 2011-12-07 07:02:45,103 urlfetch_stub.py:428] Stripped prohibited headers from URLFetch request: ['Host']
ERROR 2011-12-07 07:02:45,210... | [
"This seems to be a bug with the SDK. I was able to replicate the exact same behavior. Is there any reason you are using urllib2 instead of urllib?\nUsing Python2.7 and SDK 1.6.1, I tested the following:\nimport urllib \nurl = 'http://maps.googleapis.com/maps/api/geocode/json' + \\\n '?latlng={},{}&sensor=f... | [
14,
2
] | [] | [] | [
"google_app_engine",
"python",
"urllib2"
] | stackoverflow_0008411622_google_app_engine_python_urllib2.txt |
Q:
Use Python to resize the active window to half the screen size in Linux?
This question is a follow up to: Manipulate window size in linux via compiled code?
Per the title, I want to resize the active window to half the screen size (either on the left or the right of the screen. I can do this with a bash script as ... | Use Python to resize the active window to half the screen size in Linux? | This question is a follow up to: Manipulate window size in linux via compiled code?
Per the title, I want to resize the active window to half the screen size (either on the left or the right of the screen. I can do this with a bash script as follows (per the answer to the previous question):
#!/bin/bash
w_h=$(xrandr |... | [
"The lag you getting is caused by xrandr command it's going to be slow anyway. You can reduce this time by parsing output of xdpyinfo | grep 'dimensions:'. From python you could call this command using subprocess.Popen.\n"
] | [
0
] | [] | [] | [
"linux",
"python",
"window_management"
] | stackoverflow_0005444377_linux_python_window_management.txt |
Q:
Remove single quotes from python list item
Actually quite simple question:
I've a python list like:
['1','2','3','4']
Just wondering how can I strip those single quotes?
I want [1,2,3,4]
A:
Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward... | Remove single quotes from python list item | Actually quite simple question:
I've a python list like:
['1','2','3','4']
Just wondering how can I strip those single quotes?
I want [1,2,3,4]
| [
"Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this:\nmap(int, your_list)\n\nand\n[int(value) for value in your_list]\n\nSee the documentation on map() and list comprehensions for more info.\nIf you want to leave the items in yo... | [
22,
5,
4
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008419817_list_python.txt |
Q:
Converting a cURL command to Python's urllib2
guys! I'm currently working with an API that uses the following cURL line:
curl -vF "files[]=@file.zip" "http://s5.example.com/123"
I'm not interested in using other libraries such as pycurl, because I really only need to convert a line or two. I really appreciate y... | Converting a cURL command to Python's urllib2 | guys! I'm currently working with an API that uses the following cURL line:
curl -vF "files[]=@file.zip" "http://s5.example.com/123"
I'm not interested in using other libraries such as pycurl, because I really only need to convert a line or two. I really appreciate your help!
| [
"This request posts the file contents in a file upload field.\nThe http body of a POST request uploading a file is tricky to assemble - for ordinary text fields, one can just send a dictionary in the \"data=\" parameter to a urllib2.urlopen call, and the fields will be posted.\nFile uploads, though, need to send a ... | [
2,
2
] | [] | [] | [
"curl",
"python",
"urllib",
"urllib2"
] | stackoverflow_0008413078_curl_python_urllib_urllib2.txt |
Q:
Logging stdout and stderr to log file using Python 'with' statement
I want to log the std output of a chunk of Python code to a file, using the 'with' statement:
with log_to_file('log'):
# execute code
Is the easiest way to do this to define the log_to_file manually, e.g.:
import sys
class log_to_file():
... | Logging stdout and stderr to log file using Python 'with' statement | I want to log the std output of a chunk of Python code to a file, using the 'with' statement:
with log_to_file('log'):
# execute code
Is the easiest way to do this to define the log_to_file manually, e.g.:
import sys
class log_to_file():
def __init__(self, filename):
self.f = open(filename, 'wb')
... | [
"The only thing I could suggest is to use the contextmanager decorator but I'm not convinced this is really better.\nfrom contextlib import contextmanager\n@contextmanager\ndef stdouterrlog(logfile):\n with open(logfile, 'wb') as lf:\n stdout = sys.stdout\n stderr = sys.stderr\n sys.stdout = lf\n sys.s... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008419018_python.txt |
Q:
Building pymssql on OS X
Attempting to build any version of pymssql on Mac OS X 10.6.6. Both versions 1.0.2 (stable) and 1.9.909 (trunk) build and install, but return the following error on import. Has anyone had success with this project? (note I am using pyodbc in the meantime, but would like to eliminate the OD... | Building pymssql on OS X | Attempting to build any version of pymssql on Mac OS X 10.6.6. Both versions 1.0.2 (stable) and 1.9.909 (trunk) build and install, but return the following error on import. Has anyone had success with this project? (note I am using pyodbc in the meantime, but would like to eliminate the ODBC layer if possible)
Python 2... | [
"fab (fabric) script I wrote to do this\nimport os\nfrom fabric.api import local\n\ndef prep_dev_env():\n os.chdir('/tmp/')\n local('cvs -d:pserver:freetds.cvs.sourceforge.net:/cvsroot/freetds login')\n local('cvs -z3 -d:pserver:freetds.cvs.sourceforge.net:/cvsroot/freetds checkout -P freetds')\n os.chd... | [
1,
1
] | [] | [] | [
"macos",
"pymssql",
"python"
] | stackoverflow_0006398292_macos_pymssql_python.txt |
Q:
Python - passing a string as input to a command
Possible Duplicate:
Python module to shellquote/unshellquote?
I am trying to pass a string's value into a command as input, in Python for executing a bash command. I currently have somthing like this:
cmd = 'echo ' + <StringValue> + ' | command'
output = commands.g... | Python - passing a string as input to a command |
Possible Duplicate:
Python module to shellquote/unshellquote?
I am trying to pass a string's value into a command as input, in Python for executing a bash command. I currently have somthing like this:
cmd = 'echo ' + <StringValue> + ' | command'
output = commands.getOutput(cmd)
but it does not work because my strin... | [
"The commands module is currently deprecated since python 2.6 and removed in python 3, you should use the subprocess module instead.\nThe replacing shell pipeline section in the python documentation should provide the information you need.\nEdit: As a follow-up to your comment question, you could use the following ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008420307_python.txt |
Q:
Python BZ2 Compressor - compress() not returning anything
I am trying to compress a data stream using pythons bz2compressor class.
The documentation says bz2compressor.compress() should return chunks of compressed data "whenever possible" but I don't get anything
I get ALL my compressed data when I flush() (I hav... | Python BZ2 Compressor - compress() not returning anything | I am trying to compress a data stream using pythons bz2compressor class.
The documentation says bz2compressor.compress() should return chunks of compressed data "whenever possible" but I don't get anything
I get ALL my compressed data when I flush() (I have tried with files 2GB+) still nothing.
Is there a way I can se... | [
"\nI get ALL my compressed data when I flush() (I have tried with files 2GB+) still nothing.\n\nThere's a trick to working with compressors.\nI'll bet that your 2GB+ file was not very random. Random data doesn't compress well. Orderly data compresses to a very small size.\nFor example\n>>> import bz2\n>>> c=bz2.B... | [
3
] | [] | [] | [
"buffer",
"bzip2",
"compression",
"python",
"stream"
] | stackoverflow_0008246769_buffer_bzip2_compression_python_stream.txt |
Q:
Extracting information from a webpage with python
Would it be possible to extract scores and goals for/against with python from a webpage like: http://www.uscho.com/standings/division-i-men/2011-2012/ ? My problem lies in the fact that the tables are structured funky. Is there any resource that could help me out w... | Extracting information from a webpage with python | Would it be possible to extract scores and goals for/against with python from a webpage like: http://www.uscho.com/standings/division-i-men/2011-2012/ ? My problem lies in the fact that the tables are structured funky. Is there any resource that could help me out with my problem?
| [
"Have you tried Beautiful Soup?\n",
"mechanize and BeatifulSoup\n",
"The example web-page is pretty easy to parse with lxml.\nHere's a basic script to get you started:\nfrom urllib2 import urlopen\nfrom lxml import etree\n\nurl = 'http://www.uscho.com/standings/division-i-men/2011-2012/'\n\ntree = etree.HTML(ur... | [
2,
1,
1
] | [] | [] | [
"extraction",
"python",
"web"
] | stackoverflow_0008419506_extraction_python_web.txt |
Q:
How to manage db connections using webpy with SQLObject?
Web.py has its own database API, web.db. It's possible to use SQLObject instead, but I haven't been able to find documentation describing how to do this properly. I'm especially interested in managing database connections. It would be best to establish a c... | How to manage db connections using webpy with SQLObject? | Web.py has its own database API, web.db. It's possible to use SQLObject instead, but I haven't been able to find documentation describing how to do this properly. I'm especially interested in managing database connections. It would be best to establish a connection at the wsgi entry point, and reuse it. Webpy cookbo... | [
"As far as I understand the SQLAlchemy example given, a processor is used, that is, a session is created for each connection and committed when the handler is complete (or rolled back if an error has occurred).\nI don't see any simple way to do what you propose, i.e. open a connection at the WSGI entry point. You ... | [
0
] | [] | [] | [
"database",
"python",
"sqlobject",
"web.py",
"web_frameworks"
] | stackoverflow_0008413978_database_python_sqlobject_web.py_web_frameworks.txt |
Q:
Python Bottle Image part 2
im unsure, if im not understanding the bottle tutorial correctly but this code:
from bottle import static_file
@route('/images/<filename:re:.*\.png>')
def send_image(filename):
return static_file(filename, root='/path/to/image/files', mimetype='image/png')
is supposed to look thro... | Python Bottle Image part 2 | im unsure, if im not understanding the bottle tutorial correctly but this code:
from bottle import static_file
@route('/images/<filename:re:.*\.png>')
def send_image(filename):
return static_file(filename, root='/path/to/image/files', mimetype='image/png')
is supposed to look through the folder for that image na... | [
"Well, answering the question you asked in the comment...\n@route('/images/:filename')\ndef send_image(filename):\n return static_file(filename + '.png', root='/path/to/image/files', mimetype='image/png')\n\n"
] | [
3
] | [] | [] | [
"bottle",
"image",
"python",
"static"
] | stackoverflow_0008415313_bottle_image_python_static.txt |
Q:
How to tell if Python/Django unit tests are hitting the network?
I was recently added to a project to add test coverage (Python/Django unittest module). This app deals heavily with web APIs and JSON requests and such, and part of my job is to make sure that none of the existing or future tests require live networ... | How to tell if Python/Django unit tests are hitting the network? | I was recently added to a project to add test coverage (Python/Django unittest module). This app deals heavily with web APIs and JSON requests and such, and part of my job is to make sure that none of the existing or future tests require live network data to function.
What I'd like to know is - is there a way I can ... | [
"You could patch all methods that are used to get a url and log every attempt, fire an event or whatever it's more convenient for you to detect that.\nLook for example at dingus mocking library. In the patching section in the pypi page, there's an example that patches urllib2.urlopen that can be useful. I remember ... | [
3,
1
] | [] | [] | [
"django",
"python",
"tdd",
"unit_testing"
] | stackoverflow_0008420710_django_python_tdd_unit_testing.txt |
Q:
Turn off buffering
Where is the buffer in this following ... and how do I turn it off?
I am writing out to stdout in a python program like so:
for line in sys.stdin:
print line
There is some buffering going on here:
tail -f data.txt | grep -e APL | python -u Interpret.py
I tried the following to shake off po... | Turn off buffering | Where is the buffer in this following ... and how do I turn it off?
I am writing out to stdout in a python program like so:
for line in sys.stdin:
print line
There is some buffering going on here:
tail -f data.txt | grep -e APL | python -u Interpret.py
I tried the following to shake off possible buffering ... wit... | [
"file.readlines() and for line in file have internal buffering which is not affected by -u option (see -u option note). Use\nwhile True:\n l=sys.stdin.readline()\n sys.stdout.write(l)\n\ninstead.\nBy the way, sys.stdout is line-buffered by default if it points to terminal and sys.stderr is unbuffered (see stdio... | [
12,
6,
3,
0
] | [] | [] | [
"bash",
"buffering",
"linux",
"python"
] | stackoverflow_0008416586_bash_buffering_linux_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.