content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How can I determine the final URL after redirection using python / urllib2? I need to get the final URL after redirection in python. What's a good way to do that? A: >>> import urllib2 >>> var = urllib2.urlopen('http://www.stackoverflow.com/') >>> var.geturl() 'http://stackoverflow.com/'
How can I determine the final URL after redirection using python / urllib2?
I need to get the final URL after redirection in python. What's a good way to do that?
[ ">>> import urllib2\n>>> var = urllib2.urlopen('http://www.stackoverflow.com/')\n>>> var.geturl()\n'http://stackoverflow.com/'\n\n" ]
[ 8 ]
[]
[]
[ "python", "redirect", "urllib2" ]
stackoverflow_0002374122_python_redirect_urllib2.txt
Q: Django - Working with multiple forms What I'm trying to do is to manage several forms in one page, I know there are formsets, and I know how the form management works, but I got some problems with the idea I have in mind. Just to help you to imagine what my problem is I'm going to use the django example models: fr...
Django - Working with multiple forms
What I'm trying to do is to manage several forms in one page, I know there are formsets, and I know how the form management works, but I got some problems with the idea I have in mind. Just to help you to imagine what my problem is I'm going to use the django example models: from django.db import models class Poll(mod...
[ "Use the prefix kwarg\nYou can declare your form as:\nform = MyFormClass(prefix='some_prefix')\n\nand then, as long as the prefix is the same, process data as:\nform = MyFormClass(request.POST, prefix='some_prefix')\n\nDjango will handle the rest.\nThis way you can have as many forms of the same type as you want on...
[ 58 ]
[]
[]
[ "django", "django_forms", "forms", "python" ]
stackoverflow_0002374224_django_django_forms_forms_python.txt
Q: 2D integrals in SciPy I am trying to integrate a multivariable function in SciPy over a 2D area. What would be the equivalent of the following Mathematica code? In[1]:= F[x_, y_] := Cos[x] + Cos[y] In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]}] Out[2]= 0 Looking at the SciPy documentation I...
2D integrals in SciPy
I am trying to integrate a multivariable function in SciPy over a 2D area. What would be the equivalent of the following Mathematica code? In[1]:= F[x_, y_] := Cos[x] + Cos[y] In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]}] Out[2]= 0 Looking at the SciPy documentation I could only find support fo...
[ "I think it would work something like this:\ndef func(x,y):\n return cos(x) + cos(y)\n\ndef func2(y, a, b):\n return integrate.quad(func, a, b, args=(y,))[0]\n\nprint integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0]\n\nWolfram|Alpha agrees\nedit: I just discovered dblquad which seems to do exactly w...
[ 13, 9 ]
[]
[]
[ "integration", "multidimensional_array", "python", "scipy", "wolfram_mathematica" ]
stackoverflow_0002368337_integration_multidimensional_array_python_scipy_wolfram_mathematica.txt
Q: How does the following code to work? How to work with struct_time objects? If I do the following I can convert from a time_struct object to a datetime object: mydate = datetime.datetime(*time.localtime()[:6]) How does this code work? What do the * and the [:6] mean? A: * is argument unpacking, [:6] is slicing. ...
How does the following code to work? How to work with struct_time objects?
If I do the following I can convert from a time_struct object to a datetime object: mydate = datetime.datetime(*time.localtime()[:6]) How does this code work? What do the * and the [:6] mean?
[ "* is argument unpacking, [:6] is slicing. That is whatever is returned from time.localtime() (i.e., time.struct_time) is sliced and first 6 elements are unpacked and 6 arguments passed to datetime.datetime. \nThere are plenty of question on SO re all of these topics.\n", "*time.localtime() means, that the tuple ...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002375101_python.txt
Q: In Django, how do I clear a sessionkey? I set a session like this: request.session['mykey']= 33 How do I clear it? I just want to DELETE it. A: del request.session['mykey']
In Django, how do I clear a sessionkey?
I set a session like this: request.session['mykey']= 33 How do I clear it? I just want to DELETE it.
[ " del request.session['mykey']\n\n" ]
[ 37 ]
[]
[]
[ "django", "python", "session" ]
stackoverflow_0002375335_django_python_session.txt
Q: Generate image for each font on a linux system using Python I'm looking for a way to list all fonts installed on a linux/Debian system, and then generate images of some strings using these fonts. I'm looking for your advice as I kind of see how to do each part, but not to do both: To list all fonts on a UNIX syst...
Generate image for each font on a linux system using Python
I'm looking for a way to list all fonts installed on a linux/Debian system, and then generate images of some strings using these fonts. I'm looking for your advice as I kind of see how to do each part, but not to do both: To list all fonts on a UNIX system, xlsfonts can do the trick: import os list_of_fonts=os.popen("...
[ "You can do this using pango, through the pygtk package. Pango can list fonts and render them.\n", "you best bet is to do a find on all the fonts on the system, and then use ImagesFont.load() on the results of that list. I don't know where the fonts are on Debian, but they should be in a well known folder you ca...
[ 1, 1 ]
[]
[]
[ "debian", "fonts", "linux", "python", "python_imaging_library" ]
stackoverflow_0002375125_debian_fonts_linux_python_python_imaging_library.txt
Q: What is the best, python or bash for generating strings from combinations of letters? I need to generate the strings STA and STB. STA and STB are strings of length 10, and each one can contain only the characters A,T,G or C. I have to generate all possible combinations of STA, and depending on STA, I generate STB....
What is the best, python or bash for generating strings from combinations of letters?
I need to generate the strings STA and STB. STA and STB are strings of length 10, and each one can contain only the characters A,T,G or C. I have to generate all possible combinations of STA, and depending on STA, I generate STB. The ways is that the character A is always associated with T and viceversa and G with C an...
[ "I'd say Python.\nHave a look here for string permutations: Permutations using a Combinations Generator (Python). Another thing to look at is itertools in Python 2.6+ - Generating all permutations of a list in python. I do note however that your requirements are more in depth, however you will probably find it easi...
[ 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002374201_bash_python.txt
Q: Python Type Conversion Whats the best way to convert int's, long's, double's to strings and vice versa in python. I am looping through a list and passing longs to a dict that should be turned into a unicode string. I do for n in l: {'my_key':n[0],'my_other_key':n[1]} Why are some of the most obvious thin...
Python Type Conversion
Whats the best way to convert int's, long's, double's to strings and vice versa in python. I am looping through a list and passing longs to a dict that should be turned into a unicode string. I do for n in l: {'my_key':n[0],'my_other_key':n[1]} Why are some of the most obvious things so complicated?
[ "To convert from a numeric type to a string:\nstr(100)\n\nTo convert from a string to an int:\nint(\"100\")\n\nTo convert from a string to a float:\nfloat(\"100\")\n\n", "You could do it like this in Python 2.x:\n>>> l = ((1,2),(3,4))\n>>> dict(map(lambda n: (n[0], unicode(n[1])), l))\n{1: u'2', 3: u'4'}\n\nor in...
[ 37, 2, 0 ]
[]
[]
[ "int", "python", "types" ]
stackoverflow_0002375334_int_python_types.txt
Q: How to do a dregradê on wx.Panel Background? I want to color the background (SetBackgroundColour) of a wx.Panel with a blue to black degradê. How can I make it? A: Adapted from DaniWeb: import wx class MyFrame(wx.Frame): def __init__(self, parent=None, title=None): wx.Frame.__init__(self, parent, wx...
How to do a dregradê on wx.Panel Background?
I want to color the background (SetBackgroundColour) of a wx.Panel with a blue to black degradê. How can I make it?
[ "Adapted from DaniWeb:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent=None, title=None):\n wx.Frame.__init__(self, parent, wx.ID_ANY, title)\n self.panel = wx.Panel(self, size=(350, 450))\n # this sets up the painting canvas\n self.panel.Bind(wx.EVT_PAINT, self.on_...
[ 5 ]
[]
[]
[ "colors", "panel", "python", "wxpython" ]
stackoverflow_0002375158_colors_panel_python_wxpython.txt
Q: Create a python function procedurally (specifically the arguments) Question How do you procedurally create a function in Python which takes specific named arguments but allow those argument names to be data-driven? Example Say, you want to create a class decorator, with_init, which adds an __init__ method with spe...
Create a python function procedurally (specifically the arguments)
Question How do you procedurally create a function in Python which takes specific named arguments but allow those argument names to be data-driven? Example Say, you want to create a class decorator, with_init, which adds an __init__ method with specific named arguments such that the following two classes are equivalent...
[ "Very roughly. This accepts kw args and checks to see that the number of args is correct\ndef __call__(self, cls):\n def init(cls_self, *args, **kw):\n if len(args)+len(kw) != len(self.params):\n raise RuntimeError(\"Wrong number of arguments\")\n for param, value in zip(self.params, arg...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002375316_python.txt
Q: Is it possible to dock wx.auiManager panes onto tops/bottoms of another panes? with this code: import wx import wx.aui class MyFrame(wx.Frame): def __init__(self, parent, id=-1, title='wx.aui Test', pos=wx.DefaultPosition, size=(800, 600), style=wx.DEFAULT_FRAME_STYLE): ...
Is it possible to dock wx.auiManager panes onto tops/bottoms of another panes?
with this code: import wx import wx.aui class MyFrame(wx.Frame): def __init__(self, parent, id=-1, title='wx.aui Test', pos=wx.DefaultPosition, size=(800, 600), style=wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, parent, id, title, pos, size, style) self._mgr ...
[ "Maybe the AuiNotebook wxPython sample works for you?\nimport wx\nimport wx.aui\n\n########################################################################\nclass TabPanel(wx.Panel):\n \"\"\"\n This will be the first notebook tab\n \"\"\"\n #--------------------------------------------------------------...
[ 1 ]
[]
[]
[ "dock", "python", "wxpython" ]
stackoverflow_0002375613_dock_python_wxpython.txt
Q: Debugging Python Crash I am building Python 2.6 4 from source on a Linux server and am experiencing a Segmentation Fault when running the tests (make test) (test_hashlib.py and test_hmac.py). When I opened the core dump file in gdb, I am told that the error is at 0x00002b73379ac446 in ??. I then recompiled pytho...
Debugging Python Crash
I am building Python 2.6 4 from source on a Linux server and am experiencing a Segmentation Fault when running the tests (make test) (test_hashlib.py and test_hmac.py). When I opened the core dump file in gdb, I am told that the error is at 0x00002b73379ac446 in ??. I then recompiled python with both my CFLAGS and CP...
[ "Typically you need to set CFLAGS before calling ./configure - it is usually written to bake a CFLAGS value into the Makefile.\n" ]
[ 0 ]
[]
[]
[ "debugging", "gdb", "linux", "python" ]
stackoverflow_0002376029_debugging_gdb_linux_python.txt
Q: Static Variables in Python C API How would one expose "static" variables like this class MyClass: X = 1 Y = 2 via the C API? The only variable on the PyTypeObject that looks like it would work is tp_members, but I see no flag in the PyMemberDef to indicate that the member should be per-class, not per-inst...
Static Variables in Python C API
How would one expose "static" variables like this class MyClass: X = 1 Y = 2 via the C API? The only variable on the PyTypeObject that looks like it would work is tp_members, but I see no flag in the PyMemberDef to indicate that the member should be per-class, not per-instance. For a bit more clarification, si...
[ "Just put them in the type's tp_dict e.g. with PyDict_SetItemString.\n" ]
[ 12 ]
[]
[]
[ "python", "python_c_api" ]
stackoverflow_0002374334_python_python_c_api.txt
Q: Emacs collaborative buffers open in the wrong mode I am using Emacs and Rudel to collaborate with a remote programmer. Rudel has a concept of published buffers. When my partner publishes a buffer, I can subscribe to it and the we can both edit it simultaneously. My problem is that when he publishes a Python file...
Emacs collaborative buffers open in the wrong mode
I am using Emacs and Rudel to collaborate with a remote programmer. Rudel has a concept of published buffers. When my partner publishes a buffer, I can subscribe to it and the we can both edit it simultaneously. My problem is that when he publishes a Python file with a *.py extension and I subscribe to it, my buffer ...
[ "I don't know Rudel well enough to give a 100% solution, but what you want to do is something like this:\n(add-hook 'rudel-document-attach-hook 'my-rudel-set-mode-appropriately)\n(defun my-rudel-set-mode-appropriately (document buffer)\n \"try to set the mode appropriately\"\n (set-buffer buffer)\n (let ((buffer...
[ 3, 0 ]
[]
[]
[ "collaboration", "emacs", "pair_programming", "python" ]
stackoverflow_0002375473_collaboration_emacs_pair_programming_python.txt
Q: Python:Which way gives better precision Is there any difference in precision between one time assignment: res=n/k and multiple assignment in for cycle: for i in range(n): res+=1/k ? A: Floating-point division a/b is not mathematical division a ÷ b, except in very rare* circumstances. Generally, floati...
Python:Which way gives better precision
Is there any difference in precision between one time assignment: res=n/k and multiple assignment in for cycle: for i in range(n): res+=1/k ?
[ "Floating-point division a/b is not mathematical division a ÷ b, except in very rare* circumstances. \nGenerally, floating point division a/b is a ÷ b + ε. \nThis is true for two reasons.\n\nFloat numbers (except in rare cases) are an approximation of the decimal number.\na is a + εa. \nb is b + εb.\nFloat numbe...
[ 8, 3, 1, 0, 0, 0 ]
[]
[]
[ "precision", "python" ]
stackoverflow_0002368626_precision_python.txt
Q: Regex redefinition error I am using python, and run into some redefinition error, I know they are redefinition but logically its not possible to reach that since its an or. Is there a way to get around this? I appreciate for any help in advance /python-2.5/lib/python2.5/re.py", line 233, in _compile raise erro...
Regex redefinition error
I am using python, and run into some redefinition error, I know they are redefinition but logically its not possible to reach that since its an or. Is there a way to get around this? I appreciate for any help in advance /python-2.5/lib/python2.5/re.py", line 233, in _compile raise error, v # invalid expression sre_...
[ "Regular expression syntax simply does not allow multiple occurrences of identically-named groups -- groups that aren't \"reached\" are defined to be \"empty\" (None) on a match.\nSo you have to change those names e.g. to dob0, dob1, dob2 and id0, id1, id2 (then you can easily \"collapse\" these sets of keys to mak...
[ 2, 2, 1 ]
[]
[]
[ "python", "regex", "scripting" ]
stackoverflow_0002376049_python_regex_scripting.txt
Q: How do I remove a column from a table in beautifulsoup (Python) I have an html table, and I would like to remove a column. What is the easiest way to do this with BeautifulSoup or any other python library? A: lxml.html is nicer for manipulating HTML, IMO. Here's some code that will remove the second column of a...
How do I remove a column from a table in beautifulsoup (Python)
I have an html table, and I would like to remove a column. What is the easiest way to do this with BeautifulSoup or any other python library?
[ "lxml.html is nicer for manipulating HTML, IMO. Here's some code that will remove the second column of an HTML table.\nfrom lxml import html\n\ntext = \"\"\"\n<table>\n<tr><th>head 1</th><th>head 2</th><th>head 3</th></tr>\n<tr><td>item 1</td><td>item 2</td><td>item 3</td></tr>\n</table>\n\"\"\"\n\ntable = html.fra...
[ 2 ]
[]
[]
[ "beautifulsoup", "html_table", "python" ]
stackoverflow_0002376427_beautifulsoup_html_table_python.txt
Q: Apache using Python 2.4, Python 2.5 scripts failing Using CentOS5, I have Apache configured with the following directives. Alias /pscript/ /var/www/pscript/ <Directory "/var/www/pscript/"> Options +ExecCGI DirectoryIndex thetest.py AddHandler cgi-script .py </Directory> When I call www.domain.com/pscr...
Apache using Python 2.4, Python 2.5 scripts failing
Using CentOS5, I have Apache configured with the following directives. Alias /pscript/ /var/www/pscript/ <Directory "/var/www/pscript/"> Options +ExecCGI DirectoryIndex thetest.py AddHandler cgi-script .py </Directory> When I call www.domain.com/pscript/ then my python script runs and prints out my sys.pat...
[ "Does the Python script have a first line something like:\n#!/usr/bin/python\n\nIf so, maybe /usr/bin/python is Python version 2.4, while running python directly from the command line is running a different Python executable (version 2.5) from somewhere else in your path. Try:\nwhich python\n\nto see what executabl...
[ 3 ]
[]
[]
[ "apache", "python" ]
stackoverflow_0002376768_apache_python.txt
Q: Markdown and Syntax Highlighting in Django with mixed code I have some problems with following string while trying to syntax highlight them: Example <code class="php"><? echo "<input type=\"text\">"; ?></code> The php part is rendered correctly, but the html part breaks. I use the Markdown and Syntax Highlightin...
Markdown and Syntax Highlighting in Django with mixed code
I have some problems with following string while trying to syntax highlight them: Example <code class="php"><? echo "<input type=\"text\">"; ?></code> The php part is rendered correctly, but the html part breaks. I use the Markdown and Syntax Highlighting snippet from http://www.djangosnippets.org/snippets/119/ Any ...
[ "Looks like you need to pass your PHP/HTML hybrid code through the escape filter, to convert instances of < to &lt; etc.\nUse it like this in a template, assuming you've got your code in a template context variable called mycode:\n{{ mycode|escape }}\n\n", "Python markdown integrates with Pygments that do the syn...
[ 1, 1 ]
[]
[]
[ "django", "markdown", "python", "syntax_highlighting" ]
stackoverflow_0002070831_django_markdown_python_syntax_highlighting.txt
Q: wx.TR_HAS_VARIABLE_ROW_HEIGHT has no effect? I created a TreeListCtrl in wxPython like following. self.tree = wx.gizmos.TreeListCtrl(self, style = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_HIDE_ROOT | wx.TR_HAS_VARIA...
wx.TR_HAS_VARIABLE_ROW_HEIGHT has no effect?
I created a TreeListCtrl in wxPython like following. self.tree = wx.gizmos.TreeListCtrl(self, style = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_HIDE_ROOT | wx.TR_HAS_VARIABLE_ROW_HEIGHT) As you see i set wx.TR_HAS_VARIAB...
[ "wx.TR_HAS_VARIABLE_ROW_HEIGHT applies to wx.TreeCntrl not wx.gizmos.TreeListCtrl, read http://www.wxpython.org/docs/api/wx.gizmos.TreeListCtrl-class.html to see what that tree cntrl can do\nIf you see the doc or code for wx.gizmos.TreeListCtrl it derives from wx.Control, so it seems to be a a generic implementatio...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002377094_python_wxpython.txt
Q: How do I print number of notes to be played? How do I do the second line in my main argument? def main(): pic= makePicture( pickAFile()) ### It will print the number of notes to be played(which is the number of pixels in the pic divided by 16, why?)### listenToPicture(pic) def listenToPicture(pic):...
How do I print number of notes to be played?
How do I do the second line in my main argument? def main(): pic= makePicture( pickAFile()) ### It will print the number of notes to be played(which is the number of pixels in the pic divided by 16, why?)### listenToPicture(pic) def listenToPicture(pic): show(pic) w= getWidth(pic) h= getHei...
[ "in function listenToPicture(), you have this code:\nw= getWidth(pic)\nh= getHeight(pic)\nfor i in range(0, w, 4):\n for j in range(0, h, 4):\n ....\n\nstrangely, i and j are not used in the rest of the code, but seem to explain why the number of notes are the number of pixels divided by 16.\nthe key is i...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002376788_python.txt
Q: How do I loop through every 4th pixel in every 4th row, using Python? Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next , it will loop through every 4th pixel in every 4th row and do the following. It will compute the total of the red, green and blue ...
How do I loop through every 4th pixel in every 4th row, using Python?
Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next , it will loop through every 4th pixel in every 4th row and do the following. It will compute the total of the red, green and blue levels of the pixel, divide that by 9, then add the result to 24. That numb...
[ "Stepped ranges come to mind range(0, len(), 4) but I don't know the type of your pic.\n", "Here's some building blocks you could base your program on:\n#!/usr/bin/env python\nimport easygui\nimport Image\nimport numpy\n\nfilename = easygui.fileopenbox() # pick a file\nim = Image.open(filename) # make picture\nim...
[ 3, 1, 1, 0 ]
[]
[]
[ "audio", "image", "python" ]
stackoverflow_0002376505_audio_image_python.txt
Q: Django form INSERTs when I want it to UPDATE I'm new to Django but I seem to have nearly identical code working on another site. I can update a record in the Django shell, but in view.py the same code insists on INSERTing a new record when I run this form. I have a "DisciplineEvent" object in the model. I let Dj...
Django form INSERTs when I want it to UPDATE
I'm new to Django but I seem to have nearly identical code working on another site. I can update a record in the Django shell, but in view.py the same code insists on INSERTing a new record when I run this form. I have a "DisciplineEvent" object in the model. I let Django create the "id" field for the primary key. I ...
[ "What you are trying to do is unconventional and a possible security hole.\nYou should not get the instance of the object from the hidden id key you populated in the form. Users can easily change this one and get your code to overwrite some other model instance that they may not even have permission for.\nThe stand...
[ 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002376797_django_python.txt
Q: deprecation of apply decorator There was a beautiful way to organize class property in frame of one function, by using the apply decorator. class Example(object): @apply def myattr(): doc = """This is the doc string.""" def fget(self): return self._half * 2 def fset(s...
deprecation of apply decorator
There was a beautiful way to organize class property in frame of one function, by using the apply decorator. class Example(object): @apply def myattr(): doc = """This is the doc string.""" def fget(self): return self._half * 2 def fset(self, value): self._half ...
[ "\nIs there any possibility to achieve such simplicity and readability for property\n\nThe new Python 2.6 way is:\n@property\ndef myattr(self):\n \"\"\"This is the doc string.\"\"\"\n return self._half * 2\n\n@myattr.setter\ndef myattr(self, value):\n self._half = value / 2\n\n@myattr.deleter\ndef myattr(s...
[ 12, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002377573_python.txt
Q: Python check for blank CSV value not working I have a CSV file and I am running a script against it to insert into a database. If the value is blank then I don't want to insert it. Here is what I have if attrs[attr] != '' and attrs[attr] != None: log.info('Attriute ID: %s' % attr) log.info...
Python check for blank CSV value not working
I have a CSV file and I am running a script against it to insert into a database. If the value is blank then I don't want to insert it. Here is what I have if attrs[attr] != '' and attrs[attr] != None: log.info('Attriute ID: %s' % attr) log.info('Attriute Value: %s' % attrs[attr]) s...
[ "It's probably whitespace i.e. a tab or string with spaces try:-\nattrs[attr].strip()\n\n", "Presumably it contains whitespace. You could check this by printing repr(attrs[attr]) which will put quotes round it and show tabs at \"\\t\"\nChange the code to if attrs[attr] is not None and attrs[attr].strip() !=\"\":...
[ 4, 3, 1 ]
[]
[]
[ "csv", "null", "python" ]
stackoverflow_0002375604_csv_null_python.txt
Q: Django Timed Events I want to schedule events to happen for my users. Is there an efficient way to do this in Python/Django easily? I'd prefer not to poll a priority queue. Thanks! Edit: I want to clarify that this job is run per user, for potentially hundreds or thousands of users. A: This may help: Django - Se...
Django Timed Events
I want to schedule events to happen for my users. Is there an efficient way to do this in Python/Django easily? I'd prefer not to poll a priority queue. Thanks! Edit: I want to clarify that this job is run per user, for potentially hundreds or thousands of users.
[ "This may help:\nDjango - Set Up A Scheduled Job?\n", "You should probably look at: http://celeryproject.org/\nFrom the website:\n\n\"Celery is already used in production to process millions of tasks a day.\"\n\n", "How about django-cron? \n" ]
[ 2, 2, 0 ]
[]
[]
[ "django", "python", "scheduled_tasks", "scheduling" ]
stackoverflow_0002377661_django_python_scheduled_tasks_scheduling.txt
Q: Imports in Python project with doctests I have a Python project with following directory structure: /(some files) /model/(python files) /tools/(more python files) ... So, I have Python files in couple subdirectories and there are some dependencies between directories as well: tools are used by model, etc. Now m...
Imports in Python project with doctests
I have a Python project with following directory structure: /(some files) /model/(python files) /tools/(more python files) ... So, I have Python files in couple subdirectories and there are some dependencies between directories as well: tools are used by model, etc. Now my problem is that I want to make doctests for...
[ "What you are trying to do is a relative import. It works fine in Python, but on the module level, not on the file system level. I know, this is confusing.\nIt means that if you run a script in a subdir, it doesn't see the upper dirs because for the running script, the root of the module is the current dir: there i...
[ 2, 1, 0 ]
[]
[]
[ "linux", "path", "python", "unix" ]
stackoverflow_0002372125_linux_path_python_unix.txt
Q: Need help on python sqlite? 1.I have a list of data and a sqlite DB filled with past data along with some stats on each data. I have to do the following operations with them. Check if each item in the list is present in DB. if no then collect some stats on the new item and add them to DB. Check if each item in DB...
Need help on python sqlite?
1.I have a list of data and a sqlite DB filled with past data along with some stats on each data. I have to do the following operations with them. Check if each item in the list is present in DB. if no then collect some stats on the new item and add them to DB. Check if each item in DB is in the list. if no delete it ...
[ "\nIt does not need to check anything, just use INSERT OR IGNORE in first case (just make sure you have corresponding unique fields so INSERT would not create duplicates) and DELETE FROM tbl WHERE data NOT IN ('first item', 'second item', 'third item') in second case.\nAs it is stated in the official SQLite FAQ, \"...
[ 0 ]
[]
[]
[ "multithreading", "python", "sqlite" ]
stackoverflow_0002378364_multithreading_python_sqlite.txt
Q: python datetime.time operation t1 = datetime.time(12, 10, 0, tzinfo=GMT1()) # 12:10 t2 = datetime.time(13, 13, 0, tzinfo=GMT1()) #13:13 t3 = datetime.time(23, 55, 0, tzinfo=GMT1()) #23:55 t4 = datetime.time(01, 10, 0, tzinfo=GMT1()) #01:10 I need the minute interval between between two times. For instance a non...
python datetime.time operation
t1 = datetime.time(12, 10, 0, tzinfo=GMT1()) # 12:10 t2 = datetime.time(13, 13, 0, tzinfo=GMT1()) #13:13 t3 = datetime.time(23, 55, 0, tzinfo=GMT1()) #23:55 t4 = datetime.time(01, 10, 0, tzinfo=GMT1()) #01:10 I need the minute interval between between two times. For instance a non working one: def minute_interval(st...
[ "Assuming time are in same timezone and no DST\nimport datetime\n\ndef minute_interval(start, end):\n reverse = False\n if start > end:\n start, end = end, start\n reverse = True\n\n delta = (end.hour - start.hour)*60 + end.minute - start.minute + (end.second - start.second)/60.0\n ...
[ 3, 1, 0 ]
[]
[]
[ "datetime", "intervals", "python" ]
stackoverflow_0002378521_datetime_intervals_python.txt
Q: Why does nose finds tests in files with only 644 permission? Today I ran a bunch of doctests using Python 2.6 on a Ubuntu 9.10 with nose : nosetests --with-doctest Ran 0 tests in 0.001s OK WTF? I had tests in that files, why didn't that work? I changed permission to 644: sudo chmod 644 * -R nosetests --with-doct...
Why does nose finds tests in files with only 644 permission?
Today I ran a bunch of doctests using Python 2.6 on a Ubuntu 9.10 with nose : nosetests --with-doctest Ran 0 tests in 0.001s OK WTF? I had tests in that files, why didn't that work? I changed permission to 644: sudo chmod 644 * -R nosetests --with-doctest Ran 11 test in 0.004s FAILED (errors=1) Changing it back to ...
[ "Try the --exe flag:\n$ nosetests --help\n\n... \n\n--exe Look for tests in python modules that are executable.\n Normal behavior is to exclude executable modules,\n since they may not be import-safe [NOSE_INCLUDE_EXE]\n\n" ]
[ 11 ]
[]
[]
[ "doctest", "nose", "permissions", "python" ]
stackoverflow_0002378146_doctest_nose_permissions_python.txt
Q: How to use Corba with Python I'm wondering if anyone have a good resource for working with Corba in Python? I've googled around and saw that fnorb was recommended by some, but that it doesn't support some new features in Corba. Omniorb seemed like a good alternative, but I have no idea how to use it with Python (n...
How to use Corba with Python
I'm wondering if anyone have a good resource for working with Corba in Python? I've googled around and saw that fnorb was recommended by some, but that it doesn't support some new features in Corba. Omniorb seemed like a good alternative, but I have no idea how to use it with Python (not fnorb either). Any advice is ap...
[ "What's wrong with the omniORBpy User's Guide ?\n" ]
[ 9 ]
[]
[]
[ "corba", "python" ]
stackoverflow_0002338331_corba_python.txt
Q: Accessing child nodein an xml in python How to retrieve the value of type in the below XML <info><category>Flip</category><info>2</info><type>Tree</type></info> A: Using ElementTree: import xml.etree.ElementTree as E e = E.parse("test.xml") print(e.find("type").text) Using minidom: import xml.dom.minidom d = x...
Accessing child nodein an xml in python
How to retrieve the value of type in the below XML <info><category>Flip</category><info>2</info><type>Tree</type></info>
[ "Using ElementTree:\nimport xml.etree.ElementTree as E\ne = E.parse(\"test.xml\")\nprint(e.find(\"type\").text)\n\nUsing minidom:\nimport xml.dom.minidom\nd = xml.dom.minidom.parse(\"test.xml\")\nprint(d.getElementsByTagName(\"type\")[0].firstChild.data)\n\nUsing BeautifulSoup:\nfrom BeautifulSoup import BeautifulS...
[ 2 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0002378834_python_xml_xml_parsing.txt
Q: Accessing python variables in a list In the following code below, how to retrieve the value of id,Id has multiple values in it.How to access the values of id and update it to result1 def parse_results (): try: xml = minidom.parseString(new_results) for xmlchild in xmldoc.childNodes[0].childNo...
Accessing python variables in a list
In the following code below, how to retrieve the value of id,Id has multiple values in it.How to access the values of id and update it to result1 def parse_results (): try: xml = minidom.parseString(new_results) for xmlchild in xmldoc.childNodes[0].childNodes : result1 = {} r...
[ "Why are you using minidom? It is really boring to use.\nI suggest you move to element tree:\nimport xml.etree.ElementTree as et\nd = et.fromstring('''\n<doc>\n <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info>\n <info><firstname>firstname</firstname><lastname>lastname</lastname><...
[ 0 ]
[]
[]
[ "class", "django_views", "python" ]
stackoverflow_0002378393_class_django_views_python.txt
Q: Installing a python module on windows I am trying to install a module called Swish-E 0.5 and for some reason im getting an error when running the command python setup.py install I keep getting this error no matter what module i try to install. I have tried installing other modules to see if the problem lay in th...
Installing a python module on windows
I am trying to install a module called Swish-E 0.5 and for some reason im getting an error when running the command python setup.py install I keep getting this error no matter what module i try to install. I have tried installing other modules to see if the problem lay in that specific module however it does not. c:\...
[ "I you haven't already, install Swish-e. If you have, then grab the development files from the source tarball and put them somewhere the compiler can find them.\n", "Search your hard disk for the file swish-e.h and make sure the directory is mentioned in the command line after a -I (= add include path).\n", "Yo...
[ 0, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002379238_python_windows.txt
Q: Python modules matching a pattern I'd like to run doctests for a set of modules (glob: invenio.webtag*) from a single module, but I'll need a way to import all these (and only these) modules and run doctest.testmod() on all of them. Any ideas? Edit: The solution: import doctest import glob import os import pkgutil...
Python modules matching a pattern
I'd like to run doctests for a set of modules (glob: invenio.webtag*) from a single module, but I'll need a way to import all these (and only these) modules and run doctest.testmod() on all of them. Any ideas? Edit: The solution: import doctest import glob import os import pkgutil pkgpath = pkgutil.extend_path([], 'inv...
[ "A module can be dynamically loaded using __import__ e.g.\nmy_module = __import__(\"mymodule\")\n\nand then passed to testmod e.g.\ndoctest.testmod(my_module)\n\nAssuming you can build a list of the matching modules using either glob.glob or filtering the results from os.listdir you should be able to use this appro...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002379285_python.txt
Q: Getting pubsubhubbub hub working I have followed the instructions found at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide to setup a hub. When I start the hub I get following warnings $ sudo python2.5 google_appengine/dev_appserver.py pubsubhubbub/hub/ INFO 2010-03-04 12:29:57,928 appe...
Getting pubsubhubbub hub working
I have followed the instructions found at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide to setup a hub. When I start the hub I get following warnings $ sudo python2.5 google_appengine/dev_appserver.py pubsubhubbub/hub/ INFO 2010-03-04 12:29:57,928 appengine_rpc.py:157] Server: appengine.go...
[ "The tutorial at http://code.google.com/p/pubsubhubbub/wiki/DeveloperGettingStartedGuide is outdated, you need to use at least google app engine 1.2.8 to make it work (where New memcache offset_multi method and batch support in incr and decr. is added)\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "websub" ]
stackoverflow_0002379263_google_app_engine_python_websub.txt
Q: problem opening a text document - unicode error i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using: import sys try: d = open("p0901aus.txt" , "W") ex...
problem opening a text document - unicode error
i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using: import sys try: d = open("p0901aus.txt" , "W") except: print("Unsucessfull") sys.exit(0) i am eithe...
[ "\n(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \\UXXXXXXXX escape\n\nThis probably means that the file you are trying to read is not in the encoding that open() expects. Apparently open() expects some Unicode encoding (most likely UTF-8 or UTF-16), but your file is not encoded...
[ 5, 2, 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0000778096_python_unicode.txt
Q: Converting date/time in YYYYMMDD/HHMMSS format to Python datetime I have a date in YYYYMMDD format and a time in HHMMSS format as strings in the 4th and 5th elements in a list. I.E.: data[4] = '20100304' data[5] = '082835' I am creating an instance of datetime (in a field named generates) like this: generatedtim...
Converting date/time in YYYYMMDD/HHMMSS format to Python datetime
I have a date in YYYYMMDD format and a time in HHMMSS format as strings in the 4th and 5th elements in a list. I.E.: data[4] = '20100304' data[5] = '082835' I am creating an instance of datetime (in a field named generates) like this: generatedtime = datetime.datetime(int(data[4][:4]),int(data[4][4:6]),int(data[4][6:...
[ "No need to import time; datetime.datetime.strptime can do it by itself.\nimport datetime\ndt=datetime.datetime.strptime(data[4]+data[5],'%Y%m%d%H%M%S')\nprint(dt)\n# 2010-03-04 08:28:35\n\nFor information on the format codes (e.g. %Y%m%d%H%M%S) available, see the docs for strftime.\n", "You might take a look at ...
[ 55, 8, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002380013_datetime_python.txt
Q: Determine current Mac Safari web page using Python Is there a way to determine programmatically, using Python, which web page is currently active in Safari? A: An Applescript example is here, and the relevant part is: tell application "Safari" set url_list to URL of every document end tell Python/AppleScrip...
Determine current Mac Safari web page using Python
Is there a way to determine programmatically, using Python, which web page is currently active in Safari?
[ "An Applescript example is here, and the relevant part is:\ntell application \"Safari\"\n set url_list to URL of every document\nend tell\n\nPython/AppleScript translation is covered here. E.g., install appscript as described here:\nsudo easy_install appscript\n\nand then, as shown here, you can do e.g.:\n>>> i...
[ 6 ]
[]
[]
[ "macos", "python", "safari" ]
stackoverflow_0002380031_macos_python_safari.txt
Q: Django/App Engine/Python 2.5: default __new__ takes no parameters New to app engine and django. I think this is an issue with my django install, which is 1.1.1, but I've also read that I can just use the django packaged with the app engine SDK. Any help on why I'm getting this error when I test locally would be g...
Django/App Engine/Python 2.5: default __new__ takes no parameters
New to app engine and django. I think this is an issue with my django install, which is 1.1.1, but I've also read that I can just use the django packaged with the app engine SDK. Any help on why I'm getting this error when I test locally would be greatly appreciated. The callback: Variable Value callback <class 'ourl...
[ "You appear to have subclassed (at least once) a Django's view class with an __init__ (but not a __new__) with a non-standard signature. If you click on the triangle towards the beginning of this message (in your own environment -- the click doesn't work on this copy/pasted msg in SO, of course;-) you should see t...
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002377627_django_google_app_engine_python.txt
Q: How to write back to a certain cell in google doc spreadsheet using python So the problem is, i get some information from first column of the row (for example A2 ) from the spreadsheet, then i will do some checking with that information, after that i want to write back to the next column in the row the result, how...
How to write back to a certain cell in google doc spreadsheet using python
So the problem is, i get some information from first column of the row (for example A2 ) from the spreadsheet, then i will do some checking with that information, after that i want to write back to the next column in the row the result, how do i do that? Is there a certain function to allow me to indicate the column be...
[ "Sure, the docs for Google Spreadsheet API in Python are here. To create or update a cell, see here; to get the \"cell range feed\" you need, see here -- basically to say \"below\" for example, get the cell feed for the specific column you want and the two rows (the one you're reading and the one you're writing), ...
[ 1 ]
[]
[]
[ "google_sheets_api", "python" ]
stackoverflow_0002378104_google_sheets_api_python.txt
Q: Python AST processing I have a Python AST [as returned by ast.parse()]. I know this is an AST of a class method. How do I find all calls to other methods of the same class? Basically, I want to collect something like: ['foo', 'bar'] for a code snippet like: def baz(self): # this is a class method '''baz docst...
Python AST processing
I have a Python AST [as returned by ast.parse()]. I know this is an AST of a class method. How do I find all calls to other methods of the same class? Basically, I want to collect something like: ['foo', 'bar'] for a code snippet like: def baz(self): # this is a class method '''baz docstring''' self.foo() + se...
[ "The general approach is to subclass ast.NodeVisitor:\n>>> class VisitCalls(ast.NodeVisitor):\n... def visit_Call(self, what):\n... if what.func.value.id == 'self':\n... print what.func.attr\n... \n>>> f='''def x(self):\n... return self.bar() + self.baz()\n... '''\n>>> xx = ast.parse(f)\n>>> VisitCall...
[ 18 ]
[]
[]
[ "abstract_syntax_tree", "python" ]
stackoverflow_0002379355_abstract_syntax_tree_python.txt
Q: urllib ignore authentication requests I'm having little trouble creating a script working with URLs. I'm using urllib.urlopen() to get content of desired URL. But some of these URLs requires authentication. And urlopen prompts me to type in my username and then password. What I need is to ignore every URL that'll...
urllib ignore authentication requests
I'm having little trouble creating a script working with URLs. I'm using urllib.urlopen() to get content of desired URL. But some of these URLs requires authentication. And urlopen prompts me to type in my username and then password. What I need is to ignore every URL that'll require authentication, just easily skip i...
[ "You are right about the urllib2.HTTPError exception:\n\nexception urllib2.HTTPError\nThough being an exception (a subclass of URLError), an HTTPError can also function as a non-exceptional file-like return value (the same thing that urlopen() returns). This is useful when handling exotic HTTP errors, such as reque...
[ 1 ]
[]
[]
[ "python", "urllib", "urlopen" ]
stackoverflow_0002380623_python_urllib_urlopen.txt
Q: Error installing scrapy on Mac Os X 10.6 Trying to install Scrapy on Mac OSX 10.6 using this guide: When running these commands from Terminal: cd libxml2-2.7.3/python sudo make install I get the following error: Making install in . make[1]: *** No rule to make target `../libxslt/libxslt.la', needed by `libxsltmod...
Error installing scrapy on Mac Os X 10.6
Trying to install Scrapy on Mac OSX 10.6 using this guide: When running these commands from Terminal: cd libxml2-2.7.3/python sudo make install I get the following error: Making install in . make[1]: *** No rule to make target `../libxslt/libxslt.la', needed by `libxsltmod.la'. Stop. make: *** [install-recursive] Err...
[ "The simplest approach is to use MacPorts to install python and the libraries you need. \n", "Credit to @Ned Deily\nThese steps seem to work if you want to run Scrapy 0.8 on OS X 10.6. It uses Macports install of Python 2.6 rather than the one bundled with the OS. Steps assume Macports is not installed yet.\nGet ...
[ 2, 1 ]
[]
[]
[ "libxml2", "macos", "python", "scrapy" ]
stackoverflow_0002372758_libxml2_macos_python_scrapy.txt
Q: C++ iostreams and python Is it possible to interoperate with a C++ iostream and python? I'm using boost-python and want to wrap a function that has istream and ostream as arguments. A: Is http://cci.lbl.gov/cctbx_sources/boost_adaptbx/python_streambuf.h what you are looking for? It comes from the Phenix project....
C++ iostreams and python
Is it possible to interoperate with a C++ iostream and python? I'm using boost-python and want to wrap a function that has istream and ostream as arguments.
[ "Is http://cci.lbl.gov/cctbx_sources/boost_adaptbx/python_streambuf.h what you are looking for? It comes from the Phenix project. \n(license information at http://cci.lbl.gov/cctbx_sources/boost_adaptbx/LICENSE_2_0.txt)\n" ]
[ 3 ]
[]
[]
[ "boost_python", "iostream", "python" ]
stackoverflow_0002378005_boost_python_iostream_python.txt
Q: Loading a document on OpenOffice using an external Python program I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet. I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as: import uno #...
Loading a document on OpenOffice using an external Python program
I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet. I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as: import uno # get the uno component context from the PyUNO runtime localContext = un...
[ "It has been a long time since I did anything with PyUNO, but looking at the code that worked last time I ran it back in '06, I did my load document like this:\ndef urlify(path):\n return uno.systemPathToFileUrl(os.path.realpath(path))\n\ndesktop.loadComponentFromURL(\n urlify(tempfilename), \"_blank\", ...
[ 4, 3 ]
[]
[]
[ "python", "pyuno" ]
stackoverflow_0002153843_python_pyuno.txt
Q: Turning on DEBUG on a Django production site I'm using the Django ORM in a non-Django application and would like to turn on the DEBUG setting so that I can periodically log my queries. So I have something vaguely like this: from django.db import connection def thread_main_loop(): while keep_going: co...
Turning on DEBUG on a Django production site
I'm using the Django ORM in a non-Django application and would like to turn on the DEBUG setting so that I can periodically log my queries. So I have something vaguely like this: from django.db import connection def thread_main_loop(): while keep_going: connection.queries[:] = [] do_something() ...
[ "In DEBUG mode any error in your application will lead to the detailed Django stacktrace. This is very undesirable in a production environment as it will probably leak sensitive information that attackers can use against your site. Even if your application seems pretty stable, I wouldn't risk it.\nI would rather em...
[ 3 ]
[]
[]
[ "debugging", "django", "python" ]
stackoverflow_0002380726_debugging_django_python.txt
Q: set() runtime in python Just wondering what the run time of lookup for set() is? O(1) or O(n)? if I have x = set() whats the runtime of if "a" in x: print a in set! A: set is implemented using a hash, so the lookup is, on average, close to O(1). The worst case is O(n), where n objects have colliding hashes.
set() runtime in python
Just wondering what the run time of lookup for set() is? O(1) or O(n)? if I have x = set() whats the runtime of if "a" in x: print a in set!
[ "set is implemented using a hash, so the lookup is, on average, close to O(1). The worst case is O(n), where n objects have colliding hashes.\n" ]
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0002381026_python.txt
Q: Can hotshot be used in multiple threads? I have a long-running multithreaded program, and I'd like to occasionally like to call a function with Profile.runcall and dump the data to a file. The hotshot documentation states: Note: The hotshot profiler does not yet work well with threads. It is useful to use an unthr...
Can hotshot be used in multiple threads?
I have a long-running multithreaded program, and I'd like to occasionally like to call a function with Profile.runcall and dump the data to a file. The hotshot documentation states: Note: The hotshot profiler does not yet work well with threads. It is useful to use an unthreaded script to run the profiler over the code...
[ "For what it's worth, we have a setting in CubicWeb (which uses multiple threads) to enable hotshot profiling, and so far I've never experienced issues when enabling profiling. \n" ]
[ 1 ]
[]
[]
[ "multithreading", "profile", "profiler", "profiling", "python" ]
stackoverflow_0002379954_multithreading_profile_profiler_profiling_python.txt
Q: Python's AppKit and ObjectiveC Delegates AppKit allows Python programs on a Mac to use ObjectiveC classes. I am not very familiar with ObjectiveC, but I want to access the NSSound class using AppKit in order to create an audio player. My player should perform some action, such as loading the next item from the pla...
Python's AppKit and ObjectiveC Delegates
AppKit allows Python programs on a Mac to use ObjectiveC classes. I am not very familiar with ObjectiveC, but I want to access the NSSound class using AppKit in order to create an audio player. My player should perform some action, such as loading the next item from the playlist, when the current audio finishes playing...
[ "The first step towards successful development of a PyObjC based Cocoa/AppKit application is to learn Objective-C and then learn Cocoa.\nThe second step is to drop Python and just use Objective-C for your application.\nPyObjC (and MacRuby) are awesome technologies, but success with both requires that you understand...
[ 4 ]
[]
[]
[ "appkit", "macos", "objective_c", "python" ]
stackoverflow_0002379473_appkit_macos_objective_c_python.txt
Q: How does one produce a specific unicode character with Python's C-API? I'm writing a Python extension that runs through a Py_UNICODE array, finds specific (ASCII, if it matters) characters, i.e. '\' or '\n', and does some additional stuff for each one that it finds. Is there a way to write those characters as lite...
How does one produce a specific unicode character with Python's C-API?
I'm writing a Python extension that runs through a Py_UNICODE array, finds specific (ASCII, if it matters) characters, i.e. '\' or '\n', and does some additional stuff for each one that it finds. Is there a way to write those characters as literals? If not, what is the correct way to obtain Py_UNICODEs for them, keepi...
[ "Use PyUnicode_FromWideChar() or one of the built-in codec decode functions.\n" ]
[ 1 ]
[]
[]
[ "python", "python_c_api", "unicode" ]
stackoverflow_0002381132_python_python_c_api_unicode.txt
Q: Redirect Python standard input/output to C# forms application I apologize if this is a duplicate question, I searched a bit and couldn't find anything similar - I have a Python library that connects to my C# application via a socket in order to allow simple Python scripting (IronPython isn't an option right now fo...
Redirect Python standard input/output to C# forms application
I apologize if this is a duplicate question, I searched a bit and couldn't find anything similar - I have a Python library that connects to my C# application via a socket in order to allow simple Python scripting (IronPython isn't an option right now for a couple of reasons). I would like to create a Windows Forms cont...
[ "In case anyone else stumbles across this, I figured out the problem - by default, the Python interpreter only enters interactive mode if it detects that a TTY device is connected to standard input (which is normally only true if the program is run from the console). In order to redirect the standard IO streams, yo...
[ 21, 1 ]
[]
[]
[ "c#", "python", "redirect", "stdin", "stdout" ]
stackoverflow_0002380649_c#_python_redirect_stdin_stdout.txt
Q: Replace a string of characters with some special characters? when i input some texts/strings, i want them to appear either as hidden or with some special characters(as we do while entering password). . . how can i implement it in a python program? pls help me. A: Use getpass import getpass getpass.getpass() A: ...
Replace a string of characters with some special characters?
when i input some texts/strings, i want them to appear either as hidden or with some special characters(as we do while entering password). . . how can i implement it in a python program? pls help me.
[ "Use getpass\nimport getpass\ngetpass.getpass()\n\n", "You want the getpass module.\n" ]
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002381423_python.txt
Q: wsdl2py requests I'm trying to get results from a SOAP service called Chrome ADS (for vehicle data). They provided php and Java samples, but I need python (our site is in Django). My question is: What should I be passing as a request to the SOAP service when using wsdl2py-generated classes? Following the examples ...
wsdl2py requests
I'm trying to get results from a SOAP service called Chrome ADS (for vehicle data). They provided php and Java samples, but I need python (our site is in Django). My question is: What should I be passing as a request to the SOAP service when using wsdl2py-generated classes? Following the examples I'm using a DataVersio...
[ "It looks like you might be passing a class to service.getDataVersions() the second time instead of an instance (it can't be an instance if it doesn't have __class__).\nWhat's happening is isinstance() returns false, and in the process of trying to raise a type error, an attribute error gets raised instead because ...
[ 1, 0 ]
[]
[]
[ "python", "soap", "wsdl" ]
stackoverflow_0002375956_python_soap_wsdl.txt
Q: Can someone explain pipe buffer deadlock? Python documentation to Popen states: Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Now, I'm trying to figure out how this deadlock ca...
Can someone explain pipe buffer deadlock?
Python documentation to Popen states: Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. Now, I'm trying to figure out how this deadlock can occur and why. My mental model: subproccess p...
[ "Careful, this has a subtle mistake in it.\n\nMy mental model: subproccess produces\n something to stdout/err, which is\n buffered and after buffer is filled,\n it's flushed to stdout/err of\n subproccess, which is send through\n pipe to parent process.\n\nThe buffer is shared by parent and child process. \nS...
[ 10, 5 ]
[]
[]
[ "operating_system", "pipe", "python" ]
stackoverflow_0002381751_operating_system_pipe_python.txt
Q: How to write a unittest for importing a module in Python What is the pythonic way of writing a unittest to see if a module is properly installed? By properly installed I mean, it does not raise an ImportError: No module named foo. A: As I have to deploy my Django application on a different server and it requ...
How to write a unittest for importing a module in Python
What is the pythonic way of writing a unittest to see if a module is properly installed? By properly installed I mean, it does not raise an ImportError: No module named foo.
[ "\nAs I have to deploy my Django\n application on a different server and\n it requires some extra modules I want\n to make sure that all required modules\n are installed.\n\nThis is not a unit test scenario at all.\nThis is a production readiness process and it isn't -- technically -- a test of your application...
[ 5, 1 ]
[]
[]
[ "django", "python", "unit_testing" ]
stackoverflow_0002381535_django_python_unit_testing.txt
Q: Python Lambda with Or Reading the documentation it seems this might not be possible, but it seems that a lot of people have been able to beat more complicated functionality into pythons lambda function. I'm leveraging the scapy libraries to do some packet creation. Specially this questions is about the Conditiona...
Python Lambda with Or
Reading the documentation it seems this might not be possible, but it seems that a lot of people have been able to beat more complicated functionality into pythons lambda function. I'm leveraging the scapy libraries to do some packet creation. Specially this questions is about the ConditionalField which takes it a fie...
[ "lambda pkt:((pkt.chksumpresent == 1) or (pkt.special == 1))\n\n", "Is lambda the most readable/maintainable? The following is just as performant:\ndef checksum_condition(pkt):\n return pkt.chksumpresent == 1 or pkt.special == 1\n\nConditionalField(XShortField(\"chksum\",None), checksum_condition)\n\n" ]
[ 8, 6 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0002382023_lambda_python.txt
Q: wsdl2py ComplexTypes How do I add complex types to a SOAP request? I'm using WSDL2py generated requests, and trying to use the other TypeDefinitions that it made in the ***_types.py file (like AccountInfo, for authentication, that goes into every request). Then passing it the wsdl2py generated server, and I'm gett...
wsdl2py ComplexTypes
How do I add complex types to a SOAP request? I'm using WSDL2py generated requests, and trying to use the other TypeDefinitions that it made in the ***_types.py file (like AccountInfo, for authentication, that goes into every request). Then passing it the wsdl2py generated server, and I'm getting this error: >>> from A...
[ "So... found out that the problem is I needed to run wsdl2py with the --complextypes flag.This creates a whole slew of awesome methods inside of the reqeust object. methods like new_XXXXX where X is the name of the complex type that's required by that request.\n" ]
[ 2 ]
[]
[]
[ "python", "soap", "wsdl" ]
stackoverflow_0002382650_python_soap_wsdl.txt
Q: Creating a palindrome list with reverse() I want to take a list [0,1,2] and turn it into [0,1,2,2,1,0]. Right now, I've got r = list(mus) r.reverse() mus = mus + r but it seems like there should be a better way. Can anyone come up with a good, pythonic one-liner? A: It looks like you might be in need of mus.ext...
Creating a palindrome list with reverse()
I want to take a list [0,1,2] and turn it into [0,1,2,2,1,0]. Right now, I've got r = list(mus) r.reverse() mus = mus + r but it seems like there should be a better way. Can anyone come up with a good, pythonic one-liner?
[ "It looks like you might be in need of\nmus.extend(reversed(mus))\n\nOr if you simply need to iterate over this and not necessarily form the list, use\nimport itertools\nfor item in itertools.chain(mus, reversed(mus)):\n do_something...\n\n", "Just a few of the many ways to do this are:\n\nm = l + reversed(l)\...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002382905_python.txt
Q: What is the associativity of Python's ** operator? I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8. Can someone explain the behavior I found? I don't see any way to group the operati...
What is the associativity of Python's ** operator?
I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8. Can someone explain the behavior I found? I don't see any way to group the operations with parentheses to actually get a result of 65536 l...
[ "2** (2**(2**2))\n\nfrom http://docs.python.org/reference/expressions.html\nOperators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).\n", ...
[ 6, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002383034_python.txt
Q: Does Django support multi-value cookies? I'd like to set a cookie via Django with that has several different values to it, similar to .NET's HttpCookie.Values property. Looking at the documentation, I can't tell if this is possible. It looks like it just takes a string, so is there another way? I've tried passing ...
Does Django support multi-value cookies?
I'd like to set a cookie via Django with that has several different values to it, similar to .NET's HttpCookie.Values property. Looking at the documentation, I can't tell if this is possible. It looks like it just takes a string, so is there another way? I've tried passing it an array ([10, 20, 30]) and dictionary ({'n...
[ ".NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem.\nI will say that you're doing the right thing, in not usin...
[ 7, 1, 1, 0 ]
[]
[]
[ "cookies", "django", "python" ]
stackoverflow_0000128815_cookies_django_python.txt
Q: %windir% in Python? How can I do something like if sys.argv[0] != '%windir%\\blabla.exe' I'm having no success at all A: import os if sys.argv[0] != os.path.join(os.environ['WINDIR'],'blalah.exe'): A: This should illustrate how to get the location of Windows: >>> import os >>> os.environ['windir'] 'C:\\Window...
%windir% in Python?
How can I do something like if sys.argv[0] != '%windir%\\blabla.exe' I'm having no success at all
[ "import os\nif sys.argv[0] != os.path.join(os.environ['WINDIR'],'blalah.exe'):\n\n", "This should illustrate how to get the location of Windows:\n>>> import os\n>>> os.environ['windir']\n'C:\\\\Windows'\n\n", "if sys.argv[0] != '%windir%\\\\blabla.exe'\n\nWhat are you trying to do here?\nargv[0] is, generally, ...
[ 5, 4, 2, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002383306_python_windows.txt
Q: Opening links in external browser in Amarok 1.4 I've tried asking this question on the KDE development forum, but haven't received a satisfying answer so far. I've developed a Python script for Amarok 1.4 which retrieves upcoming events for the currently playing artist and displays them in the context browser. Th...
Opening links in external browser in Amarok 1.4
I've tried asking this question on the KDE development forum, but haven't received a satisfying answer so far. I've developed a Python script for Amarok 1.4 which retrieves upcoming events for the currently playing artist and displays them in the context browser. The user can click each event to know more about it, bu...
[ "I know nothing about Amarok, but in general you can spawn the platform's default web browser on a URL:\n\non modern open-source desktops (KDE, GNOME, Xfce) by spawning the xdg-open command;\non OS X with the open command;\non Windows with the built-in os.startfile method.\n\nThere is also the webbrowser module, bu...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002382263_python.txt
Q: Rendering mathematical notation in Python / OpenGL? How can I render mathematical notations / expressions in Python with OpenGL? I'm actually using pyglet however it uses OpenGL. Such things as this: I can't store static images as I am generating the expressions as well. A: I would say generate suitable latex e...
Rendering mathematical notation in Python / OpenGL?
How can I render mathematical notations / expressions in Python with OpenGL? I'm actually using pyglet however it uses OpenGL. Such things as this: I can't store static images as I am generating the expressions as well.
[ "I would say generate suitable latex expression, rendering it into an image, then load the image as a texture.\n", "You can use GL_TEXTURE_RECTANGLE_ARB opengl extension to quickly load dynamicaly generated image of arbitrary size into OpenGL texture. \nYou can look for python examples of using dynamic vector gra...
[ 10, 3, 1 ]
[]
[]
[ "math", "opengl", "pyglet", "python", "rendering" ]
stackoverflow_0002377944_math_opengl_pyglet_python_rendering.txt
Q: How to I make the result of this a variable? right now its set up to write to a file, but I want it to output the value to a variable. not sure how. from BeautifulSoup import BeautifulSoup import sys, re, urllib2 import codecs woof1 = urllib2.urlopen('someurl').read() woof_1 = BeautifulSoup(woof1) woof2 = urllib2...
How to I make the result of this a variable?
right now its set up to write to a file, but I want it to output the value to a variable. not sure how. from BeautifulSoup import BeautifulSoup import sys, re, urllib2 import codecs woof1 = urllib2.urlopen('someurl').read() woof_1 = BeautifulSoup(woof1) woof2 = urllib2.urlopen('someurl').read() woof_2 = BeautifulSoup...
[ "values = []\nfor row in woof_1.findAll(\"tr\", { \"class\" : \"row_b\" }):\n for col in row.findAll(re.compile('td')):\n if col.string:\n values.append(col.string)\nresult = ''.join(values)\n\n" ]
[ -1 ]
[ "maybe like this.\ngedb = \"\";\nfor row in woof_1.findAll(\"tr\", { \"class\" : \"row_b\" }):\n for col in row.findAll(re.compile('td')):\n if col.string:\n gedb += col.string\n\n\n", "Get rid of all mentions of GE_DB.\nDo a\n outputtext = \"\"\ntowards the beginning.\nReplace GE_DB.write(col.string ...
[ -1, -1, -2 ]
[ "beautifulsoup", "python", "scrape", "variables" ]
stackoverflow_0002383546_beautifulsoup_python_scrape_variables.txt
Q: strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array Here's a very simple way to build an suffix array from a string in python: def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffi...
strcmp for python or how to sort substrings efficiently (without copy) when building a suffix array
Here's a very simple way to build an suffix array from a string in python: def sort_offsets(a, b): return cmp(content[a:], content[b:]) content = "foobar baz foo" suffix_array.sort(cmp=sort_offsets) print suffix_array [6, 10, 4, 8, 3, 7, 11, 0, 13, 2, 12, 1, 5, 9] However, "content[a:]" makes a copy of content, w...
[ "The buffer function does not copy the whole string, but creates an object that only references the source string. Using interjay's suggestion, that would be:\nsuffix_array.sort(key=lambda a: buffer(content, a))\n\n", "I don't know if there's a fast way to compare substrings, but you can make your code much faste...
[ 6, 5, 3, 0 ]
[]
[]
[ "python", "sorting", "string", "suffix_array" ]
stackoverflow_0002282579_python_sorting_string_suffix_array.txt
Q: Regex: Using lookahead assertion to check if character exist at most a certain number of times How do I use lookahead assertion to determine if a certain character exist at most a certain number of times in a string. For example, let's say I want to check a string that has at least one character to make sure that ...
Regex: Using lookahead assertion to check if character exist at most a certain number of times
How do I use lookahead assertion to determine if a certain character exist at most a certain number of times in a string. For example, let's say I want to check a string that has at least one character to make sure that it contains "@" at most 2 times. Thanks in advance. Using python if that matters.
[ "There are lots of ways to do this, for example:\n/^(?=([^@]*@){,2}[^@]*$)./\n\n", "Using a negative lookahead assertion, you can make sure that @ doesn't occur three times:\n(?!.*@.*@.*@.*).*\n\n", "I believe Mark's answer wont quite work as you need to exclude the @ from being matched at other times. Try this...
[ 5, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002383682_python_regex.txt
Q: Change Node Display Size in Networkx I am not using GraphViz because I am having problems with making it play nice with Networkx. I know this is weird, but I've tried many suggestions to fix this problem, but I just seem to have some of the worst luck in the world. Therefore the problem that I have must be solved ...
Change Node Display Size in Networkx
I am not using GraphViz because I am having problems with making it play nice with Networkx. I know this is weird, but I've tried many suggestions to fix this problem, but I just seem to have some of the worst luck in the world. Therefore the problem that I have must be solved withing Networkx without using GraphViz. M...
[ "Try nx.draw(G, node_size=size), where size can be a scalar or an array of length equal to the number of nodes.\n" ]
[ 31 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002383121_networkx_python.txt
Q: key/value (general) and tokyo cabinet (python tc-specific) question i have been in the RDBMS world for many years now but wish to explore the whole nosql movement. so here's my first question: is it bad practice to have the possibility of duplicate keys? for example, an address book keyed off of last name (most ...
key/value (general) and tokyo cabinet (python tc-specific) question
i have been in the RDBMS world for many years now but wish to explore the whole nosql movement. so here's my first question: is it bad practice to have the possibility of duplicate keys? for example, an address book keyed off of last name (most probably search item?) could have multiple entities. is it bad practice ...
[ "This depend on no-sql implementation. Cassandra, for example, allows range queries, so you could model data to do queries on last name, or with full name (starting with last name, then first name).\nBeyond this, many simpler key-value stores would indeed require you to store a list structure (or such) for multi-va...
[ 1, 0 ]
[]
[]
[ "python", "tokyo_cabinet" ]
stackoverflow_0002068473_python_tokyo_cabinet.txt
Q: Why aren't there any dates in the Netflix.com NewWatchInstantlyRSS feed entries (when parsed with feedparser)? The output from the following: import feedparser d = feedparser.parse('http://www.netflix.com/NewWatchInstantlyRSS') d.entries[177].keys() is: ['summary_detail', 'links', 'title', 'summary', 'guidislink'...
Why aren't there any dates in the Netflix.com NewWatchInstantlyRSS feed entries (when parsed with feedparser)?
The output from the following: import feedparser d = feedparser.parse('http://www.netflix.com/NewWatchInstantlyRSS') d.entries[177].keys() is: ['summary_detail', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'id'] According to http://feedparser.org/docs/common-rss-elements.html, there should be a...
[ "IF you look at the raw source of the RSS feed at http://www.netflix.com/NewWatchInstantlyRSS (Open in a web browser and view the source) you'll see they did not include a date element. There SHOULD be, but there is not.\nEDIT: Sorry I didn't read your question completely. I don't know where Google is getting its v...
[ 1 ]
[]
[]
[ "feedparser", "netflix", "python", "rss" ]
stackoverflow_0002384056_feedparser_netflix_python_rss.txt
Q: Using Numpy to find the average distance in a set of points I have an array of points in unknown dimensional space, such as: data=numpy.array( [[ 115, 241, 314], [ 153, 413, 144], [ 535, 2986, 41445]]) and I would like to find the average euclidean distance between all points. Please note that I have over 20,000 ...
Using Numpy to find the average distance in a set of points
I have an array of points in unknown dimensional space, such as: data=numpy.array( [[ 115, 241, 314], [ 153, 413, 144], [ 535, 2986, 41445]]) and I would like to find the average euclidean distance between all points. Please note that I have over 20,000 points, so I would like to do this as efficiently as possible. Th...
[ "If you have access to scipy, you could try the following:\nscipy.spatial.distance.cdist(data,data)\n", "Well, I don't think that there is a super fast way to do this, but this should do it:\ntot = 0.\n\nfor i in xrange(data.shape[0]-1):\n tot += ((((data[i+1:]-data[i])**2).sum(1))**.5).sum()\n\navg = tot/((da...
[ 13, 5, 4, 4, 4, 1 ]
[]
[]
[ "algorithm", "distance", "numpy", "performance", "python" ]
stackoverflow_0002383645_algorithm_distance_numpy_performance_python.txt
Q: Why is '' > 0 True in Python 2? In Python 2.x: >>> '' > 0 True Why is that? A: The original design motivation for allowing order-comparisons of arbitrary objects was to allow sorting of heterogeneous lists -- usefully, that would put all strings next to each other in alphabetical order, and all numbers next to ...
Why is '' > 0 True in Python 2?
In Python 2.x: >>> '' > 0 True Why is that?
[ "The original design motivation for allowing order-comparisons of arbitrary objects was to allow sorting of heterogeneous lists -- usefully, that would put all strings next to each other in alphabetical order, and all numbers next to each other in numerical order, although which of the two blocks came first was not...
[ 92, 23 ]
[]
[]
[ "logic", "operators", "python", "python_2.x" ]
stackoverflow_0002384078_logic_operators_python_python_2.x.txt
Q: python: _winreg problem the windows registry may contain keys whose names with embedded nulls when i call _winreg.OpenKey(key, subkey_string_with_embbeded_null) i get the following error: TypeError: OpenKey() argument 2 must be string without null bytes or None, not str Q1: is the meaning of the error that python...
python: _winreg problem
the windows registry may contain keys whose names with embedded nulls when i call _winreg.OpenKey(key, subkey_string_with_embbeded_null) i get the following error: TypeError: OpenKey() argument 2 must be string without null bytes or None, not str Q1: is the meaning of the error that python _winreg module has a limitat...
[ "Q1: right.\nQ2: download and install win32all.\n" ]
[ 4 ]
[]
[]
[ "python", "winreg" ]
stackoverflow_0002384064_python_winreg.txt
Q: Crontab job does not start... ideas? thanks for helping me setting my cron jobs, crontab has really been a gold mine for me. Unfortunately I have a problem, and have no idea what so ever what it might be... basically a job does not start while the neighbour jobs do. I'll explain This is my crontabs job list: */1...
Crontab job does not start... ideas?
thanks for helping me setting my cron jobs, crontab has really been a gold mine for me. Unfortunately I have a problem, and have no idea what so ever what it might be... basically a job does not start while the neighbour jobs do. I'll explain This is my crontabs job list: */10 * * * * python /webapps/foo/manage.py f...
[ "Cron always runs in an environment different to what you think :-)\nI always have my cronjobs set up like:\n*/10 * * * * ( date ; python /webapps/foo/manage.py fetch_articles ) >>/tmp/fetch.out 2>&1\n\nto ensure that there's something logged that I can look at.\nThis will narrow your problem down to either:\n\ncro...
[ 6, 4, 1 ]
[]
[]
[ "cron", "crontab", "linux", "python", "ubuntu" ]
stackoverflow_0002384225_cron_crontab_linux_python_ubuntu.txt
Q: Python in SU cron gives different output than manually execution Ubuntu Server 9.10, Here is my file, test.py import commands blkid = commands.getoutput('blkid') print blkid When I manually run (as SU) this: python test.py I get the output of the blkid as expected: /dev/sda1: UUID="3f0ac5bb-f0da-4574-81f5-778445...
Python in SU cron gives different output than manually execution
Ubuntu Server 9.10, Here is my file, test.py import commands blkid = commands.getoutput('blkid') print blkid When I manually run (as SU) this: python test.py I get the output of the blkid as expected: /dev/sda1: UUID="3f0ac5bb-f0da-4574-81f5-77844530b561" TYPE="ext4" /dev/sda5: UUID="67df0e7c-74fb-47dd-8520-ad720fbed...
[ "The problem is probably with your $PATH versus root's (os.environ['PATH'] if you're looking at it in Python rather than shell;-). root's PATH is typically very conservative (it would be risky for it NOT to be!) and since you're running blkid without specifying an absolute path that may easily mean that it's on yo...
[ 2, 0 ]
[]
[]
[ "cron", "crontab", "python", "sudo" ]
stackoverflow_0002384327_cron_crontab_python_sudo.txt
Q: py2app Not Finding BeautifulSoup I have a script that uses BeautifulSoup that I want to make into a standalone app using py2app. When I run the app made by py2app I get an error saying that the module BeautifulSoup could not be found. My sys.path has '/Library/Python/2.6/site-packages/BeautifulSoup-3.1.0.1-py2.6...
py2app Not Finding BeautifulSoup
I have a script that uses BeautifulSoup that I want to make into a standalone app using py2app. When I run the app made by py2app I get an error saying that the module BeautifulSoup could not be found. My sys.path has '/Library/Python/2.6/site-packages/BeautifulSoup-3.1.0.1-py2.6.egg' so it seems like it should be th...
[ "Ppy2app doesn't work with python eggs. You need to extract the contents of the egg (a zip file), or install BeuatifulSoup from a different source. I Believe BeautifulSoup is 1 source file, so you could just copy it into you app folder.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "py2app", "python" ]
stackoverflow_0002384296_beautifulsoup_py2app_python.txt
Q: How to get the Python date object for last Wednesday Using Python I would like to find the date object for last Wednesday. I can figure out where today is on the calendar using isocalendar, and determine whether or not we need to go back a week to get to the previous Wednesday. However, I can't figure out how to...
How to get the Python date object for last Wednesday
Using Python I would like to find the date object for last Wednesday. I can figure out where today is on the calendar using isocalendar, and determine whether or not we need to go back a week to get to the previous Wednesday. However, I can't figure out how to create a new date object with that information. Essentia...
[ "I think you want this. If the specified day is a Wednesday it will give you that day.\nfrom datetime import date\nfrom datetime import timedelta\nfrom calendar import WEDNESDAY\n\ntoday = date.today()\noffset = (today.weekday() - WEDNESDAY) % 7\nlast_wednesday = today - timedelta(days=offset)\n\nExample, the last ...
[ 58, 9 ]
[ "read http://docs.python.org/library/datetime.html\nWrite your own function using date2 = date1 - timedelta(days=1) and date.isoweekday() iterating over previous days while isoweek is not equal to 3(Wednesday)\n", "I'm not sure if this meets your requirements, but it should get you the Wednesday closest to a gi...
[ -1, -1 ]
[ "date", "datetime", "python" ]
stackoverflow_0002381786_date_datetime_python.txt
Q: Sqlalchemy - Can we use date comparison in relation definition? I have this mapper defined: mapper(Resource, resource_table, properties = {'type' : relation(ResourceType,lazy = False), 'groups' : relation(Group, secondary = model.tables['resource_group'], backref = 'resources'), 'parent' : relation(Rel...
Sqlalchemy - Can we use date comparison in relation definition?
I have this mapper defined: mapper(Resource, resource_table, properties = {'type' : relation(ResourceType,lazy = False), 'groups' : relation(Group, secondary = model.tables['resource_group'], backref = 'resources'), 'parent' : relation(Relation, uselist=False, primaryjoin = and_(relation_table.c.res_...
[ "I have actually found what was wrong.\nThe relation is actually working.\nThe problem was solved by setting the end_date to something like datetime.now() - 1 second, so it happens before the resource is actually refreshed by SQLAlchemy.\nA milliseconds issue I suppose.\nRichard Lopes\n" ]
[ 0 ]
[]
[]
[ "database", "mapper", "orm", "python", "sqlalchemy" ]
stackoverflow_0002384438_database_mapper_orm_python_sqlalchemy.txt
Q: SQLAlchemy - Problem with an association table and dates in primary join I am working on defining my mapping with SQLAlchemy and I am pretty much done except one thing. I have a 'resource' object and an association table 'relation' with several properties and a relationship between 2 resources. What I have been tr...
SQLAlchemy - Problem with an association table and dates in primary join
I am working on defining my mapping with SQLAlchemy and I am pretty much done except one thing. I have a 'resource' object and an association table 'relation' with several properties and a relationship between 2 resources. What I have been trying to do almost successfully so far, is to provide on the resource object 2 ...
[ "Consider using >= instead of > in date comparison.\n" ]
[ 0 ]
[]
[]
[ "database", "mapping", "orm", "python", "sqlalchemy" ]
stackoverflow_0002377220_database_mapping_orm_python_sqlalchemy.txt
Q: Why does Django say I haven't set DATABASE_ENGINE yet? I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database: import unittest from foo.models import ObjectType class DbTest(unittest.TestCase): def testDBConnection(se...
Why does Django say I haven't set DATABASE_ENGINE yet?
I have a Django project, and I'm somewhat of a newbie in it. I have the following PyUnit test trying to save an object into a PostgreSQL database: import unittest from foo.models import ObjectType class DbTest(unittest.TestCase): def testDBConnection(self): object_type = ObjectType() object_type...
[ "That's probably because you're running tests directly, i.e. just python testfile.py. This way you effectively bypass all Django mechanisms and use Model classes directly.\nThe downside is, the DB backend isn't set up automatically (by Django, which loads settings.py and connects to the appropriate DB), hence the e...
[ 3, 2, 2 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0001895916_django_postgresql_python.txt
Q: Sqlalchemy file organization Does anyone has any insight on organizing sqlalchemy based projects? I have many tables and classes with foreign keys, and relations. What is everyone doing in terms of separating classes, tables, and mappers ? I am relatively new to the framework, so any help would be appreciated. Exa...
Sqlalchemy file organization
Does anyone has any insight on organizing sqlalchemy based projects? I have many tables and classes with foreign keys, and relations. What is everyone doing in terms of separating classes, tables, and mappers ? I am relatively new to the framework, so any help would be appreciated. Example: classA.py # table definition...
[ "Take a look at Pylons project including SA setup.\nmeta.py includes engine and metadata objects\nmodels package includes declerative classes (no mapper needed). Inside that package, structure your classes by relavance into modules. \nMaybe a good example would be reddit source code:)\n", "There are two features ...
[ 3, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002377549_python_sqlalchemy.txt
Q: pycurl and lot of callback functions I have big URL list, which I have to download in parallel and check one of headers that is returned with each response. I can use CurlMulti for parallelization. I can use /dev/null as fb, because I am not interested in body, only headers. But how can I check each header? To rec...
pycurl and lot of callback functions
I have big URL list, which I have to download in parallel and check one of headers that is returned with each response. I can use CurlMulti for parallelization. I can use /dev/null as fb, because I am not interested in body, only headers. But how can I check each header? To receive header, I must set HEADERFUNCTION cal...
[ "I would use Python's built in httplib and threading modules. I don't see need for a 3rd party module.\n", "I know you're asking about pycurl, but I find it too hard and unpythonic to use. The API is weird.\nHere's a twisted example:\nfrom twisted.web.client import Agent\nfrom twisted.internet import reactor, de...
[ 1, 0, 0 ]
[]
[]
[ "libcurl", "pycurl", "python" ]
stackoverflow_0002379240_libcurl_pycurl_python.txt
Q: Debug/Monitor middleware for python wsgi applications I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields. Something like firefox live headers, but for the server side. A: That shouldn't be too hard to write y...
Debug/Monitor middleware for python wsgi applications
I'm searching a wsgi middleware which I can warp around a wsgi applications and which lets me monitor incoming and outgoing http requests and header fields. Something like firefox live headers, but for the server side.
[ "That shouldn't be too hard to write yourself as long as you only need the headers. Try that:\nimport sys\n\ndef log_headers(app, stream=None):\n if stream is None:\n stream = sys.stdout\n def proxy(environ, start_response):\n for key, value in environ.iteritems():\n if key.startswit...
[ 2, 2, 2, 1, 1 ]
[]
[]
[ "debugging", "middleware", "python", "wsgi" ]
stackoverflow_0000117986_debugging_middleware_python_wsgi.txt
Q: can't call __add__ through __getattr__( __getattribute__ ) It is object of the class A, in container's class tmpA. Not all method from A are in the tmpA. So for example: A + B is present , tmpA + B isn't present. I try to call method from A for tmpA. I can to call simple method, such as change(), but __add__ - ...
can't call __add__ through __getattr__( __getattribute__ )
It is object of the class A, in container's class tmpA. Not all method from A are in the tmpA. So for example: A + B is present , tmpA + B isn't present. I try to call method from A for tmpA. I can to call simple method, such as change(), but __add__ - don't work. If to remove inheritance from object, the code wor...
[ "Special methods are looked up on the class, that is, not on the instance of the class (except for some irregularities in old-style classes, which just mean a huge headache). So in particular the class's __getattr__ (for sane, new-style classes) is not getting called to look up __add__ when a + is performed - the ...
[ 7, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002384905_python.txt
Q: wx.ProgressDialog too small My program uses wx.ProgressDialog to give feedback on a process that is in multiple stages. At the beginning of each stage, I use the second argument of Update to change the message in the dialog. The problem is that the width of the dialog is determined from the message in the constru...
wx.ProgressDialog too small
My program uses wx.ProgressDialog to give feedback on a process that is in multiple stages. At the beginning of each stage, I use the second argument of Update to change the message in the dialog. The problem is that the width of the dialog is determined from the message in the constructor, and the dialog is not resiz...
[ "call wx.Fit() on the dialog, or you can use SetSize((x, y))\n" ]
[ 6 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002384397_python_wxpython.txt
Q: Counting Duplicates Integers in Python How do I find the total number of duplicates in a string? i.e., if it was j= [1,1,1,2,2,2] it would find 4 duplicates? I've only been able to find counting which shows how many times each individual number occurred. A: >>> j= [1,1,1,2,2,2] >>> len(j) - len(set(j)) 4 and bt...
Counting Duplicates Integers in Python
How do I find the total number of duplicates in a string? i.e., if it was j= [1,1,1,2,2,2] it would find 4 duplicates? I've only been able to find counting which shows how many times each individual number occurred.
[ ">>> j= [1,1,1,2,2,2]\n>>> len(j) - len(set(j))\n4\n\nand btw, j is a list and not a string, although for the purpose of this exercise it doesn't really matter.\n", "There seems to be a popular answer already, but if you would like to maintain the individual duplicate counts as well, the new Counter() collection ...
[ 17, 8 ]
[]
[]
[ "count", "duplicates", "python" ]
stackoverflow_0002385867_count_duplicates_python.txt
Q: Why does the "name" parameter to __setattr__ include the class, but __getattr__ doesn't? The following code: class MyClass(): def test(self): self.__x = 0 def __setattr__(self, name, value): print name def __getattr__(self, name): print name raise AttributeError(name) ...
Why does the "name" parameter to __setattr__ include the class, but __getattr__ doesn't?
The following code: class MyClass(): def test(self): self.__x = 0 def __setattr__(self, name, value): print name def __getattr__(self, name): print name raise AttributeError(name) x = MyClass() x.test() x.__y Outputs: _MyClass__x __y Traceback (most recent call last): ......
[ "The double underscore invokes name mangling. If you don't need name mangling, don't use double undescore\nWhat is the meaning of a single- and a double-underscore before an object name?\nFrom the Python docs\n\n9.6. Private Variables\n“Private” instance variables that cannot be accessed except from inside an objec...
[ 6, 1 ]
[]
[]
[ "getattr", "python", "setattr" ]
stackoverflow_0002386418_getattr_python_setattr.txt
Q: Python 2.6 - I can not write dwords greater than 0x7fffffff into registry using _winreg.SetValueEx() using regedit.exe I have manually created a key in registry called HKEY_CURRENT_USER/00_Just_a_Test_Key and created two dword values dword_test_1 and dword_test_2 I am trying to write some values into those two ...
Python 2.6 - I can not write dwords greater than 0x7fffffff into registry using _winreg.SetValueEx()
using regedit.exe I have manually created a key in registry called HKEY_CURRENT_USER/00_Just_a_Test_Key and created two dword values dword_test_1 and dword_test_2 I am trying to write some values into those two keys using following program import _winreg aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_CURRENT_USER...
[ "Most likely the function expects an int within the limits of a signed C integer, so you'll need to subtract 0x100000000 before passing to the function.\nYes, ideally this would be solved in the bindings. Unfortunately someone let this one slide.\n", "I have solved the problem the following way\nimport _winreg\n\...
[ 3, 1 ]
[]
[]
[ "python", "registry", "winreg" ]
stackoverflow_0002381205_python_registry_winreg.txt
Q: Is it possible to generate and return a ZIP file with App Engine? I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it. Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-...
Is it possible to generate and return a ZIP file with App Engine?
I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it. Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be genera...
[ "zipfile is available at appengine and reworked example follows:\nfrom contextlib import closing\nfrom zipfile import ZipFile, ZIP_DEFLATED\n\nfrom google.appengine.ext import webapp\nfrom google.appengine.api import urlfetch\n\ndef addResource(zfile, url, fname):\n # get the contents \n contents = urlfe...
[ 33, 9, 2 ]
[]
[]
[ "google_app_engine", "in_memory", "python", "zip" ]
stackoverflow_0000583791_google_app_engine_in_memory_python_zip.txt
Q: Is it possible to get the width of a character when using OpenGL bitmap fonts? I am trying to align my bitmap font text in my OpenGL application but I can't find anything on getting the width of each character. This is my renderText function: def renderText( self, text, fontFace, position ): ..... (omitted cod...
Is it possible to get the width of a character when using OpenGL bitmap fonts?
I am trying to align my bitmap font text in my OpenGL application but I can't find anything on getting the width of each character. This is my renderText function: def renderText( self, text, fontFace, position ): ..... (omitted code to make post shorter) glRasterPos2i( position[0], self.windowSize[1] - positio...
[ "glutBitmapWidth, glutBitmapLength — returns the width/length of a bitmap character/string.\nPython Specification:\nglutBitmapWidth(font, character) -> None\nglutBitmapLength(font, string) -> None\n\n" ]
[ 1 ]
[]
[]
[ "fonts", "opengl", "python", "text", "width" ]
stackoverflow_0002386849_fonts_opengl_python_text_width.txt
Q: OperationalError creating an index in sqlite EDIT: TL;DR version I typed this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); instead of this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE ON table_name (file_size); Don't do that. A: Some silly questions: Is it a concidence that the offending sta...
OperationalError creating an index in sqlite
EDIT: TL;DR version I typed this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); instead of this CREATE INDEX IF NOT EXISTS IDX_FILE_SIZE ON table_name (file_size); Don't do that.
[ "Some silly questions:\nIs it a concidence that the offending statement is missing the word ON?\nCREATE INDEX IF NOT EXISTS IDX_FILE_FULLPATH_FILE_PARENT_DIR ON table_name (file_fullpath, file_parent_dir);\nCREATE INDEX IF NOT EXISTS IDX_FILE_SIZE table_name (file_size); -- missing ON\nCREATE INDEX IF NOT EXISTS ID...
[ 5 ]
[]
[]
[ "indexing", "python", "sql", "sqlite" ]
stackoverflow_0002384754_indexing_python_sql_sqlite.txt
Q: Creating a custom Django form field that uses two s How can I make a Django field that renders itself as a pair of input fields? Reasoning: I am trying to write a new custom field. I will use it for a captcha-like service. The service works by requesting a question - then receiving one and a token. The validation ...
Creating a custom Django form field that uses two s
How can I make a Django field that renders itself as a pair of input fields? Reasoning: I am trying to write a new custom field. I will use it for a captcha-like service. The service works by requesting a question - then receiving one and a token. The validation happens by sending the answer along with the token. I wan...
[ "I think you're looking for the MultiWidget, you can simply give it 2 regular widgets and it will render the combination.\n", "Here you have a ready example(taken from my blog):\nclass ComplexMultiWidget(forms.MultiWidget):\n def __init__(self, attrs=None):\n widgets = (\n forms.TextInput(),\...
[ 9, 4, 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002386541_django_django_forms_python.txt
Q: Calculating difference within lists I have two files and the content is as follows: alt text http://img144.imageshack.us/img144/4423/screencapture2b.png alt text http://img229.imageshack.us/img229/9153/screencapture1c.png Please only consider the bolded column and the red column. The remaining text is junk and unn...
Calculating difference within lists
I have two files and the content is as follows: alt text http://img144.imageshack.us/img144/4423/screencapture2b.png alt text http://img229.imageshack.us/img229/9153/screencapture1c.png Please only consider the bolded column and the red column. The remaining text is junk and unnecessary. As evident from the two files t...
[ "The direct answer to your question is to alter the last condition, \nif y[35:38] !=x[35:38]:\nso that instead the \"field\" at [35:38] get converted to int (or float...) and a difference can be applied to them. Giving something like\n try:\n iy = int(y[35:38])\n ix = int(x[35:38])\n except ValueError:...
[ 2, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002387126_list_python.txt
Q: Django: Manually getting the view corresponding to a URL I have a Django project. Given a url, how can I know which view will be dispatched to handle the request? A: You want django.core.urlresolvers.resolve, which allows you to map an URL to a view and to keep your URL & view logic separate. This is the opposi...
Django: Manually getting the view corresponding to a URL
I have a Django project. Given a url, how can I know which view will be dispatched to handle the request?
[ "You want django.core.urlresolvers.resolve, which allows you to map an URL to a view and to keep your URL & view logic separate. This is the opposite of django.core.urlresolvers.reverse which allows you to map a view to a URL.\nSee the documentation for how to use it!\n" ]
[ 6 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0002387427_django_python_url.txt
Q: Batch Paypal Payments Can you send a paypal payment with a script? I've been googling for this, but I can't seem to find the answer I want (yes) ;-) An example of what I am talking about: Lets say I have a site where users share in the profit. Instead of sending each users payment out manually at the end of the...
Batch Paypal Payments
Can you send a paypal payment with a script? I've been googling for this, but I can't seem to find the answer I want (yes) ;-) An example of what I am talking about: Lets say I have a site where users share in the profit. Instead of sending each users payment out manually at the end of the month, I would like to aut...
[ "Yes. This page may help:\nhttps://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_masspay\nClarification edit:\nBasically you use the mass-pay API call. However, even though it's called mass pay, I believe you can send payments to just one person with it.\n", "You might want to ch...
[ 2, 2 ]
[]
[]
[ "django", "paypal", "python" ]
stackoverflow_0002387591_django_paypal_python.txt
Q: What is the most pythonic way to extend a list with the reversal of another? I have one list that I want to take a slice of, reverse that slice and append each of those items onto the end of another list. The following are the options I have thought of (although if you have others please share), which of these is...
What is the most pythonic way to extend a list with the reversal of another?
I have one list that I want to take a slice of, reverse that slice and append each of those items onto the end of another list. The following are the options I have thought of (although if you have others please share), which of these is the most pythonic? # Option 1 tmp = color[-bits:] tmp.reverse() my_list.extend(tm...
[ "I like\nmy_list.extend(reversed(color[-bits:]))\n\nIt explains what you are doing ( extending a list by reverse of another list's slice) and is short too.\nand a obligatory itertools solution\nmy_list.extend( itertools.islice( reversed(color), 0, bits))\n\n", "my_list.extend(color[:-(bits + 1):-1])\n\n", "For ...
[ 4, 0, 0 ]
[]
[]
[ "list", "python", "reverse" ]
stackoverflow_0002387558_list_python_reverse.txt
Q: how can I make a suggestion for a new feature in python Suppose I think I have a great idea for some feature that should be in python's standard library. Not something of the magnitude of a new keyword etc, just a suggestion for another decorator that would help a lot, IMO. How can I suggest such a feature to the ...
how can I make a suggestion for a new feature in python
Suppose I think I have a great idea for some feature that should be in python's standard library. Not something of the magnitude of a new keyword etc, just a suggestion for another decorator that would help a lot, IMO. How can I suggest such a feature to the consideration of the "python committee :)"?
[ "It really depends on the nature of the suggestion.\nIf it's a bug, it should definitely be put on the tracker. Otherwise, it probably should not go in the tracker right away. Python developers have specifically asked that the tracker not be used to create discussions, but to track implementation-specific aspects.\...
[ 10, 5, 3, 1, 0, 0, 0 ]
[]
[]
[ "pep", "python" ]
stackoverflow_0002386421_pep_python.txt
Q: Python - Can I access the object who call me? If I have this: class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() class C: def otherFunction(self): # here I wan't to have acces to the instance of A or B who call m...
Python - Can I access the object who call me?
If I have this: class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() class C: def otherFunction(self): # here I wan't to have acces to the instance of A or B who call me. ... # in main or other object (not matter wher...
[ "If this is for debugging purposes you can use inspect.currentframe():\nimport inspect\n\nclass C:\n def otherFunction(self):\n print inspect.currentframe().f_back.f_locals\n\nHere is the output:\n>>> A().callFunction(C())\n{'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951e...
[ 11, 3, 1 ]
[]
[]
[ "function_calls", "oop", "python" ]
stackoverflow_0002387756_function_calls_oop_python.txt
Q: Calling Java app with "subprocess" from Python and reading the Java app output What is the nicest way to read the output (i.e. via System.out.println) of a Java app which is called from Python with subprocess.Popen("java MyClass", shell=True) without writing and reading a file? (Using Jython etc is not a possibl...
Calling Java app with "subprocess" from Python and reading the Java app output
What is the nicest way to read the output (i.e. via System.out.println) of a Java app which is called from Python with subprocess.Popen("java MyClass", shell=True) without writing and reading a file? (Using Jython etc is not a possible solution)
[ "p1 = subprocess.Popen([\"/usr/bin/java\", \"MyClass\"], stdout=subprocess.PIPE)\nprint p1.stdout.read() \n\n", "I just found the solution:\np = subprocess.Popen(\"java MyClass\",\n shell=True,\n stdout=subprocess.PIPE)\noutput, errors = p.communicate()\n\nS.Mark's is fine too!\n" ]
[ 5, 3 ]
[]
[]
[ "communication", "java", "python" ]
stackoverflow_0002388423_communication_java_python.txt
Q: unbound python method, potentially scope issue I'm using iPython right now to interactively set up a Twisted network. The script that I run in iPython describes best of what I have to do: import router, pdb # creates nodes which encapsulate RandomVector and VectorAdder objects a = router.LocalNode(router.RandomVe...
unbound python method, potentially scope issue
I'm using iPython right now to interactively set up a Twisted network. The script that I run in iPython describes best of what I have to do: import router, pdb # creates nodes which encapsulate RandomVector and VectorAdder objects a = router.LocalNode(router.RandomVector, '/topic/a_c') b = router.LocalNode(router.Rand...
[ "I don't think this is a scoping issue. Are you sure you don't need to use:\na = router.LocalNode(router.RandomVector(), '/topic/a_c')\nb = router.LocalNode(router.RandomVector(), '/topic/b_c')\n\ni.e. instantiate the RandomVector you pass to LocalNode?\nThis recommendation is triggered by the Unboud method error m...
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002388359_python_twisted.txt