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: Why has Python decided against constant references? Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers. I have a large data s...
Why has Python decided against constant references?
Note: I'm not talking about preventing the rebinding of a variable. I'm talking about preventing the modification of the memory that the variable refers to, and of any memory that can be reached from there by following the nested containers. I have a large data structure, and I want to expose it to other modules, on a ...
[ "It's the same as with private methods: as consenting adults authors of code should agree on an interface without need of force. Because really really enforcing the contract is hard, and doing it the half-assed way leads to hackish code in abundance.\nUse get-only descriptors, and state clearly in your documentatio...
[ 13, 10, 8, 1, 1 ]
[]
[]
[ "constants", "language_design", "language_features", "python", "reference" ]
stackoverflow_0004192053_constants_language_design_language_features_python_reference.txt
Q: 'C-style' strings in Python A very popular question is how to reverse a C-Style string. The C-Style string by definition is a string that is terminated by a null('\0'). Using C(or maybe C++), it is possible to use pointers to manipulate the string to reverse its contents in-place. If somebody asks the question, "H...
'C-style' strings in Python
A very popular question is how to reverse a C-Style string. The C-Style string by definition is a string that is terminated by a null('\0'). Using C(or maybe C++), it is possible to use pointers to manipulate the string to reverse its contents in-place. If somebody asks the question, "How do you reverse a C-style strin...
[ "If you need to \"reverse a C-style string in Python\", I think the end result must also be a c-style string. \nThat is how I would understand the question, but the above answers do not support this.\nSee the interactive session below:\n>>> \n>>> original = \"abc\\0\"\n>>> finish_correct = \"cba\\0\"\n>>> original\...
[ 5, 3, 3, 1 ]
[]
[]
[ "null", "python", "string" ]
stackoverflow_0004238537_null_python_string.txt
Q: Python: Replace tags but preserve inner text? I have a string. "This is an [[example]] sentence. It is [[awesome]]." I want to replace all instances of [[.]] with <b>.</b> preserving the wildcard text matched by . The result should be: "This is an <b>example</b> sentence. It is <b>awesome</b>." I could go in and m...
Python: Replace tags but preserve inner text?
I have a string. "This is an [[example]] sentence. It is [[awesome]]." I want to replace all instances of [[.]] with <b>.</b> preserving the wildcard text matched by . The result should be: "This is an <b>example</b> sentence. It is <b>awesome</b>." I could go in and manually replace [[ with <b> and ]] with </b>, but i...
[ "You can just use the replace method on the string.\n>>> s = 'This is an [[example]] sentence. It is [[awesome]].'\n>>> s.replace('[[', '<b>').replace(']]', '</b>')\n\n'This is an <b>example</b> sentence. It is <b>awesome</b>.'\n\nJust to get some timeit results in here:\n$ python -mtimeit -s'import re' \"re.sub(r'...
[ 5, 3, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004236243_python_regex.txt
Q: Look for multiple occurances of a character using regex i using the pattern pat='dd|dddd' , and i thought it would either match dd or dddd. import re re.search(pat,'ddd') re.search(pat,'ddddd') any number of d(s) matches for that matter why is it so ? A: You'll need to anchor the regular expression somehow. A ...
Look for multiple occurances of a character using regex
i using the pattern pat='dd|dddd' , and i thought it would either match dd or dddd. import re re.search(pat,'ddd') re.search(pat,'ddddd') any number of d(s) matches for that matter why is it so ?
[ "You'll need to anchor the regular expression somehow. A regular expression searches within strings to find a pattern. So \"dd\" will be found in \"dddddddd\" at offset 0,1,2,3,4,5,6.\nIf you want to match only entire strings try ^dd$. ^ matches the beginning of a string, $ matches the end. So ^(dd|dddd)$ will...
[ 10, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004239346_python_regex.txt
Q: Suggestions on how to speed up a distance calculation Consider the following class: class SquareErrorDistance(object): def __init__(self, dataSample): variance = var(list(dataSample)) if variance == 0: self._norm = 1.0 else: self._norm = 1.0 / (2 * variance) ...
Suggestions on how to speed up a distance calculation
Consider the following class: class SquareErrorDistance(object): def __init__(self, dataSample): variance = var(list(dataSample)) if variance == 0: self._norm = 1.0 else: self._norm = 1.0 / (2 * variance) def __call__(self, u, v): # u and v are floats ret...
[ "The following cython code (I realize the first line of __init__ is different, I replaced it with random stuff because I don't know var and because it doesn't matter anyway - you stated __call__ is the bottleneck):\ncdef class SquareErrorDistance:\n cdef double _norm\n\n def __init__(self, dataSample):\n ...
[ 2, 0 ]
[]
[]
[ "performance", "python", "python_c_api" ]
stackoverflow_0004239371_performance_python_python_c_api.txt
Q: How can I get the key_name of the entry in Model() on GAE for Python? I have a Model() called Member and I'm inserting new entries using Member.get_or_insert(key_name='lipis') for example. My question is how can I get a key_name that I used to insert a new entry for a specific member? A: Do you mean how do you t...
How can I get the key_name of the entry in Model() on GAE for Python?
I have a Model() called Member and I'm inserting new entries using Member.get_or_insert(key_name='lipis') for example. My question is how can I get a key_name that I used to insert a new entry for a specific member?
[ "Do you mean how do you then find that record using the key name, or how do you take an entity and find its key name?\nTo get that record back out of the datastore, do:\nmyMember = Member.get_by_key_name('lipis')\n\n...if you have the member record and want to get its key name, you can then do:\nkeyName = myMember....
[ 20, 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004239709_google_app_engine_google_cloud_datastore_python.txt
Q: Dynamic Module loading scope in Python When I run the following sample: def a(): exec('import math') b() def b(): print math.cos(90) a() I get the following error: NameError: global name 'math' is not defined What I am trying to do is to dynamically load some modules from within the a() function an...
Dynamic Module loading scope in Python
When I run the following sample: def a(): exec('import math') b() def b(): print math.cos(90) a() I get the following error: NameError: global name 'math' is not defined What I am trying to do is to dynamically load some modules from within the a() function and use them in function b() I want it to be a...
[ "One approach for Python 2.x would be:\ndef a():\n exec 'import math' in globals()\n b()\n\ndef b():\n print math.cos(90)\n\na()\n\nBut I would generally recommend using __import__(). I don't know what you are actually trying to achieve, but maybe this works for you:\ndef a():\n global hurz\n hurz =...
[ 2, 2 ]
[]
[]
[ "dynamic", "module", "python", "scope" ]
stackoverflow_0004239797_dynamic_module_python_scope.txt
Q: Which Python libraries exist for extracting useful data from tweets? I've found this: https://github.com/dryan/twitter-text-py based on Matt Sanford's Ruby code however it hasn't been updated since June 2010. I've also found this: https://github.com/BonsaiDen/twitter-text-python based on Matt Sanford's Java code. ...
Which Python libraries exist for extracting useful data from tweets?
I've found this: https://github.com/dryan/twitter-text-py based on Matt Sanford's Ruby code however it hasn't been updated since June 2010. I've also found this: https://github.com/BonsaiDen/twitter-text-python based on Matt Sanford's Java code. Are there any others?
[ "Twitter has a list of libraries: http://dev.twitter.com/pages/libraries .\n" ]
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0004239984_python_twitter.txt
Q: How do I duplicate certificate authentication (Mumble (c/c++)) in Python? Alright so, before I really get into this post, I am going to have to warn you that this might not be an easy fix. Whoever reads and is able to reply to this post must know a lot of c/c++, and at least some python to be able to answer the q...
How do I duplicate certificate authentication (Mumble (c/c++)) in Python?
Alright so, before I really get into this post, I am going to have to warn you that this might not be an easy fix. Whoever reads and is able to reply to this post must know a lot of c/c++, and at least some python to be able to answer the question I have above. Basically, I have a connection method from Mumble (a VOIP...
[ "From the C++ code it looks like you simply need to have ssl support and negotiate with the correct certification file and encrypt the payload with the correct private key. Those certifications and privates keys are most likely stored in your original program somewhere. If there are non-standard Authorities that ...
[ 0 ]
[]
[]
[ "c++", "python", "ssl", "ssl_certificate", "voip" ]
stackoverflow_0003455472_c++_python_ssl_ssl_certificate_voip.txt
Q: Convert seconds to hh:mm:ss in Python How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss? I need to do this with Python code (and if possible in a Django template). A: I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch....
Convert seconds to hh:mm:ss in Python
How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss? I need to do this with Python code (and if possible in a Django template).
[ "I can't believe any of the many answers gives what I'd consider the \"one obvious way to do it\" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):\n>>> import time\n>>> time.strftime('%H:%M:%S', time.gmtime(12345))\n'03:25:45'\n\nDoing it in a Django templa...
[ 211, 106, 28, 27, 15, 12, 1, 1, 0 ]
[ "Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:\nminutes = seconds / 60\nhours = minutes / 60\n\nNow, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59\n" ]
[ -2 ]
[ "django", "python", "time" ]
stackoverflow_0001384406_django_python_time.txt
Q: How to Identify Dynamically created window/buttons in wxpython? I am creating a series of buttons(Or windows) etc on RUN time. Now how do i identify when user clicks on these buttons? A: HI, I did an R&D on wx.Event(GetEventObject) and found out that i can get object details. SO i solved my problem using this. ...
How to Identify Dynamically created window/buttons in wxpython?
I am creating a series of buttons(Or windows) etc on RUN time. Now how do i identify when user clicks on these buttons?
[ "HI,\nI did an R&D on wx.Event(GetEventObject) and found out that i can get object details. \nSO i solved my problem using this.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004239896_python_wxpython.txt
Q: Importing values in Python I have a little module that creates a window (program1). I've imported this into another python program of mine (program2). How do I make program 2 get self.x and x that's in program1? This is program1. import Tkinter class Class(Tkinter.Tk): def __init__(self, parent): Tk...
Importing values in Python
I have a little module that creates a window (program1). I've imported this into another python program of mine (program2). How do I make program 2 get self.x and x that's in program1? This is program1. import Tkinter class Class(Tkinter.Tk): def __init__(self, parent): Tkinter.Tk.__init__(self, parent) ...
[ "You can access the variable self.x as a member of an instance of Class:\nc = Class(parent)\nprint(c.x)\n\nYou cannot access the local variable - it goes out of scope when the method call ends.\n", "I'm not sure exactly what the purpose of 'self.x' and 'x' are but one thing to note in the 'Main' method of class C...
[ 5, 1 ]
[]
[]
[ "class", "import", "python", "tkinter" ]
stackoverflow_0004240266_class_import_python_tkinter.txt
Q: How to read cookies in a python script when using mod_python I've got a website that I wrote in python using the CGI. This was great up until very recently, when the ability to scale became important. I decided, because it was very simple, to use mod_python. Most of the functionality of my site is stored in a py...
How to read cookies in a python script when using mod_python
I've got a website that I wrote in python using the CGI. This was great up until very recently, when the ability to scale became important. I decided, because it was very simple, to use mod_python. Most of the functionality of my site is stored in a python module which I call to render the various pages. One of the ...
[ "Which version of mod_python are you using? Mod_python 3.x includes a separate Cookie class to make this easier (see here)\nUnder earlier versions IIRC you can get the incoming cookies inside of the headers_in member of the request object.\n" ]
[ 0 ]
[]
[]
[ "cookies", "mod_python", "python" ]
stackoverflow_0004241131_cookies_mod_python_python.txt
Q: Looking for parallel function to actionscript's BitmapData.draw() but in OpenGL I have a flash application that I have been working on for 11 months, and would like to translate it to a different language / platform, preferably Python and OpenGL. One of the main features in my program is to draw flash vector graph...
Looking for parallel function to actionscript's BitmapData.draw() but in OpenGL
I have a flash application that I have been working on for 11 months, and would like to translate it to a different language / platform, preferably Python and OpenGL. One of the main features in my program is to draw flash vector graphics (or display objects) and then redraw them to a bitmap texture. Is there any way t...
[ "OpenGL doesn't provide any features for drawing your typical 2D vector graphics. It's a very generic API, but mostly suited for 3D solutions. Implementing the rendering capabilities of Flash in OpenGL is possible, but a lot of work to do yourself.\nIf you want only a subset (drawing sprites, triangles, convex poly...
[ 2 ]
[]
[]
[ "actionscript", "flash", "opengl", "python" ]
stackoverflow_0004240625_actionscript_flash_opengl_python.txt
Q: Python smtplib slower than PHP mail() I ported some PHP applications to Python. To my surprise, performance dropped by ten times in the newsletter module (100k+ subscribers). I was expecting some overhead for using SMTP (I think PHP calls sendmail directly), but not that much. How can I speedup Pythons mail deliv...
Python smtplib slower than PHP mail()
I ported some PHP applications to Python. To my surprise, performance dropped by ten times in the newsletter module (100k+ subscribers). I was expecting some overhead for using SMTP (I think PHP calls sendmail directly), but not that much. How can I speedup Pythons mail delivery? EDITED: For anyone digging this questi...
[ "PHP's mail() does indeed use sendmail. You can do the same thing in Python by invoking it via subprocess.\n" ]
[ 3 ]
[]
[]
[ "php", "python", "smtp", "smtplib" ]
stackoverflow_0004241434_php_python_smtp_smtplib.txt
Q: How to get the path to the opened file from a script inside a OS X .app bundle? So I have Foo.app, which is configured to run Foo.app/Contents/MacOS/foo.py when it is launched. In the app's Info.plist file I also have it set as the application to handle the launching of ".bar" files. When I double-click a .bar fil...
How to get the path to the opened file from a script inside a OS X .app bundle?
So I have Foo.app, which is configured to run Foo.app/Contents/MacOS/foo.py when it is launched. In the app's Info.plist file I also have it set as the application to handle the launching of ".bar" files. When I double-click a .bar file, Foo.app opens as expected. The problem is that when a file is opened in this way, ...
[ "You can get your app's process ID then ask the OS for all open files using lsof, looking for your process's ID:\nfrom string import *\nfrom os import getpid\nfrom subprocess import check_output, STDOUT\n\npid = getpid()\n\nlsof = (check_output(['/usr/sbin/lsof', '-p', str(pid)], stderr=STDOUT)).split(\"\\n\")\nfor...
[ 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0004241458_macos_python.txt
Q: Why is my system using my old PYTHONPATH after explicitly setting? I am running a script that explicitly sets the PYTHONPATH to avoid naming collisions. However, even if I say os.environ['PYTHONPATH'] = '', it looks as though the system is still able to find my old path that "lives" outside the script. How is my ...
Why is my system using my old PYTHONPATH after explicitly setting?
I am running a script that explicitly sets the PYTHONPATH to avoid naming collisions. However, even if I say os.environ['PYTHONPATH'] = '', it looks as though the system is still able to find my old path that "lives" outside the script. How is my system able to see the old PYTHONPATH even after I explicitly set it to ...
[ "The PYTHONPATH environment variable is parsed at startup and inserted into sys.path. If you need to adjust the path from within your Python code, manipulate sys.path, not PYTHONPATH.\n" ]
[ 4 ]
[]
[]
[ "collision", "python", "pythonpath", "setting" ]
stackoverflow_0004241632_collision_python_pythonpath_setting.txt
Q: Appengine Django Template - Read template tags UPDATE 1 ADDED UPDATED CODE I have a django template on app engine. Currently all my data is in several templates and I would like to read the templates off disk. Very easy, but I would like to get the values out of these templates in AppEngine. eg. file : p1.html {%...
Appengine Django Template - Read template tags
UPDATE 1 ADDED UPDATED CODE I have a django template on app engine. Currently all my data is in several templates and I would like to read the templates off disk. Very easy, but I would like to get the values out of these templates in AppEngine. eg. file : p1.html {%block price%}$259{%endblock%} {%block buy%}http://...
[ "Sounds like you've shot yourself in the foot. Lets just pretend we aren't to blame and fix it:\nentry = \"\"\"{%block price%}$259{%endblock%} \n{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%} \n{%block info%}http://www.inov-8.co.nz/oroc280.html{%end...
[ 3, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004241595_django_google_app_engine_python.txt
Q: Why are list(), dict(), and tuple() slower than [], {}, and ()? I've recently looked into using list(), dict(), tuple() in place of [], {}, and (), respectively when needing to create an empty one of of the three. The reasoning is that it seemed more readable. I was going to ask for opinions on the style, but then...
Why are list(), dict(), and tuple() slower than [], {}, and ()?
I've recently looked into using list(), dict(), tuple() in place of [], {}, and (), respectively when needing to create an empty one of of the three. The reasoning is that it seemed more readable. I was going to ask for opinions on the style, but then I decided to test performance. I did this: >>> from timeit import Ti...
[ "the function call requires a variable name lookup, followed by a function invocation. the function called then creates a list and returns it. The list syntax literal gets the interpreter to just make a list:\n>>> import dis\n>>> foo = lambda :[]\n>>> bar = lambda :list()\n>>> dis.dis(foo)\n 1 0 BUILD_...
[ 19, 6, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004241716_python.txt
Q: recursion with python argparse I'm writing a recursive program using argparse. The only required argument is a file (or files) to act on. When I call it recursively, I don't need the filenames (as I'll be calling on a new directory), but i need the options. the problem is that argparse allows both python programna...
recursion with python argparse
I'm writing a recursive program using argparse. The only required argument is a file (or files) to act on. When I call it recursively, I don't need the filenames (as I'll be calling on a new directory), but i need the options. the problem is that argparse allows both python programname.py -options arg FILENAME FILENAME...
[ "You're just making life difficult for yourself. You don't make programs recursive, you make functions recursive. Making a program recursive is an excellent way to run out of memory and generally overwhelm a system.\nRewrite your application so that the recursive work is confined to a function that calls itself, in...
[ 7, 1 ]
[]
[]
[ "argparse", "python", "recursion" ]
stackoverflow_0004241652_argparse_python_recursion.txt
Q: Python Inspect - Lookup the data type for a property in a GAE db.model Class class Employee(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() address1 = db.StringProperty() timezone = db.FloatProperty() #might be -3.5 (ca...
Python Inspect - Lookup the data type for a property in a GAE db.model Class
class Employee(db.Model): firstname = db.StringProperty() lastname = db.StringProperty() address1 = db.StringProperty() timezone = db.FloatProperty() #might be -3.5 (can contain fractions) class TestClassAttributes(webapp.RequestHandler): """ E...
[ "Iterate using \"for name, property in Employee.properties().items()\". The property argument is the Property instance, which you can compare using instanceof.\n", "For problems like these, the interactive Python shell is really handy. If you had used it to poke around at your Employee object, you might have dis...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "inspection", "python", "reflection" ]
stackoverflow_0001440958_google_app_engine_inspection_python_reflection.txt
Q: Sending serial data with python gives an error on windows but not on linux I'm using python to send data out to my arduino and for some reason under windows it's giving me an error. Below is my code. import serial ser = serial.Serial("COM3") ser.write('1') Here is the error. File "C:\Python25\lib\site-packa...
Sending serial data with python gives an error on windows but not on linux
I'm using python to send data out to my arduino and for some reason under windows it's giving me an error. Below is my code. import serial ser = serial.Serial("COM3") ser.write('1') Here is the error. File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 255, in write raise SerialException(...
[ "Are you sure COM3 is a valid serial port on your Windows box? Can you open it with HyperTerminal and send stuff to it?\nIf it is, another thing to try is to replace it with the fully qualified name, for example:\nport = \"\\\\\\\\.\\\\COM3\"\nser = serial.Serial(port, 38400)\n\n" ]
[ 1 ]
[]
[]
[ "python", "serial_port" ]
stackoverflow_0004242256_python_serial_port.txt
Q: How do I check out a file from perforce in python? I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and ...
How do I check out a file from perforce in python?
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
[ "Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:\nhttp://www.perforce.com/perforce/loadsupp.html#api\nYou will find their documentation of the scripting API to be helpful:\nhttp://www.perforce.com/perforce/doc.current/manuals/p4script/p4sc...
[ 22, 7, 4, 3, 2, 2 ]
[]
[]
[ "perforce", "python", "scripting" ]
stackoverflow_0000184187_perforce_python_scripting.txt
Q: How do you maintain user data when updating a Django site? I have a live Django site that already has registered users. I am trying to update the site with a new version that is different from the original site -similar idea but different models. How can I keep the current users on the new site? I have heard South...
How do you maintain user data when updating a Django site?
I have a live Django site that already has registered users. I am trying to update the site with a new version that is different from the original site -similar idea but different models. How can I keep the current users on the new site? I have heard South may be a good solution, but the old site doesn't have it instal...
[ "yes http://south.aeracode.org/docs/convertinganapp.html#converting-an-app\n", "+1 to South, but...\nWe need more information! Are you doing radical changes to your Models, or just adding or removing fields here or there?\nSouth can handle some pretty radical migrations, but you'll have to write some custom migr...
[ 2, 0 ]
[]
[]
[ "django_database", "django_south", "mysql", "python" ]
stackoverflow_0004241227_django_database_django_south_mysql_python.txt
Q: Getting registry information using Python I am trying to pull registry info from many servers and put them all into one txt file. I got the code working fine in a .bat file. I hear that there is a way simpler way to do this in Python. I am intrigued and delighted to hear this. Can anyone help finish my code: My wo...
Getting registry information using Python
I am trying to pull registry info from many servers and put them all into one txt file. I got the code working fine in a .bat file. I hear that there is a way simpler way to do this in Python. I am intrigued and delighted to hear this. Can anyone help finish my code: My working bat file: echo rfsqlcl01app >> foo.txt re...
[ "Without knowing much about your setup, this might work for you the way that you want.\nimport _winreg\n\n################################################################################\n\nclass HKEY:\n 'Hive Constants'\n CLASSES_ROOT = -2147483648\n CURRENT_USER = -2147483647\n LOCAL_MACHINE = -214748...
[ 2, 0 ]
[]
[]
[ "python", "winreg" ]
stackoverflow_0002424648_python_winreg.txt
Q: Linux email server, how to know a new email has arrived I am developing an email parsing application using python POP3 library on a linux server using Dovecot email server. I have parsed the emails to get the contents and the attachments etc. using POP3 library. Now the issue is how to notify a user or actually th...
Linux email server, how to know a new email has arrived
I am developing an email parsing application using python POP3 library on a linux server using Dovecot email server. I have parsed the emails to get the contents and the attachments etc. using POP3 library. Now the issue is how to notify a user or actually the application that a new email has arrived? I guess there sho...
[ "POP3 does not have push ability. Like a regular ol' post office you need to actually go to check your e-mail. IMAP does have functionality similar to (but not exactly the same as) mail pushing. I'd suggest taking a look at it.\n" ]
[ 2 ]
[]
[]
[ "email", "linux", "python" ]
stackoverflow_0004242540_email_linux_python.txt
Q: wxPython not binding callbacks to events properly Here's a roughly minimal demonstrative example: import wx app = wx.App(False) frame = wx.Frame(None) menuBar = wx.MenuBar() menu = wx.Menu() menuBar.Append(menu, "&Menu") frame.SetMenuBar(menuBar) for name in ['foo','bar','baz']: menuitem = menu.Append(-1,"&...
wxPython not binding callbacks to events properly
Here's a roughly minimal demonstrative example: import wx app = wx.App(False) frame = wx.Frame(None) menuBar = wx.MenuBar() menu = wx.Menu() menuBar.Append(menu, "&Menu") frame.SetMenuBar(menuBar) for name in ['foo','bar','baz']: menuitem = menu.Append(-1,"&"+name,name) def menuclick(e): print(name) ...
[ "After the for loop name will be \"baz\", it's value will not go back in time to when you bound the menuclick to the menu event.\nYou can get to the menu item name via the event itself like this:\ndef menuclick(e):\n print(menu.FindItemById(e.Id).Label)\n\n", "I found this solution, by I'm not sure why this wo...
[ 2, 0 ]
[]
[]
[ "closures", "python", "wxpython" ]
stackoverflow_0004242147_closures_python_wxpython.txt
Q: python 3.1 boolean check with for loop How can I add a Boolean check to a for loop? I was trying something like this: for i in range (0, someNumber) and keepGoing == True It is giving me the error 'bool' object is not iterable. Thanks for the help. A: This isn't a for loop like in C; what you're doing here is c...
python 3.1 boolean check with for loop
How can I add a Boolean check to a for loop? I was trying something like this: for i in range (0, someNumber) and keepGoing == True It is giving me the error 'bool' object is not iterable. Thanks for the help.
[ "This isn't a for loop like in C; what you're doing here is creating a range object and iterating over each element in it (naming it \"i\") in the process. In C, you can have multiple checks during an iteration of a loop, but in Python you iterate over iterable objects such as lists or tuples.\nfor i in range(0, so...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0004242913_python.txt
Q: Pattern and design for functions that differ greatly from each other but are processed similarly I'm writing some Python code to scrape websites, and what I'm going to end up with is a growing collection of custom scrapers, each about 50 lines long and tailored extract specific information from a specific website....
Pattern and design for functions that differ greatly from each other but are processed similarly
I'm writing some Python code to scrape websites, and what I'm going to end up with is a growing collection of custom scrapers, each about 50 lines long and tailored extract specific information from a specific website. My first iteration of the program is one giant file that takes a website as an argument, and scrapes...
[ "You can put the code in a class with an __init__ method to get everything configured, a _download method to connect to the site and download it, a _store method to save the results and a run method to tie it all together, like so:\nclass Scraper(object):\n def __init__(self, parser, page_generator):\n se...
[ 5, 1 ]
[]
[]
[ "design_patterns", "oop", "python", "web_scraping" ]
stackoverflow_0004243491_design_patterns_oop_python_web_scraping.txt
Q: Is Django's templating markup for views safe for end user editing like rails liquid templating? I want end users to be able to edit their view templates online, so it has to be safe or 'jailed' such that only the objects I explicitly push to the view page are made accessible. i.e. I don't want the end user to be a...
Is Django's templating markup for views safe for end user editing like rails liquid templating?
I want end users to be able to edit their view templates online, so it has to be safe or 'jailed' such that only the objects I explicitly push to the view page are made accessible. i.e. I don't want the end user to be able to write python code, or figure out my connection string information etc. etc. Is django's templa...
[ "Django templates are safe for this kind of code as far as I know.\nThe only kind of logic beyond simple loops/branches that can be executed in the template is whatever is registered as a template tag or filter. TT or Filters can only be registered through the backend code.\nHere you can see a list of template tags...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004219735_django_python.txt
Q: How can I augment the method of a Python object? I have a list of Spam objects: class Spam: def update(self): print('updating spam!') some of them might be SpamLite objects: class SpamLite(Spam): def update(self): print('this spam is lite!') Spam.update(self) I would like to be ab...
How can I augment the method of a Python object?
I have a list of Spam objects: class Spam: def update(self): print('updating spam!') some of them might be SpamLite objects: class SpamLite(Spam): def update(self): print('this spam is lite!') Spam.update(self) I would like to be able to take an arbitrary object from the list, and add ...
[ "def poison(spam):\n tmp = spam.update\n def newUpdate():\n print 'this spam has been poisoned!'\n tmp()\n spam.update = newUpdate\n\nFull Script:\nclass Spam:\n def update(self):\n print('updating spam!')\n\nclass SpamLite(Spam):\n def update(self):\n print('this spam is ...
[ 4, 3, 0, 0 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0004243586_methods_python.txt
Q: run python command from C code with specific encoding int PyRun_SimpleString(const char *command) is the function which can run a command of Python. I call this function in my program, but how can I specify the encoding of the command argument. I found that Python 3 seems to use UTF-8 as the default encoding whe...
run python command from C code with specific encoding
int PyRun_SimpleString(const char *command) is the function which can run a command of Python. I call this function in my program, but how can I specify the encoding of the command argument. I found that Python 3 seems to use UTF-8 as the default encoding when I run a command. Can I change this encoding in the C leve...
[ "You can prepend one of the \"magic comments\" described in PEP 263 to your command:\nchar buf[1024];\nsnprintf(buf, sizeof(buf), \"-*- coding: %s -*-\\n\", yourEncoding);\nstrncat(buf, yourCommand, sizeof(buf) - strlen(buf) - 1);\nPyRun_SimpleString(buf);\n\n" ]
[ 3 ]
[]
[]
[ "c", "embed", "encoding", "python", "python_3.x" ]
stackoverflow_0004244082_c_embed_encoding_python_python_3.x.txt
Q: What is wrong with this Python code? Can anyone tell me what is wrong with this? I'm getting a syntax error after the 2nd quote on the print line... It seems like this should work perfectly fine. Thanks def main(): print "blah" return main() A: In case you're using Python 3, the print statement is go...
What is wrong with this Python code?
Can anyone tell me what is wrong with this? I'm getting a syntax error after the 2nd quote on the print line... It seems like this should work perfectly fine. Thanks def main(): print "blah" return main()
[ "In case you're using Python 3, the print statement is gone in that version and you need to use the print() function.\nSee: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function\n", "You're using python 3.\nuse \nprint(\"blah\")\n\nThe print statement turned into the print function in the tra...
[ 4, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004241529_python.txt
Q: to parse a file with text (with offset information) and binary data in python I have an xml file, which contains a set of textual element tags (each contains the decimal offset value and data length of the corresponding binary element) and the whole binary data of all the elements at the end. An example is as foll...
to parse a file with text (with offset information) and binary data in python
I have an xml file, which contains a set of textual element tags (each contains the decimal offset value and data length of the corresponding binary element) and the whole binary data of all the elements at the end. An example is as follows. <?xml version="1.0" encoding="UTF-8"?> <Package> <element> <offset>0...
[ "The trick is going to be stopping XML parsers from puking on the binary data. lxml lets you feed a line at a time to a parser, so you can watch for the last XML tag and stop there:\nfrom lxml import etree\n\ndef process(filename):\n f = file(filename,\"r\")\n parser = etree.XMLParser()\n for l in f:\n ...
[ 2, 1, 0 ]
[]
[]
[ "binary_data", "file", "parsing", "python" ]
stackoverflow_0004243855_binary_data_file_parsing_python.txt
Q: Django Models Foreign Key Field Match I have the following Django Model - class M(models.Model): ... disp_name = models.CharField(max_length=256, db_index=True) ... class XX(models.Model): x = models.ForeignKey(User) y = models.ForeignKey(M, unique=True) Now in my views.py, I want to do a pa...
Django Models Foreign Key Field Match
I have the following Django Model - class M(models.Model): ... disp_name = models.CharField(max_length=256, db_index=True) ... class XX(models.Model): x = models.ForeignKey(User) y = models.ForeignKey(M, unique=True) Now in my views.py, I want to do a partial string match on all items in XX with ...
[ "I wish you had used proper field names rather than X, Y and M - it's really hard to follow.\nBut in any case, you should always use the double-underscore syntax to follow relations on the left hand side of the filter expression:\nXX.objects.filter(y__disp_name__istartswith='string')\n\n(The technical reason for th...
[ 2 ]
[]
[]
[ "django", "django_models", "python", "string_matching" ]
stackoverflow_0004244552_django_django_models_python_string_matching.txt
Q: PyGTK app is not quitting properly I wrote a little PyGTK app: Workcycler Now I have the problem that I need to hit the quit button twice for it to quit and I don't know why. I´ve tested it extensively and it allways calls all quit functions but the program simply doesn't close after the first time. It's a pretty ...
PyGTK app is not quitting properly
I wrote a little PyGTK app: Workcycler Now I have the problem that I need to hit the quit button twice for it to quit and I don't know why. I´ve tested it extensively and it allways calls all quit functions but the program simply doesn't close after the first time. It's a pretty short script so could someone please hav...
[ "You are running the workcycle.ui.tray.WorkcycleTray.start method twice (so gtk.main run twice )\nonce in the workcycler and another in workcycle.py line 20, comment that line and everything works fine.\n" ]
[ 1 ]
[]
[]
[ "pygame", "pygtk", "python" ]
stackoverflow_0004243911_pygame_pygtk_python.txt
Q: Want to find date data in python shell I have a model something like this. #models.py class ItemStatusHistory(models.Model): date = models.DateTimeField(auto_now = True) contact = models.ForeignKey(Contact) item = models.ForeignKey(StorageItem) status = models.ForeignKey(Status) user = models.F...
Want to find date data in python shell
I have a model something like this. #models.py class ItemStatusHistory(models.Model): date = models.DateTimeField(auto_now = True) contact = models.ForeignKey(Contact) item = models.ForeignKey(StorageItem) status = models.ForeignKey(Status) user = models.ForeignKey(User) def __unicode__(self): ...
[ "Get the object from the django db in the usual way and access foo.name_of_attribute:\nThe example in the django docs should help, see:\nhttp://docs.djangoproject.com/en/dev/intro/tutorial01/\n >>> p = Poll.objects.get(pk=1)\n >>> p.pub_date\n datetime.datetime(2007, 7, 15, 12, 00, 53)\n\nAnd thats a standard pytho...
[ 1, 0 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0004245243_django_models_python.txt
Q: How do I access template cache? - Django I am caching html within a few templates e.g.: {% cache 900 stats %} {{ stats }} {% endcache %} Can I access the cache using the low level library? e.g. html = cache.get('stats') I really need to have some fine-grained control over the template caching :) Any ideas? ...
How do I access template cache? - Django
I am caching html within a few templates e.g.: {% cache 900 stats %} {{ stats }} {% endcache %} Can I access the cache using the low level library? e.g. html = cache.get('stats') I really need to have some fine-grained control over the template caching :) Any ideas? Thanks everyone! :D
[ "This is how I access the template cache in my project:\nfrom django.utils.hashcompat import md5_constructor\nfrom django.utils.http import urlquote\n\ndef someView(request):\n variables = [var1, var2, var3] \n hash = md5_constructor(u':'.join([urlquote(var) for var in variables]))\n cache_key = 'template....
[ 6, 2 ]
[]
[]
[ "caching", "django", "django_cache", "django_templates", "python" ]
stackoverflow_0004245081_caching_django_django_cache_django_templates_python.txt
Q: How do you write special characters ("\n","\b",...) to a file in Python? I'm using Python to process some plain text into LaTeX, so I need to be able to write things like \begin{enumerate} or \newcommand to a file. When Python writes this to a file, though, it interprets \b and \n as special characters. How do ...
How do you write special characters ("\n","\b",...) to a file in Python?
I'm using Python to process some plain text into LaTeX, so I need to be able to write things like \begin{enumerate} or \newcommand to a file. When Python writes this to a file, though, it interprets \b and \n as special characters. How do I get Python to write \newcommand to a file, instead of writing ewcommand on a...
[ "One solution is to escape the escape character (\\). This will result in a literal backslash before the b character instead of escaping b:\nwith open(fileout,'w',encoding='utf-8') as fout:\n fout.write(\"\\\\begin{enumerate}[1.]\\n\")\n\nThis will be written to the file as\n\\begin{enumerate}[1.]<newline>\n\n(I...
[ 11, 9, 4 ]
[]
[]
[ "latex", "python" ]
stackoverflow_0004245709_latex_python.txt
Q: How can I annotate a class in pypy? I am using pypy to translate some python script to C language. Say that I have a python class like this: class A: def __init__(self): self.a = 0 def func(self): pass I notice that A.func is a unbound method rather than a function so that it cannot be tr...
How can I annotate a class in pypy?
I am using pypy to translate some python script to C language. Say that I have a python class like this: class A: def __init__(self): self.a = 0 def func(self): pass I notice that A.func is a unbound method rather than a function so that it cannot be translated by pypy. So I change the code sl...
[ "Essentially PyPy's entry point is a function (accepting sys.argv usually as an argument). Whatever this function calls (create objects, call methods) will get annotated. There is no way to annotate a class, since PyPy's compiled code does not export this as API, but rather as a standalone program.\nYou might want ...
[ 5, 1 ]
[]
[]
[ "annotate", "pypy", "python" ]
stackoverflow_0004241673_annotate_pypy_python.txt
Q: Buttons with line breaks don't display properly on Mac OS X This code works fine in Windows. On Mac OS X it only shows "Multiple" in the button and everything past the newline gets wiped out. I'm running Python 2.6.5 on Mac. import Tkinter as tk class App: def __init__(self, master): self.a_button = ...
Buttons with line breaks don't display properly on Mac OS X
This code works fine in Windows. On Mac OS X it only shows "Multiple" in the button and everything past the newline gets wiped out. I'm running Python 2.6.5 on Mac. import Tkinter as tk class App: def __init__(self, master): self.a_button = tk.Button(master, text="Multiple\nLines\nOf Text") self.a...
[ "Mac native pushbuttons don't let you do that; they have 3 predefined heights for the various control sizes and that's it. Other button styles do support arbitrary dimensions; one option is to use a Tile button instead:\n self.a_button = tk.Widget(master, 'ttk::button',\n dict(text=\...
[ 4 ]
[]
[]
[ "button", "macos", "python", "tkinter" ]
stackoverflow_0004244855_button_macos_python_tkinter.txt
Q: Question about whether to include something in the __init__() method I am new to OOP and hence, am looking for suggestions on good practice for coding something where the following issue arises. I am defining a Seller(a, b, c, d) class. There are many attributes of this class, two of which are, mostRecentProfit an...
Question about whether to include something in the __init__() method
I am new to OOP and hence, am looking for suggestions on good practice for coding something where the following issue arises. I am defining a Seller(a, b, c, d) class. There are many attributes of this class, two of which are, mostRecentProfit and profitHistory. However, values of these two are not known when the class...
[ "Defining the attributes in __init__() makes the code better for when someone who has not seen the code has to start working with it. It can be confusing when a class starts accessing an attribute that doesn't seem to exist at first.\nAlso, since one of your default values is a list instead of None, initializing it...
[ 4, 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0004245566_oop_python.txt
Q: Parsing spanish text and saving it in a db I'm parsing a web page written in spanish with scrapy. The problem is that I can't save the text because of the wrong encoding. This is the parse function: def parse(self, response): hxs = HtmlXPathSelector(response) text = hxs.select('//text()').extract()...
Parsing spanish text and saving it in a db
I'm parsing a web page written in spanish with scrapy. The problem is that I can't save the text because of the wrong encoding. This is the parse function: def parse(self, response): hxs = HtmlXPathSelector(response) text = hxs.select('//text()').extract() # Ex: [u' Sustancia mineral, m\xe1s o menos dur...
[ "Please, don't remember that DBF files don't support unicode at all \nand I also suggest to use Ethan Furman's dbf package (link in another answer)\nYou can use only 'table = dbf.Table('filename') to guess real type.\nExample of usage with non cp437 encoding is:\n#!/usr/bin/env python\n# coding: koi8-r\nimport dbf\...
[ 1, 0 ]
[]
[]
[ "parsing", "python", "unicode" ]
stackoverflow_0004175246_parsing_python_unicode.txt
Q: python - wx.lib.pubsub.Publisher not working when called from buttons pressed? I'm implementing a MVC app using wxPyton, and I have an issue with wx.lib.pubsub.Publisher. I'd like to keep my Controller as separated from my View as possible. For example, I don't want my controller to 'know' the names of the buttons...
python - wx.lib.pubsub.Publisher not working when called from buttons pressed?
I'm implementing a MVC app using wxPyton, and I have an issue with wx.lib.pubsub.Publisher. I'd like to keep my Controller as separated from my View as possible. For example, I don't want my controller to 'know' the names of the buttons used in the view. On the wxPython example, the controller has to know them, so it c...
[ "You need to save a reference to your controller otherwise the object gets GC'd and therefore won't exist by the time the message is sent. Change the second-to-last line to:\ncontroller = Controller(app)\n\n" ]
[ 4 ]
[]
[]
[ "messaging", "python", "wxpython" ]
stackoverflow_0004245224_messaging_python_wxpython.txt
Q: installing libxml2 on python 2.7 windows I've searched but theres no libxml2 binaries for py2.7. I have also tried running setup.py for version py2.6.9 but it gave me the error failed to find headers for libxml2: update includes_dir Does anyone have a solution? A: Some time before I found a good page with prebu...
installing libxml2 on python 2.7 windows
I've searched but theres no libxml2 binaries for py2.7. I have also tried running setup.py for version py2.6.9 but it gave me the error failed to find headers for libxml2: update includes_dir Does anyone have a solution?
[ "Some time before I found a good page with prebuilt libraries for different versions of python and arch: http://www.lfd.uci.edu/~gohlke/pythonlibs/ \nI suspect it will be useful for you.\n" ]
[ 10 ]
[]
[]
[ "libxml2", "python" ]
stackoverflow_0003520826_libxml2_python.txt
Q: Python input string error (don't want to use raw_input) I have a menu that asks for the user to pick one of the options. Since this menu is from 1 to 10, I'm using input besides raw_input. My code as an if statement that if the number the user inputs is from 1 to 10 it does the option. If the user inputs any numbe...
Python input string error (don't want to use raw_input)
I have a menu that asks for the user to pick one of the options. Since this menu is from 1 to 10, I'm using input besides raw_input. My code as an if statement that if the number the user inputs is from 1 to 10 it does the option. If the user inputs any number besides that ones, the else statement says to the user pick...
[ "You can throw an exception when you try to convert your string into a number.\nExample:\ntry:\n int(myres)\nexcept:\n print \"Only numbers are valid\"\n\n", "Im not sure what you consider advanced - a simple way to do it would be with something like this.\ndef getUserInput():\n while True:\n a = ra...
[ 5, 4, 4, 3, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004245637_python.txt
Q: How to increase the font size of a Text widget? How to increase the font size of a Text widget? A: There are several ways to specify a font: the simplest is a tuple of the form (family, size, style). import Tkinter as tk root=tk.Tk() text=tk.Text(width = 40, height=4, font=("Helvetica", 32)) text.pack() roo...
How to increase the font size of a Text widget?
How to increase the font size of a Text widget?
[ "There are several ways to specify a font: the simplest is a tuple of the form (family, size, style).\nimport Tkinter as tk\n\nroot=tk.Tk()\ntext=tk.Text(width = 40, height=4, font=(\"Helvetica\", 32))\ntext.pack() \nroot.mainloop()\n\n" ]
[ 21 ]
[]
[]
[ "block", "font_size", "python", "textbox", "tkinter" ]
stackoverflow_0004246353_block_font_size_python_textbox_tkinter.txt
Q: python function call syntax ... result = foo() ['abc'] number = droid.readPhoneState()['result']['incomingNumber'] What are 'result' and 'incomingNumber' in this syntax -- are they not parameters? How are they related to the function readPhoneState? import android droid = android.Android() droid.startTrackingPho...
python function call syntax ... result = foo() ['abc']
number = droid.readPhoneState()['result']['incomingNumber'] What are 'result' and 'incomingNumber' in this syntax -- are they not parameters? How are they related to the function readPhoneState? import android droid = android.Android() droid.startTrackingPhoneState() number = droid.readPhoneState()['result']['incomi...
[ "droid.readPhoneState() returns a dict of dicts. Equivalent code:\nouterDict = droid.readPhoneState()\ninnerDict = outerDict['result']\nnumber = innerDict['incomingNumber']\n\n", "result and incomingNumber are keys to a dictionary or an instance of a class that implements method __getitem__. This means that readP...
[ 9, 2, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0004246535_python_syntax.txt
Q: ICMP Ping packet is not generating a reply when using Scapy I recently began exploring Scapy. A wonderful tool indeed! I have a problem... When I monitor my network card using Wireshark and I do a regular ping from the systems command prompt with the standard PING installation, wireshark pops up with "Ping reques...
ICMP Ping packet is not generating a reply when using Scapy
I recently began exploring Scapy. A wonderful tool indeed! I have a problem... When I monitor my network card using Wireshark and I do a regular ping from the systems command prompt with the standard PING installation, wireshark pops up with "Ping request" and then "Ping reply" indication that it sent a reply. But whe...
[ "This is an FAQ item:\n\nI can't ping 127.0.0.1. Scapy does not work with 127.0.0.1 or on the loopback interface\nThe loopback interface is a very special interface. Packets going through it are not really assembled and dissassembled. The kernel routes the packet to its destination while it is still stored an inter...
[ 8, 0 ]
[]
[]
[ "ping", "python", "scapy" ]
stackoverflow_0004245810_ping_python_scapy.txt
Q: Python "map or" on elements in list What's the most elegant way of doing something like this: >>> tests = [false, false, false] >>> map_or(test) false >>> tests = [true, false, false] >>> map_or(test) true The map_or function should return true if one or more of list elements are true. A: Use any(). It is a b...
Python "map or" on elements in list
What's the most elegant way of doing something like this: >>> tests = [false, false, false] >>> map_or(test) false >>> tests = [true, false, false] >>> map_or(test) true The map_or function should return true if one or more of list elements are true.
[ "Use any(). It is a built-in function that just does what you want.\n", "any(tests)\n\nBuilt in function :)\n", "any(tests)\n\n(and the rest of this is padding because yet again StackOverflow treats users like idiots and sets minimum answer lengths)\n" ]
[ 9, 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004246984_python.txt
Q: Having a console in a single-threaded Python script I would like to have an interactive console in a single-threaded script that has several TCP connections open. This means I can't just have a standard input blocking the thread. Is there an easy way to do this? Or should I just put the console in its own thread a...
Having a console in a single-threaded Python script
I would like to have an interactive console in a single-threaded script that has several TCP connections open. This means I can't just have a standard input blocking the thread. Is there an easy way to do this? Or should I just put the console in its own thread and be done with it?
[ "You can subclass InteractiveConsole (from the builtin 'code' module) and\noverride the push() method with a wrapper that redirects stdout/stderr\nto a StringIO instance before forwarding to the base\nInteractiveConsole's push() method. Your wrapper can return a 2-tuple\n(more, result) where 'more' indicates wheth...
[ 3, 0 ]
[]
[]
[ "console", "interactive", "multithreading", "python" ]
stackoverflow_0004241234_console_interactive_multithreading_python.txt
Q: Python keeping newlines in lxml.html after cssselect and text_content() In python, How do I preserve paragraphs (i.e. keep newlines) when using lxml.html? For example, the following will strip <p></p> tags and join the lines, which is not what I want: body = doc.cssselect("div.body")[0] content = body.text_content...
Python keeping newlines in lxml.html after cssselect and text_content()
In python, How do I preserve paragraphs (i.e. keep newlines) when using lxml.html? For example, the following will strip <p></p> tags and join the lines, which is not what I want: body = doc.cssselect("div.body")[0] content = body.text_content() Here's what I've tried that doesn't work: lxml.html.clean.clean_html: W...
[ "The lxml text_content is doing what is supposed to according to the docs, it is stripping the html tags and leaving the text behind.\nYou can fix this up by adding your own newlines before outputting the content.\nbody = doc.cssselect(\"div.body\")[0]\nfor para in body.xpath(\"*//p\"):\n para.text = \"\\n%s\\n\...
[ 2 ]
[]
[]
[ "html_parsing", "lxml", "newline", "python" ]
stackoverflow_0004242712_html_parsing_lxml_newline_python.txt
Q: is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc? is there any efficient and easy way to execute statements similar to: CREATE TABLE IF NOT EXISTS fubar ( id int, name varchar(80)) for columns as you perform insert statements. I'd ...
is there an easy/efficient way to make a mysql database dynamically 'build it's own structure' as it saves name/value pairs to disc?
is there any efficient and easy way to execute statements similar to: CREATE TABLE IF NOT EXISTS fubar ( id int, name varchar(80)) for columns as you perform insert statements. I'd imagine it will be a lot more complicated, but just for the sake of explanation, i guess I'm looking for something like.... IF NOT EXISTS ...
[ "I believe that you're looking for an Object Relational Mapping system.\nFor Python there are a couple available:\n\nSQLAlchemy: http://www.sqlalchemy.org/\nSQLObject: http://sqlobject.org/\n\nOr if you're building a website, the Django project includes an ORM system: http://www.djangoproject.com/\nTo simplify the ...
[ 2 ]
[]
[]
[ "dynamic", "mysql", "python" ]
stackoverflow_0004246876_dynamic_mysql_python.txt
Q: how do i insert inputs to find value of integrals in python? I am working a physics coursework, and I am currently stuck at this section. I've trying but I couldn't get it right. Really need help here. Its about the trapezium rule, Question: What is the value of the integral in equation f(x)=x4*(1-x)44/(1+x^2) th...
how do i insert inputs to find value of integrals in python?
I am working a physics coursework, and I am currently stuck at this section. I've trying but I couldn't get it right. Really need help here. Its about the trapezium rule, Question: What is the value of the integral in equation f(x)=x4*(1-x)44/(1+x^2) this is the code I've tried, but I can not get the answer from math ...
[ "Your definition of f is bogus. This is all you need to write:\ndef f(x):\n return x**4 * (1 - x)**4 / (1 + x**2)\n\nThe rest of your code looks good to me, so long as you call trap0 with floating-point arguments for a and b.\n>>> trap0(math.cos, 0.0, math.pi/2, 100)\n0.99997943823960744\n\nIf you want to call i...
[ 2, 0 ]
[]
[]
[ "input", "integral", "python" ]
stackoverflow_0004247380_input_integral_python.txt
Q: Python "join" function like unix "join" I am curious if there is a built-in python join function like the unix version (see http://linux.about.com/library/cmd/blcmdl_join.htm https://www.man7.org/linux/man-pages/man1/join.1.html). I know the functionality is included through the built in sqlite3 module and probabl...
Python "join" function like unix "join"
I am curious if there is a built-in python join function like the unix version (see http://linux.about.com/library/cmd/blcmdl_join.htm https://www.man7.org/linux/man-pages/man1/join.1.html). I know the functionality is included through the built in sqlite3 module and probably through some other modules like pytables. S...
[ "Here's a python version of the join function, does not handle all of the potential error cases. But demonstrates the basic idea.\n# usage join(open('f1.txt'), open('f2.txt'))\n\ndef join(fd_a, fd_b) :\n result = []\n la = fd_a.readline()\n lb = fd_b.readline()\n while la and lb :\n start_a, res...
[ 6, 4, 1 ]
[]
[]
[ "join", "python" ]
stackoverflow_0004247792_join_python.txt
Q: Returning random element from a Python array based on search criteria Apologies if this is straightforward, but I've been looking for a little while now and can't find a simple, efficient solution. I have a two-dimensional Python list of lists which only consists of 1's and 0's. e.g.: a=[[0,1,0],[0,1,1],[1,0,1]] ...
Returning random element from a Python array based on search criteria
Apologies if this is straightforward, but I've been looking for a little while now and can't find a simple, efficient solution. I have a two-dimensional Python list of lists which only consists of 1's and 0's. e.g.: a=[[0,1,0],[0,1,1],[1,0,1]] I wish to return, at random, the indices of a random element which is = 1. ...
[ "I'd use a list comprehension to generate a list of tuples (positions of 1), then random.choice :\nfrom random import choice\n\na = [[0,1,0],[0,1,1],[1,0,1]]\nmylist = []\n\n[[mylist.append((i,j)) for j, x in enumerate(v) if x == 1] for i, v in enumerate(a)]\nprint(choice(mylist))\n\n", "I would use a NumPy array...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "arrays", "indices", "python", "search" ]
stackoverflow_0004247983_arrays_indices_python_search.txt
Q: Python Thread not returning the value Using: Django with Python Overall objective: Call a function which processes video conversion (internally makes a curl command to the media server) and should immediately return back to the user. Using message queue would be an overkill for the app. So I had decided to use th...
Python Thread not returning the value
Using: Django with Python Overall objective: Call a function which processes video conversion (internally makes a curl command to the media server) and should immediately return back to the user. Using message queue would be an overkill for the app. So I had decided to use threads, I have written a class which overwri...
[ "I wouldn't rely on threads being executed correctly within web applications. Depending on the web server's MPM, the process that executes the request might get killed after a request is done (I guess).\nI'd recommend to make the media server request synchronously but let the media server return immediately after i...
[ 0, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0004242770_django_django_views_python.txt
Q: How to exclude comment lines when searching with regular expression? Need to exclude blocks that are located with a regular expression when preceded with # and any number of spaces. Here is a example file &START A=23 ... more data ... B=24 &END # &START A=34 ... more data ... ...
How to exclude comment lines when searching with regular expression?
Need to exclude blocks that are located with a regular expression when preceded with # and any number of spaces. Here is a example file &START A=23 ... more data ... B=24 &END # &START A=34 ... more data ... B=24 &END &START .... block 3 of data across multiple lines ...
[ "Skip the line altogether.\nif line.lstrip().startswith('#'):\n continue\n\n", "This seems to work:\nimport re\n\ntarget=\"\"\"\n&START A=23 ... more data ...\n B=24 &END\n# &START A=C34 ... more data ...\n B=C24 &END\n&START .... block 3 of data across multiple ...
[ 6, 2, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004248010_python_string.txt
Q: Error with new version I have Arch linux and recently it's python packages was upgraded to the 3rd branch. Now I'm not able to run selenium-python bindings. When I run it (even with old-python version) I get: from selenium import selenium File "/usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg/seleni...
Error with new version
I have Arch linux and recently it's python packages was upgraded to the 3rd branch. Now I'm not able to run selenium-python bindings. When I run it (even with old-python version) I get: from selenium import selenium File "/usr/lib/python2.7/site-packages/selenium-2.0a5-py2.7.egg/selenium/__init__.py", line 23, in...
[ "I've tried it and it works for me. The error doesn't make sense to me since line 193 in selenium.py is part of the Selenium object \"start\" method - it shouldn't be called at import time.\nMaybe ask the user group?\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0004248413_python_selenium.txt
Q: GAE+ Picasa heavy use. Restrictions or quotes I suppose it can be offtopic, but I didn't find this info anywhere. I am going to build a GAE app that will heavily work with Picasa as an image hosting. It will add new images, fetch existing, update them, work with comments etc. I have read Picasa API docs and I thin...
GAE+ Picasa heavy use. Restrictions or quotes
I suppose it can be offtopic, but I didn't find this info anywhere. I am going to build a GAE app that will heavily work with Picasa as an image hosting. It will add new images, fetch existing, update them, work with comments etc. I have read Picasa API docs and I think it can be integrated and used with GAE quite quic...
[ "I just read this blog article:\nhttp://www.carlosble.com/?p=719\nLong story short, the guy wasted 15 grand because he did not do his research and found out GAE was not appropriate for this needs.\nIt sounds like your app might hit the quotas imposed by GAE, I guess it would depend on how popular your app is. Here...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "picasa", "python" ]
stackoverflow_0004248368_google_app_engine_picasa_python.txt
Q: Sandboxing web services with Python I'm building an integration test for a web application that has multiple interdependent services. All of them depend on a shared resource in order to run correctly. I'd like to make sure that the data in the system is sane when its live so I'm leveraging a live service. I'm usin...
Sandboxing web services with Python
I'm building an integration test for a web application that has multiple interdependent services. All of them depend on a shared resource in order to run correctly. I'd like to make sure that the data in the system is sane when its live so I'm leveraging a live service. I'm using Python to build it and this is my idea ...
[ "You definitely don't want to test with live data first. In order to build the integration test, you should first mock your dependencies and use I/O sets you control. Having expected input and output is very important. Building those unit tests will help you immensely when doing your integration testing.\nAs for...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "sandbox", "web_services" ]
stackoverflow_0003522584_python_sandbox_web_services.txt
Q: Dynamic symbol lookup fails with statically embedded Python on Mac OS X I'm building a Mac OS X application that is to embed Python. My application is technically a bundle (i.e. its main executable is MH_BUNDLE); it's a plug-in for another application. I'd like it to embed Python statically, but want to be able to...
Dynamic symbol lookup fails with statically embedded Python on Mac OS X
I'm building a Mac OS X application that is to embed Python. My application is technically a bundle (i.e. its main executable is MH_BUNDLE); it's a plug-in for another application. I'd like it to embed Python statically, but want to be able to load extensions dynamically. I did the following: I included a whole library...
[ "The “update” I made suggests it right: the main plug-in bundle is loaded locally (RTLD_LOCAL), so nobody can see any symbols there, unless using explicit dlopen followed by dlsym. \nIf it were Linux I could promote the bundle to the global namespace by dlopening it again with the RTLD_GLOBAL flag, but under Mac OS...
[ 1 ]
[]
[]
[ "dynamic", "lookup", "macos", "python" ]
stackoverflow_0004193539_dynamic_lookup_macos_python.txt
Q: URLError: urlopen error timed out Whenever i try to make a HTTP request to some url through my django application which is running on top of apache mod_python (Machine: Ubuntu 10.04 server edition, 64-bits), it gives a timeout error. The strange thing is that it works fine on Ubuntu 10.04 server edition, 32-bits. ...
URLError: urlopen error timed out
Whenever i try to make a HTTP request to some url through my django application which is running on top of apache mod_python (Machine: Ubuntu 10.04 server edition, 64-bits), it gives a timeout error. The strange thing is that it works fine on Ubuntu 10.04 server edition, 32-bits. I feel there could be some proxy connec...
[ "Run simple network analysis first, \ntracert\nping \nwireshark (for network analysis)\nCheck your firewall and proxy settings on the server and make sure the correct ports, routes and permissions are fine.\n", "Step 1:\nTry it in the python shell first. Just take whatever you're trying to do with urlopen and do ...
[ 0, 0 ]
[]
[]
[ "apache2", "django", "python", "ubuntu" ]
stackoverflow_0004243550_apache2_django_python_ubuntu.txt
Q: Is there a reason I should be dissuaded from using an alternative templating engine in my Django app? I've done a few small-ish Django projects, and each time I've been struck by the apparent limitations of Django's templating language. Just as a random example, I was shocked to learn that if, in the context of a ...
Is there a reason I should be dissuaded from using an alternative templating engine in my Django app?
I've done a few small-ish Django projects, and each time I've been struck by the apparent limitations of Django's templating language. Just as a random example, I was shocked to learn that if, in the context of a template, I had a variable bar and a dict foo, I couldn't access foo[bar] unless I wrote my own filter to d...
[ "I'll be honest, I didn't thoroughly read the responses. But I'm guessing it's a lot of \"no python in your templates\" and \"your view shouldn't have much logic\" type stuff.\nIf you put idealism aside and opt for pragmatism then I think Mako is a fine choice. I'm using it in a production capacity (mainly for spee...
[ 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "django", "mako", "python", "templating" ]
stackoverflow_0004241871_django_mako_python_templating.txt
Q: Structuring Django-App to Attach Custom Business Rules to Object Instances I'm torn how to structure my code to accommodate business rules specific to instances of a particular model. For example. Lets say I have a Contact model with a type field and choices=(('I','Individual'),('C','Company)). Based on the type o...
Structuring Django-App to Attach Custom Business Rules to Object Instances
I'm torn how to structure my code to accommodate business rules specific to instances of a particular model. For example. Lets say I have a Contact model with a type field and choices=(('I','Individual'),('C','Company)). Based on the type of model that I have, I might want to have custom methods. So thinking out loud, ...
[ "Take a look at django proxy models. They allow you to do exactly what you want.\nhttp://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models\nBut since in you case the behavior is dependent on the field value, then you should add custom managers to the proxy models that retrieve items only of only that typ...
[ 1 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0004250092_django_models_python.txt
Q: Trace speed issues in python running on google app engine I'm new to python, django and google app engine. All great tools and have been enjoying working with them. However, on my production site its taking 4 seconds to load a webpage, which I think is horrible and needs to be less than a second. I've also verifie...
Trace speed issues in python running on google app engine
I'm new to python, django and google app engine. All great tools and have been enjoying working with them. However, on my production site its taking 4 seconds to load a webpage, which I think is horrible and needs to be less than a second. I've also verified the long amount of time is in the request to the get the page...
[ "Use appstats.\n" ]
[ 8 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004250065_django_django_nonrel_google_app_engine_google_cloud_datastore_python.txt
Q: Python 'self' for function I have read the SO post on 'self' explained, and I have read the Python documentation on classes. I think I understand the use of self in Python classes and the convention therein. However, being relatively new to Python and its idioms, I cannot understand why some use self in a procedu...
Python 'self' for function
I have read the SO post on 'self' explained, and I have read the Python documentation on classes. I think I understand the use of self in Python classes and the convention therein. However, being relatively new to Python and its idioms, I cannot understand why some use self in a procedural type function definition. Fo...
[ "In the example bit_length is defined as a function for the int class, so there is actually a 'class or method'. The idea is that you 'ask' an integer to give its bit_length, hence it is defined to take self as an argument.\n", "No real reason. But if you're going to monkeypatch it onto an existing class then it ...
[ 6, 4 ]
[]
[]
[ "idioms", "python", "self" ]
stackoverflow_0004250222_idioms_python_self.txt
Q: Python Default Variable in for loop I am wondering if Python has the concept of storing data in the default variable in for loop. For example, in perl, the equivalent is as follow foreach (@some_array) { print $_ } Thanks, Derek A: No. You should just use for each in some_array: print each A: Just for...
Python Default Variable in for loop
I am wondering if Python has the concept of storing data in the default variable in for loop. For example, in perl, the equivalent is as follow foreach (@some_array) { print $_ } Thanks, Derek
[ "No. You should just use\nfor each in some_array:\n print each\n\n", "Just for fun, here's something that does just about what you desire. By default it binds the loop variable to the name \"_each\", but you can override this with one of your own choosing by supplying a var keyword argument to it.\nimport insp...
[ 15, 2, 1, 0 ]
[]
[]
[ "for_loop", "python", "variables" ]
stackoverflow_0004247626_for_loop_python_variables.txt
Q: OpenCV 2.1 Python Bindings Segfaulting Hello I have a problem when grouping the OpenCV's functions in functions of my own and getting segmentation fault. Even with code as simple as this def acquire_imagen(): capture = cv.CaptureFromCAM( 0 ) img = cv.QueryFrame( capture ) return img img = acquire_image() pri...
OpenCV 2.1 Python Bindings Segfaulting
Hello I have a problem when grouping the OpenCV's functions in functions of my own and getting segmentation fault. Even with code as simple as this def acquire_imagen(): capture = cv.CaptureFromCAM( 0 ) img = cv.QueryFrame( capture ) return img img = acquire_image() print img[0,0] If I call the same instructions...
[ "To prevent the capture object from being garbage-collected, keep a reference to it in a variable until you no longer need the images. In your code: the \"capture\" variable cannot be a local variable of the function, but a variable outside the function. Or, if you want it to be initialized inside the function, ret...
[ 2, 1 ]
[]
[]
[ "opencv", "python", "segmentation_fault" ]
stackoverflow_0003689871_opencv_python_segmentation_fault.txt
Q: Django and thread safety If I read the django documentation, only the documents about the template tags mention the potential danger of thread safety. However, I'm curious what kind of things I have to do / avoid to write thread-safe code in Django... One example is, I have the following function to config the log...
Django and thread safety
If I read the django documentation, only the documents about the template tags mention the potential danger of thread safety. However, I'm curious what kind of things I have to do / avoid to write thread-safe code in Django... One example is, I have the following function to config the loggers used in django. _LOGGER_C...
[ "There's not really a whole lot you can do about django templates and their issues with threading, besides not using them, or at least not using the tags that are sensitive to threading issues. There aren't many django template tags that do have issues, only the stateful ones do, such as cycle. \nIn the example y...
[ 1 ]
[]
[]
[ "django", "python", "thread_safety" ]
stackoverflow_0004250019_django_python_thread_safety.txt
Q: _tkinter.TclError: invalid command name "labelframe" I'm getting the following error when running a python/tkinter GUI application I wrote. I thought it could be a Tcl/Tk version issue, but the LabelFrame() command was added in Tcl/Tk 8.4, (which is the version I am using). The other computer that I am attempti...
_tkinter.TclError: invalid command name "labelframe"
I'm getting the following error when running a python/tkinter GUI application I wrote. I thought it could be a Tcl/Tk version issue, but the LabelFrame() command was added in Tcl/Tk 8.4, (which is the version I am using). The other computer that I am attempting to execute the program on is able to run another pyt...
[ "python may be using its own special version of TCL/TK, depending on how it was built and installed. This is usually the case on on windows, sometimes the case on linux, and seldom the case on MacOS X. You must rely on the version reported inside python to know what version it is using. \nIf python is not using t...
[ 2, 1 ]
[]
[]
[ "python", "tcl", "tkinter" ]
stackoverflow_0004250138_python_tcl_tkinter.txt
Q: Python Library for packet creation//manipulation I am currently working on libpcap-python, I found it does not help(I don't know how) in modifying packet data. Is there any library which can be used to create network packet? A: Did you have a look at scapy http://www.secdev.org/projects/scapy/
Python Library for packet creation//manipulation
I am currently working on libpcap-python, I found it does not help(I don't know how) in modifying packet data. Is there any library which can be used to create network packet?
[ "Did you have a look at scapy\n\nhttp://www.secdev.org/projects/scapy/\n\n" ]
[ 4 ]
[]
[]
[ "libpcap", "python" ]
stackoverflow_0004251076_libpcap_python.txt
Q: ListProperty of custom properties Is there a elegant way of using a ListProperty for storing a subclassed db.Property type? For example, the FuzzyDateProperty from this example uses get_value_for_datastore() and make_value_from_datastore() to convert its attributes into one int that is stored in the datastore. Si...
ListProperty of custom properties
Is there a elegant way of using a ListProperty for storing a subclassed db.Property type? For example, the FuzzyDateProperty from this example uses get_value_for_datastore() and make_value_from_datastore() to convert its attributes into one int that is stored in the datastore. Since that one int is a Python primitive,...
[ "According to the Types and Property Classes doc\n\nThe App Engine datastore supports a\n fixed set of value types for\n properties on data entities. Property\n classes can define new types that are\n converted to and from the underlying\n value types, and the value types can\n be used directly with Expando d...
[ 2, 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004221580_google_app_engine_google_cloud_datastore_python.txt
Q: Good advice for coming to javascript (from Python) I am coming to JavaScript, from Python. I want to write testable, modular JS code, and want advice on tools, best practices and the like. I know about: JSLint (and the existence of Douglas Crockford) Paul Irish (hi Paul!) and the 10 Things...From the jQuery So...
Good advice for coming to javascript (from Python)
I am coming to JavaScript, from Python. I want to write testable, modular JS code, and want advice on tools, best practices and the like. I know about: JSLint (and the existence of Douglas Crockford) Paul Irish (hi Paul!) and the 10 Things...From the jQuery Source podcast jQuery, jQuery.ui and Themeroller the exist...
[ "For techniques check out this post about js patterns: https://stackoverflow.com/questions/7002/what-javascript-patterns-do-you-use-most\nAlso, I use Aptana (an Eclipse derivative) as an IDE. Works out pretty nicely.\n", "You should consider investigating Pyjamas which allows you to write rich internet applicati...
[ 1, 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0004251406_javascript_python.txt
Q: In Django, when should I use doctests instead of unit testing? From Django docs: ...the database is not refreshed between doctests, so if your doctest requires a certain state you should consider flushing the database or loading a fixture. Quite frankly, 90% of my testing is currently done in doctests. A colleag...
In Django, when should I use doctests instead of unit testing?
From Django docs: ...the database is not refreshed between doctests, so if your doctest requires a certain state you should consider flushing the database or loading a fixture. Quite frankly, 90% of my testing is currently done in doctests. A colleague of mine thought that was peculiar. In all honesty, I do very litt...
[ "As your project grows, you'll find that unittests are far better for testing your code.\nThe Django project itself is in the process of converting all doctests to unittests (we'll be done by the 1.3 release). The reason we're doing this is that prior to this conversion, the order of execution in the test suite wou...
[ 15, 1 ]
[]
[]
[ "django", "doctest", "python", "testing", "unit_testing" ]
stackoverflow_0004251381_django_doctest_python_testing_unit_testing.txt
Q: Using python mechanize to login on webpage with javascript md5 hashing function I'm trying to use python / mechanize to login to this webpage: http://www.solaradata.com/cgi-bin/mainProgram.cgi The login form uses a Javascript function that produces an MD5 hash from several field values before submitting the resul...
Using python mechanize to login on webpage with javascript md5 hashing function
I'm trying to use python / mechanize to login to this webpage: http://www.solaradata.com/cgi-bin/mainProgram.cgi The login form uses a Javascript function that produces an MD5 hash from several field values before submitting the results for authentication. Since mechanize can't do javascript, I tried to replicate the ...
[ "Use m1.hexdigest() instead of m1.digest()\n", "I'm not familiar with python, but it appears the they are returning the hex value of the MD5 hash in the javascript version of the algorithm. Does the python MD5 do the same?\nYou should be able to test this without going through the submission process and testing ...
[ 1, 0, 0 ]
[]
[]
[ "autologin", "javascript", "md5", "mechanize", "python" ]
stackoverflow_0004250061_autologin_javascript_md5_mechanize_python.txt
Q: Problem reading hex data from image - python automatically converts to a string I am reading in an image one byte at a time with with read(1), and appending it to a list. The image data is all hex data. When I print out the list with the print function it is in the format '\xd7' ['\xd7', '\xd7', '\xd7', '\xd7', '\...
Problem reading hex data from image - python automatically converts to a string
I am reading in an image one byte at a time with with read(1), and appending it to a list. The image data is all hex data. When I print out the list with the print function it is in the format '\xd7' ['\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7', '\xd7',...] The problem is that now I need to perform some calculation...
[ "It's interpreting them as characters, so use ord to turn them into numbers. I.e. ord('\\xd7') gives 215.\nAlso if you use Windows, or the program might have to run on Windows, make sure that you've got the file open in binary mode: open(\"imagefile.png\",\"rb\"). Makes no difference on other operating systems.\n",...
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "hex", "image", "python", "string" ]
stackoverflow_0004250682_hex_image_python_string.txt
Q: Filter out the accelerometers noise using Kalman filter in Python I get from a socket a stream of data from an accelerometer with a lot of noise. something like this: ... -0.014532123 0.183950298 0.003323536 -0.342343526 ... I tried with low pass filter but I can't get a really smoothed result.. I think I need to...
Filter out the accelerometers noise using Kalman filter in Python
I get from a socket a stream of data from an accelerometer with a lot of noise. something like this: ... -0.014532123 0.183950298 0.003323536 -0.342343526 ... I tried with low pass filter but I can't get a really smoothed result.. I think I need to use Kalman filter so I have to implement a function that "corrects" ev...
[ "Taking an average of the last x results could do the smoothing.\nx would be a constant that can be tweaked for the best results depending on your application\nYou can also filter out input that is more than y off from the average of the last x numbers.\n" ]
[ 1 ]
[]
[]
[ "accelerometer", "filter", "kalman_filter", "python" ]
stackoverflow_0004251596_accelerometer_filter_kalman_filter_python.txt
Q: possible to define a function in commandline window of a programming language? Is it possible to define a function in commandline window of Matlab? Looks no to me. But for R, it is possible to do so. I was wondering why there is this difference and if there is more to say behind this kind of feature of a programmi...
possible to define a function in commandline window of a programming language?
Is it possible to define a function in commandline window of Matlab? Looks no to me. But for R, it is possible to do so. I was wondering why there is this difference and if there is more to say behind this kind of feature of a programming language, or can I say just interpretive language (such as Python, Bash,...)? Tha...
[ "You can define functions in the command window of Matlab. It will be evaluated like a function, but it won't be available to you in your next Matlab session (though you can save and load it like a variable). \nAs an example, I copy @Dirk Eddelbuettel's function\n>> cubed = @(x)x^3;\n>> cubed(2)\nans =\n 8\n\nE...
[ 4, 2, 1 ]
[]
[]
[ "bash", "matlab", "python", "r" ]
stackoverflow_0004251553_bash_matlab_python_r.txt
Q: Java and whitespace-as-syntax (ala Python)? There is a part of java syntax that bugs the crap out of me: that's curly braces and semicolons. Is there some sort of translator that exists that will allow me to use all of the Java syntax except for this? I want to do something like this: public class Hello: publi...
Java and whitespace-as-syntax (ala Python)?
There is a part of java syntax that bugs the crap out of me: that's curly braces and semicolons. Is there some sort of translator that exists that will allow me to use all of the Java syntax except for this? I want to do something like this: public class Hello: public static void main(String[] args): System...
[ "Can you switch to Jython? Python's syntax, Java's runtime environment.\n", "You might consider instead investing time in learning to use eclipse and the code formatter. \nPython's model is great in that it (more or less) forces all developers into the same code style format. Modern software firms have code-style...
[ 2, 0, 0 ]
[]
[]
[ "java", "python", "syntax", "whitespace" ]
stackoverflow_0004251478_java_python_syntax_whitespace.txt
Q: Switching from amara to lxml in Python I am trying to accomplish with lxml library something like this: http://www.xml.com/pub/a/2005/01/19/amara.html from amara import binderytools container = binderytools.bind_file('labels.xml') for l in container.labels.label: print l.name, 'of', l.address.city but I have...
Switching from amara to lxml in Python
I am trying to accomplish with lxml library something like this: http://www.xml.com/pub/a/2005/01/19/amara.html from amara import binderytools container = binderytools.bind_file('labels.xml') for l in container.labels.label: print l.name, 'of', l.address.city but I have had the hardest time to get my feel wet! Wh...
[ "import lxml.etree as le\nimport io\n\ncontent='''\\\n<foo><X><Y>skip this</Y><Y><Z name=\"apple\"><W>not here</W></Z>\n<Z name=\"bacon\"><W><A>42</A><B>b</B><C>c</C></W><W><A>256</A><B>b</B><C>c</C></W></Z>\n<Z name=\"bacon\"><W><A>42</A><B>b</B><C>c</C></W><W><A>256</A><B>b</B><C>c</C></W></Z>\n</Y></X></foo>\n''...
[ 3 ]
[]
[]
[ "amara", "lxml", "python", "xml_parsing" ]
stackoverflow_0004251750_amara_lxml_python_xml_parsing.txt
Q: Opening Webpage using Python I am new to Python coding and i am trying to open a web page using python. I used web browser.open to open the web page. After i opened the web page i want to click a tab called "Submit" on the web page when the timer on the page reaches zero. If i get a error then it should return to ...
Opening Webpage using Python
I am new to Python coding and i am trying to open a web page using python. I used web browser.open to open the web page. After i opened the web page i want to click a tab called "Submit" on the web page when the timer on the page reaches zero. If i get a error then it should return to the original page without any user...
[ "Instead of using that particular module, maybe you want to use Selenium RC, which has python bindings.\n", "This will depend on if you need to use a \"real\" browser application to do this. Can you explain what you are trying to do in a bit more detail?\nAnyway...\nIf you need a \"real\" browser to launch and m...
[ 3, 2, 1 ]
[]
[]
[ "python", "python_webbrowser", "url" ]
stackoverflow_0004251809_python_python_webbrowser_url.txt
Q: beginner question about python multiprocessing? I have a number of records in the database I want to process. Basically, I want to run several regex substitution over tokens of the text string rows and at the end, and write them back to the database. I wish to know whether does multiprocessing speeds up the time r...
beginner question about python multiprocessing?
I have a number of records in the database I want to process. Basically, I want to run several regex substitution over tokens of the text string rows and at the end, and write them back to the database. I wish to know whether does multiprocessing speeds up the time required to do such tasks. I did a multiprocessing....
[ "\nWhy is this so?\nCan someone please enlighten in what cases does multiprocessing gives better performances?\n\nHere's one trick.\nMultiprocessing only helps when your bottleneck is a resource that's not shared.\nA shared resource (like a database) will be pulled in 8 different directions, which has little real b...
[ 5, 1, 1 ]
[]
[]
[ "multicore", "postgresql", "python" ]
stackoverflow_0004252126_multicore_postgresql_python.txt
Q: passing multiple parameters for the url using pycurl I want to make a curl call with a URL that has multiple parameters. I have listed the code below. Is there an equivalent option for "curl -d @filter" for instance or do I have URL encode the parameters? SER = foobar PASS = XXX STREAM_URL = "http://status.dummy....
passing multiple parameters for the url using pycurl
I want to make a curl call with a URL that has multiple parameters. I have listed the code below. Is there an equivalent option for "curl -d @filter" for instance or do I have URL encode the parameters? SER = foobar PASS = XXX STREAM_URL = "http://status.dummy.com/status.json?userId=12&page=1" class Client: ...
[ "Pycurl is a pretty thin wrapper for libcurl. If you can do it with libcurl, you can do it with pycurl. (Mostly.)\nFor instance:\n\npycurl.setopt corresponds to curl_easy_setopt in libcurl, where option is specified with the CURLOPT_* constants in libcurl, except that the CURLOPT_ prefix has been removed.\n\nSee: ...
[ 3 ]
[]
[]
[ "curl", "pycurl", "python" ]
stackoverflow_0004252262_curl_pycurl_python.txt
Q: Fast algorithm to calculate delta of two list I have two list of album names, ordered by some score. albums_today = ['album1', 'album2', 'album3'] albums_yesterday = ['album2', 'album1', 'album3'] How can I calculate the change of list order and get something like {'album1':1, 'album2':-1, 'album3':0} A: >>> al...
Fast algorithm to calculate delta of two list
I have two list of album names, ordered by some score. albums_today = ['album1', 'album2', 'album3'] albums_yesterday = ['album2', 'album1', 'album3'] How can I calculate the change of list order and get something like {'album1':1, 'album2':-1, 'album3':0}
[ ">>> albums_today = ['album1', 'album2', 'album3']\n>>> albums_yesterday = ['album2', 'album1', 'album3']\n>>> D = dict((k,v) for v,k in enumerate(albums_yesterday))\n>>> dict((k,D[k]-v) for v,k in enumerate(albums_today))\n{'album1': 1, 'album3': 0, 'album2': -1}\n\nIn Python2.7 or Python3 it can be written even m...
[ 6, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0004251732_algorithm_python.txt
Q: recursive search boolean return function Write a recursive function search(l,key) that returns a boolean: True if key is in the list l; False if it isn’t. Describe the base case(s) and how the smaller problem relates to the bigger one. You may not use the in operator or the index() list method. Can anyone explain ...
recursive search boolean return function
Write a recursive function search(l,key) that returns a boolean: True if key is in the list l; False if it isn’t. Describe the base case(s) and how the smaller problem relates to the bigger one. You may not use the in operator or the index() list method. Can anyone explain what i need to do here for the description? I ...
[ "All recursion tends to follow the same rules:\n\nHave one or more terminating cases.\nEvery other case is a slightly simpler form of the current case.\n\nSo, for example, a (very inefficient) way to add two positive numbers a and b:\n\nif b is zero, return a.\notherwise add the two numbers a+1 and b-1.\n\nSomethin...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004252471_python.txt
Q: Generate all possible numpad/keypad sequences I am trying to generate all possible keypad sequences (7 digit length only right now). For example if the mobile keypad looks like this: 1 2 3 4 5 6 7 8 9 0 Some of the possible sequences can be: 123698 147896 125698 789632 The requirement is that the each d...
Generate all possible numpad/keypad sequences
I am trying to generate all possible keypad sequences (7 digit length only right now). For example if the mobile keypad looks like this: 1 2 3 4 5 6 7 8 9 0 Some of the possible sequences can be: 123698 147896 125698 789632 The requirement is that the each digit of number should be neighbor of previous digit...
[ "Try this.\n neighbors = {0: [8], \n 1: [2,4], \n 2: [1,4,3], \n 3: [2,6], \n 4: [1,5,7], \n 5: [2,4,6,8], \n 6: [3,5,9], \n 7: [4,8], \n 8: [7,5,9,0], \n 9: [6,8]}\n\n\ndef get_sequences(n):\n if not n:\n...
[ 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "numbers", "python" ]
stackoverflow_0004250342_algorithm_numbers_python.txt
Q: AppEngine Python project moved to Ubuntu from Windows will no longer run Since moving from Windows to Ubuntu (and setting up AppEngine, AppEngine Launcher, Python 2.5), my AppEngine projects will no longer run properly. Here is what's thrown back from any file when trying to browse the app in my web browser (runni...
AppEngine Python project moved to Ubuntu from Windows will no longer run
Since moving from Windows to Ubuntu (and setting up AppEngine, AppEngine Launcher, Python 2.5), my AppEngine projects will no longer run properly. Here is what's thrown back from any file when trying to browse the app in my web browser (running locally through dev_appserver.py), for example: Traceback (most recent call...
[ "Check your line endings to make sure they are Unix style, and no longer DOS style.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004252504_google_app_engine_python.txt
Q: Python GeoModel alternative I'm looking for an alternative library for the app engine datastore that will do nearest-n or boxed geo-queries, currently i'm using GeoModel 0.2 and it runs quite slow ( > 1.5s in some cases). Does anyone have any suggestions? Thanks! A: I have a same problem with geomodel. For corre...
Python GeoModel alternative
I'm looking for an alternative library for the app engine datastore that will do nearest-n or boxed geo-queries, currently i'm using GeoModel 0.2 and it runs quite slow ( > 1.5s in some cases). Does anyone have any suggestions? Thanks!
[ "I have a same problem with geomodel.\nFor correct it, i use a resolution of 4 and i use a python sorted and filter.\nSEARCHED_LOCATION = db.GeoPt(\"48.8566667, 2.3509871\") # Location of Paris.\nDISTANCE = 50000 #Between 10000 and 150000.\nMAX_RESULTS = 300\n\n# Resolution '4' is about 150 kilometers i suppose it'...
[ 6, 4, 2 ]
[]
[]
[ "geohashing", "gis", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003993862_geohashing_gis_google_app_engine_google_cloud_datastore_python.txt
Q: Uneven base-36 support in Python? I've been working with base-36 recently and have never been satisfied with the usual answer to converting ints into base-36 strings. It looks a little imbalanced… def to_base36(value): if not isinstance(value, int): raise TypeError("expected int, got %s: %r" % (value....
Uneven base-36 support in Python?
I've been working with base-36 recently and have never been satisfied with the usual answer to converting ints into base-36 strings. It looks a little imbalanced… def to_base36(value): if not isinstance(value, int): raise TypeError("expected int, got %s: %r" % (value.__class__.__name__, value)) if val...
[ "Have you tried the basin package? \n>>> import basin\n>>> basin.encode(\"0123456789abcdefghijklmnopqrstuvwxyz\", 100)\n'2s'\n\nIt's not batteries included, but the pypi repository is like a convenience store for picking up batteries with the minimum of fuss.\n", "Correct. Not every store carries N or J batterie...
[ 8, 4, 1 ]
[]
[]
[ "base36", "python" ]
stackoverflow_0004253053_base36_python.txt
Q: Inserting bold characters in pyGTK's TextView/TextBuffer I have a TextView and a TextBuffer associated with it. When the user presses Ctrl+b, I would like the text to be start typing in bold until user presses Ctrl+b again. I was trying my own methods, which weren't working, and then I found this post on the maili...
Inserting bold characters in pyGTK's TextView/TextBuffer
I have a TextView and a TextBuffer associated with it. When the user presses Ctrl+b, I would like the text to be start typing in bold until user presses Ctrl+b again. I was trying my own methods, which weren't working, and then I found this post on the mailing list: http://www.daa.com.au/pipermail/pygtk/2009-April/0169...
[ "In the sample code you make the call to iter.backward_chars in TextBuffer.text_inserted \nbut you never use that iter!, so I make a sample script to show you desired behavior and clarify:\nimport gtk\nimport pango\n\nclass TextBuffer(gtk.TextBuffer):\n def __init__(self):\n gtk.TextBuffer.__init__(self)\...
[ 5 ]
[]
[]
[ "gtk_textbuffer", "pygtk", "python", "textview" ]
stackoverflow_0004251658_gtk_textbuffer_pygtk_python_textview.txt
Q: Django Subprocess live/unbuffered reporting of stdout from batch scripts Basically the back story is that i've built a selecting of python scripts for a client to process importing and exporting batch jobs between their operations database and their ecomms site database. this works fine. these scripts write to std...
Django Subprocess live/unbuffered reporting of stdout from batch scripts
Basically the back story is that i've built a selecting of python scripts for a client to process importing and exporting batch jobs between their operations database and their ecomms site database. this works fine. these scripts write to stdout to update the user on the status of the batch script. I'm trying to produc...
[ "It helps if you use the following:\n['python','-u','path/to/python/script.py']\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_views", "mod_python", "python", "subprocess" ]
stackoverflow_0004222035_django_django_views_mod_python_python_subprocess.txt
Q: Can PyPy/RPython be used to produce a small standalone executable? (Or, "Can PyPy/RPython be used to compile/translate Python to C/C++ without requiring the Python runtime?") I have tried to comprehend PyPy with its RPython and its Python, its running and its compiling and its translating, and have somewhat failed...
Can PyPy/RPython be used to produce a small standalone executable?
(Or, "Can PyPy/RPython be used to compile/translate Python to C/C++ without requiring the Python runtime?") I have tried to comprehend PyPy with its RPython and its Python, its running and its compiling and its translating, and have somewhat failed. I have a hypothetical Python project (for Windows); I would like to ke...
[ "Yes, PyPy can produce standalone executables from RPython code. That means, you need to follow all the awkward RPython rules when it comes to writing code. Your Python code is completely unlikely to function out of the box and porting existing Python code is usually not fun. It won't make executables as small as C...
[ 18 ]
[]
[]
[ "compiler_construction", "pypy", "python", "rpython", "translate" ]
stackoverflow_0004251964_compiler_construction_pypy_python_rpython_translate.txt
Q: Sorting alphanumerical dictionary keys in python I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ... def sort_keys(dictionary): keys = dictionary.keys() keys.sort() return map(dictionary.get, keys) How do I sort it so that they get in the r...
Sorting alphanumerical dictionary keys in python
I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ... def sort_keys(dictionary): keys = dictionary.keys() keys.sort() return map(dictionary.get, keys) How do I sort it so that they get in the right order, ie A1, A2, A3 ... ?
[ "keys.sort(key=lambda k:(k[0], int(k[1:])) )\n\nEdit: This will fail in the keys are not like A23, e.g. AA12 will stop the program. In the general case, see Python analog of natsort function (sort a list using a \"natural order\" algorithm).\n", "dictionary.keys() return a list and you can sort list by your own f...
[ 9, 1, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0004253785_dictionary_python_sorting.txt
Q: How do you translate this to objective C? class MyClass(): def printer(name="abc", description="123") print name + description This is python...how can you translate that to objective C? A: Something like this will get you started: - (void)printName:(NSString *)name andDescription:(NSString *)descri...
How do you translate this to objective C?
class MyClass(): def printer(name="abc", description="123") print name + description This is python...how can you translate that to objective C?
[ "Something like this will get you started:\n- (void)printName:(NSString *)name andDescription:(NSString *)description\n{\n if (name == nil) name = @\"abc\";\n if (description == nil) description = @\"123\";\n NSLog(@\"%@%@\", name, description);\n}\n\n" ]
[ 2 ]
[]
[]
[ "objective_c", "oop", "python" ]
stackoverflow_0004254130_objective_c_oop_python.txt
Q: POST data has wrong value for Django template variable? I have the following code in my template: <form action="" method="post">{% csrf_token %} {%for category, category_votes in votes%} <p>{{category}}: {{category_votes}} <!-- displays as expected --> <input type="hidden" name="voted...
POST data has wrong value for Django template variable?
I have the following code in my template: <form action="" method="post">{% csrf_token %} {%for category, category_votes in votes%} <p>{{category}}: {{category_votes}} <!-- displays as expected --> <input type="hidden" name="votedCat" value="{{category}}" id={{forloop.counter}}> ...
[ "Because you only have one single form, with multiple inputs for votedCat. Clicking any of the buttons submits the whole form, with all the values for votedCat. If you were to access request.POST.getlist('votedCat') you would see that you actually have all the values.\nThere are two ways of fixing this. The first i...
[ 3, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004254252_django_django_templates_python.txt
Q: django-sphinx: SphinxClient instance has no attribute 'SetFieldWeights' In my models, when I refer to SphinxSearch with defaults like: from djangosphinx.models import SphinxSearch class Blog(models.Model): ... search = SphinxSearh() the fulltext search works fine. But when I give weights attribute as doc...
django-sphinx: SphinxClient instance has no attribute 'SetFieldWeights'
In my models, when I refer to SphinxSearch with defaults like: from djangosphinx.models import SphinxSearch class Blog(models.Model): ... search = SphinxSearh() the fulltext search works fine. But when I give weights attribute as documented: search = SphinxSearch( weights={'title': 10, 'body': 5, 'tags': ...
[ "This problem is coming due to version of sphinxapi, put \n\nSPHINX_API_VERSION = 0x116\n\nin your settings.py file. problem will get resolve.\nDefault version getting picked up is 0x107, which doesn't have implemented 'SetFieldWeights' function.\n" ]
[ 4 ]
[]
[]
[ "django_sphinx", "full_text_search", "python" ]
stackoverflow_0004139208_django_sphinx_full_text_search_python.txt
Q: where to start programing a server application Question: Where is a good starting point for learning to write server applications? Info: I'm looking in to writing a distributed computing system to harvest the idle cycles of the couple hundred computers sitting idle around my college's campus. There are systems th...
where to start programing a server application
Question: Where is a good starting point for learning to write server applications? Info: I'm looking in to writing a distributed computing system to harvest the idle cycles of the couple hundred computers sitting idle around my college's campus. There are systems that come close, but don't quite meet all the requirem...
[ "Check out the following discussion on SO\n\nWould twisted be a good choice for building a multi-threaded server?\n\nAlso check out the fantastic introductions at\n\nTwisted Introduction : http://krondo.com/?page_id=1327\nTwisted Web in 60 seconds : http://jcalderone.livejournal.com/50562.html\n\n", "Twisted is a...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004253557_python.txt
Q: Looking to write my own 'Application Whitelisting Tool' Something like Bit9? Playing around with project ideas that I might actually use, figured I might try to write my own simple version of Bit9 Parity, in either C# or Python. My question is what is the best way to go about doing this. I've googled .Net function...
Looking to write my own 'Application Whitelisting Tool' Something like Bit9?
Playing around with project ideas that I might actually use, figured I might try to write my own simple version of Bit9 Parity, in either C# or Python. My question is what is the best way to go about doing this. I've googled .Net functionality for prevent processes from executing, but I havn't really found what I'm loo...
[ "This blog post (Using WMI to monitor process creation, deletion and modification in .NET) shows how to do that. With a few changes, you should be able to do exactly what you want.\n", "\nHow do I block ALL other processes from starting? \n\nDeep, mysterious OS API magic. After all, you're interfering with how t...
[ 2, 1 ]
[]
[]
[ "c#", "process", "python", "whitelist" ]
stackoverflow_0004252725_c#_process_python_whitelist.txt
Q: Testing Google App Engine app from terminal (python cli) I'm running from appname import model, which gives me: ImportError: No module named google.appengine.api So I add the following Python path (the only path I could find): PYTHONPATH=/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine...
Testing Google App Engine app from terminal (python cli)
I'm running from appname import model, which gives me: ImportError: No module named google.appengine.api So I add the following Python path (the only path I could find): PYTHONPATH=/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/:~/src/app...
[ "From dev_appserver.py:\nDIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))\n# ...\n\nEXTRA_PATHS = [\n DIR_PATH,\n os.path.join(DIR_PATH, 'lib', 'antlr3'),\n os.path.join(DIR_PATH, 'lib', 'django'),\n os.path.join(DIR_PATH, 'lib', 'fancy_urllib'),\n os.path.join(DIR_PATH, 'lib', 'ipaddr')...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004255380_google_app_engine_python.txt