content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to get list index and element simultaneously in Python? I find myself frequently writing code like this: k = 0 for i in mylist: # y[k] = some function of i k += 1 Instead, I could do for k in range(K): # y[k] = some function of mylist[k] but that doesn't seem "pythonic". (You know... indexing. Ic...
How to get list index and element simultaneously in Python?
I find myself frequently writing code like this: k = 0 for i in mylist: # y[k] = some function of i k += 1 Instead, I could do for k in range(K): # y[k] = some function of mylist[k] but that doesn't seem "pythonic". (You know... indexing. Ick!) Is there some syntax that allows me to extract both the index...
[ "You can use enumerate:\nfor k,i in enumerate(mylist):\n #do something with index k\n #do something with element i\n\nMore information about looping techniques.\nEdit:\nAs pointed out in the comments, using other variable names like\nfor i, item in enumerate(mylist):\n\nmakes it easier to read and understand ...
[ 62, 19 ]
[]
[]
[ "python" ]
stackoverflow_0002072407_python.txt
Q: "Real" and non-embedded use of Ruby, Python and their friends So I'm aware of the big ammount of general-purpose scripting languages like Ruby, Python, Perl, maybe even PHP, etc. that actually claim being usable for creating desktop applications too. I think my question can be answered clearly Are there actually ...
"Real" and non-embedded use of Ruby, Python and their friends
So I'm aware of the big ammount of general-purpose scripting languages like Ruby, Python, Perl, maybe even PHP, etc. that actually claim being usable for creating desktop applications too. I think my question can be answered clearly Are there actually companies using a special scripting language only to create their a...
[ "The company I work for uses Perl and Tk with PerlApp to build executable packages to produce or major software application.\nPerl beats C and C++ for simplicity of code. You can do things in one line of Perl that take 20 lines of C.\nWe've used WxPerl for a few smaller projects. We'd like to move fully to WxPerl...
[ 6, 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "perl", "python", "ruby", "scripting" ]
stackoverflow_0002067907_perl_python_ruby_scripting.txt
Q: Python thread for pre-importing modules I am writing a Python application in the field of scientific computing. Currently, when the user works with the GUI and starts a new physics simulation, the interpreter immediately imports several necessary modules for this simulation, such as Traits and Mayavi. These module...
Python thread for pre-importing modules
I am writing a Python application in the field of scientific computing. Currently, when the user works with the GUI and starts a new physics simulation, the interpreter immediately imports several necessary modules for this simulation, such as Traits and Mayavi. These modules are heavy and take too long to import, and ...
[ "The problem with this is that the imports must still complete before they are usable. Depending on when they're first used, the application could still have to block for 10 seconds before it could start up anyway. Much more productive would be to profile the modules and figure out why they take so long to import.\...
[ 2, 2, 1 ]
[ "\"the user works with the GUI and starts a new physics simulation\"\nNot really clear. Does \"works with the GUI\" means double click? Double click what? Some wxWidgets GUI application? Or IDLE? \nIf so, what does \"starts a new physics simulation\" mean? Click a button somewhere else? A GUI button to bring ...
[ -1 ]
[ "import", "multithreading", "python" ]
stackoverflow_0002071786_import_multithreading_python.txt
Q: '%s' % 'somestring' Here are a couple of examples taken from django-basic-apps: # self.title is a unicode string already def __unicode__(self): return u'%s' % self.title # 'q' is a string search_term = '%s' % request.GET['q'] What's the point of this string formatting? A: It's just a habit of mine. In ...
'%s' % 'somestring'
Here are a couple of examples taken from django-basic-apps: # self.title is a unicode string already def __unicode__(self): return u'%s' % self.title # 'q' is a string search_term = '%s' % request.GET['q'] What's the point of this string formatting?
[ "It's just a habit of mine. In these cases it's not necessary.\n", "At first glance, it doesn't look sensible, but it does have the benefit of forcing the result to be a string (or unicode string), rather than whatever it might have been from before. Another way to do the same thing might be to call str on the fo...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002069362_django_python.txt
Q: Django Views Join Models Using Foreign Key I have the following models defined: class Player(models.Model): Team = models.ForeignKey(Team) Name = models.CharField(max_length=200) Position = models.CharField(max_length=3) ... snip ... What I would like to output in a view is a list of players who a...
Django Views Join Models Using Foreign Key
I have the following models defined: class Player(models.Model): Team = models.ForeignKey(Team) Name = models.CharField(max_length=200) Position = models.CharField(max_length=3) ... snip ... What I would like to output in a view is a list of players who are in the team with id = 1. I have tried things ...
[ "You need a view that looks something like this:\ndef players(request):\n players_in_team_one = Player.objects.filter(Team__pk = 1)\n return render_to_response('players.html', {'players': players_in_team_one})\n\nand you can loop through it like this in players.html:\n{% for player in players %}\n <tr><...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002072966_django_python.txt
Q: Need help with python list manipulation i have two seperate lists list1 = ["Infantry","Tanks","Jets"] list2 = [ 10, 20, 30] so in reality, I have 10 Infantry, 20 Tanks and 30 Jets I want to create a class so that in the end, I can call this: for unit in units: print unit.amount print unit.name #and it will p...
Need help with python list manipulation
i have two seperate lists list1 = ["Infantry","Tanks","Jets"] list2 = [ 10, 20, 30] so in reality, I have 10 Infantry, 20 Tanks and 30 Jets I want to create a class so that in the end, I can call this: for unit in units: print unit.amount print unit.name #and it will produce: # 10 Infantry # 20 Tanks # 3...
[ "class Unit(object):\n def __init__(self, amount, name):\n self.amount = amount\n self.name = name\n\nunits = [Unit(a, n) for (a, n) in zip(list2, list1)]\n\n", "from collections import namedtuple\n\nUnit = namedtuple(\"Unit\", \"name, amount\")\nunits = [Unit(*v) for v in zip(list1, list2)]\n\nfor unit in...
[ 18, 8, 5, 5, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002072936_list_python.txt
Q: Python class methods I have a class as follows: class X: def __init__(self): self.sum_x =0.0 self.sum_x_squared=0.0 self.var_x =0.0 self.sum_y =0.0 self.sum_y_squared=0.0 self.var_y =0.0 def update(self,data): [x,y,vx,vy]=data s...
Python class methods
I have a class as follows: class X: def __init__(self): self.sum_x =0.0 self.sum_x_squared=0.0 self.var_x =0.0 self.sum_y =0.0 self.sum_y_squared=0.0 self.var_y =0.0 def update(self,data): [x,y,vx,vy]=data self.update_sums(self.sum_x...
[ "First, note that your question has nothing to do with classmethod (which makes class methods in Python) -- it's entirely about normal instance methods (you should edit your title... or your question, if you do mean it to be about class methods).\nFor the Q as it stands, the only way to do what you want is to pass ...
[ 5, 2, 1, 1, 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002072875_oop_python.txt
Q: Django error opening SQLite3 db file on when running off Apache I got this error: OperationalError at / unable to open database file Things I've tried so far are setting the absolute path of my dev.db file in the settings.py. I've tried adding www-data to my admin group and setting the group of my project folder t...
Django error opening SQLite3 db file on when running off Apache
I got this error: OperationalError at / unable to open database file Things I've tried so far are setting the absolute path of my dev.db file in the settings.py. I've tried adding www-data to my admin group and setting the group of my project folder to the admin, and setting the group to www-data, none of which solved ...
[ "Just passed the last 30 minutes banging my head on this problem ..\nSolution\nIn your settings.py:\nDATABASE_NAME = '/absolute/path/to/your/database.db'\n\nSetting rights:\nchown www-data /absolute/path/to/your/\nchown www-data /absolute/path/to/your/database.db\n\n" ]
[ 8 ]
[]
[]
[ "django", "python", "sqlite", "ubuntu" ]
stackoverflow_0001733050_django_python_sqlite_ubuntu.txt
Q: Access to widget in GTK+ Building a GTK+ widget dynamically from code allows for easy access to the child widgets directly. Now, how do I access to the child widgets when building a GTK+ Dialog (as example) from a .glade file? class ConfigDialog(object): def __init__(self, glade_file, testing=False): s...
Access to widget in GTK+
Building a GTK+ widget dynamically from code allows for easy access to the child widgets directly. Now, how do I access to the child widgets when building a GTK+ Dialog (as example) from a .glade file? class ConfigDialog(object): def __init__(self, glade_file, testing=False): self.testing=testing bu...
[ "Already you are making the call\nself.dialog = builder.get_object(\"config_dialog\")\n\nYou should also be able to do\nself.nameEntry = builder.get_object(\"name_entry\")\n\nThis is at least how python-glade works and I assume GtkBuilder is the same.\n", "In addition, if you want to search for a named widget and...
[ 7, 4 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0002072976_gtk_python.txt
Q: How to draw complement of a network graph? Any function in that Graphviz which can do that? If not, any other free software that can do that? A: Given that you want to render your graphs in graphviz, i suggest using the python library, networkx, to calculate graph complement. Networkx is an excellent library for...
How to draw complement of a network graph?
Any function in that Graphviz which can do that? If not, any other free software that can do that?
[ "Given that you want to render your graphs in graphviz, i suggest using the python library, networkx, to calculate graph complement. Networkx is an excellent library for graph theoretic analysis; it also has a seamless interface with graphviz.\n(Rough definition of a graph complement: imagine a graph A', which has ...
[ 5, 0 ]
[]
[]
[ "complement", "graph", "graphviz", "plot", "python" ]
stackoverflow_0002066259_complement_graph_graphviz_plot_python.txt
Q: Use function from Python script in OS path I have a third-party Python script (foo.py) in a folder that is in my system path (but not the Python sys.path). foo.py is not part of any Python module. I am writing another script (bar.py) in which I'd like to call a function located in foo.py. Is this possible? Can it ...
Use function from Python script in OS path
I have a third-party Python script (foo.py) in a folder that is in my system path (but not the Python sys.path). foo.py is not part of any Python module. I am writing another script (bar.py) in which I'd like to call a function located in foo.py. Is this possible? Can it be done without explicitly naming the folder of ...
[ "You can include the path of foo.py in the PYTHONPATH environment variable. The interpreter will look also the directories contained there, so you can make the import just like it was on the same directory.\n", "If Python does not find the module, I don't think there's another way then to specify where it can be ...
[ 2, 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002074071_import_python.txt
Q: Finding python.exe programmatically in python Possible Duplicate: Getting python.exe path at run time I have a python app that launches other apps with explicit calls to C:\python25\python.exe, but this doesn't work if the user has 2.6 installed or if they have it installed to another location. There is a %PYTHO...
Finding python.exe programmatically in python
Possible Duplicate: Getting python.exe path at run time I have a python app that launches other apps with explicit calls to C:\python25\python.exe, but this doesn't work if the user has 2.6 installed or if they have it installed to another location. There is a %PYTHON% variable for the exe, but this is only availabl...
[ "import sys\nprint sys.executable\n\n", ">>> import sys\n>>> sys.executable\n'C:\\\\Program Files\\\\Python31\\\\pythonw.exe'\n\n", "Consider using execfile. This executes the script you want using the same python instance that's already running.\n" ]
[ 9, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002074212_python.txt
Q: max size in BlobProperty (appengine) What is the maximum size of one BlobProperty in appengine? I'm not talking about of the Blobstore API, i'm referring to the property class BlobProperty Please add a link who support your answers A: The limit is 1 megabyte. Docs here. Like db.Text, a db.Blob value can be ...
max size in BlobProperty (appengine)
What is the maximum size of one BlobProperty in appengine? I'm not talking about of the Blobstore API, i'm referring to the property class BlobProperty Please add a link who support your answers
[ "The limit is 1 megabyte. Docs here.\n\nLike db.Text, a db.Blob value can be\n as large as 1 megabyte, but is not\n indexed, and cannot be used in query\n filters or sort orders. The db.Blob\n class takes a str value as an argument\n to its constructor. Blobs are modeled\n using the BlobProperty class.\n\n" ]
[ 11 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002074154_google_app_engine_python.txt
Q: mysql-python static linking on Linux 64-bit Has anyone tried to statically link mysql-python with mysql client library on 64-bit Linux? gcc -pthread -shared build/temp.linux-x86_64-2.6/_mysql.o /home/apy/MySQL- python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a -L/home/apy/MyS QL-python-1.2.3c1/mysql-5.1....
mysql-python static linking on Linux 64-bit
Has anyone tried to statically link mysql-python with mysql client library on 64-bit Linux? gcc -pthread -shared build/temp.linux-x86_64-2.6/_mysql.o /home/apy/MySQL- python-1.2.3c1/mysql-5.1.42/i/lib/mysql/libmysqlclient_r.a -L/home/apy/MyS QL-python-1.2.3c1/mysql-5.1.42/i/lib/mysql -lmysqlclient_r -lz -lpthread -lcr...
[ "\nSet CFLAGS=\"-fPIC\" environment variable. (reason)\nPass --disable-shared to ./configure (besides --enable-static, that is) when building mysql.\n\n" ]
[ 1 ]
[]
[]
[ "64_bit", "linux", "mysql", "python", "static_libraries" ]
stackoverflow_0002052791_64_bit_linux_mysql_python_static_libraries.txt
Q: Scrapy SgmlLinkExtractor is ignoring allowed links Please take a look at this spider example in Scrapy documentation. The explanation is: This spider would start crawling example.com’s home page, collecting category links, and item links, parsing the latter with the parse_item method. For each item response, some...
Scrapy SgmlLinkExtractor is ignoring allowed links
Please take a look at this spider example in Scrapy documentation. The explanation is: This spider would start crawling example.com’s home page, collecting category links, and item links, parsing the latter with the parse_item method. For each item response, some data will be extracted from the HTML using XPath, and a...
[ "The parse function is actually implemented and used in the CrawlSpider class, and you're unintentionally overriding it. If you change the name to something else, like parse_item, then the Rule should work.\n" ]
[ 11 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0001811132_python_scrapy_web_crawler.txt
Q: Uploading files to App Engine using webapp and Django forms My basic question is this: Is there an equivalent of form = MyForm(request.POST, request.FILES) when handling file uploads using the webapp framework on Google App Engine? I know that I can pull out specific uploaded file data using self.request.get('f...
Uploading files to App Engine using webapp and Django forms
My basic question is this: Is there an equivalent of form = MyForm(request.POST, request.FILES) when handling file uploads using the webapp framework on Google App Engine? I know that I can pull out specific uploaded file data using self.request.get('field_name') or a FieldStorage object using self.request.params['f...
[ "Here's the solution I came up with. I added the following method to my custom webapp.RequestHandler subclass:\n# Required imports\nimport cgi\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\ndef get_uploaded_files(self):\n \"\"\"Gets a dictionary mapping field names to SimpleUploadedFile object...
[ 3, 0, 0 ]
[]
[]
[ "django", "file_upload", "forms", "google_app_engine", "python" ]
stackoverflow_0002052673_django_file_upload_forms_google_app_engine_python.txt
Q: Django ManyToManyField Creation Problems I currently have these models: class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') description = models.TextField(blank=True,null=True) class Item(models.Model): ...
Django ManyToManyField Creation Problems
I currently have these models: class Category(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='child') description = models.TextField(blank=True,null=True) class Item(models.Model): name = models.CharField(max_length=500) ...
[ "Have a look at some examples here.\nBasically, you should do:\nclass Item(models.Model):\n name = models.CharField(max_length=500)\n ...\n tags = models.ManyToManyField(Category, blank=True)\n\nTo create an item, a tag and associate them, do the following:\nitem = Item(name='test')\nitem.save()\ntag = Cat...
[ 4 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0002074900_django_django_models_many_to_many_python.txt
Q: Random weighted choice I have data like this: d = ( (701, 1, 0.2), (701, 2, 0.3), (701, 3, 0.5), (702, 1, 0.2), (702, 2, 0.3), (703, 3, 0.5) ) Where (701, 1, 0.2) = (id1, id2, priority) Is there a pretty way to choose id2 if I know id1, using priority? Func(701) should return:   1 - in 20% cases   2 ...
Random weighted choice
I have data like this: d = ( (701, 1, 0.2), (701, 2, 0.3), (701, 3, 0.5), (702, 1, 0.2), (702, 2, 0.3), (703, 3, 0.5) ) Where (701, 1, 0.2) = (id1, id2, priority) Is there a pretty way to choose id2 if I know id1, using priority? Func(701) should return:   1 - in 20% cases   2 - 30%   3 - 50% Percent will...
[ "Generate a Cumulative Distribution Function for each ID1 thus:\ncdfs = defaultdict()\nfor id1,id2,val in d:\n prevtotal = cdfs[id1][-1][0]\n newtotal = prevtotal + val\n cdfs[id1].append( (newtotal,id2) )\n\nSo you will have\ncdfs = { 701 : [ (0.2,1), (0.5,2), (1.0,3) ], \n 702 : [ (0.2,1), (0.5,2...
[ 7, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002073235_python.txt
Q: Using an index to recursively get all files in a directory really fast Attempt #2: People don't seem to be understanding what I'm trying to do. Let me see if I can state it more clearly: 1) Reading a list of files is much faster than walking a directory. 2) So let's have a function that walks a directory and wr...
Using an index to recursively get all files in a directory really fast
Attempt #2: People don't seem to be understanding what I'm trying to do. Let me see if I can state it more clearly: 1) Reading a list of files is much faster than walking a directory. 2) So let's have a function that walks a directory and writes the resulting list to a file. Now, in the future, if we want to get al...
[ "Do not try to duplicate the work that the filesystem already does. You are not going to do better than it already does.\nYour scheme is flawed in many ways and it will not get you an order-of-magnitude improvement.\nFlaws and potential problems:\nYou are always going to be working with a snapshot of the file syste...
[ 7, 3, 2, 1, 0, 0 ]
[]
[]
[ "all_files", "directory", "indexing", "performance", "python" ]
stackoverflow_0002059912_all_files_directory_indexing_performance_python.txt
Q: django logging local javascript events Say there exists a template x.html in Django templates section. The contents of this page are <html> <a href="#" onclick="noserverrequest"> <input type="button onclick="noserverrequest"/> ... </html> I have n number of buttons and hyperlinks as said above in a page. My que...
django logging local javascript events
Say there exists a template x.html in Django templates section. The contents of this page are <html> <a href="#" onclick="noserverrequest"> <input type="button onclick="noserverrequest"/> ... </html> I have n number of buttons and hyperlinks as said above in a page. My question is how to record all the clicks that a...
[ "you should better trigger an image load in javascript : \nfunction log(info) {\n document.getElementById('pixel').src = '/tracker?'+info;\n}\n\nsomewhere on your page :\n<img id='pixel' src='pixel.gif' style='display:none'/>\n\nthen call it this way in javascript : \nlog('clicked_Button_BuyStuff');\n\nserver side...
[ 0 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0002073962_django_javascript_jquery_python.txt
Q: wxpython GetStatusText() Hey, I have a wxpython frame object with a status bar. I can do self.SetStatusText() without any trouble, but when I do self.GetStatusText() I get this error: Traceback (most recent call last): File "D:\python\code\test.pyw", line 87, in <module> frame = mainframe() File "D:\p...
wxpython GetStatusText()
Hey, I have a wxpython frame object with a status bar. I can do self.SetStatusText() without any trouble, but when I do self.GetStatusText() I get this error: Traceback (most recent call last): File "D:\python\code\test.pyw", line 87, in <module> frame = mainframe() File "D:\python\code\test.pyw", line 40...
[ "Because there is no such function. See the documentation. Try self.GetStatusBar().GetStatusText(), as defined here.\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002075378_python_wxpython.txt
Q: Python fails Tor check using urllib2 to initiate requests After reading through the other questions on StackOverflow, I got a snippet of Python code that is able to make requests through a Tor proxy: import urllib2 proxy = urllib2.ProxyHandler({'http':'127.0.0.1:8118'}) opener = urllib2.build_opener(proxy) print ...
Python fails Tor check using urllib2 to initiate requests
After reading through the other questions on StackOverflow, I got a snippet of Python code that is able to make requests through a Tor proxy: import urllib2 proxy = urllib2.ProxyHandler({'http':'127.0.0.1:8118'}) opener = urllib2.build_opener(proxy) print opener.open('https://check.torproject.org/').read() Since Tor ...
[ "You've set up a proxy to your local Tor instance for the http protocol, but you're using https to talk to \"check.torproject.org\". Try:\nprint opener.open('http://check.torproject.org/').read()\n\n" ]
[ 5 ]
[]
[]
[ "python", "security", "tor", "urllib2" ]
stackoverflow_0002075469_python_security_tor_urllib2.txt
Q: Python 2 and IPv6 I'm trying to enable IPv6 in a Python 2 application and am running into trouble. Whenever I try to bind to an IPv6 socket, a socket.error: getsockaddrarg: bad family exception is thrown. I can reproduce the error simply by doing: import socket s = socket.socket(socket.AF_INET6, socket.SOCK_STR...
Python 2 and IPv6
I'm trying to enable IPv6 in a Python 2 application and am running into trouble. Whenever I try to bind to an IPv6 socket, a socket.error: getsockaddrarg: bad family exception is thrown. I can reproduce the error simply by doing: import socket s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s.bind(('', 12345)...
[ "Okay here's the answer from the comments:\nSeems like Python wasn't configured with --enable-ipv6.\nIt shouldn't be a OS problem because Python 3 works. Even if the OS doesn't have IPv6 support, it seems that socket.AF_INET6 is always available (if it is defined in the OS header files). Cf. socketmodule.c, line 44...
[ 4, 3, 2 ]
[]
[]
[ "ipv6", "python" ]
stackoverflow_0002075383_ipv6_python.txt
Q: Draw a colored sphere from cartesian coordinates in pymol I was looking in the wiki how to convert the following information about beads, cartesian coordinates + energy : 23.4 54.6 12.3 -123.5 54.5 23.1 9.45 -56.7 ....... to a draw in pymol that contains for each atom a sphere of radius R, centered on its coordina...
Draw a colored sphere from cartesian coordinates in pymol
I was looking in the wiki how to convert the following information about beads, cartesian coordinates + energy : 23.4 54.6 12.3 -123.5 54.5 23.1 9.45 -56.7 ....... to a draw in pymol that contains for each atom a sphere of radius R, centered on its coordinates, and with color, in a rainbow gradient. Thanks
[ "Does what you're rendering actually have anything to do with molecular structure (i.e. what is the motivation for using PyMol)?\nIf you are drawing some molecular structure, I would recommend just outputting a custom PDB file with the sphere coordinates (you can use the B-factor field per ATOM line as a way of con...
[ 10 ]
[]
[]
[ "bioinformatics", "python", "visualization" ]
stackoverflow_0002060582_bioinformatics_python_visualization.txt
Q: Connecting signals in GTK+: anonymous way? After reading "Using your signals" I am wondering if it is possible to connect the signals to "sinks" in an "anonymous" way? In order words, if the example following (snippet from reference above): aCar = Car() aCar.connect('engine-started', myCallback) Is it possible j...
Connecting signals in GTK+: anonymous way?
After reading "Using your signals" I am wondering if it is possible to connect the signals to "sinks" in an "anonymous" way? In order words, if the example following (snippet from reference above): aCar = Car() aCar.connect('engine-started', myCallback) Is it possible just to connect myCallback to all the signal engi...
[ "Yes, you can use gobject.add_emission_hook (g_signal_add_emission_hook).\n" ]
[ 1 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0002074372_gtk_python.txt
Q: Python: Help Me optimize this code. I am looking to see if this code can be optimized. def gB(a,b,c): x=len(b) d=a.find(b)+x e=a.find(c,d) return a[d:e] print gB("abc","a","c") A: There's a couple of problems with your code that you probably should fix before trying to optimize it. Fir...
Python: Help Me optimize this code.
I am looking to see if this code can be optimized. def gB(a,b,c): x=len(b) d=a.find(b)+x e=a.find(c,d) return a[d:e] print gB("abc","a","c")
[ "There's a couple of problems with your code that you probably should fix before trying to optimize it.\nFirstly, it's undocumented and the naming is not helpful. I assume it is trying to extract a string between start and end markers.\nSecondly, it gives an apparent match even if the start and/or end markers aren'...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002075573_python.txt
Q: Any tutorial for Python PalmDB library? I've downloaded the Python PalmDB lib, but can't find any info on how to use it. I've tried reading docstrings and so far I've been able to come up with the following code: from pprint import pprint from PalmDB.PalmDatabase import PalmDatabase pdb = PalmDatabase() with ope...
Any tutorial for Python PalmDB library?
I've downloaded the Python PalmDB lib, but can't find any info on how to use it. I've tried reading docstrings and so far I've been able to come up with the following code: from pprint import pprint from PalmDB.PalmDatabase import PalmDatabase pdb = PalmDatabase() with open('testdb.pdb','rb') as data: pdb.fromByt...
[ "There are two problems with the PalmDB module. The first is that it comes with almost no documentation. The other is that in order to do anything useful with the records in the database you need to figure out the binary structure for the particular record type you're dealing with (it's different for each type) a...
[ 2 ]
[]
[]
[ "palmdb", "pdb_palm", "python" ]
stackoverflow_0001700229_palmdb_pdb_palm_python.txt
Q: Is it possible to edit the inline code in with BeautifulSoup? I am aware of the ability to edit text with beautifulsoup, is it possible to edit the href links? I would like to be able to take say <a href="/foo/bar/"> and use beautifulsoup to change it to <a href="http://www.foobarinc.com/foo/bar/">. I am not sure ...
Is it possible to edit the inline code in with BeautifulSoup?
I am aware of the ability to edit text with beautifulsoup, is it possible to edit the href links? I would like to be able to take say <a href="/foo/bar/"> and use beautifulsoup to change it to <a href="http://www.foobarinc.com/foo/bar/">. I am not sure how I would use beautifulsoup to do this? Any help, much appreciate...
[ "As in your other question: with BeautifulSoup you're parsing in the content to a set of hierarchically nested objects representing the document, then changing those objects before serialising them back to different text. You're not editing the text directly.\nThe href=\"...\" part of the markup represents an attri...
[ 6, 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002075454_beautifulsoup_python.txt
Q: Accessing related object key without fetching object in App Engine In general, it's better to do a single query vs. many queries for a given object. Let's say I have a bunch of 'son' objects each with a 'father'. I get all the 'son' objects: sons = Son.all() Then, I'd like to get all the fathers for that group of...
Accessing related object key without fetching object in App Engine
In general, it's better to do a single query vs. many queries for a given object. Let's say I have a bunch of 'son' objects each with a 'father'. I get all the 'son' objects: sons = Son.all() Then, I'd like to get all the fathers for that group of sons. I do: father_keys = {} for son in sons: father_keys.setdefaul...
[ "You can find the answer by studying the sources of appengine.ext.db in your download of the App Engine SDK sources -- and the answer is, no, there's no special-casing as you require: the __get__ method (line 2887 in the sources for the 1.3.0 SDK) of the ReferenceProperty descriptor gets invoked before knowing if ....
[ 10, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002075951_google_app_engine_google_cloud_datastore_python.txt
Q: Get only the keys out of a reference property in GAE-Py I've got a an app where I'm storing posts and their authors. Very straightforward each post has one author model. The problem is this: I fetch the last 10 posts using one call, using fetch() with limit = 10. But when I print them out, GAE uses 10 extra get...
Get only the keys out of a reference property in GAE-Py
I've got a an app where I'm storing posts and their authors. Very straightforward each post has one author model. The problem is this: I fetch the last 10 posts using one call, using fetch() with limit = 10. But when I print them out, GAE uses 10 extra gets to access the author details, because the author object is ...
[ "See my response to this question just a couple hours ago -- a Q almost identical by amazing coincidence by this one, though by a different poster.\nIn short, to do this, use the get_value_for_datastore of the Property object.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002076260_google_app_engine_python.txt
Q: Extract string from between quotations I want to extract information from user-inputted text. Imagine I input the following: SetVariables "a" "b" "c" How would I extract information between the first set of quotations? Then the second? Then the third? A: >>> import re >>> re.findall('"([^"]*)"', 'SetVariables "...
Extract string from between quotations
I want to extract information from user-inputted text. Imagine I input the following: SetVariables "a" "b" "c" How would I extract information between the first set of quotations? Then the second? Then the third?
[ ">>> import re\n>>> re.findall('\"([^\"]*)\"', 'SetVariables \"a\" \"b\" \"c\" ')\n['a', 'b', 'c']\n\n", "You could do a string.split() on it. If the string is formatted properly with the quotation marks (i.e. even number of quotation marks), every odd value in the list will contain an element that is between quo...
[ 60, 40, 15 ]
[]
[]
[ "extraction", "python", "quotations", "string" ]
stackoverflow_0002076343_extraction_python_quotations_string.txt
Q: Simple modeling of existing SQL Server database schema in Python I'm looking to write a few small tools for managing table content for an existing SQL Server 2005 DB. I have a few dozen tables of reference content for an application that is deployed on many client databases (often for different schema versions) an...
Simple modeling of existing SQL Server database schema in Python
I'm looking to write a few small tools for managing table content for an existing SQL Server 2005 DB. I have a few dozen tables of reference content for an application that is deployed on many client databases (often for different schema versions) and I want to build a few python scripts to export, import, diff, and me...
[ "SqlAlchemy may actually help you . You can have a look here http://www.sqlalchemy.org/docs/05/ormtutorial.html\n", "Django has documentation on using it with legacy databases, but you will still have to handle things such as specifying relations yourself.\n" ]
[ 1, 0 ]
[]
[]
[ "orm", "python", "sql_server" ]
stackoverflow_0002076365_orm_python_sql_server.txt
Q: Split list in python I have following list: mylist = ['Hello,\r', 'Whats going on.\r', 'some text'] When I write "mylist" to a file called file.txt open('file.txt', 'w').writelines(mylist) I get for every line a little bit text because of the \r: Hello, Whats going on. some text How can I manipulate mylist to s...
Split list in python
I have following list: mylist = ['Hello,\r', 'Whats going on.\r', 'some text'] When I write "mylist" to a file called file.txt open('file.txt', 'w').writelines(mylist) I get for every line a little bit text because of the \r: Hello, Whats going on. some text How can I manipulate mylist to substitute the \r with a sp...
[ "mylist = [s.replace(\"\\r\", \" \") for s in mylist]\n\nThis loops through your list, and does a string replace on each element in it.\n", "open('file.txt', 'w').writelines(map(lambda x: x.replace('\\r',' '),mylist))\n\n", "Iterate through the list to a match with a regular expression to replace /r with a spac...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002075199_python.txt
Q: Using classes for Django views, is it Pythonic? I'm currently learning Python and coming from a strong C# background. I keep hearing about doing things in a Pythonic way to take advantage of the dynamic nature of the language and some of it I get and some I don't. I'm creating a site with Django and my approach t...
Using classes for Django views, is it Pythonic?
I'm currently learning Python and coming from a strong C# background. I keep hearing about doing things in a Pythonic way to take advantage of the dynamic nature of the language and some of it I get and some I don't. I'm creating a site with Django and my approach to views is to use classes. My current thinking is to...
[ "Certainly there's nothing wrong with using a class for a view, provided you route the URL to an actual instance of a class and not just a class directly.\n", "The Django admin does exactly this - look at the source code in django/contrib/admin. \nThe advantage of classes is that they are much easier to customize...
[ 4, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002071258_django_python.txt
Q: Implementation limitations of float.as_integer_ratio() Recently, a correspondent mentioned float.as_integer_ratio(), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations of real numbers. Intrigued, I had to try π: >>> float.as_integer_ratio(math.pi); (884279...
Implementation limitations of float.as_integer_ratio()
Recently, a correspondent mentioned float.as_integer_ratio(), new in Python 2.6, noting that typical floating point implementations are essentially rational approximations of real numbers. Intrigued, I had to try π: >>> float.as_integer_ratio(math.pi); (884279719003555L, 281474976710656L) I was mildly surprised not to...
[ "You get better approximations using\nfractions.Fraction.from_float(math.pi).limit_denominator()\n\nFractions are included since maybe version 3.0.\nHowever, math.pi doesn't have enough accuracy to return a 30 digit approximation.\n", "May I recommend gmpy's implementation of the Stern-Brocot tree:\n>>> import gm...
[ 10, 5, 4 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002076290_math_python.txt
Q: Python C-API Making len(...) work with extension class When creating a class in Python, I can simply make a def __len__(self): method to make the len(InstanceOfMyClass) work, however I can't find out how to do this with an extension class via the C-API. I tried adding a __len__ method, but that appears to not work...
Python C-API Making len(...) work with extension class
When creating a class in Python, I can simply make a def __len__(self): method to make the len(InstanceOfMyClass) work, however I can't find out how to do this with an extension class via the C-API. I tried adding a __len__ method, but that appears to not work {"__len__",(PyCFunction)&TestClass_GetLen,METH_NOARGS,""}, ...
[ "As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example:\n#include <Python.h>\n\n/**\n * C structure and methods definitions\n */\n\ntypedef struct {\n PyObject_HEAD;\n} TestObject;\n\nstatic Py_ssize_t\nTestClass_len(TestObject* self) \n{ \n ret...
[ 3, 3 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0002064276_c_python_python_c_api.txt
Q: Finding the performance bottleneck in a Python and MySQL script I have a script with a main for loop that repeats about 15k times. In this loop it queries a local MySQL database and does a SVN update on a local repository. I placed the SVN repository in a RAMdisk as before most of the time seemed to be spent readi...
Finding the performance bottleneck in a Python and MySQL script
I have a script with a main for loop that repeats about 15k times. In this loop it queries a local MySQL database and does a SVN update on a local repository. I placed the SVN repository in a RAMdisk as before most of the time seemed to be spent reading/writing to disk. Now I have a script that runs at basically the sa...
[ "Doing SQL queries in a for loop 15k times is a bottleneck in every language.. \nIs there any reason you query every time again ? If you do a single query before the for loop and then loop over the resultset and the SVN part, you will see a dramatic increase in speed.\nBut I doubt that you will get a higher CPU usa...
[ 4, 1, 1 ]
[]
[]
[ "mysql", "performance", "python", "svn" ]
stackoverflow_0002076582_mysql_performance_python_svn.txt
Q: GAE: Making many queries into one I have a productpart database containing a string property named 'type'. What I'm trying to do is to get all products by a given type (sometimes more then one type). I've tried to use GAE filter method but can't get it to work properly. The only solution I've got working is to ma...
GAE: Making many queries into one
I have a productpart database containing a string property named 'type'. What I'm trying to do is to get all products by a given type (sometimes more then one type). I've tried to use GAE filter method but can't get it to work properly. The only solution I've got working is to make a new db.GqlQuery for each type. The...
[ "You can use the IN operator. It would create the three different queries and group the results together for you under the scenes. See the docs:\n\nGQL does not have an OR operator.\n However, it does have an IN operator,\n which provides a limited form of OR.\nThe IN operator compares value of a\n property to e...
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002077034_google_app_engine_google_cloud_datastore_python.txt
Q: DB a table for the category and another table for the subcategory with similar fields, why? I recently joined a new company and the development team was in the progress of a project to rebuild the database categories structure as follows: if we have category and subcategory for items, like food category and italia...
DB a table for the category and another table for the subcategory with similar fields, why?
I recently joined a new company and the development team was in the progress of a project to rebuild the database categories structure as follows: if we have category and subcategory for items, like food category and italian food category in food category. They were building a table for each category, instead of having...
[ "First, the most obvious answer is that you should ask them, not us, since I can tell you this, that design seems bogus deluxe.\nThe only reason I can come up with is that you have inexperienced DBA's that does not know how to performance-tune a database, and seems to think that a table with less rows will always v...
[ 2, 0 ]
[]
[]
[ "database", "django", "mysql", "performance", "python" ]
stackoverflow_0002077522_database_django_mysql_performance_python.txt
Q: Why should I make multiple wx.Panel's? Following this tutorial on WxPython, I've noticed that in the Find/Replace Dialog example there are extra panels where it doesn't seem like they're actually doing anything. In fact, they seem to mess up even more the layout (though that is probably some mistake I made somewhe...
Why should I make multiple wx.Panel's?
Following this tutorial on WxPython, I've noticed that in the Find/Replace Dialog example there are extra panels where it doesn't seem like they're actually doing anything. In fact, they seem to mess up even more the layout (though that is probably some mistake I made somewhere) For example, the tutorial has this code:...
[ "I'm not sure. I've re-written the example into less code, although it's a bit hard to follow. I may e-mail this suggestions to her.\nimport wx\n\nclass FindReplace(wx.Dialog):\n def __init__(self, parent, id, title):\n wx.Dialog.__init__(self, parent, id, title, size=(255, 365))\n\n vbox_top = wx....
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002075638_python_wxpython.txt
Q: Python deque performance for small iterables I was playing around with Python's collection.deque and wrote the following benchmark: #!/usr/bin/python import timeit if __name__=='__main__': number = 1000000 for r in (1,10,100,1000,5000,10000,100000): print r print timeit.timeit("while x: x...
Python deque performance for small iterables
I was playing around with Python's collection.deque and wrote the following benchmark: #!/usr/bin/python import timeit if __name__=='__main__': number = 1000000 for r in (1,10,100,1000,5000,10000,100000): print r print timeit.timeit("while x: x.pop(0);", "x = list(r...
[ "The timeit module runs the setup code once, and then the timed code number times (in this case, number==1000000). In your case this looks like (for the list case):\nx = list(range(r))\n#timer is started here\nfor iteration in xrange(1000000):\n while x: x.pop(0)\n#timer is stopped here\n\nAs you can see, only t...
[ 4, 3, 2 ]
[]
[]
[ "deque", "performance", "python" ]
stackoverflow_0002077379_deque_performance_python.txt
Q: New field in Django model doesn't show up in admin interface or model forms I've created a model in one of my apps which works fine. However, I needed to add a new field. I did this, and used manage.py reset <appname> to drop the tables and add them again. This process went fine - the new field appears in the data...
New field in Django model doesn't show up in admin interface or model forms
I've created a model in one of my apps which works fine. However, I needed to add a new field. I did this, and used manage.py reset <appname> to drop the tables and add them again. This process went fine - the new field appears in the database. However, I can't get the field to show up in the admin interface, nor in th...
[ "Have you restarted your server?\n", "By any chance, did you forget to update your ModelAdmin definitions?\n" ]
[ 7, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002077977_django_django_admin_django_models_python.txt
Q: Django: Chicken or Egg question I am building an application that will send an API call and save the resulting information after processing the information in a APIRecord(models.Model) class. 1) Should I build a separate class in such a way that the class does the API call, processes the information (including che...
Django: Chicken or Egg question
I am building an application that will send an API call and save the resulting information after processing the information in a APIRecord(models.Model) class. 1) Should I build a separate class in such a way that the class does the API call, processes the information (including checking against business rules) and the...
[ "it is design decision.\nit depends to your design and programming interests.\ni used the combination of three methods you said. if i need to some informations that can be build from other fields then i will create an internal function in model class. if i need other records of database to do something i will creat...
[ 1 ]
[]
[]
[ "application_design", "design_patterns", "django", "python" ]
stackoverflow_0002076678_application_design_design_patterns_django_python.txt
Q: generating a binary tree from given data in python i wanted to know how to read values from a list into a binary tree. i have a triangle like this: 0 1 2 3 4 5 6 7 8 9 i have written a class node like this class node: def __init__(self,data,left=None,right=None): se...
generating a binary tree from given data in python
i wanted to know how to read values from a list into a binary tree. i have a triangle like this: 0 1 2 3 4 5 6 7 8 9 i have written a class node like this class node: def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=r...
[ "This does sound like homework, so I won't write code, but here are a couple of hints:\n\nThis could be done even if your triangle were written as a list, like \n0 1 2 3 4 5 6 7 8 9\nBecause it seems like this is a full binary tree (assuming your triangle is wrong and the third row is actually supposed to be 3 4 5 ...
[ 1, 0 ]
[]
[]
[ "binary_tree", "python" ]
stackoverflow_0002078669_binary_tree_python.txt
Q: GAE Simple Searching + Autocomplete I'm looking to create a search function for my flash game website. One of the problems with the site is that it is difficult to find a specific game you want, as users must go to the alphabetical list to find one they want. It's run with Google App Engine written in python, usin...
GAE Simple Searching + Autocomplete
I'm looking to create a search function for my flash game website. One of the problems with the site is that it is difficult to find a specific game you want, as users must go to the alphabetical list to find one they want. It's run with Google App Engine written in python, using the webapp framework. At the very least...
[ "I have written the code below to handle this. Basically, I save all the possible word \"starts\" in a list instead of whole sentences. That's how the jquery autocomplete of this site works.\nimport unicodedata\nimport re\n\nsplitter = re.compile(r'[\\s|\\-|\\)|\\(|/]+')\n\ndef remove_accents(text):\n nkfd_form ...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002078738_google_app_engine_python.txt
Q: Pythonic way to sort list of objects by a dict value (by key) contained within the object I'm seeking advice on doing the following in a more pythonic way. Consider: class MyObj(object): def __init__(self): self.dict_properties = {} Suppose I've got a list which contains multiple MyObj instances: myli...
Pythonic way to sort list of objects by a dict value (by key) contained within the object
I'm seeking advice on doing the following in a more pythonic way. Consider: class MyObj(object): def __init__(self): self.dict_properties = {} Suppose I've got a list which contains multiple MyObj instances: mylist = [<__main__.MyObj object at 0x1005e3b90, ...] Now i want to sort mylist based on the value...
[ "mylist.sort(key=lambda x: x.dict_properties['mykey'])\n\nis way simpler, and faster. You could reach for operator and try to compose an attrgetter and an itemgetter, but a straightforward lambda (or def) seems simplest here.\n", "I'd just do:\nmylist.sort(key=lambda o: o.dict_properties[\"kykey\"])\nYou could a...
[ 9, 3, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002078986_python_sorting.txt
Q: Better way to port Java into Python? After several hours of working on porting this program over, it appears to finally be in a working state. However, I was wondering if anyone knew of a better way or more complete way of porting Java servlets over into Python. The beginning of the Python script contains a lot of...
Better way to port Java into Python?
After several hours of working on porting this program over, it appears to finally be in a working state. However, I was wondering if anyone knew of a better way or more complete way of porting Java servlets over into Python. The beginning of the Python script contains a lot of support code to make it easier to port th...
[ "My best suggestion is to not write a line by line port. Python is not Java and you're hamstringing yourself if you're just writing Java style code in the Python language.\nHere's a starter for recognizing some of the common differences/mistakes: http://dirtsimple.org/2004/12/python-is-not-java.html\nIf you're luc...
[ 7, 3, 2, 2 ]
[]
[]
[ "java", "porting", "python", "servlets" ]
stackoverflow_0002079076_java_porting_python_servlets.txt
Q: Which methods implement the buffer interface in Python? I have a custom class with a serialize method, and I want to be able to write this class directly to files and have the return value of the serialize method get written, in Python 2.6. (I'm not trying to pickle my objects, this is something totally different....
Which methods implement the buffer interface in Python?
I have a custom class with a serialize method, and I want to be able to write this class directly to files and have the return value of the serialize method get written, in Python 2.6. (I'm not trying to pickle my objects, this is something totally different.) For example: class Foo(object): def serialize(self): ...
[ "Peculiarly, there are no special methods that a pure-Python coded class can directly implement to support the buffer interface -- that would have been PEP 298, but it was withdrawn.\nI'm afraid you'll have to use some explicit attribute or method (or a built-in like str which internally calls a special method) to...
[ 13, 1 ]
[]
[]
[ "buffer", "python" ]
stackoverflow_0002079272_buffer_python.txt
Q: Missing datetime.time.__sub__? Why can't subtract two time objects? For example, 12:00 - 11:00 = 1:00 from datetime import time time(12,00) - time(11,00) # -> timedelta(hours=1) It seems that datetime.time.__sub__ is missing TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' do y...
Missing datetime.time.__sub__?
Why can't subtract two time objects? For example, 12:00 - 11:00 = 1:00 from datetime import time time(12,00) - time(11,00) # -> timedelta(hours=1) It seems that datetime.time.__sub__ is missing TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' do you know why?
[ "The time objects have no date, so for example, the 12:00 might be (say) on a Wed and the 11:00 on the preceding Tue, making the difference 25 hours, not one (any multiple of 24 might be added or subtracted). If you know they're actually on the same date, just apply any arbitrary date to each of them (making two d...
[ 6, 0 ]
[]
[]
[ "datetime", "missing_features", "python", "time" ]
stackoverflow_0002079323_datetime_missing_features_python_time.txt
Q: Passing options to Python executable in non-interactive mode I would like to pass some options to Python (version 2.6) every time, not just in interactive mode. Is there a file I can put such commands in? EDIT: Specifically, I'm wanting to silence the Deprecation warnings. A: The #!/usr/bin/python line at the b...
Passing options to Python executable in non-interactive mode
I would like to pass some options to Python (version 2.6) every time, not just in interactive mode. Is there a file I can put such commands in? EDIT: Specifically, I'm wanting to silence the Deprecation warnings.
[ "The #!/usr/bin/python line at the beginning of a Python script under Linux can be used to also pass options to the interpreter.\nThere are also a number of modules imported whenever Python starts up. On my system, a likely candidate for modification to set options in the manner suggested by other posters are here...
[ 6, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002078752_python.txt
Q: String matching in Python does anyone know which string matching algorithm is implemented in Python? A: Per the sources, it's a fast search/count implementation, based on a mix between boyer-moore and horspool, with a few more bells and whistles on the top. for some more background, see: http://effbo...
String matching in Python
does anyone know which string matching algorithm is implemented in Python?
[ "Per the sources, it's a\n\nfast search/count implementation,\n based on a mix between boyer-moore and\n horspool, with a few more bells and\n whistles on the top. for some more\n background, see:\n http://effbot.org/zone/stringlib.htm\n\nThe essay in question is really well worth reading!\n", "I assume you...
[ 9, 1 ]
[]
[]
[ "python", "string_matching" ]
stackoverflow_0002079676_python_string_matching.txt
Q: Data modeling advice for a forum application on Google App Engine I'm writing a simple forum-like application on Google App Engine and trying to avoid scalability issues. I'm new to this non-RBDMS approach, i'd like to avoid pitfalls from the beginning. The forum design is pretty simple, posts and replies will be ...
Data modeling advice for a forum application on Google App Engine
I'm writing a simple forum-like application on Google App Engine and trying to avoid scalability issues. I'm new to this non-RBDMS approach, i'd like to avoid pitfalls from the beginning. The forum design is pretty simple, posts and replies will be the only concepts. What will be the best approach to the problem if the...
[ "Firstly, why don't you use user = db.UserProperty() instead of user = db.StringProperty()?\nSecondly, I'm quite sure you should use whatever it works and is more readable and test the performance later, for three reasons:\n\nKISS (Keep it simple)\nEarly optimizations are bad\nYou can't improve what you can't measu...
[ 2 ]
[ "You might want to take a look at a good tutorial on creating a php forum from scratch. Sure that one is about PHP but it also covers the general overview of forum design.\nBasically, don't split posts and replies or threads and posts. It will lead to some really awkward queries later on. A thread is simply a post ...
[ -2 ]
[ "data_modeling", "google_app_engine", "python" ]
stackoverflow_0002079763_data_modeling_google_app_engine_python.txt
Q: static file with mod_wsgi in django I've searched a lot but I still have a problem with the static files (css, image,...) with my django website. I'm using mod_wsgi with apache on archlinux 64bits I've added it in my http.conf : LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost *:80> WSGIDaemonProcess ...
static file with mod_wsgi in django
I've searched a lot but I still have a problem with the static files (css, image,...) with my django website. I'm using mod_wsgi with apache on archlinux 64bits I've added it in my http.conf : LoadModule wsgi_module modules/mod_wsgi.so <VirtualHost *:80> WSGIDaemonProcess mart.localhost user=mart group=users proc...
[ "It is not sufficient for just the directory '/home/mart/programmation/python/django/martfiles/media' containing static files to be readable and searchable. The user that Apache runs as must have read and potentially search access, to all parent directories of it back up to root directory. Since home directories on...
[ 7, 3, 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0002078160_apache_django_mod_wsgi_python.txt
Q: Undesired python feedparser instantiation relic Question: How do I kill an instantiation or insure i'm creating a new instantiation of the python universal feedparser? Info: I'm working on a program right now that downloads and catalogs large numbers of blogs. It has worked well so for except for an unfortunate b...
Undesired python feedparser instantiation relic
Question: How do I kill an instantiation or insure i'm creating a new instantiation of the python universal feedparser? Info: I'm working on a program right now that downloads and catalogs large numbers of blogs. It has worked well so for except for an unfortunate bug. My code is set up to take a list of blog urls and...
[ "The problem is posts=[]. Default arguments are calculated at compile time, not runtime, so mutations to the object remain for the lifetime of the class. Instead use posts=None and test:\nif posts is None:\n self.posts = []\n\n", "As what Ignacio said, any mutations that happen to the default arguments in the fu...
[ 1, 0 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0002080071_feedparser_python.txt
Q: Django TemplateSyntaxError: too many values to unpack I'm working with a django form, and I have a choice field. I think the problem may be that the choices are fetched dynamically, and right now there's only one value. I'm getting the TemplateSyntaxError: too many values to unpack. Some of the other posts seem to...
Django TemplateSyntaxError: too many values to unpack
I'm working with a django form, and I have a choice field. I think the problem may be that the choices are fetched dynamically, and right now there's only one value. I'm getting the TemplateSyntaxError: too many values to unpack. Some of the other posts seem to say that having only one value is a problem, so i adjusted...
[ "choices is supposed to be an iterable of 2-tuples. You are only appending a single string, which is causing chaos due to how strings and tuples interact (I'll give you details if you really care). Append 2-tuples instead.\n" ]
[ 6 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002080186_django_django_templates_python.txt
Q: Finding intersections Given a scenario where there are millions of potentially overlapping bounding boxes of variable sizes less the 5km in width. Create a fast function with the arguments findIntersections(Longitude,Latitude,Radius) and the output is a list of those bounding boxes ids where each bounding box orig...
Finding intersections
Given a scenario where there are millions of potentially overlapping bounding boxes of variable sizes less the 5km in width. Create a fast function with the arguments findIntersections(Longitude,Latitude,Radius) and the output is a list of those bounding boxes ids where each bounding box origin is inside the perimeter ...
[ "This is normally done using an R-tree data structure\ndbs like mysql or postgresql have GIS modules that use an r-tree under the hood to quickly retrieve locations within a certain proximity to a point on a map.\nFrom http://en.wikipedia.org/wiki/R-tree:\n\nR-trees are tree data structures that\n are similar to B...
[ 4, 1, 0 ]
[]
[]
[ "algorithm", "localization", "optimization", "performance", "python" ]
stackoverflow_0002062325_algorithm_localization_optimization_performance_python.txt
Q: @register.filter in my code from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload" } @register.filter#<-------- def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxinput"...
@register.filter in my code
from django import template register = template.Library() class_converter = { "textinput":"textinput textInput", "fileinput":"fileinput fileUpload" } @register.filter#<-------- def is_checkbox(field): return field.field.widget.__class__.__name__.lower() == "checkboxinput" @register.filter#<-------- def ...
[ "Not exactly. The decorator syntax:\n@register.filter\ndef a():\n pass\n\nis syntactic sugar for:\ndef a():\n pass\na = register.filter(a)\n\nSo register.filter in this case will be called with the first positional argument, 'name' being your function. The django register.filter function handles that usage how...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002080296_django_python.txt
Q: What happen when I add a Django app to INSTALLED_APPS? Here is the situation. I have a django project with two installed apps. Both apps appear to function properly if they are installed independently of each other. However if I list both apps in the settings.INSTALLED_APPS the reverse() function seems to break ...
What happen when I add a Django app to INSTALLED_APPS?
Here is the situation. I have a django project with two installed apps. Both apps appear to function properly if they are installed independently of each other. However if I list both apps in the settings.INSTALLED_APPS the reverse() function seems to break for urls in the first app. So this leads me to believe that...
[ "Nothing particular happens when you add an app to INSTALLED_APPS, but the main thing that affects you is that its views are checked when you call reverse(). \nThe way reverse works is to import all the views in the project, and see which ones match the URL name you have given. However, it is quite fragile, and if ...
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002079898_django_python.txt
Q: How to copy a file via the browser to Amazon S3 using Python (and boto)? Creating a file (key) into Amazon S3 using Python (and boto) is not a problem. With this code, I can connect to a bucket and create a key with a specific content: bucket_instance = connection.get_bucket('bucketname') key = bucket_instance.new...
How to copy a file via the browser to Amazon S3 using Python (and boto)?
Creating a file (key) into Amazon S3 using Python (and boto) is not a problem. With this code, I can connect to a bucket and create a key with a specific content: bucket_instance = connection.get_bucket('bucketname') key = bucket_instance.new_key('testfile.txt') key.set_contents_from_string('Content for File') I want ...
[ "You can't do this with boto, because what you're asking for is purely client-side - there's no direct involvement from the server except to generate the form to post.\nWhat you need to use is Amazon's browser-based upload with POST support. There's a demo of it here.\n", "do you mean this one? Upload files in Go...
[ 2, 0 ]
[]
[]
[ "amazon_ec2", "amazon_s3", "boto", "google_app_engine", "python" ]
stackoverflow_0002079594_amazon_ec2_amazon_s3_boto_google_app_engine_python.txt
Q: Why the following python code works? class Square: def __init__(self,start,stop): self.value = start - 1 self.stop = stop def __iter__(self): return self def next(self): if self.value == self.stop: raise StopIterat...
Why the following python code works?
class Square: def __init__(self,start,stop): self.value = start - 1 self.stop = stop def __iter__(self): return self def next(self): if self.value == self.stop: raise StopIteration ...
[ "why wouldn't it? It looks like a normal iterator to me...\nthe next() method is a 'known' method in python that along with the __iter__() method signals a generator.\nHere is the python docs on iterators.\n", "This is a Python iterator: every time through the loop the next() method is called\n", "It's an iter...
[ 1, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002054124_python_syntax.txt
Q: os.unlink multiple file in python Possible Duplicate: Deleting files by type in Python on Windows How can I delete all files with the extension ".txt" in a directory? I normally just do import os filepath = 'C:\directory\thefile.txt' os.unlink(filepath) Is there a command like os.unlink('C:\directory\*.txt') tha...
os.unlink multiple file in python
Possible Duplicate: Deleting files by type in Python on Windows How can I delete all files with the extension ".txt" in a directory? I normally just do import os filepath = 'C:\directory\thefile.txt' os.unlink(filepath) Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can...
[ "#!/usr/bin/env python\n\nimport glob\nimport os\n\nfor i in glob.glob(u'*.txt'):\n os.unlink (i)\n\nshould do the job.\nEdit: You can also do it in \"one line\" using map operation:\n#!/usr/bin/env python\n\nimport glob\nimport os\n\nmap(os.unlink, glob.glob(u'*.txt'))\n\n", "Use the glob module to get a list o...
[ 15, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002081139_python.txt
Q: Python calling raw_input from a subprocess I'm calling a python script from the below one using subprocess. From the command line the user chooses which file to open using raw_input import optparse import subprocess import readline import os def main(): options = {'0': './option_0.py', '1': './op...
Python calling raw_input from a subprocess
I'm calling a python script from the below one using subprocess. From the command line the user chooses which file to open using raw_input import optparse import subprocess import readline import os def main(): options = {'0': './option_0.py', '1': './option_1.py', '2': './option_2.py', ...
[ "Here's an example where the subprocess receives my input:\nimport subprocess\nimport sys\n\ncommand = 'python -c \\'print raw_input(\"Please make a selection: \")\\''\nsp = subprocess.Popen(command, shell = True, stdin = sys.stdin)\nsp.wait()\n\n", "If I understand your question, you want to redirect the current...
[ 3, 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002081124_python_subprocess.txt
Q: How to print nicely? I have two classes: class Dog(object): def __init__(self, name): self.name = name class Toy(object): def play(self): print "Squeak!" I need to come up with a method called play(self, toy, n) for class Dog. It prints "Yip! " (with a space) followed by the output from t...
How to print nicely?
I have two classes: class Dog(object): def __init__(self, name): self.name = name class Toy(object): def play(self): print "Squeak!" I need to come up with a method called play(self, toy, n) for class Dog. It prints "Yip! " (with a space) followed by the output from toy.play on the same line. ...
[ "In your example call, Dog('big').play(0), you are not passing the toy argument -- that's what it's complaining about! Pass a toy argument before n and that will be better.\nThen you can start addressing the bugs in your play implementation: why are you making a new toy rather than use the argument, why are you pr...
[ 1, 0 ]
[]
[]
[ "printing", "python" ]
stackoverflow_0002080101_printing_python.txt
Q: How to test type of an object in Python? import string print string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz print type(string.ascii_lowercase) # <type 'str'> print string.ascii_lowercase is str # False Shouldn't it be True? A: The is operator compares the identity of two objects. This is what I believe it ...
How to test type of an object in Python?
import string print string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz print type(string.ascii_lowercase) # <type 'str'> print string.ascii_lowercase is str # False Shouldn't it be True?
[ "The is operator compares the identity of two objects. This is what I believe it does behind the scenes:\nid(string.ascii_lowercase) == id(str)\n\nActual strings are always going to have a different identity than the type str, so this will always be False.\nHere is the most Pythonic way to test whether something is...
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0002081377_python_types.txt
Q: Can you/should you modify objects in the database in the model of other classes I want to perform some delete() and some save() methods on some objects that are not an instance of the current class I'm in. I'm trying to do this in an overloaded save() method of a class. Here is the scenerio: class Item(models.Mo...
Can you/should you modify objects in the database in the model of other classes
I want to perform some delete() and some save() methods on some objects that are not an instance of the current class I'm in. I'm trying to do this in an overloaded save() method of a class. Here is the scenerio: class Item(models.Model): name = models.CharField(max_length=500) category = models.ForeignKey(Ca...
[ "I notice you are trying to update a ManyToMany in your save(). You might take a look at my answer to this thread and see if it applies to your situation. If you are using the admin interface and are encountering this error, then it is almost certainly part of the problem you are having. You also might want to look...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "model_view_controller", "python" ]
stackoverflow_0002075411_django_django_models_model_view_controller_python.txt
Q: Prompt on file/directory delete When coding in Python, I often need to write a function like this one: def delete_dir(dir_name): if os.path.exists(dir_name): reply = raw_input("Delete directory "+dir_name+"? [y/[n]] ") if reply=='y': os.system('rm -r '+dir_name) else: ...
Prompt on file/directory delete
When coding in Python, I often need to write a function like this one: def delete_dir(dir_name): if os.path.exists(dir_name): reply = raw_input("Delete directory "+dir_name+"? [y/[n]] ") if reply=='y': os.system('rm -r '+dir_name) else: print "Aborting..." ...
[ "It wouldn't be a Python thing, but if you keep using os.system() to make the delete call, you can pass the -i parameter to rm. The man page explains it:\n\n-i       prompt before every removal\n\nEDIT: I just read your code again and it looks like you're only prompting once before the entire delete process, not fo...
[ 2, 1, 0 ]
[]
[]
[ "delete_directory", "file_io", "prompt", "python" ]
stackoverflow_0002081407_delete_directory_file_io_prompt_python.txt
Q: Technique for multi-language support of big static portions text in Django For small portions of text we use django standart {% trans %} tag What to do with big texts such as FAQ, terms and other static pages A: There is a {% blocktrans %} templatetag you can use. You could also write a simple templatetag yours...
Technique for multi-language support of big static portions text in Django
For small portions of text we use django standart {% trans %} tag What to do with big texts such as FAQ, terms and other static pages
[ "There is a {% blocktrans %} templatetag you can use.\nYou could also write a simple templatetag yourself which includes anathor template based on the current language.\n{% i18ninclude \"faq/question1.html\" \"en\" %}\n\nWould include faq/question1.en.html. Here is the code:\nimport os\nfrom django import template\...
[ 6, 2 ]
[]
[]
[ "django", "multilingual", "python" ]
stackoverflow_0002081436_django_multilingual_python.txt
Q: Python list : How to sort by timestamp? ( App Engine related ) I have ten entities in my Feed model ( this is an App Engine model) class Feed(db.Model): sometext = db.StringProperty() timestamp = db.DateTimeProperty(auto_now=True) list_of_keys = ["key1","key2","key3".... "key10"] so i call my entities using ...
Python list : How to sort by timestamp? ( App Engine related )
I have ten entities in my Feed model ( this is an App Engine model) class Feed(db.Model): sometext = db.StringProperty() timestamp = db.DateTimeProperty(auto_now=True) list_of_keys = ["key1","key2","key3".... "key10"] so i call my entities using db.key() method: feeds = db.keys(list_of_keys) # this loop below pri...
[ "import operator\n\n ...\n\nfor feed in sorted(feeds, key=operator.attrgetter('timestamp'), reverse=True):\n print humanizeTimeDiff(feed.timestamp) \n\n" ]
[ 10 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002081754_google_app_engine_python.txt
Q: Python raw strings and unicode : how to use Web input as regexp patterns? EDIT : This question doesn't really make sense once you have picked up what the "r" flag means. More details here. For people looking for a quick anwser, I added on below. If I enter a regexp manually in a Python script, I can use 4 combinat...
Python raw strings and unicode : how to use Web input as regexp patterns?
EDIT : This question doesn't really make sense once you have picked up what the "r" flag means. More details here. For people looking for a quick anwser, I added on below. If I enter a regexp manually in a Python script, I can use 4 combinations of flags for my pattern strings : p1 = "pattern" p2 = u"pattern" p3 = r"p...
[ "Apart from possibly having to encode Unicode properly (in Python 2.*), no processing is needed because there is no specific type for \"raw strings\" -- it's just a syntax for literals, i.e. for string constants, and you don't have any string constants in your code snippet, so there's nothing to \"process\".\n", ...
[ 7, 2, 2 ]
[]
[]
[ "python", "rawstring", "regex", "unicode" ]
stackoverflow_0002081622_python_rawstring_regex_unicode.txt
Q: Authentication in django I'm trying to do connect form on my django website If in a shell I do : $ ./manage.py shell Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib import aut...
Authentication in django
I'm trying to do connect form on my django website If in a shell I do : $ ./manage.py shell Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib import auth >>> user = auth.authenticate...
[ "This works for me:\nIn the top of your script:\nfrom django.contrib.auth import authenticate, login, logout\n\nAuthentification:\n user = authenticate(username=request.POST['username'], password=request.POST['password'])\n if user is not None:\n if user.is_active:\n login(request, ...
[ 1, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0002080854_authentication_django_python.txt
Q: Passing multiple values to a function call (Python) import re def strip_tags(value): "Return the given HTML with all tags stripped." return re.sub(r'<[^>]*?>', '', value) I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple ...
Passing multiple values to a function call (Python)
import re def strip_tags(value): "Return the given HTML with all tags stripped." return re.sub(r'<[^>]*?>', '', value) I have this function to strip HTML tags, but it seems to accept only single value, what do I need to change if I want to pass multiple (not fixed) values at once? Thanks
[ "Python offers a way to use arbitrary-length argument lists:\ndef myfunc(*args):\n for argument in args:\n print \"myfunc was given\", argument\n\nIf you put *args in your function definition, all values passed to the function are available as a tuple called args. Note that you can also put additional arg...
[ 8, 2, 1, 1, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002081929_function_python.txt
Q: Simplest way to integrate python gui app with c console app I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform) What I would like to do is have a python gui app to allow the user to select a fil...
Simplest way to integrate python gui app with c console app
I have a c console app which converts a c file to a html file, the c file location is passed to the program as a command line argument.(the app is for the windows platform) What I would like to do is have a python gui app to allow the user to select a file and pass the location of the file to the c app for processing. ...
[ "You probably want the subprocess module.\nAt the very minimum:\nimport subprocess\nretcode = subprocess.call([\"/path/to/myCprogram\", \"/path/to/file.c\"])\nif retcode == 0:\n print \"success!\"\n\nThis will run the program with the arguments, and then return its return code.\nNote that subprocess.call will blo...
[ 10, 2 ]
[]
[]
[ "c", "integrate", "python", "user_interface" ]
stackoverflow_0002082028_c_integrate_python_user_interface.txt
Q: How to create a custom django filter tag I am having trouble in getting my site to recognise custom template tags. I have the following dir structure: project_name project_name templatetags _ __init __ _.py getattribute.py views _ __init __ _.py index.html views settings.py main.py manage.py urls.py nbpro...
How to create a custom django filter tag
I am having trouble in getting my site to recognise custom template tags. I have the following dir structure: project_name project_name templatetags _ __init __ _.py getattribute.py views _ __init __ _.py index.html views settings.py main.py manage.py urls.py nbproject Then I have added this to the INSTA...
[ "The error is becaus you have wrong your folder's structure, i think you must read the docs, this tutorial (part1) explains the right structure:\nYou have a project that isn't same thing that app:\n\nproject_name\n\n\napp_name\n\n\ntemplatetags\n\n\ngetattribute.py\n\nmodels.py\nviews.py \n\n\nsettings.py\nmanage.p...
[ 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002081834_django_python.txt
Q: Strange bug while combining images in Python I have a hundred 10x10 px images, and I want to combine them into a big 100x100 image. I'm using the Image library to first create a blank image and then paste in the smaller images: blank = Image.new('P',(100,100)) blank.paste(im,box) The smaller images are in color, ...
Strange bug while combining images in Python
I have a hundred 10x10 px images, and I want to combine them into a big 100x100 image. I'm using the Image library to first create a blank image and then paste in the smaller images: blank = Image.new('P',(100,100)) blank.paste(im,box) The smaller images are in color, but the resulting image turns out in all grayscale...
[ "It's probably something to do with using a palette type image (mode P). Is there a specific reason you are doing this? If not, try passing 'RGB' as the first argument.\n" ]
[ 2 ]
[]
[]
[ "image", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0002082145_image_image_processing_python_python_imaging_library.txt
Q: How to export C# methods? How can we export C# methods? I have a dll and I want to use its methods in the Python language with the ctypes module. Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python. So, how can I export the C# methods (like they do in C++)? A:...
How to export C# methods?
How can we export C# methods? I have a dll and I want to use its methods in the Python language with the ctypes module. Because I need to use the ctypes module, I need to export the C# methods for them to be visible in Python. So, how can I export the C# methods (like they do in C++)?
[ "Contrary to popular belief, this is possible.\nSee here.\n", "With the normal Python implementation (\"CPython\"), you can't, at least not directly.\nYou could write native C wrappers around our C# methods using C++/CLI, and call these wrappers from Python.\nOr, you could try IronPython. This lets you run Python...
[ 22, 1, 1, 1 ]
[]
[]
[ "c#", "export", "methods", "python", "python.net" ]
stackoverflow_0002082159_c#_export_methods_python_python.net.txt
Q: Python function returning None after recursion I can't figure out why this python function returns None if it calls itself recursively. It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it s...
Python function returning None after recursion
I can't figure out why this python function returns None if it calls itself recursively. It was part of my solution to a Project Euler problem. I have solved the problem in a better way anyhow, but this is still annoying me as the function seems to work OK - and it seems to know the value of the variable I wanted to r...
[ "You forgot to return a value when there is failure to find a prime:\nfor div in range(2,candidate//2,1):\n if candidate % div == 0:\n prime = False\n print candidate, \"is not prime - divisible by\", div\n return next_prime(candidate)\n\nRecursion isn't really suitable here though. It isn't...
[ 6, 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002082635_python_recursion.txt
Q: How make a better markdown for developer blog I'm rebuilding my blog at http://www.elmalabarista.com/blog/. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile. I try to put some python there I can't make markdown mark it...
How make a better markdown for developer blog
I'm rebuilding my blog at http://www.elmalabarista.com/blog/. I have use in my previous version markdown and now I remember why I have almost zero code samples. Doing code samples in markdown is very fragile. I try to put some python there I can't make markdown mark it as code!. The main culprit? The syntax is markdown...
[ "Consider using reStructuredText -- it's the standard lightweight markup for Python, and is often used for docstrings and embedded documentation. It's quite easy, but also powerful -- if I remember correctly, the core Python libraries and Django both use it.\n", "I've been using google-code-prettify, which works ...
[ 3, 1, 1 ]
[]
[]
[ "code_formatting", "markdown", "python" ]
stackoverflow_0001540834_code_formatting_markdown_python.txt
Q: Opening and Printing files using Recursion in python So I am trying to write a code that opens a file and inside that file might be empty or contains the name of other files to open on each line. For example. 1.txt has 2.txt. on the first line and 3.txt on the second line. 2.txt is a empty file and 3.txt has 4.txt...
Opening and Printing files using Recursion in python
So I am trying to write a code that opens a file and inside that file might be empty or contains the name of other files to open on each line. For example. 1.txt has 2.txt. on the first line and 3.txt on the second line. 2.txt is a empty file and 3.txt has 4.txt on the first line. I have to have an output that prints t...
[ "I am going to assume that a line contains the full path to the file. If this is not the case, then you should be able to make the necessary path modifications very easily. This IS homework, so I'll let you figure that out on your own\nTry this:\ndef search(doc):\n print \"Visiting\", doc\n f = open(doc, 'r')...
[ 4 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002083185_python_recursion.txt
Q: preprocessing RIPEMD-160 is the padding of RIPEMD-160 exactly the same as MD4 padding, down to the little-endian change? if i input "abc" in ascii, the processed data in hex should be 8063626100000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000001800000000 r...
preprocessing RIPEMD-160
is the padding of RIPEMD-160 exactly the same as MD4 padding, down to the little-endian change? if i input "abc" in ascii, the processed data in hex should be 8063626100000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000001800000000 right?
[ "Yes, per the good pseudocode file found here (for ripemd-128, but ripemd-160 just extends that),\nPadding is identical to that of MD4.\n\n" ]
[ 0 ]
[]
[]
[ "cryptography", "python" ]
stackoverflow_0002082474_cryptography_python.txt
Q: "Pre-importing" a variable into a module Python beginner here, so I apologize if this question has a simple answer. (I hope it does.) I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this mod...
"Pre-importing" a variable into a module
Python beginner here, so I apologize if this question has a simple answer. (I hope it does.) I am working on a python module--a plugin for a larger program. I'm trying to develop the module using the Eclipse IDE (with pydev), which means I need to be able to run this module stand-alone, i.e. not as a plugin from the...
[ "Presumably, when you run it \"stand-alone\" under Eclipse (or \"stand-alone\" without Eclipse, for that matter, just as \"python foobar.py\" at a shell prompt), your module's __name__ global variable has the value of '__main__' (if the module gets imported, instead, that global variable's value will be 'foobar' --...
[ 2 ]
[]
[]
[ "pydev", "python" ]
stackoverflow_0002083350_pydev_python.txt
Q: Cannot change global variables in a function through an exec() statement? Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem: >>> myvar = 'test' >>> def myfunc(): ... global myvar ... ...
Cannot change global variables in a function through an exec() statement?
Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem: >>> myvar = 'test' >>> def myfunc(): ... global myvar ... exec('myvar = "changed!"') ... print(myvar) ... >>> myfunc() test >>> pr...
[ "Per the docs, the exec statement takes two optional expressions, defaulting to globals() and locals(), and always performs changes (if any) in the locals() one.\nSo, just be more explicit/specific/precise...:\n>>> def myfunc():\n... exec('myvar=\"boooh!\"', globals())\n... \n>>> myfunc()\n>>> myvar\n'boooh!'\n\n...
[ 42, 5, 4 ]
[]
[]
[ "exec", "global", "python" ]
stackoverflow_0002083353_exec_global_python.txt
Q: Is there any difference between UserDict and Dict? If I want a class to have a dictionary behavior, why should I inherit from dict or UserDict? A: You can inherit from dict in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of __g...
Is there any difference between UserDict and Dict?
If I want a class to have a dictionary behavior, why should I inherit from dict or UserDict?
[ "You can inherit from dict in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of __getitem__ will not be used by get unless you also override that one, and so on, and so forth.\nThe UserDict.DictMixin mix-in goes back a lot further a...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0002083504_python.txt
Q: Python C-API module exit handler - an atexit equivalent? I'm using Python ver 2.6.4 There is a function I have to call from a C library when my extension module exits/is unloaded. What would be the equivalent of atexit for a C extension module? A: The Py_AtExit() function can be used to register up to 32 clean...
Python C-API module exit handler - an atexit equivalent?
I'm using Python ver 2.6.4 There is a function I have to call from a C library when my extension module exits/is unloaded. What would be the equivalent of atexit for a C extension module?
[ "The Py_AtExit() function can be used to register up to 32 cleanup functions.\n" ]
[ 4 ]
[]
[]
[ "python", "python_c_api", "python_c_extension" ]
stackoverflow_0002083523_python_python_c_api_python_c_extension.txt
Q: ftplib in combination with os.unlink in python With the following code I upload file.txt to a ftp server. When the file has been uploaded I delete it on my local machine. import os from ftplib import FTP HOST = 'host.com' FTP_NAME = 'username' FTP_PASS = 'password' filepath = 'C:\file.txt' while True: try: ...
ftplib in combination with os.unlink in python
With the following code I upload file.txt to a ftp server. When the file has been uploaded I delete it on my local machine. import os from ftplib import FTP HOST = 'host.com' FTP_NAME = 'username' FTP_PASS = 'password' filepath = 'C:\file.txt' while True: try: ftp = FTP(HOST) ftp.login(FTP_NAME, FT...
[ "import os\nfrom ftplib import FTP\n\nHOST = 'host.com'\nFTP_NAME = 'username'\nFTP_PASS = 'password'\nfilepath = 'C:\\file.txt'\nfile = open(filepath, 'r')\nwhile True:\n try:\n ftp = FTP(HOST)\n ftp.login(FTP_NAME, FTP_PASS) \n ftp.storlines('STOR file.txt', file)\n except all_er...
[ 0, 0, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002081289_exception_python.txt
Q: Checking for value within same type in python a = 0 if a == False: print a in php I can say: $a = 0; if $a === false { echo $a; } The triple === in php check for the value within the same type, thus making the integer 0 not be read as a boolean value False How can I do this in python? I would like to diff...
Checking for value within same type in python
a = 0 if a == False: print a in php I can say: $a = 0; if $a === false { echo $a; } The triple === in php check for the value within the same type, thus making the integer 0 not be read as a boolean value False How can I do this in python? I would like to differentiate between 0 the integer and False the boole...
[ "You should use the is keyword in that case. It's the identity operator, the same as === in PHP.\n>>> a = 0\n>>> if a is False:\n... print a\n...\n>>> \n\n", "type() will give you the type of an object. But if you're worried about distinguishing between 0 and False then perhaps you should use None instead.\n"...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002084017_python.txt
Q: How to remove expired items from database with Scrapy I am using spidering a video site that expires content frequently. I am considering using scrapy to do my spidering, but am not sure how to delete expired items. Strategies to detect if an item is expired are: Spider the site's "delete.rss". Every few days, t...
How to remove expired items from database with Scrapy
I am using spidering a video site that expires content frequently. I am considering using scrapy to do my spidering, but am not sure how to delete expired items. Strategies to detect if an item is expired are: Spider the site's "delete.rss". Every few days, try reloading the contents page and making sure it still wor...
[ "I haven't tested this!\nI have to confess that I haven't tried using the Django models in Scrapy, but here goes:\nThe simplest way I imagine would be to create a new spider for the deleted.rss file by extending the XMLFeedSpider (Copied from the scrapy documentation, then modified). I suggest you do create a new s...
[ 4, 0 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0002051842_python_scrapy_screen_scraping.txt
Q: sendinput to directinput(like games) I'm trying to simulate keypress to my games that use direct input. I googled around and I found out the method SendIput(). It works fine if I try to send keypress to notepad.exe but nothing happend when I tried to games. I checked this site, and I edited my code a little bit bu...
sendinput to directinput(like games)
I'm trying to simulate keypress to my games that use direct input. I googled around and I found out the method SendIput(). It works fine if I try to send keypress to notepad.exe but nothing happend when I tried to games. I checked this site, and I edited my code a little bit but still I don't get any of keypress event ...
[ "It seems you are looking for a Python answer, but personally I would try using AutoHotkey. Its scripting language is on the ugly side, but rather easy to use. There are forum posts (both on Warhammer forums and AutoHotkey forums) to indicate that other Warhammer players are using AutoHotkey.\n" ]
[ 0 ]
[]
[]
[ "c", "directinput", "keypress", "python", "sendinput" ]
stackoverflow_0002084634_c_directinput_keypress_python_sendinput.txt
Q: Running syncdb on Django project not working: Can't create/write to file When I run: $ python manage.py syncdb I get the following output: Creating table auth_permission Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-pack...
Running syncdb on Django project not working: Can't create/write to file
When I run: $ python manage.py syncdb I get the following output: Creating table auth_permission Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager util...
[ "The question was how to debug the problem and as already pointed out by Agos, Errno 2 is 'No such file or directory'. You might want to look in the data directory of MySQL and check if the directory is actually there and has correct permissions\nshell> cd /usr/local/mysql/data/\nshell> ls -ld *\ndrwx------ 17 g...
[ 4, 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002084760_django_mysql_python.txt
Q: Python: create graph based on degree correlation I want to create a graph using networkx which has positive or negative degree correlation. Like a graph for a social network or citations in academic papers etc. Can you suggest some function for this? A: If you are talking about producing a visual graph (diagram)...
Python: create graph based on degree correlation
I want to create a graph using networkx which has positive or negative degree correlation. Like a graph for a social network or citations in academic papers etc. Can you suggest some function for this?
[ "If you are talking about producing a visual graph (diagram) you could look at using matplotlib to generate them. I'm not sure if there is going to be a single function that will do what you want (not enough detail) but its a comprehensive library used in many projects to achieve complex graphing related tasks.\n"...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002085231_python.txt
Q: When loading a dll in Python does the dir function shows its methods? Does this code shows the methods from a dll? from ctypes import * x = cdll.LoadLibrary("olari.dll") dir(x) if not, how can we see the .dll methods in python? A: No, it doesn't. But It can cache when you call, and will show in dir after that. ...
When loading a dll in Python does the dir function shows its methods?
Does this code shows the methods from a dll? from ctypes import * x = cdll.LoadLibrary("olari.dll") dir(x) if not, how can we see the .dll methods in python?
[ "No, it doesn't. But It can cache when you call, and will show in dir after that.\nYou could take a look this SO Thread, even in Win32, seems like need to parse PE Header. I think python need to do similar way.\nUPDATE:\nI found pefile read/write module written in python, there you can find exported entries.\nfor e...
[ 2 ]
[]
[]
[ "dllimport", "methods", "python" ]
stackoverflow_0002085295_dllimport_methods_python.txt
Q: Python matplotlib graph problem import matplotlib import matplotlib.pyplot as plt import pylab as PL matplotlib.rcParams['axes.unicode_minus'] = False fig = plt.figure() ax = fig.add_subplot(111) PL.loglog(a, b,'o') ax.set_title('Graph Example') plt.show() 1) This displays the graph with points on the plot. Is t...
Python matplotlib graph problem
import matplotlib import matplotlib.pyplot as plt import pylab as PL matplotlib.rcParams['axes.unicode_minus'] = False fig = plt.figure() ax = fig.add_subplot(111) PL.loglog(a, b,'o') ax.set_title('Graph Example') plt.show() 1) This displays the graph with points on the plot. Is there a way to join these points with ...
[ "\nSee @Ber's comment\nSimply call PL.loglog multiple times.\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002084805_python.txt
Q: Pylons Custom Middleware return 404 I have the following code as a middleware in an pylons application: import testing.model as model import re from pylons.controllers.util import abort class SubdomainCheckMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, sta...
Pylons Custom Middleware return 404
I have the following code as a middleware in an pylons application: import testing.model as model import re from pylons.controllers.util import abort class SubdomainCheckMiddleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): if 'subdomaincheck'...
[ "It's pretty straightforward to return a basic 404 in a WSGI app: \nif error:\n start_response(\"404 Not Found\", [('Content-type', 'text/plain')])\n return ['Page not found']\n\nIf you want something more elaborate you could use some other middleware to handle errors for you. It actually looks like Pylons c...
[ 2 ]
[]
[]
[ "paster", "pylons", "python", "wsgi" ]
stackoverflow_0002085334_paster_pylons_python_wsgi.txt
Q: How to read file headers in Python similar to C? I am new to Python. I am a C programmer by profession. I have file, whose header has some specific data, that I need to extract. For example, Byte 0-5 has a magic, Byte 6-8 has offset etc. In C (An Example) : struct { int32_t payload_offset, int32_t len, ...
How to read file headers in Python similar to C?
I am new to Python. I am a C programmer by profession. I have file, whose header has some specific data, that I need to extract. For example, Byte 0-5 has a magic, Byte 6-8 has offset etc. In C (An Example) : struct { int32_t payload_offset, int32_t len, char *magic, int32_t type int32_t header...
[ "One way is to use the python struct module, docs are here.\nAnother option, if you need something more powerful, is to use the awesome construct library that can do the above and much more.\n", "This is typically done using the struct module in Python. It allows you to extract values from packed binary represent...
[ 7, 3 ]
[]
[]
[ "file_io", "header", "python" ]
stackoverflow_0002085464_file_io_header_python.txt
Q: Interpolate Question import re from decimal import * import numpy from scipy.signal import cspline1d, cspline1d_eval import scipy.interpolate import scipy import math import numpy from scipy import interpolate Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60...
Interpolate Question
import re from decimal import * import numpy from scipy.signal import cspline1d, cspline1d_eval import scipy.interpolate import scipy import math import numpy from scipy import interpolate Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60200199999999993, 0.6407140...
[ "I believe it's due to the X1 values not being ordered from smallest to largest plus also you have one duplicate x point, i.e, you need to sort the values for X1 and Y1 before you can use the splrep and remove duplicates.\nsplrep from the docs seem to be low level access to FITPACK libraries which expects a sorted,...
[ 12, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0002009379_python_scipy.txt
Q: Windows file creation date/time using python I need to get a file creation date&time using python. I tried: os.stat(r"path")[ST_CTIME] But it is returning: 1263538277 This is not the creation date time. Is there a way to do it? A: Why not? >>> import time >>> time.ctime(1263538277) 'Fri Jan 15 04:51:17 2010' ...
Windows file creation date/time using python
I need to get a file creation date&time using python. I tried: os.stat(r"path")[ST_CTIME] But it is returning: 1263538277 This is not the creation date time. Is there a way to do it?
[ "Why not?\n>>> import time\n>>> time.ctime(1263538277)\n'Fri Jan 15 04:51:17 2010'\n\nLooks like a valid creation time to me.\n", "From bytes.com:\nimport os\nimport time\ncreate_date = os.stat('/tmp/myfile.txt')[9]\nprint time.strftime(\"%Y-%m-%d\", time.gmtime(create_date))\n\nWhich gives:\n2009-11-25\n\nYou ca...
[ 10, 5, 3, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002085992_datetime_python.txt
Q: How do I customize formish error messages? I'm using formish to handle web forms but I don't like the automatically generated error messages when validation fails. Where do I customize those error messages? A: The best place for feedback on formish is in the google groups which is linked to from the http://form....
How do I customize formish error messages?
I'm using formish to handle web forms but I don't like the automatically generated error messages when validation fails. Where do I customize those error messages?
[ "The best place for feedback on formish is in the google groups which is linked to from the http://form.ish.io page.. \nAs for customising the error messages, the best way would be to create your own validator (which is pretty simple, have a look in the validatish module). However, you've inspired me to think about...
[ 0, 0 ]
[]
[]
[ "formish", "python", "webforms" ]
stackoverflow_0001923634_formish_python_webforms.txt
Q: What is the difference between these codes, and what does the repr do? 1. >>> s = u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf" >>> print s 4-12个英文字母、数字和下划线 >>> print repr(s) u'4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' 2. print repr("4-12个英文字母、...
What is the difference between these codes, and what does the repr do?
1. >>> s = u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf" >>> print s 4-12个英文字母、数字和下划线 >>> print repr(s) u'4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' 2. print repr("4-12个英文字母、数字和下划线") '4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\x...
[ "I'll take a stab at this, 'repr' is the machine representation of the object while 'print' shows the human readable representation of the object. There are built in methods 'repr', 'str', and 'unicode' that can be used by programmers to implement the different printable representations of an object. Here is a simp...
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002084728_python.txt
Q: Regex for removing whitespace def remove_whitespaces(value): "Remove all whitespaces" p = re.compile(r'\s+') return p.sub(' ', value) The above code strips tags but doesn't remove "all" whitespaces from the value. Thanks A: The fastest general approach eschews REs in favor of string's fast, powerful...
Regex for removing whitespace
def remove_whitespaces(value): "Remove all whitespaces" p = re.compile(r'\s+') return p.sub(' ', value) The above code strips tags but doesn't remove "all" whitespaces from the value. Thanks
[ "The fastest general approach eschews REs in favor of string's fast, powerful .translate method:\nimport string\nidentity = string.maketrans('', '')\n\ndef remove_whitespace(value):\n return value.translate(identity, string.whitespace)\n\nIn 2.6, it's even simpler, just\n return value.translate(None, string.white...
[ 6, 3, 1, 1, 0, 0 ]
[]
[]
[ "function", "python", "regex" ]
stackoverflow_0002081991_function_python_regex.txt
Q: what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no thanks and if i have '4-12个英文字母、数字和下划线' how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u5...
what is the encoding of this string,'base64' or 'utf-8'??? ,how can i get it readable
print "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf".decode('base64')#no thanks and if i have '4-12个英文字母、数字和下划线' how can i get the string '4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf' is print '4-12个英文字母、数字和下划线'.decode('what')# i write: print u'4-12个英...
[ "It's a Unicode representation. Try .decode('unicode-escape').\nEDIT:\nFor the second decode, what you use depends on your terminal/console settings. 'utf-8' is a sane starting point, then encode using 'unicode-escape' in order to get the Unicode escape sequences.\n", "It's encoded as a python unicode literal:\n...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002083734_javascript_python.txt
Q: Is the new GIL in Python 3.2 sufficient to make the switch? I was reading this page on the new GIL found/to be found in Python 3.2 and I was wondering if it is the "killer feature" that will trigger a transition from Python 2.x to 3.x. What do you guys think? A: It's still a GIL. Python implementations without a...
Is the new GIL in Python 3.2 sufficient to make the switch?
I was reading this page on the new GIL found/to be found in Python 3.2 and I was wondering if it is the "killer feature" that will trigger a transition from Python 2.x to 3.x. What do you guys think?
[ "It's still a GIL. Python implementations without any GIL at all have been available for over a decade now. Python implementations that are much faster than CPython have been available for years.\n(Almost) noone uses them, which clearly shows that nobody cares about performance or the GIL, so I hardly see them bein...
[ 9, 3, 0 ]
[]
[]
[ "gil", "python" ]
stackoverflow_0002086840_gil_python.txt