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:
match until a certain pattern using regex
I have string in a text file containing some text as follows:
txt = "java.awt.GridBagLayout.layoutContainer"
I am looking to get everything before the Class Name, "GridBagLayout".
I have tried something the following , but I can't figure out how to get rid of the "."
tx... | match until a certain pattern using regex | I have string in a text file containing some text as follows:
txt = "java.awt.GridBagLayout.layoutContainer"
I am looking to get everything before the Class Name, "GridBagLayout".
I have tried something the following , but I can't figure out how to get rid of the "."
txt = re.findall(r'java\S?[^A-Z]*', txt)
and I g... | [
"Without using capture groups, you can use lookahead (the (?= ... ) business).\njava\\s?[^A-Z]*(?=\\.[A-Z]) should capture everything you're after. Here it is broken down:\njava //Literal word \"java\"\n\\s? //Match for an optional space character. (can change to \\s* if there can be multiple... | [
19,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006656515_python_regex.txt |
Q:
If statement returning the wrong value?
An if statement in Python evaluates and it appears returns the non-expected value.
p = sub.Popen('md5.exe -n md5.exe',stdout=sub.PIPE,stderr=sub.PIPE)
md5, errors = p.communicate()
print md5
abc = "8D443F2E93A3F0B67F442E4F1D5A4D6D"
print abc
if md5 == abc: print 'TRUE'
else:... | If statement returning the wrong value? | An if statement in Python evaluates and it appears returns the non-expected value.
p = sub.Popen('md5.exe -n md5.exe',stdout=sub.PIPE,stderr=sub.PIPE)
md5, errors = p.communicate()
print md5
abc = "8D443F2E93A3F0B67F442E4F1D5A4D6D"
print abc
if md5 == abc: print 'TRUE'
else: print 'FALSE'
repr(md5) is '8D443F2E93A3F0B... | [
"Your md5 contains trailing whitespace, which the abc value does not have. Most command-line programs end with a line break because it can be disruptive to shell users not to. It's possible to output this to the standard error stream so as not to interfere with programs like yours, but this is often not done.\nYou ... | [
9
] | [] | [] | [
"if_statement",
"python",
"string"
] | stackoverflow_0006656861_if_statement_python_string.txt |
Q:
Calculating the percentage of variance measure for k-means?
On the Wikipedia page, an elbow method is described for determining the number of clusters in k-means. The built-in method of scipy provides an implementation but I am not sure I understand how the distortion as they call it, is calculated.
More precisel... | Calculating the percentage of variance measure for k-means? | On the Wikipedia page, an elbow method is described for determining the number of clusters in k-means. The built-in method of scipy provides an implementation but I am not sure I understand how the distortion as they call it, is calculated.
More precisely, if you graph the percentage of variance explained by
the clust... | [
"The distortion, as far as Kmeans is concerned, is used as a stopping criterion (if the change between two iterations is less than some threshold, we assume convergence)\nIf you want to calculate it from a set of points and the centroids, you can do the following (the code is in MATLAB using pdist2 function, but it... | [
57,
6
] | [] | [] | [
"cluster_analysis",
"k_means",
"numpy",
"python",
"statistics"
] | stackoverflow_0006645895_cluster_analysis_k_means_numpy_python_statistics.txt |
Q:
Manager for a user profile to create and delete both user and the profile
I have a model called Personnel which I'm using as the profile model for the User model. Moderators on my site can create and their own accounts but all the profile fields should be filled in. Here's my model
class Personnel(models.Model):
... | Manager for a user profile to create and delete both user and the profile | I have a model called Personnel which I'm using as the profile model for the User model. Moderators on my site can create and their own accounts but all the profile fields should be filled in. Here's my model
class Personnel(models.Model):
"""
Model for storing the personnel information
"""
user = model... | [
"It's probably easier to add methods to Personnel.save() and Personnel.delete() to do this work.\nhttps://docs.djangoproject.com/en/1.3/topics/db/models/#overriding-model-methods\nThe Personnel.save() is called by Django and can create a missing User and Profile.\nThe \"Overriding Delete\" sidebar may not be relev... | [
1,
1
] | [] | [] | [
"authentication",
"django",
"django_contrib",
"python"
] | stackoverflow_0006656034_authentication_django_django_contrib_python.txt |
Q:
Content-based video searching using python or other alternatives?
I came across this library PimPy http://pim.gforge.inria.fr/pimpy/
and it has the content-based retrieval feature http://pim.gforge.inria.fr/pimpy/examples.html#video-content-based-retrieval.
But I've been facing too many errors. I've been googling... | Content-based video searching using python or other alternatives? | I came across this library PimPy http://pim.gforge.inria.fr/pimpy/
and it has the content-based retrieval feature http://pim.gforge.inria.fr/pimpy/examples.html#video-content-based-retrieval.
But I've been facing too many errors. I've been googling alot for solutions but haven't found any. So basically I'm wondering i... | [
"Python is high-level language and not suitalbe for video processing as is. What Python libs do is that they provide a wrapper around some lower lever graphics library to rely the actual processing.\nPython: easy programming\nLow level library: needed speed for video processing\nYou should stop googling around Pyth... | [
1
] | [] | [] | [
"python",
"video"
] | stackoverflow_0006655236_python_video.txt |
Q:
Setting up Pyramid to use MySQL raw instead of SQLAlchemy
We're trying to set up a Pyramid project that will use MySQL instead of SQLAlchemy.
My experience with Pyramid/Python is limited, so I was hoping to find a guide online. Unfortunately, I haven't been able to find anything to push us in the right direction. ... | Setting up Pyramid to use MySQL raw instead of SQLAlchemy | We're trying to set up a Pyramid project that will use MySQL instead of SQLAlchemy.
My experience with Pyramid/Python is limited, so I was hoping to find a guide online. Unfortunately, I haven't been able to find anything to push us in the right direction. Most search results were for people trying to use raw SQL/MySQL... | [
"Pyramid at its base does not assume that you will use any one specific library to help you with your persistence. In order to make things easier, then, for people who DO wish to use libraries such as SQLALchemy, the Pyramid library contains Scaffolding, which is essentially some auto-generated code for a basic sit... | [
10,
5,
4
] | [] | [] | [
"mysql",
"pylons",
"pyramid",
"python"
] | stackoverflow_0006643780_mysql_pylons_pyramid_python.txt |
Q:
python sax parser skipping over exception
Is there a way to "skip" a line using a SAX XML parser?
I've got a non-confirming XML document which is a concatenation of valid XML documents and thus the <?xml ...?> appears for each document. Also note I need to use a SAX parser since the input documents are huge.
I tr... | python sax parser skipping over exception | Is there a way to "skip" a line using a SAX XML parser?
I've got a non-confirming XML document which is a concatenation of valid XML documents and thus the <?xml ...?> appears for each document. Also note I need to use a SAX parser since the input documents are huge.
I tried crafting a "custom stream" class as feeder ... | [
"When you are concatenating the documents together, just replace the beginning <? and ?> with <!-- and -->, this will comment out the xml declarations.\n"
] | [
0
] | [] | [] | [
"python",
"sax",
"xml"
] | stackoverflow_0006344070_python_sax_xml.txt |
Q:
text layout recognition with python
I'm trying to sort through several thousand scanned files and sort them into folders based on type (ie: if one of the files is a scanned copy of formA, then it should go in the formA folder, if it's a scanned copy of formB, then it should go in the formB folder, etc...). I feel ... | text layout recognition with python | I'm trying to sort through several thousand scanned files and sort them into folders based on type (ie: if one of the files is a scanned copy of formA, then it should go in the formA folder, if it's a scanned copy of formB, then it should go in the formB folder, etc...). I feel like the best way to match the files and ... | [
"This library is probably of interest to you -\nhttp://code.google.com/p/ocropus/\nIts made by googlers and lets you do OCR and layout analysis from python.\nI had some trouble installing it, but that was quite a while back, so things may have gotten fixed by now.\n",
"I don't know in what format you've got the s... | [
4,
1
] | [] | [] | [
"document_layout_analysis",
"image_processing",
"ocr",
"python"
] | stackoverflow_0006656012_document_layout_analysis_image_processing_ocr_python.txt |
Q:
How do I use Selenium to login to sites that require username and password?
I am developing an automated test scripts using selenium api with python. But when i run the script from selenium rc its goes to the login page. How will I be able to put in my username and password on that page as it does not contain any ... | How do I use Selenium to login to sites that require username and password? | I am developing an automated test scripts using selenium api with python. But when i run the script from selenium rc its goes to the login page. How will I be able to put in my username and password on that page as it does not contain any sessions or cookies?
| [
"Here's the suggestion that was made to me by Adam Goucher on the Selenium IRC channel ( irc://irc.freenode.net/selenium ):\nTake advantage of the situation of a completely clean browser cache/cookie history. Code your test to do the login.\nHowever, instead of hard-coding into your code a username and password, k... | [
8,
5
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0005577065_python_selenium.txt |
Q:
Python: using pyodbc and replacing row field values
I'm trying to figure out if it's possible to replace record values in a Microsoft Access (either .accdb or .mdb) database using pyodbc. I've poured over the documentation and noted where it says that "Row Values Can Be Replaced" but I have not been able to make i... | Python: using pyodbc and replacing row field values | I'm trying to figure out if it's possible to replace record values in a Microsoft Access (either .accdb or .mdb) database using pyodbc. I've poured over the documentation and noted where it says that "Row Values Can Be Replaced" but I have not been able to make it work.
More specifically, I'm attempting to replace a ro... | [
"The \"Row values can be replaced\" from the pyodbc documentation refers to the fact that you can modify the values on the returned row objects, for example to perform some cleanup or conversion before you start using them. It does not mean that these changes will automatically be persisted in the database. You wil... | [
0
] | [] | [] | [
"pyodbc",
"python"
] | stackoverflow_0006656462_pyodbc_python.txt |
Q:
When walking through files and folders, how do I compare the current filename with the next, in python?
I'm running a script that runs through folders and files and use these very simple loops. Now I was wondering how I could compare the current filename with the one that comes next, within this loop?
list_of_file... | When walking through files and folders, how do I compare the current filename with the next, in python? | I'm running a script that runs through folders and files and use these very simple loops. Now I was wondering how I could compare the current filename with the one that comes next, within this loop?
list_of_files = {}
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
... | [
"You may be able to extend this to do what you want:\n>>> for a, b in zip(range(10), range(10)[1:]):\n... print a, b\n\nlike this:\nfor filename, next in zip(filenames, filenames[1:]):\n print filename, next\n\nEdit: I forgot about itertools.\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), .... | [
4,
1,
0
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0006657599_directory_python.txt |
Q:
Python scientific notation using D instead of E
Some results file produced by Fortran programs report double precision numbers (in scientific notation) using the letter D instead of E, for instance:
1.2345D+02
# instead of
1.2345E+02
I need to process huge amounts of this data using Python, and I just realized it... | Python scientific notation using D instead of E | Some results file produced by Fortran programs report double precision numbers (in scientific notation) using the letter D instead of E, for instance:
1.2345D+02
# instead of
1.2345E+02
I need to process huge amounts of this data using Python, and I just realized it cannot read the numbers in the D notation, for insta... | [
"The simplest way, from your Python program, would be just to add a step before you interpret each entry:\n>>> val = \"1.5698D+03\" # 1,569.8\n>>> print float(val.replace('D', 'E'))\n1569.8\n\n",
"If you are dealing with lots of data and/or are doing a lot computations with that data, you might consider using th... | [
14,
14,
8
] | [] | [] | [
"locale",
"python",
"scientific_notation"
] | stackoverflow_0001959210_locale_python_scientific_notation.txt |
Q:
Replace character in HTML tag with REGEX
Possible Duplicate:
Replace all < and > that are NOT part of an HTML tag
Using Python
I know how much everyone here hates REGEX questions surrounding HTML tags, but I am just doing this as a exercise to help my learn REGEX.
Replace (1 can be any character):
<b>< </b>
<b>... | Replace character in HTML tag with REGEX |
Possible Duplicate:
Replace all < and > that are NOT part of an HTML tag
Using Python
I know how much everyone here hates REGEX questions surrounding HTML tags, but I am just doing this as a exercise to help my learn REGEX.
Replace (1 can be any character):
<b>< </b>
<b> < </b>
<b> <</b>
<b><</b>
<b><111</b>
<b>11... | [
"I sincerely hope this is never used on actual HTML, but here is a solution that works for your example data. Note that it replaces with < like your sample code, not & like in your sample data.\nre.sub(r'<+([^<>]*?)(?=</)', r'<\\1', your_string)\n\n",
"You could use something like this:\nre.sub(r'(?:<(?!/?... | [
0,
-1
] | [
"if a is your string, this seems to work:\nre.sub('<+([^b/])','&\\\\1',a)\n\nand a second version, more generic...\nre.sub('(<[^<>]+>)([^<>]*)<+([^<>]*)(<[^<>]+>)','\\\\1\\\\2&\\\\3\\\\4',a)\n\n",
"This tested regex works for your given test data:\nreobj = re.compile(r\"\"\"\n # Match left angle brackets not p... | [
-1,
-1
] | [
"html",
"python",
"regex"
] | stackoverflow_0006657118_html_python_regex.txt |
Q:
How to page the dataset
Hi I want to enable web pagination that used to work and it broke during an update to the environment or my implementation (not sure which). I want to paginate a list ordered by GAE
Since objects tend to have a "natural ordering" ie time, numbers, words etc could this code be already avail... | How to page the dataset | Hi I want to enable web pagination that used to work and it broke during an update to the environment or my implementation (not sure which). I want to paginate a list ordered by GAE
Since objects tend to have a "natural ordering" ie time, numbers, words etc could this code be already available somewhere usable? I trie... | [
"Query cursors are built for exactly this. You should use them instead of building your own solution.\n",
"You may need to base64 encoded your bookmark before you pass it to client.\nI have tried [Your site][1], but it is impossible to answer your question clearly without the server side error message.\nMoreover,... | [
3,
1
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"pagination",
"python"
] | stackoverflow_0006642707_django_django_templates_google_app_engine_pagination_python.txt |
Q:
Using imaplib to log into Gmail using credentials from a file
I apologise in advance, I know this will be a simple answer but I'm not having any luck and it's starting to bug me.
I just want to log into my Gmail account using imaplib and credentials pulled from a file.
I can log into Gmail no worries using:
srv = ... | Using imaplib to log into Gmail using credentials from a file | I apologise in advance, I know this will be a simple answer but I'm not having any luck and it's starting to bug me.
I just want to log into my Gmail account using imaplib and credentials pulled from a file.
I can log into Gmail no worries using:
srv = imaplib.IMAP_SSL("imap.gmail.com")
srv.login("bob@gmail.com", "mypa... | [
"readline() includes the newline character at the end of the line, so you're really saying: login with 'bob@gmail.com\\n'\nTry readline().strip() to strip whitespace characters from both sides of the line.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006658057_python.txt |
Q:
python: composition of `int` and `float`
As part of some other calculations, I noticed that I sometimes apply float() and then int() function to an integer input. Is it safe to assume that:
int(float(x)) == x
if x is integer?
Why? (Or why not?) And is it documented anywhere?
A:
If x needs more precision than pr... | python: composition of `int` and `float` | As part of some other calculations, I noticed that I sometimes apply float() and then int() function to an integer input. Is it safe to assume that:
int(float(x)) == x
if x is integer?
Why? (Or why not?) And is it documented anywhere?
| [
"If x needs more precision than provided by double-precision floating point numbers then the comparison will fail.\n>>> int(float(10**23))\n99999999999999991611392L\n\n",
">>> x = 10**300\n>>> int(float(x)) == x\nFalse\n\n",
"\nWhy? (Or why not?) And is it documented anywhere?\n\nOne of the definitive guides th... | [
8,
5,
4,
3
] | [] | [] | [
"floating_point",
"python",
"python_3.x"
] | stackoverflow_0006657995_floating_point_python_python_3.x.txt |
Q:
Class Inheritance, redefining __init__ on with taking a new argument
I'm new to Python, I still have issues with the semantics of class inheritance.
The following is the relevant class from the module games.py module that I am importing:
class Text(Sprite):
"""
Alphanumeric values displayed on the scre... | Class Inheritance, redefining __init__ on with taking a new argument | I'm new to Python, I still have issues with the semantics of class inheritance.
The following is the relevant class from the module games.py module that I am importing:
class Text(Sprite):
"""
Alphanumeric values displayed on the screen.
"""
def __init__(self, value, size, color, angle=0,
... | [
"Your problem is, that you you are ordering the arguments incorrectly: there are positional and keyword arguments. All keywords arguments must succeed the positional arguments.\nThis would work:\nself.scorebox = games.Text (\n pygame.font.Font(ardarlingopentype, 50),\n ... | [
2,
1,
0
] | [] | [] | [
"class",
"inheritance",
"pygame",
"python"
] | stackoverflow_0006652186_class_inheritance_pygame_python.txt |
Q:
Java: BufferedReader reads self-updating shell-output from a Python Script and regexes live, updates every 5 sec
The problem is this: I have a Python Script which generates Shell output. This output looks like this:
Result: good.
[123 SPEED] [456 GOOD] [789 BAD]
The last line updates itself and becomes either a... | Java: BufferedReader reads self-updating shell-output from a Python Script and regexes live, updates every 5 sec | The problem is this: I have a Python Script which generates Shell output. This output looks like this:
Result: good.
[123 SPEED] [456 GOOD] [789 BAD]
The last line updates itself and becomes either a result:good or result:bad line. Then again the last line updates itself and erases the previous one. I found a way ho... | [
"Try not using a BufferedReader -- use the InputStreamReader directly--\nOr have the python process output new lines between each bracketed item\nThe BufferedStreamReader is waiting for the buffer to fill or for a new line before it returns anything to your Java process\n"
] | [
2
] | [] | [] | [
"bash",
"java",
"python",
"regex",
"timer"
] | stackoverflow_0006658339_bash_java_python_regex_timer.txt |
Q:
'With' in pre python 2.5
Is there a means of converting a python 'with' statement into a format that can be used in previous versions of python. 4 month's work hinging on this question. with are there to be more efficient than their previous counterparts, but efficiency is not important here.
A:
Use try: excep... | 'With' in pre python 2.5 | Is there a means of converting a python 'with' statement into a format that can be used in previous versions of python. 4 month's work hinging on this question. with are there to be more efficient than their previous counterparts, but efficiency is not important here.
| [
"Use try: except: finally:\nThe finally: clause can handle the close.\nSee http://www.python.org/dev/peps/pep-0343/ for alternatives.\n",
"As S.Lott has stated, try and finally should handle the work of the with clause. I'm not sure that with actually catches any errors, so given that assumption:\nwith open(file_... | [
3,
0
] | [] | [] | [
"legacy",
"python",
"with_statement"
] | stackoverflow_0006658346_legacy_python_with_statement.txt |
Q:
Is there a way to cache the fetch output?
I'm working on a closed system running in the cloud.
What I need is a search function that uses user-typed-in regexp to filter the rows in a dataset.
phrase = re.compile(request.get("query"))
data = Entry.all().fetch(50000) #this takes around 10s when there are 6000 recor... | Is there a way to cache the fetch output? | I'm working on a closed system running in the cloud.
What I need is a search function that uses user-typed-in regexp to filter the rows in a dataset.
phrase = re.compile(request.get("query"))
data = Entry.all().fetch(50000) #this takes around 10s when there are 6000 records
result = x for x in data if phrase.search(x.... | [
"You can also use cachepy or performance engine (shameless plug) to store the data on app engine's local instances, so you can have faster access to all entities without getting limited by memcache boundaries or datastore latency. \nHint: A local instance gets killed if it surpasses about 185 MB of memory, so you c... | [
2,
1,
1
] | [] | [] | [
"datastore",
"google_app_engine",
"python"
] | stackoverflow_0006653853_datastore_google_app_engine_python.txt |
Q:
delete a line in .txt using python by matching the number in the line
I finally came to my last part.. and I'm stuck..
In my orderlist.txt file I have
[99 ,1, "3/03/2011", ["ScrewDriver", "Hammer", "Stone"]]
[2 ,2, "3/03/2011", ["hammer,nails"]]
[31 ,2, "3/03/2011", ["plaster,studd"]]
[100 ,2, "3/03/2011", ["hamme... | delete a line in .txt using python by matching the number in the line | I finally came to my last part.. and I'm stuck..
In my orderlist.txt file I have
[99 ,1, "3/03/2011", ["ScrewDriver", "Hammer", "Stone"]]
[2 ,2, "3/03/2011", ["hammer,nails"]]
[31 ,2, "3/03/2011", ["plaster,studd"]]
[100 ,2, "3/03/2011", ["hammer,studd"]]
my code:
def delorder():
f=open('orderlist.txt',"r+")
l... | [
"I'm not sure if you see them, but look closely at those quotation marks:\n[1,'1','3/03/2011', [“ScrewDriver”, “Hammer”, “Stone”]]\n\nThere's a difference between this:\n”\n\nand this:\n\"\n\nThe first one (”) is a curly quote, which screws up the interpreter. Use normal quotes (\") and post back what your script r... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006658879_python.txt |
Q:
Python find object in a list
I have a list of people:
[
{'name' : 'John', 'wins' : 10 },
{'name' : 'Sally', 'wins' : 0 },
{'name' : 'Fred', 'wins' : 3 },
{'name' : 'Mary', 'wins' : 6 }
]
I am adding wins using a list of names (['Fred', 'Mary', 'Sally']). I don't know if the name is in the list of ... | Python find object in a list | I have a list of people:
[
{'name' : 'John', 'wins' : 10 },
{'name' : 'Sally', 'wins' : 0 },
{'name' : 'Fred', 'wins' : 3 },
{'name' : 'Mary', 'wins' : 6 }
]
I am adding wins using a list of names (['Fred', 'Mary', 'Sally']). I don't know if the name is in the list of people already, and I need to inse... | [
"I'm assuming here that you don't want to use any structure other than the list. Your code should work, although you unnecessarily write the dictionary back to the list after updating it. Dictionaries are copied by reference, so once you update it, it stays updated in the list. After a little housekeeping, your cod... | [
14,
9,
7,
4,
0
] | [] | [] | [
"indexing",
"list",
"python",
"search"
] | stackoverflow_0005120391_indexing_list_python_search.txt |
Q:
mongodb python get the element position from an array in a document
I use python + mongodb to store some item ranking data in a collection called chart
{
date: date1,
region: region1,
ranking: [
{
item: bson.dbref.DBRef(db.item.find_one()),
price: current_price,
version: '1.0'
},
... | mongodb python get the element position from an array in a document | I use python + mongodb to store some item ranking data in a collection called chart
{
date: date1,
region: region1,
ranking: [
{
item: bson.dbref.DBRef(db.item.find_one()),
price: current_price,
version: '1.0'
},
{
item: bson.dbref.DBRef(db.item.find_another_one()),
price... | [
"The $ positional operator is only used in update(...) calls, you can't use it to return the position within an array.\nHowever, you can use field projection to limit the fields returned to just those you need to calculate the position in the array from within Python:\ndb.foo.insert({\n'date': '2011-04-01',\n'regio... | [
3
] | [] | [] | [
"mongodb",
"nosql",
"python"
] | stackoverflow_0006658842_mongodb_nosql_python.txt |
Q:
Schedule some jobs with php/python at some specific time without crontab
I have some irregular jobs to do(frequent and many), so I can't use the crontab.
for example:
send an email at 10:20AM on July 22 2012
post a article at 11PM tonight
run a script at 9:50AM tomorrow.
I found the linux commond at, but that ca... | Schedule some jobs with php/python at some specific time without crontab | I have some irregular jobs to do(frequent and many), so I can't use the crontab.
for example:
send an email at 10:20AM on July 22 2012
post a article at 11PM tonight
run a script at 9:50AM tomorrow.
I found the linux commond at, but that can't be managed easily, otherwise, I search some message queue (like zeromq) an... | [
"Unfortunately, your choice is cron or manually manage sleep.\nIf you're using Django, however, this has already been accomplished for you.\n",
"How about APScheduler?\nimport time\nfrom datetime import datetime\nfrom apscheduler.scheduler import Scheduler\n\n# Schedule my_job for year, month, day, hour (out of 2... | [
0,
0
] | [] | [] | [
"at_job",
"php",
"python",
"schedule"
] | stackoverflow_0006659035_at_job_php_python_schedule.txt |
Q:
python PIL YCbCr support
Trying to create an PIL image in YCbCr mode crashes even a fresh python/PIL installation from synaptic in my ubuntu 11.04
wim@wim-ubuntu:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information... | python PIL YCbCr support | Trying to create an PIL image in YCbCr mode crashes even a fresh python/PIL installation from synaptic in my ubuntu 11.04
wim@wim-ubuntu:~$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Image
>>> Image.V... | [
"Tracing down the source and it seems that it's the strcpy() at libImaging/Storage.c:186 that caused the buffer overflow. Further looking at the code and I found that im->mode is not big enough to hold \"YCbCr\".\nTo solve this problem, just change libImaging/Imaging.h:78 from char mode[4+1]; to char mode[4+2];char... | [
6
] | [] | [] | [
"crash",
"python",
"python_imaging_library",
"yuv"
] | stackoverflow_0006080825_crash_python_python_imaging_library_yuv.txt |
Q:
'LIKE' function for Lists
Is there any equivalent 'LIKE' function(like in MySQL) for lists. for example;
This is my list:
abc = ['one', 'two', 'three', 'twenty one']
if I give the word "on", it should print the matching words from the list (in this case: 'one', 'twenty one') and if I give "fo", it should print F... | 'LIKE' function for Lists | Is there any equivalent 'LIKE' function(like in MySQL) for lists. for example;
This is my list:
abc = ['one', 'two', 'three', 'twenty one']
if I give the word "on", it should print the matching words from the list (in this case: 'one', 'twenty one') and if I give "fo", it should print False
| [
"You can use list comprehension:\n[m for m in abc if 'on' in m]\n\nThis roughly translates to \"for each element in abc, append element to a list if the element contains the substring 'on'\"\n",
">>> abc = ['one', 'two', 'three', 'twenty one']\n>>> print [word for word in abc if 'on' in word]\n['one', 'twenty one... | [
10,
3,
3
] | [
"for x in abc:\n if \"on\" in x:\n print x\n\nOr, as a function,\ndef like(str, search):\n res = []\n for x in search:\n if str in x:\n res.append(x)\n return res\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0006659616_python.txt |
Q:
App Engine Datastore join with filter on reference
I'm very new to App Engine Datastore and I could not figure this out.
I have these models:
class SomeUser(User):
name = db.StringProperty()
class Group(db.Model):
title = db.StringProperty()
date_started = db.DateTimeProperty(auto_now_add... | App Engine Datastore join with filter on reference | I'm very new to App Engine Datastore and I could not figure this out.
I have these models:
class SomeUser(User):
name = db.StringProperty()
class Group(db.Model):
title = db.StringProperty()
date_started = db.DateTimeProperty(auto_now_add=True)
class GroupParticipant(db.Model):
group ... | [
"There is no joins at all. You have to fetch all data manually. For example you can fetch all records from GroupParticipant, and then fetch all Group and SomeUser in loop (note that fetching by Key is very fast)\n--\nbtw, probably it's better to use different data structures, like\nclass SomeUser(User):\n na... | [
3
] | [] | [] | [
"datastore",
"google_app_engine",
"gql",
"python"
] | stackoverflow_0006659958_datastore_google_app_engine_gql_python.txt |
Q:
Insertion With SQLAlchemy
So I have a class defined as follows:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
hashed_password = db.Column(db.String(100))
friends = db.relationship('User',
... | Insertion With SQLAlchemy | So I have a class defined as follows:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
hashed_password = db.Column(db.String(100))
friends = db.relationship('User',
backref='user', lazy='dynam... | [
"You need to look at your problem from the database schema perspective and then write the SQLAlchemy code to generate that schema. This is important because SA abstracts little out of the schema generation and the ORM is a separate component (this is one of the best aspects SQLAlchemy). Using the declarative extens... | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006658137_python_sqlalchemy.txt |
Q:
IOErrors for regular expression in python
I've been working on a program, but due to Mac OS X's difficulties in updating python, I've been doing it in both 3.2 and 2.6, nevertheless, both versions of the script give me IOErrors (they're different though). Here's the script:
This is the 3.2 version:
import sys
impo... | IOErrors for regular expression in python | I've been working on a program, but due to Mac OS X's difficulties in updating python, I've been doing it in both 3.2 and 2.6, nevertheless, both versions of the script give me IOErrors (they're different though). Here's the script:
This is the 3.2 version:
import sys
import os
import re
import urllib
import urllib.... | [
"You call open on the string, which tries to open a file named whatever the string contains. In this case <!DOCTYPE.... And that is not a valid filename or existing file. If you replace open(urlfile).read() with just urlfile, it should work.\nAlso, you might want to escape the []s in the regexp, or it won't do what... | [
3,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006659981_python_regex.txt |
Q:
Understanding some Python code
I'm working my way through Gmail access using imaplib and came across:
# Count the unread emails
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount
I just wish to know what:
status,
does in front of t... | Understanding some Python code | I'm working my way through Gmail access using imaplib and came across:
# Count the unread emails
status, response = imap_server.status('INBOX', "(UNSEEN)")
unreadcount = int(response[0].split()[2].strip(').,]'))
print unreadcount
I just wish to know what:
status,
does in front of the "response =". I would google it, ... | [
"When a function returns a tuple, it can be read by more than one variable.\ndef ret_tup():\n return 1,2 # can also be written with parens\n\na,b = ret_tup()\n\na and b are now 1 and 2 respectively\n",
"See this page:\nhttp://docs.python.org/tutorial/datastructures.html\nSection 5.3 mentions 'multiple assignme... | [
13,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0006659073_python.txt |
Q:
Manipulating paths in python
I am writing a python script 2.5 in Windows whose CurrentDir = C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\source my file is test.py. From this path I would like to access files in this path: C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\Common\
I tried using os.pa... | Manipulating paths in python | I am writing a python script 2.5 in Windows whose CurrentDir = C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\source my file is test.py. From this path I would like to access files in this path: C:\users\spring\projects\sw\demo\753\ver1.1\011\rev120\Common\
I tried using os.path.join but it does not work and I... | [
"from os.path import dirname, join\njoin(dirname(dirname(__file__)), 'Common')\n\nshould work.\n",
"Your problem can be solved by using os.path.join, but you're not using it properly.\ncurrentdir = os.getcwd() \nconfig_file_path = os.path.join(currentdir,\"\\\\..\\\\Common\")\n\n\"\\\\..\\\\Common\" is not a ... | [
2,
2,
0
] | [] | [] | [
"path_manipulation",
"python"
] | stackoverflow_0006660102_path_manipulation_python.txt |
Q:
Showing form elements based on another tables data
I have the following models:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
bool1_name = models.CharField(max_length=... | Showing form elements based on another tables data | I have the following models:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
bool1_name = models.CharField(max_length=60, blank=True, null=True)
bool1_default = models.Bo... | [
"Why bother with exclude, and metaclasses - just delete fields you want to exclude:\nclass ProductDataForm(ModelForm):\n __init__():\n ...\n for field_name in PRODUCTDATA_EXCLUDE_FIELDS:\n del self.fields[field_name]\n ...\n\nMaybe it's not quite right, but it's simple, and... | [
4,
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0006608185_django_django_forms_django_models_python.txt |
Q:
reprompting after invalid input
There was no problem until I tried to make an input go through validity check and if invalid ask again for input
i'm counting on you for ideas thanks in advance :)
a=0
def reinp(a,b):
while True:
if a in [1,2,3,4,5,6]: #checking for valid input
return int(a)
... | reprompting after invalid input | There was no problem until I tried to make an input go through validity check and if invalid ask again for input
i'm counting on you for ideas thanks in advance :)
a=0
def reinp(a,b):
while True:
if a in [1,2,3,4,5,6]: #checking for valid input
return int(a)
break
a=input(b)
... | [
"[EDIT: Deleted original answer, since no longer relevant with fixed formatting on question]\nThe problem with reinp is that a will be a string, and you're checking it against integers.\n...so change: \n if a in [1,2,3,4,5,6]: #checking for valid input\n\nto:\n if a in ['1','2','3','4','5','6']: #checking fo... | [
1,
1
] | [] | [] | [
"input",
"loops",
"python",
"while_loop"
] | stackoverflow_0006653655_input_loops_python_while_loop.txt |
Q:
Python: Map float range [0.0, 1.0] to color range [red, green]?
I have a function that returns float results in the interval [0.0, 1.0]. I would like to visualize the results using color ranging from red for 0.0 to green for 1.0 (maybe through yellow for 0.5). How could I do that? Thanks!
A:
I think the simplest... | Python: Map float range [0.0, 1.0] to color range [red, green]? | I have a function that returns float results in the interval [0.0, 1.0]. I would like to visualize the results using color ranging from red for 0.0 to green for 1.0 (maybe through yellow for 0.5). How could I do that? Thanks!
| [
"I think the simplest way is to work in HSL/HSB (hue saturation lightness), where the hue values 0-33% of the maximum will map to the range red-orange-yellow-green. The advantage of working is HSL (vs RGB) is that the resulting color range will be much better-looking (eg bright yellow in RGB contains a pinch of bl... | [
4,
2
] | [] | [] | [
"colors",
"python",
"range"
] | stackoverflow_0006660879_colors_python_range.txt |
Q:
creating dmg for python distribution
So I'm having a little problem here. I'm developing a project on MacOS using python. So far I've created an install that looks like this:
python get-pip.py
python ez_setup.py
pip install numpy
pip install scipy
pip install quantities
cd ../../externals
python setup.py install... | creating dmg for python distribution | So I'm having a little problem here. I'm developing a project on MacOS using python. So far I've created an install that looks like this:
python get-pip.py
python ez_setup.py
pip install numpy
pip install scipy
pip install quantities
cd ../../externals
python setup.py install
cd buffet
python setup.py install
cd ..... | [
"I really wonder why you are not using python distutils or setuptools and using an install.sh file.\nhttp://docs.python.org/library/distutils.html\n"
] | [
2
] | [] | [] | [
"dmg",
"python"
] | stackoverflow_0006661337_dmg_python.txt |
Q:
Reverse looking up a table linked to the profile model linked to the User model
I'm uisng django.contrib.auth for authentication. The User mode has a custom profile model called Personnel. Personnel is linked to another table called Company.
class Personnel(models.Model):
"""
Model for storing the personne... | Reverse looking up a table linked to the profile model linked to the User model | I'm uisng django.contrib.auth for authentication. The User mode has a custom profile model called Personnel. Personnel is linked to another table called Company.
class Personnel(models.Model):
"""
Model for storing the personnel information
"""
user = models.OneToOneField(
User
)
company... | [
"You should be able to access the company through request.user.get_profile().company. See the django documentation.\nYou cannot access request directly in a form, as the form could instantiated somewhere else too, not only in a view where no request object exists. You could pass the current user to the form when yo... | [
1,
0,
0
] | [] | [] | [
"authentication",
"django",
"django_contrib",
"python",
"request"
] | stackoverflow_0006661299_authentication_django_django_contrib_python_request.txt |
Q:
How to structure nose unit tests which build on each other?
Example
Let's say you have a hypothetical API like this:
import foo
account_name = foo.register()
session = foo.login(account_name)
session.do_something()
The key point being that in order to do_something(), you need to be registered and logged in.
Here... | How to structure nose unit tests which build on each other? | Example
Let's say you have a hypothetical API like this:
import foo
account_name = foo.register()
session = foo.login(account_name)
session.do_something()
The key point being that in order to do_something(), you need to be registered and logged in.
Here's an over-simplified, first-pass, suite of unit tests one might ... | [
"Rather than answering the explicit question, I think a better answer is to use mock objects. In general, unit tests should not require accessing external databases (as is presumably required to log in). However, if you want to have some integration tests that do this (which is a good idea), then those tests should... | [
4,
0
] | [] | [] | [
"nose",
"python",
"unit_testing"
] | stackoverflow_0006657497_nose_python_unit_testing.txt |
Q:
Help understanding this piece of code
The full source code is @ PEP 333. These two lines:
status, response_headers = headers_sent[:] = headers_set
.. and ..
headers_set[:] = [status, response_headers]
What am I looking at here? How does [:] differ from giving nothing at all (just headers_set)? If someone could p... | Help understanding this piece of code | The full source code is @ PEP 333. These two lines:
status, response_headers = headers_sent[:] = headers_set
.. and ..
headers_set[:] = [status, response_headers]
What am I looking at here? How does [:] differ from giving nothing at all (just headers_set)? If someone could provide an explanation, I'd be really glad.
| [
"[:] means that you are overwriting the entire list's contents.\n>>> a = [1,2,3]\n>>> a[:] = [3,4]\n>>> a\n[3, 4]\n>>> a[]\n File \"<stdin>\", line 1\n a[]\n ^\nSyntaxError: invalid syntax\n\nAnd you can use the same syntax to overwrite some index range of the list:\n>>> a[2:] = [3,4]\n>>> a\n[3, 4, 3, 4]\... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006662146_python.txt |
Q:
google app engine sending mail twice
I wrote a sample code to send email from google app engine in Python. I'm not able to figure out why is it sending out every mail twice?
mail.py:-
from google.appengine.api import mail
mail.send_mail(sender="ALPHA <ALPHA@gmail.com>",
to="BETA <BETA@hotmail.com>",
... | google app engine sending mail twice | I wrote a sample code to send email from google app engine in Python. I'm not able to figure out why is it sending out every mail twice?
mail.py:-
from google.appengine.api import mail
mail.send_mail(sender="ALPHA <ALPHA@gmail.com>",
to="BETA <BETA@hotmail.com>",
subject="test mail",
body="""
... | [
"If that really is your app.yaml, then any request to your app is going to result in a mail being sent.\nIf you visit the site with a web-browser, it will first make a request for /, then probably also make a request for /favicon.ico and potentially other unintended requests. Each resulting in a mail being sent.\nY... | [
10
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0006661937_email_google_app_engine_python.txt |
Q:
GUI is very sluggish using PyQt and Qthreads
I have a problem with keeping a GUI responsive using PyQt and Qthreads. What I do is spawn a worker Qthread from the GUI which is cpu heavy. The worker Qthread sends a signal containing a numerical value in every cycle. In the GUI the signal is connected to an update fu... | GUI is very sluggish using PyQt and Qthreads | I have a problem with keeping a GUI responsive using PyQt and Qthreads. What I do is spawn a worker Qthread from the GUI which is cpu heavy. The worker Qthread sends a signal containing a numerical value in every cycle. In the GUI the signal is connected to an update function which takes the numerical value and repaint... | [
"\nA solution would be to have the worker thread trigger the signal less frequent, but I would like to get a fast update of the progress.\n\nBecause human reaction speed is much slower than the processing speed of a computer, this is the best, or at least the most likely to be simplest, solution. You can still get ... | [
2,
2
] | [] | [] | [
"pyqt4",
"python",
"qthread",
"user_interface"
] | stackoverflow_0006627513_pyqt4_python_qthread_user_interface.txt |
Q:
dealing with python global variables when using recursive functions
I made a program that extracts the text from a HTML file. It recurses down the HTML document and returns the list of tags. For eg,
input < li >no way < b > you < /b > are doing this < /li >
output ['no','way','you','are'...].
Here is a highl... | dealing with python global variables when using recursive functions | I made a program that extracts the text from a HTML file. It recurses down the HTML document and returns the list of tags. For eg,
input < li >no way < b > you < /b > are doing this < /li >
output ['no','way','you','are'...].
Here is a highly simplified pseudocode for this:
def get_leaves(node):
kids=getchild... | [
"You can pass the result list as optional argument.\ndef get_leaves(node, list_of_leaves=None):\n list_of_leaves = [] if list_of_leaves is None else list_of_leaves\n kids=getchildren(node)\n for i in kids:\n if leafnode(i):\n get_leaves(i, list_of_leaves)\n else:\n a=pro... | [
11,
8,
2,
2,
0
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0006661189_global_variables_python.txt |
Q:
How to download files from a web based file server with Python Mechanize
I have a series of files on a private ftp file server that I am trying to download using mechanize.
The mechanize link objects have the structure
Link(base_url='http://myfileserver.com/cgi-bin/index.cgi', url='index.cgi?page=download&file=%2... | How to download files from a web based file server with Python Mechanize | I have a series of files on a private ftp file server that I am trying to download using mechanize.
The mechanize link objects have the structure
Link(base_url='http://myfileserver.com/cgi-bin/index.cgi', url='index.cgi?page=download&file=%2Fhome%2Fjmyfileserver%2Fpublic_html%2Fuser_data%2Fmycompany%2F.ftpquota', text... | [
"You could try with:\nfor index, linkobj in enumerate(myfiles):\n if \"sca\" in linkobj.url:\n resp = br.follow_link(text='Download [IMG]',nr=0)\n content = resp.read()\n with open('output%s.txt' % index, 'w') as fo:\n fo.write(content)\n\n",
"If you have a ftp server, mechanize ... | [
5,
0
] | [] | [] | [
"download",
"mechanize",
"python"
] | stackoverflow_0006662774_download_mechanize_python.txt |
Q:
c style loop for in python
I need c style loop for:
for( int i = 0; i < n; i++ )
There's equivalent i've found, but when iterating with big number of iterations, it consumes a lot of memory.
for i in range( 0, n ):
Is there any other equivalent?
A:
You can use xrange instead of range, which uses a generator in... | c style loop for in python | I need c style loop for:
for( int i = 0; i < n; i++ )
There's equivalent i've found, but when iterating with big number of iterations, it consumes a lot of memory.
for i in range( 0, n ):
Is there any other equivalent?
| [
"You can use xrange instead of range, which uses a generator instead of building a whole list.\n",
"Use xrange instead of range to prevent the list from being constructed upfront. That will reduce your memory cost. \nEither that or use a while loop with a counter and break when it reaches n. \nUsually, I've found... | [
3,
3,
2,
1,
1,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0006661997_loops_python.txt |
Q:
I've defined a function and want to write the output of it to a txt file, what do I need to change in my code?
print "I can write my function to a txt file:"
my_function = raw_input("File name? ")
print_bills = input(bills(1010, 200, 100, 120))
open(my_function, 'w')
my_function.write('%r' % (print_bills))
my_fu... | I've defined a function and want to write the output of it to a txt file, what do I need to change in my code? | print "I can write my function to a txt file:"
my_function = raw_input("File name? ")
print_bills = input(bills(1010, 200, 100, 120))
open(my_function, 'w')
my_function.write('%r' % (print_bills))
my_function.close()
i'm working in python and am trying to get my function written to a txt file, the function goes like... | [
"You can reassign stdout\nimporst sys\nf = open(\"test.txt\", \"w\")\nsto = sys.stdout # save stdout so we can revert back to it\nsys.stdout = f # from now on, anything that is printed will go to test.txt\n\n# here, call any method that calls print\n# or even \nprint \"hello\"\n\n#finally when no more redirectio... | [
3,
0,
0
] | [] | [] | [
"function",
"python",
"string"
] | stackoverflow_0006658783_function_python_string.txt |
Q:
stderr.write; printing strings
I am new to Python and having some trouble with the stderr.write function. I will try to illustrate it with code. Before I was doing this:
print "Unexpected error! File {0} could not be converted." .format(src)
But then I wanted to separate the error messages from other status messa... | stderr.write; printing strings | I am new to Python and having some trouble with the stderr.write function. I will try to illustrate it with code. Before I was doing this:
print "Unexpected error! File {0} could not be converted." .format(src)
But then I wanted to separate the error messages from other status messages so I tried doing this:
sys.stder... | [
"In Python 2.x:\nsys.stderr.write(\"Unexpected error! File %s could not be converted.\" % src)\n\nOr, in Python 2.x and 3.x:\nsys.stderr.write(\"Unexpected error! File {0} could not be converted.\".format(src))\n\n",
"Functions in Python need to be followed by parens ((...)), optionally containing arguments, in o... | [
8,
1,
0,
0
] | [] | [] | [
"python",
"stderr"
] | stackoverflow_0006663778_python_stderr.txt |
Q:
From HTML to CSS style with Python
I've extracted certain elements from a HTML page with beautifulsoup and want to extract the according CSS styles (which reside in most cases in external css files) via python.
How can i get a jQuery selector if I have a HTML element? If i had this selector, i could use cssutils t... | From HTML to CSS style with Python | I've extracted certain elements from a HTML page with beautifulsoup and want to extract the according CSS styles (which reside in most cases in external css files) via python.
How can i get a jQuery selector if I have a HTML element? If i had this selector, i could use cssutils to parse the CSS and get it.
TIA for help... | [
"You may take a look at PyQuery's API. It provides similar css selector syntax as jQuery does and it's much faster than beautifulsoup because it relies on lxml to do the parsing work.\nimport pyquery.PyQuery as pq # you can treat it as a css selector\n\nhtml = '<div class=\"foo\"><a href=\"somewhere\"></a></div>'\n... | [
0
] | [] | [] | [
"beautifulsoup",
"css",
"python"
] | stackoverflow_0006662320_beautifulsoup_css_python.txt |
Q:
url requesting with different proxies in python
I am trying to retrive some pages which are google search results and cached. Actually i have two problems for now. I can normally download the first ten results, but cant get it to work to go to "next" 10 pages. I have tried to use regular expressions to find the ne... | url requesting with different proxies in python | I am trying to retrive some pages which are google search results and cached. Actually i have two problems for now. I can normally download the first ten results, but cant get it to work to go to "next" 10 pages. I have tried to use regular expressions to find the next control in the page and go from there, i couldn't ... | [
"5th example? Or maybe 3rd example?\n"
] | [
1
] | [] | [] | [
"proxy",
"python",
"web_crawler"
] | stackoverflow_0006664101_proxy_python_web_crawler.txt |
Q:
Pythonic way to remove directories from a file listing
I can think of easy ways to accomplish this, but what is the most pythonic way? I get a file listing for os.listdir, and some may be directories.
I could check through each one in a loop and check if os.isdir returns false, then remove it from the list. W... | Pythonic way to remove directories from a file listing | I can think of easy ways to accomplish this, but what is the most pythonic way? I get a file listing for os.listdir, and some may be directories.
I could check through each one in a loop and check if os.isdir returns false, then remove it from the list. What is a pythonic way to write this?
| [
"[x for x in os.listdir(...) if not os.path.isdir(os.path.join(..., x))]\n\n",
"files = filter(lambda f: os.path.isfile(os.path.join(path, f)), os.listdir(path))\n\nOR\nfiles = [f for f in os.listdir(path) if not os.path.isdir(os.path.join(path, f))]\n\nEdited: removed bug per Ignacio's answer (added in calls to ... | [
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0006664205_python.txt |
Q:
How can I use one django app ( with one db ) in two projects ? ( Using my app as a service )
The Problem ->
Suppose you have a django app called "blog", that you want to use in "www.cool.com" and "www.hot.com" which would essentially be two different django projects, ( except for the "blog" app ofcourse ).
I want ... | How can I use one django app ( with one db ) in two projects ? ( Using my app as a service ) | The Problem ->
Suppose you have a django app called "blog", that you want to use in "www.cool.com" and "www.hot.com" which would essentially be two different django projects, ( except for the "blog" app ofcourse ).
I want to this "blog" app to be like a service, which can be used by any 3rd party site.
How would you do... | [
"The question is very, very hard to follow.\nTwo django sites which share a common app is trivial. It's done all the time.\nYou're simply sharing the app code among the two sites.\nUse subversion to keep the master copy of the blog app.\nCheckout working copies for both sites.\n\nI want to this \"blog\" app to be ... | [
2,
1
] | [] | [] | [
"django",
"python",
"soa"
] | stackoverflow_0006663447_django_python_soa.txt |
Q:
How to put an image from python to klipper?
Using python, one can read in an image:
from PIL import Image, ImageTk
image = Image.open("test.jpg")
Then one can write to klipper in the following way:
import dbus
bus = dbus.SessionBus()
proxy = bus.get_object("org.kde.klipper","/klipper")
iface = dbus.Interface(prox... | How to put an image from python to klipper? | Using python, one can read in an image:
from PIL import Image, ImageTk
image = Image.open("test.jpg")
Then one can write to klipper in the following way:
import dbus
bus = dbus.SessionBus()
proxy = bus.get_object("org.kde.klipper","/klipper")
iface = dbus.Interface(proxy,"org.kde.klipper.klipper")
iface.setClipboardCo... | [
"Image is a raw Python imaging library object. You need to find out \n1) What input format Klipper excepts for images (not text?)\n2) How to serialize the image to this format. You don't pass Python image object, but probably saved data (PNG file data) to Klipper.\n",
"Found some solution - not with python but wi... | [
0,
0
] | [] | [] | [
"clipboard",
"kde4",
"kde_plasma",
"python"
] | stackoverflow_0006652559_clipboard_kde4_kde_plasma_python.txt |
Q:
Is there a simple method for mkdir that is more than one directory deep unmade?
Assume I only have the folder /root, with no subdirectories. Is there an easy method in python to create all directories for the following (in one line) /root/a/b/c/d/e/f/g/foo.exe?
A:
os.makedirs()
http://docs.python.org/library/os... | Is there a simple method for mkdir that is more than one directory deep unmade? | Assume I only have the folder /root, with no subdirectories. Is there an easy method in python to create all directories for the following (in one line) /root/a/b/c/d/e/f/g/foo.exe?
| [
"os.makedirs()\nhttp://docs.python.org/library/os.html#os.makedirs\n",
"os module:\nos.makedirs('/root/a/b/c/d/e/f/g/')\n\ndocs\n"
] | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0006664494_python.txt |
Q:
How would I get numbers from the beginning of a line of text, split them and print them out
Here is my dilemma: I'm writing an application in Python that will allow me to search a flat file (KJV bible.txt) for particular strings, and return the line number, book, and string searched for. However, I would also lik... | How would I get numbers from the beginning of a line of text, split them and print them out | Here is my dilemma: I'm writing an application in Python that will allow me to search a flat file (KJV bible.txt) for particular strings, and return the line number, book, and string searched for. However, I would also like to return the chapter and verse in which the string was found. That calls for me going to the b... | [
"Do a single split on whitespace, then split on :.\npassage, text = line.split(None, 1)\nchapter, verse = passage.split(':')\n\n",
"Use a regular expression: r'(\\d+)\\.(\\d+)'\nAfter finding a match (match = re.match(r'(\\d+)\\.(\\d+)', line)), you can find the chapter in group 1 (chapter = match.group(1)) and t... | [
5,
1
] | [] | [] | [
"file",
"python",
"text"
] | stackoverflow_0006664506_file_python_text.txt |
Q:
Use the python interpreter packaged with py2exe
I have a python script I want to distribute to Windows, where people might not have python installed. So I use py2exe. The problem is in the script I run other python scripts by using subprocess, which requires python interpreter as the program to execute. As I don... | Use the python interpreter packaged with py2exe | I have a python script I want to distribute to Windows, where people might not have python installed. So I use py2exe. The problem is in the script I run other python scripts by using subprocess, which requires python interpreter as the program to execute. As I don't have python interpreter installed on Windows, is t... | [
"It's probably more simple than you think: Instead of starting sub-processes, use the built-in eval() command to execute the scripts.\n[EDIT] To redirect stdio, replace sys.stdout/sys.stderr with buffers or something else that supports \"write()\".\nTo restore the original values, the sys module offers __stdout__, ... | [
1
] | [] | [] | [
"py2exe",
"python",
"windows"
] | stackoverflow_0006664493_py2exe_python_windows.txt |
Q:
In Python is augmented addition of sets are not supported?
In the Python sets, why augmented removal of elements are supported but addition is not supported?
For example if s is a mutable set:
s = set(['e', 'd', 'h', 's'])
s -= set('ds') gives s = set(['e', 'h'])
but this does not work for s += set('pk') and resu... | In Python is augmented addition of sets are not supported? | In the Python sets, why augmented removal of elements are supported but addition is not supported?
For example if s is a mutable set:
s = set(['e', 'd', 'h', 's'])
s -= set('ds') gives s = set(['e', 'h'])
but this does not work for s += set('pk') and results in TypeError.
| [
"The correct syntax for what you want to do is\ns |= set('ds')\n\nFor sets, the binary operators |, & and ^ are used for union, intersection and symmetric difference, respectively. I guess the reason + is not considered a valid set operation is because it is not used in set theory, while - is.\nThere's a nice symme... | [
10,
1,
1
] | [] | [] | [
"python",
"set"
] | stackoverflow_0006664356_python_set.txt |
Q:
Setting sqlite I/O priority from python module (speeding up sqlite commits)
I have a python program in an embedded system that needs to write to an sqlite database. This database is mission critical and thus needs to be fully synchronous. The problem is that the database commits take a LONG time (3-30 seconds) for... | Setting sqlite I/O priority from python module (speeding up sqlite commits) | I have a python program in an embedded system that needs to write to an sqlite database. This database is mission critical and thus needs to be fully synchronous. The problem is that the database commits take a LONG time (3-30 seconds) for a single insert. The insert is wrapped in a transaction, but there's really no w... | [
"Have you tried 3.7's WAL?\nHistorically, SQLite has been very slow at handling safe writes (eg. without changing to synchronous=off). It wrote the entire transaction to a journal, flushed it to disk, then copied the whole thing back over the original file, with many blocking syncs happening in between, serializin... | [
2,
2,
1,
0
] | [] | [] | [
"file_io",
"performance",
"python",
"sqlite"
] | stackoverflow_0004393936_file_io_performance_python_sqlite.txt |
Q:
Python, declared object with variable number of attr
I got a problem. I have a array of random elements, and i have object (max array = max attr in object). But if I use:
breadcrumbs = breadObject(element[0],element[1],element[2])
but if i have array with only 2 elements ([0][1]) i got error.
I try with:
exec("... | Python, declared object with variable number of attr | I got a problem. I have a array of random elements, and i have object (max array = max attr in object). But if I use:
breadcrumbs = breadObject(element[0],element[1],element[2])
but if i have array with only 2 elements ([0][1]) i got error.
I try with:
exec("breadcrumbs = breadObject(%s)"%string_bread)
return brea... | [
"Not sure that understand you correctly but think you can use the following syntax:\nbreadcrumbs = breadObject(*element)\n\n\nArbitrary number of arguments can be collected with *args syntax and\n an arbitrary number of keyword arguments can be collected as a\n dictionary with **kwargs syntax.:\ndef function(*arg... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006664978_python.txt |
Q:
Calling statistics functions from Scipy
This may well be completely trivial.
I want to call the spearmanr function from scipy: (the data are just examples)
import scipy
from numpy import *
Len = [2,3,5,7,2]
Pop = [5,2,6,3,2]
a = array(Len)
b = array(Pop)
print scipy.stats.spearmanr(a,b)
This generates the erro... | Calling statistics functions from Scipy | This may well be completely trivial.
I want to call the spearmanr function from scipy: (the data are just examples)
import scipy
from numpy import *
Len = [2,3,5,7,2]
Pop = [5,2,6,3,2]
a = array(Len)
b = array(Pop)
print scipy.stats.spearmanr(a,b)
This generates the error:
AttributeError: 'module' object has no att... | [
"Use import scipy.stats. Then it works. Importing a package does not automatically import all the subpackages/modules. In these cases you have to do this explicitly.\n"
] | [
53
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0006664996_numpy_python_scipy.txt |
Q:
Finding the elbow point of a curve in a stable way?
I am aware of the existence of this, and this on this topic. However, I would like to finalize on an actual implementation in Python this time.
My only problem is that the elbow point seems to be changing from different instantiations of my code. Observe the two... | Finding the elbow point of a curve in a stable way? | I am aware of the existence of this, and this on this topic. However, I would like to finalize on an actual implementation in Python this time.
My only problem is that the elbow point seems to be changing from different instantiations of my code. Observe the two plots shown in this post. While they appear to be visual... | [
"Its sounds like your actual concern is how to smooth your data as it contains noise? in which case perhaps you should fit a curve to the data first, then find the elbow of the fitted curve?\nWhether this will work would depend on the source of the noise, and if the noise is important for your application? by the w... | [
3
] | [] | [] | [
"machine_learning",
"math",
"numerical_methods",
"python",
"statistics"
] | stackoverflow_0006659648_machine_learning_math_numerical_methods_python_statistics.txt |
Q:
How to pass an 'if' statement to a function?
I want to pass an optional 'if' statement to a Python function to be executed. For example, the function might copy some files from one folder to another, but the function could take an optional condition.
So, for example, one call to the method could say "copy the fil... | How to pass an 'if' statement to a function? | I want to pass an optional 'if' statement to a Python function to be executed. For example, the function might copy some files from one folder to another, but the function could take an optional condition.
So, for example, one call to the method could say "copy the files from source to dest if source.endswith(".exe")
... | [
"Functions are objects. It's just a function that returns a boolean result.\ndef do_something( condition, argument ):\n if condition(argument):\n # whatever\n\ndef the_exe_rule( argument ):\n return argument.endswith('.exe')\n\ndo_something( the_exe_rule, some_file )\n\nLambda is another way to create s... | [
14,
5,
0
] | [] | [] | [
"arguments",
"function",
"if_statement",
"python"
] | stackoverflow_0006665082_arguments_function_if_statement_python.txt |
Q:
String & Regex manipulation in HTML file using Python
I am a newbie to Python. I have a HTML file where I need to do some "Find and Replace operation using Regex". What is the best way to do this?
Can I get the contents of the HTML file as a string and do this? Or is there a better way?
A:
Have a look at a HTML ... | String & Regex manipulation in HTML file using Python | I am a newbie to Python. I have a HTML file where I need to do some "Find and Replace operation using Regex". What is the best way to do this?
Can I get the contents of the HTML file as a string and do this? Or is there a better way?
| [
"Have a look at a HTML Parser like Beautiful Soup.\nUsing regex to parse HTML is a bad idea.\nEdit: \nBeautiful Soup License:\n\nBeautiful Soup is licensed under the same terms as Python itself\n\nPythons license\n\nNote:\n GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licens... | [
5
] | [] | [] | [
"file",
"html",
"python",
"regex"
] | stackoverflow_0006665229_file_html_python_regex.txt |
Q:
How can I acess a metod from an object inside a class in python 2.6?
In my code I have a class that contain a lot of functions and a pair of classes (subclass I think). The main problem is that I want the subclasses to call an object, defined in the function init and I don't know ho to referencing it
The main issu... | How can I acess a metod from an object inside a class in python 2.6? | In my code I have a class that contain a lot of functions and a pair of classes (subclass I think). The main problem is that I want the subclasses to call an object, defined in the function init and I don't know ho to referencing it
The main issue in code:
class principal:
def __init__(self):
self.a = objec... | [
"You have to instantiate a principal object in the __init__ for secondary\np = principal()\n\nand then reference the a object\npa = p.a()\npa.proceed()\n\nNote that my variables names are horrendous\nNote too that you're not subclassing principal, you're subclassing threading.Thread. Indenting isn't enough, you ha... | [
1,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0006665196_class_python.txt |
Q:
randint with leading zero's
I want to generate numbers from 00000 to 99999.
with
number=randint(0,99999)
I only generate values without leading zero's, of course, a 23 instead of a 00023.
Is there a trick to generate always 5 digit-values in the sense of %05d or do I really need to play a python-string-trick to ... | randint with leading zero's | I want to generate numbers from 00000 to 99999.
with
number=randint(0,99999)
I only generate values without leading zero's, of course, a 23 instead of a 00023.
Is there a trick to generate always 5 digit-values in the sense of %05d or do I really need to play a python-string-trick to fill the missing 0s at front in c... | [
"You will have to do a python-string-trick since an integer, per se, does not have leading zeroes\nnumber=\"%05d\" % randint(0,99999)\n\n",
"The numbers generated by randint are integers. Integers are integers and will be printed without leading zeroes.\nIf you want a string representation, which can have leading... | [
10,
3,
0,
0,
0
] | [] | [] | [
"python",
"random",
"zero_pad"
] | stackoverflow_0006664949_python_random_zero_pad.txt |
Q:
syntax error in python due to whitespaces i think
I am still confused in the way of writting a python code as i am used to java codes with brakets and i cant fully understand the indentation concept. So this is a code that produces a syntax error so any one can help please ? Thank You in advance
def SendSMS2 (phon... | syntax error in python due to whitespaces i think | I am still confused in the way of writting a python code as i am used to java codes with brakets and i cant fully understand the indentation concept. So this is a code that produces a syntax error so any one can help please ? Thank You in advance
def SendSMS2 (phone_number,sms_text):
print 'made it to def'
res = MDM.... | [
"All of the code after the def statement should be indented, like this:\ndef SendSMS2 (phone_number,sms_text):\n\n print 'made it to def' \n res = MDM.send('AT+CMGS='+ phone_number + '\\r',5)\n n=0\n while n < 20:\n res=MDM.receive(1)\n if res.find(\">\") >-1:\n print n\n ... | [
3,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006665329_python.txt |
Q:
Are python-ldap's exceptions organized in a hierarchy?
I have a code like this:
try:
....
l.simple_bind_s(user, password)
except ldap.CONNECT_ERROR, e:
sys.exit(1)
except ldap.BUSY, e:
sys.exit(2)
except ldap.OPT_NETWORK_TIMEOUT, e:
sys.exit(3)
except ldap.TIMEOUT, e:
sys.exit(4)
exc... | Are python-ldap's exceptions organized in a hierarchy? | I have a code like this:
try:
....
l.simple_bind_s(user, password)
except ldap.CONNECT_ERROR, e:
sys.exit(1)
except ldap.BUSY, e:
sys.exit(2)
except ldap.OPT_NETWORK_TIMEOUT, e:
sys.exit(3)
except ldap.TIMEOUT, e:
sys.exit(4)
except ldap.SERVER_DOWN, e:
sys.exit(5)
I am trying to cat... | [
"Yes there is a hierarchy of exceptions, you should always start catching the more specific exceptions and finally catch the broader exceptions. The hierarchy is usually determined by Inheritance.\nIn your case since you are catching that exception last, it should be because the timeout exception you are catching f... | [
2,
1
] | [] | [] | [
"custom_exceptions",
"exception",
"ldap",
"python"
] | stackoverflow_0006665504_custom_exceptions_exception_ldap_python.txt |
Q:
Is there any safe way to parameterize database names in MySQL queries?
I'm writing a little python script to help me automate the creation of mysql databases and associated accounts for my personal projects. Part of this script is a function that takes the database name as a string, then goes to create the databas... | Is there any safe way to parameterize database names in MySQL queries? | I'm writing a little python script to help me automate the creation of mysql databases and associated accounts for my personal projects. Part of this script is a function that takes the database name as a string, then goes to create the database.
def createDB(dbConn, dbName):
import MySQLdb
c = dbConn.cursor()... | [
"A database name (nor column or table names) are not data values, and thus are not an appropriate use of placeholders. wanting to do this is usually a bad sign; only the DBA should be able to issue a create database, since doing so requires some considerable privileges. Most applications require the DBA to issue ... | [
5,
2
] | [] | [] | [
"mysql",
"mysql_python",
"python",
"sql_parametrized_query"
] | stackoverflow_0006656636_mysql_mysql_python_python_sql_parametrized_query.txt |
Q:
Python: How to determine subprocess children have all finished running
I am trying to detect when an installation program finishes executing from within a Python script. Specifically, the application is the Oracle 10gR2 Database. Currently I am using the subprocess module with Popen. Ideally, I would simply use th... | Python: How to determine subprocess children have all finished running | I am trying to detect when an installation program finishes executing from within a Python script. Specifically, the application is the Oracle 10gR2 Database. Currently I am using the subprocess module with Popen. Ideally, I would simply use the wait() method to wait for the installation to finish executing, however, t... | [
"Ok, here is a trick that will work only under Unix. It is similar to one of the answers to this question: Ensuring subprocesses are dead on exiting Python program. The idea is to create a new process group. You can then wait for all processes in the group to terminate.\npid = os.fork()\nif pid == 0:\n os.set... | [
3,
2,
2,
1
] | [] | [] | [
"child_process",
"oracle10g",
"python",
"spawning",
"subprocess"
] | stackoverflow_0006102535_child_process_oracle10g_python_spawning_subprocess.txt |
Q:
django-paypal module for DJango
I have to use a Django project that uses django-paypal. So when I run the command "python manage.py runserver" it throws "ImportError: No module named paypal.standard" .
My question is how can I install Paypal module as this module does not have any setup.py file. I am using Bitnam... | django-paypal module for DJango | I have to use a Django project that uses django-paypal. So when I run the command "python manage.py runserver" it throws "ImportError: No module named paypal.standard" .
My question is how can I install Paypal module as this module does not have any setup.py file. I am using Bitnami Django Stack for Windows.
| [
"I'm not sure from where you've downloaded but this one has setup.py\nOr you can just copy the paypal folder into your site-packages dir.\nFor further setup you can also check out:\ndjango-paypal setup\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006665607_django_python.txt |
Q:
Lancaster Or Porter
Which of lancaster or porter is best for Stemming ?
Is Porter stemmer too old for stemming?
A:
Porter is simple, but if you are stemming huge amounts of data, it's not a bad option.
| Lancaster Or Porter | Which of lancaster or porter is best for Stemming ?
Is Porter stemmer too old for stemming?
| [
"Porter is simple, but if you are stemming huge amounts of data, it's not a bad option.\n"
] | [
2
] | [] | [] | [
"nltk",
"porter_stemmer",
"python",
"stemming"
] | stackoverflow_0006666019_nltk_porter_stemmer_python_stemming.txt |
Q:
Automatically using maximum column width in wxPython's HyperTreeList
In wxPython, there is a ListCtrlAutoWidthMixin which makes sure that the last column in the list uses up all the space available to the list, even when it resizes.
However, I have had problems with the native wxListCtrl on Windows that mean I wan... | Automatically using maximum column width in wxPython's HyperTreeList | In wxPython, there is a ListCtrlAutoWidthMixin which makes sure that the last column in the list uses up all the space available to the list, even when it resizes.
However, I have had problems with the native wxListCtrl on Windows that mean I want to use a different list, like the HyperTreeList that is new in 2.8.12. ... | [
"Possibly the best answer would have been to use the UltimateListCtrl from the same library, which shares the same API. However, this too seems to have problems. Still investigating.\n"
] | [
0
] | [] | [] | [
"listview",
"python",
"wxpython"
] | stackoverflow_0006652365_listview_python_wxpython.txt |
Q:
Django Userprofile form extension
Im extending the django User model with User profile like this :
class UserProfile(BaseModel):
user = models.ForeignKey(User, unique=True, related_name="profile")
city = models.CharField(_("City"), max_length=200)
tel = models.CharField(_("Phone Number"), max_length=50... | Django Userprofile form extension | Im extending the django User model with User profile like this :
class UserProfile(BaseModel):
user = models.ForeignKey(User, unique=True, related_name="profile")
city = models.CharField(_("City"), max_length=200)
tel = models.CharField(_("Phone Number"), max_length=50,
help_text=_("(+ Country Code... | [
"Hope, this will help\nclass UserProfileForm(forms.ModelForm): \n email = forms.EmailField(label=u'Email address',required=True)\n\n class Meta:\n model = UserProfile\n exclude = ['user',]\n\n def __init__(self, *args, **kw):\n super(UserProfileForm, self).__init__(*args, **kw)\n ... | [
3,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006652403_django_django_models_python.txt |
Q:
Why does `type(myField)` return `` and not ``?
I am confronted to a python problem. I want to use type() to find out what type of variable I am using. The code looks similar to this one:
class Foo():
array=[ myField(23),myField(42),myField("foo"), myField("bar")]
def returnArr(self):
for ... | Why does `type(myField)` return `` and not ``? | I am confronted to a python problem. I want to use type() to find out what type of variable I am using. The code looks similar to this one:
class Foo():
array=[ myField(23),myField(42),myField("foo"), myField("bar")]
def returnArr(self):
for i in self.array:
print type(i)
if __... | [
"in python 2, all of your classes should inherit from object. If you don't, you end up with \"old style classes\", which are always of type classobj, and whose instances are always of type instance. \n>>> class myField():\n... pass\n... \n>>> class yourField(object):\n... pass\n... \n>>> m = myField()\n>>... | [
97,
0
] | [] | [] | [
"python"
] | stackoverflow_0006666856_python.txt |
Q:
Is there a way to make multiple horizontal boxplots in matplotlib?
I am trying to make a matplotlib figure that will have multiple horizontal boxplots stacked on one another. The documentation shows both how to make a single horizontal boxplot and how to make multiple vertically oriented plots in this section.
I t... | Is there a way to make multiple horizontal boxplots in matplotlib? | I am trying to make a matplotlib figure that will have multiple horizontal boxplots stacked on one another. The documentation shows both how to make a single horizontal boxplot and how to make multiple vertically oriented plots in this section.
I tried using subplots as in the following code:
import numpy as np
import ... | [
"If I'm understanding you correctly, you just need to pass boxplot a list (or a 2d array) containing each array you want to plot.\nimport numpy as np\nimport pylab as plt\n\ntotfigs = 5\n\nplt.figure()\nplt.hold = True\nboxes=[]\nfor i in np.arange(totfigs): \n x = np.random.random(50)\n boxes.append(x)\n\... | [
6,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006665771_matplotlib_python.txt |
Q:
Does try/except block causes commit_on_success to fail
@transection.commit_on_success
def recordIt(...)
try:
....
recordable = firstDataInsertionFunction(...)
if recordable:
myRec = SecondDataInsertion(.....)
except:
....
As for commit_on_success, if my second data in... | Does try/except block causes commit_on_success to fail | @transection.commit_on_success
def recordIt(...)
try:
....
recordable = firstDataInsertionFunction(...)
if recordable:
myRec = SecondDataInsertion(.....)
except:
....
As for commit_on_success, if my second data insertion fails, django must automatically rollback, so my fir... | [
"First of all, don't ever do except:. It's just bad, and catches too much, and hides bugs.\nAnd yes, if you handle the exception, then commit_on_success cannot possibly know there was an error. If you need to run logic on exception, reraise it afterwards (just raise, with no argument). Or rollback yourself.\n"
] | [
4
] | [] | [] | [
"django",
"exception_handling",
"python"
] | stackoverflow_0006667061_django_exception_handling_python.txt |
Q:
Sort list of lists ascending and then descending
If I have a list that contains a list that looks like this
['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]
How can I sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like
['b',1] ['b',2] ['b',3] ['a',1] ['a',2... | Sort list of lists ascending and then descending | If I have a list that contains a list that looks like this
['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]
How can I sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like
['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3]
Using itemgetter I can pass in reverse on e... | [
"L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]]\nL.sort(key=lambda k: (k[0], -k[1]), reverse=True)\n\nL now contains:\n[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]\n\n",
"You can do successive rounds of sorting as python's sort is stable. You need to first sort on the secondary key tho... | [
64,
47,
4
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0006666748_python_sorting.txt |
Q:
Parsing XML Using minidom
I have an XML file in which I want to extract data from certain tags that are ONLY nested within other tags, i.e. the tags containing the data I want to extract occur elsewhere in the XML document.
Sample XML:
<root>
<tag1>content I don't want</tag1>
<tag2>content I don't want</ta... | Parsing XML Using minidom | I have an XML file in which I want to extract data from certain tags that are ONLY nested within other tags, i.e. the tags containing the data I want to extract occur elsewhere in the XML document.
Sample XML:
<root>
<tag1>content I don't want</tag1>
<tag2>content I don't want</tag2>
<tag3>content I don't w... | [
"You can always call getElementsByTagName() on any subnode:\nfor item in XML_Document.getElementsByTagName('item'):\n tag1 = item.getElementsByTagName('tag1')[0].toxml(encoding=\"utf-8\")\n tag2 = item.getElementsByTagName('tag2')[0].toxml(encoding=\"utf-8\")\n tag3 = item.getElementsByTagName('tag3')[0].t... | [
1
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0006665725_minidom_python_xml.txt |
Q:
Any easy way to do 'mad lib' style form fields in Django?
I am curious about making a "mad lib" style form (cf. http://www.lukew.com/ff/entry.asp?1007) for my django form. I could do it by iterating over all the form fields and laying out the text by hand, e.g. <li>There should be {{ form.num_widgets }} widgets</l... | Any easy way to do 'mad lib' style form fields in Django? | I am curious about making a "mad lib" style form (cf. http://www.lukew.com/ff/entry.asp?1007) for my django form. I could do it by iterating over all the form fields and laying out the text by hand, e.g. <li>There should be {{ form.num_widgets }} widgets</li>, however I dislike how the label on the form field is unused... | [
"This is a good case for a custom template tag, as documented here: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/\nYou could easily create a tag that does something along the lines of:\n@register.simple_tag\ndef madlibfield(formfield):\n return formfield.label % formfield\n\nYou could then use... | [
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006666899_django_django_forms_python.txt |
Q:
Why two for statements will not run together in python?
I am trying to run a Python program to calculate the total and average charges that are contained within a CSV file.
I then want to calculate the total and average charge per invoice. The program calculates the total charges and average charges correctly, bu... | Why two for statements will not run together in python? | I am trying to run a Python program to calculate the total and average charges that are contained within a CSV file.
I then want to calculate the total and average charge per invoice. The program calculates the total charges and average charges correctly, but the second for statement will not run. Both for statement r... | [
"Because the file's already been read by that point, so there's nothing for the second loop to do. You should close and reopen the file after the first loop, and move the instantiation of inv_reader to after that.\nBetter still, you should merge the loops into one - it'll be much more efficient.\n",
"It's like yo... | [
3,
2,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006666756_python.txt |
Q:
Comparing TCP checksums with Scapy?
I am trying to identify packets with incorrect checksums while using Scapy as a sniffer. I am able to get the original checksum by accessing
packet[TCP].chksum
I then remove this using
del packet[TCP].chksum
I would like to do something like
if(originalChecksum == recomput... | Comparing TCP checksums with Scapy? | I am trying to identify packets with incorrect checksums while using Scapy as a sniffer. I am able to get the original checksum by accessing
packet[TCP].chksum
I then remove this using
del packet[TCP].chksum
I would like to do something like
if(originalChecksum == recomputedChecksum):
# Checksum is valid
I ... | [
"to make Scapy recompute all fields, assemble the packet by dumping it to a string, then parse the string. \noriginalChecksum=packet['TCP'].chksum\ndel packet['TCP'].chksum\npacket=IP(str(packet))\nrecomputedChecksum=packet['TCP'].chksum\n\n"
] | [
2
] | [] | [] | [
"networking",
"python",
"scapy"
] | stackoverflow_0006665844_networking_python_scapy.txt |
Q:
Python Concatenation
This issue is probably very easy but I can't figure it out -
I have the following values: ['2000']['09']['22']
I want the following: 20000922 or '20000922'
code
def transdatename(d):
year = re.findall('\d\d\d\d', str(d))
premonth = re.findall('[A-Z][a-z]{2,9}', str(d))
month = re... | Python Concatenation | This issue is probably very easy but I can't figure it out -
I have the following values: ['2000']['09']['22']
I want the following: 20000922 or '20000922'
code
def transdatename(d):
year = re.findall('\d\d\d\d', str(d))
premonth = re.findall('[A-Z][a-z]{2,9}', str(d))
month = replace_all(str(premonth), r... | [
"Are you trying to do this?\n>>> input= '\\nSeptember 23, 2000'\n>>> format= '\\n%B %d, %Y'\n>>> datetime.datetime.strptime(input,format)\ndatetime.datetime(2000, 9, 23, 0, 0)\n>>> (_+datetime.timedelta(-1)).strftime(\"%Y%m%d\")\n'20000922'\n\nIf so, you're making it too hard.\n",
"Use itertools.chain:\nfrom iter... | [
4,
2,
2,
0,
0
] | [] | [] | [
"concatenation",
"python"
] | stackoverflow_0006665566_concatenation_python.txt |
Q:
How can I prevent children from being re-created in a SQLAlchemy one to many relationship?
I am using Python 2.6.6 and SQLAlchemy 0.6.6 to handle a one to many relationship in my database, and am unsure how to prevent SQLAlchemy from adding new child records in the case where similar data already exists.
Database ... | How can I prevent children from being re-created in a SQLAlchemy one to many relationship? | I am using Python 2.6.6 and SQLAlchemy 0.6.6 to handle a one to many relationship in my database, and am unsure how to prevent SQLAlchemy from adding new child records in the case where similar data already exists.
Database code:
from sqlalchemy import *
from sqlalchemy.orm import backref, relationship, sessionmaker, c... | [
"You could explicitely check the contents of the list and only append new AuthorMetadata objects if they don't exist, rather than delete the entire collection and re-create it with brand new objects. That would at least avoid discarding the previously created records.\nYour use case matches attribute_mapped_collect... | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006662091_python_sqlalchemy.txt |
Q:
Simplest way to get initial text input in pygame
So, Iv'e got a pygame application. Right now, it takes a command line argument to specify which display to show the main screen on. However, I'm running it on windows, where it's hard to specify command line input to a graphical application.
So, I'd like to have a v... | Simplest way to get initial text input in pygame | So, Iv'e got a pygame application. Right now, it takes a command line argument to specify which display to show the main screen on. However, I'm running it on windows, where it's hard to specify command line input to a graphical application.
So, I'd like to have a very very very simple dialog box which pops up, prompts... | [
"A better solution might be to just assume that you are going on the first monitor. In game, you can have a configuration option, which you save to a config file to be read next time, which the user can select. If the user decides that your application is on the wrong monitor, you should just inform them that the... | [
1,
1,
0
] | [] | [] | [
"pygame",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0006656750_pygame_python_tkinter_user_interface.txt |
Q:
About text files to arrays in Python
I have a large text file that reads like
Kyle 40
Greg 91
Reggie 58
How would I convert this to an array that looks like this
array = ([Kyle, 40], [Greg, 91], [Reggie, 58])
Thanks in advance.
A:
Assuming proper input:
array = []
with open('file.txt', 'r') as f:
for... | About text files to arrays in Python | I have a large text file that reads like
Kyle 40
Greg 91
Reggie 58
How would I convert this to an array that looks like this
array = ([Kyle, 40], [Greg, 91], [Reggie, 58])
Thanks in advance.
| [
"Assuming proper input:\narray = []\nwith open('file.txt', 'r') as f: \n for line in f:\n name, value = line.split()\n value = int(value)\n array.append((name, value)) \n\n",
"Alternative to Manny's solution:\nwith open('file.txt', 'r') as f: \n myarray = [line.split() for lin... | [
6,
1,
1,
0
] | [] | [] | [
"arrays",
"python",
"text"
] | stackoverflow_0006666920_arrays_python_text.txt |
Q:
Django - Models + A list of dictionaries
I have a data structure that looks like this
[{'name': 'sfsdf sdfsdf', 'id': '621205528'},
{'name': 'test name', 'id': '32324234234'},
{'name': 'another name', 'id': '3434535342221'}]
Now I have a model called Profile where the id in the dictionary maps to the uid field ... | Django - Models + A list of dictionaries | I have a data structure that looks like this
[{'name': 'sfsdf sdfsdf', 'id': '621205528'},
{'name': 'test name', 'id': '32324234234'},
{'name': 'another name', 'id': '3434535342221'}]
Now I have a model called Profile where the id in the dictionary maps to the uid field in the model.
I'd like to remove every entry... | [
"You could get a matching list from the db in one go, and compare:\ndb_ids = set(Profile.objects.values_list('uid', flat=True))\nmy_ids = set([d['id'] for d in original_list])\nids_to_keep = my_ids - db_ids\nlist_to_keep = [l for l in original_list if l['id'] in ids_to_keep]\n\n",
"ids = [x['id'] for x in my_list... | [
1,
1,
0,
0
] | [
"Assuming there are not hundreds of records to delete, you can use the below.\nobjs = [{'name': 'sfsdf sdfsdf', 'id': '621205528'}, ...]\n\nProfile.objects.filter(id__in=[x.get('id') for x in objs]).delete()\n\n"
] | [
-1
] | [
"django",
"django_models",
"python"
] | stackoverflow_0006667210_django_django_models_python.txt |
Q:
Python: Access a dictionary that is located inside of a text file
I am working on a quick and dirty script to get Chromium's bookmarks and turn them into a pipe menu for Openbox. Chromium stores it's bookmarks in a file called Bookmarks that stores information in a dictionary form like this:
{
"checksum": "999... | Python: Access a dictionary that is located inside of a text file | I am working on a quick and dirty script to get Chromium's bookmarks and turn them into a pipe menu for Openbox. Chromium stores it's bookmarks in a file called Bookmarks that stores information in a dictionary form like this:
{
"checksum": "99999999999999999999",
"roots": {
"bookmark_bar": {
"chi... | [
"Do you know if this is a json file? If so, python provides a json library.\nJson can be used as a data serialization/interchange format. It's nice because it's cross platform. Importing this like you ask seems fairly easy, an example from the docs:\n>>> import json\n>>> json.loads('[\"foo\", {\"bar\":[\"baz\", nul... | [
4,
1
] | [] | [] | [
"bookmarks",
"dictionary",
"file",
"google_chrome",
"python"
] | stackoverflow_0006667731_bookmarks_dictionary_file_google_chrome_python.txt |
Q:
best algorithm for finding distance for all pairs where edges' weight is 1
As the title said, I'm trying to implement an algorithm that finds out the distances between all pairs of nodes in given graph. But there is more: (Things that might help you)
The graph is unweighted. Meaning that all the edges can be cons... | best algorithm for finding distance for all pairs where edges' weight is 1 | As the title said, I'm trying to implement an algorithm that finds out the distances between all pairs of nodes in given graph. But there is more: (Things that might help you)
The graph is unweighted. Meaning that all the edges can be considered as having weight of 1.
|E| <= 4*|V|
The graph is pretty big (at most ~144... | [
"There is space for improvement because in unweighted graphs, you gain an additional attribute which does not hold for weighted graphs, namely:\n\nFor any edge directly connecting A to C, you know for sure that there is no shorter path via a third node B.\n\nWith this in mind, you should be able to simplify Dijkstr... | [
11,
9,
1,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"dijkstra",
"graph_algorithm",
"python",
"shortest_path"
] | stackoverflow_0005851154_algorithm_dijkstra_graph_algorithm_python_shortest_path.txt |
Q:
Python--Need to Read and find data, and copy a file to another location (beginner)
I'm a beginner at this, and not really sure how to accomplish it. Basically, I need to be able to open a file (user inputs the name, and a starting and ending address). I need to be able to search through the file and find the start... | Python--Need to Read and find data, and copy a file to another location (beginner) | I'm a beginner at this, and not really sure how to accomplish it. Basically, I need to be able to open a file (user inputs the name, and a starting and ending address). I need to be able to search through the file and find the starting address, and only copy the information from the given starting address to the ending... | [
"Well, let's look through your code:\nfilename = raw_input(\"Please enter your filename:\\n\")\nopenedFile = open(filename, \"rb\")\nstartAddress = raw_input(\"From the EEPROM file, enter 'Start Address':\\n\")\nendAddress = raw_input(\"From the EEPROM file, enter 'End Address':\\n\")\n\nThis is mostly correct, but... | [
2
] | [] | [] | [
"copy",
"python"
] | stackoverflow_0006668107_copy_python.txt |
Q:
How can i successfully use UNICODE characters in my .py files without causing trouble?
I am writing a test for a database which has Swedish characters in it. In the test, i directly use characters with umlauts and other such Swedish ligatures and it runs just fine, reading filenames in from a database and doing st... | How can i successfully use UNICODE characters in my .py files without causing trouble? | I am writing a test for a database which has Swedish characters in it. In the test, i directly use characters with umlauts and other such Swedish ligatures and it runs just fine, reading filenames in from a database and doing string compares successfully.
However, upon importing this file to do pydoc generation, i get ... | [
"You need to set your encoding in your editor and the database so that they match. If your database is utf-8 encoded, and not iso-8859-15, then setting your editor to utf-8 should fix it. However, since your u'string' comparisons fail, this might not be the case.\nReplace\n# -*- coding: iso-8859-15 -*-\n\nwith\n# -... | [
10
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0006668218_python_unicode.txt |
Q:
wxPython: refresh and update combobox
I got a wxPython combobox which contains a list of sections of my .ini file.
I add new section while my program is running. And I also want to see the NEW entries in my combobox.
How can I refresh / update it?
My code :
self.cbxCfgProfiles = wx.ComboBox(self, pos=(170, 120), s... | wxPython: refresh and update combobox | I got a wxPython combobox which contains a list of sections of my .ini file.
I add new section while my program is running. And I also want to see the NEW entries in my combobox.
How can I refresh / update it?
My code :
self.cbxCfgProfiles = wx.ComboBox(self, pos=(170, 120), size=(440, -1),
... | [
"If you have a new list of strings that you want to set the combobox to, the SetItems() method is probably the easiest way. It clears the control and then adds all the new selections.\n",
"Sorry I only worked with pyGtk until now, and one alternative for you it's to make a thread that verifies wheter there is a n... | [
3,
0
] | [] | [] | [
"python",
"refresh",
"wxpython"
] | stackoverflow_0006665577_python_refresh_wxpython.txt |
Q:
Would limiting a GILed Python program to a single CPU boost performance?
Following up on David Beazley's paper regarding Python and GIL, would it be a good practice to limit a Python program (CPython with GIL and all) to a single CPU in a Windows based multi-core system?
Would it boost performance?
UPDATE: Assume... | Would limiting a GILed Python program to a single CPU boost performance? | Following up on David Beazley's paper regarding Python and GIL, would it be a good practice to limit a Python program (CPython with GIL and all) to a single CPU in a Windows based multi-core system?
Would it boost performance?
UPDATE: Assume multiple threads are used (not sure if it makes a difference)
| [
"The paper does indeed imply that limiting a program to a single core would improve performance in that particular case. However, there are a number of concerns that you would need to deal with:\n\nHis tests are mainly for compute intensive threads rather than IO bound threads. If the threads you are using often bl... | [
4,
0
] | [] | [] | [
"gil",
"multicore",
"python"
] | stackoverflow_0006667750_gil_multicore_python.txt |
Q:
Block folder with regular expressions
I need to block a folder with PCRE Regular expressions. I am using Interarchy to mirror my work files via ftp but it keeps crashing on the _notes folder.
How do I block the folder _notes and all contents via PCRE RE's?
Here is a list of the standard blocks-
(?isx-m)
^\. ... | Block folder with regular expressions | I need to block a folder with PCRE Regular expressions. I am using Interarchy to mirror my work files via ftp but it keeps crashing on the _notes folder.
How do I block the folder _notes and all contents via PCRE RE's?
Here is a list of the standard blocks-
(?isx-m)
^\. | # .files
^\(.*\)$ | # (parentheses)
... | [
"I don't have Interarchy, but the regex ^_notes will match any path that begins with \"_notes\" including \"_notes\" itself and any subpaths such as \"_notes/a_file\"\n"
] | [
1
] | [] | [] | [
"curl",
"pcre",
"python",
"regex"
] | stackoverflow_0006668137_curl_pcre_python_regex.txt |
Q:
Import a bunch of parameters as a dictionary?
I want to put all the parameters of my code in a parameter file (parms.py), so that everything I may need to tweak later will be at the same place. What would be the best way to import just the parameters I want, to save some work?
I was thinking of grouping my paramet... | Import a bunch of parameters as a dictionary? | I want to put all the parameters of my code in a parameter file (parms.py), so that everything I may need to tweak later will be at the same place. What would be the best way to import just the parameters I want, to save some work?
I was thinking of grouping my parameters in dictionaries; is that the Pythonic way? I th... | [
"Just import the module and access the parameters you want using their fully-qualiifed names:\nimport parms\n\nparms.foo\nparms.bar\nparms.baz\n\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0006668475_python.txt |
Q:
How to input HTTP data from a WSGI implementation into Django?
I want to create a Django application that acts as middleware between two transparent WSGI implementations which simply pass along data. So far, all I want this application to do is log the HTTP data that it receives into a database for debugging purp... | How to input HTTP data from a WSGI implementation into Django? | I want to create a Django application that acts as middleware between two transparent WSGI implementations which simply pass along data. So far, all I want this application to do is log the HTTP data that it receives into a database for debugging purposes and then passes the information to the next WSGI implementation ... | [
"There was a GSOC project in the past related to making it easier/possible to plug WSGI middleware into Django. Code at:\nhttps://code.djangoproject.com/browser/django/branches/soc2009/http-wsgi-improvements\nI don't know what happened to that.\nAlex Gaynor has also played with better WSGI integration:\nhttp://alex... | [
0
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0006655997_django_mod_wsgi_python_wsgi.txt |
Q:
What's the best way to setup a user post image uploading system?
I'm using django. I want a user to upload an image for a user post, but I'm not sure the backend of this. Should I setup a db with the url of the image, a folder for the user, a folder inside of the post, and the image finally in that folder? What ... | What's the best way to setup a user post image uploading system? | I'm using django. I want a user to upload an image for a user post, but I'm not sure the backend of this. Should I setup a db with the url of the image, a folder for the user, a folder inside of the post, and the image finally in that folder? What is the best (fastest, efficient, nonconfusing) way of doing this?
| [
"You can use the built in django ImageField. This essentially is set up to store and reference a url relative to a media dir on the webserver. \nThere is a pretty basic example here. \nEDIT:\nFor your own implementation outside of django most people would implement it in a similar way to how Django's imagefield ... | [
2,
0
] | [] | [] | [
"django",
"html",
"image",
"python",
"sql"
] | stackoverflow_0006668455_django_html_image_python_sql.txt |
Q:
Not able to run celeryd as normal user but runs with root
I have installed celeryd and django-celery
i run via python manage.py celeryd
If i run it via root then i get this message
WARNING/MainProcess]
/opt/python27/lib/python2.7/site-packages/celery-2.2.7-py2.7.egg/celery/apps/worker.py:124:
UserWarning: Run... | Not able to run celeryd as normal user but runs with root | I have installed celeryd and django-celery
i run via python manage.py celeryd
If i run it via root then i get this message
WARNING/MainProcess]
/opt/python27/lib/python2.7/site-packages/celery-2.2.7-py2.7.egg/celery/apps/worker.py:124:
UserWarning: Running celeryd with superuser privileges is not
encouraged! "... | [
"You are not giving r/w access for the user that runs celery to the shared memory (/dev/shm), that it's accessed by multiprocessing.\nYou should add this to your /etc/fstab:\nnone /dev/shm tmpfs rw,nosuid,nodev,noexec 0 0\n\nAnd restart your linux.\n\nEDIT:\nYou can try adding permissions manually to /dev/shm:\nsud... | [
2
] | [] | [] | [
"django",
"django_celery",
"python"
] | stackoverflow_0006667596_django_django_celery_python.txt |
Q:
What's the correct include path in this template?
I am editing file:
/templates/account/base.html
and in it want to include:
/templates/profiles/includes/sub_nav.html
I have tried the following:
{% block subnav %}{% include "profiles/includes/sub_nav.html"%}{% endblock %}
result: no error but no inclusion of side... | What's the correct include path in this template? | I am editing file:
/templates/account/base.html
and in it want to include:
/templates/profiles/includes/sub_nav.html
I have tried the following:
{% block subnav %}{% include "profiles/includes/sub_nav.html"%}{% endblock %}
result: no error but no inclusion of side bar
and I have also tried
{% block subnav %}{% include... | [
"\"result: no error but no inclusion of side bar\". \nLogical conclusion\nYour sub_nav.html has problems. Or your base.html has problem The include is working. It must be the HTML, CSS or Django Tags.\n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"include_path",
"python"
] | stackoverflow_0006669154_django_django_templates_include_path_python.txt |
Q:
In Python, how to write back a stringIO text file to a zip archive, then back to bytea field in PostgreSQL?
A relative noob to Python, I've successfully pulled a text file, out of a zip archive, contained in a PostgreSQL bytea field, using this code:
myzip = ZipFile(StringIO(rv[0]["archivefield"]), 'a')
data = myz... | In Python, how to write back a stringIO text file to a zip archive, then back to bytea field in PostgreSQL? | A relative noob to Python, I've successfully pulled a text file, out of a zip archive, contained in a PostgreSQL bytea field, using this code:
myzip = ZipFile(StringIO(rv[0]["archivefield"]), 'a')
data = myzip.read("content.txt",'a')
# *** WORK ON content.txt HAPPENS HERE ***
I've then done the work I need on that te... | [
"Use ZipFile.writestr:\nstrf = StringIO(rv[0][\"archivefield\"])\nzipf = ZipFile(strf, \"a\")\ndata = myzip.read(\"content.txt\"')\n\n# process data, changing its value\n\nzipf.writestr(\"content.txt\", data)\nzipf.close() # actually write contents out\n\nthen write str.getvalue() back to your PostgreSQL database,... | [
0
] | [] | [] | [
"plpython",
"python",
"stringio",
"zip"
] | stackoverflow_0006669081_plpython_python_stringio_zip.txt |
Q:
Python ctypes structure being overwritten when allocating more memory
In Python 3.2 I am creating a Structure object from the data returned by the ctypes.windll.kernel32.DeviceIoControl function. After this is done I can access the Structure fields and return the data. However, if i do something the uses a memory,... | Python ctypes structure being overwritten when allocating more memory | In Python 3.2 I am creating a Structure object from the data returned by the ctypes.windll.kernel32.DeviceIoControl function. After this is done I can access the Structure fields and return the data. However, if i do something the uses a memory, such as opening a file the data inside the structure is modified. In the f... | [
"Some observations:\n\nDevIoCtl should be called with byref(BytesReturned).\nctypes.cast's first argument must be an \"object that can be interpreted as a pointer\".\nWhat you are casting, however, is a raw bytes object (from output[:BytesReturned.value]).\nAt this point, what you returned from __DeviceIoControl is... | [
2
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0006669074_ctypes_python.txt |
Q:
WxPthon Question: Subpanels within a Notebook Panel
I am currently a summer research student helping out with computational biology research, and my role is to make a GUI that visualizes data. At the moment, I am using wxPython and matplotlib. I have two panels set up within a notebook - the first panel is the opt... | WxPthon Question: Subpanels within a Notebook Panel | I am currently a summer research student helping out with computational biology research, and my role is to make a GUI that visualizes data. At the moment, I am using wxPython and matplotlib. I have two panels set up within a notebook - the first panel is the options and the second panel is where the visualization will... | [
"First of all, I don't see any point in creating a panel on top of the tab's panel. That's redundant. You can just use the tab's panel as the top panel and eliminate selfPanel. Then you can just create 4 other panels with a parent of \"self\" (i.e. the tab itself). \nYou'll need 3 BoxSizers or 1 GridSizer. I person... | [
1
] | [] | [] | [
"matplotlib",
"panel",
"python",
"wxpython"
] | stackoverflow_0006669340_matplotlib_panel_python_wxpython.txt |
Q:
Splitting a url into a list in python
I am currently working on a project that involves splitting a url. I have used the urlparse module to break up the url, so now I am working with just the path segment.
The problem is that when I try to split() the string based on the delimiter "/" to separate the directories,... | Splitting a url into a list in python | I am currently working on a project that involves splitting a url. I have used the urlparse module to break up the url, so now I am working with just the path segment.
The problem is that when I try to split() the string based on the delimiter "/" to separate the directories, I end up with empty strings in my list.
F... | [
"\nI do not want these empty strings. I realize that I can remove them by making a new list without them, but that seems sloppy. Is there a better way to remove the empty strings and slashes?\n\nWhat? There's only one empty string and it's always first, by definition.\npathlist = path.split(\"/\")[1:] \n\nIs pretty... | [
5,
3,
2,
1,
1
] | [] | [] | [
"python",
"urlparse",
"urlsplit"
] | stackoverflow_0006669407_python_urlparse_urlsplit.txt |
Q:
How to split up a file by keyword?
I have a large XML file that looks like
<data> skdfnlsniisimsoinfsdfoisdfinsdofinodnfonf <emrosem> 23324097234097g </emrosem>
<peto> oifmisnie </peto>
</data>
<data> sfnseosfnosefoisneofinseionfoaisenfoisen <emrosem> 3249087203470w </emrosem>
<peto> sdfn </peto>
</data>
I ... | How to split up a file by keyword? | I have a large XML file that looks like
<data> skdfnlsniisimsoinfsdfoisdfinsdofinodnfonf <emrosem> 23324097234097g </emrosem>
<peto> oifmisnie </peto>
</data>
<data> sfnseosfnosefoisneofinseionfoaisenfoisen <emrosem> 3249087203470w </emrosem>
<peto> sdfn </peto>
</data>
I want to separate this into a list that l... | [
"The included XML Parser is one way to parse XML. It might be a bit kludgey to get data off of it and into a list with the tags intact but it should be doable.\n",
"Please don't use regular expressions for this. If you need to parse XML, use an XML parser. XML just has too many subtleties to handle it with simple... | [
2,
0
] | [] | [] | [
"list",
"python",
"split",
"xml"
] | stackoverflow_0006670093_list_python_split_xml.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.