title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python csv reader - convert string to int on the for line when iterating
3,682,321
6
2010-09-10T04:53:00Z
3,682,332
8
2010-09-10T04:57:13Z
[ "python" ]
I'm interested in not having to write map the int function to the tuple of strings where I currently have it. See the last part of my example: ``` import os import csv filepath = os.path.normpath("c:/temp/test.csv") individualFile = open(filepath,'rb') dialect = csv.Sniffer().sniff(individualFile.read(1000)) indiv...
what you want is something like: ``` def int_wrapper(reader): for v in reader: yield map(int, v) ``` Your code would then look like: ``` reader = csv.reader(individualFile,dialect) reader = int_wrapper(reader) # all that other stuff for m, f, s, g, a, c, t in reader: try: census[m][f][s][g]...
python multiprocessing pool, wait for processes and restart custom processes
3,682,469
4
2010-09-10T05:39:26Z
3,682,526
12
2010-09-10T05:55:36Z
[ "python", "multiprocessing" ]
I used python multiprocessing and do wait of all processes with this code: ``` ... results = [] for i in range(num_extract): url = queue.get(timeout=5) try: print "START PROCESS!" result = pool.apply_async(process, [host,ur...
You are getting the error because you need to call `pool.close()` before calling `pool.join()` I don't know of a good way to shut down a process started with `apply_async` but see if properly shutting down the pool doesn't make your memory leak go away. The reason I think this is that the `Pool` class has a bunch of ...
Django models.py Circular Foreign Key
3,682,513
17
2010-09-10T05:50:45Z
3,682,524
37
2010-09-10T05:54:12Z
[ "python", "mysql", "django", "foreign-keys" ]
I have a django app which basically is just a photo album. Right now I have two models: `Image` and `Album`. Among other things, each `Album` has a foreign key to an `Image` to be its thumbnail and each `Image` has a foreign key to the `Album` it belongs in. However, when I try to use `manage.py syncdb` or `manage.py s...
You don't actually have a circular reference; the issue is that, at the time you define Album, you haven't defined Image yet. You can fix that by using a string instead: ``` class Album(models.model): thumb = models.ForeignKey('Image', null=True, blank=True) ``` However, in this case, you might want to use a [OneTo...
Django models.py Circular Foreign Key
3,682,513
17
2010-09-10T05:50:45Z
3,682,539
11
2010-09-10T05:59:47Z
[ "python", "mysql", "django", "foreign-keys" ]
I have a django app which basically is just a photo album. Right now I have two models: `Image` and `Album`. Among other things, each `Album` has a foreign key to an `Image` to be its thumbnail and each `Image` has a foreign key to the `Album` it belongs in. However, when I try to use `manage.py syncdb` or `manage.py s...
Use quotes to force a lazy reference: ``` models.ForeignKey('Image', null=True, blank=True) ``` Also, ForeignKey.related\_name is your friend (avoids back-reference name clashes).
Converting unix timestamp string to readable date in Python
3,682,748
333
2010-09-10T06:56:58Z
3,682,766
98
2010-09-10T06:59:57Z
[ "python", "datetime", "unix-timestamp", "strftime" ]
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use `time.strftime`, I get a `TypeError`: ``` >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "<stdin>", line 1, in <module> Type...
``` >>> from datetime import datetime >>> datetime.fromtimestamp(1172969203.1) datetime.datetime(2007, 3, 4, 0, 46, 43, 100000) ``` Taken from <http://seehuhn.de/pages/pdate>
Converting unix timestamp string to readable date in Python
3,682,748
333
2010-09-10T06:56:58Z
3,682,808
538
2010-09-10T07:09:25Z
[ "python", "datetime", "unix-timestamp", "strftime" ]
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use `time.strftime`, I get a `TypeError`: ``` >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "<stdin>", line 1, in <module> Type...
Use `datetime` module: ``` import datetime print( datetime.datetime.fromtimestamp( int("1284101485") ).strftime('%Y-%m-%d %H:%M:%S') ) ``` In this code `datetime.datetime` can look strange, but 1st `datetime` is module name and 2nd is class name. So `datetime.datetime.fromtimestamp()` is `fromtimestam...
Converting unix timestamp string to readable date in Python
3,682,748
333
2010-09-10T06:56:58Z
3,683,166
53
2010-09-10T08:28:06Z
[ "python", "datetime", "unix-timestamp", "strftime" ]
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use `time.strftime`, I get a `TypeError`: ``` >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "<stdin>", line 1, in <module> Type...
``` >>> import time >>> time.ctime(int("1284101485")) 'Fri Sep 10 16:51:25 2010' >>> time.strftime("%D %H:%M", time.localtime(int("1284101485"))) '09/10/10 16:51' ```
Converting unix timestamp string to readable date in Python
3,682,748
333
2010-09-10T06:56:58Z
9,597,396
15
2012-03-07T07:30:39Z
[ "python", "datetime", "unix-timestamp", "strftime" ]
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use `time.strftime`, I get a `TypeError`: ``` >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "<stdin>", line 1, in <module> Type...
You can convert the current time like this ``` t=datetime.fromtimestamp(time.time()) t.strftime('%Y-%m-%d') '2012-03-07' ``` To convert a date in string to different formats. ``` import datetime,time def createDateObject(str_date,strFormat="%Y-%m-%d"): timeStamp = time.mktime(time.strptime(str_date,strForma...
Converting unix timestamp string to readable date in Python
3,682,748
333
2010-09-10T06:56:58Z
14,048,587
26
2012-12-27T02:11:00Z
[ "python", "datetime", "unix-timestamp", "strftime" ]
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use `time.strftime`, I get a `TypeError`: ``` >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "<stdin>", line 1, in <module> Type...
For a human readable timestamp from a UNIX timestamp, I have used this in scripts before: ``` import os, datetime datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y") ``` Output: 'December 26, 2012'
Converting unix timestamp string to readable date in Python
3,682,748
333
2010-09-10T06:56:58Z
37,188,257
19
2016-05-12T13:23:00Z
[ "python", "datetime", "unix-timestamp", "strftime" ]
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use `time.strftime`, I get a `TypeError`: ``` >>>import time >>>print time.strftime("%B %d %Y", "1284101485") Traceback (most recent call last): File "<stdin>", line 1, in <module> Type...
The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC: ``` datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ') ``` Where posix\_time is the Posix epoch time you want to convert
Flask error: werkzeug.routing.BuildError
3,683,108
45
2010-09-10T08:15:03Z
3,683,531
102
2010-09-10T09:31:36Z
[ "python", "flask" ]
I modify the login of flaskr sample app, the first line get error. But www.html is in the template dir. ``` return redirect(url_for('www')) #return redirect(url_for('show_entries')) ``` display error: ``` werkzeug.routing.BuildError BuildError: ('www', {}, None) ``` Thanks for help!
`return redirect(url_for('www'))` would work if you have a function somewhere else like this: ``` @app.route('/welcome') def www(): return render_template('www.html') ``` `url_for` looks for a function, you pass it the *name* of the function you are wanting to call. Think of it like this: ``` @app.route('/login'...
Parameter names in Python functions that take single object or iterable
3,683,116
8
2010-09-10T08:17:57Z
3,683,839
7
2010-09-10T10:23:04Z
[ "python", "naming-conventions" ]
I have some functions in my code that accept either an object or an iterable of objects as input. I was taught to use meaningful names for everything, but I am not sure how to comply here. What should I call a parameter that can a sinlge object or an iterable of objects? I have come up with two ideas, but I don't like ...
> I have some functions in my code that accept either an object or an iterable of objects as input. This is a very exceptional and often very bad thing to do. It's trivially avoidable. i.e., pass [foo] instead of foo when calling this function. The only time you can justify doing this is when (1) you have an install...
Getting non-contiguous text with lxml / ElementTree
3,683,997
3
2010-09-10T10:51:58Z
3,782,771
11
2010-09-23T21:45:30Z
[ "python", "html-parsing", "lxml", "elementtree" ]
Suppose I have this sort of HTML from which I need to select "text2" using lxml / ElementTree: ``` <div>text1<span>childtext1</span>text2<span>childtext2</span>text3</div> ``` If I already have the div element as mydiv, then mydiv.text returns just "text1". Using itertext() seems problematic or cumbersome at best si...
Well, lxml.etree provides full XPath support, which allows you to address the text items: ``` >>> import lxml.etree >>> fragment = '<div>text1<span>childtext1</span>text2<span>childtext2</span>text3</div>' >>> div = lxml.etree.fromstring(fragment) >>> div.xpath('./text()') ['text1', 'text2', 'text3'] ```
Peak detection in a 2D array
3,684,484
634
2010-09-10T12:12:25Z
3,684,652
8
2010-09-10T12:38:45Z
[ "python", "image-processing" ]
I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an exampl...
Just a couple of ideas off the top of my head: * take the gradient (derivative) of the scan, see if that eliminates the false calls * take the maximum of the local maxima You might also want to take a look at [OpenCV](http://opencv.willowgarage.com/wiki/), it's got a fairly decent Python API and might have some funct...
Peak detection in a 2D array
3,684,484
634
2010-09-10T12:12:25Z
3,684,808
7
2010-09-10T13:05:10Z
[ "python", "image-processing" ]
I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an exampl...
Here is an idea: you calculate the (discrete) Laplacian of the image. I would expect it to be (negative and) large at maxima, in a way that is more dramatic than in the original images. Thus, maxima could be easier to find. Here is another idea: if you know the typical size of the high-pressure spots, you can first sm...
Peak detection in a 2D array
3,684,484
634
2010-09-10T12:12:25Z
3,685,235
34
2010-09-10T14:09:34Z
[ "python", "image-processing" ]
I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an exampl...
### Solution Data file: [paw.txt](http://pastebin.com/XX3Egq7x). Source code: ``` from scipy import * from operator import itemgetter n = 5 # how many fingers are we looking for d = loadtxt("paw.txt") width, height = d.shape # Create an array where every element is a sum of 2x2 squares. fourSums = d[:-1,:-1] + d...
Peak detection in a 2D array
3,684,484
634
2010-09-10T12:12:25Z
3,685,653
23
2010-09-10T14:54:44Z
[ "python", "image-processing" ]
I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an exampl...
This is an [image registration problem](http://en.wikipedia.org/wiki/Image_registration). The general strategy is: * Have a known example, or some kind of *prior* on the data. * Fit your data to the example, or fit the example to your data. * It helps if your data is *roughly* aligned in the first place. **Here's a r...
Peak detection in a 2D array
3,684,484
634
2010-09-10T12:12:25Z
3,688,923
10
2010-09-10T22:49:13Z
[ "python", "image-processing" ]
I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an exampl...
This problem has been studied in some depth by physicists. There is a good implementation in [ROOT](http://root.cern.ch/drupal/). Look at the [TSpectrum](http://root.cern.ch/root/html526/TSpectrum.html) classes (especially [TSpectrum2](http://root.cern.ch/root/html526/TSpectrum2.html) for your case) and the documentati...
Peak detection in a 2D array
3,684,484
634
2010-09-10T12:12:25Z
3,689,710
213
2010-09-11T03:38:07Z
[ "python", "image-processing" ]
I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an exampl...
I detected the peaks using a **local maximum filter**. Here is the result on your first dataset of 4 paws: ![Peaks detection result](http://i.stack.imgur.com/Kgt4H.png) I also ran it on the second dataset of 9 paws and [it worked as well](http://i.stack.imgur.com/4CKCh.png). Here is how you do it: ``` import numpy a...
trying to install MySQL-python-1.2.3 but I get an error
3,685,111
3
2010-09-10T13:51:53Z
3,702,388
8
2010-09-13T16:28:48Z
[ "python", "mysql" ]
Here tis the error I get while trying to install MySQL-python-1.2.3. any idea's? ``` Traceback (most recent call last): File "C:\Documents and Settings\Desktop\MySQL-python-1.2.3\setup.py", line 15, in <module> metadata, options = get_config() File "C:\Documents and Settings\Desktop\MySQL-python-1.2.3\setup_window...
Please take a look at this page: <http://www.lfd.uci.edu/~gohlke/pythonlibs/> and search for "MySQL-python". You'll find some pre-compiled packages of MySQL-python for Windows. Maybe one of them will be ok for you. Using one of them (for Windows 7) was the only way I found to make MySQL-python work on Windows.
Line up columns of numbers (print output in table format)
3,685,195
8
2010-09-10T14:04:36Z
3,685,338
7
2010-09-10T14:20:26Z
[ "python" ]
I have data (numbers) saved in the following format (example): ``` 234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567 ... ``` Is there any python-way method to line up the numbers and get them as ``` 234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567 ``` (I cannot predict the...
You need some way of finding the column size, maybe by reading all the data and finding the maximum width. ``` >>> line='234 127 34 23 45567' >>> line.split() ['234', '127', '34', '23', '45567'] >>> max(map(len, line.split())) 5 ``` Repeat over all lines, to find column size (e.g., 5). Constructing a formatted line w...
Line up columns of numbers (print output in table format)
3,685,195
8
2010-09-10T14:04:36Z
3,685,943
12
2010-09-10T15:28:40Z
[ "python" ]
I have data (numbers) saved in the following format (example): ``` 234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567 ... ``` Is there any python-way method to line up the numbers and get them as ``` 234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567 ``` (I cannot predict the...
Here is a simple, self-contained example that shows how to format variable column widths: ``` data = '''\ 234 127 34 23 45567 23 12 4 4 45 23456 2 1 444 567''' # Split input data by row and then on spaces rows = [ line.strip().split(' ') for line in data.split('\n') ] # Reorganize data by columns cols = zip(*rows) ...
How to write a multidimensional array to a text file?
3,685,265
59
2010-09-10T14:13:21Z
3,685,295
19
2010-09-10T14:15:47Z
[ "python", "file-io", "numpy" ]
In another question, other users offered some help if I could supply the array I was having trouble with. However, I even fail at a basic I/O task, such as writing an array to a file. **Can anyone explain what kind of loop I would need to write a 4x11x14 numpy array to file?** This array consist of four 11 x 14 array...
I'm not certain if this meets your requirements, given I think you're interested in making the file readable by people, but if that's not a primary concern, just [`pickle`](http://docs.python.org/library/pickle.html) it. To save it: ``` import pickle my_data = {'a': [1, 2.0, 3, 4+6j], 'b': ('string', u'Un...
How to write a multidimensional array to a text file?
3,685,265
59
2010-09-10T14:13:21Z
3,685,339
113
2010-09-10T14:20:32Z
[ "python", "file-io", "numpy" ]
In another question, other users offered some help if I could supply the array I was having trouble with. However, I even fail at a basic I/O task, such as writing an array to a file. **Can anyone explain what kind of loop I would need to write a 4x11x14 numpy array to file?** This array consist of four 11 x 14 array...
If you want to write it to disk so that it will be easy to read back in as a numpy array, look into [`numpy.save`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html). Pickling it will work fine, as well, but it's less efficient for large arrays (which yours isn't, so either is perfectly fine). If you...
Python: Iterate a certain number of times without storing the iteration number anywhere
3,685,974
21
2010-09-10T15:32:22Z
3,686,000
25
2010-09-10T15:36:04Z
[ "python", "loops", "range" ]
I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere. For instance, let's say I want to print two "hello" messages on the console. Right now I know I can do: ``` for i in range(2): print "hello" ``` but then the "i" variable is going to ta...
The idiom (shared by quite a few other languages) for an unused variable is a single underscore `_`. Code analysers typically won't complain about `_` being unused, and programmers will instantly know it's a shortcut for `i_dont_care_wtf_you_put_here`. There is no way to iterate without having an item variable - as the...
Flask/Werkzeug, how to return previous page after login
3,686,465
20
2010-09-10T16:37:40Z
3,686,541
19
2010-09-10T16:48:01Z
[ "python", "login", "flask", "werkzeug" ]
I am using the Flask micro-framework which is based on Werkzeug, which uses Python. Before each restricted page there is a decorator to ensure the user is logged in, currently returning them to the login page if they are not logged in, like so: ``` # Decorator def logged_in(f): @wraps(f) def decorated_functio...
I think standard practice is to append the URL to which the user needs to be redirected after a successful login to the end of the login URL's querystring. You'd change your decorator to something like this (with redundancies in your decorator function also removed): ``` def logged_in(f): @wraps(f) def decora...
Flask/Werkzeug, how to return previous page after login
3,686,465
20
2010-09-10T16:37:40Z
3,689,851
11
2010-09-11T04:57:56Z
[ "python", "login", "flask", "werkzeug" ]
I am using the Flask micro-framework which is based on Werkzeug, which uses Python. Before each restricted page there is a decorator to ensure the user is logged in, currently returning them to the login page if they are not logged in, like so: ``` # Decorator def logged_in(f): @wraps(f) def decorated_functio...
You could use a query string to keep the file info intact over a click or two. One of the nice things about `url_for` is how it [passes unknown parameters as query strings](http://librelist.com/browser/flask/2010/4/26/implementing-list-with-sort-filter/#ac19ff7d428cd21b5013c978bad4c30e). So without changing your regist...
twisted: difference between `defer.execute` and `threads.deferToThread`
3,686,608
7
2010-09-10T16:56:20Z
3,686,693
9
2010-09-10T17:10:51Z
[ "python", "multithreading", "twisted", "deferred-execution" ]
What is the difference between `defer.execute()` and `threads.deferToThread()` in twisted? Both take the same arguments - a function, and parameters to call it with - and return a deferred which will be fired with the result of calling the function. The `threads` version explicitly states that it will be run in a thre...
defer.execute does indeed execute the function in a blocking manner, in the same thread and you are correct in that `defer.execute(f, args, kwargs)` does the same as `defer.succeed(f(*args, **kwargs))` **except** that `defer.execute` will return a callback that has had the errback fired if function **f** throws an exce...
Killing a program using multiprocessing
3,686,677
8
2010-09-10T17:07:18Z
3,686,703
16
2010-09-10T17:12:34Z
[ "python" ]
I'm using the multiprocessing module to do parallel processing in my program. When I'm testing it, I'll often want to kill the program early when I notice a bug, since it takes a while to run to completion. In my Linux environment, I run my program from a terminal, and use Ctrl+C to kill it. With multiprocessing, this ...
Hit Ctrl-Z to suspend the Python process, then do `kill %1` to kill it. You can also just hit Ctrl-\ (backslash), but that may cause the process to leave a core file.
CherryPy - saving checkboxes selection to variables
3,686,773
4
2010-09-10T17:23:45Z
3,688,508
7
2010-09-10T21:33:46Z
[ "python", "cherrypy", "checkbox" ]
I'm trying to build a simple webpage with multiple checkboxes, a Textbox and a submit buttom. I've just bumped into web programing in Python and am trying to figure out out to do it with CherryPy. I need to associate each checkbox to a variable so my .py file knows which ones were selected when clicking the 'Start bu...
Here's a minimal example: ``` import cherrypy class Root(object): @cherrypy.expose def default(self, **kwargs): print kwargs return '''<form action="" method="POST"> Host Availability: <input type="checkbox" name="goal" value="cpu" /> CPU idle <input type="checkbox" name="goal" value="lighttpd...
Python Sphinx autodoc and decorated members
3,687,046
21
2010-09-10T17:59:59Z
3,696,342
13
2010-09-12T19:52:47Z
[ "python", "decorator", "python-sphinx" ]
I am attempting to use Sphinx to document my Python class. I do so using autodoc: ``` .. autoclass:: Bus :members: ``` While it correctly fetches the docstrings for my methods, those that are decorated: ``` @checkStale def open(self): """ Some docs. """ # Code ``` with `@c...
To expand on my comment: > Have you tried using the decorator package and putting @decorator on checkStale? I had > a similar issue using epydoc with a decorated function. As you asked in your comment, the decorator package is not part of the standard library. You can fall back using code something like the followin...
Python Sphinx autodoc and decorated members
3,687,046
21
2010-09-10T17:59:59Z
15,693,082
10
2013-03-28T22:11:40Z
[ "python", "decorator", "python-sphinx" ]
I am attempting to use Sphinx to document my Python class. I do so using autodoc: ``` .. autoclass:: Bus :members: ``` While it correctly fetches the docstrings for my methods, those that are decorated: ``` @checkStale def open(self): """ Some docs. """ # Code ``` with `@c...
I had the same problem with the celery @task decorator. You can also fix this in your case by adding the correct function signature to your rst file, like this: ``` .. autoclass:: Bus :members: .. automethod:: open(self) .. automethod:: some_other_method(self, param1, param2) ``` It will still document ...
Make Python bool print 'On' or 'Off' rather than 'True' or 'False'
3,687,109
5
2010-09-10T18:07:51Z
3,687,134
10
2010-09-10T18:11:01Z
[ "python", "printing", "boolean" ]
What is the best way to make a variable that works exactly like a bool but prints `On` or `Off` rather than `True` or `False`? Currently the program is printing: `Color: True`, whereas `Color: On` would make more sense. For the record, I initially tried to make an `OnOff` class that inherits from `bool`: ``` class On...
``` def Color(object): def __init__(self, color_value=False): self.color_value = color_value def __str__(self): if self.color_value: return 'On' else: return 'Off' def __cmp__(self, other): return self.color_value.__cmp__(other.color_value) ``` Although ...
Make Python bool print 'On' or 'Off' rather than 'True' or 'False'
3,687,109
5
2010-09-10T18:07:51Z
3,687,180
16
2010-09-10T18:16:34Z
[ "python", "printing", "boolean" ]
What is the best way to make a variable that works exactly like a bool but prints `On` or `Off` rather than `True` or `False`? Currently the program is printing: `Color: True`, whereas `Color: On` would make more sense. For the record, I initially tried to make an `OnOff` class that inherits from `bool`: ``` class On...
`print ("Off", "On")[value]` works too (because `(False, True) == (0,1)`)
Change enclosing quotes in Vim
3,687,260
5
2010-09-10T18:27:24Z
3,687,276
18
2010-09-10T18:29:24Z
[ "python", "vim", "surround" ]
In Vim, it's a quick 3-character command to change what's inside the current quoted string (e.g., ci"), but is there a simple way to change what type of quotes are currently surrounding the cursor? Sometimes I need to go from "blah" to """blah""" or "blah" to 'blah' (in Python source code) and I'd ideally like to do i...
Try the [surround.vim](http://www.vim.org/scripts/script.php?script_id=1697) plugin. I find it an essential addition to any vim installation.
Python define dynamic functions
3,687,682
9
2010-09-10T19:25:57Z
3,687,711
14
2010-09-10T19:29:36Z
[ "python" ]
I have functions like this: ``` def activate_field_1(): print 1 def activate_field_2(): print 2 def activate_field_3(): print 3 ``` How do I define `activate_field_[x]` for `x=1:10`, without typing out each one of them? I'd much rather pass a parameter, of course, but for my purposes this is not possible. ...
Do you want to define these individually in your source file, statically? Then your best option would be to write a script to generate them. If on the other hand you want these functions at runtime you can use a higher order function. For e.g. ``` >>> def make_func(value_to_print): ... def _function(): ... ...
How to change a tuple into array in Python?
3,687,702
10
2010-09-10T19:28:09Z
3,687,716
44
2010-09-10T19:30:04Z
[ "python", "arrays", "tuples" ]
Let's say I have a tuple `t = (1,2,3,4)`. What's the simple way to change it into Array? I can do something like this, ``` array = [] for i in t: array.append(i) ``` But I prefer something like x.toArray() or something.
If you want to convert a tuple to a *list* (as you seem to want) use this: ``` >>> t = (1, 2, 3, 4) # t is the tuple (1, 2, 3, 4) >>> l = list(t) # l is the list [1, 2, 3, 4] ``` In addition I would advise against using `tuple`as the name of a variable.
How to get pydoc command working in Windows?
3,689,350
9
2010-09-11T00:59:31Z
24,156,676
16
2014-06-11T07:07:26Z
[ "python", "command-line", "command", "pydoc" ]
`pydoc` does not work in Windows. at this post <http://stackoverflow.com/questions/3391998/pydoc-is-not-working-windows-xp> the last answer by dave webb says to create a **pydoc.bat** file with this code in it: ``` @python c:\Python27\Lib\pydoc.py %* ``` After I create pydoc.bat where should it be placed so the `pydo...
Use `python -m pydoc os` instead of `pydoc` directly, no need to add to path variable. the -m tells python that pydoc is a pre-built module in python and NOT a script (.py file) sitting in the current working folder. See <https://docs.python.org/3/using/cmdline.html> for details
How is pip install using git different than just cloning a repository?
3,689,685
12
2010-09-11T03:28:58Z
3,691,652
25
2010-09-11T16:01:57Z
[ "python", "django", "pip" ]
I'm a beginner with Django and I'm having trouble installing django-basic-apps using pip. If I do this... ``` $ cat requirements.txt git+git://github.com/nathanborror/django-basic-apps.git $ pip install -r requirements.txt ``` I end up with `lib/python2.6/site-packages/basic/blog` that does NOT have a templates di...
When you use "pip" to install something, the package's `setup.py` is used to determine what packages to install. And this project's `setup.py`, if I'm reading it correctly, says "just install these Python packages inside the `basic` directory" — the `setup.py` makes absolutely no mention of any non-Python files it wa...
Merge SQLite files into one db file, and 'begin/commit' question
3,689,694
5
2010-09-11T03:32:31Z
3,689,929
11
2010-09-11T05:34:40Z
[ "python", "sqlite", "merge", "sqlite3" ]
[This post](http://stackoverflow.com/questions/80801/how-can-i-merge-many-sqlite-databases) refers to this [page](http://old.nabble.com/Attempting-to-merge-large-databases-td18131366.html) for merging SQLite databases. The sequence is as follows. Let's say I want to merge a.db and b.db. In command line I do the follow...
Apparently, `Cursor.execute` doesn't support the 'commit' command. It does support the 'begin' command but this is redundant because sqlite3 begins them for you anway: ``` >>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> cur = conn.cursor() >>> cur.execute('begin') <sqlite3.Cursor object at 0x0104B020> >>...
Writing white-space delimited text to be human readable in Python
3,689,936
4
2010-09-11T05:35:50Z
3,689,947
10
2010-09-11T05:40:23Z
[ "python", "whitespace", "human-readable" ]
I have a list of lists that looks something like this: ``` data = [['seq1', 'ACTAGACCCTAG'], ['sequence287653', 'ACTAGNACTGGG'], ['s9', 'ACTAGAAACTAG']] ``` I write the information to a file like this: ``` for i in data: for j in i: file.write('\t') file.write(j) file.write('\...
You need a format string: ``` for i,j in data: file.write('%-15s %s\n' % (i,j)) ``` `%-15s` means left justify a 15-space field for a string. Here's the output: ``` seq1 ACTAGACCCTAG sequence287653 ACTAGNACTGGG s9 ACTAGAAACTAG ```
What is the purpose of __str__ and __repr__ in Python?
3,691,101
33
2010-09-11T13:10:01Z
3,691,117
42
2010-09-11T13:14:17Z
[ "python" ]
I really don't understand where are `__str__` and `__repr__` used in Python. I mean, I get that `__str__` returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of `__repr__` But what I don't understand is, where would I use them?
[`__repr__`](http://docs.python.org/reference/datamodel.html#object.__repr__) > Called by the `repr()` built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to rec...
What is the purpose of __str__ and __repr__ in Python?
3,691,101
33
2010-09-11T13:10:01Z
3,691,121
7
2010-09-11T13:16:10Z
[ "python" ]
I really don't understand where are `__str__` and `__repr__` used in Python. I mean, I get that `__str__` returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of `__repr__` But what I don't understand is, where would I use them?
Grasshopper, when in doubt [go to the mountain](http://www.google.com/search?q=python+__repr__) and [read the Ancient Texts](http://docs.python.org/reference/datamodel.html#object.__repr__). In them you will find that \_\_repr\_\_() should: > If at all possible, this should look like a valid Python expression that cou...
What is the purpose of __str__ and __repr__ in Python?
3,691,101
33
2010-09-11T13:10:01Z
3,691,806
31
2010-09-11T16:48:15Z
[ "python" ]
I really don't understand where are `__str__` and `__repr__` used in Python. I mean, I get that `__str__` returns the string representation of an object. But why would I need that? In what use case scenario? Also, I read about the usage of `__repr__` But what I don't understand is, where would I use them?
The one place where you use them both a lot is in an interactive session. If you print an object then its `__str__` method will get called, whereas if you just use an object by itself then its `__repr__` is shown: ``` >>> from decimal import Decimal >>> a = Decimal(1.25) >>> print(a) 1.25 <---- this i...
Embedding Python in an iPhone app
3,691,655
81
2010-09-11T16:02:35Z
3,691,738
26
2010-09-11T16:23:59Z
[ "iphone", "python", "xcode" ]
So it's a new millennium; Apple has waved their hand; it's now legal to include a Python interpreter in an iPhone (App Store) app. How does one go about doing this? All the existing discussion (unsurprisingly) refers to jailbreaking. (Older question: [Can I write native iPhone apps using Python](http://stackoverflow.c...
It doesn't really matter how you build Python -- you don't need to build it in Xcode, for example -- but what does matter is the product of that build. Namely, you are going to need to build something like libPython.a that can be statically linked into your application. Once you have a .a, that can be added to the Xco...
Embedding Python in an iPhone app
3,691,655
81
2010-09-11T16:02:35Z
3,705,297
20
2010-09-14T00:06:26Z
[ "iphone", "python", "xcode" ]
So it's a new millennium; Apple has waved their hand; it's now legal to include a Python interpreter in an iPhone (App Store) app. How does one go about doing this? All the existing discussion (unsurprisingly) refers to jailbreaking. (Older question: [Can I write native iPhone apps using Python](http://stackoverflow.c...
I've put a very rough script up on github that fetches and builds python2.6.5 for iPhone and simulator. <http://github.com/cobbal/python-for-iphone> Work in progress Somewhat depressing update nearly 2 years later: (copied from README on github) > This project never really got python running on the iPhone to my > s...
Embedding Python in an iPhone app
3,691,655
81
2010-09-11T16:02:35Z
11,007,555
8
2012-06-13T02:42:04Z
[ "iphone", "python", "xcode" ]
So it's a new millennium; Apple has waved their hand; it's now legal to include a Python interpreter in an iPhone (App Store) app. How does one go about doing this? All the existing discussion (unsurprisingly) refers to jailbreaking. (Older question: [Can I write native iPhone apps using Python](http://stackoverflow.c...
I also started such a project. It comes with its own simplified compile script so there is no need to mess around with autoconf to get your cross compiled static library. It is able to build a completely dependency-free static library of Python with some common modules. It should be easily extensible. <https://github....
How should I do rapid GUI development for R and Octave methods (possibly with Python)?
3,691,944
20
2010-09-11T17:34:33Z
3,692,702
8
2010-09-11T21:19:23Z
[ "python", "user-interface", "octave" ]
We are a medium-sized academic research lab whose main outputs are new statistical methods for analyzing large datasets. We generally develop in R and MATLAB/Octave. We would like to expand the reach of our work by building simple, wizard-style user interfaces to access our methods, either web-apps like [RNAfold](http...
Why not continue to develop directly in R? There are a number of packages that allow you to develop GUIs (gWidgets RGtk, tcl/tk, RQt, Rwxwidgets, rjava) or [web applications](http://stackoverflow.com/questions/1397097/r-web-application-introduction).
How should I do rapid GUI development for R and Octave methods (possibly with Python)?
3,691,944
20
2010-09-11T17:34:33Z
3,694,299
8
2010-09-12T09:10:16Z
[ "python", "user-interface", "octave" ]
We are a medium-sized academic research lab whose main outputs are new statistical methods for analyzing large datasets. We generally develop in R and MATLAB/Octave. We would like to expand the reach of our work by building simple, wizard-style user interfaces to access our methods, either web-apps like [RNAfold](http...
I'd go with Python and PyQt4 for the UI, and use Rpy to interface to R. There's the QtDesigner for interface designing and you can generate python from that. QtAssistant gives you a fully hyperlinked documentation set for Qt which is the best I've ever used. Well worth it!
"%s" % format vs "{0}".format() vs "?" format
3,691,975
15
2010-09-11T17:45:15Z
3,692,022
17
2010-09-11T17:56:29Z
[ "python", "string-formatting", "pysqlite" ]
In this [post about SQLite](http://stackoverflow.com/questions/3689694/merge-sqlite-files-into-one-db-file-and-begin-commit-question), aaronasterling told me that * `cmd = "attach \"%s\" as toMerge" % "b.db"` : is wrong * `cmd = 'attach "{0}" as toMerge'.format("b.db")` : is correct * `cmd = "attach ? as toMerge"; cur...
``` "attach \"%s\" as toMerge" % "b.db" ``` You should use `'` instead of `"`, so you don't have to escape. You used the old formatting strings that are deprecated. ``` 'attach "{0}" as toMerge'.format("b.db") ``` This uses the new format string feature from newer Python versions that should be used instead of the ...
How do I redefine functions in python?
3,692,159
6
2010-09-11T18:37:02Z
3,692,197
8
2010-09-11T18:47:27Z
[ "django", "python" ]
I got a function in a certain module that I want to redefine(mock) at runtime for testing purposes. As far as I understand, function definition is nothing more than an assignment in python(the module definition itself is a kind of function being executed). As I said, I wanna do this in the setup of a test case, so the ...
``` import module1 import unittest class MyTest(unittest.TestCase): def setUp(self): # Replace othermod.function with our own mock self.old_func1 = module1.func1 module1.func1 = self.my_new_func1 def tearDown(self): module1.func1 = self.old_func1 def my_new_func1(self, x):...
In Python, how can I get the correctly-cased path for a file?
3,692,261
12
2010-09-11T19:06:43Z
3,788,191
8
2010-09-24T14:45:52Z
[ "python", "windows", "filenames" ]
Windows uses case-insensitive file names, so I can open the same file with any of these: ``` r"c:\windows\system32\desktop.ini" r"C:\WINdows\System32\DESKTOP.ini" r"C:\WiNdOwS\SyStEm32\DeSkToP.iNi" ``` etc. Given any of these paths, how can I find the true case? I want them all to produce: ``` r"C:\Windows\System32\...
Ned's `GetLongPathName` answer doesn't quite work (at least not for me). You need to call `GetLongPathName` on the return value of `GetShortPathname`. Using pywin32 for brevity (a ctypes solution would look similar to Ned's): ``` >>> win32api.GetLongPathName(win32api.GetShortPathName('stopservices.vbs')) 'StopServices...
Adding shared python packages to multiple virtualenvs
3,692,632
9
2010-09-11T20:59:33Z
3,692,811
10
2010-09-11T21:59:44Z
[ "python", "virtualenv", "pip", "virtualenvwrapper" ]
### Current Python Workflow I have [pip](http://pip.openplans.org/), [distribute](http://packages.python.org/distribute/), [virtualenv](http://virtualenv.openplans.org/), and [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/) installed into my Python 2.7 site-packages (a [framework Python ins...
Unless you are doing development on an embedded system, I find that chasing disk space in this way is always counter-productive. It took me a long time to reach this realization, because I grew up when a very large hard drive was a few megabytes in size, and RAM was measured in K. But today, unless you are under very s...
Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form
3,692,822
4
2010-09-11T22:01:20Z
3,694,474
8
2010-09-12T10:21:09Z
[ "python", "django", "django-admin", "many-to-many" ]
The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out. ``` class Galler...
Yes you are right, you have to wrap your widget with `django.contrib.admin.widgets.RelatedFieldWidgetWrapper`, which turns out to be a bit complicated since it expects the current admin site as a parameter for initialization! Maybe you will find this [post](https://groups.google.com/group/django-users/browse_thread/thr...
Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form
3,692,822
4
2010-09-11T22:01:20Z
3,694,736
9
2010-09-12T11:58:48Z
[ "python", "django", "django-admin", "many-to-many" ]
The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out. ``` class Galler...
With the help from lazerscience and this [post](https://groups.google.com/group/django-users/browse_thread/thread/5950235765d8e46a/c21bed1e9bdeab57?show_docid=c21bed1e9bdeab57) I ended up with the following. The ModelAdmin: ``` class GalleryAdmin(admin.ModelAdmin): form = GalleryForm def __init__(self, mode...
How should a ZeroMQ worker safely "hang up"?
3,692,854
19
2010-09-11T22:10:34Z
4,381,323
11
2010-12-07T20:36:35Z
[ "python", "concurrency", "message-queue", "rpc", "zeromq" ]
I started using ZeroMQ this week, and when using the Request-Response pattern I am not sure how to have a worker safely "hang up" and close his socket without possibly dropping a message and causing the customer who sent that message to never get a response. Imagine a worker written in Python who looks something like t...
You seem to think that you are trying to avoid a “simple” race condition such as in ``` ... = zmq_recv(fd); do_something(); zmq_send(fd, answer); /* Let's hope a new request does not arrive just now, please close it quickly! */ zmq_close(fd); ``` but I think the problem is that fair queuing (round-robin) makes th...
Why doesn't the save button work on a matplotlib plot?
3,692,928
10
2010-09-11T22:31:07Z
4,781,033
7
2011-01-24T10:41:34Z
[ "python", "matplotlib", "virtualenv" ]
I have [matplotlib 1.0.0](http://matplotlib.sourceforge.net/) installed in a Python 2.7 virtualenv on Mac OS X 10.6. I can create plots fine. However, whenever I press the *Save* button, I can't type text into the save dialog window nor can I save the plot. The only thing I can do is hit cancel. Any thoughts on what's ...
You need to convince OSX that the virtualenv is actually running from an Application Bundle. Fix discussed here: <http://groups.google.com/group/python-virtualenv/browse_thread/thread/83fa4a12d22a30c8/744e19c194f1618a> And implemented here: <https://github.com/gldnspud/virtualenv-pythonw-osx>
Django/python is converting my post data from JavaScript
3,693,621
3
2010-09-12T03:32:04Z
3,693,678
7
2010-09-12T03:57:57Z
[ "javascript", "python", "django", "json", "unicode" ]
When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending: ``` info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' } ``` Yet when I access it in the django request I am seeing: ``` u'{\'mid\':1,\'sid\':27,\'name\':\...
How are you encoding your JSON string? The single quotes need to be double quotes, per the [spec](http://json.org/): ``` In [40]: s1 = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }" In [41]: simplejson.loads(s1) JSONDecodeError: Expecting property name: line 1 column 1 (char 1) In [42]: s2 = '{"mid":1,"sid":2...
Trying to understand python with statement and context managers
3,693,771
11
2010-09-12T04:40:01Z
3,693,784
16
2010-09-12T04:46:40Z
[ "python", "contextmanager" ]
I am new to this, and am just trying to understand the `with` statement. I understand that it is supposed to replace the `try`/`except` block. Now suppose I do something like this: ``` try: name='rubicon'/2 # to raise an exception except Exception as e: print "no not possible" finally: print "Ok I caught you...
`with` doesn't really replace `try`/`except`, but, rather, `try`/`finally`. Still, you *can* make a context manager do something different in exception cases from non-exception ones: ``` class Mgr(object): def __enter__(self): pass def __exit__(self, ext, exv, trb): if ext is not None: print "no not po...
Trying to understand python with statement and context managers
3,693,771
11
2010-09-12T04:40:01Z
3,693,785
11
2010-09-12T04:47:15Z
[ "python", "contextmanager" ]
I am new to this, and am just trying to understand the `with` statement. I understand that it is supposed to replace the `try`/`except` block. Now suppose I do something like this: ``` try: name='rubicon'/2 # to raise an exception except Exception as e: print "no not possible" finally: print "Ok I caught you...
The `with` in Python is intended for wrapping a set of statements where you should set up and destroy or close resources. It is in a way similar to `try...finally` in that regard as the finally clause will be executed even after an exception. A context manager is an object that implements two methods: `__enter__` and ...
Trying to understand python with statement and context managers
3,693,771
11
2010-09-12T04:40:01Z
18,003,208
13
2013-08-01T19:48:18Z
[ "python", "contextmanager" ]
I am new to this, and am just trying to understand the `with` statement. I understand that it is supposed to replace the `try`/`except` block. Now suppose I do something like this: ``` try: name='rubicon'/2 # to raise an exception except Exception as e: print "no not possible" finally: print "Ok I caught you...
The [contextlib.contextmanager](http://docs.python.org/2.7/library/contextlib.html#contextlib.contextmanager) function decorator provides a handy way of providing a context manager without the need to write a full-fledged `ContextManager` class of your own (with `__enter__` and `__exit__` methods, so you don't have to ...
How do I initialize the base (super) class in Python?
3,694,371
61
2010-09-12T09:43:50Z
3,694,385
22
2010-09-12T09:49:11Z
[ "python" ]
In Python, consider I have the following code: ``` >>> class SuperClass(object): def __init__(self, x): self.x = x >>> class SubClass(SuperClass): def __init__(self, y): self.y = y # how do I initialize the SuperClass __init__ here? ``` How do I initialize the `SuperClass __init__` i...
Both ``` SuperClass.__init__(self, x) ``` or ``` super(SubClass,self).__init__( x ) ``` will work (I prefer the 2nd one, as it adheres more to the DRY principle). See here: <http://docs.python.org/reference/datamodel.html#basic-customization>
How do I initialize the base (super) class in Python?
3,694,371
61
2010-09-12T09:43:50Z
3,694,393
87
2010-09-12T09:52:55Z
[ "python" ]
In Python, consider I have the following code: ``` >>> class SuperClass(object): def __init__(self, x): self.x = x >>> class SubClass(SuperClass): def __init__(self, y): self.y = y # how do I initialize the SuperClass __init__ here? ``` How do I initialize the `SuperClass __init__` i...
Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from 'object' and are what you are using, and invoke their base class through super(), e.g. ``` class X(object): def __init__(self, x): pass def doit(self, bar): pass class Y(X): def __init__(self): s...
Initialize a datetime object with seconds since epoch
3,694,487
121
2010-09-12T10:28:52Z
3,694,496
201
2010-09-12T10:33:04Z
[ "python", "datetime", "date", "time", "epoch" ]
The `time` module can be initialized using seconds since epoch: ``` >>> import time >>> t1=time.gmtime(1284286794) >>> t1 time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0) ``` Is there an elegant way to initialize a `datetime.d...
[`datetime.datetime.fromtimestamp`](http://docs.python.org/library/datetime.html#datetime.datetime.fromtimestamp) will do, if you know the time zone, you could produce the same output as with `time.gmtime` ``` >>> datetime.datetime.fromtimestamp(1284286794) datetime.datetime(2010, 9, 12, 11, 19, 54) ``` or ``` >>> d...
Initialize a datetime object with seconds since epoch
3,694,487
121
2010-09-12T10:28:52Z
15,188,866
15
2013-03-03T18:03:28Z
[ "python", "datetime", "date", "time", "epoch" ]
The `time` module can be initialized using seconds since epoch: ``` >>> import time >>> t1=time.gmtime(1284286794) >>> t1 time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0) ``` Is there an elegant way to initialize a `datetime.d...
Seconds since epoch to [`datetime`](http://docs.python.org/2/library/datetime.html#datetime.datetime) to [`strftime`](http://docs.python.org/2/library/datetime.html#datetime.datetime.strftime): ``` >>> ts_epoch = 1362301382 >>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S') >>> ts '2013-0...
selenium.wait_for_condition equivalent in Python bindings for WebDriver
3,694,508
8
2010-09-12T10:37:18Z
8,089,040
8
2011-11-11T02:38:03Z
[ "python", "selenium", "webdriver" ]
I'm moving some tests from Selenium to the WebDriver. My problem is that I can't find an equivalent for selenium.wait\_for\_condition. Do the Python bindings have this at the moment, or is it still planned?
Currently it isn't possible to use wait\_for\_condition with WebDriver. The python selenium code does provide the DrivenSelenium class for accessing the old selenium methods, but it can't do wait\_for\_condition. [The selenium wiki has some info on that](http://code.google.com/p/selenium/wiki/SeleniumEmulation). Your ...
Global static variables in Python
3,694,580
3
2010-09-12T11:03:04Z
3,694,600
11
2010-09-12T11:10:48Z
[ "python", "variables", "static", "global" ]
``` def Input(): c = raw_input ('Enter data1,data2: ') data = c.split(',') return data ``` I need to use list `data` in other functions, but I don't want to enter `raw_input` everytime. How I can make `data` like a **global static** in c++ and put it everywhere where it needed?
Add a single line to your function: ``` def Input(): global data c = raw_input ('Enter data1,data2: ') data = c.split(',') return data ``` The `global data` statement is a declaration that makes `data` a global variable. After calling `Input()` you will be able to refer to `data` in other functions.
Python 2.6.5: Divide timedelta with timedelta
3,694,835
13
2010-09-12T12:35:02Z
3,694,895
23
2010-09-12T12:51:20Z
[ "python", "division", "timedelta" ]
I'm trying to divide one `timedelta` object with another to calculate a server uptime: ``` >>> import datetime >>> installation_date=datetime.datetime(2010,8,01) >>> down_time=datetime.timedelta(seconds=1400) >>> server_life_period=datetime.datetime.now()-installation_date >>> down_time_percentage=down_time/server_lif...
In Python ≥2.7, there is [a `.total_seconds()` method](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds) to compute the total seconds contained in the timedelta: ``` >>> down_time.total_seconds() / server_life_period.total_seconds() 0.0003779903727652387 ``` Otherwise, there is no way b...
how to extract frequency associated with fft values in python
3,694,918
16
2010-09-12T12:59:43Z
3,695,448
31
2010-09-12T15:45:56Z
[ "python", "numpy", "fft" ]
I used `fft` function in numpy which resulted in a complex array. How to get the exact frequency values?
`np.fft.fftfreq` tells you the frequencies associated with the coefficients: ``` import numpy as np x = np.array([1,2,1,0,1,2,1,0]) w = np.fft.fft(x) freqs = np.fft.fftfreq(len(x)) for coef,freq in zip(w,freqs): if coef: print('{c:>6} * exp(2 pi i t * {f})'.format(c=coef,f=freq)) # (8+0j) * exp(2 pi i t...
Python: module for plotting Gantt charts
3,695,117
19
2010-09-12T14:03:26Z
3,695,220
10
2010-09-12T14:42:21Z
[ "python", "gantt-chart" ]
Is there a good Python module for plotting [Gantt Charts](http://en.wikipedia.org/wiki/Gantt_chart)? I've tried [CairoPlot](http://linil.wordpress.com/2008/09/16/cairoplot-11/), but it produces buggy results for complex data sets and lacks many configuration options. Code samples and images are highly appreciated. Th...
ChartDirector is pretty good at generating advanced charts of all kinds. It has decent python bindings, but it's, unfortunately, not native python or open source in general. There are actually some [Gantt chart examples/screenshots](http://www.advsofteng.com/gallery_gantt.html). The code also includes python demo's fo...
Efficient way to create a diagonal sparse matrix
3,695,434
5
2010-09-12T15:43:23Z
3,695,528
7
2010-09-12T16:06:30Z
[ "python", "numpy", "scipy", "sparse-matrix" ]
I have the following code in Python using Numpy: ``` p = np.diag(1.0 / np.array(x)) ``` How can I transform it to get the sparse matrix `p2` with the same values as `p` without creating `p` first?
Use [`scipy.sparse.spdiags`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.spdiags.html#scipy.sparse.spdiags) (which does a lot, and so may be confusing, at first), [`scipy.sparse.dia_matrix`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.dia_matrix.html#scipy.sparse.dia_matrix) an...
Check if I can write a file to a directory or not with Python
3,696,080
6
2010-09-12T18:47:00Z
3,696,146
7
2010-09-12T19:03:28Z
[ "python", "exception", "file-access" ]
I need to check if I can write a file to a directory that user point to with Python. Is there an way to check it in advance? I may be using try .. catch for this purpose, but I expect something better in the sense that I can check in advance.
Despite Jim Brissom's claim, exception handling is *not* cheap in Python compared to 'check then try' idioms if you expect the thing to fail more than a few percent of the time. (Read to the end for an exception!) However, the key thing here is that you need to check the exception anyway, because the permissions can ch...
SWIG - Problem with namespaces
3,696,084
3
2010-09-12T18:48:31Z
3,762,478
8
2010-09-21T16:39:21Z
[ "c++", "python", "osx", "namespaces", "swig" ]
I'm having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I don't wrap it in a namespace, but as soon as I do I get a compilation error in the generated **test\_wrap.c**. test.h: ``` #ifndef __TEST_H__ #def...
In your test.i file, add a "using namespace ns" line after the #include. Without that, your swig wrapper code won't know to look for Foo in the "ns" namespace.
How to know the directory where the python script is called?
3,696,223
6
2010-09-12T19:25:09Z
3,696,230
9
2010-09-12T19:26:11Z
[ "python", "path" ]
Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py. * In a.py, how to detect /X/Y/? I mean, how to know in which directory the python call is made?
You can get the current working directory with: os.getcwd()
print colorful string out to console with python
3,696,430
5
2010-09-12T20:15:07Z
3,696,436
8
2010-09-12T20:16:44Z
[ "python", "string", "printing" ]
Is there a way to print string in colorful way with python? For example, can I print some part of string red or something to a console? I use Mac OS X.
You could use [colorama](http://pypi.python.org/pypi/colorama), but use it sparingly.
How to solve import errors while trying to deploy Flask using WSGI on Apache2
3,696,606
26
2010-09-12T21:02:06Z
3,696,785
24
2010-09-12T21:45:00Z
[ "python", "apache", "wsgi", "flask" ]
I am having an issue deploying a flask app on apache2 using wsgi. I have posted the error logs and config files below. I have tried moving things around, renaming them, etc, but all give me an internal server error. Not sure why I'm getting the import error. Any input / suggestions are appreciated, thanks! Here is my ...
Thanks to `zarf` and `damjan` on irc.freenode.org at #pocoo, they were able to help me get this fixed. The problem was the PythonPath was not correct. We fixed this by using the following wsgi.py ``` import sys sys.path.insert(0, "/sites/flaskfirst") from app import app application = app ```
Reading a CR2 (Raw Canon Image) header using Python
3,696,642
9
2010-09-12T21:14:43Z
3,696,783
7
2010-09-12T21:44:48Z
[ "python", "image-processing", "metadata", "binary-data" ]
I'm trying to extract the date/time when a picture was taken from the CR2 (Canon format for raw pictures). I know the [CR2 specification](http://lclevy.free.fr/cr2/), and I know I can use Python [struct](http://docs.python.org/library/struct.html) module to extract pieces from a binary buffer. Briefly, the specificat...
Have you taken into account the header which should (according to the spec) precede the IFD block you're talking about? I looked through the spec and it says the first IFD block follows the 16 byte header. So if we read bytes 16 and 17 (at offset 0x10 hex) we should get the number of entries in the first IFD block. Th...
python: does `for i in obj.func()` re-run `func` every iteration?
3,696,992
2
2010-09-12T22:57:43Z
3,697,003
7
2010-09-12T23:02:15Z
[ "python", "optimization", "loops", "for-loop" ]
let's say I have the following code: ``` for a in object.a_really_huge_function(): print a ``` In order to prevent `a_really_huge_function` from running multiple times, I am used to doing this in other languages: ``` a_list = object.a_really_huge_function() for a in a_list: print a ``` Is that necessary in ...
The python interpreter is your friend. ``` >>> def some_func(): ... print 'in some_func' ... return [1, 2, 3, 10] ... >>> for a in some_func(): ... print a ... in some_func 1 2 3 10 ``` In short, no, it gets called once.
How to find list intersection?
3,697,432
40
2010-09-13T01:30:14Z
3,697,438
89
2010-09-13T01:32:48Z
[ "python" ]
``` a = [1,2,3,4,5] b = [1,3,5,6] c = a and b print c ``` actual output: `[1,3,5,6]` expected output: `[1,3,5]` How can we achieve a boolean AND operation (list intersection) on two lists?
If order is not important and you don't need to worry about duplicates then you can use set intersection: ``` >>> a = [1,2,3,4,5] >>> b = [1,3,5,6] >>> list(set(a) & set(b)) [1, 3, 5] ```
How to find list intersection?
3,697,432
40
2010-09-13T01:30:14Z
3,697,448
10
2010-09-13T01:35:49Z
[ "python" ]
``` a = [1,2,3,4,5] b = [1,3,5,6] c = a and b print c ``` actual output: `[1,3,5,6]` expected output: `[1,3,5]` How can we achieve a boolean AND operation (list intersection) on two lists?
Make a set out of the larger one: ``` _auxset = set(a) ``` Then, ``` c = [x for x in b if x in _auxset] ``` will do what you want (preserving `b`'s ordering, not `a`'s -- can't necessarily preserve *both*) and do it *fast*. (Using `if x in a` as the condition in the list comprehension would also work, and avoid the...
How to find list intersection?
3,697,432
40
2010-09-13T01:30:14Z
3,697,450
21
2010-09-13T01:36:19Z
[ "python" ]
``` a = [1,2,3,4,5] b = [1,3,5,6] c = a and b print c ``` actual output: `[1,3,5,6]` expected output: `[1,3,5]` How can we achieve a boolean AND operation (list intersection) on two lists?
If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using `intersection()`: ``` a = [1,2,3,4,5] b = [1,3,5,6] set(a).intersection(b) ```
How can I get better error information with try/catch in Python
3,697,452
8
2010-09-13T01:37:50Z
3,697,502
8
2010-09-13T02:02:02Z
[ "python", "error-handling" ]
Consider this try/catch block I use for checking error message stored in `e`. ### Try/Catch to get the `e` ``` queryString = "SELECT * FROM benchmark WHERE NOC = 2" try: res = db.query(queryString) except SQLiteError, e: # `e` has the error info print `e` ``` The `e` object here contains nothing more t...
This will show the trace to the error. ``` import traceback try: res = db.query(queryString) except SQLiteError, e: # `e` has the error info print `e` for tb in traceback.format_tb(sys.exc_info()[2]): print tb ```
Is there a functional programming idiom for filtering a list into trues and falses?
3,697,556
7
2010-09-13T02:27:06Z
3,697,584
9
2010-09-13T02:36:35Z
[ "python", "functional-programming", "filter" ]
Say you have some list `L` and you want to split it into two lists based on some boolean function `P`. That is, you want one list of all the elements `l` where `P(l)` is true and another list where `P(l)` is false. I can implement this in Python like so: ``` def multifilter(pred,seq): trues,falses = [],[] for...
From itertools examples: ``` from itertools import tee, filterfalse def partition(pred, iterable): t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2) ```
prefer windows or unix line ending for code?
3,698,084
4
2010-09-13T05:56:23Z
3,698,117
9
2010-09-13T06:03:26Z
[ "c++", "python", "multiplatform", "line-endings" ]
I writing code that should compiled and run on both Windows and unix like Linux. I know about difference between line endings, but question is **which to prefer** for my code? Does it matter? I want it to be consistent - say all my code uses LF only, or is it better CRLF only? Are there critaria for comparing? If it m...
Use a version control system that's smart enough to ignore line-endings on check-in, and use the correct value for the platform on check-out.
Getting cursor position in Python
3,698,635
13
2010-09-13T07:52:42Z
3,698,659
11
2010-09-13T07:55:49Z
[ "python", "windows" ]
Is it possible to get the overall cursor position in Windows using the standard Python libraries?
``` win32gui.GetCursorPos(point) ``` This retrieves the cursor's position, in screen coordinates - point = (x,y) ``` flags, hcursor, (x,y) = win32gui.GetCursorInfo() ``` Retrieves information about the global cursor. Links: * <http://msdn.microsoft.com/en-us/library/ms648389(VS.85).aspx> * <http://msdn.microsoft.c...
Getting cursor position in Python
3,698,635
13
2010-09-13T07:52:42Z
24,567,802
7
2014-07-04T06:15:51Z
[ "python", "windows" ]
Is it possible to get the overall cursor position in Windows using the standard Python libraries?
Using the standard ctypes library, this should yeild the current on screen mouse coordinates without any third party modules: ``` from ctypes import windll, Structure, c_ulong, byref class POINT(Structure): _fields_ = [("x", c_ulong), ("y", c_ulong)] def queryMousePosition(): pt = POINT() windll.user3...
Python, Django, how to use getattr (or other method) to call object that has multiple attributes?
3,698,845
5
2010-09-13T08:33:56Z
3,698,861
11
2010-09-13T08:37:05Z
[ "python", "django", "object", "code-reuse", "getattr" ]
After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner: the way I do it that works (non-g...
You forgot to call the result. ``` dbobject = mymodel.objects.all() ``` Accesses the method `mymodel.objects.all` and then calls it. ``` ret = getattr(mymodel,'objects') self.dbobject = getattr(ret,'all') ``` accesses the method `mymodel.objects.all` but does not call it. All you need is to change the last line to...
How to add Autoscroll on insert in Tkinter Listbox?
3,699,104
3
2010-09-13T09:20:42Z
3,699,952
9
2010-09-13T11:29:05Z
[ "python", "listbox", "scrollbar", "tkinter" ]
I'm using a listbox (with scrollbar) for logging: ``` self.listbox_log = Tkinter.Listbox(root, height = 5, width = 0,) self.scrollbar_log = Tkinter.Scrollbar(root,) self.listbox_log.configure(yscrollcommand = self.scrollbar_log.set) self.scrollbar_log.configure(command = self.listbox_log.yview) ``` Now, when I do: ...
AFAIK the ScrollBar widget doesn't have an auto-scroll feature, but it can be easily implemented by calling the `listBox`'s `yview()` method after you insert a new item. If you need the new item to be selected then you can do that manually too using the `listbox`'s `select_set` method. ``` from Tkinter import * class...
Python bizarre class problem
3,699,440
5
2010-09-13T10:11:27Z
3,699,492
7
2010-09-13T10:19:28Z
[ "python", "override" ]
I have the following piece of code where I try to override a method: ``` import Queue class PriorityQueue(Queue.PriorityQueue): def put(self, item): super(PriorityQueue, self).put((item.priority, item)) ``` However, when I run it I get `TypeError` exception: ``` super() argument 1 must be type, not class...
`Queue.PriorityQueue` is not a new-style class, and `super` [only works with new-style classes](http://docs.python.org/library/functions.html#super). You must use ``` import Queue class PriorityQueue(Queue.PriorityQueue): def put(self, item): Queue.PriorityQueue.put(self,(item.priority, item)) ``` instead...
SQLAlchemy memory hog on select statement
3,699,532
8
2010-09-13T10:26:23Z
3,699,677
10
2010-09-13T10:47:02Z
[ "python", "sqlalchemy" ]
As per the SQLAlchemy, select statements are treated as iterables in for loops. The effect is that a select statement that would return a massive amount of rows does not use excessive memory. I am finding that the following statement on a MySQL table: ``` for row in my_connections.execute(MyTable.__table__.select()):...
The basic `MySQLdb` cursor fetches the entire query result at once from the server. This can consume a lot of memory and time. Use [MySQLdb.cursors.SSCursor](http://mysql-python.sourceforge.net/MySQLdb.html) when you want to make a huge query and pull results from the server one at a time. Therefore, try passing `conn...
Word sense disambiguation in NLTK Python
3,699,810
19
2010-09-13T11:04:26Z
3,952,286
7
2010-10-17T06:41:33Z
[ "python", "nltk" ]
I am new to NLTK Python and i am looking for some sample application which can do word sense disambiguation. I have got a lot of algorithms in search results but not a sample application. I just want to pass a sentence and want to know the sense of each word by referring to wordnet library. Thanks I have found a simil...
Refer <http://jaganadhg.freeflux.net/blog/archive/2010/10/16/wordnet-sense-similarity-with-nltk-some-basics.html>
Word sense disambiguation in NLTK Python
3,699,810
19
2010-09-13T11:04:26Z
8,594,816
7
2011-12-21T18:49:57Z
[ "python", "nltk" ]
I am new to NLTK Python and i am looking for some sample application which can do word sense disambiguation. I have got a lot of algorithms in search results but not a sample application. I just want to pass a sentence and want to know the sense of each word by referring to wordnet library. Thanks I have found a simil...
Yes, in fact, there is [a book](http://www.nltk.org/book/) that the NLTK team wrote which has multiple chapters on classification and they explicitly cover [how to use WordNet](http://www.nltk.org/book/ch02.html#wordnet). You can also buy a physical version of the book from Safari. FYI: NLTK is written by natural lang...
Getting formatted datetime in Python like in PHP
3,700,118
2
2010-09-13T11:52:39Z
3,700,226
7
2010-09-13T12:07:58Z
[ "php", "python", "datetime", "time" ]
How to get formatted date time in Python the same way as in PHP `date('M d Y', $timestamp);`?
``` >>> import time >>> timestamp = 1284375159 >>> time.strftime("%m %d %Y",time.localtime(timestamp)) '09 13 2010' ```
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
3,701,722
8
2010-09-13T15:13:00Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
You need to add to your **PYTHONPATH** variable instead of Windows **PATH** variable. <http://docs.python.org/using/windows.html>
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
3,701,730
31
2010-09-13T15:14:09Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
From Windows command line: ``` set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib ``` To set the PYTHONPATH permanently, add the line to your `autoexec.bat`. Alternatively, if you edit the system variable through the System Properties, it will also be changed permanently.
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
3,702,243
38
2010-09-13T16:11:38Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this: ``` import sys if "C:\\My_Python_Lib" not in sys.path: sys.path.append("C:\\My_Python_Lib") ``` That should take care of your problems
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
4,855,685
216
2011-01-31T20:23:05Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
You know what has worked for me really well on windows. `My Computer > Properties > Advanced System Settings > Environment Variables >` Then under system variables I create a new Variable called `PythonPath`. In this variable I have `C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-foolder-on-the-path...
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
14,656,842
10
2013-02-01T23:31:55Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
You can also add a `.pth` file containing the desired directory in either your `c:\PythonX.X` folder, or your `\site-packages folder`, which tends to be my preferred method when I'm developing a Python package. See [here](http://bob.ippoli.to/archives/2005/02/06/using-pth-files-for-python-development/) for more inform...
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
14,753,412
54
2013-02-07T14:26:21Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
**Just append** your installation path (ex. **C:\Python27\**) to the **PATH** variable in **System variables**. Then close and open your **command line and type 'python'**.
How to add to the pythonpath in windows 7?
3,701,646
153
2010-09-13T15:04:26Z
21,433,154
49
2014-01-29T13:55:24Z
[ "python", "windows", "environment-variables", "pythonpath" ]
I have a directory which hosts all of my Django apps (`C:\My_Projects`). I want to add this directory to my `pythonpath` so I can call the apps directly. I have tried adding `C:\My_Projects\;` to my `Path` variable from the Windows GUI (`My Computer > Properties > Advanced System Settings > Environment Variables`). Bu...
Windows 7 Professional I Modified @mongoose\_za's answer to make it easier to change the python version: 1. [Right Click]Computer > Properties >Advanced System Settings > Environment Variables 2. Click [New] under "System Variable" 3. Variable Name: PY\_HOME, Variable Value:C:\path\to\python\version ![enter image d...