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
Use regular expressions to replace overlapping subpatterns
15,301,832
8
2013-03-08T19:32:45Z
15,301,961
16
2013-03-08T19:40:52Z
[ "python", "regex" ]
I have the following regular expression substitution: ``` input=re.sub( r"([a-zA-Z0-9])\s+([a-zA-Z0-9])" , r"\1*\2" , input ) ``` I use the regular expression on the string `"3 a 5 b"`. I get back `"3*a 5*b"`. I am thinking I should get back `"3*a*5*b"`. So somehow my regular expression substitutions are interferi...
Use a [lookahead assertion](http://docs.python.org/2/library/re.html#regular-expression-syntax), `(?=...)`, so as not to eat up the second pattern: ``` In [33]: re.sub( r"([a-zA-Z0-9])\s+(?=[a-zA-Z0-9])" , r"\1*" , '3 a 5 b') Out[33]: '3*a*5*b' In [32]: re.sub( r"([a-zA-Z0-9])\s+(?=[a-zA-Z0-9])" , r"\1*" , "3 /a 5! b...
Python 2.x - default arguments with *args and **kwargs
15,301,999
37
2013-03-08T19:43:12Z
15,302,038
29
2013-03-08T19:45:23Z
[ "python", "python-2.7" ]
In **Python 2.x** (I use 2.7), which is the proper way to use default arguments with `*args` and `**kwargs`? I've found a question on SO related to this topic, but that is for **Python 3**: [Calling a Python function with \*args,\*\*kwargs and optional / default arguments](http://stackoverflow.com/questions/9872824...
The syntax in the other question is python3.x only and specifies keyword only arguments. It doesn't work on python2.x. For python2.x, I would `pop` it out of kwargs: ``` def func(arg1,arg2,*args,**kwargs): opt_arg = kwargs.pop('opt_arg','def_val') ```
Python 2.x - default arguments with *args and **kwargs
15,301,999
37
2013-03-08T19:43:12Z
15,302,042
32
2013-03-08T19:45:36Z
[ "python", "python-2.7" ]
In **Python 2.x** (I use 2.7), which is the proper way to use default arguments with `*args` and `**kwargs`? I've found a question on SO related to this topic, but that is for **Python 3**: [Calling a Python function with \*args,\*\*kwargs and optional / default arguments](http://stackoverflow.com/questions/9872824...
Just put the default arguments before the `*args`: ``` def foo(a, b=3, *args, **kwargs): ``` Now, `b` will be explicitly set if you pass it as a keyword argument or the second positional argument. Examples: ``` foo(x) # a=x, b=3, args=(), kwargs={} foo(x, y) # a=x, b=y, args=(), kwargs={} foo(x, b=y) # a=x, b=y, ar...
HTML encoding and lxml parsing
15,302,125
7
2013-03-08T19:50:46Z
15,305,248
14
2013-03-08T23:44:05Z
[ "python", "unicode", "web-scraping", "beautifulsoup", "lxml" ]
I'm trying to finally solve some encoding issues that pop up from trying to scrape HTML with lxml. Here are three sample HTML documents that I've encountered: 1. ``` <!DOCTYPE html> <html lang='en'> <head> <title>Unicode Chars: 은 —’</title> <meta charset='utf-8'> </head> <body></body> </html> ``` 2. ```...
`lxml` has [several](https://github.com/lxml/lxml/issues/94) [issues](https://github.com/lxml/lxml/pull/51) related to handling Unicode. It might be best to use bytes (for now) while specifying the character encoding explicitly: ``` #!/usr/bin/env python import glob from lxml import html from bs4 import UnicodeDammit ...
How to apply function to only certain array elements?
15,303,043
4
2013-03-08T20:49:23Z
15,303,168
9
2013-03-08T20:58:10Z
[ "python", "numpy", "indexing" ]
I have an array `x` and I want to apply a function `f` to every item in the matrix that meets some condition. Does Numpy offer a mechanism to make this easy? Here's an example. My matrix `x` is supposed to contain only elements in the exclusive range `(0, 1)`. However, due to rounding errors, some elements can be equa...
You can do this: ``` a = np.array([0,.1,.5,1]) epsilon = 1e-5 a[a==0] += epsilon a[a==1] += -epsilon ``` The reason this works is that `a==0` returns a boolean array, just like what [Валера Горбунов](http://stackoverflow.com/users/2149700/) referred to in their answer: ``` In : a==0 Out: array([True, F...
Django User table as Foreign Key
15,303,686
3
2013-03-08T21:32:25Z
15,303,714
7
2013-03-08T21:34:43Z
[ "python", "django", "web" ]
I'm a new user to Django and am just starting my first app, "myapp". In my models.py for my app I have the following model: ``` class Subcalendar(models.Model): user = models.ForeignKey(User) ``` But when I try running: ``` python manage.py sql myapp ``` I get an error stating: ``` NameError: name 'User' is not...
You need import the `User` model at the top of your file ``` from django.contrib.auth.models import User ``` so python can resolve the reference.
Python: Fibonacci Sequence
15,305,362
9
2013-03-08T23:56:12Z
15,305,412
11
2013-03-09T00:00:41Z
[ "python", "fibonacci" ]
I'm just trying to improve my programming skill by making some basic functions. I want to fill a list with fibonacci values, but I think my code gives the sum of all the numbers put together and prints that instead.. ``` numberlist = [] i = 0 for i in range(20): numberlist.append(i) print numberlist fibonaccinu...
``` print a ``` Well, you print the final value. --- Also some more comments on your code: ``` numberlist = [] i = 0 for i in range(20): numberlist.append(i) ``` You don’t need to initialize `i` there, the for loop does that for you. Also, you can simplify the whole block by just doing this: ``` numberlist ...
pick combinations from multiple lists
15,305,719
4
2013-03-09T00:33:59Z
15,305,799
7
2013-03-09T00:44:40Z
[ "python", "python-2.7" ]
I am new to python and I am struggling to form a combination of multiple lists. So, I have three (and possible more) looking like this: ``` uk_rock_stars=[1,2,3,4,5,6,7,8,9] uk_pop_stars=[10,11,12,13,1,4,6,22,81] us_stars=[22,34,44,7,33,99,22,77,99] . . ``` with all lists of the same length. Now, I would like to gene...
Read over this <http://docs.python.org/2/library/itertools.html#itertools.product>, it explains everything. `itertools` is a package that has a bunch of useful functionality for iterating over collections. One useful feature is the `product` function which creates a generator that will iterate over the cartesian produ...
Python matplotlib decrease size of colorbar labels
15,305,737
26
2013-03-09T00:36:12Z
15,305,969
77
2013-03-09T01:06:50Z
[ "python", "attributes", "matplotlib", "labels", "colorbar" ]
I need your help! I have a plotting code which is the following: ``` fig = plt.figure() ax1 = fig.add_subplot(111) imax1 = ax1.imshow(data,interpolation = 'nearest', origin = 'lower',cmap=cm.jet)#plot cbar = plt.colorbar(imax1, extend='neither', spacing='proportional', orientation='vertical', shrink=0...
Aha! Found the answer [here](http://stackoverflow.com/a/6568248/1062948): ``` cbar.ax.tick_params(labelsize=10) ``` P.S. Upvote [that](http://stackoverflow.com/a/6568248/943773) answer and give Paul some love!
How to execute process in Python where data is written to stdin?
15,305,843
6
2013-03-09T00:49:01Z
15,306,001
7
2013-03-09T01:11:58Z
[ "python", "subprocess", "stdout", "stdin", "io-redirection" ]
I have a flag in my Python script which specifies whether I setup and use an external process or not. This process is a command called `my_command` and it takes data from standard input. If I was to run this on the command-line, it would be something like: ``` $ my_command < data > result ``` I want to use a Python s...
After writing to the stdin, you need to close it: ``` process.stdin.write(modified_line) process.stdin.close() ``` ### Update I failed to notice that the `process.stdin.write()` was executed in a for loop. In which case, you should move the `process.stdin.close()` to outside the loop. Also, Raymond mentione...
Automatically close window after a certain time
15,306,222
3
2013-03-09T01:44:51Z
15,306,290
8
2013-03-09T01:55:28Z
[ "python", "tkinter" ]
In a class, in a function I am creating a Tkinter Canvas. This function is being called by another class, I would like for the Tkinter window to pop up for 30 seconds and then close itself. I have it call ``` master.mainloop() time.sleep(30) master.destroy() ``` But I get an error > "elf.tk.call('destroy', self.\_w)...
Don't use `time.sleep()` with tkinter. Instead, call the function [`after`](http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm#AEN9509) on the widget you want to close. Here it is the most simple example: ``` import tkinter as tk w = tk.Tk() w.after(30000, lambda: w.destroy()) ...
How to:Create children windows using python tkinter
15,306,631
3
2013-03-09T02:57:39Z
15,306,785
16
2013-03-09T03:26:23Z
[ "python", "window", "tkinter", "call" ]
I'm working on a pedestrian fleeing simulation these days.I use Python 3.3 to write algorithm and tkinter to make my GUI interface. I've write two simulation programs,and they worked well.However,I got stuck when I was trying to call them in another program(\*.py,my GUI main window).I want the simulation window to appe...
You create child windows by creating instances of `Toplevel`. See <http://effbot.org/tkinterbook/toplevel.htm> for more information. Here's an example that lets you create new windows by clicking on a button: ``` import Tkinter as tk class MainWindow(tk.Frame): counter = 0 def __init__(self, *args, **kwargs)...
Django reverse lookup of foreign keys
15,306,897
23
2013-03-09T03:43:54Z
15,307,225
37
2013-03-09T04:41:09Z
[ "python", "django", "django-forms", "django-views" ]
I have a venue, this venue has many events happening there. My models look like this: ``` class Event(models.Model): title = models.CharField(max_length=200) date_published = models.DateTimeField('published date',default=datetime.now, blank=True) date_start = models.DateTimeField('start date') date_end...
You can use `events = venue.event_set` to go the other way See the [Django documentation](https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward)
How can I remove an item from a repeated protobuf field in python?
15,307,079
6
2013-03-09T04:16:34Z
15,308,305
10
2013-03-09T07:17:19Z
[ "python", "protocol-buffers" ]
I have a protobuf message that contains a repeated field. I would like to remove one of the items in the list but I can't seem to find a good way to do so without copying all of the items out of the repeated field into a list, clearing the repeated field, and repopulating it. In C++ there is a `RemoveLast()` function,...
As noted in the [documentation](https://developers.google.com/protocol-buffers/docs/reference/python-generated), the object wrapping a repeated field in Protobuf behaves like a regular Python sequence. Therefore, you should be able to simply do ``` del foo.fields[index] ``` For example, to remove the last element, `...
Can't compare naive and aware datetime.now() <= challenge.datetime_end
15,307,623
28
2013-03-09T05:38:56Z
15,307,743
25
2013-03-09T05:54:15Z
[ "python", "django", "datetime", "comparison" ]
I am trying to compare the current date and time with dates and times specified in models using comparison operators: ``` if challenge.datetime_start <= datetime.now() <= challenge.datetime_end: ``` The script errors out with: ``` TypeError: can't compare offset-naive and offset-aware datetimes ``` The models look ...
By default the `datetime` object is `naive` in Python, so you need to make both of them to either naive or aware `datetime` objects. This can be done using. ``` import datetime import pytz utc=pytz.UTC challenge.datetime_start = utc.localize(challenge.datetime_start) challenge.datetime_end = utc.localize(challenge....
Can't compare naive and aware datetime.now() <= challenge.datetime_end
15,307,623
28
2013-03-09T05:38:56Z
15,309,419
25
2013-03-09T09:59:53Z
[ "python", "django", "datetime", "comparison" ]
I am trying to compare the current date and time with dates and times specified in models using comparison operators: ``` if challenge.datetime_start <= datetime.now() <= challenge.datetime_end: ``` The script errors out with: ``` TypeError: can't compare offset-naive and offset-aware datetimes ``` The models look ...
`datetime.datetime.now` is not timezone aware. Django comes with a helper for this, which requires `pytz` ``` from django.utils import timezone now = timezone.now() ``` You should be able to compare `now` to `challenge.datetime_start`
Installing Distribute when doing an altinstall of Python
15,311,235
4
2013-03-09T13:31:04Z
16,239,588
8
2013-04-26T15:03:51Z
[ "python", "python-2.7", "install", "centos", "distribute" ]
I'm doing an altinstall of Python 2.7.3 on CentOS 5.8, and I want distribute which gives pip and all that jazz. However I'm having trouble understanding the correct procedure, and the setup script for distribute is giving me errors. The current order of commands: (will ultimately be a setup script used for a project o...
I have a very similar setup here on RHEL5.8, and I get the same permission denied exception when I execute: ``` $ sudo python2.7 distribute_setup.py ``` The problem is solved by using an absolute path: ``` $ sudo /usr/local/bin/python2.7 distribute_setup.py ``` The underlying issue is simply that the root account d...
How to see if a widget exists in Tkinter?
15,311,698
4
2013-03-09T14:18:37Z
15,311,949
12
2013-03-09T14:44:56Z
[ "python", "button", "listbox", "tkinter" ]
Now, I know that you can check to see if a window exists by: ``` x.winfo_exists() ``` Which returns a Boolean. Now I have searched but haven't been able to find exactly what I need. More specifically I need to check the existence of my buttons, labels, list boxes, sliders etc.
`winfo_exists` returns 1 unless you have destroyed the widget, in which case it returns 0. This method can be called on any widget class, not only the Tk root or Toplevels. Alternatively, you can get all the children of a widget with `winfo_children`: ``` >>> import Tkinter as tk >>> root = tk.Tk() >>> label = tk.Labe...
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
15,312,732
48
2013-03-09T16:00:59Z
15,312,750
84
2013-03-09T16:02:41Z
[ "python", "mysql", "database", "django" ]
The problem Im facing while trying to connect to database for mysql. I have also given the database settings that i have used. ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/dja...
It looks like you don't have the python mysql package installed, try: ``` pip install mysql-python ``` or if not using a virtual environment (on \*nix hosts): ``` sudo pip install mysql-python ```
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
15,312,732
48
2013-03-09T16:00:59Z
16,734,735
26
2013-05-24T12:15:10Z
[ "python", "mysql", "database", "django" ]
The problem Im facing while trying to connect to database for mysql. I have also given the database settings that i have used. ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/dja...
you have to install python-mysqldb - Python interface to MySQL Try `sudo apt-get install python-mysqldb`
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
15,312,732
48
2013-03-09T16:00:59Z
19,133,958
11
2013-10-02T09:35:46Z
[ "python", "mysql", "database", "django" ]
The problem Im facing while trying to connect to database for mysql. I have also given the database settings that i have used. ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/dja...
When I set up Django development environment for PyCharm in Mac OS X Mountain Lion with python, mysql, sequel pro application I got error same as owner of this thread. However, my answer for them who is running python-mysqldb under Mac OS Mountain Lion x86\_x64 (MySql and Python also should be same architecture) and al...
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
15,312,732
48
2013-03-09T16:00:59Z
23,681,230
7
2014-05-15T14:30:22Z
[ "python", "mysql", "database", "django" ]
The problem Im facing while trying to connect to database for mysql. I have also given the database settings that i have used. ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ar/Desktop/test/testprac/local/lib/python2.7/site-packages/dja...
My answer is similar to @Ron-E, but I got a few more errors/corrections so I'm putting my steps below for Mac OSX on Mavericks and Python 2.7.6. 1. Install Python mysql package (if you get a success message, then ignore the below steps) ``` pip install mysql-python ``` 2. When I did the above, I got the erro...
Choose a file starting with a given string
15,312,953
7
2013-03-09T16:18:38Z
15,313,024
9
2013-03-09T16:25:24Z
[ "python", "file" ]
In a directory I have a lot of files, named more or less like this: ``` 001_MN_DX_1_M_32 001_MN_SX_1_M_33 012_BC_2_F_23 ... ... ``` In Python, I have to write a code that selects from the directory a file starting with a certain string. For example, if the string is `001_MN_DX`, Python selects the first file, and so ...
Try using `os.listdir`,`os.path.join` and `os.path.isfile`. In long form (with for loops), ``` import os path = 'C:/' files = [] for i in os.listdir(path): if os.path.isfile(os.path.join(path,i)) and '001_MN_DX' in i: files.append(i) ``` Code, with list-comprehensions is ``` import os path = 'C:/' file...
Choose a file starting with a given string
15,312,953
7
2013-03-09T16:18:38Z
15,313,611
14
2013-03-09T17:16:59Z
[ "python", "file" ]
In a directory I have a lot of files, named more or less like this: ``` 001_MN_DX_1_M_32 001_MN_SX_1_M_33 012_BC_2_F_23 ... ... ``` In Python, I have to write a code that selects from the directory a file starting with a certain string. For example, if the string is `001_MN_DX`, Python selects the first file, and so ...
``` import os prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")] ```
Python BeautifulSoup Extract specific URLs
15,313,250
4
2013-03-09T16:45:19Z
15,313,357
9
2013-03-09T16:54:37Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Is it possible to get only specific URLs? Like: ``` <a href="http://www.iwashere.com/washere.html">next</a> <span class="class">...</span> <a href="http://www.heelo.com/hello.html">next</a> <span class="class">...</span> <a href="http://www.iwashere.com/wasnot.html">next</a> <span class="class">...</span> ``` Output...
You can match multiple aspects, including using a regular expression for the attribute value: ``` import re soup.find_all('a', href=re.compile('http://www\.iwashere\.com/')) ``` which matches (for your example): ``` [<a href="http://www.iwashere.com/washere.html">next</a>, <a href="http://www.iwashere.com/wasnot.htm...
Python multiprocessing pool hangs at join?
15,314,189
20
2013-03-09T18:15:14Z
15,316,328
31
2013-03-09T21:51:48Z
[ "python", "multiprocessing" ]
I'm trying to run some python code on several files in parallel. The construct is basically: ``` def process_file(filename, foo, bar, baz=biz): # do stuff that may fail and cause exception if __name__ == '__main__': # setup code setting parameters foo, bar, and biz psize = multiprocessing.cpu_count()*2 ...
Sorry to answer my own question, but I've found at least a workaround so in case anyone else has a similar issue I want to post it here. I'll accept any better answers out there. I believe the root of the issue is <http://bugs.python.org/issue9400> . This tells me two things: * I'm not crazy, what I'm trying to do re...
In Python how do I split a string into multiple integers?
15,314,421
3
2013-03-09T18:35:52Z
15,314,446
12
2013-03-09T18:38:02Z
[ "python", "arrays", "string", "csv" ]
I'm reading a string which is always five numbers separated by a space, I want to split this up into five individual integers so that I can process them separately. so far I have: ``` reader = csv.reader([data.data], skipinitialspace=True) for r in reader: print r ``` which allows me to print the values out, how...
You could do it like this. Assuming `s` is your line from `reader`. ``` >>> s='2 3 4 5 6' >>> s.split(' ') ['2', '3', '4', '5', '6'] #just split will give strings >>> [int(i) for i in s.split(' ')] #typecasting to ints [2, 3, 4, 5, 6] #now you have ints ``` A word of caution though, I am assuming there is no other da...
Selecting with complex criteria from pandas.DataFrame
15,315,452
55
2013-03-09T20:17:49Z
15,315,507
121
2013-03-09T20:24:23Z
[ "python", "pandas" ]
For example I have simple DF: ``` df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)], 'B': [randint(1, 9)*10 for x in xrange(10)], 'C': [randint(1, 9)*100 for x in xrange(10)]}) ``` Can I select values from 'A' for which corresponding values for 'B' will be greater than ...
Sure! Setup: ``` >>> import pandas as pd >>> from random import randint >>> df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)], 'B': [randint(1, 9)*10 for x in xrange(10)], 'C': [randint(1, 9)*100 for x in xrange(10)]}) >>> df A B C 0 9 40 300 1 9 70 700 2 ...
How can I call 'git pull' from within Python?
15,315,573
22
2013-03-09T20:30:31Z
15,315,617
20
2013-03-09T20:34:19Z
[ "python", "git", "bash", "github" ]
Using the github webhooks, I would like to be able to pull any changes to a remote development server. At the moment, when in the appropriate directory, `git pull` gets any changes that need to be made. However, I can't figure out how to call that function from within Python. I have tried the following: ``` import sub...
[`subprocess.Popen`](http://docs.python.org/3/library/subprocess.html#subprocess.Popen) expects a list of the program name and arguments. You're passing it a single string, which is (with the default `shell=False`) equivalent to: ``` ['git pull'] ``` That means that subprocess tries to find a program named literally ...
How can I call 'git pull' from within Python?
15,315,573
22
2013-03-09T20:30:31Z
15,315,667
56
2013-03-09T20:38:43Z
[ "python", "git", "bash", "github" ]
Using the github webhooks, I would like to be able to pull any changes to a remote development server. At the moment, when in the appropriate directory, `git pull` gets any changes that need to be made. However, I can't figure out how to call that function from within Python. I have tried the following: ``` import sub...
Have you considered using GitPython? It's designed to handle all this nonsense for you. ``` import git g = git.cmd.Git(git_dir) g.pull() ``` <https://github.com/gitpython-developers/GitPython>
Open tor browser with selenium
15,316,304
15
2013-03-09T21:49:18Z
21,836,296
7
2014-02-17T18:09:37Z
[ "python", "selenium", "tor" ]
Is it possible to make selenium use the TOR browser? Does anyone have any code they could copy-paste?
Don't use the TBB, just set the correct proxy settings in whatever browser you're using. In FF for example, like this: ``` #set some privacy settings ff_prof.set_preference( "places.history.enabled", False ) ff_prof.set_preference( "privacy.clearOnShutdown.offlineApps", True ) ff_prof.set_preference( "privacy.clearOnS...
Check a command's return code when subprocess raises a CalledProcessError exception
15,316,398
15
2013-03-09T22:01:18Z
15,316,680
26
2013-03-09T22:33:16Z
[ "python", "python-3.x", "subprocess" ]
I want to capture the `stdout` stream of a shell command in a python (3) script, and being able, at the same time, to check the return code of the shell command if it returns an error (that is, if its return code is not 0). `subprocess.check_output` seems to be the appropriate method to do this. From `subprocess`'s ma...
To get both the process output and the returned code: ``` from subprocess import Popen, PIPE p = Popen(["ls", "non existent"], stdout=PIPE) output = p.communicate()[0] print(p.returncode) ``` `subprocess.CalledProcessError` is a class. To access `returncode` use the exception instance: ``` from subprocess import Ca...
Calculating Covariance with Python and Numpy
15,317,822
21
2013-03-10T01:14:44Z
15,317,971
48
2013-03-10T01:40:55Z
[ "python", "numpy", "covariance" ]
I am trying to figure out how to calculate covariance with the Python Numpy function cov. When I pass it two one-dimentional arrays, I get back a 2x2 matrix of results. I don't know what to do with that. I'm not great at statistics, but I believe covariance in such a situation should be a single number. [This](http://i...
When `a` and `b` are 1-dimensional sequences, `numpy.cov(a,b)[0][1]` is equivalent to your `cov(a,b)`. The 2x2 array returned by `np.cov(a,b)` has elements equal to ``` cov(a,a) cov(a,b) cov(a,b) cov(b,b) ``` (where, again, `cov` is the function you defined above.)
Cython: unsigned int indices for numpy arrays gives different result
15,317,851
7
2013-03-10T01:18:44Z
15,322,215
7
2013-03-10T12:28:00Z
[ "python", "numpy", "cython" ]
I converted to cython a python function by just adding some types and compiling it. I was getting small numerical differences between the results of the python and cython functions. After some work I found that the differences came from accessing a numpy array using unsigned int instead of int. I was using unsigned in...
I modified the example in the question to make it simpler to read the generated C source for the module. I'm only interested in seeing the logic that creates Python `float` objects instead of getting `np.float32` objects from the `response` array. I'm using `pyximport` to compile the extension module. It saves the gen...
Capture Control-C in Python
15,318,208
15
2013-03-10T03:22:36Z
15,319,004
21
2013-03-10T04:44:14Z
[ "python", "error-handling", "keyboard-events" ]
I want to know if it's possible to catch a Control-C in python in the following manner: ``` if input != contr-c: #DO THINGS else: #quit ``` I've read up on stuff with `try` and `except KeyboardInterrupt` but they're not working for me.
Consider reading [this](http://docs.python.org/3/tutorial/errors.html#handling-exceptions) page about handling exceptions.. It should help. As [@abarnert](http://stackoverflow.com/a/15318291/1931274) has said, do `sys.exit()` after `except KeyboardInterrupt:`. Something like ``` try: # DO THINGS except KeyboardI...
Pythonic way to assign the parameter into attribute?
15,318,258
5
2013-03-10T03:33:10Z
15,318,266
7
2013-03-10T03:34:23Z
[ "python", "oop", "class", "methods" ]
The sample codes are like this: ``` def assign(self, input=None, output=None, param=None, p1=None, p2=None): if input: self.input = input if output: self.output = output if param: self.param = param if p1: self.p1 = p1 if p2: self.p2 = p2 ``` Though this loo...
you can do something like: ``` def assign(self,**kwargs): for k,v in kwargs.items(): if v: setattr(self,k,v) ``` This is quite simple and suitable for many situations. If you want to maintain a set of keywords which you'll accept and raise TypeError for the rest: ``` #python2.7 and newer def a...
Matplotlib stops animating after first frame
15,318,690
9
2013-03-10T03:46:15Z
15,328,016
11
2013-03-10T21:42:01Z
[ "python", "animation", "matplotlib" ]
I'm trying to animate two subplots, each with multiple lines. I am using [Matplotlib](http://matplotlib.org/), and I am using the [`FuncAnimation`](http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation), which is used by many of the [animation examples](http://matplotlib.org/examples/animation...
### (Undocumented?) Hooks So, I was digging around the source-code of `matplotlib.animation.Animation`, and I noticed these lines in the `__init__()` function: ``` # Clear the initial frame self._init_draw() # Instead of starting the event source now, we connect to the figure's # draw_event, so that we only start on...
How to implement a Median-heap
15,319,561
11
2013-03-10T06:24:30Z
15,319,593
49
2013-03-10T06:30:05Z
[ "java", "python", "algorithm", "data-structures" ]
Like a Max-heap and Min-heap, I want to implement a Median-heap to keep track of the median of a given set of integers. The API should have the following three functions: ``` insert(int) // should take O(logN) int median() // will be the topmost element of the heap. O(1) int delmedian() // should take O(logN) ``` I ...
You need two heaps: one min-heap and one max-heap. Each heap contains about one half of the data. Every element in the min-heap is greater or equal to the median, and every element in the max-heap is less or equal to the median. When the min-heap contains one more element than the max-heap, the median is in the top of...
generate update query using django orm
15,319,875
7
2013-03-10T07:15:57Z
15,321,524
19
2013-03-10T11:05:08Z
[ "python", "django", "orm", "sql-update" ]
I need to implement this query using django orm: ``` update table set field=field+1 where id=id ``` I don't whant to use this: ``` o = model.objects.get(id=id) o.field+=1 o.save() ``` because it use select and when update, and not thread safe. How to implement this via orm?
Both the previous answerers have part of the solution: you should use `update` in conjunction with `F()`: ``` Model.objects.filter(id=id).update(field=F('field') +1)) ``` Note this does an in-place UPDATE without any need for SELECT at all.
Cannot return results from stored procedure using Python cursor
15,320,265
6
2013-03-10T08:14:32Z
15,320,433
7
2013-03-10T08:36:52Z
[ "python", "mysql", "stored-procedures" ]
For some odd reason I can't get results from a callproc call in a Python test app. The stored procedure in MqSQL 5.2.47 looks like this: ``` CREATE PROCEDURE `mytestdb`.`getperson` (IN personid INT) BEGIN select person.person_id, person.person_fname, person.person_mi, person.person_lna...
Have you tried picking one of the resultsets? ``` for result in cursor.stored_results(): people = result.fetchall() ``` It could be that it's allocating for multiple resultsets even though you only have one `SELECT` stmt. I know in PHP's MySQLi stored procedures do this to allow for INOUT and OUT variable returns...
python http/udp bittorrent tracker scrape library
15,321,098
7
2013-03-10T10:12:21Z
15,330,958
8
2013-03-11T03:56:14Z
[ "python", "bittorrent", "tracker", "libtorrent" ]
I have a list of torrent info\_hashes. For each info\_hash, I have a list of trackers that correspond with that info\_hash. What I would like to do is scrape each tracker in the list to get the seeder/leecher/completed count. However, i'd rather not attempt to write this myself as i'm sure this code has been implement...
I didnt want to use libtorrent also because it is quite inefficient - I want to be able to query a tracker for multiple info\_hashes instead of one at a time. I ended up writing my own python HTTP/UDP tracker scraping code, see here: <https://github.com/erindru/m2t/blob/master/m2t/scraper.py> (improvements most welcom...
a=list().append("hello") vs a=list(); a.append("hello") in python?
15,321,119
3
2013-03-10T10:14:53Z
15,321,139
9
2013-03-10T10:17:25Z
[ "python", "list" ]
I have ``` try: a = list().append('hello') ``` but `a` is `NoneType` ``` try: b = list() b.append('hello') ``` and `b` is a `list` type I think `list()` returns a list object, and `list().append('hello')` will use the return list to do append, but why is the value of `a` `None`?
`list()` does indeed return an empty list (`[]`), but the `append` method operates on a list *in-place* - it changes the list itself, and doesn't return a new list. It returns `None` instead. For example: ``` >>> lst = [] >>> lst.append('hello') # appends 'hello' to the list >>> lst ['hello'] >>> result = lst.append...
Removing unicode \u2026 like characters in a string in python2.7
15,321,138
23
2013-03-10T10:17:18Z
15,321,222
55
2013-03-10T10:26:21Z
[ "python", "python-2.7", "python-unicode", "unicode-escapes" ]
I have a string in python2.7 like this, ``` This is some \u03c0 text that has to be cleaned\u2026! it\u0027s annoying! ``` How do i convert it to this, ``` This is some text that has to be cleaned! its annoying! ```
``` >>> s 'This is some \\u03c0 text that has to be cleaned\\u2026! it\\u0027s annoying!' >>> print(s.decode('unicode_escape').encode('ascii','ignore')) This is some text that has to be cleaned! it's annoying! ```
How to pass a list from python , by jinja2 to javascript
15,321,431
34
2013-03-10T10:54:07Z
15,322,060
49
2013-03-10T12:11:24Z
[ "javascript", "python", "variables", "jinja2" ]
I'm new to javascript, and im dealing that kind of problem at the moment. Lets say i got python variable: `listOfItems= ['1','2','3','4','5']` and I pass it to JinJa by rendering Html, but I got also function in JavaScript called `somefunction(variable)` I were trying to pass each of 'listOfItems' item. I tried somthin...
To pass some context data to javascript code, you have to serialize it in a way it will be "understood" by javascript (namely JSON). You also need to mark it as safe using the `safe` Jinja filter, to prevent your data from being htmlescaped. You can achieve this by doing something like that: ### The view ``` import ...
How to pass a list from python , by jinja2 to javascript
15,321,431
34
2013-03-10T10:54:07Z
22,157,700
10
2014-03-03T21:20:51Z
[ "javascript", "python", "variables", "jinja2" ]
I'm new to javascript, and im dealing that kind of problem at the moment. Lets say i got python variable: `listOfItems= ['1','2','3','4','5']` and I pass it to JinJa by rendering Html, but I got also function in JavaScript called `somefunction(variable)` I were trying to pass each of 'listOfItems' item. I tried somthin...
I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list `letters = ['a','b','c']` with `render_template('show_entries.html', letters=letters)`, and set ``` var letters = {{ letters|safe }} ``` in my javascript code. Jinja2 replaced `{{ letters }}` with `['a','b','c']`, which ja...
Where in the python source code is math.exp() defined?
15,321,570
3
2013-03-10T11:11:35Z
15,322,395
11
2013-03-10T12:48:09Z
[ "python", "exp" ]
I want to known how to implement the `math.exp()` function in python. Where in the Python source code is `math.exp()` defined?
This one is a little tricky. The `math` module is implemented in a C module, [`mathmodule.c`](http://hg.python.org/cpython/file/tip/Modules/mathmodule.c). At the end of that file there is a specific Python library structure that defines [`exp` as implemented by `math_exp`](http://hg.python.org/cpython/file/tip/Modules...
python pandas, DF.groupby().agg(), column reference in agg()
15,322,632
26
2013-03-10T13:16:20Z
15,322,715
50
2013-03-10T13:24:45Z
[ "python", "group-by", "pandas" ]
On a concrete problem, say I have a DataFrame DF ``` word tag count 0 a S 30 1 the S 20 2 a T 60 3 an T 5 4 the T 10 ``` I want to find, **for every "word", the "tag" that has the most "count"**. So the return would be something like ``` word tag count 1 th...
`agg` is the same as `aggregate`. It's callable is passed the columns (`Series` objects) of the `DataFrame`, one at a time. --- You could use `idxmax` to collect the index labels of the rows with the maximum count: ``` idx = df.groupby('word')['count'].idxmax() print(idx) ``` yields ``` word a 2 an 3 th...
python pandas, DF.groupby().agg(), column reference in agg()
15,322,632
26
2013-03-10T13:16:20Z
15,322,920
12
2013-03-10T13:47:18Z
[ "python", "group-by", "pandas" ]
On a concrete problem, say I have a DataFrame DF ``` word tag count 0 a S 30 1 the S 20 2 a T 60 3 an T 5 4 the T 10 ``` I want to find, **for every "word", the "tag" that has the most "count"**. So the return would be something like ``` word tag count 1 th...
Here's a simple way to figure out what is being passed (the unutbu) solution then 'applies'! ``` In [33]: def f(x): ....: print type(x) ....: print x ....: In [34]: df.groupby('word').apply(f) <class 'pandas.core.frame.DataFrame'> word tag count 0 a S 30 2 a T 60 <class 'pandas.core....
How to connect a progress bar to a function?
15,323,574
5
2013-03-10T14:55:30Z
15,323,917
15
2013-03-10T15:30:20Z
[ "python", "tkinter" ]
I'm trying to connect a progress bar to a function for my project. This is what I have so far but im pretty sure it does nothing: ``` def main(): pgBar.start() function1() function2() function3() function4() pgBar.stop() ``` Here is the code where I make my progress bar if that helps at all: ...
Since tkinter is *single threaded*, you need another thread to execute your `main` function without freezing the GUI. One common approach is that the working thread puts the messages into a synchronized object (like a [`Queue`](http://docs.python.org/2/library/queue.html)), and the GUI part consumes this messages, upda...
How to connect a progress bar to a function?
15,323,574
5
2013-03-10T14:55:30Z
15,374,078
8
2013-03-12T23:12:55Z
[ "python", "tkinter" ]
I'm trying to connect a progress bar to a function for my project. This is what I have so far but im pretty sure it does nothing: ``` def main(): pgBar.start() function1() function2() function3() function4() pgBar.stop() ``` Here is the code where I make my progress bar if that helps at all: ...
To understand the 'freezing' you need to understand [`mainloop()`](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.mainloop-method). Calling this method starts the *tkinter* event loop. The main thread is responsible for this loop. Therefore, when your work intensive function runs in the main thread, it is also...
Python replace function [replace once]
15,324,240
20
2013-03-10T15:57:28Z
15,324,369
22
2013-03-10T16:08:35Z
[ "python", "string", "replace" ]
I need help with a program I'm making in Python. Assume I wanted to replace every instance of the word `"steak"` to `"ghost"` (just go with it...) but I also wanted to replace every instance of the word `"ghost"` to `"steak"` at the same time. The following code does not work: ``` s="The scary ghost ordered an expen...
I'd probably use a regex here: ``` >>> import re >>> s = "The scary ghost ordered an expensive steak" >>> sub_dict = {'ghost':'steak','steak':'ghost'} >>> regex = '|'.join(sub_dict) >>> re.sub(regex, lambda m: sub_dict[m.group()], s) 'The scary steak ordered an expensive ghost' ``` Or, as a function which you can cop...
Python replace function [replace once]
15,324,240
20
2013-03-10T15:57:28Z
15,324,396
12
2013-03-10T16:11:36Z
[ "python", "string", "replace" ]
I need help with a program I'm making in Python. Assume I wanted to replace every instance of the word `"steak"` to `"ghost"` (just go with it...) but I also wanted to replace every instance of the word `"ghost"` to `"steak"` at the same time. The following code does not work: ``` s="The scary ghost ordered an expen...
Split the string by one of the targets, do the replace, and put the whole thing back together. ``` pieces = s.split('steak') s = 'ghost'.join(piece.replace('ghost', 'steak') for piece in pieces) ``` This works *exactly* as `.replace()` would, including ignoring word boundaries. So it will turn `"steak ghosts"` into `...
Convert list to namedtuple
15,324,547
7
2013-03-10T16:26:22Z
15,324,557
19
2013-03-10T16:27:15Z
[ "python" ]
In python 3, I have a tuple `Row` and an array `A` as following ``` Row = namedtuple('Row', ['first', 'second', 'third']) A = ['1', '2', '3'] ``` How do I insert this array into named tuple? Note that in my situation I cannot directly do this: ``` newRow = Row('1', '2', '3') ``` I have tried different methods ``` ...
You can do `Row(*A)` which using argument unpacking. ``` >>> from collections import namedtuple >>> Row = namedtuple('Row', ['first', 'second', 'third']) >>> A = ['1', '2', '3'] >>> Row(*A) Row(first='1', second='2', third='3') ``` Note that if your linter doesn't complain too much about using methods which start wit...
How to filter rows in pandas by regex
15,325,182
35
2013-03-10T17:23:39Z
15,333,283
52
2013-03-11T07:27:34Z
[ "python", "regex", "pandas" ]
I would like to cleanly filter a dataframe using regex on one of the columns. For a contrived example: ``` In [210]: foo = pd.DataFrame({'a' : [1,2,3,4], 'b' : ['hi', 'foo', 'fat', 'cat']}) In [211]: foo Out[211]: a b 0 1 hi 1 2 foo 2 3 fat 3 4 cat ``` I want to filter the rows to those that start wi...
Use [contains](http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods) instead: ``` In [10]: df.b.str.contains('^f') Out[10]: 0 False 1 True 2 True 3 False Name: b, dtype: bool ```
Matplotlib half black and half white circle
15,326,069
5
2013-03-10T18:45:23Z
15,326,764
12
2013-03-10T19:51:06Z
[ "python", "matplotlib" ]
I would like to place a half black, half white circle of radius R at the origin of a matplotlib plot. I'm aware that there exists a [Circle class](http://stackoverflow.com/questions/3439639/matplotlib-add-circle-to-plot), but I don't know how to specify that the left half of the circle should be white and the right hal...
The easiest way is to use two `Wedge`s. (This doesn't automatically rescale the axes, but that's easy to add, if you'd like.) As a quick example: ``` import matplotlib.pyplot as plt from matplotlib.patches import Wedge def main(): fig, ax = plt.subplots() dual_half_circle((0.5, 0.5), radius=0.3, angle=90, ax...
How to implement __eq__ for set inclusion test?
15,326,985
7
2013-03-10T20:09:21Z
15,327,042
7
2013-03-10T20:14:40Z
[ "python", "set", "equality" ]
I am running into an issue where I'm adding an instance to a set and then later testing to see whether or not that object exists in that set. I've overridden `__eq__()` but it doesn't get called during the inclusion test. Do I have to override `__hash__()` instead? If so, how would I implement `__hash__()` given that I...
From the [documentation on sets](https://docs.python.org/2/library/sets.html): > The set classes are implemented using dictionaries. Accordingly, the > requirements for set elements are the same as those for dictionary > keys; namely, that the element defines both \_\_eq\_\_() and \_\_hash\_\_(). The [\_\_hash\_\_ fu...
Python/Django - Avoid saving passwords in source code
15,327,776
22
2013-03-10T21:20:55Z
15,327,779
32
2013-03-10T21:20:55Z
[ "python", "django", "security", "version-control", "django-settings" ]
I use Python and Django to create web applications, which we store in source control. The way Django is normally set up, the passwords are in plain text within the settings.py file. Storing my password in plain text would open me up to a number of security problems, particularly because this is an open source project ...
Although I wasn't able to come across anything Python-specific on stackoverflow, I did find a [website that was helpful](http://opensourcehacker.com/2012/12/13/configuring-your-python-application-using-environment-variables/), and thought I'd share the solution with the rest of the community. The solution: environment...
Dynamically limiting queryset of related field
15,328,632
21
2013-03-10T22:43:00Z
15,368,724
30
2013-03-12T18:03:04Z
[ "python", "django", "django-rest-framework" ]
Using Django REST Framework, I want to limit which values can be used in a related field in a creation. For example consider this example (based on the filtering example on <http://django-rest-framework.org/api-guide/filtering.html> , but changed to ListCreateAPIView): ``` class PurchaseList(generics.ListCreateAPIVie...
I ended up doing something similar to what [Khamaileon suggested here](https://groups.google.com/forum/?fromgroups=#!searchin/django-rest-framework/filter/django-rest-framework/m3pYCyTbQ3o/Sj-TmD6p62QJ). Basically I modified my serializer to peek into the request, which kind of smells wrong, but it gets the job done......
Getting: 'TypeError: can only concatenate tuple (not "int") to tuple', even though it is an int
15,328,728
2
2013-03-10T22:51:35Z
15,328,767
9
2013-03-10T22:55:32Z
[ "python", "python-3.x" ]
``` num_1 = 3 num_2 = 5 num_3 = 15 div_1 = 1000/3 div_2 = 1000/5 div_3 = 1000/15 sum_1 = 0 sum_2 = 0 sum_3 = 0 i = 0 while (i<300): sum_1 = sum_1 + i*3, i = i + 1 print (sum_1) i = 0 while (i<div_2): sum_2 = sum_2 + i*5, i += 1 i = 0 while (i<div_1): sum_3 = sum_3 + i*5, i += 1 print (sum_1)...
You are using commas where you shouldn't, creating tuples by accident: ``` sum_1 = sum_1 + i*3, # < no comma needed there ``` Get rid of those commas and your code will work. A comma creates a tuple in Python: ``` >>> 2, (2,) ```
Removing Set Identifier when Printing sets in Python
15,328,788
9
2013-03-10T22:58:35Z
15,328,795
22
2013-03-10T22:59:26Z
[ "python", "python-2.7", "set" ]
I am trying to print out the contents of a set and when I do, I get the set identifier in the print output. For example, this is my output `set(['a', 'c', 'b', 'e', 'd', 'f', 'gg', 'ff', 'jk'])`" for the code below. I want to get rid of the word `set`. My code is very simple and is below. ``` infile = open("P3TestData...
You could convert the set to a list, just for printing: ``` print list(words) ``` or you could use `str.join()` to join the contents of the set with a comma: ``` print ', '.join(words) ```
replace empty elements in list of list
15,328,826
2
2013-03-10T23:02:56Z
15,328,851
9
2013-03-10T23:06:04Z
[ "python" ]
I am a newbie to python and I have a weird list of lists (for scientif experiments), which looks as follows: ``` aaa=[['2.2', '2.05', '', '2.2', '2', '', '2.2', '2', '2.1', '2.05', '2', '2', '', '', '2.15', '2', '2.05', '2.1', '', '', '', '', ''], ['2.2', '2.05', '', '2.2', '2', '', '2.2', '2', '2.1', '2.05', '2', '2'...
Using list comprehensions: ``` new_list = [[element or '0.00' for element in sublist] for sublist in big_list] ```
How to run two modules at the same time in IDLE
15,329,649
4
2013-03-11T00:53:03Z
15,329,711
7
2013-03-11T01:01:14Z
[ "python", "sockets", "python-idle" ]
I am working on a super simple socket program and I have code for the client and code for the server. How do I run both these .py files at the same time to see if they work ?
You can run multiple instances of IDLE/Python shell at the same time. So open IDLE and run the server code and then open up IDLE again, which will start a separate instance and then run your client code.
How can I get argparse in Python 2.6?
15,330,175
32
2013-03-11T02:11:20Z
15,330,186
29
2013-03-11T02:12:59Z
[ "python", "argparse" ]
I have some Python 2.7 code written that uses the argparse module. Now I need to run it on a Python 2.6 machine and it won't work since argparse was added in 2.7. Is there anyway I can get argparse in 2.6? I would like to avoid rewriting the code, since I will be transferring this kind of code between the machines oft...
You can install it via pip or easy\_install: <https://pypi.python.org/pypi/argparse>
How can I get argparse in Python 2.6?
15,330,175
32
2013-03-11T02:11:20Z
22,974,755
23
2014-04-09T21:57:27Z
[ "python", "argparse" ]
I have some Python 2.7 code written that uses the argparse module. Now I need to run it on a Python 2.6 machine and it won't work since argparse was added in 2.7. Is there anyway I can get argparse in 2.6? I would like to avoid rewriting the code, since I will be transferring this kind of code between the machines oft...
On Centos, Scientific, or Redhat, you can fix this by running the command:for ``` yum install python-argparse ```
How does the functools partial work in Python?
15,331,726
59
2013-03-11T05:23:43Z
15,331,841
67
2013-03-11T05:35:54Z
[ "python", "functools" ]
I am not able to get my head on how the partial works in functools. I have the following code from [here](http://stackoverflow.com/questions/3252228/python-why-is-functools-partial-necessary): ``` >>> sum = lambda x, y : x + y >>> sum(1, 2) 3 >>> incr = lambda y : sum(1, y) >>> incr(2) 3 >>> def sum2(x, y): return...
Roughly, `partial` does something like this (apart from keyword args support etc): ``` def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper ``` So, by calling `partial(sum2, 4)` you create a new funct...
How does the functools partial work in Python?
15,331,726
59
2013-03-11T05:23:43Z
15,331,967
29
2013-03-11T05:46:35Z
[ "python", "functools" ]
I am not able to get my head on how the partial works in functools. I have the following code from [here](http://stackoverflow.com/questions/3252228/python-why-is-functools-partial-necessary): ``` >>> sum = lambda x, y : x + y >>> sum(1, 2) 3 >>> incr = lambda y : sum(1, y) >>> incr(2) 3 >>> def sum2(x, y): return...
**partials** are incredibly useful so for instance, in a 'pipe-lined' sequence of function calls (in which the returned value from one function is the argument passed to the next) sometimes a function in such a pipeline requires a *single argument* but the function immediately upstream from it returns *two values*. ...
Why must c++ code be contained within functions?
15,331,859
5
2013-03-11T05:37:28Z
15,331,880
12
2013-03-11T05:39:26Z
[ "c++", "python" ]
As a newbie to c++, coming from python, I'm not sure why c++ doesn't allow code outside of a function (in the global namespace?). It seems like this could be useful to do some initialization before main() is called or other functions are even declared. (I'm not trying to argue with the compiler, I'd just like to know t...
When you're running a python program, the interpreter runs through it from top to bottom executing as it goes. In C++, that doesn't happen. The compiler builds all your functions into little blobs of machine code and then the linker hooks them up. At runtime, the operating system calls your `main` function, and everyth...
Saving image/file through django shell
15,332,086
11
2013-03-11T05:57:31Z
16,366,870
29
2013-05-03T20:15:54Z
[ "django", "django-models", "django-file-upload", "django-shell", "python" ]
I am trying to save an image file through django shell. My `model.py` is: ``` class user(models.Model): name=models.CharField(max_length=20) pic=models.ImageField() ``` Everyhing is fine with admin and forms but I want to save image using shell: something like ``` >>>user1=User(name='abc', pic="what to wri...
``` from django.core.files import File user1=User(name='abc') user1.pic.save('abc.png', File(open('/tmp/pic.png', 'r'))) ``` You will end up with the image `abc.png` copied into the `upload_to` directory specified in the `ImageField`. In this case, the `user1.pic.save` method will also save the `user1` instance. The...
Python unittesting: run tests in another module
15,334,042
7
2013-03-11T08:28:35Z
15,335,550
8
2013-03-11T09:54:24Z
[ "python", "unit-testing", "module", "tdd" ]
I want to have the files of my application under the folder /Files, whereas the test units in /UnitTests, so that I have clearly separated app and test. To be able to use the same module routes as the mainApp.py, I have created a testController.py in the root folder. ``` mainApp.py testController.py Files |__init__...
The method unittest.main() looks at all the unittest.TestCase classes present in the context. So you just need to import your test classes in your testController.py file and call unittest.main() in the context of this file. So your file testController.py should simply look like this : ``` import unittest from Uni...
Correct path usage in Cygwin : Difference between `python c:\somefile.py` & `python /cygdrive/c/somefile.py`
15,334,201
9
2013-03-11T08:37:55Z
15,350,646
19
2013-03-11T23:36:06Z
[ "python", "django", "bash", "cygwin" ]
I'm using Django 1.5 & Python 2.7 on Windows + Cygwin. The following command gives me an error in bash shell ``` $ python /cygdrive/c/Python27/Lib/site-packages/django/bin/django-admin.py ``` Error: ``` C:\Python27\python.exe: can't open file '/cygdrive/c/Python27/Lib/site-packages/django/bin/django-admin.py': [Errn...
As others have noted, part of the problem here is that you're calling Windows Python from Cygwin. This is an odd thing to do, as you hit strange behaviour like this, but it can work with care. When you call Python from Cygwin - and this is the case for both Cygwin Python and Windows Python - the path you pass will be ...
Kivy button text alignment issue
15,334,280
9
2013-03-11T08:43:26Z
15,340,940
22
2013-03-11T14:21:08Z
[ "python", "kivy" ]
I am trying to develop an email application in Kivy, basically just as an exercise to learn the in's and out's of the framework... I am trying to create the initial window and have reached a bit of a stumbling block! The idea is that it will simply display a list of emails in the inbox, much like any basic email app on...
The documentation of [Button](http://kivy.org/docs/api-kivy.uix.button.html#module-kivy.uix.button) starts with "A Button is a Label". Even for [Widgets](http://kivy.org/docs/api-kivy.uix.html) that don't mention their lineage explicitly, you should take a note of the second line in the [API doc](http://kivy.org/docs/a...
Multiplying values from two different dictionaries together in Python
15,334,783
4
2013-03-11T09:14:52Z
15,334,818
12
2013-03-11T09:16:45Z
[ "python", "matrix-multiplication", "dictionary" ]
I have two separate dictionaries with keys and values that I would like to multiply together. The values should be multiplied just by the keys that they have. i.e. ``` dict1 = {'a': 1, 'b': 2, 'c': 3} dict2 = {'a': 15, 'b': 10, 'd': 17} dict3 = dict.items() * dict.items() print dict3 #### #dict3 should equal {'a':...
You can use a [dict comprehension](http://docs.python.org/2/tutorial/datastructures.html#dictionaries): ``` >>> {k : v * dict2[k] for k, v in dict1.items() if k in dict2} {'a': 15, 'b': 20} ``` Or, in pre-2.7 Python, the [`dict`](http://docs.python.org/2/library/stdtypes.html#dict) constructor in combination with a [...
How to pass a random function as an argument?
15,334,846
8
2013-03-11T09:18:11Z
15,334,932
8
2013-03-11T09:23:03Z
[ "python", "function", "random", "arguments" ]
Python is so flexible, that I can use functions as elements of lists or arguments of other functions. For example: ``` x = [sin, cos] y = s[0](3.14) # It returns sin(3.14) ``` or ``` def func(f1, f2): return f1(2.0) + f2(3.0) ``` However, it is not clear to me how to do the same with random functions. For exampl...
Try it with [`lambda`](http://docs.python.org/2/reference/expressions.html#lambda) functions: ``` [lambda: random.normalvariate(3.0, 2.0), lambda: random.normalvariate(1.0, 4.0)] ``` You see the difference with parentheses. `sin` is a function, `sin(x)` is the return value of this function. As you cannot create a fun...
How to pass a random function as an argument?
15,334,846
8
2013-03-11T09:18:11Z
15,334,943
7
2013-03-11T09:23:46Z
[ "python", "function", "random", "arguments" ]
Python is so flexible, that I can use functions as elements of lists or arguments of other functions. For example: ``` x = [sin, cos] y = s[0](3.14) # It returns sin(3.14) ``` or ``` def func(f1, f2): return f1(2.0) + f2(3.0) ``` However, it is not clear to me how to do the same with random functions. For exampl...
Use [functools.partial](http://docs.python.org/2/library/functools.html#functools.partial) or `lambda` Those are basically the same: ``` [lambda: normalvariate(3, 2), ...] # or [partial(normalvariate, 3, 2), ...] ``` They are both equivalent to: ``` def _function(): return normalvariate(3, 2) [_function, ...] ...
MySQL Unread Result with Python
15,336,767
9
2013-03-11T10:54:00Z
17,268,389
10
2013-06-24T05:09:35Z
[ "python", "mysql" ]
I use mysql.connector to do SQL operations. I have a short scripts which executes the following operations (strings) on the cursor with `cursor.execute(...)`: ``` "use {}".format(db) "show tables" command = """ ALTER TABLE Object DROP PRIMARY KEY; ALTER TABLE Object ADD `id` bigint(20) NOT NULL PRIMARY KEY AUTO_INCR...
Using MySQL Connector/Python, the *Unread results found* might happen when you use the connection object in different places without reading the result. It's not something one can go around. You can use the [*buffered* option](https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html) to read resu...
setter method of property decorator not being called
15,338,659
6
2013-03-11T12:32:47Z
15,338,749
15
2013-03-11T12:37:35Z
[ "python", "class", "properties" ]
I am trying to use a property method to set the status of a class instance, with the following class definition: ``` class Result: def __init__(self,x=None,y=None): self.x = float(x) self.y = float(y) self._visible = False self._status = "You can't see me" @property def vis...
On Python 2, you *must* inherit from `object` for properties to work: ``` class Result(object): ``` to make it a new-style class. With that change your code works: ``` >>> res = Result(5,6) >>> res.visible False >>> res.visible = True >>> res.currentStatus() 'You can see me!' ```
Python extract pattern matches
15,340,582
11
2013-03-11T14:04:05Z
15,340,666
7
2013-03-11T14:08:05Z
[ "python", "regex" ]
Python 2.7.1 I am trying to use python regular expression to extract words inside of a pattern I have some string that looks like this ``` someline abc someother line name my_user_name is valid some more lines ``` I want to extract the word "my\_user\_name". I do something like ``` import re s = #that big string p ...
You can use matching groups: ``` p = re.compile('name (.*) is valid') ``` e.g. ``` >>> import re >>> p = re.compile('name (.*) is valid') >>> s = """ ... someline abc ... someother line ... name my_user_name is valid ... some more lines""" >>> p.findall(s) ['my_user_name'] ``` Here I use `re.findall` rather than `r...
Python extract pattern matches
15,340,582
11
2013-03-11T14:04:05Z
15,340,694
18
2013-03-11T14:09:16Z
[ "python", "regex" ]
Python 2.7.1 I am trying to use python regular expression to extract words inside of a pattern I have some string that looks like this ``` someline abc someother line name my_user_name is valid some more lines ``` I want to extract the word "my\_user\_name". I do something like ``` import re s = #that big string p ...
You need to capture from regex. `search` for the pattern, if found, retrieve the string using `group(index)`. Assuming valid checks are performed: ``` >>> p = re.compile("name (.*) is valid") >>> p.search(s) # The result of this is referenced by variable name '_' <_sre.SRE_Match object at 0x10555e738> >>> _.group(1...
Python Numpy Data Types Performance
15,340,781
15
2013-03-11T14:13:07Z
15,341,193
12
2013-03-11T14:33:43Z
[ "python", "performance", "types", "numpy", "benchmarking" ]
So I did some testing and got odd results. Code: ``` import numpy as np import timeit setup = """ import numpy as np A = np.ones((1000,1000,3), dtype=datatype) """ datatypes = "np.uint8", "np.uint16", "np.uint32", "np.uint64", "np.float16", "np.float32", "np.float64" stmt1 = """ A = A * 255 A = A / 255 A = A - 1...
Half precision arithmetic (float16) is something which must be "emulated" by numpy I guess, as there are no corresponding types in the underlying C language (and in the appropriate processor instructions) for it. On the other hand, single precision (float32) and double precision (float64) operations can be done very ef...
Python Numpy Data Types Performance
15,340,781
15
2013-03-11T14:13:07Z
15,341,303
8
2013-03-11T14:38:39Z
[ "python", "performance", "types", "numpy", "benchmarking" ]
So I did some testing and got odd results. Code: ``` import numpy as np import timeit setup = """ import numpy as np A = np.ones((1000,1000,3), dtype=datatype) """ datatypes = "np.uint8", "np.uint16", "np.uint32", "np.uint64", "np.float16", "np.float32", "np.float64" stmt1 = """ A = A * 255 A = A / 255 A = A - 1...
16 bit floating point numbers are not supports by most common CPUs directly (though graphics card vendors are apparently involved in this data type, so I expect GPUs to support it eventually). I expect them to be emulated, in a comparatively slow way. Google tells me that [float16 was once hardware-dependent](http://ma...
how to call a django function on button click
15,341,285
15
2013-03-11T14:37:56Z
15,343,899
16
2013-03-11T16:42:15Z
[ "python", "django" ]
I am trying to write a Django application and i am stuck at how i can call a view function when a button is clicked. In my template, i have a link button as below when clicked takes you to a different webpage. ``` <a target="_blank" class="btn btn-info pull-right" href="{{ column_3_item.link_for_item }}">Check It Out...
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library ([or even no libraries at all](http://net.tutsplus.com/articles/news/how-to-make-ajax-requests-with-raw-javascript/)). ``` <html> <head> <title>An example</title> <script src="http://ajax.googleapis.com/ajax/...
Argumentless lambdas in Python?
15,341,410
4
2013-03-11T14:43:03Z
15,341,427
9
2013-03-11T14:44:11Z
[ "python", "lambda" ]
Is there a way to code: ``` def fn(): return None ``` as a lambda, in Python?
Yes, the argument list can be omitted: ``` fn = lambda: None ``` The production from [5.12. Lambdas](http://docs.python.org/2/reference/expressions.html#lambda) is: ``` lambda_form ::= "lambda" [parameter_list]: expression ``` The square brackets around `parameter_list` indicate an optional element.
NumPy/OpenCV 2: how do I crop non-rectangular region?
15,341,538
13
2013-03-11T14:49:10Z
15,343,106
17
2013-03-11T16:00:39Z
[ "python", "opencv", "image-processing", "numpy" ]
I have a set of points that make a **shape** (closed polyline). Now I want to copy/crop all pixels from some image **inside this shape**, leaving the rest black/transparent. How do I do this? For example, I have this: ![enter image description here](http://i.stack.imgur.com/2QXbO.jpg) and I want to get this: ![ente...
\*edit - updated to work with images that have an alpha channel. This worked for me: * Make a mask with all black (all masked) * Fill a polygon with white in the shape of your ROI * combine the mask and your image to get the ROI with black everywhere else You probably just want to keep the image and mask separate fo...
How to check that pylab backend of matplotlib runs inline?
15,341,757
6
2013-03-11T14:58:46Z
15,346,737
9
2013-03-11T19:17:37Z
[ "python", "matplotlib", "ipython", "ipython-notebook" ]
I am modifying a python module that plots some special graphs using matplotlib. Right now, this module just saves all figures as files. I would like to make it possible to import the module while working in ipython notebook and see the results "inline", on the other hand I would like to keep the default functionality...
You can check the matplotlib backend with: ``` import matplotlib matplotlib.get_backend() ``` To check for inline matplotlib in particular: ``` mpl_is_inline = 'inline' in matplotlib.get_backend() ``` Note that with the IPython notebook, you can *always* display inline figures, regardless of the active matplotlib b...
Python variable naming/binding confusion
15,342,545
9
2013-03-11T15:33:44Z
15,342,610
10
2013-03-11T15:36:49Z
[ "python", "variables", "binding", "python-2.7", "scope" ]
I am relatively new to Python development, and in reading through the language documentation, I came across a line that read: > It is illegal to unbind a name that is referenced by an enclosing scope; the compiler will report a SyntaxError. So in a learning exercise, I am trying to create this error in the interactiv...
The deletion has to take place in the *outer* scope: ``` >>> def foo(): ... a = 5 ... def bar(): ... return a ... del a ... SyntaxError: can not delete variable 'a' referenced in nested scope ``` The compile-time restriction has been removed in Python 3: ``` $ python3.3 Python 3.3.0 (default, Se...
Bash style process substitution with Python's Popen
15,343,447
4
2013-03-11T16:17:51Z
15,343,686
7
2013-03-11T16:30:56Z
[ "python", "bash", "subprocess", "popen" ]
In Bash you can easily redirect the output of a process to a temporary file descriptor and it is all automagically handled by bash like this: ``` $ mydaemon --config-file <(echo "autostart: True \n daemonize: True") ``` or like this: ``` $ wc -l <(ls) 15 /dev/fd/63 ``` see how it is not stdin redirection: ``` $ vi...
If `pram_axdnull` understands `"-"` convention to mean: "read from stdin" then you could: ``` p = Popen(["pram_axdnull", str(kmer), input_filename, "-"], stdin=PIPE, stdout=PIPE) output = p.communicate(generate_kmers(3))[0] ``` If the input is generated by external process: ``` kmer_proc = Popen(["generate...
Copying from one text file to another using Python
15,343,743
8
2013-03-11T16:33:39Z
15,343,861
32
2013-03-11T16:40:20Z
[ "python", "text-files" ]
I would like to copy certain lines of text from one text file to another. In my current script when I search for a string it copies everything afterwards, how can I copy just a certain part of the text? E.g. only copy lines when it has "tests/file/myword" in it? current code: ``` #!/usr/bin/env python f = open('list1...
The oneliner: ``` open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l]) ``` Recommended with `with`: ``` with open("in.txt") as f: lines = f.readlines() lines = [l for l in lines if "ROW" in l] with open("out.txt", "w") as f1: f1.writelines(lines) `...
Re-assign exception from within a python __exit__ block
15,344,002
7
2013-03-11T16:46:59Z
15,344,080
13
2013-03-11T16:50:47Z
[ "python", "exception-handling", "with-statement" ]
From within an `__exit__` block in a custom cursor class I want to catch an exception so I can in turn throw a more specific exception. What is the proper way to do this? ``` class Cursor: def __enter__(self): ... def __exit__(self, ex_type, ex_val, tb): if ex_type == VagueThirdPartyError: ...
The proper procedure is to raise the new exception inside of the `__exit__` handler. You should *not* raise the exception that was passed in though; to allow for context manager chaining, in that case you should just return a falsey value from the handler. Raising your own exceptions is however perfectly fine. Note t...
Get yesterday's date in Python, DST-safe
15,344,710
21
2013-03-11T17:23:09Z
15,344,831
34
2013-03-11T17:29:28Z
[ "python" ]
I have a python script that uses this call to get yesterday's date in YYYY-MM-DD format: ``` str(date.today() - timedelta(days=1))) ``` It works most of the time, but when the script ran this morning at `2013-03-11 0:35 CDT` it returned `"2013-03-09"` instead of `"2013-03-10"`. Presumably daylight saving time (which...
``` datetime.date.fromordinal(datetime.date.today().toordinal()-1) ```
Get yesterday's date in Python, DST-safe
15,344,710
21
2013-03-11T17:23:09Z
15,345,064
7
2013-03-11T17:42:30Z
[ "python" ]
I have a python script that uses this call to get yesterday's date in YYYY-MM-DD format: ``` str(date.today() - timedelta(days=1))) ``` It works most of the time, but when the script ran this morning at `2013-03-11 0:35 CDT` it returned `"2013-03-09"` instead of `"2013-03-10"`. Presumably daylight saving time (which...
I'm not able to reproduce your issue in python2.7 or python3.2: ``` >>> import datetime >>> today = datetime.date(2013, 3, 11) >>> print today 2013-03-11 >>> day = datetime.timedelta(days=1) >>> print today - day 2013-03-10 ``` It seems to me that this is already the simplest implementation of a "daylight-savings saf...
scipy.misc module has no attribute imread?
15,345,790
15
2013-03-11T18:24:03Z
15,345,969
30
2013-03-11T18:34:35Z
[ "python", "installation", "scipy", "dependencies", "python-imaging-library" ]
I am trying to read an image with scipy. However it does not accept the `scipy.misc.imread` part. What could be the cause of this? ``` >>> import scipy >>> scipy.misc <module 'scipy.misc' from 'C:\Python27\lib\site-packages\scipy\misc\__init__.pyc'> >>> scipy.misc.imread('test.tif') Traceback (most recent call last): ...
You need to install [PIL](http://www.pythonware.com/products/pil/). From [the docs](http://docs.scipy.org/doc/scipy/reference/misc.html) on `scipy.misc`: > Note that the Python Imaging Library (PIL) is not a dependency of SciPy and therefore the pilutil module is not available on systems that don’t have PIL installe...
Checking process status from Python
15,346,287
2
2013-03-11T18:52:28Z
15,346,373
13
2013-03-11T18:56:56Z
[ "python", "linux" ]
I am running on a Linux x86-64 system. From a Python (2.6) script, I wish to periodically check whether a given process (identified by pid) has become "defunct"/zombie (this means that entry in the process table exists but the process is doing nothing). It would be also good to know how much CPU the process is consumin...
I'd use the [`psutil` library](https://pypi.python.org/pypi/psutil): ``` import psutil proc = psutil.Process(pid) if proc.status() == psutil.STATUS_ZOMBIE: # Zombie process! ```
Is a Python Decorator the same as Java annotation, or Java with Aspects?
15,347,136
14
2013-03-11T19:40:39Z
15,347,250
15
2013-03-11T19:46:32Z
[ "java", "python", "python-decorators", "java-annotations" ]
Are Python Decorators the same or similar, or fundamentally different to Java annotations or something like Spring AOP, or Aspect J?
Python decorators are just syntactic sugar for passing a function to another function and replacing the first function with the result: ``` @decorator def function(): pass ``` is syntactic sugar for ``` def function(): pass function = decorator(function) ``` Java annotations by themselves just store metadat...
Python Finding Prime Factors
15,347,174
17
2013-03-11T19:42:33Z
15,347,389
8
2013-03-11T19:53:45Z
[ "python", "primes" ]
Two part question... 1) Trying to determine the largest prime factor of 600851475143, found this program online that seems to work, the problem is im having a hard time figuring out how it works exactly (i understand the basics of what the program is doing)...also if you could shed some light on any method you may kno...
For prime number generation I always use [`Sieve of Eratosthenes`](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes): ``` def primes(n): if n<=2: return [] sieve=[True]*(n+1) for x in range(3,int(n**0.5)+1,2): for y in range(3,(n//x)+1,2): sieve[(x*y)]=False return [2]+[i...
Python Finding Prime Factors
15,347,174
17
2013-03-11T19:42:33Z
17,311,362
21
2013-06-26T04:05:44Z
[ "python", "primes" ]
Two part question... 1) Trying to determine the largest prime factor of 600851475143, found this program online that seems to work, the problem is im having a hard time figuring out how it works exactly (i understand the basics of what the program is doing)...also if you could shed some light on any method you may kno...
Ok. So you said you understand the basics, but you're not sure EXACTLY how it works. First of all, this is a great answer to the Project Euler question it stems from. I've done a lot of research into this problem and this is by far the simplest response. For the purpose of explanation, I'll let `n = 20`. To run the re...
Python Finding Prime Factors
15,347,174
17
2013-03-11T19:42:33Z
22,808,285
26
2014-04-02T10:17:10Z
[ "python", "primes" ]
Two part question... 1) Trying to determine the largest prime factor of 600851475143, found this program online that seems to work, the problem is im having a hard time figuring out how it works exactly (i understand the basics of what the program is doing)...also if you could shed some light on any method you may kno...
This question was the first link that popped up when I googled `"python prime factorization"`. As pointed out by @quangpn88, this algorithm is *wrong (!)* for perfect squares such as `n = 4, 9, 16, ...` However, @quangpn88's fix does not work either, since it will yield incorrect results if the largest prime factor occ...
valueError zero length field name in format
15,347,483
2
2013-03-11T19:59:55Z
15,347,595
9
2013-03-11T20:06:28Z
[ "python" ]
I am using python version 2.7.3 and im trying to print out some information with a certain format. ``` final="<".join('< {} >'.format(' '.join(items)) for items in list) ``` But i got a valueError zero length field name in format error, is this because my python version does not allow certain syntaxs?
Pyhon2.6 requires you to put a positional argument in the `{}` ``` '< {0} >'.format(' '.join(items)) ```
AssertionError when threading in Python
15,349,997
11
2013-03-11T22:36:53Z
15,350,008
18
2013-03-11T22:37:52Z
[ "python", "multithreading" ]
I'm trying to run some simple threading in Python using: ``` t1 = threading.Thread(analysis("samplequery")) t1.start() other code runs in here t1.join() ``` Unforunately I'm getting the error: > "AssertionError: group argument must be none for now" I've never implemented threading in Python before, so I'm a bit u...
You want to specify the `target` keyword parameter instead: ``` t1 = threading.Thread(target=analysis("samplequery")) ``` You probably meant to make `analysis` the run target, but `'samplequery` the argument *when started*: ``` t1 = threading.Thread(target=analysis, args=("samplequery",)) ``` The first parameter to...
how to check which compiler was used to build Python
15,350,780
9
2013-03-11T23:49:27Z
15,350,792
12
2013-03-11T23:51:06Z
[ "python", "compiler-construction" ]
Is there a way to tell which compiler was used to build a `Python` install on a specific linux machine? I tried using `ldd` on the `Python` dynamic libraries [1], but I didn't manage to understand if it was compiled with `gcc` or Intel compiler. [1] ``` $ ldd libpython2.7.so.1.0 linux-vdso.so.1 => (0x00007fff4a5ff0...
I think you have it in `sys.version`: ``` >>> import sys >>> print(sys.version) 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] ``` It should also usually tell you when you start the interactive interpreter: ``` wim@wim-zenbook:~$ python3 Python 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] on linux2 Type ...
Plotting dashed 2D vectors with matplotlib?
15,352,129
4
2013-03-12T02:14:24Z
15,352,908
7
2013-03-12T03:42:40Z
[ "python", "matplotlib" ]
I'm using `quiver` to draw vectors in matplotlib: ``` from itertools import chain import matplotlib.pyplot as pyplot pyplot.figure() pyplot.axis('equal') axis = pyplot.gca() axis.quiver(*zip(*map(lambda l: chain(*l), [ ((0, 0), (3, 1)), ((0, 0), (1, 0)), ])), angles='xy', scale_units='xy', scale=1) axis.set_x...
Ah! Actually, `linestyle='dashed'` does work, it's just that quiver arrows are only filled by default and don't have a linewidth set. They're patches instead of paths. If you do something like this: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.axis('equal') ax.quiver((0,0), (0,0), (3,1), (1,0), a...