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 |
|---|---|---|---|---|---|---|---|---|---|
Which Python ternary operation is better and why? | 14,627,870 | 3 | 2013-01-31T14:16:13Z | 14,627,952 | 12 | 2013-01-31T14:19:50Z | [
"python"
] | I have been reading all over the place, including [Ternary conditional operator in Python](http://stackoverflow.com/questions/394809/ternary-conditional-operator-in-python). It is supposed that
```
result = a if a > b else b
```
is better code than
```
result = a > b and a or b
```
But no one ever explains why. Wi... | `result = a if a > b else b` is better because it is always semantically correct. In other words, you will always get what you expect from it, regardless of the value of either `a` or `b`. `result = a > b and a or b` will result in `b` every time if `a` is a falsey value (`0`, `None`, etc).
Additionally, since `a if x... |
python find items in a list given indices | 14,629,678 | 2 | 2013-01-31T15:49:50Z | 14,629,728 | 7 | 2013-01-31T15:51:49Z | [
"python",
"list"
] | Is there any other FASTER way to find the items at index locations.
```
items = ['aaa','sss','ddd','fff','gggg','hhhh']
indices = [1,3,4]
My way:
[items[i] for i in indices]
``` | If you're using the same indices over and over, you might do better with `operator.itemgetter`:
```
getter = itemgetter(1,3,4)
desired = getter(items)
```
According to my simple benchmark, `itemgetter` is about 2.5x faster (but I didn't time how long it takes to actually construct the `getter` function to begin with)... |
ImportError: DLL load failed: %1 is not a valid Win32 application | 14,629,818 | 20 | 2013-01-31T15:55:53Z | 17,821,100 | 18 | 2013-07-23T21:06:49Z | [
"python",
"opencv",
"importerror"
] | I have this issue where I try to import cv2 on python and get the following error message.
```
>>> import cv2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: DLL load failed: %1 is not a valid Win32 application.
```
I do understand there are many posts about this where it is sugges... | The ImportError message is a bit misleading because of the reference to Win32, whereas the problem was simply the opencv DLLs were not found.
This problem was solved by adding the path the opencv binaries to the Windows PATH environment variable (as an example, on my computer this path is : C:\opencv\build\bin\Release... |
UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function | 14,630,288 | 67 | 2013-01-31T16:18:30Z | 16,120,218 | 53 | 2013-04-20T12:13:34Z | [
"python",
"encoding",
"decode",
"encode"
] | I am writing a Python (Python 3.3) program to send some data to a webpage using POST method. Mostly for debugging process I am getting the page result and displaying it on the screen using `print()` function.
The code is like this:
```
conn.request("POST", resource, params, headers)
response = conn.getresponse()
prin... | I see three solutions to this:
1. Change the output encoding, so it will always output UTF-8. See e.g. [Setting the correct encoding when piping stdout in python](http://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python), but I could not get these example to work.
2. Followin... |
UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function | 14,630,288 | 67 | 2013-01-31T16:18:30Z | 29,988,426 | 15 | 2015-05-01T14:08:47Z | [
"python",
"encoding",
"decode",
"encode"
] | I am writing a Python (Python 3.3) program to send some data to a webpage using POST method. Mostly for debugging process I am getting the page result and displaying it on the screen using `print()` function.
The code is like this:
```
conn.request("POST", resource, params, headers)
response = conn.getresponse()
prin... | Based on Dirk Stöcker's answer, here's a neat wrapper function for Python 3's print function. Use it just like you would use print.
As an added bonus, compared to the other answers, this won't print your text as a bytearray ('b"content"'), but as normal strings ('content'), because of the last decode step.
```
def u... |
UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function | 14,630,288 | 67 | 2013-01-31T16:18:30Z | 32,173,072 | 7 | 2015-08-24T00:52:02Z | [
"python",
"encoding",
"decode",
"encode"
] | I am writing a Python (Python 3.3) program to send some data to a webpage using POST method. Mostly for debugging process I am getting the page result and displaying it on the screen using `print()` function.
The code is like this:
```
conn.request("POST", resource, params, headers)
response = conn.getresponse()
prin... | For debugging purposes, you could use `print(repr(data))`.
To display text, always print Unicode. Don't hardcode the character encoding of your environment such as `cp850` inside your script. To decode the http response, see [A good way to get the charset/encoding of an HTTP response in Python](http://stackoverflow.co... |
Additional empty elements when splitting a string with re.split | 14,631,157 | 7 | 2013-01-31T17:00:30Z | 14,631,276 | 7 | 2013-01-31T17:07:37Z | [
"python",
"regex",
"python-2.6"
] | I'm trying to split a string looking like this in Python using re.split:
```
#NAME="Foo" NAME2="foobar" NAME3="BAR BAR"
comp = "NAME=\"Foo\" NAME2=\"FOO BAR\" NAME3=\"BAR BAR\""
```
This is how my split-function including regex looks like:
```
re.split('(\s\w+\=\".*?\")', comp)
```
The result looks like this:
```
... | Is this what you're looking for:
```
In [10]: re.findall(r'\w+=".*?"', comp)
Out[10]: ['NAME="Foo"', 'NAME2="FOO BAR"', 'NAME3="BAR BAR"']
```
?
It doesn't sound like `re.split()` is the right tool for the job. |
Why does the is_(a,b) function work faster than eq(a,b) in python 2.7.3? | 14,631,681 | 3 | 2013-01-31T17:31:30Z | 14,631,810 | 9 | 2013-01-31T17:39:26Z | [
"python",
"python-2.7"
] | I search the answer why `a is None` works faster than `a == None`. I measure time by using this code:
```
>>> timeit.timeit("1 is None", number=10000000)
0.4035069934390217
>>> timeit.timeit("1 == None", number=10000000)
0.8190256083633187
```
[The documentation](http://docs.python.org/2/library/operator.html) says t... | Testing for identity (`is`) is as simple pointer comparison (are the two values the same object).
Testing for equality needs to do more work than that; for lists for example it does need to test for equality of each and every element in both lists until either something tests negative for equality or all elements in t... |
calculate turning points / pivot points in trajectory (path) | 14,631,776 | 16 | 2013-01-31T17:37:23Z | 14,635,868 | 12 | 2013-01-31T21:55:19Z | [
"python",
"algorithm",
"matlab",
"signal-processing"
] | I'm trying to come up with an algorithm that will determine turning points in a trajectory of x/y coordinates. The following figures illustrates what I mean: green indicates the starting point and red the final point of the trajectory (the entire trajectory consists of ~ 1500 points):
 algorithm](http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm) to simplify the path. Then you could compute the change in directions along each segment of the simplified path. The points corresponding to the greatest change in direction could be called the turnin... |
How to install Python for .NET on Windows | 14,633,695 | 13 | 2013-01-31T19:33:28Z | 25,091,750 | 10 | 2014-08-02T04:44:49Z | [
"c#",
"python",
".net",
"mono",
"python.net"
] | I downloaded [*Python for .NET*](http://pythonnet.github.io/).
Inside the zip is `clr.pyd`, `nPython.exe`, `Python.Runtime.dll` and 2 debug database files.
I put the clr.pyd and Python.Runtime.dll in my python DLLs dir C:\Python27\DLLs thinking this is all that's needed for installation. I then open up the Python G... | The proper way to load CLR in Python is like this:
1. Make sure no old stuff is left from PythonNET in Python installation folder (e.g. C:\Python27). In my case I had legacy clr.pyd in one of folders. Note that pip for some old versions did not remove all parts of PythonNET.
2. Append the directory with PythonNET file... |
Loading .coverage files from coverage.py into IntelliJ IDEA/PyCharm's coverage view | 14,633,836 | 3 | 2013-01-31T19:41:38Z | 14,634,494 | 7 | 2013-01-31T20:25:55Z | [
"python",
"intellij-idea",
"pycharm"
] | I have `.coverage` files indicating code coverage of my Django project produced by [coverage.py](http://nedbatchelder.com/code/coverage/):
```
coverage run --branch --source='.' manage.py test style
```
I can produce nice HTML reports with `coverage html`, but I'd really prefer to take advantage of IDEA's coverage vi... | This is possible, at least as long as you run `coverage` in the root directory of your project.
First you need convert the `.coverage` file to `coverage.xml` by running `coverage xml`. Then it's just a matter of going to the *Analyze* menu, selecting "Show Code Coverage Data" and adding the XML file.
> Â Â Â Â Â Â Â ... |
ast.literal_eval: SyntaxError: unexpected EOF while parsing | 14,634,925 | 2 | 2013-01-31T20:52:32Z | 14,635,052 | 8 | 2013-01-31T21:00:34Z | [
"python"
] | When trying to parse an empty string I get a `SyntaxError`. Why does it raise a different error than parsing a `'foo'`? In the source of `ast.literal_eval` only `ValueError` is explicitly raised.
```
In [1]: import ast
In [2]: ast.literal_eval('foo')
-------------------------------------------------------------------... | `ast` uses `compile` to compile the source string (which must be an expression) into an AST.
If the source string is not a valid expression (like an empty string), a `SyntaxError` will be raised by `compile`. If, on the other hand, the source string would be a valid expression (e.g. a variable name like `foo`), `compi... |
Breakpoint-induced interactive debugging of Python with IPython | 14,635,299 | 23 | 2013-01-31T21:16:33Z | 14,635,386 | 9 | 2013-01-31T21:22:37Z | [
"python",
"debugging",
"breakpoints",
"ipython"
] | Say I have an IPython session, from which I call some script:
```
> run my_script.py
```
Is there a way to induce a breakpoint in `my_script.py` from which I can inspect my workspace from IPython?
I remember reading that in previous versions of IPython one could do:
```
from IPython.Debugger import Tracer;
de... | You can run it and set a breakpoint at a given line with:
```
run -d -b12 myscript
```
Where -b12 sets a breakpoint at line 12. When you enter this line, you'll immediately drop into pdb, and you'll need to enter `c` to execute up to that breakpoint. |
Breakpoint-induced interactive debugging of Python with IPython | 14,635,299 | 23 | 2013-01-31T21:16:33Z | 18,911,658 | 19 | 2013-09-20T07:58:38Z | [
"python",
"debugging",
"breakpoints",
"ipython"
] | Say I have an IPython session, from which I call some script:
```
> run my_script.py
```
Is there a way to induce a breakpoint in `my_script.py` from which I can inspect my workspace from IPython?
I remember reading that in previous versions of IPython one could do:
```
from IPython.Debugger import Tracer;
de... | The `Tracer()` still exists in ipython in a different module. You can do the following:
```
from IPython.core.debugger import Tracer
def my_function():
x = 5
Tracer()()
print 5
```
Note the additional call parentheses around `Tracer` |
Compressing "n"-time object member call | 14,635,914 | 3 | 2013-01-31T21:58:17Z | 14,635,987 | 7 | 2013-01-31T22:02:43Z | [
"python",
"for-loop",
"lambda",
"beautifulsoup"
] | Is there any non-explicit `for` way to call a member `n` times upon an object?
I was thinking about some `map/reduce/lambda` approach, but I couldn't figure out a way to do this -- if it's possible.
Just to add context, I'm using `BeautifulSoup`, and I'm extracting some elements from an html table; I extract some ele... | I have a strong preference for the loop, but you *could* use `reduce`:
```
>>> class Foo(object):
... def __init__(self):
... self.count = 0
... def callme(self):
... self.count += 1
... return self
...
>>> a = Foo()
>>> reduce(lambda x,y:x.callme(),range(7),a)
<__main__.Foo object at 0xe... |
SQLAlchemy: Modification of detached object | 14,636,192 | 14 | 2013-01-31T22:19:32Z | 14,657,112 | 28 | 2013-02-02T00:04:24Z | [
"python",
"sqlalchemy",
"duplicates",
"clone",
"instance"
] | I want to duplicate a model instance (row) in SQLAlchemy using the orm. My first thought was to do this:
```
i = session.query(Model)
session.expunge(i)
old_id = i.id
i.id = None
session.add(i)
session.flush()
print i.id #New ID
```
However, apparently the detached object still "remembers" what id it had, even thoug... | this case is available using the [make\_transient()](http://docs.sqlalchemy.org/en/latest/orm/session_api.html?highlight=make_transient#sqlalchemy.orm.session.make_transient) helper function:
```
inst = session.query(Model).first()
session.expunge(inst)
make_transient(inst)
inst.id = None
session.add(inst)
session.fl... |
Secure credential storage in python | 14,636,290 | 6 | 2013-01-31T22:26:57Z | 14,682,785 | 13 | 2013-02-04T08:18:21Z | [
"python",
"security",
"reflection",
"storage",
"credentials"
] | ## The attack
One possible threat model, in the context of credential storage, is an attacker which has the ability to :
* inspect any (user) process memory
* read local (user) files
AFAIK, the consensus on this type of attack is that it's impossible to prevent (since the credentials must be stored in memory for the... | There are two very different reasons why you might store authentication credentials:
1. To authenticate *your* user: For example, you only allow the user access to the services after the user authenticates to your program
2. To authenticate *the program* with another program or service: For example, the user starts yo... |
Writing append only gzipped log files in Python | 14,636,640 | 6 | 2013-01-31T22:53:22Z | 14,636,673 | 7 | 2013-01-31T22:56:31Z | [
"python",
"gzip"
] | I am building a service where I log plain text format logs from several sources (one file per source). I do not intend to rotate these logs as they must be around forever.
To make these forever around files smaller I hope I could gzip them in fly. As they are log data, the files compress very well.
What is a good app... | Note: On unix systems you should seriously consider using an external program, written for this exact task:
* [`logrotate`](http://linuxcommand.org/man_pages/logrotate8.html) (rotates, compresses, and mails system logs)
You can set the number of *rotations* so high, that the first file would be deleted [in 100 years]... |
Performing len on list of a zip object clears zip | 14,637,154 | 5 | 2013-01-31T23:36:35Z | 14,637,264 | 8 | 2013-01-31T23:45:32Z | [
"python",
"python-3.x"
] | I am seeing a strange behavior when working with the zip() function. When I perform the following operation len(list(z)) where z is a zip object, the result is 0 (which seems wrong to me), and the action seems to clear out the zip object. Can someone please help me understand what is going on.
```
# python3
Python 3.2... | In Python 3 [zip is a generator](http://docs.python.org/3/library/functions.html#zip). The generator is being exhausted when you do `list(z)`. You can create a list from the values returned by the generator and operate on that.
```
l = list(z)
len(l)
# -> 3
l
# -> [(1, 'a', 11), (2, 'b', 22), (3, 'c', 33)]
```
---
[... |
Python for loop isn't iterating '0' from a list | 14,637,155 | 2 | 2013-01-31T23:36:54Z | 14,637,209 | 8 | 2013-01-31T23:40:39Z | [
"python",
"list",
"for-loop",
"iteration"
] | Python for loop isn't iterating '0' from a list!
I tried to make a code to separate an input into numbers and letters(or operators):
```
g='10+10+20x'
t=[]
for each_g in g:
t.append(each_g)
lol=[]
a=[]
for each_t in t:
if each_t.isdigit():
lol.append(each_t)
x = t.index(each_t)
t.pop... | Don't modify a sequence that you're iterating over. Each `pop` is shifting a character down before you can process it.
In this case since you're not using `t` when you're done, there's no need for the `pop` at all - it's redundant. |
Making a weighted USA map based on state-level data | 14,637,396 | 5 | 2013-01-31T23:58:14Z | 14,637,692 | 7 | 2013-02-01T00:25:45Z | [
"java",
"python",
"maps",
"data-visualization"
] | I have a list of state-level data with numbers for each state, e.g.:
```
AL 10.5
AK 45.6
AZ 23.4
AR 15.0
...
```
and I want to make it into a weighted map, with darkest where the number is highest and lightest here it is lowest. Is there any software, or a java or python library that can generate such an image? | If you want to build it yourself, all you need is a good map, a set of positions for each state in this map, and flood fill.
Using the map <http://www.clker.com/cliparts/S/r/a/w/L/0/black-and-white-u-s-map-hi.png>, here is what we get:

The code to b... |
Length of longest word in a list | 14,637,696 | 7 | 2013-02-01T00:25:54Z | 14,637,742 | 7 | 2013-02-01T00:30:56Z | [
"python",
"string",
"performance",
"list",
"coding-style"
] | What is the more pythonic way of getting the length of the longest word:
`len(max(words, key=len))`
Or:
`max(len(w) for w in words)`
Or.. something else? `words` is a list of strings.
I am finding I need to do this often and after timing with a few different sample sizes the first way seems to be consistently faste... | Although:
```
max(len(w) for w in words)
```
does kind of "read" easier - you've got the overhead of a generator.
While:
```
len(max(words, key=len))
```
can optimise away with the key using builtins and since `len` is normally a very efficient op for strings, is going to be faster... |
python numpy array of arbitrary length strings | 14,639,496 | 19 | 2013-02-01T03:58:21Z | 14,639,548 | 8 | 2013-02-01T04:05:43Z | [
"python",
"arrays",
"string",
"numpy"
] | I'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. I.e. you can take a `string str` and keeping adding to it: `str += "some stuff..."`. Is there a way to make an array of such strings?
When I try this, each element only stores a single character
```
strArr ... | You could use the object data type:
```
>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)
``` |
python numpy array of arbitrary length strings | 14,639,496 | 19 | 2013-02-01T03:58:21Z | 14,639,568 | 40 | 2013-02-01T04:07:39Z | [
"python",
"arrays",
"string",
"numpy"
] | I'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. I.e. you can take a `string str` and keeping adding to it: `str += "some stuff..."`. Is there a way to make an array of such strings?
When I try this, each element only stores a single character
```
strArr ... | You can do so by creating an array of `dtype=object`. If you try to assign a long string to a normal numpy array, it truncates the string:
```
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
```
But when you use `dtype=object`, y... |
Python twisted reactor - address already in use | 14,640,711 | 7 | 2013-02-01T06:06:14Z | 15,773,500 | 25 | 2013-04-02T20:13:54Z | [
"python",
"osx",
"sockets",
"twisted"
] | I'm following a tutorial <http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server> for creating a sample using socket programming in Mac OS X enviromment.
I'm writing using post 80 for reactor.listenTCP(80, factory).
When I run the server.py file, getting an error:
```
File "server.py", l... | Open Activity Monitor, search for Python and kill the process. You probably messed up with closing a server once. |
How to guess image mime type? | 14,644,880 | 4 | 2013-02-01T11:03:07Z | 14,646,324 | 8 | 2013-02-01T12:28:10Z | [
"python",
"image",
"cross-platform",
"mime"
] | How can I guess an image's mime type, in a cross-platform manner, and without any external libraries? | If you know in advance that you only need to handle a limited number of file formats you can use the [imghdr.what](http://docs.python.org/3/library/imghdr.html#imghdr.what) function. |
Dynamically added static methods to a Python class | 14,645,353 | 5 | 2013-02-01T11:31:08Z | 14,645,396 | 9 | 2013-02-01T11:33:17Z | [
"python",
"oop",
"static-methods"
] | I [found](http://code.activestate.com/recipes/81732-dynamically-added-methods-to-a-class/) really good example how to add new method to the class dynamically (transplant class):
```
def say(host, msg):
print '%s says %s' % (host.name, msg)
def funcToMethod(func, clas, method_name=None):
setattr(clas, method_nam... | All you need to do is wrap the function in a `staticmethod()` call:
```
say = staticmethod(say)
```
or apply it as a decorator to the function definition:
```
@staticmethod
def say(host, msg):
# ...
```
which comes down to the same thing.
Just remember; the `@decorator` syntax is just syntactic sugar for writi... |
NumPy reading file with filtering lines on the fly | 14,645,789 | 8 | 2013-02-01T11:56:27Z | 14,791,245 | 14 | 2013-02-09T20:29:38Z | [
"python",
"input",
"numpy",
"large-files",
"bigdata"
] | I have a large array of numbers written in a CSV file and need to load only a slice of that array. Conceptually I want to call `np.genfromtxt()` and then row-slice the resulting array, but
1. the file is so large that may not to fit in RAM
2. the number of relevant rows might be small, so there is no need to parse eve... | I can think of two approaches that provide some of the functionality you are asking for:
1. **To read a file either in chunks / or in strides of n-lines / etc.:**
You can pass a `generator` to [numpy.genfromtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html#numpy.genfromtxt) as well as... |
Pandas - grouping intra day timeseries by date | 14,646,336 | 7 | 2013-02-01T12:29:00Z | 14,647,083 | 11 | 2013-02-01T13:12:35Z | [
"python",
"numpy",
"pandas",
"time-series"
] | I have an intra day series of log returns over multiple days that I would like to downsample to daily ohlc. I can do something like
```
hi = series.resample('B', how=lambda x: np.max(np.cumsum()))
low = series.resample('B', how=lambda x: np.min(np.cumsum()))
```
But it seems inefficient to compute cumsum on each call... | ```
df.groupby([df.index.year, df.index.month, df.index.day]).transform(np.cumsum).resample('B', how='ohlc')
```
I think this might be what I want but I have to test.
EDIT:
After zelazny7's repsonse:
```
df.groupby(pd.TimeGrouper('D')).transform(np.cumsum).resample('D', how='ohlc')
```
works and is also more effici... |
Python strip method | 14,646,436 | 6 | 2013-02-01T12:35:04Z | 14,646,468 | 14 | 2013-02-01T12:36:50Z | [
"python"
] | Today in python terminal, I tried
```
a = "serviceCheck_postmaster"
a.strip("serviceCheck_")
```
But instead of getting `"postmaster"`, I got `"postmast"`.
What could cause this? And how can I get `"postmaster"` as output? | You are misunderstanding what `.strip()` *does*. It removes *any* of the characters found in the string you pass. From the [`str.strip()` documentation](http://docs.python.org/2/library/stdtypes.html#str.strip):
> The *chars* argument is a string specifying the **set** of characters to be removed.
emphasis mine; the ... |
Python dictionary in to html table | 14,652,325 | 10 | 2013-02-01T18:02:11Z | 14,656,262 | 11 | 2013-02-01T22:39:27Z | [
"python",
"flask",
"jinja2"
] | Is there any way to print the python dictionary in to a table in HTML. I have a python dictionary and am sending to HTML by using
```
return render_template('index.html',result=result)
```
Now I need to print the elements in result dictionary in to HTML as a table. | Flask uses Jinja as the templating framework. You can just do the following in your template (html)
```
<table>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
``` |
How to pass SSH options with Fabric? | 14,652,965 | 10 | 2013-02-01T18:42:30Z | 14,653,419 | 7 | 2013-02-01T19:13:06Z | [
"python",
"ssh",
"automation",
"fabric"
] | We are trying to improve automation of some server processes; we use Fabric. I anticipate having to manage multiple hosts, and that means that SSH connections must be made to servers that haven't been SSH'd into before. If that happens, SSH always asks for verification of connection, which will break automation.
I hav... | The short answer is:
1. For new hosts, nothing is needed. `env.reject_unknown_hosts` defaults to `False`
2. For known hosts with changed keys, `env.disable_known_hosts = True` will decide to proceed connecting to changed hosts.
Read ye olde docs: <http://docs.fabfile.org/en/1.5/usage/ssh.html#unknown-hosts>
> The pa... |
Get HWND of each Window Python | 14,653,168 | 2 | 2013-02-01T18:56:17Z | 14,654,287 | 16 | 2013-02-01T20:16:03Z | [
"python",
"hwnd"
] | I am developing a python application and I want to get the HWND of each open windows. I need the name of the windows and the HWND to filter the list to manage some specifics windows, moving and resizing them.
I have tried to do it myself looking information around but I did not get the correct piece of code. I tried w... | You mixed up `ctypes` and `win32gui`.
The `hwnd` you've got is obtained via `ctypes` and is a `LP_c_long` object. That's why `win32gui.MoveWindow` didn't accept it. You should pass it to
```
ctypes.windll.user32.MoveWindow(titles[5][0], 0, 0, 760, 500, True)
```
If you want to use `win32gui.MoveWindow`, you can use... |
OpenCV error: the function is not implemented | 14,655,969 | 3 | 2013-02-01T22:17:22Z | 14,656,610 | 9 | 2013-02-01T23:07:52Z | [
"python",
"opencv"
] | I'm trying to get OpenCV working with Python on my Ubuntu machine. I've downloaded and installed OpenCV, but when I attempt to run the following python code (which should capture images from a webcam and push them to the screen)
```
import cv
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)
... | If it's giving you errors with gtk, try qt.
```
sudo apt-get install libqt4-dev
cmake -D WITH_QT=ON ..
make
sudo make install
```
If this doesn't work, there's an easy way out.
```
sudo apt-get install libopencv-*
```
This will download all the required dependencies(although it seems that you have all the required ... |
Cleaner way to read/gunzip a huge file in python | 14,655,982 | 7 | 2013-02-01T22:18:20Z | 14,656,093 | 39 | 2013-02-01T22:26:12Z | [
"python",
"gzip",
"subprocess",
"gunzip"
] | So I have some fairly gigantic .gz files - we're talking 10 to 20 gb each when decompressed.
I need to loop through each line of them, so I'm using the standard:
```
import gzip
f = gzip.open(path+myFile, 'r')
for line in f.readlines():
#(yadda yadda)
f.close()
```
However, both the `open()` and `close()` comman... | I'm 99% sure that your problem is not in the `gzip.open()`, but in the `readlines()`.
As [the documentation](http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) explains:
> f.readlines() returns a list containing all the lines of data in the file.
Obviously, that requires reading reading and ... |
Python Beginner's Loop (Finding Primes) | 14,656,473 | 3 | 2013-02-01T22:55:23Z | 14,656,759 | 9 | 2013-02-01T23:23:12Z | [
"python",
"primes"
] | I'm truly a beginner at python so I apologise for the lack of knowledge, but the reason I'm asking is that reading the Python manual and tutorial (<http://docs.python.org/2.7/tutorial>) I'm not unable to totally grasp how loops work. I've written some simple programs so I think I get the basics but for whatever reason ... | I would actually restructure the program to look like this:
```
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p,
print 'Done'
```
This is perhaps a more idiomatic solution (using a `for` loop instead of a `while` loop), and works perfectly.
The out... |
How to use pandas dataframes and numpy arrays in Rpy2? | 14,656,852 | 12 | 2013-02-01T23:32:46Z | 14,789,513 | 7 | 2013-02-09T15:17:40Z | [
"python",
"numpy",
"pandas",
"ipython",
"rpy2"
] | I'd like to use pandas for all my analysis along with numpy but use Rpy2 for plotting my data. I want to do all analyses using pandas dataframes and then use full plotting of R via rpy2 to plot these. py2, and am using ipython to plot. What's the correct way to do this?
Nearly all commands I try fail. For example:
* ... | [note: Your code in "edit 2" is working here (Python 2.7, rpy2-2.3.2, R-1.15.2).]
As @dale mentions it whenever R objects are anonymous (that is no R symbol exists for the object) the R `deparse(substitute())` will end up returning the `structure()` of the R object, and a possible fix is to specify the "xlab" and "yla... |
2 inputs to a function? | 14,656,951 | 5 | 2013-02-01T23:44:56Z | 14,656,967 | 12 | 2013-02-01T23:46:10Z | [
"python",
"python-2.7"
] | So Ive been giving the following code in a kind of sort of python class. Its really a discrete math class but he uses python to demonstrate everything. This code is supposed to demonstate a multiplexer and building a xor gate with it.
```
def mux41(i0,i1,i2,i3):
return lambda s1,s0:{(0,0):i0,(0,1):i1,(1,0):i2,(1,1... | The `(a, b)` is actually the input to the `lambda` function that you return in the `mux41` function.
Your `mux41` function returns a `lambda` function which looks like it returns a value in a dictionary based on the input to the `mux41` function. You need the second input to say which value you want to return.
It is ... |
Get local timezone in django | 14,657,173 | 10 | 2013-02-02T00:12:21Z | 14,661,355 | 13 | 2013-02-02T11:21:24Z | [
"python",
"django"
] | I have a mysql `DATETIME` value that is stored in system time, UTC. I need to convert that to my local timezone in django. Here is what I currently have:
```
# value in mysql
`timestamp`
2013-02-01 22:48:45
# settings.py
TIME_ZONE = 'America/Los_Angeles'
# views.py
last_updated = PathLastUpdated.objects.all()[0].tim... | The [Django documentation for timezones](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#time-zones) documents all the necessary details for converting `datetime` objects to the appropriate time zone for display.
Your data is stored in UTC which is good. When you obtain a `DateTime` field object from the ... |
Get local timezone in django | 14,657,173 | 10 | 2013-02-02T00:12:21Z | 29,616,811 | 9 | 2015-04-13T23:39:30Z | [
"python",
"django"
] | I have a mysql `DATETIME` value that is stored in system time, UTC. I need to convert that to my local timezone in django. Here is what I currently have:
```
# value in mysql
`timestamp`
2013-02-01 22:48:45
# settings.py
TIME_ZONE = 'America/Los_Angeles'
# views.py
last_updated = PathLastUpdated.objects.all()[0].tim... | After cry a lot, I could show the correct date for my country doing something like this:
```
>>> from django.utils.timezone import get_current_timezone
>>> from front.models import Training
>>> tz = get_current_timezone()
>>> stored_date = Training.objects.first().start_date
datetime.datetime(2015, 4, 25, 17, 0, tzin... |
How do I get a list of all the duplicate items using pandas in python? | 14,657,241 | 7 | 2013-02-02T00:22:08Z | 14,657,511 | 10 | 2013-02-02T01:01:09Z | [
"python",
"pandas"
] | I have a list of items that likely has some export issues. I would like to get a list of the duplicate items so I can manually compare them. When I try to use pandas [duplicated method](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.duplicated.html), it only returns the first duplicate. Is there a ... | Method #1: print all rows where the ID is one of the IDs in duplicated:
```
>>> import pandas as pd
>>> df = pd.read_csv("dup.csv")
>>> ids = df["ID"]
>>> df[ids.isin(ids[ids.duplicated()])].sort("ID")
ID ENROLLMENT_DATE TRAINER_MANAGING TRAINER_OPERATOR FIRST_VISIT_DATE
24 11795 27-Feb-12 ... |
Cython: "fatal error: numpy/arrayobject.h: No such file or directory" | 14,657,375 | 53 | 2013-02-02T00:38:35Z | 14,657,667 | 77 | 2013-02-02T01:26:29Z | [
"python",
"windows-7",
"numpy",
"cython"
] | I'm trying to speed up the answer [here](http://stackoverflow.com/a/14469557/1658908) using Cython. I try to compile the code (after doing the `cygwinccompiler.py` hack explained [here](http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o/6035864#6035... | In your `setup.py`, the `Extension` should have the argument `include_dirs=[numpy.get_include()]`.
Also, you are missing `np.import_array()` in your code.
--
**Example setup.py:**
```
from distutils.core import setup, Extension
from Cython.Build import cythonize
import numpy
setup(
ext_modules=[
Extens... |
Cython: "fatal error: numpy/arrayobject.h: No such file or directory" | 14,657,375 | 53 | 2013-02-02T00:38:35Z | 14,678,559 | 24 | 2013-02-03T23:24:34Z | [
"python",
"windows-7",
"numpy",
"cython"
] | I'm trying to speed up the answer [here](http://stackoverflow.com/a/14469557/1658908) using Cython. I try to compile the code (after doing the `cygwinccompiler.py` hack explained [here](http://stackoverflow.com/questions/6034390/compiling-with-cython-and-mingw-produces-gcc-error-unrecognized-command-line-o/6035864#6035... | For a one-file project like yours, another alternative is to use `pyximport`. You don't need to create a `setup.py` ... you don't need to even open a command line if you use IPython ... it's all very convenient. In your case, try running these commands in IPython or in a normal Python script:
```
import numpy
import p... |
correlation matrix in python | 14,657,433 | 10 | 2013-02-02T00:48:21Z | 14,657,458 | 14 | 2013-02-02T00:53:53Z | [
"python"
] | How do I calculate correlation matrix in python? I have an n-dimensional vector in which each element has 5 dimension. For example my vector looks like
```
[
[0.1, .32, .2, 0.4, 0.8],
[.23, .18, .56, .61, .12],
[.9, .3, .6, .5, .3],
[.34, .75, .91, .19, .21]
]
```
In this case dimension of the vector is ... | Using [numpy](http://www.numpy.org/), you could use [np.corrcoef](http://docs.scipy.org/doc/numpy/reference/generated/numpy.corrcoef.html):
```
In [88]: import numpy as np
In [89]: np.corrcoef([[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3], [.34, .75, .91, .19, .21]])
Out[89]:
array([[ 1.... |
Most pythonic way to process this text file using python | 14,657,543 | 2 | 2013-02-02T01:06:24Z | 14,657,604 | 7 | 2013-02-02T01:16:35Z | [
"python"
] | I have a text file containg test data that looks like:
```
hdr 1
hdr2
hdr3
data1
data2
data3
data1
data2
....
```
There is a blank line between every line.
I need to create a list of lists containing
```
[[hdr1,hdr2,hdr3],[data1,data2,data3],[data1,data2,...]
```
What would be a concise, pythonic way of do... | Assuming your data will always be in blocks of 3 like in your example, you could probably use `itertools`, and if you pass the same iterator 6 times then you should end up with 6 fields, 3 of them the empty lines, and the other ones the group of 3 you're interested in:
```
import itertools
arr = []
with open('input.t... |
Convert Python dictionary to JSON array | 14,661,051 | 39 | 2013-02-02T10:44:40Z | 14,661,102 | 67 | 2013-02-02T10:50:04Z | [
"python",
"python-2.7"
] | Currently I have this dictionary, printed using `pprint`:
```
{'AlarmExTempHum': '\x00\x00\x00\x00\x00\x00\x00\x00',
'AlarmIn': 0,
'AlarmOut': '\x00\x00',
'AlarmRain': 0,
'AlarmSoilLeaf': '\x00\x00\x00\x00',
'BarTrend': 60,
'BatteryStatus': 0,
'BatteryVolts': 4.751953125,
'CRC': 55003,
'EOL': '\n\r',
'... | If you are fine with non-printable symbols in your json, then add `ensure_ascii=False` to `dumps` call.
```
>>> json.dumps(your_data, ensure_ascii=False)
```
> If `ensure_ascii` is false, then the return value will be a
> `unicode` instance subject to normal Python `str` to `unicode`
> coercion rules instead of being... |
Convert Python dictionary to JSON array | 14,661,051 | 39 | 2013-02-02T10:44:40Z | 14,661,482 | 11 | 2013-02-02T11:36:50Z | [
"python",
"python-2.7"
] | Currently I have this dictionary, printed using `pprint`:
```
{'AlarmExTempHum': '\x00\x00\x00\x00\x00\x00\x00\x00',
'AlarmIn': 0,
'AlarmOut': '\x00\x00',
'AlarmRain': 0,
'AlarmSoilLeaf': '\x00\x00\x00\x00',
'BarTrend': 60,
'BatteryStatus': 0,
'BatteryVolts': 4.751953125,
'CRC': 55003,
'EOL': '\n\r',
'... | ensure\_ascii=False really only defers the issue to the decoding stage:
```
>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "����"}
>>> json.loads(json1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Fi... |
How to drop a list of rows from Pandas dataframe? | 14,661,701 | 92 | 2013-02-02T12:03:46Z | 14,661,768 | 131 | 2013-02-02T12:11:11Z | [
"python",
"pandas"
] | I have a dataframe df :
```
>>> df
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20060630 6.590 NaN 6.590 5.291
20060930 10.103 NaN 10.103 7.981
20061231 15... | Use [DataFrame.drop](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html) and pass it a Series of index labels:
```
In [65]: df
Out[65]:
one two
one 1 4
two 2 3
three 3 2
four 4 1
In [66]: df.drop(df.index[[1,3]])
Out[66]:
one two
one 1... |
How to drop a list of rows from Pandas dataframe? | 14,661,701 | 92 | 2013-02-02T12:03:46Z | 34,614,046 | 23 | 2016-01-05T14:28:26Z | [
"python",
"pandas"
] | I have a dataframe df :
```
>>> df
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20060630 6.590 NaN 6.590 5.291
20060930 10.103 NaN 10.103 7.981
20061231 15... | Note that it may be important to use the "inplace" command when you want to do the drop in line.
```
df.drop(df.index[[1,3]], inplace=True)
```
Because your original question is not returning anything, this command should be used.
<http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.drop.ht... |
How to drop a list of rows from Pandas dataframe? | 14,661,701 | 92 | 2013-02-02T12:03:46Z | 37,097,791 | 10 | 2016-05-08T08:28:42Z | [
"python",
"pandas"
] | I have a dataframe df :
```
>>> df
sales discount net_sales cogs
STK_ID RPT_Date
600141 20060331 2.709 NaN 2.709 2.245
20060630 6.590 NaN 6.590 5.291
20060930 10.103 NaN 10.103 7.981
20061231 15... | You can also pass to [DataFrame.drop](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html) the *label itself* (instead of Series of index labels):
```
In[17]: df
Out[17]:
a b c d e
one 0.456558 -2.536432 0.216279 -1.305855 -0.121635
two -1.015... |
Determining if a given Python module is part of the standard library | 14,662,220 | 5 | 2013-02-02T13:11:18Z | 14,662,355 | 8 | 2013-02-02T13:28:54Z | [
"python",
"module",
"standard-library"
] | How can I determine whether a Python module is part of the standard library?
In other words: is there a Python equivalent of perl's corelist utility?
I would use this to set my expectations on portability during development.
In case it's implementation dependent, I'm interested in CPython.
The best answer I found so ... | When using a setuptools install script (`setup.py`), you *test* for the required module, and update the installation dependencies list to add backports if needed.
For example, say you need the `collections.OrderedDict` class. The documentation states it was added in Python 2.7, but a [backport is available](http://pyp... |
blender game engine import error | 14,662,663 | 8 | 2013-02-02T14:03:15Z | 14,664,287 | 11 | 2013-02-02T17:08:25Z | [
"python",
"blender"
] | i just started learning blender and its scripting and tried to run its sample code
```
import bge
def main():
cont = bge.logic.getCurrentController()
own = cont.owner
sens = cont.sensors['mySensor']
actu = cont.actuators['myActuator']
if sens.positive:
cont.activate(actu)
else:
cont.deactivate(actu)
main(... | Running import bge does not work when you press "Run script" or try to issue this command in the terminal. You have to press "P" to activate game engine mode. To run your script, connect a controller to the script. |
Foreign Key Django Model | 14,663,523 | 14 | 2013-02-02T15:43:28Z | 14,663,580 | 33 | 2013-02-02T15:48:07Z | [
"python",
"django"
] | I'm trying to create 3 models ; `Person`, `Address` and `Anniversy`. The plan is to have one address and one anniversy for each person. But each address and anniversy can have multiple persons.
So far I have the following, but I think the `OneToMany(foreign key)` relationships maybe the wrong way round. i.e each addre... | You create the relationships the other way around; add foreign keys to the `Person` type to create a Many-to-One relationship:
```
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(Anniversary)
address = models.ForeignKey(Ad... |
Parse HTML using LXML in Python | 14,663,659 | 2 | 2013-02-02T15:57:44Z | 14,663,673 | 13 | 2013-02-02T15:59:17Z | [
"python",
"html",
"parsing",
"html-parsing",
"lxml"
] | I am trying to parse a website for
```
blahblahblah
<a href="THIS IS WHAT I WANT" title="NOT THIS">I DONT CARE ABOUT THIS EITHER</a>
blahblahblah
```
(there are many of these, and I want all of them in some tokenized form). Unfortunately the HTML is very large and a little complicated, so trying to crawl down the t... | If you just want the href's for `a` tags, then use:
```
data = """blahblahblah
<a href="THIS IS WHAT I WANT" title="NOT THIS">I DONT CARE ABOUT THIS EITHER</a>
blahblahblah"""
import lxml.html
tree = lxml.html.fromstring(data)
print tree.xpath('//a/@href')
# ['THIS IS WHAT I WANT']
``` |
Python .split() without 'u | 14,664,209 | 7 | 2013-02-02T16:58:34Z | 14,664,221 | 16 | 2013-02-02T17:00:07Z | [
"python",
"unicode-string"
] | In Python, if I have a string like:
```
a =" Hello - to - everybody"
```
And I do
```
a.split('-')
```
then I get
```
[u'Hello', u'to', u'everybody']
```
This is just an example.
How can I get a simple list without that annoying u'?? | The `u` means that it's a unicode string - your original string must also have been a unicode string. Generally it's a good idea to keep strings Unicode as trying to convert to normal strings could potentially fail due to characters with no equivalent.
The `u` is purely used to let you know it's a unicode string in th... |
'Attempted relative import in non-package' although packages with __init__.py in one directory | 14,664,313 | 18 | 2013-02-02T17:10:58Z | 14,664,354 | 29 | 2013-02-02T17:14:14Z | [
"python",
"python-2.7",
"python-import"
] | I have a module named `extended.py` contains has the following line
```
from .basic import BasicModule
```
and the file `basic.py` resides in the same directory ad does `__init__.py`. But still, when I try to run is as
```
python extended.py
```
I get the error
```
ValueError: Attempted relative import in non-pack... | Relative imports only work for packages, but when you import `extended.py` you are running a *top-level module* instead.
The current directory may hold a `__init__.py` file but that doesn't make `exended.py` part of a package yet.
For something to be considered a package, you need to import the *directory name* inste... |
Using Python ârequestsâ with existing socket connection | 14,665,064 | 8 | 2013-02-02T18:30:01Z | 14,671,133 | 8 | 2013-02-03T09:33:11Z | [
"python",
"http",
"sockets",
"python-requests"
] | The Python ârequestsâ library is currently all the rage, because of the beautiful interface that it provides for making HTTP requests â but beneath it there seems to be many layers of indirection â sessions, HTTP adapters, and finally the mechanics of urllib3.
Where in this stack of abstractions is the right p... | The following code needs requests from git (especially `requests.packages.urllib3.poolmanager.PoolManager._new_pool()`)
I tested it using `ncat -v -l 127.0.0.1 8000`
The problem is the fact, that the connection isn't opened by urllib3 but by httplib from the standard library.
```
import socket
import requests
from r... |
How to easily distribute Python software that has Python module dependencies? Frustrations in Python package installation on Unix | 14,665,216 | 51 | 2013-02-02T18:45:27Z | 14,666,146 | 13 | 2013-02-02T20:24:00Z | [
"python",
"pip",
"setuptools",
"package-managers",
"distribute"
] | My goal is to distribute a Python package that has several other widely used Python packages as dependencies. My package depends on well written, Pypi-indexed packages like pandas, scipy and numpy, and specifies in the setup.py that certain versions or higher of these are needed, e.g. "numpy >= 1.5".
I found that it's... | We also develop software projects that depend on numpy, scipy and other PyPI packages. Hands down, the best tool currently available out there for managing remote installations is [zc.buildout](http://www.buildout.org/). It is **very** easy to use. You download a bootstrapping script from their website and distribute t... |
argparse choices structure of allowed values | 14,665,234 | 6 | 2013-02-02T18:47:16Z | 14,711,925 | 14 | 2013-02-05T16:15:30Z | [
"python",
"argparse"
] | Using `argparse` in relation to [Python dependencies between groups using argparse](http://stackoverflow.com/questions/14660876/python-dependencies-between-groups-using-argparse), I have an argument part of some parser group of a parser - for example:
```
group_simulate.add_argument('-P',
h... | You can define a custom type that will raise an `argparse.ArgumentTypeError` if the string
doesn't match the format you need.
```
def SpecialString(v):
fields = v.split(":")
# Raise a value error for any part of the string
# that doesn't match your specification. Make as many
# checks as you need. I've... |
Networkx specific nodes labeling | 14,665,767 | 4 | 2013-02-02T19:45:22Z | 14,667,533 | 9 | 2013-02-02T23:08:48Z | [
"python",
"networkx"
] | I want to draw a network and I want it to be unlabeled with the exception for cretin nodes.
What I have at the moment is something like this:
```
nx.draw(G, pos=pos, node_color='b', node_size=8, with_labels=False)
for hub in hubs:
nx.draw_networkx_nodes(G, pos, nodelist=[hub[0]], node_color='r')
```
The code a... | From Bula's comment the solution is quite easy
The trick is to set the labels in a dictionary where the key is the node name and the value is the label you require. Therefore to label only the hubs, the code will be something similar to this:
```
labels = {}
for node in G.nodes():
if node in hubs:
#se... |
Understanding Virtual Environment for Python | 14,667,005 | 5 | 2013-02-02T22:03:43Z | 14,667,125 | 11 | 2013-02-02T22:18:28Z | [
"python",
"unix",
"virtualenv"
] | I've been reading up on virtual environment, and it seems like an extremely useful tool, but now I'm questioning how I've set up my entire python environment thus far. Right now, all of the modules and packages that I have installed are residing in this directory:
```
/Library/Frameworks/Python.framework/Versions/2.7/... | If you've already installed virtualenv like this:
```
pip install virtualenv
```
You'll then want to setup a particular virtualenv folder:
```
virtualenv [your project folder name]
```
This will create that project folder with a few important subdirectories.
You'll activate your virtualenv first before installing ... |
check if a number already exist in a list in python | 14,667,578 | 15 | 2013-02-02T23:15:39Z | 14,667,593 | 7 | 2013-02-02T23:17:42Z | [
"python",
"list"
] | I am writing a python code where I will be appending numbers into a list, but I dont want the numbers in the list to repeat. So how do i check if a number is already in the list, before I do `list.append()`? | If you want to have unique elements in your list, then why not use a set, if of course, order does not matter for you: -
```
>>> s = set()
>>> s.add(2)
>>> s.add(4)
>>> s.add(5)
>>> s.add(2)
>>> s
39: set([2, 4, 5])
```
If order is a matter of concern, then you can use: -
```
>>> def addUnique(l, num):
... if nu... |
check if a number already exist in a list in python | 14,667,578 | 15 | 2013-02-02T23:15:39Z | 14,667,600 | 39 | 2013-02-02T23:18:47Z | [
"python",
"list"
] | I am writing a python code where I will be appending numbers into a list, but I dont want the numbers in the list to repeat. So how do i check if a number is already in the list, before I do `list.append()`? | You could do
```
if item not in mylist:
mylist.append(item)
```
But you should really use a set, like this :
```
myset = set()
myset.add(item)
```
**EDIT:** If order is important but your list is very big, you should probably use both a list *and* a set, like so:
```
mylist = []
myset = set()
for item in ...:... |
User defined type checking in python: "type(A()) is A" returns false | 14,668,105 | 9 | 2013-02-03T00:21:12Z | 14,668,172 | 13 | 2013-02-03T00:30:52Z | [
"python",
"types"
] | From this post - [What's the canonical way to check for type in python?](http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python), I could use this code to check object o is string type.
```
o = "str"; print type(o) is str --> True
```
However, with user defined type, `type(a) is... | You should use the new-style classes:
```
class A(object):
pass
```
That is, derive it from `object`.
The problem is that object of old-style are implemented as if all of them were of type `instance`.
Deriving directly or indirectly from `object` will solve this issue. Or moving to Python3, where there is no mo... |
Pickle versus shelve storing large dictionaries in Python | 14,668,475 | 12 | 2013-02-03T01:13:58Z | 14,668,786 | 18 | 2013-02-03T02:07:01Z | [
"python",
"pickle",
"shelve"
] | If I am storing a large directory as a `pickle` file, does loading it via `cPickle` mean that it will all be consumed into memory at once?
If so, is there a cross platform way to get something like `pickle`, but access each entry one key at a item (i.e. avoid loading all of the dictionary into memory and only load eac... | > I know shelve is supposed to do this: is that as portable as pickle though?
Yes. [`shelve`](http://docs.python.org/2/library/shelve.html) is part of [The Python Standard Library](http://docs.python.org/2/library/) and is written in Python.
### Edit
So if you have a large dictionary:
```
bigd = {'a': 1, 'b':2, # .... |
Mathematical function, unassigned variables? | 14,668,495 | 2 | 2013-02-03T01:17:16Z | 14,668,615 | 7 | 2013-02-03T01:37:29Z | [
"python",
"function",
"unassigned-variable"
] | I am looking for a way to add together multiple mathematical functions before assigning the numerical values for the variables in the equations.
I am doing it this way because I need to optimize my code, and I want to assign different values to the variables each time. An example of what I am trying to do:
1. `f(x, ... | [SymPy](http://sympy.org/en/index.html) can do this:
```
import sympy as sym
x, y = sym.symbols('xy')
f = x + 2*y
g = 3*x - y
h = f + g
```
This shows that [SymPy](http://sympy.org/en/index.html) has simplified the expression:
```
print(h)
# y + 4*x
```
And this shows how you can evaluate `h` as a function of `x` ... |
Calculating strings as values | 14,668,750 | 3 | 2013-02-03T02:01:23Z | 14,668,905 | 7 | 2013-02-03T02:29:06Z | [
"python",
"string"
] | Is it possible in Python to calculate a term in a string?
For example:
```
string_a = "4 ** (3 - 2)"
unknown_function(string_a) = 4
```
Is this possible? Is there a function that mimics "unknown\_function" in my example?
Thanks! | Just like `sympy` was a useful module for your [last question](http://stackoverflow.com/questions/14668495/mathematical-function-unassigned-variables), it can apply here:
```
>>> import sympy
>>> sympy.sympify("4**(3-2)")
4
```
and even
```
>>> sympy.sympify("2*x+y")
2*x + y
>>> sympy.sympify("2*x+y").subs(dict(x=2,... |
Python: urlretrieve PDF downloading | 14,669,827 | 3 | 2013-02-03T05:40:40Z | 14,669,892 | 9 | 2013-02-03T05:54:32Z | [
"python",
"pdf",
"urllib2",
"urllib"
] | I am using urllib's urlretrieve() function in Python in order to try to grab some pdf's from websites. It has (at least for me) stopped working and is downloading damaged data (15 KB instead of 164 KB).
I have tested this with several pdf's, all with no success (ie [random.pdf](http://www.mathworks.com/moler/random.pd... | I would suggest trying out [requests](http://docs.python-requests.org/en/latest/). It is a really nice library that hides all of the implementation behind a simple api.
```
>>> import requests
>>> req = requests.get("http://www.mathworks.com/moler/random.pdf")
>>> len(req.content)
167633
>>> req.headers
{'content-leng... |
Handling multiple requests in Flask | 14,672,753 | 13 | 2013-02-03T13:02:59Z | 14,672,774 | 18 | 2013-02-03T13:05:18Z | [
"python",
"flask"
] | My Flask applications has to do quite a large calculation to fetch a certain page. While Flask is doing that function, another user cannot access the website, because Flask is busy with the large calculation.
Is there any way that I can make my Flask application accept requests from multiple users? | Yes, deploy your application on a different WSGI server, see the [Flask deployment options documentation](http://flask.pocoo.org/docs/deploying/).
The server component that comes with Flask is really only meant for when you are developing your application; even though it can be configured to handle concurrent requests... |
How to make Jinja2 convert all UndefinedError exceptions to blank strings? | 14,672,992 | 4 | 2013-02-03T13:29:57Z | 14,764,798 | 7 | 2013-02-08T02:31:22Z | [
"python",
"flask",
"jinja2"
] | A lot of the models in my code have relations that can be None. Many times, this requires checks for `None` before accessing the data:
```
{% if foo.bar %}
{{ foo.bar.baz }}
{% endif %}
```
If I don't add that check, the page breaks completely with an UndefinedError. Is there any way I can fail silently for Undefi... | Simply create a subclass of [`jinja2.Undefined`](http://jinja.pocoo.org/docs/api/#jinja2.Undefined) that returns itself on attribute access and set it as the Undefined type for your environment by overriding the [`create_jinja_environment`](http://flask.pocoo.org/docs/api/#flask.Flask.create_jinja_environment) method:
... |
SQLAlchemy Union Parenthesis Issue | 14,673,060 | 6 | 2013-02-03T13:37:32Z | 14,673,111 | 14 | 2013-02-03T13:42:28Z | [
"python",
"python-2.7",
"sqlalchemy"
] | I need to generate a query similar to the following:
```
(select * from ... where .. and .. order by .. limit ..)
union all
(select * from ... where .. and .. order by .. limit ..)
order by ..
```
Using SQLAlchemy, I create two query objects as in:
```
q1 = Session.query(..).filter(..).filter(..).order_by(..).limit(... | You need to create subqueries, then select from those subqueries:
```
from sqlalchemy import union_all
q1 = Session.query(..).filter(..).filter(..).order_by(..).limit(..).subquery()
q2 = Session.query(..).filter(..).filter(..).order_by(..).limit(..).subquery()
q = Session.query(..).select_entity_from(union_all(q1.sel... |
python pandas extract unique dates from time series | 14,673,394 | 9 | 2013-02-03T14:14:50Z | 14,673,649 | 20 | 2013-02-03T14:41:41Z | [
"python",
"datetime",
"dataframe",
"pandas",
"time-series"
] | I have a DataFrame which contains a lot of intraday data, the DataFrame has several days of data, dates are not continuous.
```
2012-10-08 07:12:22 0.0 0 0 2315.6 0 0.0 0
2012-10-08 09:14:00 2306.4 20 326586240 2306.4 472 2306.8 4
2012-10-08 09:15:00 2306.8... | If you have a `Series` like:
```
In [116]: df["Date"]
Out[116]:
0 2012-10-08 07:12:22
1 2012-10-08 09:14:00
2 2012-10-08 09:15:00
3 2012-10-08 09:15:01
4 2012-10-08 09:15:01.500000
5 2012-10-08 09:15:02
6 2012-10-08 09:15:02.500000
7 2012-10-10 07:19:3... |
Can't parse simple json with python | 14,674,057 | 3 | 2013-02-03T15:29:28Z | 14,674,108 | 8 | 2013-02-03T15:34:20Z | [
"python",
"json",
"simplejson"
] | I have a very simple json I can't parse with simplejson module.
Reproduction:
```
import simplejson as json
json.loads(r'{"translatedatt1":"Vari\351es"}')
```
Result:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.5/simplejson/__init__.py", line 307, i... | That would be quite correct; `Vari\351es` contains an invalid escape, the JSON standard does not allow for a `\` followed by just numbers.
Whatever produced that code should be fixed. If that is impossible, you'll need to use a regular expression to either remove those escapes, or replace them with valid escapes.
If ... |
Word Frequency calculation for 1Gb text file in Python | 14,674,266 | 4 | 2013-02-03T15:51:16Z | 14,674,326 | 13 | 2013-02-03T15:57:28Z | [
"python",
"word-frequency"
] | I am trying to calculate word frequency for a text file of size 1.2 GB which was around 203 million words. I am using the following Python code. But its giving me a memory error. Is there any solution for this?
Here is my code:
```
import re
# this one in honor of 4th July, or pick text file you have!!!!!!!
filename ... | The problem begins right here:
```
file(filename).read()
```
This reads in the whole file into a string. Instead, if you process the file line-by-line or chunk-by-chunk, you won't run into a memory problem.
```
with open(filename) as f:
for line in f:
```
---
You could also benefit from using a [collections.Co... |
How to read text file into a list or array with Python | 14,676,265 | 30 | 2013-02-03T19:19:51Z | 14,676,357 | 46 | 2013-02-03T19:29:10Z | [
"python",
"arrays",
"list",
"text"
] | I am trying to read the lines of a text file into a list or array in python. I just need to be able to individually access any item in the list or array after it is created.
The text file is formatted as follows:
```
0,0,200,0,53,1,0,255,...,0.
```
Where the `...` is above, there actual text file has hundreds or tho... | You will have to split your string into a list of values using `split()`
So,
```
lines = text_file.read().split(',')
``` |
How to read text file into a list or array with Python | 14,676,265 | 30 | 2013-02-03T19:19:51Z | 14,685,073 | 13 | 2013-02-04T10:46:55Z | [
"python",
"arrays",
"list",
"text"
] | I am trying to read the lines of a text file into a list or array in python. I just need to be able to individually access any item in the list or array after it is created.
The text file is formatted as follows:
```
0,0,200,0,53,1,0,255,...,0.
```
Where the `...` is above, there actual text file has hundreds or tho... | You can also use numpy loadtxt like
```
from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)
``` |
How to read text file into a list or array with Python | 14,676,265 | 30 | 2013-02-03T19:19:51Z | 24,284,411 | 16 | 2014-06-18T11:31:22Z | [
"python",
"arrays",
"list",
"text"
] | I am trying to read the lines of a text file into a list or array in python. I just need to be able to individually access any item in the list or array after it is created.
The text file is formatted as follows:
```
0,0,200,0,53,1,0,255,...,0.
```
Where the `...` is above, there actual text file has hundreds or tho... | **python's file.readLines() method returns a list of the lines in the file:**
```
f = open('file_name.ext', 'r')
x = f.readlines()
```
Now you should be able to iterate through the array of lines x. |
multiprocessing with large data | 14,677,287 | 18 | 2013-02-03T21:02:57Z | 14,677,441 | 13 | 2013-02-03T21:21:07Z | [
"python",
"multiprocessing",
"generator"
] | I am using `multiprocessing.Pool()` to parallelize some heavy computations.
The target function returns a lot of data (a huge list). I'm running out of RAM.
Without `multiprocessing`, I'd just change the target function into a generator, by `yield`ing the resulting elements one after another, as they are computed.
I... | This sounds like an ideal use case for a Queue: <http://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes>
Simply feed your results into the queue from the pooled workers and ingest them in the master.
Note that you still may run into memory pressure issues unless you drain the queue... |
Python Hexadecimal | 14,678,132 | 29 | 2013-02-03T22:33:29Z | 14,678,150 | 65 | 2013-02-03T22:34:37Z | [
"python",
"hex"
] | How to convert decimal to hex in the following format?
Input: `255` Output:`ff`
Input: `2` Output: `02`
I tried `hex(int)[2:]` but it seems that it displays the first example but not the second one. | Use the [`format()` function](http://docs.python.org/2/library/functions.html#format) with a `'02x'` format.
```
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
```
The `02` part tells `format()` to use at least 2 digits and to use zeros to pad it to length, `x` means lower-case hexadecimal.
The [*Format Speci... |
Python Hexadecimal | 14,678,132 | 29 | 2013-02-03T22:33:29Z | 14,678,368 | 12 | 2013-02-03T22:58:20Z | [
"python",
"hex"
] | How to convert decimal to hex in the following format?
Input: `255` Output:`ff`
Input: `2` Output: `02`
I tried `hex(int)[2:]` but it seems that it displays the first example but not the second one. | I think this is what you want:
```
>>> def twoDigitHex( number ):
... return '%02x' % number
...
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'
``` |
Finding every nth element in a list | 14,680,273 | 3 | 2013-02-04T04:13:30Z | 14,680,282 | 16 | 2013-02-04T04:15:37Z | [
"python"
] | I'm attempting to find every nth element in a list, but I'm pretty lost on it. Here is my code:
```
def returnNth(lst, n):
'list ==> list, return every nth element in lst for n > 0'
res = []
for a in lst:
res = res + [a[::n]]
return res
```
I figured [a[::n]] could be used to find the result, but I just get the e... | You need `lst[::n]` only, no need to iterate over the elements of the list at all.
example:
```
>>> lst=[1,2,3,4,5,6,7,8,9,10]
>>> lst[::3]
[1, 4, 7, 10]
>>>
``` |
typeError: isinstance() arg 2 must be a type or tuple of types >>> | 14,681,096 | 6 | 2013-02-04T05:52:55Z | 14,681,115 | 14 | 2013-02-04T05:54:05Z | [
"python"
] | ```
>>> names=['jhon','jack']
>>> isinstance(names,list)
Traceback (most recent call last):
File "<pyshell#291>", line 1, in <module>
isinstance(names,list)
TypeError: isinstance() arg 2 must be a type or tuple of types
>>>
```
am i missing something here? | You've stomped on `list` by assigning to a local variable of the same name. Don't do that. |
Create a 2D list out of 1D list | 14,681,609 | 2 | 2013-02-04T06:45:13Z | 14,681,687 | 8 | 2013-02-04T06:51:41Z | [
"python",
"matrix"
] | I am a bit new to Python and I want to convert a 1D list to a 2D list, given the `width` and `length` of this `matrix`.
Say I have a `list=[0,1,2,3]` and I want to make a `2 by 2` matrix of this list.
How can I get `matrix [[0,1],[2,3]]` `width`=2, `length`=2 out of the `list`? | Try something like that:
```
In [53]: l = [0,1,2,3]
In [54]: def to_matrix(l, n):
...: return [l[i:i+n] for i in xrange(0, len(l), n)]
In [55]: to_matrix(l,2)
Out[55]: [[0, 1], [2, 3]]
``` |
Can somone explain how unicodedata.normalize(form, unistr) work with examples? | 14,682,397 | 12 | 2013-02-04T07:48:09Z | 14,682,498 | 18 | 2013-02-04T07:56:43Z | [
"python",
"unicode",
"encoding",
"normalization",
"unicode-normalization"
] | So on the API doc, <http://docs.python.org/2/library/unicodedata.html#unicodedata.normalize>. It says
> Return the normal form *form* for the Unicode string *unistr*. Valid values for form are âNFCâ, âNFKCâ, âNFDâ, and âNFKDâ.`
The documentation is rather vague, can someone explain the `valid values` ... | I find the documentation pretty clear, but here are a few code examples:
```
from unicodedata import normalize
print '%r' % normalize('NFD', u'\u00C7') # decompose: convert à to "C + ̧"
print '%r' % normalize('NFC', u'C\u0327') # compose: convert "C + ̧" to Ã
```
Both 'D' (=decompose) forms convert a single com... |
How to export virtualenv? | 14,684,968 | 11 | 2013-02-04T10:39:43Z | 14,685,017 | 29 | 2013-02-04T10:43:09Z | [
"python",
"django",
"virtualenv"
] | I'm new to virtualenv but I'm writting django app and finally I will have to deploy it somehow.
So lets assume I have my app working on my local virtualenv where I installed all the required libraries. What I want to do now, is to run some kind of script, that will take my virtualenv, check what's installed inside and... | You don't copy paste your virtualenv. You export the list of all the packages installed like -
```
pip freeze > requirements.txt
```
Then push the `requirements.txt` file to anywhere you want to deploy the code, and then just do what you did on dev machine -
```
$ virtualenv <env_name>
$ source <env_name>/bin/activa... |
Django: How can I check the last activity time of user if user didn't log out? | 14,685,576 | 9 | 2013-02-04T11:14:02Z | 14,685,763 | 18 | 2013-02-04T11:24:53Z | [
"python",
"django",
"middleware"
] | django's User model has a `last_login` field, which is great if all the users were to log out each time they leave the site, but what if they don't?
How can I track when a user who never logged out and his activity on the site? | You need to have the `last_activity` field in the user profile (or custom user model). This field will be updated on every request. To achieve this you need to have custom middleware:
profiles/middleware.py:
```
from django.utils import timezone
from myproject.profiles.models import Profile
class UpdateLastActivit... |
Trigger an event when clipboard content changes | 14,685,999 | 4 | 2013-02-04T11:38:56Z | 14,687,465 | 7 | 2013-02-04T13:09:53Z | [
"python",
"multithreading",
"osx",
"events",
"clipboard"
] | I'm trying to get the clipboard content using a Python script on my Mac Lion.
I'm searching for an event or something similar, because if I use a loop, my application spends all its time watching the clipboard.
Any ideas? | Have you thought about using an endless loop and "sleeping" between tries?
I used [pyperclip](http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/) for a simple PoC and it worked like a charm, and Windows and Linux.
```
import time
import sys
import os
sys.path.append(os.path.abspa... |
Python IPC - Twisted, RabbitMQ, | 14,686,136 | 6 | 2013-02-04T11:48:00Z | 14,715,652 | 9 | 2013-02-05T19:46:55Z | [
"python",
"ipc",
"twisted",
"rabbitmq",
"zeromq"
] | I want to create 2 applications in Python which should communicate with each other. One of these application should behave like a server and the second should be the GUI of a client. They could be run on the same system(on the same machine) or remotely and on different devices.
I want to ask you, which technology shou... | Twisted is used to solve the C10k networking problem by giving you asynchronous networking through the [Reactor Pattern](http://en.wikipedia.org/wiki/Reactor_pattern). Its also convenient because it provides a nice concurrency abstraction as threading/concurrency in Python is not as easy as say Erlang. Consequently som... |
Dumping HTTP requests with Flask | 14,687,468 | 9 | 2013-02-04T13:10:01Z | 14,687,973 | 9 | 2013-02-04T13:39:28Z | [
"python",
"flask"
] | I am developing a Flask application based web application ( <https://github.com/opensourcehacker/sevabot> ) which has HTTP based API services.
Many developers are using and extending the API and I'd like to add a feature which prints Flask's HTTP request to Python logging output, so you can see raw HTTP payloads, sour... | Flask makes a standard [logger](http://docs.python.org/dev/library/logging.html#logging.Logger) available at at [`current_app.logger`](http://flask.pocoo.org/docs/quickstart/#logging), there's an example configuration in [this gist](https://gist.github.com/3257877), though you can centralise the logging calls in a befo... |
Google API Python client error | 14,687,552 | 3 | 2013-02-04T13:14:41Z | 14,728,471 | 9 | 2013-02-06T11:54:22Z | [
"python",
"api",
"oauth-2.0",
"google-api-python-client"
] | I want to have a script for getting home feed of Google+. I use for that google's [script](https://github.com/musicmetric/google-api-python-client/blob/master/samples/plus/plus.py). The client-secrets.json file is:
```
{
"web": {
"client_id": "##########",
"client_secret": "############",
"redirect_uris": ["... | I found the solution! You should create another Client ID, but for desktop application! After that you need to use it's **client\_id** and **client\_secret**. It works for developing without hosting. |
How can I remove all non-letter (all languages) and non-numeric characters from a string? | 14,687,890 | 3 | 2013-02-04T13:34:29Z | 14,687,971 | 9 | 2013-02-04T13:39:23Z | [
"python",
"regex",
"python-2.7"
] | I've been searching for quite some time now yet I can not find any explanation on the subject.
If I have a string, say: `u'à aeëÃ35+{}"´'`. I want all non-alphanumeric charachters removed (however, I want `à , ë, Ã` etc. kept.
I'm fairly new to Python and I could not figure out a regex to perform this task.
Only... | ```
In [63]: s = u'à aeëÃ35+{}"´'
In [64]: print ''.join(c for c in s if c.isalnum())
à aeëÃ35
``` |
Adding meta-information/metadata to pandas DataFrame | 14,688,306 | 24 | 2013-02-04T13:59:18Z | 14,688,398 | 28 | 2013-02-04T14:03:39Z | [
"python",
"pandas"
] | Is it possible to add some meta-information/metadata to a pandas DataFrame?
For example, the instrument's name used to measure the data, the instrument responsible, etc.
*One workaround would be to create a column with that information, but it seems wasteful to store a single piece of information in every row!* | Sure, like most Python objects, you can attach new attributes to a `pandas.DataFrame`:
```
import pandas as pd
df = pd.DataFrame([])
df.instrument_name = 'Binky'
```
Note, however, that while you can attach attributes to a DataFrame, operations performed on the DataFrame (such as `groupby`, `pivot`, `join` or `loc` t... |
Adding meta-information/metadata to pandas DataFrame | 14,688,306 | 24 | 2013-02-04T13:59:18Z | 14,688,529 | 9 | 2013-02-04T14:12:33Z | [
"python",
"pandas"
] | Is it possible to add some meta-information/metadata to a pandas DataFrame?
For example, the instrument's name used to measure the data, the instrument responsible, etc.
*One workaround would be to create a column with that information, but it seems wasteful to store a single piece of information in every row!* | Not really. Although you could add attributes containing metadata to the DataFrame class as @unutbu mentions, many DataFrame methods return a new DataFrame, so your meta data would be lost. If you need to manipulate your dataframe, then the best option would be to wrap your metadata and DataFrame in another class. See ... |
Adding meta-information/metadata to pandas DataFrame | 14,688,306 | 24 | 2013-02-04T13:59:18Z | 25,715,719 | 8 | 2014-09-07T23:31:15Z | [
"python",
"pandas"
] | Is it possible to add some meta-information/metadata to a pandas DataFrame?
For example, the instrument's name used to measure the data, the instrument responsible, etc.
*One workaround would be to create a column with that information, but it seems wasteful to store a single piece of information in every row!* | Just ran into this issue myself. As of pandas 0.13, DataFrames have a \_metadata attribute on them that does persist through functions that return new DataFrames. Also seems to survive serialization just fine (I've only tried json, but I imagine hdf is covered as well). |
How to apply standardization to SVMs in scikit-learn? | 14,688,391 | 15 | 2013-02-04T14:03:14Z | 14,693,358 | 23 | 2013-02-04T18:45:05Z | [
"python",
"scikit-learn",
"svm"
] | I'm using the current stable version 0.13 of scikit-learn. I'm applying a linear support vector classifier to some data using the class [`sklearn.svm.LinearSVC`](http://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC).
In the [chapter about preprocessing](http://scikit-learn.... | Neither.
`scaler.transform(X_train)` doesn't have any effect. The `transform` operation is not in-place.
You have to do
```
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
or
```
X_train = scaler.fit(X_train).transform(X_train)
```
You always need to do the same preprocessing on both... |
How to match a new line character in Python raw string | 14,689,531 | 7 | 2013-02-04T15:05:45Z | 14,689,821 | 8 | 2013-02-04T15:22:51Z | [
"python",
"regex",
"rawstring"
] | I got a little confused about Python raw string. I know that if we use raw string, then it will treat '\' as a normal backslash (ex. r'\n' would be '\' and 'n'). However, I was wondering what if I want to match a new line character in raw string. I tried r'\n', but it didn't work. Anybody has some good idea about this? | In a regular expression, you need to specify that you're in multiline mode:
```
>>> import re
>>> s = """cat
... dog"""
>>>
>>> re.match(r'cat\ndog',s,re.M)
<_sre.SRE_Match object at 0xcb7c8>
```
Notice that `re` translates the `\n` (raw string) into newline. As you indicated in your comments, you don't actually **n... |
How do I test if a certain log message is logged in a Django test case? | 14,690,267 | 6 | 2013-02-04T15:48:34Z | 14,690,655 | 14 | 2013-02-04T16:07:36Z | [
"python",
"django",
"unit-testing",
"testing",
"pyunit"
] | I want to ensure that a certain condition in my code causes a log message to be written to the django log. How would I do this with the Django unit testing framework?
Is there a place where I can check logged messages, similarly to how I can check sent emails? My unit test extends `django.test.TestCase`. | Using the [`mock`](http://www.voidspace.org.uk/python/mock/) module for mocking the logging module or the logger object. When you've done that, check the arguments with which the logging function is called.
For example, if you code looks like this:
```
import logging
logger = logging.getLogger('my_logger')
logger.e... |
Unpack list and cast at the same time | 14,690,722 | 3 | 2013-02-04T16:11:24Z | 14,690,745 | 8 | 2013-02-04T16:12:53Z | [
"python",
"list",
"casting"
] | I have a long list of stings which need to be passed into a function as integers. What I am doing right now is:
```
my_function(int(list[0]), int(list[1]), int(list[2]), int(list[3])...)
```
But I know I can make a much shorter function call by unpacking the list:
```
my_function(*list)
```
I was wondering if there... | Use the built-in method `map`, e.g.
```
my_function(*map(int, list))
```
Alternatively, try list-comprehension:
```
my_function(*[int(x) for x in list])
```
BTW:
Please don't use `list` as name for a local variable, this will hide the built-in method `list`.
It is common use to append an underscore for variable-n... |
Access python nested dictionary items via a list of keys | 14,692,690 | 46 | 2013-02-04T18:04:35Z | 14,692,747 | 76 | 2013-02-04T18:07:38Z | [
"python",
"list",
"dictionary",
"python-2.7"
] | I have a complex dictionary structure which I would like to access via a list of keys to address the correct item.
```
dataDict = {
"a":{
"r": 1,
"s": 2,
"t": 3
},
"b":{
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
... | Use `reduce()` to traverse the dictionary:
```
def getFromDict(dataDict, mapList):
return reduce(lambda d, k: d[k], mapList, dataDict)
```
and reuse `getFromDict` to find the location to store the value for `setInDict()`:
```
def setInDict(dataDict, mapList, value):
getFromDict(dataDict, mapList[:-1])[mapLis... |
How can I remove the ANSI escape sequences from a string in python | 14,693,701 | 23 | 2013-02-04T19:07:04Z | 14,693,789 | 44 | 2013-02-04T19:12:52Z | [
"python",
"string",
"escaping",
"ansi-escape"
] | This is my string:
```
'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
```
I was using code to retrieve the output from a SSH command and I want my string to only contain 'examplefile.zip'
What I can use to remove the extra escape sequences? | Delete them with a regular expression:
```
import re
ansi_escape = re.compile(r'\x1b[^m]*m')
ansi_escape.sub('', sometext)
```
Demo:
```
>>> import re
>>> ansi_escape = re.compile(r'\x1b[^m]*m')
>>> sometext = 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
>>> ansi_escape.sub('', sometext)
'ls\r\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.