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:
python fails to fetch a whole web page
I am working on a scrapy project to scrape some data on http://58.com
I find some divs are missing from the page when using scrapy to scrape it.
I think this may have something to do with request headers, so I copy the user-agent of Firefox to fake one, just to find it fails.... | python fails to fetch a whole web page | I am working on a scrapy project to scrape some data on http://58.com
I find some divs are missing from the page when using scrapy to scrape it.
I think this may have something to do with request headers, so I copy the user-agent of Firefox to fake one, just to find it fails.
what can be the problem and how can I solve... | [
"use the urllib2, try this \nreq.add_header('User-Agent', \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)\")\nI can pass the request\n",
"There is a python binding of libcurl named pycurl. I use pycurl to emulate human behaviors to visit a website and it works well. For html parsing,... | [
1,
0
] | [] | [] | [
"python",
"scrapy",
"web_crawler"
] | stackoverflow_0006826261_python_scrapy_web_crawler.txt |
Q:
How to convert this particular json string into a python dictionary?
How do I convert this string ->
string = [{"name":"sam"}]
into a python dictionary like so ->
data = {
"name" : "sam"
}
A:
In [1]: import json
In [2]: json.loads('[{"name":"sam"}]')
Out[2]: [{u'name': u'sam'}]
This returns a... | How to convert this particular json string into a python dictionary? | How do I convert this string ->
string = [{"name":"sam"}]
into a python dictionary like so ->
data = {
"name" : "sam"
}
| [
"In [1]: import json\n\nIn [2]: json.loads('[{\"name\":\"sam\"}]')\nOut[2]: [{u'name': u'sam'}]\n\nThis returns a list, the first element of which is the desired dictionary.\n",
"string = [{ \"name\" : \"sam\" }]\ndata = string[0]\n\nnow the data is the dict\n"
] | [
15,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0006826495_json_python.txt |
Q:
Running Django development server
I'm trying to create and run a project.
I used the following article:
https://docs.djangoproject.com/en/dev/intro/tutorial01/?from=olddocs
When I'm running the following command
C:\django\mysite>python manage.py runserver
This error shows up:
Traceback (most recent call last):
... | Running Django development server | I'm trying to create and run a project.
I used the following article:
https://docs.djangoproject.com/en/dev/intro/tutorial01/?from=olddocs
When I'm running the following command
C:\django\mysite>python manage.py runserver
This error shows up:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
... | [
"Here is what I would do.\nTry to use virtualenv.\nthere might be some old python modules that mess up your django for some reason.\nSo use virtualenv to create a fresh python.\nand install django with pip install.\nif it solves the problem its definetely your system python that is messing things up a little bit.\n... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006826619_django_python.txt |
Q:
Decoding a string in python ... with _\x08__\x08_d\x08de\x08el\x08li\x08it\x08te\x08em in it
I have some strings with all this kind of characters in it which also has normal letters ,
and i want to transform all the "wired" characters in they're normal representation .
So my question is :
Is there a Pythonic way... | Decoding a string in python ... with _\x08__\x08_d\x08de\x08el\x08li\x08it\x08te\x08em in it | I have some strings with all this kind of characters in it which also has normal letters ,
and i want to transform all the "wired" characters in they're normal representation .
So my question is :
Is there a Pythonic way of doing this ?
I have a string for example this one :
Mymethods defined here:
|
| __add__(.... | [
"Some (very old) bits of software used to simulate bold text on printers (such as daisy wheel of golfball typewriters) but printing a character then a backspace then the same character again. It looks like your text is an example of this.\nThat means you need to remove not just the backspace but also the character ... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0006827011_python.txt |
Q:
How can PyImport_AppendInittab fail?
According to the official docs, PyImport_AppendInittab will return -1 on failure. It does not, however, specify why this function would fail.
I'd like to know if it can only fail due to the programmer's fault (incorrect arguments, not being called at the right time, etc), or if... | How can PyImport_AppendInittab fail? | According to the official docs, PyImport_AppendInittab will return -1 on failure. It does not, however, specify why this function would fail.
I'd like to know if it can only fail due to the programmer's fault (incorrect arguments, not being called at the right time, etc), or if it can also fail because of some other fa... | [
"According to the docs, PyImport_AppendInittab() is a convenience wrapper around PyImport_ExtendInittab() and returns -1 \"if the table could not be extended\". Furthermore, PyImport_ExtendInittab() returns -1 \"if insufficient memory could be allocated to extend the internal table\". Both functions \"should be c... | [
6
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0006827185_c_c++_python.txt |
Q:
python dictionary keys
I'm having a bit of a problem, don't even know if this is doable. I have a number of launchers that each have a interface defined with the expected inputs. The input values come as a dictionary. For example:
dict_key = str(req_input[0]['name'])
data = dict(dict_key = value)
Now req... | python dictionary keys | I'm having a bit of a problem, don't even know if this is doable. I have a number of launchers that each have a interface defined with the expected inputs. The input values come as a dictionary. For example:
dict_key = str(req_input[0]['name'])
data = dict(dict_key = value)
Now req_input[0]['name'] is the key... | [
"The best way to do this is simply using the dict literal {}:\ndata = {dict_key: value}\n\n\nOther ways would be\ndata = dict({dict_key: value})\n\nor\ndata = dict()\ndata[dict_key] = value\n\nbut these are longer so stay with the first one.\n",
"Another way is:\ndata = {}\ndata[req_input[0]['name']] = value\n\nT... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006827220_python.txt |
Q:
reverse() does not work on a Python literal?
Why doesn't this work in Python?
>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse()
None
I expected to get back the list in reverse order.
A:
>>> a = [3, 4, 5]
>>> print a.reverse()
None
>>> a
[5, 4, 3]
>>>
It's because reverse() does not return the list, rather i... | reverse() does not work on a Python literal? | Why doesn't this work in Python?
>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse()
None
I expected to get back the list in reverse order.
| [
">>> a = [3, 4, 5]\n>>> print a.reverse()\nNone\n>>> a\n[5, 4, 3]\n>>>\n\nIt's because reverse() does not return the list, rather it reverses the list in place. So the return value of a.reverse() is None which is shown in the print.\n",
"If you want it to return a new list in reverse order, you can use [::-1]\n>>... | [
52,
23,
22,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0006827413_python.txt |
Q:
How to filter a dict to contain only keys in a given list?
Both very new to Python and stackoverflow. Thank you for your patience, and your help.
I would like to filter a dict according to the content of a list like this:
d={'d1':1, 'd2':2, 'd3':3}
f = ['d1', 'd3']
r = {items of d where the key is in f}
Is this... | How to filter a dict to contain only keys in a given list? | Both very new to Python and stackoverflow. Thank you for your patience, and your help.
I would like to filter a dict according to the content of a list like this:
d={'d1':1, 'd2':2, 'd3':3}
f = ['d1', 'd3']
r = {items of d where the key is in f}
Is this absurd?
If not, what would be the right syntax?
Thank you for y... | [
"Assuming you want to create a new dictionary (for whatever reason):\nd = {'d1':1, 'd2':2, 'd3':3}\nkeys = ['d1', 'd3']\n\nfiltered_d = dict((k, d[k]) for k in keys if k in d)\n# or: filtered_d = dict((k, d[k]) for k in keys)\n# if every key in the list exists in the dictionary\n\n",
"You can iterate over the lis... | [
22,
5
] | [] | [] | [
"dictionary",
"filter",
"list",
"python"
] | stackoverflow_0006827834_dictionary_filter_list_python.txt |
Q:
NameError: global name 'thing' is not defined
I don't think there is quite the need for the continued downvoting, I am just trying to learn here!
One.py
from two import *
ADooDah = Doodah()
something = Thing(ADooDah)
something.DoThis()
something.DoThat
something.DoAnother
if (something.has_done_stuff() == True)
... | NameError: global name 'thing' is not defined | I don't think there is quite the need for the continued downvoting, I am just trying to learn here!
One.py
from two import *
ADooDah = Doodah()
something = Thing(ADooDah)
something.DoThis()
something.DoThat
something.DoAnother
if (something.has_done_stuff() == True)
self.SomeFunction
Two.py
class Thing(var):
... | [
"Something = Thing(ADooDah)\n\nthing.DoThis()\n\nYour thing is called Something.\nAlso, your class Thing has none of the methods you are calling/not calling (missing parens). This is pretty much non-sense code. \n",
"There are a few issues:\nYou claim Thing is defined in Two.py. If so, you need to import it thus:... | [
3,
2,
1
] | [] | [] | [
"python",
"scope",
"while_loop"
] | stackoverflow_0006827730_python_scope_while_loop.txt |
Q:
Quarantine mails before sending with smtplib
I'm sending mails form a Python script with smtplib. I'm wary that there may be unforeseen bugs in my script that would cause it to erroneously send mails to all customers from the production database. Is there any way to temporarily store the mails before sending them?... | Quarantine mails before sending with smtplib | I'm sending mails form a Python script with smtplib. I'm wary that there may be unforeseen bugs in my script that would cause it to erroneously send mails to all customers from the production database. Is there any way to temporarily store the mails before sending them? Another mail library maybe?
I still want to send... | [
"Some suggestions:\n1: Set up a local Postfix server and configure it to put all e-mails on hold. Then manually inspect the mail queues after running your script. Release the e-mails when you see that everything is good.\nI am no postfix expert, so I'm unsure about the details. Here's a man page with some info: htt... | [
0
] | [] | [] | [
"email",
"python",
"smtplib"
] | stackoverflow_0006828219_email_python_smtplib.txt |
Q:
How to efficiently do many tasks a "little later" in Python?
I have a process, that needs to perform a bunch of actions "later" (after 10-60 seconds usually). The problem is that those "later" actions can be a lot (1000s), so using a Thread per task is not viable. I know for the existence of tools like gevent and ... | How to efficiently do many tasks a "little later" in Python? | I have a process, that needs to perform a bunch of actions "later" (after 10-60 seconds usually). The problem is that those "later" actions can be a lot (1000s), so using a Thread per task is not viable. I know for the existence of tools like gevent and eventlet, but one of the problem is that the process uses zeromq f... | [
"consider using a priority queue with one or more worker threads to service the tasks. The main thread can add work to the queue, with a timestamp of the soonest it should be serviced. Worker threads pop work off the queue, sleep until the time of priority value is reached, do the work, and then pop another item ... | [
19,
12,
7,
3,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"concurrency",
"eventlet",
"gevent",
"python"
] | stackoverflow_0006694338_concurrency_eventlet_gevent_python.txt |
Q:
Split dictionary of lists into single lists
How can I split a dictionary of two lists into two different lists?
The structure of the dictionary is following:
{'key1': ['PTRG0097',
'CPOG0893',
'MMUG0444',
'BTAG0783'],
'key2': ['CPOG0893',
'MMUG0444',
'PPYG0539',
... | Split dictionary of lists into single lists | How can I split a dictionary of two lists into two different lists?
The structure of the dictionary is following:
{'key1': ['PTRG0097',
'CPOG0893',
'MMUG0444',
'BTAG0783'],
'key2': ['CPOG0893',
'MMUG0444',
'PPYG0539',
'BTAG0083']}
| [
"That's how we unroll:\n>>> d = {'key1': ['PTRG0097', 'CPOG0893', 'MMUG0444', 'BTAG0783'], 'key2': ['CPOG0893', 'MMUG0444', 'PPYG0539', 'BTAG0083']}\n>>> l1, l2 = d.values() # or this: d['key1'], d['key2']\n>>> l1\n['PTRG0097', 'CPOG0893', 'MMUG0444', 'BTAG0783']\n>>> l2\n['CPOG0893', 'MMUG0444', 'PPYG0539', 'BTAG0... | [
2,
2,
2
] | [
"Well you cna try something like :\nl1=l2=[]\nfor key, val in dict.items()\n l1.append(key)\n l2.append(val)\n\nas Each dict entry has key and val you can use items() method of dict \nor \n l = [ for val in d.values() ]\nRegards\n"
] | [
-1
] | [
"dictionary",
"list",
"python",
"split"
] | stackoverflow_0006828768_dictionary_list_python_split.txt |
Q:
Radical Use of Admin's Interface
I was wondering....
Is it possible in Django the creation of an Admin page completely independent of a model or even a app?
I was thinking in something like a dashboard or interface of control, that only gather data from other models but does not have it's own.
If so, any further r... | Radical Use of Admin's Interface | I was wondering....
Is it possible in Django the creation of an Admin page completely independent of a model or even a app?
I was thinking in something like a dashboard or interface of control, that only gather data from other models but does not have it's own.
If so, any further reference or link?
Thanks
| [
"As what Ben said, you can do this by creating a view function for your dashboard page. The view function itself can live anywhere within your project, but Django needs to know where it is (i.e. unlike the Django's default model admin views, you need to define your view in a urls.py file that is known to Django).\n... | [
3,
2,
2,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004975563_django_django_admin_python.txt |
Q:
Any Python modules out there that do anything with HTTP_ACCEPT_LANGAUGE?
I have read that decoding the potentially long string which can be returned from a website for HTTP_ACCEPT_LANGUAGE is not necessarily straightforward. Are there any packages out there in Python that try to do anything with this. I, in part... | Any Python modules out there that do anything with HTTP_ACCEPT_LANGAUGE? | I have read that decoding the potentially long string which can be returned from a website for HTTP_ACCEPT_LANGUAGE is not necessarily straightforward. Are there any packages out there in Python that try to do anything with this. I, in particular, am interested in getting at least the list of languages that are accep... | [
"some time ago I took this snippet from tweetengine \nIt's worked well for me. Hope it helps.\n"
] | [
1
] | [] | [] | [
"http",
"http_accept_language",
"http_headers",
"python"
] | stackoverflow_0006684091_http_http_accept_language_http_headers_python.txt |
Q:
How to delete a variable in a Scientific.IO.NetCDF.NetCDFFile?
Is it possible to delete a variable from a Scientific.IO.NetCDF.NetCDFFile? If a file is opened like so:
nc = Scientific.IO.NetCDF.NetCDFFile("File.nc", "a")
neither a
del nc.variables["var"]
nor a
nc.variables["var"] = None
will delete the variable... | How to delete a variable in a Scientific.IO.NetCDF.NetCDFFile? | Is it possible to delete a variable from a Scientific.IO.NetCDF.NetCDFFile? If a file is opened like so:
nc = Scientific.IO.NetCDF.NetCDFFile("File.nc", "a")
neither a
del nc.variables["var"]
nor a
nc.variables["var"] = None
will delete the variable var.
Thx in advance for any insight.
| [
"The simple answer is that you can not delete a variable. This is a \"feature\" of the NetCDF C-API and is not a shortcoming of Scientific.IO.NetCDF or any of the other python netcdf modules. \nFrom the official NetCDF user guide:\nAttributes are more dynamic than variables or dimensions; they can be deleted and ha... | [
9
] | [] | [] | [
"netcdf",
"python"
] | stackoverflow_0006816613_netcdf_python.txt |
Q:
convert d-m-Y in python
I want to convert date from one format to another.Let's say, I have some date:
February 27, 1820
April 3, 1885
And I want to convert it:
27 February 1820
3 April 1885
I tried but getting error:
dt = "February 12, 1809"
dt = datetime.strptime('%d %b %Y')
Any kind of help will be greatl... | convert d-m-Y in python | I want to convert date from one format to another.Let's say, I have some date:
February 27, 1820
April 3, 1885
And I want to convert it:
27 February 1820
3 April 1885
I tried but getting error:
dt = "February 12, 1809"
dt = datetime.strptime('%d %b %Y')
Any kind of help will be greatly appreciated.
| [
"Nor time.strftime nor datetime.datetime.strftime don't accept year values less then 1900. So it looks like there is job for re (although it is a bad style to use it for such tasks):\n>>> import re\n>>> s = 'February 27, 1820'\n>>> month, day, year = re.findall('(\\w+) (\\d+), (\\d+)', s)[0] \n>>> '%s %s %s' % (d... | [
2,
1,
1,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0006829033_datetime_python.txt |
Q:
python multiprocess pinning
I am currently using python multiprocess to do some simple parallel programming.
I use an async decorator
def async(decorated):
module = getmodule(decorated)
decorated.__name__ += '_original'
setattr(module, decorated.__name__, decorated)
def send(*args, **opts):
... | python multiprocess pinning | I am currently using python multiprocess to do some simple parallel programming.
I use an async decorator
def async(decorated):
module = getmodule(decorated)
decorated.__name__ += '_original'
setattr(module, decorated.__name__, decorated)
def send(*args, **opts):
return async.pool.apply_async(d... | [
"If the function being called by apply_async (e.g. evalfunc) finishes very quickly, then all worker processes in the pool may not be utilized. \nIf that is indeed your situation, then you need to pass more data to each call to evalfunc so each process has more to chew on.\n"
] | [
1
] | [] | [] | [
"concurrency",
"multiprocessing",
"numpy",
"python"
] | stackoverflow_0006829351_concurrency_multiprocessing_numpy_python.txt |
Q:
Python-Oracle Passing in a Cursor Out Parameter
I am trying to call a stored procedure between python and an oracle db. The problem I am having is passing a cursor out-parameter.
The Oracle stored procedure is essentially:
create or replace procedure sp_procedure(
cid int,
rep_date date,
ret out sys_r... | Python-Oracle Passing in a Cursor Out Parameter | I am trying to call a stored procedure between python and an oracle db. The problem I am having is passing a cursor out-parameter.
The Oracle stored procedure is essentially:
create or replace procedure sp_procedure(
cid int,
rep_date date,
ret out sys_refcursor
) is
begin
open ret for
select
...
... | [
"After a couple of hours of googling and trail/error, here's the solution:\ncid = 1\nrep_date = date(2011,06,30)\n\nl_cur = curs.var(cx_Oracle.CURSOR)\nl_query = curs.callproc('sp_procedure', (cid,rep_date,l_cur))\n\nl_results = l_query[2]\n\nfor row in l_results:\n print row\n\n# Column Specs\nfor row in l_resu... | [
12,
0
] | [] | [] | [
"cx_oracle",
"database_cursor",
"oracle",
"python"
] | stackoverflow_0006821372_cx_oracle_database_cursor_oracle_python.txt |
Q:
Python - unexpected behaviour when using a named constructor argument with empty list default value
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm obviously missing something here: can anyone explain why t1 "mysteriously" acquires the self.thelist value of t2? What am I doin... | Python - unexpected behaviour when using a named constructor argument with empty list default value |
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm obviously missing something here: can anyone explain why t1 "mysteriously" acquires the self.thelist value of t2? What am I doing wrong?
>>> class ThingyWithAList(object):
... def __init__(self, alist=[]):
... super(Thin... | [
"Because the default argument 'alist=[]', creates only one list, once, when the module is read. This single list becomes the default argument for that __init__\", and is shared by all your Thingys.\nTry using None as a dummy symbol meaning \"make a new empty list here\". E.g.\ndef __init__(self, alist=None):\n ... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0006829364_python.txt |
Q:
App Engine with Python: How to convert pdf file into different jpeg images
I'm using Google App Engine with Python.
I would like to know how to convert a pdf file into different jpeg images (one for each page). Is it possible?
I found an opensource pdf library: reportlab but it looks like they don't have such a fe... | App Engine with Python: How to convert pdf file into different jpeg images | I'm using Google App Engine with Python.
I would like to know how to convert a pdf file into different jpeg images (one for each page). Is it possible?
I found an opensource pdf library: reportlab but it looks like they don't have such a feature in their API. Am I wrong?
Thanks in advance
| [] | [] | [
"You want a library called PythonMagick, which can be found here.\n"
] | [
-1
] | [
"google_app_engine",
"jpeg",
"pdf",
"python"
] | stackoverflow_0006829571_google_app_engine_jpeg_pdf_python.txt |
Q:
Python's paramiko with threading, strange delay
In order to check the existence of a certain file on many servers, I've created a threaded class that uses paramiko to execute a remote command using ssh. The results of each thread are inserted into a thread safe Queue.Queue, and I read its contents after all the jo... | Python's paramiko with threading, strange delay | In order to check the existence of a certain file on many servers, I've created a threaded class that uses paramiko to execute a remote command using ssh. The results of each thread are inserted into a thread safe Queue.Queue, and I read its contents after all the join()s are done. This is the main part of the thread:
... | [
"The timeout is just for the TCP connect, not the entire operations on the connection.\nI would expect the __init__ to be called on the original thread - only the run() method runs on the new thread. So your time might be invalid.\nSSH involved a certain amount of processing for the encryption and setup of the tunn... | [
3
] | [] | [] | [
"multithreading",
"paramiko",
"python"
] | stackoverflow_0006829120_multithreading_paramiko_python.txt |
Q:
CPython is bytecode interpreter?
I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture?
Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different f... | CPython is bytecode interpreter? | I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture?
Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different from CPython (except they are implement... | [
"CPython is the implementation of Python in C. It's the first implementation, and still the main one that people mean when they talk about Python. It compiles .py files to .pyc files. .pyc files contain bytecodes. The CPython implementation also interprets those bytecodes.\nCPython is not written in C++, it is ... | [
16,
14,
8
] | [] | [] | [
"bytecode",
"c++",
"cpython",
"interpreter",
"python"
] | stackoverflow_0001644619_bytecode_c++_cpython_interpreter_python.txt |
Q:
the proper method for making a DB connection available across many python modules
I want to make a single database object available across many python modules.
For a related example, I create globl.py:
DOCS_ROOT="c:\docs" ## as an example
SOLR_BASE="http://localhost:8636/solr/"
Any other module which needs it can... | the proper method for making a DB connection available across many python modules | I want to make a single database object available across many python modules.
For a related example, I create globl.py:
DOCS_ROOT="c:\docs" ## as an example
SOLR_BASE="http://localhost:8636/solr/"
Any other module which needs it can do a
from globl import DOCS_ROOT
Now this example aside, I want to do the same thing... | [
"Even if the import doesn't run the code multiple times, this is definitely not the correct way.\nYou should instead hide the process of obtaining a connection or cursor behind a function. You can then implement this function using either a Singleton or Object Pool design pattern. \nSo it would be something like t... | [
49,
5,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0006829675_mysql_python.txt |
Q:
Should a validate method throw an exception?
I've implemented a little validation library which is used like this:
domain_object.validate()
# handle validation errors in some way ...
if domain_object.errors:
for error in domain_object.errors:
print(error)
validate() performs the checks and populates ... | Should a validate method throw an exception? | I've implemented a little validation library which is used like this:
domain_object.validate()
# handle validation errors in some way ...
if domain_object.errors:
for error in domain_object.errors:
print(error)
validate() performs the checks and populates a list called errors.
I know from other validation... | [
"No, I wouldn't think that a validation method should throw an exception.\nThat would create a bit of an anti-pattern, as the client code calling the method would reasonably expect an exception to be thrown, and would then need to catch the exception. Since it's generally recommended that exceptions not be used for... | [
10,
6
] | [] | [] | [
"error_handling",
"exception",
"python",
"validation"
] | stackoverflow_0006828160_error_handling_exception_python_validation.txt |
Q:
Using Python Tk as a front-end for threaded code
I know that Python’s Tk interface has some problems when using threads, and I’ve already run into problems with it. My idea is now to use a Queue.Queue to somehow pass events to the Tk mainloop, similarly to the following example.
from Tkinter import *
import Queue
... | Using Python Tk as a front-end for threaded code | I know that Python’s Tk interface has some problems when using threads, and I’ve already run into problems with it. My idea is now to use a Queue.Queue to somehow pass events to the Tk mainloop, similarly to the following example.
from Tkinter import *
import Queue
import time
# this queue will be filled by other thre... | [
"As a general rule of thumb a GUI application should never, ever call sleep, should never have an infinite loop (except for the event loop), and you should never call 'update'. The only exception to never calling update is that is is ok only when you truly understand why you should not. \nCreate a method that does ... | [
3
] | [] | [] | [
"multithreading",
"python",
"tk_toolkit",
"tkinter",
"user_interface"
] | stackoverflow_0006828828_multithreading_python_tk_toolkit_tkinter_user_interface.txt |
Q:
PyQt4 Missing in import statement
I tried to download PyQt4 however it no lomger appears to be available, so I downloaded the nearest thing to it that I could find PyQt-win-gpl-4.8.4. The problem is when I try to follow the examples in "Rapid GUI programming with Python and QT" i cannot use some of the imports e.g... | PyQt4 Missing in import statement | I tried to download PyQt4 however it no lomger appears to be available, so I downloaded the nearest thing to it that I could find PyQt-win-gpl-4.8.4. The problem is when I try to follow the examples in "Rapid GUI programming with Python and QT" i cannot use some of the imports e.g. from PyQt4.QtCore import * gives me t... | [
"You downloaded a source package, so you'd have to compile everything. Try the binary package at the bottom of Riverbank's page. As you have python 2.7 on a 32bit system, you want to download PyQt-Py2.7-x86-gpl-4.8.4-1.exe.\n",
"As far as I know you could just intall pyqt4 with either:\npip install pyqt4\n\nor\ne... | [
3,
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0006830107_pyqt_pyqt4_python.txt |
Q:
Python Email Header parsing get_all()
I'm parsing mailbox files with Python and stumbled upon a strange behvior when trying to get all "To:" headers with get_all():
tos = message.get_all('to', [])
if tos:
tos = getaddresses(tos)
for to in tos:
receiver = EmailInformant()
receiver_email = to... | Python Email Header parsing get_all() | I'm parsing mailbox files with Python and stumbled upon a strange behvior when trying to get all "To:" headers with get_all():
tos = message.get_all('to', [])
if tos:
tos = getaddresses(tos)
for to in tos:
receiver = EmailInformant()
receiver_email = to[1]
get_all() gets all "to:" values, which... | [
"Parsing emails is very hard, as there are several different specifications, many behaviors that are or were poorly defined, and implementations that don't follow the specifications. Many of them conflict in some ways.\nI know the email module in the standard library is currently being rewritten for Python 3.3, see... | [
0
] | [] | [] | [
"email",
"email_headers",
"parsing",
"python"
] | stackoverflow_0006830611_email_email_headers_parsing_python.txt |
Q:
PyQt processing causing GUI lag
I am writing an application in Qt using python that will process a txt file. The user selects a file from their hard drive and the program will open and process it. The main problem I am having is that the 1st time you run it, it is fine; but if you run it multiple times without res... | PyQt processing causing GUI lag | I am writing an application in Qt using python that will process a txt file. The user selects a file from their hard drive and the program will open and process it. The main problem I am having is that the 1st time you run it, it is fine; but if you run it multiple times without restarting the program, each time after ... | [
"This is resolvable by using threads so that the actual user interface isn't affected.\nYou could either use the python thread module or the qt qthread module.\nTwio links to that topic:\nmailing list discussion\nstackoverflow question asked earlier slightly diffrent\nHere a tutorial to threading with pyqt:\nthread... | [
2
] | [] | [] | [
"pyqt",
"python",
"user_interface"
] | stackoverflow_0006830724_pyqt_python_user_interface.txt |
Q:
thread in python vs C# vs Ruby
I think I've found something which C# and Ruby can do but Python can not
in C#:
for (var i = 0; i < 100; i++)
new Thread(() => { Console.Write(i+" "); }).Start();
Console.ReadLine();
in Ruby:
for i in 0...100
Thread.start{
print i + ''
}
end
gets
Any ideas? Cou... | thread in python vs C# vs Ruby | I think I've found something which C# and Ruby can do but Python can not
in C#:
for (var i = 0; i < 100; i++)
new Thread(() => { Console.Write(i+" "); }).Start();
Console.ReadLine();
in Ruby:
for i in 0...100
Thread.start{
print i + ''
}
end
gets
Any ideas? Could you rewrite the above code in pyt... | [
"Well, actually you can:\n>>> import threading\n>>> def target():\n... print 123\n...\n>>> threading.Thread(target=target).start()\n123\n\nYour example would look like next:\n>>> def target(i):\n... print i\n...\n>>> for i in xrange(100):\n... threading.Thread(target=target, args=(i,)).start()\n...\n0\n... | [
2,
2,
1,
1
] | [] | [] | [
"c#",
"closures",
"multithreading",
"python",
"ruby"
] | stackoverflow_0006830458_c#_closures_multithreading_python_ruby.txt |
Q:
How to change function parameters during runtime?
I'm a beginner and use Python 2.7. I want to make the definitions parameters to be changeable so I can controll the pause and string output on the fly. Is this possible? I've read some thread stuff but it seems to be more about executing two tasks at the same time.... | How to change function parameters during runtime? | I'm a beginner and use Python 2.7. I want to make the definitions parameters to be changeable so I can controll the pause and string output on the fly. Is this possible? I've read some thread stuff but it seems to be more about executing two tasks at the same time. I want communication between the two tasks during runt... | [
"Threads are for simultaneous work. I guess if you just redesign your code you will have the effect you want. Consider removing the while clause from you function and put it outside:\ndef writeAndPause(stringToWrite,pauseSeconds)\n print stringToWrite\n sleep(pauseSeconds)\n\nAnd somewhere you call this funct... | [
3,
0,
0
] | [] | [] | [
"on_the_fly",
"python"
] | stackoverflow_0006830446_on_the_fly_python.txt |
Q:
Showing a field in ModelForm when it is being created but hiding it when it is being updated
I have a simple ModelForm that looks like this:
class ProfInfo(forms.ModelForm):
email = forms.EmailField(
required=True, label=_("Email")
)
class Meta:
model = Prof
The email field is display... | Showing a field in ModelForm when it is being created but hiding it when it is being updated | I have a simple ModelForm that looks like this:
class ProfInfo(forms.ModelForm):
email = forms.EmailField(
required=True, label=_("Email")
)
class Meta:
model = Prof
The email field is displayed when I'm creating or a updating a record using the model form but I'd like to remove it when I'... | [
"You can check whether form.instance.pk exists.\nSomething like:\ndef __init__(self, *args, **kwargs):\n super(ProfInfo, self).__init__(*args, **kwargs)\n if self.instance.pk:\n del self.field['email']\n\n"
] | [
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006831022_django_django_forms_python.txt |
Q:
Using python-oauth2 I get oauth_parameters_absent:scope
Try to use python-auth2 for my project, but I got:
In [1]: import oauth2 as oauth
In [2]: consumer_key='dijscrape.ep.io'
In [3]: consumer_secret='my-secret-here'
In [4]: REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken'
In [5]: co... | Using python-oauth2 I get oauth_parameters_absent:scope | Try to use python-auth2 for my project, but I got:
In [1]: import oauth2 as oauth
In [2]: consumer_key='dijscrape.ep.io'
In [3]: consumer_secret='my-secret-here'
In [4]: REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken'
In [5]: consumer = oauth.Consumer(consumer_key, consumer_secret)
In [6... | [
"Google requires a 'scope' parameter for the request_token uri.\nhttp://code.google.com/apis/accounts/docs/OAuth.html#prepScope\nSo something like\nscope = \"http://www.google.com/calendar/feeds/default/allcalendars/full\"\nREQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken?scope={0}'.format(... | [
2
] | [] | [] | [
"oauth",
"python"
] | stackoverflow_0006831179_oauth_python.txt |
Q:
How to find a fix number of (almost) fixed proportion rectangles with opencv?
I am writing a simple fly tracking software and I would love some input from opencv experts.
The image I have looks pretty much like:
I used to do tracking using kmeans and PIL/numpy but I re-wrote everything to use blob detection in o... | How to find a fix number of (almost) fixed proportion rectangles with opencv? | I am writing a simple fly tracking software and I would love some input from opencv experts.
The image I have looks pretty much like:
I used to do tracking using kmeans and PIL/numpy but I re-wrote everything to use blob detection in opencv. Tracking works OK but I would also like to automatize division of ROI.
What... | [
"I don't think cvCornerHarris is even close to what you need. \nA much better start would be to experiment with the demo available at: OpenCV-2.3.0/samples/cpp/squares.cpp. This technique uses Canny(), dilate() and findCountour().\nRight out of the box, this demo outputs:\n\nI believe that with a few tweaks here an... | [
3
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0006830013_opencv_python.txt |
Q:
Python, SQLAlchemy: Storing business hours as binary bitmask
I am programming in Python and using SQLAlchemy to store business hours.
The business hours are composed of three parts:
The days of the week stored in binary as a bitmask
the time the business opens,
the time the business closes.
The bitmask works ... | Python, SQLAlchemy: Storing business hours as binary bitmask | I am programming in Python and using SQLAlchemy to store business hours.
The business hours are composed of three parts:
The days of the week stored in binary as a bitmask
the time the business opens,
the time the business closes.
The bitmask works like this. There are 7 digits, which are either 0 or 1, which will... | [
"As far as checking days of the week, if by binary you mean a string of the form '1011011':\noverlap = [n for n in range(7) if (bitmask1[n] == bitmask2[n] == '1')]\n\nwill give you a list of the numbers (from 0-6) of the overlapping days -- [4] for Friday overlapping.\noverlap = ''.join(('1' if (bitmask1[n] == bitm... | [
3
] | [] | [] | [
"algorithm",
"binary",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0006823627_algorithm_binary_python_sql_sqlalchemy.txt |
Q:
Python File Concatenation
I have a data folder, with subfolders for each subject that ran through a program. So, for example, in the data folder, there are folders for Bob, Fred, and Tom. Each one of those folders contains a variety of files and subfolders. However, I am only interested in the 'summary.log' file c... | Python File Concatenation | I have a data folder, with subfolders for each subject that ran through a program. So, for example, in the data folder, there are folders for Bob, Fred, and Tom. Each one of those folders contains a variety of files and subfolders. However, I am only interested in the 'summary.log' file contained in each subject's fold... | [
"The syntax is not related to the use of glob.\nYou forget the \":\" at the end of the for statement:\nfor filename in iglob(os.path.join(PATH, '*.log')):\n ^--- missing\n\nBut the following pattern works :\nPATH = r'/Users/slevclab/Desktop/Acceptability Judgement Ta... | [
1,
0,
0,
0
] | [] | [] | [
"concatenation",
"file",
"logging",
"python"
] | stackoverflow_0006831780_concatenation_file_logging_python.txt |
Q:
List question in Python
Alright, so I have a list of 296 data points and four blank spaces. I cannot edit this list of data points. i have another list of 300 data points. I want to multiply the lists together, with python skipping multiplying the data points when a blank space shows up. Here's what the lists look... | List question in Python | Alright, so I have a list of 296 data points and four blank spaces. I cannot edit this list of data points. i have another list of 300 data points. I want to multiply the lists together, with python skipping multiplying the data points when a blank space shows up. Here's what the lists look like:
a = [[6], [7], [], [7]... | [
"Is the length of both lists actually 300 then, with 0's or blank strings for the missing data points? If so, this should come close:\nnewList = [x[0] * y[0] if x else None for x, y in zip(l1, l2)]\n\n-- Edited --\nI realized I didn't review the sample data quite as well as I could've. As the inner list is empty ... | [
5,
0
] | [] | [] | [
"exception",
"exception_handling",
"list",
"python"
] | stackoverflow_0006831734_exception_exception_handling_list_python.txt |
Q:
Optimizing Python for loop
I have a loop that is my biggest time suck for a particular function and I'd like to speed it up. Current, this single loop takes up about 400ms, while the execution for the rest of the function takes about 610ms.
The code is:
for ctr in xrange(N):
list1[ctr] = in1[ctr] - in1[0] - c... | Optimizing Python for loop | I have a loop that is my biggest time suck for a particular function and I'd like to speed it up. Current, this single loop takes up about 400ms, while the execution for the rest of the function takes about 610ms.
The code is:
for ctr in xrange(N):
list1[ctr] = in1[ctr] - in1[0] - ctr * c1
list2[ctr] = in2[ctr... | [
"Assuming that list1, list2, etc, all are numerical, consider using numpy arrays instead of lists. For large sequences of integers or floats you'll see a huge speedup.\nIf you go that route, your loop above could be written like this:\nctr = np.arange(N)\nlist1 = n1 - n1[0] - ctr * c1\nlist2 = n2 - n2[0] - ctr * c... | [
9,
2,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0006831539_optimization_python.txt |
Q:
Python and closed variables
Have a look at this code:
def closure():
value = False
def method_1():
value = True
def method_2():
print 'value is:', value
method_1()
method_2()
closure()
I would expect it to print 'Value is: True' but it doesn't. Why is this and what is the s... | Python and closed variables | Have a look at this code:
def closure():
value = False
def method_1():
value = True
def method_2():
print 'value is:', value
method_1()
method_2()
closure()
I would expect it to print 'Value is: True' but it doesn't. Why is this and what is the solution?
| [
"This happens because method_1 gets its own local scope where it can declare variables. Python sees value = True and thinks you're creating a new variable named value, local to method_1.\nThe reason Python does this is to avoid polluting the outer scope's locals with variables from an inner function. (You wouldn't ... | [
17,
2,
2,
2,
1
] | [] | [] | [
"closures",
"python",
"python_2.x"
] | stackoverflow_0006831950_closures_python_python_2.x.txt |
Q:
passing a value calculated from one function to another
I have been doing python programming for my project and I have just started. This might be another trivial question. I have this code in which I need to use a value calculated in the function poly_root() which is x. That value should be used as u in the bezie... | passing a value calculated from one function to another | I have been doing python programming for my project and I have just started. This might be another trivial question. I have this code in which I need to use a value calculated in the function poly_root() which is x. That value should be used as u in the bezier() function. After poly_root() function it should go to bezi... | [
"In this part of code:\nif r_i:\n #print [x, counter])\n return [x, counter]\nelse:\n #print x\n return x\nbezier(x)\n\nbezier(x) is unreachable. You need to rewrite it.\n",
"It would be better for poly_root to return the same type of thing in both situations (i.e. a list with two elements) ...\nif r... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0006831672_python.txt |
Q:
A Question regarding methods of dumping ram [All languages, and platforms]
I recently decided that I'd like to write an application that would be an open source alternative to some of the closed source ram dump applications on the market; primarily as a learning experience.
But I'm not entirely sure where to start... | A Question regarding methods of dumping ram [All languages, and platforms] | I recently decided that I'd like to write an application that would be an open source alternative to some of the closed source ram dump applications on the market; primarily as a learning experience.
But I'm not entirely sure where to start (for Windows machines). I guess that I'd have to iterate through memory using a... | [
"For Windows everything you need is in dbghelp.dll - reference here. \nYou can either call the Minidump functions directly, or walk all the structures by hand (which is a lot more work but more in line with the educational exercise you describe).\nFor process control, the info on writing a basic debugger should be... | [
1,
0,
0
] | [] | [] | [
"c++",
"linux",
"memory_dump",
"python",
"windows"
] | stackoverflow_0004246716_c++_linux_memory_dump_python_windows.txt |
Q:
python 2.7, using Counter on open('file.txt')
I got a good answer before for a similar problem but I didnt consider the scalability of the question that I asked. I had trouble with the text editor I am using concerning pasting in large amounts of text and ending up with either newlines, or if I remove all the newl... | python 2.7, using Counter on open('file.txt') | I got a good answer before for a similar problem but I didnt consider the scalability of the question that I asked. I had trouble with the text editor I am using concerning pasting in large amounts of text and ending up with either newlines, or if I remove all the newlines from the document then the text goes off the s... | [
"replace text for text.read(), the first make a collection of lines and the second of caracters.\nfrom collections import Counter\n\ndef main():\n with open('garbledText.txt') as text:\n collection = Counter(text.read())\n print [char for char, times in collection.items() if times < 3]\n\nif __name__==... | [
1
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006831758_python_python_2.7.txt |
Q:
What functions do the order of Django Managers affect?
So, I've read most of the docs and I've been looking around on SO a bit, but I can't quite find the answer to my question. I'll start with the code.
# Manager
class ActiveManager(models.Manager):
def get_query_set(self):
return super(ActiveManager,... | What functions do the order of Django Managers affect? | So, I've read most of the docs and I've been looking around on SO a bit, but I can't quite find the answer to my question. I'll start with the code.
# Manager
class ActiveManager(models.Manager):
def get_query_set(self):
return super(ActiveManager, self).get_query_set().filter(is_active=True)
# Model
class... | [
"Here's the relevant bit from the docs: \"If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they're defined in the model) has a special status. Django interprets the first Manager defined in a class as the \"default\" Manager, and several parts of Django (i... | [
2,
0
] | [] | [] | [
"django",
"django_managers",
"python"
] | stackoverflow_0006832268_django_django_managers_python.txt |
Q:
python syntax error
when I try to run this code :
def table():
nb = 7
i = 0
while i < 20 :
if ((i+1)*nb)%3 == 0 :
print(i+1 , "*" , nb , "=" , (i+1)*nb'*')
else :
print(i+1 , "*" , nb , "=" , (i+1)*nb)
i += 1
I get an syntax error for this part (the las... | python syntax error | when I try to run this code :
def table():
nb = 7
i = 0
while i < 20 :
if ((i+1)*nb)%3 == 0 :
print(i+1 , "*" , nb , "=" , (i+1)*nb'*')
else :
print(i+1 , "*" , nb , "=" , (i+1)*nb)
i += 1
I get an syntax error for this part (the last ')
print(i+1 , ... | [
"I suspect you're trying to do:\nprint(i+1 , \"*\" , nb , \"=\" , (i+1)*nb, '*')\n ^\n\nNote the comma before the final argument.\n",
"You are missing a comma. Try this:\nprint(i+1 , \"*\" , nb , \"=\" , (i+1)*nb , '*')\n\n",
"You are missing a comma, and also your indentatio... | [
10,
2,
2,
1,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0006832332_python_syntax.txt |
Q:
Complex 'AND' Django Queries
I'm trying to do the equivalent of this SQL query:
"SELECT * FROM something WHERE ((something >= something AND something <= something) AND(something >= something AND something <= something))"
And I can't quite figure it out. I've tried the following with no success..
.filter(( Q(some... | Complex 'AND' Django Queries | I'm trying to do the equivalent of this SQL query:
"SELECT * FROM something WHERE ((something >= something AND something <= something) AND(something >= something AND something <= something))"
And I can't quite figure it out. I've tried the following with no success..
.filter(( Q(something__gte=something) & Q(somethin... | [
"the logical operator AND is associative. a & b & c == (a & b) & c == a & (b & c). No parentheses are needed\n"
] | [
3
] | [] | [] | [
"django",
"django_database",
"django_queryset",
"python",
"sql"
] | stackoverflow_0006832518_django_django_database_django_queryset_python_sql.txt |
Q:
Python classes and __init__ method
I am learning python via dive into python. Got few questions and unable to understand, even through the documentation.
1) BaseClass
2) InheritClass
What exactly happens when we assign a InheritClass instance to a variable, when the InheritClass doesn't contain an __init__ method ... | Python classes and __init__ method | I am learning python via dive into python. Got few questions and unable to understand, even through the documentation.
1) BaseClass
2) InheritClass
What exactly happens when we assign a InheritClass instance to a variable, when the InheritClass doesn't contain an __init__ method and BaseClass does ?
Is the BaseClass _... | [
"Yes, BaseClass.__init__ will be called automatically. Same goes for any other methods defined in the parent class but not the child class. Observe:\n>>> class Parent(object):\n... def __init__(self):\n... print 'Parent.__init__'\n... def func(self, x):\n... print x\n...\n>>> class Child(Parent):\n... ... | [
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0006831685_python.txt |
Q:
twisted + gtk: should I run GUI things in threads, or in the reactor thread?
From what I understand about twisted, nothing running in the reactor thread should block. All blocking activities should be delegated to other threads, to fire callbacks back into the reactor thread when they're done.
So does this apply t... | twisted + gtk: should I run GUI things in threads, or in the reactor thread? | From what I understand about twisted, nothing running in the reactor thread should block. All blocking activities should be delegated to other threads, to fire callbacks back into the reactor thread when they're done.
So does this apply to gtk things as well? For example, I want to display a "connection failed" message... | [
"Your problem doesn't actually have anything to do with threads and GUIs. You should always use Twisted and GTK from the same thread: there's no need to do otherwise.\nYour problem is that you are using gtk.Dialog.run(). This is an API that you should never use, Twisted or not. It runs a re-entrant main loop, wh... | [
10,
0,
0
] | [] | [] | [
"gtk",
"multithreading",
"pygtk",
"python",
"twisted"
] | stackoverflow_0003504739_gtk_multithreading_pygtk_python_twisted.txt |
Q:
Pass an output of a function to django filter
I have a scenario in which I have to pass the output of a function to Django custom filter. Consider the object:
class Money(object):
def __init__(self, amount):
self.amount = amount
class ConversionRate(object):
def GetEuroRate(self):
... some calcula... | Pass an output of a function to django filter | I have a scenario in which I have to pass the output of a function to Django custom filter. Consider the object:
class Money(object):
def __init__(self, amount):
self.amount = amount
class ConversionRate(object):
def GetEuroRate(self):
... some calculation and return a float value.
def GetGBPRate(... | [
"I replicated your classes and filter, and the following is working for me:\n#template_additions.py\nfrom django import template\nregister = template.Library()\n\n@register.filter\ndef convert(value, conversion_rate):\n return float(value * conversion_rate)\n\n#models.py\nclass Money(object):\n def __init__(s... | [
1
] | [] | [] | [
"django",
"django_filters",
"django_templates",
"python"
] | stackoverflow_0006688312_django_django_filters_django_templates_python.txt |
Q:
Confusing change of scope - what's going on?
def Test(value):
def innerFunc():
print value
innerFunc()
def TestWithAssignment(value):
def innerFunc():
print value
value = "Changed value"
innerFunc()
Test("Hello 1")
# Prints "Hello 1"
TestWithAssignment("Hello 2")
# Throws... | Confusing change of scope - what's going on? | def Test(value):
def innerFunc():
print value
innerFunc()
def TestWithAssignment(value):
def innerFunc():
print value
value = "Changed value"
innerFunc()
Test("Hello 1")
# Prints "Hello 1"
TestWithAssignment("Hello 2")
# Throws UnboundLocalError: local variable 'value' referen... | [
"The issue is that Python wants you to be explicit and you want to be implicit. The execution model that Python uses binds names to the nearest available enclosing scope.\ndef Test(value):\n # Local Scope #1\n def innerFunc():\n # Local Scope #2\n print value \n # No immediate local in L... | [
9,
0
] | [] | [] | [
"python"
] | stackoverflow_0006832836_python.txt |
Q:
Mercurial Pre-Commit Hook: How to hook to python program in current directory?
I'm trying to create a Mercurial hook that runs when the commits are being pushed to the main repository. I created a python script as given below:
# commit.py
from mercurial import ui, hg
from mercurial.i18n import gettext as _
def ... | Mercurial Pre-Commit Hook: How to hook to python program in current directory? | I'm trying to create a Mercurial hook that runs when the commits are being pushed to the main repository. I created a python script as given below:
# commit.py
from mercurial import ui, hg
from mercurial.i18n import gettext as _
def getV1ID(ui, repo, **kwargs):
ui.write("The hook works!!!")
v1id = ui.prompt(... | [
"I got this solution over IRC for Mercurial. As stated in one of my comments, the script for the hook should be specified as an absolute path or it should a python module in PYTHONPATH. Hence, I was suggested by pmezard over IRC that I should have a fixed script that invokes the local commit.py. This can be done as... | [
6
] | [] | [] | [
"mercurial",
"pre_commit_hook",
"python",
"windows"
] | stackoverflow_0006829112_mercurial_pre_commit_hook_python_windows.txt |
Q:
Django template filter: HTML Sanitization AND Embedding YouTube, Vimeo, etc?
I have some user-entered content (currently entered in Markdown) and I want to allow users to embed YouTube, vimeo, etc. videos. So somehow I need to allow specific object, param and embed tags while still blocking others.
Currently I'm s... | Django template filter: HTML Sanitization AND Embedding YouTube, Vimeo, etc? | I have some user-entered content (currently entered in Markdown) and I want to allow users to embed YouTube, vimeo, etc. videos. So somehow I need to allow specific object, param and embed tags while still blocking others.
Currently I'm sanitizing the HTML using a whitelist. I realize I could customize the whitelist so... | [
"What you should do is check that the markdown is safe, have a look at bleach, then pass it through markdown:\nbleached = bleach.clean(user_input, tags=bleach.ALLOWED_TAGS + ['object', 'param', 'embed'], strip=True)\noutput = markdown(bleached)\n\nAdditionally, django-janior looks like it might be useful.\n"
] | [
2
] | [] | [] | [
"django",
"django_template_filters",
"python"
] | stackoverflow_0006832064_django_django_template_filters_python.txt |
Q:
music visualization error with gstreamer
hi I am trying to visualize a music file in gstreamer using the following command:
gst-launch filesrc location=file.mp3 ! decodebin ! audioconvert !
tee name=myT myT. ! queue ! autoaudiosink myT. ! queue ! goom !
colorspace ! autovideosink
But I get this error : "There m... | music visualization error with gstreamer | hi I am trying to visualize a music file in gstreamer using the following command:
gst-launch filesrc location=file.mp3 ! decodebin ! audioconvert !
tee name=myT myT. ! queue ! autoaudiosink myT. ! queue ! goom !
colorspace ! autovideosink
But I get this error : "There may be a timestamping problem, or this computer... | [
"I cannot give you an exact answer because i don't have windows installed.\nFor debugging this use your first pipeline (in linux works). Use parameter -v with gst-launch and put element identity just before autovideosink. This will print buffer information that passes through element identity, look for anything str... | [
1,
0
] | [] | [] | [
"audio",
"c++",
"gstreamer",
"linux",
"python"
] | stackoverflow_0002339512_audio_c++_gstreamer_linux_python.txt |
Q:
Python's PIL crop problem: color of cropped image screwed
I have a probably very basic problem with PIL's crop function: The cropped image's colors are totally screwed. Here's the code:
>>> from PIL import Image
>>> img = Image.open('football.jpg')
>>> img
<PIL.JpegImagePlugin.JpegImageFile instance at 0x00
>>> im... | Python's PIL crop problem: color of cropped image screwed | I have a probably very basic problem with PIL's crop function: The cropped image's colors are totally screwed. Here's the code:
>>> from PIL import Image
>>> img = Image.open('football.jpg')
>>> img
<PIL.JpegImagePlugin.JpegImageFile instance at 0x00
>>> img.format
'JPEG'
>>> img.mode
'RGB'
>>> box = (120,190,400,415)
... | [
"output should be a file name, not a handler.\n",
"instead of\noutput = open('cropped_football.jpg', 'w')\narea.save(output)\noutput.close()\n\njust do\narea.save('cropped_football.jpg')\n\n",
"Since the call to save actually produced output, I have to assume that PIL is able to use either a filename or an open... | [
4,
3,
1
] | [] | [] | [
"colors",
"crop",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0000830366_colors_crop_image_processing_python_python_imaging_library.txt |
Q:
Django-Pydev-Eclipse and multiple projects problem
I have set up Eclipse (Windows XP) with pydev in order to run and debug a django web app project I have. I also have this projcet under subversion control. At the moment I have a working copy of the trunk operating within Eclipse (with full debugging capability). ... | Django-Pydev-Eclipse and multiple projects problem | I have set up Eclipse (Windows XP) with pydev in order to run and debug a django web app project I have. I also have this projcet under subversion control. At the moment I have a working copy of the trunk operating within Eclipse (with full debugging capability). I always run into problems when I check out a branch of ... | [
"I'm using Python 2.7 + PyDev + Aptana on Windows 7 64-bit.\nI created a separate branch for my project in svn, and imported that branch as a new project. From there, I created a debug configuration (Run > Debug Configurations).\nUnder the Python Run section I created a \"My Test Branch\" debug configuration settin... | [
0
] | [] | [] | [
"django",
"eclipse",
"manage.py",
"pydev",
"python"
] | stackoverflow_0004399986_django_eclipse_manage.py_pydev_python.txt |
Q:
os.access returning useless value for mode os.F_OK in IronPython
I have a pile of python scripts that I am trying to use within IronPython (I need C# functionality), and I am having some issues with the os.access method.
When using the os.access method with the mode set to os.F_OK (see whether a path can be access... | os.access returning useless value for mode os.F_OK in IronPython | I have a pile of python scripts that I am trying to use within IronPython (I need C# functionality), and I am having some issues with the os.access method.
When using the os.access method with the mode set to os.F_OK (see whether a path can be accessed), I am getting False returned every time, even when the python inte... | [
"For one, os.access can be misleading - it's better to just open the file and catch any exceptions that occur.\nIronPython uses os.F_OK to mean \"does this file exist\", and boils it down to a call to File.Exists() - which returns false for a directory.\nThis is a bug, and should be fixed in 2.7.1.\n"
] | [
1
] | [] | [] | [
"c#",
"file",
"ironpython",
"python",
"windows"
] | stackoverflow_0006823785_c#_file_ironpython_python_windows.txt |
Q:
Python EOF Error in raw_input()
I am trying to get input from the user at the command prompt. The program reads in data from a text file in the manner of "cat text.txt | ./thescript.py"
At the point of the script in question, all data has already been read in, processed, and put into a list of lists.
Now I am ... | Python EOF Error in raw_input() | I am trying to get input from the user at the command prompt. The program reads in data from a text file in the manner of "cat text.txt | ./thescript.py"
At the point of the script in question, all data has already been read in, processed, and put into a list of lists.
Now I am iterating through that list of lists ... | [
"This works under windows (I tested it by running python cons.py < cons.py and was able to see the prompt and not get an error about EOF):\nimport sys\n\nfor line in sys.stdin:\n print line\n\nsys.stdin = open('CON', 'r')\nq = raw_input('---->')\n\nUnder Unix, you'd probably just have to replace 'CON' with some... | [
3,
2,
1
] | [] | [] | [
"eoferror",
"input",
"python"
] | stackoverflow_0006833526_eoferror_input_python.txt |
Q:
Use Disqus' gargoyle for whole apps
Is there a way to use disqus opensource gargoyle project to switch off whole apps.
For example, I have a management app where I allow users to change their accounts and delete them etc.
If i want to tweak around with those features I want to switch the whole app off, so that the... | Use Disqus' gargoyle for whole apps | Is there a way to use disqus opensource gargoyle project to switch off whole apps.
For example, I have a management app where I allow users to change their accounts and delete them etc.
If i want to tweak around with those features I want to switch the whole app off, so that they cant use it anymore.
I know I can switc... | [
"That doesn't seem to be how Gargoyle works. In the simplest sense, Gargoyle is just a set of conditions you add. You use decorators and such to test if a view or a piece of code is allowed to run based on whether it meets the specified conditions.\nI'm sure you understand that, but it fundamentally colors your que... | [
2
] | [] | [] | [
"disqus",
"django",
"gargoyle",
"python"
] | stackoverflow_0006829794_disqus_django_gargoyle_python.txt |
Q:
Struggling with a longitude/latitude SQL query I copied from PHP into our new Python backend. Need some second opinions
I'm moving the backend of a site to Django because it was originally coded in PHP and it's the biggest mess on Earth or Mars... anyway.. so I copied the PHP and Python that I've conjured up to co... | Struggling with a longitude/latitude SQL query I copied from PHP into our new Python backend. Need some second opinions | I'm moving the backend of a site to Django because it was originally coded in PHP and it's the biggest mess on Earth or Mars... anyway.. so I copied the PHP and Python that I've conjured up to copy it below. They both return IDENTICAL values, but for some reason, the Django/Python doesn't return anything from the quer... | [
"I noticed that you're converting the latitude and longitude on orderloc to floats. What field type are they on your model in the first place? Django has a FloatField field type, so if you're dealing with floats, you should use that field type on your model. I'm thinking based on this that it might be an issue of c... | [
2
] | [] | [] | [
"django",
"django_queryset",
"mysql",
"python",
"sql"
] | stackoverflow_0006833659_django_django_queryset_mysql_python_sql.txt |
Q:
Checkbox input using python mechanize
I want to fill a form using python mechanize. form looks like:
<POST https://10.20.254.39/cloud_computing/vmuser/migrate_vm/cli multipart/form-data
<TextControl(vm=cli)>
<TextControl(chost=10.20.14.39)>
<SelectControl(dhost=[*, 28, 27])>
<CheckboxControl(live=[on])>
... | Checkbox input using python mechanize | I want to fill a form using python mechanize. form looks like:
<POST https://10.20.254.39/cloud_computing/vmuser/migrate_vm/cli multipart/form-data
<TextControl(vm=cli)>
<TextControl(chost=10.20.14.39)>
<SelectControl(dhost=[*, 28, 27])>
<CheckboxControl(live=[on])>
<CheckboxControl(undefinesource=[on])>
<C... | [
"One way that I have done it is\nbr.find_control(\"live\").items[0].selected=True\n\n"
] | [
12
] | [] | [] | [
"checkbox",
"mechanize",
"python"
] | stackoverflow_0006833868_checkbox_mechanize_python.txt |
Q:
Do simple things with a Google Wave robot
I wanted to add 3 features to the robot from the tutorial here:
http://code.google.com/apis/wave/extensions/robots/python-tutorial.html
Before adding all these features, my robot is working as intended.
Now the odd features still shows up (with "v2" at the bck of the blip ... | Do simple things with a Google Wave robot | I wanted to add 3 features to the robot from the tutorial here:
http://code.google.com/apis/wave/extensions/robots/python-tutorial.html
Before adding all these features, my robot is working as intended.
Now the odd features still shows up (with "v2" at the bck of the blip content), but neither of the new features shows... | [
"events.BLIP_SUMBITTED should be events.BLIP_SUBMITTED\n"
] | [
1
] | [] | [] | [
"google_wave",
"python"
] | stackoverflow_0002297420_google_wave_python.txt |
Q:
Basic lzw compression help in python
I'm just trying to write a really basic script that'll take some input text and compress it with lzw, using this package: http://packages.python.org/lzw/
I've never tried any encoding with python before and am thoroughly confused =( - I also can't find any documentation online ... | Basic lzw compression help in python | I'm just trying to write a really basic script that'll take some input text and compress it with lzw, using this package: http://packages.python.org/lzw/
I've never tried any encoding with python before and am thoroughly confused =( - I also can't find any documentation online about it, other than the package info.
Her... | [
"Here is the package API : http://packages.python.org/lzw/lzw-module.html\nYou can read psuedo-code of compression and decompression here\nIs there anything else you are confused about?\nHere is an example:\nPython\nIn this version the dicts contain mixed typed data:\ndef compress(uncompressed):\n \"\"\"Compress... | [
12
] | [] | [] | [
"encode",
"lzw",
"python"
] | stackoverflow_0006834388_encode_lzw_python.txt |
Q:
python on macos import fails on missing package
I'm trying to install PIL on snow-leopard , but I am running into a few problems.
1st this system needs to be cleaned up, too many tests with macports, easy_install etc.. I thing I might have too many versions of python in there... but that is not really the problem.... | python on macos import fails on missing package | I'm trying to install PIL on snow-leopard , but I am running into a few problems.
1st this system needs to be cleaned up, too many tests with macports, easy_install etc.. I thing I might have too many versions of python in there... but that is not really the problem.
It seems that no matter what I try I can't get PIL t... | [
"As utdemir commented, try using\nfrom PIL import Image\n\n",
"Ok after finding out more, I was able to install it to the macports 2.7 using\nsudo port install py2.7 then the pil.\nAs i suspected the problem persisted when I launched python it was not the macports version that was fired up but the other one.. the... | [
0,
0
] | [] | [] | [
"easy_install",
"osx_snow_leopard",
"pip",
"python",
"python_imaging_library"
] | stackoverflow_0006833743_easy_install_osx_snow_leopard_pip_python_python_imaging_library.txt |
Q:
for loops in python
Is there a pythonic way (I know I can loop using range(len(..)) and get an index) to do the following example:
for line in list_of_strings:
if line[0] == '$':
while line[-1] == '#':
# read in the Next line and do stuff
# after quitting out of the while loop, the ... | for loops in python | Is there a pythonic way (I know I can loop using range(len(..)) and get an index) to do the following example:
for line in list_of_strings:
if line[0] == '$':
while line[-1] == '#':
# read in the Next line and do stuff
# after quitting out of the while loop, the next iteration of the for... | [
"One of the most basic challenges in python is getting clever when iterating over lists and dicts. If you actually need to modify the collection while iterating, you may need to work on a copy, or store changes to apply at the end of iteration. \nIn your case, though, you just need to skip items in the list. You... | [
9,
5
] | [] | [] | [
"python"
] | stackoverflow_0006834368_python.txt |
Q:
Rebuilding a Django site every night
I have a django site that needs to be rebuilt every night. I would like to check out the code from the Git repo and then begin doing the stuff like setting up the virtual environment, downloading the packages, etc. This would have no manual intervention as this would be run fro... | Rebuilding a Django site every night | I have a django site that needs to be rebuilt every night. I would like to check out the code from the Git repo and then begin doing the stuff like setting up the virtual environment, downloading the packages, etc. This would have no manual intervention as this would be run from cron
I'm really confused as to what to u... | [
"You'll need to create some sort of build script that does everything but the GIT checkout. I've never used any Python build tools, but perhaps something like: http://www.scons.org/.\nOnce you've created a script you can use Jenkins to schedule a nightly build and report success/failure: http://jenkins-ci.org/. ... | [
1,
0,
0
] | [] | [] | [
"deployment",
"django",
"python",
"web_deployment"
] | stackoverflow_0006834032_deployment_django_python_web_deployment.txt |
Q:
How to handle multiple members of a C++ class simultaneously?
I'm used to Python, and struggling to learn some C++. In Python, when I have a class with a "move" function, I can simply add its members to a list and iterate over the list like this:
for i in list:
i.move(n)
Now, how is the corresponding thing do... | How to handle multiple members of a C++ class simultaneously? | I'm used to Python, and struggling to learn some C++. In Python, when I have a class with a "move" function, I can simply add its members to a list and iterate over the list like this:
for i in list:
i.move(n)
Now, how is the corresponding thing done conveniently in C++?
| [
"You can do the same in C++ by using pointers or reference to your objects.\nIf your class is MyClass, you could declare:\nstd::vector<MyClass*> list;\n\nthen add your objects to the list:\nlist.push_back(&objectOfMyClass); //-- for all of your objects\n\nand finally:\nstd::vector<MyClass*>::iterator itr;\nfor (itr... | [
6,
1,
0,
0
] | [] | [] | [
"c++",
"class",
"python"
] | stackoverflow_0006833343_c++_class_python.txt |
Q:
Moving python code to separate file
I'm having trouble moving my functions into a separate file as they access a wxpython gui.
The functions are from "onSaveMovieFile" to "LogThis"
#!/usr/bin/env python
# -*- coding: us-ascii -*-
# generated by wxGlade 0.6.3 on Fri Jul 22 11:53:07 2011
"""
Copyright (c) 2011 M... | Moving python code to separate file | I'm having trouble moving my functions into a separate file as they access a wxpython gui.
The functions are from "onSaveMovieFile" to "LogThis"
#!/usr/bin/env python
# -*- coding: us-ascii -*-
# generated by wxGlade 0.6.3 on Fri Jul 22 11:53:07 2011
"""
Copyright (c) 2011 Mitchell Lafferty <coolspeedy6 at gmail do... | [
"I see you are using wxglade for the design of you gui.\nThe best procedure is to keep the code from glade untouched in a file. Then you import and subclass the wxglade created class in a new file. There you write all your Bind() and functions there.\nFor example suposse this is your wxglade autogenerated file:\nmy... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006833625_python_wxpython.txt |
Q:
os.getcwd() for a different drive in Windows
According to http://docs.python.org/library/os.path.html
"On Windows, there is a current directory for each drive"
This is giving me some trouble when I use os.getcwd() on Windows.
I am using Python 2.7 on my C drive to call a script located on the shared network dri... | os.getcwd() for a different drive in Windows | According to http://docs.python.org/library/os.path.html
"On Windows, there is a current directory for each drive"
This is giving me some trouble when I use os.getcwd() on Windows.
I am using Python 2.7 on my C drive to call a script located on the shared network drive F:. Yet, os.getcwd() from within this script is... | [
"Actually, it depends:\nIf Python is started directly (not going through cmd.exe), then yes, you only have the one current directory (it's like always specifying cd /d ...):\n--> import os\n--> os.getcwd()\n'c:\\\\source\\\\dbf-dev'\n--> os.chdir('z:')\n--> os.getcwd()\n'Z:\\\\'\n--> os.chdir('c:') # assumes roo... | [
6,
2
] | [
"I believe that the section you are reading that from is worded poorly. There is only one current working directory for your python session, and you get it from os.getcwd(). You can use os.chdir(r'F:\\') to change directories to your F drive.\nThe part that that quote is referencing is relating to the os.path.join ... | [
-1
] | [
"python"
] | stackoverflow_0006614323_python.txt |
Q:
Python: replace a string by a float in txt file
Here is a problem.
I have a .py file and a .txt.
To simplify, my .txt looks like:
@x@
In the .py I have
x=15
I would like to replace @x@ in the txt by the value saved in the py, ie my txt should look like
15
I tried with this:
for i, line in enumerate(fileinput.... | Python: replace a string by a float in txt file | Here is a problem.
I have a .py file and a .txt.
To simplify, my .txt looks like:
@x@
In the .py I have
x=15
I would like to replace @x@ in the txt by the value saved in the py, ie my txt should look like
15
I tried with this:
for i, line in enumerate(fileinput.input('mytxtfile.txt', inplace = 1)):
sys.stdout.... | [
"The string.Template class is a good way to do this.\nhttp://docs.python.org/library/string.html#template-strings\nfrom string import Template\nclass MyTemplate( Template ): \n delimiter= '@'\n pattern= r\"@(?P<escaped>@)|@(?P<named>[_a-z][_a-z0-9]*)@|@(?P<braced>[_a-z][_a-z0-9]*)@|@(?P<invalid>)\"\n\nGiven t... | [
9,
7,
0,
0
] | [] | [] | [
"python",
"replace",
"string",
"text_files"
] | stackoverflow_0006789230_python_replace_string_text_files.txt |
Q:
Add foreign key children to model form in Django
I have the following Django models:
class Contact(models.Model):
id #primary key
#Other contact info
class ContactType(models.Model):
contacttype_choices=(('Primary', 'Primary'),
('Billing', 'Billing'),
... | Add foreign key children to model form in Django | I have the following Django models:
class Contact(models.Model):
id #primary key
#Other contact info
class ContactType(models.Model):
contacttype_choices=(('Primary', 'Primary'),
('Billing', 'Billing'),
('Business', 'Business'),
('T... | [
"I would probably structure the models as such, so I can choose which contact type when creating/editing the Contact. If ContactType is related as a ManyToMany, we automatically get a ModelMultpleChoiceField in the ModelForm, and all we need to do is use the CheckboxSelectMultiple widget to get the output you're lo... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006834569_django_django_forms_python.txt |
Q:
Integrate stiff ODEs with Python
I'm looking for a good library that will integrate stiff ODEs in Python. The issue is, scipy's odeint gives me good solutions sometimes, but the slightest change in the initial conditions causes it to fall down and give up. The same problem is solved quite happily by MATLAB's stiff... | Integrate stiff ODEs with Python | I'm looking for a good library that will integrate stiff ODEs in Python. The issue is, scipy's odeint gives me good solutions sometimes, but the slightest change in the initial conditions causes it to fall down and give up. The same problem is solved quite happily by MATLAB's stiff solvers (ode15s and ode23s), but I ca... | [
"If you can solve your problem with Matlab's ode15s, you should be able to solve it with the vode solver of scipy. To simulate ode15s, I use the following settings:\node15s = scipy.integrate.ode(f)\node15s.set_integrator('vode', method='bdf', order=15, nsteps=3000)\node15s.set_initial_value(u0, t0)\n\nand then you ... | [
22,
17,
3,
2
] | [] | [] | [
"pygsl",
"python",
"scipy"
] | stackoverflow_0002088473_pygsl_python_scipy.txt |
Q:
Among Lucene/Solr, Whoosh, Sphinx, Xapian which integrates best with python?
I am a newb coder in a startup and I am implementing search of documents in a directory in a web host.
I am comparing Lucene/Solr, Whoosh, Sphinx and Xapian. Whoosh is natively python. But I want your opinions on it too. Which of these ha... | Among Lucene/Solr, Whoosh, Sphinx, Xapian which integrates best with python? | I am a newb coder in a startup and I am implementing search of documents in a directory in a web host.
I am comparing Lucene/Solr, Whoosh, Sphinx and Xapian. Whoosh is natively python. But I want your opinions on it too. Which of these have
mature and easy to use and install interfaces with python? (Whoosh is a no-br... | [
"Use Whoosh if you don't need the speed, extra features of the alternatives. It's great, has a nice API, good documentation. My second choice would probably be Xapian, which is fast and has a fairly decent API. They are all fairly mature products. If you don't know what you really need, I'd just go with Whoosh for ... | [
2,
2,
2
] | [] | [] | [
"full_text_search",
"python",
"solr",
"sphinx",
"whoosh"
] | stackoverflow_0006724672_full_text_search_python_solr_sphinx_whoosh.txt |
Q:
Python: Get Mount Point on Windows or Linux
I need a function to determine if a directory is a mount point for a drive.
I found this code already which works well for linux:
def getmount(path):
path = os.path.abspath(path)
while path != os.path.sep:
if os.path.ismount(path):
return path
path = os... | Python: Get Mount Point on Windows or Linux | I need a function to determine if a directory is a mount point for a drive.
I found this code already which works well for linux:
def getmount(path):
path = os.path.abspath(path)
while path != os.path.sep:
if os.path.ismount(path):
return path
path = os.path.abspath(os.path.join(path, os.pardir))
re... | [
"Windows didn't use to call them \"mount points\" [edit: it now does, see below!], and the two typical/traditional syntaxes you can find for them are either a drive letter, e.g. Z:, or else \\\\hostname (with two leading backslashes: escape carefully or use r'...' notation in Python fpr such literal strings).\nedit... | [
3,
3,
0
] | [] | [] | [
"linux",
"mount",
"operating_system",
"python",
"windows"
] | stackoverflow_0001138383_linux_mount_operating_system_python_windows.txt |
Q:
What's hanging up this use of map.pool in python?
I have a command line program I'm running and I pipe in text as arguments:
somecommand.exe < someparameters_tin.txt
It runs for a while (typically a good fraction of an hour to several hours) and then writes results in a number of text files. I'm trying to write... | What's hanging up this use of map.pool in python? | I have a command line program I'm running and I pipe in text as arguments:
somecommand.exe < someparameters_tin.txt
It runs for a while (typically a good fraction of an hour to several hours) and then writes results in a number of text files. I'm trying to write a script to launch several of these simultaneously, us... | [
"Is there any chance that the processes are trying to write to a common file? Under Linux it would probably just work, clobbering data but not slowing down; but under Windows one process might get the file and all the other processes might hang waiting for the file to become available.\nIf you replace your actual ... | [
0,
0
] | [] | [] | [
"multiprocessing",
"pool",
"python",
"windows"
] | stackoverflow_0006835628_multiprocessing_pool_python_windows.txt |
Q:
how to pass id from url to post_save_redirect in urls.py
I have several objects in the database. Url to edit an object using the generic view looks like site.com/cases/edit/123/ where 123 is an id of the particular object. Consider the cases/url.py contents:
url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { .... | how to pass id from url to post_save_redirect in urls.py | I have several objects in the database. Url to edit an object using the generic view looks like site.com/cases/edit/123/ where 123 is an id of the particular object. Consider the cases/url.py contents:
url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'),
where up... | [
"In short what you need to do is wrap the update_object function.\ndef update_object_wrapper(request, object_id, *args, **kwargs):\n redirect_to = reverse('your object edit url name', object_id)\n return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs)\n\n",
"First, read up... | [
1,
0,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0000474203_django_django_urls_python.txt |
Q:
read file names from directory w/ python
I'm trying to make a pygame executable. I will use the following setup file:
from distutils.core import setup
import py2exe
setup(
console = [ "game.py" ],
author = "me",
data_files = [ ( directory, [ file_1, file_2... ] ) ]
)
I've gotten this to work fine on a si... | read file names from directory w/ python | I'm trying to make a pygame executable. I will use the following setup file:
from distutils.core import setup
import py2exe
setup(
console = [ "game.py" ],
author = "me",
data_files = [ ( directory, [ file_1, file_2... ] ) ]
)
I've gotten this to work fine on a simple game, but the game I want to package up h... | [
"import os\n\ndata_files = [(x[0], x[2]) for x in os.walk(root_dir)]\n\nhttp://docs.python.org/library/os.html#os.walk\nThis will give you the files for every subdirectory contained within root_dir (along with the ones in root_dir itself, of course) as tuples in the format [(dirpath1, [file1, file2, ...]), (dirpath... | [
7,
6,
4,
1
] | [] | [] | [
"distutils",
"filenames",
"py2exe",
"pygame",
"python"
] | stackoverflow_0006682284_distutils_filenames_py2exe_pygame_python.txt |
Q:
Help improve my file upload method (Pyramid framework)
Currently, I am using the following method for uploading files (via HTML form) in Pyramid.
if request.params.get('form.submitted'):
upload_directory = os.getcwd() + '/myapp/static/uploads/'
my_file = request.POST.get('thumbnail')
saved_file = str... | Help improve my file upload method (Pyramid framework) | Currently, I am using the following method for uploading files (via HTML form) in Pyramid.
if request.params.get('form.submitted'):
upload_directory = os.getcwd() + '/myapp/static/uploads/'
my_file = request.POST.get('thumbnail')
saved_file = str(upload_directory) + str(my_file.filename)
perm_file = ... | [
"You'll want to use something like werkzug's safe_join rather than just adding the upload directory to the given file name. An attacker could create a POST with a filename of ../../../some/important/path and cause this script to overwrite some file outside of your upload_directory.\n"
] | [
14
] | [] | [] | [
"multipart",
"pylons",
"pyramid",
"python"
] | stackoverflow_0006836029_multipart_pylons_pyramid_python.txt |
Q:
Possible to do this in Python?
I am fairly new to Python, and am not sure if this can be done. As you can see, I couldn't even figure out a good title for the question. Say I have 2 classes,
class A:
self.B = None
class B:
def c(self):
pass
def d(self):
pass
Now if I make an instance... | Possible to do this in Python? | I am fairly new to Python, and am not sure if this can be done. As you can see, I couldn't even figure out a good title for the question. Say I have 2 classes,
class A:
self.B = None
class B:
def c(self):
pass
def d(self):
pass
Now if I make an instance of the class,
a = A()
a.b = B()
I ... | [
"Have A.__getattr__() catch the access to a.c and have it return a.b.c instead.\n",
"Why would you want it to work like that? Have A inherit from B if it is going to be understood as having B's methods.\n",
"class A:\n self.B = None\n\nThis won't compile. What does self refer to? Perhaps you meant the follow... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006836781_python.txt |
Q:
Nested views in openerp
I'm trying to show a field in the tree view not referenced directly in the object fields, in my case stock.picking.
The field I'm trying to show is referenced by other referenced field, in my case:
stock.pinking -> address_id -> partner_id -> payment_days.
And I've modify the xml view add... | Nested views in openerp | I'm trying to show a field in the tree view not referenced directly in the object fields, in my case stock.picking.
The field I'm trying to show is referenced by other referenced field, in my case:
stock.pinking -> address_id -> partner_id -> payment_days.
And I've modify the xml view adding:
<field name="address_id"... | [
"As far as I know, OpenERP will just ignore that nested tree tag. To display a field from a related table in a tree view, I think you have to add it to the main table as a related field and then display it in the view.\n"
] | [
1
] | [] | [] | [
"erp",
"openerp",
"python"
] | stackoverflow_0006671669_erp_openerp_python.txt |
Q:
simple application using wxPython and matplotlib freezes
I'm trying to make matplotlib cooperate with wxPython, and my application listed below behaves awkward: under Ubuntu it works as intended, but under Windows XP it seems to freeze, i.e. button does not react to clicking, and elements are overlapping(as if Gri... | simple application using wxPython and matplotlib freezes | I'm trying to make matplotlib cooperate with wxPython, and my application listed below behaves awkward: under Ubuntu it works as intended, but under Windows XP it seems to freeze, i.e. button does not react to clicking, and elements are overlapping(as if GridSizer didn't work). What am I doing wrong?
Update: After cha... | [
"This works (after modifying MyFrame):\nfrom matplotlib.backends.backend_wxagg import \\\nFigureCanvasWxAgg as FigureCanvas\n\nclass MyFigurePanel(wx.Panel):\n \"\"\"Class to represent a Matplotlib Figure as a wxFrame\"\"\"\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n self.figure = Figu... | [
3
] | [] | [] | [
"matplotlib",
"python",
"windows"
] | stackoverflow_0006836274_matplotlib_python_windows.txt |
Q:
Find offset between system-time and Internet time using Python
How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?
A:
Use ntplib. Right from the manual:
>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe... | Find offset between system-time and Internet time using Python | How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?
| [
"Use ntplib. Right from the manual:\n>>> import ntplib\n>>> c = ntplib.NTPClient()\n>>> response = c.request('europe.pool.ntp.org', version=3)\n>>> response.offset\n-0.143156766891\n\n",
"Just to save you some time. Here's the code I ended up with using phihag's answer. It prints the drift every interval_sec to s... | [
6,
1
] | [] | [] | [
"python",
"systemtime"
] | stackoverflow_0006621870_python_systemtime.txt |
Q:
Executing an xmgrace batch with subprocess.Popen()
I have to make graphs from several files with data. I already found a way to run a simple command
xmgrace -batch batch.bfile -nosafe -hardcopy
in which batch.bfile is a text file with grace commands to print the graph I want. I already tried it manually and it wo... | Executing an xmgrace batch with subprocess.Popen() | I have to make graphs from several files with data. I already found a way to run a simple command
xmgrace -batch batch.bfile -nosafe -hardcopy
in which batch.bfile is a text file with grace commands to print the graph I want. I already tried it manually and it works perfectly. To do this with several files I just have... | [
"You may want to check out http://sourceforge.net/projects/graceplot/\n",
"When use use Popen, you can capture the application's output to stdout to stderr and print it within your application - this way you can see what is happening:\nfrom subprocess import Popen, PIPE\nps = Popen(reportParameters,bufsize=512, s... | [
0,
0,
0
] | [] | [] | [
"batch_processing",
"command_line",
"popen",
"python",
"subprocess"
] | stackoverflow_0006823535_batch_processing_command_line_popen_python_subprocess.txt |
Q:
improve this very-simple dictionary generator in python
I'm trying to make a simple dict generator. It works but it isn't very functional yet.
I'd like to improve it by being able to change the max size of the output without touching the code.
letr='abcdefghijklmnopqrstuvwxyz'
for i in range(len(letr)):
t=let... | improve this very-simple dictionary generator in python | I'm trying to make a simple dict generator. It works but it isn't very functional yet.
I'd like to improve it by being able to change the max size of the output without touching the code.
letr='abcdefghijklmnopqrstuvwxyz'
for i in range(len(letr)):
t=letr[i]
print t
for t2 in letr:
print t+t2
... | [
"import itertools\n\ndef dict_gen(n):\n letr = 'abcdefghijklmnopqrstuvwxyz'\n return itertools.chain(''.join(j) for i in range(n) \n for j in itertools.product(letr, repeat=i+1))\n\nUsage:\nfor word in dict_gen(n): # replace n with the max word length you want\n print word\n\nUnl... | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006837180_python.txt |
Q:
How to call already defined function in an main selenium python script
I have defined python function in one py file and I want to include that function in my main script.
Please provide me the solution.
A:
from other_file import other_function
# use other function:
val = other_function()
| How to call already defined function in an main selenium python script | I have defined python function in one py file and I want to include that function in my main script.
Please provide me the solution.
| [
"from other_file import other_function\n\n# use other function:\nval = other_function()\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006837454_python.txt |
Q:
How do I merge a tuple or convert a list to a tuple?
I have a tuple, INSTALLED_APPS, and I want to merge extra items into it to get my local apps in the tuple too without altering the main settings file. I came this far:
DEFAULT_APPS = list(INSTALLED_APPS)
MY_APPS_LIST = DEFAULT_APPS.append('south')
however if I ... | How do I merge a tuple or convert a list to a tuple? | I have a tuple, INSTALLED_APPS, and I want to merge extra items into it to get my local apps in the tuple too without altering the main settings file. I came this far:
DEFAULT_APPS = list(INSTALLED_APPS)
MY_APPS_LIST = DEFAULT_APPS.append('south')
however if I try to convert this into a tuple again by running:
INSTALL... | [
"append doesn't return a new list -- it modifies the original list, returning None. You want MY_APPS_LIST = DEFAULT_APPS + ['south']\n",
"list methods operate in-place, and hence return None. If you want to add another element to an existing list and only return the result then just add them.\nMY_APPS_LIST = DEFA... | [
8,
3,
3,
1
] | [] | [] | [
"append",
"django",
"merge",
"python"
] | stackoverflow_0006837643_append_django_merge_python.txt |
Q:
Libimobiledevice python bindings?
Could someone explain or put me in a direction where i can find information about how to use the python bindings of libimobiledevice for my application?
I already searched for a documentation and the like but i can't find anything at all.
A:
Edit November 2015: NoBugs added a li... | Libimobiledevice python bindings? | Could someone explain or put me in a direction where i can find information about how to use the python bindings of libimobiledevice for my application?
I already searched for a documentation and the like but i can't find anything at all.
| [
"Edit November 2015: NoBugs added a link to an example of using the bindings in a comment: https://github.com/upbit/python-imobiledevice_demo\nThere doesn't seem to be any documentation for the Python bindings specifically. They use SWIG, and here is the source in case you read C: http://cgit.sukimashita.com/libimo... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006837716_python.txt |
Q:
How to read a file in python which has newline and tabs into a string?
I am trying to read a file which has tabs and newline etc and the data is JSON format.
When I read it using file.read()/readlines() etc, all the newlines and tabs are also read.
I have tried rstrip(), split etc but in vain, maybe I am missing s... | How to read a file in python which has newline and tabs into a string? | I am trying to read a file which has tabs and newline etc and the data is JSON format.
When I read it using file.read()/readlines() etc, all the newlines and tabs are also read.
I have tried rstrip(), split etc but in vain, maybe I am missing some thing:
Here is essentially what I am doing:
f = open('/path/to/file.txt... | [
"Why not just use json.load() if the data is json?\nimport json\nd = json.load(open('myfile.txt', 'r'))\n\n",
"A little hack, inefficient I guess:\nf = open(\"/path/to/file.txt\")\nlines = f.read().replace(\"\\n\", \"\").replace(\"\\t\", \"\").replace(\" \", \"\")\n\nprint lines\n\n",
"Where did that structure ... | [
6,
2,
0,
0,
0,
0
] | [] | [] | [
"fileparsing",
"json",
"python"
] | stackoverflow_0006837368_fileparsing_json_python.txt |
Q:
numpy2ri conversion problem with rpy2 2.2.2
I am using rpy2-2.2.2 with the new free Enthought python distribution that includes numpy 1.6.0 and python 2.7.2. I easy_installed rpy2 which resulted in v. 2.2.2 being installed and all tests were successful.
The problem I'm having is with code I wrote that worked fine ... | numpy2ri conversion problem with rpy2 2.2.2 | I am using rpy2-2.2.2 with the new free Enthought python distribution that includes numpy 1.6.0 and python 2.7.2. I easy_installed rpy2 which resulted in v. 2.2.2 being installed and all tests were successful.
The problem I'm having is with code I wrote that worked fine with rpy2 2.1.8 and python 2.6. The issue is in c... | [
"From http://rpy.sourceforge.net/rpy2/doc-2.2/html/numpy.html#from-numpy-to-rpy2:\n\nWarning\nIn earlier versions of rpy2, the import was all that was needed to have the conversion. A side-effect when importing a module can lead to problems, and there is now an extra step to make the conversion active: call the fun... | [
3
] | [] | [] | [
"python",
"r",
"rpy2"
] | stackoverflow_0006837774_python_r_rpy2.txt |
Q:
Python subprocess: how to pipe to gnuplot a command to plot a variable?
I am not trying to do anything fancy here. I am trying to automate plotting some experiment data in the following script:
print "processing: ", filename
gnuplot = Popen(gnuplot_bin,stdin = PIPE).stdin
if state_plot:
gnuplot.write( "... | Python subprocess: how to pipe to gnuplot a command to plot a variable? | I am not trying to do anything fancy here. I am trying to automate plotting some experiment data in the following script:
print "processing: ", filename
gnuplot = Popen(gnuplot_bin,stdin = PIPE).stdin
if state_plot:
gnuplot.write( "set term x11\n".encode())
gnuplot.write( "set term png size 1920,1010... | [
"You want \n gnuplot.write(\"plot %s using 1 with lines lt -1 lw 0.5 title 'X axis' \\n \" % filename1)\n\nSee http://docs.python.org/library/string.html#formatstrings for new style formatting and http://docs.python.org/library/stdtypes.html#string-formatting for old style formatting, which looks like what you w... | [
6,
1
] | [] | [] | [
"escaping",
"gnuplot",
"python",
"string_formatting",
"subprocess"
] | stackoverflow_0006837494_escaping_gnuplot_python_string_formatting_subprocess.txt |
Q:
database to csv in django using python
I am writing this small code which is part of my Django application. It is supposed to pick up data from a DB table(MySql) and make a csv file. May be its a very simple error I am getting, but I am not able to resolve it.
Name of the file: write_to_csv.py
import csv
def ... | database to csv in django using python | I am writing this small code which is part of my Django application. It is supposed to pick up data from a DB table(MySql) and make a csv file. May be its a very simple error I am getting, but I am not able to resolve it.
Name of the file: write_to_csv.py
import csv
def createCSV():
from django.db import con... | [
"open's second argument should be wb not wt. Other than that, it looks like you are doing everything right. \nIf it's still not working, can you update your question with the results of doing dir(csv)? (It's most likely that you have some other module installed in your Python distribution or in the same directory... | [
2,
1
] | [] | [] | [
"csv",
"django",
"mysql",
"python"
] | stackoverflow_0006837347_csv_django_mysql_python.txt |
Q:
A Hadoop-ready reducer for finding the longest run of 1s. Imposible?
Is it possible to write a Hadoop-ready reduce function that can find the longest run of 1s (only the length of the run)?
I'm thinking of something that can run on Python's functools.reduce. But I would eventually like to run on a Hadoop cluster (... | A Hadoop-ready reducer for finding the longest run of 1s. Imposible? | Is it possible to write a Hadoop-ready reduce function that can find the longest run of 1s (only the length of the run)?
I'm thinking of something that can run on Python's functools.reduce. But I would eventually like to run on a Hadoop cluster (by "Hadoop-ready" I mean that the reduction steps can run in any arbitrary... | [
"This doesnt seem like a perfect fit for a set of parallel reducers. One alternative is to implement it as a separate map-reduce task which will run after your original algo (the one that converts ur sequence to 1s and 0s).\nYou then implement a Custom Input format and record reader that splits your input stream in... | [
2,
1
] | [] | [] | [
"hadoop",
"python"
] | stackoverflow_0006828545_hadoop_python.txt |
Q:
Twisted authentication cread problem
I have error in pb, cred...
We have a simple client:
#!/usr/bin/env python
from twisted.spread import pb
from twisted.internet import reactor
from twisted.cred import credentials
def main():
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8801, factory... | Twisted authentication cread problem | I have error in pb, cred...
We have a simple client:
#!/usr/bin/env python
from twisted.spread import pb
from twisted.internet import reactor
from twisted.cred import credentials
def main():
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8801, factory)
def1 = factory.login(credentials.Use... | [
"You need to use a twisted.spread.pb.IUsernameMD5Password credentials object to log in, because Twisted's PB uses a little challenge/response scheme during authentication, which requires the password to be hashed (MD5). This algorithm is currently hard-coded in the PB module. You cannot easily implement/use other c... | [
2,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0006766588_python_twisted.txt |
Q:
Comparing a string to multiple items in Python
I'm trying to compare a string called facility to multiple possible strings to test if it is valid. The valid strings are:
auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7
Is there an efficient way of doing this other... | Comparing a string to multiple items in Python | I'm trying to compare a string called facility to multiple possible strings to test if it is valid. The valid strings are:
auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7
Is there an efficient way of doing this other than:
if facility == "auth" or facility == "authpri... | [
"If, OTOH, your list of strings is indeed hideously long, use a set:\naccepted_strings = {'auth', 'authpriv', 'daemon'}\n\nif facility in accepted_strings:\n do_stuff()\n\nTesting for containment in a set is O(1) on average.\n",
"Unless your list of strings gets hideously long, something like this is probably ... | [
57,
11,
3
] | [] | [] | [
"python",
"string",
"string_comparison"
] | stackoverflow_0006838238_python_string_string_comparison.txt |
Q:
Is there a simple way to match a value in a csv file using python?
Is there a simple way to match a value in a given field of a csv file using python without using a regex? I have a field in a csv file that contains text. I wish to write a python script to do stuff to all the fields that contain the text 'eagle' i... | Is there a simple way to match a value in a csv file using python? | Is there a simple way to match a value in a given field of a csv file using python without using a regex? I have a field in a csv file that contains text. I wish to write a python script to do stuff to all the fields that contain the text 'eagle' in a file called file.csv.
For example:
import csv
with open('file.csv',... | [
"It works on my machine.\nbash-4.1$ cat > file.csv\ntree,rock,10000,eagle\nplant,stone,500,owl\nseed,boulder,7000,crane\nfruit,pebble,60000000,hawk\nbash-4.1$ python\nPython 2.7 (r27:82500, Sep 16 2010, 18:03:06) \n[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"lice... | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0006838130_csv_python.txt |
Q:
paramiko can't open SFTP connection
I'm having some trouble opening an SFTP connection with paramiko. My current code is:
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.load_system_host_keys()
client.connect('some.example.com', username="myuser", password="mypassword")
sftp_client... | paramiko can't open SFTP connection | I'm having some trouble opening an SFTP connection with paramiko. My current code is:
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
client.load_system_host_keys()
client.connect('some.example.com', username="myuser", password="mypassword")
sftp_client = client.open_sftp()
sftp_client.put(my_... | [
"You need to first create and connect to a transport:\ntransport = Transport((host, port))\ntransport.connect(username = username, pkey = mykey) # or password = mypassword\n\nNow to can start the SFTP client:\nsftp_client = SFTPClient.from_transport(transport)\n\nThen you can\nsftp_client.put(my_local_file)\n\nand ... | [
6
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0006838138_paramiko_python.txt |
Q:
Python - Error Parsing HTML w/ BeautifulSoup
I'm developing an app that inputs data onto a webpage shopping cart and verifies the total. That works fine, however, I am having issue with parsing the HTML output.
A previous discussion; retrieving essential data from a webpage using python, recommended using Beautifu... | Python - Error Parsing HTML w/ BeautifulSoup | I'm developing an app that inputs data onto a webpage shopping cart and verifies the total. That works fine, however, I am having issue with parsing the HTML output.
A previous discussion; retrieving essential data from a webpage using python, recommended using BeautifulSoup to make solve said user's problem.
I've bor... | [
"As to why it doesn't work on Ubutntu, no idea. However, you can try this:\ndump = [(cell.getText() if cell.getText() else '').strip() for cell in table.findAll('td')]\n\n",
"It doesn't seem to be a problem with the code but with the HTML you are reading, what I would do is changing your code to do this:\ndump = ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006837687_python.txt |
Q:
Adding Dynamic elements to logging.filters in django 1.3
I'm attempting to add some contextual information to some logs via the logging module. I need to be able to view a projectid next to each line in the logs, with over 20,000 projects created daily this data is really helpful. To do this I've created a derivat... | Adding Dynamic elements to logging.filters in django 1.3 | I'm attempting to add some contextual information to some logs via the logging module. I need to be able to view a projectid next to each line in the logs, with over 20,000 projects created daily this data is really helpful. To do this I've created a derivative of the logging.Filter module.
import logging
class MTFil... | [
"\nWhat I'd like to do is grab the 'projectid' value dynamically somehow,\n eg. when creating a logger object, or using some Middleware but I just\n don't know how to do it.\n\nIt's not appropriate to do this when creating a logger, as that's a one-time operation. What you probably need to do is to find some way ... | [
3,
0
] | [] | [] | [
"django",
"django_1.3",
"filter",
"logging",
"python"
] | stackoverflow_0006827078_django_django_1.3_filter_logging_python.txt |
Q:
What is the best way to parse a log file into a python list?
I have an interesting log file format and I would like to parse it into Python for analysis.
The format is key=value with each separated by tabs, and a newline at the end of each entry, like this:
date="Mon, 04 Jul 2011 05:05:45 GMT" addr=127.0.0.1 ... | What is the best way to parse a log file into a python list? | I have an interesting log file format and I would like to parse it into Python for analysis.
The format is key=value with each separated by tabs, and a newline at the end of each entry, like this:
date="Mon, 04 Jul 2011 05:05:45 GMT" addr=127.0.0.1 response_time=13 method=GET url=/ status=200 referrer= us... | [
"Two for loops seems fine for this problem. If I were coding it, I'd probably do something like this:\nwith open('log_file') as f:\n for line in f:\n fields = line.split('\\t')\n for field in fields:\n key,_,val = field.partition('=')\n # Do something with each key and val\n\n... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006838604_python.txt |
Q:
Python - is there an elegant way to avoid dozens try/except blocks while getting data out of a json object?
I'm looking for ways to write functions like get_profile(js) but without all the ugly try/excepts.
Each assignment is in a try/except because occasionally the json field doesn't exist. I'd be happy with an ... | Python - is there an elegant way to avoid dozens try/except blocks while getting data out of a json object? | I'm looking for ways to write functions like get_profile(js) but without all the ugly try/excepts.
Each assignment is in a try/except because occasionally the json field doesn't exist. I'd be happy with an elegant solution which defaulted everything to None even though I'm setting some defaults to [] and such, if doin... | [
"\nUse get(key[, default]) method of dictionaries\nCode generate this boilerplate code and save yourself even more trouble.\n\n",
"Replace each of your try catch blocks with chained calls to the dictionary get(key [,default]) method. All calls to get before the last call in the chain should have a default value o... | [
8,
8,
3,
2,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0006838681_json_python.txt |
Q:
How can I load an NPAPI plugin in my own application?
The docs I've found on NPAPI plugins explain how to write plugins to be loaded by browsers, but how hard is it to write an application that loads existing NPAPI plugins?
(My ultimate goal here is to find a way to use SWF content inside an application written wi... | How can I load an NPAPI plugin in my own application? | The docs I've found on NPAPI plugins explain how to write plugins to be loaded by browsers, but how hard is it to write an application that loads existing NPAPI plugins?
(My ultimate goal here is to find a way to use SWF content inside an application written with Python and wxPython in Linux. I've accomplished this on ... | [
"Your best bet (assuming basing your hosting code on open source software isn't an issue for you licensing-wise) is probably to look at the implementation of NPAPI host in WebKit, Chromium, and/or Gecko.\nThe Mozilla documentation for the browser side of NPAPI will help, but there are a lot of little corner cases w... | [
0
] | [] | [] | [
"flash",
"linux",
"npapi",
"python"
] | stackoverflow_0006838281_flash_linux_npapi_python.txt |
Q:
removing http referer problem
I want to remove the http referer from the header while redirecting to other page. I am using python and django in the application. Is there a way to remove or reset the referer info.
A:
Referer header is sent by the browser, so you can't control it from the server side.
| removing http referer problem | I want to remove the http referer from the header while redirecting to other page. I am using python and django in the application. Is there a way to remove or reset the referer info.
| [
"Referer header is sent by the browser, so you can't control it from the server side.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006839116_django_python.txt |
Q:
Twisted task.loop and pb auth
Learn Twisted. I decided to write a server and client that once a second to share data.
Wrote one implementation, but it seems to me that it is not correct.
# -*- coding: utf-8 -*-
from twisted.spread import pb
from twisted.internet import reactor, task
from twisted.cred import crede... | Twisted task.loop and pb auth | Learn Twisted. I decided to write a server and client that once a second to share data.
Wrote one implementation, but it seems to me that it is not correct.
# -*- coding: utf-8 -*-
from twisted.spread import pb
from twisted.internet import reactor, task
from twisted.cred import credentials
from win32com.server import ... | [
"I believe this should do the trick.\n# Upper case first letter of class name is good policy.\nclass Login_send:\n\n def __init__(self):\n # initialize the state variable to False.\n self.connection = False\n self.count=0\n self.timeout = 1.0\n self.factory = pb.PBClientFactory... | [
2
] | [] | [] | [
"loops",
"python",
"twisted"
] | stackoverflow_0006838728_loops_python_twisted.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.