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
Very simple concurrent programming in Python
10,475,448
5
2012-05-07T00:29:04Z
10,475,452
14
2012-05-07T00:30:25Z
[ "python", "concurrency" ]
I have a simple Python script that uses two much more complicated Python scripts, and does something with the results. I have two modules, Foo and Bar, and my code is like the following: ``` import Foo import Bar output = [] a = Foo.get_something() b = Bar.get_something_else() output.append(a) output.append(b) ```...
In general, you'd use [`threading`](http://docs.python.org/library/threading.html) to do this. First, create a thread for each thing you want to run in parallel: ``` import threading import Foo import Bar results = {} def get_a(): results['a'] = Foo.get_something() a_thread = threading.Thread(target=get_a) a_t...
Calculating crossing (intercept) points of a Series or DataFrame
10,475,488
3
2012-05-07T00:38:47Z
10,619,525
10
2012-05-16T13:24:19Z
[ "python", "pandas" ]
I have periodic data with the index being a floating point number like so: ``` time = [0, 0.1, 0.21, 0.31, 0.40, 0.49, 0.51, 0.6, 0.71, 0.82, 0.93] voltage = [1, -1, 1.1, -0.9, 1, -1, 0.9,-1.2, 0.95, -1.1, 1.11] df = DataFrame(data=voltage, index=time, columns=['voltage']) df.plot(marker='o') ``` I want to...
To do this I ended up with the following. It is a vectorized version which is 150x faster than one that uses a loop. ``` def cross(series, cross=0, direction='cross'): """ Given a Series returns all the index values where the data values equal the 'cross' value. Direction can be 'rising' (for rising...
How to generate a cross platform interface with SWIG?
10,476,483
4
2012-05-07T03:59:16Z
10,479,460
8
2012-05-07T09:12:46Z
[ "python", "c", "gcc", "swig" ]
I'm wrapping a library with SWIG (Python as target). The library functions contains parameters with the datatypes "uint32\_t", "uint8\_t", etc. I want to create the interface as cross-platform as possible, so I want to use the original function signatures in my `interface.i` file. For example: ``` uint32_t func(uint32...
If you want to use these types in your SWIG interface file you can do something like: ``` %module test %include "stdint.i" uint32_t my_function(); ``` Which is an existing SWIG interface has the correct `typedef`s for your system.
How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?
10,477,294
15
2012-05-07T05:53:47Z
10,477,490
18
2012-05-07T06:14:07Z
[ "python", "regex", "file-io", "text-mining", "string-parsing" ]
So essentially I'm looking for specifically a 4 digit code within two angle brackets within a text file. I know that I need to open the text file and then parse line by line, but I am not sure the best way to go about structuring my code after checking "for line in file". I think I can either somehow split it, strip i...
``` import re pattern = re.compile("<(\d{4,5})>") for i, line in enumerate(open('test.txt')): for match in re.finditer(pattern, line): print 'Found on line %s: %s' % (i+1, match.groups()) ``` A couple of notes about the regex: * You don't need the `?` at the end and the outer `(...)` if you don't want to...
temp.readline() empty?
10,478,242
5
2012-05-07T07:24:26Z
10,478,270
13
2012-05-07T07:26:37Z
[ "python" ]
I'm able to create and write to a temp file, however when reading the file lines are empty. I confirmed temp file has content. Here is my code. Thanks ``` import tempfile temp = tempfile.NamedTemporaryFile() with open("~/somefile.txt") as inf: for line in inf: if line==line.lstrip(): temp.writ...
You have to re-open (or rewind) the temp file before you can read from it: ``` import tempfile temp = tempfile.NamedTemporaryFile() with open("~/somefile.txt") as inf: for line in inf: if line==line.lstrip(): temp.write(line) temp.seek(0) # <=============== ADDED line = str(temp.readline())....
How to answer to prompts automatically with python fabric?
10,479,078
17
2012-05-07T08:40:34Z
10,483,096
10
2012-05-07T13:38:08Z
[ "python", "command-prompt", "fabric" ]
I want to run a command which prompts me to enter yes/no or y/n or whatever. If I just run the command `local("my_command")` then it stops and asks me for input. When I type what is needed, script continues to work. How can I automatically respond to the prompt?
See <http://stackoverflow.com/a/10007635/708221> `pip install fexpect` ``` from ilogue.fexpect import expect, expecting, run prompts = [] prompts += expect('What is your name?','John') prompts += expect('Are you at stackoverflow?','Yes') with expecting(prompts): run('my_command') ``` [Fexpect adds answering t...
How to answer to prompts automatically with python fabric?
10,479,078
17
2012-05-07T08:40:34Z
10,483,408
16
2012-05-07T13:57:58Z
[ "python", "command-prompt", "fabric" ]
I want to run a command which prompts me to enter yes/no or y/n or whatever. If I just run the command `local("my_command")` then it stops and asks me for input. When I type what is needed, script continues to work. How can I automatically respond to the prompt?
I have used simple echo pipes to answer prompts with Fabric. ``` run('echo "yes\n"| my_command') ```
How to answer to prompts automatically with python fabric?
10,479,078
17
2012-05-07T08:40:34Z
25,378,036
29
2014-08-19T07:39:55Z
[ "python", "command-prompt", "fabric" ]
I want to run a command which prompts me to enter yes/no or y/n or whatever. If I just run the command `local("my_command")` then it stops and asks me for input. When I type what is needed, script continues to work. How can I automatically respond to the prompt?
Starting from version `1.9`, Fabric includes a way of managing this properly. The [section about Prompts](http://docs.fabfile.org/en/1.9/usage/env.html#prompts) in the Fabric documentation says: > The prompts dictionary allows users to control interactive prompts. If > a key in the dictionary is found in a command’...
Possible to return two lists from a list comprehension?
10,479,319
14
2012-05-07T08:59:33Z
10,479,343
26
2012-05-07T09:01:19Z
[ "python", "list-comprehension" ]
Is it possible to return two lists from a list comprehension? Well, this obviously doesn't work, but something like: ``` rr, tt = [i*10, i*12 for i in xrange(4)] ``` So `rr` and `tt` both are lists with the results from `i*10` and `i*12` respectively. Many thanks
``` >>> rr,tt = zip(*[(i*10, i*12) for i in xrange(4)]) >>> rr (0, 10, 20, 30) >>> tt (0, 12, 24, 36) ```
Static files not being served on Bottle in Python
10,480,037
9
2012-05-07T09:54:31Z
10,480,289
8
2012-05-07T10:12:22Z
[ "javascript", "python", "css", "bottle" ]
I'm trying to set an application up which takes a template HTML file and modifies it live. It's working to an extent, but the images and CSS on the pages aren't being served, and there are HTTP 500 errors on the console when they are requested. This is my directory structure ``` Server/ assets/ css/ ...
I also had problems with serving static files. Here is my solution: ``` @route('/static/:filename#.*#') def send_static(filename): return static_file(filename, root='./static/') ``` and when you want to access a static file eg. a template file: ``` @route('/') def index(): output = template('static/index.tpl...
Compare dictionaries ignoring specific keys
10,480,806
15
2012-05-07T10:55:02Z
10,480,904
10
2012-05-07T11:01:41Z
[ "python", "dictionary" ]
How can I test if two dictionaries are equal while taking some keys out of consideration. For example, ``` equal_dicts( {'foo':1, 'bar':2, 'x':55, 'y': 77 }, {'foo':1, 'bar':2, 'x':66, 'z': 88 }, ignore_keys=('x', 'y', 'z') ) ``` should return True. UPD: I'm looking for an efficient, fast solution. UPD2...
``` def equal_dicts(d1, d2, ignore_keys): d1_filtered = dict((k, v) for k,v in d1.iteritems() if k not in ignore_keys) d2_filtered = dict((k, v) for k,v in d2.iteritems() if k not in ignore_keys) return d1_filtered == d2_filtered ``` EDIT: This might be faster and more memory-efficient: ``` def equal_dict...
Compare dictionaries ignoring specific keys
10,480,806
15
2012-05-07T10:55:02Z
10,481,044
7
2012-05-07T11:11:32Z
[ "python", "dictionary" ]
How can I test if two dictionaries are equal while taking some keys out of consideration. For example, ``` equal_dicts( {'foo':1, 'bar':2, 'x':55, 'y': 77 }, {'foo':1, 'bar':2, 'x':66, 'z': 88 }, ignore_keys=('x', 'y', 'z') ) ``` should return True. UPD: I'm looking for an efficient, fast solution. UPD2...
``` {k: v for k,v in d1.iteritems() if k not in ignore_keys} == {k: v for k,v in d2.iteritems() if k not in ignore_keys} ```
Django Celery tasks dont finish and constantly remain pending
10,482,197
4
2012-05-07T12:36:19Z
10,483,149
7
2012-05-07T13:41:20Z
[ "python", "django", "celery", "amqp", "django-celery" ]
I installed Django Celery bur running `pip install django-celery`. This installed celery and the necessary libraries e.g. celery and kombu. I added `djcelery` to my list of installed apps and ran the `syncdb` and `migrate` commands to create the tables. I've installed RabbitMQ and created a user and vhost using these...
Fixed. This was due to my `__init__.py` in Django inside which I was patching some Python modules using Gevent. Gunicorn uses Gevent and it seems that Celery uses Eventlet. Gevent's monkey patching of thread and multiprocessing modules causes hiccups in Celery.
Use of class typenames in python
10,482,512
5
2012-05-07T12:58:02Z
10,482,688
11
2012-05-07T13:08:45Z
[ "python" ]
What is the use of typename associated with a particular class? For example, ``` Point = namedtuple('P', ['x', 'y']) ``` Where would you normally use typename 'P'? Thank you!
Just for sanity's sake, the first argument to namedtuple should be the same as the variable name you assign it to: ``` >>> from collections import namedtuple >>> Point = namedtuple('P','x y') >>> pp = Point(1,2) >>> type(pp) <class '__main__.P'> ``` isinstance isn't too concerned about this, although just what is 'P'...
Python extending with - using super() python 3 vs python 2
10,482,953
27
2012-05-07T13:28:42Z
10,483,143
13
2012-05-07T13:41:01Z
[ "python", "inheritance", "configparser" ]
Originally I wanted to ask [this question](http://stackoverflow.com/questions/4058400/using-colons-in-configparser-python), but then I found it was already thought of before ... Googling around I found this example of [extending configparser](http://sureshamrita.wordpress.com/2011/08/28/extending-python-configparser/o...
In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes `__init__`. So if you don't define it in your class, you will get the one from the base. Things start being complicated if you introduce multiple inheritance (subclassing more than one clas...
Python extending with - using super() python 3 vs python 2
10,482,953
27
2012-05-07T13:28:42Z
10,483,204
45
2012-05-07T13:44:13Z
[ "python", "inheritance", "configparser" ]
Originally I wanted to ask [this question](http://stackoverflow.com/questions/4058400/using-colons-in-configparser-python), but then I found it was already thought of before ... Googling around I found this example of [extending configparser](http://sureshamrita.wordpress.com/2011/08/28/extending-python-configparser/o...
* [`super()`](http://docs.python.org/py3k/library/functions.html#super) (without arguments) was introduced in python3: ``` super() -> same as super(__class__, <first argument>) ``` so that would be the python2 equivalent for new-style classes: ``` super(CurrentClass, self) ``` * for old-style classes y...
Python extending with - using super() python 3 vs python 2
10,482,953
27
2012-05-07T13:28:42Z
10,486,308
7
2012-05-07T17:22:29Z
[ "python", "inheritance", "configparser" ]
Originally I wanted to ask [this question](http://stackoverflow.com/questions/4058400/using-colons-in-configparser-python), but then I found it was already thought of before ... Googling around I found this example of [extending configparser](http://sureshamrita.wordpress.com/2011/08/28/extending-python-configparser/o...
In short, they are equivalent. Let's have a history view: (1) at first, the function looks like this. ``` class MySubClass(MySuperClass): def __init__(self): MySuperClass.__init__(self) ``` (2) to make code more abstract (and more portable). A common method to get Super-Class is invented like...
Find dictionary items whose key matches a substring
10,484,261
10
2012-05-07T14:54:49Z
10,484,313
21
2012-05-07T14:58:48Z
[ "python" ]
I have a large dictionary constructed like so: ``` programs['New York'] = 'some values...' programs['Port Authority of New York'] = 'some values...' programs['New York City'] = 'some values...' ... ``` How can I return all `programs` whose key mentions "new york" (case insensitive) - which in the example above, wou...
``` [value for key, value in programs.items() if 'new york' in key.lower()] ```
How to get the directory of an argparse file in Python?
10,485,660
8
2012-05-07T16:29:01Z
10,485,748
11
2012-05-07T16:36:16Z
[ "python", "path", "argparse" ]
I use [`argparse`](http://docs.python.org/library/argparse.html) to get a file from the user: ``` import argparse, os parser = argparse.ArgumentParser() parser.add_argument('file', type=file) args = parser.parse_args() ``` Then I want to know the directory where this file is, something like: ``` print(os.path.abspat...
You can get the name of the file from the `.name` attribute, and then pass this to `os.path.abspath`. For example: ``` args = parser.parse_args() path = os.path.abspath(args.file.name) ```
Removing html image tags and everything in between from a string
10,486,027
6
2012-05-07T17:01:22Z
10,486,278
7
2012-05-07T17:20:15Z
[ "python", "html", "regex", "beautifulsoup" ]
I've seen a number of questions about removing HTML tags from strings, but I'm still a bit unclear on how my specific case should be handled. I've seen that many posts advise against using regular expressions to handle HTML, but I suspect my case may warrant judicious circumvention of this rule. I'm trying to parse P...
I would vote that in your case it is acceptable to use a regular expression. Something like this should work: ``` def remove_html_tags(data): p = re.compile(r'<.*?>') return p.sub('', data) ``` I found that snippet here (http://love-python.blogspot.com/2008/07/strip-html-tags-using-python.html) edit: version...
Bottle Static files
10,486,224
17
2012-05-07T17:16:00Z
13,258,941
57
2012-11-06T20:34:28Z
[ "python", "python-2.7", "bottle" ]
So, I have tried reading the Doc's for Bottle, however, I am still unsure about how static file serving works. I have `index.tpl`, however, within it it has a css file attatched to it, and it works. However, i was reading that Bottle does not automatically serve the css files, which cant be true if it loads correctly. ...
This is a template I usually use for serving statics with Bottle: ``` # Static Routes @get('/<filename:re:.*\.js>') def javascripts(filename): return static_file(filename, root='static/js') @get('/<filename:re:.*\.css>') def stylesheets(filename): return static_file(filename, root='static/css') @get('/<filen...
Python - How to declare and add items to an array?
10,487,278
67
2012-05-07T18:40:49Z
10,487,291
8
2012-05-07T18:41:52Z
[ "python", "arrays" ]
I'm trying to add items to an array in python. I run ``` array = {} ``` Then, I try to add something to this array by doing: ``` array.append(valueToBeInserted) ``` There doesn't seem to be a `.append` method for this. How do I add items to an array?
No, if you do: ``` array = {} ``` IN your example you are using `array` as a dictionary, not an array. If you need an array, in Python you use lists: ``` array = [] ``` Then, to add items you do: ``` array.append('a') ```
Python - How to declare and add items to an array?
10,487,278
67
2012-05-07T18:40:49Z
10,487,303
141
2012-05-07T18:42:42Z
[ "python", "arrays" ]
I'm trying to add items to an array in python. I run ``` array = {} ``` Then, I try to add something to this array by doing: ``` array.append(valueToBeInserted) ``` There doesn't seem to be a `.append` method for this. How do I add items to an array?
`{}` represents an empty dictionary What you are looking for for a list is `[]` To initialize an empty list do something like ``` my_list = [] ``` or ``` my_list = list() ``` To add elements to the standard python list you use `append` ``` my_list.append(12) ``` To `extend` the list to include the elements from ...
Unicode error handling with Python 3's readlines()
10,487,563
9
2012-05-07T19:02:39Z
10,487,617
18
2012-05-07T19:06:54Z
[ "python", "text", "encoding" ]
I keep getting this error while reading a text file. Is it possible to handle/ignore it and proceed? > UnicodeEncodeError: ‘charmap’ codec can’t decode byte 0x81 in position > 7827: character maps to undefined.
In Python 3, pass an appropriate `errors=` value (such as `errors=ignore` or `errors=replace`) on creating your file object (presuming it to be a subclass of `io.TextIOWrapper` -- and if it isn't, consider wrapping it in one!); also, consider passing a more likely encoding than `charmap` (when you aren't sure, `utf-8` ...
Why am I forced to os.path.expanduser in python?
10,487,827
15
2012-05-07T19:23:03Z
10,487,862
18
2012-05-07T19:25:01Z
[ "python" ]
I'm sure it's intentional, so can someone explain the rationale for this behavior: ``` Python 2.7.2 (default, Oct 13 2011, 15:27:47) [GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from os.path import isdir,expanduser >>> isdir("~amosa/pdb")...
Because the underlying system calls don't recognize user paths, and the file access APIs are a fairly thin wrapper over them. Additionally, it would be fairly surprising for non-Unix users if (for example) `fopen("~foo")` returned a "foo: no such user" error (as `"~foo"` is a valid file name on, for example, Windows)â...
Python Fabric: Keep permissions of executables when putting them to a remote machine
10,488,073
2
2012-05-07T19:42:28Z
10,491,803
7
2012-05-08T02:33:29Z
[ "python", "permissions", "fabric" ]
My executables lose the execute permissions after putting them to a remote server with Fabric (files are created with default permissions). Does Fabric provide a simple way to keep the file permissions unchanged, or I need to handle them manually? Thanks in advance.
If you're using [put](http://docs.fabfile.org/en/1.4.1/api/core/operations.html#fabric.operations.put) look at it's mirror\_local\_mode kwarg, or if you want some mode specifically, there is a kwarg for mode as well. Both have blurbs on the link I provided.
python celery - ImportError: No module named _curses - while attempting to run manage.py celeryev
10,488,826
10
2012-05-07T20:41:35Z
10,490,084
13
2012-05-07T22:36:51Z
[ "python", "celery", "curses" ]
**Background** Windows 7 x 64 Python 2.7 Django 1.4 Celery with Redis bundle While trying to run manage.py celeryev, I get the following error in the terminal ``` import curses File 'c:\Python2\lib\curses\__init__.py', line 15, in <module> from _curses import * ImportError: No module named _curses ``` I've tried lo...
According to <http://docs.python.org/library/curses.html> the curses module is only supported on Unix platforms. Try the Windows binaries from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses>.
How to obtain a user access token in Python
10,488,913
3
2012-05-07T20:48:28Z
10,489,744
11
2012-05-07T21:59:03Z
[ "python", "facebook", "sdk", "token" ]
I'm using the unofficial python sdk for Facebook. This works fine for alot of graph api calls, but my recent project requires using more FQL. Certain tables (notifications for example) require a user access token rather than an app access token. When using ``` graph.facebook.com/oauth/access_token?client_id=YOUR_APP_...
You can not get a user access token without a direct interaction of a logged in user with your application using the facebook authentication flows. The only token that can be obtained without a user is the application token and you've got that covered already. You can create a user token manually, the easiest way, I t...
Can't find bjam in boost homebrew installation
10,489,049
3
2012-05-07T20:59:39Z
10,498,890
11
2012-05-08T12:45:35Z
[ "c++", "python", "boost-python", "homebrew" ]
I installed Boost with homebrew(`brew install boost`) on my Mac running Lion with the purpose of extending python with an existing C++ program I have. Now I can't follow the [starting guide](http://www.boost.org/doc/libs/1_49_0/libs/python/doc/tutorial/doc/html/python/hello.html) because 1 - I don't have 'bjam' install...
The right formula to install boost for linking c++ with python programs is: `brew install boost-build` as pointed out by senderle in the comments to my question. This installs `bjam` automatically.
How do you create a legend for a contour plot in matplotlib?
10,490,302
14
2012-05-07T23:03:53Z
10,491,152
21
2012-05-08T01:00:12Z
[ "python", "plot", "matplotlib", "contour" ]
I can't seem to find the answer anywhere! I found a discussion [here](http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg08735.html), but trying this I get a `TypeError: 'NoneType' object is not iterable`: ``` >>> import numpy as np >>> import matplotlib.pyplot as plt >>> x, y = np.meshgrid(np.arang...
You can create proxy artists to make the legend: ``` import numpy as np import matplotlib.pyplot as plt x, y = np.meshgrid(np.arange(10),np.arange(10)) z = np.sqrt(x**2 + y**2) cs = plt.contourf(x,y,z,levels=[2,3,4,6]) proxy = [plt.Rectangle((0,0),1,1,fc = pc.get_facecolor()[0]) for pc in cs.collections] plt.le...
How do you create a legend for a contour plot in matplotlib?
10,490,302
14
2012-05-07T23:03:53Z
10,494,136
14
2012-05-08T07:05:50Z
[ "python", "plot", "matplotlib", "contour" ]
I can't seem to find the answer anywhere! I found a discussion [here](http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg08735.html), but trying this I get a `TypeError: 'NoneType' object is not iterable`: ``` >>> import numpy as np >>> import matplotlib.pyplot as plt >>> x, y = np.meshgrid(np.arang...
You could also do it directly with the lines of the contour, without using proxy artists. ``` import matplotlib import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['ytick.direction'] = 'out' de...
Scrapy installation on OSX Lion
10,490,303
4
2012-05-07T23:03:55Z
10,502,565
13
2012-05-08T16:28:01Z
[ "python", "osx-lion", "scrapy" ]
So I'm trying to install Scrapy on Lion and am not sure if it's properly installed or not. I followed the guide here <http://doc.scrapy.org/en/latest/intro/install.html#intro-install> Then tried to do the first step to create a tutorial project here, <http://doc.scrapy.org/en/latest/intro/tutorial.html> But when I ...
Well turns out it's likely a path issue. On my Mac, I used `easy_install` from `/usr/bin`. ``` sudo /usr/bin/easy_install scrapy ``` The resulting `scrapy` command is then installed into `/usr/local/bin/scrapy`. You might not have that directory in your path, so see if that's true with: ``` echo $PATH ``` If it i...
Python subprocess Popen not sending all arguments to shell
10,490,529
2
2012-05-07T23:30:10Z
10,490,603
7
2012-05-07T23:40:08Z
[ "python", "subprocess", "popen" ]
I am using Python's subprocess module to launch another program. The program requires an argument '-c{0-7}'. ``` this_dir = os.path.dirname(os.path.abspath(__file__)) cmd = [os.path.join(this_dir,'foobar'),'-c%d' % channel] print "Starting process: %s" % str(cmd) Proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,shel...
The issue is with `shell=True`. Quoting [the docs](http://docs.python.org/library/subprocess.html#subprocess.Popen): > On Unix, with shell=True: […] If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That means it...
Operator overloading in python with the object on the right hand side of the operator
10,490,610
7
2012-05-07T23:40:50Z
10,490,652
8
2012-05-07T23:46:35Z
[ "python", "operator-overloading" ]
I recently learned about operator overloading in python and I would like to know if the following is possible. Consider the folowing hypothetica/contrived class. ``` class My_Num(object): def __init__(self, val): self.val = val def __add__(self, other_num): if isinstance(other_num, My_Num): ...
Yes. For example, there is [`__radd__`](http://docs.python.org/reference/datamodel.html#object.__radd__). Also, [there are none](http://docs.python.org/reference/datamodel.html#object.__lt__) for `__le__()`, `__ge__()`, etc., but as Joel Cornett rightly observes, if you define only `__lt__`, `a > b` calls the `__lt__` ...
How to create a temporary file with Unicode encoding?
10,490,816
12
2012-05-08T00:08:06Z
10,491,145
12
2012-05-08T00:59:29Z
[ "python", "unicode", "temporary-files" ]
When I use `open()` to open a file, I am not able to write unicode strings. I have learned that I need to use `codecs` and open the file with Unicode encoding (see <http://docs.python.org/howto/unicode.html#reading-and-writing-unicode-data>). Now I need to create some temporary files. I tried to use the `tempfile` lib...
Everyone else's answers are correct, I just want to clarify what's going on: The difference between the literal 'foo' and the literal u'foo' is that the former is a string of bytes and the latter is the Unicode object First, understand that Unicode is the character set. UTF-8 is the encoding. The Unicode object is th...
How can I turn <br> and <p> into line breaks?
10,491,223
6
2012-05-08T01:10:56Z
10,491,429
10
2012-05-08T01:42:21Z
[ "python", "html", "xml", "regex" ]
Let's say I have an HTML with `<p>` and `<br>` tags inside. Aftewards, I'm going to strip the HTML to clean up the tags. How can I turn them into line breaks? I'm using Python's [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library, if that helps at all.
Without some specifics, it's hard to be sure this does exactly what you want, but this should give you the idea... it assumes your b tags are wrapped inside p elements. ``` from BeautifulSoup import BeautifulSoup import types def replace_with_newlines(element): text = '' for elem in element.recursiveChildGene...
Differences in RegEx syntax between Python and Java
10,492,180
4
2012-05-08T03:29:37Z
10,502,921
8
2012-05-08T16:53:01Z
[ "java", "python", "regex" ]
I have a working regex in Python and I am trying to convert to Java. It seems that there is a subtle difference in the implementations. The RegEx is trying to match another reg ex. The RegEx in question is: ``` /(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/([gim]+\b|\B) ``` One of the strings that it is having problems on i...
Java doesn't parse Regular Expressions in the same way as Python for a small set of cases. In this particular case the nested `[`'s were causing problems. In Python you don't need to escape any nested `[` but you do need to do that in Java. The original RegEx (for Python): ``` /(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/([...
Why can't I replace the __str__ method of a Python object with another function?
10,493,025
4
2012-05-08T05:26:03Z
10,493,071
12
2012-05-08T05:31:02Z
[ "python" ]
Here is the code: ``` class Dummy(object): def __init__(self, v): self.ticker = v def main(): def _assign_custom_str(x): def _show_ticker(t): return t.ticker x.__str__ = _show_ticker x.__repr__ = _show_ticker return x...
Magic methods are only guaranteed to work if they're [defined on the type rather than on the object](http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes). For example: ``` def _assign_custom_str(x): def _show_ticker(self): return self.ticker ...
Setting SQLAlchemy autoincrement start value
10,494,033
14
2012-05-08T06:57:05Z
10,495,449
12
2012-05-08T08:51:16Z
[ "python", "sqlalchemy", "auto-increment" ]
The `autoincrement` argument in SQLAlchemy seems to be only `True` and `False`, but I want to set the pre-defined value `aid = 1001`, the via autoincrement `aid = 1002` when the next insert is done. In SQL, can be changed like: ``` ALTER TABLE article AUTO_INCREMENT = 1001; ``` I'm using `MySQL` and I have tried fol...
According to [the docs](http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#sqlalchemy.schema.Column.__init__): > autoincrement – > This flag may be set to False to indicate an integer primary key column that should not be considered to be the “autoincrement” column, that is the integer primary key column whi...
Setting SQLAlchemy autoincrement start value
10,494,033
14
2012-05-08T06:57:05Z
10,500,177
12
2012-05-08T14:03:10Z
[ "python", "sqlalchemy", "auto-increment" ]
The `autoincrement` argument in SQLAlchemy seems to be only `True` and `False`, but I want to set the pre-defined value `aid = 1001`, the via autoincrement `aid = 1002` when the next insert is done. In SQL, can be changed like: ``` ALTER TABLE article AUTO_INCREMENT = 1001; ``` I'm using `MySQL` and I have tried fol...
You can achieve this by using [`DDLEvents`](http://docs.sqlalchemy.org/en/rel_0_7/core/events.html?highlight=after_create#sqlalchemy.events.DDLEvents). This will allow you to run additional SQL statements just after the `CREATE TABLE` ran. Look at the examples in the link, but I am guessing your code will look similar ...
Parsing time string in Python
10,494,312
20
2012-05-08T07:19:36Z
10,494,427
41
2012-05-08T07:28:36Z
[ "python", "datetime" ]
I have a date time string that I don't know how to parse it in Python. The string is like this: ``` Tue May 08 15:14:45 +0800 2012 ``` I tried `datetime.strptime("Tue May 08 15:14:45 +0800 2012","%a %b %d %H:%M:%S %z %Y")`, but Python raises `'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'` According ...
`datetime.datetime.strptime` has problems with timezone parsing. Have a look at the [`dateutil` package](http://labix.org/python-dateutil): ``` >>> from dateutil import parser >>> parser.parse("Tue May 08 15:14:45 +0800 2012") datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800)) ```
Parsing time string in Python
10,494,312
20
2012-05-08T07:19:36Z
10,494,434
9
2012-05-08T07:29:05Z
[ "python", "datetime" ]
I have a date time string that I don't know how to parse it in Python. The string is like this: ``` Tue May 08 15:14:45 +0800 2012 ``` I tried `datetime.strptime("Tue May 08 15:14:45 +0800 2012","%a %b %d %H:%M:%S %z %Y")`, but Python raises `'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'` According ...
Your best bet is to have a look at strptime()( <http://docs.python.org/library/time.html#time.strptime> ) something along the lines of ``` >>> from datetime import datetime >>> date_str = 'Tue May 08 15:14:45 +0800 2012' >>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y') >>> date datetime.datetime(2...
Python convert string literals to strings
10,494,789
11
2012-05-08T07:58:08Z
10,495,193
14
2012-05-08T08:31:54Z
[ "python", "string", "string-literals" ]
I want to convert a string literal like `r"r'\nasdf'"` to a string (`'\\nasdf'` in this case). Another case: `r"'\nasdf'"` to `'\nasdf'`. I hope you get it. This is important, because I have a parser of python scripts, that wants to know the exact contents of a string literal. Is `eval` a clever solution? The string...
You want the [`ast` module](http://docs.python.org/library/ast.html): ``` >>> import ast >>> raw = r"r'\nasdf'" >>> ast.literal_eval(raw) '\\nasdf' >>> raw = r"'\nasdf'" >>> ast.literal_eval(raw) '\nasdf' ``` This is a safe method for evaluating/parsing strings that contain Python source code (unlike `eval()`).
Python: How to format large text outputs to be 'prettier' and user defined
10,495,058
2
2012-05-08T08:21:17Z
10,495,153
8
2012-05-08T08:29:20Z
[ "python", "formatting" ]
Ahoy StackOverlow-ers! I have a rather trivial question but it's something that I haven't been able to find in other questions here or on online tutorials: How might we be able to format the output of a Python program that so that it fits a certain aesthetic format without any extra modules? The aim here is that I ha...
Checkout the [python textwrap module](http://docs.python.org/library/textwrap.html) (a standard module) ``` >>> import textwrap >>> t="""Latest news tragic murder innocent victims family quiet neighbourhood""" >>> print "\n".join(textwrap.wrap(t, width=20)) Latest news tragic murder innocent victims family quiet neigh...
mechanize select form using id
10,495,313
19
2012-05-08T08:41:05Z
13,666,943
19
2012-12-02T06:20:44Z
[ "python", "forms", "mechanize" ]
I am working on mechanize with python. ``` <form action="/monthly-reports" accept-charset="UTF-8" method="post" id="sblock"> ``` The form here does not have a name. How can I parse the form using it's `id`?
I found this as a solution for the same problem. `br` is the mechanize object: ``` formcount=0 for frm in br.forms(): if str(frm.attrs["id"])=="sblock": break formcount=formcount+1 br.select_form(nr=formcount) ``` I'm sure the loop counter method above could be done more pythonic, but this should select the...
mechanize select form using id
10,495,313
19
2012-05-08T08:41:05Z
17,302,776
14
2013-06-25T16:33:09Z
[ "python", "forms", "mechanize" ]
I am working on mechanize with python. ``` <form action="/monthly-reports" accept-charset="UTF-8" method="post" id="sblock"> ``` The form here does not have a name. How can I parse the form using it's `id`?
Improving a bit on python412524's example, the documentation states that this is valid as well, and I find it a bit cleaner: ``` for form in br.forms(): if form.attrs['id'] == 'sblock': br.form = form break ```
mechanize select form using id
10,495,313
19
2012-05-08T08:41:05Z
24,575,117
7
2014-07-04T13:08:42Z
[ "python", "forms", "mechanize" ]
I am working on mechanize with python. ``` <form action="/monthly-reports" accept-charset="UTF-8" method="post" id="sblock"> ``` The form here does not have a name. How can I parse the form using it's `id`?
For any future viewers, here's another version using the `predicate` argument. Note that this could be made into a single line with a lambda, if you were so inclined: ``` def is_sblock_form(form): return "id" in form.attrs and form.attrs['id'] == "sblock" br.select_form(predicate=is_sblock_form) ``` Source: <htt...
How do I find out what version of reportlab I'm running?
10,495,526
5
2012-05-08T08:56:53Z
10,495,629
7
2012-05-08T09:02:46Z
[ "python", "reportlab" ]
I need to know what version of reportlab I'm running. The following doesn't seem to work. ``` import reportlab print reportlab.__version__ ```
Can you try: ``` print reportlab.Version ```
How to read windows environment variable value in python?
10,496,748
8
2012-05-08T10:20:55Z
10,496,790
23
2012-05-08T10:24:24Z
[ "python", "environment-variables" ]
I tried this: ``` os.environ['MyVar'] ``` But it did not work! Is there any way suitable for all operating systems?
Try using the following: ``` os.getenv('MyVar') ``` From the [documentation](https://docs.python.org/2/library/os.html#os.getenv): > os.getenv(varname[, value]) > > Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None. > > Availability: most flavors of U...
Python/Plone: Getting all unique keywords (Subject)
10,497,342
4
2012-05-08T11:02:09Z
10,497,719
8
2012-05-08T11:28:09Z
[ "python", "plone", "keyword", "subject" ]
Is there a way of getting all the unique keyword index i.e. Subject in Plone by querying the catalog? I have been using [this](http://collective-docs.readthedocs.org/en/latest/searching_and_indexing/query.html) as a guide but not yet successful. This is what I have so far ``` def search_content_by_keywords(self): ...
``` catalog = self.context.portal_catalog my_keys = catalog.uniqueValuesFor('Subject') ``` reference: <http://docs.plone.org/develop/plone/searching_and_indexing/query.html#unique-values>
How to filter dictionary keys based on its corresponding values
10,498,132
57
2012-05-08T11:57:59Z
10,498,166
81
2012-05-08T11:59:57Z
[ "python", "dictionary" ]
I have: ``` dictionary = {"foo":12, "bar":2, "jim":4, "bob": 17} ``` I want to iterate over this dictionary, but over the values instead of the keys, so I can use the values in another function. For example, I want to test which dictionary values are greater than `6`, and then store their keys in a list. My code loo...
``` >>> d = {"foo": 12, "bar": 2, "jim": 4, "bob": 17} >>> [k for k, v in d.items() if v > 6] # Use d.iteritems() on python 2.x ['bob', 'foo'] ``` --- I'd like to just update this answer to also showcase the solution by @glarrain which I find myself tending to use nowadays. ``` [k for k in d if d[k] > 6] ``` This i...
How to filter dictionary keys based on its corresponding values
10,498,132
57
2012-05-08T11:57:59Z
10,498,171
36
2012-05-08T12:00:17Z
[ "python", "dictionary" ]
I have: ``` dictionary = {"foo":12, "bar":2, "jim":4, "bob": 17} ``` I want to iterate over this dictionary, but over the values instead of the keys, so I can use the values in another function. For example, I want to test which dictionary values are greater than `6`, and then store their keys in a list. My code loo...
To just get the values, use `dictionary.values()` To get key value pairs, use `dictionary.items()`
How to filter dictionary keys based on its corresponding values
10,498,132
57
2012-05-08T11:57:59Z
10,498,187
10
2012-05-08T12:01:34Z
[ "python", "dictionary" ]
I have: ``` dictionary = {"foo":12, "bar":2, "jim":4, "bob": 17} ``` I want to iterate over this dictionary, but over the values instead of the keys, so I can use the values in another function. For example, I want to test which dictionary values are greater than `6`, and then store their keys in a list. My code loo...
Use `items` or `iteritems` on dictionary. Something like: ``` list = [] for k, v in dictionary.iteritems(): if v > 6: list.append(k) print list ```
Django load local json file
10,498,234
8
2012-05-08T12:04:25Z
10,498,280
18
2012-05-08T12:07:13Z
[ "python", "django", "json" ]
I have an ajax view: ``` def ajax_prices(request): data = {'data':'data'} return HttpResponse(json.dumps(data), mimetype='application/json') ``` I want to test this with a local json file (prices.json). How can I import a local json file? Local json file 'prices.json' ``` {"aaData": [ [1, "70.1700", "2008-1...
Use the json module: ``` import json json_data = open('/static/prices.json') data1 = json.load(json_data) // deserialises it data2 = json.dumps(json_data) // json formatted string json_data.close() ``` See [here](http://docs.python.org/library/json.html) for more info. As Joe has said, it's a better practice to...
Format string in python with variable formatting
10,498,434
5
2012-05-08T12:16:30Z
10,498,485
10
2012-05-08T12:19:40Z
[ "python", "string", "string-formatting" ]
How can I use variables to format my variables? ``` cart = {"pinapple": 1, "towel": 4, "lube": 1} column_width = max(len(item) for item in items) for item, qty in cart.items(): print "{:column_width}: {}".format(item, qty) > ValueError: Invalid conversion specification ``` or ``` (...): print "{:"+str(colum...
Okay, problem solved already, here's the answer for future reference: variables can be nested, so this works perfectly fine: ``` for item, qty in cart.items(): print "{0:{1}} - {2}".format(item, column_width, qty) ```
Using matplotlib to annotate certain points
10,499,885
3
2012-05-08T13:45:32Z
10,500,375
7
2012-05-08T14:14:44Z
[ "python", "matplotlib" ]
While I can hack together code to draw an XY plot, I want some additional stuff: * Vertical lines that extend from the X axis to a specified distance upward * text to annotate that point, proximity is a must (see the red text) * the graph to be self-contained image: a 800-long sequence should occupy 800 pixels in widt...
You can do it like this: ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) data = (0, 2, 3, 5, 5, 5, 9, 7, 8, 6, 6) ax.plot(data, 'r-', linewidth=4) plt.axvline(x=5, ymin=0, ymax=4.0 / max(data), linewidth=4) plt.text(5, 4, 'your text here') plt.show() ``` Note, that somewhat stra...
Best way to generate random file names in Python
10,501,247
47
2012-05-08T15:03:23Z
10,501,262
67
2012-05-08T15:04:18Z
[ "python", "hash" ]
In Python, what is a good, or the best way to generate some random text to prepend to a file(name) that I'm saving to a server, just to make sure it does not overwrite. Thank you!
Python has facilities to generate temporary file names, see <http://docs.python.org/library/tempfile.html>. For instance: ``` In [4]: import tempfile ``` Each call to `tempfile.NamedTemporaryFile()` results in a different temp file, and its name can be accessed with the `.name` attribute, e.g.: ``` In [5]: tf = temp...
Best way to generate random file names in Python
10,501,247
47
2012-05-08T15:03:23Z
10,501,355
51
2012-05-08T15:09:10Z
[ "python", "hash" ]
In Python, what is a good, or the best way to generate some random text to prepend to a file(name) that I'm saving to a server, just to make sure it does not overwrite. Thank you!
You could use the [UUID module](http://docs.python.org/library/uuid.html) for generating a random string: ``` import uuid filename = str(uuid.uuid4()) ``` This is a valid choice, given that an [UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) generator is extremely unlikely to produce a duplicate ide...
Python modules with identical names (i.e., reusing standard module names in packages)
10,501,473
5
2012-05-08T15:16:21Z
28,854,227
7
2015-03-04T12:14:05Z
[ "python", "module", "namespaces", "package" ]
Suppose I have a package that contains modules: ``` SWS/ __init.py__ foo.py bar.py time.py ``` and the modules need to refer to functions contained in one another. It seems like I run into problems with my `time.py` module since there is a standard module that goes by the same name. For instance, in the case...
Reusing names of standard functions/classes/modules/packages is never a good idea. Try to avoid it as much as possible. However there are clean workarounds to your situation. The behaviour you see, importing your `SWS.time` instead of the stdlib `time`, is due to the semantics of `import` in ancient python versions (2...
How does Python importing exactly work?
10,501,724
23
2012-05-08T15:31:02Z
10,501,768
35
2012-05-08T15:33:01Z
[ "python", "import", "module" ]
I have two specific situations where I don't understand how importing works in Python: **1st specific situation:** When I import the same module in two different Python scripts, the module isn't imported twice, right? The first time Python encounters it, it is imported, and second time, does it check if the module ha...
**Part 1** The module is only loaded once, so there is no performance loss by importing it again. If you actually wanted it to be loaded/parsed again, you'd have to `reload()` the module. > The first place checked is `sys.modules`, the cache of all modules that have been imported previously. [[source](http://docs.pyt...
Explanation of Merge Sort for Dummies
10,502,533
12
2012-05-08T16:26:15Z
10,503,204
12
2012-05-08T17:10:48Z
[ "python", "algorithm", "sorting", "mergesort" ]
I found this code online: ``` def merge(left, right): result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result ...
When I'm stumbled into diffuculty to uderstand how the algorithm works, I add debug output to check what really happens inside the algorithm. Here the code with debug output. Try to uderstand all the steps with recursive calls of `mergesort` and what `merge` does with the output: ``` def merge(left, right): resul...
Explanation of Merge Sort for Dummies
10,502,533
12
2012-05-08T16:26:15Z
10,503,273
37
2012-05-08T17:15:15Z
[ "python", "algorithm", "sorting", "mergesort" ]
I found this code online: ``` def merge(left, right): result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result ...
I believe that the key to understanding merge sort is understanding the following principle -- I'll call it the merge principle: > Given two separate lists A and B ordered from least to greatest, construct a list C by repeatedly comparing the least value of A to the least value of B, removing the lesser value, and app...
Get the first 100 elements of OrderedDict
10,503,666
8
2012-05-08T17:42:36Z
10,503,702
12
2012-05-08T17:44:54Z
[ "python", "python-3.x" ]
`preresult` is an `OrderedDict()`. I want to save the first 100 elements in it. Or keep `preresult` but delete everything other than the first 100 elements. The structure is like this ``` stats = {'a': {'email1':4, 'email2':3}, 'the': {'email1':2, 'email3':4}, 'or': {'email1':2, 'email3':1}} ``...
Here's a simple solution using `itertools`: ``` >>> import collections >>> from itertools import islice >>> preresult = collections.OrderedDict(zip(range(200), range(200))) >>> list(islice(preresult, 100))[-10:] [90, 91, 92, 93, 94, 95, 96, 97, 98, 99] ``` This returns only keys. If you want items, use `iteritems` (o...
Left eigenvectors not giving correct (markov) stationary probability in scipy
10,504,158
4
2012-05-08T18:16:24Z
10,505,866
7
2012-05-08T20:18:20Z
[ "python", "scipy", "markov-chains" ]
Given the following Markov Matrix: ``` import numpy, scipy.linalg A = numpy.array([[0.9, 0.1],[0.15, 0.85]]) ``` The stationary probability exists and is equal to `[.6, .4]`. This is easy to verify by taking a large power of the matrix: ``` B = A.copy() for _ in xrange(10): B = numpy.dot(B,B) ``` Here `B[0] = [0.6,...
The `[0.83205029, 0.5547002]` is just `[0.6, 0.4]` multiplied by ~1.39. Although from "physical" point of view you need eigenvector with sum of its components equal 1, [scaling eigenvector by some factor does not change it's "eigenness"](http://en.wikipedia.org/wiki/Eigenvector): If ![\vec{v} A = \lambda \vec{v}](htt...
Assigning a proxy model instance to foreign key
10,504,521
2
2012-05-08T18:43:03Z
10,504,952
13
2012-05-08T19:12:49Z
[ "python", "django" ]
I have a django auth user proxy model that has some extra permissions attached to it like so: ``` class User(User): class Meta: proxy = True permissions = ( ("write_messages","May add new messages to front page"), ("view_maps","Can view the maps section"), ) ``` Els...
In addition to what @DavidRobinson said, you need to be careful about creating foreign keys to proxy models. A proxy model is still a subclass of the model it proxies, despite being for all intents and purposes the same as the model. If you have a foreign key to the proxy it will not accept the base class, however a fo...
Writing fortran ordered binary files from python
10,504,543
3
2012-05-08T18:44:11Z
10,504,701
8
2012-05-08T18:55:38Z
[ "python", "numpy", "fortran", "scipy" ]
I have some python code which generates a 256^3 numpy array of data that I'd like to read in with a different fortran code. This would be relatively easy if the numpy ndarray function tofile() had an option to write fortran ordered data, but it does not and will always write C-ordered data. Is there an equivalent func...
You could [`transpose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.transpose.html) the array before writing it out.
Format a float in Python with a maximum number of decimal places and without extra zero padding
10,504,697
8
2012-05-08T18:55:00Z
10,505,705
11
2012-05-08T20:07:04Z
[ "python", "string-formatting", "padding" ]
I need to do some decimal place formatting in python. Preferably, the floating point value should always show at least a starting 0 and one decimal place. Example: ``` Input: 0 Output: 0.0 ``` Values with more decimal places should continue to show them, until it gets 4 out. So: ``` Input: 65.53 Output: 65.53 Input...
What you are asking for should be adressed by the rounding methods like the `round` function and let the float number being naturally displayed with its string representation. ``` >>> round(65.53, 4) '65.53' >>> round(40.355435, 4) '40.3554' >>> round(0, 4) '0.0' ```
Row-to-Column Transposition in Python
10,507,104
18
2012-05-08T21:52:21Z
10,507,199
16
2012-05-08T22:01:28Z
[ "python" ]
I'm new to scripting. I have a table (Table1.txt) and I need to create another table that has Table1's rows arranged in columns and vice versa. I have found solutions to this problem for Perl and SQL but not for Python. I just started learning Python two days ago, so this is as far as I got: ``` import csv import sys ...
The solution in general to transpose a sequence of iterables is: zip(\*original\_list) sample input: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` **program:** ``` with open('in.txt') as f: lis = [x.split() for x in f] for x in zip(*lis): for y in x: print(y+'\t', end='') print('\n') ``...
Row-to-Column Transposition in Python
10,507,104
18
2012-05-08T21:52:21Z
10,507,603
21
2012-05-08T22:44:38Z
[ "python" ]
I'm new to scripting. I have a table (Table1.txt) and I need to create another table that has Table1's rows arranged in columns and vice versa. I have found solutions to this problem for Perl and SQL but not for Python. I just started learning Python two days ago, so this is as far as I got: ``` import csv import sys ...
@Ashwini's answer is perfect. The magic happens in ``` zip(*lis) ``` Let me explain why this works: zip takes (in the simplest case) two lists and "zips" them: `zip([1,2,3], [4,5,6])` will become `[(1,4), (2,5), (3,6)]`. So if you consider the outer list to be a matrix and the inner tuples to be the rows, that's a tr...
Row-to-Column Transposition in Python
10,507,104
18
2012-05-08T21:52:21Z
10,507,708
22
2012-05-08T22:56:43Z
[ "python" ]
I'm new to scripting. I have a table (Table1.txt) and I need to create another table that has Table1's rows arranged in columns and vice versa. I have found solutions to this problem for Perl and SQL but not for Python. I just started learning Python two days ago, so this is as far as I got: ``` import csv import sys ...
Since we are talking about columns, rows and transposes, perhaps it is worth it to mention `numpy` ``` >>> import numpy as np >>> x = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) >>> x array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) >>> x.T array([[ 1, 4, 7, 10], [ 2, 5...
Insert line at middle of file with Python?
10,507,230
12
2012-05-08T22:04:52Z
10,507,291
24
2012-05-08T22:10:20Z
[ "python" ]
Is there a way to do this? Say I have a file that's a list of names that goes like this: 1. Alfred 2. Bill 3. Donald How could I insert the third name, "Charlie", at line x (in this case 3), and automatically send all others down one line? I've seen other questions like this, but they didn't get helpful answers. Can ...
This is a way of doing the trick. ``` f = open("path_to_file", "r") contents = f.readlines() f.close() contents.insert(index, value) f = open("path_to_file", "w") contents = "".join(contents) f.write(contents) f.close() ``` "index" and "value" are the line and value of your choice, lines starting from 0.
Splitting path strings into drive, path and file name parts
10,507,298
11
2012-05-08T22:11:04Z
10,507,464
17
2012-05-08T22:28:04Z
[ "python", "path", "split", "filepath" ]
I am new to python and coding in general. I am trying to read from a text file which has path names on each line. I would like to read the text file line by line and split the line strings into drive, path and file name. Here is my code thus far: ``` import os,sys, arcpy ## Open the file with read only permit f = op...
You need to use `os.path.splitdrive` first: ``` with open('C:/Users/visc/scratch/scratch_child/test.txt') as f: for line in f: drive, path = os.path.splitdrive(line) path, filename = os.path.split(path) print('Drive is %s Path is %s and file is %s' % (drive, path, filename)) ``` Notes: * ...
Python string interpolation: only show necessary decimal places
10,507,554
6
2012-05-08T22:37:42Z
10,507,593
7
2012-05-08T22:43:54Z
[ "python", "string", "formatting" ]
If I have for example x = 40 I want the following result: ``` 40" ``` For x = 2.5 the result should be like... ``` 2.5" ``` So I basically want to format to at most one decimal place. I currently use this: ``` "{0:0.1f}\"".format(x, 1) ``` But this displays always exactly one decimal place, which is not really wh...
One option is something like ``` "{0}\"".format(str(round(x, 1) if x % 1 else int(x))) ``` which will display `x` as an integer if there's no fractional part. There's quite possibly a better way to go about this.
Matrix Multiplication in python?
10,508,021
11
2012-05-08T23:41:14Z
10,508,133
13
2012-05-08T23:55:50Z
[ "python", "matrix-multiplication" ]
I'm trying to multiply two matrices together using pure python. Input (X1 is a 3x3 and Xt is a 3x2): ``` X1 = [[1.0016, 0.0, -16.0514], [0.0, 10000.0, -40000.0], [-16.0514, -40000.0, 160513.6437]] Xt = [(1.0, 1.0), (0.0, 0.25), (0.0, 0.0625)] ``` where Xt is the zip transpose of anot...
This is incorrect initialization. You interchanged row with col! ``` C = [[0 for row in range(len(A))] for col in range(len(B[0]))] ``` Correct initialization would be ``` C = [[0 for col in range(len(B[0]))] for row in range(len(A))] ``` Also I would suggest using better naming conventions. Will help you a lot in ...
Matrix Multiplication in python?
10,508,021
11
2012-05-08T23:41:14Z
10,508,239
21
2012-05-09T00:10:47Z
[ "python", "matrix-multiplication" ]
I'm trying to multiply two matrices together using pure python. Input (X1 is a 3x3 and Xt is a 3x2): ``` X1 = [[1.0016, 0.0, -16.0514], [0.0, 10000.0, -40000.0], [-16.0514, -40000.0, 160513.6437]] Xt = [(1.0, 1.0), (0.0, 0.25), (0.0, 0.0625)] ``` where Xt is the zip transpose of anot...
If you really don't want to use `numpy` you can do something like this: ``` def matmult(a,b): zip_b = zip(*b) # uncomment next line if python 3 : # zip_b = list(zip_b) return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) for col_b in zip_b] for row_a in a] x = [[1,2,3],[4,5,6...
Python - Installing matplotlib in Mac OSX Snow Leopard
10,508,360
4
2012-05-09T00:30:44Z
12,759,678
7
2012-10-06T12:11:01Z
[ "python", "matplotlib", "install" ]
I've been having trouble installing matplotlib. I'm getting a similar error to many other topics, but none of those solutions have been working for me. I have tried installing matplotlib via pip and via git and I receive the same error every time I would very much appreciate help. ``` In file included from src/ft2font...
I had the same problem. I use brew. I fixed this by doing ``` brew install freetype brew link freetype brew install libpng brew link libpng brew install matplotlib ``` By default, brew leaves your system versions of freetype and libpng active, which is why you need to do "brew link" as well. Hope that helps. Update:...
Get IP Mask from IP Address and Mask Length in Python
10,508,560
3
2012-05-09T01:00:24Z
10,508,581
12
2012-05-09T01:04:21Z
[ "python", "sockets", "networking", "ip", "subnet" ]
Given an IP Address in dotted quad notation, for example: 192.192.45.1 And a mask length for example 8, 16, 24 typically, but could be anything i.e. 17. Can somebody please provide the code in python to calculate the subnet mask? Preferably I could get the result as 32-bit integer so that it is easy to hash and ...
The simplest way is to use google's [ipaddr](https://github.com/google/ipaddr-py) module. I assume a 25 bit mask below, but as you say, it could be anything ``` >>> import ipaddr >>> mask = ipaddr.IPv4Network('192.192.45.1/25') >>> mask.netmask IPv4Address('255.255.255.128') >>> ``` The module is rather efficient at ...
Get IP Mask from IP Address and Mask Length in Python
10,508,560
3
2012-05-09T01:00:24Z
10,508,732
7
2012-05-09T01:29:53Z
[ "python", "sockets", "networking", "ip", "subnet" ]
Given an IP Address in dotted quad notation, for example: 192.192.45.1 And a mask length for example 8, 16, 24 typically, but could be anything i.e. 17. Can somebody please provide the code in python to calculate the subnet mask? Preferably I could get the result as 32-bit integer so that it is easy to hash and ...
You can calcuate the 32 bit value of the mask like this ``` (1<<32) - (1<<32>>mask_length) ``` eg. ``` >>> import socket, struct >>> mask_length = 24 >>> mask = (1<<32) - (1<<32>>mask_length) >>> socket.inet_ntoa(struct.pack(">L", mask)) '255.255.255.0' ```
How do I concatenate a boolean to a string in Python?
10,509,803
24
2012-05-09T04:21:56Z
10,509,829
51
2012-05-09T04:25:08Z
[ "python", "string", "casting", "boolean", "concatenation" ]
I want to accomplish the following ``` answer = True myvar = "the answer is " + answer ``` and have myvar's value be "the answer is True". I'm pretty sure you can do this in Java.
``` answer = True myvar = "the answer is " + str(answer) ``` Python does not do implicit casting, as implicit casting can mask critical logic errors. Just cast answer to a string itself to get its string representation ("True"), or use string formatting like so: ``` myvar = "the answer is %s" % answer ``` Note that ...
How do I concatenate a boolean to a string in Python?
10,509,803
24
2012-05-09T04:21:56Z
10,509,878
8
2012-05-09T04:30:59Z
[ "python", "string", "casting", "boolean", "concatenation" ]
I want to accomplish the following ``` answer = True myvar = "the answer is " + answer ``` and have myvar's value be "the answer is True". I'm pretty sure you can do this in Java.
The recommended way is to let `str.format` handle the casting ([docs](http://docs.python.org/library/string.html#formatstrings)). Methods with `%s` substitution may be deprecated eventually (see [PEP3101](http://legacy.python.org/dev/peps/pep-3101/)). ``` >>> answer = True >>> myvar = "the answer is {}".format(answer)...
Enforcing side effects in python
10,509,916
4
2012-05-09T04:36:33Z
10,509,967
8
2012-05-09T04:45:06Z
[ "python", "functional-programming", "code-analysis" ]
Is there a tool that enables you to annotate functions/methods as "pure" and then analyzes the code to test if said functions/methods are side effect free ?
In the Python world, the question doesn't make much sense since objects have so much say in what happens in a function call. For example, how could you tell if the following function is pure? ``` def f(x): return x + 1 ``` The answer depends on what *x* is: ``` >>> class A(int): def __add__(self, other):...
Finding unusual value in an array, list
10,510,169
5
2012-05-09T05:12:50Z
10,510,190
9
2012-05-09T05:15:37Z
[ "python", "algorithm", "algorithmic-trading" ]
I have sales statistic data in array form to calc standard deviation or average from this data. ``` stats = [100, 98, 102, 100, 108, 23, 120] ``` let said +-20% differential is normal situation, **23** is obviously a special case. what's the best algorithm (in any language, pseudo or any principle) to find this unus...
You could convert them to [Z-scores](http://en.wikipedia.org/wiki/Standard_score) and look for outliers. ``` >>> import numpy as np >>> stats = [100, 98, 102, 100, 108, 23, 120] >>> mean = np.mean(stats) >>> std = np.std(stats) >>> stats_z = [(s - mean)/std for s in stats] >>> np.abs(stats_z) > 2 array([False, False, ...
in Ipython notebook, Pandas is not displying the graph I try to plot.
10,511,024
53
2012-05-09T06:45:29Z
10,511,230
17
2012-05-09T07:00:40Z
[ "python", "ipython", "pandas" ]
I am trying to plot some data using pandas in Ipython Notebook, and while it gives me the object, it doesn't actually plot the graph itself. So it looks like this: ``` In [7]: pledge.Amount.plot() Out[7]: <matplotlib.axes.AxesSubplot at 0x9397c6c> ``` The graph should follow after that, but it simply doesn't appea...
With your `import matplotlib.pyplot as plt` just add ``` plt.show() ``` and it will show all stored plots.
in Ipython notebook, Pandas is not displying the graph I try to plot.
10,511,024
53
2012-05-09T06:45:29Z
10,511,545
49
2012-05-09T07:24:51Z
[ "python", "ipython", "pandas" ]
I am trying to plot some data using pandas in Ipython Notebook, and while it gives me the object, it doesn't actually plot the graph itself. So it looks like this: ``` In [7]: pledge.Amount.plot() Out[7]: <matplotlib.axes.AxesSubplot at 0x9397c6c> ``` The graph should follow after that, but it simply doesn't appea...
Ok, It seems the answer is to start ipython notebook with --pylab=inline. so ipython notebook --pylab=inline This has it do what I saw earlier and what I wanted it to do. Sorry about the vague original question.
in Ipython notebook, Pandas is not displying the graph I try to plot.
10,511,024
53
2012-05-09T06:45:29Z
23,901,625
85
2014-05-28T01:47:44Z
[ "python", "ipython", "pandas" ]
I am trying to plot some data using pandas in Ipython Notebook, and while it gives me the object, it doesn't actually plot the graph itself. So it looks like this: ``` In [7]: pledge.Amount.plot() Out[7]: <matplotlib.axes.AxesSubplot at 0x9397c6c> ``` The graph should follow after that, but it simply doesn't appea...
Note that --pylab is deprecated and has been removed from newer builds of IPython, so the accepted answer will no longer work. The recommended way to enable inline plotting in the IPython Notebook is now to run: ``` %matplotlib inline import matplotlib.pyplot as plt ``` See [this post](http://mail.scipy.org/pipermail...
Installing `numpy` within a virtualenv in Ubuntu 11.10
10,511,646
6
2012-05-09T07:31:53Z
10,525,417
8
2012-05-09T23:10:09Z
[ "python", "numpy", "packages", "virtualenv", "pip" ]
I got the following exceptions when install `numpy` using `easy_install numpy`, could somebody help please? Whether I am using `pip` or `easy_install`, I got the same problems. It is hard to understand what's going wrong. ``` non-existing path in 'numpy/core': 'build/src.linux-x86_64-2.7/numpy/core/src/multiarray' non...
Perhaps the GCC is not updated. I just did a `apt-get upgrade gcc` and `numpy` compiled successfully.
Python: What does "foo() for i in range(bar)" mean?
10,512,925
16
2012-05-09T09:03:09Z
10,512,963
34
2012-05-09T09:05:57Z
[ "python" ]
What exactly does the following statement mean in Python? ``` randrange(10**10) for i in range(100) ``` I'm aware that `randrange` is a random number generator but cant really make out the effect of the statement.
The way you posted it, it's a [`SyntaxError`](http://docs.python.org/library/exceptions.html#exceptions.SyntaxError). But I guess the statement is inside `[]`. Then it's a [**list comprehension**](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) which creates a list containing 100 random numbe...
Python: What does "foo() for i in range(bar)" mean?
10,512,925
16
2012-05-09T09:03:09Z
10,512,968
25
2012-05-09T09:06:14Z
[ "python" ]
What exactly does the following statement mean in Python? ``` randrange(10**10) for i in range(100) ``` I'm aware that `randrange` is a random number generator but cant really make out the effect of the statement.
On its own, it would be a syntax error. Enclosed in parentheses, it's a [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions): ``` (randrange(10**10) for i in range(100)) ``` returns a generator that will yield the results of 100 calls to `randrange(10**10)`, one at a time. ...
How to add a second x-axis in matplotlib
10,514,315
33
2012-05-09T10:32:30Z
10,515,113
8
2012-05-09T11:24:54Z
[ "python", "matplotlib" ]
I have a very simple question. I need to have a second x-axis on my plot and I want that this axis has a certain number of tics that correspond to certain position of the first axis. Let's try with an example. Here I am plotting the dark matter mass as a function of the expansion factor, defined as 1/(1+z), that range...
You can use twiny to create 2 x-axis scales. For Example: ``` import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twiny() a = np.cos(2*np.pi*np.linspace(0, 1, 60.)) ax1.plot(range(60), a) ax2.plot(range(100), np.ones(100)) # Create a dummy plot ax2.cla() plt.sh...
How to add a second x-axis in matplotlib
10,514,315
33
2012-05-09T10:32:30Z
10,517,481
43
2012-05-09T13:49:02Z
[ "python", "matplotlib" ]
I have a very simple question. I need to have a second x-axis on my plot and I want that this axis has a certain number of tics that correspond to certain position of the first axis. Let's try with an example. Here I am plotting the dark matter mass as a function of the expansion factor, defined as 1/(1+z), that range...
I'm taking a cue from the comments in @Dhara's answer, it sounds like you want to set a list of `new_tick_locations` by a function from the old x-axis to the new x-axis. The `tick_function` below takes in a numpy array of points, maps them to a new value and formats them: ``` import numpy as np import matplotlib.pyplo...
Python/Django: synonym for field "type" in database model (reserved built-in symbol)
10,515,891
10
2012-05-09T12:16:45Z
10,515,967
7
2012-05-09T12:20:55Z
[ "python", "django", "model" ]
I created a django project. It contains a model class with a **"type" attribute**. I think that "type" is the most appropriate term to describe that field, because it defines the kind of the entry. ``` class Vehicle(models.Model): TYPE = ( (u'car', u'Car'), (u'motorcycle', u'Motorcycle'), (...
1. It's always a bad idea to have a variable name that shadows one of [python's built-ins](http://docs.python.org/library/functions.html). It will confuse people reading your code, who expect type to mean something specific. Less important than readability to other users it can also throw off syntax highlighting. 2....
How do i create a custom django backend for django-registration?
10,517,391
2
2012-05-09T13:44:16Z
10,517,538
7
2012-05-09T13:51:22Z
[ "python", "django", "django-forms", "django-registration" ]
I've had a read of this > <http://docs.b-list.org/django-registration/0.8/backend-api.html> and i've had a shot at making my own backend. I am doing this because I want to create a backend that disallows having the same email used for registration, and I wanted to change the email-error message. I also wanted to add ...
You're trying to use a form as a backend, but that's not what a backend is at all. As the document you link to explains, a backend is a class that implements certain methods, including `registration_allowed`. The form doesn't implement any of those, which is not surprising, because it's meant for user input and validat...
django-debug-toolbar not showing up
10,517,765
65
2012-05-09T14:05:43Z
10,518,040
70
2012-05-09T14:21:03Z
[ "python", "django", "django-debug-toolbar" ]
I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar: 1. pip install django-debug-toolbar 2. added to middleware classes: > ``` > MIDDLEWARE_CLASSES = ( > 'django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware...
Stupid question, but you didn't mention it, so... What is `DEBUG` set to? It won't load unless it's `True`. If it's still not working, try adding '127.0.0.1' to `INTERNAL_IPS` as well. **UPDATE** This is a last-ditch-effort move, you shouldn't *have* to do this, but it will clearly show if there's merely some config...
django-debug-toolbar not showing up
10,517,765
65
2012-05-09T14:05:43Z
10,518,184
7
2012-05-09T14:30:07Z
[ "python", "django", "django-debug-toolbar" ]
I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar: 1. pip install django-debug-toolbar 2. added to middleware classes: > ``` > MIDDLEWARE_CLASSES = ( > 'django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware...
I have the toolbar working just perfect. With this configurations: 1. `DEBUG = True` 2. `INTERNAL_IPS = ('127.0.0.1', '192.168.0.1',)` 3. `DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS': False,}` 4. The middleware is the first element in `MIDDLEWARE_CLASSES`: > ``` > MIDDLEWARE_CLASSES = ( > 'debug_toolbar.middlew...
django-debug-toolbar not showing up
10,517,765
65
2012-05-09T14:05:43Z
12,340,567
31
2012-09-09T15:55:37Z
[ "python", "django", "django-debug-toolbar" ]
I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar: 1. pip install django-debug-toolbar 2. added to middleware classes: > ``` > MIDDLEWARE_CLASSES = ( > 'django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware...
If everything else is fine, it could also be that your template lacks an explicit closing `<body>` tag— > [Note: The debug toolbar will only display itself if the mimetype of the response is either text/html or application/xhtml+xml and contains a closing tag.](https://github.com/django-debug-toolbar/django-debug-to...
django-debug-toolbar not showing up
10,517,765
65
2012-05-09T14:05:43Z
14,697,123
52
2013-02-04T22:43:01Z
[ "python", "django", "django-debug-toolbar" ]
I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar: 1. pip install django-debug-toolbar 2. added to middleware classes: > ``` > MIDDLEWARE_CLASSES = ( > 'django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware...
Debug toolbar wants the ip address in request.META['REMOTE\_ADDR'] to be set in the INTERNAL\_IPS setting. Throw in a print statement in one of your views like such: ``` print("IP Address for debug-toolbar: " + request.META['REMOTE_ADDR']) ``` And then load that page. Make sure that IP is in your INTERNAL\_IPS settin...
django-debug-toolbar not showing up
10,517,765
65
2012-05-09T14:05:43Z
20,411,160
11
2013-12-05T21:30:57Z
[ "python", "django", "django-debug-toolbar" ]
I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar: 1. pip install django-debug-toolbar 2. added to middleware classes: > ``` > MIDDLEWARE_CLASSES = ( > 'django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware...
The current stable version 0.11.0 requires the following things to be true for the toolbar to be shown: **Settings file:** 1. `DEBUG = True` 2. `INTERNAL_IPS` to include your browser IP address, as opposed to the server address. If browsing locally this should be `INTERNAL_IPS = ('127.0.0.1',)`. If browsing remotely ...
django-debug-toolbar not showing up
10,517,765
65
2012-05-09T14:05:43Z
26,473,088
7
2014-10-20T19:05:40Z
[ "python", "django", "django-debug-toolbar" ]
I looked at other questions and can't figure it out... I did the following to install django-debug-toolbar: 1. pip install django-debug-toolbar 2. added to middleware classes: > ``` > MIDDLEWARE_CLASSES = ( > 'django.middleware.common.CommonMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware...
Add `10.0.2.2` to your INTERNAL\_IPS on Windows, it is used with vagrant internally INTERNAL\_IPS = ( '10.0.2.2', ) This should work.
Django queryset filtering by ISO week number
10,518,074
8
2012-05-09T14:22:46Z
10,518,266
8
2012-05-09T14:35:06Z
[ "python", "django", "date", "filter", "iso" ]
I have a model that contains `datefield`. I'm trying to get query set of that model that contains current week (starts on Monday). So since Django `datefield` contains simple `datetime.date` model I assumed to filter by using `.isocalendar()`. Logically it's exactly what I want without no extra comparisons and calcula...
You're not going to be able to do this. Remember it's not just an issue of what Python supports, Django has to communicate the filter to the database, and the database doesn't support such complex date calculations. You *can* use `__range`, though, with a start date and end date.
How does this function definition work in python?
10,518,739
3
2012-05-09T15:01:38Z
10,518,754
8
2012-05-09T15:02:20Z
[ "python" ]
I'm a newbie to Python, with a Java background. I came across the following function definition ``` def S(seq,i=0): print i if i==len(seq): return 0 return S(seq,i+1)+seq[i] ``` What exactly does the `i=0` do here, is it re-initialised to 0 each time? Because I notice that the value of i is i...
It provides the *default value* for the second argument. The function can be called with either one or two arguments. If it's called with one, the second argument, `i`, defaults to zero.