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 prevent table regeneration in PLY
12,644,902
5
2012-09-28T17:47:48Z
14,864,448
10
2013-02-13T22:28:18Z
[ "python", "parsing", "ply" ]
I am using PLY in a command line application that I package as a Python egg to be installed via `pip`. Everytime I run my script from the command line, I see the following message: ``` "Generating LALR tables" ``` Additionally, parser.out and parsetab.py files are written to the directory from which the script is inv...
use ``` yacc.yacc(debug=0, write_tables=0) ```
Should I use `scipy.pi`, `numpy.pi`, or `math.pi`?
12,645,547
54
2012-09-28T18:36:58Z
12,645,565
88
2012-09-28T18:38:41Z
[ "python", "numpy", "scipy", "python-module" ]
In a project using scipy and numpy, should I use `scipy.pi`, `numpy.pi`, or `math.pi`? Ten minutes on google and Stack Overflow doesn't give an answer.
``` >>> import math >>> import numpy as np >>> import scipy >>> math.pi == np.pi == scipy.pi True ``` So it doesn't matter, they are all the same value. The only reason all three modules provide a `pi` value is so if you are using just one of the three modules, you can conveniently have access to pi without having to...
Should I use `scipy.pi`, `numpy.pi`, or `math.pi`?
12,645,547
54
2012-09-28T18:36:58Z
23,602,400
20
2014-05-12T06:29:48Z
[ "python", "numpy", "scipy", "python-module" ]
In a project using scipy and numpy, should I use `scipy.pi`, `numpy.pi`, or `math.pi`? Ten minutes on google and Stack Overflow doesn't give an answer.
One thing to note is that not *all* libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy: ``` import math import numpy import scipy import sympy print(math.pi == numpy.p...
Pydoc messes up with -*- coding: utf-8 -*-
12,645,673
6
2012-09-28T18:47:33Z
12,645,827
7
2012-09-28T18:59:20Z
[ "python", "emacs", "encoding", "pydoc" ]
I edit Python scripts with Emacs, and I always put this at the beginning of my scripts: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- ``` It is recommended (at least, not discourage) in [PEP 0236](http://www.python.org/dev/peps/pep-0263/). However, I just found that `pydoc` doesn't recognize (ignore) it correctl...
It appears that if you actually provide a documentation string the encoding line will be skipped. File contents: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """Documentation for myscript""" ``` pydoc output: ``` $ pydoc myscript.py Help on module myscript: NAME myscript - Documentation for myscript ```
Efficient way to import a lot of csv files into PostgreSQL db
12,646,305
7
2012-09-28T19:38:21Z
12,651,899
7
2012-09-29T10:23:07Z
[ "python", "csv", "import", "postgresql-9.1" ]
I see plenty of examples of importing a CSV into a PostgreSQL db, but what I need is an efficient way to import 500,000 CSV's into a single PostgreSQL db. Each CSV is a bit over 500KB (so grand total of approx 272GB of data). The CSV's are identically formatted and there are no duplicate records (the data was generate...
If you start by reading the [PostgreSQL guide "Populating a Database"](http://www.postgresql.org/docs/current/interactive/populate.html) you'll see several pieces of advice: 1. Load the data in a single transaction. 2. Use `COPY` if at all possible. 3. Remove indexes, foreign key constraints etc before loading the dat...
Calling a class function inside of __init__
12,646,326
32
2012-09-28T19:40:05Z
12,646,396
40
2012-09-28T19:45:30Z
[ "python", "class" ]
I'm writing some code that takes a filename, opens the file, and parses out some data. I'd like to do this in a class. The following code works: ``` class MyClass(): def __init__(self, filename): self.filename = filename self.stat1 = None self.stat2 = None self.stat3 = None ...
Call the function in this way: ``` self.parse_file() ``` You also need to define your parse\_file() function like this: ``` def parse_file(self): ``` The parse\_file method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the obj...
Calling a class function inside of __init__
12,646,326
32
2012-09-28T19:40:05Z
12,646,407
8
2012-09-28T19:45:59Z
[ "python", "class" ]
I'm writing some code that takes a filename, opens the file, and parses out some data. I'd like to do this in a class. The following code works: ``` class MyClass(): def __init__(self, filename): self.filename = filename self.stat1 = None self.stat2 = None self.stat3 = None ...
If I'm not wrong, both functions are part of your class, you should use it like this: ``` class MyClass(): def __init__(self, filename): self.filename = filename self.stat1 = None self.stat2 = None self.stat3 = None self.stat4 = None self.stat5 = None self....
pickle cython class
12,646,436
5
2012-09-28T19:47:58Z
12,647,497
7
2012-09-28T21:17:35Z
[ "python", "class", "pickle", "cython", "reduce" ]
I have to save and load a cython class instance. My cython class is this plus several methods: ``` import numpy as np cimport numpy as np cimport cython cdef class Perceptron_avg_my: cdef int wlen,freePos cdef np.ndarray w,wtot,wac,wtotc #np.ndarray[np.int32_t] cdef np.ndarray wmean #np.ndarray[np.flo...
I don't know if you found it, but the official Python documentation has [a section on pickling extension types](http://docs.python.org/library/pickle.html#pickling-and-unpickling-extension-types). I think you have three problems here. Firstly, the function returned by `__reduce__` is supposed to create a new object fr...
Stepping into a function in IPython
12,646,670
20
2012-09-28T20:04:16Z
12,647,065
33
2012-09-28T20:36:32Z
[ "python", "debugging", "ipython", "pdb" ]
Is there a way to step into the first line of a function in ipython. I imagine something that would look like: ``` %step foo(1, 2) ``` which runs `ipdb` and sets a breakpoint at the first line of `foo`. If I want to do this now I have to go to the function's source code and add an `import ipdb; ipdb.set_trace()` lin...
ipdb has had support for runcall, runeval and run since 0.7, earlier this year. You can use it just like `pdb.runcall`: ``` In [1]: def foo(a, b): ...: print a + b ...: In [2]: import ipdb In [3]: ipdb.runcall(foo, 1, 2) > <ipython-input-1-2e565fd9c4a4>(2)foo() 1 def foo(a, b): ----> 2 print a + ...
Getting next line in a file
12,647,006
14
2012-09-28T20:30:36Z
12,647,022
25
2012-09-28T20:32:04Z
[ "python", "file-io" ]
I am reading in a file and wonder if there's a way to read the next line in a for loop? I am currently reading the file like this: ``` file = open(input,"r").read() for line in file.splitlines(): line = doSomething() ``` So is there anyway I can retrieve the next line of the file in that for loop such that I can p...
Just loop over the open file: ``` infile = open(input,"r") for line in infile: line = doSomething(line, next(infile)) ``` Because you now use the file as an iterator, you can call the [`next()` function](http://docs.python.org/2/library/functions.html#next) on the `input` variable at any time to retrieve an extra...
Getting next line in a file
12,647,006
14
2012-09-28T20:30:36Z
12,647,112
8
2012-09-28T20:40:41Z
[ "python", "file-io" ]
I am reading in a file and wonder if there's a way to read the next line in a for loop? I am currently reading the file like this: ``` file = open(input,"r").read() for line in file.splitlines(): line = doSomething() ``` So is there anyway I can retrieve the next line of the file in that for loop such that I can p...
I think that you mean that if you are in line n, you want to be able to access line n+1. The simplest way to do that is to replace `for line in file.splitlines():` with ``` lines = file.readlines() for i in xrange(len(lines)): ``` then you can get the current line with `lines[i]` and the next line with `lines[i...
How do I shut down a python simpleHTTPserver?
12,647,196
34
2012-09-28T20:48:17Z
12,647,283
20
2012-09-28T20:56:33Z
[ "python", "d3.js", "simplehttpserver" ]
So I'm trying to learn d3, and the [wiki](https://github.com/mbostock/d3/wiki) suggested that > To view the examples locally, you must have a local web server. Any > web server will work; for example you can run Python's built-in > server: > > `python -m SimpleHTTPServer 8888 &` Great... only now I have a server runn...
You are simply sending signals to the processes. `kill` is a command to send those signals. The keyboard command Ctrl+C (`⌃`+`C`) sends a SIGINT, `kill -9` sends a SIGKILL, and `kill -15` sends a SIGTERM. What signal do you want to send to your server to end it?
How do I shut down a python simpleHTTPserver?
12,647,196
34
2012-09-28T20:48:17Z
12,647,509
12
2012-09-28T21:18:21Z
[ "python", "d3.js", "simplehttpserver" ]
So I'm trying to learn d3, and the [wiki](https://github.com/mbostock/d3/wiki) suggested that > To view the examples locally, you must have a local web server. Any > web server will work; for example you can run Python's built-in > server: > > `python -m SimpleHTTPServer 8888 &` Great... only now I have a server runn...
or you can just do `kill %1`, which will kill the first job put in background
How do I shut down a python simpleHTTPserver?
12,647,196
34
2012-09-28T20:48:17Z
31,334,292
7
2015-07-10T06:52:08Z
[ "python", "d3.js", "simplehttpserver" ]
So I'm trying to learn d3, and the [wiki](https://github.com/mbostock/d3/wiki) suggested that > To view the examples locally, you must have a local web server. Any > web server will work; for example you can run Python's built-in > server: > > `python -m SimpleHTTPServer 8888 &` Great... only now I have a server runn...
if you have started the server with ``` python -m SimpleHTTPServer 8888 ``` then you can press ctrl + c to down the server. But if you have started the server with ``` python -m SimpleHTTPServer 8888 & ``` or ``` python -m SimpleHTTPServer 8888 & disown ``` you have to see the list first to kill the process, ru...
Project Euler 17
12,647,254
2
2012-09-28T20:53:19Z
12,647,289
7
2012-09-28T20:57:05Z
[ "python" ]
I've been trying to solve Euler 17 and have been running into some trouble. The definition of that problem is: > If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. > > If all the numbers from 1 to 1000 (one thousand) inclusive were ...
### Explaining the discrepancy Your code is riddled with errors: 1. This is wrong: ``` maps[60] = 6 ``` Contribution to error: +100 (because it affects 60 to 69, 160 to 169, ..., 960 to 969). 2. Several teenagers are mistaken: ``` >>> teen(12) 7 >>> teen(13) 9 >>> teen(15) 8 >>>...
Where is virtualenvwrapper.sh after pip install?
12,647,266
41
2012-09-28T20:54:49Z
12,648,034
34
2012-09-28T22:11:23Z
[ "python", "osx", "virtualenv", "pip", "virtualenvwrapper" ]
I'm trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I've found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I've checked all the python and site-packages directories, and I can't find any virtualenvwrapper.sh. Is this something I need to download s...
You can use the `find` command to search for a file: `find / -name virtualenvwrapper.sh` This will search all directories from the root for the file. --- on ubuntu 12.04 LTS, installing through pip, it is installed to `/usr/local/bin/virtualenvwrapper.sh`
Where is virtualenvwrapper.sh after pip install?
12,647,266
41
2012-09-28T20:54:49Z
15,678,306
7
2013-03-28T09:32:20Z
[ "python", "osx", "virtualenv", "pip", "virtualenvwrapper" ]
I'm trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I've found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I've checked all the python and site-packages directories, and I can't find any virtualenvwrapper.sh. Is this something I need to download s...
or, like I did..just uninstall virtualenvwrapper > sudo pip uninstall virtualenvwrapper and then install it with easy\_install > sudo easy\_install virtualenvwrapper this time I found the file "**/usr/local/bin/virtualenvwrapper.sh**" installed... Before that I weren't finding that file anywhere even by this comman...
Where is virtualenvwrapper.sh after pip install?
12,647,266
41
2012-09-28T20:54:49Z
16,705,807
24
2013-05-23T04:42:40Z
[ "python", "osx", "virtualenv", "pip", "virtualenvwrapper" ]
I'm trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I've found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I've checked all the python and site-packages directories, and I can't find any virtualenvwrapper.sh. Is this something I need to download s...
did you already try this ? ``` $ which virtualenvwrapper.sh ```
Where is virtualenvwrapper.sh after pip install?
12,647,266
41
2012-09-28T20:54:49Z
17,897,962
25
2013-07-27T12:46:47Z
[ "python", "osx", "virtualenv", "pip", "virtualenvwrapper" ]
I'm trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I've found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I've checked all the python and site-packages directories, and I can't find any virtualenvwrapper.sh. Is this something I need to download s...
I just reinstalled it with pip. ``` sudo pip uninstall virtualenvwrapper sudo pip install virtualenvwrapper ``` And this time it put it in /usr/local/bin.
The truth value of an array with more than one element is ambigous when trying to index an array
12,647,471
7
2012-09-28T21:14:50Z
12,647,556
22
2012-09-28T21:22:52Z
[ "python", "numpy", "list-comprehension" ]
I am trying to put all elements of rbs into a new array if the elements in var(another numpy array) is >=0 and <=.1 . However when I try the following code I get this error: ``` ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` ``` --- ``` rbs = [ish[4] for ish...
As I told you in a comment to a previous answer, you need to use either: ``` c[a & b] ``` or ``` c[np.logical_and(a, b)] ``` The reason is that the `and` keyword is used by Python to test between two booleans. How can an array be a boolean? If 75% of its items are `True`, is it `True` or `False`? Therefore, numpy r...
What could affect Python string comparison performance for strings over 64 characters?
12,648,002
20
2012-09-28T22:08:12Z
12,648,271
9
2012-09-28T22:40:30Z
[ "python", "string", "performance", "time-complexity" ]
I'm trying to evaluate if comparing two string get slower as their length increases. My calculations suggest comparing strings should take an amortized constant time, but my Python experiments yield strange results: Here is a plot of string length (1 to 400) versus time in milliseconds. Automatic garbage collection is...
Python *can* 'intern' short strings; stores them in a special cache, and re-uses string objects from that cache. When then comparing strings, it'll first test if it is the same pointer (e.g. an interned string): ``` if (a == b) { switch (op) { case Py_EQ:case Py_LE:case Py_GE: result = Py_True; ...
Huge memory leak in repeated os.path.isdir calls?
12,648,737
20
2012-09-28T23:58:33Z
12,650,207
8
2012-09-29T05:30:25Z
[ "python", "memory-leaks", "python-2.7", "system-calls" ]
I've been scripting something that has to do with scanning directories and noticed a severe memory leak when calling os.path.isdir, so I've tried the following snippet: ``` def func(): if not os.path.isdir('D:\Downloads'): return False while True: func() ``` Within a few seconds, the Python process re...
The root cause is a failure to call `PyMem_Free` on the `path` variable in the non-Unicode path: ``` if (!PyArg_ParseTuple(args, "et:_isdir", Py_FileSystemDefaultEncoding, &path)) return NULL; attributes = GetFileAttributesA(path); if (attributes == INVALID_FILE_ATTRIBUTE...
fatest way to mix two lists in python
12,649,239
8
2012-09-29T01:45:30Z
12,649,244
10
2012-09-29T01:46:57Z
[ "python", "list" ]
Let's have 2 lists ``` l1 = [1, 2, 3] l2 = [a, b, c, d, e, f, g...] ``` result: ``` list = [1, a, 2, b, 3, c, d, e, f, g...] ``` Cannot use `zip()` because it shorten result to the smallest `list`. I need also a `list` at the output not an `iterable`.
``` >>> l1 = [1,2,3] >>> l2 = ['a','b','c','d','e','f','g'] >>> [i for i in itertools.chain(*itertools.izip_longest(l1,l2)) if i is not None] [1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g'] ``` To allow `None` values to be included in the lists you can use the following modification: ``` >>> from itertools import chain,...
fatest way to mix two lists in python
12,649,239
8
2012-09-29T01:45:30Z
12,649,267
7
2012-09-29T01:50:27Z
[ "python", "list" ]
Let's have 2 lists ``` l1 = [1, 2, 3] l2 = [a, b, c, d, e, f, g...] ``` result: ``` list = [1, a, 2, b, 3, c, d, e, f, g...] ``` Cannot use `zip()` because it shorten result to the smallest `list`. I need also a `list` at the output not an `iterable`.
Another possibility... ``` [y for x in izip_longest(l1, l2) for y in x if y is not None] ``` (after importing izip\_longest from itertools, of course)
Building an HTML Diff/Patch Algorithm
12,649,740
17
2012-09-29T03:44:24Z
12,732,485
9
2012-10-04T17:24:22Z
[ "python", "html", "algorithm", "html-parsing", "diff" ]
A description of what I'm going to accomplish: * Input 2 (N is not essential) HTML documents. * Standardize the HTML format * Diff the two documents -- external styles are not important but anything inline to the document will be included. * Determine delta at the HTML Block Element level. Expanding the last point: ...
If you were going to start from scratch, a useful search term would be "tree diff". There's a pretty awesome blog post [here](http://useless-factor.blogspot.com/2008/01/matching-diffing-and-merging-xml.html), although I just found it by googling "daisydiff python" so I bet you've already seen it. Besides all the inter...
How to run a scrapy with a py file
12,649,862
3
2012-09-29T04:17:56Z
12,650,507
7
2012-09-29T06:28:51Z
[ "python", "scrapy" ]
Hi i am working on scrapy, i created a scrapy folder with `scrapy startproject example` and written spider to scrape all the data from the url, and I had run the spider using the command `scrapy crawl spider_name`, its working fine and able to fetch data. But i had a requirement that i need to run the scrapy with a si...
Yes! If you want to do it programmatically instead of invoking the command via Popen, you can run it as follows: ``` >>> from scrapy.cmdline import execute >>> execute(['scrapy','crawl','dmoz']) ``` Let me know if you have any trouble. I'm used the version that the scrapy docs refer to on Github for testing purposes:...
How can I pool connections using psycopg and gevent?
12,650,048
12
2012-09-29T04:53:05Z
12,650,915
11
2012-09-29T07:44:12Z
[ "python", "postgresql", "asynchronous", "gevent", "psycopg" ]
The psycopg docs state: "Psycopg connections are not green thread safe and can’t be used concurrently by different green threads. Trying to execute more than one command at time using one cursor per thread will result in an error (or a deadlock on versions before 2.4.2). Therefore, programmers are advised to either a...
I assume you know [gevent-psycopg2](https://github.com/zacharyvoase/gevent-psycopg2) module, which makes `psycopg` greenlet-friendly. Looking for connection pooling solution I've tried 2 solutions: * `SQLALchemy` - it seems to work properly with monkey-patched threads and `gevent-psycopg2`. The [`QueuePool`](http://d...
Processing Simultaneous/Asynchronous Requests with Python BaseHTTPServer
12,650,238
7
2012-09-29T05:36:13Z
12,651,298
8
2012-09-29T08:47:53Z
[ "python", "simplehttpserver" ]
I've set up a threaded (with Python threads) HTTP server by creating a class that inherits from HTTPServer and ThreadingMixIn: ``` class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): pass ``` I have a handler class which inherits from BaseHTTPRequestHandler, and I start the server with something like this: ```...
``` class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): pass ``` is enough. Your client probably don't make concurrent requests. If you make the requests in parallel the threaded server works as expected. Here's the client: ``` #!/usr/bin/env python import sys import urllib2 from threading import Thread def m...
how can I make a numpy function that accepts a numpy array, an iterable, or a scalar?
12,653,120
7
2012-09-29T13:31:56Z
12,653,164
8
2012-09-29T13:38:00Z
[ "python", "arrays", "numpy" ]
Suppose I have this: ``` def incrementElements(x): return x+1 ``` but I want to modify it so that it can take either a numpy array, an iterable, or a scalar, and promote the argument to a numpy array and add 1 to each element. How could I do that? I suppose I could test argument class but that seems like a bad id...
You could try ``` def incrementElements(x): x = np.asarray(x) return x+1 ``` `np.asarray(x)` is the equivalent of `np.array(x, copy=False)`, meaning that a scalar or an iterable will be transformed to a `ndarray`, but if `x` is already a `ndarray`, its data will not be copied. If you pass a scalar and want a...
Find 'hello', 'man' and '' in '/?user=hello&user=man&user=' using regex
12,653,503
2
2012-09-29T14:21:52Z
12,653,534
11
2012-09-29T14:26:08Z
[ "python", "regex", "string" ]
I want to extract any string after `'user='` from the string `'/?user=hello&user=man&user='`. In this case that would get me `'hello'`, `'man'` and `''`. **I'm stuck here:** ``` >>> import re >>> s = '/?user=hello&user=man&user=' >>> re.findall("user=(.*)",s) ['hello&user=man&user='] ``` I would be able to find wha...
I would drop the `re` and use the tools meant for this: ``` from urlparse import urlsplit, parse_qs s = '/?user=hello&user=man&user=' parse_qs(urlsplit(s).query, keep_blank_values=True) {'user': ['hello', 'man', '']} ```
List comprehension with if-condition
12,653,670
2
2012-09-29T14:41:37Z
12,653,685
7
2012-09-29T14:44:29Z
[ "python", "optimization", "coding-style" ]
The following line of Python code ``` values = ", ".join(["\"%s\"" % x for x in row]) ``` takes a list of elements in "row" to create a comma-separated string "values", while each value is put in double quotes, e.g.: "New York", "5", "", "3.2" However, since the result is to be part of a mysqldump file, empty fields...
``` values = ", ".join('"%s"' % x if x else 'NULL' for x in row) ``` For example: ``` >>> row = ["foo", "", "bar"] >>> values = ", ".join('"%s"' % x if x else 'NULL' for x in row) >>> values '"foo", NULL, "bar"' ``` Thanks to DSM for pointing out that it's of course even better to change the list comprehension into ...
Something strange in numpy
12,655,210
2
2012-09-29T18:13:48Z
12,655,277
8
2012-09-29T18:21:56Z
[ "python", "numpy", "linear-algebra" ]
`a` is a numpy array and `a.T` is it's transpose. Once I add `a` and `a.T` as `a += a.T`, the answer isn't expected. Could any one tell me why? Thanks. ``` import numpy a = numpy.ones((100, 100)) a += a.T a array([[ 2., 2., 2., ..., 2., 2., 2.], [ 2., 2., 2., ..., 2., 2., 2.], [ 2., 2., 2....
Note that `a.T` is only a view on `a`, which means they hold the same data. Now: ``` a += a.T ``` Adds `a.T` in place to `a`, but while doing so, changes `a.T` (as `a.T` points at the same data). Since the order of accessing `a` is a bit more complex, this fails (and you should not trust the result to be reproducabl...
How to set QWidget background color?
12,655,538
8
2012-09-29T18:55:31Z
12,655,587
27
2012-09-29T19:01:30Z
[ "python", "qt" ]
The line `w.setBackgroundRole(QPalette.Base)` in the code below has no effect. Why? How do I fix that? ``` import sys from PySide.QtCore import * from PySide.QtGui import * app = QApplication(sys.argv) w = QWidget() w.setBackgroundRole(QPalette.Base) w.show() app.exec_() ```
You need to call `setAutoFillBackground(True)` on the widget. By default, a `QWidget` doesn't fill its background. For more information, see the documentation for the [`setAutoFillBackground`](http://qt-project.org/doc/qt-4.8/qwidget.html#autoFillBackground-prop) property. If you want to use an arbitrary background c...
Parse xml with lxml - extract element value
12,657,043
8
2012-09-29T22:23:50Z
12,657,237
14
2012-09-29T22:57:35Z
[ "python", "xml", "xpath", "lxml" ]
Let's suppose we have the XML file with the structure as follows. ``` <?xml version="1.0" ?> <searchRetrieveResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/zing/srw/ http://www.loc.gov/standards/sru/sru1-1archive/xml-files/srw-types.xsd" xmlns="http://www.loc.gov/...
I would be more direct in your XPath: go straight for the elements you want, in this case `datafield`. ``` >>> for df in doc.xpath('//datafield'): # Iterate over attributes of datafield for attrib in df.attrib: print '@' + attrib + '=' + df.attrib[attrib] # subfield is a child ...
Python: cannot import urandom module (OS X)
12,658,141
9
2012-09-30T02:28:17Z
12,658,205
16
2012-09-30T02:46:38Z
[ "python", "importerror", "python-import" ]
I'm quite ashamed to ask a question like this one, but I've been trying for a couple of hours already...it seems I can't get my python version to do random things anymore. More precisely, it's missing the module `urandom`. First, here are some info about my system: * OSX version: 10.7.4 * python version: Python 2.7.1...
Ok, I figured it out. I had a dirty hash table in my terminal. Solution: ``` hash -r # will erase the currently used hash table ``` Once this was done, I ran python again and I got: ``` Python 2.7.3 (default, Apr 19 2012, 00:55:09) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Typ...
Python objects from existing objects using __new__
12,658,824
12
2012-09-30T05:12:53Z
12,658,921
12
2012-09-30T05:32:49Z
[ "python", "object", "types", "instantiation" ]
In learning about Python's data model, I am playing with creating objects from existing objects using the `__new__` method. Here are some examples which create new objects of various types: ``` x = 2; print type(x).__new__(x.__class__) x = {}; print type(x).__new__(x.__class__) x = [1,2]; print type(x).__new__(...
It's nothing too special, it's just that for some types there is a default "empty" object of that type, while for others there is not. Your working examples are basically equivalent to: ``` int() dict() list() float() str() complex() tuple() ``` . . . all of which work. Your last three examples are basically trying t...
What does this Python statement mean?
12,659,781
14
2012-09-30T08:19:23Z
12,659,825
14
2012-09-30T08:26:56Z
[ "python" ]
I'm writing a parser, and in the process of debugging it, I found that apparently, this is legal Python: ``` for [] in [[]]: print 0 ``` and so is this (!): ``` for [][:] in [[]]: print 0 ``` I don't blame the parser for getting confused... *I'm* having trouble figuring out how to interpret it! What exactly doe...
In terms of execution: nothing. The `for` loop itself loops over an empty list, so no iterations will take place. And that's a good thing, because the `for []` means: assign each entry in the loop to 0 variables. The latter part is probably what is puzzling you. The statement is legal because the [target token `toke...
Associativity of "in" in Python?
12,660,870
108
2012-09-30T11:24:52Z
12,660,938
123
2012-09-30T11:35:18Z
[ "python", "syntax", "python-2.x" ]
I'm making a Python parser, and this is *really* confusing me: ``` >>> 1 in [] in 'a' False >>> (1 in []) in 'a' TypeError: 'in <string>' requires string as left operand, not bool >>> 1 in ([] in 'a') TypeError: 'in <string>' requires string as left operand, not list ``` How exactly does "in" work in Python, w...
`1 in [] in 'a'` is evaluated as `(1 in []) and ([] in 'a')`. Since the first condition (`1 in []`) is `False`, the whole condition is evaluated as `False`; `([] in 'a')` is never actually evaluated, so no error is raised. Here are the statement definitions: ``` In [121]: def func(): .....: return 1 in [] in ...
Associativity of "in" in Python?
12,660,870
108
2012-09-30T11:24:52Z
12,660,978
22
2012-09-30T11:41:59Z
[ "python", "syntax", "python-2.x" ]
I'm making a Python parser, and this is *really* confusing me: ``` >>> 1 in [] in 'a' False >>> (1 in []) in 'a' TypeError: 'in <string>' requires string as left operand, not bool >>> 1 in ([] in 'a') TypeError: 'in <string>' requires string as left operand, not list ``` How exactly does "in" work in Python, w...
Python does special things with chained comparisons. The following are evaluated differently: ``` x > y > z # in this case, if x > y evaluates to true, then # the value of y is being used to compare, again, # to z (x > y) > z # the parenth form, on the other hand, will first # e...
Associativity of "in" in Python?
12,660,870
108
2012-09-30T11:24:52Z
12,661,136
11
2012-09-30T12:06:45Z
[ "python", "syntax", "python-2.x" ]
I'm making a Python parser, and this is *really* confusing me: ``` >>> 1 in [] in 'a' False >>> (1 in []) in 'a' TypeError: 'in <string>' requires string as left operand, not bool >>> 1 in ([] in 'a') TypeError: 'in <string>' requires string as left operand, not list ``` How exactly does "in" work in Python, w...
[From the documentation:](http://docs.python.org/reference/expressions.html#not-in) > Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). What this means is, that...
How to fail the chain if it's sub task gives an exception
12,660,994
3
2012-09-30T11:43:59Z
12,672,680
10
2012-10-01T11:48:59Z
[ "python", "django", "rabbitmq", "celery" ]
I have faced a pretty strange issue with celery: There is a chain of tasks, and one of them gives an exception and does several retries ``` chain = (err.si(1) | err.si(2)) result = chain.apply_async() result.state result.get() ``` here is the code of the task: ``` @celery.task(base=MyTask) def err(x): try: if x...
When you have a chain: ``` >>> c = a.s() | b.s() | c.s() >>> res = c() >>> res.get() ``` Calling the chain will generate unique id's for all of the task in the chain, send the messages and return the *last result in the chain*. So when you do `res.get()` you are simple trying to retrieve the result of the last task ...
How optimize adding new nodes in `django-mptt`?
12,661,488
2
2012-09-30T13:12:32Z
12,681,061
9
2012-10-01T21:05:12Z
[ "python", "database", "django", "performance", "django-mptt" ]
I am creating a script which will synchronize two databases. There is a data in the database which should be stored as a tree so I use [django-mptt](http://django-mptt.github.com/django-mptt/) for the new DB. When I syncing DB's I select new data from the old DB and should save it in the new one. I want to know if the...
Firstly, don't use `insert_at`. It's not the reason for slow performance, but it's unnecessary and looks ugly. Just set `node.parent`: ``` for new_record in new_records: new_node = MyMPTTModel(..., parent=get_parent(new_record)) new_node.save() ``` Now for the performance question. If you're using the latest ...
ntp client in python
12,664,295
10
2012-09-30T19:24:24Z
12,664,736
13
2012-09-30T20:13:47Z
[ "python" ]
I've written a ntp client in python to query a time server and display the time and the program executes but does not give me any results. I'm using python's 2.7.3 integrated development environment and my OS is Windows 7. Here is the code: ``` # File: Ntpclient.py from socket import AF_INET, SOCK_DGRAM import sys imp...
Use [ntplib](http://pypi.python.org/pypi/ntplib/): ``` import ntplib from time import ctime c = ntplib.NTPClient() response = c.request('pool.ntp.org') print ctime(response.tx_time) ```
SqlAlchemy metaclass confusion
12,664,385
9
2012-09-30T19:35:22Z
12,699,607
11
2012-10-02T22:55:53Z
[ "python", "sqlalchemy", "metaclass" ]
I'm trying to inject some of my own code in the class construction process of SqlAlchemy. Trying to understand the code, I'm somewhat confused by the implementation of the metaclass. Here are the relevant snippets: The default "metaclass" of SqlAlchemy: ``` class DeclarativeMeta(type): def __init__(cls, classname...
First things first. `__init__` is **required** to return `None`. The [Python docs](http://docs.python.org/reference/datamodel.html#object.__init__) say "no value may be returned", but in Python "dropping off the end" of a function without hitting a return statement is equivalent to `return None`. So explicitly returnin...
SqlAlchemy metaclass confusion
12,664,385
9
2012-09-30T19:35:22Z
12,729,591
8
2012-10-04T14:31:21Z
[ "python", "sqlalchemy", "metaclass" ]
I'm trying to inject some of my own code in the class construction process of SqlAlchemy. Trying to understand the code, I'm somewhat confused by the implementation of the metaclass. Here are the relevant snippets: The default "metaclass" of SqlAlchemy: ``` class DeclarativeMeta(type): def __init__(cls, classname...
the `__init__` in SQLAlchemy's version is wrong, basically. It probably got written like that three years ago by cutting and pasting a metaclass from somewhere, or perhaps it started out as a different method that became `__init__` later, and has just not been changed. I just checked 0.5 when it was first written and i...
Linear regression - reduce degrees of freedom
12,664,590
9
2012-09-30T19:58:30Z
12,664,893
8
2012-09-30T20:33:52Z
[ "python", "numpy", "statistics", "pandas", "curve-fitting" ]
I have a Pandas dataframe with columns like ``` Order Balance Profit cum (%) ``` I'm doing a linear regression ``` model_profit_tr = pd.ols(y=df_closed['Profit cum (%)'], x=df_closed['Order']) ``` The problem with this is that standard model is like (equation of a line that does not pass through the origin)...
Use the `intercept` keyword argument: ``` model_profit_tr = pd.ols(y=df_closed['Profit cum (%)'], x=df_closed['Order'], intercept=False) ``` From docs: ``` In [65]: help(pandas.ols) Help on function ols in module pandas.stats.interface: ols(**kwargs) [snip] ...
how to run scripts with multiple python versions installed?
12,665,103
2
2012-09-30T21:02:37Z
12,665,128
8
2012-09-30T21:06:56Z
[ "python", "command-line-interface" ]
I have 2 versions of python installed on windows, 2.7.3 and 3.3. Some of my scripts are 2.x and some 3.x. Is there an easy way when executing these scripts from a command line to direct them to the appropriate interpreter?
**Note:** For Windows use the new Windows Python launcher (available with *Python 3.3* and downloadable [here](https://bitbucket.org/vinay.sajip/pylauncher/downloads) for earlier releases) which recognizes Unix shell shebangs. You can read about it [here](http://blog.python.org/2011/07/python-launcher-for-windows_11.ht...
numpy.shape gives inconsistent responses - why?
12,665,810
11
2012-09-30T22:48:43Z
12,669,291
8
2012-10-01T07:48:57Z
[ "python", "numpy" ]
I'm a newbie to python. What I would like to know is, Why does the program ``` import numpy as np c = np.array([1,2]) print(c.shape) d = np.array([[1],[2]]).transpose() print(d.shape) ``` give ``` (2,) (1,2) ``` as its output? Shouldn't it be ``` (1,2) (1,2) ``` instead? I got this in both python 2.7.3 and pytho...
When you invoke the `.shape` attribute of a `ndarray`, you get a tuple with as many elements as dimensions of your array. The length, ie, the number of rows, is the first dimension (`shape[0]`) * You start with an array : `c=np.array([1,2])`. That's a plain 1D array, so its shape will be a 1-element tuple, and `shape[...
Function Not Changing Global Variable
12,665,994
11
2012-09-30T23:21:17Z
12,666,008
15
2012-09-30T23:23:35Z
[ "python", "global-variables" ]
my code is as follow: ``` done = False def function(): for loop: code if not comply: done = True #let's say that the code enters this if-statement while done == False: function() ``` For some reason when my code enters the if statement, it doesn't exit the while loop after it's ...
Your issue is that functions create their own namespace, which means that `done` within the function is a different one than `done` in the second example. Use `global done` to use the first `done` instead of creating a new one. ``` def function(): global done for loop: code if not comply: ...
Python GUI App Distribution: written in wxPython, TKinter or QT
12,666,278
7
2012-10-01T00:22:22Z
12,667,986
8
2012-10-01T05:38:15Z
[ "python", "user-interface", "wxpython", "pyqt", "tkinter" ]
My question is about the easiness of distributing the GUI app across the platforms (Mac/Linux/Windows), and I want to know the one that makes the user's job easiest. My current understanding is that Tkinter app is the easiest for the users (to install) because as long as the user has installed a Python in her box, my ...
If you're running Kubuntu, PyQt will be installed by default. Most linux distros will have one of PyGtk or PyQt installed by default. WxPython was most likely installed in your Ubuntu box as a dependency for some other package in your system. If your target market is Linux, you can just create a deb or rpm package and...
convert string object to list object in python
12,666,421
3
2012-10-01T00:55:11Z
12,666,425
7
2012-10-01T00:56:46Z
[ "python" ]
Let's say I have a string like `'banana'` and I'd to convert it into a list `['banana']`, in python. I tried `''.join(list('banana'))` and other tricks, and I'm still back to square one! Thanks
Why not `[mystring]`? It uses the list literal to create a list with just the value of `mystring` inside.
How do I decide which way to backtrack in the Smith–Waterman algorithm?
12,666,494
3
2012-10-01T01:10:35Z
12,671,810
10
2012-10-01T10:47:06Z
[ "python", "numpy", "bioinformatics" ]
I am trying to implement local sequence alignment in Python using the [Smith–Waterman algorithm](http://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm). Here's what I have so far. It gets as far as building the [similarity matrix](http://en.wikipedia.org/wiki/Similarity_matrix): ``` import sys, string from ...
When you build the similarity matrix, you need to store not only the similarity score, but *where that score came from*. You currently have a line of code: ``` p[i][j]=max(0,vertical_score,horizontal_score,diagonal_score); ``` so here you need to remember not the just the maximum score, but *which of these* was the m...
Removing an item from list matching a substring - Python
12,666,897
7
2012-10-01T02:31:18Z
12,666,912
17
2012-10-01T02:34:46Z
[ "python", "list", "substring", "string-matching" ]
How do i remove an element from a list if it matches a substring? I have tried removing an element from a list using the `pop()` and `enumerate` method but seems like i'm missing a few contiguous items that needs to be removed: ``` sents = ['@$\tthis sentences needs to be removed', 'this doesnt', '@$\tthis sente...
How about something simple like: ``` >>> [x for x in sents if not x.startswith('@$\t') and not x.startswith('#')] ['this doesnt', 'this shouldnt', 'this isnt', 'this musnt'] ```
Removing an item from list matching a substring - Python
12,666,897
7
2012-10-01T02:31:18Z
12,666,970
7
2012-10-01T02:45:16Z
[ "python", "list", "substring", "string-matching" ]
How do i remove an element from a list if it matches a substring? I have tried removing an element from a list using the `pop()` and `enumerate` method but seems like i'm missing a few contiguous items that needs to be removed: ``` sents = ['@$\tthis sentences needs to be removed', 'this doesnt', '@$\tthis sente...
Another technique using `filter` ``` filter( lambda s: not (s[0:3]=="@$\t" or s[0]=="#"), sents) ``` The problem with your orignal approach is when you're on list item `i` and determine it should be deleted, you remove it from the list, which slides the `i+1` item into the `i` position. The next iteration of the loop...
Invoking top-level function by name in Python
12,667,537
3
2012-10-01T04:28:53Z
12,667,576
7
2012-10-01T04:35:51Z
[ "python" ]
How can I invoke a top-level function by name? For example, ``` #!/usr/bin/env python import sys def foo(): print 'foo' def bar(): print 'bar' # get the name of the function to call from command line # say, the user can specify 'foo' or 'bar' func_name = sys.argv[1] # how do I invoke the function by func_name...
The easiest way is to use `globals` ``` globals()[func_name]() ``` You can also get the current module object by looking it up in `sys.modules`. ``` getattr(sys.modules[__name__], func_name)() ```
Django limit query
12,667,764
2
2012-10-01T05:05:16Z
12,667,785
7
2012-10-01T05:08:45Z
[ "python", "django" ]
I am trying to run a Django query that will limit the returned results to 5 items. This is easy, except for the fact that the query will not always return 5 items. In that case, a statement like this (my code) fails: ``` users = User.objects.filter(username__istartswith = name)[5].only('Person__profile_picture', 'use...
As in doc: <https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets> For example, this returns the first 5 objects (LIMIT 5): ``` Entry.objects.all()[:5] ```
Good ways to "expand" a numpy ndarray?
12,668,027
12
2012-10-01T05:42:10Z
12,668,172
16
2012-10-01T05:59:41Z
[ "python", "numpy", "multidimensional-array" ]
Are there good ways to "expand" a numpy ndarray? Say I have an ndarray like this: ``` [[1 2] [3 4]] ``` And I want each row to contains more elements by filling zeros: ``` [[1 2 0 0 0] [3 4 0 0 0]] ``` I know there must be some brute-force ways to do so (say construct a bigger array with zeros then copy elements ...
There are the index tricks `r_` and `c_`. ``` >>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> z = np.zeros((2, 3), dtype=a.dtype) >>> np.c_[a, z] array([[1, 2, 0, 0, 0], [3, 4, 0, 0, 0]]) ``` If this is performance critical code, you might prefer to use the equivalent `np.concatenate` rather than...
Good ways to "expand" a numpy ndarray?
12,668,027
12
2012-10-01T05:42:10Z
12,672,984
10
2012-10-01T12:09:41Z
[ "python", "numpy", "multidimensional-array" ]
Are there good ways to "expand" a numpy ndarray? Say I have an ndarray like this: ``` [[1 2] [3 4]] ``` And I want each row to contains more elements by filling zeros: ``` [[1 2 0 0 0] [3 4 0 0 0]] ``` I know there must be some brute-force ways to do so (say construct a bigger array with zeros then copy elements ...
Just to be clear: there's no "good" way to extend a NumPy array, as NumPy arrays are **not** expandable. Once the array is defined, the space it occupies in memory, a combination of the number of its elements and the size of each element, is fixed and cannot be changed. The only thing you can do is to create a new arra...
Good ways to "expand" a numpy ndarray?
12,668,027
12
2012-10-01T05:42:10Z
25,173,755
20
2014-08-07T03:43:20Z
[ "python", "numpy", "multidimensional-array" ]
Are there good ways to "expand" a numpy ndarray? Say I have an ndarray like this: ``` [[1 2] [3 4]] ``` And I want each row to contains more elements by filling zeros: ``` [[1 2 0 0 0] [3 4 0 0 0]] ``` I know there must be some brute-force ways to do so (say construct a bigger array with zeros then copy elements ...
You can use `numpy.pad`, as follows: ``` >>> import numpy as np >>> a=[[1,2],[3,4]] >>> np.pad(a, ((0,0),(0,3)), mode='constant', constant_values=0) array([[1, 2, 0, 0, 0], [3, 4, 0, 0, 0]]) ``` Here `np.pad` says, "Take the array `a` and add 0 rows above it, 0 rows below it, 0 columns to the left of it, and 3...
Is there any way to run a python script on remote machine without sending it?
12,672,143
10
2012-10-01T11:10:07Z
12,672,245
10
2012-10-01T11:17:35Z
[ "python", "ssh" ]
I can run a shell script on remote machine with ssh. For example: ``` ssh -l foo 192.168.0.1 "`cat my_script.sh`" ``` Now I want to run a python script without sending .py file. Is there any way?
This will put the contents of my\_script.py on your computer into an echo command that is performed on the remote computer and passed into python. ``` ssh -l foo 192.168.0.1 "echo '`cat my_script.py`' | python" ``` If you want to add command line args it should be as simple as putting them after the python command li...
A bit of math and logic
12,673,041
3
2012-10-01T12:12:54Z
12,673,076
7
2012-10-01T12:14:45Z
[ "python", "math", "logic" ]
So I have this problem here: > If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. > The sum of these multiples is 23. > Find the sum of all the multiples of 3 or 5 below 1000. And I wrote this here: ``` def multiples(num, below): counter = 1 z = 0 while Tr...
Actually you need to remove multiples of 15 once below 1000, because it will be duplicated in both 3 & 5.. Which does not happens for below 10.. ``` Multiple of 3 & 5 = (multiple of 3 + multiple of 5 - multiple of 15) ``` So, you can use a `Set` to store those multiples, to remove the duplicate..
How should I understand the output of dis.dis?
12,673,074
31
2012-10-01T12:14:33Z
12,673,195
45
2012-10-01T12:24:17Z
[ "python", "python-2.7" ]
I would like to understand how to use [dis (the dissembler of Python bytecode)](http://docs.python.org/library/dis.html). Specifically, how should one interpret the output of [`dis.dis`](http://docs.python.org/library/dis.html#dis.dis) (or [`dis.disassemble`](http://docs.python.org/library/dis.html#dis.disassemble))? ...
You are trying to disassemble a string containing source code, but that's not supported by `dis.dis` in Python 2. With a string argument, it treats the string as if it contained byte code (see the function [`disassemble_string` in `dis.py`](http://hg.python.org/cpython/file/ed76eac4491e/Lib/dis.py#l110)). So you are s...
Python: numerical sorting in QTableWidget
12,673,598
2
2012-10-01T12:48:36Z
12,676,014
7
2012-10-01T15:10:44Z
[ "python", "sorting", "pyqt", "qtablewidget" ]
I need first column of my QTableWidget to be populated as: Row: 1, Row: 2...Row: 100 , but sorting doesn't work as expected (numerically). Sorting works fine with this code, but I don't get expected text: ``` for i in range(0, self.rows): item = QtGui.QTableWidgetItem() item.setData(Qt.DisplayRole, "Row: %s" %...
For `QTableWidgetItem`, the `Qt.DisplayRole` and `Qt.EditRole` are treated the same. This means that, in the code: ``` item.setData(Qt.DisplayRole, "Row: %s" %(i) ) item.setData(Qt.EditRole, i) ``` the second line will simply overwrite the data set in the first line. So, effectively, there is no separate `EditRole` ...
Python unittest discovery with subfolders
12,674,167
11
2012-10-01T13:22:52Z
12,674,358
15
2012-10-01T13:34:21Z
[ "python", "unit-testing", "discover" ]
My unittest folder is organized this way. ``` . |-- import | |-- import.kc | |-- import.kh | `-- import_test.py |-- module | |-- module.kc | |-- module.kh | `-- module_test.py `-- test.py ``` I'd want to simply run `test.py` to run each of my `*_test.py` using unittest python module. Currently, my test.py...
Add `__init__.py` in the `import` and `module` directories.
highest palindrome with 3 digit numbers in python
12,674,389
6
2012-10-01T13:36:04Z
12,674,475
7
2012-10-01T13:40:57Z
[ "python", "math", "logic", "palindrome" ]
In problem 4 from <http://projecteuler.net/> it says: > A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 \* 99. > > Find the largest palindrome made from the product of two 3-digit numbers. I have this code here ``` def isPalindrome(num):...
Iterating in reverse doesn't find the largest `x*y`, it finds the palindrome with the largest `x`. There's a larger answer than 580085; it has a smaller `x` but a larger `y`.
Ackermann Function Understanding
12,678,099
5
2012-10-01T17:30:35Z
12,678,675
9
2012-10-01T18:13:08Z
[ "python", "function", "recursion" ]
I'm finding it difficult to understand how the Ackermann Function works. I think my understanding of recursion is flawed? Here is the code in Python: ``` def naive_ackermann(m, n): global calls calls += 1 if m == 0: return n + 1 elif n == 0: return naive_ackermann(m - 1, 1) else:...
The computation of **A(3,4)** is not as easy or short as it might appear at first from the small values of the arguments. The complexity (# of iteration steps) of the Ackermann function grows very rapidly with its arguments, as does the computed result. Here is the definition of the Ackermann function from [Wikipedia]...
Problems embedding IronPython in C# (Missing Compiler required member 'Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember'
12,678,365
21
2012-10-01T17:51:31Z
12,678,409
60
2012-10-01T17:54:48Z
[ "c#", "python", ".net", "dynamic", "ironpython" ]
I'm trying to do a simple hello world to test out embedding IronPython within C# but can't seem to resolve this problem.. This is my C# file; ``` using System; using IronPython.Hosting; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using System.IO; public class dynamic_demo { static void Main() ...
You need to add a reference to `Microsoft.CSharp.dll`. This provides the required types for using `dynamic` in C#. Also, you will likely need to upgrade to IronPython 2.7[.3] or later, as there are some incompatibilities with old releases and the newer .NET frameworks.
Performance or style difference between "if" and "if not"?
12,680,109
7
2012-10-01T19:55:01Z
12,680,174
9
2012-10-01T20:00:16Z
[ "python", "performance", "if-statement", "coding-style" ]
Is there a performance difference or style preference between these two ways of writing if statements? It is basically the same thing, the 1 condition will be met only once while the other condition will be met every other time. Should the condition that is met only once be first or second? Does it make a difference pe...
In your example, `if` isn't needed at all: ``` data = range[0,1023] length = len(data) max_chunk = 10 for offset in xrange(0,length,max_chunk): write_data(data[offset:offset+max_chunk]) # It works correctly ``` I think this is the most efficient way in your case.
loop backwards using django template
12,680,691
19
2012-10-01T20:36:41Z
12,680,719
41
2012-10-01T20:39:01Z
[ "python", "django", "django-templates" ]
I have a list of objects and I am trying to display them all (and so I am using the django `{% for %} {% endfor %}`) However, I need to iterate through each object backwards one at a time, rather than forwards. I've looked at <https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for> but I couldn't really figu...
directly from the page you linked You can loop over a list in reverse by using `{% for obj in list reversed %}`.
Split pandas dataframe string entry to separate rows
12,680,754
21
2012-10-01T20:42:16Z
12,681,217
12
2012-10-01T21:15:03Z
[ "python", "numpy", "pandas" ]
I have a `pandas dataframe` in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be split on ','). For example, `a` should become `b`: ``` In [7]: a Out[7]: var1 var2 0 a,b,c 1 1 d,e,f ...
How about something like this: ``` In [55]: pd.concat([Series(row['var2'], row['var1'].split(',')) for _, row in a.iterrows()]).reset_index() Out[55]: index 0 0 a 1 1 b 1 2 c 1 3 d 2 4 e 2 5 f 2 ``` Then you just have to rename the columns
Split pandas dataframe string entry to separate rows
12,680,754
21
2012-10-01T20:42:16Z
28,182,629
10
2015-01-28T00:28:46Z
[ "python", "numpy", "pandas" ]
I have a `pandas dataframe` in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (assume that CSV are clean and need only be split on ','). For example, `a` should become `b`: ``` In [7]: a Out[7]: var1 var2 0 a,b,c 1 1 d,e,f ...
After painful experimentation to find something faster than the accepted answer, I got this to work. It ran around 100x faster on the dataset I tried it on. If someone knows a way to make this more elegant, by all means please modify my code. I couldn't find a way that works without setting the other columns you want ...
Is there a direct approach to format numbers in jinja2?
12,681,036
19
2012-10-01T21:03:32Z
12,681,178
30
2012-10-01T21:12:32Z
[ "python", "google-app-engine", "jinja2" ]
I need to format decimal numbers in jinja2. When I need to format dates, I call the strftime() method in my template, like this: ``` {{ somedate.strftime('%Y-%m-%d') }} ``` I wonder if there is a similar approach to do this over numbers. Thanks in advance!
You can do it simply like this, the Python way: ``` {{ '%04d' % 42 }} {{ 'Number: %d' % variable }} ``` Or using that method: ``` {{ '%d' | format(42) }} ``` I personally prefer the first one since it's exactly like in Python.
Is there a direct approach to format numbers in jinja2?
12,681,036
19
2012-10-01T21:03:32Z
12,681,234
8
2012-10-01T21:17:21Z
[ "python", "google-app-engine", "jinja2" ]
I need to format decimal numbers in jinja2. When I need to format dates, I call the strftime() method in my template, like this: ``` {{ somedate.strftime('%Y-%m-%d') }} ``` I wonder if there is a similar approach to do this over numbers. Thanks in advance!
You could use round it will let you round the number to a given precision usage is: ``` round(value, precision=0, method='common') ``` The first parameter specifies the precision (default is 0), the second the rounding method from which you can choose 3: ``` 'common' rounds either up or down 'ceil' always rounds up...
Is there a direct approach to format numbers in jinja2?
12,681,036
19
2012-10-01T21:03:32Z
23,451,718
15
2014-05-04T01:47:53Z
[ "python", "google-app-engine", "jinja2" ]
I need to format decimal numbers in jinja2. When I need to format dates, I call the strftime() method in my template, like this: ``` {{ somedate.strftime('%Y-%m-%d') }} ``` I wonder if there is a similar approach to do this over numbers. Thanks in advance!
I want to highlight Joran Beasley's comment because I find it the best solution: Original comment: > can you not do {{ "{0:0.2f}".format(my\_num) }} or {{ my\_num|format "%0.2f" }} (wsgiarea.pocoo.org/jinja/docs/filters.html#format) – Joran Beasley Oct 1 '12 at 21:07` Indeed, `{{ '{0:0.2f}'.format(100) }}` works f...
When to use or not use iterator() in the django ORM
12,681,653
8
2012-10-01T21:52:13Z
12,688,222
13
2012-10-02T09:59:42Z
[ "python", "django", "orm", "iterator", "django-queryset" ]
This is from the [django docs on the queryset `iterator()` method](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.iterator): > A QuerySet typically caches its results internally so that repeated evaluations > do not result in additional queries. In contrast, iterator() will...
Note the first part of the sentence you call out: `For a QuerySet which returns a large number of objects that you only need to access once` So the converse of this is: if you need to re-use a set of results, and they are not so numerous as to cause a memory problem then you should not use `iterator`. Because the extr...
Python list comprehension, with unique items
12,681,753
7
2012-10-01T22:02:07Z
12,681,879
17
2012-10-01T22:14:37Z
[ "python", "list", "list-comprehension" ]
Is there a way to make a list comprehension in Python that only contains unique items? My original idea was to use something like this : `new_items = [unicode(item) for item in items]` However, I later realized that I needed to omit duplicate items. So I ended up with this ugly monstrosity : ``` unique_items = [] fo...
Well, there is no ordered set, but we can misuse OrderedDict: ``` from collections import OrderedDict t = "never gonna give you up" OrderedDict.fromkeys(t).keys() ``` Gives: ``` ['n', 'e', 'v', 'r', ' ', 'g', 'o', 'a', 'i', 'y', 'u', 'p'] ```
Python list comprehension, with unique items
12,681,753
7
2012-10-01T22:02:07Z
26,032,781
7
2014-09-25T07:17:41Z
[ "python", "list", "list-comprehension" ]
Is there a way to make a list comprehension in Python that only contains unique items? My original idea was to use something like this : `new_items = [unicode(item) for item in items]` However, I later realized that I needed to omit duplicate items. So I ended up with this ugly monstrosity : ``` unique_items = [] fo...
Your original idea works with a set comprehension: ``` new_items = {unicode(item) for item in items} ```
Using Celery with existing RabbitMQ messages
12,681,802
6
2012-10-01T22:07:22Z
12,689,936
8
2012-10-02T12:09:28Z
[ "python", "rabbitmq", "celery" ]
I have an existing RabbitMQ deployment that that a few Java applications are using the send out log messages as string JSON objects on various channels. I would like to use Celery to consume these messages and write them to various places (e.g. DB, Hadoop, etc.). I can see that Celery is design to be both the producer...
It's currently hard to add custom consumers to the celery workers, but this is changing in the development version (to become 3.1) where I've added support for Consumer boot-steps. There's no documentation yet as I've just finished implementing it, but here's an example: ``` from celery import Celery from celery.bin ...
Reversing bits of Python integer
12,681,945
16
2012-10-01T22:20:35Z
12,682,003
21
2012-10-01T22:26:51Z
[ "python", "python-2.7", "bit-manipulation" ]
Given a decimal integer (eg. 65), how does one reverse the underlying bits in Python? ie. the following operation: ``` 65 → 01000001 → 10000010 → 130 ``` It seems that this task can be broken down into three steps: 1. Convert the decimal integer to binary representation 2. Reverse the bits 3. Convert back to d...
``` int('{:08b}'.format(n)[::-1], 2) ``` You can specify any filling length in place of the 8. If you want to get really fancy, ``` b = '{:0{width}b}'.format(n, width=width) int(b[::-1], 2) ``` lets you specify the width programmatically.
Django models - assign id instead of object
12,682,254
6
2012-10-01T22:54:05Z
12,682,379
7
2012-10-01T23:10:39Z
[ "python", "django", "django-models" ]
I apologize if my question turns out to be silly, but I'm rather new to Django, and I could not find an answer anywhere. I have the following model: ``` class BlackListEntry(models.Model): user_banned = models.ForeignKey(auth.models.User,related_name="user_banned") user_banning = models.ForeignKey(auth.models.Use...
The answer to your question is: YES. Django will hit the database (at least) 3 times, 2 to retrieve the two User objects and a third one to commit your desired information. This will cause an absolutelly unnecessary overhead. Just try: ``` BlackListEntry.objects.create(user_banned_id=int(user_id),user_banning_id=int...
How to write an exception catching code works in Python2.4 to Python3
12,682,558
8
2012-10-01T23:33:10Z
12,682,585
11
2012-10-01T23:36:27Z
[ "python", "python-3.x" ]
Is there anyway to write an exception catch code that's compatible from python 2.4 to python 3? Like this code: ``` # only works in python 2.4 to 2.7 try: pass except Exception,e: print(e) # only works in python 2.6 to 3.3 try: pass except Exception as e: print(e) ```
Trying to write code that works in both Python 2 and Python 3 is ultimately rather futile, because of the sheer number of differences between them. Indeed, a lot of projects are now maintained in separate Python 2 and Python 3 versions as a result. That said, if you're hell-bent on doing this in a super-portable way.....
python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50
12,683,201
7
2012-10-02T01:02:02Z
12,683,250
25
2012-10-02T01:09:23Z
[ "python", "regex" ]
I want to use python `re.split()` to split a string into individual words by spaces, commas and periods. But I don't want `"1,200"` to be split into `["1", "200"]` or `["1.2"]` to be split into `["1", "2"]`. Example ``` l = "one two 3.4 5,6 seven.eight nine,ten" ``` The result should be `["one", "two", "3.4", "5,6" ...
Use a negative lookahead and a negative lookbehind: ``` > s = "one two 3.4 5,6 seven.eight nine,ten" > parts = re.split('\s|(?<!\d)[,.](?!\d)', s) ['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten'] ``` In other words, you always split by `\s` (whitespace), and only split by commas and periods if they are *...
Heroku/Django: No module named dj_database_url
12,683,367
4
2012-10-02T01:29:05Z
12,684,284
11
2012-10-02T03:50:44Z
[ "python", "django", "postgresql", "heroku" ]
I'm trying to set up PostgresSQL for the first time on Django, running into this error when I try to do a syndb? > ImportError: Could not import settings 'testapp.settings' (Is it on sys.path?): Also have this at the toop of my settings.py file, no idea if this is correct? ``` import dj_database_url DATABASES = {'de...
You don't give a lot of information about exactly where you are trying to run your sync db? Locally? Or up on Heroku? My answer is going to assume that it's locally. Basically, you need to have virtualenv install and pip. While working in your virtualenv (with it activated), you need to do a ``` pip install dj-datab...
Defining nested namespaces in a URLConf, for reversing Django URLs -- does anyone have a cogent example?
12,683,494
9
2012-10-02T01:47:26Z
12,683,926
16
2012-10-02T02:51:40Z
[ "python", "django", "namespaces", "url-mapping", "urlconf" ]
I have been trying to to figure out how to define a nested URL namespace (which `look:like:this`) in a Django URLConf. Before this, I figured out how to do a basic URL namespace and came up with [this simple example snippet](https://gist.github.com/1290418), containing what you might put in a `urls.py` file: ``` from...
It works rather intuitively. `include` a urlconf that has yet another namespaced `include` will result in nested namespaces. ``` ## urls.py nested2 = patterns('', url(r'^index/$', 'index', name='index'), ) nested1 = patterns('', url(r'^nested2/', include(nested2, namespace="nested2"), url(r'^index/$', 'index...
How to remove back end of a list in python?
12,683,576
2
2012-10-02T01:59:59Z
12,683,599
11
2012-10-02T02:02:44Z
[ "python", "list", "range" ]
So for part of class, I have an given input from a `txt` file. Basically, an input string I can be given is something like ``` listy = ["Miko's Lounge", '41.2', '56.7', '99th Ave, NY', '3', '4', '5', '2'] ``` What I need to do with this input is remove the address, and put the numbers at the end of the list into thei...
You can use [list slicing](http://techearth.net/python/index.php5?title=Python%3aBasics%3aSlices) to do this easily: ``` >>> listy[:3]+[listy[4:]] ["Miko's Lounge", '41.2', '56.7', ['3', '4', '5', '2']] ```
Running scipy's oneway anova in a script
12,683,683
6
2012-10-02T02:13:47Z
12,683,697
14
2012-10-02T02:16:36Z
[ "python", "scipy", "anova" ]
I have a problem. I want to run the scipy.stats f\_oneway() ANOVA in a script that loads a data-archive containing groups with numpy arrays like so: ``` archive{'group1': array([ 1, 2, 3, ..., ]), 'group2': array([ 9, 8, 7, ..., ]), ...} ``` Now my problem is that the number of groups is not fixed for...
I suppose you should try: ``` scipy.stats.f_oneway(*archive.values()) ```
How to copy directory recursively in python and overwrite all?
12,683,834
20
2012-10-02T02:37:58Z
12,686,557
24
2012-10-02T08:04:54Z
[ "python", "copy", "distutils" ]
I'm trying to copy `/home/myUser/dir1/` and all its contents (and their contents, etc.) to `/home/myuser/dir2/` in python. Furthermore, I want the copy to overwrite everything in `dir2/`. It *looks* like `distutils.dir_util.copy_tree` might be the right tool for the job, but not sure if there's anything easier/more ob...
You can use [`distutils.dir_util.copy_tree`](https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.copy_tree). It works just fine and you don't have to pass every argument, only `src` and `dst` are mandatory. However in your case you can't use a similar tool like`shutil.copytree` because it behaves differ...
How to copy directory recursively in python and overwrite all?
12,683,834
20
2012-10-02T02:37:58Z
12,687,372
8
2012-10-02T09:02:48Z
[ "python", "copy", "distutils" ]
I'm trying to copy `/home/myUser/dir1/` and all its contents (and their contents, etc.) to `/home/myuser/dir2/` in python. Furthermore, I want the copy to overwrite everything in `dir2/`. It *looks* like `distutils.dir_util.copy_tree` might be the right tool for the job, but not sure if there's anything easier/more ob...
Have a look at the `shutil` package, especially `rmtree` and `copytree`. You can check if a file / path exists with `os.paths.exists(<path>)`. ``` import shutil import os def copy_and_overwrite(from_path, to_path): if os.path.exists(to_path): shutil.rmtree(to_path) shutil.copytree(from_path, to_path) ...
How to copy directory recursively in python and overwrite all?
12,683,834
20
2012-10-02T02:37:58Z
15,824,216
7
2013-04-05T00:54:32Z
[ "python", "copy", "distutils" ]
I'm trying to copy `/home/myUser/dir1/` and all its contents (and their contents, etc.) to `/home/myuser/dir2/` in python. Furthermore, I want the copy to overwrite everything in `dir2/`. It *looks* like `distutils.dir_util.copy_tree` might be the right tool for the job, but not sure if there's anything easier/more ob...
Here's a simple solution to recursively overwrite a destination with a source, creating any necessary directories as it goes. This does not handle symlinks, but it would be a simple extension (see answer by @Michael above). ``` def recursive_overwrite(src, dest, ignore=None): if os.path.isdir(src): if not ...
How to left align a fixed width string?
12,684,368
31
2012-10-02T04:03:09Z
12,684,382
18
2012-10-02T04:05:08Z
[ "python", "string-formatting" ]
I just want fixed width columns of text but the strings are all padded right, instead of left!!? ``` sys.stdout.write("%6s %50s %25s\n" % (code, name, industry)) ``` produces ``` BGA BEGA CHEESE LIMITED Food Beverage & Tobacco BHP BHP BILLITON LIMITED ...
``` sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry)) ``` on a side note you can make the width variable with `*-s` ``` >>> d = "%-*s%-*s"%(25,"apple",30,"something") >>> d 'apple something ' ```
How to left align a fixed width string?
12,684,368
31
2012-10-02T04:03:09Z
12,684,403
68
2012-10-02T04:08:41Z
[ "python", "string-formatting" ]
I just want fixed width columns of text but the strings are all padded right, instead of left!!? ``` sys.stdout.write("%6s %50s %25s\n" % (code, name, industry)) ``` produces ``` BGA BEGA CHEESE LIMITED Food Beverage & Tobacco BHP BHP BILLITON LIMITED ...
You can prefix the size requirement with `-` to left-justify: ``` sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry)) ```
How to left align a fixed width string?
12,684,368
31
2012-10-02T04:03:09Z
12,684,524
25
2012-10-02T04:24:49Z
[ "python", "string-formatting" ]
I just want fixed width columns of text but the strings are all padded right, instead of left!!? ``` sys.stdout.write("%6s %50s %25s\n" % (code, name, industry)) ``` produces ``` BGA BEGA CHEESE LIMITED Food Beverage & Tobacco BHP BHP BILLITON LIMITED ...
This version uses the [str.format](http://docs.python.org/library/stdtypes.html#str.format) method. **Python 2.7 and newer** ``` sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry)) ``` **Python 2.6 version** ``` sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry)) ``` **UPDATE**...
Could you explain more detailed differences between mod_wsgi and werkzeug? (SOS newbies)
12,684,509
4
2012-10-02T04:22:26Z
12,684,610
13
2012-10-02T04:37:58Z
[ "python", "mod-wsgi", "wsgi", "werkzeug" ]
As I stated on the title, I'm currently feeling pretty uncomfortable of basic understanding of them. As far as I know, mod\_wsgi implemented WSGI specification which can be run under Apache web server. It was coded in C language. Another one, werkzeug is a kind of toolkit which have useful utilities. I also reviewed...
WSGI stands for Web Server Gateway Interface, (mostly) defined by PEP 333 at <http://www.python.org/dev/peps/pep-0333/> . It is an effort by the Python community to establish a standard mechanism for web servers to speak to Python applications. In theory, any wsgi compliant server (or extension to an existing web ser...
Could you explain more detailed differences between mod_wsgi and werkzeug? (SOS newbies)
12,684,509
4
2012-10-02T04:22:26Z
12,684,831
7
2012-10-02T05:06:50Z
[ "python", "mod-wsgi", "wsgi", "werkzeug" ]
As I stated on the title, I'm currently feeling pretty uncomfortable of basic understanding of them. As far as I know, mod\_wsgi implemented WSGI specification which can be run under Apache web server. It was coded in C language. Another one, werkzeug is a kind of toolkit which have useful utilities. I also reviewed...
`mod_wsgi` is a wsgi compliant python module that bridges python and apache. it lets you run applications coded to the wsgi spec under apache. `werkzeug` is a wsgi utility library, used to build wsgi compliant applications. it ships with a development server. there are a handful of Python Web Application Frameworks: ...
Is there a python library for notification and waiting?
12,686,283
2
2012-10-02T07:42:02Z
12,686,939
8
2012-10-02T08:33:59Z
[ "python", "zookeeper" ]
I'm using python-zookeeper for locking, and I'm trying to figure out a way of getting the execution to wait for notification when it's watching a file, because `zookeeper.exists()` returns immediately, rather than blocking. Basically, I have the code listed below, but I'm unsure of the best way to implement the `notif...
The Condition variables from Python's threading module are probably a very good fit for what you're trying to do: <http://docs.python.org/library/threading.html#condition-objects> I've extended to the example to make it a little more obvious how you would adapt it for your purposes: ``` #!/usr/bin/env python from c...
How to get last Friday?
12,686,991
5
2012-10-02T08:37:48Z
12,687,078
8
2012-10-02T08:43:35Z
[ "python", "datetime" ]
The code below should return last Friday, 16:00:00. But it returns [Friday of previous week](http://stackoverflow.com/questions/6172782/find-the-friday-of-previous-last-week-in-python). How to fix that? ``` now = datetime.datetime.now() test = (now - datetime.timedelta(days=now.weekday()) + timedelta(days=4, weeks=-1)...
The [`dateutil` library](http://dateutil.readthedocs.org/en/latest/relativedelta.html) is great for things like this: ``` >>> from datetime import datetime >>> from dateutil.relativedelta import relativedelta, FR >>> datetime.now() + relativedelta(weekday=FR(-1)) datetime.datetime(2012, 9, 28, 9, 42, 48, 156867) ```
Multiple negative lookbehind assertions in python regex?
12,689,046
4
2012-10-02T11:00:18Z
12,689,275
7
2012-10-02T11:16:14Z
[ "python", "regex" ]
I'm new to programming, sorry if this seems trivial: I have a text that I'm trying to split into individual sentences using regular expressions. With the `.split` method I search for a dot followed by a capital letter like ``` "\. A-Z" ``` However I need to refine this rule in the following way: The `.` (dot) may not...
First, I think you may want to replace the space with `\s+`, or `\s` if it really is exactly one space (you often find double spaces in English text). Second, to match an uppercase letter you have to use `[A-Z]`, but `A-Z` will not work (but remember there may be other uppercase letters than `A-Z` ...). Additionally,...
ctypes error: libdc1394 error: Failed to initialize libdc1394
12,689,304
52
2012-10-02T11:17:59Z
12,689,392
19
2012-10-02T11:23:53Z
[ "python", "c++", "shared-libraries", "ctypes", "libdc1394" ]
I'm trying to compile my program to a shared library that I can use from within Python code using ctypes. The library compiles fine using this command: ``` g++ -shared -Wl,-soname,mylib -O3 -o mylib.so -fPIC [files] `pkg-config --libs --cflags opencv` ``` However, when I try and import it using ctypes ``` from ctyp...
`libdc1394` is a library for controlling camera hardware. I presume it comes the opencv you link in. Maybe the kernel driver does not load ? I guess there is a number of reasons why it can fail. Maybe some OpenCV expert can answer better. But I bet the problem is on OpenCV lib side. Some initial search for the same e...
ctypes error: libdc1394 error: Failed to initialize libdc1394
12,689,304
52
2012-10-02T11:17:59Z
26,028,597
126
2014-09-25T00:24:59Z
[ "python", "c++", "shared-libraries", "ctypes", "libdc1394" ]
I'm trying to compile my program to a shared library that I can use from within Python code using ctypes. The library compiles fine using this command: ``` g++ -shared -Wl,-soname,mylib -O3 -o mylib.so -fPIC [files] `pkg-config --libs --cflags opencv` ``` However, when I try and import it using ctypes ``` from ctyp...
Very frustrating that nobody actually shows a concrete solution. I had this issue after installing OpenCV. For me the easiest solution to remove this warning was actually to disable this driver: ``` sudo ln /dev/null /dev/raw1394 ```
ctypes error: libdc1394 error: Failed to initialize libdc1394
12,689,304
52
2012-10-02T11:17:59Z
31,769,286
7
2015-08-02T06:47:17Z
[ "python", "c++", "shared-libraries", "ctypes", "libdc1394" ]
I'm trying to compile my program to a shared library that I can use from within Python code using ctypes. The library compiles fine using this command: ``` g++ -shared -Wl,-soname,mylib -O3 -o mylib.so -fPIC [files] `pkg-config --libs --cflags opencv` ``` However, when I try and import it using ctypes ``` from ctyp...
Okay. I spent a entire day on it. Basically, the link between `/dev/raw1394` and `/dev/null` is not permanent. You can bash into your VM, call `ln /dev/null /dev/raw1394`, but it will last only until you re-start your container. What I had to do, that seemed to be the simplest, but not the perfect approach, is to pla...