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:
Converting specific time format with strptime
I'm trying to convert
[16/Jan/2010:18:11:06 +0100] (common log format)
to a timestamp. How can I use strptime to convert this?
time zone can be different from +0100
A:
import time
log = '16/Jan/2010:18:11:06 +0100'
dt = time.strptime(log, '%d/%b/%Y:%H:%M:%S +0100')... | Converting specific time format with strptime | I'm trying to convert
[16/Jan/2010:18:11:06 +0100] (common log format)
to a timestamp. How can I use strptime to convert this?
time zone can be different from +0100
| [
"import time\nlog = '16/Jan/2010:18:11:06 +0100'\ndt = time.strptime(log, '%d/%b/%Y:%H:%M:%S +0100')\n\nReference: http://docs.python.org/library/time.html#time.strptime\nPython's timezone support is problematic and platform dependant.\nSee this post (see also its first part). \n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003452188_python.txt |
Q:
How to detect HTTP Request in python + twisted?
I am learning network programming using twisted 10 in python. In below code is there any way to detect HTTP Request when data recieved? also retrieve Domain name, Sub Domain, Port values from this? Discard it if its not http data?
from twisted.internet import stdio,... | How to detect HTTP Request in python + twisted? | I am learning network programming using twisted 10 in python. In below code is there any way to detect HTTP Request when data recieved? also retrieve Domain name, Sub Domain, Port values from this? Discard it if its not http data?
from twisted.internet import stdio, reactor, protocol
from twisted.protocols import bas... | [
"protocol.dataReceived, which you're overriding, is too low-level to serve for the purpose without smart buffering that you're not doing -- per the docs I just quoted,\n\nCalled whenever data is received.\nUse this method to translate to a\n higher-level message. Usually, some\n callback will be made upon the rec... | [
3,
1
] | [] | [] | [
"http",
"packet",
"python",
"twisted"
] | stackoverflow_0003430689_http_packet_python_twisted.txt |
Q:
Running CGI outside of cgi-bin. Good idea?
I'm considering moving from PHP to Python (for personal projects), and I really don't like seeing /cgi-bin/ in my URL.
I got the Python to execute outside of cgi-bin, but I just wanted to make sure there were no possible security issues that could pop up, and that there w... | Running CGI outside of cgi-bin. Good idea? | I'm considering moving from PHP to Python (for personal projects), and I really don't like seeing /cgi-bin/ in my URL.
I got the Python to execute outside of cgi-bin, but I just wanted to make sure there were no possible security issues that could pop up, and that there were no major impacts on the speed.
So are there ... | [
"Being as how it's nominally just a URL, there aren't any impacts on speed per-se. However, it is standard practice, just like it's standard practice to make the entry page to a website index.html, but it's not required by any stretch (as evidenced by default.aspx, home.php, etc)\nI would change it as a security th... | [
1
] | [] | [] | [
"cgi",
"cgi_bin",
"python"
] | stackoverflow_0003452388_cgi_cgi_bin_python.txt |
Q:
twisted: Failure vs. Error
When should I use a twisted.python.failure.Failure, and when should I use something like twisted.internet.error.ConnectionDone? Or should I do twisted.python.failure.Failure(twisted.internet.error.ConnectionDone), and if so, in what casese should I do that?
A:
A Failure represents an e... | twisted: Failure vs. Error | When should I use a twisted.python.failure.Failure, and when should I use something like twisted.internet.error.ConnectionDone? Or should I do twisted.python.failure.Failure(twisted.internet.error.ConnectionDone), and if so, in what casese should I do that?
| [
"A Failure represents an exception and a traceback (often different from the current stack trace). You should use Failure when you are constructing an asynchronous exception. So, when you're going to fire a Deferred with an error, or when you're going to call a method like IProtocol.connectionLost or ClientFactor... | [
10
] | [] | [] | [
"exception",
"exception_handling",
"python",
"twisted"
] | stackoverflow_0003452022_exception_exception_handling_python_twisted.txt |
Q:
wxPython: How do I find out which widget has the focus?
How do I find out which widget in my wx.Frame has the focus?
A:
You should be able to use the Window class's static FindFocus() method to return the object that has focus.
api: http://www.wxpython.org/docs/api/wx.Window-class.html#FindFocus
examples: http:/... | wxPython: How do I find out which widget has the focus? | How do I find out which widget in my wx.Frame has the focus?
| [
"You should be able to use the Window class's static FindFocus() method to return the object that has focus.\napi: http://www.wxpython.org/docs/api/wx.Window-class.html#FindFocus\nexamples: http://nullege.com/codes/search/wx.Window.FindFocus/all/page:2\n"
] | [
10
] | [] | [] | [
"focus",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003452489_focus_python_wxpython_wxwidgets.txt |
Q:
Big picture questions regarding Django, Java, Python, HTML and web-site development in general
I am trying to get a handle on the state of the art regarding web site development and have several questions. Maybe I'll end up finding most of the answers on my own. I come from a background of C++ and Windows develop... | Big picture questions regarding Django, Java, Python, HTML and web-site development in general | I am trying to get a handle on the state of the art regarding web site development and have several questions. Maybe I'll end up finding most of the answers on my own. I come from a background of C++ and Windows development, and generally I am befuddled by what seems to be the ad-hoc nature of web development.
I focus... | [
"Hmm, you've asked a laundry list of questions here. I'll pick a couple of the important ones and answer.\nAs for the rationale for languages like Python... the truth is that many web applications are either I/O bound or database bound. When that's the case it doesn't matter much if the language you're using is not... | [
12,
10,
7,
2,
1,
1,
1,
1
] | [] | [] | [
"django",
"html",
"java",
"mobile",
"python"
] | stackoverflow_0003345916_django_html_java_mobile_python.txt |
Q:
Custom class instance copying
I'm new to programming and Python. The problem I have is with removing list elements that are instances of custom class.
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
z.remove(zcopy[0])
This retu... | Custom class instance copying | I'm new to programming and Python. The problem I have is with removing list elements that are instances of custom class.
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
z.remove(zcopy[0])
This returns:
ValueError: list.remove(x): x ... | [
"No, because the call to deepcopy creates a copy of the some_class instance. That copy, zcopy[0] is a different object from the original, z[0], so when you try to remove zcopy[0] from the list z, it rightly complains that the copy doesn't exist in the original list. Furthermore, there is no link between the copied ... | [
1
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0003452691_deep_copy_python.txt |
Q:
Can Cherokee serve a fallback/default page when a reverse proxy is unavailable?
I have a Cherokee installation that I'm using to serve a few web applications - one blog/calendar/etc. and two CPU-intensive web applications (1 stable version and 1 development version). All of them are Django or Pylons webservices se... | Can Cherokee serve a fallback/default page when a reverse proxy is unavailable? | I have a Cherokee installation that I'm using to serve a few web applications - one blog/calendar/etc. and two CPU-intensive web applications (1 stable version and 1 development version). All of them are Django or Pylons webservices served with CherryPy. I'm using the reverse-proxy handler in Cherokee to handle the ma... | [
"You could set a custom 504 error page.\n"
] | [
0
] | [] | [] | [
"cherokee",
"python",
"reverse_proxy",
"web_services"
] | stackoverflow_0003449673_cherokee_python_reverse_proxy_web_services.txt |
Q:
Boost Python (Suse and Ubuntu)
I created a simple .so library containing definition of a C++ class which should be accessed from Python and used for this purpose boost python library.
When I'm testing this library using x64 Ubuntu it is enough to set LD_LIBRARY_PATH with the path to boost libs before running pytho... | Boost Python (Suse and Ubuntu) | I created a simple .so library containing definition of a C++ class which should be accessed from Python and used for this purpose boost python library.
When I'm testing this library using x64 Ubuntu it is enough to set LD_LIBRARY_PATH with the path to boost libs before running python. It doesn't work, however, when I'... | [
"You should never set LD_LIBRARY_PATH, see here and here.\nFirst of all I have to assume that you installed the Boost libraries in a nonstandard location, otherwise the loader would find them automatically. If you have root access to the machine, install the libraries in a standard place (e.g. with the package mana... | [
0
] | [] | [] | [
"boost",
"c++",
"python",
"suse",
"ubuntu"
] | stackoverflow_0003452505_boost_c++_python_suse_ubuntu.txt |
Q:
Respond to Listctrl change exactly once
I'm working on a form using wxPython where I want want listctrl's list of values to change based on the selection of another listctrl. To do this, I'm using methods linked to the controlling object's EVT_LIST_ITEM_SELECTED and EVT_LIST_ITEM_DESELECTED events to call Publish... | Respond to Listctrl change exactly once | I'm working on a form using wxPython where I want want listctrl's list of values to change based on the selection of another listctrl. To do this, I'm using methods linked to the controlling object's EVT_LIST_ITEM_SELECTED and EVT_LIST_ITEM_DESELECTED events to call Publisher.sendMessage. The control to be changed ha... | [
"The best solution seems to be to use wx.CallAfter with a flag to execute the follow-up procedure exactly once:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwds):\n wx.Frame.__init__(self, *args, **kwds)\n self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKE... | [
4,
0,
0
] | [] | [] | [
"listctrl",
"python",
"wxpython"
] | stackoverflow_0003441991_listctrl_python_wxpython.txt |
Q:
How to customize wx.ProgressDialog?
Is it possible to customize ProgressDialog in wxPython?
For instance, I would like to make the progressbar slimmer, and the window size wider.
SetSize() method doesn't appear to have any effect.
A:
The wx.ProgressDialog isn't customizable its just a wrapper around the native P... | How to customize wx.ProgressDialog? | Is it possible to customize ProgressDialog in wxPython?
For instance, I would like to make the progressbar slimmer, and the window size wider.
SetSize() method doesn't appear to have any effect.
| [
"The wx.ProgressDialog isn't customizable its just a wrapper around the native ProgressDialog, the the easiest solution would be to roll your own by extending the wx.Dialog class and using a wx.Gauge\n"
] | [
1
] | [] | [] | [
"progress_bar",
"python",
"wxpython"
] | stackoverflow_0003452986_progress_bar_python_wxpython.txt |
Q:
Apply raw string to function return value
I'm not sure if I've phrased it correctly, but hopefully the example will clear it up:
re.search(fileMask.replace('*','.*?'),fileName):
For the first parameter in the re.search() call, how can I ensure that I will pass the value returned by the fileMask.replace() call as ... | Apply raw string to function return value | I'm not sure if I've phrased it correctly, but hopefully the example will clear it up:
re.search(fileMask.replace('*','.*?'),fileName):
For the first parameter in the re.search() call, how can I ensure that I will pass the value returned by the fileMask.replace() call as a raw string?
Something to the effect of:
re.se... | [
"There is no such type as \"a raw string\" -- there are literals (of string types) that are so named, but the objects such literals stand for are string objects -- nothing more, nothing less. For example, literals r'a\\b'' (a \"raw string literal\") and 'a\\\\b' (a normal string literal) represent exactly the same... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003452925_python.txt |
Q:
Rename config.ini section using ConfigParser in python
Is there an easy way to rename a section in a config file using ConfigParser in python? I'd prefer not to have to delete the section and recreate it, but that is my only answer right now.
A:
No. The builtin ConfigParser stores sections as _sections, which is... | Rename config.ini section using ConfigParser in python | Is there an easy way to rename a section in a config file using ConfigParser in python? I'd prefer not to have to delete the section and recreate it, but that is my only answer right now.
| [
"No. The builtin ConfigParser stores sections as _sections, which is a dict. Since this is python you could access that variable to do an easy copy. \n(config._sections[new_name] = config._sections[old_name]; config._sections.pop(old_name) \nBut ConfigParser may change at some later date and this would break your i... | [
0
] | [] | [] | [
"config",
"configparser",
"python"
] | stackoverflow_0003452788_config_configparser_python.txt |
Q:
BeautifulSoup doesn't give me Unicode
I'm using Beautiful soup to scrape data. The BS documentation states that BS should always return Unicode but I can't seem to get Unicode. Here's a code snippet
import urllib2
from libs.BeautifulSoup import BeautifulSoup
# Fetch and parse the data
url = 'http://wiki.gnhlug.or... | BeautifulSoup doesn't give me Unicode | I'm using Beautiful soup to scrape data. The BS documentation states that BS should always return Unicode but I can't seem to get Unicode. Here's a code snippet
import urllib2
from libs.BeautifulSoup import BeautifulSoup
# Fetch and parse the data
url = 'http://wiki.gnhlug.org/twiki2/bin/view/Www/PastEvents2007?skin=p... | [
"As you may have noticed renderContent returns (by default) a string encoded in UTF-8, but if you really want a Unicode string representing the entire document you can also do unicode(soup) or decode the output of renderContents/prettify using unicode(soup.prettify(), \"utf-8\").\nRelated\n\nHow to render contents ... | [
5,
2
] | [] | [] | [
"beautifulsoup",
"character_encoding",
"python",
"unicode"
] | stackoverflow_0003192645_beautifulsoup_character_encoding_python_unicode.txt |
Q:
How to dynamically create directories and output files into them python
I have a python script that is trying to create a directory tree dynamically depending on the user input. This is what my code looks like so far.
if make_directories:
os.makedirs(outer_dir)
os.chdir(outer_dir)
for car in cars:
... | How to dynamically create directories and output files into them python | I have a python script that is trying to create a directory tree dynamically depending on the user input. This is what my code looks like so far.
if make_directories:
os.makedirs(outer_dir)
os.chdir(outer_dir)
for car in cars:
os.makedirs(car)
os.chdir(car)
#create a bunch of text files a... | [
"I tend to do path manipulations rather than changing directories; just because the current directory is a bit of \"implied state\" whereas the paths can be explicity rooted. \nif make_directories:\n for car in cars:\n carpath = os.path.join(outer_dir, car)\n os.makedirs(carpath)\n for fn in... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003453329_python.txt |
Q:
TimeUUID with Cassandra and Lazyboy
I try to insert column with UUID1 keys to be able to sort them by date. I always get the error "cassandra.ttypes.InvalidRequestException: InvalidRequestException(why='UUIDs must be exactly 16 bytes')", and I don't know why.
Here is the code generating this error :
from lazyboy i... | TimeUUID with Cassandra and Lazyboy | I try to insert column with UUID1 keys to be able to sort them by date. I always get the error "cassandra.ttypes.InvalidRequestException: InvalidRequestException(why='UUIDs must be exactly 16 bytes')", and I don't know why.
Here is the code generating this error :
from lazyboy import *
from lazyboy.key import Key
impor... | [
"The column name must be of uuid version 1. Looks like your key is a uuid version 1\n"
] | [
1
] | [] | [] | [
"cassandra",
"python",
"uuid"
] | stackoverflow_0003450560_cassandra_python_uuid.txt |
Q:
Communicating multiple times with a subprocess
I'm trying to pipe input to a program opened as a subprocess in Python. Using communicate() does what I want, but it only does so once, then waits for the subprocess to terminate before allowing things to continue.
Is there a method or module similar to communicate()... | Communicating multiple times with a subprocess | I'm trying to pipe input to a program opened as a subprocess in Python. Using communicate() does what I want, but it only does so once, then waits for the subprocess to terminate before allowing things to continue.
Is there a method or module similar to communicate() in function, but allows multiple communications wit... | [
"You can write to p.stdin (and flush every time to make sure the data is actually sent) as many separate times as you want. The problem would be only if you wanted to be sure to get results back (since it's so hard to convince other processes to not buffer their output!-), but since you're not even setting stdout=... | [
7
] | [] | [] | [
"communication",
"python",
"subprocess"
] | stackoverflow_0003453345_communication_python_subprocess.txt |
Q:
How to programmatically add bindings to the current class scope in Python?
Though the question is very specific, I'd also really appreciate general advice and other approaches that would make my question moot. I'm building a collection of AI programs, and many of the functions and classes need to deal with a lot o... | How to programmatically add bindings to the current class scope in Python? | Though the question is very specific, I'd also really appreciate general advice and other approaches that would make my question moot. I'm building a collection of AI programs, and many of the functions and classes need to deal with a lot of different states and actions that cause transitions between states, so I need ... | [
"You could use meta classes so that you would end up with code like:\nclass DerivedAgent(Agent):\n __states__ = ['StateA', 'StateB', ...]\n\nfor example:\nclass AgentMeta(type):\n def __new__(meta, classname, bases, classdict):\n for clsname in classdict['__states__']:\n classdict[clsname] =... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003453058_python.txt |
Q:
Getting current url
I have a couple of views which are rendering the same template and I have some {% url %} tags into that template which needs to point to different location based on the current view. Is there any context variable which gives the name of the view(for named urls), like view-1 view-2, so in my tem... | Getting current url | I have a couple of views which are rendering the same template and I have some {% url %} tags into that template which needs to point to different location based on the current view. Is there any context variable which gives the name of the view(for named urls), like view-1 view-2, so in my template I can use it like t... | [
"Pass RequestContext to the template renderer and write yourself a context processor to reconstruct the url from the request.\nhttp://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext\n",
"I don't think there is any direct way in django to see which view rendered current template... | [
2,
1,
1,
0
] | [] | [] | [
"dispatcher",
"django",
"python",
"url"
] | stackoverflow_0003450903_dispatcher_django_python_url.txt |
Q:
Are Python 2.5 .pyc files compatible with Python 2.6 .pyc files?
A while ago I had to upgrade some servers from Python 2.4 to Python 2.5. I found that .pyc files created under Python 2.4 would crash when Python 2.5 tried to run them.
Will this happen again when I upgrade from 2.5 to 2.6?
EDIT: Here is a bit more d... | Are Python 2.5 .pyc files compatible with Python 2.6 .pyc files? | A while ago I had to upgrade some servers from Python 2.4 to Python 2.5. I found that .pyc files created under Python 2.4 would crash when Python 2.5 tried to run them.
Will this happen again when I upgrade from 2.5 to 2.6?
EDIT: Here is a bit more detail
I have a fileserver that contains the python code. This is acces... | [
"In general, .pyc files are specific to one Python version (although portable across different machine architectures, as long as they're running the same version); the files carry the information about the relevant Python version in their headers -- so, if you leave the corresponding .py files next to the .pyc ones... | [
17,
6,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002263356_python.txt |
Q:
Convert 12hr date/time string to 24hr datetime
Like other questions asked here, im looking to do a simple conversion of time formats. I've found answers on how to do this in Perl, but not in Python.
I have a string like so:
on Jun 03, 02010 at 10:22PM
and I'd like to convert it to a datetime object like this:
Th... | Convert 12hr date/time string to 24hr datetime | Like other questions asked here, im looking to do a simple conversion of time formats. I've found answers on how to do this in Perl, but not in Python.
I have a string like so:
on Jun 03, 02010 at 10:22PM
and I'd like to convert it to a datetime object like this:
Thu, 03 Jun 2010 22:22:00 -0000
I have sliced up my i... | [
"Using dateutil:\nimport datetime as dt\nimport dateutil.parser as dparser\n\ndate_str='on Jun 03, 02010 at 10:22PM'\ndate=dparser.parse(date_str)\nprint(date)\n# 2010-06-03 22:22:00\nprint(date.strftime('%a, %d %b %Y %H:%M:%S'))\n# Thu, 03 Jun 2010 22:22:00\n\nIf you can somehow strip out the pesky 'on' and change... | [
4,
3,
1
] | [] | [] | [
"datetime",
"python",
"time"
] | stackoverflow_0003453702_datetime_python_time.txt |
Q:
Infinity Loop and user input as the termination
I have my code and it does go run to infinity. What I want is that if on the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and then come out of the loop. So I want it to break, but I want it to finish the current... | Infinity Loop and user input as the termination | I have my code and it does go run to infinity. What I want is that if on the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and then come out of the loop. So I want it to break, but I want it to finish the current loop. Is using ctrl C ok? Should I look to a differe... | [
"To do this correctly and exactly as you want it is a bit complicated.\nBasically you want to trap the Ctrl-C, setup a flag, and continue until the start of the loop (or the end) where you check that flag. This can be done using the signal module. Fortunately, somebody has already done that and you can use the code... | [
3
] | [] | [] | [
"copy_paste",
"infinity",
"loops",
"python",
"signals"
] | stackoverflow_0003453757_copy_paste_infinity_loops_python_signals.txt |
Q:
twisted: catch keyboardinterrupt and shutdown properly
UPDATE: For ease of reading, here is how to add a callback before the reactor gets shutdown:
reactor.addSystemEventTrigger('before', 'shutdown', callable)
Original question follows.
If I have a client connected to a server, and it's chilling in the reactor m... | twisted: catch keyboardinterrupt and shutdown properly | UPDATE: For ease of reading, here is how to add a callback before the reactor gets shutdown:
reactor.addSystemEventTrigger('before', 'shutdown', callable)
Original question follows.
If I have a client connected to a server, and it's chilling in the reactor main loop waiting for events, when I hit CTRL-C, I get a "Con... | [
"If you really, really want to catch C-c specifically, then you can do this in the usual way for a Python application - use signal.signal to install a handler for SIGINT that does whatever you want to do. If you invoke any Twisted APIs from the handler, make sure you use reactor.callFromThread since almost all oth... | [
31,
2
] | [] | [] | [
"python",
"shutdown",
"twisted"
] | stackoverflow_0003453451_python_shutdown_twisted.txt |
Q:
How to get files from directories in Python
I have a list of directories (their absolute path). Each directory contains a certain number of files. Of these files I want to get two of them from each directory. The two files I want have some string pattern in their name, for the sake of this example the strings will... | How to get files from directories in Python | I have a list of directories (their absolute path). Each directory contains a certain number of files. Of these files I want to get two of them from each directory. The two files I want have some string pattern in their name, for the sake of this example the strings will be 'stringA', 'stringB'.
So what I need is a li... | [
"See if this works for you:\nimport glob\nresult = zip(sorted(glob.glob('/dir/*stringA*')), sorted(glob.glob('/dir/*stringB*')))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003454121_python.txt |
Q:
Implementing separate incrementing primary keys in Django
I am developing an internal app on the side for the company I work for, and am wanting to use Django in order to learn it and Python in general, however I've hit a bit of a snag with the PKs.
I'm trying to emulate a part of the current application where 2 M... | Implementing separate incrementing primary keys in Django | I am developing an internal app on the side for the company I work for, and am wanting to use Django in order to learn it and Python in general, however I've hit a bit of a snag with the PKs.
I'm trying to emulate a part of the current application where 2 MySQL tables, TaskCategory and Tasks, handle the tasks that need... | [
"What is your goal here?\nIf you're trying to maintain field-to-field table compatibility with the older application, you're going to have problems because (as you've observed) Django does not do compound/composite keys -- it really prefers a surrogate key. Given the operations that Django permits, and current thi... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003453897_django_python.txt |
Q:
How to get two python processes talking over pipes?
I'm having troubles getting this to work. Basically I have a python program that expect some data in stdin, that is reading it as sys.stdin.readlines() I have tested this and it is working without problems with things like echo "" | myprogram.py
I have a second p... | How to get two python processes talking over pipes? | I'm having troubles getting this to work. Basically I have a python program that expect some data in stdin, that is reading it as sys.stdin.readlines() I have tested this and it is working without problems with things like echo "" | myprogram.py
I have a second program that using the subprocess module calls on the firs... | [
"You want to redirect the subprocess's stdin, so you need stdin=subprocess.PIPE.\nYou should not need to write Control-D ('\\4') to the file object. Control-D tells the shell to close the standard input that's connected to the program. The program doesn't see a Control-D character in that context.\n"
] | [
2
] | [] | [] | [
"python",
"shell",
"subprocess"
] | stackoverflow_0003454427_python_shell_subprocess.txt |
Q:
Is there a way to format a variety of currencies on Python?
I've got a Python web server (mod_python, if that makes any difference) that I want to start formatting some currency. I've got two pieces of information when I format the currency - the value (as a number) and the currency (as the three-letter ISO 4217 ... | Is there a way to format a variety of currencies on Python? | I've got a Python web server (mod_python, if that makes any difference) that I want to start formatting some currency. I've got two pieces of information when I format the currency - the value (as a number) and the currency (as the three-letter ISO 4217 code). I can also retrieve the country (or even city) that the c... | [
"For my internationalization needs, I almost invariably turn to ICU, a truly awesome package in both breadth and depth -- usually via pyIcu, although in the past I've had to do some wrapping of my own when pyIcu hadn't yet wrapped some corner of ICU I needed (I'm not sure if they're currently wrapping all the curre... | [
2,
1
] | [] | [] | [
"currency",
"formatting",
"python"
] | stackoverflow_0003454074_currency_formatting_python.txt |
Q:
How to efficiently parse emails without touching attachments using Python
I'm playing with Python imaplib (Python 2.6) to fetch emails from GMail. Everything I fetch an email with method http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch I get whole email. I need only text part and also parse names of... | How to efficiently parse emails without touching attachments using Python | I'm playing with Python imaplib (Python 2.6) to fetch emails from GMail. Everything I fetch an email with method http://docs.python.org/library/imaplib.html#imaplib.IMAP4.fetch I get whole email. I need only text part and also parse names of attachments, without downloading them. How this can be done? I see that emails... | [
"Take a look at this recipe: http://code.activestate.com/recipes/498189/\nI adapted it slightly to print the From, Subject, Date, name of attachments, and message body (just plaintext for now -- its trivial to add html messages).\nI used the Gmail pop3 server in this case, but it should work for IMAP as well.\nimpo... | [
5,
2,
0
] | [] | [] | [
"gmail",
"imap",
"imaplib",
"parsing",
"python"
] | stackoverflow_0002301213_gmail_imap_imaplib_parsing_python.txt |
Q:
How does Python stack up to other scripting languages?
I'm learning Python (and it's my first programming language so don't be too intense with your reasons) and I wanted to know how it stacks up to other scripting languages, like Perl and Ruby. What is Python better in comparison to other scripting languages, and... | How does Python stack up to other scripting languages? | I'm learning Python (and it's my first programming language so don't be too intense with your reasons) and I wanted to know how it stacks up to other scripting languages, like Perl and Ruby. What is Python better in comparison to other scripting languages, and what is it worse for?
| [
"First off, an advice - look for POSITIVE things said from opposite sides. Meaning, you should trust positive things said about Perl by Python-related sources (or positive things said about Python by Perl related sources) much more than the opposite. \nThe two reasons are that:\n1) People who have reason to like Py... | [
10,
6,
2
] | [] | [] | [
"comparison",
"perl",
"python",
"ruby"
] | stackoverflow_0003452729_comparison_perl_python_ruby.txt |
Q:
conditionally setting and conditionally using a variable python
I know it is bad convention/design to conditionally declare a variable. i.e.:
if some_boolean:
x = 1
where x is not declared anywhere else. But is it bad to conditionally declare a variable if you only use it later on if that condition is met?
if... | conditionally setting and conditionally using a variable python | I know it is bad convention/design to conditionally declare a variable. i.e.:
if some_boolean:
x = 1
where x is not declared anywhere else. But is it bad to conditionally declare a variable if you only use it later on if that condition is met?
if some_boolean and some_other_boolean:
x+=1
| [
"It's dubious style, as it's prone to bugs based on imperfect, impartial understanding on some future maintainer's part. I also think that initially setting variables to None (unless more useful values are known for them) is helpful to readability, in part because it gives you one, natural place to document all of... | [
2,
1,
0
] | [] | [] | [
"convention",
"python"
] | stackoverflow_0003454501_convention_python.txt |
Q:
Django: automatically import MEDIA_URL in context
like exposed here, one can set a MEDIA_URL in settings.py (for example i'm pointing to Amazon S3) and serve the files in the view via {{ MEDIA_URL }}. Since MEDIA_URL is not automatically in the context, one have to manually add it to the context, so, for example, ... | Django: automatically import MEDIA_URL in context | like exposed here, one can set a MEDIA_URL in settings.py (for example i'm pointing to Amazon S3) and serve the files in the view via {{ MEDIA_URL }}. Since MEDIA_URL is not automatically in the context, one have to manually add it to the context, so, for example, the following works:
#views.py
from django.shortcuts i... | [
"There is a generic view for this use :\ndirect_to_template(request, template, extra_context=None, mimetype=None, **kwargs)\n\nIt is not well documented (in my opinion : it doesn't tell that it uses a RequestContext), so I advise you to check out the implementation :\nhttp://code.djangoproject.com/browser/django/tr... | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002880748_django_python.txt |
Q:
How to save a whole web page with something block in it
I want to save a web page. I use python urllib to parse the web page. But I
find the saved file, where some content is missing. The missing part
is block from the source web page, such as this part <div
style="display: block;" id="GeneInts">...</div>.
I don'... | How to save a whole web page with something block in it | I want to save a web page. I use python urllib to parse the web page. But I
find the saved file, where some content is missing. The missing part
is block from the source web page, such as this part <div
style="display: block;" id="GeneInts">...</div>.
I don't know how to parse a whole page without something block in i... | [
"Whenever I need to let Javascript operate on a page before I can scrape it, the first thing I always turn to is SeleniumRC -- while it's mainly designed for purposes of testing, I've never found a better tool for this challenging task. For the \"using it from Python\" part, see here and links therefrom.\n",
"Th... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0003454819_python.txt |
Q:
Wikipedia with Python
I have this very simple python code to read xml for the wikipedia api:
import urllib
from xml.dom import minidom
usock = urllib.urlopen("http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500")
xmldoc=minidom.parse(usock)
usock.close()
print xmldoc.toxml()
But... | Wikipedia with Python | I have this very simple python code to read xml for the wikipedia api:
import urllib
from xml.dom import minidom
usock = urllib.urlopen("http://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500")
xmldoc=minidom.parse(usock)
usock.close()
print xmldoc.toxml()
But this code returns with the... | [
"The URL you're requesting is an HTML representation of the XML that would be returned:\nhttp://en.wikipedia.org/w/api.php?action=query&titles=Fractal&prop=links&pllimit=500\n\nSo the XML parser fails. You can see this by pasting the above in a browser. Try adding a format=xml at the end:\nhttp://en.wikipedia.org... | [
9
] | [] | [] | [
"python",
"wikipedia",
"xml"
] | stackoverflow_0003455104_python_wikipedia_xml.txt |
Q:
I extend QApplication and calling a method after exec_ does not work
The following code works (and it's very simple):
class Scrape(QApplication):
def __init__(self):
super(Scrape, self).__init__(None)
self.webView = QWebView()
self.webView.loadFinished.connect(self.loadFinished)
def load(self, url... | I extend QApplication and calling a method after exec_ does not work | The following code works (and it's very simple):
class Scrape(QApplication):
def __init__(self):
super(Scrape, self).__init__(None)
self.webView = QWebView()
self.webView.loadFinished.connect(self.loadFinished)
def load(self, url):
self.webView.load(QUrl(url))
def loadFinished(self):
document... | [
"The exec_ call starts the event loop. This is where keyboard and mouse events, timer events, as well as async slot calls are dispatched.\nThe load method does what you expect: sets the Url in the view. This doesn't need events to be processed for it to work. But if you don't finish with exec_, there will be nothin... | [
2
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0003455260_pyqt4_python.txt |
Q:
Python: Simple file formating problem
I'm using the code below to to write to a file but at the moment it writes everything onto a new line.
import csv
antigens = csv.reader(open('PAD_n1372.csv'), delimiter=',')
lista = []
pad_file = open('pad.txt','w')
for i in antigens:
lista.append(i[16])
lista.appen... | Python: Simple file formating problem | I'm using the code below to to write to a file but at the moment it writes everything onto a new line.
import csv
antigens = csv.reader(open('PAD_n1372.csv'), delimiter=',')
lista = []
pad_file = open('pad.txt','w')
for i in antigens:
lista.append(i[16])
lista.append(i[21])
lista.append(i[0])
for k in l... | [
"If lista is [['apple','car','red'],['orange','boat','black']], then each k in your loop is going to be one of the sub-lists, so all you need to do is join the elements of that sub-list on a , and output that as a single line:\nfor k in lista:\n pad_file.write(','.join(k))\n pad_file.write('\\n')\n\n\nEdit ba... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003452320_python.txt |
Q:
Passing instance/default value to a ModelFormSet for the empty forms to use, in a view
How do i pre-populate the exclude fields in a ModelFormSet. AuthorFormSet below doesn't take an instance argument here, only queryset. So how do i force the empty forms coming in not to have a NULL/None user attribute. I want to... | Passing instance/default value to a ModelFormSet for the empty forms to use, in a view | How do i pre-populate the exclude fields in a ModelFormSet. AuthorFormSet below doesn't take an instance argument here, only queryset. So how do i force the empty forms coming in not to have a NULL/None user attribute. I want to be able to set that user field to request.user
models.py
class Author(models.Model):
us... | [
"You can exclude fields in the model form, these will then be excluded from the formset created by modelformset_factory.\nclass AuthorForm(forms.ModelForm):\n class Meta:\n model = Author\n exclude = ('user',)\n\nIn your view, pass commit=False to the form's save() method, then set the user field m... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003453416_django_django_forms_python.txt |
Q:
Calling code in a string without exec/eval, python
I have this code that executes when a player attempts to eat something:
def eat(target='object'):
global current_room
global locations
global inventory
if target in inventory:
items[target]['on_eat'] #This is showing no results.
else:
... | Calling code in a string without exec/eval, python | I have this code that executes when a player attempts to eat something:
def eat(target='object'):
global current_room
global locations
global inventory
if target in inventory:
items[target]['on_eat'] #This is showing no results.
else:
print 'You have no ' + target + ' to eat.'
and t... | [
"You can store your function and function arguments as a partial:\nfrom functools import partial\n\nitems = { \n'strawberry': { \n 'weight': 1, \n 'text': 'The strawberry is red', \n 'on_eat': partial(normal_eat, 'strawberry', 'pretty good, but not as sweet as you expected') \n }, \n'trees': { \n 'we... | [
6,
1,
0
] | [] | [] | [
"eval",
"exec",
"python",
"reference"
] | stackoverflow_0003455490_eval_exec_python_reference.txt |
Q:
Can selenium open a search result page?
I'm new to selenium. I want to ask about if there's a easy way to open a search result page of some urls, not just the homepages.
for examples,
I search stack overflow in google. The url is here, but the return page is google homepage.Is it possible to get the result page di... | Can selenium open a search result page? | I'm new to selenium. I want to ask about if there's a easy way to open a search result page of some urls, not just the homepages.
for examples,
I search stack overflow in google. The url is here, but the return page is google homepage.Is it possible to get the result page directly? I want to scratch some result pages. ... | [
"You should change your code:\nfrom selenium import selenium\nurl ='http://www.google.com/'\nsel = selenium('localhost', 4444, '*firefox', url)\nsel.start()\nsel.open('/search?hl=en&source=hp&q=stack+overflow&aq=o&aqi=&aql=&oq=&gs_rfai=')\nsel.wait_for_page_to_load(10000)\n\nSo your url is pointing to the start pag... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0003456470_python_selenium_selenium_rc.txt |
Q:
Remove duplicate rows from a large file in Python
I've a csv file that I want to remove duplicate rows from, but it's too large to fit into memory. I found a way to get it done, but my guess is that it's not the best way.
Each row contains 15 fields and several hundred characters, and all fields are needed to det... | Remove duplicate rows from a large file in Python | I've a csv file that I want to remove duplicate rows from, but it's too large to fit into memory. I found a way to get it done, but my guess is that it's not the best way.
Each row contains 15 fields and several hundred characters, and all fields are needed to determine uniqueness. Instead of comparing the entire row ... | [
"If you want a really simple way to do this, just create a sqlite database:\nimport sqlite3\nconn = sqlite3.connect('single.db')\ncur = conn.cursor()\ncur.execute(\"\"\"create table test(\nf1 text,\nf2 text,\nf3 text,\nf4 text,\nf5 text,\nf6 text,\nf7 text,\nf8 text,\nf9 text,\nf10 text,\nf11 text,\nf12 text,\nf13 ... | [
13,
6,
2,
1,
0,
0
] | [] | [] | [
"duplicates",
"python"
] | stackoverflow_0003452832_duplicates_python.txt |
Q:
python analyse 2 logfiles
I have 2 large logfiles. I want to see if a device is in a but not b and vice versa (exclude lines where the device is common) the files look like this example.
04/09/2010,13:11:52,Authen OK,user1,Default Group,00-24-2B-A1-08-88,29,10.1.1.1,(Default),,,,,,13,EAP-TLS,,device1,
04/19/2010... | python analyse 2 logfiles | I have 2 large logfiles. I want to see if a device is in a but not b and vice versa (exclude lines where the device is common) the files look like this example.
04/09/2010,13:11:52,Authen OK,user1,Default Group,00-24-2B-A1-08-88,29,10.1.1.1,(Default),,,,,,13,EAP-TLS,,device1,
04/19/2010,15:35:24,Authen OK,user2,Defau... | [
"You are looking for a symmetric difference:\nchst = { ( line.split( \",\" )[ -2 ], line.split( \",\" )[ 7 ] ) for line in open( ... ) }\nchbs = { ( line.split( \",\" )[ -2 ], line.split( \",\" )[ 7 ] ) for line in open( ... ) }\n\ndiff = chst ^ chbs\n\nIf you need the asymmetric differences, use -:\nchst - chbs # ... | [
1,
0
] | [] | [] | [
"logfiles",
"python"
] | stackoverflow_0003456651_logfiles_python.txt |
Q:
Python importing modules that all import another module that is the same
What i want to is, I have foo.py it imports classes from bar1, bar2, and they both need bar3, e.g.
foo.py
from src import *
...
src/ __ init__.py
from bar1 import specialSandwichMaker
from bar2 import specialMuffinMaker
src/bar1.py
import b... | Python importing modules that all import another module that is the same | What i want to is, I have foo.py it imports classes from bar1, bar2, and they both need bar3, e.g.
foo.py
from src import *
...
src/ __ init__.py
from bar1 import specialSandwichMaker
from bar2 import specialMuffinMaker
src/bar1.py
import bar3
class specialSandwichMaker(bar3.sandwichMaker)
...
src/bar2.py
import bar... | [
"This is fully efficient; when importing a module Python will add it to sys.modules. import statements first check this dictionary (which is fast because dictionary lookups are fast) to see whether the module has been imported already. So in this case, bar1 will import bar3 and add it to sys.modules. Then bar2 will... | [
8,
1
] | [] | [] | [
"python"
] | stackoverflow_0003456874_python.txt |
Q:
Python subprocess.Popen communicate through a pipeline
I want to be able to use Popen.communicate and have the stdout logged to a file (in addition to being returned from communicate().
This does what I want - but is it really a good idea?
cat_task = subprocess.Popen(["cat"], stdout=subprocess.PIPE, stdin=subproc... | Python subprocess.Popen communicate through a pipeline | I want to be able to use Popen.communicate and have the stdout logged to a file (in addition to being returned from communicate().
This does what I want - but is it really a good idea?
cat_task = subprocess.Popen(["cat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
tee_task = subprocess.Popen(["tee", "-a", "/tmp/lo... | [
"Depending on your definition of \"nicer\", I would say that the following is probably nicer in the sense that it avoids having an additional tee process:\nimport subprocess\n\ndef logcommunicate(self, s):\n std = self.oldcommunicate(s)\n self.logfilehandle.write(std[0])\n return std\n\nsubprocess.Popen.ol... | [
1
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0003456692_popen_python_subprocess.txt |
Q:
How to save a webpage by seleniumRC
I use seleniumRC to open a url, then how to save this web page? How to realize it like urllib.urlretrieve do it? But urllib can't operate javascript in the page. One more question: Will it save the whole page with what I see as seleniumRC open it?
A:
It sounds like you are con... | How to save a webpage by seleniumRC | I use seleniumRC to open a url, then how to save this web page? How to realize it like urllib.urlretrieve do it? But urllib can't operate javascript in the page. One more question: Will it save the whole page with what I see as seleniumRC open it?
| [
"It sounds like you are confusing two very different libraries.\nurllib:\n\nThis module provides a high-level interface for fetching data across the World Wide Web. In particular, the urlopen() function is similar to the built-in function open(), but accepts Universal Resource Locators (URLs) instead of filenames. ... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0003456852_python_selenium_selenium_rc.txt |
Q:
Difference between simple Python function call and wrapping it in cProfile.run()
I have a rather simple Python script that contains a function call like
f(var, other_var)
i.e. a function that gets several parameters. All those parameters can be accessed within f and have values.
When I instead call
cProfile.run('f... | Difference between simple Python function call and wrapping it in cProfile.run() | I have a rather simple Python script that contains a function call like
f(var, other_var)
i.e. a function that gets several parameters. All those parameters can be accessed within f and have values.
When I instead call
cProfile.run('f(var, other_var)')
it fails with the error message:
NameError: "name 'var' is not defi... | [
"This is because cProfile attempts to exec the code you pass it as a string, and fails because, well, var is not defined in that piece of code! It is using the variables in the scope of the call to run(), but since you haven't told cProfile about them it doesn't know to use them. Use runctx instead, since it allows... | [
9
] | [] | [] | [
"profiler",
"python",
"python_2.6"
] | stackoverflow_0003457129_profiler_python_python_2.6.txt |
Q:
Comparing dates and times in different formats using Python
I have lines of the following format in a file.
Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z
I need to create a function that has two inputs: time and date in the following formats Time: HH:MM a... | Comparing dates and times in different formats using Python | I have lines of the following format in a file.
Summary;meeting;Description;None;DateStart;20100629T110000;DateEnd;20100629T120000;Time;20100805T084547Z
I need to create a function that has two inputs: time and date in the following formats Time: HH:MM and date as mmddyyyy. (These are strings). Now the function needs ... | [
"You can parse a string into a datetime with strptime:\n>>> datetime.datetime.strptime('20100629T110000', '%Y%m%dT%H%M%S')\ndatetime.datetime(2010, 6, 29, 11, 0)\n>>> datetime.datetime.strptime('23:45 06192005', '%H:%M %m%d%Y')\ndatetime.datetime(2005, 6, 19, 23, 45)\n\nAnd then you can compare (<, <=, etc) the two... | [
4,
1,
1
] | [] | [] | [
"date",
"python",
"time"
] | stackoverflow_0003457452_date_python_time.txt |
Q:
Elegant way to create a dictionary of pairs, from a list of tuples?
I have defined a tuple thus:
(slot, gameid, bitrate)
and created a list of them called myListOfTuples. In this list might be tuples containing the same gameid.
E.g. the list can look like:
[
(1, "Solitaire", 1000 ),
(2, "Diner Dash", 223... | Elegant way to create a dictionary of pairs, from a list of tuples? | I have defined a tuple thus:
(slot, gameid, bitrate)
and created a list of them called myListOfTuples. In this list might be tuples containing the same gameid.
E.g. the list can look like:
[
(1, "Solitaire", 1000 ),
(2, "Diner Dash", 22322 ),
(3, "Solitaire", 0 ),
(4, "Super Mario Kart", 854564 ),
..... | [
"For python2.6 \ndict(x[1:] for x in reversed(myListOfTuples))\n\nIf you have Python2.7 or 3.1, you can use katrielalex's answer\n",
"{ gameId: bitrate for _, gameId, bitrate in reversed( myListOfTuples ) }.items( )\n\n(This is a view, not a set. It has setlike operations, but if you need a set, cast it to one.)\... | [
10,
4
] | [] | [] | [
"python"
] | stackoverflow_0003457673_python.txt |
Q:
nagare framework on gae?
anyone using nagare framework on google app engine ?
it seems interesting, but i could not find any documentaiton on how to use it on
google app engine, as it uses stackless python.
so any chances of its running on google app engine ?
also, how stack less python differ from normal python ... | nagare framework on gae? | anyone using nagare framework on google app engine ?
it seems interesting, but i could not find any documentaiton on how to use it on
google app engine, as it uses stackless python.
so any chances of its running on google app engine ?
also, how stack less python differ from normal python ?
thanks.
links :
Nagare Frame... | [
"I currently have a not-yet-released, prototype version of Nagare for GAE (you can see the canonical Counter example at http://nagareproject.appspot.com/)\nHere are the 3 Nagare components not working on GAE, with their workarounds in this prototype:\n\nStackless Python:\n\nProblem: GAE is only pure vanilla CPython... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"python_stackless"
] | stackoverflow_0003449787_google_app_engine_python_python_stackless.txt |
Q:
Can't read file in__init__
I am a newbe to Python.
I have tried to create a class, named ic0File.
Here is what I get when I use it (Python 3.1)
>>> import sys
>>> sys.path.append('/remote/us01home15/ldagan/python/')
>>> import ic0File
>>> a=ic0File.ic0File('as_client/nohpp.ic0')
Traceback (most recent call last):
... | Can't read file in__init__ | I am a newbe to Python.
I have tried to create a class, named ic0File.
Here is what I get when I use it (Python 3.1)
>>> import sys
>>> sys.path.append('/remote/us01home15/ldagan/python/')
>>> import ic0File
>>> a=ic0File.ic0File('as_client/nohpp.ic0')
Traceback (most recent call last):
File "<stdin>", line 1, in <mo... | [
"To reload a module (e.g. if you have modified the code), use reload(). In your case:\nreload( ic0file )\n\nIn Python 3, reload was moved to the imp library:\nimport imp\nimp.reload( ic0file )\n\n",
"As other users have pointed out, the code that actually raised that exception would be helpful, but my guess is th... | [
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003457302_class_python.txt |
Q:
Make an installer for python project
I downloaded an open source project http://gmapcatcher.googlecode.com/files/GMapCatcher-0.7.2.0.tar.gz and I am trying to modify a few things in the code but don't know how to test the code!
I tried to make an installer for the project but nothing worked till now maybe I didn'... | Make an installer for python project | I downloaded an open source project http://gmapcatcher.googlecode.com/files/GMapCatcher-0.7.2.0.tar.gz and I am trying to modify a few things in the code but don't know how to test the code!
I tried to make an installer for the project but nothing worked till now maybe I didn't follow the right steps or I am missing s... | [
"Looks like the package has a setup.py for the use with distutils. The setup.py works kind of like Makefile for python. The way you use it is (in the directory where setup.py is located:\n$ python setup.py command\n\nWhere \"command\" is... well... a command. Type\n$ python setup.py --help\n\nfor more information. ... | [
3
] | [] | [] | [
"open_source",
"python",
"windows"
] | stackoverflow_0003457130_open_source_python_windows.txt |
Q:
Concurrency Testing For A Web Service Using Python
I have a web service that is required to handle significant concurrent utilization and volume and I need to test it. Since the service is fairly specialized, it does not lend itself well to a typical testing framework. The test would need to simulate multiple clie... | Concurrency Testing For A Web Service Using Python | I have a web service that is required to handle significant concurrent utilization and volume and I need to test it. Since the service is fairly specialized, it does not lend itself well to a typical testing framework. The test would need to simulate multiple clients concurrently posting to a URL, parsing the resulting... | [
"The Global Interpreter Lock prevents threads simultaneously executing Python code. This doesn't change when Python is compiled to bytecode, because the bytecode is still run by the Python interpreter, which will enforce the GIL. threading works by switching threads every sys.getcheckinterval() bytecodes.\nThis doe... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003458249_python.txt |
Q:
When while loop placed in wxPython events
I'm trying to write a GUI program grabbing specific contents from a webpage. The idea is when I hit the start button, the program should start extracting information from that page. And I want to add some code to check if connected to the Internet. If not, continue trying ... | When while loop placed in wxPython events | I'm trying to write a GUI program grabbing specific contents from a webpage. The idea is when I hit the start button, the program should start extracting information from that page. And I want to add some code to check if connected to the Internet. If not, continue trying until connected.
So I just added the following... | [
"When you have an event based program, the overall flow of the program is this:\nwhile the-program-is-running:\n wait-for-an-event\n service-the-event\nexit\n\nNow, lets see what happens when service-the-event calls something with a (potentially) infinite loop: \nwhile the-program-is-running:\n wait-for-an... | [
4,
0
] | [] | [] | [
"event_handling",
"python",
"wxpython"
] | stackoverflow_0003458023_event_handling_python_wxpython.txt |
Q:
Reason for low Pylint ratings of Python standard library code
A friend told me about Pylint and just out of curiosity, I ran it against some of the standard library modules. To my surprise, the ratings were low. Here are a few runs:
os.py
Your code has been rated at 3.55/10
random.py
Your code has been rated at ... | Reason for low Pylint ratings of Python standard library code | A friend told me about Pylint and just out of curiosity, I ran it against some of the standard library modules. To my surprise, the ratings were low. Here are a few runs:
os.py
Your code has been rated at 3.55/10
random.py
Your code has been rated at 4.74/10
I ran it on some more modules and the found the rating to ... | [
"Pylint's defaults are quite strict, and complain about things they should not. For example, if you use foo(**kwargs), you get a message about using \"magic\". Sometimes it seems as if pylint is looking at Python from a Java programmer's point of view.\nYou'd have to look at the specific messages and decide if yo... | [
13,
8
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0003355998_pylint_python.txt |
Q:
Using built-in type(,,) function to create a dynamic module
I'm trying to use the type(,,) function to dynamically build a module. The module creates classes representing templates, and I need a new class for every .tex file that lives in a particular folder. For instance, if I have a a4-page-template.tex file, I ... | Using built-in type(,,) function to create a dynamic module | I'm trying to use the type(,,) function to dynamically build a module. The module creates classes representing templates, and I need a new class for every .tex file that lives in a particular folder. For instance, if I have a a4-page-template.tex file, I need to create a class called A4PageTemplate.
I can create the ty... | [
"You have created the new class and assigned it to the global variable _newClass, but you're not storing this variable! Notice that if you do dynamictypes._newClass you will get the final type created. \nYou need to make a variable to hold each new class, as you create it:\nglobals()[ _className ] = _newClass\n\nTh... | [
3
] | [] | [] | [
"metaprogramming",
"module",
"python",
"python_module"
] | stackoverflow_0003458671_metaprogramming_module_python_python_module.txt |
Q:
loop through list of dictionaries
i have a list of dictionaries. there are several points inside the list, some are multiple. When there is a multiple entry i want to calculate the average of the x and the y of this point. My problem is, that i don't know how to loop through the list of dictionaries to compare the... | loop through list of dictionaries | i have a list of dictionaries. there are several points inside the list, some are multiple. When there is a multiple entry i want to calculate the average of the x and the y of this point. My problem is, that i don't know how to loop through the list of dictionaries to compare the ids of the points!
when i use somethin... | [
"One way would be changing the way you store your points, because as you already noticed, it's hard to get what you want out of it. \nA much more useful structure would be a dict where the id maps to a list of points:\nfrom collections import defaultdict\npoints_dict = defaultdict(list)\n\n# make the new dict\nfor ... | [
4,
0
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0003458285_dictionary_loops_python.txt |
Q:
Viewing Contents Of a DLL File
is this possible to view contents and Functions of a DLL file...
few times ago i was playing with OlyDBG then i found there is option for viewing contents of dll...
so suggest me any good tool or soft for this...
and suppose i have a DLL named "Python27.dll"...
now i need to view ... | Viewing Contents Of a DLL File | is this possible to view contents and Functions of a DLL file...
few times ago i was playing with OlyDBG then i found there is option for viewing contents of dll...
so suggest me any good tool or soft for this...
and suppose i have a DLL named "Python27.dll"...
now i need to view the content of this DLL so what do i... | [
"While not trivial to use (you need to understand the format of a Portable Executable, aka PE, file), pefile seems a good, powerful and versatile tool for the purpose of viewing a DLL or any other PE file (I wouldn't risk using it to change such a file, although I see it's one of its features).\nFor example, excerp... | [
5,
3,
1,
0
] | [] | [] | [
"c",
"c#",
"dll",
"import",
"python"
] | stackoverflow_0003454647_c_c#_dll_import_python.txt |
Q:
python code problem
i have this code:
class Check(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
... | python code problem | i have this code:
class Check(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
be = "SELECT * FROM Benutzer ORDER BY date "
c = db.GqlQuery(be)
for x in c:
if x.benutzer == user:
s=1
break
else:
s=2
if s is 0:
self.redirect('/')
to... | [
"Define s before to assign it a value (also, change the test on s):\nuser = users.get_current_user()\n\nbe = \"SELECT * FROM Benutzer ORDER BY date \"\n\nc = db.GqlQuery(be)\n\ns=0 # <- init s here\n\nfor x in c:\n if x.benutzer == user:\n s=1\n break\n else:\n s=2\nif s == 0: # <- change test on s... | [
6,
4,
2,
2,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003458950_google_app_engine_python.txt |
Q:
Python 3.X or Python 2.X
What's the ideal Python version for a beginner to start learning Python? I need to recommend some newbies a programming language to learn and I chose Python. I'm still not sure which version.
A:
It depends what you're going to do with it.
Unicode handling has vastly improved in Python 3.... | Python 3.X or Python 2.X | What's the ideal Python version for a beginner to start learning Python? I need to recommend some newbies a programming language to learn and I chose Python. I'm still not sure which version.
| [
"It depends what you're going to do with it.\nUnicode handling has vastly improved in Python 3. So if you intend to use this for building web pages or some such, Python 3 might be the obvious choice.\nOn the other hand, many libraries and frameworks still only support Python 2. For example, the numerical processing... | [
9,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003456088_python.txt |
Q:
Django admin - Edit parent model and related models on the same page
I want to be able to edit all data on one page. How can i achieve this ? Should i modify my models? If so, then how should i modify them?
class TextStyle(models.Model):
color = models.CharField(_("color"), max_length=7)
style = models.C... | Django admin - Edit parent model and related models on the same page | I want to be able to edit all data on one page. How can i achieve this ? Should i modify my models? If so, then how should i modify them?
class TextStyle(models.Model):
color = models.CharField(_("color"), max_length=7)
style = models.CharField(_("style"), max_length=30)
typeface = models.CharField(_("typ... | [
"You need to create an inline model in your admin.py. See: InlineModelAdmin. \n",
"I have created a module for inline editting of OneToOne relationships which i called ReverseModelAdmin. You can find it here. \nYou could use it on your Coupon entity to get all OneToOne relationships inlined like this:\nclass Coup... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003129289_django_django_admin_python.txt |
Q:
Django: Is there a way to set global views? For example enable data for a sidebar through all URLS
I am building a Django application that is a pretty basic blog, so far it has been wonderful. I got comments, tags etc up. But one thing is bugging me: I cant get the sidebar i want to work. I use the django.views.ge... | Django: Is there a way to set global views? For example enable data for a sidebar through all URLS | I am building a Django application that is a pretty basic blog, so far it has been wonderful. I got comments, tags etc up. But one thing is bugging me: I cant get the sidebar i want to work. I use the django.views.generic.date_based generic view and this is my urls.py for the blog:
urlpatterns = patterns('django.v... | [
"People do things like that with template tags. The documentation for custom template tags might be helpful, and there's also a great little tutorial here.\nAlternatively, you can use context processors - but that adds an overhead to every single request, which may not be necessary.\n"
] | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003459487_django_python.txt |
Q:
What is the best library for reliably dealing with attachments from email?
I have an application and need to write a program that is able to figure out attachments from all kinds of email senders (and MUAs) reliably. PHP doesn't seem to have a great MIME parser so I was hoping some other languages might.
I've see... | What is the best library for reliably dealing with attachments from email? | I have an application and need to write a program that is able to figure out attachments from all kinds of email senders (and MUAs) reliably. PHP doesn't seem to have a great MIME parser so I was hoping some other languages might.
I've seen the PHP Mail Mime Parser but it's not robust at all and I know (and have confi... | [
"How about Perl 5's Email::MIME? Looks like something that will fulfill Your needs, if I understood You correctly.\n",
"Python's email module is excellent and includes full support for MIME emails, including incremental parsing. I think the moral here is that you can do this in many languages. \nOf course, you sh... | [
4,
3,
3,
0
] | [] | [] | [
"email",
"parsing",
"perl",
"php",
"python"
] | stackoverflow_0003427688_email_parsing_perl_php_python.txt |
Q:
Django: Accessing method on child different child classes through common name
I have an abstract base class for defining common attributes shared by different user profiles.
class Profile(models.Model):
...
def has_permissions(self, project):
...
class Meta:
abstract = True
class Standard(P... | Django: Accessing method on child different child classes through common name | I have an abstract base class for defining common attributes shared by different user profiles.
class Profile(models.Model):
...
def has_permissions(self, project):
...
class Meta:
abstract = True
class Standard(Profile):
...
class Premium(Profile):
...
Now I would like to check the perm... | [
"overwrite the auth.User method get_profile() to investigate in all Child-Profile Models Until you find it:\n class MyUser(auth.models.User):\n profile = models.OneToOneField(Profile)\n def get_profile(self):\n prof = None\n try:\n prof = Standard.objects.get(id=s... | [
1,
0
] | [] | [] | [
"abstract",
"django",
"inheritance",
"python"
] | stackoverflow_0003457685_abstract_django_inheritance_python.txt |
Q:
How to lock django command for single run. Django. Python
How to lock django commands so it will not run twise in the same time?
A:
Create a lock somewhere - I recently saw very simple lock implementation that used cache:
LOCK_EXPIRE = 60 * 5
lock_id = "%s-lock-%s" % (self.name, id_hexdigest) #computed earlier
... | How to lock django command for single run. Django. Python | How to lock django commands so it will not run twise in the same time?
| [
"Create a lock somewhere - I recently saw very simple lock implementation that used cache:\nLOCK_EXPIRE = 60 * 5\n\nlock_id = \"%s-lock-%s\" % (self.name, id_hexdigest) #computed earlier\n\nis_locked = lambda: str(cache.get(lock_id)) == \"true\"\nacquire_lock = lambda: cache.set(lock_id, \"true\", LOCK_EXPIRE)\nrel... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003459631_django_python.txt |
Q:
Multiple drag and drop in PyQt4
i can't find an example on dragging (and dropping) multiple elements with Qt/PyQt;
In my case i need to drag elements from this QTableView:
class DragTable(QTableView):
def __init__(self, parent = None):
super(DragTable, self).__init__(parent)
self.setDragEnabled... | Multiple drag and drop in PyQt4 | i can't find an example on dragging (and dropping) multiple elements with Qt/PyQt;
In my case i need to drag elements from this QTableView:
class DragTable(QTableView):
def __init__(self, parent = None):
super(DragTable, self).__init__(parent)
self.setDragEnabled(True)
def dragEnterEvent(self, ... | [
"Here's a full working example:\nfrom PyQt4 import QtCore, QtGui, Qt\nimport cPickle\nimport pickle\n\nWhy are you using cPickle as well as pickle?\nclass DragTable(QtGui.QTableView):\n def __init__(self, parent = None):\n super(DragTable, self).__init__(parent)\n self.setDragEnabled(True)\n ... | [
6
] | [] | [] | [
"drag_and_drop",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0003458542_drag_and_drop_pyqt_pyqt4_python.txt |
Q:
I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?
I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not se... | I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines? | I am aware that the standard Python convention for line width is 79 characters. I know lines can be continued in a number of ways, such as automatic string concatenation, parentheses, and the backslash. What does not seem to be as clearly defined is how exactly the overflowing text should be formatted. Do I push it all... | [
"\nSupposing that the format I used above would fit the 79 character limit, is the indentation of the second line correct?\n\nYes, that's how PEP 8 shows it in examples:\nclass Rectangle(Blob):\n\n def __init__(self, width, height,\n color='black', emphasis=None, highlight=0):\n if width =... | [
11,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"code_formatting",
"conventions",
"python"
] | stackoverflow_0003459423_code_formatting_conventions_python.txt |
Q:
Is it possible to make Python functions behave like instances?
I understand that functions can have attributes. So I can do the following:
def myfunc():
myfunc.attribute += 1
print(myfunc.attribute)
myfunc.attribute = 1
Is it possible by any means to make such a function behave as if it were an instance?... | Is it possible to make Python functions behave like instances? | I understand that functions can have attributes. So I can do the following:
def myfunc():
myfunc.attribute += 1
print(myfunc.attribute)
myfunc.attribute = 1
Is it possible by any means to make such a function behave as if it were an instance? For example, I'd like to be able to do something like this:
x = cle... | [
"You can make a class with a __call__ method which would achieve a similar thing.\nEdit for clarity: Instead of making myfunc a function, make it a callable class. It walks like a function and it quacks like a function, but it can have members like a class.\n",
"A nicer way:\ndef funfactory( attribute ):\n def... | [
7,
2,
1,
0,
0
] | [] | [] | [
"attributes",
"function",
"python"
] | stackoverflow_0003459758_attributes_function_python.txt |
Q:
Converting (part of) a numpy recarray into a 2d array?
We've got a set of recarrays of data for individual days - the first attribute is a timestamp and the rest are values.
Several of these:
ts a b c
2010-08-06 08:00, 1.2, 3.4, 5.6
2010-08-06 08:05, 1.2, 3.4, 5.6
2010-08-06 08:10, 1.2, 3.4,... | Converting (part of) a numpy recarray into a 2d array? | We've got a set of recarrays of data for individual days - the first attribute is a timestamp and the rest are values.
Several of these:
ts a b c
2010-08-06 08:00, 1.2, 3.4, 5.6
2010-08-06 08:05, 1.2, 3.4, 5.6
2010-08-06 08:10, 1.2, 3.4, 5.6
2010-08-06 08:15, 2.2, 3.3, 5.6
2010-08-06 08:20, 1.2, ... | [
"There are several ways to do this. One way is to select multiple columns of the recarray and cast them as floats, then reshape back into a 2D array:\nnew_data = data[['a','b','c']].astype(np.float).reshape((data.size, 3))\n\nAlternatively, you might consider something like this (negligibly slower, but more readab... | [
8
] | [] | [] | [
"numpy",
"python",
"recarray"
] | stackoverflow_0003459611_numpy_python_recarray.txt |
Q:
Python + and * operators
I'm working my way through some code examples and I stumbled upon this:
endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th']
+ ['st']
I understand that for numbers after 4 and until 20 they end in 'th' and I can see that we are adding 17 more items to the list, and... | Python + and * operators | I'm working my way through some code examples and I stumbled upon this:
endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th']
+ ['st']
I understand that for numbers after 4 and until 20 they end in 'th' and I can see that we are adding 17 more items to the list, and I understand that '17 * ['th'... | [
"17 * ['th'] generates ['th', 'th', ..., 'th'] (17 items).\nIn addition it's worth noting 2 behaviours:\n\nThat this is only really useful because the contents 'th' is immutable (unless of course you never intended to modify the ending list).\nThe list object ['th'] is only created once, however it is extended by i... | [
5,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003460162_operators_python.txt |
Q:
Is there a good language/syntax for field validation we can re-use?
I'm working on a web app (using Python & Bottle) and building a decorator for validating HTTP parameters sent in GET or POST. The early version takes callables, so this:
@params(user_id=int, user_name=unicode)
... ensures that user_id is an int, u... | Is there a good language/syntax for field validation we can re-use? | I'm working on a web app (using Python & Bottle) and building a decorator for validating HTTP parameters sent in GET or POST. The early version takes callables, so this:
@params(user_id=int, user_name=unicode)
... ensures that user_id is an int, user_name is a string, and both fields exist.
But that's not enough. I wan... | [
"You could use lists.\n@validate(user_id=[int, min(1)], user_name=[unicode,required,max(40)])\n\nAnd each item could be a function (or class/object) that gets executed with the corresponding field as an argument. If it raises an error, it fails validation.\n"
] | [
2
] | [] | [] | [
"forms",
"html",
"http",
"python",
"validation"
] | stackoverflow_0003460398_forms_html_http_python_validation.txt |
Q:
Storing data for web application in python dictionary
Is it feasible to store data for a web application inside the program itself, e.g. as a large dictionary? The data would mostly be just a few hundred short-ish text blocks (roughly blog post size), and it will not be altered/added to at all by the users (althou... | Storing data for web application in python dictionary | Is it feasible to store data for a web application inside the program itself, e.g. as a large dictionary? The data would mostly be just a few hundred short-ish text blocks (roughly blog post size), and it will not be altered/added to at all by the users (although I would want to be able to update it myself every so oft... | [
"It is certainly possible. The amount of data you can store will be limited mostly by memory available.\nIf you are planning to perform database-like operations on the data then you are better off with an in-memory database like SQLite. If the data is picked up from a database and hashed then you might want to use ... | [
2
] | [] | [] | [
"database",
"python",
"sql",
"web_applications"
] | stackoverflow_0003460853_database_python_sql_web_applications.txt |
Q:
Plotting in a loop (with basemap and pyplot)....problems with pyplot.clf()
I am plotting some weather data for a research project. The plot consists of 18 timesteps. I decided the best way to accomplish this was to make a new plot for each timestep, save it a file, and create a new plot for the next timestep (us... | Plotting in a loop (with basemap and pyplot)....problems with pyplot.clf() | I am plotting some weather data for a research project. The plot consists of 18 timesteps. I decided the best way to accomplish this was to make a new plot for each timestep, save it a file, and create a new plot for the next timestep (using a for loop).
For example:
map_init #[Basemap Instance]
extra_shapes #[Bas... | [
"Try making a new figure instead of using clf().\ne.g.\nfor i in range(timesteps):\n fig = pyplot.figure()\n ...\n fig.savefig(filepath)\n\nAlternatively (and faster) you could just update the data in your image object\n(returned by imshow()).\ne.g. something like (completely untested):\nmap_init #[Basema... | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003460707_matplotlib_python.txt |
Q:
Python: File works on the command line but not with crontab
So I have a file that looks like so:
#!/usr/bin/python
import MySQLdb
import subprocess
from subprocess import call
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select... | Python: File works on the command line but not with crontab | So I have a file that looks like so:
#!/usr/bin/python
import MySQLdb
import subprocess
from subprocess import call
import re
conx = MySQLdb.connect (user = 'root', passwd = '******', db = 'vaxijen_antigens')
cursor = conx.cursor()
cursor.execute('select * from sequence')
row = cursor.fetchall()
f = open('/home/rv/nc... | [
"I suspect it's complaining about the path to \"formatdb\" in your subprocess call. Try changing that to the full path:\nsubprocess.call(['/home/path/formatdb', ...])\n\n",
"The cron daemon usually provides only a very limited PATH. Either put a more complete PATH in the crontab or use the full pathname in the P... | [
5,
3
] | [] | [] | [
"crontab",
"python"
] | stackoverflow_0003460867_crontab_python.txt |
Q:
Format date like: Monday, 1st March
Seems like it should be simple enough but it's driving me up the wall. I've looked at the python date formatting strings and it still doesn't make too much sense.
Here's what I'm trying to do: <Full day>, <Day of month><Ordinal> <Month>
Where <Ordinal> is st, nd, rd, th, etc dep... | Format date like: Monday, 1st March | Seems like it should be simple enough but it's driving me up the wall. I've looked at the python date formatting strings and it still doesn't make too much sense.
Here's what I'm trying to do: <Full day>, <Day of month><Ordinal> <Month>
Where <Ordinal> is st, nd, rd, th, etc depending on the day.
| [
"Update 2: Looks like OP found this useful after all :)\nUpdate: Never mind. The OP was looking for Django date formatting, not Python.\nAFAIK there is no built in format specifier for the ordinal. The others are easy:\nmy_date.strftime('%A, %d %B')\n\nI found this solution on the web:\nif 4 <= day <= 20 or 24 <= d... | [
5,
4
] | [] | [] | [
"date",
"date_formatting",
"django",
"python"
] | stackoverflow_0003460962_date_date_formatting_django_python.txt |
Q:
Get global variables from file as dict?
I've got a file, constants.py, that contains a bunch of global constants. Is there a way I can grab all of them as dict, for just this file?
A:
It should be simple:
import constants
print(constants.__dict__)
A:
import constants
constants_dict = {}
for constant in dir(co... | Get global variables from file as dict? | I've got a file, constants.py, that contains a bunch of global constants. Is there a way I can grab all of them as dict, for just this file?
| [
"It should be simple:\nimport constants\nprint(constants.__dict__)\n\n",
"import constants\n\nconstants_dict = {}\nfor constant in dir(constants):\n constants_dict[constant] = getattr(constants, constant)\n\nI'm not sure I see the point of this though. How is writing constants_dict['MY_CONSTANT'] any better/e... | [
5,
2
] | [] | [] | [
"global",
"import",
"python"
] | stackoverflow_0003460864_global_import_python.txt |
Q:
Indexer with two keys in python
I'm newbie with python. I want to write a class with two keys as indexer. also need to be able to use them inside of class like this:
a = Cartesian(-10,-10,10,10) # Cartesian is the name of my class
a[-5][-1]=10
and in the Cartesian class:
def fill(self,value):
self[x][y] = x*y-... | Indexer with two keys in python | I'm newbie with python. I want to write a class with two keys as indexer. also need to be able to use them inside of class like this:
a = Cartesian(-10,-10,10,10) # Cartesian is the name of my class
a[-5][-1]=10
and in the Cartesian class:
def fill(self,value):
self[x][y] = x*y-value
I try with
def __getitem__(sel... | [
"If you just need a lightweight application, you can have __getitem__ accept a tuple:\ndef __getitem__(self, c):\n x, y = c\n return self.data[x-self.dx][y-self.dy]\n\ndef __setitem__(self, c, v):\n x, y = c\n self.data[x-self.dx][y-self.dy] = v\n\nand use like this:\na[-5,-1] = 10\n\nHowever, if you are doing ... | [
14,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003461167_python.txt |
Q:
Printing output from classes other than main class with python?
In order to keep my code clean and organized, I split my classes up into a bunch of different files and folders, here is what a typical project structure will look like for me:
> Project
__init__.py
main.py
ui.py
> lib
foo.py
... | Printing output from classes other than main class with python? | In order to keep my code clean and organized, I split my classes up into a bunch of different files and folders, here is what a typical project structure will look like for me:
> Project
__init__.py
main.py
ui.py
> lib
foo.py
bar.py
In my ui.py file, I usually define some sort of info f... | [
"import project.ui or from project import ui should do the trick. Don't tell anyone I told you about the second option. The parent directory of project needs to be on your python path.\n"
] | [
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003461223_oop_python.txt |
Q:
Parse this date in Python: 5th November 2010
I'm having a bad time with date parsing and formatting today.
Points for somebody who can parse this date format into a datetime.date or datetime.datetime (I'm not too fussy but I'd prefer .date):
5th November 2010
A:
Using dateutil:
In [2]: import dateutil.parser as ... | Parse this date in Python: 5th November 2010 | I'm having a bad time with date parsing and formatting today.
Points for somebody who can parse this date format into a datetime.date or datetime.datetime (I'm not too fussy but I'd prefer .date):
5th November 2010
| [
"Using dateutil:\nIn [2]: import dateutil.parser as dparser\n\nIn [3]: date = dparser.parse('5th November 2010')\n\nIn [4]: date\nOut[4]: datetime.datetime(2010, 11, 5, 0, 0)\n\n",
"Unfortunately, strptime has no format characters for \"skip an ordinal suffix\" -- so, I'd do the skipping first, with a little RE, ... | [
17,
10,
5
] | [] | [] | [
"date_formatting",
"python",
"python_datetime"
] | stackoverflow_0003461435_date_formatting_python_python_datetime.txt |
Q:
Django Url Not Resolving with Query Parameters
I have an issue where I need to pass in query parameters for a GET request, but Django is not resolving the URL correctly to the view.
My urls.py looks like this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^confirm_cancel',
... | Django Url Not Resolving with Query Parameters | I have an issue where I need to pass in query parameters for a GET request, but Django is not resolving the URL correctly to the view.
My urls.py looks like this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^confirm_cancel',
'myapp.views.confirm_cancel_method',
... | [
"I don't think the problem is with your url. Are you using a shortcut like get_object_or_4o4 somewhere in your view? For example:\nget_object_or_404(MyModel, pk=99)\n\nwould result in a \"No MyModel matches given query, if there wasn't a record in your table with a primary key of 99.\n",
"We need to see what's ... | [
1,
1,
1,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003460910_django_django_urls_python.txt |
Q:
Problem using replaceWith to replace HTML tags with BeautifulSoup on Python
I am using BeautifulSoup in Python and am having trouble replacing some tags. I am finding <div> tags and checking for children. If those children do not have children (are a text node of NODE_TYPE = 3), I am copying them to be a <p>.
from... | Problem using replaceWith to replace HTML tags with BeautifulSoup on Python | I am using BeautifulSoup in Python and am having trouble replacing some tags. I am finding <div> tags and checking for children. If those children do not have children (are a text node of NODE_TYPE = 3), I am copying them to be a <p>.
from BeautifulSoup import Tag, BeautifulSoup
class bar:
self.soup = BeautifulSoup(... | [
"The error says:\n myIndex = self.parent.index(self)\nAttributeError: 'NoneType' object has no attribute 'index'\n\nThis code occurs on line 131 of BeautifulSoup.py.\nIt says that self.parent is None.\nLooking at the surrounding code shows that self should equal node in your code, since node is calling its repla... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003461814_beautifulsoup_python.txt |
Q:
Django, subdomains and mod_rewrite. URLs messing up on deployment setups
I have a Django application being served of (say) example.com. It contains a number of sub-applications (say) strength, speed and skill. The URL scheme is something like http://example.com/strength, http://example.com/speed and http://example... | Django, subdomains and mod_rewrite. URLs messing up on deployment setups | I have a Django application being served of (say) example.com. It contains a number of sub-applications (say) strength, speed and skill. The URL scheme is something like http://example.com/strength, http://example.com/speed and http://example.com/skill. This is how I run my dev server (using runserver) and there are no... | [
"For this answer I'm assuming that you're willing to do a mod_rewrite for each subdomain. I don't think this will work for any subdomain (i.e. the x you mention).\nThis will strip out the leading /skill/ so that your app will continue to work:\nRewriteCond %{HTTP_HOST} !www.example.com$ [NC]\nRewriteCond %{HTTP_HOS... | [
3
] | [] | [] | [
"django",
"mod_rewrite",
"python",
"subdomain"
] | stackoverflow_0003461806_django_mod_rewrite_python_subdomain.txt |
Q:
Multithreaded Python script taking longer than non-threaded script
Disclaimer: I'm pretty terrible with multithreading, so it's entirely possible I'm doing something wrong.
I've written a very basic raytracer in Python, and I was looking for ways to possibly speed it up. Multithreading seemed like an option, s... | Multithreaded Python script taking longer than non-threaded script | Disclaimer: I'm pretty terrible with multithreading, so it's entirely possible I'm doing something wrong.
I've written a very basic raytracer in Python, and I was looking for ways to possibly speed it up. Multithreading seemed like an option, so I decided to try it out. However, while the original script took ~85 ... | [
"I suspect the Python Global Interpreter Lock is preventing your code from running in two threads at once.\nWhat is a global interpreter lock (GIL)?\nClearly you want to take advantage of multiple CPUs. Can you split the ray tracing across processes instead of threads?\nThe multithreaded version obviously does more... | [
8,
2,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003461899_multithreading_python.txt |
Q:
Python subprocess problem
I'm writing a script to generate a CSR in Python. The script is very simple. I generate an RSA private key by using the following:
keycmd = "openssl genrsa -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdout=PIPE)
csrcmd = "openssl req -new -key mykey.pem -subj "+ subj + "... | Python subprocess problem | I'm writing a script to generate a CSR in Python. The script is very simple. I generate an RSA private key by using the following:
keycmd = "openssl genrsa -out mykey.pem 2048"
keyprocess = Popen(keycmd, shell=True, stdout=PIPE)
csrcmd = "openssl req -new -key mykey.pem -subj "+ subj + " -out mycsr.csr"
reqprocess = P... | [
"Add the option -passout stdin to the openssl genrsa command, and it will read the passphrase from standard input. That should allow you to send it in via communicate.\nThere are several other values you can provide to the -passout option to obtain the passphrase from another source. See the OpenSSL man page for de... | [
3,
2
] | [] | [] | [
"csr",
"openssl",
"pipe",
"python"
] | stackoverflow_0003460971_csr_openssl_pipe_python.txt |
Q:
Python Object Oriented Design; Return, Set Instance Variable Or Both
Ok I have some code that boils down to a pattern like this
class Foo(object):
def get_something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
self.s... | Python Object Oriented Design; Return, Set Instance Variable Or Both | Ok I have some code that boils down to a pattern like this
class Foo(object):
def get_something1(self):
# in the actual code it asks a web server but here I replaced that with "foo_something1" instead of the code from a web server
self.something1 = "foo_something1"
def get_something2(self):
# needs the re... | [
"Don't use get_* methods. In Python the better way is to use properties:\nclass Foo(object):\n @property\n def something1(self):\n # in the actual code it asks a web server but here I replaced that with \"foo_something1\" instead of the code from a web server\n return \"foo_something1\"\n @pr... | [
4
] | [] | [] | [
"object",
"oop",
"python"
] | stackoverflow_0003462645_object_oop_python.txt |
Q:
In Python, how do I check that a file is a text file?
The file is uploaded through a Django form. The contents of the file need to be saved into a models.TextField(), for editors to review it before publication.
I am already checking UploadedFile.content_type. I have considered using a regular input field, but as ... | In Python, how do I check that a file is a text file? | The file is uploaded through a Django form. The contents of the file need to be saved into a models.TextField(), for editors to review it before publication.
I am already checking UploadedFile.content_type. I have considered using a regular input field, but as the text is going to be quite long, it would be unwieldy fo... | [
"Google is your friend on this one - see here\n",
"Not all sequences of bytes are valid for ex. UTF-8, maybe you should check this?\n"
] | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003462951_django_python.txt |
Q:
site.addsitedir not fully processing .pth file
This is a apache/mod_wsgi/virtualenv/django stack. In the virtualenv site-packages dir I've got a virtualenv_path_extensions.pth file. The apache conf has a
WSGIScriptAlias / /path/to/my.wsgi
my.wsgi has
site.addsitedir('/path/to/virtualenv/site-packages')
Now, if I... | site.addsitedir not fully processing .pth file | This is a apache/mod_wsgi/virtualenv/django stack. In the virtualenv site-packages dir I've got a virtualenv_path_extensions.pth file. The apache conf has a
WSGIScriptAlias / /path/to/my.wsgi
my.wsgi has
site.addsitedir('/path/to/virtualenv/site-packages')
Now, if I start up a python shell, import site, and call the ... | [
"Ah, selinux :D\nThe paths that were not getting loaded had the wrong context, and apache wasn't able to touch them ...\n** must remember to check those selinux logs when mysteries arise **\n"
] | [
1
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0003460585_apache_mod_wsgi_python_virtualenv.txt |
Q:
Why is a success message considered an error in ftplib
import ftplib
server = '192.168.1.109'
user = 'bob'
password = 'likes_sandwiches'
box = ftplib.FTP(server)
box.login(user, password)
s = box.mkd('\\a\\this4\\')
box.close()
x = raw_input('done, eat sandwiches now')
This returns:
Traceback (most recent call... | Why is a success message considered an error in ftplib | import ftplib
server = '192.168.1.109'
user = 'bob'
password = 'likes_sandwiches'
box = ftplib.FTP(server)
box.login(user, password)
s = box.mkd('\\a\\this4\\')
box.close()
x = raw_input('done, eat sandwiches now')
This returns:
Traceback (most recent call last):
File "C:\scripts\ftp_test.py", line 25, in
s ... | [
"According to RFC 959 (FTP), the only valid response code to MKD is 257. Looks like this is a problem caused by the FTP server not conforming to the standard.\nFor your interest, this is the relevant ftplib code:\nif resp[:3] != '257':\n raise error_reply, resp\n\n",
"ftplib is expecting a result of 257, defin... | [
1,
1
] | [] | [] | [
"ftp",
"ftplib",
"python"
] | stackoverflow_0003463033_ftp_ftplib_python.txt |
Q:
Python App Engine import issues after app is cached
I'm using a modified version on juno (http://github.com/breily/juno/) in Google App Engine. The problem I'm having is I have code like this:
import juno
import pprint
@get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name__ == '__main__'... | Python App Engine import issues after app is cached | I'm using a modified version on juno (http://github.com/breily/juno/) in Google App Engine. The problem I'm having is I have code like this:
import juno
import pprint
@get('/')
def home(web):
pprint.pprint("test")
def main():
run()
if __name__ == '__main__':
main()
The first time I start the app up in the dev ... | [
"Is it possible you are reassigning the name pprint somewhere? The only two ways I know of for a module-level name (like what you get from the import statement) to become None is if you either assign it yourself pprint = None or upon interpreter shutdown, when Python's cleanup assigns all module-level names to Non... | [
0,
0
] | [] | [] | [
"caching",
"google_app_engine",
"import",
"python"
] | stackoverflow_0001895744_caching_google_app_engine_import_python.txt |
Q:
Reading and comparing lines in a file using Python
I have a file of the following format.
15/07/2010 14:14:13 changed_status_from_Offline_to_Available
15/07/2010 15:01:09 changed_status_from_Available_to_Offline
15/07/2010 15:15:35 changed_status_from_Offline_to_Away became_idle
15/07/2010 15:16:29 changed_status... | Reading and comparing lines in a file using Python | I have a file of the following format.
15/07/2010 14:14:13 changed_status_from_Offline_to_Available
15/07/2010 15:01:09 changed_status_from_Available_to_Offline
15/07/2010 15:15:35 changed_status_from_Offline_to_Away became_idle
15/07/2010 15:16:29 changed_status_from_Away_to_Available became_unidle
15/07/2010 15:45:4... | [
"import datetime\nimport time\n\ndef lines( path_to_file ):\n '''Open path_to_file and read the lines one at a time, yielding tuples\n ( date of line, time of line, status before line )'''\n with open( path_to_file ) as theFile:\n for line in theFile:\n line = line.rsplit( \" \", 1 )\n ... | [
1,
0,
0,
-1
] | [
"Try this:\nimport datetime\n\nfilein = open(\"filein\", \"r\")\n\nclass Status: \n def __init__(self, date, time, status):\n print date.split('/')\n day, month, year = map(int, date.split('/'))\n hour, minute, second = map(int, time.split(':'))\n self.date_and_time = datetime.datet... | [
-1,
-1
] | [
"compare",
"file",
"python"
] | stackoverflow_0003404686_compare_file_python.txt |
Q:
Python: urlopen not downloading the entire site
Greetings,
I have done:
import urllib
site = urllib.urlopen('http://www.weather.com/weather/today/Temple+TX+76504')
site_data = site.read()
site.close()
but it doesn't compare to viewing the source when loaded in firefox.
I suspected the user agent and did this:
cl... | Python: urlopen not downloading the entire site | Greetings,
I have done:
import urllib
site = urllib.urlopen('http://www.weather.com/weather/today/Temple+TX+76504')
site_data = site.read()
site.close()
but it doesn't compare to viewing the source when loaded in firefox.
I suspected the user agent and did this:
class AppURLopener(urllib.FancyURLopener):
version ... | [
"It's more likely that there is an iframe in the code or that javascript is modifying the DOM. If theres an iframe, you'll have to parse the page to get the url for the iframe or just do it manually if it's a one-off. If it's javascript, I hear that selenium-rc is good but have no first hand experience with it.\n"... | [
3,
2
] | [] | [] | [
"python",
"urllib",
"urlopen"
] | stackoverflow_0003463533_python_urllib_urlopen.txt |
Q:
TurboMail 3 with Pylons 1.0 - MailNotEnabledException
I am trying to setup TurboMail 3 with Pylons 1.0
Followed the docs here
I have added this to the development.ini
[DEFAULT]
...
mail.on = true
mail.manager = immediate
mail.transport = smtp
mail.smtp.server = localhost
and my app_globals.py looks like:
"""The... | TurboMail 3 with Pylons 1.0 - MailNotEnabledException | I am trying to setup TurboMail 3 with Pylons 1.0
Followed the docs here
I have added this to the development.ini
[DEFAULT]
...
mail.on = true
mail.manager = immediate
mail.transport = smtp
mail.smtp.server = localhost
and my app_globals.py looks like:
"""The application's Globals object"""
from beaker.cache import ... | [
"Pylons 1.0 made several backwards-incompatible changes to how (and when) the configuration is stored in a global object. In this case, the configuration is no longer loaded when the Globals object is instantiated. Instead, you will have to change your code to the following:\nimport atexit\nfrom turbomail import ... | [
3
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003458344_pylons_python.txt |
Q:
Python compile all non-words except dot[.]
I am trying to break a line on all non-word patterns except .(dot)
Usually I guess it can be done as [\W ^[.]] in java, but how to I do in python?
A:
>>> import re
>>> the_string="http://hello-world.com"
>>> re.findall(r'[\w.]+',the_string)
['http', 'hello', 'world.com'... | Python compile all non-words except dot[.] | I am trying to break a line on all non-word patterns except .(dot)
Usually I guess it can be done as [\W ^[.]] in java, but how to I do in python?
| [
">>> import re\n>>> the_string=\"http://hello-world.com\"\n>>> re.findall(r'[\\w.]+',the_string)\n['http', 'hello', 'world.com']\n\n",
"A very good reference for Python's regular expression module is available here. Following should do the trick for you.\nimport re\nre.split(r'[\\w.]+', text_string)\n\nOr,\nimpor... | [
4,
1,
1,
0
] | [
"Python has a convenience function for that\n>>> s = \"ab.cd.ef.gh\"\n>>> s.split(\".\")\n['ab', 'cd', 'ef', 'gh']\n\n"
] | [
-1
] | [
"python",
"regex"
] | stackoverflow_0003463650_python_regex.txt |
Q:
M2Crypto: verifying DSA signatures
I'm having trouble verifying DSA signatures using Python/M2Crypto. The signatures are generated in Java, using standard java.security.Signature class, with Sun's crypto provider and SHA1withDSA algorithm designation.
Here's some shell output:
>>> pk
<M2Crypto.DSA.DSA_pub instance... | M2Crypto: verifying DSA signatures | I'm having trouble verifying DSA signatures using Python/M2Crypto. The signatures are generated in Java, using standard java.security.Signature class, with Sun's crypto provider and SHA1withDSA algorithm designation.
Here's some shell output:
>>> pk
<M2Crypto.DSA.DSA_pub instance at 0x20b6a28>
>>> sig = '302c02141c4bbb... | [
"Found a solution in the tests: http://svn.osafoundation.org/m2crypto/trunk/tests/test_dsa.py\nThe verify_asn1 method should be used as follows:\n>>> pk.verify_asn1(sha1(data).digest(), sig)\n\n"
] | [
4
] | [] | [] | [
"digital_signature",
"dsa",
"m2crypto",
"python"
] | stackoverflow_0003454523_digital_signature_dsa_m2crypto_python.txt |
Q:
What is a .pyc_dis file?
I have a folder that has a .pyc_dis file from a module. What can I do with it? How do I run it? What does this file even come from?
I couldn't find any information with a Google search.
Thanks.
A:
it's probably a disassembled python bytecode obtained by decompyle.
you can generate simila... | What is a .pyc_dis file? | I have a folder that has a .pyc_dis file from a module. What can I do with it? How do I run it? What does this file even come from?
I couldn't find any information with a Google search.
Thanks.
| [
"it's probably a disassembled python bytecode obtained by decompyle.\nyou can generate similar data like this:\n>>> import code, dis\n>>> c = code.compile_command('x = []; x.append(\"foo\")')\n>>> dis.disassemble(c)\n 1 0 BUILD_LIST 0\n 3 STORE_NAME 0 (x)\n ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003464145_python.txt |
Q:
Django select options
I'm making an app that has a file name field, an upload file field and a select. Lets say I have something like this for the select
<select name="menu">
<option value="0" selected> select imp </option>
<option value="1"> imp 1 </option>
<option value="2"> imp 2 </option>
<option v... | Django select options | I'm making an app that has a file name field, an upload file field and a select. Lets say I have something like this for the select
<select name="menu">
<option value="0" selected> select imp </option>
<option value="1"> imp 1 </option>
<option value="2"> imp 2 </option>
<option value="3"> imp 3 </option>
... | [
"You need to use a ChoiceField:\nIMP_CHOICES = (\n ('1', 'imp 1'),\n ('2', 'imp 2'),\n ('3', 'imp 3'),\n ('4', 'imp 4'),\n)\n\nclass UploadFileForm(forms.Form):\n title = forms.CharField(max_length=50)\n file = forms.FileField(widget=forms.FileInput())\n imp = forms.ChoiceField(choices=IMP_CHO... | [
12
] | [] | [] | [
"combobox",
"django",
"drop_down_menu",
"forms",
"python"
] | stackoverflow_0003463700_combobox_django_drop_down_menu_forms_python.txt |
Q:
How to simply read in input from stdin delimited by space or spaces
Hello I'm a trying to learn python,
In C++ to read in string from stdin I simply do
string str;
while (cin>>str)
do_something(str)
but in python, I have to use
line = raw_input()
then
x = line.split()
then I have to loop through the list x ... | How to simply read in input from stdin delimited by space or spaces | Hello I'm a trying to learn python,
In C++ to read in string from stdin I simply do
string str;
while (cin>>str)
do_something(str)
but in python, I have to use
line = raw_input()
then
x = line.split()
then I have to loop through the list x to access each str to do_something(str)
this seems like a lot of code jus... | [
"Python doesn't special-case such a specific form of input for you, but it's trivial to make a little generator for it of course:\ndef fromcin(prompt=None):\n while True:\n try: line = raw_input(prompt)\n except EOFError: break\n for w in line.split(): yield w\n\nand then, in your application code, you lo... | [
6,
0,
0
] | [] | [] | [
"python",
"raw_input",
"stdin"
] | stackoverflow_0003464212_python_raw_input_stdin.txt |
Q:
I can retrieve values from datastore
I want to retrieve some values I put in the data store with a model class name "Ani" and I have tried using the script below to do that but I am having problem with. Can someone please, help me with it
import random
import getpass
import sys
# Add the Python SDK to the package... | I can retrieve values from datastore | I want to retrieve some values I put in the data store with a model class name "Ani" and I have tried using the script below to do that but I am having problem with. Can someone please, help me with it
import random
import getpass
import sys
# Add the Python SDK to the package path.
# Adjust these paths accordingly.
s... | [
"You need to import the file where you define the class Ani before you can run queries on the data. \n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003420699_google_app_engine_python.txt |
Q:
What is the subprocess equivalent of passing "b" to os.popen2?
In Python 2.x, os.popen(command, "b") gives me a binary stream of the given command's output. This is primarily important on Windows, where binary and text streams actually give you different bytes.
The subprocess module is supposed to replace os.pope... | What is the subprocess equivalent of passing "b" to os.popen2? | In Python 2.x, os.popen(command, "b") gives me a binary stream of the given command's output. This is primarily important on Windows, where binary and text streams actually give you different bytes.
The subprocess module is supposed to replace os.popen and the other child-process spawning APIs. However, the conversio... | [
"It does by default, unless you're doing Popen(..., universal_newlines=True).\nclass Popen(object):\n [...]\n def __init__(self, ...):\n [...]\n if p2cwrite is not None:\n self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)\n if c2pread is not None:\n if universal_newlin... | [
2
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003464589_python_subprocess.txt |
Q:
Django:How can I ensure that a view can only be directed from another view
I have two views
def view1(request):
do something
return HttpResponseRedirect(reverse(view2), args1)
Now I need view2 to only work if it's referred by view1. How do I do that? I did read it somewhere, not able to recollect
@somefi... | Django:How can I ensure that a view can only be directed from another view | I have two views
def view1(request):
do something
return HttpResponseRedirect(reverse(view2), args1)
Now I need view2 to only work if it's referred by view1. How do I do that? I did read it somewhere, not able to recollect
@somefilter
def view2(request):
do something
#view2 will only be referred from ... | [
"I think you should check for the HTTP_REFERER HTTP header. See the documentation. Here is a Django snippet that gives you a decorator to check for referrers. \n"
] | [
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0003463698_django_django_views_python.txt |
Q:
Throwing exception in Python and reading the message in jQuery
How can I throw an exception on my server and have the exception's message be read in JavaScript (I'm using AJAX with jQuery). My server environment is Google App Engine (Python).
Here's my server code:
def post(self):
answer_text = util.escapeTex... | Throwing exception in Python and reading the message in jQuery | How can I throw an exception on my server and have the exception's message be read in JavaScript (I'm using AJAX with jQuery). My server environment is Google App Engine (Python).
Here's my server code:
def post(self):
answer_text = util.escapeText(self.request.get("answer"))
# Validation
if ( len(str(answ... | [
"If you have debug=True in your WSGI app configuration, the stack trace from your exception will get populated to the HTTP response body, and you can parse your message out of the stack trace client side.\nDon't do this, though. It's insecure, and a bad design choice. For predictable, recoverable error conditions, ... | [
3,
2
] | [] | [] | [
"ajax",
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0003464434_ajax_google_app_engine_jquery_python.txt |
Q:
Is there way to make costum signal when Manytomany relations created? Django!
Is there way to make custom signal when ManyToMany relations created?
A:
Without knowing more details about what you are trying to accomplish I'd suggest that you take a look at this previously asked question. If this is not what you ... | Is there way to make costum signal when Manytomany relations created? Django! | Is there way to make custom signal when ManyToMany relations created?
| [
"Without knowing more details about what you are trying to accomplish I'd suggest that you take a look at this previously asked question. If this is not what you are looking for then posting more details (including code) about what you want to do will help.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_signals",
"python"
] | stackoverflow_0003462294_django_django_models_django_signals_python.txt |
Q:
Why does Cassandra act strange with byte keys (with Lazyboy)?
I wrote a test program for testing Cassandra, and I had problems reading data. Seems like Cassandra sometimes takes one key for another.
Here is my test program :
from lazyboy import *
from lazyboy.key import Key
import uuid
import random
class TestIte... | Why does Cassandra act strange with byte keys (with Lazyboy)? | I wrote a test program for testing Cassandra, and I had problems reading data. Seems like Cassandra sometimes takes one key for another.
Here is my test program :
from lazyboy import *
from lazyboy.key import Key
import uuid
import random
class TestItemKey(Key):
def __init__(self, key=None):
Key.__init__(self... | [
"Sounds a lot like you're hitting https://issues.apache.org/jira/browse/CASSANDRA-1235 which is fixed in the 0.6 branch and will be in 0.6.5, the next stable release.\n"
] | [
2
] | [] | [] | [
"cassandra",
"python",
"uuid"
] | stackoverflow_0003459086_cassandra_python_uuid.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.