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: Type of slice impacts mutability of numpy array I create netCDF files using python. When I try to assign values (data) to parts (or slices) of variables, depending on what is the "type" of slice, I can or I cannot assign the values. I don't know why. Any help to understand why that is would be appreciated. E.g...
Type of slice impacts mutability of numpy array
I create netCDF files using python. When I try to assign values (data) to parts (or slices) of variables, depending on what is the "type" of slice, I can or I cannot assign the values. I don't know why. Any help to understand why that is would be appreciated. E.g.: import numpy as np from netCDF4 import Dataset ...
[ "Your example code seems to work on my machine, but I think you might be having a problem because you're using multiple index on the left side of your assignment. A[0, :, ::-1][...] = something where A is an array is weird, and even though it seems to work on my machine, I would try and avoid it. If that doesn't so...
[ 2 ]
[]
[]
[ "arrays", "netcdf", "numpy", "python", "slice" ]
stackoverflow_0008485107_arrays_netcdf_numpy_python_slice.txt
Q: How can I examine the network communications of the Python HTTP Client? I'm trying to isolate a bug that exists either in Python's httplib2 HTTP client or an API. (First guess is the API.) While using httplib2 to POST data to a RESTful API, I'm getting a 401 response status (no authorization) and saving data to...
How can I examine the network communications of the Python HTTP Client?
I'm trying to isolate a bug that exists either in Python's httplib2 HTTP client or an API. (First guess is the API.) While using httplib2 to POST data to a RESTful API, I'm getting a 401 response status (no authorization) and saving data to the API. I'd like to examine the HTTP request and response to the client,...
[ "I use http://www.charlesproxy.com for all my network debugging.\n", "http://www.wireshark.org/ enables you to monitor local sockets too.\nI was able to monitor local loopback even on windows using trick whit adding route. \nhttp://wiki.wireshark.org/CaptureSetup/Loopback check Other Alternatives\nOr you can just...
[ 4, 2 ]
[]
[]
[ "http", "httplib2", "network_programming", "python" ]
stackoverflow_0008567802_http_httplib2_network_programming_python.txt
Q: Importing a python module without actually executing it In the context of a complex application, I need to import user-supplied 'scripts'. Ideally, a script would have def init(): blah def execute(): more blah def cleanup(): yadda so I'd just import imp fname, path, desc = imp.find_module(userscript...
Importing a python module without actually executing it
In the context of a complex application, I need to import user-supplied 'scripts'. Ideally, a script would have def init(): blah def execute(): more blah def cleanup(): yadda so I'd just import imp fname, path, desc = imp.find_module(userscript) foo = imp.load_module(userscript, fname, path, desc) foo.in...
[ "My attempt using the ast module:\nimport ast\n\n# which syntax elements are allowed at module level?\nwhitelist = [\n # docstring\n lambda x: isinstance(x, ast.Expr) \\\n and isinstance(x.value, ast.Str),\n # import\n lambda x: isinstance(x, ast.Import),\n # class\n lambda x: isinstance(x, ast.Cl...
[ 10, 6, 4, 2, 0 ]
[ "A solution to 1 to 3, ( not the yadda part ) is to hand out \"generic_class.py\" with all the methods that you need. So, \nclass Generic(object):\n\n def __init__(self):\n return\n\n def execute(self):\n return\n\n # etc\n\nYou can then check for the existence of \"generic\" in what you've i...
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0008552165_python_python_3.x.txt
Q: snmpset in python I am using the python to send an snmpset message to an snmp agent. I have the correct OID as I can use it to get data with snmpget. However, it will not set the data. I am sending octets in hex format (two hex values) separated by a colon. I might have to put apostrophes around it, right? He...
snmpset in python
I am using the python to send an snmpset message to an snmp agent. I have the correct OID as I can use it to get data with snmpget. However, it will not set the data. I am sending octets in hex format (two hex values) separated by a colon. I might have to put apostrophes around it, right? Here is the example of th...
[ "A couple of things:\n1) there is a native python interface you could use instead of calling a system command. There are in fact multiple choices, including pysnmp (done in python) and Net-SNMP's python module (done in C).\n2) The Net-SNMP snmpset command expects straight hex code without any :s in it. So if you ...
[ 0 ]
[]
[]
[ "python", "snmp" ]
stackoverflow_0008438594_python_snmp.txt
Q: Python: How to access only some boolean elements of a list with a loop? I have list like this: listvalues = [True, True, False, True, False, 24, somestring, 50] So the first five elements of the list are booleans, the rest are strings and ints. Now I want to check the first five elements if they are true or false,...
Python: How to access only some boolean elements of a list with a loop?
I have list like this: listvalues = [True, True, False, True, False, 24, somestring, 50] So the first five elements of the list are booleans, the rest are strings and ints. Now I want to check the first five elements if they are true or false, and if they are true, I want to use a certain method, depending on the index...
[ "There are a number of things that might help here. First off, you should use list slicing to isolate the booleans. If you know the first 5 elements are what you're after, then myList[0:5] will get just those and ignore the others.\nNext, look into the any function. It'll return True if any of the elements is Tr...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "boolean", "indexing", "list", "python" ]
stackoverflow_0008568242_boolean_indexing_list_python.txt
Q: Python - Append to CSV I am trying to append to a CSV file with the following code import csv cat_options = [row for row in csv.reader(open('catOptions.csv', 'r'), delimiter =',')] print cat_options new_cat = raw_input("\nEnter the new category: ") cat_options = csv.writer(open('catOptions.csv', 'a')) cat_options ...
Python - Append to CSV
I am trying to append to a CSV file with the following code import csv cat_options = [row for row in csv.reader(open('catOptions.csv', 'r'), delimiter =',')] print cat_options new_cat = raw_input("\nEnter the new category: ") cat_options = csv.writer(open('catOptions.csv', 'a')) cat_options = cat_options.writerows(new_...
[ "Use csvwriter.writerow() if you only want to write a single row.\n" ]
[ 5 ]
[]
[]
[ "append", "python" ]
stackoverflow_0008568570_append_python.txt
Q: Adding a field to an existing SQLAlchemy schema that contains data Is there a way I could update my database schema without affecting my existing data? A: There are at least two possible options: first is to manually update the database schema (ALTER TABLE foo ADD COLUMN foo ...) and second option would be using...
Adding a field to an existing SQLAlchemy schema that contains data
Is there a way I could update my database schema without affecting my existing data?
[ "There are at least two possible options: first is to manually update the database schema (ALTER TABLE foo ADD COLUMN foo ...) and second option would be using some kind of migrations tool.\n" ]
[ 1 ]
[]
[]
[ "flask", "python", "sqlalchemy" ]
stackoverflow_0007889345_flask_python_sqlalchemy.txt
Q: How do you organize Python modules? When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them. How do you keep everything manageable? A: My advice: Read Installing Python Modules. Read Distributing Python M...
How do you organize Python modules?
When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them. How do you keep everything manageable?
[ "My advice:\n\nRead Installing Python Modules.\nRead Distributing Python Modules.\nStart using easy_install from setuptools. Read the documentation for setuptools.\nAlways use virtualenv. My site-packages directory contains setuptools and virtualenv only.\nCheck out Ian Bicking's new project pyinstall. \nFollow eve...
[ 13, 5, 5, 2, 2, 1, 1, 1 ]
[]
[]
[ "module", "python" ]
stackoverflow_0000171785_module_python.txt
Q: B2B App authentication on GAE - Google Accounts or custom user base (Django or Web2Py)? Which of these would you pick for a B2B app (targeting small/med-small businesses) built on GAE with python: Google Accounts Custom Users with Django Custom Users with Web2Py I'm very tempted to go the Google Accounts route a...
B2B App authentication on GAE - Google Accounts or custom user base (Django or Web2Py)?
Which of these would you pick for a B2B app (targeting small/med-small businesses) built on GAE with python: Google Accounts Custom Users with Django Custom Users with Web2Py I'm very tempted to go the Google Accounts route as it's very well integrated into GAE and takes care of everything from user creation to sessi...
[ "Google Accounts forces users to have Google Apps or Gmail accounts. Some customers might not like this.\nRolling your own is an (unnecessary) burden: you have to have sign up process (with captcha and/or 3rd party email confirmation), keep all user records, handle the security, etc..\nI'd suggest you go with OpenI...
[ 2, 2, 1, 1 ]
[]
[]
[ "django", "google_app_engine", "python", "web2py" ]
stackoverflow_0008566399_django_google_app_engine_python_web2py.txt
Q: psycopg2 + stored procedure + compound type I have a stored procedure in PostgreSQL that takes a t_document composite type defined as follows: CREATE TYPE t_document AS ( title text, metadata text, data text ); The stored procedure takes other arguments as well, with a signature like: CREATE or...
psycopg2 + stored procedure + compound type
I have a stored procedure in PostgreSQL that takes a t_document composite type defined as follows: CREATE TYPE t_document AS ( title text, metadata text, data text ); The stored procedure takes other arguments as well, with a signature like: CREATE or REPLACE FUNCTION sp_insertItem ( name varch...
[ "You can pass name, phone, and address in a tuple, eventually with an explicit cast to better disambiguate:\ncur.execute(\"sp_insertItem(%s, %s, %s, %s::t_document)\",\n ['Name', 'Phone', 'Address', ('Title', 'Metadata', 'Data')])\n\nYou could also use a namedtuple: it is adapted the same way.\nDocument = namedt...
[ 3 ]
[]
[]
[ "postgresql", "psycopg2", "python", "stored_procedures" ]
stackoverflow_0008208218_postgresql_psycopg2_python_stored_procedures.txt
Q: Python main control I've run into an issue and am looking for guidance from a few veterans. I've written a program in python that I'd like to run only periodically. I'm going to upload it to my sever, and what I'd like for it to do is to run every Monday through Friday, and every 5 minutes between 9:30 and 4. Bas...
Python main control
I've run into an issue and am looking for guidance from a few veterans. I've written a program in python that I'd like to run only periodically. I'm going to upload it to my sever, and what I'd like for it to do is to run every Monday through Friday, and every 5 minutes between 9:30 and 4. Basically I've written modul...
[ "\nAn application should do one thing, and it should do it well.\n    - unix philosophy\n\n\nUnless there is any true reason for keeping the application running 24/7 (data consistency or such) I'd really recommend you to use a daemon to fire it up according to some schedule.\nYour application should focus on quer...
[ 3, 2, 1 ]
[]
[]
[ "controls", "daemon", "date", "python", "time" ]
stackoverflow_0008569433_controls_daemon_date_python_time.txt
Q: Web.py How to access render function in this case I am new to Python and Web.py, but I am tearing my hair out over this issue. I have a code layout where I have my app.py file in the root of my site. All the pages are in a sub director, named pages. Here is my app.py code import web import page.index urls = ( ...
Web.py How to access render function in this case
I am new to Python and Web.py, but I am tearing my hair out over this issue. I have a code layout where I have my app.py file in the root of my site. All the pages are in a sub director, named pages. Here is my app.py code import web import page.index urls = ( '/', 'page.index.index', ) render = web.template.rend...
[ "In the index.py page, should you include from web.template import render ?\n", "Presuming web.template.render() returns an object containing an index() method (I'm not familiar with web.py), you'll need to tell Python where to find this object.\nIn index.py:\nimport app\n\nThen:\n return app.render.index(test...
[ 1, 1, 1 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0006811412_python_web.py.txt
Q: SFTP error with Python/Paramiko writing a file I'm trying to write a small Python script that will get query results from a database, write them to a file, and then sftp the file to a different server. The pieces work just fine but I'm getting a weird error when trying to sftp the file immediately after it's writt...
SFTP error with Python/Paramiko writing a file
I'm trying to write a small Python script that will get query results from a database, write them to a file, and then sftp the file to a different server. The pieces work just fine but I'm getting a weird error when trying to sftp the file immediately after it's written. The error I'm getting is File "/usr/lib/python2....
[ "The error message is telling you that it (in this case, os.stat) wants a stringlike object, and you're giving it the file instead.\nLooking at the source of sftp_client.py in my copy of paramiko, we see\ndef put(self, localpath, remotepath, callback=None, confirm=True):\n [...]\n file_size = os.stat(localpat...
[ 1 ]
[]
[]
[ "paramiko", "python", "sftp" ]
stackoverflow_0008569480_paramiko_python_sftp.txt
Q: How to separate this Python list? How to separate this list into pieces in Python 2.6, I'm totally confused after 3 hours and need help! ['X1', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X2', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X3', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)'] I need something like t...
How to separate this Python list?
How to separate this list into pieces in Python 2.6, I'm totally confused after 3 hours and need help! ['X1', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X2', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)', 'X3', 'P1(0, 0, 0)', 'P2(0, 0, 0)', 'P3(0, 0, 0)'] I need something like this for output: X1 P1 0 0 0 X1 P2 0 0 0...
[ " for i in xrange(0,12,4):\n for j in xrange(1,4):\n sub_list = list[i+j].strip(')').split('(')\n print list[i], sub_list[0], ' '.join(sub_list[1].split(','))\n print '\\n'\n\nWill give you the desired output. \n", "Solution using itertools.groupby and translate:\nimport ite...
[ 3, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008569557_list_python.txt
Q: There are many missing files in egg packages when run plone 4 buildout I need help. I am trying to build plone 4.1 on my Fedora 14 Os. But I got a problem. It seems most of egg packages had many missing files. What I did: paster create -t plone4_buildout --> python2.6 boottrap.py --> bin/buildout. I did a workarou...
There are many missing files in egg packages when run plone 4 buildout
I need help. I am trying to build plone 4.1 on my Fedora 14 Os. But I got a problem. It seems most of egg packages had many missing files. What I did: paster create -t plone4_buildout --> python2.6 boottrap.py --> bin/buildout. I did a workaround: download packages from pypi and replace error packages. Could anyone tel...
[ "Most probably you ran a buildout that finished very badly during an extraction of some egg. Then you re-ran the buildout and the egg seemed to be already present but it was just a half of the real egg. Indeed, if you check the product on pypi, the missing dir do exists in the archive and I'm confident that would b...
[ 0 ]
[]
[]
[ "buildout", "plone", "python" ]
stackoverflow_0008542400_buildout_plone_python.txt
Q: How can I make wxTextCtrls in a FlexGridSizer all be 'x' lines high? I have an array, of unknown length, of key:val pairs. Each pair occupies a row in a FlexGridSizer. The keys are in the first column, as wx.StaticTexts, and the vals are in the second column, as wx.TextCtrls. The problem is that there isn't a lot...
How can I make wxTextCtrls in a FlexGridSizer all be 'x' lines high?
I have an array, of unknown length, of key:val pairs. Each pair occupies a row in a FlexGridSizer. The keys are in the first column, as wx.StaticTexts, and the vals are in the second column, as wx.TextCtrls. The problem is that there isn't a lot of room available, and some of the vals are relatively long, and don't fi...
[ "I suggest you use wxGrid.\nhttp://docs.wxwidgets.org/2.9.2/overview_grid.html\n", "According to the documentation for the wx.TextCtrl, you can apply the wx.HSCROLL style to it to make the control have a horizontal scrollbar, but this won't work on GTK1-based systems: http://xoomer.virgilio.it/infinity77/wxPython...
[ 0, 0, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0008440186_python_wxpython_wxwidgets.txt
Q: Does PyPy translate itself? Am I getting this straight? Does the PyPy interpreter actually interpret itself and then translate itself? So here's my current understanding: RPython's toolchain involves partially executing the program to be translated to get a sort of preprocessed version to annotate and translate....
Does PyPy translate itself?
Am I getting this straight? Does the PyPy interpreter actually interpret itself and then translate itself? So here's my current understanding: RPython's toolchain involves partially executing the program to be translated to get a sort of preprocessed version to annotate and translate. The PyPy interpreter, running o...
[ "PyPy's translation process is actually much less conceptually recursive than it sounds.\nReally all it is is a Python program that processes Python function/class/other objects (not Python source code) and outputs C code. But of course it doesn't process just any Python objects; it can only handle particular forms...
[ 66, 14 ]
[]
[]
[ "pypy", "python", "rpython" ]
stackoverflow_0008452396_pypy_python_rpython.txt
Q: Python sockets - stop stripping carriage return from UDP datagram I have a Python script that is reading an ASCII file (basically NMEA strings) and then broadcasting them over UDP using the basic socket library. Every second a 'paragraph' of NMEA strings are send out with a header. The server expects each paragrap...
Python sockets - stop stripping carriage return from UDP datagram
I have a Python script that is reading an ASCII file (basically NMEA strings) and then broadcasting them over UDP using the basic socket library. Every second a 'paragraph' of NMEA strings are send out with a header. The server expects each paragraph to begin with an empty line (specifically a \r\n, ie 0d 0a). I build ...
[ "You need to edit your original post with actual code so we can get a handle on what might be going wrong.\nThis is a short demonstration on Python 2.6 which does not have magic newline munging:\nPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyr...
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008568932_python_sockets.txt
Q: Python Object Comparison without defining __cmp__ for the class Suppose I create a class in python, but I don't define a __cmp__ method for my class. Now I create two instances of that class and compare them. What cmp method does Python use? I ran the code and it returns false when comparing for equality. Does Pyt...
Python Object Comparison without defining __cmp__ for the class
Suppose I create a class in python, but I don't define a __cmp__ method for my class. Now I create two instances of that class and compare them. What cmp method does Python use? I ran the code and it returns false when comparing for equality. Does Python compare memory addresses? class A(object): def __init__(self,...
[ "lambda x,y: id(x)==id(y) if memory serves.\n" ]
[ 2 ]
[]
[]
[ "cmp", "oop", "python" ]
stackoverflow_0008569962_cmp_oop_python.txt
Q: Python Twisted integration with Cmd module I like Python's Twisted and Cmd. I want to use them together. I got some things working, but so far I haven't figured out how to make tab-completion work, because I don't see how to receive tab keypres events right away (without pressing Enter) in Twisted's LineReceiver....
Python Twisted integration with Cmd module
I like Python's Twisted and Cmd. I want to use them together. I got some things working, but so far I haven't figured out how to make tab-completion work, because I don't see how to receive tab keypres events right away (without pressing Enter) in Twisted's LineReceiver. Here's my code so far: #!/usr/bin/env python f...
[ "You have a couple of difficulties with this approach:\n\nCmd.onecmd is not going to do any tab processing.\nEven if it did, your terminal needs to be in cbreak mode in order for individual keystrokes to make it to the Python interpreter (tty.setcbreak can take care of that).\nAs you know, Cmd.cmdloop is not reacto...
[ 9 ]
[]
[]
[ "python", "python_cmd", "stdin", "tab_completion", "twisted" ]
stackoverflow_0008568241_python_python_cmd_stdin_tab_completion_twisted.txt
Q: django python eval I have some code snippet of code I'd like to abstract to a function that only has one small change that needs to be dynamic if myUser.profile.get_setting_c == True : # below does not work but you get the idea, how if myUser.profile.eval('get_setting_c') == True : A: Is this what you want? get...
django python eval
I have some code snippet of code I'd like to abstract to a function that only has one small change that needs to be dynamic if myUser.profile.get_setting_c == True : # below does not work but you get the idea, how if myUser.profile.eval('get_setting_c') == True :
[ "Is this what you want?\ngetattr(myUser.profile, 'get_setting_c')\nBTW, using eval is considered bad practice in python, see Is using eval in Python a bad practice? .\n" ]
[ 4 ]
[ "Why not\nif eval('myUser.profile.get_setting_c') == True:\n\nor\ndef fun(setting):\n return eval('myUser.profile.%s' % setting)\n\nif fun('get_setting_c') == True:\n\n?\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0008569969_django_python.txt
Q: Storing RSS pubDate in App Engine Datastore The pubDate in an RSS feed is in the format: 2011-12-19T01:56:28-06:00 2011-10-19T06:11:02+00:00 How can I convert this to a common timezone so I can store it in db.DateTimeProperty() and sort items by date, regardless of timezone? A: That's a variant of ISO8601 date...
Storing RSS pubDate in App Engine Datastore
The pubDate in an RSS feed is in the format: 2011-12-19T01:56:28-06:00 2011-10-19T06:11:02+00:00 How can I convert this to a common timezone so I can store it in db.DateTimeProperty() and sort items by date, regardless of timezone?
[ "That's a variant of ISO8601 datetime format. This is my function for parsing dates like that:\nfrom datetime import datetime, timedelta\n\ndef parse_iso8601_datetime(dtstr, loose=False):\n \"\"\"\n Convert ISO8601 datetime string and return Python datetime.datetime.\n Specify loose=True for more relaxed ...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008569396_google_app_engine_python.txt
Q: Building a variable that combines several enumerations in an enormous list I'd like to come up with the simplest way possible to create an enormous list. Let's say I have three six-sided dice, so they'll each have a value of randint(1,6). I want the set of values that encompasses every possible way to combine tho...
Building a variable that combines several enumerations in an enormous list
I'd like to come up with the simplest way possible to create an enormous list. Let's say I have three six-sided dice, so they'll each have a value of randint(1,6). I want the set of values that encompasses every possible way to combine those 3 numbers, so it could be die1 * die2 + die3 or it could be die1 ** die3 - di...
[ "The key thing to know here is that you can pass a function as an argument to another function (or in a list). Once you understand that this problem becomes much easier to solve.\nIf you want a list comprehension:\nfrom operator import add,sub,mul,div\nfuncs = [add,sub,mul,div]\ndie = [1,2,3,4,5,6]\n\nresults = [f(...
[ 2, 0 ]
[]
[]
[ "combinatorics", "list", "python" ]
stackoverflow_0008569818_combinatorics_list_python.txt
Q: Which messaging queue for user messages I have application (tornado) where users can send/recieve private mesaages to/from each other and also can chat publicly. I am using redis (brukva) pub/sub mesaaging for realtime chat but I cant decide which mesaaging queue system should I use for private messaging part sinc...
Which messaging queue for user messages
I have application (tornado) where users can send/recieve private mesaages to/from each other and also can chat publicly. I am using redis (brukva) pub/sub mesaaging for realtime chat but I cant decide which mesaaging queue system should I use for private messaging part since its not realistic to send and process messa...
[ "The Redis List data structure makes a perfect queue, with atomic push/pop operations and everything else you would expect from a queue.\n" ]
[ 2 ]
[]
[]
[ "message_queue", "python", "redis", "tornado" ]
stackoverflow_0008528156_message_queue_python_redis_tornado.txt
Q: curses in python getstr() while refreshing I am writing a front end for a server application using the curses module. THe main windows returned by curses is divided into 2 sub-windows. The top half of the screen prints output from the server while the bottom line takes input with window.getstr(). Sometimes when ...
curses in python getstr() while refreshing
I am writing a front end for a server application using the curses module. THe main windows returned by curses is divided into 2 sub-windows. The top half of the screen prints output from the server while the bottom line takes input with window.getstr(). Sometimes when I am entering text and the top half is updating ...
[ "I'm guessing you are using a thread to update the upper display while window.getstr() runs in the main thread?\nIf so, the problem is that the curses terminal state is a shared resource that can't be updated from two different threads simultaneously. You need to put the terminal into non-blocking mode, use window....
[ 4 ]
[]
[]
[ "curses", "ncurses", "python" ]
stackoverflow_0008569878_curses_ncurses_python.txt
Q: is it safe to overwrite __setitem__ on an appengine polymodel? I'm making a spam filter library for google app engine, which uses app engine hooks to modify some data right before it is put() into the datastore. To do so, I created a model that subclasses the PolyModel class, which classes wishing to be checkable ...
is it safe to overwrite __setitem__ on an appengine polymodel?
I'm making a spam filter library for google app engine, which uses app engine hooks to modify some data right before it is put() into the datastore. To do so, I created a model that subclasses the PolyModel class, which classes wishing to be checkable should subclass. But for some data in the class, I'd like to do some...
[ "There is no danger in overriding methods, if you don't forget to call the parent method with super. But in your case __setitem__ is wrong place, because then everytime when instance is created it will be cleaned from spam, even if it is created from already cleaned values.\nWhat is wrong if you do that explicitly?...
[ 2, 2 ]
[]
[]
[ "google_app_engine", "magic_methods", "polymodel", "python" ]
stackoverflow_0008568353_google_app_engine_magic_methods_polymodel_python.txt
Q: Replace letters in a secret text I want to change every letter in a text to after next following letter. But this program doesnt work. Does anyone know why. Thanks in advance. There is also a minor problem with y and z. import string letters = string.ascii_lowercase text=("g fmnc wms bgblr rpylqjyrc gr zw fylb. r...
Replace letters in a secret text
I want to change every letter in a text to after next following letter. But this program doesnt work. Does anyone know why. Thanks in advance. There is also a minor problem with y and z. import string letters = string.ascii_lowercase text=("g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr ...
[ "Strings are immutable in python.\nSo text.replace returns a string, but doesn't change its original string.\nGiven that, you shouldn't actually use text.replace, since you would have to change the string 24 (or probably 26; see below) times. Rather, you can actually create a translation table to do all the changes...
[ 8, 4, 3, 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001971911_python_string.txt
Q: Running a Celery task when unable to import that task I have two servers: one running a django app and one running both a rabbitmq queue and a celery worker. My tasks.py on the server running the queue/worker contains a task as follows: @task(queue="reports") def test_task(): time.sleep(120) My goal is to exe...
Running a Celery task when unable to import that task
I have two servers: one running a django app and one running both a rabbitmq queue and a celery worker. My tasks.py on the server running the queue/worker contains a task as follows: @task(queue="reports") def test_task(): time.sleep(120) My goal is to execute this task from a django view. Since the code for the t...
[ "Resolved, turns out the publisher keyword arg i was passing to send_task was invalid and throwing an error. Didn't see the error because I was AJAX-requesting the page rather than navigating to it directly. Everything else about this situation was correct. I also removed the unnecessary keyword args and args being...
[ 8, 2 ]
[]
[]
[ "amqp", "celery", "django", "python", "rabbitmq" ]
stackoverflow_0008565862_amqp_celery_django_python_rabbitmq.txt
Q: Submitting Forms with Mechanize (Python) Well, I am trying to login to a site using Python and mechanize. I've got the site opened: site = br.open("http://example.com/login.php") And I've got a list of the forms (with br.forms). <GET http://example.com/search.php application/x-www-form-urlencoded <HiddenControl(s...
Submitting Forms with Mechanize (Python)
Well, I am trying to login to a site using Python and mechanize. I've got the site opened: site = br.open("http://example.com/login.php") And I've got a list of the forms (with br.forms). <GET http://example.com/search.php application/x-www-form-urlencoded <HiddenControl(search=1) (readonly)> ... <POST http://example....
[ "to select a form using its name you should use:\nbr.select_form(name=\"order\")\n\nwhat you are doing here:\nbr.form[\"username\"] = 'usernamehere'\n\nis trying to set a value to a control under the selected form, so when he can't find it, it throws the exception you are seeing.\n", "You might have several issue...
[ 4, 0 ]
[]
[]
[ "authentication", "forms", "mechanize", "python" ]
stackoverflow_0008570920_authentication_forms_mechanize_python.txt
Q: Is there an equivalent of a SQL View in Google App Engine Python? I've been learning python by building a webapp on google app engine over the past five or six months. I also just finished taking a databases class this semester where I learned about views, and their benefits. Is there an equivalent with the GAE da...
Is there an equivalent of a SQL View in Google App Engine Python?
I've been learning python by building a webapp on google app engine over the past five or six months. I also just finished taking a databases class this semester where I learned about views, and their benefits. Is there an equivalent with the GAE datastore using python?
[ "Read-only views (the most common type) are basically queries against one or more tables to present the illusion of new tables. If you took a college-level database course, you probably learned about relational databases, and I'm guessing you're looking for something like relational views.\nThe short answer is No.\...
[ 5, 2 ]
[]
[]
[ "google_app_engine", "python", "sql" ]
stackoverflow_0008570066_google_app_engine_python_sql.txt
Q: How to fix error while deploying Django in Apache2 using WSGI ( wsgi.py, line 284 ) I'm running into this error message while deploying django in apache2 using mod_wsgi and i cannot fix it: tail -f /var/log/apache2/error.log [Tue Dec 20 04:15:45 2011] [info] mod_wsgi (pid=3959): Adding '/usr/local/lib/python2.7/si...
How to fix error while deploying Django in Apache2 using WSGI ( wsgi.py, line 284 )
I'm running into this error message while deploying django in apache2 using mod_wsgi and i cannot fix it: tail -f /var/log/apache2/error.log [Tue Dec 20 04:15:45 2011] [info] mod_wsgi (pid=3959): Adding '/usr/local/lib/python2.7/site-packages/' to path. [Tue Dec 20 04:15:45 2011] [info] [client 80.226.1.7] mod_wsgi (pi...
[ "For the Python error, it looks like your mod_wsgi is compiled against Python 3.1 and not Python 2.7. You need to ensure that mod_wsgi which is installed was compiled against Python 2.7.\nThe clue is that error message is complaining that status is a byte string instead of text string. This can only occur in Python...
[ 2 ]
[]
[]
[ "apache2", "django", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0008570527_apache2_django_mod_wsgi_python_wsgi.txt
Q: Variable will be instantiated more than once I got something unusual when developing a small web server using Python2.7+Apache+mod_wsgi. The main usage of this server is: Receiving regular requests from another server(server A), and put the request body into DB. Using some background threads to parse the reques...
Variable will be instantiated more than once
I got something unusual when developing a small web server using Python2.7+Apache+mod_wsgi. The main usage of this server is: Receiving regular requests from another server(server A), and put the request body into DB. Using some background threads to parse the request body in DB and send the parsed information to a ...
[ "You likely modified the WSGI script file which caused mod_wsgi to reload it.\nTurn off reloading using:\nWSGIScriptReloading Off\n\nWhenever you make code changes then make sure you restart Apache.\nRead:\nhttp://code.google.com/p/modwsgi/wiki/ReloadingSourceCode#Reloading_In_Embedded_Mode\nhttp://code.google.com/...
[ 1 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0008570446_apache_mod_wsgi_python.txt
Q: Running .py files I have .ui, .py and .pyc files generated. Now, when I edit the .py file, how will it reflect changes in the .ui file? How do I connect .the ui and .py files together as QT designer allows only .ui files for running purposes? A: Don't edit the generated .py file. Create another .py file for the ...
Running .py files
I have .ui, .py and .pyc files generated. Now, when I edit the .py file, how will it reflect changes in the .ui file? How do I connect .the ui and .py files together as QT designer allows only .ui files for running purposes?
[ "Don't edit the generated .py file. Create another .py file for the Python code you need to write. This module should load the UI. This would also be the module to run, if these are the only files in the project. See a tutorial from here: http://diotavelli.net/PyQtWiki/Tutorials\n", "the .py file generated from p...
[ 1, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0008571366_pyqt_python.txt
Q: How can I modify the STDOUT? I'm currently writing a very simple terminal tool and I want to implement the following behavior. The terminal should display: Downloading "Something" ... And after I have completed the download, I want to replace that line with: Downloading "Something" [Done] I have seen this done o...
How can I modify the STDOUT?
I'm currently writing a very simple terminal tool and I want to implement the following behavior. The terminal should display: Downloading "Something" ... And after I have completed the download, I want to replace that line with: Downloading "Something" [Done] I have seen this done o create the following animation: [...
[ "Use the backspace character -- \\b.\nDon't forget to flush the output stream, it's likely buffered.\n", "Terminate the intermediate version of the line with \"\\r\". Any subsequent write will overwrite that line (so long as the new write is at least as long as the original).\nThere was a similar question not to...
[ 3, 3, 2, 2, 2 ]
[]
[]
[ "bash", "c", "python", "stdout", "terminal" ]
stackoverflow_0008571302_bash_c_python_stdout_terminal.txt
Q: What is the difference between class and data attributes? To quote diveintopython, "You already know about data attributes, which are variables owned by a specific instance of a class. Python also supports class attributes, which are variables owned by the class itself." In what sense are class attributes ow...
What is the difference between class and data attributes?
To quote diveintopython, "You already know about data attributes, which are variables owned by a specific instance of a class. Python also supports class attributes, which are variables owned by the class itself." In what sense are class attributes owned by a class? If you change the value of a class attribute in...
[ "I think that this example will explain the meaning to you.\nclass A(object):\n bar = 1\n\na = A()\nb = A()\nb.bar = 2\nprint a.bar # outputs 1\nA.bar = 3\nprint a.bar # outputs 3\nprint b.bar # outputs 2\n\nIn this case b.bar will be owned by instance after b.bar = 2 but a.bar will still be owned by class. T...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008572063_python.txt
Q: Getting all href from a code I'm making a web-crawler. For finding the links in a page I was using xpath in selenium driver = webdriver.Firefox() driver.get(side) Listlinker = driver.find_elements_by_xpath("//a") This worked fine. Testing the crawler however, I found that not all links come under the a tag. href ...
Getting all href from a code
I'm making a web-crawler. For finding the links in a page I was using xpath in selenium driver = webdriver.Firefox() driver.get(side) Listlinker = driver.find_elements_by_xpath("//a") This worked fine. Testing the crawler however, I found that not all links come under the a tag. href is sometimes used in area or div t...
[ "Try this:\nListlinkerHref = driver.find_elements_by_xpath(\"//*[@href]\")\n\n" ]
[ 6 ]
[]
[]
[ "beautifulsoup", "lxml", "python", "selenium", "web_crawler" ]
stackoverflow_0008572540_beautifulsoup_lxml_python_selenium_web_crawler.txt
Q: Last.FM cannot return more than 500 records when using pylast program I use pylast to get information from Last.fm API. When I use the code below: #!/usr/bin/env python import pylast API_KEY = "############################" API_SECRET = "##############################" ###### In order to perform a write operati...
Last.FM cannot return more than 500 records when using pylast program
I use pylast to get information from Last.fm API. When I use the code below: #!/usr/bin/env python import pylast API_KEY = "############################" API_SECRET = "##############################" ###### In order to perform a write operation you need to authenticate yourself username = "########" password_hash = ...
[ "It is a limitation of Last.fm.\n" ]
[ 4 ]
[]
[]
[ "last.fm", "python" ]
stackoverflow_0008572696_last.fm_python.txt
Q: See call stack while debugging in Pydev Is there a way to see the call stack while debugging python in Pydev? A: This is the "Debug" view of the "Debug" perspective : You can see that I was inside a failUnlessEqual method, called by test_01a, called by a new_method... A: To have the complete stacktrace you c...
See call stack while debugging in Pydev
Is there a way to see the call stack while debugging python in Pydev?
[ "This is the \"Debug\" view of the \"Debug\" perspective : \n\nYou can see that I was inside a failUnlessEqual method, called by test_01a, called by a new_method...\n", "To have the complete stacktrace you could add the following watch expression:\n[stackLine for stackLine in __import__(\"traceback\").format_stac...
[ 13, 1 ]
[]
[]
[ "callstack", "debugging", "pydev", "python" ]
stackoverflow_0008572680_callstack_debugging_pydev_python.txt
Q: How to get only the values from the file while parsing it? I am parsing a config file I would like to get only the values which are file paths in the file for example the config file has apache.access = /var/log/apache2/access.log apache.errors = /var/log/apache2/errors.log I would like to get only '/var/log/a...
How to get only the values from the file while parsing it?
I am parsing a config file I would like to get only the values which are file paths in the file for example the config file has apache.access = /var/log/apache2/access.log apache.errors = /var/log/apache2/errors.log I would like to get only '/var/log/apache2/access.log' and '/var/log/apache2/errors.log' from the C...
[ "First you have to define, what is a file path (1. does it have to exist? 2. does it have to be creatable in an existing directory? 3. anything else?). This tests whether the given string is a path pointing to an existing dir/file:\nimport os\n\n# ...\n\n[v for v in options.itervalues() if os.path.exists(v)]\n\n", ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008572984_python.txt
Q: How to create many-to-one relation with django and to display it in admin interface I have the following problem - I would like to create many-to-one mapping in django to represent what is basically relation between object and pieces of object like: class Website(models.Model): name = models.CharField(max_leng...
How to create many-to-one relation with django and to display it in admin interface
I have the following problem - I would like to create many-to-one mapping in django to represent what is basically relation between object and pieces of object like: class Website(models.Model): name = models.CharField(max_length = 100) class WebsiteIp(models.Model): website = models.ForeignKey(Website, primar...
[ "Add the related_name parameter to your ForeignKey on WebsiteIP like so:\nclass Website(models.Model):\n name = models.CharField(max_length = 100)\n\nclass WebsiteIp(models.Model):\n website = models.ForeignKey(Website, primary_key = True, related_name=\"IPs\")\n ip = models.CharField(max_length = 40)\n ...
[ 3, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0008546781_django_django_admin_django_models_python.txt
Q: Easy way to switch between renderers within the same view method I set up my function like this @view_config( route_name = 'route_name', permissions = 'permissions', renderer = 'r.mako' ) def r( request ): # stuff goes here now, I want to add functionality such that I check certain conditions (usi...
Easy way to switch between renderers within the same view method
I set up my function like this @view_config( route_name = 'route_name', permissions = 'permissions', renderer = 'r.mako' ) def r( request ): # stuff goes here now, I want to add functionality such that I check certain conditions (using ajax) i would use one template, otherwise use another. is there a ...
[ "Well you can add the view multiple times with different renderers if you can determine what you want to do via predicates. For example\n@view_config(route_name='route', xhr=True, renderer='json')\n@view_config(route_name='route', renderer='r.mako')\n@view_config(route_name='route', request_param='fmt=json', render...
[ 16 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008573149_pyramid_python.txt
Q: python - is there no better way to get the expression in a debug function in c code I frequently use printf debugging macros like #define DPRINT_INT(i) fprintf(stderr,"%s has the value %i at line %i", #i,i, __LINE__) and then i can do things like DPRINT_INT(height) where it will print the variable or things like ...
python - is there no better way to get the expression in a debug function
in c code I frequently use printf debugging macros like #define DPRINT_INT(i) fprintf(stderr,"%s has the value %i at line %i", #i,i, __LINE__) and then i can do things like DPRINT_INT(height) where it will print the variable or things like DPRINT_INT(from_cm_to_inch(get_average(heights))) and it will print out the who...
[ "In Python we tend to write modules that we can unittest and / or import into the REPL and drive them there if necessary. \nIf you can unit-test your functions, you can prove their behaviour for any given input. However, if you must write debug statements, you should use debug() from the standard logging module.\nF...
[ 2 ]
[]
[]
[ "abstract_syntax_tree", "debugging", "macros", "printf_debugging", "python" ]
stackoverflow_0008573023_abstract_syntax_tree_debugging_macros_printf_debugging_python.txt
Q: Is there a way to get a view of several lists/variables as a list like thing in python I have several variables like: class X(object): ... class XY(X): ... class XZ(X): ... class XA(X): ... y=XY() z=[XZ(i) for i in range(1,10)] a=[XA(i) for i in range(1,10)] I would like to have a listlike vie...
Is there a way to get a view of several lists/variables as a list like thing in python
I have several variables like: class X(object): ... class XY(X): ... class XZ(X): ... class XA(X): ... y=XY() z=[XZ(i) for i in range(1,10)] a=[XA(i) for i in range(1,10)] I would like to have a listlike view(including iteration and length) of the different variable y and the variables inside z and...
[ "If I understand correctly you want to \"chain\" the iterators of self.z and self.a and add self.y to that. Perhaps this does what you want:\nimport itertools\nitertools.chain(self.a, self.z, [self.y])\n\nThe cleanest would probably be to implement it like this:\nclass C(object):\n def __init__(self, y, z, a):\n...
[ 2, 0 ]
[]
[]
[ "abstraction", "python", "view" ]
stackoverflow_0008572847_abstraction_python_view.txt
Q: Python - online data collection I need to test application with testers around the world. I've written class for saving important data to the file. What is the easiest way to send this file (or simple coded string) from tester's pc to me (I suppose to some server, or a special mail?) without interrupting the teste...
Python - online data collection
I need to test application with testers around the world. I've written class for saving important data to the file. What is the easiest way to send this file (or simple coded string) from tester's pc to me (I suppose to some server, or a special mail?) without interrupting the tester in a Python?
[ "I think what you want is a Version Control System such as mercurial, git, etc\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008573807_python.txt
Q: How to call an AutoIt script in Python How can I call an AutoIt EXE file to Python code? I need add to code which were generated by a Selenium AutoIt script. A: If you want to just run the AutoIt script then use os.system or os.popen and take a look at the page Running Scripts. If you want to call AutoIt methods...
How to call an AutoIt script in Python
How can I call an AutoIt EXE file to Python code? I need add to code which were generated by a Selenium AutoIt script.
[ "If you want to just run the AutoIt script then use os.system or os.popen and take a look at the page Running Scripts. If you want to call AutoIt methods from your Python script then:\n\nRegister AutoItX3.dll in your system: regsvr32 AutoItX3.dll\nInstall PyWin32\nUse AutoIt from your code as follows:\nimport win32...
[ 5 ]
[]
[]
[ "autoit", "call", "python", "selenium" ]
stackoverflow_0008573464_autoit_call_python_selenium.txt
Q: python on script unload event (destructor) I am using file locking in python script (to control single instance of it execution). http://code.google.com/p/pylockfile/ I release lock in finally code block. But if script closed, for example, closing the terminal running it, the finally block doesn't execute and the...
python on script unload event (destructor)
I am using file locking in python script (to control single instance of it execution). http://code.google.com/p/pylockfile/ I release lock in finally code block. But if script closed, for example, closing the terminal running it, the finally block doesn't execute and the file stays locked. How to catch python script d...
[ "See this blog post regarding this subject. It uses the win32api when under Windows, while under Linux the SIGTERM signal is caught. To verify its working, it might be helpful to write something to a file in the on_exit handler like as done below. As the snippet is quite brief, I'll just include it (full props to t...
[ 2 ]
[]
[]
[ "destructor", "locking", "python" ]
stackoverflow_0008574119_destructor_locking_python.txt
Q: Calling Python from .NET in a loop is just too slow We've got a number of python libraries that need to be called from inside some loops in .NET that are just too slow. We're using Process.Start, which is taking about 1/3 of a second per call, which means that a few dialogs take 30 seconds to load (on an 8 core ma...
Calling Python from .NET in a loop is just too slow
We've got a number of python libraries that need to be called from inside some loops in .NET that are just too slow. We're using Process.Start, which is taking about 1/3 of a second per call, which means that a few dialogs take 30 seconds to load (on an 8 core machine - our customers will most likely have much slower c...
[ "You can rewrite your scripts to accept commands from the standard input instead and not exit when they're finished.\nThen start up a process (or a pool of them) and feed them commands, instead of starting new processes. For example instead of creating a new some_script.py args1, some_script.py args2, ... only spaw...
[ 3, 2, 1 ]
[]
[]
[ ".net", "performance", "python" ]
stackoverflow_0005682572_.net_performance_python.txt
Q: python try-finally Why does the exception in foo whizz by unnoticed, but the exception in bar is raised? def foo(): try: raise Exception('foo') finally: return def bar(): try: raise Exception('bar') finally: pass foo() bar() A: From the Python documentation: If ...
python try-finally
Why does the exception in foo whizz by unnoticed, but the exception in bar is raised? def foo(): try: raise Exception('foo') finally: return def bar(): try: raise Exception('bar') finally: pass foo() bar()
[ "From the Python documentation:\n\nIf the finally clause raises another exception or executes a return or break statement, the saved exception is lost.\n\n" ]
[ 35 ]
[]
[]
[ "exception", "finally", "python", "try_catch" ]
stackoverflow_0008574856_exception_finally_python_try_catch.txt
Q: Extract text between pattern using REGEX I need help with regex in python. I've got a large html file[around 400 lines] with the following pattern text here(div,span,img tags) <!-- 3GP||Link|| --> text here(div,span,img tags) So, now i am searching for a regex expression which can extract me this-: Link The g...
Extract text between pattern using REGEX
I need help with regex in python. I've got a large html file[around 400 lines] with the following pattern text here(div,span,img tags) <!-- 3GP||Link|| --> text here(div,span,img tags) So, now i am searching for a regex expression which can extract me this-: Link The given pattern is unique in the html file.
[ ">>> d = \"\"\"\n... Some text here(div,span,img tags)\n...\n... <!-- 3GP||**Some link**|| -->\n...\n... Some text here(div,span,img tags)\n... \"\"\"\n>>> import re\n>>> re.findall(r'\\<!-- 3GP\\|\\|([^|]+)\\|\\| --\\>',d)\n['**Some link**']\n\n\nr'' is a raw literal, it stops interpretation of standard string esc...
[ 4, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008574906_python_regex.txt
Q: Secure communication between servers I'm writing a simple control panel. It's going to be hosted on a single server, which communicates with other servers to do whatever it needs to. I need suggestions on how to do this securely, both from an authentication and an encryption standpoint. The only thing I've come up...
Secure communication between servers
I'm writing a simple control panel. It's going to be hosted on a single server, which communicates with other servers to do whatever it needs to. I need suggestions on how to do this securely, both from an authentication and an encryption standpoint. The only thing I've come up with so far is to use RSA keys to encrypt...
[ "Use SSH.\nSee also: What is the simplest way to SSH using Python?\n", "Stunnel is pretty handy. I like it since the code doesn't need to deal with encryption at all. \n", "You could use SSL with client/server certificate validation.\nValidate SSL certificates with Python\n", "We are developing Versile Python...
[ 3, 0, 0, 0 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0008572746_encryption_python.txt
Q: Efficient Longest arithmetic progression for a set of linear Points Longest arithmetic progression of a set of numbers {ab1,ab2,ab3 .... abn} is defined as a subset {bb1,bb2,bb3 .... bbn} such that bi+1 - bi is constant. I would like to extend this problems to a set of two dimensional points lying on a straight l...
Efficient Longest arithmetic progression for a set of linear Points
Longest arithmetic progression of a set of numbers {ab1,ab2,ab3 .... abn} is defined as a subset {bb1,bb2,bb3 .... bbn} such that bi+1 - bi is constant. I would like to extend this problems to a set of two dimensional points lying on a straight line. Lets define Dist(P1,P2) is the distance between two Points P1(X1,Y1)...
[ "You could study the Fast Fourier Transform methods for multiplication.O(N log N) \nYou might be able to do something similar with your problem.\n", "Firstly, your definition of distance is wrong. You have to take the square root. Secondly, if you know that all the points lie on a straight line, you can simply i...
[ 1, 1, 1 ]
[]
[]
[ "algorithm", "c++", "geometry", "math", "python" ]
stackoverflow_0008575225_algorithm_c++_geometry_math_python.txt
Q: Using crontab with django I need to create a function for sending newsletters everyday from crontab. I've found two ways of doing this on the internet : First - file placed in the django project folder: #! /usr/bin/env python import sys import os from django.core.management import setup_environ import settings se...
Using crontab with django
I need to create a function for sending newsletters everyday from crontab. I've found two ways of doing this on the internet : First - file placed in the django project folder: #! /usr/bin/env python import sys import os from django.core.management import setup_environ import settings setup_environ(settings) from dja...
[ "i would suggest creating your functionality as django-management-command and run it via crontab\nif your command is send_newsletter then simply\n0 0 * * * python /path/to/project/manage.py send_newsletter\n\nand you don't need to take care of setting the settings module in this case/\n", "Ashok's suggestion of r...
[ 38, 11, 3, 1, 1, 1, 0 ]
[]
[]
[ "cron", "crontab", "django", "python" ]
stackoverflow_0003200001_cron_crontab_django_python.txt
Q: How to pickle an object of a class B (having many variables) that inherits from A, that defines __setstate__ and __getstate__ My problem is: class A(object): def __init__(self): #init def __setstate__(self,state): #A __setstate__ code here def __getstate__(self): #A ...
How to pickle an object of a class B (having many variables) that inherits from A, that defines __setstate__ and __getstate__
My problem is: class A(object): def __init__(self): #init def __setstate__(self,state): #A __setstate__ code here def __getstate__(self): #A __getstate__ code here return state class B(A): def __init__(self): #creates many object variables here A is ...
[ "According to the documentation, when __getstate__ isn't defined, the instance's __dict__ is pickled so maybe, you can use this to define your own state methods as a combination of the A methods and the instance's __dict__:\nimport pickle\n\nclass A(object):\n def __init__(self):\n self.a = 'A state'\n\n ...
[ 4, 0 ]
[]
[]
[ "inheritance", "pickle", "python" ]
stackoverflow_0008574742_inheritance_pickle_python.txt
Q: Need help setting up Python Flask framework I've got a XAMPP apache server, Python 2.7 and I've installed setuptools and all the Flask requirements. Still I cannot run setup.py, which generates the following error: You need to specify DATABASE in settings.py, and ensure that Flask-SQLAlchemy is installed. Since ...
Need help setting up Python Flask framework
I've got a XAMPP apache server, Python 2.7 and I've installed setuptools and all the Flask requirements. Still I cannot run setup.py, which generates the following error: You need to specify DATABASE in settings.py, and ensure that Flask-SQLAlchemy is installed. Since I've installed Flask alchemy it must be my settin...
[ "Problem already solved.\nThe solution is to change the 'slash' in the database path: \nDATABASE = 'C:\\xampp\\htdocs\\maraschino\\maraschino.db'\n\nmust be:\nDATABASE = 'C:/xampp/htdocs/maraschino/maraschino.db'\n\nResult: \n\n'Database sucessfully initialised'\n\n" ]
[ 2 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0008561587_flask_python.txt
Q: Dynamic class based on database query in Python (Django) I'd like to do something like this in Django: class MyForm(forms.Form): items = Items.objects.all() for item in items: # How does this part work? exec(item.name) = forms.BooleanField() The goal is to create one form field for eac...
Dynamic class based on database query in Python (Django)
I'd like to do something like this in Django: class MyForm(forms.Form): items = Items.objects.all() for item in items: # How does this part work? exec(item.name) = forms.BooleanField() The goal is to create one form field for each item returned from the database query. So, if I get ten item...
[ "You can dynamically modify a form however you please:\nclass MyForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n for item in Item.objects.all():\n self.fields[item.name] = forms.BooleanField()\n\nI suppose the danger is if the...
[ 2, 0 ]
[]
[]
[ "django", "django_forms", "metaprogramming", "python" ]
stackoverflow_0008556844_django_django_forms_metaprogramming_python.txt
Q: How to mock a function defined in a module of a package? I've got a following structure: |-- dirBar | |-- __init__.py | |-- bar.py |-- foo.py `-- test.py bar.py def returnBar(): return 'Bar' foo.py from dirBar.bar import returnBar def printFoo(): print returnBar() test.py from mock import Mock fro...
How to mock a function defined in a module of a package?
I've got a following structure: |-- dirBar | |-- __init__.py | |-- bar.py |-- foo.py `-- test.py bar.py def returnBar(): return 'Bar' foo.py from dirBar.bar import returnBar def printFoo(): print returnBar() test.py from mock import Mock from foo import printFoo from dirBar import bar bar.returnBar = ...
[ "I'm guessing you are going to mock the function returnBar, you'd like to use patch decorator:\nfrom mock import patch\n\nfrom foo import printFoo\n\n@patch('foo.returnBar')\ndef test_printFoo(mockBar):\n mockBar.return_value = 'Foo'\n printFoo()\n\ntest_printFoo()\n\n", "Just import the bar module before t...
[ 44, 32 ]
[ "Another way to deal with those case is to use some dependency injection. \nAn easy way to do it in python is to use the magical **kwargs : \nfoo.py\nfrom dirBar.bar import returnBar\n\ndef printFoo(**kwargs):\n real_returnBar = kwargs.get(\"returnBar\", returnBar)\n print real_returnBar()\n\ntest.py\nfrom mo...
[ -3 ]
[ "mocking", "python" ]
stackoverflow_0008575713_mocking_python.txt
Q: Django/Python - Collect the data to the right form (Algorithm) I have the models like this: Item: name desc AttrGroup: name order AttrName: name group.ForeinKey(AttrGroup) order AttrVal: value attr.ForeinKey(AttrName) item.ForeinKey(Item) So I want to compare the attrib...
Django/Python - Collect the data to the right form (Algorithm)
I have the models like this: Item: name desc AttrGroup: name order AttrName: name group.ForeinKey(AttrGroup) order AttrVal: value attr.ForeinKey(AttrName) item.ForeinKey(Item) So I want to compare the attributes of n items in the list items_id=[1,3,7,...] In views, I do some...
[ "In your view function you can can find the AttrName and AttrGroup for each AttrValue in the attrs query set. You create the relevant groups in the view function. Then you display the details in your template.\ngroups = defaultdict( list )\nfor a in attrs:\n groups[a.attr.group.order, a.attr.group.name].append...
[ 1, 0 ]
[]
[]
[ "algorithm", "django", "django_templates", "python", "sorting" ]
stackoverflow_0005832143_algorithm_django_django_templates_python_sorting.txt
Q: how to open up a child process to tail the files present in a config file using python on a mac machine? I am trying to tail the files in a config file using python on mac I am able to get the values from the config file but not able to open up child processes for the same a sample config file has [section1] ho...
how to open up a child process to tail the files present in a config file using python on a mac machine?
I am trying to tail the files in a config file using python on mac I am able to get the values from the config file but not able to open up child processes for the same a sample config file has [section1] host_prefix = true timestamp_prefix = true [section2] host = localhost port = 1463 pids = /var/run/harvester [fi...
[ "Try ConfigParser. It can work with INI files.\n", "\nuse os.path.exists to check if a file exists\nuse ConfigParser to parse an ini-type config file\n\n" ]
[ 1, 1 ]
[]
[]
[ "macos", "python", "terminal" ]
stackoverflow_0008576241_macos_python_terminal.txt
Q: Python: Make new tuple by attaching info from existing list I have 2 lists: l = [1,2,3,4,5,6,7] f = [[3,'Red'],[2,'Blue']] I want to do with l based on f so the result will be something like: result = ((1,'Red'), (2,'Red'), (3,'Red'), (4,'Blue'), (5,'Blue'), (6,'None'), (7,'None')) Could you give me some code to...
Python: Make new tuple by attaching info from existing list
I have 2 lists: l = [1,2,3,4,5,6,7] f = [[3,'Red'],[2,'Blue']] I want to do with l based on f so the result will be something like: result = ((1,'Red'), (2,'Red'), (3,'Red'), (4,'Blue'), (5,'Blue'), (6,'None'), (7,'None')) Could you give me some code to do this simple and easy? Thanks for any help!
[ "result = tuple(itertools.izip_longest(l, (x[1] for x in f for y in range(x[0])), fillvalue='None'))\n\n" ]
[ 9 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008576975_algorithm_python.txt
Q: tilde char on IDLE 3.2.2 MacOS-X Lion Impossible to get tilde char ~ on Python IDLE 3.2.2 MacOS-X Lion. I tried the prefs/Keys, no success, no entry "Option-N space". Please help ! A: I often have the same problem as well - my IDLE crashes immediately when I am trying to use Option-N. If you want to use it in a ...
tilde char on IDLE 3.2.2 MacOS-X Lion
Impossible to get tilde char ~ on Python IDLE 3.2.2 MacOS-X Lion. I tried the prefs/Keys, no success, no entry "Option-N space". Please help !
[ "I often have the same problem as well - my IDLE crashes immediately when I am trying to use Option-N.\nIf you want to use it in a string, you can replace it using\n\"\\x007E\"\n\ninstead of\n\"~\"\n\nUnfortunately, if you want to use it in your code, for example as a bitwise NOT operation, this is not possible eit...
[ 2 ]
[]
[]
[ "python", "python_3.x", "python_idle", "tkinter" ]
stackoverflow_0008576181_python_python_3.x_python_idle_tkinter.txt
Q: how to get around UnboundLocalError? I just started programming and tried to write something but (of course) it failed. After I while I got to the real problem: The UnboundLocalError. So to save you from all the rubble around I stripped the code down to this: def test(): try: i1 = int(i1) i2 = ...
how to get around UnboundLocalError?
I just started programming and tried to write something but (of course) it failed. After I while I got to the real problem: The UnboundLocalError. So to save you from all the rubble around I stripped the code down to this: def test(): try: i1 = int(i1) i2 = int(i2) except ValueError: pri...
[ "The most standard way to do this is to give parameters to your test method :\ndef test(i1, i2):\n try:\n i1 = int(i1)\n i2 = int(i2)\n except ValueError:\n print \"you failed in typing a number\"\n\ndef input(): \n i1 = raw_input('please type a number \\n >')\n i2 = raw_input('plea...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008573254_python.txt
Q: How can I create a tmp file in Python? I have this function that references the path of a file: some_obj.file_name(FILE_PATH) where FILE_PATH is a string of the path of a file, i.e. H:/path/FILE_NAME.ext I want to create a file FILE_NAME.ext inside my python script with the content of a string: some_string = 'thi...
How can I create a tmp file in Python?
I have this function that references the path of a file: some_obj.file_name(FILE_PATH) where FILE_PATH is a string of the path of a file, i.e. H:/path/FILE_NAME.ext I want to create a file FILE_NAME.ext inside my python script with the content of a string: some_string = 'this is some content' How to go about this? Th...
[ "I think you're looking for a tempfile.NamedTemporaryFile.\nimport tempfile\nwith tempfile.NamedTemporaryFile() as tmp:\n print(tmp.name)\n tmp.write(...)\n\nBut:\n\nWhether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so...
[ 224, 97 ]
[]
[]
[ "python" ]
stackoverflow_0008577137_python.txt
Q: How to get started with Python SCTP stack (pysctp)? I've just installed pysctp from http://www.epx.com.br/pysctp/, and I'm having trouble getting the basic example working. What could I be doing wrong? I'm on Red Hat Linux. Python 2.7.2 (default, Oct 25 2011, 10:11:43) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on l...
How to get started with Python SCTP stack (pysctp)?
I've just installed pysctp from http://www.epx.com.br/pysctp/, and I'm having trouble getting the basic example working. What could I be doing wrong? I'm on Red Hat Linux. Python 2.7.2 (default, Oct 25 2011, 10:11:43) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" fo...
[ "Someone broke the ABI (added a few more fields to struct sctp_event_subscribe and the kernel wants userspace to want the new amount). Here's a kludge, proper fix would be for the kernel to accept old apps that have been compiled against headers with a smaller struct_event_subscribe and just not give them the new ...
[ 2, 1, 1 ]
[]
[]
[ "linux", "python", "sctp" ]
stackoverflow_0008522192_linux_python_sctp.txt
Q: On click button, data from panel two field should be copied to panel one field? I am a beginner in python language and I am trying to make a simple gui for my program using wxpython. My gui consists of a frame and two tabs (using wxPanel) on it (tab 1 and tab 2). I placed txtctrl widgets on both tab 1 and tab 2. O...
On click button, data from panel two field should be copied to panel one field?
I am a beginner in python language and I am trying to make a simple gui for my program using wxpython. My gui consists of a frame and two tabs (using wxPanel) on it (tab 1 and tab 2). I placed txtctrl widgets on both tab 1 and tab 2. On tab 1 , I placed a button which gets all txtctrl values and assigns them to corresp...
[ "You are creating PageTwo twice, when you have already created it in MainFrame \nnb = wxNotebook(panel1)\npage1 = PageOne(nb)\npage2 = PageTwo(nb)\n\nnb.AddPage(page1, \"Tab 1\")\nnb.AddPage(page2, \"Tab 2\")\n\nyou don't need to recreate it in PageOne, so remove this\nself.PTWO=PageTwo(self)\nself.PTWO.Show()\n\nI...
[ 0, 0 ]
[]
[]
[ "panels", "python", "wxpython" ]
stackoverflow_0008568694_panels_python_wxpython.txt
Q: How to only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges? I have Directed Graph in networkx. I want to only keep those nodes which have two or more than two outgoing edges or no outgoing edge at all. How do I do this? or How do I removes nodes which have exactly one outgoing edge in a n...
How to only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges?
I have Directed Graph in networkx. I want to only keep those nodes which have two or more than two outgoing edges or no outgoing edge at all. How do I do this? or How do I removes nodes which have exactly one outgoing edge in a networkx graph.
[ "You can find the nodes in graph G with one outgoing edge using the out_degree method:\noutdeg = G.out_degree()\nto_remove = [n for n in outdeg if outdeg[n] == 1]\n\nRemoving is then:\nG.remove_nodes_from(to_remove)\n\nIf you prefer to create a new graph instead of modifying the existing graph in place, create a su...
[ 26 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0008576737_networkx_python.txt
Q: python dynamic class names Trying to instantiate a class based on a string value and... failing. The parser object below is a dict, in the example let's say we have one called foo and here parser['name'] is 'foo': obj = parser['name']() Fails, yielding TypeError: 'str' object is not callable. But, since I have: c...
python dynamic class names
Trying to instantiate a class based on a string value and... failing. The parser object below is a dict, in the example let's say we have one called foo and here parser['name'] is 'foo': obj = parser['name']() Fails, yielding TypeError: 'str' object is not callable. But, since I have: class foo: def __init__(self(...
[ "classmap = {\n 'foo': foo\n}\n\nobj = classmap[parser['name']]()\n\n", "As answered in:\nPython dynamic class names \nThere is an easier way to do this if you know which module the classes are defined in, for example:\ngetattr(my_module, my_class_name)()\n\n", "Don't use strings:\nparser = {}\n\nclass foo:\n ...
[ 15, 14, 7, 5, 4, 2 ]
[ "In response to your update: The only way to do this is with a mapping system. If you don't want to use an explicit mapping system, then you can use one of Python's built-in mapping systems, though it's much less nice and explicit in my opinion.\nobj = globals()[parser['name']]() \n\nwill access the global object o...
[ -1, -4 ]
[ "python" ]
stackoverflow_0004513192_python.txt
Q: Open a child process to tail each file in config file? I am using config parser to parse a config file I need to tail each file in the files section in a separate terminal I am using python on mac the code I wrote gets me all the things in the files section I need only the paths and need to tail each one of them i...
Open a child process to tail each file in config file?
I am using config parser to parse a config file I need to tail each file in the files section in a separate terminal I am using python on mac the code I wrote gets me all the things in the files section I need only the paths and need to tail each one of them in a separate child process import ConfigParser import o...
[ "Since tail is accepting multiple files, you can rely on it:\nfrom ConfigParser import ConfigParser\nfrom subprocess import Popen\n\nconfig = ConfigParser()\nconfig.read('/etc/harvest.conf')\nfilenames = [value for name, value in config.items('files')]\n\nprocess = Popen(['tail', '-f'] + filenames)\nprocess.communi...
[ 1 ]
[]
[]
[ "macos", "python", "terminal" ]
stackoverflow_0008576699_macos_python_terminal.txt
Q: Why do these two implementations of expmod differ for large values? I've written out a couple of functions for doing expmod, that is, (x ** y) % n. These are both standard functions, I've checked and re-checked both but can't find any silly errors. Here's the recursive one: def expmod(x,y,m): if y == 0: return...
Why do these two implementations of expmod differ for large values?
I've written out a couple of functions for doing expmod, that is, (x ** y) % n. These are both standard functions, I've checked and re-checked both but can't find any silly errors. Here's the recursive one: def expmod(x,y,m): if y == 0: return 1 if y % 2 == 0: return square(expmod(x,y/2,m)) % m # def sq...
[ "Your function non_recursive_expmod has some suspicious steps in it: Remove the %m for x and y at the beginning. Both are not needed.\nAdditionally make sure that the division of y is an integer division by using y = y // 2.\nIn total the function should look like this:\ndef non_recursive_expmod(x, y, m):\n resu...
[ 2, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008577459_algorithm_python.txt
Q: Some Regex stuff I'm just starting to figure out regex and would love some help trying to understand it. I've been using this to help me get started, but am still having some trouble figuring it out. What I am trying to do is take this text: <td>8.54/10 over 190 reviews</td> And pull out the "8.54", so basically ...
Some Regex stuff
I'm just starting to figure out regex and would love some help trying to understand it. I've been using this to help me get started, but am still having some trouble figuring it out. What I am trying to do is take this text: <td>8.54/10 over 190 reviews</td> And pull out the "8.54", so basically anything in between th...
[ "Use quantifiers.\nYou want one or more digits, followed by a dot, followed by one or more digits. A digit can also be written \\d, and the \"one or more\" quantifier is +.\nThe dot needs to be escaped as it is a regex metacharacter which means \"any character\". Your regex therefore should be:\n\\d+\\.\\d+\n\nNow,...
[ 8, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008577564_python_regex.txt
Q: comparing tuples in python I have the following piece of code: while current is not problem.getStartState(): print "Current: ", current, "Start: ", problem.getStartState() now for some reason the comparison is not working well, you can see in the following output: Current: (3, 5, 0, 0, 0, 0) Start: (4,...
comparing tuples in python
I have the following piece of code: while current is not problem.getStartState(): print "Current: ", current, "Start: ", problem.getStartState() now for some reason the comparison is not working well, you can see in the following output: Current: (3, 5, 0, 0, 0, 0) Start: (4, 5, 0, 0, 0, 0) Current: (4, 5,...
[ "is tests for identity, not equality. You want current != problem.getStartState()\nThere is an idiom is (not) None which works because None is guaranteed to be a singleton. Don't use it for other types unless you really mean it!\n", "while current != problem.getStartState():\n\n print \"Current: \", current, \...
[ 5, 2 ]
[ "is is not the correct check to be used in this case.\nTo compare 2 tuples just use != or ==\nfor instance the problem can be solved as follows:\nwhile current != problem.getStartState(): \n print \"Current: \", current, \"Start: \", problem.getStartState()\n\ncheers,\n" ]
[ -1 ]
[ "comparison", "pacman", "python", "tuples" ]
stackoverflow_0008577702_comparison_pacman_python_tuples.txt
Q: Where are the external Pinax (Starter) Projects? I've just installed Pinax, and wanted to try some of the external starter projects (as opposed to the four basic ones provided with Pinax). Their documentation links to this page, but instead of showing a list of external projects, it just links back to that same pa...
Where are the external Pinax (Starter) Projects?
I've just installed Pinax, and wanted to try some of the external starter projects (as opposed to the four basic ones provided with Pinax). Their documentation links to this page, but instead of showing a list of external projects, it just links back to that same page. So my question is, until they fix their documenta...
[ "We're in the process of rewriting them for the fresh-started Pinax 0.9a2. As we do that, they'll appear at http://pinaxproject.com/ecosystem/starter_projects/ but no external ones have been upgraded yet. You can find the old ones on the master-old branch of https://github.com/pinax/pinax though.\n", "You can fin...
[ 2, 0 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0008575522_django_pinax_python.txt
Q: Why do I get an error when running mysqld in a virtualenv? When I run mysqld in my virtualenv I get an error and abort message. (nettuts)sez@sez-laptop:~/.virtualenvs$ mysqld 111220 15:22:59 [Warning] Can't create test file /var/lib/mysql/sez-laptop.lower-test 111220 15:22:59 [Warning] Can't create test file /var/...
Why do I get an error when running mysqld in a virtualenv?
When I run mysqld in my virtualenv I get an error and abort message. (nettuts)sez@sez-laptop:~/.virtualenvs$ mysqld 111220 15:22:59 [Warning] Can't create test file /var/lib/mysql/sez-laptop.lower-test 111220 15:22:59 [Warning] Can't create test file /var/lib/mysql/sez-laptop.lower-test mysqld: Can't change dir to '/va...
[ "It doesn't have anything to do with Python and virtualenv. Your mysqld isn't configured to properly run under a normal user's privileges - it needs to be invoked using your distributions normal service startup mechanism (for instance sudo invoke-rc.d mysql start on Ubuntu).\n", "you need root priviledges:\ntry w...
[ 1, 0 ]
[]
[]
[ "mysql", "mysql_python", "python", "virtualenv", "virtualenvwrapper" ]
stackoverflow_0008577055_mysql_mysql_python_python_virtualenv_virtualenvwrapper.txt
Q: How to make inner functions see variables of enclosing function? Possible Duplicate: Read/Write Python Closures In the following function, the internal function does not modify the argument but just modifies the copy. def func(): i = 3 def inc(i): i = i + 3 print i inc(i) inc(i) print i func() ...
How to make inner functions see variables of enclosing function?
Possible Duplicate: Read/Write Python Closures In the following function, the internal function does not modify the argument but just modifies the copy. def func(): i = 3 def inc(i): i = i + 3 print i inc(i) inc(i) print i func() Is it possible to avoid repeated code and put that inside a function...
[ "In python 3 you'd do this:\ndef func():\n i = 3\n def inc():\n nonlocal i\n i = i+3\n print(i)\n inc()\n inc()\n print(i)\n\nfunc()\n\nIn python 2.x using global doesn't work because the variable is in an outer scope, but it's not global. Hence, you'll need to pass the variable as an argument.\nThis is...
[ 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008577893_python.txt
Q: Daemonizing python's BaseHTTPServer I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, b...
Daemonizing python's BaseHTTPServer
I am working on a daemon where I need to embed a HTTP server. I am attempting to do it with BaseHTTPServer, which when I run it in the foreground, it works fine, but when I try and fork the daemon into the background, it stops working. My main application continues to work, but BaseHTTPServer does not. I believe thi...
[ "After a bit of googling I finally stumbled over this BaseHTTPServer documentation and after that I ended up with:\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nfrom SocketServer import ThreadingMixIn\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n \"\"\"Handle requests in a separate t...
[ 8, 4, 2, 1, 0, 0 ]
[]
[]
[ "basehttpserver", "daemon", "python" ]
stackoverflow_0000888834_basehttpserver_daemon_python.txt
Q: Running in 32-bit mode permanently I'm not sure if this is possible but I want to force my mac to run in 32-bit mode permanently. Currently I've been using this piece of code: arch -i386 /usr/bin/python to change it but once I exit python in the terminal it switches back to 64. The reason I want to do this is so I...
Running in 32-bit mode permanently
I'm not sure if this is possible but I want to force my mac to run in 32-bit mode permanently. Currently I've been using this piece of code: arch -i386 /usr/bin/python to change it but once I exit python in the terminal it switches back to 64. The reason I want to do this is so I can install pygame. I've already instal...
[ "For the built in python, you can set the VERSIONER_PYTHON_PREFER_32_BIT environment variable to 1. For non-built-in Python, you can just install 32-bit instead of 64-bit.\nSee this question: How do I force Python to be 32-bit on Snow Leopard and other 32-bit/64-bit questions\n", "With the default python install ...
[ 1, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0008283370_macos_python.txt
Q: Django newbie trying to get treeio to work behind apache I seem to have similar problem as this guy: Django newbie deployment question - ImportError: Could not import settings 'settings' but i cant make heads or tails of it. The server is running Debian. The app runs fine on internal server, however when trying to...
Django newbie trying to get treeio to work behind apache
I seem to have similar problem as this guy: Django newbie deployment question - ImportError: Could not import settings 'settings' but i cant make heads or tails of it. The server is running Debian. The app runs fine on internal server, however when trying to use apache + mod_python i get the following problem. File "...
[ "Your main problem is that you're using mod-python, despite clear warnings that it's deprecated and shouldn't be used for new projects.\nBut if you really insist on using it, the problem is quite clear: you're adding /var/www/trio to the path, so everything in trio needs to be referenced directly - settings, not tr...
[ 2 ]
[]
[]
[ "apache", "django", "mod_python", "python" ]
stackoverflow_0008578188_apache_django_mod_python_python.txt
Q: Python callback working with functions but not methods I have a third-party Python library that allows me to register a callback function that it called later. While the code works okay with functions, when I tried to pass a method it fails, the callback is never called. I have no control over the third party libr...
Python callback working with functions but not methods
I have a third-party Python library that allows me to register a callback function that it called later. While the code works okay with functions, when I tried to pass a method it fails, the callback is never called. I have no control over the third party library (source code not available).   def old_callbackFunction(...
[ "Sorin actually figured this out himself, with help from my comment, but he indicated that he wanted me to post the original comment as an answer. I was reluctant to post this originally because I'm unsure of the precise behavior of the setCallback and callbackFunction code; use at your own risk and modify as reaso...
[ 1 ]
[]
[]
[ "callback", "python" ]
stackoverflow_0008563080_callback_python.txt
Q: wxPython inherit font How to avoid writing for each label: static_text.SetFont(wx.Font(...)) static_text.SetForegroundColour(wx.Colour(...)) and instead inherit the font from parent element or something? A: If you change the font of the parent container you get that font for all the widgets on it. For example c...
wxPython inherit font
How to avoid writing for each label: static_text.SetFont(wx.Font(...)) static_text.SetForegroundColour(wx.Colour(...)) and instead inherit the font from parent element or something?
[ "If you change the font of the parent container you get that font for all the widgets on it. For example changing the font for the Frame instance, font gets changed in the static text and the checkbox without the need to set them separately:\n\nAfaik if you want to modify existing code you can not access to write t...
[ 2, 1 ]
[]
[]
[ "fonts", "python", "wxpython" ]
stackoverflow_0008576138_fonts_python_wxpython.txt
Q: Python using self as an argument I have two classes, one which handles the GUI = GUI(), and one that handles the Client connection to my server = Client(). So, my error report would be: TypeError: change_state() takes exactly 2 arguments (1 given) when having a self argument within change_state() in GUI(), and ca...
Python using self as an argument
I have two classes, one which handles the GUI = GUI(), and one that handles the Client connection to my server = Client(). So, my error report would be: TypeError: change_state() takes exactly 2 arguments (1 given) when having a self argument within change_state() in GUI(), and calling GUI.change_state('NORMAL') from ...
[ "Your question is rather vague, but as far as I can tell you are calling the change_state class method on the GUI class. This won't work, you should instantiate a GUI object, and then call the change_state method on that:\ngui = GUI()\ngui.change_state('NORMAL')\n\n", "you call the change_state function as it wer...
[ 2, 0 ]
[]
[]
[ "arguments", "class", "python", "self" ]
stackoverflow_0008578896_arguments_class_python_self.txt
Q: how to run python script from shell I have a noob question. I got a python script path1/path2/file.py The script has a function: def run (datetime = None): In the shell I call import path1.path2.file import datetime path1.path2.file.run(datetime = datetime(2011,12,1)) but I am getting TypeError: 'module' object...
how to run python script from shell
I have a noob question. I got a python script path1/path2/file.py The script has a function: def run (datetime = None): In the shell I call import path1.path2.file import datetime path1.path2.file.run(datetime = datetime(2011,12,1)) but I am getting TypeError: 'module' object is not callable whats the correct way to...
[ "The problem is actually in the datetime module.\nYou are trying to call the module itself.\nThe function you want to call is itself called datetime.\nso what you want to call is:\ndatetime.datetime()\n\nOR you can import the function with:\nfrom datetime import datetime\n\nand then call it with:\ndatetime()\n\n", ...
[ 4, 1, 0, 0 ]
[ "you can import a folder doing\nimport path1\n\nand then call simply the script doing:\npath1.path2.file.run(...)\n\notherwhise if you do not want to include all the other stuff within the directory you can try with \nfrom path1.path2.file import run\n\nin this case you have only to call:\nrun()\n\nCheers,\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0008577430_python.txt
Q: How to Transpose Dictionary Names from one module into Dictionary Keys in another module? I have a set of values belonging to users that will be parameters to a given function. There are multiple groups I'll be comparing and each has their own set of assumptions - about 80% of the time they will be common variable...
How to Transpose Dictionary Names from one module into Dictionary Keys in another module?
I have a set of values belonging to users that will be parameters to a given function. There are multiple groups I'll be comparing and each has their own set of assumptions - about 80% of the time they will be common variables (though not the values themselves). I'll be adding a new variable more frequently than a new ...
[ "I think defaultdict from the collections module is what you are looking for.\nHere is an example\nfrom collections import defaultdict\n\n# you must use `lambda` here as using just `None` will result with\n# KeyError on undefined keys\nfund_dict = defaultdict(lambda: None, {'assume01':15, 'assume03':2})\nprint fund...
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "import", "python", "transpose" ]
stackoverflow_0008571966_dictionary_import_python_transpose.txt
Q: Web service call in Python (Twisted + ZSI) not working in chroot jail I have a Python script that calls a web service using ZSI with Twisted. On Linux, I'm running this script and it works fine. Now, I want this script to run in a chroot jail which is somewhere in my filesystem. I have added the usr, lib and the e...
Web service call in Python (Twisted + ZSI) not working in chroot jail
I have a Python script that calls a web service using ZSI with Twisted. On Linux, I'm running this script and it works fine. Now, I want this script to run in a chroot jail which is somewhere in my filesystem. I have added the usr, lib and the etc directories in the jail. When I execute the script from the jail, there ...
[ "If your application is raising an unexpected exception at some point - eg, because some dependency fails to import, because it is not installed in the chroot - then this can cause connections to be unexpectedly closed. It's hard to say with any precision, since you haven't mentioned what kind of connections you h...
[ 0 ]
[]
[]
[ "chroot", "linux", "python", "twisted", "web_services" ]
stackoverflow_0008578664_chroot_linux_python_twisted_web_services.txt
Q: PyQt give color to a specific element This might be an easy question, but I'm trying to give a color to a specific QLabel in my application and it doesn't work. The code I tried is the following : nom_plan_label = QtGui.QLabel() nom_plan_label.setText(nom_plan_vignette) nom_plan_label.setStyleSheet("QLabel#nom_pla...
PyQt give color to a specific element
This might be an easy question, but I'm trying to give a color to a specific QLabel in my application and it doesn't work. The code I tried is the following : nom_plan_label = QtGui.QLabel() nom_plan_label.setText(nom_plan_vignette) nom_plan_label.setStyleSheet("QLabel#nom_plan_label {color: yellow}") Any hint would b...
[ "There are a few things wrong with the stylesheet syntax you are using.\nFirstly, ID selectors (i.e. #nom_plan_label) must refer to the objectName of the widget.\nSecondly, it is only necessary to use selectors when a stylesheet is applied to an ancestor widget and you want certain style rules to cascade down to pa...
[ 33 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qlabel", "qtstylesheets" ]
stackoverflow_0008577610_pyqt_pyqt4_python_qlabel_qtstylesheets.txt
Q: Why is sleep() in the time-module and not in threading-module? Why is the sleep method (for sleeping a thread for some time) stored in the time-module and not in the threading-module (like in java). I mean, is it not much more related to thread? A: Sleep method in time module is derived from *nix sleep function ...
Why is sleep() in the time-module and not in threading-module?
Why is the sleep method (for sleeping a thread for some time) stored in the time-module and not in the threading-module (like in java). I mean, is it not much more related to thread?
[ "Sleep method in time module is derived from *nix sleep function (in unistd.h). It's not more thread related, it's a general function for stopping the execution of the program (or script)\n", "time.sleep pauses the execution of the program/script. As a thread can also be regarded as a second program that can inte...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008572636_python.txt
Q: select sub item in a tuple list in python Here I have one list like this: a = [[13245,0.123],[12435,0.435],[12345,0.799],[98775,0.573]...] I want to use the first item in every tuple as x axis, and the second item in every tuple as y axis to plot a figure. like x = [13245,12435,12345,68775] y = [0.123,0.435,0.799,...
select sub item in a tuple list in python
Here I have one list like this: a = [[13245,0.123],[12435,0.435],[12345,0.799],[98775,0.573]...] I want to use the first item in every tuple as x axis, and the second item in every tuple as y axis to plot a figure. like x = [13245,12435,12345,68775] y = [0.123,0.435,0.799,0.573] How can I select them out?
[ "Simplest is probably to use zip:\nx, y = zip(*a)\n\n", "Try this:\nx = [tmplist[0] for tmplist in a]\ny = [tmplist[1] for tmplist in a]\n\nAlso, [] doesn't define tuples, but lists. But in your case the handling is equal.\n", "use:\nx = []\ny = []\nfor e in a:\n x.append(e[0])\n y.append(e[1])\n\nedit: I...
[ 6, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008578561_python.txt
Q: cx_oracle OSX install error So I followed these directions here to install Oracle InstantClient, installing Oracle Instantclient on Mac OS/X without setting environment variables? But when I try to install cx_oracle I get the following stack trace, python setup.py build running build running build_ext building 'c...
cx_oracle OSX install error
So I followed these directions here to install Oracle InstantClient, installing Oracle Instantclient on Mac OS/X without setting environment variables? But when I try to install cx_oracle I get the following stack trace, python setup.py build running build running build_ext building 'cx_Oracle' extension creating buil...
[ "You have not got a clntsh library to link against\nTo fix this you need in /usr/lib to link libclntsh.dylib.10.1 to libclntsh.dylib and libocci.dylib.10.1 to libocci.dylib\nNote that I don't have the oracle library and so cannot confirm this will be sufficient.\n" ]
[ 13 ]
[]
[]
[ "cx_oracle", "instantclient", "macos", "oracle", "python" ]
stackoverflow_0008579715_cx_oracle_instantclient_macos_oracle_python.txt
Q: Redirect Print to statusbar Is it possible to redirect text to status bar. Here I want to display a print to status bar. It should look like this but it doesn't work: import sys import wx class RedirectText: def __init__(self, statusbar): self.statusbar = statusbar def write(self,string): ...
Redirect Print to statusbar
Is it possible to redirect text to status bar. Here I want to display a print to status bar. It should look like this but it doesn't work: import sys import wx class RedirectText: def __init__(self, statusbar): self.statusbar = statusbar def write(self,string): self.statusbar.SetStatusText(stri...
[ "This might be a bit unexpected, but the write function you defined will get called twice in your current code: first it will receive the \"hello\" string, then a newline. Because the newline isn't visible in your statusbar, it looks like nothing was updated.\nAn easy fix is to check the contents of string in your ...
[ 3, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008575548_python_wxpython.txt
Q: is it possible sending data via NIC directly instead of via routing table lookup (linux command or python) Suppose I have 3 NIC in one host PC, name them eth0, eth1 and eth2 All interface have it's own ip address in different subnet, however, all the gateway router of those NIC have route to one server I want to a...
is it possible sending data via NIC directly instead of via routing table lookup (linux command or python)
Suppose I have 3 NIC in one host PC, name them eth0, eth1 and eth2 All interface have it's own ip address in different subnet, however, all the gateway router of those NIC have route to one server I want to access, I want to establish 3 connetions to that server and get response via different NIC. I setting static rout...
[ "The problem is that routing is determined by the destination and just because you have multiple routes available, doesn't mean that the OS will in fact use those multiple routes. What you want is the OS to take into account the source address when determining which outbound route to use. Once you get the routing...
[ 0 ]
[]
[]
[ "iptables", "linux", "python", "sockets" ]
stackoverflow_0008530286_iptables_linux_python_sockets.txt
Q: Storing and Accessing U.S. State Attributes in Python / Flask Question: How best* can I store and access fixed U.S. State attributes in my python program? * the most reasonable combination of clear, maintainable, quick and idiomatic Background info: I'm creating a python/flask app that regularly accesses U.S. Stat...
Storing and Accessing U.S. State Attributes in Python / Flask
Question: How best* can I store and access fixed U.S. State attributes in my python program? * the most reasonable combination of clear, maintainable, quick and idiomatic Background info: I'm creating a python/flask app that regularly accesses U.S. State attributes for various displays and sorting. An example of the at...
[ "You might want to take a look at this config module. It would allow you to define all of your state attributes in one place and would be more simple and efficient than accessing them through a database. \n", "I ended up using a database to solve this problem. I considered a bunch of options and it seems to be th...
[ 0, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0008542650_flask_python.txt
Q: reference counts in a Python C extension I'm writing my first C extension to Python and am confused about my reference counts. Here's what I'm trying to do. I populate a dict in a for loop: mydict = PyDict_New(); for (...) { pair = PyTuple_Pack(2, PyString_FromString("some string"), PyString_FromSt...
reference counts in a Python C extension
I'm writing my first C extension to Python and am confused about my reference counts. Here's what I'm trying to do. I populate a dict in a for loop: mydict = PyDict_New(); for (...) { pair = PyTuple_Pack(2, PyString_FromString("some string"), PyString_FromString("some other string")); /* at this po...
[ "If you look at the CPython source code (Objects/tupleobject.c) for PyTuple_Pack, you will see that it indeed does increment the reference count on each packed object. If you instead do a PyTuple_New followed by PyTuple_SetItem calls, you will not need to decrement the reference counts since SetItem steals the ref...
[ 6 ]
[]
[]
[ "c", "python" ]
stackoverflow_0008528483_c_python.txt
Q: How to get dropped file names in PyQt/PySide I am trying to set up an application that will accept havin files dropped into it. So, I am looking for a way to extract the path when they are dropped in. Right now, I have drag and drop enabled for the right part of the application, and it will accept text dropped in...
How to get dropped file names in PyQt/PySide
I am trying to set up an application that will accept havin files dropped into it. So, I am looking for a way to extract the path when they are dropped in. Right now, I have drag and drop enabled for the right part of the application, and it will accept text dropped in, but I do not know how to handle having a file dr...
[ "The QMimeData class has methods for dealing with dropped urls. Below is a minimal working example:\n# from PyQt4.QtGui import QApplication, QLabel\n# from PySide2.QtWidgets import QApplication, QLabel\nfrom PyQt5.QtWidgets import QApplication, QLabel\n\nclass Window(QLabel):\n def __init__(self):\n super...
[ 19 ]
[]
[]
[ "drag_and_drop", "events", "pyqt", "pyside", "python" ]
stackoverflow_0008568500_drag_and_drop_events_pyqt_pyside_python.txt
Q: Set up basic Twisted Reactor I am very new to using Twisted. I have set up a protocol in a .py and it works perfectly. The thing is that currently to test it I have to ssh into my server and run it. I would like to have it running as a service/server so it is always serving my protocol. I read on the twisted site ...
Set up basic Twisted Reactor
I am very new to using Twisted. I have set up a protocol in a .py and it works perfectly. The thing is that currently to test it I have to ssh into my server and run it. I would like to have it running as a service/server so it is always serving my protocol. I read on the twisted site something about .tac files but I'm...
[ "Daemonization in twisted is achieved via the twistd shell command. I found this tutorial quite useful: Using the Twisted Application Framework\n" ]
[ 2 ]
[]
[]
[ "python", "reactor", "twisted" ]
stackoverflow_0008570403_python_reactor_twisted.txt
Q: python multiprocessing pass dict from child process back to parent I have a subprocess function (called parseContents) that gets called using the following code: def main(): p = Process(target=parseContents, args=(event.name,)) p.start() p.join() Utilizing the multiprocessing module and the Queue method,...
python multiprocessing pass dict from child process back to parent
I have a subprocess function (called parseContents) that gets called using the following code: def main(): p = Process(target=parseContents, args=(event.name,)) p.start() p.join() Utilizing the multiprocessing module and the Queue method, how would I go about passing a variable from parseContents back to main...
[ "To use a Queue in this way you have to instantiate it in main() and pass it to parseContents as an argument. Once you do that you should be able to use the code you have (in the correct places) to pass the item from the child process to the parent process.\nThe Python docs warn that you should not attempt to join ...
[ 1 ]
[]
[]
[ "multiprocessing", "python", "queue", "variables" ]
stackoverflow_0008580883_multiprocessing_python_queue_variables.txt
Q: wxpython: centering text within a panel within a sizer It seems to me that the following code should display text right in the centre of the window; that is, in the centre of the inner panel. It doesn't however, and I'm wondering why not. If you run the code, you'll see a white panel in the middle of the frame, 15...
wxpython: centering text within a panel within a sizer
It seems to me that the following code should display text right in the centre of the window; that is, in the centre of the inner panel. It doesn't however, and I'm wondering why not. If you run the code, you'll see a white panel in the middle of the frame, 150px by 150px. I do not want this area to change in size at a...
[ "You just need to add a couple spacers to make it work.\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, id, title):\n wx.Frame.__init__(self, parent, id, title)\n\n self.rootPanel = wx.Panel(self)\n\n innerPanel = wx.Panel(self.rootPanel,-1, size=(150,150), style=wx.ALIGN...
[ 8 ]
[]
[]
[ "center", "panel", "python", "sizer", "wxpython" ]
stackoverflow_0008580831_center_panel_python_sizer_wxpython.txt
Q: Puppet like syntax for python Anyone know of any good ways to do puppet like pp files for python. Almost like config files that can inherit other configs files and also have limited logic in them like if statements and variables? Thanks! A: Kokki is an interesting project which attempts to be Chef / Puppet but f...
Puppet like syntax for python
Anyone know of any good ways to do puppet like pp files for python. Almost like config files that can inherit other configs files and also have limited logic in them like if statements and variables? Thanks!
[ "Kokki is an interesting project which attempts to be Chef / Puppet but for Python. It looks a little immature to use in production, but if you're looking for a Python-based configuration management system and don't want to use something more well established (and heavy-handed) like Bcfg2, I'd go with Kokki.\n", ...
[ 5, 3, 1 ]
[]
[]
[ "puppet", "python" ]
stackoverflow_0005366136_puppet_python.txt
Q: Python subprocess call with arguments having multiple quotations I use the following command in bash to execute a Python script. python myfile.py -c "'USA'" -g "'CA'" -0 "'2011-10-13'" -1 "'2011-10-27'" I'm writing a Python script to wrap around this one. I'm currently having to use os.system (I know, it's crapp...
Python subprocess call with arguments having multiple quotations
I use the following command in bash to execute a Python script. python myfile.py -c "'USA'" -g "'CA'" -0 "'2011-10-13'" -1 "'2011-10-27'" I'm writing a Python script to wrap around this one. I'm currently having to use os.system (I know, it's crappy) since I can't figure out how to get the quotes to work with subproc...
[ "You don't need to escape the values. To the process everything is passed as a string.\nYou can use the shlex module to figure out what is the best way to pass variables:\nimport shlex\nshlex.split('python myfile.py -c \"USA\" -g \"CA\" -0 \"2011-10-13\" -1 \"2011-10-27\"') \n['python',\n 'myfile.py',\n '-c',\n 'US...
[ 8, 4, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0008581140_python_subprocess.txt
Q: Can a Python script identify itself in memory at runtime? I am looking for methods other than file locking to make sure that only one instance of a Python script is being run at the same time. Is there a way to identify a currently running script in memory? Perhaps by setting a flag of some kind that other instan...
Can a Python script identify itself in memory at runtime?
I am looking for methods other than file locking to make sure that only one instance of a Python script is being run at the same time. Is there a way to identify a currently running script in memory? Perhaps by setting a flag of some kind that other instances can read so they can exit?
[ "If you are running on Linux, /dev/shm is a tmpfs partition on most distros.\nThis means that any files stored there only exist in memory and are not written to disk.\n", "If you are running on Windows, use a Mutex. You can use ctypes to call the Win32 APIs: CreateMutex, WaitForSingleObject, and ReleaseMutex.\n"...
[ 2, 0 ]
[]
[]
[ "locking", "python", "singleton" ]
stackoverflow_0008578284_locking_python_singleton.txt
Q: can't intercept PyDict_New with LD_PRELOAD I'm trying to use LD_PRELOAD to intercept the PyDict_New function. I've verified that this recipe workd with getpid in the python interpreter, and I've adapted it to use PyDict_New instead, but it simply doesn't work as I expect. Although I'm clearly allocating dictionari...
can't intercept PyDict_New with LD_PRELOAD
I'm trying to use LD_PRELOAD to intercept the PyDict_New function. I've verified that this recipe workd with getpid in the python interpreter, and I've adapted it to use PyDict_New instead, but it simply doesn't work as I expect. Although I'm clearly allocating dictionaries, and this function must be used, my override ...
[ "LD_PRELOAD can only overload functions that are themselves loaded dynamically. If you're using the python binary, PyDict_New is not dynamically loaded and therefore there's no way for the dynamic loader to intercept the resolution of that symbol. If you instead create your own \"python\" by compiling your own bi...
[ 3, 1 ]
[]
[]
[ "c", "dlsym", "ld_preload", "python" ]
stackoverflow_0008549671_c_dlsym_ld_preload_python.txt
Q: Python/wxPython: auinotebook get all pages I have an auinotebook, is there anyway to get a list of all pages in the notebook? When the user selects an action from a list, a new page is added to the notebook. If they select that action again, then the page should not be added again (instead, that page will be sel...
Python/wxPython: auinotebook get all pages
I have an auinotebook, is there anyway to get a list of all pages in the notebook? When the user selects an action from a list, a new page is added to the notebook. If they select that action again, then the page should not be added again (instead, that page will be selected for them). I can't see to figure out how ...
[ "Assuming you are using wx.lib.agw.aui.AuiNotebook:\nimport wx.lib.agw.aui as aui\n\nclass MyNotebook(aui.AuiNotebook):\n def __getitem__(self, index):\n ''' More pythonic way to get a specific page, also useful for iterating\n over all pages, e.g: for page in notebook: ... '''\n if inde...
[ 4, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008580656_python_wxpython.txt
Q: "Iterate" a function's return values Suppose I have a function which consults some external stateful service and returns a value from it, for simplicity let's assume the value is an integer: i = 10 def foo(): global i i -= 1 return i It's clear that I can call this function 9 times before it returns a...
"Iterate" a function's return values
Suppose I have a function which consults some external stateful service and returns a value from it, for simplicity let's assume the value is an integer: i = 10 def foo(): global i i -= 1 return i It's clear that I can call this function 9 times before it returns a falsy value (the 10th call will return 0 ...
[ "This can actually be done using the built-in iter(), if you provide two arguments instead of one then the first is expected to be a function that will be called repeatedly until the return value of the function reaches the sentinel value:\nfor x in iter(foo, 0):\n print x\n\nHere is what the itertools solution ...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0008581804_python.txt