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:
LaTeX type rendering with pygame
I am trying to read text with LaTeX formatting and render it using pygame. I am a novice to pygame and any help will be appreciated.
I looked into Glyph package. The problem is that I would have to rewrite all my .txt files in Glyph formatting for them to be useful. If I try and de... | LaTeX type rendering with pygame | I am trying to read text with LaTeX formatting and render it using pygame. I am a novice to pygame and any help will be appreciated.
I looked into Glyph package. The problem is that I would have to rewrite all my .txt files in Glyph formatting for them to be useful. If I try and define macros I would essentially have t... | [
"You could render LaTeX via matplotlib and use these figures in PyGame as sprites.\nhttp://matplotlib.sourceforge.net/users/usetex.html\n",
"Check out pylasem (yes, it says MathML rendering library, but it also supports a subset of Latex) or lasem itself via gobject-introspection.\n"
] | [
1,
1
] | [] | [] | [
"latex",
"pygame",
"python"
] | stackoverflow_0007401692_latex_pygame_python.txt |
Q:
os.walk certain file types into an existing ZipFile?
Basically I need to copy all files of a certain type within a folder into a ZipFile at the highest level (so not within a folder).
For example I have a folder, 'A Folder' and within that folder are a load of .png files. I want to copy all those files into an exi... | os.walk certain file types into an existing ZipFile? | Basically I need to copy all files of a certain type within a folder into a ZipFile at the highest level (so not within a folder).
For example I have a folder, 'A Folder' and within that folder are a load of .png files. I want to copy all those files into an existing ZipFile. Currently I can only get the Folder to copy... | [
"According to the python docs, the zipfile.write() method supports a second argument that is the destination name (ie the name in archive), try tto use it like this : \nfor root, dirs, files in os.walk('A Folder'):\n for f in files:\n fname = os.path.join(root, f)\n new_path = os.path.normpath(fnam... | [
2
] | [] | [] | [
"copy",
"file",
"python",
"zip"
] | stackoverflow_0007402200_copy_file_python_zip.txt |
Q:
Good way (and/or platform-independent place) to cache data from web
My pygtk program is an editor for XML-based documents which reference other documents, possibly online, that may in turn reference further documents.
When I load a file, the references are resolved and the documents loaded (already asynchronously)... | Good way (and/or platform-independent place) to cache data from web | My pygtk program is an editor for XML-based documents which reference other documents, possibly online, that may in turn reference further documents.
When I load a file, the references are resolved and the documents loaded (already asynchronously). However, this process repeats every time I start the editor, so I want ... | [
"Personnaly I use os.path.expanduser to find a good place for caches, it's quite common in unix environnement where most of the current user's config/cache is saved under his home directory, the use of a directory name starting with a dot, making an \"hidden\" directory. \nI would do something like :\ndirectory = o... | [
3
] | [] | [] | [
"caching",
"python",
"webpage"
] | stackoverflow_0007401256_caching_python_webpage.txt |
Q:
Run a task every hour on the hour with App Engine's cron API
I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.
There is an example of running at ask every hour, but this doesn't fit because ... | Run a task every hour on the hour with App Engine's cron API | I need to run a task every hour on the hour (00:00, 01:00, 02:00, ..., 23:00) every day of the week, but can't seem to find an example in App Engine's docs of how to do this.
There is an example of running at ask every hour, but this doesn't fit because the "start" of that hour depends on when you deploy the applicatio... | [
"You could do this, and give up the exactly on the hour, but it will be close...\n(Example came from a app I was debuging)\ncron:\n- description: Description of what you want done...\n url: /script/path/goes/here\n schedule: every 60 minutes synchronized\n timezone: America/New_York\n\nBelow is a screenshot of t... | [
5,
4,
1
] | [
"Looking over the docs, I agree that your 24 cron entry idea is the only documented way that would work. Not ideal, but should work.\n"
] | [
-1
] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0001501907_cron_google_app_engine_python.txt |
Q:
Read a text file between user given starting and ending position in python
I have a huge text file from which i want to selectively read a few lines.
Using tell() i know the positions i want to read between.
Is there a way i can read all the text in the file between the two positions?
like file.read(beginPos, endP... | Read a text file between user given starting and ending position in python | I have a huge text file from which i want to selectively read a few lines.
Using tell() i know the positions i want to read between.
Is there a way i can read all the text in the file between the two positions?
like file.read(beginPos, endPos)
or maybe, read all text between line number containing beginPos and line num... | [
"If you now the start point (with tell()) and the end point, you could simply do a file.read(end-start), it will read the end-start bytes. If you're not at the correct offset on begining, use the seek() method (file.seek(start)) first.\n",
"You will want to open the file then fileobj.seek(beginPos) and then fileo... | [
6,
0,
0
] | [] | [] | [
"file_io",
"python",
"text"
] | stackoverflow_0007402597_file_io_python_text.txt |
Q:
How can I have Google App Engine clear memcache every time a site is deployed?
The title asks it all. The content on the site I'm building wont change very quickly at all and so Memcache could potentially store data for months except for when I put up an update. Is there a way to make it clear the cache every time... | How can I have Google App Engine clear memcache every time a site is deployed? | The title asks it all. The content on the site I'm building wont change very quickly at all and so Memcache could potentially store data for months except for when I put up an update. Is there a way to make it clear the cache every time I deploy the site? I'm using the Python runtime.
Update 1
Using jldupont's answer I... | [
"Have you tried flush_all() function? Docs here. You'll need a bit of logic & state to detect a new deployment or have a special script to perform the flushing.\nUpdated: look at the absolute path of one of your script: this changes on every deployment. You can use http://shell.appspot.com/ to experiment:\n impor... | [
21,
3,
2,
0
] | [] | [] | [
"caching",
"deployment",
"google_app_engine",
"memcached",
"python"
] | stackoverflow_0001983556_caching_deployment_google_app_engine_memcached_python.txt |
Q:
Integration with "quad" and "quadrature" from Python/SciPy
After reading this and that, it occurs to me that both "quad" and "quadrature" should be interchangeable*, atleast syntax-wise. Strangely it does seem they are not:
from scipy.integrate import quad as q
#from scipy.integrate import quadrature as q
def myf... | Integration with "quad" and "quadrature" from Python/SciPy | After reading this and that, it occurs to me that both "quad" and "quadrature" should be interchangeable*, atleast syntax-wise. Strangely it does seem they are not:
from scipy.integrate import quad as q
#from scipy.integrate import quadrature as q
def myfunc(x):
return x
def integr():
return q(myfunc, 0, 1)[0... | [
"The problem is in the line return q(myfunc2, 0, 1, args=(y))[0], specifically in the args=(y) part. What you want is args=(y,) (notice the comma after y) or args=[y].\nThe issue is that in Python tuples are created with commas, not with parentheses. Look:\n>>> a = (1,)\n>>> b = (1)\n>>> print a, type(a)\n(1,) <t... | [
5
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0007402541_python_syntax.txt |
Q:
Get int-type from 'int' string
In Python, given the string'int', how can I get the type int? Using getattr(current_module, 'int') doesn't work.
A:
int isn't part of the namespace of your current module; it's part of the __builtins__ namespace. So you would run getattr on __builtins__.
To verify that it's a type ... | Get int-type from 'int' string | In Python, given the string'int', how can I get the type int? Using getattr(current_module, 'int') doesn't work.
| [
"int isn't part of the namespace of your current module; it's part of the __builtins__ namespace. So you would run getattr on __builtins__.\nTo verify that it's a type you can just check whether it's an instance of type, since all types are derived from it.\n>>> getattr(__builtins__, 'int')\n<type 'int'>\n>>> foo =... | [
6,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007403156_python.txt |
Q:
How to add a custom implicit conversion to a C++ type in Boost::Python?
In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:
class Foo {
public:
void do_this(Bar b);
void do_that(Bar b);
/* ... */
};
Bar has a number of constructors that create a new object from man... | How to add a custom implicit conversion to a C++ type in Boost::Python? | In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:
class Foo {
public:
void do_this(Bar b);
void do_that(Bar b);
/* ... */
};
Bar has a number of constructors that create a new object from many common types such as int, std::string, float, etc:
class Bar {
public:
Ba... | [
"Subclass Bar near the wrapper code and give your subclass a ctor that takes a bp::object (or a more specific python type)\nstruct Bar_wrapper:Bar,bp::wrapper<Bar>\n{\n Bar_wrapper(bp::object arg)\n {\n //code to build a Bar_wrapper Here\n }\n}\n\nThen export a Bar_wrapper to python instead of a Bar... | [
2,
1,
0,
0,
0
] | [
"You can export function do_that which take boost::python::object param, check if param is a python tuple, extract data and pass it to object.\n"
] | [
-1
] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0001254013_boost_python_c++_python.txt |
Q:
using python 2.5 to subtract two lists
i have made a function which uses subtraction of two values stored in two lists as follows:
import sys,os
import math
c1 = [10]
c2 = [5]
d1 = [8]
d2 = [4]
x = d2 - c2
y = d1 - c1
z = x*x
w = y*y
answer = sqrt(z +... | using python 2.5 to subtract two lists | i have made a function which uses subtraction of two values stored in two lists as follows:
import sys,os
import math
c1 = [10]
c2 = [5]
d1 = [8]
d2 = [4]
x = d2 - c2
y = d1 - c1
z = x*x
w = y*y
answer = sqrt(z + w)
print answer
My error is: TypeEr... | [
"Is this what you are trying to do?\nimport math\n\nc = [10,5]\nd = [8,4]\nx = d[1] - c[1]\ny = d[0] - c[0]\nz = x*x \nw = y*y \n\nprint math.sqrt(z+w)\n\n",
"You can't subtract a whole list at once like that, even if there is only one item in the list. You have to do them one at a time. You could do it in a loop... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007403161_python.txt |
Q:
Save python plistlib data
how do I save the output I get for this program(as a variable), instead of it being printed?
import plistlib, time
import plistlib as pl
p=pl.readPlist("Restore.plist")
print p["ProductType"]#I want this to be outputted as a variable, such as 'x' instead of python printing it.
print p[... | Save python plistlib data | how do I save the output I get for this program(as a variable), instead of it being printed?
import plistlib, time
import plistlib as pl
p=pl.readPlist("Restore.plist")
print p["ProductType"]#I want this to be outputted as a variable, such as 'x' instead of python printing it.
print p["ProductVersion"]
print p["Prod... | [
"something like this?\noutputfile = open('output.plist', 'w')\noutputfile.write(p[\"ProductVersion\"])\noutputfile.close()\n\n",
"It's already a variable. Namely, it's part of the variable p. If you want to assign it to another variable use the = sign like on line 3 of your code.\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007403200_python.txt |
Q:
how to do linear interpolation on a 2D numpy array having sparse data?
I have a 2D numpy array... there are some values in the image and rest is sparse. For linear imterpolation, I want to take the first column of the array. See where the values are present and do the linear interpolation on the zero values but on... | how to do linear interpolation on a 2D numpy array having sparse data? | I have a 2D numpy array... there are some values in the image and rest is sparse. For linear imterpolation, I want to take the first column of the array. See where the values are present and do the linear interpolation on the zero values but only on one interval.
We loop over every column of the 2D array
As an example,... | [
"Try something like this:\nimport numpy as np\n\na = np.array([0,0,0,0,1,0,0,0,2,0,0,10,0,0,3,4,6,0,0,1,0,0])\nx, = np.nonzero(a)\na_filled = np.interp(np.arange(a.size), x, a[x])\n\nThis yields:\narray([1, 1, 1, 1, 1, 1.25, 1.5, 1.75, 2, 4.67, 7.33, 10, 7.67, 5.33, 3, 4, 6, 4.33, 2.67, 1, 1, 1])\n\n"
] | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007402837_numpy_python.txt |
Q:
Building console executable using py2exe, receiving suds import error
Attempting to build .exe using py2exe: python setup.py py2exe , receiving error:
ImportError: No module named suds
I have done some research which suggests that the module(s) have to be specifically included in setup.py. Here is my setup.py:
fr... | Building console executable using py2exe, receiving suds import error | Attempting to build .exe using py2exe: python setup.py py2exe , receiving error:
ImportError: No module named suds
I have done some research which suggests that the module(s) have to be specifically included in setup.py. Here is my setup.py:
from distutils.core import setup
import py2exe
setup(console = [{'script':'r... | [
"Problem is not with py2exe, I've narrowed it down to the imp.find_module call at line 498 in py2exe/mf.py. The suds module imports OK, and I can see it in sys.path, but \nimport imp\nimp.find_module('suds', sys.path)\n\nreports no module found.\nOpening a followup question that is specific to imp module.\n",
"Ge... | [
2,
0
] | [] | [] | [
"py2exe",
"python",
"setup.py",
"suds",
"windows"
] | stackoverflow_0007393868_py2exe_python_setup.py_suds_windows.txt |
Q:
Is the database already created?
I'm currently writing an initialization script for my sqlalchemy database.
And one thing I want to know is if the database has already been created once.
If the database is a sqlite one it's easy, I just have to check if the sqlite file exists, but what about for a postgresql/mysql... | Is the database already created? | I'm currently writing an initialization script for my sqlalchemy database.
And one thing I want to know is if the database has already been created once.
If the database is a sqlite one it's easy, I just have to check if the sqlite file exists, but what about for a postgresql/mysql database ?
So is there a generic way ... | [
"From the docs for sqlalchemy.schema.Metadata.create_all\ncreate_all(bind=None, tables=None, checkfirst=True)\n\nCreate all tables stored in this metadata.\n\nConditional by default, will not attempt to recreate tables already present in the \ntarget database.\n\n",
"This may help you :\nCREATE DATABASE [IF NOT E... | [
2,
0
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0007399362_orm_python_sqlalchemy.txt |
Q:
How can I detect whether my python class instance is cast as an integer or float?
I have a python class to calculate the number of bits when they have been specified using "Kb", "Mb" or "Gb" notation. I assigned a @property to the bits() method so it will always return a float (thus working well with int(BW('foo'... | How can I detect whether my python class instance is cast as an integer or float? | I have a python class to calculate the number of bits when they have been specified using "Kb", "Mb" or "Gb" notation. I assigned a @property to the bits() method so it will always return a float (thus working well with int(BW('foo').bits)).
However, I am having trouble figuring out what to do when a pure class instan... | [
"Read this\nhttp://docs.python.org/reference/datamodel.html#emulating-numeric-types\n__int__()\n__float__()\n",
"Basically what you want lies within overriding __trunc__ and __float__ in the Models.Network.Bandwidth.BW class:\n#!/usr/bin/python\n\nclass NumBucket:\n\n def __init__(self, value):\n self.v... | [
3,
2
] | [] | [] | [
"casting",
"class",
"python",
"types"
] | stackoverflow_0007403510_casting_class_python_types.txt |
Q:
Force Django to use a period for specific decimals
I've got an issue with the Django template localisation. In the German locale, it forces decimals to use a comma as the separator, which is fine for display. However I also need to modify some JS tracking to send a price to the reporting engine.
Django is also loc... | Force Django to use a period for specific decimals | I've got an issue with the Django template localisation. In the German locale, it forces decimals to use a comma as the separator, which is fine for display. However I also need to modify some JS tracking to send a price to the reporting engine.
Django is also localising that value (It's inline with the HTML, bad I kno... | [
"The best way that does is casting the number to a string before I send it to the template, which works perfectly every time.\n\nI'd like to know if there's a better way to do it.\n\nNope.\n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0007403836_django_django_templates_python.txt |
Q:
Monster heads problem in Python
Two guns A and B need to be used to kill a monster(with N heads). When gun A is used it cuts 6 heads, but if the monster doesn't die(no of heads > 0), it will grow 3 heads. When gun B is used it cuts 4 heads but if the monster doesn't die it grows 2 heads. If N< (no. of heads the gu... | Monster heads problem in Python | Two guns A and B need to be used to kill a monster(with N heads). When gun A is used it cuts 6 heads, but if the monster doesn't die(no of heads > 0), it will grow 3 heads. When gun B is used it cuts 4 heads but if the monster doesn't die it grows 2 heads. If N< (no. of heads the gun can cut), in that case the gun cann... | [
"You are searching for a path that is not smallest. You need to save and check the length of the path like that:\ndef A(heads, path, path_len):\n if heads < -1:\n path = []\n return float('inf') #Impossible to kill\n heads -= 6\n if heads < 0:\n return float('inf')\n path_len = path... | [
1,
0
] | [] | [] | [
"operations_research",
"python",
"shortest_path"
] | stackoverflow_0007403829_operations_research_python_shortest_path.txt |
Q:
How to use the "native" GUI look with Tkinter?
By default Tkinter still uses the old Windows 2000-style widgets (random example):
but I want it to use the Windows XP/Vista/7-style widgets instead:
How can I do this? I would prefer to use the latest style version, so Windows 7 > Vista > XP > 2000.
A:
On Windows... | How to use the "native" GUI look with Tkinter? | By default Tkinter still uses the old Windows 2000-style widgets (random example):
but I want it to use the Windows XP/Vista/7-style widgets instead:
How can I do this? I would prefer to use the latest style version, so Windows 7 > Vista > XP > 2000.
| [
"On Windows, use tkinter.ttk to get the the themed version of Tk.\n",
"The ttk themed widgets are what you are looking for. Be sure to use the 'vista' theme to get native appearance on Vista/Win7. \n"
] | [
21,
3
] | [] | [] | [
"python",
"tkinter",
"windows"
] | stackoverflow_0007385343_python_tkinter_windows.txt |
Q:
Python loop doubt
I have a function called gett(int) that returns a series upon every call. It works fine when I write like this :
print gett(0)
print gett(1)
and so on..
but when I try to automate same in a for loop like this :
for a in range(28):
print gett(a)
It works fine for only first value and I get fo... | Python loop doubt | I have a function called gett(int) that returns a series upon every call. It works fine when I write like this :
print gett(0)
print gett(1)
and so on..
but when I try to automate same in a for loop like this :
for a in range(28):
print gett(a)
It works fine for only first value and I get following output:
[..seri... | [
"In the first iteration, you're reading the file completely.\nIn all subsequent iterations, the entire for x in trend: loop will therefore be skipped.\nHow about something like this:\nimport csv\n\ndef read_csv():\n with open(\"D:\\\\trend.csv\", \"rb\") as f:\n trend = csv.reader(f, delimiter=\",\")\n ... | [
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0007404017_python.txt |
Q:
help need to write regex
Possible Duplicate:
help need to write regex
I have a logfile formatted as follows:
Using data from (yyyy/mm/dd): 2011/8/3
0 files queued for scanning.
Warning: E:\test\foo
Händler.pdf File not Found.
Loading com, please wait.
1520 file scanned.... | help need to write regex |
Possible Duplicate:
help need to write regex
I have a logfile formatted as follows:
Using data from (yyyy/mm/dd): 2011/8/3
0 files queued for scanning.
Warning: E:\test\foo
Händler.pdf File not Found.
Loading com, please wait.
1520 file scanned.
I want to write a regex to ... | [
"With out a broad view of your log file, this may help you:\nIn [1]: import re\n\nIn [2]: txt = open('foo.log', 'r').read()\n\nIn [3]: regexp = re.compile(r'''Using data.+\\): (?P<Defs_Date>\\d{4}/\\d+/\\d+).+(?P<Warning>Warning: .+)Loading.+scanned.''', re.S)\n\nIn [4]: regexp.search(txt).groupdict()\nOut[4]: \n{'... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007404497_python_regex.txt |
Q:
Using python script to close eclipse and update from svn
I am new to python and the first project that I have has the following steps which should be executed through a python script run from command-line on a Mac:
(1) Close Eclipse.
(2) Update the code from svn
(3) Run a Ant deploy script
As I said I am very new ... | Using python script to close eclipse and update from svn | I am new to python and the first project that I have has the following steps which should be executed through a python script run from command-line on a Mac:
(1) Close Eclipse.
(2) Update the code from svn
(3) Run a Ant deploy script
As I said I am very new to python and plan to learn as I go along coding the script. A... | [
"Python's kinda the 'hard way' to do this. Eclipse has CLI scripting capabilities that you might be able to make use of. For example update_standalone reference. Granted you have to play a bit in jar-land to do this, consider that literally nobody developing for Eclipse is going to lift a finger to make things easi... | [
0
] | [] | [] | [
"automation",
"eclipse",
"python",
"svn"
] | stackoverflow_0007391632_automation_eclipse_python_svn.txt |
Q:
Undefined constants in eclipse
I'm using eclipse/aptana for python development.
I have no issue with my python path config, autocomplete works fine with everything, however I am having the following problem:
When I have a "constant" in one of my classes and I try to access it, eclipse complains about "undefined va... | Undefined constants in eclipse | I'm using eclipse/aptana for python development.
I have no issue with my python path config, autocomplete works fine with everything, however I am having the following problem:
When I have a "constant" in one of my classes and I try to access it, eclipse complains about "undefined variable from import" on the constant,... | [
"if, (see @Aix) you meant from mymodel import Universe: \nUse ctrl+1 after Universe.ULTIMATE_ANSWER; You will be asked to add a comment to ignore that error.\nYou can also add your model as a forced builtin, prompting analyzis as in runtime (which you said, gave no error)\n",
"You don't import a class, you import... | [
1,
0
] | [] | [] | [
"aptana",
"eclipse",
"pydev",
"python"
] | stackoverflow_0007400108_aptana_eclipse_pydev_python.txt |
Q:
Script or command to get a user's memory consumption
My host is offering me a limited amount of RAM for my websites and I would like to monitor the memory consumption by running a script in the cron.
I have made up this command:
ps -u xxxxxx -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}'
... | Script or command to get a user's memory consumption | My host is offering me a limited amount of RAM for my websites and I would like to monitor the memory consumption by running a script in the cron.
I have made up this command:
ps -u xxxxxx -o rss,command | grep -v peruser | awk '{sum+=$1} END {print sum/1024}'
But the way my host is calculating memory has a particular... | [
"Use etime to find the elapsed time of a process. You can then modify your awk command to check if this time is greater than 5 mins.\nps -u xxxxxx -o rss,etime,command | ...\n\nThe format of elapsed time is [[dd-]hh:]mm:ss. This means the time could be 00:30, 12:57:39 or even 4-08:27:12. You can use awk to parse th... | [
1
] | [] | [] | [
"memory",
"python",
"unix"
] | stackoverflow_0007404269_memory_python_unix.txt |
Q:
ImportError: No module named suds
Having trouble with py2exe importing the suds module, and narrowed it down to the following:
>>> imp.find_module('suds', sys.path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named suds
However, a simple import works fine:
>>> i... | ImportError: No module named suds | Having trouble with py2exe importing the suds module, and narrowed it down to the following:
>>> imp.find_module('suds', sys.path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named suds
However, a simple import works fine:
>>> import suds
>>> suds.__version__
'0.4'
... | [
"Extracted the suds egg at:\n\nC:\\Python27\\lib\\site-packages\\suds-0.4-py2.7.egg\n\nand created C:\\Python27\\lib\\site-packages\\suds directory that contains source files. Module is now found:\n>>> imp.find_module('suds')\n(None, 'C:\\\\Python27\\\\lib\\\\site-packages\\\\suds', ('', '', 5))\n\npy2exe build com... | [
8
] | [] | [] | [
"import",
"importerror",
"path",
"python",
"suds"
] | stackoverflow_0007403738_import_importerror_path_python_suds.txt |
Q:
ValueError: need more than 1 value to unpack
I want to change the contents in a list of tuples, returned by a findall() function. And I am not sure whether I could change the elements from string to integer like this. And the error always shows that I need more than 1 value.
Ntuple=[]
match = re.findall(r'Answer... | ValueError: need more than 1 value to unpack | I want to change the contents in a list of tuples, returned by a findall() function. And I am not sure whether I could change the elements from string to integer like this. And the error always shows that I need more than 1 value.
Ntuple=[]
match = re.findall(r'AnswerCount="(\d+)"\s*CommentCount="(\d+)"', x)
print m... | [
"The problem is in the line for posts, comments in tuples:. Here tuples is actually a single tuple containing two strings, so there is no need to iterate over it. You probably want something like:\nmatches = re.findall(...)\nfor posts, comments in matches:\n ....\n\n",
"match is a list of tuples. The correct w... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007404773_python.txt |
Q:
Fastest way to cast values to their respective datatypes in Python
I have a list of values - all strings. I want to convert these values to their respective datatypes. I have mapping of values to the types information available.
There are three different datatypes: int, str, datetime.
The code needs to be able to ... | Fastest way to cast values to their respective datatypes in Python | I have a list of values - all strings. I want to convert these values to their respective datatypes. I have mapping of values to the types information available.
There are three different datatypes: int, str, datetime.
The code needs to be able to handle the error cases with the data.
I am doing something like:-
tlist ... | [
"Something like:\n>>> values = [\"12\", \"a\", \"bcd\", \"2.2\"]\n>>> types = [int, int, str, float]\n>>> defaults = {int: 0, float: 0.0}\n>>> res = []\n>>> for v, f in itertools.izip(values, types): #Just use zip for Python 3+.\n try:\n res.append(f(v))\n except ValueError:\n res.append(default... | [
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"casting",
"performance",
"python"
] | stackoverflow_0007364076_casting_performance_python.txt |
Q:
IP address of client in Python SimpleXMLRPCServer?
I have a SimpleXMLRPCServer server (Python).
How can I get the IP address of the client in the request handler?
This information appears in the log. However, I am not sure how to access this information from within the request handler.
A:
As Michael noted, you ... | IP address of client in Python SimpleXMLRPCServer? | I have a SimpleXMLRPCServer server (Python).
How can I get the IP address of the client in the request handler?
This information appears in the log. However, I am not sure how to access this information from within the request handler.
| [
"As Michael noted, you can get client_address from within the request handler. For instance, you can override the __init__ function which is inherited indirectly from BaseRequestHandler.\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n def __init__(self, request, client_address, server):\n print clien... | [
4,
3,
2
] | [] | [] | [
"ip_address",
"python",
"simplexmlrpcserver",
"xml_rpc"
] | stackoverflow_0002129374_ip_address_python_simplexmlrpcserver_xml_rpc.txt |
Q:
python Global Interpreter Lock GIL problem
I want to provide a service on the web that people can test out the performance of an algo, which is written in python and running on the linux machine
basically what I want to do is that, there is a very trivial PHP handler, let's say start_algo.php, which accepts the re... | python Global Interpreter Lock GIL problem | I want to provide a service on the web that people can test out the performance of an algo, which is written in python and running on the linux machine
basically what I want to do is that, there is a very trivial PHP handler, let's say start_algo.php, which accepts the request coming from browser, and in the php code t... | [
"If you are opening each script by invoking a new process; you will not run afoul of the GIL. Each process gets its own interpreter and therefore its own interpreter lock.\n",
"The GIL is per-process. If you start multiple python processes, each will have its own GIL that prevents the interpreter(s) in this spec... | [
10,
7
] | [] | [] | [
"gil",
"python"
] | stackoverflow_0007404904_gil_python.txt |
Q:
help need to write regex in optional condition [Close]
I have a logfile having contains as below
log=
Using data from (yyyy/mm/dd): 2011/8/3
0 files queued for scanning.
Warning: E:\test\Händler.pdf File not Found.
Loading com, please wait.
1520 file scanned.
I want to write a... | help need to write regex in optional condition [Close] | I have a logfile having contains as below
log=
Using data from (yyyy/mm/dd): 2011/8/3
0 files queued for scanning.
Warning: E:\test\Händler.pdf File not Found.
Loading com, please wait.
1520 file scanned.
I want to write a regex to detect the Warning message because this is optiona... | [
"One way to handle optional parts is to use regex text (optional part|). The part inside parenthesis will match either \"optional part\" (which can be a regex on its own) or nothing.\n",
"The following works fine for me:\ntxt = open(\"test.txt\").read()\nprint txt\n\nimport re\nlogdate = re.compile(\"Using.*: (?P... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007401688_python_regex.txt |
Q:
django forms - reusing form request functions
I have a base.html which most of my pages inherit. Inside it defines a header which contains a search box. The code for the search box is some thing along the lines of....
if request.method == 'POST':
if 'search_button' in request.POST:
location = request... | django forms - reusing form request functions | I have a base.html which most of my pages inherit. Inside it defines a header which contains a search box. The code for the search box is some thing along the lines of....
if request.method == 'POST':
if 'search_button' in request.POST:
location = request.POST['location']
# Do something with loc... | [
"You should POST your search form to it's own search view, and display the results on that page.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007405333_django_python.txt |
Q:
django flatpages works with DEBUG=True, doesn't work with DEBUG=False
I can see that django looks for 500.html when DEBUG is False. What could be the problem?
A:
When debug is set to False django renders the 500.html template instead of the debug stack-trace thing.
It might be that on a http 404 (not found) exc... | django flatpages works with DEBUG=True, doesn't work with DEBUG=False | I can see that django looks for 500.html when DEBUG is False. What could be the problem?
| [
"When debug is set to False django renders the 500.html template instead of the debug stack-trace thing.\nIt might be that on a http 404 (not found) exception it tries to render the 404.html template and if it's not found than tries with the 500.html (internal error).\nIt is not a problem in itself but just a confi... | [
1
] | [] | [] | [
"django",
"django_flatpages",
"python"
] | stackoverflow_0007400156_django_django_flatpages_python.txt |
Q:
use type() information to cast values stored as strings
In my application I have generated a number of values (three columns, of type int, str and datetime, see example below) and these values are stored in a flat file as comma-separated strings. Furthermore, I store a file containing the type of the values (see b... | use type() information to cast values stored as strings | In my application I have generated a number of values (three columns, of type int, str and datetime, see example below) and these values are stored in a flat file as comma-separated strings. Furthermore, I store a file containing the type of the values (see below). Now, how can I use this information to cast my values ... | [
"As I understand, you already parsed the file, you now just need to get the right type. So let's say id_, type_ and value are three strings that contain the values in the file. (Note, type_ should contain 'int' — for example —, not '<type 'int'>'.\ndef convert(value, type_):\n import importlib\n try:\n ... | [
4,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"built_in_types",
"casting",
"data_conversion",
"python"
] | stackoverflow_0007402573_built_in_types_casting_data_conversion_python.txt |
Q:
Problem decoding json strings using json module
After contacting a server I get the following strings as response
{"kind": "t2", "data": {"has_mail": null, "name": "shadyabhi", "created": 1273919273.0, "created_utc": 1273919273.0, "link_karma": 1343, "comment_karma": 301, "is_gold": false, "is_mod": false, "id": "... | Problem decoding json strings using json module | After contacting a server I get the following strings as response
{"kind": "t2", "data": {"has_mail": null, "name": "shadyabhi", "created": 1273919273.0, "created_utc": 1273919273.0, "link_karma": 1343, "comment_karma": 301, "is_gold": false, "is_mod": false, "id": "425zf", "has_mod_mail": null}}
which is stored as ty... | [
"You need to load it before you can dump it. Try this:\ndata = json.loads(returnFromWebService)\n\njson.dumps(data, sort_keys=True, indent=4)\n\nTo add a bit more detail - you're receiving a string, and then asking the json library to dump it to a string. That doesn't make a great deal of sense. What you need to... | [
2,
1,
1,
1
] | [] | [] | [
"json",
"python",
"reddit"
] | stackoverflow_0007405673_json_python_reddit.txt |
Q:
How do I insert table from numpy into Mysql
I cant get the insert to work in this code.
I have other numpy to mysql that work fine. But there are no errors in running code. Mysql gives no errors. Using python 2.7 and pyodbc on winx64.
p = np.arange(1, 33, 3)
print p
def prow (f1,series):
rowp=[]
series =... | How do I insert table from numpy into Mysql | I cant get the insert to work in this code.
I have other numpy to mysql that work fine. But there are no errors in running code. Mysql gives no errors. Using python 2.7 and pyodbc on winx64.
p = np.arange(1, 33, 3)
print p
def prow (f1,series):
rowp=[]
series = series.tolist()
ss = series[8:]
rowp.app... | [
"Your commit is missing parens:\ncxn.commit\n\n# Should be:\ncxn.commit()\n\nRun from the interpreter, cxn.commit without parens simply returns a reference to the commit() method:\n# Something like\n>>> conn.commit\n<built-in method commit of Connection object at 0x9cfe13c>\n\n"
] | [
2
] | [] | [] | [
"mysql",
"numpy",
"python"
] | stackoverflow_0007406554_mysql_numpy_python.txt |
Q:
Python, best way to return/handle complex data from a method
I need to handle a bunch of similar but exclusively called function from a single method. e.g. (maybe not a great example)
class Util(object):
def method1(self):
return "method1", [1,2,3]
def method2(self):
return "method2", {"1"... | Python, best way to return/handle complex data from a method | I need to handle a bunch of similar but exclusively called function from a single method. e.g. (maybe not a great example)
class Util(object):
def method1(self):
return "method1", [1,2,3]
def method2(self):
return "method2", {"1":4, "2":5, "3":6}
def method3(self):
return [1,2,3], ... | [
"namedtuple is very Pythonic alternative for returning \"nameless\" tuples\nhttp://docs.python.org/library/collections.html#collections.namedtuple\nThis way the caller does not need to extract all tuple members if it needs read only some of them. \n",
"If you can modify the methods:\nclass Util(object):\n def ... | [
3,
1,
1
] | [] | [] | [
"class",
"data_structures",
"python"
] | stackoverflow_0007406349_class_data_structures_python.txt |
Q:
Python: How do you use re to ignore links in parentheses?
The relevant part of the code is:
import re
reargs = '<a\s*href=[\'|"](.*?)[\'"].*?>'
link = re.search(reargs,content,flags=re.IGNORECASE)
I'm building a crawler and the web pages I'm working with have links in parentheses that I don't want so it would be ... | Python: How do you use re to ignore links in parentheses? | The relevant part of the code is:
import re
reargs = '<a\s*href=[\'|"](.*?)[\'"].*?>'
link = re.search(reargs,content,flags=re.IGNORECASE)
I'm building a crawler and the web pages I'm working with have links in parentheses that I don't want so it would be like:
Foo foo foo foo (link) foo foo foo foo link foo foo foo f... | [
"If there can be multiple sets of nested parentheses like \"((foo) link)\", I don't think this is possible with regular expressions. In particular, note that parentheses can be used inside URLs (such as at wikipedia), so there may still be nested parens even if the text itself doesn't contain any. So, in the genera... | [
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007406320_python_regex.txt |
Q:
Save python plistlib data (revised)
How can I use this working code:
import plistlib, time
import zipfile
from contextlib import closing
import os
with closing(zipfile.ZipFile("fw.zip")) as zfile:
for info in zfile.infolist():
if info.filename.endswith('Restore.plist'):
zfile.extract(inf... | Save python plistlib data (revised) | How can I use this working code:
import plistlib, time
import zipfile
from contextlib import closing
import os
with closing(zipfile.ZipFile("fw.zip")) as zfile:
for info in zfile.infolist():
if info.filename.endswith('Restore.plist'):
zfile.extract(info)
import plistlib as pl
p=pl.readPli... | [
"What happens when you print p[\"RestoreRamDisks\"]? You can probably get the value by simply doing \np[\"RestoreRamDisks\"][\"Update\"]\n# If your plist may not contain a key called \"RestoreRamDisks\"\n# use this instead\np.get(\"RestoreRamDisks\", dict(Update=None)).get(\"Update\", None)\n# This will get the va... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007404618_python.txt |
Q:
Counting strings
Edited question based on response below:
I have a list of strings in a text file. I want to count the occurrences of these strings in another text file.
Here is an example of strings I have in a file
Red Car
No lake
Newjersey turnpike
Here is the text file I want to search for the strings mention... | Counting strings | Edited question based on response below:
I have a list of strings in a text file. I want to count the occurrences of these strings in another text file.
Here is an example of strings I have in a file
Red Car
No lake
Newjersey turnpike
Here is the text file I want to search for the strings mentioned above:
I have a red... | [
"Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) \n[GCC 4.5.2] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> teststr = '''I have a red car which I drove on newjersey \n... turnpike. When I took exit 39 there was no \n... lake. I drove my car on muddy roads which tu... | [
1,
1,
0
] | [
"If you're just getting started, take a look at the Python Tutorial. This is a good read for people of any level of programming experience who just want to learn Python quickly.\n"
] | [
-1
] | [
"count",
"python",
"string"
] | stackoverflow_0007405230_count_python_string.txt |
Q:
Unique combination of fields in SQLite?
I'm trying to populate a new SQLite database with rows based on a set of data, but I'm having trouble with avoiding duplicate rows. I could accomplish this in Python, but there certainly must be a design option in SQLite to handle this.
I need each row to exist for only a u... | Unique combination of fields in SQLite? | I'm trying to populate a new SQLite database with rows based on a set of data, but I'm having trouble with avoiding duplicate rows. I could accomplish this in Python, but there certainly must be a design option in SQLite to handle this.
I need each row to exist for only a unique combination of three text fields. If I... | [
"CREATE TABLE (col1 typ\n , col2 typ\n , col3 typ\n , CONSTRAINT unq UNIQUE (col1, col2, col3))\n\nhttp://www.sqlite.org/lang_createtable.html\n",
"If the three columns really are the primary key then you can make a composite primary key:\ncreate table t (\n a text not nu... | [
29,
4
] | [] | [] | [
"database_design",
"python",
"sqlite",
"unique_constraint"
] | stackoverflow_0007407506_database_design_python_sqlite_unique_constraint.txt |
Q:
cElementTree : not well-formed (invalid token)
trying to scrape this xml file on the web with urllib and cElementTree. I am using Google App Engine but I don't think the problem is relevant to my platform.
This is my error:
<type 'exceptions.SyntaxError'>: not well-formed (invalid token): line 1, column 25
Traceba... | cElementTree : not well-formed (invalid token) | trying to scrape this xml file on the web with urllib and cElementTree. I am using Google App Engine but I don't think the problem is relevant to my platform.
This is my error:
<type 'exceptions.SyntaxError'>: not well-formed (invalid token): line 1, column 25
Traceback (most recent call last):
File "/base/data/home/... | [
"I tried your code (added imports, so that others can try):\n#!/usr/bin/env python\nimport xml.etree.cElementTree as ET\nimport urllib\n\nxml_url = \"http://www.shoppingcar.it/feed/export_vel.asp?parametro=1\"\nreq = urllib.urlopen(xml_url)\nparser = ET.XMLParser(encoding=\"windows-1252\")\ntree = E... | [
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0007407543_elementtree_python_xml.txt |
Q:
Create (sane/safe) app bundle identifier from any (unsafe) string
I want to create a sane/safe app bundle name (i.e. somewhat readable, no "strange" characters, etc.) from some random Unicode string (mich might contain just anything).
(It doesn't matter for me wether the function is Cocoa, ObjC, Python, etc.)
(Thi... | Create (sane/safe) app bundle identifier from any (unsafe) string | I want to create a sane/safe app bundle name (i.e. somewhat readable, no "strange" characters, etc.) from some random Unicode string (mich might contain just anything).
(It doesn't matter for me wether the function is Cocoa, ObjC, Python, etc.)
(This is related to the filename question and the bundle name question but ... | [
"Bundle identifiers are meant to be in reverse URL form (guaranteeing global uniqueness):\ncom.apple.xcode, for example\nSo really you need a domain name, then you can invent whatever scheme you like below that.\nGiven this, and some knowledge of the characters in your input, you can either scan through your input ... | [
0
] | [] | [] | [
"app_bundle",
"cocoa",
"macos",
"python"
] | stackoverflow_0007406294_app_bundle_cocoa_macos_python.txt |
Q:
Python subprocess, subshells, and redirection
I want to use the magic of subshells and redirection with the python subprocess module, but it doesn't seem to work, complaining about unexpected tokens are the parenthesis. For example, the command
cat <(head tmp)
when passed to subprocess gives this
>>> subprocess.P... | Python subprocess, subshells, and redirection | I want to use the magic of subshells and redirection with the python subprocess module, but it doesn't seem to work, complaining about unexpected tokens are the parenthesis. For example, the command
cat <(head tmp)
when passed to subprocess gives this
>>> subprocess.Popen("cat <(head tmp)", shell=True)
<subprocess.Pop... | [
"The <(head tmp) syntax is a bash feature called \"process substitution\". The basic/portable /bin/sh doesn't support it. (This is true even on systems where /bin/sh and /bin/bash are the same program; it doesn't allow this feature when invoked as plain /bin/sh so you won't inadvertently depend on a non-portable fe... | [
11
] | [] | [] | [
"bash",
"python",
"subprocess",
"subshell"
] | stackoverflow_0007407667_bash_python_subprocess_subshell.txt |
Q:
Inherited method returning no data
When subclassing a base class, an inherited method is not working as expected.
I've broken my module into a couple of pieces (sorry if this difficult to follow) all in a directory named Lan.
in Lan/__init__.py I have:
from Bridge import Bridge
from Ethernet import Ethernet
fro... | Inherited method returning no data | When subclassing a base class, an inherited method is not working as expected.
I've broken my module into a couple of pieces (sorry if this difficult to follow) all in a directory named Lan.
in Lan/__init__.py I have:
from Bridge import Bridge
from Ethernet import Ethernet
from BaseInterface import BaseInterface
d... | [
"You are not returning from restart\nYou either need to change:\ndef up(self):\n return 'Bringing up Bridge'\n\nto \ndef up(self):\n print 'Bringing up Bridge'\n\nor change:\ndef restart(self, delay = 1.0):\n self.down()\n sleep(delay)\n self.up()\n\nto \ndef restart(self, delay = 1.0):\n vals = [... | [
2,
1,
0
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0007407664_inheritance_oop_python.txt |
Q:
Python Unicode Output Format
In Python I pull in data via Win32Com as a tuple:
((u'863579XK9',),)
How can I parse this so that I am left with just 863579XK9 so I can write that to a file?
A:
data = ((u'863579XK9',),)
print data[0][0] # prints "863579XK9"
A:
>>> print ((u'863579XK9',),)[0][0]
863579XK9
A:
S... | Python Unicode Output Format | In Python I pull in data via Win32Com as a tuple:
((u'863579XK9',),)
How can I parse this so that I am left with just 863579XK9 so I can write that to a file?
| [
"data = ((u'863579XK9',),)\nprint data[0][0] # prints \"863579XK9\"\n\n",
">>> print ((u'863579XK9',),)[0][0]\n863579XK9\n\n",
"Since this is a unicode string, you'd want to write it to a unicode encoded file:\nimport codecs\nmyfile = codecs.open('myfile.txt', encoding='utf8', mode='w')\ndata = ((u'863579XK9',)... | [
3,
1,
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0007407838_python_tuples.txt |
Q:
%d by python and addition ValueError: unsupported format character 'O' (0x4f) at index 2
i wrote a small function to do this job
x = 'INV-%05d'
m = x %(100+1)
i should have m = INV-0101
but i receive this error
ValueError: unsupported format character 'O' (0x4f) at index 2
this works without any problem, but i w... | %d by python and addition ValueError: unsupported format character 'O' (0x4f) at index 2 | i wrote a small function to do this job
x = 'INV-%05d'
m = x %(100+1)
i should have m = INV-0101
but i receive this error
ValueError: unsupported format character 'O' (0x4f) at index 2
this works without any problem, but i want to use an external variable
m = INV-%05d %(100+1)
-> m = INV-0101
because the original va... | [
"0x4f, as reported in the error message, is the ASCII value for the capital letter O. It looks like you have made a typographical error, and put an O in when you want a zero.\n"
] | [
4
] | [] | [] | [
"addition",
"python"
] | stackoverflow_0007408017_addition_python.txt |
Q:
In Python, how do I convert a .exe file to a string of 1s and 0s?
I seem to be able to find information on how to do this in C#, but not on how to perform the same operation in Python.
Any advice or suggestions would be appreciated. Thank you very much.
A:
def padded_bin(number, width=8, padchar='0'):
return... | In Python, how do I convert a .exe file to a string of 1s and 0s? | I seem to be able to find information on how to do this in C#, but not on how to perform the same operation in Python.
Any advice or suggestions would be appreciated. Thank you very much.
| [
"def padded_bin(number, width=8, padchar='0'):\n return bin(number)[2:].rjust(width, padchar)\n\nwith open(r'C:\\path\\to\\file.txt', 'rb') as f:\n as_binary = ''.join(padded_bin(ord(c)) for c in f.read())\n\n",
"''.join((map(''.join, itertools.product(*['01']*8))[ord(c)]\n for c in open('foo').read... | [
4,
2,
0,
0
] | [] | [] | [
"binary",
"python"
] | stackoverflow_0007408089_binary_python.txt |
Q:
Corresponding Objects to Tables in Database Design
Say I have an object which is composed of multiple pieces of information: rating, like, comment. Let's call this object a preference. Each preference would be associated with a user. That is, each user has many preferences, but each preference has only one user.
I... | Corresponding Objects to Tables in Database Design | Say I have an object which is composed of multiple pieces of information: rating, like, comment. Let's call this object a preference. Each preference would be associated with a user. That is, each user has many preferences, but each preference has only one user.
In what ways would it be better for my preference object ... | [
"You might want to look into the Entity-Attribute-Value model:\nhttp://weblogs.sqlteam.com/davidm/articles/12117.aspx\n"
] | [
2
] | [] | [] | [
"database",
"database_design",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0007408327_database_database_design_python_sql_sqlalchemy.txt |
Q:
Curious (bad?) behavior creating all-sky projections with matplotlib
I am trying to make a density "all-sky" plot which is complete in RA (i.e 0 to 360 deg) but incomplete in DEC (let's say from -45 to 90 deg). If I plot this without any projection it is ok, but when I try to plot using the 'mollweide' projection... | Curious (bad?) behavior creating all-sky projections with matplotlib | I am trying to make a density "all-sky" plot which is complete in RA (i.e 0 to 360 deg) but incomplete in DEC (let's say from -45 to 90 deg). If I plot this without any projection it is ok, but when I try to plot using the 'mollweide' projection I am not recovering the input, but if I do a little change in the code I ... | [
"if you don't mind depending on an external package, you could do this with healpy, that provides a Mollweide projection for the Healpix sky pixellization:\nhttps://github.com/healpy/healpy\nSee an example similar to your script here:\nhttps://gist.github.com/1215159\nMore info about healpix:\nhttp://healpix.jpl.na... | [
3,
2
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0007355497_matplotlib_plot_python.txt |
Q:
GStreamer and Theora
I'm trying to work with GStreamer. I'm following a tutorial (http://pygstdocs.berlios.de/pygst-tutorial/pipeline.html) that gives me the following code:
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
class GTK_Main:
def __in... | GStreamer and Theora | I'm trying to work with GStreamer. I'm following a tutorial (http://pygstdocs.berlios.de/pygst-tutorial/pipeline.html) that gives me the following code:
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
class GTK_Main:
def __init__(self):
window... | [
"It is not reliable to determine pad type by it's template name because it does not always have this property.\nIt's better to check capabilities. Here is diff:\n@@ -85,10 +85,11 @@\n gtk.gdk.threads_leave()\n\n def demuxer_callback(self, demuxer, pad):\n- if pad.get_property(\"template\").na... | [
2
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0007296888_gstreamer_python.txt |
Q:
How can I parse an external XML file with django/python
I've done some research on trying to parse an XML file from another web server and came across something called minidom.
I've tried implementing this in my view.py file:
from xml.dom import minidom
import models
def test(request):
data={}
doc=minido... | How can I parse an external XML file with django/python | I've done some research on trying to parse an XML file from another web server and came across something called minidom.
I've tried implementing this in my view.py file:
from xml.dom import minidom
import models
def test(request):
data={}
doc=minidom.parse("http://www.someotherdomain.com/XML.aspx?id=27550&lim... | [
"Apparently minidom cannot parse URLs. You have to do\nimport urllib2\ndoc = urllib2.urlopen(your_url)\nparsed = minidom.parse(doc)\n\n"
] | [
9
] | [] | [] | [
"django",
"django_models",
"parsing",
"python",
"xml"
] | stackoverflow_0007408420_django_django_models_parsing_python_xml.txt |
Q:
Problem with ToasterBox, can you join() a timer or force a thread to wait on a timer to finish in python
Basically I am using toasterbox and I want code to run, lets say every 30 seconds. Well every 30 seconds the toasterbox should pop up. The code looks like this
event = threading.Event()
########################... | Problem with ToasterBox, can you join() a timer or force a thread to wait on a timer to finish in python | Basically I am using toasterbox and I want code to run, lets say every 30 seconds. Well every 30 seconds the toasterbox should pop up. The code looks like this
event = threading.Event()
#############################################
bWidth = 200
bHeight = 100
tb = TB.ToasterBox(self, TB.TB_COMPLEX, TB.DEFAULT_TB_STYLE, ... | [
"What is this toasterbox you're using? There's one included with wxPython. See here http://xoomer.virgilio.it/infinity77/AGW_Docs/toasterbox_module.html#toasterbox or here http://www.wxpython.org/docs/api/wx.lib.agw.toasterbox.ToasterBox-class.html\nI don't think the agw one supports blocking and I'm guessing the ... | [
2
] | [] | [] | [
"blocking",
"multithreading",
"python",
"wxpython"
] | stackoverflow_0007407075_blocking_multithreading_python_wxpython.txt |
Q:
cherrypy handle all request with one function or class
i'd like to use cherrypy but i don't want to use the normal dispatcher, i'd like to have a function that catch all the requests and then perform my code. I think that i have to implement my own dispatcher but i can't find any valid example. Can you help me by ... | cherrypy handle all request with one function or class | i'd like to use cherrypy but i don't want to use the normal dispatcher, i'd like to have a function that catch all the requests and then perform my code. I think that i have to implement my own dispatcher but i can't find any valid example. Can you help me by posting some code or link ?
Thanks
| [
"make a default function:\nimport cherrypy\n\nclass server(object):\n @cherrypy.expose\n def default(self,*args,**kwargs):\n return \"It works!\"\n\ncherrypy.quickstart(server())\n\n",
"What you ask can be done with routes and defining a custom dispatcher\nhttp://tools.cherrypy.org/wi... | [
13,
2,
1
] | [] | [] | [
"cherrypy",
"dispatcher",
"python",
"routes"
] | stackoverflow_0006657848_cherrypy_dispatcher_python_routes.txt |
Q:
Python, search for html tags inside a file using regex
So I am doing some data analysis in which I am required to extract the page title, breadcrumb, h1 tags from hundreds of HTML and SHTML files.
Those tags are in the following format (meaning stuffs inside , and breadcrumb):
<title>Mapping a Drive: Macintosh OS... | Python, search for html tags inside a file using regex | So I am doing some data analysis in which I am required to extract the page title, breadcrumb, h1 tags from hundreds of HTML and SHTML files.
Those tags are in the following format (meaning stuffs inside , and breadcrumb):
<title>Mapping a Drive: Macintosh OSX < Mapping a Drive < eHelp < Cal Poly Pomona</titl... | [
"Use a real HTML parser, not a regex. You will be happier. lxml.html is highly regarded, as is BeautifulSoup.\n",
"Since most HTML is basically xml (or can easily be trimmed to be compatible with most xml parsers) I would suggest using an xml parser. Most python HTML-specific parsers are just subclasses of an ... | [
6,
2,
0
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0007408539_html_python_regex.txt |
Q:
python beginner - how to read contents of several files into unique lists?
I'd like to read the contents from several files into unique lists that I can call later - ultimately, I want to convert these lists to sets and perform intersections and subtraction on them. This must be an incredibly naive question, but a... | python beginner - how to read contents of several files into unique lists? | I'd like to read the contents from several files into unique lists that I can call later - ultimately, I want to convert these lists to sets and perform intersections and subtraction on them. This must be an incredibly naive question, but after poring over the iterators and loops sections of Lutz's "Learning Python," I... | [
"#!/usr/bin/env python\n\nimport sys\n\nFileList = sys.argv[1: ]\nPathwayList = []\nfor InFileName in FileList:\n sys.stderr.write(\"Processing file %s\\n\" % (i))\n InFile = open(InFileName, 'r')\n PathwayList.append(InFile.readlines())\n InFile.close()\n\nAssuming you read in two files, the following ... | [
2,
1,
1,
1,
0,
0
] | [] | [] | [
"for_loop",
"python",
"readlines"
] | stackoverflow_0007407934_for_loop_python_readlines.txt |
Q:
Bizarre Intermittent Error on Video (GStreamer)
I have a project that runs Python 2.7, PyGTK 2.24, and the most recent version of PyGST.
I am getting a weird intermittent error in the following code. With the first, longer error, the video will play just fine, and the error will only appear AFTER I close the video... | Bizarre Intermittent Error on Video (GStreamer) | I have a project that runs Python 2.7, PyGTK 2.24, and the most recent version of PyGST.
I am getting a weird intermittent error in the following code. With the first, longer error, the video will play just fine, and the error will only appear AFTER I close the video window. The second prevents the window from opening ... | [
"You need to synchronise with X server to get window xid.\nHere is how:\n def on_sync_message(bus, message):\n if message.structure is None:\n return False\n if message.structure.get_name() == \"prepare-xwindow-id\":\n gtk.gdk.threads_enter()\n gtk.gdk.display_get_d... | [
3
] | [] | [] | [
"gstreamer",
"python"
] | stackoverflow_0007369712_gstreamer_python.txt |
Q:
Inheritance + Class members
I'm starting with Python and encountered this weird behaviour (atleast for me):
class Parent:
myStr = ""
myInt = 0
myDict = {}
....
class ChildA:
...
def ...():
self.myDict.<something>(...)
print self.myStr
...
class ChildB:
...
def ... | Inheritance + Class members | I'm starting with Python and encountered this weird behaviour (atleast for me):
class Parent:
myStr = ""
myInt = 0
myDict = {}
....
class ChildA:
...
def ...():
self.myDict.<something>(...)
print self.myStr
...
class ChildB:
...
def ...():
self.myDict.<somet... | [
"This happens because names bound at the class level belong to the class, not any instance. Therefore, all myDict are the same dict. Since dict instances are mutable, changes you make via one class/instance reference show up in all. Strings and numbers are immutable, so they are rebound instead when assigned via a ... | [
3,
3,
2,
0
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0007408865_inheritance_oop_python.txt |
Q:
python: easiest way to get a string of spaces of length N
What's the easiest way to generate a string of spaces of length N in Python?
(besides something like this, which is multiline and presumably inefficient for large n:
def spaces(n):
s = ''
for i in range(n):
s += ' '
return s
)
A:
try this, simp... | python: easiest way to get a string of spaces of length N | What's the easiest way to generate a string of spaces of length N in Python?
(besides something like this, which is multiline and presumably inefficient for large n:
def spaces(n):
s = ''
for i in range(n):
s += ' '
return s
)
| [
"try this, simple, only one line:\n ' ' * n\n\n",
"It's as simple as:\ns = ' ' * N\n\n",
"You could do it as a function:\ndef spaces(n):\n return ' ' * n\n\nOr just use the expression:\n' ' * n\n\n",
"Off the top of my head:\nspaces = lambda x: ' ' * x\n\n",
"All these point mongers are no fun, and th... | [
32,
3,
3,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007408874_python_string.txt |
Q:
Portfolio Variance of a Portfolio of N Assets in Python
Portfolio variance is calculated as:
port_var = W'_p * S * W_p
for a portfolio with N assest where
W'_p = transpose of vector of weights of stocks in portfolios
S = sample covariance matrix
W_p = vector of weights of stocks in portfolios
I have the followin... | Portfolio Variance of a Portfolio of N Assets in Python | Portfolio variance is calculated as:
port_var = W'_p * S * W_p
for a portfolio with N assest where
W'_p = transpose of vector of weights of stocks in portfolios
S = sample covariance matrix
W_p = vector of weights of stocks in portfolios
I have the following numpy matrixes.
Array (vector) of weights of stocks in the ... | [
"np.dot(weights.T,np.dot(covar,weights))\n# array([[ 0.00064654]])\n\nFor 2D numpy arrays, np.dot is equivalent to matrix multiplication.\nFor a 2D array np.dotted with a 1D array, np.dot is equivalent to matrix-vector multiplication.\nFor 1D arrays, np.dot is equivalent to the inner product.\nFor numpy arrays, the... | [
5
] | [] | [] | [
"arrays",
"numpy",
"portfolio",
"python",
"variance"
] | stackoverflow_0007409108_arrays_numpy_portfolio_python_variance.txt |
Q:
How to Create a JSON Tree from a Tabulated Hierarchy in Python
I'm sure there's an elegant way of doing this in Python (or at a push, Javascript), but for the life of me I can't see it...
I have a CSV file of the form:
ID, Name, Description
A, A-name,
A100, A100-name, A100-desc
A110, A110-name, A110-desc
A111, A11... | How to Create a JSON Tree from a Tabulated Hierarchy in Python | I'm sure there's an elegant way of doing this in Python (or at a push, Javascript), but for the life of me I can't see it...
I have a CSV file of the form:
ID, Name, Description
A, A-name,
A100, A100-name, A100-desc
A110, A110-name, A110-desc
A111, A111-name, A111-desc
A112, A112-name, A112-desc
A113, A113-name, A113-d... | [
"This does it...\nimport csv\nimport json\n\nclass Node(dict):\n def __init__(self, (nid, name, ndescr)):\n dict.__init__(self)\n self['id'] = nid\n self['name'] = name.lstrip() # you have badly formed csv....\n self['description'] = ndescr.lstrip()\n self['children'] = []\n\n ... | [
2
] | [] | [] | [
"json",
"python",
"thejit"
] | stackoverflow_0007408615_json_python_thejit.txt |
Q:
mysql python combine results
trying to write the following in python more elegantly...from mysql perspective. You will notice I am trying to combine results in one table based upon the entries in another. What is the proper,clean, industry smart way of writing such SQL query?
Essentially, I would like to say thi... | mysql python combine results | trying to write the following in python more elegantly...from mysql perspective. You will notice I am trying to combine results in one table based upon the entries in another. What is the proper,clean, industry smart way of writing such SQL query?
Essentially, I would like to say this... "select all urls from urls ta... | [
"Welcome to SQL. Now that you've written two queries, it's time to learn about JOIN and SQL injection.\nselect *\nfrom urls, sites\nwhere urls.site_id = sites.id\nand sitename like ?\n\nGood luck.\n"
] | [
4
] | [] | [] | [
"mysql",
"python",
"sql"
] | stackoverflow_0007409472_mysql_python_sql.txt |
Q:
Convert dynamic python object to json
Possible Duplicate:
Python serializable objects json
I need to know how to convert a dynamic python object into JSON. The object must be able to have multiple levels object child objects. For example:
class C(): pass
class D(): pass
c = C()
c.dynProperty1 = "something"
c.... | Convert dynamic python object to json |
Possible Duplicate:
Python serializable objects json
I need to know how to convert a dynamic python object into JSON. The object must be able to have multiple levels object child objects. For example:
class C(): pass
class D(): pass
c = C()
c.dynProperty1 = "something"
c.dynProperty2 = { 1, 3, 5, 7, 9 }
c.d = D()... | [
"Specify the default= parameter (doc):\njson.dumps(c, default=lambda o: o.__dict__)\n\n",
"json.dumps(c.__dict__)\n\nThat will give you a generic JSON object, if that's what you're going for.\n",
"Try using this package python-jsonpickle\n\nPython library for serializing any arbitrary object graph into JSON. It... | [
140,
16,
9,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0007408647_json_python.txt |
Q:
Is it possible to use Ropemacs with TRAMP in Emacs?
I recently installed the hg tip version of Ropemacs and I'd like to use it when editing remote files using TRAMP. Has anyone done this? When I try to use M-/ to complete a variable name, I am asked to enter the Rope project root folder and I enter: /ssh:myhost:/p... | Is it possible to use Ropemacs with TRAMP in Emacs? | I recently installed the hg tip version of Ropemacs and I'd like to use it when editing remote files using TRAMP. Has anyone done this? When I try to use M-/ to complete a variable name, I am asked to enter the Rope project root folder and I enter: /ssh:myhost:/path/to/myproject/ and it gives me the following error:
Op... | [
"No, this is not possible using TRAMP, because the Python rope library does not make calls back into Emacs when it wants to scan the filesystem for Python files to find their classes and functions — instead, it uses calls like listdir() and open() on the filesystem directly, without giving Emacs a chance to get in ... | [
6
] | [] | [] | [
"emacs",
"python",
"ropemacs",
"tramp"
] | stackoverflow_0002815228_emacs_python_ropemacs_tramp.txt |
Q:
post form in django, get blank screen, broken or bug?
I've created a form in django which works fine on desktop browsers, but on mobile browsers when the form submits it just displays a blank screen (doesn't even load the title or an error), am I missing something?
If there's no way to make it work using post, how... | post form in django, get blank screen, broken or bug? | I've created a form in django which works fine on desktop browsers, but on mobile browsers when the form submits it just displays a blank screen (doesn't even load the title or an error), am I missing something?
If there's no way to make it work using post, how could I submit a form to locations/<zip code> or use get ... | [
"If the form is valid then you do all this fancy stuff... but you forgot to handle the case where the form isn't valid.\n"
] | [
0
] | [] | [] | [
"django",
"mobile",
"python"
] | stackoverflow_0007407974_django_mobile_python.txt |
Q:
Iterating Over Dictionary Key Values Corresponding to List in Python
Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list:
NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}
I would like to be abl... | Iterating Over Dictionary Key Values Corresponding to List in Python | Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list:
NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}
I would like to be able to feed the dictionary into a function and iterate over each team (the k... | [
"You have several options for iterating over a dictionary.\nIf you iterate over the dictionary itself (for team in league), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league) itself, or league.keys():\nfor team ... | [
233,
11,
6,
5,
4
] | [] | [] | [
"dictionary",
"function",
"list",
"loops",
"python"
] | stackoverflow_0007409078_dictionary_function_list_loops_python.txt |
Q:
How to get worked mod_wsgi with .pyo files only (without .py)?
I'm trying to start apache + mod_wsgi and I have strong restriction to put source .py files onto server, so I compile them first and put .pyo files onto server.
That's what I have in apache conf:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIPythonPat... | How to get worked mod_wsgi with .pyo files only (without .py)? | I'm trying to start apache + mod_wsgi and I have strong restriction to put source .py files onto server, so I compile them first and put .pyo files onto server.
That's what I have in apache conf:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIPythonPath /var/wwwroot/
WSGIPythonOptimize 1
WSGIScriptAlias /home /var/wwwr... | [
"A straightforward workaround is to add next to your home.pyo an extra file which just contains from home import *. You could call it foo.py, you could call it home.wsgi, you could call it the-quick-brown-fox-ate-the-lazy-dog if you wanted to. (So if you're having problems with it having the extension \".py\", it d... | [
1,
1,
1
] | [] | [] | [
"apache",
"mod_wsgi",
"python"
] | stackoverflow_0007401971_apache_mod_wsgi_python.txt |
Q:
Get and iterating over large dataset, what is ok? And why the difference in admin log/appstas?
When trying to optimize a query for getting store records based on location, I dumped in to something strange (I think), getting large dataset takes ALOT of cpu time.
Basically I have > 1000 records that need to be itera... | Get and iterating over large dataset, what is ok? And why the difference in admin log/appstas? | When trying to optimize a query for getting store records based on location, I dumped in to something strange (I think), getting large dataset takes ALOT of cpu time.
Basically I have > 1000 records that need to be iterated over to find stores within the 3000m of a users position, and I got quite high numbers in the ad... | [
"Why is it surprising that retrieving a lot of records takes a lot of resources? This is an O(n) process, and you really shouldn't be doing this on a per-request basis. To answer your questions in order:\n\nHow much CPU time it uses depends on the nature of the records, but this result isn't surprising. Note that i... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007400892_google_app_engine_python.txt |
Q:
Distributing python modules for another architecture
I'm wondering how I can create a 32-bit binary with my 64bit cx_freeze. I've looked at the homepage and I can't find a setting to tell it what architecture to build for.
I'm running 32bit(otherwise PyQt won't work) Python 2.6, so the dependencies should already ... | Distributing python modules for another architecture | I'm wondering how I can create a 32-bit binary with my 64bit cx_freeze. I've looked at the homepage and I can't find a setting to tell it what architecture to build for.
I'm running 32bit(otherwise PyQt won't work) Python 2.6, so the dependencies should already be 32bit, on 64bit Kubuntu 10.10.
| [
"If you were using Windows or a Mac, then you could use py2exe or py2app, respectively. I think that freeze may be a more general solution that may work for you.\n",
"Maybe this link will help you: http://linux.die.net/man/8/linux32\nOtherwise you can create a x32 virtual machine by using QEmu or VirtualBox...\n"... | [
0,
0,
0
] | [] | [] | [
"architecture",
"pyqt",
"python"
] | stackoverflow_0004128467_architecture_pyqt_python.txt |
Q:
Writing a simple DMS web service in Python
I recently learned Python and want to do a project just to get my hands dirty and let the knowledge settle.
So I was thinking to create a simple Document Management System in Python because I have another project written in Java which needs it. I want the two to be linke... | Writing a simple DMS web service in Python | I recently learned Python and want to do a project just to get my hands dirty and let the knowledge settle.
So I was thinking to create a simple Document Management System in Python because I have another project written in Java which needs it. I want the two to be linked by SOAP so the DMS will be a web service.
I ne... | [
"Mayan EDMS a complete free open source electronic document management system, no REST API yet, but all the other parts you need are already coded.\n",
"you can have a look at django-dms\nDon't be afraid about django, it is a framework that will save you a lot of time (and will make you developp neat applications... | [
3,
1,
1,
1
] | [] | [] | [
"content_management_system",
"file",
"python",
"web_services"
] | stackoverflow_0003433949_content_management_system_file_python_web_services.txt |
Q:
Python: iterating through a list of objects within a list of objects
I've made two classes called House and Window. I then made a list containing four Houses. Each instance of House has a list of Windows. I'm trying to iterate over the windows in each house and print it's ID. However, I seem to get some odd result... | Python: iterating through a list of objects within a list of objects | I've made two classes called House and Window. I then made a list containing four Houses. Each instance of House has a list of Windows. I'm trying to iterate over the windows in each house and print it's ID. However, I seem to get some odd results :S I'd greatly appreciate any help.
#!/usr/bin/env python
# Minimal h... | [
"Currently you are using class attributes instead of instance attributes. Try changing your class definitions to the following:\nclass House:\n def __init__(self):\n self.ID = \"\"\n self.window_list = []\n\nclass Window:\n def __init__(self):\n self.ID = \"\"\n\nThe way your code is now... | [
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007408237_python.txt |
Q:
sql dump file.. load to mysql
Ok first, please assume that this is the first time I will be writing a single alphabet of code in SQL.. so please please please... it would be very kind if you can explain me each step. :)
I am using mac for this development.
So in the desktop, I have a huge (1.5GB) dumpfile of a dat... | sql dump file.. load to mysql | Ok first, please assume that this is the first time I will be writing a single alphabet of code in SQL.. so please please please... it would be very kind if you can explain me each step. :)
I am using mac for this development.
So in the desktop, I have a huge (1.5GB) dumpfile of a database.
I have mysqlworkbench (yes I... | [
"In order to use the data in the file, it needs to be imported into the database. (Think of the file as a recipe for MySQL to make a database. Now you need to tell MySQL to make the database from the recipe). \nYou can import the database using command line, a python script or even MySQL workbench. However, due to ... | [
4
] | [] | [] | [
"mysql_python",
"mysql_workbench",
"python",
"sql"
] | stackoverflow_0007409748_mysql_python_mysql_workbench_python_sql.txt |
Q:
Django application using UTC throughout
I am building a Django application that will be using UTC for all time stamps and datetime fields. The users (operators of a networks of environmental research stations) are trained to enter times in UTC (GMT) and the server as well as the users' work desktop/laptop computer... | Django application using UTC throughout | I am building a Django application that will be using UTC for all time stamps and datetime fields. The users (operators of a networks of environmental research stations) are trained to enter times in UTC (GMT) and the server as well as the users' work desktop/laptop computers are set to UTC with no daylight saving time... | [
"I could be wrong on this (I've only partially updated a project to correctly handle timezones), but I believe that the TIME_ZONE variable is only used by the Postgres backend (determined by grepping the source). So, if you're not using Postgres, it doesn't really matter what you use… And if you are using Postgres,... | [
1,
0
] | [] | [] | [
"datetime",
"django",
"python",
"utc"
] | stackoverflow_0007407981_datetime_django_python_utc.txt |
Q:
List of modules working with ironpython
Is there a place that lists standard library and 3rd party modules that work with IronPython? If not, please let me know here.
Here are some I have tried:
cherrypy - works with fepy - example
comtypes: has no hope until ctypes is functional which seems far off still.
dulwic... | List of modules working with ironpython | Is there a place that lists standard library and 3rd party modules that work with IronPython? If not, please let me know here.
Here are some I have tried:
cherrypy - works with fepy - example
comtypes: has no hope until ctypes is functional which seems far off still.
dulwich: builds after removing optional extensions ... | [
"The official IronPython website has a page that lists the compatibility status of third-party libraries.\nHowever, currently only two libraries are listed. If you're a third-party library developer and you know how well your library works with IronPython, it would be great to add it there.\n",
"pywin32 and PyOD... | [
1,
0,
0
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0004670369_ironpython_python.txt |
Q:
Is it possible to store data from Python in Access file?
Well, I might be doing some work in Python that would end up with hundreds of thousands, maybe millions of rows of data, each with entries in maybe 50 or more columns. I want a way to keep track of this data and work with it. Since I also want to learn Mic... | Is it possible to store data from Python in Access file? | Well, I might be doing some work in Python that would end up with hundreds of thousands, maybe millions of rows of data, each with entries in maybe 50 or more columns. I want a way to keep track of this data and work with it. Since I also want to learn Microsoft Access, I suggest putting the data in there. Is there ... | [
"Yes, you can talk to any ODBC database from Python, and that should include Access. You'll want the \"windows\" version of Python (which includes stuff like ODBC) from ActiveState.\nI'd be more worried about the \"millions of rows\" in Access, it can get a bit slow on retrieval if you're actually using it for re... | [
1,
0
] | [] | [] | [
"database",
"ms_access",
"python"
] | stackoverflow_0007410458_database_ms_access_python.txt |
Q:
Achieving a border for a QTreeWidgetItem in PyQT
I don't see that there's any way to define a stylesheet for a specific QTreeWidgetItem, so I'm resolved to attempt to figure my solution out using either SetBackground or SetForeground. The effect I'm trying to achieve is border around a single widgetitem for a tree... | Achieving a border for a QTreeWidgetItem in PyQT | I don't see that there's any way to define a stylesheet for a specific QTreeWidgetItem, so I'm resolved to attempt to figure my solution out using either SetBackground or SetForeground. The effect I'm trying to achieve is border around a single widgetitem for a treeview, but I can't figure out how to draw one manually ... | [
"You can't draw a border with a QTreeWidgetItem alone, you have to use a delegate.\nAnd you can store a border style in each item for which you want to have a border under a custom \"role\" to be able to retrieve it and use it inside the delegate.\nHere is a complete working and commented example:\nimport sys\nfrom... | [
2
] | [] | [] | [
"pyqt",
"python",
"user_interface"
] | stackoverflow_0007408264_pyqt_python_user_interface.txt |
Q:
Bulk uploading data in Google App Engine - problem
I am trying to upload some data to GAE using the bulk uploader outlined;
http://code.google.com/appengine/docs/python/tools/uploadingdata.html
When I run the command;
appcfg.py create_bulkloader_config --filename=bulkloader.yaml
I get:
appcfg.py: error: Expected... | Bulk uploading data in Google App Engine - problem | I am trying to upload some data to GAE using the bulk uploader outlined;
http://code.google.com/appengine/docs/python/tools/uploadingdata.html
When I run the command;
appcfg.py create_bulkloader_config --filename=bulkloader.yaml
I get:
appcfg.py: error: Expected either --url or a single <directory> argument.
From lo... | [
"You must specify the application folder. If you are in it, just run:\nappcfg.py create_bulkloader_config --filename=bulkloader.yaml .\n\notherwise run:\nappcfg.py create_bulkloader_config --filename=bulkloader.yaml\npath/to/root/gae/app/\n\n",
"There are plenty of steps in the process. After spending much time o... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006974033_google_app_engine_python.txt |
Q:
App Engine Bulk Data Upload- Authentication Error
When I try to upload data using appcfg.py I get an authentication error regardless of my login details being completely correct.
appcfg.py upload_data --config_file=bulkloader.yaml --filename=/output.csv --kind=AutoCompleteIndex .
Application: qwertifyy; versio... | App Engine Bulk Data Upload- Authentication Error | When I try to upload data using appcfg.py I get an authentication error regardless of my login details being completely correct.
appcfg.py upload_data --config_file=bulkloader.yaml --filename=/output.csv --kind=AutoCompleteIndex .
Application: qwertifyy; version: dev.
Uploading data records.
[INFO ] Logging to b... | [
"I think you are using OpenID? If so, it appears that remote_api doesn't work with OpenID:\nhttp://blog.notdot.net/2010/06/Using-remote-api-with-OpenID-authentication\n",
"I encounter this issue when trying to authenticate with a \"Google Apps\" account.\nGet around the issue by setting up another \"Google\" acco... | [
2,
0,
0
] | [] | [] | [
"bigtable",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003435873_bigtable_google_app_engine_google_cloud_datastore_python.txt |
Q:
DB not persisting after end of program
I've created a simple DB using SQLAlchemy. After I connect to it via the engine, define the tables and classes, then create a User, it outputs the user fine. When the program ends and I try accessing the DB via the Python prompt (importing SQLAlchemy, creating a new engine, e... | DB not persisting after end of program | I've created a simple DB using SQLAlchemy. After I connect to it via the engine, define the tables and classes, then create a User, it outputs the user fine. When the program ends and I try accessing the DB via the Python prompt (importing SQLAlchemy, creating a new engine, etc.) the previous users are gone.
Can someon... | [
"Are you calling .commit() on the connection before releasing it?\nBy default the Python SQLite module does not use AUTOCOMMIT mode and, unless you finish your session with a DDL statement, it will be rolled back.\nFor more info: http://docs.python.org/library/sqlite3.html#controlling-transactions.\n"
] | [
4
] | [] | [] | [
"database",
"python",
"sqlalchemy",
"sqlite",
"terminal"
] | stackoverflow_0007410928_database_python_sqlalchemy_sqlite_terminal.txt |
Q:
How to reformat a timestamp in Python
I have some text below that needs to handled. The timestamp is currently listed and then the value. The format for the timestamp is yyyymmdd and I want to be able to alter it to yyyy-mm-dd or some other variation: yyyy/mm/dd, etc. I can't seem to find a string method that inse... | How to reformat a timestamp in Python | I have some text below that needs to handled. The timestamp is currently listed and then the value. The format for the timestamp is yyyymmdd and I want to be able to alter it to yyyy-mm-dd or some other variation: yyyy/mm/dd, etc. I can't seem to find a string method that inserts characters into strings so I'm unsure o... | [
"I'd do something like this:\n#!/usr/bin/env python\n\nfrom datetime import datetime\n\nwith open(\"stuff.txt\", \"r\") as f:\n for line in f:\n # Remove initial or ending whitespace (like line endings)\n line = line.strip()\n\n # Split the timestamp and value\n raw_timestamp, value =... | [
3,
1,
1
] | [] | [] | [
"methods",
"parsing",
"python",
"string",
"text"
] | stackoverflow_0007411037_methods_parsing_python_string_text.txt |
Q:
Beautiful Soup - handling errors
I'd like to know how to handle a situation when href doesn't exist after the <strong>Text:</strong>
Is there a better way to search for the content that exists after <strong>Contact:</strong>
http://pastebin.com/FYMxTJkf
A:
How about findNext?
import re
from BeautifulSoup import... | Beautiful Soup - handling errors |
I'd like to know how to handle a situation when href doesn't exist after the <strong>Text:</strong>
Is there a better way to search for the content that exists after <strong>Contact:</strong>
http://pastebin.com/FYMxTJkf
| [
"How about findNext?\nimport re\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = '''<strong>Text:</strong> \n\n <a href='http://domain.com'>url</a>'''\n\nsoup = BeautifulSoup(html)\nlabel = soup.find(\"strong\" , text='Text:')\ncontact = label.findNext('a')\n\nif contact.get('href') != None:\n print c... | [
2
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0007410919_beautifulsoup_html_parsing_python.txt |
Q:
Importing a model in Django that shares it's name between two different applications problem
I have two apps one named "challenge" another named "stats"; within the models.py files of both I have classes named Team. They serve two complete seperate purposes. When I import from another app
from stats.models impo... | Importing a model in Django that shares it's name between two different applications problem | I have two apps one named "challenge" another named "stats"; within the models.py files of both I have classes named Team. They serve two complete seperate purposes. When I import from another app
from stats.models import Team
it will only and always import the Team model from challenge, rather than from stats. If ... | [
"how about:\nfrom challenge.models import Team as ChallengeTeam\nfrom stats.models import Team as StatsTeam\n\nChallengeTeam\n>>> <class 'challenge.models.Team'>\n\nStatsTeam\n>>> <class 'stats.models.Team'>\n\n"
] | [
1
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0007407671_django_models_python.txt |
Q:
merging dicts in python
I am new to python..I have two sorted arrays (by key) that I would like to merge. Both arrays have some common keys and some exist uniquely in one of the arrays. I want to do an outer join.
Array1 = {'key_1': 10, 'key_2': 14,..'key_m': 321}
Array2 = {'key_1': 15, 'key_2': 12..'key_m':2,..'k... | merging dicts in python | I am new to python..I have two sorted arrays (by key) that I would like to merge. Both arrays have some common keys and some exist uniquely in one of the arrays. I want to do an outer join.
Array1 = {'key_1': 10, 'key_2': 14,..'key_m': 321}
Array2 = {'key_1': 15, 'key_2': 12..'key_m':2,..'key_n':34}
I want to merge us... | [
"How about this?\n#!/usr/bin/env python\nfrom itertools import chain\n\ndict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}\ndict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}\n\ndict3 = {}\n\n# Go through all keys in both dictionaries\nfor key in set(chain(dict1, dict2)):\n\n # Find the key in either dictio... | [
3,
1
] | [] | [] | [
"arrays",
"merge",
"python"
] | stackoverflow_0007411150_arrays_merge_python.txt |
Q:
How do you connect remotely using Python + Webdriver
I am trying to figure out how to connect to my remote webdriver instance.
This is the code I am currently using:
from selenium.remote.webdriver import WebDriver
driver = WebDriver("http://172.16.205.129:4444", "firefox", "ANY")
driver.get('http://google.com')
d... | How do you connect remotely using Python + Webdriver | I am trying to figure out how to connect to my remote webdriver instance.
This is the code I am currently using:
from selenium.remote.webdriver import WebDriver
driver = WebDriver("http://172.16.205.129:4444", "firefox", "ANY")
driver.get('http://google.com')
driver.quit()
I find that I can't connect and will get a c... | [
"You need to ensure selenium server hub and node are set up before the test. Please refer to this. \nExample on hub run \njava -jar selenium-server-standalone-2.5.0.jar -role hub\n\nExample on node to connect to hub ,run\njava -jar selenium-server-standalone-2.5.0.jar -role webdriver -hub\n http://localhost:4444/... | [
4,
2
] | [] | [] | [
"python",
"selenium",
"webdriver"
] | stackoverflow_0002850460_python_selenium_webdriver.txt |
Q:
Dynamically serve static content based on server name in Django
I'm writing a web application in Django that is accessed from multiple domains to the same IP address. The idea is that each domain the application is accessed from will receive unique branding.
So for example, if there were two domains, reseller.com ... | Dynamically serve static content based on server name in Django | I'm writing a web application in Django that is accessed from multiple domains to the same IP address. The idea is that each domain the application is accessed from will receive unique branding.
So for example, if there were two domains, reseller.com and oem.com, and you went to oem.com, it would take you to to the sam... | [
"You're looking for the \"sites\" framework.\n",
"Not sure how to do simple rewrite rule in nginx. Aside from a template tag (if you are only swapping out static content, then I think a template tag is the way to go), if the sites are gonna be different at all, template-wise, you can handle it by writing a custom... | [
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007409666_django_python.txt |
Q:
Is this python code doing what I want it to do?
I have this code
import random
b = 20
x = random.randrange(0,b)
y = random.randrange(0,b)
ab = 0
xc = 0
while ab != 10:
if x != y:
x = random.randrange(0,b)
y = random.randrange(0,b)
xc = xc + 1
elif x == y:
print ab
p... | Is this python code doing what I want it to do? | I have this code
import random
b = 20
x = random.randrange(0,b)
y = random.randrange(0,b)
ab = 0
xc = 0
while ab != 10:
if x != y:
x = random.randrange(0,b)
y = random.randrange(0,b)
xc = xc + 1
elif x == y:
print ab
print 'number of tries out of', b, ' : ', xc
a... | [
"I'd say that you were somewhat unlucky.\nThe average there is 27.8. But if you pick two numbers between 0 and 20, you'd expect them to match about 1/20 of the time, and hence you expect to wait about 20 times before you get a match.\n",
"Check it with a larger number of iterations:\n#!/usr/bin/env python\nimpor... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007410964_python.txt |
Q:
How to unwrap wrapped lines in text file, reformat text file
I need help finding a Python solution to reformat the wrapped lines / rewrite the log file so there are no line breaks as described. That will allow me to continue to find on unbroken lines.
Every entry in the *.log is time stamped. Lines that are too lo... | How to unwrap wrapped lines in text file, reformat text file | I need help finding a Python solution to reformat the wrapped lines / rewrite the log file so there are no line breaks as described. That will allow me to continue to find on unbroken lines.
Every entry in the *.log is time stamped. Lines that are too long are wrapped as expected, however: The wrapped part is also time... | [
"for filename in validfilelist:\n logfile = open(filename, 'r')\n logfile_list = logfile.readlines()\n logfile.close()\n for line in logfile_list:\n if(line[21:].strip()[0] == '>'):\n #line_is_broken\n else:\n #line_is_not_broken\n\n",
"#!/usr/bin/python\n\nimport re\... | [
0,
0,
0
] | [] | [] | [
"file_io",
"python",
"python_2.7",
"text"
] | stackoverflow_0007411457_file_io_python_python_2.7_text.txt |
Q:
SQLAlchemy - create table template
I am just starting with SQLAlchemy and I have been wondering... I am going to have a lot of tables in my model. I would like to have own file for each table I will have in my model.
I am currently using following code:
from sqlalchemy import MetaData
from sqlalchemy.orm import sc... | SQLAlchemy - create table template | I am just starting with SQLAlchemy and I have been wondering... I am going to have a lot of tables in my model. I would like to have own file for each table I will have in my model.
I am currently using following code:
from sqlalchemy import MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalche... | [
"Marek,do one thing try defining the foreign key along with the schema name i.e 'test.t_vfilers.filer_id'(here 'test' is the schema name),this will solve the problem.\n",
"Have you remembered to import the different modules containing the models.\nIn my init.py I have at the bottom a ton of:\nfrom comparty3.mode... | [
1,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006803072_python_sqlalchemy.txt |
Q:
Compare two images in Monkeyrunner under windows
I am trying to compare two images that are taken from monkeyrunner.
I found that there is sameAs in monkeyrunner but it seems to not work.
There are two other ways, one is install package ImageMagick, but I don't know how to install and use it under windows, the use... | Compare two images in Monkeyrunner under windows | I am trying to compare two images that are taken from monkeyrunner.
I found that there is sameAs in monkeyrunner but it seems to not work.
There are two other ways, one is install package ImageMagick, but I don't know how to install and use it under windows, the useful information just could be used in Linux system.
An... | [
"I would use PhotoShop. Put 2 images in 2 layers, make \"Difference\" blending, and you may see difference in pixels visually, or when you choose Histogram from menu. Histogram values shown as zeros mean identical images.\nPShop layers:\n\nHistogram:\n\nVisual difference (may be harder to spot)\n\nThis test is from... | [
0
] | [] | [] | [
"imagemagick",
"monkeyrunner",
"python",
"python_imaging_library"
] | stackoverflow_0007410995_imagemagick_monkeyrunner_python_python_imaging_library.txt |
Q:
Can't get Crontab to work
I've been trying to get crontab to work for a while but it doesnt seem to want to work. The python script I need to initialise every midnight works perfectly from the command terminal. The location of my python script is:
/home/rv/ncbi-blast-2.2.23+/database_backup/backup.py
My contab ... | Can't get Crontab to work | I've been trying to get crontab to work for a while but it doesnt seem to want to work. The python script I need to initialise every midnight works perfectly from the command terminal. The location of my python script is:
/home/rv/ncbi-blast-2.2.23+/database_backup/backup.py
My contab looks like this:
SHELL=/bin/bas... | [
"If it works from your user account but not from cron it's usually not cron. The cron daemon tries to start your application but since it doesn't set up the environment variables it will fail. Create a simple shell script to setup your environment variables and starts your python script. (You don't have a PATH so y... | [
1,
1,
1,
0
] | [] | [] | [
"crontab",
"linux",
"python"
] | stackoverflow_0003095394_crontab_linux_python.txt |
Q:
Python - how to compute all nth roots of a number?
Is it possible to calculate n complex roots of a given number using Python? I've shortly checked it, and it looks like Python gives me wrong/incomplete answers:
(-27.0j)**(1.0/3.0) produces (2.598076211353316-1.4999999999999998j)
but proper roots should be 3 compl... | Python - how to compute all nth roots of a number? | Is it possible to calculate n complex roots of a given number using Python? I've shortly checked it, and it looks like Python gives me wrong/incomplete answers:
(-27.0j)**(1.0/3.0) produces (2.598076211353316-1.4999999999999998j)
but proper roots should be 3 complex numbers, because every non-zero number has n differen... | [
"I don't think standard Python will do this unless you write a function for it, but you can do it with Numpy:\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html\n",
"There are many multi-valued complex functions - functions that can have more than one value corresponding to any point in their d... | [
6,
4,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0007402488_math_python.txt |
Q:
Positional frequency counts for letters in cells in a csv file
I've been trying to use PHP / Python to figure out the most efficient way to parse the contents of a CSV file that has been uploaded to it through a web form. In short, it contains a series of strings that has already been split by letter and where the... | Positional frequency counts for letters in cells in a csv file | I've been trying to use PHP / Python to figure out the most efficient way to parse the contents of a CSV file that has been uploaded to it through a web form. In short, it contains a series of strings that has already been split by letter and where the first integer indicates the number of occurrences for that particul... | [
"The guys are correct that you should attempt this, especially since it's not very hard, also if it is homework (is it?)\nHere are enough hints:\n\nDefine a base class Counter using collections.defaultdict to implement the collections.Counter just like the new Counter in 3.1. It must have an update() method, you ca... | [
0
] | [] | [] | [
"counter",
"csv",
"design_patterns",
"php",
"python"
] | stackoverflow_0007410567_counter_csv_design_patterns_php_python.txt |
Q:
Joining a list in python with different conditions
I want to join a list with a conditional statement such as:
str = "\n".join["a" if some_var is True, "b", "c", "d" if other_var==1, "e"]
Each element has a different conditional clause (if at all) so a normal list comprehension is not suitable in this case.
The s... | Joining a list in python with different conditions | I want to join a list with a conditional statement such as:
str = "\n".join["a" if some_var is True, "b", "c", "d" if other_var==1, "e"]
Each element has a different conditional clause (if at all) so a normal list comprehension is not suitable in this case.
The solution I thought of is:
lst = ["a" if some_var is True ... | [
"If each element should only be added to a list if a condition is met, state each condition separately and add the element if it's met. A list comprehension is for when you have an existing list and you want to process the elements in it in some way.\nlst = []\nif some_var is True:\n lst.append('a')\nlst.extend(... | [
1,
0,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0007412773_list_comprehension_python.txt |
Q:
Python. How to fix error: "print tablecsv.read() AttributeError: 'tuple' object has no attribute 'read"
I lern Python and try to do parcer for html table and then I wont to create .csv file for import data into mySQL.
>>> htmlread = handlestatbydate.read()
>>> soup = BeautifulSoup("".join(htmlread))
>>> souptable ... | Python. How to fix error: "print tablecsv.read() AttributeError: 'tuple' object has no attribute 'read" | I lern Python and try to do parcer for html table and then I wont to create .csv file for import data into mySQL.
>>> htmlread = handlestatbydate.read()
>>> soup = BeautifulSoup("".join(htmlread))
>>> souptable = soup('tbody', limit=2)[1].findAll('tr')
>>> souptablestr = ''.join(str(t) for t in souptable)
>>> reclearby... | [
"You have missed the method name here: tablecsv = (r'/tmp/table.csv', 'r') i.e. you probably want to open the file .e.g tablecsv = open(r'/tmp/table.csv', 'r')\nYou should also close the file after writing before reading from it with tablecsv.close()\nIf you just have a list of items in brackets e.g. (r'/tmp/table.... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0007413109_csv_python.txt |
Q:
django list of unicode string to pure string
I'm using Django and Python
unicode_countries = request.POST.getlist(u'countries')
Returns [u'ai', u'ag', u'aw', u'bs']
My goals it to convert unicode_countries to MySQL IN string, which should look like 'ai', 'ag', 'aw', 'bs' which I will use in a MySQL statement as "... | django list of unicode string to pure string | I'm using Django and Python
unicode_countries = request.POST.getlist(u'countries')
Returns [u'ai', u'ag', u'aw', u'bs']
My goals it to convert unicode_countries to MySQL IN string, which should look like 'ai', 'ag', 'aw', 'bs' which I will use in a MySQL statement as "WHERE countries in ('ai', 'ag', 'aw', 'bs')"
Pleas... | [
"No conversion needed.\nMyModel.objects.filter(countries__in=unicode_countries)\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007412610_django_python.txt |
Q:
Are there any fundamental differences to use numpy.zeros or zeros?
I have downloaded the python 2.6 and installed numpy-1.6.1-win32-superpack-python2.6 and scipy-0.9.0-win32-superpack-python2.6. It is running on a Window with window 2000 professional as OS.
However, when I run python, with the following commands,... | Are there any fundamental differences to use numpy.zeros or zeros? | I have downloaded the python 2.6 and installed numpy-1.6.1-win32-superpack-python2.6 and scipy-0.9.0-win32-superpack-python2.6. It is running on a Window with window 2000 professional as OS.
However, when I run python, with the following commands, following error message appear, could you mind to teach me how to solve... | [
"The error message says it all: You're using a name that hasn't been defined yet.\nIf you import numpy, and numpy contains a zeros() function, then you must call it as numpy.zeros(). If you want to refer to zeros() directly, you can from numpy import zeros.\nIf you pass the variable K to a function, K must have bee... | [
2,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007413326_numpy_python.txt |
Q:
Loop based on range in Django templates
I saw a question that is similar to my one but not the same, so I ask about it here.
Assume, I have an SELECT with a list of OPTION elements that I want to fill with years, for example, from 1920 to current year. How can I start iterating not from zero to some value but from... | Loop based on range in Django templates | I saw a question that is similar to my one but not the same, so I ask about it here.
Assume, I have an SELECT with a list of OPTION elements that I want to fill with years, for example, from 1920 to current year. How can I start iterating not from zero to some value but from some value to some another value? For exampl... | [
"You can pass range(1920, 2012) from the view.\n"
] | [
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0007412762_django_django_templates_python.txt |
Q:
Too many arguments in my function - Python
I am trying to access my function in a dll and pass by value as integer in it. But I am getting a ValueError as:
Procedure probably called with too many arguments (4 bytes in excess)
My python .py script is as below:
func2.restype = c_int
func2.argtypes = [c_int]
func2(3... | Too many arguments in my function - Python | I am trying to access my function in a dll and pass by value as integer in it. But I am getting a ValueError as:
Procedure probably called with too many arguments (4 bytes in excess)
My python .py script is as below:
func2.restype = c_int
func2.argtypes = [c_int]
func2(3)
...
My actual function in the dll is just a s... | [
"Looks weird because integer should be automatically cast, but try with a func2(c_int(3))\nEDIT : \nAccording to the ctypes doc, this exception could be raised because of a wrong calling convention (cdecl instead of stdcall). But the function is still called (just a sort of warning :s)\nBe sure of you declaration i... | [
4
] | [] | [] | [
"dll",
"function",
"python"
] | stackoverflow_0007413894_dll_function_python.txt |
Q:
Calling a function at datetime in Python
What is a good way to call a function at datetime in Python?
There 3 ways that I know of:
"Are we there yet?!" (check at if date has passed at interval (time.sleep(interval)))
This is obviously bad. It can only be precise if interval is low, which becomes inefficient.
Slee... | Calling a function at datetime in Python | What is a good way to call a function at datetime in Python?
There 3 ways that I know of:
"Are we there yet?!" (check at if date has passed at interval (time.sleep(interval)))
This is obviously bad. It can only be precise if interval is low, which becomes inefficient.
Sleep off the difference (time.sleep(timedelta.sec... | [
"If this is something that might be six months out like you said, a chron job is probably more suitable than keeping a python program running the whole time.\n",
"I use the gobject main loop, but any library with an event loop should have this ability.\n",
"It might be a good idea to use a cron job.\nyou can ed... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007412941_python.txt |
Q:
API of a package in python. In __init__.py?
I have written a python package which consists of several .py files which contain classes and so on. I want to expose it to client using "Facade" pattern. So I don't want clients to learn all internal classes but only methods exposed by this API interface.
Question is: w... | API of a package in python. In __init__.py? | I have written a python package which consists of several .py files which contain classes and so on. I want to expose it to client using "Facade" pattern. So I don't want clients to learn all internal classes but only methods exposed by this API interface.
Question is: where do I put this api ? Do I define a file api.p... | [
"The most common choice is to use __init__.py -- it's worth hiving off to a module of its own (or more) only if it's complex enough to warrant it (then it wouldn't be much of a Facade;-) or, more importantly, if you provide alternative APIs (a simplified one with reduced functionality but greater ease of use, and a... | [
11,
8,
7
] | [] | [] | [
"python"
] | stackoverflow_0003271794_python.txt |
Q:
USBView/ Device manager in python
How can I access Device Manager in python, so that i can get the usb device's serial number/other info through python?
A:
Instead of using the Device Manager (A graphical application), you can programmatically access information about USB devices via PyUSB:
import usb.core
allDe... | USBView/ Device manager in python | How can I access Device Manager in python, so that i can get the usb device's serial number/other info through python?
| [
"Instead of using the Device Manager (A graphical application), you can programmatically access information about USB devices via PyUSB:\nimport usb.core\nallDevs = usb.core.find(find_all=True)\n\nNow, iterate over allDevs to get information about connected devices.\n"
] | [
2
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0007414492_cmd_python.txt |
Q:
A simple python program not being able to access my dll
I have created a simple MFC .dll file and I am able to access it via another MFC Application program. I was trying to do the same thing using Python 3.2.2 but after I load my library, It does not detect the function in my dll and gives an error like:
Trac... | A simple python program not being able to access my dll | I have created a simple MFC .dll file and I am able to access it via another MFC Application program. I was trying to do the same thing using Python 3.2.2 but after I load my library, It does not detect the function in my dll and gives an error like:
Traceback (most recent call last):
File "<interactive input>", ... | [
"I have been able to get a hold of my problem and have solved it. For those who might expect this in the future, I would just like to paste the python script code in order to make your functions accessible in your python scripts. The way to go with your C++ function is obviously to declare this in your .dll file.\n... | [
0
] | [] | [] | [
"dll",
"mfc",
"python",
"scripting",
"visual_c++"
] | stackoverflow_0007390732_dll_mfc_python_scripting_visual_c++.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.