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
How to append list to second list (concatenate lists)
1,720,421
919
2009-11-12T07:04:09Z
31,270,002
9
2015-07-07T13:30:48Z
[ "python", "list" ]
How do I concatenate two lists in Python? Example: ``` listone = [1, 2, 3] listtwo = [4, 5, 6] ``` Expected outcome: ``` joinedlist == [1, 2, 3, 4, 5, 6] ```
If you want to merge the two lists in sorted form, you can use merge function from the heapq library. ``` from heapq import merge a = [1,2,4] b = [2,4,6,7] print list(merge(a,b)) ```
How to append list to second list (concatenate lists)
1,720,421
919
2009-11-12T07:04:09Z
33,048,483
7
2015-10-09T23:21:27Z
[ "python", "list" ]
How do I concatenate two lists in Python? Example: ``` listone = [1, 2, 3] listtwo = [4, 5, 6] ``` Expected outcome: ``` joinedlist == [1, 2, 3, 4, 5, 6] ```
This question directly asks about joining two lists. However it's pretty high in search even when you are looking for a way of joining many lists (including the case when you joining zero lists). Consider this more generic approach: ``` a = [[1,2,3], [4,5,6], [7,8,9]] reduce(lambda c, x: c + x, a, []) ``` Will output...
How to append list to second list (concatenate lists)
1,720,421
919
2009-11-12T07:04:09Z
35,631,185
11
2016-02-25T15:13:10Z
[ "python", "list" ]
How do I concatenate two lists in Python? Example: ``` listone = [1, 2, 3] listtwo = [4, 5, 6] ``` Expected outcome: ``` joinedlist == [1, 2, 3, 4, 5, 6] ```
### Python `>= 3.5` alternative: Even though this is an old answer, another alternative has been introduced via the acceptance of **[`PEP 448`](https://www.python.org/dev/peps/pep-0448/)** which deserves mentioning. The PEP, titled ***Additional Unpacking Generalizations***, generally reduced some syntactic restricti...
Non-blocking file access with Twisted
1,720,816
26
2009-11-12T08:47:11Z
2,450,504
13
2010-03-15T21:08:59Z
[ "python", "twisted" ]
I'm trying to figure out if there is a defacto pattern for file access using twisted. Lots of examples I've looked at (twisted.python.log, twisted.persisted.dirdbm, twisted.web.static) actually don't seem to worry about blocking for file access. It seems like there should be some obvious interface, probably inheriting...
I think you are looking for the [fdesc module](http://twistedmatrix.com/documents/current/api/twisted.internet.fdesc.html). For more information on non-blocking I/O in Python, you can also watch this [video](http://pyvideo.org/video/333/pycon-2010--demystifying-non-blocking-and-asynchr).
Remove "add another" in Django admin screen
1,721,037
13
2009-11-12T09:35:36Z
13,159,832
36
2012-10-31T14:05:47Z
[ "python", "django", "django-admin" ]
Whenever I'm editing object A with a foreign key to object B, a plus option "add another" is available next to the choices of object B. How do I remove that option? I configured a user without rights to add object B. The plus sign is still available, but when I click on it, it says "Permission denied". It's ugly. I'm...
(stop upvoting this wrong answer!!!) **ERRATA** : This answer is basically wrong, and does not answer OP's question. See below. > (this is only applicable to inline forms, not foreign key fields as OP asked) > > Simpler solution, no CSS hack, no editing Django codebase : > > Add this to your Inline class : > > `max_n...
Howto bin series of float values into histogram in Python?
1,721,273
7
2009-11-12T10:21:48Z
1,721,833
11
2009-11-12T12:28:17Z
[ "python", "statistics", "histogram", "binning" ]
I have set of value in float (always less than 0). Which I want to bin into histogram, i,e. each bar in histogram contain range of value [0,0.150) The data I have looks like this: ``` 0.000 0.005 0.124 0.000 0.004 0.000 0.111 0.112 ``` Whith my code below I expect to get result that looks like ``` [0, 0.005) 5 [0.0...
When possible, don't reinvent the wheel. NumPy has everything you need: ``` #!/usr/bin/env python import numpy as np a = np.fromfile(open('file', 'r'), sep='\n') # [ 0. 0.005 0.124 0. 0.004 0. 0.111 0.112] # You can set arbitrary bin edges: bins = [0, 0.150] hist, bin_edges = np.histogram(a, bins=bin...
Is there any "remote console" for twisted server?
1,721,699
5
2009-11-12T11:55:01Z
1,721,768
13
2009-11-12T12:11:46Z
[ "python", "console", "twisted" ]
I am developing a twisted server. I need to control the memory usage. It is not a good idea to modify code, insert some memory logging command and restart the server. I think it is better to use a "remote console", so that I can type heapy command and see the response from the server directly. All I need is a remote co...
`twisted.manhole.telnet` uses the deprecated module `twisted.protocols.telnet`. It is recommended to use `twisted.conch.manhole` instead. Here are some tutorials of how to use it: * [Writing a client with Twisted.Conch](http://twistedmatrix.com/projects/conch/documentation/howto/conch%5Fclient.html) -- twisted.conch ...
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
60
2009-11-12T12:20:32Z
1,722,075
7
2009-11-12T13:09:50Z
[ "python", "matlab", "numpy" ]
I would like to execute the equivalent of the following MATLAB code using NumPy: `repmat([1; 1], [1 1 1])`. How would I accomplish this?
See [NumPy for Matlab users](http://www.scipy.org/NumPy_for_Matlab_Users). Matlab: ``` repmat(a, 2, 3) ``` Numpy: ``` numpy.kron(numpy.ones((2,3)), a) ```
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
60
2009-11-12T12:20:32Z
1,722,154
11
2009-11-12T13:24:02Z
[ "python", "matlab", "numpy" ]
I would like to execute the equivalent of the following MATLAB code using NumPy: `repmat([1; 1], [1 1 1])`. How would I accomplish this?
Note that some of the reasons you'd need to use MATLAB's repmat are taken care of by NumPy's [broadcasting](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) mechanism, which allows you to do various types of math with arrays of similar shape. So if you had, say, a 1600x1400x3 array representing a 3-color ...
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
60
2009-11-12T12:20:32Z
1,724,410
69
2009-11-12T18:36:56Z
[ "python", "matlab", "numpy" ]
I would like to execute the equivalent of the following MATLAB code using NumPy: `repmat([1; 1], [1 1 1])`. How would I accomplish this?
Here is a much better (official) [NumPy for Matlab Users](http://www.scipy.org/NumPy%5Ffor%5FMatlab%5FUsers) link - I'm afraid the mathesaurus one is quite out of date. The numpy equivalent of `repmat(a, m, n)` is [`tile(a, (m, n))`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html). This works wit...
Finding the MAC address of the sender of a multicast UDP message in Python?
1,722,254
2
2009-11-12T13:42:02Z
1,722,329
7
2009-11-12T13:53:48Z
[ "python", "sockets", "udp", "multicast", "mac-address" ]
I have some code that listens for "announcements" via UDP multicast. I can get the IP address of the sender, but what I really need is the MAC address of the sender (since the IP address can and will change). Is there an easy way to do this in Python? A code snippet is included for reference, but likely unnecessary. ...
You cannot, in general, get the mac address. You might succeed using ARP on a LAN, but across the Internet it's not possible. Consider the case where the packet you receive has the IP address of the sender's [NATting](http://en.wikipedia.org/wiki/Network%5Faddress%5Ftranslation) router. The packet may have traversed a...
Which CAS implementation to use in django?
1,722,664
23
2009-11-12T14:44:10Z
6,512,247
8
2011-06-28T19:46:48Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following: * <http://code.google.com/p/django-cas/> * <http://github.com/Nitron/django-cas-consumer> I've used django-cas before...
I've been using an older version of django-cas for a long time now, and it works as expected. I've never used django-cas-consumer, but I've looked into it. Comparing the code between the two projects, it looks like django-cas-consumer is a stripped-down version of django-cas. The two most glaring differences are: * ...
Which CAS implementation to use in django?
1,722,664
23
2009-11-12T14:44:10Z
13,566,412
8
2012-11-26T14:00:54Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following: * <http://code.google.com/p/django-cas/> * <http://github.com/Nitron/django-cas-consumer> I've used django-cas before...
Django-cas was missing features we needed, so we rolled our own: <http://github.com/KTHse/django-cas2>
Find (and keep) duplicates of sublist in python
1,723,072
4
2009-11-12T15:32:11Z
1,723,086
8
2009-11-12T15:33:42Z
[ "python", "list", "duplicates", "sublist" ]
I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists. Example: ``` x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] output => [3, 4] ``` How can I do this?
``` common = set(x[0]) for l in x[1:]: common &= set(l) print list(common) ``` or: ``` import operator print reduce(operator.iand, map(set, x)) ```
python function slowing down for no apparent reason
1,723,494
2
2009-11-12T16:26:16Z
1,723,560
12
2009-11-12T16:34:59Z
[ "python" ]
I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP ``` def compareLists(list1, list2): curIndex = 0 while curIndex < len(list1): if list1[curIndex] in list2: list1.pop(curIndex) els...
Try a more pythonic approach to the filtering, something like ``` [x for x in list1 if x not in set(list2)] ``` Converting both lists to sets is unnessescary, and will be very slow and memory hungry on large amounts of data. Since your data is a list of lists, you need to do something in order to hash it. Try out `...
How could I print out the nth letter of the alphabet in Python?
1,724,473
11
2009-11-12T18:47:18Z
1,724,485
32
2009-11-12T18:49:09Z
[ "python" ]
ASCII math doesn't seem to work in Python: > > 'a' + 5 > > DOESN'T WORK How could I quickly print out the nth letter of the alphabet without having an array of letters? My naive solution is this: ``` letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', ...
`chr` and `ord` convert characters from and to integers, respectively. So: ``` chr(ord('a') + 5) ``` is the letter `'f'`.
How could I print out the nth letter of the alphabet in Python?
1,724,473
11
2009-11-12T18:47:18Z
1,724,536
21
2009-11-12T18:57:28Z
[ "python" ]
ASCII math doesn't seem to work in Python: > > 'a' + 5 > > DOESN'T WORK How could I quickly print out the nth letter of the alphabet without having an array of letters? My naive solution is this: ``` letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', ...
ASCII math aside, you don't have to type your letters table by hand. The [string constants](http://docs.python.org/library/string.html#string-constants) in the `string module` provide what you were looking for. ``` >>> import string >>> string.ascii_uppercase[5] 'F' >>> ```
Given a list of slices, how do I split a sequence by them?
1,724,675
11
2009-11-12T19:19:21Z
1,724,900
9
2009-11-12T19:49:33Z
[ "python" ]
### Given a list of slices, how do I separate a sequence based on them? I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it: ``` str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] output >> ['M', '(...
Strange way to split strings you have there: ``` def splitter( s, points ): c = 0 for x,y in points: yield s[c:x] yield "(%s)" % s[x:y+1] c=y+1 yield s[c:] print list(splitter(str, split_points)) # => ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC'] # if some start and endpoin...
Find a file in python
1,724,693
34
2009-11-12T19:21:52Z
1,724,723
84
2009-11-12T19:25:29Z
[ "python" ]
I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?
[os.walk](http://docs.python.org/library/os.html#os.walk) is the answer, this will find the first match: ``` import os def find(name, path): for root, dirs, files in os.walk(path): if name in files: return os.path.join(root, name) ``` And this will find all matches: ``` def find_all(name, pa...
Find a file in python
1,724,693
34
2009-11-12T19:21:52Z
24,679,920
7
2014-07-10T15:00:13Z
[ "python" ]
I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?
I used a version of `os.walk` and on a larger directory got times around 3.5 sec. I tried two random solutions with no great improvement, then just did: ``` paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()] ``` While it's POSIX-only, I got 0.25 sec. From this, I...
Lxml html xpath context
1,725,268
8
2009-11-12T20:48:01Z
1,725,377
12
2009-11-12T21:02:37Z
[ "python", "xpath", "lxml" ]
I'm using lxml to parse a HTML file and I'd like to know how can I set the `context` of xpath search. What I mean I that I have a node element and want to make xpath search only inside this node as if it was the root one. For example, I have a form node and xpath search `//input` return only inputs of the given form as...
XPath expression `//input` will match all input elements, anywhere in your document, while `.//input` will match all inside current context. Maybe if you improve your scenario description we can help you further.
Can a python module have a __repr__?
1,725,515
4
2009-11-12T21:24:17Z
1,725,604
8
2009-11-12T21:39:04Z
[ "python", "module" ]
Can a python module have a \_\_repr\_\_? The idea would be to do something like: ``` import mymodule print mymodule ``` EDIT: precision: I mean a **user-defined** repr!
**Short answer**: basically the answer is no. But can't you find the functionality you are looking for using docstrings? ``` testmodule.py ``` ``` """ my module test does x and y """ class myclass(object): ... ``` ``` test.py ``` ``` import testmodule print testmodule.__doc__ ``` **Long answer:** You can def...
Working with JSON in Python 2.6?
1,725,682
2
2009-11-12T21:55:31Z
1,725,769
11
2009-11-12T22:09:52Z
[ "python", "json" ]
I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way. I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do a simple p...
What you get when you `json.load` a file containing the JSON form of a Javascript object such as `{'abc': 'def'}` is a Python [dictionary](http://docs.python.org/tutorial/datastructures.html#dictionaries) (normally and affectionately called a `dict`) (which in this case happens to have the same textual representation a...
Get functions called in a Python expression
1,726,251
2
2009-11-12T23:54:51Z
1,726,372
11
2009-11-13T00:23:57Z
[ "python" ]
I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter `cubic_fit(1, ...
The built-in function [compile](http://docs.python.org/library/functions.html#compile) will do that for you exactly: ``` >>> compile("cubic_fit(1, 2, get_data())", '<string>', 'eval').co_names ('cubic_fit', 'get_data') ``` And it is safe to run. No code is actually being executed just compiled.
Matplotlib: draw grid lines behind other graph elements
1,726,391
49
2009-11-13T00:30:55Z
1,726,527
43
2009-11-13T01:13:26Z
[ "python", "matplotlib", "grid" ]
In Matplotlib, I make dashed grid lines as follows: ``` fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.yaxis.grid(color='gray', linestyle='dashed') ``` however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bars. Changing the order of ad...
According to this - <http://old.nabble.com/axis-elements-and-zorder-td6119088.html> - you can use Axis.set\_axisbelow() (I am currently installing matplotlib for the first time, so have no idea if that's correct - I just found it by googling "matplotlib z order grid" - "z order" is typically used to describe this kind...
In Python, how do I use urllib to see if a website is 404 or 200?
1,726,402
78
2009-11-13T00:35:14Z
1,726,431
121
2009-11-13T00:45:14Z
[ "python", "urllib", "http-status-codes" ]
How to get the code of the headers through urllib?
The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL. ``` >>> a=urllib.urlopen('http://www.google.com/asdfsf') >>> a.getcode() 404 >>> a=urllib.urlopen('http://www.google.com/') >>> a.getcode() 200 ```
In Python, how do I use urllib to see if a website is 404 or 200?
1,726,402
78
2009-11-13T00:35:14Z
1,726,434
67
2009-11-13T00:46:01Z
[ "python", "urllib", "http-status-codes" ]
How to get the code of the headers through urllib?
You can use [urllib2](http://www.voidspace.org.uk/python/articles/urllib2.shtml#urlerror) as well: ``` import urllib2 req = urllib2.Request('http://www.python.org/fish.html') try: resp = urllib2.urlopen(req) except urllib2.HTTPError as e: if e.code == 404: # do something... else: # ... exc...
python stdin eof
1,726,590
3
2009-11-13T01:32:15Z
1,726,619
8
2009-11-13T01:41:49Z
[ "python", "stdin", "eof" ]
How to pass python eof to stdin here is my code ``` p = Popen(commd,stdout=PIPE,stderr=PIPE,stdin=PIPE) o = p.communicate(inputstring)[0] ``` when i run the commd in command line after i input the inputstring windows still expecting a Ctrl+Z to finish accepting input. How can I pass eof or Ctrl+Z in program? Thank...
``` p.stdin.close() ``` after p.communicate, finishes the input and sends EOF to commd.
How should unit tests be documented?
1,726,622
16
2009-11-13T01:43:46Z
1,726,633
11
2009-11-13T01:47:04Z
[ "python", "unit-testing", "documentation", "docstring" ]
I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been addre...
I document most on my unit tests with the method name exclusively: ``` testInitializeSetsUpChessBoardCorrectly() testSuccessfulPromotionAddsCorrectPiece() ``` For almost 100% of my test cases, this clearly explains what the unit test is validating and that's all I use. However, in a few of the more complicated test c...
An enterprise scheduler for python (like quartz)
1,727,138
16
2009-11-13T04:31:57Z
1,727,176
12
2009-11-13T04:43:21Z
[ "python", "scheduled-tasks", "enterprise", "quartz-scheduler" ]
I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: * Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and must be fired after restarting. * Jobs must enter and exit the scheduler in a transaction (i.e. if some database operati...
Is [APScheduler](http://pypi.python.org/pypi/APScheduler/1.01) what you're looking for?
replace URLs in text with links to URLs
1,727,535
5
2009-11-13T06:39:27Z
1,727,552
9
2009-11-13T06:43:18Z
[ "python", "regex", "url", "hyperlink" ]
Using Python I want to replace all URLs in a body of text with links to those URLs, like what Gmail does. Can this be done in a one liner regular expression? Edit: by body of text I just meant plain text - no HTML
You can load the document up with a DOM/HTML parsing library ( see html5lib ), grab all text nodes, match them against a regular expression and replace the text nodes with a regex replacement of the URI with anchors around it using a PCRE such as: ``` /(https?:[;\/?\\@&=+$,\[\]A-Za-z0-9\-_\.\!\~\*\'\(\)%][\;\/\?\:\@\&...
How to create a UserProfile form in Django with first_name, last_name modifications?
1,727,564
19
2009-11-13T06:46:24Z
1,727,685
32
2009-11-13T07:25:30Z
[ "python", "django", "profile", "django-forms" ]
If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it. However, I could not find any help on the django documentation or in the Django Book. When you want to do a UserProfile form in with Django Forms, you'd like to modify the profile fields as well as ...
Here is how I finally did : ``` class UserProfileForm(forms.ModelForm): first_name = forms.CharField(label=_(u'Prénom'), max_length=30) last_name = forms.CharField(label=_(u'Nom'), max_length=30) def __init__(self, *args, **kw): super(UserProfileForm, self).__init__(*args, **kw) self.fiel...
How to create a UserProfile form in Django with first_name, last_name modifications?
1,727,564
19
2009-11-13T06:46:24Z
2,213,802
32
2010-02-06T16:39:02Z
[ "python", "django", "profile", "django-forms" ]
If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it. However, I could not find any help on the django documentation or in the Django Book. When you want to do a UserProfile form in with Django Forms, you'd like to modify the profile fields as well as ...
I stumbled across this today and after some googling I found a solution that is a bit cleaner in my opinion: ``` #in forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ["username", "email"] class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile...
Contruct 3d array in numpy from existing 2d array
1,727,669
5
2009-11-13T07:20:38Z
1,727,700
14
2009-11-13T07:31:25Z
[ "python", "numpy" ]
during preparing data for numpy calculate ,i curious about way to contruct ``` myarray.shape => (2,18,18) ``` from ``` d1.shape => (18,18) d2.shape => (18,18) ``` i try to use numpy command ``` hstack([[d1],[d2]]) ``` but it looks not work!!
Just doing `d3 = array([d1,d2])` seems to work for me: ``` >>> from numpy import array >>> # ... create d1 and d2 ... >>> d1.shape (18,18) >>> d2.shape (18,18) >>> d3 = array([d1, d2]) >>> d3.shape (2, 18, 18) ```
Seeking a High-Level Library for Socket Programming (Java or Python)
1,728,266
5
2009-11-13T09:55:41Z
1,728,556
7
2009-11-13T11:04:55Z
[ "java", "python", "sockets" ]
In short I'm creating a Flash based multiplayer game and I'm now starting to work on the server-side code. Well I'm the sole developer of the project so I'm seeking a high-level socket library that works well with games to speed up my development time. I was trying to use the Twisted Framework (for Python) but I'm hav...
An option for Python is the [Concurrence](http://opensource.hyves.org/concurrence/) framework. I used it fairly recently, in conjunction with [Stackless Python](http://www.stackless.com/), to simulate an environment in which there were potentially thousands of requests per second, each of which had to be processed in l...
How to get process's grandparent id
1,728,330
4
2009-11-13T10:13:58Z
1,728,386
7
2009-11-13T10:27:35Z
[ "python", "linux", "process", "subprocess" ]
How can i get process id of the current process's parent? In general given a process id how can I get its parent process id? e.g. os.getpid() can be used to get the proccess id, and os.getppid() for the parent, how do I get grandparent, My target is linux(ubuntu) so platform specific answers are ok.
linux specific: ``` os.popen("ps -p %d -oppid=" % os.getppid()).read().strip() ```
How to get process's grandparent id
1,728,330
4
2009-11-13T10:13:58Z
4,229,596
17
2010-11-19T21:36:35Z
[ "python", "linux", "process", "subprocess" ]
How can i get process id of the current process's parent? In general given a process id how can I get its parent process id? e.g. os.getpid() can be used to get the proccess id, and os.getppid() for the parent, how do I get grandparent, My target is linux(ubuntu) so platform specific answers are ok.
By using psutil ( <https://github.com/giampaolo/psutil> ): ``` >>> import psutil, os >>> psutil.Process(os.getpid()).ppid() 2335 >>> psutil.Process(os.getpid()).parent <psutil.Process (pid=2335, name='bash', cmdline='bash') at 140052120886608> >>> ```
Get a list of all the encodings Python can encode to
1,728,376
38
2009-11-13T10:24:29Z
1,728,414
9
2009-11-13T10:32:22Z
[ "python", "unicode", "encoding", "character-encoding" ]
I am writing a script that will try encoding bytes into many different encodings in Python 2.6. Is there some way to get a list of available encodings that I can iterate over? The reason I'm trying to do this is because a user has some text that is not encoded correctly. There are funny characters. I know the unicode ...
You could [use a technique](http://stackoverflow.com/questions/1707709/is-there-a-straightforward-way-to-find-all-the-modules-that-are-part-of-a-python/1707786#1707786) to list all modules in the `encodings` package. ``` import pkgutil import encodings false_positives = set(["aliases"]) found = set(name for imp, nam...
Get a list of all the encodings Python can encode to
1,728,376
38
2009-11-13T10:24:29Z
1,736,533
17
2009-11-15T04:08:22Z
[ "python", "unicode", "encoding", "character-encoding" ]
I am writing a script that will try encoding bytes into many different encodings in Python 2.6. Is there some way to get a list of available encodings that I can iterate over? The reason I'm trying to do this is because a user has some text that is not encoded correctly. There are funny characters. I know the unicode ...
**Unfortunately `encodings.aliases.aliases.keys()` is NOT an appropriate answer.** `aliases`(as one would/should expect) contains several cases where different keys are mapped to the same value e.g. `1252` and `windows_1252` are both mapped to `cp1252`. You could save time if instead of `aliases.keys()` you use `set(a...
Get a list of all the encodings Python can encode to
1,728,376
38
2009-11-13T10:24:29Z
1,779,263
12
2009-11-22T17:03:09Z
[ "python", "unicode", "encoding", "character-encoding" ]
I am writing a script that will try encoding bytes into many different encodings in Python 2.6. Is there some way to get a list of available encodings that I can iterate over? The reason I'm trying to do this is because a user has some text that is not encoded correctly. There are funny characters. I know the unicode ...
Maybe you should try using the [Universal Encoding Detector](https://pypi.python.org/pypi/chardet) (chardet) library instead of implementing it yourself. ``` >>> import chardet >>> s = '\xe2\x98\x83' # ☃ >>> chardet.detect(s) {'confidence': 0.505, 'encoding': 'utf-8'} ```
Get a list of all the encodings Python can encode to
1,728,376
38
2009-11-13T10:24:29Z
25,584,253
15
2014-08-30T15:59:40Z
[ "python", "unicode", "encoding", "character-encoding" ]
I am writing a script that will try encoding bytes into many different encodings in Python 2.6. Is there some way to get a list of available encodings that I can iterate over? The reason I'm trying to do this is because a user has some text that is not encoded correctly. There are funny characters. I know the unicode ...
Other answers here seem to indicate that constructing this list *programmatically* is difficult and fraught with traps. However, doing so is probably unnecessary since the documentation contains a complete list of the [standard encodings](https://docs.python.org/2/library/codecs.html#standard-encodings) Python supports...
One Line 'If' or 'For'
1,729,034
30
2009-11-13T12:47:59Z
1,729,047
37
2009-11-13T12:50:41Z
[ "python", "for-loop", "if-statement" ]
Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works. I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some exa...
Well, ``` if "exam" in "example": print "yes!" ``` Is this an improvement? **No**. You could even add more statements to the body of the `if`-clause by separating them with a semicolon. I recommend **against** that though.
One Line 'If' or 'For'
1,729,034
30
2009-11-13T12:47:59Z
1,729,048
15
2009-11-13T12:50:58Z
[ "python", "for-loop", "if-statement" ]
Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works. I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some exa...
More generally, all of the following are valid syntactically: ``` if condition: do_something() if condition: do_something() if condition: do_something() do_something_else() if condition: do_something(); do_something_else() ``` ...etc.
One Line 'If' or 'For'
1,729,034
30
2009-11-13T12:47:59Z
1,729,068
10
2009-11-13T12:55:39Z
[ "python", "for-loop", "if-statement" ]
Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works. I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some exa...
an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose version > a = 1 if x > 15 else 2
One Line 'If' or 'For'
1,729,034
30
2009-11-13T12:47:59Z
1,729,131
7
2009-11-13T13:10:09Z
[ "python", "for-loop", "if-statement" ]
Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works. I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some exa...
``` for a in someList: list.append(splitColon.split(a)) ``` You can rewrite the above as: ``` newlist = [splitColon.split(a) for a in someList] ```
One Line 'If' or 'For'
1,729,034
30
2009-11-13T12:47:59Z
1,729,213
35
2009-11-13T13:31:32Z
[ "python", "for-loop", "if-statement" ]
Every so often on here I see someone's code and what looks to be a 'one-liner', that being a one line statement that performs in the standard way a traditional 'if' statement or 'for' loop works. I've googled around and can't really find what kind of ones you can perform? Can anyone advise and preferably give some exa...
I've found that in the majority of cases doing block clauses on one line is a bad idea. It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python. In some cases python will offer ways todo things on one line that are definitely more pythoni...
Django upload_to outside of MEDIA_ROOT
1,729,051
22
2009-11-13T12:51:06Z
1,729,359
46
2009-11-13T13:59:54Z
[ "python", "django", "security", "upload", "media" ]
My deployment script overwrites the media and source directories which means I have to move the uploads directory out of the media directory, and replace it after the upload has been extracted. How can I instruct django to upload to /uploads/ instead of /media/? So far I keep getting django Suspicious Operation error...
I did the following: ``` from django.core.files.storage import FileSystemStorage upload_storage = FileSystemStorage(location=UPLOAD_ROOT, base_url='/uploads') image = models.ImageField(upload_to='/images', storage=upload_storage) ``` `UPLOAD_ROOT` is defined in my `settings.py` file: `/foo/bar/webfolder/uploads`
Multiple grids on matplotlib
1,729,995
16
2009-11-13T15:37:39Z
1,730,437
31
2009-11-13T16:44:44Z
[ "python", "matplotlib" ]
I'm making plots in python and matplotlib, which I found huge and flexible, till now. The only thing I couldn't find how to do, is to make my plot have multiple grids. I've looked into the [docs](http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.grid), but that's just for line style... I'm th...
How about something like this (adapted from [here](http://matplotlib.sourceforge.net/examples/pylab_examples/major_minor_demo1.html)): ``` from pylab import * from matplotlib.ticker import MultipleLocator, FormatStrFormatter t = arange(0.0, 100.0, 0.1) s = sin(0.1*pi*t)*exp(-t*0.01) ax = subplot(111) plot(t,s) ax.x...
How to find where a function was imported from in Python?
1,730,466
8
2009-11-13T16:49:12Z
1,730,492
17
2009-11-13T16:52:08Z
[ "python", "module" ]
I have a Python module with a function in it: ``` == bar.py == def foo(): pass == EOF == ``` And then I import it into the global namespace like so: ``` from bar import * ``` So now the function `foo` is available to me. If I print it: ``` print foo ``` The interpreter happily tells me: ``` <function foo ...
`foo.__module__` should return `bar` If you need more info, you can get it from `sys.modules['bar']`, its `__file__` and `__package__` attributes may be interesting.
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
1,730,690
28
2009-11-13T17:19:46Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
You might have a look at [MDP](http://mdp-toolkit.sourceforge.net/). I have not had the chance to test it myself, but I've bookmarked it exactly for the PCA functionality.
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
1,731,092
30
2009-11-13T18:44:50Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
[matplotlib.mlab](http://matplotlib.sourceforge.net/api/mlab_api.html) has a [PCA implementation](http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.PCA).
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
1,732,758
7
2009-11-14T00:29:28Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
I just finish reading the book [Machine Learning: An Algorithmic Perspective](http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html). All code examples in the book was written by Python(and almost with Numpy). The code snippet of [chatper10.2 Principal Components Analysis](http://seat.massey.ac.nz/personal/s.r.mar...
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
1,736,415
13
2009-11-15T02:59:26Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
SVD should work fine with 460 dimensions. It takes about 7 seconds on my Atom netbook. The eig() method takes *more* time (as it should, it uses more floating point operations) and will almost always be less accurate. If you have less than 460 examples then what you want to do is diagonalize the scatter matrix (x - da...
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
2,629,704
63
2010-04-13T13:04:55Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
Months later, here's a small class PCA, and a picture: ``` #!/usr/bin/env python """ a small class for Principal Component Analysis Usage: p = PCA( A, fraction=0.90 ) In: A: an array of e.g. 1000 observations x 20 variables, 1000 rows x 20 columns fraction: use principal components that account for e.g. ...
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
12,273,032
37
2012-09-05T00:28:27Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
PCA using `numpy.linalg.svd` is super easy. Here's a simple demo: ``` import numpy as np import matplotlib.pyplot as plt from scipy.misc import lena # the underlying signal is a sinusoidally modulated image img = lena() t = np.arange(100) time = np.sin(0.1*t) real = time[:,np.newaxis,np.newaxis] * img[np.newaxis,...]...
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
14,263,875
8
2013-01-10T17:34:50Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
You can quite easily "roll" your own using `scipy.linalg` (assuming a pre-centered dataset `data`): ``` covmat = data.dot(data.T) evs, evmat = scipy.linalg.eig(covmat) ``` Then `evs` are your eigenvalues, and `evmat` is your projection matrix. If you want to keep `d` dimensions, use the first `d` eigenvalues and fir...
Principal component analysis in Python
1,730,600
94
2009-11-13T17:04:31Z
18,389,738
25
2013-08-22T19:58:02Z
[ "python", "numpy", "scipy", "pca" ]
I'd like to use principal component analysis (PCA) for dimensionality reduction. Does numpy or scipy already have it, or do I have to roll my own using [`numpy.linalg.eigh`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html)? I don't just want to use singular value decomposition (SVD) because ...
You can use sklearn: ``` import sklearn.decomposition as deco import numpy as np x = (x - np.mean(x, 0)) / np.std(x, 0) # You need to normalize your data first pca = deco.PCA(n_components) # n_components is the components number after reduction x_r = pca.fit(x).transform(x) print ('explained variance (first %d compon...
More pythonic way of skipping header lines
1,730,649
9
2009-11-13T17:12:24Z
1,730,661
14
2009-11-13T17:15:07Z
[ "python" ]
Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character? In other words, a neater way of doing this ``` fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() ```
``` for line in open('data.txt'): if line.startswith('#'): continue # work with line ``` of course, if your commented lines are only at the beginning of the file, you might use some optimisations.
More pythonic way of skipping header lines
1,730,649
9
2009-11-13T17:12:24Z
1,730,741
10
2009-11-13T17:27:28Z
[ "python" ]
Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character? In other words, a neater way of doing this ``` fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() ```
``` from itertools import dropwhile for line in dropwhile(lambda line: line.startswith('#'), file('data.txt')): pass ```
More pythonic way of skipping header lines
1,730,649
9
2009-11-13T17:12:24Z
1,730,990
14
2009-11-13T18:23:31Z
[ "python" ]
Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character? In other words, a neater way of doing this ``` fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() ```
At this stage in my arc of learning Python, I find this most Pythonic: ``` def iscomment(s): return s.startswith('#') from itertools import dropwhile with open(filename, 'r') as f: for line in dropwhile(iscomment, f): # do something with line ``` to skip all of the lines at the top of the file starting...
Is there an existing Python class that can hold any user attributes?
1,730,769
2
2009-11-13T17:31:37Z
1,730,787
9
2009-11-13T17:35:58Z
[ "python", "struct" ]
I can use this when I need multiple objects with different attributes: ``` class struct(object): def __init__(self,*args,**kwargs): for key,val in kwargs.items(): setattr(self,key,val) ``` But I'm wondering if there isn't a built-in already?
Unless I'm not understanding your question, isn't this what we use a `dict` for? Sure, it's notationally slightly different, but an object's attributes are internally still stored in a `dict` (namely `__dict__`). It's a matter of notation. But, if you insist, then this is one way to do it: ``` >>> class struct(dict):...
Process two files at the same time in Python
1,731,102
3
2009-11-13T18:47:36Z
1,731,180
8
2009-11-13T19:02:30Z
[ "python", "string" ]
I have information about 12340 cars. This info is stored sequentially in two different files: 1. car\_names.txt, which contains one line for the name of each car 2. car\_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR\_NAME I would like to do in p...
I'm not sure if I completely understand what you're trying to do, is something like this? ``` f1 = open ('car_names.txt') f2 = open ('car_descriptions.txt') for car_name in f1.readlines (): for i in range (6): # echo the first 6 lines print f2.readline () assert f2.readline() == '@CAR...
Process two files at the same time in Python
1,731,102
3
2009-11-13T18:47:36Z
1,731,539
9
2009-11-13T20:00:12Z
[ "python", "string" ]
I have information about 12340 cars. This info is stored sequentially in two different files: 1. car\_names.txt, which contains one line for the name of each car 2. car\_descriptions.txt, which contains the descriptions of each car. So 40 lines for each one, where the 6th line reads @CAR\_NAME I would like to do in p...
First, make a generator that retrieves the car name from a sequence. You could yield every 7th line; I've made mine yield whatever line follows the line that starts with `@CAR_NAME`: ``` def car_names(seq): yieldnext=False for line in seq: if yieldnext: yield line yieldnext = line.startswith('@...
How do I check the HTTP status code of an object without downloading it?
1,731,298
4
2009-11-13T19:22:30Z
1,731,388
16
2009-11-13T19:33:29Z
[ "python", "http" ]
``` >>> a=urllib.urlopen('http://www.domain.com/bigvideo.avi') >>> a.getcode() 404 >>> a=urllib.urlopen('http://www.google.com/') >>> a.getcode() 200 ``` My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it immediately check the error code without saving the file?
You want to actually tell the server *not* to send the full content of the file. HTTP has a mechanism for this called "HEAD" that is an alternative to "GET". It works the same way, but the server only sends you the headers, none of the actual content. That'll save at least one of you bandwidth, while simply not doing ...
How to get two random records with Django
1,731,346
18
2009-11-13T19:27:42Z
1,731,373
17
2009-11-13T19:31:24Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.
If you specify the random operator in the ORM I'm pretty sure it will give you two distinct random results won't it? ``` MyModel.objects.order_by('?')[:2] # 2 random results. ```
How to get two random records with Django
1,731,346
18
2009-11-13T19:27:42Z
6,405,601
74
2011-06-19T23:03:35Z
[ "python", "django", "django-models", "random", "sql-order-by" ]
How do I get two distinct random records using Django? I've seen questions about how to get one but I need to get two random records and they must differ.
The `order_by('?')[:2]` solution suggested by other answers is actually an extraordinarily bad thing to do for tables that have large numbers of rows. It results in an `ORDER BY RAND()` SQL query. As an example, here's how mysql handles that (the situation is not much different for other databases). Imagine your table ...
Is there a 'multimap' implementation in Python?
1,731,971
36
2009-11-13T21:14:58Z
1,731,989
73
2009-11-13T21:18:40Z
[ "python", "dictionary" ]
I am new to Python, and I am familiar with implementations of [Multimaps](http://en.wikipedia.org/wiki/Multimap) in [other](http://www.sgi.com/tech/stl/Multimap.html) [languages](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html). Does Python have such a data structure built...
Such a thing is not present in the standard library. You can use a [`defaultdict`](http://docs.python.org/3.1/library/collections.html#collections.defaultdict) though: ``` >>> from collections import defaultdict >>> md = defaultdict(list) >>> md[1].append('a') >>> md[1].append('b') >>> md[2].append('c') >>> md[1] ['a'...
Is there a 'multimap' implementation in Python?
1,731,971
36
2009-11-13T21:14:58Z
23,981,416
8
2014-06-01T15:29:33Z
[ "python", "dictionary" ]
I am new to Python, and I am familiar with implementations of [Multimaps](http://en.wikipedia.org/wiki/Multimap) in [other](http://www.sgi.com/tech/stl/Multimap.html) [languages](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html). Does Python have such a data structure built...
Just for future visitors. Currently there is a python implementation of Multimap. It's available via [pypi](https://pypi.python.org/pypi/MultiMap)
Override save_model on Django InlineModelAdmin
1,732,151
15
2009-11-13T21:52:03Z
29,596,310
8
2015-04-13T00:38:34Z
[ "python", "django" ]
I have a model that has a `user` field that needs to be auto-populated from the currently logged in user. I can get it working as specified [here](http://www.b-list.org/weblog/2008/dec/24/admin/) if the `user` field is in a standard ModalAdmin, but if the model I'm working with is in an [`InlineModelAdmin`](http://docs...
Here's what I think is the best solution. Took me a while to find it... this answer gave me the clues: <http://stackoverflow.com/a/24462173/2453104> On your admin.py: ``` class YourInline(admin.TabularInline): model = YourInlineModel formset = YourInlineFormset def get_formset(self, request, obj=None, **...
how to run all Python unit tests in a directory
1,732,438
95
2009-11-13T23:01:39Z
1,732,477
57
2009-11-13T23:12:06Z
[ "python", "unit-testing", "testing" ]
So I have a directory that contains my Python unit test. Each unit test module is of the form "test\_\*.py". I am attempting to make a file called "all\_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
You could use a test runner that would do this for you. [nose](https://nose.readthedocs.org/en/latest/) is very good for example. When run, it will find tests in the current tree and run them. Updated: Here's some code from my pre-nose days. You probably don't want the explicit list of module names, but maybe the res...
how to run all Python unit tests in a directory
1,732,438
95
2009-11-13T23:01:39Z
1,735,277
27
2009-11-14T19:18:22Z
[ "python", "unit-testing", "testing" ]
So I have a directory that contains my Python unit test. Each unit test module is of the form "test\_\*.py". I am attempting to make a file called "all\_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
Well by studying the code above a bit (specifically using `TextTestRunner` and `defaultTestLoader`), I was able to get pretty close. Eventually I fixed my code by also just passing all test suites to a single suites constructor, rather than adding them "manually", which fixed my other problems. So here is my solution. ...
how to run all Python unit tests in a directory
1,732,438
95
2009-11-13T23:01:39Z
6,887,071
16
2011-07-31T01:58:04Z
[ "python", "unit-testing", "testing" ]
So I have a directory that contains my Python unit test. Each unit test module is of the form "test\_\*.py". I am attempting to make a file called "all\_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
If you want to run all the tests from various test case classes and you're happy to specify them explicitly then you can do it like this: ``` from unittest import TestLoader, TextTestRunner, TestSuite from uclid.test.test_symbols import TestSymbols from uclid.test.test_patterns import TestPatterns if __name__ == "__m...
how to run all Python unit tests in a directory
1,732,438
95
2009-11-13T23:01:39Z
9,311,779
9
2012-02-16T13:04:49Z
[ "python", "unit-testing", "testing" ]
So I have a directory that contains my Python unit test. Each unit test module is of the form "test\_\*.py". I am attempting to make a file called "all\_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
I have used the `discover` method and an overloading of `load_tests` to achieve this result in a (minimal, I think) number lines of code: ``` def load_tests(loader, tests, pattern): ''' Discover and load all unit tests in all files named ``*_test.py`` in ``./src/`` ''' suite = TestSuite() for all_test_suite in...
how to run all Python unit tests in a directory
1,732,438
95
2009-11-13T23:01:39Z
15,630,454
139
2013-03-26T06:09:40Z
[ "python", "unit-testing", "testing" ]
So I have a directory that contains my Python unit test. Each unit test module is of the form "test\_\*.py". I am attempting to make a file called "all\_test.py" that will, you guessed it, run all files in aforementioned test form and return the result. I have tried two methods so far, both have failed, I will show the...
With Python 2.7 and higher you don't have to write new code or use third-party tools to do this; recursive test execution via the command line is built-in. ``` python -m unittest discover <test_directory> # or python -m unittest discover -s <directory> -p '*_test.py' ``` You can read more in the [python 2.7](http://d...
Django ease of building a RESTful interface
1,732,452
10
2009-11-13T23:03:56Z
1,732,520
15
2009-11-13T23:20:36Z
[ "python", "django", "rest" ]
I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but some...
This is probably pretty easy to do. URL mappings are easy to construct, for example: ``` urlpatterns = patterns('books.views', (r'^books/$', 'index'), (r'^books/(\d+)/$', 'get')) ``` Django supports [model serialization](http://docs.djangoproject.com/en/dev/topics/serialization/), so it's easy to turn models int...
Unzipping part of a .gz file using python
1,732,709
4
2009-11-14T00:14:37Z
1,732,726
7
2009-11-14T00:19:33Z
[ "python", "gzip", "zlib" ]
So here's the problem. I have sample.gz file which is roughly 60KB in size. I want to decompress the first 2000 bytes of this file. I am running into CRC check failed error, I guess because the gzip CRC field appears at the end of file, and it requires the entire gzipped file to decompress. Is there a way to get around...
I seems that you need to look into [**Python zlib**](http://docs.python.org/library/zlib.html) library instead The GZIP format relies on zlib, but introduces a a file-level compression concept along with CRC checking, and this appears to be what you do not want/need at the moment. See for example these [**code snippe...
PyQt display fullscreen image
1,732,935
3
2009-11-14T01:36:10Z
1,733,241
7
2009-11-14T04:16:47Z
[ "python", "pyqt", "screenshot", "fullscreen" ]
I'm using PyQt to capture my screen with QPixmap.grabWindow(QApplication.desktop().winId()) and I was wondering if there was a way I could display my screengrab fullscreen (no window borders, etc.) I'm trying to find a way to desaturate my display with PyQt
Passing QtCore.Qt.FramelessWindowHint to the QWidget constructor in symphony with self.showFullScreen() in the image widget's code achieves this.
Python: next() function
1,733,004
17
2009-11-14T02:17:05Z
1,733,017
42
2009-11-14T02:21:49Z
[ "python", "sum", "next" ]
I'm learning Python from a book, and I came across this example: ``` M = [[1,2,3], [4,5,6], [7,8,9]] G = (sum(row) for row in M) # create a generator of row sums next(G) # Run the iteration protocol ``` Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the nex...
The expression `(sum(row) for row in M)` creates what's called a **generator**. This generator will evaluate the expression (`sum(row)`) once for each row in `M`. However, the generator doesn't do anything yet, we've just set it up. The statement `next(G)` actually *runs* the generator on `M`. So, if you run `next(G)`...
Python: next() function
1,733,004
17
2009-11-14T02:17:05Z
1,733,180
8
2009-11-14T03:49:51Z
[ "python", "sum", "next" ]
I'm learning Python from a book, and I came across this example: ``` M = [[1,2,3], [4,5,6], [7,8,9]] G = (sum(row) for row in M) # create a generator of row sums next(G) # Run the iteration protocol ``` Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the nex...
If you've come that far, then you should already know how a common for-in statement works. The following statement: ``` for row in M: print row ``` would see M as a sequence of 3 rows (sub sequences) consisting of 3 items each, and iterate through M, outputting each row on the matrix: ``` [1, 2, 3] [4, 5, 6] [7, 8,...
Django error opening SQLite3 db file on when running off Apache
1,733,050
6
2009-11-14T02:41:44Z
2,073,142
7
2010-01-15T16:33:08Z
[ "python", "django", "ubuntu", "sqlite3" ]
I got this error: OperationalError at / unable to open database file Things I've tried so far are setting the absolute path of my dev.db file in the settings.py. I've tried adding www-data to my admin group and setting the group of my project folder to the admin, and setting the group to www-data, none of which solv...
Just passed the last 30 minutes banging my head on this problem .. **Solution** In your settings.py: ``` DATABASE_NAME = '/absolute/path/to/your/database.db' ``` Setting rights: ``` chown www-data /absolute/path/to/your/ chown www-data /absolute/path/to/your/database.db ```
Grokking Timsort
1,733,073
22
2009-11-14T02:52:18Z
1,733,137
8
2009-11-14T03:31:07Z
[ "java", "python", "algorithm", "sorting", "timsort" ]
There's a (relatively) new sort on the block called Timsort. It's been used as Python's list.sort, and is now going to be [the new Array.sort in Java 7](http://download.java.net/jdk7/docs/api/java/util/Arrays.html#sort%28java.lang.Object%5B%5D)). There's [some documentation](http://svn.python.org/projects/python/trunk...
This change went through the [core-libs mailing list](http://mail.openjdk.java.net/pipermail/core-libs-dev/) when it went in so there is some discussion and useful links there. Here's the [web rev](http://cr.openjdk.java.net/~martin/webrevs/openjdk7/timsort/) with code review changes and also the [original patch](http:...
Grokking Timsort
1,733,073
22
2009-11-14T02:52:18Z
1,734,276
12
2009-11-14T13:49:43Z
[ "java", "python", "algorithm", "sorting", "timsort" ]
There's a (relatively) new sort on the block called Timsort. It's been used as Python's list.sort, and is now going to be [the new Array.sort in Java 7](http://download.java.net/jdk7/docs/api/java/util/Arrays.html#sort%28java.lang.Object%5B%5D)). There's [some documentation](http://svn.python.org/projects/python/trunk...
You should look at this blog post: [Visualising Sorting Algorithms: Python's timsort](http://corte.si/%2Fposts/code/timsort/index.html) ![alt text](http://corte.si/%2Fposts/code/timsort/combo.png) **Summary**: > The business-end of timsort is a mergesort that operates on runs of pre-sorted elements. A minimum run le...
Convert PyQt to PIL image
1,733,096
7
2009-11-14T03:08:15Z
1,756,587
10
2009-11-18T14:59:01Z
[ "python", "pyqt", "python-imaging-library" ]
I have an image in a QImage and I want to process it in PIL before I display it. While the ImageQT class lets me convert a PIL Image to a QImage, there doesn't appear to anything to go from a QImage to a PIL Image.
I convert it from QImage to PIL with this code: ``` img = QImage("/tmp/example.png") buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) pil_im = Image.open(strio) ``` I tried many combinations before getting...
How do I include unicode strings in Python doctests?
1,733,414
16
2009-11-14T05:51:24Z
1,734,503
14
2009-11-14T15:10:33Z
[ "python", "unicode", "doctest" ]
I am working on some code that has to manipulate unicode strings. I am trying to write doctests for it, but am having trouble. The following is a minimal example that illustrates the problem: ``` # -*- coding: utf-8 -*- def mylen(word): """ >>> mylen(u"áéíóú") 5 """ return len(word) print mylen(u"áéÃ...
If you want unicode strings, you have to use unicode docstrings! Mind the `u`! ``` # -*- coding: utf-8 -*- def mylen(word): u""" <----- SEE 'u' HERE >>> mylen(u"áéíóú") 5 """ return len(word) print mylen(u"áéíóú") ``` This will work -- as long as the tests pass. For Python 2.x you need yet...
wxPython: Update wx.ListBox list
1,733,461
7
2009-11-14T06:17:47Z
1,733,492
8
2009-11-14T06:28:00Z
[ "python", "wxpython" ]
I have a wx.ListBox in a python program, and I wan't to change out the list in it on a wx.Timer update. I have the timer working, I just don't know how to change out the list that it displays.
[Here's an example](http://www.daniweb.com/code/snippet216484.html#) for modifying a ListBox. Generally, it uses the `Append` and `Clear` methods of ListBox. You can call those in your timer handler. Since `ListBox` derives from `ItemContainer`, see more item modification methods [here](http://www.wxpython.org/docs/ap...
Writing a key-value store
1,733,619
10
2009-11-14T07:42:57Z
1,733,720
19
2009-11-14T08:44:52Z
[ "python", "key-value-store" ]
I am looking to write a Key/value store (probably in python) mostly just for experience, and because it's something I think that is a very useful product. I have a couple of questions. How, in general, are key/value pairs normally stored in memory and on disk? How would one go about loading the things stored on disk, b...
It all depends on the level of complexity you want to dive into. Starting with a simple Python `dict` serialized to a file in a myriad of possible ways (of which pickle is probably the simplest), you can go as far as implementing a complete database system. Look up `redis` - it's a key/value store written in C and ope...
Why isn't psycopg2 executing any of my SQL functions? (IndexError: tuple index out of range)
1,734,814
15
2009-11-14T16:55:28Z
1,735,731
27
2009-11-14T21:54:17Z
[ "python", "sql", "django", "postgresql", "psycopg2" ]
I'll take the simplest of the SQL functions as an example: ``` CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR) RETURNS BOOL AS $$ SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater WHERE name||' '||surname ILIKE '%'||$2||'%' OR surname||' '||name ILIKE '%'||$2||'%'); $...
By default psycopg2 identifies argument placeholders using the `%` symbol (usually you'd have `%s` in the string). So, if you use `cursor.execute('... %s, %s ...', (arg1, arg2))` then those `%s` get turned into the values of arg1 and arg2 respectively. But since you call: `cursor.execute(sql_function_above)`, without...
How to normalize a NumPy array to within a certain range?
1,735,025
40
2009-11-14T17:52:38Z
1,735,064
9
2009-11-14T18:04:54Z
[ "python", "arrays", "numpy", "scipy", "convenience-methods" ]
After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file. This can be done like so: ``` # Normalize audio channels to between -1.0 and +1.0 audio[:,0] = audio[:,0]/abs(audio[:,0]).max() audio[:,1] = audio[:,1]/abs(audio[:,1]).max() # Norm...
You can use the "i" (as in idiv, imul..) version, and it doesn't look half bad: ``` image /= (image.max()/255.0) ``` For the other case you can write a function to normalize an n-dimensional array by colums: ``` def normalize_columns(arr): rows, cols = arr.shape for col in xrange(cols): arr[:,col] /=...
How to normalize a NumPy array to within a certain range?
1,735,025
40
2009-11-14T17:52:38Z
1,735,122
48
2009-11-14T18:22:58Z
[ "python", "arrays", "numpy", "scipy", "convenience-methods" ]
After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file. This can be done like so: ``` # Normalize audio channels to between -1.0 and +1.0 audio[:,0] = audio[:,0]/abs(audio[:,0]).max() audio[:,1] = audio[:,1]/abs(audio[:,1]).max() # Norm...
``` audio /= np.max(np.abs(audio),axis=0) image *= (255.0/image.max()) ``` Using `/=` and `*=` allows you to eliminate an intermediate temporary array, thus saving some memory. Multiplication is less expensive than division, so ``` image *= 255.0/image.max() # Uses 1 division and image.size multiplications ``` is...
How to normalize a NumPy array to within a certain range?
1,735,025
40
2009-11-14T17:52:38Z
21,195,655
13
2014-01-17T20:53:11Z
[ "python", "arrays", "numpy", "scipy", "convenience-methods" ]
After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file. This can be done like so: ``` # Normalize audio channels to between -1.0 and +1.0 audio[:,0] = audio[:,0]/abs(audio[:,0]).max() audio[:,1] = audio[:,1]/abs(audio[:,1]).max() # Norm...
You can also rescale using `sklearn`. The advantages are that you can adjust normalize the standard deviation, in addition to mean-centering the data, and that you can do this on either axis, by features, or by records. ``` from sklearn.preprocessing import scale X = scale( X, axis=0, with_mean=True, with_std=True, co...
Setting Python Interpreter in Eclipse (Mac)
1,735,109
10
2009-11-14T18:18:32Z
1,735,148
7
2009-11-14T18:37:09Z
[ "python", "eclipse", "osx" ]
How do I direct Eclipse to the Python interpreter on my Mac? I've looked in Library which contains the directory 'Python' then '2.3' and '2.5', however they contain nothing except 'Site-packages' - Which is weird considering I can go into the terminal and type `python`. I then installed the latest 2.6 version with pac...
An alias to the python interpreter was likely installed into `/usr/local/bin`. So, to invoke python2.6, type `/usr/local/bin/python2.6` or, most likely, just `python2.6`. If you want python to invoke python2.6, try rearranging your `$PATH` so that `/usr/local/bin` precedes `/usr/bin`.
Setting Python Interpreter in Eclipse (Mac)
1,735,109
10
2009-11-14T18:18:32Z
1,735,193
7
2009-11-14T18:54:14Z
[ "python", "eclipse", "osx" ]
How do I direct Eclipse to the Python interpreter on my Mac? I've looked in Library which contains the directory 'Python' then '2.3' and '2.5', however they contain nothing except 'Site-packages' - Which is weird considering I can go into the terminal and type `python`. I then installed the latest 2.6 version with pac...
Running $which python should help locate your Python installation.
Help with Python UnboundLocalError: local variable referenced before assignment
1,735,263
2
2009-11-14T19:13:42Z
1,735,311
9
2009-11-14T19:25:10Z
[ "python", "numpy" ]
I have post the similar question before,however,I think I may have misinterpreted my question,so may I just post my origin code here,and looking for someone can help me,I am really stuck now..thanks alot. ``` from numpy import * import math as M #initial condition All in SI unit G=6.673*10**-11 #Gravitational cons...
where do you call force in this code? In any event, the problem is in update\_r. You reference vs in the first line of update\_r even though vs is not defined in this function. Python is not looking at the vs defined above. Try adding ``` global vs ``` as the first line of update\_r or adding vs to the parameter lis...
Class-level read-only properties in Python
1,735,434
24
2009-11-14T20:06:05Z
1,735,726
8
2009-11-14T21:50:56Z
[ "python" ]
Is there some way to make a class-level read-only property in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29)? For instance, if I have a class `Foo`, I want to say: ``` x = Foo.CLASS_PROPERTY ``` but prevent anyone from saying: ``` Foo.CLASS_PROPERTY = y ``` **EDIT:** I like the simplic...
The existing solutions are a bit complex -- what about just ensuring that each class in a certain group has a unique metaclass, then setting a normal read-only property on the custom metaclass. Namely: ``` >>> class Meta(type): ... def __new__(mcl, *a, **k): ... uniquemcl = type('Uniq', (mcl,), {}) ... retur...
Debugging a pyQT4 app?
1,736,015
31
2009-11-14T23:46:58Z
1,745,965
63
2009-11-17T01:03:06Z
[ "python", "qt", "pyqt4" ]
I have a fairly simple app built with pyqt4. I wanted to debug one of the functions connected to one of the buttons in my app. However, when I do the following ``` python -m pdb app.pyw > break app.pyw:55 # This is where the signal handling function starts. ``` things don't quite work like I'd hope. Instead of break...
You need to call [QtCore.pyqtRemoveInputHook](http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg13112.html). I wrap it in my own version of `set_trace`: ``` def debug_trace(): '''Set a tracepoint in the Python debugger that works with Qt''' from PyQt4.QtCore import pyqtRemoveInputHook # Or for Qt5 #f...
Python: data vs. text?
1,736,228
11
2009-11-15T01:13:19Z
1,736,279
17
2009-11-15T01:35:09Z
[ "python", "unicode", "python-3.x" ]
Guido van Rossum's presentation about [Python 3000](http://www.python.org/doc/essays/ppt/euro2008/Py3kEuro08.pdf) mentions several things to make a transition from Python 2 to Python 3 easier eventually. He is specifically talking about text handling since the move to Unicode as the only representation of strings in Py...
In a nutshell, the way text and data is handled in Py3k may arguably be the most "breaking" change in the language. By knowing and avoiding,when possible, the situations where some Python 2.6 logic will work differently than in 3.x, we can facilitate the migration when it happens. Yet we should expect that some parts o...
Using Windows 7 taskbar features in PyQt
1,736,394
12
2009-11-15T02:45:40Z
1,744,503
23
2009-11-16T20:00:05Z
[ "python", "windows-7", "pyqt", "pyqt4", "taskbar" ]
I am looking for information on the integration of some of the new Windows 7 taskbar features into my PyQt applications. Specifically if there already exists the possibility to use the new progress indicator ([see here](http://www.petri.co.il/wp-content/uploads/new%5Fwin7%5Ftaskbar%5Ffeatures%5F10.gif)) and the quick ...
As quark said, the functionality is not in Qt 4.5, but you can call the windows API directly from Qt. Its a little bit of work though. 1. The new taskbar API is exposed through COM, so you can't use ctypes.windll . You need to create a .tlb file to access the functions. Get the interface definition for ITaskbarList fr...
Django auto_now and auto_now_add
1,737,017
136
2009-11-15T08:47:56Z
1,737,078
194
2009-11-15T09:26:31Z
[ "python", "django", "datetime", "django-models", "django-admin" ]
For Django 1.1. I have this in my models.py: ``` class User(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) ``` When updating a row I get: ``` [Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base....
Any field with the `auto_now` attribute set will also inherit `editable=False` and therefore will not show up in the admin panel. There has been talk in the past about making the `auto_now` and `auto_now_add` arguments go away, and although they still exist, I feel you're better off just using a custom `save()` method....
Django auto_now and auto_now_add
1,737,017
136
2009-11-15T08:47:56Z
3,330,128
96
2010-07-25T17:01:35Z
[ "python", "django", "datetime", "django-models", "django-admin" ]
For Django 1.1. I have this in my models.py: ``` class User(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) ``` When updating a row I get: ``` [Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base....
Bah... Not enough reputation to comment... But I wanted to point out that the opinion expressed in the accepted answer is somewhat outdated. According to more recent discussions (django bugs [#7634](https://code.djangoproject.com/ticket/7634) and [#12785](https://code.djangoproject.com/ticket/12785)), auto\_now and aut...
Django auto_now and auto_now_add
1,737,017
136
2009-11-15T08:47:56Z
11,646,630
20
2012-07-25T09:25:41Z
[ "python", "django", "datetime", "django-models", "django-admin" ]
For Django 1.1. I have this in my models.py: ``` class User(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) ``` When updating a row I get: ``` [Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base....
Talking about a side question: if you want to see this fields in admin (though, you won't be able to edit it), you can add `readonly_fields` to your admin class. ``` class SomeAdmin(ModelAdmin): readonly_fields = ("created","modified",) ``` Well, this applies only to latest Django versions (I believe, 1.3 and abo...