content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How do I use udev to find info about inserted video media (e.g. DVDs)
I'm trying to port an application from using HAL to using pure udev. It is written in python and will use the gudev library, though I would love to see examples in any language. I'm able to get all attached video devices (such as cameras) via:
i... | How do I use udev to find info about inserted video media (e.g. DVDs) | I'm trying to port an application from using HAL to using pure udev. It is written in python and will use the gudev library, though I would love to see examples in any language. I'm able to get all attached video devices (such as cameras) via:
import gudev
client = gudev.Client(["video4linux"])
for device in client.ge... | [
"Have a look at the device properties:\nimport gudev\n\nclient = gudev.Client(['block'])\nfor device in client.query_by_subsystem(\"block\"):\n print device\n for device_key in device.get_property_keys():\n print \" property %s: %s\" % (device_key, device.get_property(device_key))\n print\n\n"
] | [
4
] | [] | [] | [
"python",
"udev"
] | stackoverflow_0002861098_python_udev.txt |
Q:
Integrating Jython Cpython
I am about to begin a project where I will likely use PyQt or Pyside.
I will need to interface with a buggy 3rd party piece of server software that provides C++ and Java APIs. The Java APIs are a lot easier to use because you get Exceptions where with the C++ libraries you get segfaults... | Integrating Jython Cpython | I am about to begin a project where I will likely use PyQt or Pyside.
I will need to interface with a buggy 3rd party piece of server software that provides C++ and Java APIs. The Java APIs are a lot easier to use because you get Exceptions where with the C++ libraries you get segfaults. Also, the Python bindings to ... | [
"If you want to maintain complete isolation and increase your robustness (the 3rd party library going down and not taking your client, and if it's buggy I would recommend that) then perhaps something like CORBA is the way forwards. Don't forget that Java comes with a CORBA implementation as standard, so you just ne... | [
0,
0
] | [] | [] | [
"jython",
"process",
"pyqt",
"python",
"qt"
] | stackoverflow_0002860650_jython_process_pyqt_python_qt.txt |
Q:
Distributing an executable zip file with __main__.py, how to access extra data?
I'm doing a little program and I want to distribute it using this recipe:
single directory with __main__.py in it
zip this directory and adding a shebang on it #!/usr/bin/env python
making it executable
The problem is that in this pa... | Distributing an executable zip file with __main__.py, how to access extra data? | I'm doing a little program and I want to distribute it using this recipe:
single directory with __main__.py in it
zip this directory and adding a shebang on it #!/usr/bin/env python
making it executable
The problem is that in this package I have also extra files (I'm using pygtk toolkit and I need images and ui xml f... | [
"I figured out by myself, It's sufficient to use pkgutil.get_data to access the data inside a package.\n"
] | [
8
] | [] | [] | [
"packaging",
"python",
"zipapp"
] | stackoverflow_0002859413_packaging_python_zipapp.txt |
Q:
How do I convert this Python punctuation-stripping function to JavaScript?
Please can anyone translate this python code into javascript.
#
def strip_punctuation(s):
#
for c in ',.":;!%$':
#
while s.find(c) is not -1:
#
s.replace(c, '')
A:
function strip_punctuation(s) {
return s.repla... | How do I convert this Python punctuation-stripping function to JavaScript? | Please can anyone translate this python code into javascript.
#
def strip_punctuation(s):
#
for c in ',.":;!%$':
#
while s.find(c) is not -1:
#
s.replace(c, '')
| [
"function strip_punctuation(s) {\n return s.replace(/[,.\":;!%$]/g, \"\");\n}\n\n"
] | [
12
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002861528_javascript_python.txt |
Q:
How to determine subprocess.Popen() failed when shell=True
Windows version of Python 2.6.4: Is there any way to determine if subprocess.Popen() fails when using shell=True?
Popen() successfully fails when shell=False
>>> import subprocess
>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
Traceback (m... | How to determine subprocess.Popen() failed when shell=True | Windows version of Python 2.6.4: Is there any way to determine if subprocess.Popen() fails when using shell=True?
Popen() successfully fails when shell=False
>>> import subprocess
>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
Traceback (most recent call last):
File ">>> pyshell#258", line 1, in <mod... | [
"returncode will work, although it will be None until you've called p.poll(). poll() itself will return the error code, so you can just do\nif a.poll() != 0:\n print \":(\"\n\n",
"In the first case it fails to start, in the second - it successfully starts shell which, in turn, fails to execute the application.... | [
16,
5
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0002861548_popen_python_subprocess.txt |
Q:
template files evaluation in python
I am trying to use python for translating a set of templates to a set of configuration files based on values taken from a main configuration file. However, I am having certain issues. Consider the following example of a template file.
file1.cfg.template
%(CLIENT1)s %(HOST1)s %(... | template files evaluation in python | I am trying to use python for translating a set of templates to a set of configuration files based on values taken from a main configuration file. However, I am having certain issues. Consider the following example of a template file.
file1.cfg.template
%(CLIENT1)s %(HOST1)s %(PORT1)d C %(COMPID1)s
%(CLIENT2)s %(HOS... | [
"Sounds like you may have outgrown your originally simple home-grown templating solution. Maybe you should move to something like Jinja? It might be less of a headache to simply implement a third-party solution than it would be to create/continue to maintain your own solution.\nOther options:\n\ncheetah\nmako\n\n... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002861543_python.txt |
Q:
Converting datetime.ctime() values to Unicode
I would like to convert datetime.ctime() values to Unicode.
Using Python 2.6.4 running under Windows I can set my locale to Spanish like below:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )
Then I can pass %a, %A, %b, and %B to ctime() to get day and ... | Converting datetime.ctime() values to Unicode | I would like to convert datetime.ctime() values to Unicode.
Using Python 2.6.4 running under Windows I can set my locale to Spanish like below:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )
Then I can pass %a, %A, %b, and %B to ctime() to get day and month names and abbreviations.
>>> import datetime... | [
"Converting with unicode() or string.decode() like in your example should work. The only problem should be that in your example you use the default locale's encoding even though you set the locale to something different before. If you use locale.getlocale()[1] instead of locale.getdefaultlocale()[1] you should get ... | [
3,
2,
0
] | [] | [] | [
"datetime",
"python",
"unicode"
] | stackoverflow_0002861583_datetime_python_unicode.txt |
Q:
parse this directory path without losing slash
I have a wxPython application. I am taking in a directory path from a textbox using GetValue().
I notice that while trying to write this string to a variable:
"C:\Documents and Settings\tchan\Desktop\InputFile.xls",
python sees the string as
'C:\\Documents and Setti... | parse this directory path without losing slash | I have a wxPython application. I am taking in a directory path from a textbox using GetValue().
I notice that while trying to write this string to a variable:
"C:\Documents and Settings\tchan\Desktop\InputFile.xls",
python sees the string as
'C:\\Documents and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash ... | [
"I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string.\nrawpath = \"%r\" % path\n\nThe resulting r... | [
4,
2,
0
] | [] | [] | [
"escaping",
"python",
"string",
"wxpython"
] | stackoverflow_0002860233_escaping_python_string_wxpython.txt |
Q:
Viewing Python's shelve objects in PHP
I am using Python for indexing utilizing the shelve functionality and I was wondering whether it was possible to open and read the files in PHP.
I checked out the PHP Shelve option and it doesn't seem to be working on PHP 5.X I am getting (when running the example they gave ... | Viewing Python's shelve objects in PHP | I am using Python for indexing utilizing the shelve functionality and I was wondering whether it was possible to open and read the files in PHP.
I checked out the PHP Shelve option and it doesn't seem to be working on PHP 5.X I am getting (when running the example they gave me)
PHP Fatal error: Cannot pass parameter... | [
"I'm not sure how mature or well developed that project is, but, if I had that need, I would try the Python In PHP project.\n"
] | [
1
] | [] | [] | [
"php",
"python",
"shelve"
] | stackoverflow_0002862016_php_python_shelve.txt |
Q:
building a pairwise matrix in scipy/numpy in Python from dictionaries
I have a dictionary whose keys are strings and values are numpy arrays, e.g.:
data = {'a': array([1,2,3]), 'b': array([4,5,6]), 'c': array([7,8,9])}
I want to compute a statistic between all pairs of values in 'data' and build an n by x matrix ... | building a pairwise matrix in scipy/numpy in Python from dictionaries | I have a dictionary whose keys are strings and values are numpy arrays, e.g.:
data = {'a': array([1,2,3]), 'b': array([4,5,6]), 'c': array([7,8,9])}
I want to compute a statistic between all pairs of values in 'data' and build an n by x matrix that stores the result. Assume that I know the order of the keys, i.e. I h... | [
"You could use a nested loop, or a list comprehension like:\nresult = [[compute_stat(data[row], data[col]) for col in labels]\n for row in labels]\n\n",
"Convert the result list into a matrix and then adjust the shape.\nmyMatrix = array(result) # or use matrix(result)\nmyMatrix.shape = (len(labels), len(... | [
2,
2
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0002861862_numpy_python_scipy.txt |
Q:
Searching for a track on iTunes
I'd like to search for tracks on iTunes using a Python script on Mac OS/X. I found a way to access the iTunes application through:
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
but I haven't figured out (yet) the way to perform searches. A little help... | Searching for a track on iTunes | I'd like to search for tracks on iTunes using a Python script on Mac OS/X. I found a way to access the iTunes application through:
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
but I haven't figured out (yet) the way to perform searches. A little help appreciated.
Disclaimer: OS/X newbie... | [
"You might want to check out appscript (note, you'll need ASDictionary for online help):\n>>> import appscript\n>>> iTunes = appscript.app(\"iTunes\")\n>>> lib = iTunes.playlists['Library']\n>>> for trk in lib.tracks():\n... if re.search(\"test\", trk.name()):\n... print trk.name()\n\nThis might give yo... | [
4,
0,
0
] | [] | [] | [
"itunes",
"macos",
"python",
"scripting"
] | stackoverflow_0002752225_itunes_macos_python_scripting.txt |
Q:
How do I get an overview and a methodology for programming in Python
I've started to learn Python and programming from scratch. I have not programmed before so it's a new experience. I do seem to grasp most of the concepts, from variables to definitions and modules. I still need to learn a lot more about what the ... | How do I get an overview and a methodology for programming in Python | I've started to learn Python and programming from scratch. I have not programmed before so it's a new experience. I do seem to grasp most of the concepts, from variables to definitions and modules. I still need to learn a lot more about what the different libraries and modules do and also I lack knowledge on OOP and cl... | [
"The MIT Intro to Computer Science course on the MIT OpenCourseWare website was taught using Python. There are 24 lectures available as videos that you can watch for free.\nIt's kind of academic to be sure, but it would give you a very solid foundation to start from.\n",
"Start working your way through the Essent... | [
4,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002861575_python.txt |
Q:
Lighting Fast CMS, a Django based CMS. Any experiences?
I've just came across Lighting Fast CMS, which seems to be very promising Django based content management system. Documentation seem to be very good, even though it is still in beta stage. It also has very nice buildout based installation. Also the core Comp... | Lighting Fast CMS, a Django based CMS. Any experiences? | I've just came across Lighting Fast CMS, which seems to be very promising Django based content management system. Documentation seem to be very good, even though it is still in beta stage. It also has very nice buildout based installation. Also the core Components of it seem to be nicely decoupled.
Does anyone have a... | [] | [] | [
"I do not know anything about lfc, but you can also give django-cms a try!\nhttp://www.django-cms.org\n"
] | [
-1
] | [
"content_management_system",
"django",
"python"
] | stackoverflow_0002862061_content_management_system_django_python.txt |
Q:
Difficulties with Django on Google App Engine
I have a Django 1.1.1 project that works fine. I'm trying to import it to Google App Engine.
I'm trying to follow these instructions.
I run it on the dev server, and I get an import error:
ImportError at /
No module named mysite.urls
This is the folder structure of my... | Difficulties with Django on Google App Engine | I have a Django 1.1.1 project that works fine. I'm trying to import it to Google App Engine.
I'm trying to follow these instructions.
I run it on the dev server, and I get an import error:
ImportError at /
No module named mysite.urls
This is the folder structure of mysite/:
app.yaml
<DIR> myapp
index.yaml
mai... | [
"Try changing ROOT_URLCONF to just 'urls'. I don't think the parent directory of your app (in the App Engine sense, not the Django sense) directory is on sys.path when running on App Engine, which means that it doesn't see mysite as a Python package/module.\nEDIT to keep up with edited question:\nNow it sounds lik... | [
2,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002861024_django_google_app_engine_python.txt |
Q:
How to format date when I load data from google-app-engine?
I use remote_api to load data from Google App Engine.
appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld
The setting is:
class AlbumExporter(bulkloader.Exporter):
def __init__(self):
... | How to format date when I load data from google-app-engine? | I use remote_api to load data from Google App Engine.
appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld
The setting is:
class AlbumExporter(bulkloader.Exporter):
def __init__(self):
bulkloader.Exporter.__init__(self, 'Greeting',
... | [
"Looks like you're getting a truncation at the space in the third column when you say\n('date', str, None),\n\n(the other attempt is clearly wrong because you're getting a datetime and you can't strptime that!-). If you want the date as a string, try:\n('date', lambda dt: str(dt.date()), None),\n\nor, change strpt... | [
1
] | [] | [] | [
"format",
"google_app_engine",
"load",
"python"
] | stackoverflow_0002862460_format_google_app_engine_load_python.txt |
Q:
Estimating the boundary of arbitrarily distributed data
I have two dimensional discrete spatial data. I would like to make an approximation of the spatial boundaries of this data so that I can produce a plot with another dataset on top of it.
Ideally, this would be an ordered set of (x,y) points that matplotlib ... | Estimating the boundary of arbitrarily distributed data | I have two dimensional discrete spatial data. I would like to make an approximation of the spatial boundaries of this data so that I can produce a plot with another dataset on top of it.
Ideally, this would be an ordered set of (x,y) points that matplotlib can plot with the plt.Polygon() patch.
My initial attempt is... | [
"I think what you are looking for is the Convex Hull of the data That will give a set of points that if connected will mean that all your points are on or inside the connected points\n",
"I may have mixed something, but what's the motivation for simply not determining the maximum and minimum x and y level? Unless... | [
2,
0
] | [] | [] | [
"python",
"sampling",
"spatial"
] | stackoverflow_0002856222_python_sampling_spatial.txt |
Q:
Show escaped string as Unicode in Python
i have just known Python for few days. Unicode seems to be a problem with Python.
i have a text file stores a text string like this
'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1'
i can read the file and print the string out but it displays i... | Show escaped string as Unicode in Python | i have just known Python for few days. Unicode seems to be a problem with Python.
i have a text file stores a text string like this
'\u0110\xe8n \u0111\u1ecf n\xfat giao th\xf4ng Ng\xe3 t\u01b0 L\xe1ng H\u1ea1'
i can read the file and print the string out but it displays incorrectly.
How can i print it out to screen c... | [
">>> x=r'\\u0110\\xe8n \\u0111\\u1ecf n\\xfat giao th\\xf4ng Ng\\xe3 t\\u01b0 L\\xe1ng H\\u1ea1'\n>>> u=unicode(x, 'unicode-escape')\n>>> print u\nĐèn đỏ nút giao thông Ngã tư Láng Hạ\n\nThis works in a Mac, where Terminal.App correctly makes sys.stdout.encoding be set to utf-8. If your platform doesn't set that a... | [
8,
1,
0
] | [] | [] | [
"escaping",
"python",
"unicode"
] | stackoverflow_0002855661_escaping_python_unicode.txt |
Q:
I'm searching for a messaging platform (like XMPP) that allows tight integration with a web application
At the company I work for, we are building a cluster of web applications for collaboration. Things like accounting, billing, CRM etc.
We are using a RESTfull technique:
For database we use CouchDB
Different app... | I'm searching for a messaging platform (like XMPP) that allows tight integration with a web application | At the company I work for, we are building a cluster of web applications for collaboration. Things like accounting, billing, CRM etc.
We are using a RESTfull technique:
For database we use CouchDB
Different applications communicate with one another and with the database via http.
Besides, we have a single sign on solu... | [
"Like frx suggested above, the StropheJS folks have an excellent book about web+xmpp coding but since you mentioned you have no experience in this type of coding I would suggest talking to some folks who have :) It will save you time in the long run - not that I'm saying don't try to implement what frx outlines, i... | [
1,
0
] | [] | [] | [
"couchdb",
"ejabberd",
"pylons",
"python",
"xmpp"
] | stackoverflow_0002833957_couchdb_ejabberd_pylons_python_xmpp.txt |
Q:
How do I get the Math equation of Python Algorithm?
ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x > 0 add all numbers together from 1 to x.
def intsum(x):
if x > 0:
return x + intsum(x - 1)... | How do I get the Math equation of Python Algorithm? | ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given x > 0 add all numbers together from 1 to x.
def intsum(x):
if x > 0:
return x + intsum(x - 1)
else:
return 0
intsum(10)
55
first what is this ... | [
"This is recursion, though for some reason you're labeling it like it's factorial.\nIn any case, the sum from 1 to n is also simply: \nn * ( n + 1 ) / 2\n(You can special case it for negative values if you like.)\n",
"Transforming recursively-defined sequences of integers into ones that can be expressed in a clo... | [
15,
8,
4,
3,
3,
3,
1,
1
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0002861996_algorithm_math_python.txt |
Q:
Replacing empty csv column values with a zero
So I'm dealing with a csv file that has missing values.
What I want my script to is:
#!/usr/bin/python
import csv
import sys
#1. Place each record of a file in a list.
#2. Iterate thru each element of the list and get its length.
#3. If the length is less than one re... | Replacing empty csv column values with a zero | So I'm dealing with a csv file that has missing values.
What I want my script to is:
#!/usr/bin/python
import csv
import sys
#1. Place each record of a file in a list.
#2. Iterate thru each element of the list and get its length.
#3. If the length is less than one replace with value x.
reader = csv.reader(open(sys.... | [
"Change your code:\nfor row in reader:\n for x in row[:]:\n if len(x)< 1:\n x = 0\n print x\n\ninto:\nfor row in reader:\n for i, x in enumerate(row):\n if len(x)< 1:\n x = row[i] = 0\n print x\n\nNot s... | [
4,
1
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0002862709_csv_list_python.txt |
Q:
How to pass variables using Unittest suite
Hello I have test's using unittest. I have a test suite and I am trying to pass variables through into each of the tests. The below code shows the test suite used.
class suite():
def suite(self): #Function stores all the modules to be tested
modules_to_test ... | How to pass variables using Unittest suite | Hello I have test's using unittest. I have a test suite and I am trying to pass variables through into each of the tests. The below code shows the test suite used.
class suite():
def suite(self): #Function stores all the modules to be tested
modules_to_test = ('testmodule1', 'testmodule2')
alltest... | [
"Passing interactive values on the command line is not really in line with the intention of automated unit tests. How about using the ConfigParser library module and have your TestCase subclass's __init__ method load some variable test input data that way?\nOf course, sticking with the code you have, what about ei... | [
4
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0002812132_python_unit_testing.txt |
Q:
Inverting image using the Python Image Library module
I'm interested in learning how to invert (make a negative of) an image using the python image libary module.
I cannot however, use the ImageOps function 'invert.' I need another solution, using the RGB values. I've searched and tried to no avail.
A:
Just subt... | Inverting image using the Python Image Library module | I'm interested in learning how to invert (make a negative of) an image using the python image libary module.
I cannot however, use the ImageOps function 'invert.' I need another solution, using the RGB values. I've searched and tried to no avail.
| [
"Just subtract each RGB value from 255 (or the max) to obtain the new RGB values.\nthis post tells you how to get the RBG values from a picture.\n",
"One obvious way is to use Image.getpixel and Image.putpixel, for RGB, each should be a tuple of three integers. You can get (255-r, 255-g, 255-b), then put it back.... | [
0,
0,
0
] | [] | [] | [
"image_manipulation",
"python",
"python_imaging_library"
] | stackoverflow_0002862659_image_manipulation_python_python_imaging_library.txt |
Q:
POSTing a form using Python and Curl
I am relatively new (as in a few days) to Python - I am looking for an example that would show me how to post a form to a website (say www.example.com).
I already know how to use Curl. Infact, I have written C+++ code that does exactly the same thing (i.e. POST a form using Cur... | POSTing a form using Python and Curl | I am relatively new (as in a few days) to Python - I am looking for an example that would show me how to post a form to a website (say www.example.com).
I already know how to use Curl. Infact, I have written C+++ code that does exactly the same thing (i.e. POST a form using Curl), but I would like some starting point (... | [
"Here is an example using urllib and urllib2 for both POST and GET:\nPOST - If urlopen() has a second parameter then it is a POST request.\nimport urllib\nimport urllib2\n\nurl = 'http://www.example.com'\nvalues = {'var' : 500}\n\ndata = urllib.urlencode(values)\nresponse = urllib2.urlopen(url, data)\npage = respon... | [
2,
0,
0
] | [] | [] | [
"curl",
"python"
] | stackoverflow_0002863260_curl_python.txt |
Q:
Uploading file from file object with PyCurl
I'm attempting to upload a file like this:
import pycurl
c = pycurl.Curl()
values = [
("name", "tom"),
("image", (pycurl.FORM_FILE, "tom.png"))
]
c.setopt(c.URL, "http://upload.com/submit")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
This works fine.... | Uploading file from file object with PyCurl | I'm attempting to upload a file like this:
import pycurl
c = pycurl.Curl()
values = [
("name", "tom"),
("image", (pycurl.FORM_FILE, "tom.png"))
]
c.setopt(c.URL, "http://upload.com/submit")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
This works fine. However, this only works if the file is local. ... | [
"It might be possible in perfect situations to basically connect the two streams, but it wouldn't be a very robust solution. There are a bunch of ugly boundary conditions:\n\nThe response socket might still be\nreceiving data, and/or be stalled,\nthus causing you to starve out and\nbreak the POST (because PycURL i... | [
4
] | [] | [] | [
"pycurl",
"python"
] | stackoverflow_0002863406_pycurl_python.txt |
Q:
The anatomy of a Python web project: development, packaging, deployment
I'm new to Python (from Java+Ant) and was wondering if someone could detail how to best use Fabric+Pip+Virtualenv to set up a Python web application package skeleton.
The end goal is to be able to do any of the following with a single command:... | The anatomy of a Python web project: development, packaging, deployment | I'm new to Python (from Java+Ant) and was wondering if someone could detail how to best use Fabric+Pip+Virtualenv to set up a Python web application package skeleton.
The end goal is to be able to do any of the following with a single command:
Set up a development environment on a fresh dev box (installing all deps)
R... | [
"Check out my answer here. It doesn't address all of your questions (mostly the first bullet-point, in fact), but hopefully it gets you started.\n",
"Keeping it framework agnostic will probably be quite hard. \nBut maybe you'll find the following paster templates (for Django projects though) quite useful too. htt... | [
2,
0
] | [] | [] | [
"deployment",
"fabric",
"python",
"virtualenv"
] | stackoverflow_0002848942_deployment_fabric_python_virtualenv.txt |
Q:
Why doesn't appending binary pickles work?
I know this isn't exactly how the pickle module was intended to be used, but I would have thought this would work. I'm using Python 3.1.2
Here's the background code:
import pickle
FILEPATH='/tmp/tempfile'
class HistoryFile():
"""
Persistent store of a history fi... | Why doesn't appending binary pickles work? | I know this isn't exactly how the pickle module was intended to be used, but I would have thought this would work. I'm using Python 3.1.2
Here's the background code:
import pickle
FILEPATH='/tmp/tempfile'
class HistoryFile():
"""
Persistent store of a history file
Each line should be a separate Python o... | [
"Why would you think appending binary pickles would produce a single pickle?! Pickling lets you put (and get back) several items one after the other, so obviously it must be a \"self-terminating\" serialization format. Forget lines and just get them back! For example:\n>>> import pickle\n>>> import cStringIO\n>>... | [
6,
4
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0002857970_pickle_python.txt |
Q:
sqlalchemy natural sorting
Currently, i am querying with this code: meta.Session.query(Label).order_by(Label.name).all()
and it returns me objects sorted by Label.name in this manner ['1','7','1a','5c']. Is there a way i can have the objects returned in the order with their Label.name sorted like this ['1','1a','... | sqlalchemy natural sorting | Currently, i am querying with this code: meta.Session.query(Label).order_by(Label.name).all()
and it returns me objects sorted by Label.name in this manner ['1','7','1a','5c']. Is there a way i can have the objects returned in the order with their Label.name sorted like this ['1','1a','5c','7']
Thanks!
| [
"Sorting is done by the database. If you database doesn't support natural sorting your are out of luck and have to sort your rows manually after retrieving them via sqlalchemy.\n"
] | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002863748_python_sqlalchemy.txt |
Q:
Autoproperty failing in IronPython works in Python?
I have this following python code, it works fine in python but fails with the following error in IronPython 2.6 any ideas as to why?
======================================================================
ERROR: testAutoProp (__main__.testProperty)
-----------... | Autoproperty failing in IronPython works in Python? | I have this following python code, it works fine in python but fails with the following error in IronPython 2.6 any ideas as to why?
======================================================================
ERROR: testAutoProp (__main__.testProperty)
--------------------------------------------------------------------... | [
"Just looking at your code and traceback, it looks to me as though lambdas on IronPython have a name such as <lambda$48> instead of just <lambda>. That means your test if self.fset.__name__ == '<lambda>' or not self.fset.__name__: will take the wrong branch.\nTry:\nif self.fset.__name__.startswith('<lambda') or not... | [
3
] | [] | [] | [
"ironpython",
"lambda",
"overriding",
"properties",
"python"
] | stackoverflow_0002863750_ironpython_lambda_overriding_properties_python.txt |
Q:
Unable to control requests for static files on Google App Engine
My simple GAE app is not redirecting to the /static directory for requests when url is multiple levels.
Dir structure:
/app/static/css/main.css
App:
I have two handlers one for /app and one for /app/new
app.yaml:
handlers:
- url: /static
static_... | Unable to control requests for static files on Google App Engine | My simple GAE app is not redirecting to the /static directory for requests when url is multiple levels.
Dir structure:
/app/static/css/main.css
App:
I have two handlers one for /app and one for /app/new
app.yaml:
handlers:
- url: /static
static_dir: static
- url: /app/static/(.*)
static_dir: static\1
- url: /a... | [
"In HTML an internal link starting with \"/\" is an absolute link, a link starting without a \"/\" is a relative link. So if you are requesting:\n/app\nand have a relative link:\nstatic/css/main.css\nthe request becomes:\n/static/css/main.css\nthe relative link uses the \"/\" in \"/app\" because the \"app\" part is... | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002853915_google_app_engine_python.txt |
Q:
gdata youtube api 302 'The document has moved'
I'm trying to get YouTube feeds with the python gdata library.
Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, an... | gdata youtube api 302 'The document has moved' | I'm trying to get YouTube feeds with the python gdata library.
Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, and any other) I get:
RequestError: {'status': 302, 'b... | [
"Solved.\nYou need to add ssl=False to the YouTubeService object. Don't see nothing about it in the docs though.\nyt = gdata.youtube.service.YouTubeService()\nyt.ssl = False\n\n"
] | [
1
] | [] | [] | [
"api",
"gdata",
"python",
"youtube",
"youtube_api"
] | stackoverflow_0002863785_api_gdata_python_youtube_youtube_api.txt |
Q:
flymake and python-execute-region
I got an error from flymake-get-file-name-mode-and-masks "Invalid file name" when I have called py-execute-region (bind to C-c |). Also void buffer with name like /tmp/python-3434.py appears.
My flymake setup:
(when (load "flymake" t)
(defun flymake-pylint-init ()
(let* ((temp-... | flymake and python-execute-region | I got an error from flymake-get-file-name-mode-and-masks "Invalid file name" when I have called py-execute-region (bind to C-c |). Also void buffer with name like /tmp/python-3434.py appears.
My flymake setup:
(when (load "flymake" t)
(defun flymake-pylint-init ()
(let* ((temp-file (flymake-init-create-temp-buffer-c... | [
"I had this same problem, and solved it by making emacs not load flymake for temporary buffers passed to the interpreter. I\nThe relevant bits of my flymake setup for Python:\n(when (load \"flymake\" t)\n (defun flymake-python-init ()\n (let* ((temp-file (flymake-init-create-temp-buffer-copy\n ... | [
4
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0002681203_emacs_python.txt |
Q:
Executing Multiple Lines in Python
When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks
>>> if (n/2) *... | Executing Multiple Lines in Python | When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks
>>> if (n/2) * 2 == n:;
print 'Even';
... | [
"Your indentation is wrong. Try this:\n>>> if (n/2) * 2 == n:\n... print 'Even'\n... else: print 'Odd'\n\nAlso you might want to write it on four lines:\n>>> if (n/2) * 2 == n:\n... print 'Even'\n... else:\n... print 'Odd'\n\nOr even just one line:\n>>> print 'Even' if (n/2) * 2 == n else 'Odd'\n\n",
... | [
9,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002863526_python.txt |
Q:
call external program in python, watch output for specific text then take action
i'm looking for a way in python to run an external binary and watch it's output for: "up to date" If "up to date" isn't returned i want to run the original command again, once "up to date" is displayed i would like to be able to run a... | call external program in python, watch output for specific text then take action | i'm looking for a way in python to run an external binary and watch it's output for: "up to date" If "up to date" isn't returned i want to run the original command again, once "up to date" is displayed i would like to be able to run another script. So far I've figured out how to run the binary with options using subpro... | [
"Use Popen from subprocess like this\nprocess = Popen(\"cmd\", shell=True, bufsize=bufsize, stdout=PIPE)\nThen use process.stdout to read from program's stdout (like reading from any other file like object).\n"
] | [
3
] | [] | [] | [
"linux",
"python",
"unix"
] | stackoverflow_0002864277_linux_python_unix.txt |
Q:
How do I specify a relation in SQLAlchemy where one condition requires a column to be null?
Not sure what the correct title for this question should be. I have the following schema:
Matters have a one-many relationship to WorkItems.
WorkItems have a one-one (or one-zero) relationship to LineItems.
I am trying to... | How do I specify a relation in SQLAlchemy where one condition requires a column to be null? | Not sure what the correct title for this question should be. I have the following schema:
Matters have a one-many relationship to WorkItems.
WorkItems have a one-one (or one-zero) relationship to LineItems.
I am trying to create the following relation between Matters and WorkItems
Matter.unbilled_work_items = orm.rel... | [
"Try using and_ as and is not overloaded:\nand_((Matter.id == WorkItem.matter_id), (WorkItem.line_item_id == None))\n\n",
"Apart from the _Null issue, this requires a left outer join to do correctly. I've decided that unbilled_work_items should be a property that executes a query and returns the result.\n# like t... | [
6,
1
] | [] | [] | [
"foreign_key_relationship",
"python",
"sqlalchemy"
] | stackoverflow_0002863786_foreign_key_relationship_python_sqlalchemy.txt |
Q:
Are classes in Python in different files?
Much like Java (or php), I'm use to seperating the classes to files.
Is it the same deal in Python? plus, how should I name the file?
Lowercase like classname.py or the same like ClassName.py?
Do I need to do something special if I want to create an object from this cla... | Are classes in Python in different files? | Much like Java (or php), I'm use to seperating the classes to files.
Is it the same deal in Python? plus, how should I name the file?
Lowercase like classname.py or the same like ClassName.py?
Do I need to do something special if I want to create an object from this class or does the fact that it's in the same "proj... | [
"In Python, one file is called a module. A module can consist of multiple classes or functions.\nAs Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class.\nOne file (module) should contain classes / functions that belong together, i.e. provide sim... | [
91,
9
] | [] | [] | [
"class",
"naming_conventions",
"python"
] | stackoverflow_0002864366_class_naming_conventions_python.txt |
Q:
Why does Ruby have Rails while Python has no central framework?
This is a(n) historical question, not a comparison-between-languages question:
This article from 2005 talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. Why, historically speaking, did this happe... | Why does Ruby have Rails while Python has no central framework? | This is a(n) historical question, not a comparison-between-languages question:
This article from 2005 talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. Why, historically speaking, did this happen for Ruby but not for Python? (or did it happen, and that framework ... | [
"As I see it, Rails put Ruby on the map. The simple fact is that before Rails, Ruby was a minor esoteric language, with very little adoption. Ruby owes its success to Rails. As such, Rails has a central place in the Ruby ecosystem. As slim points out, there are other web frameworks, but it's going to be very dif... | [
35,
7,
7,
5,
5,
5,
2,
2,
1,
0,
0
] | [] | [] | [
"frameworks",
"history",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0000406907_frameworks_history_python_ruby_ruby_on_rails.txt |
Q:
Convert GNU find command to Python function
I want to convert this GNU command into a python function:
find folder/ 2>/dev/null > file.txt
The find will list all files and folders from the directory recursively and write them
to a file.
What I have now in Python is:
import os
project="/folder/path"
i=0
for (proje... | Convert GNU find command to Python function | I want to convert this GNU command into a python function:
find folder/ 2>/dev/null > file.txt
The find will list all files and folders from the directory recursively and write them
to a file.
What I have now in Python is:
import os
project="/folder/path"
i=0
for (project, dirs, files) in os.walk(project):
print pr... | [
"import os\npath = \"folder\"\nfor dirpath, dirnames, filenames in os.walk(path):\n print(dirpath)\n for filename in filenames:\n print(os.path.join(dirpath, filename))\n\nInstead of print you can write to file.\n"
] | [
4
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0002864474_bash_python.txt |
Q:
python: importing modules with incorrect import statements => unexhaustive info from resulting ImportError
I have a funny problem I'd like to ask you guys ('n gals) about.
I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError.
This is what A.py looks... | python: importing modules with incorrect import statements => unexhaustive info from resulting ImportError | I have a funny problem I'd like to ask you guys ('n gals) about.
I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError.
This is what A.py looks like
import B
Now let's import A
>>> import A
Traceback (most recent call last):
File "<stdin>", line 1, in <m... | [
"There is the imp module in the standard lib, so you could do:\n>>> import imp\n>>> imp.find_module('collections')\n(<_io.TextIOWrapper name=4 encoding='utf-8'>, 'C:\\\\Program Files\\\\Python31\\\\lib\\\\collections.py', ('.py', 'U', 1))\n>>> imp.find_module('col')\nTraceback (most recent call last):\n File \"<py... | [
2,
0
] | [] | [] | [
"import",
"importerror",
"python"
] | stackoverflow_0002864700_import_importerror_python.txt |
Q:
Randomly add buttons to Tkinter GUI?
How do I randomly add buttons to a Tkinter GUI? I need it to be able to create a button, then put it anywhere on the window, is this possible? I am using Python 2.6 on Windows.
A:
If you want random button placement (or anything not aligned along a grid, etc.), you can use th... | Randomly add buttons to Tkinter GUI? | How do I randomly add buttons to a Tkinter GUI? I need it to be able to create a button, then put it anywhere on the window, is this possible? I am using Python 2.6 on Windows.
| [
"If you want random button placement (or anything not aligned along a grid, etc.), you can use the place geometry manager. Depending on platform, overlapped buttons may not behave as you expect, though, so you may want to avoid them.\nHere's a simple example:\nfrom Tkinter import *\nfrom random import random\n\nro... | [
2,
0
] | [] | [] | [
"button",
"python",
"random",
"tkinter",
"windows"
] | stackoverflow_0002853933_button_python_random_tkinter_windows.txt |
Q:
removing elements incrementally from a list
I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:
for j in range(beginIndex, endIndex+1):
print ("remove [%d] => val: %g" % (j, myList[j]))
del myList[j]
However, since I'm iterating ove... | removing elements incrementally from a list | I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:
for j in range(beginIndex, endIndex+1):
print ("remove [%d] => val: %g" % (j, myList[j]))
del myList[j]
However, since I'm iterating over the same list, the indexes (range)
are not vali... | [
"Do you really need to remove them incrementaly?\nIf not, you can do it like this:\ndel myList[beginIndex:endIndex+1]\n\n",
"You can iterate from the end to beginning of the sequence:\nfor j in range(endIndex, beginIndex-1, -1):\n print (\"remove [%d] => val: %g\" % (j, myList[j]))\n del myList[j]\n\n",
"... | [
9,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002864854_list_python.txt |
Q:
logical operators evaluation in return statement in python
How does this execute?
def f(x):
return x>0 and (x%2)+f(x/2) or 0
x is an array, for instance: [1, 1, 1, 3]
A:
This code is broken. For starters, x>0 is always true. But x%2 and x/2 yield type errors.
A:
Did you mean this?
$ python
Python 2.5.5 (r... | logical operators evaluation in return statement in python | How does this execute?
def f(x):
return x>0 and (x%2)+f(x/2) or 0
x is an array, for instance: [1, 1, 1, 3]
| [
"This code is broken. For starters, x>0 is always true. But x%2 and x/2 yield type errors.\n",
"Did you mean this?\n$ python\nPython 2.5.5 (r255:77872, Apr 21 2010, 08:40:04) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def f(x):\n... return x>0 ... | [
2,
0,
0,
0
] | [] | [] | [
"logical_operators",
"python"
] | stackoverflow_0002865140_logical_operators_python.txt |
Q:
How can i read bzr repository from python script?
like getting information about changesets/comments etc.
A:
First off, if you are on Windows, you should consider using the "Python 2.x" installers rather than the standalone installer for Bazaar. This will install bzrlib in Python's site-packages directory, so y... | How can i read bzr repository from python script? | like getting information about changesets/comments etc.
| [
"First off, if you are on Windows, you should consider using the \"Python 2.x\" installers rather than the standalone installer for Bazaar. This will install bzrlib in Python's site-packages directory, so you don't have to mess around with %PYTHONPATH%. If you have already used the stanadalone installer, you'll n... | [
3,
1
] | [] | [] | [
"bazaar",
"python"
] | stackoverflow_0002864789_bazaar_python.txt |
Q:
Python Class Variables Question
I have some doubt about python's class variables. As my understanding, if I define a class variable, which is declared outside the __init__() function, this variable will create only once as a static variable in C++.
This seems right for some python types, for instance, dict and li... | Python Class Variables Question | I have some doubt about python's class variables. As my understanding, if I define a class variable, which is declared outside the __init__() function, this variable will create only once as a static variable in C++.
This seems right for some python types, for instance, dict and list type, but for those base type, e.g... | [
"The difference is that you never assign to self.dict1 or self.list1 — you only ever read those fields from the class — whereas you do assign to self.int1, thus creating an instance field that hides the class field.\n"
] | [
7
] | [] | [] | [
"class_variables",
"python"
] | stackoverflow_0002865538_class_variables_python.txt |
Q:
Openid not working in OSQA hosted on hostgator
I have installed osqa on server hosted on hostgator. Openid is not working at all.
When I click on google under login I get a Page not found (404) error.
What could be the reason for this?
A:
as you noted in your comment on a similar question at http://meta.osqa.net... | Openid not working in OSQA hosted on hostgator | I have installed osqa on server hosted on hostgator. Openid is not working at all.
When I click on google under login I get a Page not found (404) error.
What could be the reason for this?
| [
"as you noted in your comment on a similar question at http://meta.osqa.net this was a problem with some whitelist issue between Google and hostgator, and apparently they have resolved it. As far as we know, the OSQA openid support works beautifully, and this issue was entirely on the hostgator side.\n"
] | [
1
] | [] | [] | [
"openid",
"osqa",
"python"
] | stackoverflow_0002856789_openid_osqa_python.txt |
Q:
For Django models, is there a shortcut for seeing if a record exists?
Say I have a table People, is there a way to just quickly check if a People object exists with a name of 'Fred'? I know I can query
People.objects.filter(Name='Fred')
and then check the length of the returned result, but is there a way to do it... | For Django models, is there a shortcut for seeing if a record exists? | Say I have a table People, is there a way to just quickly check if a People object exists with a name of 'Fred'? I know I can query
People.objects.filter(Name='Fred')
and then check the length of the returned result, but is there a way to do it in a more elegant way?
| [
"Update: \nAs mentioned in more recent answers, since Django 1.2 you can use the exists() method instead (link).\n\nOriginal Answer:\nDont' use len() on the result, you should use People.objects.filter(Name='Fred').count(). According to the django documentation, \n\ncount() performs a SELECT COUNT(*)\n behind th... | [
49,
47,
10,
8
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002854080_django_django_models_python.txt |
Q:
How do I get the application title of a Google AppEngine app from within that app
Under the application settings page in the Administration console, it is possible to specify a name for the application, AFAIK this is used in the login page when using the users API to login.
I would like to be able to use this info... | How do I get the application title of a Google AppEngine app from within that app | Under the application settings page in the Administration console, it is possible to specify a name for the application, AFAIK this is used in the login page when using the users API to login.
I would like to be able to use this information within an application, currently, the title is also specified in a separate con... | [
"There's actually a way to do it, but it might be a little too much on the hacky side.. you can get the title (ab)using the users API like this:\n>>> from google.appengine.api import users\n>>> import urllib\n>>> url = users.create_login_url()\n>>> url_dict = dict((p.split('=') for p in url.split('&')))\n>>> urllib... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002864747_google_app_engine_python.txt |
Q:
From interpeted to native code: "dynamic" languages compiler support
First, I am aware that dynamic languages is a term used mainly by a vendor; I am using it just to have a container word to include languages like Perl (a favorite of mine), Python, Tcl, Ruby, PHP and so on. They are interpreted but I am intereste... | From interpeted to native code: "dynamic" languages compiler support | First, I am aware that dynamic languages is a term used mainly by a vendor; I am using it just to have a container word to include languages like Perl (a favorite of mine), Python, Tcl, Ruby, PHP and so on. They are interpreted but I am interested here to refer to languages featuring strong capability to support the pr... | [
"I think you're operating under a misunderstanding: These executables aren't huge because they just lump the interpreter in there, they're huge because the whole runtime is in there.\nOn Windows, most of your runtime is already installed, so you don't have to ship it. You think your program is small, but a quick lo... | [
4,
2,
1
] | [] | [] | [
"perl",
"programming_languages",
"python"
] | stackoverflow_0002865669_perl_programming_languages_python.txt |
Q:
Python3 function annotations for type hinting versus Boo
I've started on a medium-sized project in python, and I decided to use python 3 because I'm not using any large external libraries and py3k has some nice new syntactic sugar and more importantly function annotations. However, it seems like none of WingIDE, P... | Python3 function annotations for type hinting versus Boo | I've started on a medium-sized project in python, and I decided to use python 3 because I'm not using any large external libraries and py3k has some nice new syntactic sugar and more importantly function annotations. However, it seems like none of WingIDE, Pydev, or pycharm actually have any support for type hinting us... | [
"Boo is a great Python-like statically-typed language, but keep in mind that there more differences than just static typing. Actually you can also do duck typing on Boo.\nTechnically, I'd say the biggest difference is that Boo runs on Mono/.Net so the libraries and framework are totally different.\nSharpDevelop and... | [
4,
1
] | [] | [] | [
"boo",
"ide",
"pydev",
"python"
] | stackoverflow_0002865130_boo_ide_pydev_python.txt |
Q:
Comparable type in extension module
To implement != and == for my CPython extension type, should I implement tp_compare, tp_richcompare or both?
Under what circumstances is each of them called?
A:
tp_richcompare is analogous to the rich comparison special methods in the Python language itself. It is chosen in pr... | Comparable type in extension module | To implement != and == for my CPython extension type, should I implement tp_compare, tp_richcompare or both?
Under what circumstances is each of them called?
| [
"tp_richcompare is analogous to the rich comparison special methods in the Python language itself. It is chosen in preference to tp_compare when the comparison operators are invoked on the class.\nUse tp_richcompare when you want finer control over the comparison logic. For instance, there might be a very cheap way... | [
6
] | [] | [] | [
"cpython",
"python"
] | stackoverflow_0002865982_cpython_python.txt |
Q:
gstreamer: interleaving 2 audios - link error
I am trying to interleave two audio files as given in the interleave GStreamer documentation:
gst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \
decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! que... | gstreamer: interleaving 2 audios - link error | I am trying to interleave two audio files as given in the interleave GStreamer documentation:
gst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \
decodebin ! audioconvert ! "audio/x-raw-int,channels=1" ! queue ! i.sink0 filesrc location=file2.wav ! \
deco... | [
"try\ngst-launch interleave name=i ! audioconvert ! wavenc ! filesink location=file.wav filesrc location=file1.wav ! \\\ndecodebin ! audioconvert ! \"audio/x-raw-int,channels=1\" ! queue ! i. filesrc location=file2.wav ! \\\ndecodebin ! audioconvert ! \"audio/x-raw-int,channels=1\" ! queue ! i.\n\nthe sink pads... | [
0
] | [] | [] | [
"c#",
"c++",
"gstreamer",
"python"
] | stackoverflow_0002306605_c#_c++_gstreamer_python.txt |
Q:
Reading a binary file in Python into a struct
How do I go about opening a binary data file in Python and reading back the values one long
at a time, into a struct. I have something like this at the moment but I think this will keep overwriting idList, I want to append to it, so I end up with a tuple of all the lon... | Reading a binary file in Python into a struct | How do I go about opening a binary data file in Python and reading back the values one long
at a time, into a struct. I have something like this at the moment but I think this will keep overwriting idList, I want to append to it, so I end up with a tuple of all the long values in the file -
file = open(filename, "rb")
... | [
"Simplest (python 2.6 or better):\nimport array\nidlist = array.array('l')\nwith open(filename, \"rb\") as f:\n while True:\n try: idlist.fromfile(f, 2000)\n except EOFError: break\nidtuple = tuple(idlist)\n\nTuples are immutable, so they can't be built incrementally: so you have to build a differe... | [
6,
0
] | [] | [] | [
"binaryfiles",
"python",
"struct"
] | stackoverflow_0002865996_binaryfiles_python_struct.txt |
Q:
How to save to two tables using one SQLAlchemy model
I have an SQLAlchemy ORM class, linked to MySQL, which works great at saving the data I need down to the underlying table. However, I would like to also save the identical data to a second archive table.
Here's some psudocode to try and explain what I mean
my_da... | How to save to two tables using one SQLAlchemy model | I have an SQLAlchemy ORM class, linked to MySQL, which works great at saving the data I need down to the underlying table. However, I would like to also save the identical data to a second archive table.
Here's some psudocode to try and explain what I mean
my_data = Data() #An ORM Class
my_data.name = "foo"
#This save... | [
"I list some options below. I would go for the DB trigger if you do not need to work on those objects in your model.\n\nuse database trigger to do this job for you\ncreate a SessionExtension which will create and add to session copy-objects (usually on before_flush). Edit-1: You can take versioning example from SA ... | [
3,
1
] | [] | [] | [
"mysql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002864904_mysql_python_sql_sqlalchemy.txt |
Q:
Using Python, How to copy files in 'temporary internet files' folder in Windows
I am using this code to find files recursively in a folder , with size greater than 50000 bytes.
def listall(parent):
lis=[]
for root, dirs, files in os.walk(parent):
for name in files:
if os.path.getsize... | Using Python, How to copy files in 'temporary internet files' folder in Windows | I am using this code to find files recursively in a folder , with size greater than 50000 bytes.
def listall(parent):
lis=[]
for root, dirs, files in os.walk(parent):
for name in files:
if os.path.getsize(os.path.join(root,name))>500000:
... | [
"It's because the saved file ‘(something)+1[1].jpg’ has non-ASCII characters in its name, characters that don't fit into the ‘system default code page’ (also misleadingly known as ‘ANSI’).\nPrograms like Python that use the byte-based C standard library (stdio) file access functions have big problems with Unicode f... | [
3
] | [] | [] | [
"path",
"python",
"unicode"
] | stackoverflow_0002866455_path_python_unicode.txt |
Q:
Regex to ensure group match doesn't end with a specific character
I'm having trouble coming up with a regular expression to match a particular case. I have a list of tv shows in about 4 formats:
Name.Of.Show.S01E01
Name.Of.Show.0101
Name.Of.Show.01x01
Name.Of.Show.101
What I want to match is the show name. My ... | Regex to ensure group match doesn't end with a specific character | I'm having trouble coming up with a regular expression to match a particular case. I have a list of tv shows in about 4 formats:
Name.Of.Show.S01E01
Name.Of.Show.0101
Name.Of.Show.01x01
Name.Of.Show.101
What I want to match is the show name. My main problem is that my regex matches the name of the show with a prece... | [
"So the only real restriction on the last group is that it doesn’t contain a dot? Easy:\n^(.*?)(\\.[^.]+)$\n\nThis matches anything, non-greedily. The important part is the second group, which starts with a dot and then matches any non-dot character until the end of the string.\nThis works with all your test cases.... | [
2,
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002866783_python_regex.txt |
Q:
adding a header to pyqt list
i want to add a headers and index to a list in pyqt , it's really not important what list of QT (qlistwidget , qlistview , qtablewidget, qtreeview)
in short .. i want something like the spin box delegate example in the pyqt demo ...
but instead of the index in the column headers i wa... | adding a header to pyqt list | i want to add a headers and index to a list in pyqt , it's really not important what list of QT (qlistwidget , qlistview , qtablewidget, qtreeview)
in short .. i want something like the spin box delegate example in the pyqt demo ...
but instead of the index in the column headers i want a strings ...
hope the idea ... | [
"QTableWidget is likely your best choice - it uses setHorizontalHeaderLabels() and setVerticalHeaderLabels() to let you control both axes. \nfrom PyQt4 import QtGui\n\nclass MyWindow(QtGui.QMainWindow):\n\n def __init__(self, parent):\n QtGui.QMainWindow.__init__(self, parent)\n\n table = QtGui.QT... | [
9
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt"
] | stackoverflow_0002749529_pyqt_pyqt4_python_qt.txt |
Q:
In Python, how to find all the files under a directory, including the files in subdirectories?
Is there any built in functions to find all the files under a particular directory including files under subdirectories ?
I have tried this code, but not working...may be the logic itself is wrong...
def fun(mydir):
... | In Python, how to find all the files under a directory, including the files in subdirectories? | Is there any built in functions to find all the files under a particular directory including files under subdirectories ?
I have tried this code, but not working...may be the logic itself is wrong...
def fun(mydir):
lis=glob.glob(mydir)
length=len(lis)
l,i=0,0
if len(lis):
while(l+i<length):
... | [
"There is no built-in function, but using os.walk it's trivial to construct it:\nimport os\ndef recursive_file_gen(mydir):\n for root, dirs, files in os.walk(mydir):\n for file in files:\n yield os.path.join(root, file)\n\nETA: the os.walk function walks directory tree recursively; the recursiv... | [
13,
3,
2
] | [] | [] | [
"file",
"list",
"python"
] | stackoverflow_0002865278_file_list_python.txt |
Q:
why datetime.now() shows invalid result when executed inside django server?
Case 1
>>> datetime.__file__
'/usr/lib/python2.6/lib-dynload/datetime.so'
>>> print datetime.datetime.now()
2010-05-19 19:45:40.202634
Case 2
from django.db import models
import datetime
print datetime.__file__
print "--------------------... | why datetime.now() shows invalid result when executed inside django server? | Case 1
>>> datetime.__file__
'/usr/lib/python2.6/lib-dynload/datetime.so'
>>> print datetime.datetime.now()
2010-05-19 19:45:40.202634
Case 2
from django.db import models
import datetime
print datetime.__file__
print "--------------------------", datetime.datetime.now()
-----------Result--------
Development server is... | [
"As Mark pointed it looks like time zone difference for Japan:\n>>> from dateutil import tz\n>>> from datetime import datetime\n>>> utc_time = datetime(2010, 5, 19, 9, 16, 43, tzinfo=tz.tzutc())\n>>> jst_time = utc_time.astimezone(tz.gettz('Japan'))\n>>> print utc_time\n2010-05-19 09:16:43+00:00\n>>> print jst_time... | [
3
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0002866343_datetime_django_python.txt |
Q:
Scraping digg rss feed with python
is there a way to get the link from digg through its rss feed? or do i have to get the website and manually scrape it with a regex?
i want to get the real link digg points to, not to the comments feed, from rss.
example -
http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Appl... | Scraping digg rss feed with python | is there a way to get the link from digg through its rss feed? or do i have to get the website and manually scrape it with a regex?
i want to get the real link digg points to, not to the comments feed, from rss.
example -
http://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_P... | [
"Take a look at the feedparser module.\n>>> import feedparser\n>>> d = feedparser.parse('http://feeds.digg.com/digg/popular.rss')\n>>> for entry in d.entries:\n... print entry.link\n...\nhttp://feeds.digg.com/~r/digg/popular/~3/Hx0VATaafSw/Apple_Scaling_Final_Cut_Studio_Apps_to_Fit_Prosumers_2\nhttp://feeds.dig... | [
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002866939_python.txt |
Q:
Python Type Checking & Inheritance Issue
I have a bit of Python code which depends on type checking. I'll try and phrase my problem in the language of math so it's clear. I have a few classes which correspond to subsets of each other and form an inheritance chain.
class Real(object):
pass
class Integer(Real):... | Python Type Checking & Inheritance Issue | I have a bit of Python code which depends on type checking. I'll try and phrase my problem in the language of math so it's clear. I have a few classes which correspond to subsets of each other and form an inheritance chain.
class Real(object):
pass
class Integer(Real):
pass
class Natural(Integer):
pass
A... | [
"def compatible_pred(obj_types, fun_signature):\n if len(obj_types) != len(fun_signature): return False\n return all(issubclass(of, ft) for of, ft in zip(obj_types, fun_signature))\n\ndef is_compatible(obj_types, fun_signatures=(t1, t2)):\n return [t for t in fun_signatures if compatible_pred(obj_types, t)]\n\nT... | [
4,
2
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0002867449_inheritance_oop_python.txt |
Q:
Why does Python sometimes upgrade a string to unicode and sometimes not?
I'm confused. Consider this code working the way I expect:
>>> foo = u'Émilie and Juañ are turncoats.'
>>> bar = "foo is %s" % foo
>>> bar
u'foo is \xc3\x89milie and Jua\xc3\xb1 are turncoats.'
And this code not at all working the way I exp... | Why does Python sometimes upgrade a string to unicode and sometimes not? | I'm confused. Consider this code working the way I expect:
>>> foo = u'Émilie and Juañ are turncoats.'
>>> bar = "foo is %s" % foo
>>> bar
u'foo is \xc3\x89milie and Jua\xc3\xb1 are turncoats.'
And this code not at all working the way I expect:
>>> try:
... raise Exception(foo)
... except Exception as e:
... ... | [
"The Python Language Reference has the answer:\n\nIf format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.\n\nfoo = u'Émilie and Juañ are turncoats.'\nbar = \"foo is %s\" % foo\n\nThis works, because foo is a unico... | [
10
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0002867773_python_unicode.txt |
Q:
google datastore - does it do lazy loading?
if I have a Customer object with a list of orders, declared using the db.ReferenceProperty
after a while I may have huge amount of orders in there, if I pull the Customer object would I be in danger of pulling the complete set of orders?
A:
Yes, db.ReferenceProperty fi... | google datastore - does it do lazy loading? | if I have a Customer object with a list of orders, declared using the db.ReferenceProperty
after a while I may have huge amount of orders in there, if I pull the Customer object would I be in danger of pulling the complete set of orders?
| [
"Yes, db.ReferenceProperty fields are loaded lazily. From the docs:\n\nReferenceProperty automatically references and dereferences model instances as property values: A model instance can be assigned to a ReferenceProperty directly, and its key will be used. The ReferenceProperty value can be used as if it were a ... | [
6
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002867730_google_app_engine_google_cloud_datastore_python.txt |
Q:
getting keyboard events with pyqt
i converted recently from wxpython to pyqt and im still facing alot of problems since im still noob in pyqt
so is it possible to detected if user pressed (CTRL+key ) in pyqt ? and how ?
i've been trying to find an answer for this for 3 days . if you know website or a good place t... | getting keyboard events with pyqt | i converted recently from wxpython to pyqt and im still facing alot of problems since im still noob in pyqt
so is it possible to detected if user pressed (CTRL+key ) in pyqt ? and how ?
i've been trying to find an answer for this for 3 days . if you know website or a good place to learn pyqt, it will be highly apprec... | [
"Add a QShortcut and listen to its activated() signal, then perform the action in the slot.\nOr you could reimplement QWidget and define keyPressEvent to what you like. Check for the event parameter's modifiers() and key() to see if they match with what you want. This listens for shortcut keys when the QWidget has ... | [
8,
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0002761512_pyqt_pyqt4_python_qt_qt4.txt |
Q:
Python ctypes in_dll string assignment
I could use some help assigning to a global C variable in DLL using ctypes.
The following is an example of what I'm trying:
test.c contains the following
#include <stdio.h>
char name[60];
void test(void) {
printf("Name is %s\n", name);
}
On windows (c... | Python ctypes in_dll string assignment | I could use some help assigning to a global C variable in DLL using ctypes.
The following is an example of what I'm trying:
test.c contains the following
#include <stdio.h>
char name[60];
void test(void) {
printf("Name is %s\n", name);
}
On windows (cygwin) I build a DLL (Test.dll) as follows:
... | [
"name is not really a character pointer (it's an array, which \"decays to\" a pointer when accessed, but can never be assigned to). You'll need to call the strcpy function from the C runtime library, instead of assigning to f.value.\n"
] | [
6
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0002867916_ctypes_python.txt |
Q:
Python: how to execute generated code?
I have this code, and I would like to use the app parameter to generate the code instead of duplicating it.
if app == 'map':
try:
from modulo.map.views import map
return map(request, *args, **kwargs)
except ImportError:
pass
elif app == 'sched... | Python: how to execute generated code? | I have this code, and I would like to use the app parameter to generate the code instead of duplicating it.
if app == 'map':
try:
from modulo.map.views import map
return map(request, *args, **kwargs)
except ImportError:
pass
elif app == 'schedule':
try:
from modulo.schedule.... | [
"I would prefer to use the dispatch-dictionary idiom, coding something like...:\nimport sys\n\ndispatch = { 'map': ('modulo.map.views', 'map'),\n 'schedule': ('modulo.schedule.views', 'schedule_day'),\n ...etc etc.. }\nif app in dispatch:\n modname, funname = dispatch[app]\n try: __import_... | [
6,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002868063_django_python.txt |
Q:
Timestamp server rfc3161 response token generation in Python
I'm trying to implement tsa server on python using twisted. Currently I'm using openssl binary to generate response, but this seems ugly to me, that's why I'm trying to figure out how to make response token with m2crypto.
Thanks in advance for help!
Mari... | Timestamp server rfc3161 response token generation in Python | I'm trying to implement tsa server on python using twisted. Currently I'm using openssl binary to generate response, but this seems ugly to me, that's why I'm trying to figure out how to make response token with m2crypto.
Thanks in advance for help!
Maris.
EDITED:
how to achieve with m2crypto?:
openssl ts -reply -secti... | [
"M2Crypto does not yet wrap those pieces of openssl, so you can't use M2Crypto for what you are using the openssl command line client for.\n",
"You may be also interested in PyASN1 project, however, I should admit there's no adequate library to implement RFC3161 functionality in Python today. I would look towards... | [
1,
0
] | [] | [] | [
"m2crypto",
"python",
"rfc3161",
"timestamping",
"trusted_timestamp"
] | stackoverflow_0002858282_m2crypto_python_rfc3161_timestamping_trusted_timestamp.txt |
Q:
how to convert a python slicing operation into java code
I have this code line:
x and k are int.
lm is an array
lz=[f(x,lm[:j]+lm[j+1:],k) for j in range(n)]
My question is:
I want to convert the above line into Java...
I have created an lm array in Java, but I am thinking of making it an arraylist to avoid the p... | how to convert a python slicing operation into java code | I have this code line:
x and k are int.
lm is an array
lz=[f(x,lm[:j]+lm[j+1:],k) for j in range(n)]
My question is:
I want to convert the above line into Java...
I have created an lm array in Java, but I am thinking of making it an arraylist to avoid the problem of the array length.
I know that for instanse lm is [1,... | [
"Will that help you?\n int[] lm = new int[] {1, 4, 1, 9};\n for (int i = 0; i < lm.length; i++) {\n int[] tmp = new int[lm.length - 1];\n System.arraycopy(lm, 0, tmp, 0, i);\n System.arraycopy(lm, i + 1, tmp, i, lm.length - i - 1);\n\n System.out.println(\"tmp = \" + Arrays.toString(... | [
0
] | [] | [] | [
"arrays",
"java",
"python",
"slice"
] | stackoverflow_0002868277_arrays_java_python_slice.txt |
Q:
Reading from CSVs in Python repeatedly?
I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks.
... | Reading from CSVs in Python repeatedly? | I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks.
orig = csv.reader(open("googlel.csv", "rb"), ... | [
"You can \"reset\" the CSV iterator by resetting the read position of the file object.\ndata = open(\"googlel.csv\", \"rb\")\norig = csv.reader(data, delimiter = ';')\ngoodrows = []\nfor feed in gotfeeds: \n for link,comments in feed.items():\n data.seek(0)\n for row in orig:\n print link... | [
41,
14
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002868354_csv_python.txt |
Q:
How to import classes into other classes within the same file in Python
I have the file below and it is part of a django project called projectmanager, this file is projectmanager/projects/models.py . Whenever I use the python interpreter to import a Project just to test the functionality i get a name error for li... | How to import classes into other classes within the same file in Python | I have the file below and it is part of a django project called projectmanager, this file is projectmanager/projects/models.py . Whenever I use the python interpreter to import a Project just to test the functionality i get a name error for line 8 that FileRepo() cannot be found. How Can I import these classes correctl... | [
"Although McPeterson is right in general that for a name to be found, it has to be defined above where it is used, in your case that won't help. In Django, you can't arbitrarily assign classes to be properties of other classes. You need to define proper relationships between them. I suggest you read the documentati... | [
3,
0
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0002868418_django_import_python.txt |
Q:
Problem with python urllib
I'm getting an error when ever I try to pull down a web page with urllib.urlopen. I've disabled windows firewall and my AV so its not that. I can access the pages in my browser. I even reinstalled python to rule out it being a broken urllib. Any help would be greatly appreciated.
>>> imp... | Problem with python urllib | I'm getting an error when ever I try to pull down a web page with urllib.urlopen. I've disabled windows firewall and my AV so its not that. I can access the pages in my browser. I even reinstalled python to rule out it being a broken urllib. Any help would be greatly appreciated.
>>> import urllib
>>> h = urllib.urlope... | [
"this could be the case:\n\nJust found the problem I had set a\n proxy through internet options, that\n proxy went offline, and so did my\n python shell.\n\n",
"urllib is working just fine.\nTry using ethereal (or some similar network sniffer) on your box to determine if the denial coming from your machine or ... | [
5,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0002868935_python_urllib.txt |
Q:
Python - Removing duplicates from a string
def remove_duplicates(strng):
"""
Returns a string which is the same as the argument except only the
first occurrence of each letter is present. Upper and lower case
letters are treated as different. Only duplicate letters are removed,
other characte... | Python - Removing duplicates from a string | def remove_duplicates(strng):
"""
Returns a string which is the same as the argument except only the
first occurrence of each letter is present. Upper and lower case
letters are treated as different. Only duplicate letters are removed,
other characters such as spaces or numbers are not changed.
... | [
"Not the most efficient, but the most straightforward way is:\n>>> s = 'The quick brown fox jumps over the lazy dog'\n>>> import string\n>>> n = ''\n>>> for i in s:\n if i not in string.ascii_letters:\n n += i\n elif i not in n:\n n += i\n\n\n>>> n\n'The quick brown fx jmps v t l... | [
3,
2,
0
] | [] | [] | [
"duplicate_removal",
"python"
] | stackoverflow_0002865150_duplicate_removal_python.txt |
Q:
How to make this gaema demo running on google-app-engine?
This is the package which has a webapp demo in it.
However, when I login use this demo, I get an error.
How to make this demo running on the gae-launcher?
A:
Looks like a bug in gaema.
The line that's failing is trying to urlencode a dictionary of argumen... | How to make this gaema demo running on google-app-engine? | This is the package which has a webapp demo in it.
However, when I login use this demo, I get an error.
How to make this demo running on the gae-launcher?
| [
"Looks like a bug in gaema.\nThe line that's failing is trying to urlencode a dictionary of arguments that get passed to the OpenID endpoint. One or more of the values, perhaps your first or last name, has non-ASCII characters.\nYou might be able to work around it by replacing instances of this:\nurllib.urlencode(a... | [
0
] | [] | [] | [
"gaema",
"google_app_engine",
"python"
] | stackoverflow_0002863839_gaema_google_app_engine_python.txt |
Q:
Setting opacity on a PyGTK label
Is there a way to make a PyGTK widget partly transparent, so that the widgets behind it can be seen through it? Specifically I'm trying to do this on a label, for typographic effect; I don't want to change the color instead, as it may not look right on all themes.
A:
No, not po... | Setting opacity on a PyGTK label | Is there a way to make a PyGTK widget partly transparent, so that the widgets behind it can be seen through it? Specifically I'm trying to do this on a label, for typographic effect; I don't want to change the color instead, as it may not look right on all themes.
| [
"No, not possible. It is possible to make entire windows partially transparent, if window manager supports compositing, but not individual widgets.\nI guess what you want can be achieved differently by \"blending\" colors:\ndef blend (color1, color2, weight = 0.5):\n return gtk.gdk.Color (\n color1.red_f... | [
2
] | [] | [] | [
"gtk",
"opacity",
"pygtk",
"python",
"transparency"
] | stackoverflow_0002869169_gtk_opacity_pygtk_python_transparency.txt |
Q:
In Python, how to I create a datetime with X hours?
How do I create the datetime that is 24 hours before NOW()?
48 before NOW()?
X hours or days before now??
A:
from datetime import datetime, timedelta
def hours_ago(hours):
return datetime.today() - timedelta(hours=hours)
def days_ago(days):
return dat... | In Python, how to I create a datetime with X hours? | How do I create the datetime that is 24 hours before NOW()?
48 before NOW()?
X hours or days before now??
| [
"from datetime import datetime, timedelta\n\ndef hours_ago(hours):\n return datetime.today() - timedelta(hours=hours)\n\ndef days_ago(days):\n return datetime.today() - timedelta(days=days)\n\n",
">>> from datetime import datetime, timedelta\n>>> datetime.now() - timedelta(hours=24)\ndatetime.datetime(2010,... | [
9,
3
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0002869407_datetime_python_time.txt |
Q:
how to encode a url with urllib or urllib2
I want a url like example.com/page.html to somthing like
example.com/a$xDzf9D84qGBOeXkXNstw%3D%3D106
A:
In case you mean this:
>>> import urllib, base64
>>> urllib.quote_plus('example.com/page.html')
'example.com%2Fpage.html'
>>> base64.urlsafe_b64encode('exampl... | how to encode a url with urllib or urllib2 | I want a url like example.com/page.html to somthing like
example.com/a$xDzf9D84qGBOeXkXNstw%3D%3D106
| [
"In case you mean this:\n >>> import urllib, base64\n >>> urllib.quote_plus('example.com/page.html')\n 'example.com%2Fpage.html'\n >>> base64.urlsafe_b64encode('example.com/page.html')\n 'ZXhhbXBsZS5jb20vcGFnZS5odG1s'\n\n",
"you probably wanted something like this:\n>>> url = 'stackoverflow.com/questions/284... | [
3,
2
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0002841879_python_urllib_urllib2.txt |
Q:
Multiple data series in real time plot
I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get mul... | Multiple data series in real time plot | I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get multiple data series into the same plot. Does a... | [
"Solved it by realizing that Plot() returned a list of lines.\n",
"Here's a matplotlib example. It was originally written to use a module that would get analog data from an arduino running firmata, but you should be able to get the relevant bits from it: http://github.com/jsnyder/jbsnyder_tools/blob/master/plota... | [
1,
1
] | [] | [] | [
"matplotlib",
"python",
"sensors"
] | stackoverflow_0002814464_matplotlib_python_sensors.txt |
Q:
How do I name a variable with acronym?
For example in Java for Data Transfer Object I use as:
ExampleDTO exampleDTO = new ExampleDTO();
So, if I am following PEP 8 (lower_case_with_underscores), what naming convention should I use for similar in Python?
A:
The style most agreeing with PEP-8 would probably be...... | How do I name a variable with acronym? | For example in Java for Data Transfer Object I use as:
ExampleDTO exampleDTO = new ExampleDTO();
So, if I am following PEP 8 (lower_case_with_underscores), what naming convention should I use for similar in Python?
| [
"The style most agreeing with PEP-8 would probably be...\nexample_dto = ExampleDTO()\n",
"You may want to look at Python Style Guide\nI personally use camelCase for variables and _ (underscore) separated in method names. \n"
] | [
10,
0
] | [
"Why use acronyms in the first place? I try to avoid them when possible. They obfuscate the code and tend to create code that is hard to browse for quick read. Worst case they bring bugs because of misinterpretation (RndCmp was a Random Compare not a Rounded Complex).\nWhat is DTO? Will it still be used in 2 years?... | [
-2
] | [
"naming_conventions",
"python"
] | stackoverflow_0002869251_naming_conventions_python.txt |
Q:
feedparser fails during script run, but can't reproduce in interactive python console
It's failing with this when I run eclipse or when I run my script in iPython:
'ascii' codec can't decode byte 0xe2 in position 32: ordinal not in range(128)
I don't know why, but when I simply execute the feedparse.parse(url) s... | feedparser fails during script run, but can't reproduce in interactive python console | It's failing with this when I run eclipse or when I run my script in iPython:
'ascii' codec can't decode byte 0xe2 in position 32: ordinal not in range(128)
I don't know why, but when I simply execute the feedparse.parse(url) statement using the same url, there is no error thrown. This is stumping me big time.
The co... | [
"Looks like the url that is giving you problem contains text with some encoding (such as latin-1, where 0xe2 would be \"lowercase a with a circle on top\" aka â) without a proper content-type header (it should have a charset= parameter in Content-Type: but doesn't).\nIf that is the case feedparser cannot gues... | [
1,
1
] | [] | [] | [
"ascii",
"character_encoding",
"feedparser",
"python",
"unicode"
] | stackoverflow_0002857450_ascii_character_encoding_feedparser_python_unicode.txt |
Q:
xml filtering with python
I have a following xml document:
<node0>
<node1>
<node2 a1="x1"> ... </node2>
<node2 a1="x2"> ... </node2>
<node2 a1="x1"> ... </node2>
</node1>
</node0>
I want to filter out node2 when a1="x2". The user provides the xpath and attribute values that need to teste... | xml filtering with python | I have a following xml document:
<node0>
<node1>
<node2 a1="x1"> ... </node2>
<node2 a1="x2"> ... </node2>
<node2 a1="x1"> ... </node2>
</node1>
</node0>
I want to filter out node2 when a1="x2". The user provides the xpath and attribute values that need to tested and filtered out. I looked at... | [
"This uses xml.etree.ElementTree which is in the standard library:\nimport xml.etree.ElementTree as xee\ndata='''\\\n<node1>\n <node2 a1=\"x1\"> ... </node2>\n <node2 a1=\"x2\"> ... </node2>\n <node2 a1=\"x1\"> ... </node2>\n</node1>\n'''\ndoc=xee.fromstring(data)\n\nfor tag in doc.findall('node2'):\n if tag.... | [
7
] | [] | [] | [
"elementtree",
"python",
"xml",
"xpath"
] | stackoverflow_0002869564_elementtree_python_xml_xpath.txt |
Q:
How do I send this email in Python, opening files and stuff?
msg = EmailMessage(subject, body, from_email, [to_email])
msg.content_subtype = "html"
msg.send()
This is how I send an email in Django.
But what if I want to open a text file and take into account all its line breaks and tabs. I want to take the body o... | How do I send this email in Python, opening files and stuff? | msg = EmailMessage(subject, body, from_email, [to_email])
msg.content_subtype = "html"
msg.send()
This is how I send an email in Django.
But what if I want to open a text file and take into account all its line breaks and tabs. I want to take the body of the text file (with line breaks \n) and email it as text of the ... | [
"If it's a text file, just send it as text. If you send it as \"HTML\", the whitespace won't be significant.\n",
"In Django itself, it uses render_to_string(\"\", {}) from django.template.loader. The advantage of it is that you can use contexts.\n"
] | [
1,
0
] | [] | [] | [
"django",
"email",
"file",
"html",
"python"
] | stackoverflow_0002869694_django_email_file_html_python.txt |
Q:
How to use regular expressions to pull a substring? (screen scraping)
Hey guys, i'm really trying to understand regular expressions while scraping a site, i've been using it in my code enough to pull the following, but am stuck here. I need to quickly grab this:
http://www.example.com/online/store/TitleDetail?deta... | How to use regular expressions to pull a substring? (screen scraping) | Hey guys, i'm really trying to understand regular expressions while scraping a site, i've been using it in my code enough to pull the following, but am stuck here. I need to quickly grab this:
http://www.example.com/online/store/TitleDetail?detail&sku=123456789
from this:
('<a href="javascript:if(handleDoubleClick(thi... | [
"http://www\\.example\\.com/online/store/TitleDetail\\?detail&sku=\\d+\n\nuse the \\d group with a \"Greedy\" +, to qualify any integer value in the sku field\n",
"You don't need regular expressions for that, just use string methods:\nresult = html[0].split(\"window.location='\")[1].split(\"'\")[0]\n\n",
"patte... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"screen_scraping"
] | stackoverflow_0002870444_python_regex_screen_scraping.txt |
Q:
Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language?
I wonder why would a C++, C#, Java developer want to learn a dynamic language?
Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language... | Why learn Perl, Python, Ruby if the company is using C++, C# or Java as the application language? | I wonder why would a C++, C#, Java developer want to learn a dynamic language?
Assuming the company won't switch its main development language from C++/C#/Java to a dynamic one what use is there for a dynamic language?
What helper tasks can be done by the dynamic languages faster or better after only a few days of lear... | [
"A lot of times some quick task comes up that isn't part of the main software you are developing. Sometimes the task is one off ie compare this file to the database and let me know the differences. It is a lot easier to do text parsing in Perl/Ruby/Python than it is in Java or C# (partially because it is a lot ea... | [
81,
21,
14,
9,
7,
5,
5,
5,
4,
3,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"c#",
"java",
"perl",
"python",
"ruby"
] | stackoverflow_0000084340_c#_java_perl_python_ruby.txt |
Q:
Twisted Matrix and telnet server implementation
I have a project which is essentially a game server where users connect and send text commands via telnet.
The code is in C and really old and unmodular and has several bugs and missing features. The main function alone is half the code.
I came to the conclusion that... | Twisted Matrix and telnet server implementation | I have a project which is essentially a game server where users connect and send text commands via telnet.
The code is in C and really old and unmodular and has several bugs and missing features. The main function alone is half the code.
I came to the conclusion that rewriting it in Python, with Twisted, could actually... | [
"Greg's suggestion to try to become familiar with Python before trying to take on Twisted is perhaps a reasonable one. Limiting the possible sources of your confusion may help you avoid some very frustrating cases.\nOn the other hand, I know a lot of people who take on a Twisted-based project as a first Python lea... | [
5,
1
] | [] | [] | [
"python",
"telnet",
"twisted"
] | stackoverflow_0002864663_python_telnet_twisted.txt |
Q:
Writing white space to CSV fields in Python?
When I try to write a field that includes whitespace in it, it gets split into multiple fields on the space. What's causing this? It's driving me insane. Thanks
data = open("file.csv", "wb")
w = csv.writer(data)
w.writerow(['word1', 'word2'])
w.writerow(['word 1', 'word... | Writing white space to CSV fields in Python? | When I try to write a field that includes whitespace in it, it gets split into multiple fields on the space. What's causing this? It's driving me insane. Thanks
data = open("file.csv", "wb")
w = csv.writer(data)
w.writerow(['word1', 'word2'])
w.writerow(['word 1', 'word2'])
data.close()
I'll get 2 fields(word1,word2) ... | [
"The writing is correct, I think; the problem would be in reading. You never said what you're using to open such generated CSV. It might be splitting fields on comma or whitespace.\nUPDATE: Try this, see if it helps:\nw = csv.writer(data, quoting=csv.QUOTE_ALL)\n\n",
"Not reproducible here:\n>>> import csv\n>>> d... | [
4,
3,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002870976_csv_python.txt |
Q:
Python and database
I am working on a personal project where I need to manipulate values in a database-like format.
Up until now I have been using dictionaries, tuples, and lists to store and consult those values.
I am thinking about starting to use SQL to manipulate those values, but I don't know if it's worth th... | Python and database | I am working on a personal project where I need to manipulate values in a database-like format.
Up until now I have been using dictionaries, tuples, and lists to store and consult those values.
I am thinking about starting to use SQL to manipulate those values, but I don't know if it's worth the effort, because I don't... | [
"SQL is nice and practical for many kinds of problems, is not that hard to learn at a simple \"surface\" level, and can be very handy to use in Python with its embedded sqlite. But if you don't know SQL, have no intrinsic motivation to learn it right now, and are already doing all you need to do to/with your data ... | [
7,
2,
2
] | [] | [] | [
"database",
"python",
"sql"
] | stackoverflow_0002870815_database_python_sql.txt |
Q:
Python readability hints for a Java programmer
I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if).
I know each language has its own convent... | Python readability hints for a Java programmer | I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if).
I know each language has its own conventions and set of "habits". So, from a readability sta... | [
"There's no simple answer to that question. It takes time for your code to be \"Pythonic\". Don't try and recreate Java idioms in Python. It will just take time to learn Python idioms.\nTake a look at Code Like a Pythonista: Idiomatic Python, Style Guide for Python Code and Python for Java Programmers (archived).\n... | [
8,
5,
3,
1,
0,
0
] | [] | [] | [
"conventions",
"java",
"python",
"readability"
] | stackoverflow_0002870292_conventions_java_python_readability.txt |
Q:
add gtk.widget in a gnome Applet
I have a question :
I write a little gnome applet, and when we click on a button i want to add a gtk.widget under the "gnome-panel" like the calendar of the clock-applet.
But I don't know how to do this.
It's my code :
listButton = gtk.Button(_("lastest"))
self.listTwitt = gtk.Tre... | add gtk.widget in a gnome Applet | I have a question :
I write a little gnome applet, and when we click on a button i want to add a gtk.widget under the "gnome-panel" like the calendar of the clock-applet.
But I don't know how to do this.
It's my code :
listButton = gtk.Button(_("lastest"))
self.listTwitt = gtk.TreeView()
mainLayout = gtk.VBox()
mainLa... | [
"You have to create a gtk.Window, position it under the applet, and add it in there.\n"
] | [
0
] | [] | [] | [
"applet",
"gnome",
"gtk",
"python"
] | stackoverflow_0002868912_applet_gnome_gtk_python.txt |
Q:
Can I move beaker.SessionMiddleware to handle method somehow?
It's a bit ugly that many lines of code fall into "__main__".
Can someone give me a tip of how to move SessionMiddleware into handle method?
I should notice that I use session in CoreXmlParser.
Thanks in advance !
def handle(environ, start_response):
... | Can I move beaker.SessionMiddleware to handle method somehow? | It's a bit ugly that many lines of code fall into "__main__".
Can someone give me a tip of how to move SessionMiddleware into handle method?
I should notice that I use session in CoreXmlParser.
Thanks in advance !
def handle(environ, start_response):
req = webob.Request(environ)
c = CoreXmlParser(req)
... | [
"I'm not sure I understand why you're trying to move just one line. If you want to reduce the amount of stuff in \"__main__\", why not just move all that \"#parse config file\" stuff into a separate function?\ndef handle(environ, start_response):\n # same as before\n\ndef create_app(config_file):\n #parse con... | [
0
] | [] | [] | [
"beaker",
"fastcgi",
"python"
] | stackoverflow_0002871424_beaker_fastcgi_python.txt |
Q:
How to send a EML file as email using python script to list of emails one at a time?
I want to write a simple python script that send a EML file exported from Outlook though given smtp server as email to a given list of emails. I know how to send a simple email but sending a EML file as email is not something i c... | How to send a EML file as email using python script to list of emails one at a time? | I want to write a simple python script that send a EML file exported from Outlook though given smtp server as email to a given list of emails. I know how to send a simple email but sending a EML file as email is not something i could do and could not find it on Google. Can anyone help me with that. The EML file is act... | [
"Building on the email module example, try using a MIME attachment with HTML content.\nIf the EML format is just HTML, this should work.\nThe example shows how to construct a message with (html) attachments:\n# Create the body of the message (a plain-text and an HTML version).\ntext = \"Hi!\\nHow are you?\\nHere is... | [
3
] | [] | [] | [
"email",
"linux",
"python"
] | stackoverflow_0002871440_email_linux_python.txt |
Q:
Snow Leopard Python 2.6 problems getting PIL to work
I installed libjpeg and PIL, but when I try to save a JPG image, I always get this error:
ImportError: The _imaging C module is not installed
Any help much appreciated!
I tried to import _imaging w/ Python interpreter to see what's wrong and got this:
>>> im... | Snow Leopard Python 2.6 problems getting PIL to work | I installed libjpeg and PIL, but when I try to save a JPG image, I always get this error:
ImportError: The _imaging C module is not installed
Any help much appreciated!
I tried to import _imaging w/ Python interpreter to see what's wrong and got this:
>>> import _imaging
Traceback (most recent call last):
File "<... | [
"I just hit this as well on SL, and the problem is likely your libjpeg was built without a matching architecture. Assuming you're using MacPorts, run file /opt/local/lib/libjpeg.dylib. The right way is to build everything with MacPorts as +universal, see \nUniversal Binaries in MacPorts as it relates to PIL depen... | [
4,
4,
2,
1
] | [] | [] | [
"image_manipulation",
"osx_snow_leopard",
"pylons",
"python",
"python_imaging_library"
] | stackoverflow_0001518573_image_manipulation_osx_snow_leopard_pylons_python_python_imaging_library.txt |
Q:
python simple json problem with a unicode string url "link": "http:\/\/www.mydomain.com"?
i have a dictionary when i pass it over simplejson.dumps(dict) the json output has put some sort of encoding on a string url?
"link": "http:\/\/www.mydomain.com"
How can i stop this?
Im using app engine simplejson.
A:
I do... | python simple json problem with a unicode string url "link": "http:\/\/www.mydomain.com"? | i have a dictionary when i pass it over simplejson.dumps(dict) the json output has put some sort of encoding on a string url?
"link": "http:\/\/www.mydomain.com"
How can i stop this?
Im using app engine simplejson.
| [
"I don't see a problem with this. This encoding for the forward slash is perfectly valid. If the other side can't decode this then it's their JSON library that is broken.\n"
] | [
2
] | [] | [] | [
"python",
"simplejson"
] | stackoverflow_0002871912_python_simplejson.txt |
Q:
Combining entries, filtering of Python dictionaries
I have two large lists that are filled with dictionaries. I need to combine the entries if a value from dict2==dict1 and place the newly combined matches somewhere else. I'm having trouble explaining it.
List one contains:
{'keyword':value, 'keyword2':value2}
Li... | Combining entries, filtering of Python dictionaries | I have two large lists that are filled with dictionaries. I need to combine the entries if a value from dict2==dict1 and place the newly combined matches somewhere else. I'm having trouble explaining it.
List one contains:
{'keyword':value, 'keyword2':value2}
List two:
{'keyword2':value2, 'keyword3':value3}
I want a ... | [
"If you don't care about \"conflicts\", i.e. that the same key is mapped to different values in two dicts, you can use the update method of dicts:\n>>> d1 = {'keyword': 1, 'keyword2': 2}\n>>> d2 = {'keyword2': 2, 'keyword3': 3}\n>>> d = {}\n>>> d.update(d1)\n>>> d\n{'keyword2': 2, 'keyword': 1}\n>>> d.update(d2)\n>... | [
2,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0002871836_dictionary_list_python_sorting.txt |
Q:
How to retrieve value from etc/sysconfig in Python
I have a config file FOO in /etc/sysconfig/. This Linux file is very similar to INI-File, but without a section declaration.
In order to retrieve a value from this file, I used to write a shell script like:
source /etc/sysconfig/FOO
echo $MY_VALUE
Now I want to d... | How to retrieve value from etc/sysconfig in Python | I have a config file FOO in /etc/sysconfig/. This Linux file is very similar to INI-File, but without a section declaration.
In order to retrieve a value from this file, I used to write a shell script like:
source /etc/sysconfig/FOO
echo $MY_VALUE
Now I want to do the same thing in python. I tried to use ConfigParser,... | [
"I suppose you could do exactly what you're doing with your shell script using the subprocess module and reading it's output. Use it with the shell option set to True.\n",
"If you want to use ConfigParser, you could do something like:\n#! /usr/bin/env python2.6\n\nfrom StringIO import StringIO\nimport ConfigParse... | [
1,
1
] | [] | [] | [
"bash",
"environment_variables",
"ini",
"linux",
"python"
] | stackoverflow_0002871930_bash_environment_variables_ini_linux_python.txt |
Q:
spam and dirty words comment post filtering/prevention/blocking in python (django)
My basic question is how to prevent spam and dirty words in a comment post system under python (django).
I have a collection of phrases (approximately 3000 phrases) to be blocked.
What I want to do is like this:
If I found a comme... | spam and dirty words comment post filtering/prevention/blocking in python (django) | My basic question is how to prevent spam and dirty words in a comment post system under python (django).
I have a collection of phrases (approximately 3000 phrases) to be blocked.
What I want to do is like this:
If I found a comment which has a dirty-word when user clicks the post button, then the web should popup a ... | [
"You may want to check out the PROFANITIES_LIST setting, looks like you can use it with validators.\nAlthough, with that many (3000 really? you must be fun at parties) phrases you want to rethink things. You shouldn't filter SPAM. You should throw it away. Just my opinion. If the comment has SPAM in it, why keep... | [
4
] | [] | [] | [
"django",
"filtering",
"python",
"spam_prevention"
] | stackoverflow_0002871978_django_filtering_python_spam_prevention.txt |
Q:
Efficient way in Python to remove an element from a comma-separated string
I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words:
For example:
string = 'Apples, Bananas, Grapes, Oranges'
subtraction = 'Bananas'
result = 'Apples, Grap... | Efficient way in Python to remove an element from a comma-separated string | I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words:
For example:
string = 'Apples, Bananas, Grapes, Oranges'
subtraction = 'Bananas'
result = 'Apples, Grapes, Oranges'
Also, a way to do this but while maintaining IDs:
string = '1:Appl... | [
"Split on ', ', remove the element, and join.\n",
"Matthew's comment above is the right approach but if you're sure that the , (comma followed by a space) occur only as separators, then something like this would work\ndef remove(str, element):\n items = str.split(\", \")\n items.remove(element)\n return ... | [
5,
1,
1,
0
] | [] | [] | [
"pylons",
"python",
"string"
] | stackoverflow_0002871915_pylons_python_string.txt |
Q:
Google app engin, python: Google, Facebook, Twitter, OpenID account
Do anyone know if there are alternatives of Django-SocialAuth which support Google, Facebook, Twitter and OpenID account.
I prefer webapp version instead of Django.
Or if you have done once would you mind sharing it?
Thanks in million.
A:
try ch... | Google app engin, python: Google, Facebook, Twitter, OpenID account | Do anyone know if there are alternatives of Django-SocialAuth which support Google, Facebook, Twitter and OpenID account.
I prefer webapp version instead of Django.
Or if you have done once would you mind sharing it?
Thanks in million.
| [
"try checking out http://code.google.com/p/gaema/\nfrom the gaema introduction, \n\ngaema is a library that provides\n various authentication systems for\n Google App Engine. It is basically the\n tornado.auth module extracted to work\n on App Engine and independently of any\n framework.\nIt supports login usi... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002871689_google_app_engine_python.txt |
Q:
Why are python extensions shared libraries? Is it possible to make a static-linked library?
I'm an extension noob. What I want to do is create an extension that doesn't require other libraries to be installed. Is this impossible because the extension has to link against a specific version of libpython at runtime... | Why are python extensions shared libraries? Is it possible to make a static-linked library? | I'm an extension noob. What I want to do is create an extension that doesn't require other libraries to be installed. Is this impossible because the extension has to link against a specific version of libpython at runtime?
| [
"You can't make a statically linked extension module because Python needs to load it dynamically at runtime and because (as you reasoned) the module needs to dynamically link against libpython.\nYou could compile your own custom version of Python with your extension statically linked into the interpreter. That's u... | [
6,
3
] | [] | [] | [
"c",
"python"
] | stackoverflow_0002865679_c_python.txt |
Q:
Where can I find documentation on assembler?
I wrote a very short program that parses a "program" using python and converts it to assembler, allowing me to compile my little proramming language to an executable.
You can read my blog for more information here http://spiceycurry.blogspot.com/2010/05/simple-compil... | Where can I find documentation on assembler? | I wrote a very short program that parses a "program" using python and converts it to assembler, allowing me to compile my little proramming language to an executable.
You can read my blog for more information here http://spiceycurry.blogspot.com/2010/05/simple-compilable-programming-language.html
my question is... W... | [
"I'd rather recomment using LLVM:\n\nIt allows you not to bother with low-level details like register allocations (you provide only SSA form)\nIt does optimizations for you. It can be faster then the hand-written and well-optimized compiler as the LLVM pipeline in GHC is showing (at the beginning - before much opti... | [
1
] | [] | [] | [
"assembly",
"compiler_construction",
"gnu_assembler",
"ld",
"python"
] | stackoverflow_0002873431_assembly_compiler_construction_gnu_assembler_ld_python.txt |
Q:
How to execute machine language from memory?
I wrote a program to compile a simple text program to a compiled executable... Is it possible that I can load an executable to memory an some how point a pc counter to the memory space at will?
Here is what I made that I would like to store the programs to memory for ex... | How to execute machine language from memory? | I wrote a program to compile a simple text program to a compiled executable... Is it possible that I can load an executable to memory an some how point a pc counter to the memory space at will?
Here is what I made that I would like to store the programs to memory for execution on demand... Kind of wanting to make a lit... | [
"Is it a executable file in memory(like ELF or something like that)? or just executable code in memory?\nIf it is executable code in memory you could jmp there if the containing memory is executable and the execution will continue from there.\nIf it is an executable file you need to actually read and interpret the ... | [
1,
1,
0
] | [] | [] | [
"assembly",
"compiler_construction",
"python"
] | stackoverflow_0002873571_assembly_compiler_construction_python.txt |
Q:
"UserWarning: Unbuilt egg for setuptools" - What does this actually mean?
When I install things into a virtualenv using pip I often see the message "UserWarning: Unbuilt egg for setuptools". I always safely ignore it and go about my business and it doesn't seem to cause me any problems.
But I've suddenly been sma... | "UserWarning: Unbuilt egg for setuptools" - What does this actually mean? | When I install things into a virtualenv using pip I often see the message "UserWarning: Unbuilt egg for setuptools". I always safely ignore it and go about my business and it doesn't seem to cause me any problems.
But I've suddenly been smacked in the face with curiosity, and wondered if someone could explain what it ... | [
"The answer and workaround in this Ubuntu bug report fixed this issue for me, where I was reading the same error while using interactive trac-admin command.\nMarius Gedminas, said:\n\nWorkaround:\nsudo rmdir /usr/lib/python2.6/dist-packages/setuptools.egg-info\nsudo apt-get install --reinstall python-setuptools\nTh... | [
14
] | [] | [] | [
"distribute",
"pip",
"python",
"setuptools"
] | stackoverflow_0002643835_distribute_pip_python_setuptools.txt |
Q:
problem in extracting the data from text file
i am new to python , and I want to extract the data from this format
FBpp0143497 5 151 5 157 PF00339.22 Arrestin_N Domain 1 135 149 83.4 1.1e-23 1 CL0135
FBpp0143497 183 323 183 324 PF02752.15 Arrestin_C Domain 1 137 138 58.5 6e-16 1 CL0135
FBpp0131987 60 280 51 280 PF... | problem in extracting the data from text file | i am new to python , and I want to extract the data from this format
FBpp0143497 5 151 5 157 PF00339.22 Arrestin_N Domain 1 135 149 83.4 1.1e-23 1 CL0135
FBpp0143497 183 323 183 324 PF02752.15 Arrestin_C Domain 1 137 138 58.5 6e-16 1 CL0135
FBpp0131987 60 280 51 280 PF00089.19 Trypsin Domain 14 219 219 127.7 3.7e-37 1 ... | [
"to iterate over a file line-by-line, you should do:\nwith open(fname) as file:\n for line in file:\n fields = line.split('\\t')\n print(fields) # select fields you want to print\n\n",
"Use the csv module to parse your tab-separated fields:\nimport csv\nfilename='/ddfs/user/data/k/ktrip_... | [
3,
1,
0
] | [] | [] | [
"python",
"string",
"text_processing"
] | stackoverflow_0002873929_python_string_text_processing.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.