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:
Creating Dependency Graphs in Python
I have inherited a huge codebase that I need to make some small changes into. I was wondering if there are utilities that would parse python code and give dependencies between functions, as in if I make changes to a function I want to be sure that I dont break other functions, ... | Creating Dependency Graphs in Python | I have inherited a huge codebase that I need to make some small changes into. I was wondering if there are utilities that would parse python code and give dependencies between functions, as in if I make changes to a function I want to be sure that I dont break other functions, so if I could see in a graph like diagram ... | [
"\nUsually \"dependency\" is defined for module / package import.\nWhat you are looking for is a visualizing call flow.\n\nhttp://pycallgraph.slowchop.com/\n\nYou can still not guarantee that you will not break functionality :)\nMy experience and solution:\nMany a times, I found the call flow data overwhelming and ... | [
35
] | [] | [] | [
"call_flow",
"dependency_management",
"python"
] | stackoverflow_0004160746_call_flow_dependency_management_python.txt |
Q:
How badly should I avoid surrogate primary keys in SQL?
Short story
I have a technical problem with a third-party library at my hands that I seem to be unable to easily solve in a way other than creating a surrogate key (despite the fact that I'll never need it). I've read a number of articles on the Net discourag... | How badly should I avoid surrogate primary keys in SQL? | Short story
I have a technical problem with a third-party library at my hands that I seem to be unable to easily solve in a way other than creating a surrogate key (despite the fact that I'll never need it). I've read a number of articles on the Net discouraging the use of surrogate keys, and I'm a bit at a loss if it ... | [
"I always make surrogate keys when using ORMs (or rather, I let the ORMs make them for me). They solve a number of problems, and don't introduce any (major) problems.\nSo, you've done your job by acknowledging that there are \"papers on the net\" with valid reasons to avoid surrogate keys, and that there's probably... | [
2,
0,
0
] | [] | [] | [
"primary_key",
"python",
"sqlalchemy"
] | stackoverflow_0003712949_primary_key_python_sqlalchemy.txt |
Q:
Algorithm Python uses to decide between >>> and ... prompt in interactive console?
I'm implementing a custom (Iron)Python console.
I need to display a >>> prompt in general, but when a statement is incomplete, I need to change the prompt to ... and gather more lines before executing them.
How do I know if a line e... | Algorithm Python uses to decide between >>> and ... prompt in interactive console? | I'm implementing a custom (Iron)Python console.
I need to display a >>> prompt in general, but when a statement is incomplete, I need to change the prompt to ... and gather more lines before executing them.
How do I know if a line entered by a user is complete or if I need to read more lines?
A simple way seems to be c... | [
"It's impractical to try to guess from just looking at the code string for colons and brackets. You would end up needing to implement half the Python parser to get that right.\nThe standard library code module reproduces the behaviour of the interactive Python interpreter, and I believe it is this module that IronP... | [
5,
3,
3,
1
] | [] | [] | [
"console",
"interactive",
"ironpython",
"python",
"read_eval_print_loop"
] | stackoverflow_0004160534_console_interactive_ironpython_python_read_eval_print_loop.txt |
Q:
Caught TypeError while rendering: 'BoundField' object is not iterable
I am trying to display a list of tags as the tag.name (instead of the list). However when I try and run a for-loop over the list, it throws the "Caught TypeError while rendering: 'BoundField' object is not iterable."
<dd>{% for tag in form.tag... | Caught TypeError while rendering: 'BoundField' object is not iterable | I am trying to display a list of tags as the tag.name (instead of the list). However when I try and run a for-loop over the list, it throws the "Caught TypeError while rendering: 'BoundField' object is not iterable."
<dd>{% for tag in form.tags %}{{tag.name}}{% endfor %}</dd>
Iterating through .all will load the pag... | [
"Code from a Howto Post\n\nTemplate:\n{% for tag in blogpost.get_tags %}\n <a href=\"/blog/tag/{{tag}}\" alt=\"{{tag}}\" title=\"{{tag}}\">{{tag}}</a>\n{%endfor%}\n\n\n\nModel:\nfrom django.db import models\nfrom tagging.fields import TagField\nfrom tagging.models import Tag\n\nclass BlogPost(models.Model):\n\n ... | [
1,
0,
0
] | [] | [] | [
"django",
"django_forms",
"django_views",
"python"
] | stackoverflow_0004159400_django_django_forms_django_views_python.txt |
Q:
Unable to close a stream opened with pycurl
I am working on a client for a web service using pycurl. The client opens a connection to a stream service and spawns it into a separate thread. Here's a stripped down version of how the connection is set up:
def _setup_connection(self):
self.conn = pycurl.Curl()
... | Unable to close a stream opened with pycurl | I am working on a client for a web service using pycurl. The client opens a connection to a stream service and spawns it into a separate thread. Here's a stripped down version of how the connection is set up:
def _setup_connection(self):
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.URL, FILTER_URL)
s... | [
"It sounds like you are invoking close() in one thread while another thread is executing perform(). Luckily, the library warns you rather than descending into unknown behavior-ville.\nYou should only use the curl session from one thread - or have the perform() thread somehow communicate when the call to perform() ... | [
1,
0
] | [] | [] | [
"multithreading",
"pycurl",
"python"
] | stackoverflow_0003788463_multithreading_pycurl_python.txt |
Q:
How to override the `is` operator
Possible Duplicate:
python: class override “is” behavior
I am trying to override the is operator, so that I could do something like
if tom is writer:
print 'tom is writing'
elif tom is programmer:
print 'tom is programming'
Is this possible in python?
A:
As far as I kno... | How to override the `is` operator |
Possible Duplicate:
python: class override “is” behavior
I am trying to override the is operator, so that I could do something like
if tom is writer:
print 'tom is writing'
elif tom is programmer:
print 'tom is programming'
Is this possible in python?
| [
"As far as I know, you can't override 'is' because it tests whether two objects are the same object by comparing their memory addresses (i.e. pointer comparison). You probably want to override '==' by implementing tom's __eq__ method.\n",
"The Python way to test for the type of an object is to use isinstance, as ... | [
5,
3
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0004160876_operators_python.txt |
Q:
problem with email parsing with python and multiple Received records
I am trying to parse emails with python email.parser. When my email contains multiple Received records, email.parser seems like ignoring those records.
Fore example, for input :
...
Received: from localhost (jalapeno [127.0.0.1])
by jmason.or... | problem with email parsing with python and multiple Received records | I am trying to parse emails with python email.parser. When my email contains multiple Received records, email.parser seems like ignoring those records.
Fore example, for input :
...
Received: from localhost (jalapeno [127.0.0.1])
by jmason.org (Postfix) with ESMTP id 5C4E816F6D
for <jm@localhost>; Sun, 6 Oct 2... | [
"The python doc for email.__getitem__() says:\n\nNote that if the named field appears\n more than once in the message’s\n headers, exactly which of those field\n values will be returned is undefined.\n Use the get_all() method to get the\n values of all the extant named\n headers.\n\nso, use e.get_all(i) inst... | [
2
] | [] | [] | [
"email",
"parsing",
"python"
] | stackoverflow_0004161122_email_parsing_python.txt |
Q:
Python "Value Error: cannot delete array elements" -- Why am I getting this?
I haven't been able to find anything about this value error online and I am at a complete loss as to why my code is eliciting this response.
I have a large dictionary of around 50 keys. The value associated with each key is a 2D array of... | Python "Value Error: cannot delete array elements" -- Why am I getting this? | I haven't been able to find anything about this value error online and I am at a complete loss as to why my code is eliciting this response.
I have a large dictionary of around 50 keys. The value associated with each key is a 2D array of many elements of the form [datetime object, some other info]. A sample would look... | [
"If you use numpy arrays, then use them as arrays and not as lists\nnumpy does comparison elementwise for the entire array, which can then be used to select the relevant subarray. This also removes the need for the inner loop.\n>>> a = np.array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1],\n ... | [
6,
3
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0004048011_arrays_numpy_python.txt |
Q:
regular expression to filter out part of key value in a json string
I have the following JSON string as part of a log line.
cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}
I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}.
How can do this using regular... | regular expression to filter out part of key value in a json string | I have the following JSON string as part of a log line.
cells : {"Lac":"7824","CntryISO":"us","NetTyp":"GSM","NetOp":"310260","Cid":"11983"}
I want to filter out to the following format: {"Lac":"7824","Cid":"11983"}.
How can do this using regular expression ? in Javascript or Python ?
the keys are constant strings(Lac... | [
"Why don't you just delete them in JavaScript?\nvar myJson = {\"Lac\":\"7824\",\"CntryISO\":\"us\",\"NetTyp\":\"GSM\",\"NetOp\":\"310260\",\"Cid\":\"11983\"};\n\ndelete myJson.Lac;\ndelete myJson.cId;\n\n",
"To expand and explain @alex answer:\nJSON is a nested multi dimensional structure. Simply filtering the \... | [
5,
1,
0
] | [] | [] | [
"javascript",
"python",
"regex"
] | stackoverflow_0004160997_javascript_python_regex.txt |
Q:
Union of two iterators
Consider the iterators count(3,3) and count(5,5). How can I create a iterator that outputs only the numbers that occur in either count(3,3) and count(5,5)?
A:
For the sake of having an answer to this question, OP accepted (x for x in count(3) if not x%3 or not x%5) as a solution in the com... | Union of two iterators | Consider the iterators count(3,3) and count(5,5). How can I create a iterator that outputs only the numbers that occur in either count(3,3) and count(5,5)?
| [
"For the sake of having an answer to this question, OP accepted (x for x in count(3) if not x%3 or not x%5) as a solution in the comments. What follows below should work for the general case so long as duplicates are acceptable. If duplicates aren't acceptable, it could be wrapped in a function that stored its outp... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004161318_python.txt |
Q:
Pass in variable to Mako template
In Perl, by using Template Toolkit, here is what I do
Perl
my $vars = {
name => 'Count Edward van Halen',
};
$tt->process('letters/overdrawn', $vars)
|| die $tt->error(), "\n";
HTML
Dear [% name %],
In Mako template, how can I do so? Check through their render funct... | Pass in variable to Mako template | In Perl, by using Template Toolkit, here is what I do
Perl
my $vars = {
name => 'Count Edward van Halen',
};
$tt->process('letters/overdrawn', $vars)
|| die $tt->error(), "\n";
HTML
Dear [% name %],
In Mako template, how can I do so? Check through their render function, doesn't get much hint.
| [
"Use named arguments\nmytemplate.render(myvar1=\"var1\", mydict=dict())\n\nIn the mako side you'd do\n${myvar1}\n% for val in mydict:\n ${val}\n% endfor\n\n"
] | [
7
] | [] | [] | [
"mako",
"python"
] | stackoverflow_0004161464_mako_python.txt |
Q:
Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue?
I'd like to do something like this:
twistedServer.start() # This would be a nonblocking call
while True:
while twistedServer.haveMessage():
message = twistedServer.getMessage()
respon... | Pattern for a background Twisted server that fills an incoming message queue and empties an outgoing message queue? | I'd like to do something like this:
twistedServer.start() # This would be a nonblocking call
while True:
while twistedServer.haveMessage():
message = twistedServer.getMessage()
response = handleMessage(message)
twistedServer.sendResponse(response)
doSomeOtherLogic()
The key thing I want to do ... | [
"\nThe key thing I want to do is run the server in a background thread.\n\nYou don't explain why this is key, though. Generally, things like \"use threads\" are implementation details. Perhaps threads are appropriate, perhaps not, but the actual goal is agnostic on the point. What is your goal? To handle multip... | [
10
] | [] | [] | [
"background",
"client",
"nonblocking",
"python",
"twisted"
] | stackoverflow_0004161403_background_client_nonblocking_python_twisted.txt |
Q:
Error installing virtualenv on Mac OS 10.6
When I try to install virtualenv on my local machine running OS 10.6.4, I get the following:
Searching for virtualenv
Reading http://pypi.python.org/simple/virtualenv/
Reading http://virtualenv.openplans.org
Best match: virtualenv 1.5.1
Downloading http://pypi.python.org/... | Error installing virtualenv on Mac OS 10.6 | When I try to install virtualenv on my local machine running OS 10.6.4, I get the following:
Searching for virtualenv
Reading http://pypi.python.org/simple/virtualenv/
Reading http://virtualenv.openplans.org
Best match: virtualenv 1.5.1
Downloading http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.5.1.ta... | [
"You need to have root permission to install into /usr/local/bin. If you are using the easy_install command, do:\n$ sudo easy_install virtualenv\n\n"
] | [
5
] | [] | [] | [
"command_line",
"python",
"terminal",
"virtualenv"
] | stackoverflow_0004162196_command_line_python_terminal_virtualenv.txt |
Q:
Uploading a video to google app engine blobstore
I'm trying to associate a video file to a record with a bunch of properties, but can't seem to allow the user to do everything in one form - name the video, provide description and answer some question, AND upload the file.
Here are the steps I'd like to perform:
U... | Uploading a video to google app engine blobstore | I'm trying to associate a video file to a record with a bunch of properties, but can't seem to allow the user to do everything in one form - name the video, provide description and answer some question, AND upload the file.
Here are the steps I'd like to perform:
User is served with a page containing a form with the f... | [
"http://demofileuploadgae.appspot.com/ - My demo uploader to the blobstore.\nMy code for the upload: http://code.google.com/p/gwt-examples/source/browse/trunk/DemoUpload/src/org/gonevertical/upload/#upload/server%3Fstate%3Dclosed\n",
"Here's the code I'm using to upload images and associate them with articles. Th... | [
5,
3,
1
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0003409375_blobstore_google_app_engine_python.txt |
Q:
jquery: post with json will actually post array
I have a python as CGI and the POST from jquery will transform json object to array, so when I see the POST from jquery, I actually see:
login_user[username]=dfdsfdsf&login_user[password]=dsfsdf
(the [ and ] already escaped)
My question is how I can convert this str... | jquery: post with json will actually post array | I have a python as CGI and the POST from jquery will transform json object to array, so when I see the POST from jquery, I actually see:
login_user[username]=dfdsfdsf&login_user[password]=dsfsdf
(the [ and ] already escaped)
My question is how I can convert this string back to JSON in python? Or, how can I convert thi... | [
"If what you want to accomplish is to send structured data from the browser and then unpack it in your Python backend and keep the same structure, I suggest the following:\n\nCreate JavaScript objects in the browser to hold your data:\nvar d = {} \nd['login_user'] = { 'username': 'foo', 'password': 'bar' }\n\nSeria... | [
5,
1,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0004162339_json_python.txt |
Q:
How can you POST JSON?
I have a python FastCGI server which accepts POST from client, I want to use JSON as the format to communicate between the client and server, but it really confuse me how it works.
The JSON representation in javascript is:
{'login_user': {'username':username, 'password':password}}
When I po... | How can you POST JSON? | I have a python FastCGI server which accepts POST from client, I want to use JSON as the format to communicate between the client and server, but it really confuse me how it works.
The JSON representation in javascript is:
{'login_user': {'username':username, 'password':password}}
When I post this JSON object, the jqu... | [
"XML for communication for a web-app? Take a deep breath and think about it. If you have doubts about it, then it means you really have no need for it. You rely on XML for fairly complex data sets with potential heavy modifications to the format of a protocol to be foreseen over time. By nature XML would make this ... | [
2
] | [] | [] | [
"jquery",
"json",
"python"
] | stackoverflow_0004162500_jquery_json_python.txt |
Q:
How to unescape a query string
I have a query string as follows:
cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf
How do I unescape it in python?
A:
import urllib
print urllib.unquote("cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf")
A:
... | How to unescape a query string | I have a query string as follows:
cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf
How do I unescape it in python?
| [
"import urllib\n\nprint urllib.unquote(\"cmd%5Blogin_user%5D%5Busername%5D=dfdsfdsf&cmd%5Blogin_user%5D%5Bpassword%5D=dsfsdf\")\n\n",
"Another way is to use the following function:\nxml.sax.saxutils.unescape()\n"
] | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004162179_python.txt |
Q:
Django request get parameters
In a Django request I have the following:
POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}>
How do I get the values of section and MAINS?
if request.method == 'GET':
qd = request.GET
elif request.method == 'POST':
qd = request.POST
section_id = qd.__getitem__('sect... | Django request get parameters | In a Django request I have the following:
POST:<QueryDict: {u'section': [u'39'], u'MAINS': [u'137']}>
How do I get the values of section and MAINS?
if request.method == 'GET':
qd = request.GET
elif request.method == 'POST':
qd = request.POST
section_id = qd.__getitem__('section') or getlist....
| [
"You may also use:\nrequest.POST.get('section','') # => [39]\nrequest.POST.get('MAINS','') # => [137] \nrequest.GET.get('section','') # => [39]\nrequest.GET.get('MAINS','') # => [137]\n\nUsing this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an excep... | [
223,
108
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0004162625_django_django_models_django_views_python.txt |
Q:
Stack performance in programming languages
Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version:
public class Fib {
public static int ... | Stack performance in programming languages | Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version:
public class Fib {
public static int fib(int n) {
if (n < 2) return 1;
return fib... | [
"You might want to crank up the optimisation level of your C compiler. With gcc -O3, that makes a big difference, a drop from 2.015 seconds to 0.766 seconds, a reduction of about 62%.\nBeyond that, you need to ensure you've tested correctly. You should run each program ten times, remove the outliers (fastest and sl... | [
17,
11,
4,
4,
2,
1,
1,
0
] | [] | [] | [
"c",
"java",
"ocaml",
"performance",
"python"
] | stackoverflow_0004121790_c_java_ocaml_performance_python.txt |
Q:
Two Zope/Plone machines and SSO
I'm installing an environment where I had two Zope/Plone servers:
plone1 -> for web content & user authentication
plone2 -> for web applications
I want to implement SSO around both servers but I don't know how to do it. I try to modify login_next and setAuthCookie(..) to share the... | Two Zope/Plone machines and SSO | I'm installing an environment where I had two Zope/Plone servers:
plone1 -> for web content & user authentication
plone2 -> for web applications
I want to implement SSO around both servers but I don't know how to do it. I try to modify login_next and setAuthCookie(..) to share the __ac cookie in the domain, but didn'... | [
"I haven't done this yet, but may need to do so. So this is what I've gathered so far.\nCAS\nPlone as CAS server and as CAS client. \nPubCookie\nSee the Pubcookie documentation.\nHere's a writeup of setting it up with Plone: Single Sign On with Pubcookie\nMore on pubcookie and plone: Setting up Apache, Plone, and P... | [
1,
0
] | [] | [] | [
"plone",
"python",
"single_sign_on",
"zope"
] | stackoverflow_0003666676_plone_python_single_sign_on_zope.txt |
Q:
Create an object using Python's C API
Say I have my object layout defined as:
typedef struct {
PyObject_HEAD
// Other stuff...
} pyfoo;
...and my type definition:
static PyTypeObject pyfoo_T = {
PyObject_HEAD_INIT(NULL)
// ...
pyfoo_new,
};
How do I create a new instance of pyfoo somewhere w... | Create an object using Python's C API | Say I have my object layout defined as:
typedef struct {
PyObject_HEAD
// Other stuff...
} pyfoo;
...and my type definition:
static PyTypeObject pyfoo_T = {
PyObject_HEAD_INIT(NULL)
// ...
pyfoo_new,
};
How do I create a new instance of pyfoo somewhere within my C extension?
| [
"Call PyObject_New(), followed by PyObject_Init().\nEDIT: The best way is to call the class object, just like in Python itself:\n/* Pass two arguments, a string and an int. */\nPyObject *argList = Py_BuildValue(\"si\", \"hello\", 42);\n\n/* Call the class object. */\nPyObject *obj = PyObject_CallObject((PyObject *)... | [
55
] | [] | [] | [
"c",
"python",
"python_c_api",
"python_embedding",
"python_extensions"
] | stackoverflow_0004163018_c_python_python_c_api_python_embedding_python_extensions.txt |
Q:
Is there a working rc-script for Celery on FreeBSD?
I have hacked together an rc script for celeryd on FreeBSD, but I can't help but think that there must be a better way. celeryd does not daemonize itself, and it seems to have a hard time responding to sigterm as well, so it might be complicated to get to work.
... | Is there a working rc-script for Celery on FreeBSD? | I have hacked together an rc script for celeryd on FreeBSD, but I can't help but think that there must be a better way. celeryd does not daemonize itself, and it seems to have a hard time responding to sigterm as well, so it might be complicated to get to work.
Is this a problem that someone else has solved before?
| [
"There's an experimental init.d script here:\nhttps://github.com/ask/celery/tree/master/contrib/generic-init.d/\nI don't know if it has been tested on FreeBSD, but it should definitely be made\nto work there.\nWhat do you mean celeryd isn't responding to TERM? This is the recommended signal\nto use for a clean shu... | [
1
] | [] | [] | [
"celery",
"freebsd",
"python",
"startup",
"startupscript"
] | stackoverflow_0004162303_celery_freebsd_python_startup_startupscript.txt |
Q:
AJAX and browser GET calls appear to have different cookies
I have 2 pages, a static html page and a python script - hosted on [local] google app engine.
/html/hello.html
define as login: required
/broadcast
which is a python script
when I access hello.html for the first time I am redirected to login page, I sign ... | AJAX and browser GET calls appear to have different cookies | I have 2 pages, a static html page and a python script - hosted on [local] google app engine.
/html/hello.html
define as login: required
/broadcast
which is a python script
when I access hello.html for the first time I am redirected to login page, I sign in, and then redirected back to hello.html.
inside hello.html - a... | [
"Stupid me... \nThe ajax call was to localhost/broadcast\nand the browser address field was 127.0.0.1/broadcast\n...\nthe cookies for \"different\" domains ('127.0.0.1' != 'localhost') are not shared ofcourse...\nThen I haven't gone mad... \n"
] | [
2
] | [] | [] | [
"ajax",
"google_app_engine",
"javascript",
"jquery",
"python"
] | stackoverflow_0004163748_ajax_google_app_engine_javascript_jquery_python.txt |
Q:
Not root user, how to kill subprocess in python 2.4
I want to kill a subprocess if the time of executing is too long.
I know I have to use os.kill or os.killpg.
However, the problems comes out when if I am not a root user. For example, in my designed GUI, I want to call subprocess, and os.kill or os.killpg to kil... | Not root user, how to kill subprocess in python 2.4 | I want to kill a subprocess if the time of executing is too long.
I know I have to use os.kill or os.killpg.
However, the problems comes out when if I am not a root user. For example, in my designed GUI, I want to call subprocess, and os.kill or os.killpg to kill the subprocess. But my GUI is owned by apache. So when ... | [
"Remove sudo from the subprocess command if it's possible which you should do because you shouldn't run a subprocess in a sudo user from your GUI , it's definitely a security breach:\nsubprocess.Popen(commandtosend, shell=True,preexec_fn=os\n ^^\n Here don't put sudo\n\nLike this you... | [
5,
3
] | [] | [] | [
"apache",
"python",
"subprocess",
"user_interface"
] | stackoverflow_0004163200_apache_python_subprocess_user_interface.txt |
Q:
writing python script on windows
I am new to python scripts .
I have few repetative testing tasks such logging to various IM's
ex (OCS,different public messengers) etc .
Is it possible to automate these tasks using python .
If so from where do I start with ?
Working on windows 2003 server .
I know the basics ... | writing python script on windows | I am new to python scripts .
I have few repetative testing tasks such logging to various IM's
ex (OCS,different public messengers) etc .
Is it possible to automate these tasks using python .
If so from where do I start with ?
Working on windows 2003 server .
I know the basics of python. want to enhance the skills .... | [
"Not quite a duplicate question, but the answers to \"How can we use ms office communicator client exposed APIs in python, is that possible ?\" should prove valuable.\nIf you are new to Python, you'll want to check out the Python Tutorial. \nYou may also wish to consider something a bit more Windows-oriented like V... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004164000_python.txt |
Q:
Stylesheet parsing error for [dir=rtl] when using cssutils python module
I'm parsing a css stylesheet with cssutils python module.
The parser emits an error when reaching the "[dir=ltr] div.row div.label" selector.
I would like to find a way to modify the CSS to make the parser happy and maintain the same function... | Stylesheet parsing error for [dir=rtl] when using cssutils python module | I'm parsing a css stylesheet with cssutils python module.
The parser emits an error when reaching the "[dir=ltr] div.row div.label" selector.
I would like to find a way to modify the CSS to make the parser happy and maintain the same functionality.
What would be the standard way for this:
div.row div.label {
float: le... | [
"it's a bit slower but\n*[dir=ltr] div.row div.label, *[dir=rtl] div.row div.formw {\n float: left;\n text-align: right;\n}\n*[dir=rtl] div.row div.label, *[dir=ltr] div.row div.formw {\n float: right;\n text-align: left;\n}\n\nshould work. Obviously change * with the element with this attribute if is possible\n"
] | [
3
] | [] | [] | [
"css",
"css_parsing",
"css_selectors",
"html",
"python"
] | stackoverflow_0004164049_css_css_parsing_css_selectors_html_python.txt |
Q:
How do I add a factory created type as a header in suds?
I can't seem to get suds working with my setup. I have to pass a context, with a remote user set before I can use any of the functions in the API. What I tried to do was this:
client = Client(url, username=userid, password=password)
apiContext = client.fac... | How do I add a factory created type as a header in suds? | I can't seem to get suds working with my setup. I have to pass a context, with a remote user set before I can use any of the functions in the API. What I tried to do was this:
client = Client(url, username=userid, password=password)
apiContext = client.factory.create("apiCallContext") # This is listed in the type... | [
"Without knowing the exact spec of the webservice you are working with, I can only hazard a guess at this answer, but the header looks similar to a web service I have used in the past. Have you tried creating the elements directly and passing them into the header thus?: \nfrom suds.sax.element import Element\n...\... | [
1
] | [] | [] | [
"header",
"python",
"soap",
"suds"
] | stackoverflow_0004107978_header_python_soap_suds.txt |
Q:
Most appropriate data structure (Python)
I'm new to Python and have what is probably a very basic question about the 'best' way to store data in my code. Any advice much appreciated!
I have a long .csv file in the following format:
Scenario,Year,Month,Value
1,1961,1,0.5
1,1961,2,0.7
1,1961,3,0.2
etc.
My scenario ... | Most appropriate data structure (Python) | I'm new to Python and have what is probably a very basic question about the 'best' way to store data in my code. Any advice much appreciated!
I have a long .csv file in the following format:
Scenario,Year,Month,Value
1,1961,1,0.5
1,1961,2,0.7
1,1961,3,0.2
etc.
My scenario values run from 1 to 100, year goes from 1961 ... | [
"I'd use a dict of tuples. Simple, fast, and a hash-table look-up to retrieve a single value:\nimport csv\n\nreader = csv.reader(open('data.csv', 'rb'))\nheader = reader.next()\ndata = {}\n\nfor row in reader:\n key = tuple([int(v) for v in row[:-1]])\n val = row[-1]\n data[key] = float(val)\n\n# Retrieve... | [
7,
4,
2,
0
] | [] | [] | [
"arrays",
"data_structures",
"dictionary",
"python"
] | stackoverflow_0004164303_arrays_data_structures_dictionary_python.txt |
Q:
Python - how to read path file/folder from server
Using Python, how might one read a file's path from a remote server?
This is a bit more clear to me on my local PC.
A:
See Reading and Writing Files in the Python Tutorial, which is a great place to start for a newbie.
Be sure to escape your backslashes on Window... | Python - how to read path file/folder from server | Using Python, how might one read a file's path from a remote server?
This is a bit more clear to me on my local PC.
| [
"See Reading and Writing Files in the Python Tutorial, which is a great place to start for a newbie.\nBe sure to escape your backslashes on Windows, viz:\nf=open('\\\\\\\\SERVER\\\\share\\\\file.ext', 'r')\n\nor use \"raw\" strings: \nf=open(r'\\\\SERVER\\share\\file.ext', 'r')\n\n",
"use the os.path module to ma... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0004163456_python.txt |
Q:
youtube data api comment paging
I'm struggling a little bit with the syntax for iterating through all comments on a youtube video. I'm using the python and have found little documentation on the GetYouTubeVideoCommentFeed() function.
What I'm really trying to do is search all comments of a video for an instance of... | youtube data api comment paging | I'm struggling a little bit with the syntax for iterating through all comments on a youtube video. I'm using the python and have found little documentation on the GetYouTubeVideoCommentFeed() function.
What I'm really trying to do is search all comments of a video for an instance of a word and increase a counter (event... | [
"Here's the code snippet for the same: \n# Comment feed URL\ncomment_feed_url = \"http://gdata.youtube.com/feeds/api/videos/%s/comments\"\n\n''' Get the comment feed of a video given a video_id''' \ndef WriteCommentFeed(video_id, data_file): \n url = comment_feed_url % video_id\n comment_feed = yt_se... | [
5,
1
] | [] | [] | [
"python",
"youtube",
"youtube_api"
] | stackoverflow_0001901487_python_youtube_youtube_api.txt |
Q:
Datetime to Second Conversion
i have two datetime string like this '2010-08-31 04:35:50.176725' and '2010-09-05 04:35:50.176725' . now my question is how calculate seconds between two dates. i used time delta but its return in hour, minute formate. i want compltely in seconds.
A:
import datetime as dt
import tim... | Datetime to Second Conversion |
i have two datetime string like this '2010-08-31 04:35:50.176725' and '2010-09-05 04:35:50.176725' . now my question is how calculate seconds between two dates. i used time delta but its return in hour, minute formate. i want compltely in seconds.
| [
"import datetime as dt\nimport time\n\nnow=dt.datetime.now()\n\nThe Epoch is defined as 1970-01-01 00:00:00 GMT.\nYou can find the number of seconds between now and the Epoch this way:\nprint(time.mktime(now.timetuple()))\n# 1289565310.0\n\nOr, if you wish to find the number of seconds between two dt.datetime objec... | [
14,
0
] | [] | [] | [
"python"
] | stackoverflow_0004164518_python.txt |
Q:
Use ssh key to encrypt and decrypt a password
My python-script (Python 2.6, on Debian Linux) asks the user for a password, wich is then saved in the users home directory.
Because i don't want to safe the password as plain text, i want to encrypt it somehow. So i thought that maybe i could use the (private) ssh-ke... | Use ssh key to encrypt and decrypt a password | My python-script (Python 2.6, on Debian Linux) asks the user for a password, wich is then saved in the users home directory.
Because i don't want to safe the password as plain text, i want to encrypt it somehow. So i thought that maybe i could use the (private) ssh-key of the user to encrypt and decrypt the password t... | [
"The only thing that's definitely worth doing is storing the file that only the user can read.\nYour argument for using the ssh key seems to be something like the following:\n\nI need to store a password, so I'll encrypt it\nIf I use the user's ssh key to do the encryption this will prevent someone decrypting the p... | [
5,
2
] | [] | [] | [
"python",
"ssh_keys"
] | stackoverflow_0004165042_python_ssh_keys.txt |
Q:
On-value-change type of event for widgets or use .trace_variable() technique?
Is there an on-value-change type of event for data input widgets like Entry, Text, Spinner, Checkbutton, Radiobutton? By on-value-change, I mean the ability to detect when the value of a widget has changed due to keyboard input or cut/de... | On-value-change type of event for widgets or use .trace_variable() technique? | Is there an on-value-change type of event for data input widgets like Entry, Text, Spinner, Checkbutton, Radiobutton? By on-value-change, I mean the ability to detect when the value of a widget has changed due to keyboard input or cut/delete/paste (and Text edit_undo/edit_redo) activity? I see no such event described i... | [
"Different widgets call for different solutions. For example, check buttons and radio buttons have a command option, and with an entry widget you can use the built-in validation features. \nFor all the widgets that can be tied to a variable, doing a variable trace is a common solution. The text widget is one except... | [
1
] | [] | [] | [
"events",
"python",
"tkinter",
"ttk",
"user_interface"
] | stackoverflow_0004165164_events_python_tkinter_ttk_user_interface.txt |
Q:
Gedit not getting views on window creation (Plugin development)
I am developing a plugin for Gedit.
import gedit
class ReloadOnSave(gedit.Plugin):
def __init__(self):
gedit.Plugin.__init__(self)
def activate(self, window):
for view in window.get_views():
self.connect_handlers... | Gedit not getting views on window creation (Plugin development) | I am developing a plugin for Gedit.
import gedit
class ReloadOnSave(gedit.Plugin):
def __init__(self):
gedit.Plugin.__init__(self)
def activate(self, window):
for view in window.get_views():
self.connect_handlers(view)
def connect_handlers(self, view):
print 'Reached ... | [
"That happens because when your plugin is activated, you don't have any tabs yet. Tabs are created after plugin activation. You might want to listen to the \"tab-added\" and \"tab-removed\" signals to fix that.\n"
] | [
4
] | [] | [] | [
"gedit",
"plugins",
"python"
] | stackoverflow_0004164078_gedit_plugins_python.txt |
Q:
problem with arrays in python ,help!
I am making a program in python and I am having an error that I cannot solve.
This is the problem:
I have a set to points in 3D space, and I am storing it in a vector(rake).
My point is to build a stream surface.
So I am appending those points to another list so that I can have... | problem with arrays in python ,help! | I am making a program in python and I am having an error that I cannot solve.
This is the problem:
I have a set to points in 3D space, and I am storing it in a vector(rake).
My point is to build a stream surface.
So I am appending those points to another list so that I can have all the points from the "line" before.
Th... | [
"Your main problem is that you should use extend instead of append:\npoints_list.extend(rake)\n\nThis is because append adds a single object to the end of the list. In this case it means that the entire second list is appended as a single element.\n\nappend - append object to end\n extend - extend list by appendin... | [
3,
1
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0004165626_arrays_python.txt |
Q:
Building a custom ZIP file in Django
I'm working on a webapp that uses SCORM so it can be included in our clients' learning management systems. This works by building a zip file that contains several files. Two of the files depend on the particular resource they want to include and the client themselves. I'd there... | Building a custom ZIP file in Django | I'm working on a webapp that uses SCORM so it can be included in our clients' learning management systems. This works by building a zip file that contains several files. Two of the files depend on the particular resource they want to include and the client themselves. I'd therefore like to generate these zip files auto... | [
"Using zipfile with StringIO will allow you to create a zip file in memory that you can later send to the client.\n"
] | [
5
] | [] | [] | [
"django",
"python",
"zip"
] | stackoverflow_0004165661_django_python_zip.txt |
Q:
Using PyQt4 - QTableView with SQLAlchemy using QSqlTableModel (or not)
i'm starting to learn Qt for python and as i was wondering after reading this post :
qt - pyqt QTableView not populating when changing databases. if there was a way to use SQLAlchemy sessions instead of (re-)opening a database connection as a T... | Using PyQt4 - QTableView with SQLAlchemy using QSqlTableModel (or not) | i'm starting to learn Qt for python and as i was wondering after reading this post :
qt - pyqt QTableView not populating when changing databases. if there was a way to use SQLAlchemy sessions instead of (re-)opening a database connection as a Table Model with Qt's QTableView widget.
Something that would work a little b... | [
"Take a look at Camelot . It does much more:)\nI happily found it when the frustration and angst, generated by Q*View and Q*Model experience forced me to start implementing my own ones on the basis of SqlAlchemy. And it was half implemented, when I found the instrument, that does much more, than I've even dream of,... | [
5
] | [] | [] | [
"pyqt4",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0002397987_pyqt4_python_sqlalchemy_sqlite.txt |
Q:
how do you radially 'sweep out' a 1D array to plot 3d figure in python? (to represent a wavefunction)
effectively I have a large 1D array of heights. As a small example consider:
u=array([0,1,2,1,0,2,4,6,4,2,1])
and a 1D array, the same size as u, of radial values which the heights correspond to, e.g.:
r=array([0... | how do you radially 'sweep out' a 1D array to plot 3d figure in python? (to represent a wavefunction) | effectively I have a large 1D array of heights. As a small example consider:
u=array([0,1,2,1,0,2,4,6,4,2,1])
and a 1D array, the same size as u, of radial values which the heights correspond to, e.g.:
r=array([0,1,2,3,4,5,6,7,8,9,10])
Obviously plotting these with:
pylab.plot(r,u)
gives a nice 2D plot.
How can one ... | [
"You're better off with something more 3D oriented than matplotlib, in this case...\nHere's a quick example using mayavi:\n\nfrom enthought.mayavi import mlab\nimport numpy as np\n\n# Generate some random data along a straight line in the x-direction\nnum = 100\nx = np.arange(num)\ny, z = np.ones(num), np.ones(num)... | [
2,
2
] | [] | [] | [
"3d",
"matplotlib",
"python"
] | stackoverflow_0004159942_3d_matplotlib_python.txt |
Q:
Blender3d vs 3DS max; which one is better suited for automation in python?
I am getting started with the development of 3d environments for using in panda3d. As I am new to this, I need to choose a modelling software to create basic geometries, etc. Therefore, which one is better suited for automation through pyth... | Blender3d vs 3DS max; which one is better suited for automation in python? | I am getting started with the development of 3d environments for using in panda3d. As I am new to this, I need to choose a modelling software to create basic geometries, etc. Therefore, which one is better suited for automation through python? 3DS Max or Blender3D? I would like to automate generating basic geometries, ... | [
"From a python automation point of view, blender itself is written largely in python, and the source is available which allows a level of automation not possible if you can't change the source. To me, having the source available in that situation is more of a benefit than the price tag.\nIf you do go with blender,... | [
4,
3
] | [] | [] | [
"blender",
"panda3d",
"python"
] | stackoverflow_0003896087_blender_panda3d_python.txt |
Q:
How to detect if the values in array are in a certain range and return a binary array in Python?
So I am trying to detect if the values in an array is in a certain range and then return a binary logical array i.e. one for true and zero for false. I have this but iPython keeps complaining
D = ( 1 < X[0,:] + X[1,:])... | How to detect if the values in array are in a certain range and return a binary array in Python? | So I am trying to detect if the values in an array is in a certain range and then return a binary logical array i.e. one for true and zero for false. I have this but iPython keeps complaining
D = ( 1 < X[0,:] + X[1,:]) < 2 ).astype(int)
the interesting thing is that just checking one way works totally ok
D = ( X[0,:] ... | [
"Y=X[0,:]+X[1,:]\nD = ((1<Y) & (Y<2)).astype(int)\n\n",
"array = (1, 2, 3, 4, 5)\nbit_array = map(lambda x: 1 < x < 5 and 1 or 0, array)\n\nbit_array is [0, 1, 1, 1, 0] after that. Is that what you wanted?\n",
"unutbu's is shorter, this is more explicit\n>>> import numpy\n>>> numpy.logical_and(1 < np.arange(5),... | [
2,
1,
1,
0,
0
] | [] | [] | [
"arrays",
"ipython",
"numpy",
"python",
"range"
] | stackoverflow_0004164862_arrays_ipython_numpy_python_range.txt |
Q:
Can Java and Python coexist in the same app?
I need to have a Java instance fetching data directly from the Python's instance datastore. I don't know if that's possible at all. Is the datastore transparent/unique, or each instance (if they can indeed coexist) has its separate datastore?
Suming it up: how can a Jav... | Can Java and Python coexist in the same app? | I need to have a Java instance fetching data directly from the Python's instance datastore. I don't know if that's possible at all. Is the datastore transparent/unique, or each instance (if they can indeed coexist) has its separate datastore?
Suming it up: how can a Java app fetch data from the datastore of a Python ap... | [
"Different versions of an app share a datastore, and AFAIK you can still have a Java version of your app, and Python version, at the same time. It used to be a necessary hack to use features that were implemented in Python but not (yet) in Java, and quite possibly still is.\nOf course only one of those versions can... | [
9,
6
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"integration",
"java",
"python"
] | stackoverflow_0004165824_google_app_engine_google_cloud_datastore_integration_java_python.txt |
Q:
Django Evolution: How do I add a new field at a specific position?
Is there a way to tell Django Evolution to add a new field to a database table at a specific position, similar to the AFTER statement of (My)SQL?
I have a table with some columns and I want to add new_column after column1. Using SQL directly I woul... | Django Evolution: How do I add a new field at a specific position? | Is there a way to tell Django Evolution to add a new field to a database table at a specific position, similar to the AFTER statement of (My)SQL?
I have a table with some columns and I want to add new_column after column1. Using SQL directly I would do this:
ALTER TABLE `db_table` ADD `new_column` DATETIME NULL DEFAU... | [
"Django does not depend or care about the column position in the database. My guess is that Django Evolution works the same way.\nSo you shouldn't depend or care too much about database internals either, in the end that is why you are using the ORM, right?\nIf you really have to do it, I suggest subclassing django_... | [
1
] | [] | [] | [
"django",
"django_evolution",
"django_models",
"python"
] | stackoverflow_0004166220_django_django_evolution_django_models_python.txt |
Q:
Why do I have to use .wait() with python's subprocess module?
I'm running a Perl script through the subprocess module in Python on Linux. The function that runs the script is called several times with variable input.
def script_runner(variable_input):
out_file = open('out_' + variable_input, 'wt')
error_f... | Why do I have to use .wait() with python's subprocess module? | I'm running a Perl script through the subprocess module in Python on Linux. The function that runs the script is called several times with variable input.
def script_runner(variable_input):
out_file = open('out_' + variable_input, 'wt')
error_file = open('error_' + variable_input, 'wt')
process = subproce... | [
"If you are using Unix, and wish to run many processes in the background, you could use subprocess.Popen this way:\nx_fork_many.py: \nimport subprocess\nimport os\nimport sys\nimport time\nimport random\nimport gc # This is just to test the hypothesis that garbage collection of p=Popen() causing the problem.\n\n# ... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004165145_python_subprocess.txt |
Q:
Is this a bug? Variables are identical references to the same string in this example (Python)
This is for Python 2.6.
I could not figure out why a and b are identical:
>>> a = "some_string"
>>> b = "some_string"
>>> a is b
True
But if there is a space in the string, they are not:
>>> a = "some string"
>>> b = "so... | Is this a bug? Variables are identical references to the same string in this example (Python) | This is for Python 2.6.
I could not figure out why a and b are identical:
>>> a = "some_string"
>>> b = "some_string"
>>> a is b
True
But if there is a space in the string, they are not:
>>> a = "some string"
>>> b = "some string"
>>> a is b
False
If this is normal behavior, could someone please explain what is going... | [
"Python may or may not automatically intern strings, which determines whether future instances of the string will share a reference.\nIf it decides to intern a string, then both will refer to the same string instance. If it doesn't, it'll create two separate strings that happen to have the same contents.\nIn gener... | [
10,
1,
0
] | [] | [] | [
"python",
"reference",
"string"
] | stackoverflow_0004165688_python_reference_string.txt |
Q:
Assigning variables from XML returned from an API call
I need to pull some data from the API. It returns the GET in XML and I have having some issues trying to figure out how to assign some of the data from the API to fields in my model in django/python.
The API for activeCollab does not allow me to create my own... | Assigning variables from XML returned from an API call | I need to pull some data from the API. It returns the GET in XML and I have having some issues trying to figure out how to assign some of the data from the API to fields in my model in django/python.
The API for activeCollab does not allow me to create my own projectID number, it automatically generates the number for... | [
"Having looked at the link you posted... something like this might get you started, using lxml and xpath:\n>>> from lxml import etree\n>>> doc = etree.XML(\"\"\"<projects>\n... <project>\n... <id>1</id>\n... <name>\n... <![CDATA[First Project]]>\n... </name>\n... <overview>\n... <![CDA... | [
1
] | [] | [] | [
"activecollab",
"api",
"django",
"python",
"xml"
] | stackoverflow_0004166291_activecollab_api_django_python_xml.txt |
Q:
How can I optimally concat a list of chars to a string?
The data:
list = ['a','b','x','d','s']
I want to create a string str = "abxds". How can I do that?
Right now I am doing something like:
str = ""
for i in list:
str = str + i
print(str)
I know strings are immutable in Python and this will create 7 string... | How can I optimally concat a list of chars to a string? | The data:
list = ['a','b','x','d','s']
I want to create a string str = "abxds". How can I do that?
Right now I am doing something like:
str = ""
for i in list:
str = str + i
print(str)
I know strings are immutable in Python and this will create 7 string object. And this goes out of my memory when I do thousands o... | [
">>> theListOfChars = ['a', 'b', 'x', 'd', 's']\n>>> ''.join(theListOfChars)\n'abxds'\n\nBTW, don't use list or str as variable names as they are names of built-in functions already.\n(Also, there is no char in Python. A \"character\" is just a string of length 1. So the ''.join method works for list of strings as ... | [
13,
4,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004166641_python_string.txt |
Q:
why just one name could taken
def path(request, mypath):
mypath = request.path_info
_listdir = os.listdir(mypath) # ['folder1', 'folder2', 'folder3', 'folder4']
mess = _listdir
a = ' '
x=0
scope = vars()
for i in mess:
scope['x']+=1
a += mess[x]
a += '\n'... | why just one name could taken | def path(request, mypath):
mypath = request.path_info
_listdir = os.listdir(mypath) # ['folder1', 'folder2', 'folder3', 'folder4']
mess = _listdir
a = ' '
x=0
scope = vars()
for i in mess:
scope['x']+=1
a += mess[x]
a += '\n'
return HttpResponse(a)
I hop... | [
"There are huge swathes of unnecessary code in that function.\ndef path(request):\n return HttpResponse('\\n'.join(os.listdir(request.path_info)))\n\nJob done!\n",
"From the docs:\n\nNote: The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.\n\nSo, don't ... | [
4,
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004162248_python.txt |
Q:
How can I read a python pickle database/file from C?
I am working on integrating with several music players. At the moment my favorite is exaile.
In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files wit... | How can I read a python pickle database/file from C? | I am working on integrating with several music players. At the moment my favorite is exaile.
In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand.
I know... | [
"http://www.picklingtools.com/\nThere is a library called the PicklingTools which I help maintain which might be useful: it allows you to form data structures in C++ that you can then pickle/unpickle ... it is C++, not C, but that shouldn't be a problem these days (assuming you are using the gcc/g++ suite). \nThe ... | [
31,
5,
3
] | [] | [] | [
"c",
"python"
] | stackoverflow_0001296162_c_python.txt |
Q:
how to parse table inside table using beautiful soup?
I tried this:
s = soup.findAll("table", {"class": "view"}) But it is giving me the table. But I need the table inside table.
<table class="view" >
<tr>
<td width="46%" valign="top">
<table>
<tr>
<td>
<div style="adasd... | how to parse table inside table using beautiful soup? | I tried this:
s = soup.findAll("table", {"class": "view"}) But it is giving me the table. But I need the table inside table.
<table class="view" >
<tr>
<td width="46%" valign="top">
<table>
<tr>
<td>
<div style="adasdasd">
<div class="abc">dasdsadasdasdas</div... | [
"s = soup.findAll(\"table\", {\"class\": \"view\"})[0].find(\"table\")\n\nIf there's just the one table, you could use .find for the first one too, and drop the [0].\n",
"Heres some better formatted html:\n<table class=\"view\" >\n <tr>\n <td width=\"46%\" valign=\"top\">\n <table>\n ... | [
2,
2
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004164301_beautifulsoup_python.txt |
Q:
A cleaner/shorter way to solve this problem?
This exercise is taken from Google's Python Class:
D. Given a list of numbers, return a list where
all adjacent == elements have been reduced to a single element,
so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
modify the passed in list.
Here's m... | A cleaner/shorter way to solve this problem? | This exercise is taken from Google's Python Class:
D. Given a list of numbers, return a list where
all adjacent == elements have been reduced to a single element,
so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
modify the passed in list.
Here's my solution so far:
def remove_adjacent(nums):
if... | [
"There is function in itertools that works here:\nimport itertools\n[key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])]\n\nYou can also write a generator:\ndef remove_adjacent(items):\n # iterate the items\n it = iter(items)\n # get the first one\n last = next(it)\n # yield it in any case\n ... | [
9,
3,
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004167009_python.txt |
Q:
Python/Tkinter: Trap text selection via keyboard/mouse as an event?
Is it possible to trap text selection via the keyboard AND mouse as a selection/selection_change type of event? (I know I can trap selection via the keyboard by watching every keypress and comparing selection range - but I see no way to detect sel... | Python/Tkinter: Trap text selection via keyboard/mouse as an event? | Is it possible to trap text selection via the keyboard AND mouse as a selection/selection_change type of event? (I know I can trap selection via the keyboard by watching every keypress and comparing selection range - but I see no way to detect selection via the mouse or as a discrete event by itself)
I've looked at the... | [
"The text widget generates a <<Selection>> event, and the listbox generates a <<ListboxSelect>> event. Do either of those meet your needs?\n"
] | [
1
] | [] | [] | [
"events",
"python",
"tkinter",
"user_interface",
"windows"
] | stackoverflow_0004165045_events_python_tkinter_user_interface_windows.txt |
Q:
Sorting datastore item by auto_now=True and auto_now_add=True
I am trying to sort an item in datastore by age by using auto_now=True and auto_now_add=True. I managed to solve datetime problems but I am unable to sort correctly by age. I appreciate any suggestions. (Sorry for the capitalized variables, I will fix t... | Sorting datastore item by auto_now=True and auto_now_add=True | I am trying to sort an item in datastore by age by using auto_now=True and auto_now_add=True. I managed to solve datetime problems but I am unable to sort correctly by age. I appreciate any suggestions. (Sorry for the capitalized variables, I will fix them eventually.) My model is:
class Rep(db.Model):
mAUTHOR = ... | [
"Off the top of my head, it looks like you're only calculating mAGE when you retrieve the records, i.e. after doing the query. Shouldn't you calculate it whenever you modify an object, before putting it into the datastore?\nBefore that, though, are you sure that it's what you want to do? mAGE will be the time betwe... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"mako",
"python"
] | stackoverflow_0004167468_google_app_engine_google_cloud_datastore_mako_python.txt |
Q:
how to configure Sweave it's work and recognize for Rpy2?
how to configure Sweave it's work and recognize for Rpy2?
I use this
import rpy2.robjects as robjects
R["library"]("utils")
R["library"]("tools")
R['sweave("/var/www/tmp/pywps/central.Rnw")']
R['texi2dvi("/var/www/tmp/pywps/central.tex", pdf=TRUE... | how to configure Sweave it's work and recognize for Rpy2? | how to configure Sweave it's work and recognize for Rpy2?
I use this
import rpy2.robjects as robjects
R["library"]("utils")
R["library"]("tools")
R['sweave("/var/www/tmp/pywps/central.Rnw")']
R['texi2dvi("/var/www/tmp/pywps/central.tex", pdf=TRUE)']
but I get these errors
[File "/usr/lib/python2.6/dist-pack... | [
"Use square brackets to get an R object, then call it from Python. Or use () brackets to pass a line to R:\nR[\"Sweave\"](\"/var/www/tmp/pywps/central.Rnw\")\nR('Sweave(\"/var/www/tmp/pywps/central.Rnw\")')\n\nSweave needs a capital S (in my tests).\n",
"Uh, does this work? You're not doing all the R[] invocatio... | [
2,
1,
1
] | [] | [] | [
"python",
"r",
"rpy2",
"sweave"
] | stackoverflow_0004160318_python_r_rpy2_sweave.txt |
Q:
Alternatives to ApacheBench for profiling my code speed
I've done some experiments using Apache Bench to profile my code response times, and it doesn't quite generate the right kind of data for me. I hope the good people here have ideas.
Specifically, I need a tool that
Does HTTP requests over the network (it doe... | Alternatives to ApacheBench for profiling my code speed | I've done some experiments using Apache Bench to profile my code response times, and it doesn't quite generate the right kind of data for me. I hope the good people here have ideas.
Specifically, I need a tool that
Does HTTP requests over the network (it doesn't need to do anything very fancy)
Records response times a... | [
"I have done this in two ways.\nWith \"loadrunner\" which is a wonderful but pretty expensive product (from I think HP these days).\nWith combination perl/php and the Curl package. I found the CURL api slightly easier to use from php. Its pretty easy to roll your own GET and PUT requests. I would also recommend man... | [
1,
1,
1,
1,
1,
0
] | [] | [] | [
"apachebench",
"benchmarking",
"latency",
"profiling",
"python"
] | stackoverflow_0004083523_apachebench_benchmarking_latency_profiling_python.txt |
Q:
How to do atomic increment/decrement with Elixir/SQLAlchemy
I'd like to increment (or decrement) a score field in an Elixir entity:
class Posting(Entity):
score = Field(Integer, PassiveDefault(text('0')))
def upvote(self):
self.score = self.score + 1
However, this doesn't work reliably with concurren... | How to do atomic increment/decrement with Elixir/SQLAlchemy | I'd like to increment (or decrement) a score field in an Elixir entity:
class Posting(Entity):
score = Field(Integer, PassiveDefault(text('0')))
def upvote(self):
self.score = self.score + 1
However, this doesn't work reliably with concurrent calls to upvote. The best I could come up with is this ugly me... | [
"I'll try, but I'm not sure if this meets your needs:\nsession.query(Posting).\\\n .filter(Posting.id==self.id)\\\n .update({'score':self.score+1})\n\nYou might wanna do session.commit() right after it?\nEDIT: [concerning the question's update]\nIf the Posting is derived from Entity which is class mapped to m... | [
2
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0004167568_python_python_elixir_sqlalchemy.txt |
Q:
How can I get the port number of the newly accepted connection in python?
When I create a socket on a server and the accept an incoming connection:
conn, addr = s.accept()
Both print conn.getsockname() and print s.getsockname() print out the same port number.
I thought 'conn' was supposed to represent a NEW socke... | How can I get the port number of the newly accepted connection in python? | When I create a socket on a server and the accept an incoming connection:
conn, addr = s.accept()
Both print conn.getsockname() and print s.getsockname() print out the same port number.
I thought 'conn' was supposed to represent a NEW socket. How do I get the port number of this new socket?
Thanks!
| [
"The local port remains the same. What you want is the remote side's port. You can use getpeername for this (or the second element of accept's return value).\n",
"It is a new socket, but it has the same local port as the original listening socket.\n"
] | [
6,
0
] | [] | [] | [
"python",
"sockets",
"tcp"
] | stackoverflow_0004168191_python_sockets_tcp.txt |
Q:
Python: Problems mocking an instance
I am having problem mocking an object to test a descriptor.
This is the code of the descriptor:
class Text(object):
def __init__(self, default_value=u'', validators=[]):
self.validators = validators
self._value = default_value
def __set__(self, instance... | Python: Problems mocking an instance | I am having problem mocking an object to test a descriptor.
This is the code of the descriptor:
class Text(object):
def __init__(self, default_value=u'', validators=[]):
self.validators = validators
self._value = default_value
def __set__(self, instance, value):
for validator in self.v... | [
"\nvalidator in Text is an object factory e.g., class object\nvalidator in the test_.. function is used as a concrete instance -- the product of an object factory. \n\nYou should give to Text() something that returns objects with .validate method not the objects themselves:\ndef test_text_validator_raises_exception... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004168301_python.txt |
Q:
best algorithm to combine multiple RSS feeds using Python
I am writing a python script to combine about 20+ RSS feeds. I would like to use a custom solution instead of feedjack or planetfeed.
I use feedparser to parse the feeds and mysql to cache them.
The problem I am running into is determining which feeds ... | best algorithm to combine multiple RSS feeds using Python | I am writing a python script to combine about 20+ RSS feeds. I would like to use a custom solution instead of feedjack or planetfeed.
I use feedparser to parse the feeds and mysql to cache them.
The problem I am running into is determining which feeds have already been cached and which haven't.
Some pseudo code fo... | [
"Depending on how often the feeds are updated and how often you check, you could simply fix broken dates (if it's in the future, reset it to today), before adding them to the database.\nOther than that, you'd have to use some sort of ID—I think RSS has an ID field on each item. If your feeds are kept in order, you ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004167863_python.txt |
Q:
find string with format '[number]' using regex
I have a string in a django/python app and need to search it for every instance of [x]. This includes the brackets and x, where x is any number between 1 and several million. I then need to replace x with my own string.
ie, 'Some string [3423] of words and numbers lik... | find string with format '[number]' using regex | I have a string in a django/python app and need to search it for every instance of [x]. This includes the brackets and x, where x is any number between 1 and several million. I then need to replace x with my own string.
ie, 'Some string [3423] of words and numbers like 9898' would turn into 'Some string [mycustomtext] ... | [
"Regex is precisely what you want. It's the re module in Python, you'll want to use re.sub, and it will look something like:\nnewstring = re.sub(r'\\[\\d+\\]', replacement, yourstring)\n\nIf you need to do a lot of it, consider compiling the regex:\nmyre = re.compile(r'\\[\\d+\\]')\nnewstring = myre.sub(replacement... | [
4,
1,
0
] | [] | [] | [
"python",
"regex",
"replace",
"string"
] | stackoverflow_0004168729_python_regex_replace_string.txt |
Q:
Is there any data structure which can avoid duplication, preserve order and random access
Previously, while I am looking for the data structure with the following characteristic.
Avoid duplication
Iteration order will be same as insertion order
In Java, I use LinkHashSet, In Python, I use OrderedDict
Now, on the... | Is there any data structure which can avoid duplication, preserve order and random access | Previously, while I am looking for the data structure with the following characteristic.
Avoid duplication
Iteration order will be same as insertion order
In Java, I use LinkHashSet, In Python, I use OrderedDict
Now, on the top of 2 requirements, I would like to have an additional requirement
Able to random access t... | [
"A simple approach in Java would be to create a wrapper class that implements both the Set and List interfaces, and that contained both a HashSet and ArrayList. Update operations would need to update both internal collections, and read operations would be mapped to whichever internal collection gives the correct s... | [
3,
1,
0,
0,
0
] | [] | [] | [
"collections",
"java",
"python"
] | stackoverflow_0004160929_collections_java_python.txt |
Q:
twisted+gtk gui crashing very rarely
I'm using twisted with gtk (and gtk2reactor). My application crashes in a strange way. So far this is the second time it's crashed in this way. The previous time was about a month ago. These are the errors Python was able to capture in my log file:
2010-11-12 05:23:10,497 ERROR... | twisted+gtk gui crashing very rarely | I'm using twisted with gtk (and gtk2reactor). My application crashes in a strange way. So far this is the second time it's crashed in this way. The previous time was about a month ago. These are the errors Python was able to capture in my log file:
2010-11-12 05:23:10,497 ERROR stderr: C:\Python25\lib\site-packages\... | [
"These are all very old versions of the software involved. Please upgrade to at least Python 2.6 and Twisted 10.1. I am not sure what the status of GTK+ on Windows is, but I know that there were some bugfixes a couple of years ago, so you should upgrade that as much as possible too.\n"
] | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python",
"segmentation_fault",
"twisted"
] | stackoverflow_0004168947_gtk_pygtk_python_segmentation_fault_twisted.txt |
Q:
Using the argparse output to call functions
Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to 'best practices'? I haven't seen code actually using the output of argparse, only how to set it up.
def useArguments():
x ... | Using the argparse output to call functions | Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to 'best practices'? I haven't seen code actually using the output of argparse, only how to set it up.
def useArguments():
x = 0
while x <= 5:
if x == 0: ... | [
"You could supply a custom action for an argument by, and I quote:\n\npassing an object that implements the\n Action API. The easiest way to do this\n is to extend argparse.Action,\n supplying an appropriate __call__\n method. The __call__ method should\n accept four parameters:\n\nparser: The ArgumentParser o... | [
11,
6,
4
] | [] | [] | [
"argparse",
"arguments",
"command_line",
"parameters",
"python"
] | stackoverflow_0003454934_argparse_arguments_command_line_parameters_python.txt |
Q:
Where are the layman non-prerequisite introductory materials for everything-testing in Python?
This question has been modified
If I had to really pick the kind of testing I would like to learn (I have no idea which way this translates to Python) is found here http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesO... | Where are the layman non-prerequisite introductory materials for everything-testing in Python? | This question has been modified
If I had to really pick the kind of testing I would like to learn (I have no idea which way this translates to Python) is found here http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd. I don't know if this is agile, extreme or if it's just called TDD. Is this unit testing, doc t... | [
"The simplest thing to start with is Python's unittest module. There are frameworks to do things more automatically later on, but unittest works fine for simple cases.\nThe basic idea is that you have a class for a particular test suite. You define a set of test methods, and optional setUp and tearDown methods to b... | [
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"testing",
"unit_testing"
] | stackoverflow_0004168401_python_testing_unit_testing.txt |
Q:
Possible to add an object to SQLAlchemy session without explicit session.add()?
I have a number of classes that are mapped to tables with SQLAlchemy (non-declaratively if that matters). Because I'd like the application to be unit-testable, all SQLAlchemy session interaction is isolated into a single class. Using t... | Possible to add an object to SQLAlchemy session without explicit session.add()? | I have a number of classes that are mapped to tables with SQLAlchemy (non-declaratively if that matters). Because I'd like the application to be unit-testable, all SQLAlchemy session interaction is isolated into a single class. Using the app goes something like this:
m = Model("mysql://localhost/mydb")
s1 = Service("so... | [
"In SQLAlchemy you can only do this with tables by binding their metadata to an engine. This does not work with the ORM part of SQLALchemy.\nhttp://www.sqlalchemy.org/docs/core/schema.html?highlight=metadata#binding-metadata-to-an-engine-or-connection\nOne approach to this sort of thing is to use a scoped session t... | [
6,
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004115818_python_sqlalchemy.txt |
Q:
Install Apache with mod_wsgi to use Python for RESTful web services and Apache for web pages
Can anyone help me install Apache with mod_wsgi to run Python for implementation of RESTful Web services. We're trying to get rid of our existing Java REST services with Apache Tomcat.
The installation platform is SUSE Lin... | Install Apache with mod_wsgi to use Python for RESTful web services and Apache for web pages | Can anyone help me install Apache with mod_wsgi to run Python for implementation of RESTful Web services. We're trying to get rid of our existing Java REST services with Apache Tomcat.
The installation platform is SUSE Linux Enterprise. Please provide a step by step installation procedure with required modules, as I tr... | [
"\nCheck if mod_wsgi is loaded as a module into the httpd.conf\nAdd apache host that points to a python/wsgi module which contains the 'def application' definition for your web-service. \nResolve any path issues that maybe arise from your import handling.\n\nIf this doesn't work, drop some error-dump here and we'll... | [
0,
0
] | [] | [] | [
"apache",
"mod_python",
"mod_wsgi",
"python",
"rest"
] | stackoverflow_0004167684_apache_mod_python_mod_wsgi_python_rest.txt |
Q:
Writing metadata to a pdf using pyobjc
I'm trying to write metadata to a pdf file using the following python code:
from Foundation import *
from Quartz import *
url = NSURL.fileURLWithPath_("test.pdf")
pdfdoc = PDFDocument.alloc().initWithURL_(url)
assert pdfdoc, "failed to create document"
print "reading pdf fi... | Writing metadata to a pdf using pyobjc | I'm trying to write metadata to a pdf file using the following python code:
from Foundation import *
from Quartz import *
url = NSURL.fileURLWithPath_("test.pdf")
pdfdoc = PDFDocument.alloc().initWithURL_(url)
assert pdfdoc, "failed to create document"
print "reading pdf file"
attrs = {}
attrs[PDFDocumentTitleAttrib... | [
"Mark is on the right track, but there are a few peculiarities that should be accounted for.\nFirst, he is correct that pdfdoc.documentAttributes is an NSDictionary that contains the document metadata. You would like to modify that, but note that documentAttributes gives you an NSDictionary, which is immutable. You... | [
6,
2
] | [] | [] | [
"cocoa",
"pdf",
"pdfkit",
"pyobjc",
"python"
] | stackoverflow_0004100405_cocoa_pdf_pdfkit_pyobjc_python.txt |
Q:
How do you do a "hidden" field in Django's forms.Form models?
lat = forms.FloatField()
How do you make this hidden?
A:
lat = forms.FloatField(widget=forms.HiddenInput())
| How do you do a "hidden" field in Django's forms.Form models? | lat = forms.FloatField()
How do you make this hidden?
| [
"lat = forms.FloatField(widget=forms.HiddenInput())\n\n"
] | [
4
] | [] | [] | [
"django",
"forms",
"hidden",
"python"
] | stackoverflow_0004170031_django_forms_hidden_python.txt |
Q:
Optimizing python for loops
Here are two programs that naively calculate the number of prime numbers <= n.
One is in Python and the other is in Java.
public class prime{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int nps = 0;
boolean isp;
for(int i = 1... | Optimizing python for loops | Here are two programs that naively calculate the number of prime numbers <= n.
One is in Python and the other is in Java.
public class prime{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int nps = 0;
boolean isp;
for(int i = 1; i <= n; i++){
isp =... | [
"As has been pointed out, straight Python really isn't made for this sort of thing. That the prime checking algorithm is naive is also not the point. However, with two simple things I was able to greatly reduce the time in Python while using the original algorithm.\nFirst, put everything inside of a function, call ... | [
11,
4,
2,
2,
0,
0,
0,
0
] | [
"Yes, Python is one of the slowest practical languages you'll encounter. While loops are marginally faster than for i in xrange(), but ultimately Python will always be much, much slower than anything else.\nPython has its place: Prototyping theory and ideas, or in any situation where the ability to produce code fas... | [
-5
] | [
"python"
] | stackoverflow_0004169828_python.txt |
Q:
How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)?
How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)?
I have to transfer data between server side (using php or python) and client side (C++ using Win32 APIs). I am not su... | How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)? | How can I implement encryption between server side in (php/python) and C++ (Win32/Native Windows)?
I have to transfer data between server side (using php or python) and client side (C++ using Win32 APIs). I am not sure that what functions/APIs or Libs I can use on the both sides so that both sides should be able to com... | [
"Use OpenSSL on client side and OpenSSL on server side. In other way you writing \"I am not looking for some complicated\" but if you don't want use some complicated then you don't have encryption. Easiest way is use cleartext transmission without encryption, if you searching something like this use for example ROT... | [
3
] | [] | [] | [
"c++",
"cryptography",
"encryption",
"php",
"python"
] | stackoverflow_0004170135_c++_cryptography_encryption_php_python.txt |
Q:
git error: cannot spawn .git/hooks/post-commit: No such file or directory
I'm trying to write a post-commit hook, I have a Git repository on a mapped drive (V:), msysgit installed in C:\Git, and Python in C:\Python26.
I'm running TortoiseGit on Windows 7 64 Bit.
The script is:
#!C:/Python26/python
import sys
from... | git error: cannot spawn .git/hooks/post-commit: No such file or directory | I'm trying to write a post-commit hook, I have a Git repository on a mapped drive (V:), msysgit installed in C:\Git, and Python in C:\Python26.
I'm running TortoiseGit on Windows 7 64 Bit.
The script is:
#!C:/Python26/python
import sys
from subprocess import Popen, PIPE, call
GIT_PATH = 'C:\Git\bin\git.exe'
BRANCHES ... | [
"According to the githooks man page,\n\n[The post-commit hook] is invoked by git-commit.\n It takes no parameter, and is invoked\n after a commit is made.\n\nIt takes no parameters. In Python, that means sys.argv[1:] will be an empty list.\nThe man page doesn't say what, if anything, is sent to stdin, but pres... | [
2
] | [] | [] | [
"git",
"python",
"shebang",
"tortoisegit",
"trac"
] | stackoverflow_0004168739_git_python_shebang_tortoisegit_trac.txt |
Q:
Django project (apache, mod_wsgi) can't import namespace packages
When installing django-piston from the bitbucket repo with pip, I noticed something weird (first indented line of the output):
$ pip install hg+http://bitbucket.org/jespern/django-piston
Downloading/unpacking hg+http://bitbucket.org/jespern/django-p... | Django project (apache, mod_wsgi) can't import namespace packages | When installing django-piston from the bitbucket repo with pip, I noticed something weird (first indented line of the output):
$ pip install hg+http://bitbucket.org/jespern/django-piston
Downloading/unpacking hg+http://bitbucket.org/jespern/django-piston
Cloning Mercurial repository http://bitbucket.org/jespern/django-... | [
"After looking some more, I discovered the answer in the docs for mod_wsgi:\n\nAs an additional step however, the WSGI script file described in the instructions would be modified to overlay the virtual environment for the application on top of the baseline environment. This would be done by adding at the very start... | [
2
] | [] | [] | [
"apache",
"django",
"django_piston",
"mod_wsgi",
"python"
] | stackoverflow_0004170305_apache_django_django_piston_mod_wsgi_python.txt |
Q:
Tuning mod_wsgi in daemon mode
I'm running wsgi application on apache mod_wsgi in daemon mode.
I have these lines in the configuration
WSGIDaemonProcess app processes=2 threads=3 display-name=%{GROUP}
WSGIProcessGroup app
How do I find the optimal combination/tuning of processes and threads?
EDIT:
This link [giv... | Tuning mod_wsgi in daemon mode | I'm running wsgi application on apache mod_wsgi in daemon mode.
I have these lines in the configuration
WSGIDaemonProcess app processes=2 threads=3 display-name=%{GROUP}
WSGIProcessGroup app
How do I find the optimal combination/tuning of processes and threads?
EDIT:
This link [given in answer bellow] was quite usefu... | [
"You might get more information on ServerFault as well. For example: https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes\nThis is another good resource for the topic: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading#The_mod_wsgi_Daemon_Processes\nwhich briefly d... | [
13,
1
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0004165213_apache_mod_wsgi_python_wsgi.txt |
Q:
How do I validate if an item uploaded to my server is an image or a video?
I'd only like to store images and videos.
How do I know whether that person uploaded a video or image?
How to verify?
I'm using Django.
A:
python-magic looks like a promising place to start.
Also, for images at least, I've successfully ma... | How do I validate if an item uploaded to my server is an image or a video? | I'd only like to store images and videos.
How do I know whether that person uploaded a video or image?
How to verify?
I'm using Django.
| [
"python-magic looks like a promising place to start.\nAlso, for images at least, I've successfully made use of this snippet.\n"
] | [
0
] | [] | [] | [
"django",
"image",
"python",
"validation",
"video"
] | stackoverflow_0004170403_django_image_python_validation_video.txt |
Q:
Using sqlite3 to track unit test results
I have my own unit testing suite based on the unittest library. I would like to track the history of each test case being run. I would also like to identify after each run tests which flipped from PASS to FAIL or vice versa.
I have very little knowledge about databases, but... | Using sqlite3 to track unit test results | I have my own unit testing suite based on the unittest library. I would like to track the history of each test case being run. I would also like to identify after each run tests which flipped from PASS to FAIL or vice versa.
I have very little knowledge about databases, but it seems that I could utilize sqlite3 for thi... | [
"Technically, yes. The only thing that you need is some kind of scripting language or shell script that can talk to sqlite.\nYou should think of a database like a file in a file system where you don't have to care about the file format. You just say, here are tables of data, with columns. And each row of that is on... | [
0
] | [] | [] | [
"python",
"sqlite",
"unit_testing"
] | stackoverflow_0004170442_python_sqlite_unit_testing.txt |
Q:
Python : Get many list from a list
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hi,
I would like to split a list in many list of a length of x elements, like:
a = (1, 2, 3, 4, 5)
and get :
b = (
(1,2),
(3,4),
(5,)
)
if the length is set to 2 or :
b = (
(1,2,3),
(... | Python : Get many list from a list |
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hi,
I would like to split a list in many list of a length of x elements, like:
a = (1, 2, 3, 4, 5)
and get :
b = (
(1,2),
(3,4),
(5,)
)
if the length is set to 2 or :
b = (
(1,2,3),
(4,5)
)
if the length is equal to 3 ...... | [
"Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.\ndef sublist(seq, length):\n return [seq[i:i + length] for i in xrange(0, len(seq), length)]\n\nUsage:\n>>> sublist((1, 2, 3, 4, 5), 1)\n[(1,), (2,), (3,), (4,), (5,)]\n\n>>> sublist([1, 2, 3,... | [
3,
2,
2
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0004170295_list_python_slice.txt |
Q:
QTreeView with drag and drop support in PyQt
In PyQt 4 I would like to create a QTreeView with possibility to reorganize its structure with drag and drop manipulation.
I have implemented my own model(QAbstractItemModel) for QTreeView so my QTreeView properly displays the data.
Now I would like to add drag and drop... | QTreeView with drag and drop support in PyQt | In PyQt 4 I would like to create a QTreeView with possibility to reorganize its structure with drag and drop manipulation.
I have implemented my own model(QAbstractItemModel) for QTreeView so my QTreeView properly displays the data.
Now I would like to add drag and drop support for tree's nodes to be able to move a nod... | [
"You can enable drag and drop support for tree view items by setting QtGui.QAbstractItemView.InternalMove into the dragDropMode property of the treeview control. Also take a look at the documentation here Using drag & drop with item views. Below is a small example of a treeview with internal drag and drop enabled f... | [
19
] | [] | [] | [
"drag_and_drop",
"pyqt",
"python",
"qtreeview"
] | stackoverflow_0004163740_drag_and_drop_pyqt_python_qtreeview.txt |
Q:
Poker hand string display
I'm brand new to programming and Python and I'm trying my hardest to understand and learn it. I'm not asking for answers but explanations in plain non-computer terms so that i can try to work out the solution myself.
Here is one more problem I'm having. I have 4 lists below:
short_card =... | Poker hand string display | I'm brand new to programming and Python and I'm trying my hardest to understand and learn it. I'm not asking for answers but explanations in plain non-computer terms so that i can try to work out the solution myself.
Here is one more problem I'm having. I have 4 lists below:
short_card = ['A', 'K', 'Q', 'J', 'T', '9',... | [
"So what you have is two sets of lists, which correlate the input values with the output strings. Note the order of the lists; they're the same. Which should make the index values of the inputs equal to the...\n",
"You don't have much, but I'll say that your lists are in pairs.\nshort_card = ['A', 'K', 'Q', 'J'... | [
1,
1,
0,
0
] | [] | [] | [
"list",
"python",
"search",
"string"
] | stackoverflow_0004170238_list_python_search_string.txt |
Q:
Generate 4000 unique pseudo-random cartesian coordinates FASTER?
The range for x and y is from 0 to 99.
I am currently doing it like this:
excludeFromTrainingSet = []
while len(excludeFromTrainingSet) < 4000:
tempX = random.randint(0, 99)
tempY = random.randint(0, 99)
if [tempX, tempY] not in excludeFr... | Generate 4000 unique pseudo-random cartesian coordinates FASTER? | The range for x and y is from 0 to 99.
I am currently doing it like this:
excludeFromTrainingSet = []
while len(excludeFromTrainingSet) < 4000:
tempX = random.randint(0, 99)
tempY = random.randint(0, 99)
if [tempX, tempY] not in excludeFromTrainingSet:
excludeFromTrainingSet.append([tempX, tempY])
... | [
"Vincent Savard has an answer that's almost twice as fast as the first solution offered here.\n\nHere's my take on it. It requires tuples instead of lists for hashability:\ndef method2(size):\n ret = set()\n while len(ret) < size:\n ret.add((random.randint(0, 99), random.randint(0, 99)))\n return re... | [
6,
4,
4,
4,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004170054_python.txt |
Q:
Suggestions for improving this little piece of code?
Any suggestions to improve this little piece of code? It works, but there must be a better way of doing it. Especially the first two lines, I have a bunch of them. Can't I merge the two somehow?
for iso in set(BAR_Items):
if iso+YEAR in heights:
myl... | Suggestions for improving this little piece of code? | Any suggestions to improve this little piece of code? It works, but there must be a better way of doing it. Especially the first two lines, I have a bunch of them. Can't I merge the two somehow?
for iso in set(BAR_Items):
if iso+YEAR in heights:
mylist.append(heights[iso+YEAR])
mylist.sort()
cut = percenti... | [
"The first three lines can be written concisely as a list comprehension.\nmylist += [heights[iso+YEAR] for iso in set(BAR_Items) if iso+YEAR in heights] \n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004170646_python.txt |
Q:
How do you check the mimetype of a file uploaded to your server?
it's just a user upload a file.
A:
UploadedFile.content_type will return the content-type header that was sent with the file when uploaded at the time of upload.
If you also need to check files after they are saved you can use the mimetypes module ... | How do you check the mimetype of a file uploaded to your server? | it's just a user upload a file.
| [
"UploadedFile.content_type will return the content-type header that was sent with the file when uploaded at the time of upload.\nIf you also need to check files after they are saved you can use the mimetypes module in python. But it appears to only check based on the file extension.\nimport mimetypes\nfile_type, fi... | [
3,
2
] | [] | [] | [
"django",
"file",
"linux",
"python",
"unix"
] | stackoverflow_0004170637_django_file_linux_python_unix.txt |
Q:
Python sqlite3: UPDATE failure claims "no such column"
The following script evokes the following exception in the UPDATE command. What I think should happen for this simple UPDATE command is that the value of db_2.foo.bar should be doubled from 1 to 2. My guess is that I have some subtle syntax error in the UPDATE... | Python sqlite3: UPDATE failure claims "no such column" | The following script evokes the following exception in the UPDATE command. What I think should happen for this simple UPDATE command is that the value of db_2.foo.bar should be doubled from 1 to 2. My guess is that I have some subtle syntax error in the UPDATE statement (or else a bug at the Python or sqlite3 level); h... | [
"To update foo with values from a different table, you can use a nested SELECT expression. Note that foo.rowid refers to the rowid of the outer table, while t.rowid refers to the rowid of the inner table:\ncur_2.execute( '''\\\n UPDATE foo SET bar = bar +\n IFNULL( (SELECT t.bar \n FROM db... | [
1,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004170171_python_sqlite.txt |
Q:
Why would one use an egg over an sdist?
About the only reason I can think of to distribute a python package as an egg is so that you can not include the .py files with your package (and only include .pyc files, which is a dubious way to protect your code anyway). Aside from that, I can't really think of any reaso... | Why would one use an egg over an sdist? | About the only reason I can think of to distribute a python package as an egg is so that you can not include the .py files with your package (and only include .pyc files, which is a dubious way to protect your code anyway). Aside from that, I can't really think of any reason to upload a package as an egg rather than a... | [
"One reason: eggs can include compiled C extension modules so that the end user does not need to have the necessary build tools and possible additional headers and libraries to build the extension module from scratch. The drawback to that is that the packager may need to supply multiple eggs to match each targeted... | [
3
] | [] | [] | [
"egg",
"packaging",
"python",
"sdist"
] | stackoverflow_0004170477_egg_packaging_python_sdist.txt |
Q:
Python Templating and Ajax
I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
@app.route('/home')
def userhome():
data=g... | Python Templating and Ajax | I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
@app.route('/home')
def userhome():
data=go get user details from the data... | [
"You have two options: template on the server, or template in the browser.\nTo template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.\nTo templa... | [
3,
2
] | [] | [] | [
"ajax",
"jquery",
"python"
] | stackoverflow_0004170532_ajax_jquery_python.txt |
Q:
Python Card Display
Possible Duplicate:
Poker hand string display
hi all im having a bit of a hard time figuring this question out . so if i can get any help i would greatly appreciate it. the question is ;
Create functions card_str(c) and hand_str(h) which return a string version of a card and a hand of
cards, ... | Python Card Display |
Possible Duplicate:
Poker hand string display
hi all im having a bit of a hard time figuring this question out . so if i can get any help i would greatly appreciate it. the question is ;
Create functions card_str(c) and hand_str(h) which return a string version of a card and a hand of
cards, respectively. A card is ... | [
"For card_str(c), you need to convert a combination of value and suit ('Kh', for example), and convert it into a longer string. You'll need to create lists that contain:\n\nA dictionary mapping short values (e.g. 'K' or 'A' to long names, 'King' and 'Ace')\nA dict mapping short suit names to full name ('c' goes to ... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004170945_python.txt |
Q:
Is there a Django "app" that can manage your users' profiles?
"My Profile", notification options, settings
...The checkbox stuff...
I'm familiar with Pinax, but is there a specific app that manages just profiles and accounts?
I don't want the other heavy stuff associated with social networking...I only want the pr... | Is there a Django "app" that can manage your users' profiles? | "My Profile", notification options, settings
...The checkbox stuff...
I'm familiar with Pinax, but is there a specific app that manages just profiles and accounts?
I don't want the other heavy stuff associated with social networking...I only want the profile account management
| [
"There is django-profiles:\nhttp://bitbucket.org/ubernostrum/django-profiles/wiki/Home\n",
"Another one, I haven't used either this or the one Mike posted, so caveat emptor. (What's Latin for 'downloader'? ;)\nhttp://code.google.com/p/django-profile/\n"
] | [
1,
0
] | [] | [] | [
"django",
"pinax",
"profile",
"python"
] | stackoverflow_0004171083_django_pinax_profile_python.txt |
Q:
What is the best way to distribute code across servers?
I have a directory of python programs, classes and packages that I currently distribute to 5 servers. It seems I'm continually going to be adding more servers and right now I'm just doing a basic rsync over from my local box to the servers.
What would a bett... | What is the best way to distribute code across servers? | I have a directory of python programs, classes and packages that I currently distribute to 5 servers. It seems I'm continually going to be adding more servers and right now I'm just doing a basic rsync over from my local box to the servers.
What would a better approach be for distributing code across n servers?
thanks... | [
"I use Mercurial with fabric to deploy all the source code. Fabric's written in python, so it'll be easy for you to get started. Updating the production service is as simple as fab production deploy. Which ends ups doing something like this:\n\nShut down all the services and put an \"Upgrade in Progress\" page.\n... | [
4,
1,
0
] | [] | [] | [
"python",
"software_distribution"
] | stackoverflow_0003073429_python_software_distribution.txt |
Q:
Is there a way to display any media, regardless of type? (especially in Django?)
If I have a .mp4 file, it will automatically display a video (flash?)
If it's a jpg, it'll just display the image...
Edit: I want this embedded inside a webpage.
A:
As eternicode says, all you need to do is make your views the norma... | Is there a way to display any media, regardless of type? (especially in Django?) | If I have a .mp4 file, it will automatically display a video (flash?)
If it's a jpg, it'll just display the image...
Edit: I want this embedded inside a webpage.
| [
"As eternicode says, all you need to do is make your views the normal way and pass the querysets to your template. \nIn the template , all you need to do is load the content from your query as part of /media as defined in your settings.py e.g \n<img src=\"/media/{{model.object}}\" width=\"135\" height=\"60\" alt=\"... | [
1,
0,
0
] | [] | [] | [
"django",
"image",
"javascript",
"python",
"video"
] | stackoverflow_0004171255_django_image_javascript_python_video.txt |
Q:
How to create a well-formatted word document(.DOC) in python on Linux?
I want to create new work document from sketch with Python on Linux platform, but do not know how to do that.
I do not willing to use RTF or use pythondocx to create docx document. Is there any other way to do so? Remember, I need the document ... | How to create a well-formatted word document(.DOC) in python on Linux? | I want to create new work document from sketch with Python on Linux platform, but do not know how to do that.
I do not willing to use RTF or use pythondocx to create docx document. Is there any other way to do so? Remember, I need the document keeps the formatting.
Thanks everyone's help!
| [
"The Python docx module allows you to do what you want. It is perfect for you and is as simple as working with any other Python library.\n",
"Openoffice has some Python scripting ability. I only heard about it, haven't studied it nor used it.\n"
] | [
2,
1
] | [] | [] | [
"linux",
"ms_word",
"python"
] | stackoverflow_0004171555_linux_ms_word_python.txt |
Q:
What builtin functions shouldn't be run by untrusted users?
I'm creating a corewars type application that runs on django and allows a user to upload some python code that will control their character. Now, I know the real answer to this is that as long as I'm taking code input from untrusted users I'll have secur... | What builtin functions shouldn't be run by untrusted users? | I'm creating a corewars type application that runs on django and allows a user to upload some python code that will control their character. Now, I know the real answer to this is that as long as I'm taking code input from untrusted users I'll have security vulnerabilities. I'm just trying to minimize the risk as muc... | [
"There are lots of answers on what to do in general about restricting Python at http://wiki.python.org/moin/SandboxedPython. When I looked at it some time ago, the Zope RestrictedPython looked the best solution, working with a whitelist system. You'll still need to take care in your own code so that you don't expos... | [
3,
2,
2,
2,
1,
1
] | [] | [] | [
"built_in",
"exec",
"python"
] | stackoverflow_0004170639_built_in_exec_python.txt |
Q:
wxPython Geometry problem
I'm trying to get the button to be right of the label. I set the tuple and am still not sure why it covers the label.
Also is there a good tutorial available on wxpython geometry?
import wx
import wx.lib.agw.gradientbutton as GB
def GetRoundBitmap( w, h, r ):
maskColor = wx.Color(0... | wxPython Geometry problem | I'm trying to get the button to be right of the label. I set the tuple and am still not sure why it covers the label.
Also is there a good tutorial available on wxpython geometry?
import wx
import wx.lib.agw.gradientbutton as GB
def GetRoundBitmap( w, h, r ):
maskColor = wx.Color(0,0,0)
shownColor = wx.Color... | [
"You forgot to set FancyFrame to have the given layout sizer.\nIn other words you need to add one line to the end of your FancyFrame's __init__ method.\nself.SetSizerAndFit(geo)\n\n"
] | [
0
] | [] | [] | [
"geometry",
"python",
"wxpython"
] | stackoverflow_0003285520_geometry_python_wxpython.txt |
Q:
Making two scripts communicate
I have to make two programs (for example a "script A" (.py) and "script B"(.exe)) communicate.
Both programs are on a infinite loop: Script A needs to write to the stdin of script B and afterwards read the stdout of script B thereafter write again etc. Script B I cannot change.
Both ... | Making two scripts communicate | I have to make two programs (for example a "script A" (.py) and "script B"(.exe)) communicate.
Both programs are on a infinite loop: Script A needs to write to the stdin of script B and afterwards read the stdout of script B thereafter write again etc. Script B I cannot change.
Both files are on my hard disk, so I ther... | [
"If you start \"Script B\" from within \"script A\" using the subprocess module, you will be able to directly interact with its stdin and stdout. For example:\nfrom subprocess import Popen, PIPE\n\nprog = Popen(\"scriptA.exe\", shell=True, stdin=PIPE, stdout=PIPE)\n\nprog.stdin.write(\"This will go to script A\\n\... | [
6,
0
] | [] | [] | [
"communication",
"python"
] | stackoverflow_0004172213_communication_python.txt |
Q:
Permuting a list of chars takes all my memory (Python)
I am building a dictionary of all the alpha and numbers. The problem with this code is "within matter of second consumes 100% of my memory". Do you think my implementation is bad?
Any Help is appreciated.
from timeit import Timer
from itertools import permuta... | Permuting a list of chars takes all my memory (Python) | I am building a dictionary of all the alpha and numbers. The problem with this code is "within matter of second consumes 100% of my memory". Do you think my implementation is bad?
Any Help is appreciated.
from timeit import Timer
from itertools import permutations
dictionary = []
small_alpha = map(chr, range(97,123))
... | [
"There are 36!/(36-10)! = 922,393,263,052,800 permutations (~1 quadrillion) of 10 alphanumeric characters. Of course this will take all your memory.\nAssuming each string takes 32 bytes to store (8 bytes for the pointer, 8 bytes for the length, 16 bytes for the content*, on a 64-bit machine), this requires 26.2 Pi... | [
10,
2,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004167586_python.txt |
Q:
How come my MongoDB query doesn't work?
I'm using pymongo: http://api.mongodb.org/python/1.9%2B/index.html
for post in db.datasets.find({"set":"flickr"}).sort("num_favs","-1"):
...
How come I can't sort this? I'd like it sorted descending.
A:
second item in each key pair must be ASCENDING, DESCENDING, or GE... | How come my MongoDB query doesn't work? | I'm using pymongo: http://api.mongodb.org/python/1.9%2B/index.html
for post in db.datasets.find({"set":"flickr"}).sort("num_favs","-1"):
...
How come I can't sort this? I'd like it sorted descending.
| [
"second item in each key pair must be ASCENDING, DESCENDING, or GEO2D\n",
"Use .sort(\"num_favs\",-1) instead of ,\"-1\".\n"
] | [
1,
1
] | [] | [] | [
"database",
"mongodb",
"python",
"sorting"
] | stackoverflow_0004171569_database_mongodb_python_sorting.txt |
Q:
python: whtat is the right way to remove element from list
google no found...
I want two solutions:
1) How to remove an element in a for..in.. loop for a list?
2) How to remove all the elements in the list?
A:
This is almost never what you want to do. Use a list comprehension to filter out the items you don't wa... | python: whtat is the right way to remove element from list | google no found...
I want two solutions:
1) How to remove an element in a for..in.. loop for a list?
2) How to remove all the elements in the list?
| [
"\nThis is almost never what you want to do. Use a list comprehension to filter out the items you don't want.\ndel L[:]\n\n"
] | [
4
] | [
"1) filter()\n2) list = []\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004172535_python.txt |
Q:
python: what does u'{' represent?
When I print out a value it has a u in front of it, I think it is some type notation, what is it? Where I can find a list of such notations?
A:
It meant UNICODE string literal before Python 3.
Documentation about all these literal adornments can be found there.
A:
Unicode Cons... | python: what does u'{' represent? | When I print out a value it has a u in front of it, I think it is some type notation, what is it? Where I can find a list of such notations?
| [
"It meant UNICODE string literal before Python 3.\nDocumentation about all these literal adornments can be found there.\n",
"Unicode Constructors talks about unicode.\n",
"That's creating a unicode string. I'd recommend this section from Dive into Python on the topic\nThere are many advantages to explicitly us... | [
7,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004172652_python.txt |
Q:
How can I represent avi video as set of matrices using Python?
I have video files written in avi format and I would like to analyze these videos using Python. For that I would like to represent every frame of the video as a 2D matrix.
How can I do that? Google search gives me PyMedia as a way to go? Is it really t... | How can I represent avi video as set of matrices using Python? | I have video files written in avi format and I would like to analyze these videos using Python. For that I would like to represent every frame of the video as a 2D matrix.
How can I do that? Google search gives me PyMedia as a way to go? Is it really the best choice or there some other approaches that I should to consi... | [
"Yeah, the latest news on the PyMedia web site is dated 01 Feb 2006. That's a pretty bad sign.\nThe most active and up-to-date open project for manipulating video is ffmpeg. Apparently there is a recently updated python wrapper for it: http://code.google.com/p/pyffmpeg/\nIn general Python is much too slow for doi... | [
1
] | [] | [] | [
"python",
"video",
"video_encoding",
"video_processing"
] | stackoverflow_0004165566_python_video_video_encoding_video_processing.txt |
Q:
Scrapy install: no acceptable C compiler found in $PATH
I am trying to install Scrapy on a a Mac OS X 10.6.2 machine...
When I try to build one of the dependent modules ( libxml2 )
I am getting the following error:
configure: error: no acceptable C compiler found in $PATH
I assume I need the gcc compiler ... is... | Scrapy install: no acceptable C compiler found in $PATH | I am trying to install Scrapy on a a Mac OS X 10.6.2 machine...
When I try to build one of the dependent modules ( libxml2 )
I am getting the following error:
configure: error: no acceptable C compiler found in $PATH
I assume I need the gcc compiler ... is that easy to install on 10.6? Is there some sort of package ... | [
"You need to install the Apple Xcode Development tools. There would be on Apple Developer Connection site or on your Mac OS X installation CDs/DVD. Ensure that the optional components for command line development are installed (\"Unix Development\" in the Xcode 3.x installer)\n",
"Might be of interest to know tha... | [
2,
2,
1
] | [] | [] | [
"gcc",
"macos",
"python",
"scrapy"
] | stackoverflow_0002371997_gcc_macos_python_scrapy.txt |
Q:
SQLalchemy with nested class
I have a rather complex object that takes a few other objects as its members. Something like this:
from engine import engine
Class Car(object):
def __init__(self,engine_type):
self.engine=engine(engine_type)
Is there a pain-free approach to map such nested definitions to... | SQLalchemy with nested class | I have a rather complex object that takes a few other objects as its members. Something like this:
from engine import engine
Class Car(object):
def __init__(self,engine_type):
self.engine=engine(engine_type)
Is there a pain-free approach to map such nested definitions to a database, using SQLAlchemy for ... | [
"It's not much clear what you're trying to accomplish. If I understood, you are trying to define Car model with engine attribute that points to another Engine model, and by creating Car object with engine_type, the code should either:\n\ncreate Engine object with engine type if it doesn't exist\nload the Engine obj... | [
1
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004172427_orm_python_sqlalchemy.txt |
Q:
Working datetime objects in Google App Engine
In this model
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT =... | Working datetime objects in Google App Engine | In this model
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.StringProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now=True)
mDATE0 = db.DateTimeProperty(auto_now_add=True)
mWEIGHT = db.IntegerProperty()
I want to do:
mWEIGHT = mCOU... | [
"This should do what you want:\nimport time\nmWEIGHT = mCOUNT / time.mktime(mDATE0.utctimetuple())\n\nSee mktime.\nmCOUNT / mDATE0.date fails because there is no division operator for int and date.\ntoordinal doesn't suit you because it operates on dates and disregards time completely.\n"
] | [
1
] | [] | [] | [
"datetime",
"google_app_engine",
"python"
] | stackoverflow_0004173245_datetime_google_app_engine_python.txt |
Q:
Extract the SHA1 hash from a torrent file
I've had a look around for the answer to this, but I only seem to be able to find software that does it for you. Does anybody know how to go about doing this in python?
A:
I wrote a piece of python code that verifies the hashes of downloaded files against what's in a .to... | Extract the SHA1 hash from a torrent file | I've had a look around for the answer to this, but I only seem to be able to find software that does it for you. Does anybody know how to go about doing this in python?
| [
"I wrote a piece of python code that verifies the hashes of downloaded files against what's in a .torrent file. Assuming you want to check a download for corruption you may find this useful.\nYou need the bencode package to use this. Bencode is the serialization format used in .torrent files. It can marshal lists, ... | [
34,
17
] | [
"According to this, you should be able to find the md5sums of files by searching for the part of the data that looks like:\nd[...]6:md5sum32:[hash is here][...]e\n(SHA is not part of the spec)\n"
] | [
-2
] | [
"bittorrent",
"extract",
"hash",
"python",
"sha1"
] | stackoverflow_0002572521_bittorrent_extract_hash_python_sha1.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.