content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to know if it is unsigned of a field from mysql by MySQLdb
I use MySQLdb(a python library) to talk with mysql. Is there some way to get the field type using MySQLdb , and the most important thing is how can I know it is unsigned or not ?
I know we can use MYSQL_FIELD struct to get what I mentioned above usin... | How to know if it is unsigned of a field from mysql by MySQLdb | I use MySQLdb(a python library) to talk with mysql. Is there some way to get the field type using MySQLdb , and the most important thing is how can I know it is unsigned or not ?
I know we can use MYSQL_FIELD struct to get what I mentioned above using mysql C api. Is there something similar in MySQLdb ?
Thank you v... | [
"No. There is no provision in MySQLdb (not even via _mysql) for calling mysql_fetch_fields(). You will either have to patch it in, get someone else to do it, or find some way to do it in SQL.\n",
"You can get the field type from the INFORMATION_SCHEMA Tables, e.g.\nSELECT COLUMN_NAME, COLUMN_TYPE\n FROM INFORMAT... | [
1,
1
] | [] | [] | [
"database",
"mysql",
"mysql_python",
"python"
] | stackoverflow_0008133633_database_mysql_mysql_python_python.txt |
Q:
accessing selenium web elements with python
I'm sure this has been answered somewhere, because it's a very basic question - I can not, however, for the life of me, find the answer on the web. I feel like a complete idiot, but I have to ask so, here goes:
I'm writing a python code that will produce a list of all pa... | accessing selenium web elements with python | I'm sure this has been answered somewhere, because it's a very basic question - I can not, however, for the life of me, find the answer on the web. I feel like a complete idiot, but I have to ask so, here goes:
I'm writing a python code that will produce a list of all page addresses on a domain. This is done using sele... | [
"I'm familiar with python's api of selenium\nbut you probably can receive link using get_attribute(attributename) method. So it should be something like:\nlinkstr = \"\"\nfor link in Listlinker: \n linkstr = link.get_attribute(\"href\")\n\n if linkstr in Domenesider:\n pass\n elif str(HovedDomene) in linkstr:... | [
18,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0008121886_python_selenium.txt |
Q:
Python/Glade/PyGTK - Check if Checkbox is Active
After going through the PyGTK libraries and tutorials, I haven't managed to find an exact answer I'm looking for, or maybe I'm just doing something wrong...
Anyway, I'm learning PyGTK and Glade, I'm in the process of scripting a simple downloader application. The G... | Python/Glade/PyGTK - Check if Checkbox is Active | After going through the PyGTK libraries and tutorials, I haven't managed to find an exact answer I'm looking for, or maybe I'm just doing something wrong...
Anyway, I'm learning PyGTK and Glade, I'm in the process of scripting a simple downloader application. The GUI of the application has three check boxes, and then ... | [
"you just need to call \"get_active\" method of gtk checkbox, get object of check button from glade file and call \"get_active\" method on click event of submit button.\nhere, code snippet to be more descriptive:\nclass GladeTest:\n\n def __init__(self):\n\n #Set the Glade file\n filename = \"gui.g... | [
5,
1
] | [] | [] | [
"checkbox",
"glade",
"pygtk",
"python"
] | stackoverflow_0008132854_checkbox_glade_pygtk_python.txt |
Q:
Can't apply image filters on 16-bit TIFs in PIL
I try to apply image filters using python's PIL. The code is straight forward:
im = Image.open(fnImage)
im = im.filter(ImageFilter.BLUR)
This code works as expected on PNGs, JPGs and on 8-bit TIFs. However, when I try to apply this code on 16-bit TIFs, I get the fol... | Can't apply image filters on 16-bit TIFs in PIL | I try to apply image filters using python's PIL. The code is straight forward:
im = Image.open(fnImage)
im = im.filter(ImageFilter.BLUR)
This code works as expected on PNGs, JPGs and on 8-bit TIFs. However, when I try to apply this code on 16-bit TIFs, I get the following error
ValueError: image has wrong mode
Note t... | [
"Your TIFF image's mode is most likely a \"I;16\".\nIn the current version of ImageFilter, kernels can only be applied to\n \"L\" and \"RGB\" images (see source of ImageFilter.py)\nTry converting first to another mode:\nim.convert('L')\n\nIf it fails, try:\nim.mode = 'I'\nim = im.point(lambda i:i*(1./256)).convert(... | [
16,
0
] | [] | [] | [
"image",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0008062564_image_image_processing_python_python_imaging_library.txt |
Q:
Flask authentication using LDAP
I've searched an answer for this but have found nothing - maybe because it's so obvious. But I want to make sure.
What is the correct way to authenticate users using an LDAP server in a Flask web app?
This link describes 4 authentication methods, so along the same lines, do I just... | Flask authentication using LDAP | I've searched an answer for this but have found nothing - maybe because it's so obvious. But I want to make sure.
What is the correct way to authenticate users using an LDAP server in a Flask web app?
This link describes 4 authentication methods, so along the same lines, do I just need to write an LDAP auth decorator... | [
"Yes, you have to write your own decorator which checks the authentication. \nIn this decorator you should call the wrapped function if a user is authenticated. If not you should return a default page reminding the user to login.\n",
"It should be quite straightforward to write an ldap backend if you combined thi... | [
4,
2,
0
] | [] | [] | [
"flask",
"ldap",
"python"
] | stackoverflow_0006748918_flask_ldap_python.txt |
Q:
Widget to Display subprocess stdout?
I have a python based tkinter script which executes some commands using subprocess module.
I need to display the standard output on the GUI itself.
Since I am new to tk (One week Bold :) ), I need your advice How should i proceed.
I have two queries:
Which widget should I lea... | Widget to Display subprocess stdout? | I have a python based tkinter script which executes some commands using subprocess module.
I need to display the standard output on the GUI itself.
Since I am new to tk (One week Bold :) ), I need your advice How should i proceed.
I have two queries:
Which widget should I learn to display the stdout.
How to link the ... | [
"You may want to use the Tkinter.Text widget, described here.\nThe description is quite long, but what you need to understand is mainly that this widget can be used as a buffer, as text should be inserted inside.\nSo, for each new line in the subprocess output, you will have to insert text where you want it. Exampl... | [
2
] | [] | [] | [
"python",
"tk_toolkit",
"tkinter"
] | stackoverflow_0008133487_python_tk_toolkit_tkinter.txt |
Q:
Fast, line-wise "grep -n" equivalent for Unix directory structure
I am trying to create a web interface for searching through a large number of huge configuration files (approx 60000 files, each one with a size between 20 KByte to 50 MByte). Those files are also updated frequently (~3 times/day).
Requirements:
Co... | Fast, line-wise "grep -n" equivalent for Unix directory structure | I am trying to create a web interface for searching through a large number of huge configuration files (approx 60000 files, each one with a size between 20 KByte to 50 MByte). Those files are also updated frequently (~3 times/day).
Requirements:
Concurrency
Must identify the line numbers for each matching line
Good up... | [
"You might wish to investigate the GNU idutils toolkit. On a local copy of the Linux kernel sources, it can give output like this:\n$ gid ugly\ninclude/linux/hil_mlc.h:66: * a positive return value causes the \"ugly\" branch to be taken.\ninclude/linux/hil_mlc.h:101: int ugly; /* Node to jump to on ti... | [
5,
1
] | [] | [] | [
"indexing",
"lucene",
"python",
"search",
"sphinx"
] | stackoverflow_0008121142_indexing_lucene_python_search_sphinx.txt |
Q:
Android SL4A: how to link to relative scripts in HTML/javascript app?
OK, so I have tried three methods to be able to add external javascript and CSS files to my SL4A app. I am on 2.3 Gingerbread (cyanogenmod with google apps) on a ZTE Racer from 3UK, and using SL4A r4, with android python 2.6.2 (where appropriate... | Android SL4A: how to link to relative scripts in HTML/javascript app? | OK, so I have tried three methods to be able to add external javascript and CSS files to my SL4A app. I am on 2.3 Gingerbread (cyanogenmod with google apps) on a ZTE Racer from 3UK, and using SL4A r4, with android python 2.6.2 (where appropriate).
Firstly, I assumed that relative links would work:
<!-- GUI.html - loade... | [
"The answer to this question is simply RTFM - \ndroid.eventWait()\n\ntakes a single optional integer parameter - the number of seconds to wait for any event.\ndroid.eventWaitFor()\n\non the other hand, lets you filter on the type of event with a string in the (compulsory) first argument.\nAll the details here.\nmy ... | [
2
] | [] | [] | [
"html",
"javascript",
"python",
"sl4a"
] | stackoverflow_0008114735_html_javascript_python_sl4a.txt |
Q:
How to create dynamical scoped variables in Python?
I am translating some code from lisp to Python.
In lisp, you can have a let construct with the variables introduced declared as special and thus having dynamic scope. (See http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping)
How can I do likewise in Pytho... | How to create dynamical scoped variables in Python? | I am translating some code from lisp to Python.
In lisp, you can have a let construct with the variables introduced declared as special and thus having dynamic scope. (See http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping)
How can I do likewise in Python? It seems the language does not support this directly,... | [
"I feel Justice is plain right in his reasoning here.\nOn the other hand -- I can't resist implementing proof of concept for still another programing paradigm \"unnatural\" to Python -- I simply love doing this. :-)\nSo, I created a class whose objects'attributes are scopped just like you require (and can be crea... | [
14,
12,
7
] | [
"Dynamic Scoping Considered Harmful.\nDon't use it; don't emulate it.\nIf you need to emulate it, define a dynamic_scope module to emulate this behavior and import the module in all source files. This module should have methods begin which is called in the first line of your functions that use dynamic scopes, end, ... | [
-7
] | [
"dynamic_scope",
"lisp",
"python",
"scope",
"variables"
] | stackoverflow_0002001138_dynamic_scope_lisp_python_scope_variables.txt |
Q:
Python - packages and settings file
I have a python package that needs to pull in settings from my project directory, here is how my project is currently structured:
~/Project/bin/mypackage
- package files
~/Project/myproject/
- project files
- start.py
- settings.py
I guess it's similar to h... | Python - packages and settings file | I have a python package that needs to pull in settings from my project directory, here is how my project is currently structured:
~/Project/bin/mypackage
- package files
~/Project/myproject/
- project files
- start.py
- settings.py
I guess it's similar to how Django is structured, you have a setti... | [
"The way I see it you have several options:\n\nlook for settings and import them either from the current working directory or as determined from environment variables. This is the \"django way\" using DJANGO_SETTINGS_MODULE and PYTHONPATH. This is nice and magical when it works and inconvenient when it doesn't suc... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008135749_python.txt |
Q:
python socket argument
I have some problem in python's socket.
I would like to write a class about sync_file,and these are what I wrote.
import socket
class sync:
def send_file(path,Socket): #I would like to income two argument. First one is the file's path, and the second one is the socket object.
f ... | python socket argument | I have some problem in python's socket.
I would like to write a class about sync_file,and these are what I wrote.
import socket
class sync:
def send_file(path,Socket): #I would like to income two argument. First one is the file's path, and the second one is the socket object.
f = open(path,"rb");
l... | [
"The problem has nothing at all to do with sockets. You're defining send_file as an instance method; it will therefore always be passed a reference to the instance itself as the first argument. \nIf you want to keep it as an instance method, the signature should be:\ndef send_file(self, path, Socket):\n\nYou could... | [
2,
1
] | [] | [] | [
"python",
"python_3.x",
"sockets"
] | stackoverflow_0008136040_python_python_3.x_sockets.txt |
Q:
Is there a multimedia library for Python that is an alternative, portable, object-oriented compared to Pygame, Pyglet and derivatives?
For 2D game development in Python there is a library or binding that has a serious and sustainable development, is pythonic and has a simple and complete design of classes for appl... | Is there a multimedia library for Python that is an alternative, portable, object-oriented compared to Pygame, Pyglet and derivatives? | For 2D game development in Python there is a library or binding that has a serious and sustainable development, is pythonic and has a simple and complete design of classes for application development.
I've learned Pygame, Pyglet, PySFML and cocos2d. But I think that, in some cases, can be very specific limiting the deg... | [
"There is a big list maintained at python wiki, probably you should check Python-Ogre.\n"
] | [
0
] | [] | [] | [
"cocos2d_python",
"pygame",
"pyglet",
"python"
] | stackoverflow_0008131985_cocos2d_python_pygame_pyglet_python.txt |
Q:
does Python logging inform a handler when it is removed with removeHandler?
I'm subclassing FileHandler to write a handler that produces correct xml files (meaning, not while the program is running, only after finishing).
what I do is:
create the file,
write a prologue (a <Diag> element opening),
each log reco... | does Python logging inform a handler when it is removed with removeHandler? | I'm subclassing FileHandler to write a handler that produces correct xml files (meaning, not while the program is running, only after finishing).
what I do is:
create the file,
write a prologue (a <Diag> element opening),
each log record causes a <line /> element in the xml
stop logging means write the </Diag> elem... | [
"Handlers are not notified when they are added or removed from loggers. Loggers use handlers, but handlers know nothing about loggers.\nHowever, a handler has a close() method that is called at program exit by logging.shutdown() (registered with atexit), so you can add your logic there. Just remember to call the ... | [
2
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0008135768_logging_python.txt |
Q:
Install Python Module in local install of web2py
I am running web2py on a Windows machine.
I'm working on an application, but it keeps erroring because it says the module I'm trying to use isn't installed. It is however installed in my local python install.
How can I install modules so that web2py can recognize t... | Install Python Module in local install of web2py | I am running web2py on a Windows machine.
I'm working on an application, but it keeps erroring because it says the module I'm trying to use isn't installed. It is however installed in my local python install.
How can I install modules so that web2py can recognize them?
| [
"web2py recognize any module you have in your local Python installation, unless you have a module with the same name under /modules folder of your application.\nIf you are on windows I do not recommend the use of .exe version of web2py (this version is only for studies) and it has a self contained isolated Python i... | [
13,
5,
0
] | [] | [] | [
"module",
"python",
"web2py",
"windows"
] | stackoverflow_0008131279_module_python_web2py_windows.txt |
Q:
Difference in recursion handling between languages
Here are some snippets in different languages.
Function double in question is taken from SICP, ex. 1.41.
Lisp:
(define (double f) (lambda (x) (f (f x))))
(define (inc x) (+ x 1))
(((double (double double)) inc) 5)
Python:
def double(f):
def result(x):
retu... | Difference in recursion handling between languages | Here are some snippets in different languages.
Function double in question is taken from SICP, ex. 1.41.
Lisp:
(define (double f) (lambda (x) (f (f x))))
(define (inc x) (+ x 1))
(((double (double double)) inc) 5)
Python:
def double(f):
def result(x):
return f(f(x))
return result
def inc(x):
return x + 1
... | [
"How you call the functions in the scheme code is different from the others. The equivalent python would be:\ndouble(double(double))(inc)(5)\n\nIn words, the scheme code creates a function that applies another function 16 times, and applies that function to inc. The python creates functions that apply inc 8 times; ... | [
10,
2
] | [] | [] | [
"javascript",
"lisp",
"python",
"recursion",
"ruby"
] | stackoverflow_0008136559_javascript_lisp_python_recursion_ruby.txt |
Q:
__str__ and pretty-printing (sub)dictionaries
I have an object that consists primarily of a very large nested dictionary:
class my_object(object):
def __init__(self):
self.the_dict = {} # Big, nested dictionary
I've modified __ str__ to pretty-print the top-level dictionary by simply "printing" the o... | __str__ and pretty-printing (sub)dictionaries | I have an object that consists primarily of a very large nested dictionary:
class my_object(object):
def __init__(self):
self.the_dict = {} # Big, nested dictionary
I've modified __ str__ to pretty-print the top-level dictionary by simply "printing" the object:
def __str__(self):
pp = pprint.P... | [
"You could provide a custom displayhook that prints builtin dictionaries and other objects you choose according to your taste at an interactive prompt:\n>>> import sys\n>>> oldhook = sys.displayhook\n>>> sys.displayhook = your_module.DisplayHook(oldhook)\n\nIt doesn't change print obj behavior.\nThe idea is that yo... | [
2,
1,
0
] | [] | [] | [
"pprint",
"python"
] | stackoverflow_0008130395_pprint_python.txt |
Q:
Python:how to change string or list elements
i've been reading from the file and i have hard time getting rid of "\t"
i've tried using i.strip().split("\t")[1] and append it to the list. but if theres more tabs in a row it isnt very useful
for example:
if i do what i described i get
z=['\t\t\t\twoman-in-lingerie',... | Python:how to change string or list elements | i've been reading from the file and i have hard time getting rid of "\t"
i've tried using i.strip().split("\t")[1] and append it to the list. but if theres more tabs in a row it isnt very useful
for example:
if i do what i described i get
z=['\t\t\t\twoman-in-lingerie', 'newspaper-photo', 'reference-to-marie-antoinette... | [
"If you don't want any of the tabs you can use filter after reading everything:\nfor item in my_list:\n item = item.filter(lambda x: x != '\\t', item)\n\n",
"If you're just trying to remove tabs you can use this list comprehension:\nl2 = [item.strip('\\t') for item in l1]\n\nThat'll get rid of any leading or tra... | [
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"split",
"string",
"tabs"
] | stackoverflow_0008131586_python_split_string_tabs.txt |
Q:
Python Data Structure for Treebank?
I'm looking for a Python data structure that handles the Penn Treebank structure. This is a sample of what the Treebank looks like:
( (S
(NP-SBJ (PRP He) )
(VP (VBD shouted) )
(. .) ))
Essentially, I would like a data structure that I can ask things like "What are t... | Python Data Structure for Treebank? | I'm looking for a Python data structure that handles the Penn Treebank structure. This is a sample of what the Treebank looks like:
( (S
(NP-SBJ (PRP He) )
(VP (VBD shouted) )
(. .) ))
Essentially, I would like a data structure that I can ask things like "What are the children of the subject NP?" or "What ... | [
"NLTK modules might be a good start to implement Penn Treebank and other NLP related stuff in Python. \n",
"I still suggest using NLTK to read the treebank (see e.g. this blog post), but I can imagine it doesn't support this kind of general queries.\n\n\"What are the children of the subject NP?\"\n\nThis would b... | [
3,
1
] | [] | [] | [
"corpus",
"nlp",
"nltk",
"python"
] | stackoverflow_0008125132_corpus_nlp_nltk_python.txt |
Q:
Openerp Unable to Show more then 100 Meetings in Calendar View?
When I create meetings in openerp for any user.. I can see them on both Calendar View and List View.. How ever When My meetings exceeds 100 for a single user it doesn't show newly created meetings in calendar view. How ever I can see all of them in my... | Openerp Unable to Show more then 100 Meetings in Calendar View? | When I create meetings in openerp for any user.. I can see them on both Calendar View and List View.. How ever When My meetings exceeds 100 for a single user it doesn't show newly created meetings in calendar view. How ever I can see all of them in my list view... Have any one faced this problem before.. Please Help
| [
"I just experimented with the calendar view for the CRM cases screen. (I don't have the meetings module installed.) It looks like the calender view doesn't update itself right away, and you can force it by moving to the next month and then back.\nHere's what I did, maybe you can do something similar:\n\nOpen the li... | [
0,
0
] | [] | [] | [
"openerp",
"python"
] | stackoverflow_0007696565_openerp_python.txt |
Q:
Twisted web - redirects in request
I was wondering if it is possible to redirect from within a render method in twisted web.
I have tried the various ways of redirecting and have only found it documented when used in the getChild method.
Basically I am checking to see if a user is logged in and if it isn't then fo... | Twisted web - redirects in request | I was wondering if it is possible to redirect from within a render method in twisted web.
I have tried the various ways of redirecting and have only found it documented when used in the getChild method.
Basically I am checking to see if a user is logged in and if it isn't then forward the user onto a different Resource... | [
"Apologies\nUpon further investigation and by fault of my own I had overlooked the \"redirectTo\" method of twisted.web.util\nThis has worked for me perfectly for me. Just thought I would post this here in case anyone else is looking for the same answer.\n from twisted.web.util import redirectTo\n\n def rende... | [
7
] | [] | [] | [
"python",
"twisted.web"
] | stackoverflow_0008128045_python_twisted.web.txt |
Q:
Python. Doing some work on background with Gtk GUI
python 3.2.2
gtk3 3.2.2
python-gobject 3.0.2
I'm trying to display a GUI and do some work in the background. As I understand it should look something like this:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from gi.repo... | Python. Doing some work on background with Gtk GUI |
python 3.2.2
gtk3 3.2.2
python-gobject 3.0.2
I'm trying to display a GUI and do some work in the background. As I understand it should look something like this:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from gi.repository import Gtk, Gdk
class Gui():
def run(s... | [
"Can't claim to be any expert on python threading nor gtk3 but after playing around a little with your example I found something that appears to work the way you want it. Instead of sub classing Thread i use threading.start(target=loop_sleep), and placed that inside Gui.\nGlib.threads_init() also seem to be needed.... | [
8
] | [] | [] | [
"gtk",
"gtk3",
"pygobject",
"python",
"python_3.x"
] | stackoverflow_0008120860_gtk_gtk3_pygobject_python_python_3.x.txt |
Q:
follow javascript redirection with python
I am trying to automate authentication into a website using the login page. The sticking point is that after submitting the login username & password form I am redirected to a new (middleman) page where there is a javascript redirect to the website i want to access.
the s... | follow javascript redirection with python | I am trying to automate authentication into a website using the login page. The sticking point is that after submitting the login username & password form I am redirected to a new (middleman) page where there is a javascript redirect to the website i want to access.
the source looks like this:
<script>
top.location=u... | [
"Try using window.location instead. \n"
] | [
0
] | [] | [] | [
"javascript",
"python",
"redirect"
] | stackoverflow_0008137368_javascript_python_redirect.txt |
Q:
How to port a Python program to Ruby
I'm trying to port a Python program to Ruby but I'm completely ignorant about Python.
Could you give me any advice?
I want to run sampletrain method. However, I dont understand why features=self.getfeatures(item) is available. getfeatures is just an instance variable, isn't it... | How to port a Python program to Ruby | I'm trying to port a Python program to Ruby but I'm completely ignorant about Python.
Could you give me any advice?
I want to run sampletrain method. However, I dont understand why features=self.getfeatures(item) is available. getfeatures is just an instance variable, isn't it? It seem to be used as a method.
docclass... | [
"In Python, because the brackets for a method call aren't optional it is possible to distinguish between a reference to a method and an invocation of a method. i.e.\ndef example():\n pass\n\nx = example # x is now a reference to the example \n # method. no invocation takes place\n # but lat... | [
5,
3,
2
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0008137317_python_ruby.txt |
Q:
print "Düsseldorf" with Python
I am trying to use the string Düsseldorf. When I do that :
# -*- coding: utf-8 -*-
print "Düsseldorf"
it prints strange characters. Could anyone help me please ?
Thank you very much.
A:
>>> print u"Düsseldorf"
Düsseldorf
"Unicode In Python, Completely Demystified"
A:
Most likel... | print "Düsseldorf" with Python | I am trying to use the string Düsseldorf. When I do that :
# -*- coding: utf-8 -*-
print "Düsseldorf"
it prints strange characters. Could anyone help me please ?
Thank you very much.
| [
">>> print u\"Düsseldorf\"\nDüsseldorf\n\n\"Unicode In Python, Completely Demystified\"\n",
"Most likely, your editor is not set to produce UTF-8 output. Setting it to output UTF-8 should fix the problem.\nAlternatively, use unicode escapes:\nprint u\"D\\u00FCsseldorf\"\n\nNote that string literals in Python 2.x ... | [
6,
2
] | [] | [] | [
"character",
"encode",
"python",
"utf_8"
] | stackoverflow_0008138348_character_encode_python_utf_8.txt |
Q:
Plone2pdf --- export to pdf in Plone
Possible Duplicate:
Generate PDF from Plone content types
I am trying to enable export to pdf option in plone ?
Do we have any option in plone for doing that ?
Say, for example I am having a document, which I can print, view in full screen, mail it to a friend and similarly... | Plone2pdf --- export to pdf in Plone |
Possible Duplicate:
Generate PDF from Plone content types
I am trying to enable export to pdf option in plone ?
Do we have any option in plone for doing that ?
Say, for example I am having a document, which I can print, view in full screen, mail it to a friend and similarly can I export that document to pdf ?
Doin... | [
"Two solutions:\nUse print as pdf file in your browser\nTesting addons like http://pypi.python.org/pypi/collective.sendaspdf\n"
] | [
1
] | [] | [] | [
"plone",
"python"
] | stackoverflow_0008118789_plone_python.txt |
Q:
PyDev: Wrong autocompleted import path in same directory
I'm running PyDev 2.2.3 on Aptana 3.0
The following example project resembles my current working project:
\project-dir
\lib
\main
In lib I have reader.py containing a base class Reader(object), and rssreader.py containing RSSReader... | PyDev: Wrong autocompleted import path in same directory | I'm running PyDev 2.2.3 on Aptana 3.0
The following example project resembles my current working project:
\project-dir
\lib
\main
In lib I have reader.py containing a base class Reader(object), and rssreader.py containing RSSReader(Reader).
I'd expect PyDev, when running the Fix/Order Imports... | [
"It is related on how is configured your PYTHONPATH in your Pydev project.\nIf looks like your PYTHONPATH contains only project-dir so Pydev autoimport in an absolute way, so it makes from lib.reader import Reader.\nIf you want to have from reader import Reader, you'll have to put in your PYTHONPATH the project-dir... | [
0
] | [] | [] | [
"aptana",
"code_completion",
"eclipse",
"pydev",
"python"
] | stackoverflow_0008138351_aptana_code_completion_eclipse_pydev_python.txt |
Q:
Plone2pdf Add-on , portalTransform exception : ITransform
Trying to setup plone2pdf in Plone 4. I have downloaded the Plone2pdf archive, extracted it and placed it under the products directory of my instance. I have restarted the instance, by ./bin/instance fg.
Now, I can see the Plone2pdf in the available add-ons... | Plone2pdf Add-on , portalTransform exception : ITransform | Trying to setup plone2pdf in Plone 4. I have downloaded the Plone2pdf archive, extracted it and placed it under the products directory of my instance. I have restarted the instance, by ./bin/instance fg.
Now, I can see the Plone2pdf in the available add-ons page. but, when I click on the activate button it throws an er... | [
"When you install an add-on product you should always first check the project page:\nhttp://plone.org/products/plone2pdf\nto verify any dependency or limitations. In this specific instance, the developer says that the product is compatible with Plone <= 3. In these case, unless you know exactly what you are doing a... | [
2,
1
] | [] | [] | [
"plone",
"python"
] | stackoverflow_0008137845_plone_python.txt |
Q:
Python file not found error when the file clearly exists
I have been working on a project that takes a MySQL dump and restores a database with the information that a user provides. I keep getting a file can not be found error then my custom error for debugging stating that. OS command has failed.
try:
username... | Python file not found error when the file clearly exists | I have been working on a project that takes a MySQL dump and restores a database with the information that a user provides. I keep getting a file can not be found error then my custom error for debugging stating that. OS command has failed.
try:
username = self.username.get()
password = self.password.get()
... | [
"If there is a space in the filename, that will cause the kind of problem you describe. The shell will parse the space as being a delimiter. You may want to do something like\nimport pipes\n...\ndatabase + \" < \" + pipes.quote(filename)\n\nBetter yet, use the subprocess module\ntest = subprocess.call(['mysql', '... | [
2
] | [] | [] | [
"mysql",
"python",
"sql",
"tkinter"
] | stackoverflow_0008138532_mysql_python_sql_tkinter.txt |
Q:
jQuery Post With Data Returned (json, xml etc) with Google App Engine (Python)
I've done jQuery post successfully. However, in order to get the data returned from server side. Can anyone gives example how this can be done in Google App Engine (Python) using webapp framework?
If possible, I need example:
How we ca... | jQuery Post With Data Returned (json, xml etc) with Google App Engine (Python) | I've done jQuery post successfully. However, in order to get the data returned from server side. Can anyone gives example how this can be done in Google App Engine (Python) using webapp framework?
If possible, I need example:
How we can send json data to template.
From template, how we can access the json after jQuery... | [
"First of all get to know the json module. The native json module won't work on appengine, so do\nimport django.utils.simplejson as json\nThen, format your to be \"json\" object(s) as Python dicts,\nobj = {\"name\": \"foo\", \"age\": 20}\nThen use json.dumps to get an str object, that represents the JSON object.\nj... | [
3,
2,
1
] | [] | [] | [
"google_app_engine",
"jquery",
"jquery_post",
"python"
] | stackoverflow_0008113761_google_app_engine_jquery_jquery_post_python.txt |
Q:
Dynamic function creation in Metaclass
I'm doing my first steps in Python 2.7 Metaprogramming, and wrote following code :
class MetaClass(type):
def __init__(cls, name, bases, attrs):
print "Defining class : %s" % (cls,)
ra = [(key, value) for key, value in cls.__dict__.items() if not key.start... | Dynamic function creation in Metaclass | I'm doing my first steps in Python 2.7 Metaprogramming, and wrote following code :
class MetaClass(type):
def __init__(cls, name, bases, attrs):
print "Defining class : %s" % (cls,)
ra = [(key, value) for key, value in cls.__dict__.items() if not key.startswith('_')]
for (k, v) in ra:
... | [
"Ah yes, closures. Read that article then come back.\n for (k, v) in ra:\n setattr(cls, \"_\"+k, v)\n def new_method(val):\n def inner_get_a(cls):\n print \"Getting value of \" + val\n return inner_get_a\n get_a = new_method(k)\n get_a(cls)\n ... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0008138808_python.txt |
Q:
Meaning of '^site_media/(?P.*)$'
# urls.py
site_media = os.path.join(os.path.dirname(__file__), 'site_media'
)
urlpatterns = patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': site_media}),
)
I have problems to understand the mean... | Meaning of '^site_media/(?P.*)$' | # urls.py
site_media = os.path.join(os.path.dirname(__file__), 'site_media'
)
urlpatterns = patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': site_media}),
)
I have problems to understand the meaning of the expression used in above st... | [
"urls are pretty well explained in the docs\n",
"(?P<path>.*) is a named group. http://docs.python.org/library/re.html\n"
] | [
3,
2
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0008138748_django_python_regex.txt |
Q:
Python shelve module question
Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?
A:
The shelve module uses an underlying database package (such as dbm, gdbm or bsddb) .
The restrictions pragraph says (my emphasis):
The shelve module d... | Python shelve module question | Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?
| [
"The shelve module uses an underlying database package (such as dbm, gdbm or bsddb) .\nThe restrictions pragraph says (my emphasis):\n\nThe shelve module does not support concurrent read/write access to shelved objects. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no ... | [
9,
2,
2
] | [] | [] | [
"python",
"shelve"
] | stackoverflow_0000486490_python_shelve.txt |
Q:
hadoop streaming: importing modules on EMR
This previous question addressed how to import modules such as nltk for hadoop streaming.
The steps outlined were:
zip -r nltkandyaml.zip nltk yaml
mv ntlkandyaml.zip /path/to/where/your/mapper/will/be/nltkandyaml.mod
You can now import the nltk module for use in your Py... | hadoop streaming: importing modules on EMR | This previous question addressed how to import modules such as nltk for hadoop streaming.
The steps outlined were:
zip -r nltkandyaml.zip nltk yaml
mv ntlkandyaml.zip /path/to/where/your/mapper/will/be/nltkandyaml.mod
You can now import the nltk module for use in your Python script:
import zipimport
importer = zipimpo... | [
"You have following options:\n\nCreate bootstrap action script and place it on S3. This script would download module in whatever format you prefer and place it where it is accessible for your mapper/reducer. To find out the place where exactly you have to put the files, start the cluster in such a way that it will ... | [
2
] | [] | [] | [
"emr",
"hadoop",
"python"
] | stackoverflow_0008129543_emr_hadoop_python.txt |
Q:
Running parallel Python threads that calls external MPI programme submitted using PBS
I am pretty new to python and I'm unsure of what is the best way to implement a multithread/multiprocess code on a distributed cluster.
I am trying to write a wrapper script using Python that calls an external MPI programme runni... | Running parallel Python threads that calls external MPI programme submitted using PBS | I am pretty new to python and I'm unsure of what is the best way to implement a multithread/multiprocess code on a distributed cluster.
I am trying to write a wrapper script using Python that calls an external MPI programme running on a large cluster using a PBS queuing system. A (very) simplified version of type of sc... | [
"\nWhat I want to do is run multiple versions of the search_loop function in parallel in different directories (containing different starting positions for example) read from a list. The processes is very IO heavy with the MPI calculations taking maybe a few minutes to run each time they are called.\nWould the thre... | [
0
] | [] | [] | [
"cluster_computing",
"multiprocessing",
"multithreading",
"pbs",
"python"
] | stackoverflow_0008139205_cluster_computing_multiprocessing_multithreading_pbs_python.txt |
Q:
Trying to reduce Django Q objects with operator.or_ seems to result in reduction with 'AND'
I am working on an application in Python/Django. I am trying to make a filter by reducing a list of Q objects with Python's operator.or_ function.
Unfortunately it results in a list that is combined with an AND rather than ... | Trying to reduce Django Q objects with operator.or_ seems to result in reduction with 'AND' | I am working on an application in Python/Django. I am trying to make a filter by reducing a list of Q objects with Python's operator.or_ function.
Unfortunately it results in a list that is combined with an AND rather than operator.or_.
The problem occurs in the following code:
print 'operator.or_', operator.or_
filter... | [
"\nq_objects[type] = [Q(**q_dict)]\n\n\nNo. You need to handle each element separately.\nq_objects[type] = [Q(**{k: v}) for (k, v) in q_dict.iteritems()]\n\n"
] | [
2
] | [] | [] | [
"django",
"django_q",
"python"
] | stackoverflow_0008138919_django_django_q_python.txt |
Q:
Implementing "likes" in SQLAlchemy
Implementing "likes" in many applications is really trivial task. However, the problem with likes in application I'm currently developing is: there are many entities that can be "liked" (e.g.: post, photo, etc.).
I've currently rolled out a simple Likeable class, which manages li... | Implementing "likes" in SQLAlchemy | Implementing "likes" in many applications is really trivial task. However, the problem with likes in application I'm currently developing is: there are many entities that can be "liked" (e.g.: post, photo, etc.).
I've currently rolled out a simple Likeable class, which manages likes. My likes table looks like that:
li... | [
"Take a look at Generic Associations example from SA. It does exactly what you are after.\nThe code is in the example directory of the installation or can be browsed here.\nThe simpliest implementation discriminator_on_association.py is what resembles your code most.\n"
] | [
1
] | [] | [] | [
"database_design",
"python",
"sqlalchemy"
] | stackoverflow_0007205229_database_design_python_sqlalchemy.txt |
Q:
Using Celery as a control channel for Twisted applications
I am trying to use Celery as the control channel for a Twisted application. My Twisted application is an abstraction layer that provides a standard interface to various locally running processes (via ProcessProtocol). I would like to use Celery to control ... | Using Celery as a control channel for Twisted applications | I am trying to use Celery as the control channel for a Twisted application. My Twisted application is an abstraction layer that provides a standard interface to various locally running processes (via ProcessProtocol). I would like to use Celery to control this remotely - AMQP seems like the ideal method of controlling ... | [
"Celery probably blocks while waiting for new messages from the network. Since you're running it in one single-threaded process along with the Twisted reactor, it blocks the reactor from running. This will disable most of Twisted, which requires the reactor to actually run (you called reactor.run, but with Celery... | [
12
] | [] | [] | [
"celery",
"python",
"twisted"
] | stackoverflow_0008137277_celery_python_twisted.txt |
Q:
How to set up django with a postgres database in a specific tablespace?
What you'd expect::
settings.py
DATABASES = {
'default': {
'NAME': 'db_name',
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'host',
'PORT... | How to set up django with a postgres database in a specific tablespace? | What you'd expect::
settings.py
DATABASES = {
'default': {
'NAME': 'db_name',
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'host',
'PORT': '5432',
'DEFAULT_TABLESPACE': 'tablespace-name',
}
}
When I u... | [
"A schema and a tablespace are two different things.\nA schema is essentially a namespace. A tablespace is a place in the filesystem. Schemas are logical things; tablespaces are physical things.\nIf you're trying to group together a bunch of related tables (and possibly other named objects) in a namespace, you wan... | [
5
] | [] | [] | [
"django",
"postgresql",
"psycopg2",
"python",
"settings"
] | stackoverflow_0008139219_django_postgresql_psycopg2_python_settings.txt |
Q:
Counting patterns in sequences
I have sequences in text file as follows
>
P1
MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD IIEKNESGWWFVSTAEEQGWVPATCLEGQDGVQDEFSLQPEEEEKYTVIYPYTAR... | Counting patterns in sequences | I have sequences in text file as follows
>
P1
MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD IIEKNESGWWFVSTAEEQGWVPATCLEGQDGVQDEFSLQPEEEEKYTVIYPYTARDQDEM NLERGAVVEVVQKNLEGWWKIRYQGKEGWA... | [
"The findall method returns a list of matching strings. So you can just use len(s) in your code instead of s.\nout.write('%s:\\t%s\\n' %(name,len(s)))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008139721_python.txt |
Q:
How do I extract table data in pairs using BeautifulSoup?
My data sample :
<table id = "history">
<tr class = "printCol">
<td class="name">Google</td><td class="date">07/11/2001</td><td class="state">
<span>CA</span>
</td>
</tr>
<tr class = "printCol">
<td class="name">Apple</td><td class="date">27/08/2001</td>
</... | How do I extract table data in pairs using BeautifulSoup? | My data sample :
<table id = "history">
<tr class = "printCol">
<td class="name">Google</td><td class="date">07/11/2001</td><td class="state">
<span>CA</span>
</td>
</tr>
<tr class = "printCol">
<td class="name">Apple</td><td class="date">27/08/2001</td>
</tr>
<tr class = "printCol">
<td class="name">Microsoft</td><td ... | [
"List comprehension will make it easier:\ntable = soup.find(\"table\", id = \"history\")\nrows = table.findAll('tr')\ndata = [[td.findChildren(text=True) for td in tr.findAll(\"td\")] for tr in rows]\n# data now contains:\n[[u'Google', u'07/11/2001'],\n [u'Apple', u'27/08/2001'],\n [u'Microsoft', u'01/11/1991']]\n\... | [
20,
2
] | [] | [] | [
"beautifulsoup",
"loops",
"python"
] | stackoverflow_0008139797_beautifulsoup_loops_python.txt |
Q:
networkx: 'super' object has no attribute 'node'
I try extend a class from networkx.DiGraph
import networkx as nx
class branch(nx.DiGraph):
def __init__(self,g,raiz):
self.b=super(branch,self)
self.b.__init__(g)
self.r = raiz
def strong(self):
print self.b.nodes(),self.b.nod... | networkx: 'super' object has no attribute 'node' | I try extend a class from networkx.DiGraph
import networkx as nx
class branch(nx.DiGraph):
def __init__(self,g,raiz):
self.b=super(branch,self)
self.b.__init__(g)
self.r = raiz
def strong(self):
print self.b.nodes(),self.b.node[self.r]
if self.b.node[self.r]['w']>0: ... | [
"Simply enough, because node[] doesn't exist. Instead, nodes() returns an array that you can index with []. The code for this might look something like self.b.nodes()[self.r].\n"
] | [
0
] | [] | [] | [
"inheritance",
"networkx",
"python",
"superclass"
] | stackoverflow_0008140110_inheritance_networkx_python_superclass.txt |
Q:
What is the best method to call a Python 3.x program from within Python 2.x?
I'm writing a Django web application. As of now, Django does not support Python 3. For the purposes of my web application, and without getting into to much detail, I essentially need to use some libraries that only support Python 3. Suffi... | What is the best method to call a Python 3.x program from within Python 2.x? | I'm writing a Django web application. As of now, Django does not support Python 3. For the purposes of my web application, and without getting into to much detail, I essentially need to use some libraries that only support Python 3. Suffice it to say that after much thorough research no 2.x alternative was found.
So my... | [
"Since the Python 3 and Python 2 interpreters are totally separate executables and have separate libraries installed on your system, using subprocess to invoke one from the other is the best practice. It's not a hack at all. There are a number of ways to pass data between them but the two interpreters should be r... | [
5,
1
] | [] | [] | [
"python",
"python_3.x",
"subprocess"
] | stackoverflow_0008138948_python_python_3.x_subprocess.txt |
Q:
Django queryset on floating point range
I came through a problem which I never happened to face before in Django queryset. I have more then 1,00,000 of floating point datatype (records) along with foreign key field in one data model class. What I am trying to do is query on these records with following procedure.
... | Django queryset on floating point range | I came through a problem which I never happened to face before in Django queryset. I have more then 1,00,000 of floating point datatype (records) along with foreign key field in one data model class. What I am trying to do is query on these records with following procedure.
User will enter value (v) e.g 1248.597290039... | [
"If you have the high and low ends of your range already computed, then you can use a simple range query in Django:\nobjects = my_model.objects.filter(field__gte=LR, field__lte=HR)\n\nor, somewhat shorter:\nobjects = my_model.objects.filter(field__range=(LR, HR))\n\n(You'll have to replace 'my_model' and 'field' wi... | [
6
] | [] | [] | [
"django",
"django_queryset",
"floating_point",
"python"
] | stackoverflow_0008137748_django_django_queryset_floating_point_python.txt |
Q:
Performing a check when saving a model in Django's admin
I'd like to perform a check when saving a model via the django Admin panel. I thought about using ModelAdmin.save_model(), however, from the documentation it says:
ModelAdmin.save_model() and ModelAdmin.delete_model() must save/delete the object, they are n... | Performing a check when saving a model in Django's admin | I'd like to perform a check when saving a model via the django Admin panel. I thought about using ModelAdmin.save_model(), however, from the documentation it says:
ModelAdmin.save_model() and ModelAdmin.delete_model() must save/delete the object, they are not for veto purposes, rather they allow you to perform extra o... | [
"Starting with Django 1.2 you can use model validation.\n",
"Simply create a modelform with normal validation via the clean methods, then assign that form to be used in the admin by doing form = MyFormClass inside the ModelAdmin class.\n",
"It's not really admin site specific, but this section describes how to ... | [
4,
3,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0008139892_django_django_admin_python.txt |
Q:
Cherrypy pass local variable between functions under Root()
Please look at the code :
class Root:
def __init__(self):
self._Name = None
def index(self):
self._Name = getNameFromUser()
return mytemplate.render()
index.exposed = True
def foo(self):
myName = self._Na... | Cherrypy pass local variable between functions under Root() | Please look at the code :
class Root:
def __init__(self):
self._Name = None
def index(self):
self._Name = getNameFromUser()
return mytemplate.render()
index.exposed = True
def foo(self):
myName = self._Name
//dosomething
return mytemplate.render( showmy... | [
"When you set something on the server object, you are setting it for the application not the user. If you want to store information on a user temporarily, use the sessions interface or (if it is not information that needs to be secured / tamper-proof) in a cookie.\n"
] | [
1
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0008139729_cherrypy_python.txt |
Q:
Pythonic way to have a "size safe" slicing
Here is a quote from https://stackoverflow.com/users/893/greg-hewgill answer to Explain Python's slice notation.
Python is kind to the programmer if there are fewer items than you ask
for. For example, if you ask for a[:-2] and a only contains one
element, you get a... | Pythonic way to have a "size safe" slicing | Here is a quote from https://stackoverflow.com/users/893/greg-hewgill answer to Explain Python's slice notation.
Python is kind to the programmer if there are fewer items than you ask
for. For example, if you ask for a[:-2] and a only contains one
element, you get an empty list instead of an error. Sometimes you
... | [
"Here's one way that is arguably more Pythonic. If you want to parse a byte string you can use the struct module that is provided for that exact purpose:\nimport struct\nfrom collections import namedtuple\nDetails = namedtuple('Details', 'name phone')\n\ndef lazy_parse(data):\n \"\"\"extract (name, phone) from a... | [
5,
3,
2,
2
] | [] | [] | [
"python",
"slice"
] | stackoverflow_0008077664_python_slice.txt |
Q:
ElementTree can't seem to run findall() on findall() results
I have XML shaped like the following:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:docs="http://schemas.google.com/docs/2007" xmlns:batch="http://schemas.go... | ElementTree can't seem to run findall() on findall() results | I have XML shaped like the following:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:docs="http://schemas.google.com/docs/2007" xmlns:batch="http://schemas.google.com/gdata/batch"
<entry gd:etag=""HxYZGQVeHyt7ImBr&q... | [
"The problem is that document_node[0] in your code already references the title element, and looking through its children returns nothing.\n"
] | [
1
] | [] | [] | [
"elementtree",
"python",
"xpath"
] | stackoverflow_0008140284_elementtree_python_xpath.txt |
Q:
Elaborate Explanation for MethodObject and FunctionObject in Python Documentation
Could somebody please elaborate this paragraph to me:
If you still don’t understand how methods work, a look at the
implementation can perhaps clarify matters. When an instance attribute
is referenced that isn’t a data attribut... | Elaborate Explanation for MethodObject and FunctionObject in Python Documentation | Could somebody please elaborate this paragraph to me:
If you still don’t understand how methods work, a look at the
implementation can perhaps clarify matters. When an instance attribute
is referenced that isn’t a data attribute, its class is searched. If
the name denotes a valid class attribute that is a funct... | [
"A method object is a wrapper for a function object that allows the function to be attached (bound) to an instance. The method object knows what instance it is bound to, and, when it is called, it calls the wrapped function, passing the instance as the first argument. In other words, the method object is responsibl... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008140469_python.txt |
Q:
Django retrieve all related attributes for model
I am writing a store based app. Say theres Store A , Store A can have multiple users, and each user can belong to multiple stores. However, each store has Products and each Product has sizes associated with them.
class Variation(models.Model):
product = models.F... | Django retrieve all related attributes for model | I am writing a store based app. Say theres Store A , Store A can have multiple users, and each user can belong to multiple stores. However, each store has Products and each Product has sizes associated with them.
class Variation(models.Model):
product = models.ForeignKey("Product")
size = models.CharField(choic... | [
"it sounds like what you want to be using is the the django \"Sites\" framework \nadd a ForeignKey to Store to point to Site and make it unique. \nit may be wise to point Variation and Products' ForeignKeys at Site instead of Store at this point too so that in your views you can filter your results by current site.... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0008129632_django_django_admin_django_models_python.txt |
Q:
Improving Newton's Method Recursion
I have solved a previous problem and now I am stuck with this one.
It is asking for an improvement of the previous solution which I posted below, but can't quite understand what the problem is asking. (Also, can't really figure out how to solve it.)
Please help
thanks.
Proble... | Improving Newton's Method Recursion | I have solved a previous problem and now I am stuck with this one.
It is asking for an improvement of the previous solution which I posted below, but can't quite understand what the problem is asking. (Also, can't really figure out how to solve it.)
Please help
thanks.
Problem:
Elena complains that the recursive new... | [
"The problem is a complaint that when somebody calls newtonSquare, they always do so with an initial estimate of 1.0. To set it as the default value, unless you explicitly provide it, you only have to modify the definition of the function to:\ndef newtonSquare(x, estimate = 1.0):\n\n",
"An alternative to the defa... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0008133298_python.txt |
Q:
Difference between python 1 and 2
Just out of complete curiosity, did Python 2 add anything major to Python 1? And if so, what?
A:
Summarised from http://docs.python.org/whatsnew/2.0.html:
Unicode objects
List comprehensions
Augmented assigment
Cyclic garbage collection
*args and **kwargs argument unpacking
A... | Difference between python 1 and 2 | Just out of complete curiosity, did Python 2 add anything major to Python 1? And if so, what?
| [
"Summarised from http://docs.python.org/whatsnew/2.0.html:\n\nUnicode objects\nList comprehensions\nAugmented assigment\nCyclic garbage collection\n*args and **kwargs argument unpacking\n\n",
"The changes to the codebase were for unicode, list comprehensions, string methods, augmented assignment operators, and ga... | [
28,
5
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0008141025_python_python_2.x.txt |
Q:
How to delete None Type object in App Engine datastore using Python?
qObj = Group.all().fetch(Group.all().count())
for g in qObj:
self.response.out.write(g.group)
I have as an output all value I have put and one value: "None" which is one of NoneType object. I want to delete this entity. When I try this code:
... | How to delete None Type object in App Engine datastore using Python? | qObj = Group.all().fetch(Group.all().count())
for g in qObj:
self.response.out.write(g.group)
I have as an output all value I have put and one value: "None" which is one of NoneType object. I want to delete this entity. When I try this code:
qResult = Group.gql( 'WHERE group=:1', g).get()
db.delete(qResult)
I am g... | [
"Hard to tell without seeing your code in full context, but assuming that your delete action is within the iterator the problem is actually within this statement:\nqResult = Group.gql( 'WHERE group=:1', g).get()\n\nYour variable 'g' is a Group entity/object and so isn't appropriate as a filter on 'group' which is a... | [
1,
0
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0008138102_google_app_engine_gql_python.txt |
Q:
Convert values in CSV column to individual columns
I have a CSV file with the following format:
ID | STUFF | Custom | Custom Value
1 | string1 | name1 | val1
1 | string1 | name2 | val2
1 | string1 | name3 | val3
2 | string2 | name1 | val4
2 | string2 | name3 | val5
3 | string3 | name2 | val6
etc...
The imp... | Convert values in CSV column to individual columns | I have a CSV file with the following format:
ID | STUFF | Custom | Custom Value
1 | string1 | name1 | val1
1 | string1 | name2 | val2
1 | string1 | name3 | val3
2 | string2 | name1 | val4
2 | string2 | name3 | val5
3 | string3 | name2 | val6
etc...
The import part about the CSV is that the current Custom Column... | [
"The csv module is definitely a good start.\nI would build a dict for each ID, mapping field names to values. E.g. for ID 1:\n{'STUFF':'String 1', 'name1':'val1', 'name2':'val2', 'name3':'val3'}\n\nYou can store these in a list (if your IDs are consecutive integers), or in another dict.\nKeep a set of all the field... | [
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008140690_csv_python.txt |
Q:
How to dynamically select a method call?
I have a code similar to this:
if command == "print":
foo_obj.print()
if command == "install":
foo_obj.install()
if command == "remove":
foo_obj.remove()
command is a string (I define it by parsing command line arguments, but that's beyond the point). Is t... | How to dynamically select a method call? | I have a code similar to this:
if command == "print":
foo_obj.print()
if command == "install":
foo_obj.install()
if command == "remove":
foo_obj.remove()
command is a string (I define it by parsing command line arguments, but that's beyond the point). Is there a way to replace the above chunck of code... | [
"Use getattr and call its result:\ngetattr(foo_obj, command)()\n\nRead that as:\nmethod = getattr(foo_obj, command)\nmethod()\n\nBut of course, be careful when taking the command string from user input. You'd better check whether the command is allowed with something like\ncommand in {'print', 'install', 'remove'}\... | [
6,
5,
3,
3,
2
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0008141165_python_python_2.7.txt |
Q:
Interpolation of satellite image with overlapping areas
I am having a problem with interpolation of the satellite images. I understand how the satellite taking image of the earth:
and I am trying to perform an interpolation by using following code:
import scipy as sc
import scipy.interpolate as spi
import numpy a... | Interpolation of satellite image with overlapping areas | I am having a problem with interpolation of the satellite images. I understand how the satellite taking image of the earth:
and I am trying to perform an interpolation by using following code:
import scipy as sc
import scipy.interpolate as spi
import numpy as np
def interpolate_data(img, lat, lon):
p_x, p_y = sc.mgr... | [
"If your images have geographical extent data attached (e.g. GeoTIFF files) you could consider using the GDAL library, this library is written in C/C++ but also has a python package.\nIt can work with dozens of different formats and has several different image processing methods for image warping and transforming.\... | [
1,
0
] | [] | [] | [
"image_processing",
"interpolation",
"python"
] | stackoverflow_0008117767_image_processing_interpolation_python.txt |
Q:
Why is my python function returning multiple brackets?
I'm somewhat of a noob to python but I'm trying to create a recursive function which works just like the built in range function:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
but its returning multiple ... | Why is my python function returning multiple brackets? | I'm somewhat of a noob to python but I'm trying to create a recursive function which works just like the built in range function:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
but its returning multiple lists.
Instead of [3,4,5,6], which is what I want, its retur... | [
"When you recurse like that, Range returns a list each time:\nRange(3,7)\n# translates to\n[3, Range(4,7)]\n# which translates to\n[3, [4, Range(5,7)]]\n# etc.\n\nIn order to avoid this, add your lists together:\ndef Range (lo, hi):\n if lo >= hi:\n return []\n else:\n return [lo] + Range(lo+1, ... | [
5,
3,
1,
0
] | [] | [] | [
"brackets",
"python",
"recursion"
] | stackoverflow_0008141482_brackets_python_recursion.txt |
Q:
Unittest in parallel
Possible Duplicate:
Can Python's unittest test in parallel, like nose can?
I have tests that are used with unittest and they are run 1 by 1. I would like to run them in parallel because I have a lot of wait so it would go much faster.
Is it possible ? I can't find a solution on the internet ... | Unittest in parallel |
Possible Duplicate:
Can Python's unittest test in parallel, like nose can?
I have tests that are used with unittest and they are run 1 by 1. I would like to run them in parallel because I have a lot of wait so it would go much faster.
Is it possible ? I can't find a solution on the internet eventhough many ppl are t... | [
"You could alternatively parallelize via the shell, no? I just tried this command\nfind -type f -name \"_test_*.py\" | sed 's/^\\.\\///; s/\\.py$//; s/\\//./g;' | xargs -t -P 10 -n 2 python -m unittest\n\nThe find outputs a list of test files, so adapt the filename pattern to your naming convention. The sed transfo... | [
2,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0008133453_python_unit_testing.txt |
Q:
Python Exceptions Control/Flow Issue
I've been working in Python and ran into something that must be a common occurrence.
I have five statements that all fall into a common pitfall of raising
FooException and BarException. I want to run each of them, guarding against
these exceptions but continuing to process eve... | Python Exceptions Control/Flow Issue | I've been working in Python and ran into something that must be a common occurrence.
I have five statements that all fall into a common pitfall of raising
FooException and BarException. I want to run each of them, guarding against
these exceptions but continuing to process even if an exception is raised after
some han... | [
"def execute_silently(fn, exceptions = (FooException, BarException)):\n try:\n fn()\n except Exception as e:\n if not isinstance(e, exceptions):\n raise\n\nexecute_silently(foo)\nexecute_silently(bar)\n# ...\n# or even:\nfor fn in (foo, bar, ...):\n execute_silently(fn)\n\n",
"Wh... | [
4,
3,
0
] | [] | [] | [
"exception_handling",
"python",
"try_except"
] | stackoverflow_0008141527_exception_handling_python_try_except.txt |
Q:
Solve nonlinear system of equations with minimal error
I have some nonlinear optimization problem (preferably solved in python):
Given are 3 circles (centers x1..3,y1..3, radii d1..3) in a 2D plane.
(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y-y3)^2 - r3^2 = 0
The common point (x/y)... | Solve nonlinear system of equations with minimal error | I have some nonlinear optimization problem (preferably solved in python):
Given are 3 circles (centers x1..3,y1..3, radii d1..3) in a 2D plane.
(x-x1)^2 + (y-y1)^2 - r1^2 = 0
(x-x2)^2 + (y-y2)^2 - r2^2 = 0
(x-x3)^2 + (y-y3)^2 - r3^2 = 0
The common point (x/y) is desired and can be computed by fsolve (scipy.optimize) i... | [
"This is actually not so hard given the decription here:\nhttp://mathworld.wolfram.com/Circle-CircleIntersection.html\nA proposed algorithm:\n\nFind x - as described in the link.\nCalculate y. \n\nBoth should be done using any 2 circles. \n\nPlug the points (x,y) and (x,-y) in the 3 circle.\nThe solution is either ... | [
1,
0
] | [] | [] | [
"nonlinear_optimization",
"optimization",
"python",
"scipy"
] | stackoverflow_0007996405_nonlinear_optimization_optimization_python_scipy.txt |
Q:
Calling tap_example.py from C# to get Membase TAP Stream
I am trying to use the dynamic language run time / IronPython to simply run a .py script with command arguments and then get the std output. This is for executing the membase TAP protocol which isn't implemented in C# yet:
public class MembaseTap
{
publi... | Calling tap_example.py from C# to get Membase TAP Stream | I am trying to use the dynamic language run time / IronPython to simply run a .py script with command arguments and then get the std output. This is for executing the membase TAP protocol which isn't implemented in C# yet:
public class MembaseTap
{
public void Tap()
{
var pyEngine = Python.CreateEngine(... | [
"You can pass in the arguments when you create the engine as shown by Jeff Hardy's answer in the Script arguments and Embedded IronPython post on StackOverflow. Your C# code would look like the following:\npublic class MembaseTap\n{\n public void Tap()\n {\n var options = new Dictionary<string, object>... | [
2
] | [] | [] | [
"c#",
"dynamic",
"ironpython",
"membase",
"python"
] | stackoverflow_0008130851_c#_dynamic_ironpython_membase_python.txt |
Q:
How can I convert input file data into date format?
How can I read a file and convert each line into a date?
Ok so I have a "holiday.txt" file that I intend to have Python read. In it, I want to have lines that say such things as:
11/24/11
11/25/11
12/25/11
12/31/11
1/1/12
5/28/12
7/4/12
9/3/12
etc. These are th... | How can I convert input file data into date format? | How can I read a file and convert each line into a date?
Ok so I have a "holiday.txt" file that I intend to have Python read. In it, I want to have lines that say such things as:
11/24/11
11/25/11
12/25/11
12/31/11
1/1/12
5/28/12
7/4/12
9/3/12
etc. These are the holidays for my company. I want the program to read the... | [
"You could use datetime.strptime to convert the strings into datetime.datetime objects:\nimport datetime as dt\ndates=[]\nwith open('holiday.txt','r') as f:\n dates=[dt.datetime.strptime(line.strip(),'%m/%d/%y')\n for line in f if line.strip()]\n\nprint(dates)\n\n",
"See the Python datetime documenta... | [
4,
0,
0
] | [] | [] | [
"python",
"time"
] | stackoverflow_0008137825_python_time.txt |
Q:
Adding a user/accounts table to Postgres in Django View
Go to edit 2
Calling the following adduser function in views.py. I save the user first because it's id (automatically created by Django upon INSERT) is the primary/foreign key for accounts and passwords. Adding a user seems to be working fine, but then when i... | Adding a user/accounts table to Postgres in Django View | Go to edit 2
Calling the following adduser function in views.py. I save the user first because it's id (automatically created by Django upon INSERT) is the primary/foreign key for accounts and passwords. Adding a user seems to be working fine, but then when it gets to the Accounts(user=u), the following error throws:
... | [
"My money is on a misspelled name. I notice in the error message that you have\nOmniCloud_App_accounts\nOmniCloud_App_user\n\nSecond table uses singular. There isn't a second table like this by chance:\nOmniCloud_App_users\n\nAlso, using mixed case identifiers in PostgreSQL is a great source of reputation here on S... | [
4,
0,
0,
0
] | [] | [] | [
"django",
"django_views",
"postgresql",
"python"
] | stackoverflow_0008039116_django_django_views_postgresql_python.txt |
Q:
Any workarounds for Python's select and handling of EINTR in Linux?
In one of my recent projects I happened to have in the same process (a Python program, its a multithreaded application):
a Boost::Python module to a library that linked against the AVT PvAPI SDK, i.e. in the widest sense a driver to get image fra... | Any workarounds for Python's select and handling of EINTR in Linux? | In one of my recent projects I happened to have in the same process (a Python program, its a multithreaded application):
a Boost::Python module to a library that linked against the AVT PvAPI SDK, i.e. in the widest sense a driver to get image frames from a camera. This library (the PvApi SDK) produces a SIGALRM intern... | [
"Try using signal.sigintterupt to make the SIGALRM signal restart system calls automatically. Or you could use signal.signal(signal.SIGALRM, signal.SIG_IGN) to ignore the alarm signal, assuming you're not using it for anything.\n"
] | [
0
] | [] | [] | [
"eintr",
"linux",
"python",
"signals"
] | stackoverflow_0008141806_eintr_linux_python_signals.txt |
Q:
Implement python replace() function without using regexp
I'm trying to rewrite the equivalent of the python replace() function without using regexp. Using this code, i've managed to get it to work with single chars, but not with more than one character:
def Replacer(self, find_char, replace_char):
s = []
f... | Implement python replace() function without using regexp | I'm trying to rewrite the equivalent of the python replace() function without using regexp. Using this code, i've managed to get it to work with single chars, but not with more than one character:
def Replacer(self, find_char, replace_char):
s = []
for char in self.base_string:
if char == find_char:
... | [
"Here is a method that should be pretty efficient:\ndef replacer(self, old, new):\n return ''.join(self._replacer(old, new))\n\ndef _replacer(self, old, new):\n oldlen = len(old)\n i = 0\n idx = self.base_string.find(old)\n while idx != -1:\n yield self.base_string[i:idx]\n yield new\n ... | [
4,
4,
1
] | [] | [] | [
"function",
"python",
"string"
] | stackoverflow_0008139746_function_python_string.txt |
Q:
How to get django form wizard extra_context to show on template?
EDIT: FWIW, I am running django 1.3
I have...
class CreateProductWizard(FormWizard):
def get_template(self, step):
if step == 1:
return 'product/form_wizard/editor.html'
else:
return 'product/form_wizard/wi... | How to get django form wizard extra_context to show on template? | EDIT: FWIW, I am running django 1.3
I have...
class CreateProductWizard(FormWizard):
def get_template(self, step):
if step == 1:
return 'product/form_wizard/editor.html'
else:
return 'product/form_wizard/wizard_%s.html' % step
def process_step(self, request, form, step):
... | [
"Looking at the docs i'd say that get_context_data is what you are after:\n\nReturns the template context for a step. You can overwrite this method\n to add more data for all or some steps. This method returns a\n dictionary containing the rendered form step.\n\n",
"So what I ended up using on the template was:... | [
5,
2
] | [] | [] | [
"django",
"django_formwizard",
"forms",
"python"
] | stackoverflow_0008130739_django_django_formwizard_forms_python.txt |
Q:
lxml classic: Get text content except for that of nested tags?
This must be an absolute classic, but I can't find the answer here. I'm parsing the following tag with lxml cssselect:
<li><a href="/stations/1"><span class="num">3</span> Detroit</a></li>
I want to get the content of the <li> tag without the content ... | lxml classic: Get text content except for that of nested tags? | This must be an absolute classic, but I can't find the answer here. I'm parsing the following tag with lxml cssselect:
<li><a href="/stations/1"><span class="num">3</span> Detroit</a></li>
I want to get the content of the <li> tag without the content of the <span> tag.
Currently I have:
stop_list = doc.cssselect('ol... | [
"For your example, I think going with XPath is cleaner and easier than CSS:\n>>> xml = '<li><a href=\"/stations/1\"><span class=\"num\">3</span> Detroit</a></li>'\n>>> root = etree.fromstring(xml)\n>>> print( root.xpath('/li/a/text()'))\n[' Detroit']\n\n>>> xml = '<li><a href=\"/stations/1\">I <span>FooBar!</span> ... | [
4,
3
] | [] | [] | [
"lxml",
"python",
"web_scraping"
] | stackoverflow_0008141956_lxml_python_web_scraping.txt |
Q:
Why is only one Flask teardown_request function being called when view raises Exception?
This simple application, has two teardown_request handlers, and I'd expect both of them to be called for every request, no matter what happens in the view implementation, as per the documentation
import flask
import werkzeug.e... | Why is only one Flask teardown_request function being called when view raises Exception? | This simple application, has two teardown_request handlers, and I'd expect both of them to be called for every request, no matter what happens in the view implementation, as per the documentation
import flask
import werkzeug.exceptions
app = flask.Flask(__name__)
@app.teardown_request
def teardown1(response):
pri... | [
"Just discovered the answer myself.\nThe teardown_request functions are not supposed to take a response and return a response, the way after_request does. They apparently take an argument which is usually None unless an Exception which does not derive from HttpException is raised by the view, in which case they are... | [
25
] | [] | [] | [
"flask",
"python",
"werkzeug"
] | stackoverflow_0008141721_flask_python_werkzeug.txt |
Q:
Simple 'if' or logic statement in Python
How would you write the following in Python?
if key < 1 or key > 34:
I've tried every way I can think of and am finding it very frustrating.
A:
If key isn't an int or float but a string, you need to convert it to an int first by doing
key = int(key)
or to a float by doi... | Simple 'if' or logic statement in Python | How would you write the following in Python?
if key < 1 or key > 34:
I've tried every way I can think of and am finding it very frustrating.
| [
"If key isn't an int or float but a string, you need to convert it to an int first by doing\nkey = int(key)\n\nor to a float by doing\nkey = float(key)\n\nOtherwise, what you have in your question should work, but\nif (key < 1) or (key > 34):\n\nor\nif not (1 <= key <= 34):\n\nwould be a bit clearer.\n",
"Here's ... | [
226,
19
] | [] | [] | [
"if_statement",
"logic",
"python"
] | stackoverflow_0007141208_if_statement_logic_python.txt |
Q:
Python: How do I redirect output of os.system to python shell?
I want to make a simple batch script using python using os.system. I am able to run the commands just fine, but the output for those commands dont print to the python shell. Is there some way to redirect the output to the python shell?
A:
You can use... | Python: How do I redirect output of os.system to python shell? | I want to make a simple batch script using python using os.system. I am able to run the commands just fine, but the output for those commands dont print to the python shell. Is there some way to redirect the output to the python shell?
| [
"You can use subprocess.\nfrom subprocess import Popen, PIPE\np1 = Popen(['ls'], stdout=PIPE)\nprint p1.communicate()[0]\n\nThis will print the directory listing for the current directory. The communicate() method returns a tuple (stdoutdata, stderrdata). If you don't include stdout=PIPE or stderr=PIPE in the Popen... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0008140750_python.txt |
Q:
Using append() on transient anonymous lists inside of a list comprehension in Python
I have a nested list that looks like this:
mylist = [['A;B', 'C'], ['D;E', 'F']]
I'd like to have it in the following form:
[['A', 'B', 'C'], ['D', 'E', 'F']]
Figured I'd write a simple list comprehension to do the task:
>>> new... | Using append() on transient anonymous lists inside of a list comprehension in Python | I have a nested list that looks like this:
mylist = [['A;B', 'C'], ['D;E', 'F']]
I'd like to have it in the following form:
[['A', 'B', 'C'], ['D', 'E', 'F']]
Figured I'd write a simple list comprehension to do the task:
>>> newlist = [item[0].split(';').append(item[1]) for item in mylist]
>>> newlist
[None, None]
A... | [
"[a.split(';') + [b] for a, b in mylist]\n\n",
"The problem is that you are storing the return value of the append() method, which is None.\nOne solution is to use itertools.chain() and store it in a list like so:\nimport itertools\nmylist = [['A;B', 'C'], ['D;E', 'F']]\nnewlist = [list(itertools.chain(item[0].sp... | [
4,
2,
1,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0008142534_list_comprehension_python.txt |
Q:
Validating and filling default values in XML based on XSD in Python
How do I fill the default value in my XML during validation against XSD? If my attribute is not defined as use="require" and have default="1", it could be possible to fill these default values from the XSD to the XML.
Example:
Original XML:
<a>
<... | Validating and filling default values in XML based on XSD in Python | How do I fill the default value in my XML during validation against XSD? If my attribute is not defined as use="require" and have default="1", it could be possible to fill these default values from the XSD to the XML.
Example:
Original XML:
<a>
<b/>
<b c="2"/>
</a>
XSD scheme:
<xs:element name="a">
<xs:complexType>... | [
"To follow up on my comment, here's some code\nfrom lxml import etree\nfrom lxml.html import parse\n\nschema_root = etree.XML('''\\\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n<xs:element name=\"a\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"b\" maxOccurs=\"unbounded\">\n <xs:com... | [
3
] | [] | [] | [
"python",
"xml",
"xsd"
] | stackoverflow_0003013270_python_xml_xsd.txt |
Q:
autotools and python setup.py
I have a project written mostly in c++ that includes a few helper scripts written in python. For the moment, the scripts contain variables substituted by the autotools:
#!@PYTHON@
# -*- coding: utf-8 -*-
...
try:
datapath = os.environ['DATA_PATH']
except KeyError:
datapath = ... | autotools and python setup.py | I have a project written mostly in c++ that includes a few helper scripts written in python. For the moment, the scripts contain variables substituted by the autotools:
#!@PYTHON@
# -*- coding: utf-8 -*-
...
try:
datapath = os.environ['DATA_PATH']
except KeyError:
datapath = '@pkgdatadir@'
And here is an extr... | [
"I'd use autoconf to setup script.py instead of 'make' as you've shown. Something like:\nAC_CONFIG_FILES([script.py], [chmod +x script.py])\n\nbefore AC_OUTPUT in configure.ac should do it.\n"
] | [
1
] | [] | [] | [
"autotools",
"python"
] | stackoverflow_0008129836_autotools_python.txt |
Q:
ADB push command android emulator
I am trying to import a python library into SL4A. From my understanding, the easiest way to do this is to import the zipped files (egg files) of the python library into the SD Card and then import it into SL4A. Since I do not have an android device yet, I am working with the emula... | ADB push command android emulator | I am trying to import a python library into SL4A. From my understanding, the easiest way to do this is to import the zipped files (egg files) of the python library into the SD Card and then import it into SL4A. Since I do not have an android device yet, I am working with the emulator. Whenever I try to push the zipped ... | [
"You can create your own sdcard image, put files on it and after that mount in emulator.\nTo create image you can use mksdcard <size> <file>: mksdcard 1024M sdcard1.iso. After that you need to mount sdcard: mount -o loop sdcard1.iso /mnt/cdrom/. Next step: copy files, umount /mnt/cdrom/ and point to image in virtua... | [
0
] | [] | [] | [
"android",
"android_emulator",
"python",
"sl4a"
] | stackoverflow_0008141746_android_android_emulator_python_sl4a.txt |
Q:
boost.python confused about similar constructor
I have a class that looks like
class Foo{
Foo();
Foo(int i);
Foo(bool b);
Foo(double d);
};
and I expose my class to python as usual
class_<Foo>("Foo")
.def(init<int>())
.def(init<bool>())
.def(init<double>());
when I try to use to in python, the py... | boost.python confused about similar constructor | I have a class that looks like
class Foo{
Foo();
Foo(int i);
Foo(bool b);
Foo(double d);
};
and I expose my class to python as usual
class_<Foo>("Foo")
.def(init<int>())
.def(init<bool>())
.def(init<double>());
when I try to use to in python, the python code always cast the c'tor parameter into double... | [
"Well, you can change the order of constructor's definitions, the last one will have higher priority. Here is my results:\nclass_<Foo>(\"Foo\")\n.def(init<bool>())\n.def(init<double>())\n.def(init<int>());\n\nFoo() # calls Foo()\nFoo(True) # calls Foo(int)\nFoo(1) # calls Foo(int)\nFoo(4.2) # calls Foo(double)\n\nA... | [
13
] | [] | [] | [
"boost",
"c++",
"python"
] | stackoverflow_0008140155_boost_c++_python.txt |
Q:
How do I launch background jobs w/ paramiko?
Here is my scenario: I am trying to automate some tasks using Paramiko. The tasks need to be started in this order (using the notation (host, task)): (A, 1), (B, 2), (C, 2), (A,3), (B,3) -- essentially starting servers and clients for some testing in the correct order. ... | How do I launch background jobs w/ paramiko? | Here is my scenario: I am trying to automate some tasks using Paramiko. The tasks need to be started in this order (using the notation (host, task)): (A, 1), (B, 2), (C, 2), (A,3), (B,3) -- essentially starting servers and clients for some testing in the correct order. Further, because in the tests networking may get m... | [
"without using nohup or screen.\ndef command(channel, cmd):\n channel.exec_command(cmd + ' > /dev/null 2>&1 &')\n\nthis says \"Redirect STDOUT from cmd into dev/null, then redirect STDERR back into STDOUT, which goes into /dev/null. Then push it into the background.\"\nexec_command wont get hung up on any output... | [
4,
0,
0
] | [] | [] | [
"nohup",
"paramiko",
"python",
"screen"
] | stackoverflow_0002202228_nohup_paramiko_python_screen.txt |
Q:
Using CSV arrays as an input to Python
I have been presented with a csv file that is full of 100+ arrays that I need to run through my data analysis code but I am not sure how to read these arrays in Python. Each array is preceded with a line that includes only an integer that gives the number of rows in the array... | Using CSV arrays as an input to Python | I have been presented with a csv file that is full of 100+ arrays that I need to run through my data analysis code but I am not sure how to read these arrays in Python. Each array is preceded with a line that includes only an integer that gives the number of rows in the array and ends with the line '1234567890' to be u... | [
"You could use itertools.groupby to parse the rows into separate arrays:\nimport csv\nimport itertools\n\nwith open('errors','w') as err: pass\nwith open('data','r') as f:\n for key, group in itertools.groupby(\n csv.reader(f),\n lambda row: row[0].startswith('1234567890')):\n if key... | [
2,
0
] | [] | [] | [
"arrays",
"ascii",
"csv",
"loops",
"python"
] | stackoverflow_0008142939_arrays_ascii_csv_loops_python.txt |
Q:
How to search strings with certain number of occurence using Regular Expression?
I am using regular expression to search for some string fit for my restrictions. For example, "HHHHLLLHHHHHLLLLL", I want to find the strings that letter H's total occurence is more than 8.
I tried to construct a regular expression us... | How to search strings with certain number of occurence using Regular Expression? | I am using regular expression to search for some string fit for my restrictions. For example, "HHHHLLLHHHHHLLLLL", I want to find the strings that letter H's total occurence is more than 8.
I tried to construct a regular expression using {8,} to search for occurence of H equal or more than 8. However, it doesn't seem t... | [
"re.search('(?:H[^H]*){8}', str1)\n\nwill find a match if there are at least 8 Hs in your string.\nBut that's not really a good fit for a regex; FailedDev's solution will be much faster and is definitely easier to understand. So unless you have another good reason to use a regex, better go with his suggestion.\n",
... | [
5,
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008143071_python_regex.txt |
Q:
How to implement OAuth2 server with CherryPy?
I am using CherryPy serving up information through a web service. I want to restrict access to some of the functions utilizing OAuth2. I see an example of an OAuth2 server at https://github.com/simplegeo/python-oauth2/blob/master/example/server.py , however, it utilize... | How to implement OAuth2 server with CherryPy? | I am using CherryPy serving up information through a web service. I want to restrict access to some of the functions utilizing OAuth2. I see an example of an OAuth2 server at https://github.com/simplegeo/python-oauth2/blob/master/example/server.py , however, it utilizes its own webserver. How can I integrate this with ... | [
"here is CherryPy example application which using it: https://bitbucket.org/Lawouach/twiseless/src\n"
] | [
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0008083747_cherrypy_python.txt |
Q:
Destroy() wxpython simple error?
i am having an interesting problem,
This program is a simple image viewer and it can contain different images in a listbox. The listbox contains the names of the images. You can load an image to an item in the listbox. You can click any item on the listbox to see its image. For so... | Destroy() wxpython simple error? | i am having an interesting problem,
This program is a simple image viewer and it can contain different images in a listbox. The listbox contains the names of the images. You can load an image to an item in the listbox. You can click any item on the listbox to see its image. For some reason Destroy() is not functioning... | [
"Here you have your code fixed to clear your current image when loading another one.\nThis is done basically using self.parent.bitmap.Destroy().\nI modified some few things without changing the structure of your code, in order for you to recognize changes. I eliminated globals calls. Look how I also eliminated the... | [
3,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008100664_python_wxpython.txt |
Q:
Using Selenium and python to save a table
I'm trying to use Selenium with Python to store the contents of a table. My script is as follows:
import sys
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://testsite.com")
valu... | Using Selenium and python to save a table | I'm trying to use Selenium with Python to store the contents of a table. My script is as follows:
import sys
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://testsite.com")
value = selenium.getTable("table_id_10")
print val... | [
"The old Selenium RC API included a get_table method:\nIn [14]: sel=selenium.selenium(\"localhost\",4444,\"*firefox\", \"http://www.google.com/webhp\")\nIn [19]: sel.get_table?\nType: instancemethod\nBase Class: <type 'instancemethod'>\nString Form: <bound method selenium.get_table of <selenium.selenium.se... | [
17
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0008143023_python_selenium.txt |
Q:
Editing related objects in ModelFormSet
I have these Models:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery")
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, related_name='images')
class Tour(models.Model):
... | Editing related objects in ModelFormSet | I have these Models:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery")
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, related_name='images')
class Tour(models.Model):
Name=models.CharField(max_length=100)
Coun... | [
"It looks like you are manually rendering the form in your template, and missing out the id field. Make sure you include {{ form.id }} for each form in the formset.\n<form method=\"post\" action=\"\">\n {{ formset.management_form }}\n {% for form in formset %}\n {{ form.id }}\n <ul>\n ... | [
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007939010_django_python.txt |
Q:
How to use a report from a view inside another view in Django?
I have a form where I upload a file, and I generate a report out of it. The thing is, I would also like to make the report available for download, as an archive. I would like to somehow include the CSS and the JS ( that I inherit from my layout ) insid... | How to use a report from a view inside another view in Django? | I have a form where I upload a file, and I generate a report out of it. The thing is, I would also like to make the report available for download, as an archive. I would like to somehow include the CSS and the JS ( that I inherit from my layout ) inside the report, but I don't really know how to go about this.
So far, ... | [
"Use the HttpResponse in the view you use to show the generated report instead of posting with urllib. If you have something along the lines of\ndef report_view(request):\n ...\n return render_to_response(request,....)\n\nThen use the response object to create an archive\ndef report_view(request):\n ...\n a... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008143228_django_python.txt |
Q:
Python/Regex/Match/Search confusion
I ran into this interesting case. I wasn't sure of the precedence of the | operator so I've originally used non-capturing groups to separate my pipes. However, this resulted in getting None for a match, removing the capturing groups also results in None. However, specifying a... | Python/Regex/Match/Search confusion | I ran into this interesting case. I wasn't sure of the precedence of the | operator so I've originally used non-capturing groups to separate my pipes. However, this resulted in getting None for a match, removing the capturing groups also results in None. However, specifying a single capturing group around them works... | [
"Your expression ^Details: WARNING|CRITICAL|ERROR is interpreted as an alternation of these three regular expressions:\n\n^Details: WARNING\nCRITICAL\nERROR\n\nSince re.match (unlike re.search) requires that the match starts at the beginning of the string, it will fail to match Details: CRITICAL and Details: ERROR.... | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008143682_python_regex.txt |
Q:
PyOpenCL vs Clyther vs pure OpenCL and C99: what's the best for novice?
I have a problem: fast linear systems solving (I have a lot of such systems). I'm going to solve it using GPU and OpenCL.
I love dynamic languages such as Ruby or Python and I got out of a habit of using low level languages like C.
So I have ... | PyOpenCL vs Clyther vs pure OpenCL and C99: what's the best for novice? | I have a problem: fast linear systems solving (I have a lot of such systems). I'm going to solve it using GPU and OpenCL.
I love dynamic languages such as Ruby or Python and I got out of a habit of using low level languages like C.
So I have two simultaneous aims:
Develop such OpenCL solution for solving linear syste... | [
"My opinion is that trying to shoehorn a dynamic language into OpenCL is not worth the effort. You will lose most of what you like about Python, and probably not save much time for your effort in the end.\nBut I am speaking only of writing OpenCL kernels in Python. There is also the host application, which prepares... | [
4,
1
] | [] | [] | [
"opencl",
"performance",
"pyopencl",
"python"
] | stackoverflow_0008142575_opencl_performance_pyopencl_python.txt |
Q:
add an object along with it's related objects in the same form in django admin
I have these models:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery")
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, related_name=... | add an object along with it's related objects in the same form in django admin | I have these models:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery")
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, related_name='images',blank=True)
class Agency(models.Model):
# some fields ...
Gallery=mo... | [
"As I said in the comment above, you're trying to do too much in the Django admin.\nLooking at your other question, you are familar with the tools you need to write your own view. Define model forms for your models. Put them in the same form tag in your template. If the form is valid, save with commit=False then fi... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008142493_django_python.txt |
Q:
import python module when using mod_python
i have been using imdbpy for some time. I was interested in making a very basic webservice to return json data.
I have a basic system working earlier today however after a reboot i now get the following error
AssertionError: Import cycle in /home/prog/www/imdb/imdb.py.
t... | import python module when using mod_python | i have been using imdbpy for some time. I was interested in making a very basic webservice to return json data.
I have a basic system working earlier today however after a reboot i now get the following error
AssertionError: Import cycle in /home/prog/www/imdb/imdb.py.
the code is being ran using mod_python. which 100... | [
"I guess this could be the problem: You named your file \"imdb.py\". Rename it and the problem could be solved.\nExplication: When importing imdb, python finds your module before finding the imdb-package that you initially wanted to import (because current folder is listed in PYTHONPATH before the the standard pyth... | [
2
] | [] | [] | [
"imdb",
"mod_python",
"python",
"web_services"
] | stackoverflow_0008143550_imdb_mod_python_python_web_services.txt |
Q:
Whoosh with Dynamic Page Creation in Google App Engine
If you aren't as familiar as you need to be with the technologies listed and would like to try to answer the question anyway, here are some useful links:
https://github.com/tallstreet/Whoosh-AppEngine
http://packages.python.org/Whoosh/quickstart.html#a-quick-i... | Whoosh with Dynamic Page Creation in Google App Engine | If you aren't as familiar as you need to be with the technologies listed and would like to try to answer the question anyway, here are some useful links:
https://github.com/tallstreet/Whoosh-AppEngine
http://packages.python.org/Whoosh/quickstart.html#a-quick-introduction
http://code.google.com/appengine/docs/whatisgoog... | [
"Use the Whoosh API to add documents to the search index as documented in your second link, whenever new content is added. You can choose whether you add the rendered template or the input data; it's more usual to do the latter when you're rolling your own custom search; otherwise you may as well just use a Google ... | [
0
] | [] | [] | [
"full_text_indexing",
"google_app_engine",
"python",
"whoosh"
] | stackoverflow_0008139557_full_text_indexing_google_app_engine_python_whoosh.txt |
Q:
Making python run a file in command line, input something, wait and then input something again
In python, I wanted to do the following:
I have a command-line program that requires user to enter input step by step & wait in between to get the result. Now, I want to automate this process using python.
The process wi... | Making python run a file in command line, input something, wait and then input something again | In python, I wanted to do the following:
I have a command-line program that requires user to enter input step by step & wait in between to get the result. Now, I want to automate this process using python.
The process will be something like:
run myProgram.exe in commandline
enter command 1
wait for command 1 to run & ... | [
"You can use subprocess module and Popen.communicate() to send data to the process stdin\nEDIT:\nYou are right, he should use stdin.write to send data, something like this:\n#!/usr/bin/env python\n\nimport subprocess\nimport time\n\nprint 'Launching new process...'\np = subprocess.Popen(['python', 'so1.py'], stdin=... | [
3,
2
] | [] | [] | [
"automation",
"command_line",
"python"
] | stackoverflow_0008144174_automation_command_line_python.txt |
Q:
Simple logging object
I have some python module, which has a class ModuleClass and I can't modify that class.
Now, I want to be able to proxify the method calls and add certain logging features. I assume this should be done via forwarding object and the corresponding proxy (following Effective Java, Item 16).
The ... | Simple logging object | I have some python module, which has a class ModuleClass and I can't modify that class.
Now, I want to be able to proxify the method calls and add certain logging features. I assume this should be done via forwarding object and the corresponding proxy (following Effective Java, Item 16).
The python pseudocode I came up... | [
"How about just subclass ModuleClass directly:\nimport logging\n\nlogger=logging.getLogger(__name__)\n\nclass LoggingModuleClass(ModuleClass):\n def method1(self):\n logger.info(\"Yay! This 'method1' really logs something!\")\n return super(LoggingModuleClass,self).method1()\n def method2(self):... | [
2,
2,
1
] | [] | [] | [
"decorator",
"logging",
"proxy_classes",
"python"
] | stackoverflow_0008143663_decorator_logging_proxy_classes_python.txt |
Q:
NotAllowedError when trying to access AppStats
After doing everything from here
http://code.google.com/appengine/docs/python/tools/appstats.html
I get
<class 'google.appengine.api.users.NotAllowedError'>:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/... | NotAllowedError when trying to access AppStats | After doing everything from here
http://code.google.com/appengine/docs/python/tools/appstats.html
I get
<class 'google.appengine.api.users.NotAllowedError'>:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/appstats/ui.py", line 324, in <module>
main(... | [
"Most likely you have created your app with authentication set to only allow users from your Google Apps domain, but you're attempting to access appstats via the appspot.com subdomain. Try again using the URL for your app on your custom domain.\n"
] | [
1
] | [] | [] | [
"appstats",
"google_app_engine",
"python"
] | stackoverflow_0008137479_appstats_google_app_engine_python.txt |
Q:
Wonder-twin power "Zoom to rectangle" activate?
Is there a way to have the "Zoom to rectangle" tool automatically activated by default when a matplotlib figure is shown?
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-300, 300)
y = x**2-7*x
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(... | Wonder-twin power "Zoom to rectangle" activate? |
Is there a way to have the "Zoom to rectangle" tool automatically activated by default when a matplotlib figure is shown?
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-300, 300)
y = x**2-7*x
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(x, y)
# Add something here to activate the "Zoom to ... | [
"This works for me:\nplt.get_current_fig_manager().toolbar.zoom()\n\n"
] | [
5
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008144492_matplotlib_python.txt |
Q:
Django: How do I use a string as the keyword in a Q() statement?
I'm writing a simple search form for a certain model. Let's call the model Orchard and give it the attributes apples, oranges, and pears, just for the sake of demonstration.
So, the form does not require all fields to be filled. So you can search on ... | Django: How do I use a string as the keyword in a Q() statement? | I'm writing a simple search form for a certain model. Let's call the model Orchard and give it the attributes apples, oranges, and pears, just for the sake of demonstration.
So, the form does not require all fields to be filled. So you can search on apples and oranges but not pears. I them need to filter like this:
Orc... | [
"this is a general issue with using a variable as the key in a keyword arg. the solution is to wrap things in a dict and unpack it:\nqueries &= Q(**{key: options[key]})\n\nor in your case\nfor option in options:\n if options[option] is None:\n del(options[option])\n# or otherwise only add the ones you act... | [
26,
3
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0008144582_django_django_queryset_python.txt |
Q:
Unicode error when passing unicode object to XML parser
I am trying to read a gzip file which contains xml and unicode, but I'm getting an error. The code I am using is:
import gzip
import xml
path = "index.mjml.gz"
gzFile = gzip.open(path, mode='r')
gzContents = gzFile.read()
gzFile.close()
unicodeContents = gz... | Unicode error when passing unicode object to XML parser | I am trying to read a gzip file which contains xml and unicode, but I'm getting an error. The code I am using is:
import gzip
import xml
path = "index.mjml.gz"
gzFile = gzip.open(path, mode='r')
gzContents = gzFile.read()
gzFile.close()
unicodeContents = gzContents.encode('utf-8')
xmlContent = xml.dom.minidom.parseSt... | [
"You can't pass a unicode string to xml.dom.minidom.parseString.\nIt has to be an appropriately encoded byte string:\n>>> import xml.dom.minidom as xmldom\n>>>\n>>> source = u\"\"\"\\\n... <?xml version=\"1.0\" encoding=\"utf-8\"?>\n... <root><text>Σὲ γνωρίζω ἀπὸ τὴν κόψη</text></root>\n... \"\"\"\n>>> doc = xmldom... | [
5
] | [] | [] | [
"python",
"unicode",
"xml_parsing"
] | stackoverflow_0008144131_python_unicode_xml_parsing.txt |
Q:
SQLite3 UPDATE error in python
I am getting an "Operator error near "?"" error when I run the following SQL statement;
key = 'field_a'
value = '01/01/2011'
#self.testac = '010101010'
self.qry.execute('''UPDATE data_base SET ?=? WHERE atnumber = ?''',(key, value, self.testac))
self.qry.commit()... | SQLite3 UPDATE error in python | I am getting an "Operator error near "?"" error when I run the following SQL statement;
key = 'field_a'
value = '01/01/2011'
#self.testac = '010101010'
self.qry.execute('''UPDATE data_base SET ?=? WHERE atnumber = ?''',(key, value, self.testac))
self.qry.commit()
key and value are dynamically gene... | [
"At a guess, the ? syntax is only for parameter binding. That is, inserting the values of bound parameters converted appropriately formatted and escaped strings. It's not a general string substitution facility – just use regular string substitution for the column names.\nFor example, you'd use: \nkey = 'field_a'\nv... | [
4,
2
] | [] | [] | [
"python",
"sql",
"sql_update",
"sqlite"
] | stackoverflow_0008130343_python_sql_sql_update_sqlite.txt |
Q:
Python SciPy Stats percentilofscore
Consider the following Python code:
In [1]: import numpy as np
In [2]: import scipy.stats as stats
In [3]: ar = np.array([0.8389, 0.5176, 0.1867, 0.1953, 0.4153, 0.6036, 0.2497, 0.5188, 0.4723, 0.3963])
In [4]: x = ar[-1]
In [5]: stats.percentileofscore(ar, x, kind='strict')
Out... | Python SciPy Stats percentilofscore | Consider the following Python code:
In [1]: import numpy as np
In [2]: import scipy.stats as stats
In [3]: ar = np.array([0.8389, 0.5176, 0.1867, 0.1953, 0.4153, 0.6036, 0.2497, 0.5188, 0.4723, 0.3963])
In [4]: x = ar[-1]
In [5]: stats.percentileofscore(ar, x, kind='strict')
Out[5]: 30.0
In [6]: stats.percentileofscore... | [
"This is a weird one, near as I can tell they are doing different calculations, Scipy will reproduce the excel result if called this way.\nIn [1]: import numpy as np\nIn [2]: In [2]: import scipy.stats as stats\nIn [3]: In [3]: ar = np.array([0.8389, 0.5176, 0.1867, 0.1953, 0.4153, 0.6036, 0.2497, 0.5188, 0.4723, 0... | [
1,
1
] | [] | [] | [
"numpy",
"percentile",
"python",
"scipy"
] | stackoverflow_0008138552_numpy_percentile_python_scipy.txt |
Q:
Setting a dynamic type's docstring in Python 3
I am dynamically creating some classes and I want them to have different docstrings. I have:
def make_class(class_docstring):
class X:
pass
X.__doc__ = class_docstring
return X
That didn't work because docstrings are read-only. Then, I tried:
de... | Setting a dynamic type's docstring in Python 3 | I am dynamically creating some classes and I want them to have different docstrings. I have:
def make_class(class_docstring):
class X:
pass
X.__doc__ = class_docstring
return X
That didn't work because docstrings are read-only. Then, I tried:
def make_class(class_name, class_docstring):
class... | [
"You can set the docstring inside the class.\n>>> def make_class(class_docstring):\n... class X:\n... __doc__ = class_docstring\n... return X\n...\n>>> x = make_class('test doc')\n>>> x\n<class '__main__.X'>\n>>> xx = x()\n>>> xx.__doc__\n'test doc'\n\nI'm not sure why your 2nd attempt is failing.\n... | [
5
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008145465_python_python_3.x.txt |
Q:
fast binary data conversion in Python
What is the fastest method for converting a binary data string to a numeric value in Python?
I am using struct.unpack_from(), but am hitting a performance limit.
Context: an incoming stream is mixed binary and ASCII data. The ASCII data conversion is done in C though ctypes... | fast binary data conversion in Python | What is the fastest method for converting a binary data string to a numeric value in Python?
I am using struct.unpack_from(), but am hitting a performance limit.
Context: an incoming stream is mixed binary and ASCII data. The ASCII data conversion is done in C though ctypes. Implementing the unpacking in C through ... | [
"Based on my experience, you are correct that the code will need to be moved to C. As you discovered the performance for the various tools for binary conversion (struct and ctypes for example) have roughly similar performance.\nCython is the easiest way to get generate a C extension for Python.\nAnother easy appr... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0008145167_python.txt |
Q:
I'm trying to create a button in Python (importing Tkinter) that changes color after every click
I am trying to create a button in Python (using Tkinter), that changes color every time I click it. I have this so far:
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__... | I'm trying to create a button in Python (importing Tkinter) that changes color after every click | I am trying to create a button in Python (using Tkinter), that changes color every time I click it. I have this so far:
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
#initialize frame
self.create_widgets()
... | [
"Python has iterators. They are similar to lists, but the items in the iterator are generated as they are needed, rather than enumerated in their entirety at definition-time. Here is an example of an infinite iterator, made by wrapping a tuple with itertools.cycle:\nIn [119]: import itertools\n\nIn [120]: color=ite... | [
4,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008144468_python_tkinter.txt |
Q:
MySQLdb Unknown MySQL server host
I have python 2.7 installed.
I have wamp running.
I have MySQL running on 10127 port.
I have root set up with no password
i have (unrelated) php code running that connects fine with the call
mysql_connect('localhost:10127', 'root', '');
when i try from the command line:
mysql ... | MySQLdb Unknown MySQL server host | I have python 2.7 installed.
I have wamp running.
I have MySQL running on 10127 port.
I have root set up with no password
i have (unrelated) php code running that connects fine with the call
mysql_connect('localhost:10127', 'root', '');
when i try from the command line:
mysql -u 'root' -p '' -h 'localhost:10127'
i... | [
"The CLI expects:\nmysql -u root -h localhost --port 10127\n\n",
"mysql -u 'root' -p '' -h localhost -p 10127\nhttps://dev.mysql.com/doc/refman/5.5/en/mysql-command-options.html\n"
] | [
2,
0
] | [] | [] | [
"mysql",
"mysql_python",
"python",
"wamp"
] | stackoverflow_0008145843_mysql_mysql_python_python_wamp.txt |
Q:
Image Recognition using Python
I have an idea, that is, I want to identify the letters in an image which may be .bmp or .jpg.
For example, here is an .bmp image with a letter 'S' in it. What I want to do is to identify the letter using Python.
It's kinda similar with those Questions about auth code recognition, a... | Image Recognition using Python | I have an idea, that is, I want to identify the letters in an image which may be .bmp or .jpg.
For example, here is an .bmp image with a letter 'S' in it. What I want to do is to identify the letter using Python.
It's kinda similar with those Questions about auth code recognition, and I read some of those Q's, but sti... | [
"You're probably looking for the OpenCV toolkit; it is commonly used for tasks where software must \"recognize\" some contents or features from images.\n",
"Also there is whole blown system Ocropus which has Python bindings or perhaps better Python bindings to tesseract\n"
] | [
5,
5
] | [] | [] | [
"image_recognition",
"python"
] | stackoverflow_0008145636_image_recognition_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.