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: Python version of C#'s conditional operator (?) I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test. I have this code in Python: if self.trait == self.spouse.trait: trait = self.trait else: trait = defualtTrait In C# I could write this as: trait = th...
Python version of C#'s conditional operator (?)
I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test. I have this code in Python: if self.trait == self.spouse.trait: trait = self.trait else: trait = defualtTrait In C# I could write this as: trait = this.trait == this.spouse.trait ? this.trait : defualtT...
[ "Yes, you can write:\ntrait = self.trait if self.trait == self.spouse.trait else defaultTrait\n\nThis is called a Conditional Expression in Python.\n", "On the null-coalescing operator in C#, what you have in the question isn't a correct usage. That would fail at compile time.\nIn C#, the correct way to write wh...
[ 14, 1 ]
[]
[]
[ "conditional_operator", "python" ]
stackoverflow_0007692121_conditional_operator_python.txt
Q: Managing Mac OS created filenames with non ASCII characters in windows environments? I deal with large collection of unknown files, and have been been learning python to help me filter / sort and otherwise wrangle these files. A collection I am looking at has a large number of resource forks, and I wrote a little...
Managing Mac OS created filenames with non ASCII characters in windows environments?
I deal with large collection of unknown files, and have been been learning python to help me filter / sort and otherwise wrangle these files. A collection I am looking at has a large number of resource forks, and I wrote a little script to find them, and delete them (next step is find them, and to move them, but thats...
[ "os.walk(u'.') is the normal way to get native-Unicode filenames and it should work fine; it does for me.\nYour problem is here instead:\nsrcNewline = src + \", \" + str(filename) + \"\\n\"\n\nstr(filename) will use the default encoding to convert your Unicode string back down to bytes, and because that encoding do...
[ 3 ]
[]
[]
[ "filenames", "macos", "python", "unicode" ]
stackoverflow_0007681698_filenames_macos_python_unicode.txt
Q: python closure + oop I'm trying to do something a bit strange (at least to me) with python closure. Say I have 2 classes like this: #!/usr/bin/python import types def method_a(self): print "ma %d" % self.val class A(object): def __init__(self): self.val = 5 pass def foo(self, a): ...
python closure + oop
I'm trying to do something a bit strange (at least to me) with python closure. Say I have 2 classes like this: #!/usr/bin/python import types def method_a(self): print "ma %d" % self.val class A(object): def __init__(self): self.val = 5 pass def foo(self, a): def closure(self): ...
[ "Give the inner self another name:\ndef foo(self, a):\n def closuer(b):\n print \"closure %d, %d\" % (self.val, a)\n return closuer\n\nAlso, rather then using types.MethodType, you might want to use functools.partial\n" ]
[ 7 ]
[]
[]
[ "closures", "oop", "python" ]
stackoverflow_0007692423_closures_oop_python.txt
Q: Individual point-sizing in Matplotlib? I'd like to have non-uniform point sizes in matplotlib (set a size for each point). Is there a way to do this? I guess I could hack it by having a separate plot command (with markersize set) for each point, but that would be really annoying. Is there a more principled way? A...
Individual point-sizing in Matplotlib?
I'd like to have non-uniform point sizes in matplotlib (set a size for each point). Is there a way to do this? I guess I could hack it by having a separate plot command (with markersize set) for each point, but that would be really annoying. Is there a more principled way?
[ "I just found out that you can use scatter for this:\n scatter(500:600,600:700,1:101);\n\nwhere the format is: scatter(x,y,sizes,markerType)\nProduces:\n\n" ]
[ 7 ]
[]
[]
[ "matlab", "matplotlib", "plot", "python" ]
stackoverflow_0007692174_matlab_matplotlib_plot_python.txt
Q: Utility to fix Python import style? We have a lot of files with ugly import statements like this: from project.foo import a, b from project.foo import c from project.bar import d, e, f, g Does there exist something that will change them all to one import per line? from project.foo import a from project.foo import...
Utility to fix Python import style?
We have a lot of files with ugly import statements like this: from project.foo import a, b from project.foo import c from project.bar import d, e, f, g Does there exist something that will change them all to one import per line? from project.foo import a from project.foo import b from project.foo import c from project...
[ "As per PEP8 style guide:\n\nImports\n- Imports should usually be on separate lines, e.g.:\n\n Yes: import os\n import sys\n\n No: import sys, os\n\n it's okay to say this though:\n\n from subprocess import Popen, PIPE\n\n\nSo, I think you should be doing what you are and should not split them. I...
[ 7, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0007692472_coding_style_python.txt
Q: SQLAlchemy: Efficient way of merging duplicate tags Let's say I have a database full of Tag objects. Each Tag has an id and a name. In the beginning of making the database I allowed for case sensitive Tags, however, I later realized I didn't need/want this capability, so I started forcing each name to be lowercase...
SQLAlchemy: Efficient way of merging duplicate tags
Let's say I have a database full of Tag objects. Each Tag has an id and a name. In the beginning of making the database I allowed for case sensitive Tags, however, I later realized I didn't need/want this capability, so I started forcing each name to be lowercase before storing the Tag. Now I have all these remnants of...
[ "If it's a tool for one-time use, do you really have to care about efficiency? Just let it run for a minute (or several), rather than spending even more time optimizing it.\nThat being said, queries are more expensive than Python loops, so loading all the Tags into a list first, and then looping over that list both...
[ 2 ]
[]
[]
[ "algorithm", "database", "database_design", "python", "sqlalchemy" ]
stackoverflow_0007692489_algorithm_database_database_design_python_sqlalchemy.txt
Q: How to detect window creation and closing? I can't find a way to add a callback for when a window is closed - and also not a reliable way to react to newly created windows. My application creates a few processes using subprocess.Popen. Each process has a visible window. The processes share some events with pyHook...
How to detect window creation and closing?
I can't find a way to add a callback for when a window is closed - and also not a reliable way to react to newly created windows. My application creates a few processes using subprocess.Popen. Each process has a visible window. The processes share some events with pyHook, using PumpMessages for this. I use this method...
[ "The only way I have ever found in doing this, and I have been looking into this for many years now, is to use the Python bindings for the Microsoft active accessibility layer (pyAA). This project is no longer actively maintained, so you will have to build it yourself for your version of Windows, but it is the only...
[ 1 ]
[]
[]
[ "python", "pywin32" ]
stackoverflow_0007669224_python_pywin32.txt
Q: Django Admin TabularInline Complaining About Missing Field I have the following model and TabularInline subclasses: class SomeModel(models.Model): name = models.CharField(max_length=50) class SomeModelInline(admin.TabularInline): model = SomeModel class SomeOtherModelAdmin(admin.ModelAdmin): inlines ...
Django Admin TabularInline Complaining About Missing Field
I have the following model and TabularInline subclasses: class SomeModel(models.Model): name = models.CharField(max_length=50) class SomeModelInline(admin.TabularInline): model = SomeModel class SomeOtherModelAdmin(admin.ModelAdmin): inlines = [SomeModelInline] Without explicitly specifying the TabularIn...
[ "Ids are non-editable, by default inline shows the editable fields, but you can show the non-editable fields as well\nFrom django docs \n\nfields can contain values defined in ModelAdmin.readonly_fields to be\n displayed as read-only.\n\nSo first add 'id' to readonly_fields, then add it to fields\n" ]
[ 4 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007692771_django_django_admin_python.txt
Q: Timer in Python for a Game this is a timer inside a game I programmed: def function(event): time.sleep(.2) tx2 = time.time() if tx2-tx1 > 0.7: #do the repetitive stuff here return function(1) tx1 = time.time() thread.start_new_thread(function,(1,)) is there a better way to write this? to...
Timer in Python for a Game
this is a timer inside a game I programmed: def function(event): time.sleep(.2) tx2 = time.time() if tx2-tx1 > 0.7: #do the repetitive stuff here return function(1) tx1 = time.time() thread.start_new_thread(function,(1,)) is there a better way to write this? to me it seems a bit dirty calling...
[ "Your current example runs into the issue of recursion limits, because of the way it calls itself recursively. The stack size continues to grow and grow until it hits the default 1000, most likely. See this modified example:\nimport time\nimport inspect\nimport thread\n\ntx1 = time.time()\n\ndef loop(event):\n p...
[ 3 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0007692763_python_timer.txt
Q: global name 'find' is not defined I am using a piece of code and am trying to debug it. But something weird is happening. In one part, I have this line: vals = find(A) But it gives me this error : global name 'find' is not defined I thought find was like an inbuilt function in python?? Clearly I am mistaken. Bu...
global name 'find' is not defined
I am using a piece of code and am trying to debug it. But something weird is happening. In one part, I have this line: vals = find(A) But it gives me this error : global name 'find' is not defined I thought find was like an inbuilt function in python?? Clearly I am mistaken. But just want to check.. in case I am for...
[ "find is a string method:\n'python'.find('y') # gives 1\n\n", "The real answer is:\nlook in this page:\nhttp://docs.python.org/genindex.html\nWhy thinking to search with Google and not in an official doc ? Did you think that Python hadn't documentation ?\n" ]
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007692772_python.txt
Q: how to add remove url from urls.py in views.py I have a model named Agency.agency has a field named URL,for example I add 2 Agencies that the first one give the value of A to URL and the second one give the value of B to URL field.now I wanna override save_model method in index in views.py to add Agencie's URL to ...
how to add remove url from urls.py in views.py
I have a model named Agency.agency has a field named URL,for example I add 2 Agencies that the first one give the value of A to URL and the second one give the value of B to URL field.now I wanna override save_model method in index in views.py to add Agencie's URL to urls.py when adding an Agency,like this: (r'^airAgen...
[ "As others have said and/or pointed to, don't hardcode specific Agencies into your urls.py\nKeep it generic and DRY by allowing variables in your urls\n# urls\n(r'^airAgency/(?P<name>[a-zA-Z0-9]+)/$', 'airAgency.views.index'),\n # this passes the value there as 'name' to the view for index\n\n#views\ndef index(re...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007683873_django_python.txt
Q: In Python, how can I use an attribute as both and attribute and a method/callable? This is kindof an experiment. I'm interested in an API that supports both of these syntaxes: obj.thing --> returns default value obj.thing(2, 'a') --> returns value derived from *args and **kwargs "thing" is the same object in bot...
In Python, how can I use an attribute as both and attribute and a method/callable?
This is kindof an experiment. I'm interested in an API that supports both of these syntaxes: obj.thing --> returns default value obj.thing(2, 'a') --> returns value derived from *args and **kwargs "thing" is the same object in both cases; I'd like the calling of thing to be optional (or implicit, if there are not () ...
[ "What you describe could work, but notice that now the value of the attribute is constrained to be an object of your CallableDefault class. This probably won't be very useful.\nI strongly suggest that you don't try to do this. For one thing, you're spending a lot of time trying to trick Python into doing somethin...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007692983_python.txt
Q: urllib2 header error: TypeError: sendall() argument 1 must be string or buffer, not dict def download(url): print url user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' headers = {'User-Agent' : user_agent } request = urllib2.Request(url, he...
urllib2 header error: TypeError: sendall() argument 1 must be string or buffer, not dict
def download(url): print url user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' headers = {'User-Agent' : user_agent } request = urllib2.Request(url, headers) response = urllib2.urlopen(request) return response What am I doing wrong here...
[ "You aren't using the exact example. The example has:\nreq = urllib2.Request(url, data, headers)\n\nwhile you have:\nrequest = urllib2.Request(url, headers)\n\nBecause these are positional arguments, it's important that you keep them straight. The second argument is a string of data, you need to supply that:\nreq...
[ 8 ]
[]
[]
[ "header", "python", "urllib2" ]
stackoverflow_0007693288_header_python_urllib2.txt
Q: Using Django Managers vs. staticmethod on Model class directly After reading up on Django Managers, I'm still unsure how much benefit I will get by using it. It seems that the best use is to add custom queries (read-only) methods like XYZ.objects.findBy*(). But I can easily do that with static methods off of the ...
Using Django Managers vs. staticmethod on Model class directly
After reading up on Django Managers, I'm still unsure how much benefit I will get by using it. It seems that the best use is to add custom queries (read-only) methods like XYZ.objects.findBy*(). But I can easily do that with static methods off of the Model classes themselves. I prefer the latter always because: code ...
[ "Adding custom queries to managers is the Django convention. From the Django docs on custom managers:\n\nAdding extra Manager methods is the preferred way to add \"table-level\" functionality to your models.\n\nIf it's your own private app, the convention word doesn't matter so much - indeed my company's internal c...
[ 42 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007692487_django_python.txt
Q: DatabaseError: table OmniCloud_App_user has no column named username So I got this when trying to add a User to the database. And I thought, I wonder what columns it does have? So I asked for the sql... DatabaseError: table OmniCloud_App_user has no column named username >>> root@Harold:~/OmniCloud/omnicloud# pyt...
DatabaseError: table OmniCloud_App_user has no column named username
So I got this when trying to add a User to the database. And I thought, I wonder what columns it does have? So I asked for the sql... DatabaseError: table OmniCloud_App_user has no column named username >>> root@Harold:~/OmniCloud/omnicloud# python manage.py sql OmniCloud_App BEGIN; CREATE TABLE "OmniCloud_App_user" (...
[ "\nHave you run a $> python manage.py syncdb?\nHave you changed the model (added the username) since you first ran syncdb?\nAre you using South? If not, you should probably learn about it.\n\nSyncdb only works on new models. You've got to sort out migrations yourself, and that's where South comes in.\nAlternatively...
[ 2, 0 ]
[]
[]
[ "django", "python", "sqlite", "terminal" ]
stackoverflow_0007693157_django_python_sqlite_terminal.txt
Q: Python 2.7: L += branch_length results in NameError: name 'L' not defined It's a populations genetics program handed out by my professors and modified by the students. Basically it's supposed to simulate the expected number of mutations twenty times with a given sample, population, and mutation rate (u). However, ...
Python 2.7: L += branch_length results in NameError: name 'L' not defined
It's a populations genetics program handed out by my professors and modified by the students. Basically it's supposed to simulate the expected number of mutations twenty times with a given sample, population, and mutation rate (u). However, a critical piece is the total branch length (L), which is the sum of the variou...
[ "L += x adds x to the existing L, but you haven't initialized L. Presumably, you want L = 0 somewhere at the top of your file.\n", "You need to define L = 0 before doing L += x.\nIn general, before modifying you need to define the variable. For assignment, there is no problem because python will infer the type f...
[ 4, 1 ]
[]
[]
[ "nameerror", "python", "python_2.7" ]
stackoverflow_0007693273_nameerror_python_python_2.7.txt
Q: Mod_wsgi versus fapws3 - Django is there a difference between using FAPWS3 and MOD_WSGI when dealing with Django? FAPWS3 seems alot faster when serving requests toward Python scripts. I would like to know if I'm missing out anything. :) Any ideas? A: The underlying web server is not the bottleneck, it is your a...
Mod_wsgi versus fapws3 - Django
is there a difference between using FAPWS3 and MOD_WSGI when dealing with Django? FAPWS3 seems alot faster when serving requests toward Python scripts. I would like to know if I'm missing out anything. :) Any ideas?
[ "The underlying web server is not the bottleneck, it is your application and database access. The differences between any underlying web server are going to very minimal or non existent in the context of an actual full application stack. You cannot base decisions on hello world type tests as they are pretty meaning...
[ 3, 2 ]
[]
[]
[ "django", "fapws3", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0002629070_django_fapws3_mod_wsgi_python_wsgi.txt
Q: Convert a youtube video into mp3 file? Does Any one know how to convert a Youtube video into an mp3 file. The solution needs to be in python. let me give more details is there a module or way to extract the embedded video that is in the youtube webpage? A: Looks like this script will do it: http://code.google.co...
Convert a youtube video into mp3 file?
Does Any one know how to convert a Youtube video into an mp3 file. The solution needs to be in python. let me give more details is there a module or way to extract the embedded video that is in the youtube webpage?
[ "Looks like this script will do it: http://code.google.com/p/pymp/\nEdit: Probably not what you're looking for, assuming you wanted a non-graphical script that ran in the background of one of your programs.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007693867_python.txt
Q: Python make method immutable I have the following code: class Hello(object): def __init__(self, names): self.names = names def getnames(self): return self.names if __name__ == "__main__": names = ['first', 'middle', 'last'] ob = Hello(names) a = ob.getnames() print a...
Python make method immutable
I have the following code: class Hello(object): def __init__(self, names): self.names = names def getnames(self): return self.names if __name__ == "__main__": names = ['first', 'middle', 'last'] ob = Hello(names) a = ob.getnames() print a a.remove('first') print a...
[ "have getnames return a copy:\ndef getnames(self):\n return self.names[:]\n\n", "In Python, assignment never makes a copy of a data structure. It only makes a name refer to a value. Also, function invocation essentially assigns the actual arguments to the argument names. So nothing is copied in your code. T...
[ 3, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007693937_python.txt
Q: Reordering items in a QTreeWidget with Drag and Drop in PyQt I have a QTreeWidget with what I thought all the proper settings setup in order to be able to reorder items by dragging them around. It can work, at times, but more often than not I drag an item into another one and it either disappears or becomes a chil...
Reordering items in a QTreeWidget with Drag and Drop in PyQt
I have a QTreeWidget with what I thought all the proper settings setup in order to be able to reorder items by dragging them around. It can work, at times, but more often than not I drag an item into another one and it either disappears or becomes a child. Is there anyway to prevent this from happening so you don't lo...
[ "You can add flags to individual tree widget items that control drag and drop behaviour (amongst other things). For instance, to prevent an item being a drop target, try something like this:\nitem = QTreeWidgetItem(parent)\nitem.setFlags(items.flags() & ~Qt.ItemIsDropEnabled)\n\nFor more details, see: Qt.ItemFlags\...
[ 3 ]
[]
[]
[ "drag_and_drop", "pyqt", "python", "qtreewidget" ]
stackoverflow_0007666823_drag_and_drop_pyqt_python_qtreewidget.txt
Q: Why django admin sometimes uses some field of the model in the index, instead of __unicode__ method? For some of my models, Django-admin, in the index of the model's objects, instead of displaying the output of the __unicode__ method like normally, it just displays one of the model's fields there. This happens us...
Why django admin sometimes uses some field of the model in the index, instead of __unicode__ method?
For some of my models, Django-admin, in the index of the model's objects, instead of displaying the output of the __unicode__ method like normally, it just displays one of the model's fields there. This happens usually when there is something like: class Meta: ordering = ['name'] in my model, then the value of th...
[ "You can customise the fields displayed in the django admin using the list_display option in your ModelAdmin class.\nThe model __unicode__ method, and the Meta.ordering option do not have any affect on the fields displayed.\nIf you do not set list_display, then the default behaviour is to display a single column wi...
[ 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007693946_django_django_admin_python.txt
Q: Stop python GUI program from exiting when run from CLI How can easily I make a blocking GUI app on OS X? I have a simple python plotting program. When I run it from inside an existing python interactive session, or from within iPython, the GUI window is displayed, and I can see it and interact with it. When I run ...
Stop python GUI program from exiting when run from CLI
How can easily I make a blocking GUI app on OS X? I have a simple python plotting program. When I run it from inside an existing python interactive session, or from within iPython, the GUI window is displayed, and I can see it and interact with it. When I run the .py file from the CLI, the GUI flashes and closes immedi...
[ "It sounds as though interactive mode has been enabled somehow, although I'm not sure where. Try it like this:\ndef main():\n import matplotlib.pyplot as plt\n data = range(1,10)\n fig = plt.plot(data)\n plt.ioff() # turns interactive mode OFF, should make show() blocking\n plt.show()\n\n\nif __nam...
[ 3 ]
[]
[]
[ "command_line", "macos", "matplotlib", "python", "user_interface" ]
stackoverflow_0007693543_command_line_macos_matplotlib_python_user_interface.txt
Q: How to change `object_name` of a model in Django I have an object LeatherChair in Django, and it pisses me off that Django gives it an object_name of leatherchair. I want it to be leather_chair, with an underscore. The object_name seems to be stored in the Options instance, but how do I change that? A: Trying to...
How to change `object_name` of a model in Django
I have an object LeatherChair in Django, and it pisses me off that Django gives it an object_name of leatherchair. I want it to be leather_chair, with an underscore. The object_name seems to be stored in the Options instance, but how do I change that?
[ "Trying to change object_name is a really bad idea. It is set in the Model._meta as you say, but it is not one of the documented available Meta options. Trying to change it risks breaking stuff.\nI don't understand why it is so important to change it. It's not displayed publicly, so it doesn't really matter whether...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007693921_django_python.txt
Q: __getattr__ in parent class causing subclass __init__ recursion error Following an advice in the answer: subclassing beautifulsoup html parser, getting type error, I'm trying to use class composition instead of subclassing BeautifulSoup. The basic Scraper class works fine on it's own (at least to my limited testin...
__getattr__ in parent class causing subclass __init__ recursion error
Following an advice in the answer: subclassing beautifulsoup html parser, getting type error, I'm trying to use class composition instead of subclassing BeautifulSoup. The basic Scraper class works fine on it's own (at least to my limited testing). The Scraper class: from BeautifulSoup import BeautifulSoup import urlli...
[ "Part 1\nYour code doesn't work because __getattr__() accesses self._soup before it has been initialized. This happens due to four innocuous-looking lines:\ntry:\n self._page = urllib2.urlopen(self._file)\nexcept (urllib2.URLError):\n print ('please enter a valid url starting with http/https/ftp/file') \n\nWhy do...
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007694170_beautifulsoup_python.txt
Q: Python, Unicode and parsing with lxml and how to deal with 35\xa0new I am extracting a field on a webpage ad the tag html text content looks like this... 35&nbsp;new In python the extracted data looks like this... 35\xa0new How to I deal with unicode in python to convert to a regular string? "35 new" what librar...
Python, Unicode and parsing with lxml and how to deal with 35\xa0new
I am extracting a field on a webpage ad the tag html text content looks like this... 35&nbsp;new In python the extracted data looks like this... 35\xa0new How to I deal with unicode in python to convert to a regular string? "35 new" what library to I use? Thanks
[ "Avoid working with regular strings whenever possible; unicodes are generally more useful for text, and there are many well-known solutions for manipulating and dealing with them.\n", "You are getting unicode strings from the parser. You can replace certain characters if you prefer others. For example, your \\x...
[ 3, 0 ]
[]
[]
[ "html", "lxml", "python", "unicode" ]
stackoverflow_0007694260_html_lxml_python_unicode.txt
Q: F# map/set comprehensions I'm looking for something akin to the dict/list/set comprehensions in Python. In Python you can do: [x+2 for x in list if x > 10] and in F# [for x in list do if x > 10 yield x+2] but in Python, you can also do: {x+2 for x in list if x > 10} to generate Sets, and {k: (v+10)/2 for k, v ...
F# map/set comprehensions
I'm looking for something akin to the dict/list/set comprehensions in Python. In Python you can do: [x+2 for x in list if x > 10] and in F# [for x in list do if x > 10 yield x+2] but in Python, you can also do: {x+2 for x in list if x > 10} to generate Sets, and {k: (v+10)/2 for k, v in list.items() if k > 5} to g...
[ "There is a set function accepting seq<_>, so you can do:\nset [for x in list do if x > 10 yield x+2]\n\nSame with dict. Here are the relevant docs:\nset: http://msdn.microsoft.com/en-us/library/ee353747.aspx\ndict: http://msdn.microsoft.com/en-us/library/ee353774.aspx\n", "Essentially F# does not have a special ...
[ 5, 3 ]
[]
[]
[ "f#", "functional_programming", "list_comprehension", "python" ]
stackoverflow_0007694289_f#_functional_programming_list_comprehension_python.txt
Q: Is there a good IDE for building GUI apps with Python I am a beginner programmer and have learned most of what I know thus far from using delphi for the past couple of months. A month or so back I decided to give python a try as I was told it may be easier to learn and I really like the language. I guess I just se...
Is there a good IDE for building GUI apps with Python
I am a beginner programmer and have learned most of what I know thus far from using delphi for the past couple of months. A month or so back I decided to give python a try as I was told it may be easier to learn and I really like the language. I guess I just seem to pick things up easier using it. The only problem is t...
[ "Boa Constructor is a classic RAD IDE for GUI applications (wxpython, both linux and windows). People is still using it but seems that development stopped some years ago. PythonCard is another RAD IDE I used in the past but also unmaintained right now \nAlthough they are not IDEs, some tools are very helpful for GU...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0007658028_ironpython_python.txt
Q: pip doesn't grab latest version of tweepy? Using 'pip install tweepy' I get version 1.7.1 of tweepy which is quite old and certainly doesn't support oauth. Has a new version of the package not been published? It's still under active development. Do I need pull the source from GIT? I'm just surprised there isn't ...
pip doesn't grab latest version of tweepy?
Using 'pip install tweepy' I get version 1.7.1 of tweepy which is quite old and certainly doesn't support oauth. Has a new version of the package not been published? It's still under active development. Do I need pull the source from GIT? I'm just surprised there isn't a newer package. Am I missing something? Thanks...
[ "1.7.1 is the latest version on pypi, and the last tag listed in on github. I'd say pip is doing exactly what it's supposed to be doing.\n" ]
[ 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0007694533_python_tweepy_twitter.txt
Q: Difference between using deepcopy and substring operation I am using Python 2.7 I have a list lst = ['a','b','c'] If I need a copy if this list, I used to do lst_cpy = lst[:]. I came across a function deepcopy in the package copy which enables me to achieve the same. import copy lst_cpy_2 = copy.deepcopy(lst) Can...
Difference between using deepcopy and substring operation
I am using Python 2.7 I have a list lst = ['a','b','c'] If I need a copy if this list, I used to do lst_cpy = lst[:]. I came across a function deepcopy in the package copy which enables me to achieve the same. import copy lst_cpy_2 = copy.deepcopy(lst) Can I use these two methods interchangeably or is there any differ...
[ "In the case of a simple list, they are the same. If your list had other structures within it, for example, elements which were lists or dictionaries, they would be different.\nL[:] makes a new list, and each element in the new list is a new reference to the values in the old list. If one of those values is mutab...
[ 5, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007694626_list_python.txt
Q: Python and using lxml to find part if a string using lxml html I have a tab that looks like this... <div id="contentDiv_reviewHistoPop_B004HYGU18_4792" style="display:none;"> I can use doc = lxml.html.document_fromstring(html) el = doc.get_element_by_id('contentDiv_reviewHistoPop_B004HYGU18_4792') to find the ...
Python and using lxml to find part if a string using lxml html
I have a tab that looks like this... <div id="contentDiv_reviewHistoPop_B004HYGU18_4792" style="display:none;"> I can use doc = lxml.html.document_fromstring(html) el = doc.get_element_by_id('contentDiv_reviewHistoPop_B004HYGU18_4792') to find the tag but how do I use e.g. a wild card to find contentDiv_reviewHisto...
[ "You should do this...\nimport lxml.etree as ET\nfrom lxml.etree import XMLParser\n\nparser = XMLParser(ns_clean=True, recover=True)\nhtml = \"\"\"<html><body><div id=\"contentDiv_reviewHistoPop_B004HYGU18_4792\" style=\"display:none;\"></body></html>\"\"\"\ntree = ET.fromstring(html, parser)\ntmp = list()\nfor ele...
[ 1 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0007694608_html_lxml_python.txt
Q: Regular expressions -- how to allow non-adjacent alternatives? In a translation-testing app (in Python) I want a regular expression that will accept either of these two strings: a = "I want the red book" b = "the book which I want is red" So far I'm using something like this: ^(the book which )*I want (is |the )r...
Regular expressions -- how to allow non-adjacent alternatives?
In a translation-testing app (in Python) I want a regular expression that will accept either of these two strings: a = "I want the red book" b = "the book which I want is red" So far I'm using something like this: ^(the book which )*I want (is |the )red (book)*$ This will accept both string a and string b. But it wil...
[ "\nHow can I indicate that one of these two substrings must be present,\n even though they're not adjacent?\n\nI am assuming that is the core question you have.\nThe solution is two regex's. Why people feel that once the say import re that the regex has to be a single line is just beyond me.\nFirst test for the fi...
[ 5, 3, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0007694168_python_regex_string.txt
Q: Insert mode in curses.textpad in python While doing this in python: tp = curses.textpad.Textbox(stdscr, insert_mode=True) text = tp.edit() I get RuntimeError: maximum recursion depth exceeded while calling a Python object Could you please tell me how to enable insert mode in curses.textpad? Thanks in advance. A...
Insert mode in curses.textpad in python
While doing this in python: tp = curses.textpad.Textbox(stdscr, insert_mode=True) text = tp.edit() I get RuntimeError: maximum recursion depth exceeded while calling a Python object Could you please tell me how to enable insert mode in curses.textpad? Thanks in advance.
[ "Patch in http://bugs.python.org/issue13051 solves the issue. Thanks to Narendra Sisodiya :)\n" ]
[ 1 ]
[]
[]
[ "ncurses", "python" ]
stackoverflow_0007673536_ncurses_python.txt
Q: fiddler doesn't capture python http request? I've tried to use fiddle2 to debug one of my python program which makes http request and gets response. However I didn't see any traffic on fiddler no matter I ran python in command prompt or python GUI. Fiddle filter is not set, i.e., set to show all processes, I did s...
fiddler doesn't capture python http request?
I've tried to use fiddle2 to debug one of my python program which makes http request and gets response. However I didn't see any traffic on fiddler no matter I ran python in command prompt or python GUI. Fiddle filter is not set, i.e., set to show all processes, I did see my browsers' traffic there. Is there any settin...
[ "Python does not use proxy by default, so fiddler cannot intercept its network traffic. You may need to change the Python program a little. Here is another thread on how to see proxy for Python programs Proxy with urllib2.\n", "It will only work if you set Python to use Fiddler as a proxy. It may be easier to us...
[ 8, 5 ]
[]
[]
[ "fiddler", "http", "python" ]
stackoverflow_0007694789_fiddler_http_python.txt
Q: How do you reverse the letters in a string? Possible Duplicate: reverse a string in Python I'm trying to understand how to reverse the letters in a string. Let's say that I have hello and am looking for the output olleh how would I implement this using the list as a tool? A: Using slice notation, forwards = "h...
How do you reverse the letters in a string?
Possible Duplicate: reverse a string in Python I'm trying to understand how to reverse the letters in a string. Let's say that I have hello and am looking for the output olleh how would I implement this using the list as a tool?
[ "Using slice notation,\nforwards = \"hello\"\nbackwards = forwards[::-1]\n\n(The third section of slice notation is the step; in this case, -1 makes it step backwards through the entirety of the string, effectively reversing it.)\nor, using the reversed() function:\nbackwards = ''.join(reversed(forwards))\n\n(Note ...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007695017_python.txt
Q: Mysql, python, SQL not executing Hi I have this basic mysql code: sql = 'INSERT INTO popularity (PersonNumber, Category, Value) VALUES (1,"Tennis","great")' connection = MySQLdb.connect(host = "localhost", user = "***", passwd = "***", db = "inb104") cursor = connection.cursor() cursor.execute(sql) cursor.close()...
Mysql, python, SQL not executing
Hi I have this basic mysql code: sql = 'INSERT INTO popularity (PersonNumber, Category, Value) VALUES (1,"Tennis","great")' connection = MySQLdb.connect(host = "localhost", user = "***", passwd = "***", db = "inb104") cursor = connection.cursor() cursor.execute(sql) cursor.close() connection.close() However, this doe...
[ "connection.commit()\n\nthat will do the trick =D\n", "You need to commit the transaction.\n", "Because you forgot to commit the transaction before closing the cursor.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0007695098_mysql_mysql_python_python.txt
Q: Processing a HTML file using Python I wanted to remove all the tags in HTML file. For that I used re module of python. For example, consider the line <h1>Hello World!</h1>.I want to retain only "Hello World!". In order to remove the tags, I used re.sub('<.*>','',string). For obvious reasons the result I get is an...
Processing a HTML file using Python
I wanted to remove all the tags in HTML file. For that I used re module of python. For example, consider the line <h1>Hello World!</h1>.I want to retain only "Hello World!". In order to remove the tags, I used re.sub('<.*>','',string). For obvious reasons the result I get is an empty string (The regexp identifies the ...
[ "Parse the HTML using BeautifulSoup, then only retrieve the text.\n", "You can make the match non-greedy: '<.*?>'\nYou also need to be careful, HTML is a crafty beast, and can thwart your regexes.\n", "make it non-greedy: http://docs.python.org/release/2.6/howto/regex.html#greedy-versus-non-greedy\noff-topic: t...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007694637_python_regex.txt
Q: How do you reverse the words in a string using python (manually)? Possible Duplicate: Reverse the ordering of words in a string I know there are methods that python already provides for this, but I'm trying to understand the basics of how those methods work when you only have the list data structure to work with...
How do you reverse the words in a string using python (manually)?
Possible Duplicate: Reverse the ordering of words in a string I know there are methods that python already provides for this, but I'm trying to understand the basics of how those methods work when you only have the list data structure to work with. If I have a string hello world and I want to make a new string world...
[ "Split the string, make a reverse iterator then join the parts back.\n' '.join(reversed(my_string.split()))\n\nIf you are concerned with multiple spaces, change split() to split(' ')\n\nAs requested, I'm posting an implementation of split (by GvR himself from the oldest downloadable version of CPython's source code...
[ 14, 7, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007694977_python.txt
Q: Which Version of Python to Use for Maximum Compatibility If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) b...
Which Version of Python to Use for Maximum Compatibility
If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current versi...
[ "As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the time line there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october.\nBeside not having python 3 available on you...
[ 6, 4, 1, 1, 0, 0 ]
[]
[]
[ "compatibility", "python" ]
stackoverflow_0000047198_compatibility_python.txt
Q: Future Development in Python 2.4 I'm starting a new python project at work that is targeted primarily at RHEL5 machines that may be upgraded to RHEL6 in couple years. Given that python 2.4 is standard on RHEL5 and the system admins won't support more than they have to, getting python 2.6 in our local repo will ta...
Future Development in Python 2.4
I'm starting a new python project at work that is targeted primarily at RHEL5 machines that may be upgraded to RHEL6 in couple years. Given that python 2.4 is standard on RHEL5 and the system admins won't support more than they have to, getting python 2.6 in our local repo will take some convincing. While it seems I ...
[ "What's in Which Python?\n", "Your best bet is probably to stick with 2.4, and have a time_machine module with all the goodies that later pythons have that you want. For example, when properties first came out you had to do something like:\ndef _get_prop(self):\n return self._prop\ndef _set_prop(self, value):...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "pygtk", "pysqlite", "python", "python_2.4", "python_2.6" ]
stackoverflow_0007694006_pygtk_pysqlite_python_python_2.4_python_2.6.txt
Q: How to compose a buildout.cfg for zc.buildout with SVN-based sub projects I want to make an zc.buildout configuration for production use. In my case, I have two sub-projects from two separate SVN repositories. I want to deploy these into the same web site. Basically, these are two sub-sites that will go into th...
How to compose a buildout.cfg for zc.buildout with SVN-based sub projects
I want to make an zc.buildout configuration for production use. In my case, I have two sub-projects from two separate SVN repositories. I want to deploy these into the same web site. Basically, these are two sub-sites that will go into the same web server. I can manually put this together on my PC, but I'd like to ...
[ "Try your luck with mr.developer, it can check out and update your svn projects during buildout automatically.\nSomething like:\n[buildout]\nextensions = mr.developer\nauto-checkout =\n foo\n bar\nparts = baaz\n\n[sources]\nfoo = svn https://svn.foo.com/trunk/\nbar = svn https://svn.bar.org/trunk/\n\n[baaz]\nreci...
[ 0 ]
[]
[]
[ "build", "build_automation", "python" ]
stackoverflow_0007694714_build_build_automation_python.txt
Q: How to get the flv file from a youtube page How would you get the "flv" file from A youtube page for example:www.youtube.com/watch?v=T8YCSJpF4g4... Any ideas? So far ive tried: import urllib import os import sys page=urllib.urlopen('http://www.youtube.com/watch?v=FuLDIgfPae8') result = page.read() #result=open("t...
How to get the flv file from a youtube page
How would you get the "flv" file from A youtube page for example:www.youtube.com/watch?v=T8YCSJpF4g4... Any ideas? So far ive tried: import urllib import os import sys page=urllib.urlopen('http://www.youtube.com/watch?v=FuLDIgfPae8') result = page.read() #result=open("test.html").read() print result startindex = resul...
[ "The problem with your current code is that indeed, var swfArgs does not appear in the source of that web page. YouTube is constantly changing their pages, so I'm going to tell you how to find what you'll need to do, rather than what YouTube currently does.\nOpen the page in a browser with good debugging tools. For...
[ 4, 3 ]
[]
[]
[ "python", "youtube" ]
stackoverflow_0007694213_python_youtube.txt
Q: How to make a post build script for buildout I'm using zc.buildout for my project. How do I execute a post-build script -- meaning, after buildout runs, fetches all the eggs and puts everything in place -- now I want it to run a script. Specifically, I want it to run my unit test runner which is a script called ...
How to make a post build script for buildout
I'm using zc.buildout for my project. How do I execute a post-build script -- meaning, after buildout runs, fetches all the eggs and puts everything in place -- now I want it to run a script. Specifically, I want it to run my unit test runner which is a script called bin/test
[ "You can specify several parts in [buildout] section, one of your parts can run test scripts (e.g. using pbp.recipe.noserunner, zc.recipe.testrunner, ...)\n" ]
[ 1 ]
[]
[]
[ "build", "build_automation", "python" ]
stackoverflow_0007694368_build_build_automation_python.txt
Q: Why is '+' not understood by Python sets? I would like to know why this is valid: set(range(10)) - set(range(5)) but this is not valid: set(range(10)) + set(range(5)) Is it because '+' could mean both intersection and union? A: Python sets don't have an implementation for the + operator. You can use | for set ...
Why is '+' not understood by Python sets?
I would like to know why this is valid: set(range(10)) - set(range(5)) but this is not valid: set(range(10)) + set(range(5)) Is it because '+' could mean both intersection and union?
[ "Python sets don't have an implementation for the + operator.\nYou can use | for set union and & for set intersection.\nSets do implement - as set difference. You can also use ^ for symmetric set difference (i.e., it will return a new set with only the objects that appear in one set but do not appear in both sets)....
[ 131, 110, 46, 24, 13, 4 ]
[]
[]
[ "python", "set" ]
stackoverflow_0007692324_python_set.txt
Q: Django:How to let 3rd party sites access images on your server.(limited access i.e. only to that folder) I am working in Django.I am trying to connect my website to Facebook. What i want to do is 1)Send post_data post_data = [('access_token',access_token), ('message', message), ('link', some_link),('picture',inte...
Django:How to let 3rd party sites access images on your server.(limited access i.e. only to that folder)
I am working in Django.I am trying to connect my website to Facebook. What i want to do is 1)Send post_data post_data = [('access_token',access_token), ('message', message), ('link', some_link),('picture',internal_server_path_of_image) 2)urllib2.urlopen(graph_url, urllib.urlencode(post_data)) What this should do is po...
[ "I have come with a solution. As people had pointed out that the imagefield gives us the url of the image. That was true, what i am doing now is passing that url. At that url i have written a controller method. This method simply renders the image and returns it. This gives access to the facebook api to get the req...
[ 0 ]
[]
[]
[ "django", "python", "url_routing", "urllib2" ]
stackoverflow_0007593220_django_python_url_routing_urllib2.txt
Q: Constructing a two-dimensional list Possible Duplicate: Unexpected feature in a Python list of lists I tried to create a list in python using following statement S = [0] * 10 And it worked out well S[0] = 1 S [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] But when I try to generate a two-dimensional list, something unexpected...
Constructing a two-dimensional list
Possible Duplicate: Unexpected feature in a Python list of lists I tried to create a list in python using following statement S = [0] * 10 And it worked out well S[0] = 1 S [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] But when I try to generate a two-dimensional list, something unexpected occurs S = [[0] * 10] * 2 S[0][1] = 1 S...
[ "Because you told it to make 2 copies of the same mutable list.\nS = [[0] * 10 for x in range(2)]\n\n", "S = [[0] * 10] * 2 means 2 references for [[0]*10], so when your change one the other will change.By the way ,the reason why [0]*10 is fine is : a reference to a number.\n" ]
[ 4, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007695758_list_python.txt
Q: How compare two xpath in python I have two xpath strings for example: /Envlope[1]/Header[1]/transactionInfo[1]/id[1] and /Envelope/Header/* How I can compare (matching) this xpaht? How I can make this on python or what algorithm is better use? Example: <?xml version="1.0" encoding="utf-8"?> <Envelope> <Heade...
How compare two xpath in python
I have two xpath strings for example: /Envlope[1]/Header[1]/transactionInfo[1]/id[1] and /Envelope/Header/* How I can compare (matching) this xpaht? How I can make this on python or what algorithm is better use? Example: <?xml version="1.0" encoding="utf-8"?> <Envelope> <Header> <transactionInfo> ...
[ "Using lxml:\nimport lxml.etree as ET\n\ndef is_descendant(tree,path1,path2):\n elt1=tree.xpath(path1)[0]\n elt2=tree.xpath(path2+'/descendant::*')\n return elt1 in elt2\n\ncontent='''\\\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Envelope>\n <Header>\n <transactionInfo>\n <id>31234<...
[ 1 ]
[]
[]
[ "compare", "python", "xpath" ]
stackoverflow_0007695144_compare_python_xpath.txt
Q: sys.exit() terminates too quickly? I'm running some code with a sys.exit() call at the end. Without the sys.exit() line, the self.response works just fine and renders the template. But when I call sys.exit(), the page returns blank. It's almost like sys.exit() is interrupting the template mid-render. Why is it doi...
sys.exit() terminates too quickly?
I'm running some code with a sys.exit() call at the end. Without the sys.exit() line, the self.response works just fine and renders the template. But when I call sys.exit(), the page returns blank. It's almost like sys.exit() is interrupting the template mid-render. Why is it doing this? page = 'index.html' template_va...
[ "Remove the sys.exit().\nIf you're basing it on the wording in http://code.google.com/appengine/docs/python/runtime.html#Responses (which has since been reworded), pretend for the moment that the use of \"exit\" in the first two sentences means \"completes\" or \"finishes\".\n", "As others have already given good...
[ 6, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007694196_google_app_engine_python.txt
Q: Yahoo BOSS V2 authorization troubles I'm having an awfully hard time with Yahoo's authentication/authorization. I've enabled BOSS in my account, set up a payment method, and now I'm trying to run a search using some python code: import urllib2 import oauth2 as oauth import time OAUTH_CONSUMER_KEY = "blahblahblah...
Yahoo BOSS V2 authorization troubles
I'm having an awfully hard time with Yahoo's authentication/authorization. I've enabled BOSS in my account, set up a payment method, and now I'm trying to run a search using some python code: import urllib2 import oauth2 as oauth import time OAUTH_CONSUMER_KEY = "blahblahblah" OAUTH_CONSUMER_SECRET = "blah" def oaut...
[ "I made some small changes to make your example work. See code for comments.\nimport urllib2\nimport oauth2 as oauth\nimport time\n\nOAUTH_CONSUMER_KEY = \"blahblahblah\"\nOAUTH_CONSUMER_SECRET = \"blah\"\n\ndef oauth_request(url, params, method=\"GET\"):\n # Removed trailing commas here - they make a difference...
[ 7, 4, 1, 1, 1, 0 ]
[]
[]
[ "oauth", "python", "yahoo" ]
stackoverflow_0006796722_oauth_python_yahoo.txt
Q: line sorting by using python I have a txt file containing lines as follows (the first field is keywords, the second field is frequency of keywords, and the third field is related texts): anorexia nervosa 1 &#22312;&#19987;&#21033;&#32593;&#30475;&#21040;&#19968; glaucoma 10 want to suck out my eye...
line sorting by using python
I have a txt file containing lines as follows (the first field is keywords, the second field is frequency of keywords, and the third field is related texts): anorexia nervosa 1 &#22312;&#19987;&#21033;&#32593;&#30475;&#21040;&#19968; glaucoma 10 want to suck out my eyeballs and have them replaced with ...
[ "solution by eudoxos will work, you have to split with tabs (\\t)\nie., \ndata=file(yourFile).readlines()\ndata.sort(key=lambda l: float(l.split('\\t')[1]),reverse=True)\n\nHere, by the looks of your input text, I assumes that, the different fields are delimited by tabs.\nHowever, delimits by comma will be a better...
[ 2, 1 ]
[]
[]
[ "python", "sorting", "text_files" ]
stackoverflow_0007695371_python_sorting_text_files.txt
Q: Getting a URL with Python I'm trying to do something similar to placekitten.com, wherein a user can input two strings after the base URL and have those strings alter the output. I'm doing this in Python, and I cannot for the life of me figure out how to grab the URL. In PHP I can do it with query string and $_REQU...
Getting a URL with Python
I'm trying to do something similar to placekitten.com, wherein a user can input two strings after the base URL and have those strings alter the output. I'm doing this in Python, and I cannot for the life of me figure out how to grab the URL. In PHP I can do it with query string and $_REQUEST. I can't find a similar met...
[ "This is just by looking at the docs but have you tried it?\ncherrypy.request.path_info\n\nThe docs say:\n\nThe ‘relative path’ portion of the Request-URI. This is relative to the script_name (‘mount point’) of the application which is handling this request.\n\nhttp://docs.cherrypy.org/stable/refman/_cprequest.html...
[ 0 ]
[]
[]
[ "python", "url" ]
stackoverflow_0007694539_python_url.txt
Q: How to run a Python Script all day on a webserver I wrote a twitter scraper that I want to run indefinitely on my server in Python/Django. How can I make sure it always runs? I understand I can make a cronjob to start it up. However, sometimes the script errors because twitter's connection fails. How can I make s...
How to run a Python Script all day on a webserver
I wrote a twitter scraper that I want to run indefinitely on my server in Python/Django. How can I make sure it always runs? I understand I can make a cronjob to start it up. However, sometimes the script errors because twitter's connection fails. How can I make something that checks if this script is still running ev...
[ "Just ignore the exception, and start the script again.\nwhile True:\n try:\n do_work()\n except Exception, e:\n print \"Exception occurred, restarting.\", e\n pass\n\n", "I use this code:\n#!/bin/sh\nwhile true; do\n /path/to/my/script;\ndone\n\n", "Add your script to the crond Jo...
[ 2, 0, 0 ]
[]
[]
[ "cron", "django", "python" ]
stackoverflow_0007696477_cron_django_python.txt
Q: Is there a way to use more than 1 variable length arguments (*args) in a Python function? I would like to create a function that uses two variable length arguments. For example: def my_func(*args1, *args2): for i in args1: do stuff for j in args2: do stuff Is there a way in Python to use m...
Is there a way to use more than 1 variable length arguments (*args) in a Python function?
I would like to create a function that uses two variable length arguments. For example: def my_func(*args1, *args2): for i in args1: do stuff for j in args2: do stuff Is there a way in Python to use more than one *args? Thanks in advance for the help.
[ "No, as there is no way to decide whether\nmy_func(a, b)\n\nmeans\nargs = [], args2 = [a,b] # or ..\nargs = [a], args2 = [b] # or ..\nargs = [a,b], args2 = []\n\nInstead, simply let the function take two lists as arguments.\n", "You should use lists. That way, it's obvious which item goes in which argument:\ndef...
[ 6, 1, 0, 0, 0 ]
[]
[]
[ "args", "python" ]
stackoverflow_0007696561_args_python.txt
Q: Am I using headers properly in python Twisted using getPage? Below us my callback for fetching a page using twisted. client.getPage(iUrl,headers,method='GET',cookies=cj).addCallback(self.processPage,iUrl).addErrback(self.printError,iUrl) Here is the format for my headers. headers = Headers({'content-type': ...
Am I using headers properly in python Twisted using getPage?
Below us my callback for fetching a page using twisted. client.getPage(iUrl,headers,method='GET',cookies=cj).addCallback(self.processPage,iUrl).addErrback(self.printError,iUrl) Here is the format for my headers. headers = Headers({'content-type': ['text/html; charset=utf-8'], 'user-agent': ["Mozilla/5.0 (Macinto...
[ "The headers parameter to twisted.web.client.getPage accepts a dict, not a twisted.web.http_headers.Headers instance.\n", "HTTPClientFactory (used internally by getPage) constructor signature looks like:\n3 def __init__(self, url, method='GET', postdata=None, headers=None,\n204 agent=\"Twis...
[ 5, 3 ]
[]
[]
[ "header", "html", "python", "twisted" ]
stackoverflow_0007694509_header_html_python_twisted.txt
Q: how do I match a specific number into number set efficiently? I have a number set which contains 2375013 unique numbers in txt file. The data structure looks like this: 11009 900221 2 3 4930568 293 102 I want to match a number in a line from another data to the number set for extracting data what I need. So, I co...
how do I match a specific number into number set efficiently?
I have a number set which contains 2375013 unique numbers in txt file. The data structure looks like this: 11009 900221 2 3 4930568 293 102 I want to match a number in a line from another data to the number set for extracting data what I need. So, I coded like this: 6 def get_US_users_IDs(filepath, mode): 7 ...
[ "What I understood is that you have a huge number of ids in a file and you want to know if a specific user_id is in this file.\nYou can use a python set.\nfd = open(filepath, mode);\nIDs = set(int(id) for id in fd)\n...\nif user_id in IDs:\n number_of_US_user += 1\n ...\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007696739_python.txt
Q: How to make a log log histogram in python Given an an array of values, I want to plot a log log histogram of these values by their counts. I only know how to log the x values, but not the y values because they are not explicitly created in my program. A: Check out the pyplot documentation. pyplot.hist can "log...
How to make a log log histogram in python
Given an an array of values, I want to plot a log log histogram of these values by their counts. I only know how to log the x values, but not the y values because they are not explicitly created in my program.
[ "Check out the pyplot documentation. \n\npyplot.hist can \"log\" y axis for you with keyword argument log=True\npyplot.hist accepts bins keyword argument, but you have to \"log\" x axis yourself\n\nFor example:\n#!/usr/bin/python\nimport numpy\nfrom matplotlib import pyplot as plt\n\ndata = numpy.random.gumbel(2 **...
[ 25 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0007694298_histogram_matplotlib_python.txt
Q: How to force numpy array order to fortran style? I am using quite a lot of fortran libraries to do some mathematical computation. So all the arrays in numpy need to be Fortran-contiguous. Currently I accomplish this with numpy.asfortranarray(). My questions are: Is this a fast way of telling numpy that the array ...
How to force numpy array order to fortran style?
I am using quite a lot of fortran libraries to do some mathematical computation. So all the arrays in numpy need to be Fortran-contiguous. Currently I accomplish this with numpy.asfortranarray(). My questions are: Is this a fast way of telling numpy that the array should be stored in fortran style or is there a faster...
[ "Use optional argument order='F' (default 'C'), when generating numpy.array objects. This is the way I do it, probably does the same thing that you are doing. About number 2, I am not aware of setting default order, but it's easy enough to just include order optional argument when generating arrays.\n", "Regardin...
[ 14, 7 ]
[]
[]
[ "arrays", "fortran", "numpy", "performance", "python" ]
stackoverflow_0007688304_arrays_fortran_numpy_performance_python.txt
Q: Errors with conditional etree lxml I'm trying to delete everything between if between is number 66: I get the following error: TypeError: argument of type 'NoneType' is not iterable...if element.tag == 'answer' and '-66' in element.text: What is wrong with that? Any help? #!/usr/local/bin/python2.7 # -*- ...
Errors with conditional etree lxml
I'm trying to delete everything between if between is number 66: I get the following error: TypeError: argument of type 'NoneType' is not iterable...if element.tag == 'answer' and '-66' in element.text: What is wrong with that? Any help? #!/usr/local/bin/python2.7 # -*- coding: UTF-8 -*- from lxml import etr...
[ "element.text seems to be None on some iterations. The error is saying that it cant look through None for \"-66\", so check that element.text is not None first like this:\nhtml = etree.fromstring(planhtmlclear_utf)\nquestions = html.xpath('/questionaire/question')\nfor question in questions:\n    for element in qu...
[ 1, 1 ]
[]
[]
[ "lxml", "python", "xml.etree" ]
stackoverflow_0007697097_lxml_python_xml.etree.txt
Q: how to implement comet via gevent's event there's a demo on how to implement comet using gevent + flask. #coding:utf-8 ''' Created on Aug 6, 2011 @author: Alan Yang ''' import time from gevent import monkey monkey.patch_all() from gevent.event import Event from gevent.pywsgi import WSGIServer from flask import...
how to implement comet via gevent's event
there's a demo on how to implement comet using gevent + flask. #coding:utf-8 ''' Created on Aug 6, 2011 @author: Alan Yang ''' import time from gevent import monkey monkey.patch_all() from gevent.event import Event from gevent.pywsgi import WSGIServer from flask import Flask,request,render_template,jsonify app = F...
[ "Use gevent.queue.Queue.\nReading from the Queue removes the message and if there are multiple readers, each message will be delivered to exactly one of them (which one is unspecified though, there's no randomness or fairness, it's just arbitrary).\n" ]
[ 0 ]
[]
[]
[ "comet", "gevent", "python" ]
stackoverflow_0007697255_comet_gevent_python.txt
Q: Python AST: several semantics unclear, e.g. expr_context Is there any more than the ast documentation about the ast module? Esp., I am wondering what expr_context (and all its possible values) exactly means. Also, what is the difference between Assign and AugAssign? Also, it is possible to reference to a real Pyth...
Python AST: several semantics unclear, e.g. expr_context
Is there any more than the ast documentation about the ast module? Esp., I am wondering what expr_context (and all its possible values) exactly means. Also, what is the difference between Assign and AugAssign? Also, it is possible to reference to a real Python object instead of its name when doing an assignment to a lo...
[ "I'll try to answer it myself.\nAfter some more testing and guessing:\nexpr_context is where the Name is defined, e.g. if it is in an assignment on the left side (Store, AugStore), right side (Load, AugLoad), in a del (Del) or in an argument list like from FunctionDef or Lambda (Param).\nAugAssign is like a = a <op...
[ 11, 2 ]
[]
[]
[ "abstract_syntax_tree", "python" ]
stackoverflow_0006679171_abstract_syntax_tree_python.txt
Q: are there any python web framework support "flush"? in php there is a flush function, which is used to push content to client, meanwhile keep current connection. i look into flask, didn't found any function like it. are there any python web framework support flush ? ps: the reason to use flush is to implement come...
are there any python web framework support "flush"?
in php there is a flush function, which is used to push content to client, meanwhile keep current connection. i look into flask, didn't found any function like it. are there any python web framework support flush ? ps: the reason to use flush is to implement comet through iframe stream, though ajax long poll can do the...
[ "Take a look at Streaming Contents\n" ]
[ 2 ]
[]
[]
[ "comet", "python" ]
stackoverflow_0007697536_comet_python.txt
Q: How to recompile the Python 2.5 bytecode to 2.7? How can I recompile some .pyc files made by Python 2.5 with Python 2.7? I do not have the source files and I cannot obtain it. I am looking for a free solution. A: You will need Python 2.5 and 2.7 and byteplay (http://code.google.com/p/byteplay/) installed to bot...
How to recompile the Python 2.5 bytecode to 2.7?
How can I recompile some .pyc files made by Python 2.5 with Python 2.7? I do not have the source files and I cannot obtain it. I am looking for a free solution.
[ "You will need Python 2.5 and 2.7 and byteplay (http://code.google.com/p/byteplay/) installed to both.\ndiz.py:\n#!/usr/bin/env python\nimport byteplay, marshal, sys\nif __name__ == '__main__':\n sys.stdin.read(8)\n c = byteplay.Code.from_code(marshal.load(sys.stdin)).code\n labels = set([ x for l in c for...
[ 3 ]
[]
[]
[ "bytecode", "python" ]
stackoverflow_0007664189_bytecode_python.txt
Q: Can I use a class attribute as a default value for an instance method? I would like to use a class attribute as a default value for one of the arguments to my class's __init__ method. This construct raises a NameError exception, though, and I don't understand why: class MyClass(): __DefaultName = 'DefaultName'...
Can I use a class attribute as a default value for an instance method?
I would like to use a class attribute as a default value for one of the arguments to my class's __init__ method. This construct raises a NameError exception, though, and I don't understand why: class MyClass(): __DefaultName = 'DefaultName' def __init__(self, name = MyClass.__DefaultName): self.name = n...
[ "An important thing to keep in mind with Python is when different bits of code are executed, along with the fact that class and def statements are executed when seen, not just stored away for later. With a def it's a little easier to understand because the only thing being executed is whatever is between the ()s -...
[ 30, 28 ]
[]
[]
[ "python" ]
stackoverflow_0004041624_python.txt
Q: How can I perform a buffered search and replace? I have XML files that contain invalid characters sequences which cause parsing to fail. They look like &#x10;. To solve the problem, I am escaping them by replacing the whole thing with an escape sequence: &#x10; --> !#~10^. Then after I am done parsing I can restor...
How can I perform a buffered search and replace?
I have XML files that contain invalid characters sequences which cause parsing to fail. They look like &#x10;. To solve the problem, I am escaping them by replacing the whole thing with an escape sequence: &#x10; --> !#~10^. Then after I am done parsing I can restore them to what they were. buffersize = 2**16 # 64 KB...
[ "First, don't bother to read and write the file, you can create a file-like object that wraps your open file, and processes the data before it's handled by the parser. Second, your buffering can just take care of the ends of read bytes. Here's some working code:\nclass Wrapped(object):\n def __init__(self, f):...
[ 2, 1 ]
[]
[]
[ "buffer", "python", "replace", "xml" ]
stackoverflow_0007697514_buffer_python_replace_xml.txt
Q: Why does Django pass a variable to a template like this? I am adding a variable to a dictionary like this: rr_context["start_date"] = c.start_date And then I pass the dictionary to render_to_response: return render_to_response( rr_template, rr_context, context_instance=RequestContext(reque...
Why does Django pass a variable to a template like this?
I am adding a variable to a dictionary like this: rr_context["start_date"] = c.start_date And then I pass the dictionary to render_to_response: return render_to_response( rr_template, rr_context, context_instance=RequestContext(request)) Then in template I try to format it this way: {{ start_d...
[ "It seems that your start_date is a tuple and not a single date value. That's why the date filter doesn't work.\nYou should check that c.start_date is a date, because it looks like it's a tuple.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007697750_django_python.txt
Q: padding arrays using numpy in my program i have a numpy array and do some convolution filtering on it. i am looking for some way to make array padding (and then unpad for output) easily using numpy to avoid boundary checking. i know that scipy can do convolution, but i have reasons to make it by myself. gnuplot.py...
padding arrays using numpy
in my program i have a numpy array and do some convolution filtering on it. i am looking for some way to make array padding (and then unpad for output) easily using numpy to avoid boundary checking. i know that scipy can do convolution, but i have reasons to make it by myself. gnuplot.py is used for output. def touch(f...
[ "There's a pad module scheduled for inclusion in Numpy 1.7.0 – see this ticket. For now, just download it and use its with_constant function.\nUnpadding is as simple as field[1:-1, 1:-1].\n" ]
[ 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007697169_numpy_python.txt
Q: How to check alignment of text using selenium RC verify alignment of text or any other element in web page using selenium rc. i use python, is there any budy who can help with this. A: In case text alignment is coded directly in HTML you could do what you want using the assertElementPresent() method and a suitab...
How to check alignment of text using selenium RC
verify alignment of text or any other element in web page using selenium rc. i use python, is there any budy who can help with this.
[ "In case text alignment is coded directly in HTML you could do what you want using the assertElementPresent() method and a suitable XPath locator. For example to check the following text\n<p id=\"paragraph\" align=\"right\">Text text text text text text text</p>\n\nyou could use\nselenium.isElementPresent(\"//p[@id...
[ 0, 0 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0007578786_python_selenium_rc.txt
Q: HTML + AJAX + Python + Session? I am trying to understand how to use AJAX with Python Sessions. I understand the basics of how sessions work. When I add AJAX to the mix, my mind is having a difficult time understanding the technical details. Part of me thinks AJAX and Python Sessoins are not possible. I know web f...
HTML + AJAX + Python + Session?
I am trying to understand how to use AJAX with Python Sessions. I understand the basics of how sessions work. When I add AJAX to the mix, my mind is having a difficult time understanding the technical details. Part of me thinks AJAX and Python Sessoins are not possible. I know web frameworks exist that probably do all ...
[ "Remember that the AJAX request is the same as any other HTTP request to the server. The session is maintained on the server side, but as far as the server can tell, a request from the browser is a request from the browser. An AJAX request can get and set the cookie just like any other request can. The method you'v...
[ 1 ]
[]
[]
[ "ajax", "html", "python", "session" ]
stackoverflow_0006718812_ajax_html_python_session.txt
Q: os.path.join with str subclass Does anybody knows why the os.path.join function doesn't work with subclasses of str? (I'm using Python3.2 x64 and Python2.7 x86 on Windows and the result is the same) That's the code I have class Path(str): def __add__(self, other): return Path(os.path.join(self, other))...
os.path.join with str subclass
Does anybody knows why the os.path.join function doesn't work with subclasses of str? (I'm using Python3.2 x64 and Python2.7 x86 on Windows and the result is the same) That's the code I have class Path(str): def __add__(self, other): return Path(os.path.join(self, other)) p = Path(r'C:\the\path') d = p + '...
[ "It looks like os.path.join uses the build in __add__ method, this can be verified by putting a print statement in the __add__ method.\n>>> class Path(str):\n... def __add__(self, other):\n... print 'add'\n... return Path(os.path.join(str(self), other))\n... \n>>> p = Path(r'/the/path')\...
[ 1, 0 ]
[]
[]
[ "path", "python", "python_3.x", "string" ]
stackoverflow_0007682198_path_python_python_3.x_string.txt
Q: How to debug urllib2 request that uses a basic authentication handler I'm making a request using urllib2 and the HTTPBasicAuthHandler like so: import urllib2 theurl = 'http://someurl.com' username = 'username' password = 'password' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, th...
How to debug urllib2 request that uses a basic authentication handler
I'm making a request using urllib2 and the HTTPBasicAuthHandler like so: import urllib2 theurl = 'http://someurl.com' username = 'username' password = 'password' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passm...
[ "Have you tried setting the debug level in your own HTTP handler? Change your code to something like this:\n>>> import urllib2\n>>> handler=urllib2.HTTPHandler(debuglevel=1)\n>>> opener = urllib2.build_opener(handler)\n>>> urllib2.install_opener(opener)\n>>> resp=urllib2.urlopen('http://www.google.com').read()\nsen...
[ 30 ]
[]
[]
[ "basic_authentication", "debugging", "python", "urllib2" ]
stackoverflow_0007697963_basic_authentication_debugging_python_urllib2.txt
Q: Python string compare issue I've got some code that looks like this: valid = set() for string in substrings: for line in dictionary_words: if string in line: valid.add(string) f.writelines(sorted(valid)) Both dictionary_words and substrings are currently lists. After t...
Python string compare issue
I've got some code that looks like this: valid = set() for string in substrings: for line in dictionary_words: if string in line: valid.add(string) f.writelines(sorted(valid)) Both dictionary_words and substrings are currently lists. After the substring is found inside any ...
[ "valid = set()\nfor string in substrings:\n for line in dictionary_words:\n if string in line:\n valid.add(string)\n break\nf.writelines(sorted(valid))\n\n@F.C.: If you use continue instead of break, it will run the next iteration of the inner for-loop.\n", "Why not try this - \n valid ...
[ 2, 1, 1, 0 ]
[]
[]
[ "compare", "list", "python", "substring" ]
stackoverflow_0007698326_compare_list_python_substring.txt
Q: Defining function without the brackets? I understand that my question might sound stupid, and that there might be something in the language definition that explicitly prohibits this notion, but since I don't know about this prohibition, I was wondering whether someone could shed some light on it. In short, I would...
Defining function without the brackets?
I understand that my question might sound stupid, and that there might be something in the language definition that explicitly prohibits this notion, but since I don't know about this prohibition, I was wondering whether someone could shed some light on it. In short, I would like to define a python function that I coul...
[ "You're going to get some syntax in there somewhere. You could try something like:\nimport os\nclass Shell(object):\n @property\n def pwd(self):\n print os.getcwd()\n\nAnd then in your interpreter, run:\n>>> s = Shell()\n>>> s.pwd\n/tmp\n\n", "You can't do this without modifying the language or the s...
[ 11, 11, 4 ]
[]
[]
[ "definition", "function", "python" ]
stackoverflow_0007698603_definition_function_python.txt
Q: How to detect a process is running using python I have to do some task whenever some specific applications were launched. Is there any way to list all the processes running in an operating system or detect whenever a new process is created in operating system A: You could use psutil. Psutil provides information...
How to detect a process is running using python
I have to do some task whenever some specific applications were launched. Is there any way to list all the processes running in an operating system or detect whenever a new process is created in operating system
[ "You could use psutil. Psutil provides information on running processes and system utilization.\n", "Yeah, there is a bit of stuff in the standard Python library that Jython doesn't implement probably because it's platform dependent and too much work for the small Jython community to implement. Try looking for a ...
[ 3, 3 ]
[]
[]
[ "jython", "process", "python" ]
stackoverflow_0007698104_jython_process_python.txt
Q: Python urljoin equivalent in AS3 Python has a function urljoin that takes two URLs and concatenates them intelligently. Is there a library that provides a similar function in AS3? urljoin documentation: http://docs.python.org/library/urlparse.html And python example: >>> urljoin('http://www.cwi.nl/doc/Python.html'...
Python urljoin equivalent in AS3
Python has a function urljoin that takes two URLs and concatenates them intelligently. Is there a library that provides a similar function in AS3? urljoin documentation: http://docs.python.org/library/urlparse.html And python example: >>> urljoin('http://www.cwi.nl/doc/Python.html', '../res/jer.png') 'http://www.cwi.nl...
[ "You can use for example the URI class from as3corelib\nUsage:\nimport com.adobe.net.URI;\n\n// create uri you want to be updated\nvar newURI:URI=new URI('../res/jer.png')\n\n// update newURI with the full path\nnewURI.makeAbsoluteURI(new URI('http://www.cwi.nl/doc/Python.html')) \n\ntrace(uri.toString()) // will o...
[ 3, 2 ]
[]
[]
[ "actionscript_3", "python", "url" ]
stackoverflow_0007649423_actionscript_3_python_url.txt
Q: Python: create a list containing dicts how would you turn this string: str='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' into a list that give you this: print x[1]['building']=CL5 which would be: x=[{'ldap':'alberthwang','eeid':'67739'},{'ldap':'meng','eeid':'107','building':'CL5'}] i've tried t...
Python: create a list containing dicts
how would you turn this string: str='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5' into a list that give you this: print x[1]['building']=CL5 which would be: x=[{'ldap':'alberthwang','eeid':'67739'},{'ldap':'meng','eeid':'107','building':'CL5'}] i've tried to split the string first and append to a lis...
[ "text='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5'\nsample=[\n dict(item.split(':') for item in part.split(','))\n for part in text.split('|')]\nprint(sample)\n# [{'eeid': '67739', 'ldap': 'alberthwang'}, {'building': 'CL5', 'eeid': '107', 'ldap': 'meng'}]\n\nprint(sample[1]['building'])\n# C...
[ 4, 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0007696593_dictionary_list_python.txt
Q: Issue with BeautifulSoup and printing a string from findAll function I'm trying to get the thread titles from /r/Askreddit. The code below returns None instead of the thread title. from BeautifulSoup import BeautifulSoup import urllib2, json site='http://www.reddit.com/r/AskReddit/' soup=BeautifulSoup(urllib2.ur...
Issue with BeautifulSoup and printing a string from findAll function
I'm trying to get the thread titles from /r/Askreddit. The code below returns None instead of the thread title. from BeautifulSoup import BeautifulSoup import urllib2, json site='http://www.reddit.com/r/AskReddit/' soup=BeautifulSoup(urllib2.urlopen(site)) questions=soup.findAll('p',{"class":"title"}) for i in que...
[ "The title is in the string attribute of the a tag, not the p tag.\nAlso, notice the space after title:\nquestions=soup.findAll('a',{\"class\":\"title \"})\n\n\nThe above was found by looking at this HTML snippet:\n<p class=\"title\"><a class=\"title \" href=\"http://www.reddit.com/r/AskReddit/comments/l5157/whats_...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007699237_beautifulsoup_python.txt
Q: Is there a shorter way to remove line breaks when reading from a file to a list? Here is my current code: dfile = open('dictionary.txt', 'r') sfile = open('substrings.txt', 'r') dictionary_words = [] substrings = [] for line in dfile: dictionary_words.append(line.rstrip('\n')) for line in sfile: substring...
Is there a shorter way to remove line breaks when reading from a file to a list?
Here is my current code: dfile = open('dictionary.txt', 'r') sfile = open('substrings.txt', 'r') dictionary_words = [] substrings = [] for line in dfile: dictionary_words.append(line.rstrip('\n')) for line in sfile: substrings.append(line.rstrip('\n')) It works but seems pretty wordy. Is this the appropriate ...
[ "Try this:\nwith open('dictionary.txt', 'r') as f:\n dictionary_words = f.read().splitlines()\n\n", "Either use map:\ndictionary_words = map(lambda line: line.rstrip('\\n'), dfile)\n\nor a list comprehension:\ndictionary_words = [line.rstrip('\\n') for line in dfile]\n\n", "A slightly less wordy alternative ...
[ 9, 4, 3, 1, 1 ]
[]
[]
[ "file_io", "list", "python", "strip", "whitespace" ]
stackoverflow_0007698798_file_io_list_python_strip_whitespace.txt
Q: Moving an image around in 3D space I'm trying to create a logo visualization in python and I would like to animate a number of images in 3D space such that the images are always "facing" the center of the screen and the images move about some fixed path. I've done this before with python using Vizard, however, I'd...
Moving an image around in 3D space
I'm trying to create a logo visualization in python and I would like to animate a number of images in 3D space such that the images are always "facing" the center of the screen and the images move about some fixed path. I've done this before with python using Vizard, however, I'd like to do this in a "free", and cross ...
[ "The following is the simplest code I could come up with that allowed me to position the image at position (0, 0, -10):\n#!/usr/bin/env python \nimport pyglet\nfrom pyglet.gl import *\n\nwindow = pyglet.window.Window()\nglEnable(GL_DEPTH_TEST)\n\nimage = pyg...
[ 6 ]
[]
[]
[ "opengl", "pyglet", "python" ]
stackoverflow_0007681899_opengl_pyglet_python.txt
Q: Simple python query So my problem is that i have a down-loader that has the percent of the file downloaded so far. And sometimes the percent doesent go up by one or some times it goes up by 4 or 5 etc. so say my files percent of download went like this: 0 % done 1 % done 2 % done 2 % done 2 % done 3 % done 3 % don...
Simple python query
So my problem is that i have a down-loader that has the percent of the file downloaded so far. And sometimes the percent doesent go up by one or some times it goes up by 4 or 5 etc. so say my files percent of download went like this: 0 % done 1 % done 2 % done 2 % done 2 % done 3 % done 3 % done 3 % done 3 % done 3 % d...
[ "Given x is the list of percents (of completion for your download):\nx = [ 0, 1, 2, 2, 2, 3, 3 ]\n\nThen use \"finite differencing\" to get the change:\ndelta_x = [ x[i+1] - x[i] for i in xrange(0, len(x)-1) ]\n\nI've written it as a list comprehension, but you could also do it with a loop.\n", "My version:\n>>> ...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007699349_python.txt
Q: What's the idiomatic python equivalent of get() for lists? Calling get(key) on a dictionary will return None by default if the key isn't present in a dictionary. What is the idiomatic equivalent for a list, such that if a list is of at least size of the passed in index the element is returned, otherwise None is r...
What's the idiomatic python equivalent of get() for lists?
Calling get(key) on a dictionary will return None by default if the key isn't present in a dictionary. What is the idiomatic equivalent for a list, such that if a list is of at least size of the passed in index the element is returned, otherwise None is returned? To rephrase, what's a more idiomatic/compact version of...
[ "Your implementation is Look Before You Leap-style. It's pythonic to execute the code and catch errors instead:\ndef get(l, i, d=None):\n try:\n return l[i]\n except IndexError:\n return d\n\n", "If you expect l[i] to often not exist, then use:\ndef get(l,i):\n return l[i] if i<len(l) else ...
[ 7, 3 ]
[]
[]
[ "idioms", "python" ]
stackoverflow_0007699937_idioms_python.txt
Q: How can I replace blank entries in a text table with 0 in Python? I have tables which looks like this: text = """ ID = 1234 Hello World 135,343 117,668 81,228 Another line of text (30,632) (48,063) More text 0 11,205 0 Even more text ...
How can I replace blank entries in a text table with 0 in Python?
I have tables which looks like this: text = """ ID = 1234 Hello World 135,343 117,668 81,228 Another line of text (30,632) (48,063) More text 0 11,205 0 Even more text 1,447 681 ID = 18372 Another table ...
[ "Here is a function for finding columns in a bunch of lines. The second argument pat defines what a column is, and can be any regex. \nimport itertools as it\nimport re\n\ndef find_columns(lines, pat = r' '):\n '''\n Usage:\n widths = find_columns(lines)\n for line in lines:\n if not line: contin...
[ 1 ]
[]
[]
[ "python", "text" ]
stackoverflow_0007700081_python_text.txt
Q: Django: ImportError: cannot import name receiver Very basic django app that gives me the following when I try to do anything (runserver, syncdb). Thoughts? If it is a problem with one of my files, could you help guide me as to what the issue may be? File "/Library/Python/2.7/site-packages/django/dispatch/__init__....
Django: ImportError: cannot import name receiver
Very basic django app that gives me the following when I try to do anything (runserver, syncdb). Thoughts? If it is a problem with one of my files, could you help guide me as to what the issue may be? File "/Library/Python/2.7/site-packages/django/dispatch/__init__.py", line 9, in <module> from django.dispatch.disp...
[ "receiver should be imported from the dispatch module:\nfrom django.dispatch import receiver\n\nNote that the receiver decorator was added in only in Django 1.3. You can check your django version by:\nimport django\ndjango.VERSION\n\nedit:\nThe wrong import statement is part of the __init__ module of the dispatch p...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007700154_django_python.txt
Q: Irregular String Parsing on Python I'm new to python/django and I am trying to suss out more effective information from my scraper. Currently, the scraper takes a list of comic book titles and correctly divides them into a CSV list in three parts (Published Date, Original Date, and Title). I then pass the current ...
Irregular String Parsing on Python
I'm new to python/django and I am trying to suss out more effective information from my scraper. Currently, the scraper takes a list of comic book titles and correctly divides them into a CSV list in three parts (Published Date, Original Date, and Title). I then pass the current date and title through to different part...
[ "Use the regular expression module re. For example, if you have the third |-delimited field of your sample record in a variable s, then you can do\nmatch = re.match(r\"^(?P<title>[^#]*) #(?P<num>[0-9]+) \\((?P<special>.*)\\)$\", s)\ntitle = match.groups('title')\nissue = match.groups('num')\nspecial = match.groups(...
[ 1, 1, 1 ]
[]
[]
[ "django", "parsing", "python", "string", "web" ]
stackoverflow_0007698034_django_parsing_python_string_web.txt
Q: types.MethodType vs functools.partial This is a continuation of my other question (python closure + oop). In the answer to that question, Winston Ewert suggested me to use functools.partial instead of types.MethodType. So now my question is: what's the difference between the two? Why is the functool way considere...
types.MethodType vs functools.partial
This is a continuation of my other question (python closure + oop). In the answer to that question, Winston Ewert suggested me to use functools.partial instead of types.MethodType. So now my question is: what's the difference between the two? Why is the functool way considered better? ps. I've managed to use functools...
[ "From a practical stand point, there isn't a whole lot of difference. Partial will curry any number of arguments (in this case, 1); an instancemethod will pass the self instance (whatever that happens to be) to the wrapped function; They're doing the same thing!\nThe difference is that they somewhat document them...
[ 4 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0007700466_functional_programming_python.txt
Q: Including resources in a Python package using setup.py I'm working on a website project. When I use setup.py and run setup.py build, the build script excludes all of the resources in my web site (basically all of the non python files). What am I doing wrong? A: The most reliable way I've found to include extra ...
Including resources in a Python package using setup.py
I'm working on a website project. When I use setup.py and run setup.py build, the build script excludes all of the resources in my web site (basically all of the non python files). What am I doing wrong?
[ "The most reliable way I've found to include extra files in a distribution using distutils is to provide a MANIFEST.in file. Place this file in the same directory as your setup.py and include in it the list of resource files you require. For example, your MANIFEST.in file might like this:\ninclude resources/somefil...
[ 3 ]
[]
[]
[ "python", "web" ]
stackoverflow_0007700270_python_web.txt
Q: How to pick the largest number in a matrix of lists in python? I have a list-of-list-of-lists, where the first two act as a "matrix", where I can access the third list as list3 = m[x][y] and the third list contains a mix of strings and numbers, but each list has the same size & structure. Let's call a spec...
How to pick the largest number in a matrix of lists in python?
I have a list-of-list-of-lists, where the first two act as a "matrix", where I can access the third list as list3 = m[x][y] and the third list contains a mix of strings and numbers, but each list has the same size & structure. Let's call a specific entry in this list The Number of Interest. This number always h...
[ "max((cell[k], x, y)\n for (y, row) in enumerate(m)\n for (x, cell) in enumerate(row))[1:]\n\nAlso, you can assign the result directly to a couple of variables:\n(_, x, y) = max((cell[k], x, y)\n for (y, row) in enumerate(m)\n for (x, cell) in enumerate(row))\n\nThis is O(n2), bt...
[ 4, 3, 0 ]
[]
[]
[ "algorithm", "optimization", "python" ]
stackoverflow_0007700545_algorithm_optimization_python.txt
Q: INSERT INTO statement with variable in python I'm trying to insert the results of a query into a table, but add a variable to the result set . I've looked at some similar questions and I think I am representing the query variables correctly but I am getting a "global variable not defined" error. Can you point me...
INSERT INTO statement with variable in python
I'm trying to insert the results of a query into a table, but add a variable to the result set . I've looked at some similar questions and I think I am representing the query variables correctly but I am getting a "global variable not defined" error. Can you point me in the right direction? I'm guessing it has to do...
[ "The execute method doesn't return a value. You would need to use fetchone or fetchall in order to get the results from the first query.\n", "You don't need to make two SQL queries to do this. Instead, use an INSERT query of the form INSERT INTO ... SELECT ...:\nconn=sqlite3.connect(...)\ncursor=conn.cursor()\n\n...
[ 2, 2 ]
[]
[]
[ "insert", "python", "sql", "sqlite", "variables" ]
stackoverflow_0007698157_insert_python_sql_sqlite_variables.txt
Q: Error was: No module named Random Python 2.4.3, when I run python via the command line and import random, it works just fine. When I run a django based website "python manage.py runserver", the server starts up fine, but as soon as I load a page, it tosses me this error. I really have no clue how to fix this. I've...
Error was: No module named Random
Python 2.4.3, when I run python via the command line and import random, it works just fine. When I run a django based website "python manage.py runserver", the server starts up fine, but as soon as I load a page, it tosses me this error. I really have no clue how to fix this. I've done some searching, random is core to...
[ "If the error is exactly \"No module named Random\", then you've written import Random when you really meant import random. There is no module in the Python standard library called Random. Module names are case sensitive in Python. If that doesn't solve your problem, please show us some code from whatever module im...
[ 4 ]
[]
[]
[ "django", "python", "random" ]
stackoverflow_0007700743_django_python_random.txt
Q: PIL Cannot Handle This Data Type I'm attempting to use the fft module in numpy: import Image, numpy i = Image.open('img.png') a = numpy.asarray(i, numpy.uint8) b = abs(numpy.fft.rfft2(a)) b = numpy.uint8(b) j = Image.fromarray(b) j.save('img2.png') However, when I try and convert the numpy array back to a PIL ...
PIL Cannot Handle This Data Type
I'm attempting to use the fft module in numpy: import Image, numpy i = Image.open('img.png') a = numpy.asarray(i, numpy.uint8) b = abs(numpy.fft.rfft2(a)) b = numpy.uint8(b) j = Image.fromarray(b) j.save('img2.png') However, when I try and convert the numpy array back to a PIL image, I get the error: TypeError: Can...
[ "I think perhaps the rfft2 is being performed over the wrong axes. \nBy default, it uses the last two axes: axes=(-2,-1). The third axis represents the RGB channels. Instead, it seems more plausible that one would want to perform an FFT over the spatial axes, axes=(0,1):\nimport Image\nimport numpy as np\n\ni = Ima...
[ 11 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0007700193_numpy_python_python_imaging_library.txt
Q: How to tell my django template where static file (dajax.core.js) is? I'm trying to use Dajax in my Django app, but I'm getting a 404 Error when I try to include it in my html template. I've installed both Dajax and Dajaxice on Windows 7. Here's what my STATIC_URL looks like: STATIC_URL = '/static/' My static fol...
How to tell my django template where static file (dajax.core.js) is?
I'm trying to use Dajax in my Django app, but I'm getting a 404 Error when I try to include it in my html template. I've installed both Dajax and Dajaxice on Windows 7. Here's what my STATIC_URL looks like: STATIC_URL = '/static/' My static folder is placed in my app's folder, so from the src folder in my Eclipse pro...
[ "I would assume it's because you need add the static server for django (which is only used for running locally)\nadd this to your urls.py:\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}),\n )\n\nor you need to ...
[ 0 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0007698418_django_python_templates.txt
Q: How to have a PyQT program keep refreshing one widget, always providing an up-to-date value? I'm learning to program with PyQT4 and Python. I'm trying to code a simple app that will display the current CPU usage in a QLCD widget. For CPU usage I'm using psutils module. The problem is that the CPU usage is not upda...
How to have a PyQT program keep refreshing one widget, always providing an up-to-date value?
I'm learning to program with PyQT4 and Python. I'm trying to code a simple app that will display the current CPU usage in a QLCD widget. For CPU usage I'm using psutils module. The problem is that the CPU usage is not updated all the time - it only records the CPU usage at the moment the app has been launched (I'm gues...
[ "You can use a QTimer[reference] object with a callback.\nSomething like that should work:\ndef call_this():\n self.wpCpuUsage.display(cpu_percent(interval=1))\n\nself.my_timer = QtCore.QTimer()\nself.my_timer.timeout.connect(call_this)\nself.my_timer.start(1000) #1 second interval\n\n" ]
[ 7 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007700841_pyqt_python.txt
Q: swapping in Tkinter I have a simple Tkinter program in Python that converts feet to meters. It has a Label, a Feet Entry box, a Meters box with a sunken border, and then 3 buttons: Quit, Covert, and Swap. I'm just trying to figure out how to make the Swap button do exactly that. Swap the position of Feet and Meter...
swapping in Tkinter
I have a simple Tkinter program in Python that converts feet to meters. It has a Label, a Feet Entry box, a Meters box with a sunken border, and then 3 buttons: Quit, Covert, and Swap. I'm just trying to figure out how to make the Swap button do exactly that. Swap the position of Feet and Meters in the window, so you c...
[ "Create a variable that stores what you are converting from, and have the swap function change the variable and update the labels. To change the text of a label you can do label['text'] = 'new text' or label.configure(text='new text'). Here's a working modification of your code:\nimport Tkinter\n\ninputmode = 'feet...
[ 3, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007690736_python_tkinter.txt
Q: Faster alternative to BeautifulSoup for parsing visible text in an html file I have a directory with 50,000 html files in it. For each of the files I want to find 'visible' texts (text data that would actually be visible to a person viewing the file in a browser). I've seen some fine solutions using libraries such...
Faster alternative to BeautifulSoup for parsing visible text in an html file
I have a directory with 50,000 html files in it. For each of the files I want to find 'visible' texts (text data that would actually be visible to a person viewing the file in a browser). I've seen some fine solutions using libraries such as BeautifulSoup, but I want something faster. A regex based solution I wrote was...
[ "It sounds like you are just trying to render every HTML file in a directory. Why write your own renderer (in Python or in any other language) when there are plenty of others out there? \nHere is an example using w3m (you could equally use Lynx, links, ...):\nfind . -name '*.html' -exec w3m -dump {} \\; \n\n" ]
[ 2 ]
[]
[]
[ "html_parsing", "performance", "python" ]
stackoverflow_0007701099_html_parsing_performance_python.txt
Q: Tweepy (Python) and Oauth (Twitter) Problem auth = tweepy.OAuthHandler(consumer_token, consumer_secret) When I run this line of tweepy code i run into two problems. I receive the code "Tweepy has no attribute OAuthHandler" despite that being in the documentation I found. One assumes that that would be valid code....
Tweepy (Python) and Oauth (Twitter) Problem
auth = tweepy.OAuthHandler(consumer_token, consumer_secret) When I run this line of tweepy code i run into two problems. I receive the code "Tweepy has no attribute OAuthHandler" despite that being in the documentation I found. One assumes that that would be valid code. The second problem is that when I registered my...
[ "First you have to get both the consumer_token and the consumer_secret. When you register the app it gives you a couple of strings you then use for authentication. The consumer_token is the Consumer Key string twitter provides you with, and then the consumer_secret is the Consumer Secret twitter provides you with. ...
[ 1, 1 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0006516244_python_tweepy_twitter.txt
Q: How to implement OpenSSL functionality in Python? I would like to encrypt a secret text by public-key and decrypt it by private-key in Python. I can achieve that with the openssl command: echo "secrettext/2011/09/14 22:57:23" | openssl rsautl -encrypt -pubin -inkey public.pem | base64 data.cry base64 -D data.cry ...
How to implement OpenSSL functionality in Python?
I would like to encrypt a secret text by public-key and decrypt it by private-key in Python. I can achieve that with the openssl command: echo "secrettext/2011/09/14 22:57:23" | openssl rsautl -encrypt -pubin -inkey public.pem | base64 data.cry base64 -D data.cry | openssl rsautl -decrypt -inkey private.pem How would...
[ "Encrypt\n#!/usr/bin/env python\nimport fileinput\nfrom M2Crypto import RSA\n\nrsa = RSA.load_pub_key(\"public.pem\")\nctxt = rsa.public_encrypt(fileinput.input().read(), RSA.pkcs1_oaep_padding)\nprint ctxt.encode('base64')\n\nDecrypt\n#!/usr/bin/env python\nimport fileinput\nfrom M2Crypto import RSA\n\npriv = RSA....
[ 20, 3, 1 ]
[]
[]
[ "openssl", "private_key", "public_key_encryption", "python" ]
stackoverflow_0007669598_openssl_private_key_public_key_encryption_python.txt
Q: Error message which running Python tools in Visual Studio I am new to python and just started learning it today. I have installed Python Tools for Visual Studio 2010 and using VS as my Editor. My test python programs run correctly but the at the last line in the output window I see the following The thread 'Python...
Error message which running Python tools in Visual Studio
I am new to python and just started learning it today. I have installed Python Tools for Visual Studio 2010 and using VS as my Editor. My test python programs run correctly but the at the last line in the output window I see the following The thread 'Python Thread' (0x6f4) has exited with code 0 (0x0). Please advice m...
[ "That means the script executed successfully. If the code was anything other than zero, that would indicate an error.\nYes, that command window is likely the \"Python Thread\".\n" ]
[ 5 ]
[]
[]
[ "ptvs", "python", "visual_studio_2010" ]
stackoverflow_0007701303_ptvs_python_visual_studio_2010.txt
Q: Log that a request was responded to after responding This probably is a very noobish question, but I want to make sure my code is doing what I think it's doing. Here's what I'm after - get a request, make a decision, respond to it the request with the decision, and only then log it. The sequence is important becau...
Log that a request was responded to after responding
This probably is a very noobish question, but I want to make sure my code is doing what I think it's doing. Here's what I'm after - get a request, make a decision, respond to it the request with the decision, and only then log it. The sequence is important because writes can be slow and I want to make sure that a respo...
[ "No matter what you do, App Engine will not send a response to a user until your handler code completes. There's currently no way, unfortunately, to tell App Engine \"send the response now, I won't output any more\".\nYou have a few options:\n\nJust put the log entry synchronously. Datastore writes aren't hugely ex...
[ 3, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0007701081_django_google_app_engine_python.txt
Q: how to call a function from another file? Sorry basic question I'm sure but I can't seem to figure this out. Say I have this program , the file is called pythonFunction.py: def function(): return 'hello world' if __name__=='__main__': print function() How can I call it in another program? I tried: import p...
how to call a function from another file?
Sorry basic question I'm sure but I can't seem to figure this out. Say I have this program , the file is called pythonFunction.py: def function(): return 'hello world' if __name__=='__main__': print function() How can I call it in another program? I tried: import pythonFunction as pythonFunction print pythonFun...
[ "You need to print the result of calling the function, rather than the function itself:\nprint pythonFunction.function()\n\nAdditionally, rather than import pythonFunction as pythonFunction, you can omit the as clause:\nimport pythonFunction\n\nIf it's more convenient, you can also use from...import:\nfrom pythonFu...
[ 38 ]
[]
[]
[ "python" ]
stackoverflow_0007701646_python.txt
Q: How do i compile .py to a .exe? I am trying to compile my .py script into a .exe using py2exe using this code: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'optimize': 2}}, windows = [{'script': "get.py"}], zipfile = "shared.lib", ) I get this in m...
How do i compile .py to a .exe?
I am trying to compile my .py script into a .exe using py2exe using this code: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'optimize': 2}}, windows = [{'script': "get.py"}], zipfile = "shared.lib", ) I get this in my console: Python 2.7.2 (default, Jun...
[ "Are you intentionally building a gui based script? If not change windows = [{'script': \"get.py\"}], to console = [\"get.py\"],:\nfrom distutils.core import setup\nimport py2exe, sys, os\nsys.argv.append('py2exe')\nsetup(\n options = {'py2exe': {'optimize': 2}},\n console = [\"get.py\"],\n zipfile = \"sh...
[ 0 ]
[]
[]
[ "compiler_errors", "py2exe", "python" ]
stackoverflow_0007700089_compiler_errors_py2exe_python.txt
Q: Adding to a int value with pre-existing dictionaries I am trying to set up a function that will calculate a score for the similarity of two films. There are pre-existing dictionaries that with the films as keys and either the directors, genres, or main actors are values. There are three actor dictionaries (the 3...
Adding to a int value with pre-existing dictionaries
I am trying to set up a function that will calculate a score for the similarity of two films. There are pre-existing dictionaries that with the films as keys and either the directors, genres, or main actors are values. There are three actor dictionaries (the 3 lead actors for each film is listed). The code mostly wo...
[ "Try with the in condition :\nif actor1[film1] in (actor1[film2], actor2[film2], actor3[film2]):\n FavActorScore += 5 \nif actor2[film1] in ( actor1[film2], actor2[film2], actor3[film2]):\n FavActorScore += 5\nif actor3[film1] in (actor1[film2], actor2[film2], actor3[film2]):\n FavActorScore += 5\n\nWhen you ...
[ 1 ]
[]
[]
[ "dictionary", "if_statement", "python" ]
stackoverflow_0007701437_dictionary_if_statement_python.txt
Q: what does the er here stands for? try: os.execvp('sqlite3', args) except OSError, er: if er.errno == 2: #file not found raise OSError, _("sqlite3 executable not found. Is it installed?") else: raise except: raise In the above code, the except statement catches the OSError ...
what does the er here stands for?
try: os.execvp('sqlite3', args) except OSError, er: if er.errno == 2: #file not found raise OSError, _("sqlite3 executable not found. Is it installed?") else: raise except: raise In the above code, the except statement catches the OSError but what does the er variable stand for...
[ "As others have said, er is the instantiated form of the exception, OSError.\nIf it's helpful, here's an alternative, somewhat more explicit syntax, using the as keyword:\ntry: \n os.execvp('sqlite3', args) \nexcept OSError as er: \n if er.errno == 2: #file not found \n raise OSError(_(\"sqlite3 execut...
[ 5, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007701842_python.txt