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:
csv utf-8 writer - compability with python2.4
At the bottom of this manual http://docs.python.org/library/csv.html we have example of UnicodeWriter
But how can i use this example in python 2.4
I got exception about codecs.getincrementalencoder(encoding)().
Property getincrementalencoder created only in version 2.... | csv utf-8 writer - compability with python2.4 | At the bottom of this manual http://docs.python.org/library/csv.html we have example of UnicodeWriter
But how can i use this example in python 2.4
I got exception about codecs.getincrementalencoder(encoding)().
Property getincrementalencoder created only in version 2.5. Who can replace this property?
Thanks!
| [
"Not sure if it will work, but try to use codecs.getencoder instead.\n"
] | [
1
] | [] | [] | [
"csv",
"python",
"utf_8"
] | stackoverflow_0001910610_csv_python_utf_8.txt |
Q:
Import error with virtualenv
I have a problem with virtualenv. I use it regulary, I use it on my development machine and on several servers. But on this last server I tried to use i got a problem.
I created a virtualenv with the --no-site-packages argument, and then I installed some python modules inside the virtu... | Import error with virtualenv | I have a problem with virtualenv. I use it regulary, I use it on my development machine and on several servers. But on this last server I tried to use i got a problem.
I created a virtualenv with the --no-site-packages argument, and then I installed some python modules inside the virtualenv. I can confirm that the modu... | [
"Is there a bash alias active on this machine for \"python\", by any chance? That will take priority over the PATH-modifications made by activate, and could cause the wrong python binary to be used.\nTry running virtualenv/bin/python directly (no need to activate) and see if you can import your module.\nIf this fix... | [
22,
10,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0001909025_python_virtualenv.txt |
Q:
How to do this GROUP BY query in Django's ORM with annotate and aggregate
I don't really have groked how to translate GROUP BY and HAVING to Django's QuerySet.annotate and QuerySet.aggregate. I'm trying to translate this SQL query into ORM speak
SELECT EXTRACT(year FROM pub_date) as year, EXTRACT(month from pub_da... | How to do this GROUP BY query in Django's ORM with annotate and aggregate | I don't really have groked how to translate GROUP BY and HAVING to Django's QuerySet.annotate and QuerySet.aggregate. I'm trying to translate this SQL query into ORM speak
SELECT EXTRACT(year FROM pub_date) as year, EXTRACT(month from pub_date) as month, COUNT(*) as article_count FROM articles_article GROUP BY year,mon... | [
"I think to do it in one query you might have to have month and year as separate fields...\nArticle.objects.values('pub_date').annotate(article_count=Count('title'))\n\nThat would group by by pub_date. But there is no way I can think of to do the equivalent of the extract function clause inline there.\nIf your mode... | [
14,
2
] | [] | [] | [
"django",
"group_by",
"orm",
"python"
] | stackoverflow_0001908741_django_group_by_orm_python.txt |
Q:
Inlines Python/Django technique for objects
I am reading the source code of the Django application blog at git://github.com/nathanborror/django-basic-apps.git.
How do you read the following Django code?
{% tags_for_object object as tag_list %}
My attempt: Make the variable object of the type tags_for_object and ... | Inlines Python/Django technique for objects | I am reading the source code of the Django application blog at git://github.com/nathanborror/django-basic-apps.git.
How do you read the following Django code?
{% tags_for_object object as tag_list %}
My attempt: Make the variable object of the type tags_for_object and rename the variable to tag_list.
The object appar... | [
"It looks like tags_for_object is the template tag from the django-tagging application.\nFrom the django-tagging documentation:\n\ntags_for_object:\nRetrieves a list of Tag objects\n associated with an object and stores\n them in a context variable.\nUsage:\n{% tags_for_object [object] as [varname] %}\n\nExample:... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001910953_django_python.txt |
Q:
concatenate items in dictionary in python using list comprehension
EDIT: Clarified the question a bit
How can I get a string from a dictionary with the format
key1 = value1
key2 = value2
in a relatively fast way ? (relative to plain concatenation)
A:
print '\n'.join('%s = %s' % (key, value) for key, value in d... | concatenate items in dictionary in python using list comprehension | EDIT: Clarified the question a bit
How can I get a string from a dictionary with the format
key1 = value1
key2 = value2
in a relatively fast way ? (relative to plain concatenation)
| [
"print '\\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())\n\n",
"There's no reason to use list comprehension here.\nPython 3.x:\nfor k,v in mydict.items():\n print(k, '=', v)\n\nPython 2.x:\nfor k,v in mydict.iteritems():\n print k, '=', v\n\nEDIT because of comment by OP in another answer:\nI... | [
10,
10,
3,
2,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0001911014_list_comprehension_python.txt |
Q:
Facebook application Django server connection
I am creating a Facebook application in Python and Django. I followed all the instructions mentioned on this page: http://wiki.developers.facebook.com/index.php/User:PyFacebook_Tutorial. But it ended up giving me this error:
The URL http://amitverma.dyndns.org/fbsampl... | Facebook application Django server connection | I am creating a Facebook application in Python and Django. I followed all the instructions mentioned on this page: http://wiki.developers.facebook.com/index.php/User:PyFacebook_Tutorial. But it ended up giving me this error:
The URL http://amitverma.dyndns.org/fbsample/?auth_token=0e80c8dbba442763d2c539d6e64e992a is n... | [
"You need to troubleshoot from somewhere outside your development box and local network. You need to figure out if this is a DNS issue, a port forwarding issue, or perhaps an issue on your dev. box (is a local firewall blocking the requests?).\nFrom a network location outside your home network, connect using the ro... | [
0
] | [] | [] | [
"django",
"facebook",
"networking",
"python"
] | stackoverflow_0001910846_django_facebook_networking_python.txt |
Q:
python checking for files
learning python there. I want to write a script to check if my webserver has picture named in the root 123.jpg
I have:
import urllib2
numeruks=100
adresiuks="http://localhost/" + str(numeruks) +".jpg"
try:
if numeruks < 150:
numeruks = numeruks + 1
urllib2.urlopen(adresiuks).... | python checking for files | learning python there. I want to write a script to check if my webserver has picture named in the root 123.jpg
I have:
import urllib2
numeruks=100
adresiuks="http://localhost/" + str(numeruks) +".jpg"
try:
if numeruks < 150:
numeruks = numeruks + 1
urllib2.urlopen(adresiuks).read()
reading manuals all day... | [
"You can test for 404 in your attempts to access the URL (and without even having to issue a read()):\nimport urllib2\n\nn = 123\n\ntry:\n url = 'http://localhost/%d.jpg' % n\n urllib2.urlopen(url)\nexcept urllib2.HTTPError, e:\n if e.code == 404:\n print '%d.jpg was not found' % n\n else:\n ... | [
1,
1,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0001911396_python_urllib2.txt |
Q:
Python: How do I find why IDLE restarts?
I am using python 2.5 on windows. All I am doing is unpickling a large file (18MB - a list of dictionaries) and modifiying some of its values. Now this works fine. But when I add a couple of prints, IDLE restarts. And weirdly enough it seems to be happening where I added th... | Python: How do I find why IDLE restarts? | I am using python 2.5 on windows. All I am doing is unpickling a large file (18MB - a list of dictionaries) and modifiying some of its values. Now this works fine. But when I add a couple of prints, IDLE restarts. And weirdly enough it seems to be happening where I added the print. I figured this out commenting and unc... | [
"Have you tried running your script from the command line rather than IDLE? Open a command prompt and type python to enter the Python interpreter. See if it crashes there too.\nSecondly, you should try using the pdb module for debugging your Python scripts. This is far more effective than print statements since ... | [
1,
0
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0001911615_python_python_idle.txt |
Q:
What is the best way to store database settings with Django?
I'm attempting to write a browser game using Django but I'm getting a bit stuck on how to store the settings for the game. For example, the game is tick based and I want to store the current tick. I have decided that I want only one game per database to ... | What is the best way to store database settings with Django? | I'm attempting to write a browser game using Django but I'm getting a bit stuck on how to store the settings for the game. For example, the game is tick based and I want to store the current tick. I have decided that I want only one game per database to avoid problems with the built-in user authorisation system (e.g. I... | [
"You could be a bit more generic and just have a \"Setting\" record. This would allow you to expand the amount of settings you could store infinitely.\nclass Setting(models.Model):\n name = models.CharField(max_length=50)\n value = models.TextField()\n\n# ...\n\n# Get the current slot setting\ncurrent_slot =... | [
7,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001911652_django_python.txt |
Q:
How do add multiple fields to a Form when trying to validate data?
What is the best way to have the IP address be included with the Form is_valid. Let me start with some code examples.
urls.py
from django.conf.urls.defaults import *
from testpost.views import TestPost
urlpatterns = patterns('',
(r'^djtestform... | How do add multiple fields to a Form when trying to validate data? | What is the best way to have the IP address be included with the Form is_valid. Let me start with some code examples.
urls.py
from django.conf.urls.defaults import *
from testpost.views import TestPost
urlpatterns = patterns('',
(r'^djtestforms/', TestPost),
)
model.py
from django.db import models
class TestPost... | [
"@czarchaic - Your'e answer gave me a good hint on what to do. I changed the model so that blank=True for ip_address, and then did a \nf = TestPostForm(request.POST)\nf.data['ip_address']=request.META['REMOTE_ADDR']\n\nAfter that is_valid worked. Thanks.\n",
"Save with commit=False\nform=TestPostForm(data=request... | [
2,
-1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001911383_django_python.txt |
Q:
More efficient way to count intersections?
I have a list of 300000 lists (fiber tracks), where each track is a list of (x,y,z) tuples/coordinates:
tracks=
[[(1,2,3),(3,2,4),...]
[(4,2,1),(5,7,3),...]
...
]
I also have a group of masks, where each mask is defined as a list of (x,y,z) tuples/coordinates:
mask_co... | More efficient way to count intersections? | I have a list of 300000 lists (fiber tracks), where each track is a list of (x,y,z) tuples/coordinates:
tracks=
[[(1,2,3),(3,2,4),...]
[(4,2,1),(5,7,3),...]
...
]
I also have a group of masks, where each mask is defined as a list of (x,y,z) tuples/coordinates:
mask_coords_list=
[[(1,2,3),(8,13,4),...]
[(6,2,2),(5,... | [
"Linearize the voxel coordinates, and put them into two scipy.sparse.sparse.csc matrices. \nLet v be the number of voxels, m the number of masks, and t the number of tracks.\nLet M be the mask csc matrix, size (m x v), where a 1 at (i,j) means mask i overlaps voxel j.\nLet T be the track csc matrix, size (t x v), ... | [
3,
1,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"python",
"set"
] | stackoverflow_0001910744_algorithm_python_set.txt |
Q:
Set django-notification to be opt in rather than the default of opt out
I'm using django-notification to allow my users to opt out of certain alerts I generate in my web-application.
By default when I create a new notice type it is enabled rather than disabled In the users notification interface (checked)
I'd lik... | Set django-notification to be opt in rather than the default of opt out | I'm using django-notification to allow my users to opt out of certain alerts I generate in my web-application.
By default when I create a new notice type it is enabled rather than disabled In the users notification interface (checked)
I'd like to make some alerts opt-in rather than the default of opt out. I've looked ... | [
"Its automatically set based on the 'default' column in the type itself, by default e-mail is a sensitivity of 2, so if you set the default to your new notice type default '1' it will no longer set it on by default for your users, the default when creating new notice types is '2' which would allow it to be sent to ... | [
4,
0
] | [] | [] | [
"code_reuse",
"django",
"pinax",
"python"
] | stackoverflow_0001884801_code_reuse_django_pinax_python.txt |
Q:
deleter decorator using Property in Python
I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google.
What I would like to achieve is when this deleter behavior is called, I can trigger ot... | deleter decorator using Property in Python | I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. I'm probably missing something, I could not find clear answers by Google.
What I would like to achieve is when this deleter behavior is called, I can trigger other actions (e.g: using my 3d application SDK).
... | [
"Make M a new-style class:\nclass M(object):\n\nSee http://www.python.org/download/releases/2.2.3/descrintro/#property:\n\nProperties do not work for classic\n classes, but you don't get a clear\n error when you try this. Your get\n method will be called, so it appears\n to work, but upon attribute\n assignmen... | [
14,
9
] | [] | [] | [
"decorator",
"properties",
"python"
] | stackoverflow_0001912229_decorator_properties_python.txt |
Q:
Limit calls to external database with Python CGI
I've got a Python CGI script that pulls data from a GPS service; I'd like this information to be updated on the webpage about once every 10s (the max allowed by the GPS service's TOS). But there could be, say, 100 users viewing the webpage at once, all calling the ... | Limit calls to external database with Python CGI | I've got a Python CGI script that pulls data from a GPS service; I'd like this information to be updated on the webpage about once every 10s (the max allowed by the GPS service's TOS). But there could be, say, 100 users viewing the webpage at once, all calling the script.
I think the users' scripts need to grab data f... | [
"Cache the results of your GPS data query in a file or database (sqlite) along with a datetime.\nYou can then do a datetime check against the last cached datetime to initiate another GPS data query.\nYou'll probably run into concurrency issues with cgi and the datetime check though...\nTo get around concurrency iss... | [
1
] | [] | [] | [
"cgi",
"python",
"sql"
] | stackoverflow_0001912253_cgi_python_sql.txt |
Q:
Extract data from a website's list, without superfluous tags
Working code: Google dictionary lookup via python and beautiful soup -> simply execute and enter a word.
I've quite simply extracted the first definition from a specific list item. However to get plain data, I've had to split my data at the line break, a... | Extract data from a website's list, without superfluous tags | Working code: Google dictionary lookup via python and beautiful soup -> simply execute and enter a word.
I've quite simply extracted the first definition from a specific list item. However to get plain data, I've had to split my data at the line break, and then strip it to remove the superfluous list tag.
My question i... | [
"I think you are looking for findAll(text=True) this will extract the text from the tags \ndefinitions = soup('ul')[0].findAll(text=True)\n\nWill return a ist of all the text contents broken at the tag boundaries\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"extract",
"html",
"python"
] | stackoverflow_0001911442_beautifulsoup_extract_html_python.txt |
Q:
App engine templates
In app engine there a way to use templates a bit more like php/javascript(document.write)?
for instance i would rather do:
<html>
<python>
print "Hello world"
</python>
</html>
rather than all the {IF } {ELSE } django stuff.
A:
You want embedded python in html page for that look into mako ... | App engine templates | In app engine there a way to use templates a bit more like php/javascript(document.write)?
for instance i would rather do:
<html>
<python>
print "Hello world"
</python>
</html>
rather than all the {IF } {ELSE } django stuff.
| [
"You want embedded python in html page for that look into mako (http://www.makotemplates.org/), you don't even need print e.g.\n<%inherit file=\"base.html\"/>\n<%\n rows = [[v for v in range(0,10)] for row in range(0,10)]\n%>\n<table>\n % for row in rows:\n ${makerow(row)}\n % endfor\n</table>\n\n<%... | [
3,
2,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001907187_google_app_engine_python.txt |
Q:
Organizing python code for handling statistic information
I'm going to create statistics based on information what builds were success or not and how much per project.
I create ProjectStat class per new project I see and inside handled statistics. For printing overall statistic I need to pass through all ProjectS... | Organizing python code for handling statistic information | I'm going to create statistics based on information what builds were success or not and how much per project.
I create ProjectStat class per new project I see and inside handled statistics. For printing overall statistic I need to pass through all ProjectStat instances. For printing success statistics per project I ne... | [
"I'm not sure I understand the Q, but I'll try to answer anyway :)\noption1:\ntotal = sum([project.projectTotal for project in dict.values()])\nsuccess = sum([project.projectSuccess for project in dict.values()])\nfailed = sum([project.projectFailed for project in dict.values()])\n\noption2:\n(total,success,failed)... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001912635_python.txt |
Q:
Building app to Classify / Describe Products - Overwhelmed somewhere between planning & execution
Greetings!
I recently started working for a company that carries a line of 20,000 Surgical Instruments. Our data on all items is currently spotty and chaotic at best. I intend to fix this.
I have been tasked with rede... | Building app to Classify / Describe Products - Overwhelmed somewhere between planning & execution | Greetings!
I recently started working for a company that carries a line of 20,000 Surgical Instruments. Our data on all items is currently spotty and chaotic at best. I intend to fix this.
I have been tasked with redesigning the web site. As part of the project, I'm building an app to classify and describe all products... | [
"Nice drawing:)\nDid you do any experiments with the actual table stucture? It does not look so hard. Here is a go while trying to keep things as simple as possible.\n==products==\nid[int]\nnumber[varchar]: unique, ie. #50-334 \ncategory_id[int]: has-one relation to category.id\n\n==categories==\n// What you call b... | [
3,
3,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"architecture",
"cakephp",
"database_design",
"mysql",
"python"
] | stackoverflow_0001909059_architecture_cakephp_database_design_mysql_python.txt |
Q:
How to become a good Python coder?
I started with c++ but as we all know, c++ is a monster. I still have to take it and I do like C++ (it takes programming a step further)
However, currently I have been working with python for a while. I see how you guys can turn some long algorithm into simple one.
I know progra... | How to become a good Python coder? | I started with c++ but as we all know, c++ is a monster. I still have to take it and I do like C++ (it takes programming a step further)
However, currently I have been working with python for a while. I see how you guys can turn some long algorithm into simple one.
I know programming is a progress, and can take up to ... | [
"\nWrite code\nRead books, http://www.coderholic.com/free-python-programming-books/\nRead code \nRead tutorials, http://www.dabeaz.com/talks.html, ...\nWrite more code\nDo exercises, e.g. Building Skills in Python\nWrite even more code\nAnswer SO python questions, https://stackoverflow.com/unanswered/tagged/python\... | [
24,
4,
4,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0001908250_python.txt |
Q:
xml.dom.minidom python issue
from xml.dom.minidom import *
resp = "<title> This is a test! </title>"
rssDoc = parseString(resp)
titles = rssDoc.getElementsByTagName('title')
moo = ""
for t in titles:
moo += t.nodeValue;
Gives the following error:
main.py, line 42, in
get moo += t.nodeValue;
TypeEr... | xml.dom.minidom python issue | from xml.dom.minidom import *
resp = "<title> This is a test! </title>"
rssDoc = parseString(resp)
titles = rssDoc.getElementsByTagName('title')
moo = ""
for t in titles:
moo += t.nodeValue;
Gives the following error:
main.py, line 42, in
get moo += t.nodeValue;
TypeError: cannot concatenate 'str' and ... | [
"The <title> node contains a text node as a subnode. Maybe you want to iterate through the subnodes instead? Something like this:\nfrom xml.dom.minidom import *\n\nresp = \"<title> This is a test! </title>\"\n\nrssDoc = parseString(resp)\n\ntitles = rssDoc.getElementsByTagName('title')\n\nmoo = \"\"\n\nfor t in t... | [
2,
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0001913613_python_xml.txt |
Q:
db.Model class variables and __init__
(New to Python and GAE)
I'm looking for an explanation to the use of class variables in db.Model subclasses, which are treated like instance variables. Why are these declared in class scope and not in __init__? Is this some kind of special GAE requirement?
A:
Yes, this is a ... | db.Model class variables and __init__ | (New to Python and GAE)
I'm looking for an explanation to the use of class variables in db.Model subclasses, which are treated like instance variables. Why are these declared in class scope and not in __init__? Is this some kind of special GAE requirement?
| [
"Yes, this is a programming model special to GAE. You can think of the class properties as the table definition. The instance properties are the contents of a row, they are populated on the fly by the metclass db.PropertiedClass.\nThere is a lot going on under the hood, if you are interested always have a look at t... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001913775_google_app_engine_python.txt |
Q:
Best place to coerce/convert to the right type in Python
I'm still fairly new to Python and I'm trying to get used to its dynamic typing. Sometimes I have a function or a class that expects a parameter of a certain type, but could get a value of another type that's coercible to it. For example, it might expect a f... | Best place to coerce/convert to the right type in Python | I'm still fairly new to Python and I'm trying to get used to its dynamic typing. Sometimes I have a function or a class that expects a parameter of a certain type, but could get a value of another type that's coercible to it. For example, it might expect a float but instead receive an int or a decimal. Or it might expe... | [
"You \"coerce\" (perhaps -- it could be a noop) when it's indispensable for you to do so, and no earlier. For example, say you have a function that takes a float and returns the sum of its sine and cosine:\nimport math\ndef spc(x):\n math.sin(x) + math.cos(x)\n\nWhere should you \"coerce\" x to float? Answer: no... | [
8,
2,
0
] | [] | [] | [
"dynamic_typing",
"python"
] | stackoverflow_0001912476_dynamic_typing_python.txt |
Q:
Django + MySQL on Mac OS 10.6.2 Snow Leopard
There were some excellent answers to this question already, however, they are now outdated.
I've been able to get the module installed, but "python manage.py runserver" fails with
iMac:myproject drhoden$ python manage.py runserver
Validating models...
Unhandled excep... | Django + MySQL on Mac OS 10.6.2 Snow Leopard | There were some excellent answers to this question already, however, they are now outdated.
I've been able to get the module installed, but "python manage.py runserver" fails with
iMac:myproject drhoden$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0... | [
"I have ultimately solved my own problem, with of course, the subconscious and conscious help from the many posts, blogs, and mail logs I've read. I would give links if I could remember.\nIn a nutshell, I reinstalled EVERYTHING using MacPorts. \nAfter editing ~/.bash_profile and commenting out all the previous mo... | [
21,
4,
1
] | [] | [] | [
"django",
"mysql",
"osx_snow_leopard",
"python"
] | stackoverflow_0001904039_django_mysql_osx_snow_leopard_python.txt |
Q:
How can I use TOR as a proxy?
I'm trying to use TOR as a generic proxy but it fails
Right now I'm trying with python but I'm pretty sure it would be the same with any other language. I can connect to other proxies with python so I get how it "should" be done.
I found a list of TOR entry nodes
h = httplib.HTTPConne... | How can I use TOR as a proxy? | I'm trying to use TOR as a generic proxy but it fails
Right now I'm trying with python but I'm pretty sure it would be the same with any other language. I can connect to other proxies with python so I get how it "should" be done.
I found a list of TOR entry nodes
h = httplib.HTTPConnection("one entry node", 80)
h.conne... | [
"First, make sure you are using the correct node location and port. Most proxies use ports other than 80. Second, specify the protocol to use with the correct URL on your request string.\nUnder normal circumstances, your code should work if it looks something like this one:\nh = httplib.HTTPConnection(\"138.45.68.1... | [
4
] | [] | [] | [
"language_agnostic",
"proxies",
"proxy",
"python",
"tor"
] | stackoverflow_0001914254_language_agnostic_proxies_proxy_python_tor.txt |
Q:
Python string pattern recognition/compression
I can do basic regex alright, but this is slightly different, namely I don't know what the pattern is going to be.
For example, I have a list of similar strings:
lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']
In this case t... | Python string pattern recognition/compression | I can do basic regex alright, but this is slightly different, namely I don't know what the pattern is going to be.
For example, I have a list of similar strings:
lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']
In this case the common pattern is two segments of common text: '... | [
"This solution finds the two longest common substrings and uses them to delimit the input strings:\ndef an_answer_to_stackoverflow_question_1914394(lst):\n \"\"\"\n >>> lst = ['asometxt0moretxt', 'bsometxt1moretxt', 'aasometxt10moretxt', 'zzsometxt999moretxt']\n >>> an_answer_to_stackoverflow_question_1914... | [
8,
3,
2,
2,
1
] | [
"How about subbing out the known text, and then splitting?\nimport re\n[re.sub('(sometxt|moretxt)', ',', x).split(',') for x in lst]\n# results in\n[['a', '0', ''], ['b', '1', ''], ['aa', '10', ''], ['zz', '999', '']]\n\n"
] | [
-1
] | [
"compression",
"pattern_recognition",
"python",
"string"
] | stackoverflow_0001914236_compression_pattern_recognition_python_string.txt |
Q:
How does this max() expression in Python work?
Here's the code:
a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
print max(a,key=lambda w: b[w])
This prints out 1.
I don't understand how max(a,key=lambda w: b[w]) is being evaluated here though; I'm guessing for each value i in a, it finds the correspondi... | How does this max() expression in Python work? | Here's the code:
a = [1,2,3,4]
b = {}
b[1] = 10
b[2] = 8
b[3] = 7
b[4] = 5
print max(a,key=lambda w: b[w])
This prints out 1.
I don't understand how max(a,key=lambda w: b[w]) is being evaluated here though; I'm guessing for each value i in a, it finds the corresponding value b[i] by
saving the current value of i as w... | [
"max(a,...) is always going to return an element of a. So the result will be either 1,2,3, or 4.\nFor each value w in a, the key value is b[w]. The largest key value is 10, and that corresponds with w equalling 1. So max(a,key=lambda w: b[w]) returns 1.\n"
] | [
9
] | [
"Try:\na = [1,2,3,4]\nb = {}\nb[1] = 10\nb[2] = 8\nb[3] = 7\nb[4] = 5\nc = a + b.values()\nprint max(*c)\n\n"
] | [
-3
] | [
"lambda",
"max",
"python"
] | stackoverflow_0001911981_lambda_max_python.txt |
Q:
How to open a webpage and search for a word in python
How to open a webpage and search for a word in python?
A:
This is a little simplified:
>>> import urllib
>>> import re
>>> page = urllib.urlopen("http://google.com").read()
# => via regular expression
>>> re.findall("Shopping", page)
['Shopping']
# => via ... | How to open a webpage and search for a word in python | How to open a webpage and search for a word in python?
| [
"This is a little simplified:\n>>> import urllib\n>>> import re\n>>> page = urllib.urlopen(\"http://google.com\").read()\n\n# => via regular expression\n\n>>> re.findall(\"Shopping\", page)\n['Shopping']\n\n# => via string.find, returns the position ...\n>>> page.find(\"Shopping\")\n2716\n\nFirst, get the page (e.g... | [
4,
0,
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0001913871_http_python.txt |
Q:
Pickling a staticmethod in Python
I've been trying to pickle an object which contains references to static class methods.
Pickle fails (for example on module.MyClass.foo) stating it cannot be pickled, as module.foo does not exist.
I have come up with the following solution, using a wrapper object to locate the fun... | Pickling a staticmethod in Python | I've been trying to pickle an object which contains references to static class methods.
Pickle fails (for example on module.MyClass.foo) stating it cannot be pickled, as module.foo does not exist.
I have come up with the following solution, using a wrapper object to locate the function upon invocation, saving the conta... | [
"This seems to work.\nclass PickleableStaticMethod(object):\n def __init__(self, fn, cls=None):\n self.cls = cls\n self.fn = fn\n def __call__(self, *args, **kwargs):\n return self.fn(*args, **kwargs)\n def __get__(self, obj, cls):\n return PickleableStaticMethod(self.fn, cls)\n... | [
5,
0
] | [] | [] | [
"pickle",
"python",
"static_methods"
] | stackoverflow_0001914261_pickle_python_static_methods.txt |
Q:
Alphabetizing functions in a Python class
Warning, this is a sheer-laziness query! As my project develops, so also do the number of functions within a class. I also have a number of classes per .py file. So what I would like to do is re-sort them to that the function names are organised [sorry, UK here, I've alrea... | Alphabetizing functions in a Python class | Warning, this is a sheer-laziness query! As my project develops, so also do the number of functions within a class. I also have a number of classes per .py file. So what I would like to do is re-sort them to that the function names are organised [sorry, UK here, I've already compromised hugely with the 'z' in Alphabeti... | [
"I don't have a solution to your question, but I have a very strong opinion: if the number of methods in your classes becomes so large you have trouble finding them, you should consider reducing the number, perhaps by splitting the class into smaller ones.\nThe same principles of cohesion that apply to functions an... | [
8,
3
] | [] | [] | [
"alphabetized",
"class",
"publishing",
"python",
"visualization"
] | stackoverflow_0001914761_alphabetized_class_publishing_python_visualization.txt |
Q:
Authenticated request in Google App Engine using fetch() function: how to provide the information in the header of the request?
I am trying to pass automatically, using Google App Engine, my password and ID to eBay, to this page:
https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&UsingSSL=1&pUserId=&co_partnerId=2&s... | Authenticated request in Google App Engine using fetch() function: how to provide the information in the header of the request? | I am trying to pass automatically, using Google App Engine, my password and ID to eBay, to this page:
https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&UsingSSL=1&pUserId=&co_partnerId=2&siteid=0&ru=http%3A%2F%2Fcgi5.ebay.com%2Fws2%2FeBayISAPI.dll%3FSellItem%26hm%3Dum.rundkoi376%26%26hc%3D1%26guest%3D1&pageType=1144
(I... | [
"I'm not sure if this helps, but ebay has an API that would be simpler to use and incorporate. Check out http://developer.ebay.com/businessbenefits/aboutus/\n",
"Looks like some of the quote-characters are the wrong kind -- reversed \"smart quotes\" rather than normal plain ordinary ASCII quote characters. Hard ... | [
3,
2
] | [] | [] | [
"authorization",
"google_app_engine",
"header",
"python"
] | stackoverflow_0001912845_authorization_google_app_engine_header_python.txt |
Q:
How to handle back and forward buttons in the hildon.Seekbar?
The hildon.Seekbar widget consists of a scale widget and two buttons. What signals does the widget send when the buttons are clicked or how could I find out? Is there a way to monitor all signals/events that a widget sends in PyGTK?
A:
The documentati... | How to handle back and forward buttons in the hildon.Seekbar? | The hildon.Seekbar widget consists of a scale widget and two buttons. What signals does the widget send when the buttons are clicked or how could I find out? Is there a way to monitor all signals/events that a widget sends in PyGTK?
| [
"The documentation you linked to shows this:\nseekbar.connect(\"value-changed\", control_changed, label)\nseekbar.connect(\"notify::fraction\", fraction_changed, label)\n\nSo it seems it has (at least) two signals called \"value-changed\" and \"notify::fraction\". It also shows an inheritance diagram that tells you... | [
1,
0
] | [] | [] | [
"gtk",
"maemo",
"pygtk",
"python",
"seekbar"
] | stackoverflow_0001083905_gtk_maemo_pygtk_python_seekbar.txt |
Q:
Python: List to ints to a single number?
Say i have a several list if ints:
x = [['48', '5', '0'], ['77', '56', '0'],
['23', '76', '34', '0']]
I want this list to be converted to a single number, but the the single number type is still an integer i.e.:
4850775602376340
i have been using this code to carry out t... | Python: List to ints to a single number? | Say i have a several list if ints:
x = [['48', '5', '0'], ['77', '56', '0'],
['23', '76', '34', '0']]
I want this list to be converted to a single number, but the the single number type is still an integer i.e.:
4850775602376340
i have been using this code to carry out the process:
num = int(''.join(map(str,x)))
bu... | [
">>> int(''.join(reduce(lambda a, b: a + b, x)))\n4850775602376340\n\n",
"I'd use itertools.chain.from_iterable for this (new in python 2.6)\nExample code:\nimport itertools\nx = [['48', '5', '0'], ['77', '56', '0'], ['23', '76', '34', '0']]\nprint int(''.join(itertools.chain.from_iterable(x)))\n\n",
">>> int('... | [
6,
6,
4,
2,
1,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001914883_list_python.txt |
Q:
On the google app engine, why does my 'import' statement fail on Live, but work on Dev(localmachine)?
I have a python/django application that runs on the google app engine.
My views.py file has some imports...
from commands.userCommands import RegisterUserCommand
from commands.accountCommands import CreateNewAccou... | On the google app engine, why does my 'import' statement fail on Live, but work on Dev(localmachine)? | I have a python/django application that runs on the google app engine.
My views.py file has some imports...
from commands.userCommands import RegisterUserCommand
from commands.accountCommands import CreateNewAccountCommand, RenameAccountCommand
These imports work fine on my development environment (local machine). But... | [
"You could be running into a clash with Python's own commands module (which doesn't have submodules like yours) -- naming your own modules and packages in ways that are meant to hide ones in the standard library (just like naming your variables in ways that are meant to hide builtin names, like list or file) is alw... | [
5,
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001914881_django_google_app_engine_python.txt |
Q:
Python: List of lists of integers to absolute value to single number
If i had a list of list of integers say:
[['12' '-4' '66' '0'], ['23' '4' '-5'
'0'], ['23' '77' '89' '-1' '0']]
I wanted to convert the numbers to their absolute values and then to a single number, so the output would be:
1246602345023778910... | Python: List of lists of integers to absolute value to single number | If i had a list of list of integers say:
[['12' '-4' '66' '0'], ['23' '4' '-5'
'0'], ['23' '77' '89' '-1' '0']]
I wanted to convert the numbers to their absolute values and then to a single number, so the output would be:
1246602345023778910
| [
"What you're showing is (maybe) a list of lists of strings, and the syntax is extremely peculiar -- the sublists are shown with the normal, usual commas, but inside each there are just literal strings with spaces between them. If you actually type that into Python, you'll get a list where each sublist contains a s... | [
2,
1,
1,
0,
0
] | [] | [] | [
"absolute",
"integer",
"list",
"mapping",
"python"
] | stackoverflow_0001915342_absolute_integer_list_mapping_python.txt |
Q:
python descriptors sharing values across classes
A python descriptor that I'm working with is sharing its value across all instances of its owner class. How can I make each instance's descriptor contain its own internal values?
class Desc(object):
def __init__(self, initval=None,name='val'):
self.val =... | python descriptors sharing values across classes | A python descriptor that I'm working with is sharing its value across all instances of its owner class. How can I make each instance's descriptor contain its own internal values?
class Desc(object):
def __init__(self, initval=None,name='val'):
self.val = initval
self.name = name
def __get__(sel... | [
"There is only one descriptor object, stored on the class object, so self is always the same. If you want to store data per-object and access it through the descriptor, you either have to store the data on each object (probably the better idea) or in some data-structure keyed by each object (an idea I don't like as... | [
7
] | [] | [] | [
"descriptor",
"python"
] | stackoverflow_0001915643_descriptor_python.txt |
Q:
with statement - backport for Python 2.5
I'd like to use with statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)?
Is this code
from __future__ import with_statement
compatible with Python 2.6?
A:
Yes, that... | with statement - backport for Python 2.5 | I'd like to use with statement in Python 2.5 in some production code. It was backported, should I expect any problems (e.g. with availability/compatibility on other machines/etc)?
Is this code
from __future__ import with_statement
compatible with Python 2.6?
| [
"Yes, that statement is a no-operation in Python 2.6, so you can freely use it to make with a keyword in your 2.5 code as well, without affecting your code's operation in 2.6. This is in fact the general design intention of \"importing from the future\" in Python!\n",
"You can call this in Python 2.6 and 3.0/1 w... | [
7,
4,
3
] | [] | [] | [
"backport",
"python",
"with_statement"
] | stackoverflow_0001915927_backport_python_with_statement.txt |
Q:
How do I add rows and columns to a NUMPY array?
Hello I have a 1000 data series with 1500 points in each.
They form a (1000x1500) size Numpy array created using np.zeros((1500, 1000)) and then filled with the data.
Now what if I want the array to grow to say 1600 x 1100? Do I have to add arrays using hstack and ... | How do I add rows and columns to a NUMPY array? | Hello I have a 1000 data series with 1500 points in each.
They form a (1000x1500) size Numpy array created using np.zeros((1500, 1000)) and then filled with the data.
Now what if I want the array to grow to say 1600 x 1100? Do I have to add arrays using hstack and vstack or is there a better way?
I would want the dat... | [
"This should do what you want (ie, using 3x3 array and 4x4 array to represent the two arrays in the OP)\n>>> import numpy as NP\n>>> a = NP.random.randint(0, 10, 9).reshape(3, 3)\n>>> a\n>>> array([[1, 2, 2],\n [7, 0, 7],\n [0, 3, 0]])\n\n>>> b = NP.zeros((4, 4))\n\nmapping a on to b:\n>>> b[:3,... | [
11,
3,
2,
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"reshape"
] | stackoverflow_0001909994_arrays_numpy_python_reshape.txt |
Q:
Python: List to Hex
I am writing a small forensics python app and I am having trouble converting a List entry to Hex. I have tried the encode/decode methood but get bogus conversions or odd-length string Type Errors. I have pasted the code below, and as you can see I need the address in hex, so I can add the cou... | Python: List to Hex | I am writing a small forensics python app and I am having trouble converting a List entry to Hex. I have tried the encode/decode methood but get bogus conversions or odd-length string Type Errors. I have pasted the code below, and as you can see I need the address in hex, so I can add the count to it.
def location_... | [
"The hex function converts integers to their hexadecimal representation:\n>>> a = 123\n>>> hex(a)\n'0x7b'\n\n"
] | [
2
] | [] | [] | [
"hex",
"python"
] | stackoverflow_0001916493_hex_python.txt |
Q:
Does Django support model classes that inherit after many non-abstract models?
Lets say I have three django model classes - lets call them A, B and C. If A and B are abstract, I can do something like:
class C(A,B):
pass
What if they aren't abstract and I do the same? Will everything still work correctly or no... | Does Django support model classes that inherit after many non-abstract models? | Lets say I have three django model classes - lets call them A, B and C. If A and B are abstract, I can do something like:
class C(A,B):
pass
What if they aren't abstract and I do the same? Will everything still work correctly or no? Or have I got it wrong and this should not be done with abstract models either?
I'... | [
"Yes, you can use normal Python multiple-inheritance with models. Bear in mind this warning though:\n\nJust as with Python's subclassing,\n it's possible for a Django model to\n inherit from multiple parent models.\n Keep in mind that normal Python name\n resolution rules apply. The first base\n class that a p... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001916522_django_django_models_python.txt |
Q:
List and Integer query
If i had a list of numbers and some maybe negative, how would i ensure all numbers in my list were positive? I can covert the items in the list to integers thats no problem.
Another question, I want to compare items in my list to an integer value say 'x' and sum all the values in my list tha... | List and Integer query | If i had a list of numbers and some maybe negative, how would i ensure all numbers in my list were positive? I can covert the items in the list to integers thats no problem.
Another question, I want to compare items in my list to an integer value say 'x' and sum all the values in my list that are less than x.
Thank you... | [
"If you have a list Ns of numbers (if it's a list of strings as in several similar questions asked recently each will have to be made into an int, or whatever other kind of number, by calling int [[or float, etc]] on it), the list of their absolute values (if that's what you mean by \"ensure\") is\n[abs(n) for n in... | [
4,
0,
0,
0,
0
] | [] | [] | [
"integer",
"list",
"python"
] | stackoverflow_0001916663_integer_list_python.txt |
Q:
resizing of button icons in pyqt4
I want to make image in my QMainWindow so when you click on it you have a signal translating like qpushbutton I use this:
self.quit=QtGui.QPushButton(self)
self.quit.setIcon(QtGui.QIcon('images/9.bmp'))
But the problem is whene I resize the window qpushbutton resized too but not ... | resizing of button icons in pyqt4 | I want to make image in my QMainWindow so when you click on it you have a signal translating like qpushbutton I use this:
self.quit=QtGui.QPushButton(self)
self.quit.setIcon(QtGui.QIcon('images/9.bmp'))
But the problem is whene I resize the window qpushbutton resized too but not his icon,
| [
"Qt won't stretch your image for you - and it's best this way. I recommend to keep the pushbutton of a constant size by adding stretchers to the layout holding it. A resizable pushbutton isn't very appealing visually, and is uncommon in GUIs, anyway.\nTo make a clickable image, here's the simplest code I can think ... | [
1
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0001916722_pyqt4_python.txt |
Q:
Why there are not any real lightweight threads for python?
I'm new to Python and seems that the multiprocessing and threads module are not very interesting and suffer from the same problems such as threads in Perl. Is there a technical reason why the interpreter can't use lightweight threads such as posix threads ... | Why there are not any real lightweight threads for python? | I'm new to Python and seems that the multiprocessing and threads module are not very interesting and suffer from the same problems such as threads in Perl. Is there a technical reason why the interpreter can't use lightweight threads such as posix threads to make an efficient thread implementation that really runs on s... | [
"It is using POSIX threads. The problem is the GIL.\nNote that the GIL is not part of the Python spec --- it's part of the CPython reference implementation. Jython, for example, does not suffer from this problem.\nThat said, looked into Stackless ?\n",
"Piotr,\nYou might want to take a look at stackless (http://w... | [
24,
0
] | [] | [] | [
"multithreading",
"pthreads",
"python"
] | stackoverflow_0001914341_multithreading_pthreads_python.txt |
Q:
Determining Build Directory from SConscript
I have an SConscript which is being copied to a build directory (variant_dir = ...) for construction. As a workaround for not being able to express dependencies, I'm trying to copy some additional files into the build directory.
How do I determine what the current build ... | Determining Build Directory from SConscript | I have an SConscript which is being copied to a build directory (variant_dir = ...) for construction. As a workaround for not being able to express dependencies, I'm trying to copy some additional files into the build directory.
How do I determine what the current build directory is, within an SConscript?
For instance,... | [
"My answer seems too simple, so maybe I misunderstood the question, but ...\nFor me, in subdir/SConscript: \nmy_build_directory = '.'\n\necho_cmd = Command('always.echo', [], \"echo %s\" % (Dir('.').abspath))\nAlias('echo', echo_cmd)\n\nproduces:\n# => cd test-scons\n# => ls \n# build/ SConstruct subdir/\n#... | [
2
] | [] | [] | [
"build_automation",
"python",
"scons"
] | stackoverflow_0001916473_build_automation_python_scons.txt |
Q:
How to pass value for python for loop?
In C/C++:
for(int i=0;i<=5;i++)
In Python:
for i in range(0,5)
Question is:
s=[1,2,3,4,1]
for i in s:
for j in s:
Here i wanna make second for loop j=1 (j value should be start with 1 like this s[1]=2).How do i pass that value.
A:
You should ask this on stackoverflo... | How to pass value for python for loop? | In C/C++:
for(int i=0;i<=5;i++)
In Python:
for i in range(0,5)
Question is:
s=[1,2,3,4,1]
for i in s:
for j in s:
Here i wanna make second for loop j=1 (j value should be start with 1 like this s[1]=2).How do i pass that value.
| [
"You should ask this on stackoverflow, but the answer is (if I got you right):\nfor i in s:\n for j in s[1:]:\n\nRead this chapter about lists in python, this will help you.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001916991_python.txt |
Q:
App engine app design questions
I want to load info from another site (this part is done), but i am doing this every time the page is loaded and that wont do. So i was thinking of having a variable in a table of settings like 'last checked bbc site' and when the page loads it would check if its been long enough si... | App engine app design questions | I want to load info from another site (this part is done), but i am doing this every time the page is loaded and that wont do. So i was thinking of having a variable in a table of settings like 'last checked bbc site' and when the page loads it would check if its been long enough since last check to check again. Is the... | [
"I think there are 2 options that would work for you, besides creating a entity in the datastore to keep track of \"last visited time\".\nOne way is to just check the external page periodically, using the cron api as described by jldupont. \nThe second way is to store the last visited time in memcache. Although ... | [
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001916009_google_app_engine_python.txt |
Q:
How to launch a Python/Tkinter dialog box that self-destructs?
Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this?
A:
You can use the after function to call a function after a delay elapsed and the destr... | How to launch a Python/Tkinter dialog box that self-destructs? | Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this?
| [
"You can use the after function to call a function after a delay elapsed and the destroy to close the window.\nHere is an example\nfrom Tkinter import Label, Tk\nroot = Tk()\nprompt = 'hello'\nlabel1 = Label(root, text=prompt, width=len(prompt))\nlabel1.pack()\n\ndef close_after_2s():\n root.destroy()\n\nroot.af... | [
11,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0001917198_python_tkinter.txt |
Q:
Would calling a function like this be considered bad practice?
Suppose I have this function signature:
def foo(a=True, b=True, c=True, d=True, e=True):
I've decided these would be concise ways to call this function, considering all passed parameters should be False:
foo(*5*[False])
foo(*[False]*5)
But something ... | Would calling a function like this be considered bad practice? | Suppose I have this function signature:
def foo(a=True, b=True, c=True, d=True, e=True):
I've decided these would be concise ways to call this function, considering all passed parameters should be False:
foo(*5*[False])
foo(*[False]*5)
But something tells me that would be bad Python style. What do you think?
| [
"if it's hard to read, it's bad style.\nremember that code is read a lot more often than written.\n",
"I like following the 80-20 rule with default values. If a function has default values for a parameter and I choose to use a different value, I need to make that evident in the call because that is an important p... | [
9,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0001917537_python.txt |
Q:
Perl within Python?
There is a Perl library I would like to access from within Python.
How can I use it?
FYI, the software is NCleaner. I would like to use it from within Python to transform an HTML string into text. (Yes, I know about aaronsw's Python html2text. NCleaner is better, because it removes boiler-plate... | Perl within Python? | There is a Perl library I would like to access from within Python.
How can I use it?
FYI, the software is NCleaner. I would like to use it from within Python to transform an HTML string into text. (Yes, I know about aaronsw's Python html2text. NCleaner is better, because it removes boiler-plate.)
I don't want to run th... | [
"pyperl provides perl embedding for python, but honestly it's not the way I'd go. I second Roboto's suggestion -- write a script that runs NCleaner (either processing from stdin to stdout, or working on temporary files, whichever one is more appropriate), and run it as a subprocess.\nOr, since I see from the NClean... | [
13
] | [] | [] | [
"perl",
"python",
"text_mining"
] | stackoverflow_0001917656_perl_python_text_mining.txt |
Q:
Python joining strings
I have run into a problem joining two strings in Python.
I have some code that is like this:
for line in sites:
site = line
for line in files:
url = site+line
That should be easy I thougth but the strings ends up "looking wierd":
http://example.com/ (this is the si... | Python joining strings | I have run into a problem joining two strings in Python.
I have some code that is like this:
for line in sites:
site = line
for line in files:
url = site+line
That should be easy I thougth but the strings ends up "looking wierd":
http://example.com/ (this is the site)
history.txt (Th... | [
"The simplest thing is to avoid using the same variable in the for statements:\nfor site in sites:\n for line in files:\n url = site + line\n\nDoes that clear things up? It is good practice in any case.\n",
"Maybe you have extra whitespace for example a newline at the end of the site\nfor site in sites:\n ... | [
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001917705_python_string.txt |
Q:
Control decimal division precision in MySQLdb
MySQLdb does some weirdness where it seems to always return a Decimal object with 2 more significant figures than the numerator of a division operation.
If the denominator is relatively large, this means that sometimes the result gets truncated to zero:
>>> import MySQ... | Control decimal division precision in MySQLdb | MySQLdb does some weirdness where it seems to always return a Decimal object with 2 more significant figures than the numerator of a division operation.
If the denominator is relatively large, this means that sometimes the result gets truncated to zero:
>>> import MySQLdb
>>> db = MySQLdb.connect(.....)
>>> c = db.curs... | [
"You can change the div_precision_increment variable. It defaults to 4.\nhttp://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_div_precision_increment\nHere's an example using your division:\nmysql> select 1000/ 20990933630;\n+-------------------+\n| 1000/ 20990933630 |\n+-------------------+\n... | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001917385_mysql_python.txt |
Q:
Need to add httpd support to this wxPython code
I need to add httpd support to this sample wxpython code.
It parses the url and display different images.
What's the easiest way to do this?
import wx
a = wx.PySimpleApp()
wximg = wx.Image('w.png',wx.BITMAP_TYPE_PNG)
wxbmp=wximg.ConvertToBitmap()
f = wx.Frame(None, -... | Need to add httpd support to this wxPython code | I need to add httpd support to this sample wxpython code.
It parses the url and display different images.
What's the easiest way to do this?
import wx
a = wx.PySimpleApp()
wximg = wx.Image('w.png',wx.BITMAP_TYPE_PNG)
wxbmp=wximg.ConvertToBitmap()
f = wx.Frame(None, -1, "Show JPEG demo")
f.SetSize( wxbmp.GetSize() )
wx.... | [
"Problem solved. \nNeed to add \nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n ....\n\nclass w_HttpThread(threading.Thread):\n def __init__(self, win):\n\n ...\n\nOn particular URL, do wx.PostEvent to the wx windows.\nwxWindows code will update the window with new image.\nIt works too. ... | [
0
] | [] | [] | [
"apache",
"python",
"wxpython"
] | stackoverflow_0001910226_apache_python_wxpython.txt |
Q:
Auth_token error at Facebook
i have been on this for the last 2 days with no result.
i am running my facebook app on my localhost with port-forwarding method.
i know my server setup is working fine as i can see the logs on the django runserver and dyndns log as well.
django is properly responding to calls as well.... | Auth_token error at Facebook | i have been on this for the last 2 days with no result.
i am running my facebook app on my localhost with port-forwarding method.
i know my server setup is working fine as i can see the logs on the django runserver and dyndns log as well.
django is properly responding to calls as well.
the problem is as soon as the app... | [
"This often happens with a failed authentication. I'm not sure what the Python client libraries might look like, but with the PHP ones you generally make an authorization call against the library, something like $facebook->require_login().\nWith the PHP library, if this call fails to verify the user's Facebook ses... | [
1,
0
] | [] | [] | [
"django",
"facebook",
"python"
] | stackoverflow_0001918047_django_facebook_python.txt |
Q:
Making Windows executables from Django applications
I am trying to make a Django website be a simple Windows executable. I've been told that py2exe does not work correctly, both due to Django using __import__, and to its attempting to dispatch manage.py in some obscure way. Is that the case? If so, is there an ... | Making Windows executables from Django applications | I am trying to make a Django website be a simple Windows executable. I've been told that py2exe does not work correctly, both due to Django using __import__, and to its attempting to dispatch manage.py in some obscure way. Is that the case? If so, is there an alternative tool that works better, or is there a way to ... | [
"You can try Pyinstaller.\n",
"PyInstaller trunk has been succesfully used to build Django applications. It has builtin support for many Django magic, but requires a careful setup (have a look at the dedicated wiki page).\n"
] | [
2,
0
] | [] | [] | [
"django",
"py2exe",
"python"
] | stackoverflow_0001821632_django_py2exe_python.txt |
Q:
Python import mechanics
I have two related Python 'import' questions. They are easily testable, but I want answers that are language-defined and not implementation-specific, and I'm also interested in style/convention, so I'm asking here instead.
1)
If module A imports module B, and module B imports module C, can ... | Python import mechanics | I have two related Python 'import' questions. They are easily testable, but I want answers that are language-defined and not implementation-specific, and I'm also interested in style/convention, so I'm asking here instead.
1)
If module A imports module B, and module B imports module C, can code in module A reference mo... | [
"The first thing you should know is that the Python language is NOT an ISO standard. This is rather different from C/C++, and it means that there's no \"proper\" way to define a language behaviour - CPython might do something just because it was coded that way, and Jython might do the other way round.\nabout your q... | [
13,
11
] | [] | [] | [
"coding_style",
"conventions",
"import",
"module",
"python"
] | stackoverflow_0001917958_coding_style_conventions_import_module_python.txt |
Q:
How to store a dynamic List into MySQL column efficiently?
I want to store a list of numbers along with some other fields into MySQL. The number of elements in the list is dynamic (some time it could hold about 60 elements)
Currently I'm storing the list into a column of varchar type and the following operations a... | How to store a dynamic List into MySQL column efficiently? | I want to store a list of numbers along with some other fields into MySQL. The number of elements in the list is dynamic (some time it could hold about 60 elements)
Currently I'm storing the list into a column of varchar type and the following operations are done.
e.g. aList = [1234122433,1352435632,2346433334,12341224... | [
"Since you wish to store integers, an effective way would be to store them in an INT/DECIMAL column.\nCreate an additional table that will hold these numbers and add an ID column to relate the records to other table(s).\n\nAlso what should be the efficient way\n for storing list of strings instead of\n numbers?\n... | [
2,
1,
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001917106_mysql_python.txt |
Q:
When using py2app, is there a way to customize the traceback dialog that gets displayed? (Or show a different Cocoa dialog?)
Is there an easy way to get any more control over the py2app traceback dialogs, or just a nice way to display GUI messages?
If I raise an exception in my py2app script, I get a dialog that s... | When using py2app, is there a way to customize the traceback dialog that gets displayed? (Or show a different Cocoa dialog?) | Is there an easy way to get any more control over the py2app traceback dialogs, or just a nice way to display GUI messages?
If I raise an exception in my py2app script, I get a dialog that says something like this:
MyAppName Error
MyAppName Error
An unexpected error has occurred during execution of the main script
MyR... | [
"Instead of using osascript, you can call display dialog via py-appscript which, if you don't already have it in your python site-library, can be installed via easy_install. This example works inside of a py2app-generated app:\n#!/usr/bin/env python\nfrom osax import *\nimport py2app\n\ndef doit():\n sa = OSAX(... | [
2,
0
] | [] | [] | [
"macos",
"py2app",
"python"
] | stackoverflow_0001917769_macos_py2app_python.txt |
Q:
Make a tkinter window appear over all other windows
#!/usr/bin/env python
# Display window with toDisplayText and timeOut of the window.
from Tkinter import *
def showNotification(notificationTimeout, textToDisplay):
## Create main window
root = Tk()
Button(root, text=textToDisplay, activebackground... | Make a tkinter window appear over all other windows | #!/usr/bin/env python
# Display window with toDisplayText and timeOut of the window.
from Tkinter import *
def showNotification(notificationTimeout, textToDisplay):
## Create main window
root = Tk()
Button(root, text=textToDisplay, activebackground="white", bg="white", command=lambda: root.destroy()).pac... | [
"According to this message you should be able to add the following after root.overridedirect(1). A quick test here suggests it should work for you.\nroot.wm_attributes(\"-topmost\", 1)\n\n"
] | [
9
] | [] | [] | [
"focus",
"python",
"stack",
"tkinter",
"windows"
] | stackoverflow_0001918752_focus_python_stack_tkinter_windows.txt |
Q:
Reading a file via open().read() vs storing it in a variable
I've written this small app in Python that will generate paragraphs of dummy text, kind of like this site, except it'll work offline. Right now you're supposed to provide a reasonably long text file (I'm currently using books from Project Gutenberg), whi... | Reading a file via open().read() vs storing it in a variable | I've written this small app in Python that will generate paragraphs of dummy text, kind of like this site, except it'll work offline. Right now you're supposed to provide a reasonably long text file (I'm currently using books from Project Gutenberg), which it will call open() and then read() on to get the initial strin... | [
"There's a few problems:\n\nYour program becomes really hard to read.\nYou run the risk of \"\"\" appearing in the text and blowing everything up\nYou break the whole concept of content existing in the format in which it belongs. The book in question is a text file, it should live in a text file and if Python need... | [
12
] | [] | [] | [
"python"
] | stackoverflow_0001918965_python.txt |
Q:
how to add all of these values in a python dictionary
last one for the night, want to see what clever ways there are with python to add all of the 'count' values from the following type of dictionary:
{0: {'count': 1000}, 1: {'count': 2000}}
so the end result should be an int value of 3000.
A:
>>> x = {0: {'cou... | how to add all of these values in a python dictionary | last one for the night, want to see what clever ways there are with python to add all of the 'count' values from the following type of dictionary:
{0: {'count': 1000}, 1: {'count': 2000}}
so the end result should be an int value of 3000.
| [
">>> x = {0: {'count': 1000}, 1: {'count': 2000}}\n>>> sum(v['count'] for v in x.values()) \n3000\n\n",
"A shorter one:\nsum(d[k]['count'] for k in d)\n\n",
"sum(i['count'] for i in d.values())\n\n",
"How about using reduction in python?\nreduce(lambda x,y: x+y, [v['count'] for v in a.values()])\n\n"
] | [
4,
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001919054_python.txt |
Q:
What is a hashtable/dictionary implementation for Python that doesn't store the keys?
I'm storing millions, possibly billions of 4 byte values in a hashtable and I don't want to store any of the keys. I expect that only the hashes of the keys and the values will have to be stored. This has to be fast and all kept ... | What is a hashtable/dictionary implementation for Python that doesn't store the keys? | I'm storing millions, possibly billions of 4 byte values in a hashtable and I don't want to store any of the keys. I expect that only the hashes of the keys and the values will have to be stored. This has to be fast and all kept in RAM. The entries would still be looked up with the key, unlike set()'s.
What is an imple... | [
"Bloomier filters - space-efficient associative array\nFrom the Wikipedia:\n\nChazelle et al. (2004) designed a\n generalization of Bloom filters that\n could associate a value with each\n element that had been inserted,\n implementing an associative array.\n Like Bloom filters, these structures\n achieve a s... | [
5,
3,
3,
2,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"data_structures",
"dictionary",
"hashtable",
"map",
"python"
] | stackoverflow_0001918456_data_structures_dictionary_hashtable_map_python.txt |
Q:
Nested Methods? Why are they useful?
So I'm just learning some new stuff in C# & Python. Turns out both lanuages support nested methods (C# sort of does).
Python:
def MyMethod():
print 'Hello from a method.'
def MyInnerMethod():
print 'Hello from a nested method.'
MyInnerMethod()
C# (using... | Nested Methods? Why are they useful? | So I'm just learning some new stuff in C# & Python. Turns out both lanuages support nested methods (C# sort of does).
Python:
def MyMethod():
print 'Hello from a method.'
def MyInnerMethod():
print 'Hello from a nested method.'
MyInnerMethod()
C# (using new features in .NET 3.5):*
static void M... | [
"First, realize I cannot give you a complete list. If you were to ask \"why are screwdrivers useful?\", I would would talk about screws and paint can lids but would miss their value in termite inspection. When you ask, \"Why are nested functions useful?\", I can tell you about scoping, closures, and entry points.... | [
17,
7,
5,
5,
3,
1,
1,
0
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0001919372_c#_python.txt |
Q:
Storing times in Python - Best format?
When storing a time in Python (in my case in ZODB, but applies to any DB), what format (epoch, datetime etc) do you use and why?
A:
The datetime module has the standard types for modern Python handling of dates and times, and I use it because I like standards (I also think ... | Storing times in Python - Best format? | When storing a time in Python (in my case in ZODB, but applies to any DB), what format (epoch, datetime etc) do you use and why?
| [
"The datetime module has the standard types for modern Python handling of dates and times, and I use it because I like standards (I also think it's well designed); I typically also have timezone information via pytz.\nMost DBs have their own standard way of storing dates and times, of course, but modern Python adap... | [
5,
5,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0001908670_datetime_python.txt |
Q:
What's a better way to handle this in Python
Simple problem, I have it solved .. but python has a million ways to solve the same problem. I don't want the most terse solution, I just want one that makes more sense than the following:
# sql query happens above, returns multiple rows
rows = cursor.fetchall()
cursor.... | What's a better way to handle this in Python | Simple problem, I have it solved .. but python has a million ways to solve the same problem. I don't want the most terse solution, I just want one that makes more sense than the following:
# sql query happens above, returns multiple rows
rows = cursor.fetchall()
cursor.close()
cntdict = {}
for row in rows:
a, b, c ... | [
"You can do the same thing with a generator expression and the dictionary constructor:\ndict((row[0], {\"b\": row[1], \"c\": row[2]}) for row in rows)\n\nAnd here is the code in action:\n>>> rows = [[1, 2, 3], [4, 5, 6]]\n>>> dict((row[0], {\"b\": row[1], \"c\": row[2]}) for row in rows)\n{1: {'c': 3, 'b': 2}, 4: {... | [
12,
0
] | [
"You might want to look into using an ORM to abstract your database. I can't tell for certain from such a short snippet, but it looks like your data might work well with an ORM if you are just going to build a dict out of it anyway.\nMy three favorite ORMs: the one in Django (easy to use, works best with data that... | [
-2
] | [
"python"
] | stackoverflow_0001918851_python.txt |
Q:
TinyMCE Spellchecker in Pylons
I've been trying to get the TinyMCE spellchecker working with my Pylons app. My first problem is actually capturing the post data in the first place. Firebug tells me that the following is being sent:
{"id":"c0","method":"checkWords","params":["en",["Lorem","ipsum","dolor","sit","ame... | TinyMCE Spellchecker in Pylons | I've been trying to get the TinyMCE spellchecker working with my Pylons app. My first problem is actually capturing the post data in the first place. Firebug tells me that the following is being sent:
{"id":"c0","method":"checkWords","params":["en",["Lorem","ipsum","dolor","sit","amet","consectetur","adipisicing","elit... | [
"That's not really an answer to your question but I hope it will help:\nYou maybe interested to look at django-tinymce as a source of inspiration. The spellchecker is based on PyEnchant\n"
] | [
1
] | [] | [] | [
"pyenchant",
"pylons",
"python",
"spell_checking",
"tinymce"
] | stackoverflow_0001920162_pyenchant_pylons_python_spell_checking_tinymce.txt |
Q:
Fill list with objects and sort (Newbie)
I'm new to Python, so please forgive me when using wrong terms :)
I'd like to have a list of several "objects", each of them having the same numeric attributes (A, B, C). This list should then be sorted by the value of attribute A.
In Java I'd define a Class with my attribu... | Fill list with objects and sort (Newbie) | I'm new to Python, so please forgive me when using wrong terms :)
I'd like to have a list of several "objects", each of them having the same numeric attributes (A, B, C). This list should then be sorted by the value of attribute A.
In Java I'd define a Class with my attributes as members, implement Sortable to compare ... | [
"class myclass(object):\n def __init__(self, a, b, c):\n self.a = a\n self.b = b\n self.c = c\n\n def __repr__(self):\n return \"(a=%s, b=%s, c=%s)\" % (self.a, self.b, self.c)\n\n>>> obj1 = myclass(1, 2, 3)\n>>> obj2 = myclass(1, 2, 4)\n>>> obj3 = myclass(2, 5, 1)\n>>> obj4 = mycl... | [
6,
4,
3,
2,
2
] | [] | [] | [
"list",
"object",
"python",
"sorting"
] | stackoverflow_0001920315_list_object_python_sorting.txt |
Q:
python write CD/DVD iso file
I'm making a cross-platform (Windows and OS X) with wxPython that will be compiled to exe later.
Is it possible for me to create ISO files for CDs or DVDs in Python to burn a data disc with?
Thanks,
Chris
A:
Following 'do not reinvent the wheel' I would try using mkisofs (part of cdr... | python write CD/DVD iso file | I'm making a cross-platform (Windows and OS X) with wxPython that will be compiled to exe later.
Is it possible for me to create ISO files for CDs or DVDs in Python to burn a data disc with?
Thanks,
Chris
| [
"Following 'do not reinvent the wheel' I would try using mkisofs (part of cdrtools) (although originating on Linux, I think there are windows builds floating around the net).\n"
] | [
1
] | [] | [] | [
"file",
"iso",
"python",
"system"
] | stackoverflow_0001920246_file_iso_python_system.txt |
Q:
Is it possible to access an xcf active memory server with python?
I'm playing around with the XCF active memory server. Is there a python library to access the contents of the active memory server?
Related:
How to write data to the ActiveMemory Server used in the XCF system?
A:
According to their documentation, ... | Is it possible to access an xcf active memory server with python? | I'm playing around with the XCF active memory server. Is there a python library to access the contents of the active memory server?
Related:
How to write data to the ActiveMemory Server used in the XCF system?
| [
"According to their documentation, the answer appears to be \"yes\".\n",
"According to one of the developers there is an outdated version of a python API for publish and subscribe over XCF. This API is not capable of contacting an active memory server. \n"
] | [
0,
0
] | [] | [] | [
"active_memory",
"python",
"xcf"
] | stackoverflow_0001907102_active_memory_python_xcf.txt |
Q:
Code bacteria: evolving mathematical behavior
It would not be my intention to put a link on my blog, but I don't have any other method to clarify what I really mean. The article is quite long, and it's in three parts (1,2,3), but if you are curious, it's worth the reading.
A long time ago (5 years, at least) I pro... | Code bacteria: evolving mathematical behavior | It would not be my intention to put a link on my blog, but I don't have any other method to clarify what I really mean. The article is quite long, and it's in three parts (1,2,3), but if you are curious, it's worth the reading.
A long time ago (5 years, at least) I programmed a python program which generated "mathemati... | [
"If you are optimising the code, perhaps you are engaged in genetic programming?\n",
"The free utility Eureqa is similar in the sense that in can create fitting symbolic functions (much more complicated than simple linear regression, etc.) based on multivariate input data. But, it uses GA to come up with the fun... | [
10,
2,
2,
1
] | [] | [] | [
"evolutionary_algorithm",
"genetic_programming",
"python"
] | stackoverflow_0001889810_evolutionary_algorithm_genetic_programming_python.txt |
Q:
What does Python's GIL have to do with the garbage collector?
I just saw this section of Unladen Swallow's documentation come up on Hacker News. Basically, it's the Google engineers saying that they're not optimistic about removing the GIL. However, it seems as though there is discussion about the garbage collec... | What does Python's GIL have to do with the garbage collector? | I just saw this section of Unladen Swallow's documentation come up on Hacker News. Basically, it's the Google engineers saying that they're not optimistic about removing the GIL. However, it seems as though there is discussion about the garbage collector interspersed with this talk about the GIL. Could someone expla... | [
"The really short version is that currently python manages memory with a reference counting+a mark&sweep cycle collector scheme, optimized for latency (instead of throughput). \nThis is all fine when there is only a single mutating thread, but in a multi-threaded system, you need to synchronize all the times you mo... | [
19,
1,
1
] | [] | [] | [
"garbage_collection",
"gil",
"python",
"unladen_swallow"
] | stackoverflow_0001914605_garbage_collection_gil_python_unladen_swallow.txt |
Q:
How do I get names of subdirectories of a directory purely in python?
I dont want to use commands or any similar module that uses unix shell.
Thanks in advance..
A:
Use os.walk():
import os, os.path
def walk_directories(src):
for root, dirs, files in os.walk(src):
for dir in dirs:
print ... | How do I get names of subdirectories of a directory purely in python? | I dont want to use commands or any similar module that uses unix shell.
Thanks in advance..
| [
"Use os.walk():\nimport os, os.path\n\ndef walk_directories(src):\n for root, dirs, files in os.walk(src):\n for dir in dirs:\n print os.path.join(root, dir)\n\nwalk_directories(r'c:\\temp')\n\n",
"If you want to do this recursively, going down a tree visiting all the directories, then you ca... | [
2,
0
] | [] | [] | [
"python",
"subdirectory"
] | stackoverflow_0001921623_python_subdirectory.txt |
Q:
Partial evaluation with pyparsing
I need to be able to take a formula that uses the OpenDocument formula syntax, parse it into syntax that Python can understand, but without evaluating the variables, and then be able to evaluate the formula many times with changing valuables for the variables.
Formulas can be user... | Partial evaluation with pyparsing | I need to be able to take a formula that uses the OpenDocument formula syntax, parse it into syntax that Python can understand, but without evaluating the variables, and then be able to evaluate the formula many times with changing valuables for the variables.
Formulas can be user input, so pyparsing allows me to both ... | [
"1) Yes, it is possible to pickle the results from parsing your expression, and save that to a database. Then you can just fetch and unpickle the expression, rather than reparse the original again. \n2) You can do a quick-and-dirty pass at this just using the compile and eval built-ins, as in the following intera... | [
4
] | [] | [] | [
"evaluation",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0001920588_evaluation_parsing_pyparsing_python.txt |
Q:
XML edit attributes
I want to edit the attributes of an element in an XML file.
The file looks like
<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
<Value>0.0</Value>
<Result>0.0</Result>
</Parameter>
I want to replace the value and Result attribute with some other value from a t... | XML edit attributes | I want to edit the attributes of an element in an XML file.
The file looks like
<Parameter name="Spec 2 Circumference/Length" type="real" mode="both">
<Value>0.0</Value>
<Result>0.0</Result>
</Parameter>
I want to replace the value and Result attribute with some other value from a text file.
Please suggest.... | [
"An example using ElementTree. It will replace the Value elements text with some string; the procedure for the Result element is analogue and omitted here:\n#!/usr/bin/env python\n\nxml = \"\"\"\n<Parameter name=\"Spec 2 Circumference/Length\" type=\"real\" mode=\"both\">\n <Value>0.0</Value> \n <Result>0.0</... | [
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0001921601_python_xml.txt |
Q:
Expressing an SConscript's Own Dependencies
I have an SCons project set up as follows:
Project/
SConstruct # "SConscript('stuff/SConscript', variant_dir = 'build')
stuff/
SConscript # "import configuration"
configuration/
__init__.py
Thing.py
When building, the SCo... | Expressing an SConscript's Own Dependencies | I have an SCons project set up as follows:
Project/
SConstruct # "SConscript('stuff/SConscript', variant_dir = 'build')
stuff/
SConscript # "import configuration"
configuration/
__init__.py
Thing.py
When building, the SConscript is copied to the build directory, but the... | [
"I have two workarounds for you. I call them workarounds because they don't express the dependency in the SConscript. \n\nDo the 'import configuration' from your SConstruct (you'll need to edit sys.path)\nIn stuff/SConscript, add the source directory to sys.path:\n\n \n import sys\n sys.path += ['%s/stuff'... | [
1,
0
] | [] | [] | [
"import",
"module",
"python",
"scons"
] | stackoverflow_0001916251_import_module_python_scons.txt |
Q:
bulkloader.py --dump without authentication
Is there some way or using the bulkloader.py dump and restore functionality without authentication?
I have tried using:
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
without the login-parameter, but login still seems to be required.... | bulkloader.py --dump without authentication | Is there some way or using the bulkloader.py dump and restore functionality without authentication?
I have tried using:
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
without the login-parameter, but login still seems to be required.
I still get
[ERROR ] Exception during authenti... | [
"remote_api, which the bulkloader uses, is written to deliberately require authentication, even if you omit the relevant clause in app.yaml. You can override it if you really want, but it's an incredibly bad idea - it would allow any anonymous user to do practically anything they liked to your app!\n"
] | [
1
] | [] | [] | [
"backup",
"google_app_engine",
"python"
] | stackoverflow_0001920936_backup_google_app_engine_python.txt |
Q:
nested regular expressions in python
In perl I can do this:
$number = qr/ zero | one | two | three | four | five | six | seven | eight | nine /ix;
$foo = qr/ quantity: \s* $number /ix;
My actual regular expression is many lines and does two-digit and ordinal numbers (e.g., "twenty-two", "forty-fourth" and "twelve... | nested regular expressions in python | In perl I can do this:
$number = qr/ zero | one | two | three | four | five | six | seven | eight | nine /ix;
$foo = qr/ quantity: \s* $number /ix;
My actual regular expression is many lines and does two-digit and ordinal numbers (e.g., "twenty-two", "forty-fourth" and "twelve are all complete matches), and I use it i... | [
"In python, you build regular expressions by passing a string to re.compile. \nYou can \"nest\" regular expression by just doing regular string manipulation:\n#!/usr/bin/env python\nimport re\nnumber = 'zero | one | two | three | four | five | six | seven | eight | nine'\nfoo = re.compile(' quantity: \\s* (%s) '%nu... | [
6,
1
] | [] | [] | [
"expression",
"nested",
"python"
] | stackoverflow_0001922261_expression_nested_python.txt |
Q:
The best solution for distribution website?
Ok, I have a question from a "client" perspective. Let's say we are talking about website designed for distribution: products + their logistics info.
Definitely less than a 2k rows, rarely changed but often accessed. Typical row with several columns will have to consist... | The best solution for distribution website? | Ok, I have a question from a "client" perspective. Let's say we are talking about website designed for distribution: products + their logistics info.
Definitely less than a 2k rows, rarely changed but often accessed. Typical row with several columns will have to consist of a picture so it might make it a bit "heavy". ... | [
"\"What i need to know is whether the porposed solution is suitable for such a small project and could not be easily replaced by less complicated languages/frameworks/dmbses like PHP with MySQL etc.\n\"\nYes. It's suitable.\nNo. Nothing is \"less complicated\" than Django. PHP language may appear less complica... | [
2,
0,
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0001921559_django_postgresql_python.txt |
Q:
Parsing a datafile in python (2.5.2)
I have a message definition file that looks like this
struct1
{
field="name" type="string" ignore="false";
field="id" type="int" enums=" 0="val1" 1="val2" ";
}
struct2
{
field = "object" type="struct1";
...
}
How can I parse this into a dictionary with keys 'struct1... | Parsing a datafile in python (2.5.2) | I have a message definition file that looks like this
struct1
{
field="name" type="string" ignore="false";
field="id" type="int" enums=" 0="val1" 1="val2" ";
}
struct2
{
field = "object" type="struct1";
...
}
How can I parse this into a dictionary with keys 'struct1, struct2' and values should be a list of ... | [
"Use can use json as file format, it supports (in python lingo) dictionaries and lists. Since json support is native only for python 2.6 and higher, you'll need this library: http://pypi.python.org/pypi/simplejson/2.0.9\n{ \"struct1\" \n [\n {\"field\" : \"name\", \"type\" : \"string\", \"ignore\" : false... | [
4,
4,
4,
2,
1,
0
] | [] | [] | [
"dictionary",
"parsing",
"python"
] | stackoverflow_0001922426_dictionary_parsing_python.txt |
Q:
Which editor/IDE should I use for Python?
Possible Duplicate:
What IDE to use for Python
I have Notepad++ and NetBeans 6.8, however I don't know if they work. I know you can edit Python with Notepad++ and compile/run it using the command line thing, but I'm not really sure how. I know NetBeans is a full-featured... | Which editor/IDE should I use for Python? |
Possible Duplicate:
What IDE to use for Python
I have Notepad++ and NetBeans 6.8, however I don't know if they work. I know you can edit Python with Notepad++ and compile/run it using the command line thing, but I'm not really sure how. I know NetBeans is a full-featured IDE and you can compile Java programs, but I ... | [
"Actually, netbeans has some python support right now: http://wiki.netbeans.org/Python. It works (still I prefer a plain text editor).\nFor a list of python IDEs i'd call this list comprehensive: What IDE to use for Python?\n",
"Eclipse with PyDev has been a great combination for me. Great editing experience and... | [
4,
4,
3,
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"compilation",
"editor",
"ide",
"python"
] | stackoverflow_0001922356_compilation_editor_ide_python.txt |
Q:
How to create an Incremental loading webpage
I'm writing a page dealing with a large amount of data. It would last forever until my resultant page loaded (nearly infinite) because the data returned is so large. Therefore, I need to implement an incrementally loading page like one at thie url:
http://docs.python.o... | How to create an Incremental loading webpage | I'm writing a page dealing with a large amount of data. It would last forever until my resultant page loaded (nearly infinite) because the data returned is so large. Therefore, I need to implement an incrementally loading page like one at thie url:
http://docs.python.org/
Everytime a search term is entered, it will co... | [
"There are various possible ways to do so, but the basic trick is to have the search program return results to the wire before finishing. This is something usually done by explicitly calling a flush() call or equivalent every so many results.\nNow, to present them you can either\n\nUse AJAX: Return a very small pag... | [
3,
1,
1,
1,
1,
1
] | [] | [] | [
"jquery",
"python"
] | stackoverflow_0001922673_jquery_python.txt |
Q:
Google Wave Python Tutorial - What next?
I just finished working through Google's Wave Robot: Python Tutorial. The API Reference looks a bit imposing. Is there anything else I can look at to get up to speed?
A:
Have a look at the Python sample bots on the sample gallery : http://wave-samples-gallery.appspot.com/... | Google Wave Python Tutorial - What next? | I just finished working through Google's Wave Robot: Python Tutorial. The API Reference looks a bit imposing. Is there anything else I can look at to get up to speed?
| [
"Have a look at the Python sample bots on the sample gallery : http://wave-samples-gallery.appspot.com/results?language=Python&api=Robots. This can give you ideas of bots to make, and show you good practices, too. The gallery outlines the specific features of the API used by each bot.\nAlso, you could join the Wave... | [
3,
1,
1
] | [] | [] | [
"google_app_engine",
"google_wave",
"python"
] | stackoverflow_0001747198_google_app_engine_google_wave_python.txt |
Q:
monolithic inheritance vs modular member based OOP design
I'm having a hard time making a design decision
I have a class in python, that processing form data, this data is very similar to other form data, and so I'm refactoring it into it's own object so it can be reused by the other classes.
The delima is weather... | monolithic inheritance vs modular member based OOP design | I'm having a hard time making a design decision
I have a class in python, that processing form data, this data is very similar to other form data, and so I'm refactoring it into it's own object so it can be reused by the other classes.
The delima is weather to make this formprocessor a member of the classes or a parent... | [
"Definitely go for the modular approach. Some of the advantages of taking the modular approach are:\n\nIt makes your code more readable, i.e. it's more clear what the PageHandler and FormProcessor do\nIt makes it easier and more effective to write unit tests on both of your classes\nIt makes it easier to change the... | [
7
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0001923101_oop_python.txt |
Q:
IronPython Webframework
There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?
A:
Django has been run on IronPython before, but as a proof-of-concept. I know the IronPython team are interested in Django support as a metric for Python-com... | IronPython Webframework | There seem to be many excellent web frameworks for Python. Has anyone used any of these (Pylons, Web2Py, Django) with IronPython?
| [
"Django has been run on IronPython before, but as a proof-of-concept. I know the IronPython team are interested in Django support as a metric for Python-compatibility.\nSomewhat related is the possibility to use IronPython with ASP.NET and ASP.NET MVC, which is probably more mature.\n",
"You may want to read this... | [
6,
6
] | [
"we2py released Feb 5, 2009 \nhttp://www.web2py.com \n\nIncludes a Database Abstraction Layer that works with SQLite, MySQL,\nPostgreSQL, FireBird, MSSQL, Oracle, AND the Google App Engine. \n\n"
] | [
-3
] | [
"ironpython",
"python"
] | stackoverflow_0000437160_ironpython_python.txt |
Q:
How should I build this Django model to do what I want
This is what I had before (but realized that you can't obviously do it in this order:
class MasterAdmin(models.Model):
"""
A permanent admin (one per Account) that shouldn't be deleted.
"""
admin = models.OneToOneField(AccountAdmin)
class Acco... | How should I build this Django model to do what I want | This is what I had before (but realized that you can't obviously do it in this order:
class MasterAdmin(models.Model):
"""
A permanent admin (one per Account) that shouldn't be deleted.
"""
admin = models.OneToOneField(AccountAdmin)
class Account(models.Model):
"""
A top-level account in the sy... | [
"Why not just make is_master a property of AccountAdmin and then override the delete() method to ensure is_master is not true?\n",
"When you have forward references, use the quotes.\nadmin = models.OneToOneField('AccountAdmin')\n\nSee the docs.\n\nIf you need to create a relationship on a model that has not yet b... | [
3,
2
] | [] | [] | [
"django",
"django_models",
"foreign_keys",
"one_to_one",
"python"
] | stackoverflow_0001923551_django_django_models_foreign_keys_one_to_one_python.txt |
Q:
How to make paramiko wait for transfer to finish?
I've tried various ways to upload a file locally to a FTP, ncftpput was really slow compared to lftp so I switched.
but what I've noticed is my python script waits for ncftpput to finish but when using lftp, it just uploads the file to the FTP and it continues on w... | How to make paramiko wait for transfer to finish? | I've tried various ways to upload a file locally to a FTP, ncftpput was really slow compared to lftp so I switched.
but what I've noticed is my python script waits for ncftpput to finish but when using lftp, it just uploads the file to the FTP and it continues on with the script..
I am using paramiko to SSH into my web... | [] | [] | [
"See the lftp docs for proper usage of the ftp:sync-mode setting. (You want true.)\n"
] | [
-1
] | [
"python"
] | stackoverflow_0001923794_python.txt |
Q:
Get class object __dict__ without special attributes
For getting all the defined class attributes I try to go with
TheClass.__dict__
but that also gives me the special attributes. Is there a way to get only the self-defined attributes or do I have to "clean" the dict myself?
A:
Another solution:
class _BaseA(ob... | Get class object __dict__ without special attributes | For getting all the defined class attributes I try to go with
TheClass.__dict__
but that also gives me the special attributes. Is there a way to get only the self-defined attributes or do I have to "clean" the dict myself?
| [
"Another solution:\nclass _BaseA(object):\n _intern = object.__dict__.keys()\n\nclass A(_BaseA):\n myattribute = 1\n\nprint filter(lambda x: x not in A._intern+['__module__'], A.__dict__.keys())\n\nI don't think this is terribly robust and there might still be a better way.\nThis does adress some of the basic... | [
5,
3,
2
] | [] | [] | [
"new_style_class",
"oop",
"python"
] | stackoverflow_0001923130_new_style_class_oop_python.txt |
Q:
True and 'True' in python condition
If:
x = 0
b = x==0
and I print b it would print 'true'
but if I did:
x = 0
b = x ==3
and I printed b it would be false.
Instead of it printing false how would I take the boolean value b to print what text I wanted?
Let me explain further:
bool = all(n > 0 for n in list)
if... | True and 'True' in python condition | If:
x = 0
b = x==0
and I print b it would print 'true'
but if I did:
x = 0
b = x ==3
and I printed b it would be false.
Instead of it printing false how would I take the boolean value b to print what text I wanted?
Let me explain further:
bool = all(n > 0 for n in list)
if bool != 'True':
print 'a value is no... | [
"Something like this you mean?\nx = 0\nif x != 3:\n print \"x does not equal 3\"\n\n",
"I think perhaps the following will help alleviate some of your confusion:\n>>> 0==0\nTrue\n>>> 'True'\n'True'\n>>> (0==0) == 'True'\nFalse\n>>> (0==0) == True\nTrue\n\n",
"An if statement as other answers suggest is a pos... | [
6,
6,
4,
3,
2,
2,
0,
0
] | [] | [] | [
"boolean",
"python",
"syntax"
] | stackoverflow_0001922849_boolean_python_syntax.txt |
Q:
Python lambdas and scoping
Given this snippet of code:
funcs = []
for x in range(3):
funcs.append(lambda: x)
print [f() for f in funcs]
I would expect it to print [0, 1, 2], but instead it prints [2, 2, 2]. Is there something fundamental I'm missing about how lambdas work with scope?
A:
This is a frequent q... | Python lambdas and scoping | Given this snippet of code:
funcs = []
for x in range(3):
funcs.append(lambda: x)
print [f() for f in funcs]
I would expect it to print [0, 1, 2], but instead it prints [2, 2, 2]. Is there something fundamental I'm missing about how lambdas work with scope?
| [
"This is a frequent question in Python. Basically the scoping is such that when f() is called, it will use the current value of x, not the value of x at the time the lambda is formed. There is a standard workaround:\nfuncs = []\nfor x in range(10):\nfuncs.append(lambda x=x: x)\nprint [f() for f in funcs]\n\nThe us... | [
9,
5,
4
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0001924214_lambda_python.txt |
Q:
suggestion required related to rewriting and string manipulation
I had to read from a file and for each data between delimiter i need to remove the white space and i have written the following program in jython
When i am trying to rewrite ,its rewriting at the end of source file.
filesrc = open('c:/FILE/split_do... | suggestion required related to rewriting and string manipulation | I had to read from a file and for each data between delimiter i need to remove the white space and i have written the following program in jython
When i am trying to rewrite ,its rewriting at the end of source file.
filesrc = open('c:/FILE/split_doc.txt','r+')
for list in filesrc.readlines():
#split the records b... | [
"You don't want to write to the same file while you're reading it. It's technically possible, but that path is fraught with trouble and misery.\nHere's the plain and simple process you should follow:\n\nread the whole file into a string then close the file\nsplit the string on newlines into a list\nprocess each lin... | [
1,
0,
0
] | [] | [] | [
"file",
"jython",
"python",
"rewrite"
] | stackoverflow_0001924043_file_jython_python_rewrite.txt |
Q:
Multiprocessing launching too many instances of Python VM
I am writing some multiprocessing code (Python 2.6.4, WinXP) that spawns processes to run background tasks. In playing around with some trivial examples, I am running into an issue where my code just continuously spawns new processes, even though I only te... | Multiprocessing launching too many instances of Python VM | I am writing some multiprocessing code (Python 2.6.4, WinXP) that spawns processes to run background tasks. In playing around with some trivial examples, I am running into an issue where my code just continuously spawns new processes, even though I only tell it to spawn a fixed number.
The program itself runs fine, bu... | [
"It looks like you didn't carefully follow the guidelines in the documentation, specifically this section where it talks about \"Safe importing of main module\".\nYou need to protect your launch code with an if __name__ == '__main__': block or you'll get what you're getting, I believe.\nI believe it comes down to t... | [
23,
0,
0
] | [] | [] | [
"multiprocessing",
"python",
"windows"
] | stackoverflow_0001923706_multiprocessing_python_windows.txt |
Q:
Couple of matplotlib newbie doubts
I am just starting to use 'matplotlib' and I have hit upon 2 major roadblocks, which I can't seem to work around from the docs/examples,etc: Here is Python source:
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for i in range(0,301):
... | Couple of matplotlib newbie doubts | I am just starting to use 'matplotlib' and I have hit upon 2 major roadblocks, which I can't seem to work around from the docs/examples,etc: Here is Python source:
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for i in range(0,301):
print "Plotting",i
# Reading a s... | [
"\nAs Tim Pietzcker points out, you can shorten if filename code at the end by\nusing string number formatting.\nfilename='plot%03d.png'%i\n\nreplaces %03d with the integer i padded with up to 3 zero's.\nIn Python2.6+, one can do the same thing with the less pretty but more powerful new string formatting syntax:\nf... | [
2
] | [] | [] | [
"matplotlib",
"python",
"scientific_computing"
] | stackoverflow_0001924323_matplotlib_python_scientific_computing.txt |
Q:
Inheritable custom exceptions in python
I want to create some custom exceptions for my class. I am trying to figure out the best way to make these exception classes inheritable in derived classes. The tutorial shows how to create the Exception classes. So I did that like this:
I created a baseclass.py:
class Er... | Inheritable custom exceptions in python | I want to create some custom exceptions for my class. I am trying to figure out the best way to make these exception classes inheritable in derived classes. The tutorial shows how to create the Exception classes. So I did that like this:
I created a baseclass.py:
class Error(Exception):
"""Base class for excepti... | [
"The custom exceptions has to be imported in all modules its used in.\nAlso, there is an error in derivedclass.py\nWrong (because of the way its imported)\nraise baseclass.OtherError, \"Error doing other\"\n\nFixed\nraise OtherError, \"Error doing other\"\n\n",
"\nSo as you can see, I imported the\n exception cl... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001924380_python.txt |
Q:
Linux group scheduling for user not being applied to setuid-ed process
On the 2.6.28-11 Linux kernel, I am using setpriority to bias the amount of cpu time different user processes receive. User 1 is to receive double the CPU power of user 2. Using Linux's setpriority, I have assigned user 2 a lower priority (high... | Linux group scheduling for user not being applied to setuid-ed process | On the 2.6.28-11 Linux kernel, I am using setpriority to bias the amount of cpu time different user processes receive. User 1 is to receive double the CPU power of user 2. Using Linux's setpriority, I have assigned user 2 a lower priority (higher in terms of nice values). When I run the exact same program via the shell... | [
"Right, this is the designed behavior, even if it's not what you want. You can update your own priority to match what you should have inherited, if you were started normally:\n/* C */\n#include <sys/resource.h>\nint proc_prio = getpriority(PRIO_PROCESS, getpid()),\n pgrp_prio = getpriority(PRIO_PGRP, getpgrp())... | [
2
] | [] | [] | [
"linux",
"python",
"scheduler",
"scheduling",
"setuid"
] | stackoverflow_0001920952_linux_python_scheduler_scheduling_setuid.txt |
Q:
get datatype length in python by parsing a string
I have strings like
uint8_t
char[5]
int[3]
How can I write a short function to get the type and length separately in an elegant way
for eg
uint8_t // return 'uint8_t', '1'
char[5] // return 'char', '5'
...
A:
Let's make it a one-liner:
import re
def type_and_si... | get datatype length in python by parsing a string | I have strings like
uint8_t
char[5]
int[3]
How can I write a short function to get the type and length separately in an elegant way
for eg
uint8_t // return 'uint8_t', '1'
char[5] // return 'char', '5'
...
| [
"Let's make it a one-liner:\nimport re\n\ndef type_and_size(s):\n return re.split('[][]', s+'[1]', 2)[:2]\n\ntype_and_size('char')\n['char', '1']\n\ntype_and_size('char[5]')\n['char', '5']\n\nObviously you can do:\ntype, size = type_and_size('char[5]')\n\n",
"In [1]: import re\nIn [2]: r = re.compile('([\\w_]+... | [
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001924828_python.txt |
Q:
Linux USB Mapping Question
I'm working on a utility that will auto mount an inserted USB stick on linux. I have tied into D-Bus to receive notification of when a device is inserted, and that works great. However, I need to determine which device in /dev is mapped to the inserted USB stick. I am getting the D-Bus n... | Linux USB Mapping Question | I'm working on a utility that will auto mount an inserted USB stick on linux. I have tied into D-Bus to receive notification of when a device is inserted, and that works great. However, I need to determine which device in /dev is mapped to the inserted USB stick. I am getting the D-Bus notification and then scanning th... | [
"You should probably ask HAL about that. You say you already get notifications from HAL by D-Bus... It maintains list of USB devices, together with their IDs and device names (block.device property).\nHere's a nice example of how to get device file name together with the notification of new USB device: How can I li... | [
2,
0,
0
] | [] | [] | [
"dbus",
"linux",
"python",
"usb"
] | stackoverflow_0001924646_dbus_linux_python_usb.txt |
Q:
XML/SWF charts example not working with cherryPy
I am trying to use use the XML/SWF Charts library with cherrypy. I want to generate html reports with nice looking charts.
I am trying to expose one of the default examples of XML/SWF charts with cherryPy, but for some reason the javascript is not working properly ... | XML/SWF charts example not working with cherryPy | I am trying to use use the XML/SWF Charts library with cherrypy. I want to generate html reports with nice looking charts.
I am trying to expose one of the default examples of XML/SWF charts with cherryPy, but for some reason the javascript is not working properly with cherryPy.
I created the following python script:
... | [
"conf = {'/js/AC_RunActiveContent.js':\n {'tools.staticfile.on': True,\n 'tools.staticfile.filename':\n os.path.join(current_dir, 'data', 'scripts', 'AC_RunActiveContent.js')}}\n\nAnd later\n<script src=\"AC_RunActiveContent.js\" language=\"javascript\"></script>\n\nMy bet is the latter produces a 40... | [
1
] | [] | [] | [
"cherrypy",
"javascript",
"python",
"xml_swf_charts"
] | stackoverflow_0001924973_cherrypy_javascript_python_xml_swf_charts.txt |
Q:
Use with form.fields.queryset?
Is it possible to set a form's ForeignKey field's queryset so that it will take separate queryset's and output them in <optgroup>'s?
Here is what I have:
views.py
form = TemplateFormBasic(initial={'template': digest.template.id})
form.fields['template'].queryset = Template.objects.f... | Use with form.fields.queryset? | Is it possible to set a form's ForeignKey field's queryset so that it will take separate queryset's and output them in <optgroup>'s?
Here is what I have:
views.py
form = TemplateFormBasic(initial={'template': digest.template.id})
form.fields['template'].queryset = Template.objects.filter(Q(default=1) | Q(user=request.u... | [
"I was able to figure it out using the example given on this blog\nviews.py\nform.fields['template'].choices = templates_as_choices(request)\n\ndef templates_as_choices(request):\n templates = []\n default = []\n user = []\n for template in Template.objects.filter(default=1).order_by('name'):\n d... | [
10,
4
] | [] | [] | [
"django",
"django_forms",
"django_queryset",
"python"
] | stackoverflow_0001924704_django_django_forms_django_queryset_python.txt |
Q:
python, convert a dictionary to a sorted list by value instead of key
I have a collections.defaultdict(int) that I'm building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turning it into a list first) in a descending fashion, ordered with the hig... | python, convert a dictionary to a sorted list by value instead of key | I have a collections.defaultdict(int) that I'm building to keep count of how many times a key shows up in a set of data. I later want to be able to sort it (obviously by turning it into a list first) in a descending fashion, ordered with the highest values first. I created my dictionary like the following:
adict = defa... | [
"A dict's keys, reverse-sorted by the corresponding values, can best be gotten as\nsorted(adict, key=adict.get, reverse=True)\n\nsince you want key/value pairs, you could work on the items as all other answers suggest, or (to use the nifty adict.get bound method instead of itemgetters or weird lambdas;-),\n[(k, adi... | [
47,
43,
6,
3,
2,
2,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0001915564_python_sorting.txt |
Q:
Python, Ruby, Haskell - Do they provide true multithreading?
We are planning to write a highly concurrent application in any of the Very-High Level programming languages.
1) Do Python, Ruby, or Haskell support true multithreading?
2) If a program contains threads, will a Virtual Machine automatically assign work ... | Python, Ruby, Haskell - Do they provide true multithreading? | We are planning to write a highly concurrent application in any of the Very-High Level programming languages.
1) Do Python, Ruby, or Haskell support true multithreading?
2) If a program contains threads, will a Virtual Machine automatically assign work to multiple cores (or to physical CPUs if there is more than 1 CPU... | [
"\n1) Do Python, Ruby, or Haskell support true multithreading?\n\nThis has nothing to do with the language. It is a question of the hardware (if the machine only has 1 CPU, it is simply physically impossible to execute two instructions at the same time), the Operating System (again, if the OS doesn't support true m... | [
34,
22,
16,
7,
1,
1,
1
] | [
"Haskell is suitable for anything.\npython has processing module, which (I think - not sure) helps to avoid GIL problems. (so it suitable for anything too). \nBut my opinion - best way you can do is to select highest level possible language with static type system for big and huge things. Today this languages are: ... | [
-2
] | [
"concurrency",
"haskell",
"multithreading",
"python",
"ruby"
] | stackoverflow_0001920805_concurrency_haskell_multithreading_python_ruby.txt |
Q:
declaring empty class member in python
i am trying to read a tree structure file in python.
I created a class to hold the tree objects. One of the members
should hold the parent object.
Since the parentObject member is of the same type as the class itself,
I need to declare this as an empty variable of type "sel... | declaring empty class member in python | i am trying to read a tree structure file in python.
I created a class to hold the tree objects. One of the members
should hold the parent object.
Since the parentObject member is of the same type as the class itself,
I need to declare this as an empty variable of type "self".
How do I do that in python?
Thank you v... | [
"\nSince the parentObject member is of\n the same type as the class itself, I\n need to declare this as an empty\n variable of type \"self\".\n\nNo, you do not need to declare anything in Python. You just define things.\nAnd self is not a type, but the conventional name for the first parameter of instance method... | [
9,
7,
6
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0001925246_python_variables.txt |
Q:
Searching a file in 3 different ways
I have been writing a program that searches a file in 3 different ways. But firstly, to choose which search program to use is differentiated in the command line.
For example in the command line I type:
Program 1 search: python file.py
'search_term' 'file-to-be-searched'
prog... | Searching a file in 3 different ways | I have been writing a program that searches a file in 3 different ways. But firstly, to choose which search program to use is differentiated in the command line.
For example in the command line I type:
Program 1 search: python file.py
'search_term' 'file-to-be-searched'
program 2 search: python file.py -z
'number'... | [
"First of all you should look at two very useful Python modules:\n\nfileinput: Iterate over lines\nfrom multiple input streams\noptparse: A powerful command\nline option parser\n\nfileinput will help you read lines from several files and even modify them if you need. You'll program will be much easier to extend and... | [
3,
1
] | [] | [] | [
"file",
"python",
"search"
] | stackoverflow_0001925284_file_python_search.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.