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 see traceback on xmlrpc server, not client?
4,659,579
4
2011-01-11T15:57:56Z
4,660,395
7
2011-01-11T17:14:56Z
[ "python", "multithreading", "simplexmlrpcserver", "xmlrpclib", "xmlrpcclient" ]
I have simple xmlrpc server code: ``` from SimpleXMLRPCServer import SimpleXMLRPCServer port = 9999 def func(): print 'Hi!' print x # error! print 'Bye!' if __name__ == '__main__': server = SimpleXMLRPCServer(("localhost", port)) print "Listening on port %s..." % port server.register_functio...
You can do something like this: ``` from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler port = 9999 def func(): print 'Hi!' print x # error! print 'Bye!' class Handler(SimpleXMLRPCRequestHandler): def _dispatch(self, method, params): try: return self...
Matplotlib: simultaneous plotting in multiple threads
4,659,680
11
2011-01-11T16:05:47Z
4,662,511
14
2011-01-11T20:51:20Z
[ "python", "multithreading", "matplotlib", "python-multithreading" ]
I am trying to do some plotting in parallel to finish large batch jobs quicker. To this end, I start a thread for each plot I plan on making. I had hoped that each thread would finish its plotting and close itself (as I understand it, Python closes threads when they get through all the statements in run()). Below is s...
Why not just use multiprocessing? As far as I can tell from your description, threading won't help you much, anyway... Matplotlib already threads so that you can display and interact with multiple figures at once. If you want to speed up batch processing on a multicore machine, you're going to need multiprocessing reg...
PIL rotate image colors (BGR -> RGB)
4,661,557
8
2011-01-11T19:06:16Z
4,661,652
10
2011-01-11T19:18:13Z
[ "python", "colors", "python-imaging-library" ]
I have an image where the colors are BGR. How can I transform my PIL image to swap the B and R elements of each pixel in an efficient manner?
Assuming no alpha band, isn't it as simple as this? ``` b, g, r = im.split() im = Image.merge("RGB", (r, g, b)) ``` Edit: Hmm... It seems PIL has a few bugs in this regard... `im.split()` doesn't seem to work with recent versions of PIL (1.1.7). It may (?) still work with 1.1.6, though... Alternatively, if you have...
PIL rotate image colors (BGR -> RGB)
4,661,557
8
2011-01-11T19:06:16Z
9,641,163
20
2012-03-09T21:19:57Z
[ "python", "colors", "python-imaging-library" ]
I have an image where the colors are BGR. How can I transform my PIL image to swap the B and R elements of each pixel in an efficient manner?
Just to add a more up to date answer: With the new cv2 interface images loaded are now numpy arrays automatically. But openCV cv2.imread() loads images as BGR while numpy.imread() loads them as RGB. The easiest way to convert is to use openCV cvtColor. ``` import cv2 srcBGR = cv2.imread("sample.png") destRGB = cv2...
Code Golf: Finite-state machine!
4,661,818
35
2011-01-11T19:38:07Z
4,662,814
21
2011-01-11T21:21:52Z
[ "python", "language-agnostic", "code-golf", "finite-state-machine" ]
## Finite state machine A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is *Accepted* or *Rejected*. [Leaving some formalities as...
I'm feeling retro today, my language of choice for this task is IBM Enterprise Cobol - char count ~~2462~~ 4078 (Sorry, pasted from a screen oriented device, trailing spaces are a tragic side effect): ``` Identification Division. Program-ID. FSM. Environment Division. ...
Code Golf: Finite-state machine!
4,661,818
35
2011-01-11T19:38:07Z
4,666,506
23
2011-01-12T08:08:04Z
[ "python", "language-agnostic", "code-golf", "finite-state-machine" ]
## Finite state machine A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is *Accepted* or *Rejected*. [Leaving some formalities as...
## Python 2.7+, ~~201 192 187 181 179 175~~ 171 chars PS. After the problem was relaxed (no need to output state line on empty input), here is new code that's notably shorter. If you are on version <2.7, there is no *dict comprehension*, so instead of `{c+o:s for o,c,s in i[1:-1]}` try `dict((c+o,s)for o,c,s in i[1:-1...
Code Golf: Finite-state machine!
4,661,818
35
2011-01-11T19:38:07Z
4,687,779
19
2011-01-14T03:42:59Z
[ "python", "language-agnostic", "code-golf", "finite-state-machine" ]
## Finite state machine A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is *Accepted* or *Rejected*. [Leaving some formalities as...
## sed -- ~~118~~ 137 characters This is using the -r flag (+3), for a total of 134+3=137 characters. ``` $!{H;D} /:/!{G;s/(\S*)..(\S*)/\2 \1:/} s/(.* .)(.*\n\1 (\S*))/\1 -> \3\n\3 \2/ /-/{P;D} /^[A-Z].* :/cACCEPT s/( .).*/\1/ /:/!P cREJECT ``` This should handle inputs without transitions correctly... hopefully it ...
Code Golf: Finite-state machine!
4,661,818
35
2011-01-11T19:38:07Z
4,723,235
8
2011-01-18T10:55:41Z
[ "python", "language-agnostic", "code-golf", "finite-state-machine" ]
## Finite state machine A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is *Accepted* or *Rejected*. [Leaving some formalities as...
## Ruby 1.9.2 - 178 190 182 177 153 161 158 154 145 characters ``` h={} o=s=p $<.map{|l|o,b,c=l.split;h[[o,b]]=c;s||=o} o.chars{|c|puts s+' '+c+((s=h[[s,c]])?' -> '+s :'')}rescue 0 puts s&&s<'['?:ACCEPT: :REJECT ``` ### Testing Script ``` [ "S1 s2 S1 0 s2 S1 1 S1 s2 0 S1 s2 1 s2 1001010", "S1 s2 S1 0 s2 S1 1 S1 ...
Are there any more elegant ways of handling lists in Java ? (Python VS Java)
4,662,091
7
2011-01-11T20:09:06Z
4,662,123
8
2011-01-11T20:14:24Z
[ "java", "python", "list", "operators", "language-design" ]
I do like the way I can treat lists in Python. It does any recursion solution to look easy and clean. For instance the typical problem of getting all the permutations of elements in a list, in Python looks like: ``` def permutation_recursion(numbers,sol): if not numbers: print "this is a permutation", sol ...
No. But this is why Martin Odersky created [Scala](http://www.scala-lang.org). He's even said that one of his goals for Scala is that it be the Python of the Java world. Scala compiles to Java bytecode and easily interops with Java compiled classes. If that's not an option, you could take a look at the [Commons Colle...
Vectors and matrices in Python 3.x
4,662,210
4
2011-01-11T20:22:25Z
4,662,284
8
2011-01-11T20:29:43Z
[ "python", "vector", "matrix", "python-3.x" ]
Is there a good Python 3 library for vectors and matrices? Here's some of the functionality I expect to find in such a library: * matrix multiplication * matrix determinant * euclidean distance between two vectors * cosine similarity between two vectors * convolution
The 1.5 version of [numpy](http://numpy.org/) is compatible with Python 3.
Implementing Single Sign On (SSO) using Django
4,662,348
24
2011-01-11T20:35:37Z
4,663,183
7
2011-01-11T22:08:32Z
[ "python", "django", "single-sign-on" ]
I would like to use Django for implementing Single Sign On (SSO) for multiple applications that we currently use. How to implement SSO using Django ?. Are there any Django packages that can be utilized for implementing SSO ? Please Help Thank You
We're using OpenAM. <http://forgerock.com/openam.html> The OpenAM Cookie means that the user is authenticated. An authentication backend for this is pretty simple. Under 50 lines of code. <https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#other-authentication-sources> We wrote a little bit of code that...
Implementing Single Sign On (SSO) using Django
4,662,348
24
2011-01-11T20:35:37Z
4,663,223
10
2011-01-11T22:13:06Z
[ "python", "django", "single-sign-on" ]
I would like to use Django for implementing Single Sign On (SSO) for multiple applications that we currently use. How to implement SSO using Django ?. Are there any Django packages that can be utilized for implementing SSO ? Please Help Thank You
Take a look at [django-cas-provider](https://github.com/Nitron/django-cas-provider) + [django-cas-consumer](https://github.com/Nitron/django-cas-consumer) (or [django-cas](https://bitbucket.org/cpcc/django-cas/overview))
Can't connect to localhost using Python's MySQLdb
4,662,364
13
2011-01-11T20:37:15Z
4,662,422
20
2011-01-11T20:44:28Z
[ "python", "mysql", "connect" ]
I'm new to this so probably have the wrong terminology but when I run the following script: ``` import MySQLdb conn = MySQLdb.connect (host = 'localhost', user = 'erin', passwd = 'erin', db = 'sec') ``` I get the error: ``` File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10...
if your mysql socket is not placed in /tmp/mysql.sock, you can specify it with ``` conn = MySQLdb.connect (unix_socket = 'path_to_your_socket', host = 'localhost', user = 'erin', passwd = 'erin', db = 'sec') ``` edit: for mamp on macosx the mysql socket path should be something like `/Applications/MAMP/tmp/mysql/mysq...
Can't connect to localhost using Python's MySQLdb
4,662,364
13
2011-01-11T20:37:15Z
12,245,403
26
2012-09-03T09:42:14Z
[ "python", "mysql", "connect" ]
I'm new to this so probably have the wrong terminology but when I run the following script: ``` import MySQLdb conn = MySQLdb.connect (host = 'localhost', user = 'erin', passwd = 'erin', db = 'sec') ``` I get the error: ``` File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10...
I've managed to solve this by setting my host to "127.0.0.1" rather than "localhost".
Django subclassing multiwidget - reconstructing date on post using custom multiwidget
4,662,835
13
2011-01-11T21:25:09Z
4,663,916
10
2011-01-11T23:38:36Z
[ "python", "django", "django-widget", "django-multiwidget" ]
So my django book is back at university and I'm struggling to work this one out. I've subclassed `django.forms.widgets.MultiWidget` like so: ``` class DateSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None, dt=None, mode=0): if dt is not None: self.datepos = dt else: ...
Answered my own question! I implemented this method: ``` def value_from_datadict(self, data, files, name): datelist = [widget.value_from_datadict(data, files, name + '_%s' % i) \ for i, widget in enumerate(self.widgets)] try: D = date(day=int(datelist[0]), month=...
How do I sum the first value in a set of lists within a tuple?
4,663,024
2
2011-01-11T21:50:12Z
4,663,062
8
2011-01-11T21:53:58Z
[ "python", "tuples" ]
Hey, I would like to be able to perform [this](http://stackoverflow.com/questions/638048/how-do-i-sum-the-first-value-in-each-tuple-in-a-list-of-tuples-in-python) but with being selective for which lists I sum up. Let's say, that same example, but with only adding up the first number from the 3rd and 4th list.
Something like: ``` sum(int(tuple_list[i][0]) for i in range(3,5)) ``` range(x, y) generates a list of integers from x(included) to y(excluded) and 1 as the step. If you want to change the `range(x, y, step)` will do the same but increasing by step. You can find the official documentation [here](http://docs.python.o...
Get a list of numbers as input from the user
4,663,306
13
2011-01-11T22:21:22Z
4,663,342
29
2011-01-11T22:24:31Z
[ "python", "list", "raw-input" ]
I tried to use `raw_input()` to get a list of numbers, however with the code ``` numbers = raw_input() print len(numbers) ``` the input `[1,2,3]` gives a result of `7`, so I guess it interprets the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use `re.findall` to extrac...
``` s = raw_input() numbers = map(int, s.split()) ``` and add the numbers separated by spaces. In Python3 `map` no longer returns a `list`, So we need to [wrap it in a `list` call](http://stackoverflow.com/questions/1303347/getting-a-map-to-return-a-list-in-python-3-x). ``` s = input() numbers = list(map(int, s.spli...
implementing a perceptron classifier
4,663,379
9
2011-01-11T22:27:03Z
4,663,805
7
2011-01-11T23:20:09Z
[ "python", "artificial-intelligence", "nlp", "machine-learning", "perceptron" ]
Hi I'm pretty new to Python and to NLP. I need to implement a perceptron classifier. I searched through some websites but didn't find enough information. For now I have a number of documents which I grouped according to category(sports, entertainment etc). I also have a list of the most used words in these documents al...
I think that trying to solve an NLP problem with a Neural Network when you're not familiar with either might be a step too far. That you're doing it in a new language is the least of your worries. I'll link you to my Neural Computation module [slides](http://www.cs.bham.ac.uk/~jxb/inc.html) that gets taught at my univ...
implementing a perceptron classifier
4,663,379
9
2011-01-11T22:27:03Z
4,664,280
16
2011-01-12T00:35:25Z
[ "python", "artificial-intelligence", "nlp", "machine-learning", "perceptron" ]
Hi I'm pretty new to Python and to NLP. I need to implement a perceptron classifier. I searched through some websites but didn't find enough information. For now I have a number of documents which I grouped according to category(sports, entertainment etc). I also have a list of the most used words in these documents al...
### How a perceptron looks like From the outside, a perceptron is a function that takes `n` arguments (i.e an `n`-dimensional vector) and produces `m` outputs (i.e. an `m`-dimensional vector). On the inside, a perceptron consists of layers of *neurons*, such that each neuron in a layer receives input from all neurons...
Python: Install a module out of source code
4,664,075
3
2011-01-12T00:03:26Z
4,664,182
7
2011-01-12T00:19:26Z
[ "python", "module", "install" ]
certainly you all know the answer and it's easy going, but I'm new to python :) I found a piece of code in the internet reading the stock price from yahoo finance ``` #!/usr/bin/env python # # Copyright (c) 2007-2008, Corey Goldberg (corey@goldb.org) # # license: GNU LGPL # # This library is free software; you can...
You could simply place it in the same directory as your script and you will be able to import it. If you want to "install" it, you can place it as `C:\Python31\Lib\site-packages\ystockquote.py`. You should then be able to import it with `import ystockquote`.
Is Python's os.path.join slow?
4,664,306
2
2011-01-12T00:39:39Z
4,664,326
8
2011-01-12T00:42:19Z
[ "python", "performance", "string", "path" ]
I've been told `os.path.join` is horribly slow in python and I should use string concatenation (`'%s/%s' % (x, y)`) instead. Is there really that big a difference and if so how can I track it?
I don't know who told you not to use it, but they're wrong. 1. Even if it were slow, it would never be slow to a program-breaking extent. I've never noticed it being remotely slow. 2. It's key to cross-platform programming. Line separators etc. differ by platform, and `os.path.join` will always join paths correctly re...
Is Python's os.path.join slow?
4,664,306
2
2011-01-12T00:39:39Z
4,664,329
12
2011-01-12T00:43:18Z
[ "python", "performance", "string", "path" ]
I've been told `os.path.join` is horribly slow in python and I should use string concatenation (`'%s/%s' % (x, y)`) instead. Is there really that big a difference and if so how can I track it?
``` $ python -mtimeit -s 'import os.path' 'os.path.join("/root", "file")' 1000000 loops, best of 3: 1.02 usec per loop $ python -mtimeit '"/root" + "file"' 10000000 loops, best of 3: 0.0223 usec per loop ``` So yes, it's nearly 50 times slower. 1 microsecond is still *nothing* though, so I really wouldn't factor the d...
Why can I not read more than 16 bytes of a JPEG file in Python?
4,664,343
5
2011-01-12T00:46:08Z
4,664,513
11
2011-01-12T01:17:26Z
[ "python", "image", "byte", "jpeg" ]
I am trying to read a JPG image in Python. So far i have: ``` f = open("test.jpg") ima = f.read(16) print "'%s'"% (ima) ``` It reads 16 bytes and displays the string in console, but it looks like I cannot display more than 32 bytes. Why? When it tries to read 32 or more bytes, the output will be the same as when i...
Two issues here: 1. Set read mode to binary. This way `file.read` function won't try to convert '\r\n' sequences. 2. You're trying to print NULL-terminated string to the console. `print` function finds first zero character in your string and terminates. Use `binascii.hexlify` to convert it to the hex: ``` f = open("t...
Is there anyway to clear python bytecode cache?
4,664,438
4
2011-01-12T01:04:05Z
4,664,554
8
2011-01-12T01:25:43Z
[ "python", "cpython" ]
each unit test I'm running is writing python code out to a file, then importing it as a module. The problem is that the code changes but further import statements don't modify the module. I think what I need is a way to ether force a reload on a module or clear the internal bytecode cache. Any ideas? Thanks!
Reimporting modules is tricky to get all the edge cases right. The documentation for [reload](http://docs.python.org/library/functions.html#reload) mentions some of them. Depending on what you are testing, you *may* be better off by testing the imports with separate invocations of the interpreter by running each via, s...
Where do you store the variables in jinja?
4,664,515
18
2011-01-12T01:17:46Z
4,664,535
47
2011-01-12T01:21:36Z
[ "python", "templates", "jinja2" ]
I've got five pages with the same page layout and structure, but some different colors, text, etc, so this is an ideal environment for templating. I've decided to use Jinja2 and probably flask. I've read through the documentation, and some tutorials online, which explain lots about what you can do with templates on a p...
Here's the basic usage: First create a template ``` >>> from jinja2 import Template >>> template = Template('Hello {{ name }}!') ``` Then render it passing the variables ``` >>> template.render(name='John Doe') u'Hello John Doe!' ``` Usually you will want to load templates from files instead of code. That's more e...
how to Change default Python version on windows xp
4,664,646
13
2011-01-12T01:44:34Z
4,664,796
10
2011-01-12T02:22:49Z
[ "python", "django", "version" ]
i have two python version, python 2.5 and python 2.7 , and this time i want to use python 2.7 when i setup django , but the django setup using python 2.5 , so What can i do , i use windows xp, not linux , thanks
Change your PATH system environment variable to point to the version of Python you want to use.
how to Change default Python version on windows xp
4,664,646
13
2011-01-12T01:44:34Z
4,665,086
21
2011-01-12T03:29:04Z
[ "python", "django", "version" ]
i have two python version, python 2.5 and python 2.7 , and this time i want to use python 2.7 when i setup django , but the django setup using python 2.5 , so What can i do , i use windows xp, not linux , thanks
Changing your PATH will help, if you always call python directly, rather than relying on file association. For example: `"python foo.py"` will run the 'foo' script with whichever python is first on your PATH. However, if you just run `"foo.py"`, the handler associated in the registry, for this file extension, will be...
how to Change default Python version on windows xp
4,664,646
13
2011-01-12T01:44:34Z
8,254,970
12
2011-11-24T09:45:27Z
[ "python", "django", "version" ]
i have two python version, python 2.5 and python 2.7 , and this time i want to use python 2.7 when i setup django , but the django setup using python 2.5 , so What can i do , i use windows xp, not linux , thanks
Make two simple .cmd files: python25.cmd: ``` @echo off set PYTHONHOME=c:\python25 set PATH=%PATH%;c:\python25 ``` python27.cmd: ``` @echo off set PYTHONHOME=c:\python27 set PATH=%PATH%;c:\python27 ``` Now you can switch between Python 2.5 and 2.7. :)
Find all occurrences of a substring in Python
4,664,850
167
2011-01-12T02:35:18Z
4,664,889
263
2011-01-12T02:43:23Z
[ "python", "regex", "string" ]
Python has `string.find()` and `string.rfind()` to get the index of a substring in string. I wonder, maybe there is something like `string.find_all()` which can return all founded indexes (not only first from beginning or first from end)? For example: ``` string = "test test test test" print string.find('test') # 0...
There is no simple built-in string function that does what you're looking for, but you could use the more powerful [regular expressions](http://www.regular-expressions.info/): ``` >>> [m.start() for m in re.finditer('test', 'test test test test')] [0, 5, 10, 15] ``` If you want to find overlapping matches, [lookahead...
Find all occurrences of a substring in Python
4,664,850
167
2011-01-12T02:35:18Z
4,664,915
25
2011-01-12T02:48:05Z
[ "python", "regex", "string" ]
Python has `string.find()` and `string.rfind()` to get the index of a substring in string. I wonder, maybe there is something like `string.find_all()` which can return all founded indexes (not only first from beginning or first from end)? For example: ``` string = "test test test test" print string.find('test') # 0...
Here's a (very inefficient) way to get *all* (i.e. even overlapping) matches: ``` >>> string = "test test test test" >>> [i for i in range(len(string)) if string.startswith('test', i)] [0, 5, 10, 15] ```
Find all occurrences of a substring in Python
4,664,850
167
2011-01-12T02:35:18Z
4,664,946
15
2011-01-12T02:55:19Z
[ "python", "regex", "string" ]
Python has `string.find()` and `string.rfind()` to get the index of a substring in string. I wonder, maybe there is something like `string.find_all()` which can return all founded indexes (not only first from beginning or first from end)? For example: ``` string = "test test test test" print string.find('test') # 0...
You can use `re.finditer()` for this. ``` >>> import re >>> aString = 'this is a string where the substring "is" is repeated several times' >>> print [(a.start(), a.end()) for a in list(re.finditer('is', astring))] [(2, 4), (5, 7), (38, 40), (42, 44)] ```
Find all occurrences of a substring in Python
4,664,850
167
2011-01-12T02:35:18Z
4,665,027
53
2011-01-12T03:13:28Z
[ "python", "regex", "string" ]
Python has `string.find()` and `string.rfind()` to get the index of a substring in string. I wonder, maybe there is something like `string.find_all()` which can return all founded indexes (not only first from beginning or first from end)? For example: ``` string = "test test test test" print string.find('test') # 0...
``` >>> help(str.find) Help on method_descriptor: find(...) S.find(sub [,start [,end]]) -> int ``` Thus, we can build it ourselves: ``` def find_all(a_str, sub): start = 0 while True: start = a_str.find(sub, start) if start == -1: return yield start start += len(sub) # use...
Find all occurrences of a substring in Python
4,664,850
167
2011-01-12T02:35:18Z
19,720,214
13
2013-11-01T03:16:00Z
[ "python", "regex", "string" ]
Python has `string.find()` and `string.rfind()` to get the index of a substring in string. I wonder, maybe there is something like `string.find_all()` which can return all founded indexes (not only first from beginning or first from end)? For example: ``` string = "test test test test" print string.find('test') # 0...
Come, let us recurse together. ``` def locations_of_substring(string, substring): """Return a list of locations of a substring.""" substring_length = len(substring) def recurse(locations_found, start): location = string.find(substring, start) if location != -1: return recur...
How to fetch dictionaries within dictionaries in a JSON string?
4,664,974
2
2011-01-12T03:00:30Z
4,664,993
7
2011-01-12T03:03:15Z
[ "python", "json", "dictionary", "facebook-graph-api" ]
Using the Facebook Graph API I want to get location data. ``` { "name": "Joe Smith", "link": "http://www.facebook.com/joey", "location": { "id": "105590706140862", "name": "Fairfield, Iowa" } } ``` I can take this object and do things like `object["name"]` to get the name Joe Smith. But how do...
``` import json json_text = """ { "name": "Joe Smith", "link": "http://www.facebook.com/joey", "location": { "id": "105590706140862", "name": "Fairfield, Iowa" } }""" obj = json.loads(json_text) print obj["location"]["name"] ```
The efficiency when using a big data structure in a function in Python
4,665,461
5
2011-01-12T04:53:37Z
4,665,517
8
2011-01-12T05:04:26Z
[ "python", "pass-by-reference", "function-call" ]
I need to use a big data structure, more specifically, a big dictionary to do the looking up job. At the very first my code is like this: ``` #build the dictionary blablabla #look up some information in the ditionary blablabla ``` As I need to look up many times, I begin to realize that it is a good idea to implemen...
Answering the core question, parameter passing is not inefficient, it's not like your values will get copied around. Python passed references around, which is not to say that the way parameters are passed fits the well-known schemes of "pass-by-value" or "pass-by-reference". It's best imagined as initializing the valu...
How to install pymssql on windows with python 2.7?
4,666,290
11
2011-01-12T07:30:16Z
5,114,814
18
2011-02-25T07:45:56Z
[ "python", "installation", "pymssql" ]
It seems that there are no such binaries yet. There is an issue on googlecode: <http://code.google.com/p/pymssql/issues/detail?id=12> but i cannot figure out what to do with those files provided.
You may also get pymssql2.7 library from this unofficial extensions library <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql>
PHP alternative for Python's fabric
4,666,392
7
2011-01-12T07:49:19Z
4,666,511
9
2011-01-12T08:08:44Z
[ "php", "python", "fabric" ]
I am happily using fabric for my Python projects for deployment. Now I am engaged in a larger PHP project and wondering if there is something like fabric for PHP?
Rasmus Lerdorf have released kind of Capistrano for PHP : [WePloy](http://blog.wepay.com/post/69915650225/weploy-wepays-deployment-tool). Maybe it will fits your needs
PHP alternative for Python's fabric
4,666,392
7
2011-01-12T07:49:19Z
4,670,514
10
2011-01-12T15:28:05Z
[ "php", "python", "fabric" ]
I am happily using fabric for my Python projects for deployment. Now I am engaged in a larger PHP project and wondering if there is something like fabric for PHP?
Hmm? Why does it matter? Fabric is just python scripting. So it's project language agnostic. You can use it put anything on a server you'd use scp for, as well as script anything via ssh you'd use bash or [insert other tool here] for. Fabric really isn't Python's capistrano. It's more akin to a combining of both cap an...
how to extract a substring from inside a string in Python?
4,666,973
80
2011-01-12T09:14:21Z
4,666,999
56
2011-01-12T09:17:23Z
[ "python", "string", "substring" ]
Lets say I have a string 'gfgfdAAA1234ZZZuijjk' I want to extract just the '1234' part. I only know what will be the few characters directly before (AAA), and after (ZZZ) the part I am interested in (1234). With sed it is possible to do something like this with a string: ``` echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ...
``` >>> s = 'gfgfdAAA1234ZZZuijjk' >>> start = s.find('AAA') + 3 >>> end = s.find('ZZZ', start) >>> s[start:end] '1234' ``` Then you can use regexps with the re module as well, if you want, but that's not necessary in your case.
how to extract a substring from inside a string in Python?
4,666,973
80
2011-01-12T09:14:21Z
4,667,005
11
2011-01-12T09:18:00Z
[ "python", "string", "substring" ]
Lets say I have a string 'gfgfdAAA1234ZZZuijjk' I want to extract just the '1234' part. I only know what will be the few characters directly before (AAA), and after (ZZZ) the part I am interested in (1234). With sed it is possible to do something like this with a string: ``` echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ...
``` import re print re.search('AAA(.*?)ZZZ', 'gfgfdAAA1234ZZZuijjk').group(1) ```
how to extract a substring from inside a string in Python?
4,666,973
80
2011-01-12T09:14:21Z
4,667,014
166
2011-01-12T09:18:56Z
[ "python", "string", "substring" ]
Lets say I have a string 'gfgfdAAA1234ZZZuijjk' I want to extract just the '1234' part. I only know what will be the few characters directly before (AAA), and after (ZZZ) the part I am interested in (1234). With sed it is possible to do something like this with a string: ``` echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ...
Using regular expressions - [documentation](http://docs.python.org/2/library/re.html) for further reference ``` import re text = 'gfgfdAAA1234ZZZuijjk' m = re.search('AAA(.+?)ZZZ', text) if m: found = m.group(1) # found: 1234 ``` or: ``` import re text = 'gfgfdAAA1234ZZZuijjk' try: found = re.search('AA...
how to extract a substring from inside a string in Python?
4,666,973
80
2011-01-12T09:14:21Z
4,917,004
9
2011-02-06T23:43:17Z
[ "python", "string", "substring" ]
Lets say I have a string 'gfgfdAAA1234ZZZuijjk' I want to extract just the '1234' part. I only know what will be the few characters directly before (AAA), and after (ZZZ) the part I am interested in (1234). With sed it is possible to do something like this with a string: ``` echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ...
### regular expression ``` import re re.search(r"(?<=AAA).*?(?=ZZZ)", your_text).group(0) ``` The above as-is will fail with an `AttributeError` if there are no "AAA" and "ZZZ" in `your_text` ### string methods ``` your_text.partition("AAA")[2].partition("ZZZ")[0] ``` The above will return an empty string if eith...
Processing a huge file (9.1GB) and processing it faster -- Python
4,667,434
11
2011-01-12T10:01:57Z
4,668,663
22
2011-01-12T12:15:35Z
[ "python", "performance" ]
I have a 9GB text file of tweets in the following format: ``` T 'time and date' U 'name of user in the form of a URL' W Actual tweet ``` There are in total 6,000,000 users and more than 60,000,000 tweets. I read 3 lines at a time using itertools.izip() and then according to the name, write it into a fi...
This is why your OS has multiprocessing pipelines. ``` collapse.py sometweetfile | filter.py | user_id.py | user_split.py -d some_directory ``` collapse.py ``` import sys with open("source","r") as theFile: tweet = {} for line in theFile: rec_type, content = line.split('\t') if rec_type in tw...
How to map coordinates in AxesImage to coordinates in saved image file?
4,668,432
6
2011-01-12T11:50:24Z
4,672,015
10
2011-01-12T17:41:20Z
[ "python", "matplotlib" ]
I use [matplotlib](http://matplotlib.sourceforge.net/) to display a matrix of numbers as an image, attach labels along the axes, and save the plot to a PNG file. For the purpose of creating an HTML image map, I need to know the pixel coordinates in the PNG file for a region in the image being displayed by imshow. I ha...
This is one of the more confusing parts of trying to get exact pixel values from matplotlib. Matplotlib separates the renderer that handles exact pixel values from the canvas that the figure and axes are drawn on. Basically, the renderer that exists when the figure is initially created (but not yet displayed) is not n...
Django database query: How to filter objects by date range?
4,668,619
108
2011-01-12T12:09:58Z
4,668,703
83
2011-01-12T12:20:10Z
[ "python", "django", "django-models" ]
I've got a field in one model like ``` class Sample(models.Model): date = fields.DateField(auto_now=False) ``` Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011? Thanks for your help!
You can use [django's `filter`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#gt) with [`datetime.date` objects](http://docs.python.org/library/datetime.html): ``` import datetime samples = Sample.objects.filter(sampledate__gt=datetime.date(2011, 1, 1), sampledate__lt=datet...
Django database query: How to filter objects by date range?
4,668,619
108
2011-01-12T12:09:58Z
4,668,718
193
2011-01-12T12:21:57Z
[ "python", "django", "django-models" ]
I've got a field in one model like ``` class Sample(models.Model): date = fields.DateField(auto_now=False) ``` Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011? Thanks for your help!
Use ``` Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"]) ``` Or if you are just trying to filter month wise: ``` Sample.objects.filter(date__year='2011', date__month='01') ``` ### Edit As lazerscience said, if you want a queryset which excludes the `specified range ends` you s...
Django database query: How to filter objects by date range?
4,668,619
108
2011-01-12T12:09:58Z
6,194,999
51
2011-06-01T00:24:19Z
[ "python", "django", "django-models" ]
I've got a field in one model like ``` class Sample(models.Model): date = fields.DateField(auto_now=False) ``` Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011? Thanks for your help!
When doing django ranges with a filter make sure you know the difference between using a date object vs a datetime object. \_\_range is inclusive on dates but if you use a datetime object for the end date it will not include the entries for that day if the time is not set. ``` startdate = date.today() enddate ...
Django database query: How to filter objects by date range?
4,668,619
108
2011-01-12T12:09:58Z
13,824,741
12
2012-12-11T16:50:26Z
[ "python", "django", "django-models" ]
I've got a field in one model like ``` class Sample(models.Model): date = fields.DateField(auto_now=False) ``` Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011? Thanks for your help!
You can get around the "impedance mismatch" caused by the lack of precision in the `DateTimeField/date` object comparison -- that can occur if using **range** -- by using a **datetime.timedelta** to add a day to last date in the range. This works like: ``` start = date(2012, 12, 11) end = date(2012, 12, 18) new_end = ...
Where does the newline come from in Python?
4,669,260
3
2011-01-12T13:23:40Z
4,669,275
16
2011-01-12T13:25:40Z
[ "python", "python-2.x" ]
In Python when I do ``` print "Line 1 is" print "big" ``` The output I get is ``` Line 1 is big ``` Where does the newline come from? And how do I type both statements in the same line using two print statements?
`print` adds a newline by default. To avoid this, use a trailing `,`: ``` print "Line 1 is", print "big" ``` The `,` will still yield a space. To avoid the space as well, either concatenate your strings and use a single `print` statement, or use `sys.stdout.write()` instead.
Python - anyone have a memoizing decorator that can handle unhashable arguments?
4,669,391
22
2011-01-12T13:39:17Z
4,669,720
14
2011-01-12T14:12:25Z
[ "python", "memoization" ]
I've been using the following memoizing decorator (from the great book Python Algorithms: Mastering Basic Algorithms in the Python Language ... love it, btw). ``` def memo(func): cache = {} @ wraps(func) def wrap(*args): if args not in cache: cache[args] = func(*args) return cac...
Here is the example in Alex Martelli [Python Cookbook](http://rads.stackoverflow.com/amzn/click/0596007973) that show how to create a memoize decorator using [cPickle](http://docs.python.org/library/pickle.html) for function that take mutable argument (**original version**) : ``` import cPickle class MemoizeMutable: ...
Embed variable using sys.stdout.write in Python
4,669,791
6
2011-01-12T14:18:57Z
4,669,802
12
2011-01-12T14:20:11Z
[ "python", "python-2.x" ]
I can embed variables using the print statement in python in this way ``` i=10 print "Value is %s" % (i) ``` Output > ``` > Value is 10 > ``` but doing this ``` i=10 sys.stdout.write ("Value is %s") % (i) ``` gives me the following error > ``` > TypeError: unsupported operand type(s) for %: 'NoneType' and 'int' ...
You got the parentheses wrong. Should be ``` i=10 sys.stdout.write("Value is %s" % i) ``` The `%` operator takes a string and a tuple (or a single object) as arguments. You tried to apply the operator to the return value of `sys.stdout.write()`, which is None. You need to apply it to the string before it is passed to...
How do I write a long integer as binary in Python?
4,670,350
7
2011-01-12T15:13:38Z
4,670,889
8
2011-01-12T15:59:34Z
[ "python", "struct", "biginteger" ]
In Python, long integers have unlimited precision. I would like to write a 16 byte (128 bit) integer to a file. `struct` from the standard library supports only up to 8 byte integers. `array` has the same limitation. Is there a way to do this without masking and shifting each integer? Some clarification here: I'm writ...
I think for unsigned integers (and ignoring endianness) something like ``` import binascii def binify(x): h = hex(x)[2:].rstrip('L') return binascii.unhexlify('0'*(32-len(h))+h) >>> for i in 0, 1, 2**128-1: ... print i, repr(binify(i)) ... 0 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\...
Conditionally passing arbitrary number of default named arguments to a function
4,670,665
7
2011-01-12T15:39:52Z
4,670,716
8
2011-01-12T15:44:16Z
[ "python", "function", "shorthand" ]
Is it possible to pass arbitrary number of named default arguments to a Python function conditionally ? For eg. there's a function: ``` def func(arg, arg2='', arg3='def') ``` Now logic is that I have a condition which determines if arg3 needs to be passed, I can do it like this: ``` if condition == True: func('...
That wouldn't be valid Python syntax you have to have something after `else`. What is done normally is: ``` func('arg', 'arg2', 'some value' if condition else None) ``` and function definition is changed accordingly: ``` def func(arg, arg2='', arg3=None): arg3 = 'def' if arg3 is None else arg3 ```
Web scraping - how to identify main content on a webpage
4,672,060
31
2011-01-12T17:46:15Z
4,672,276
23
2011-01-12T18:06:48Z
[ "python", "web-scraping", "html-parsing", "webpage" ]
Given a news article webpage (from any major news source such as times or bloomberg), I want to identify the main article content on that page and throw out the other misc elements such as ads, menus, sidebars, user comments. What's a generic way of doing this that will work on most major news sites? What are some go...
There are a number of ways to do it, but, none will always work. Here are the two easiest: * if it's a known finite set of websites: in your scraper convert each url from the normal url to the print url for a given site (cannot really be generalized across sites) * Use the arc90 readability algorithm (reference implem...
Web scraping - how to identify main content on a webpage
4,672,060
31
2011-01-12T17:46:15Z
12,202,767
8
2012-08-30T17:57:39Z
[ "python", "web-scraping", "html-parsing", "webpage" ]
Given a news article webpage (from any major news source such as times or bloomberg), I want to identify the main article content on that page and throw out the other misc elements such as ads, menus, sidebars, user comments. What's a generic way of doing this that will work on most major news sites? What are some go...
Diffbot offers a free(10.000 urls) API to do that, don't know if that approach is what you are looking for, but it might help someone <http://www.diffbot.com/>
Problems installing PyCurl on python2.7.0+
4,672,682
6
2011-01-12T18:47:13Z
4,672,702
8
2011-01-12T18:48:43Z
[ "python", "pycurl", "ubuntu-10.10" ]
pycurl installs fine on python2.6 but i get the following error when I try to install in on 2.7 via easy\_install on maverick ``` $ sudo easy_install pycurl install_dir /usr/local/lib/python2.7/dist-packages/ Searching for pycurl Reading http://pypi.python.org/simple/pycurl/ Reading http://pycurl.sourceforge.net/ Read...
``` sudo apt-get install python-dev ``` This installs the Python development package that is required and fixes the problem of the missing header file. (Please read the comment by Corey)
How to unit test a Python function that draws PDF graphics?
4,672,945
17
2011-01-12T19:11:51Z
4,675,060
18
2011-01-12T23:05:12Z
[ "python", "unit-testing", "pdf-generation", "imagemagick", "cairo" ]
I'm writing a CAD application that outputs PDF files using the Cairo graphics library. A lot of the unit testing does not require actually generating the PDF files, such as computing the expected bounding boxes of the objects. However, I want to make sure that the generated PDF files "look" correct after I change the c...
### (See also update below!) I'm doing the same thing using a shell script on Linux that wraps 1. ImageMagick's `compare` command 2. the `pdftk` utility 3. Ghostscript (optionally) (It would be rather easy to port this to a `.bat` Batch file for DOS/Windows.) I have a few reference PDFs created by my application wh...
python httplib Name or service not known
4,673,166
5
2011-01-12T19:33:25Z
7,668,559
9
2011-10-05T22:35:53Z
[ "python", "ssl", "httplib" ]
I'm trying to use httplib to send credit card information to authorize.net. When i try to post the request, I get the following traceback: ``` File "./lib/cgi_app.py", line 139, in run res = method() File "/var/www/html/index.py", line 113, in ProcessRegistration conn.request("POST", "/gateway/transact.dll", mystring,...
As an (obvious) heads up, this same error can also be triggered by including the protocol in the host parameter. For example this code: ``` conn = httplib.HTTPConnection("http://secure.authorize.net", 80, ....) ``` will also cause the "gaierror: [Errno -2] Name or service not known" error, even if all your networking...
Logging within py.test tests
4,673,373
18
2011-01-12T19:53:52Z
4,673,562
12
2011-01-12T20:14:04Z
[ "python", "logging", "py.test" ]
I would like to put some logging statements within test function to examine some state variables. I have the following code snippet: ``` import pytest,os import logging logging.basicConfig(level=logging.DEBUG) mylogger = logging.getLogger() ###########################################################################...
Works for me, here's the output I get: [snip -> example was incorrect] Edit: It seems that you have to pass the `-s` option to py.test so it won't capture stdout. Here (py.test not installed), it was enough to use `python pytest.py -s pyt.py`. For your code, all you need is to pass `-s` in `args` to `main`: ``` pyt...
How to take two lists and combine them excluding any duplicates?
4,674,013
10
2011-01-12T21:00:37Z
4,674,061
25
2011-01-12T21:04:44Z
[ "python" ]
I'd like to make one list from two separate lists of unique items. There are other similar questions but there didn't seem to be any that concerned doing this problem effectively since the lists are a few million items long. Totally unrelated: am I the only one who hates how the tags suggestion box covers up the "pos...
Use a `set`. ``` >>> first = [1, 2, 3, 4] >>> second = [3, 2, 5, 6, 7] >>> third = list(set(first) | set(second)) # '|' is union >>> third [1, 2, 3, 4, 5, 6, 7] ```
Is it faster to union sets or check the whole list for a duplicate?
4,674,208
6
2011-01-12T21:22:57Z
4,674,277
18
2011-01-12T21:31:46Z
[ "python", "set" ]
Sorry for the poorly worded title but I asked a question earlier about getting a unique list of items from two lists. People told me to make the list -> sets and then union. So now I'm wondering if it's faster to: 1. While adding **one** item to a list, scan the whole list for duplicates. 2. Make that one item a set ...
as you can see extending one list by another end then remove duplicates by making set is the fastest way(at least in python;)) ``` >>> def foo(): ... """ ... extending one list by another end then remove duplicates by making set ... """ ... l1 = range(200) ... l2 = range(150, 250) ... l1.extend...
Is it faster to union sets or check the whole list for a duplicate?
4,674,208
6
2011-01-12T21:22:57Z
4,676,424
7
2011-01-13T03:08:55Z
[ "python", "set" ]
Sorry for the poorly worded title but I asked a question earlier about getting a unique list of items from two lists. People told me to make the list -> sets and then union. So now I'm wondering if it's faster to: 1. While adding **one** item to a list, scan the whole list for duplicates. 2. Make that one item a set ...
I really like the approach virhilo did, but it's a pretty specific set of data he was testing. In all this don't just test the functions, but test them how you'll be doing it. I put together a much more exhaustive test set. It runs each function you specify (with just a little decorator) through a list of comparisons, ...
problem with jinja2 autoescape in google app engine webapp
4,674,366
5
2011-01-12T21:41:28Z
4,677,844
8
2011-01-13T07:47:31Z
[ "python", "google-app-engine", "jinja2" ]
I decided to install jinja2 to use with my webapp application in order to support the autoescape functionality. So I installed jinja2 into python 2.5 and created a symlink within my project to point to that directory. It's mostly working fine. EXCEPT, when I actually try to use the {% autoescape true %} tag, I get the...
The `{% autoescape %}` tag needs Jinja 2.4 or higher and the `jinja2.ext.autoescape` extension loaded. ``` env = Environment(autoescape=True, extensions=['jinja2.ext.autoescape'], loader=...) ```
How to get favicon by using beatiful soup and python
4,674,460
2
2011-01-12T21:54:49Z
4,674,902
9
2011-01-12T22:48:11Z
[ "python", "beautifulsoup", "favicon" ]
Hey guys, I wrote some stupid code for learning just, but it doesn't work for any sites. here is the code: ``` import urllib2, re from BeautifulSoup import BeautifulSoup as Soup class Founder: def Find_all_links(self, url): page_source = urllib2.urlopen(url) a = page_source.read() soup = S...
You're making it far more complicated than it needs to be. Here's a simple way to do it: ``` import urllib page = urllib.urlopen("http://5pd.ru/") soup = BeautifulSoup(page) icon_link = soup.find("link", rel="shortcut icon") icon = urllib.urlopen(icon_link['href']) with open("test.ico", "wb") as f: f.write(icon.re...
ValueError: setting an array element with a sequence
4,674,473
36
2011-01-12T21:58:19Z
4,675,383
61
2011-01-12T23:51:27Z
[ "python", "arrays", "numpy", "slice" ]
This code: ``` import numpy as p def firstfunction(): UnFilteredDuringExSummaryOfMeansArray = [] MeanOutputHeader=['TestID','ConditionName','FilterType','RRMean','HRMean','dZdtMaxVoltageMean','BZMean','ZXMean' ,'LVETMean','Z0Mean','StrokeVolumeMean','CardiacOutputMean','VelocityIndexMean...
From the code you showed us, the only thing we can tell is that you trying to create an array from a list that isn't shaped like a multi-dimensional array. For example ``` numpy.array([[1,2], [2, 3, 4]]) ``` or ``` numpy.array([[1,2], [2, [3, 4]]]) ``` will yield this error message, because the shape of the input l...
What are the first 32 bits of the fractional part of this float?
4,674,956
5
2011-01-12T22:52:47Z
4,675,080
7
2011-01-12T23:07:29Z
[ "python", "hash", "bit-manipulation" ]
I am looking at the following [SHA256 pseudocode](http://en.wikipedia.org/wiki/SHA-2#SHA-256_.28a_SHA-2_variant.29_pseudocode) on wikipedia. Specifically, I am looking at the following section. ``` //Initialize variables //(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): h0 := ...
Endianness does not matter for hexadecimal constants; each digit is a nibble, with the least significant nibble last. It does matter if you deal with differing size pointers. If you do need to use byte orders, the struct module can help. Anyhow, you've retrieved the fractional part just fine; converting it to hex is ea...
Redirect stdout to a file in Python?
4,675,728
144
2011-01-13T00:51:00Z
4,675,741
7
2011-01-13T00:52:51Z
[ "python", "stdout" ]
How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the...
``` import sys sys.stdout = open('stdout.txt', 'w') ```
Redirect stdout to a file in Python?
4,675,728
144
2011-01-13T00:51:00Z
4,675,744
184
2011-01-13T00:53:28Z
[ "python", "stdout" ]
How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the...
If you want to do the redirection within the Python script, set `sys.stdout` to an file object does the trick: ``` import sys sys.stdout = open('file', 'w') print 'test' ``` A far more common method is to use shell redirection when executing (same on Windows and Linux): ``` $ python foo.py > file ```
Redirect stdout to a file in Python?
4,675,728
144
2011-01-13T00:51:00Z
5,916,874
63
2011-05-06T20:49:48Z
[ "python", "stdout" ]
How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the...
you can try this too much better ``` import sys class Logger(object): def __init__(self, filename="Default.log"): self.terminal = sys.stdout self.log = open(filename, "a") def write(self, message): self.terminal.write(message) self.log.write(message) sys.stdout = Logger("your...
Redirect stdout to a file in Python?
4,675,728
144
2011-01-13T00:51:00Z
11,632,982
24
2012-07-24T14:24:53Z
[ "python", "stdout" ]
How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the...
The other answers didn't cover the case where you want forked processes to share your new stdout. To do that: ``` from os import open, close, dup, O_WRONLY old = dup(1) close(1) open("file", O_WRONLY) # should open on 1 ..... do stuff and then restore close(1) dup(old) # should dup to 1 close(old) # get rid of lef...
Redirect stdout to a file in Python?
4,675,728
144
2011-01-13T00:51:00Z
14,707,227
19
2013-02-05T12:09:49Z
[ "python", "stdout" ]
How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the...
Quoted from [PEP 343 -- The "with" Statement](http://www.python.org/dev/peps/pep-0343/) (added import statement): Redirect stdout temporarily: ``` import sys from contextlib import contextmanager @contextmanager def stdout_redirected(new_stdout): save_stdout = sys.stdout sys.stdout = new_stdout try: ...
Redirect stdout to a file in Python?
4,675,728
144
2011-01-13T00:51:00Z
22,434,262
59
2014-03-16T07:39:19Z
[ "python", "stdout" ]
How do I redirect stdout to an arbitrary file in Python? When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the...
There is [`contextlib.redirect_stdout()` function](http://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout) in Python 3.4: ``` from contextlib import redirect_stdout with open('help.txt', 'w') as f: with redirect_stdout(f): print('it now prints to `help.text`') ``` It is similar to:...
keyboard short cut for accessing previous statements in python IDLE using a Mac
4,676,130
6
2011-01-13T02:08:37Z
4,676,215
11
2011-01-13T02:28:06Z
[ "python", "keyboard-shortcuts", "python-idle" ]
Is there a keyboard short cut for accessing previous statements in python IDLE? I am using a Mac Thanks
On Windows this hotkey is alt-p. However, assuming IDLE has options in Mac ;) you should be able to find out by going to Options->Configure IDLE. Then look in the Keys tab and under Custom Key Bindings, look for "history-previous". That should tell you what you need to know.
Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame
4,676,433
79
2011-01-13T03:10:18Z
4,676,478
138
2011-01-13T03:18:50Z
[ "python", "pygame" ]
I recently installed Python 3.1 and the Pygame module for Python 3.1 When I type import python in the console I get the following error: ``` Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> import pygame File "C:\Python31\lib\site-packages\pygame\__init__.py", line 95, in <module> ...
It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version [Python 3.1](http://www.python.org/ftp/python/3.1.3/python-3.1.3.msi) and [Pygame](http://pygame.org/ftp/pygame-1.9.1.win32-py3.1.msi), which is available officia...
Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame
4,676,433
79
2011-01-13T03:10:18Z
11,910,566
7
2012-08-10T23:37:25Z
[ "python", "pygame" ]
I recently installed Python 3.1 and the Pygame module for Python 3.1 When I type import python in the console I get the following error: ``` Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> import pygame File "C:\Python31\lib\site-packages\pygame\__init__.py", line 95, in <module> ...
Looks like the question has been long ago answered but the solution did not work for me. When I was getting that error, I was able to fix the problem by downloading [PyWin32](http://sourceforge.net/projects/pywin32/)
Value error trying to install Python for Windows extensions
4,676,728
24
2011-01-13T04:18:27Z
4,676,840
17
2011-01-13T04:39:34Z
[ "python", "command-line" ]
I have Microsoft Visual Studio 2008 installed already. I downloaded the zip file [Python for Windows extensions](http://sourceforge.net/tracker/index.php?func=detail&aid=3083722&group_id=78018&atid=551954) and extracted the contents into my Python27 folder. There's now a subfolder called pywin32-214. (Is the 32 part a ...
If you have a 64 bit Python installation: Install "Microsoft Visual Studio 2008 Professional Edition" with the "X64 Compiler and Tools" option enabled. Alternatively, download pywin32-214.win-amd64-py2.7.exe from <http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/>
Value error trying to install Python for Windows extensions
4,676,728
24
2011-01-13T04:18:27Z
11,601,340
18
2012-07-22T15:00:21Z
[ "python", "command-line" ]
I have Microsoft Visual Studio 2008 installed already. I downloaded the zip file [Python for Windows extensions](http://sourceforge.net/tracker/index.php?func=detail&aid=3083722&group_id=78018&atid=551954) and extracted the contents into my Python27 folder. There's now a subfolder called pywin32-214. (Is the 32 part a ...
Another possible reason for this problem to appear is that you have just installed Visual Studio and the command prompt you're using had been hanging around from the time **before** the installation. This is because MSVC installer sets few environment variables and one of these variables ( VS90COMNTOOLS )has to be set...
Value error trying to install Python for Windows extensions
4,676,728
24
2011-01-13T04:18:27Z
22,511,789
8
2014-03-19T16:11:04Z
[ "python", "command-line" ]
I have Microsoft Visual Studio 2008 installed already. I downloaded the zip file [Python for Windows extensions](http://sourceforge.net/tracker/index.php?func=detail&aid=3083722&group_id=78018&atid=551954) and extracted the contents into my Python27 folder. There's now a subfolder called pywin32-214. (Is the 32 part a ...
As stated it's trying to use a 32-bit compiler for 64-bit python. I was able to build successfully by: 1. Finding `vcvarsx86_amd64.bat` in `C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\x86_amd64` (depends on your setup) 2. Open a cmd prompt 3. Run `SET VS90COMNTOOLS=%VS120COMNTOOLS%` (depends on setup, s...
Getting shell output with Python?
4,676,749
3
2011-01-13T04:23:03Z
4,676,792
8
2011-01-13T04:29:59Z
[ "python", "linux", "shell" ]
I have a shell script that gets whois info for domains, and outputs `taken` or `available` to the shell depending on the domain. I'd like to execute the script, and be able to read this value inside my Python script. I've been playing around with `subprocess.call` but can't figure out how to get the output. e.g., `...
`subprocess.call()` does not give you the output, only the return code. For the output you should use `subprocess.check_output()` instead. These are friendly wrappers around the popen family of functions, which you could also use directly. For more details, see: <http://docs.python.org/library/subprocess.html>
Python: Can't pickle type X, attribute lookup failed
4,677,012
21
2011-01-13T05:14:04Z
4,677,063
18
2011-01-13T05:23:44Z
[ "python", "pickle" ]
I am trying to pickle a `namedtuple`: ``` from collections import namedtuple import cPickle class Foo: Bar = namedtuple('Bar', ['x', 'y']) def baz(self): s = set() s.add(Foo.Bar(x=2, y=3)) print cPickle.dumps(s) if __name__ == '__main__': f = Foo() f.baz() ``` This produces...
Yes, the fact that it's a class member is a problem: ``` >>> class Foo(): ... Bar = namedtuple('Bar', ['x','y']) ... def baz(self): ... b = Foo.Bar(x=2, y=3) ... print(type(b)) ... >>> a = Foo() >>> a.baz() <class '__main__.Bar'> ``` The problem is that when `namedtuple()` returns a type objec...
Python: Can't pickle type X, attribute lookup failed
4,677,012
21
2011-01-13T05:14:04Z
4,678,982
7
2011-01-13T10:22:50Z
[ "python", "pickle" ]
I am trying to pickle a `namedtuple`: ``` from collections import namedtuple import cPickle class Foo: Bar = namedtuple('Bar', ['x', 'y']) def baz(self): s = set() s.add(Foo.Bar(x=2, y=3)) print cPickle.dumps(s) if __name__ == '__main__': f = Foo() f.baz() ``` This produces...
Nesting classes makes pickle fail, since it relies on the path of the object inside your application to reconstruct it later. The immediate solution is to not nest classes, i.e. move `Bar` definition to outside `Foo`. Code will work all the same. But a better thing to do is to **not use** `pickle` at all to store dat...
In Python, how do I check the size of a StringIO object?
4,677,433
33
2011-01-13T06:31:43Z
4,677,448
14
2011-01-13T06:35:19Z
[ "python" ]
And get the bytes of that StringIO object?
By checking the **len** attribute and using the **getvalue()** method ``` Type "help", "copyright", "credits" or "license" for more information. >>> import StringIO >>> s = StringIO.StringIO() >>> s.write("foobar") >>> s.len 6 >>> s.write(" and spameggs") >>> s.len 19 >>> s.getvalue() 'foobar and spameggs' ```
In Python, how do I check the size of a StringIO object?
4,677,433
33
2011-01-13T06:31:43Z
4,677,542
40
2011-01-13T06:53:59Z
[ "python" ]
And get the bytes of that StringIO object?
`StringIO` objects implement the file API, so you can get their size in exactly the same way as you can with a `file` object: seek to the end and see where it goes. ``` from StringIO import StringIO import os s = StringIO() s.write("abc") s.seek(0, os.SEEK_END) print s.tell() ``` As Kimvais mentions, you can also use...
Can I use cStringIO the same as StringIO?
4,677,512
17
2011-01-13T06:47:33Z
4,677,518
23
2011-01-13T06:48:51Z
[ "python", "c", "stringio" ]
I did this: ``` import cStringIO.StringIO as StringIO ``` And I realize I've been using it everywhere. Is that fine? Is it treated the same as StringIO?
They are not the same. `cStringIO` doesn't correctly handle unicode characters. ``` >>> StringIO.StringIO().write(u'\u0080') >>> cStringIO.StringIO().write(u'\u0080') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0...
Chart of mutable versus immutable types
4,677,529
7
2011-01-13T06:51:00Z
4,677,598
9
2011-01-13T07:04:08Z
[ "python", "types", "immutability", "mutable" ]
Is there a table or a chart somewhere online which shows what types (inbuilt) are mutable and immutable in python?
I am not sure of a chart, but basically: **Mutable:** `list`, `dictionary`, `bytearray` Note: `bytearray` is not a sequence though. **Immutable:** `tuple`, `str` You can check for mutability with: ``` >>> import collections >>> l = range(10) >>> s = "Hello World" >>> isinstance(l, collections.MutableSequence) Tru...
how to dynamically create SQLAlchemy columns
4,678,115
10
2011-01-13T08:39:40Z
4,678,925
11
2011-01-13T10:17:32Z
[ "python", "sqlalchemy", "dynamic-data" ]
I have a csv file with first line as fields and remaining lines as data. With this file I would like to create a table. Since the fields are quite long and may vary, I want to dynamically create it. After several tries and searches, I figured I could maybe generate a Class from factory and then assign the attributes to...
I'm the author of the related answer: [sqlalchemy dynamic mapping](http://stackoverflow.com/questions/2574105/sqlalchemy-dynamic-mapping/2575016#2575016) I have this answer to another question, which I think is even more related - it could even be a duplicate: [Database on the fly with scripting languages](http://st...
In Django, how can I get an exception's message?
4,678,584
10
2011-01-13T09:42:10Z
4,694,505
11
2011-01-14T18:23:03Z
[ "python", "django", "exception-handling" ]
In a view function, I have something like: ``` try: url = request.POST.get('u', '') if len(url) == 0: raise ValidationError('Empty URL') except ValidationError, err: print err ``` The output is a string: `[u'Empty URL']` When I try to pass the error message to my template (stuffed in a dict, some...
`ValidationError` actually holds multiple error messages. The output of `print err` is `[u'Empty URL']` because that is the string returned by `repr(err.messages)` (see `ValidationError.__str__` source code). If you want to print a single readable message out of a `ValidationError`, you can concatenate the list of er...
How to find instance of a bound method in Python?
4,679,592
18
2011-01-13T11:35:22Z
4,679,626
7
2011-01-13T11:39:32Z
[ "python", "class", "methods" ]
``` >>> class A(object): ... def some(self): ... pass ... >>> a=A() >>> a.some <bound method A.some of <__main__.A object at 0x7f0d6fb9c090>> ``` IOW, I need to get access to "a" after being handed over only "a.some".
``` >>> class A(object): ... def some(self): ... pass ... >>> a = A() >>> a <__main__.A object at 0x7fa9b965f410> >>> a.some <bound method A.some of <__main__.A object at 0x7fa9b965f410>> >>> dir(a.some) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattr...
How to find instance of a bound method in Python?
4,679,592
18
2011-01-13T11:35:22Z
4,679,630
23
2011-01-13T11:40:07Z
[ "python", "class", "methods" ]
``` >>> class A(object): ... def some(self): ... pass ... >>> a=A() >>> a.some <bound method A.some of <__main__.A object at 0x7f0d6fb9c090>> ``` IOW, I need to get access to "a" after being handed over only "a.some".
Starting python 2.6 you can use special attribute `__self__`: ``` >>> a.some.__self__ is a True ``` `im_self` is phased out in py3k. For details, see the [`inspect` module in the Python Standard Library.](https://docs.python.org/3/library/inspect.html)
Several many to many table joins with sqlalchemy
4,679,846
6
2011-01-13T12:11:13Z
4,780,595
17
2011-01-24T09:49:17Z
[ "python", "sqlalchemy", "join" ]
New with SQLalchemy, here is my problem: My model is: ``` user_group_association_table = Table('user_group_association', Base.metadata, Column('user_id', Integer, ForeignKey('user.id')), Column('group_id', Integer, ForeignKey('group.id')) ) department_group_association_table = Table('department_group_as...
``` session.query(User).join((Group, User.groups)) \ .join((Department, Group.departments)).filter(Department.name == 'R&D') ``` This also works, but uses a sub-select: ``` session.query(User).join((Group, User.groups)) \ .filter(Group.departments.any(Department.name == 'R&D')) ```
SqlAlchemy and Multiprocessing
4,680,332
6
2011-01-13T12:59:22Z
4,686,890
12
2011-01-14T00:28:17Z
[ "python", "orm", "sqlalchemy", "multiprocessing" ]
I use SqlAlchemy to connect to my database backend and make heavy use of multiprocessing in my Python application. I came to a situation which requires to pass an object reference, which is the result of a database query, from one process to another. This is a problem, because when accessing an attribute of the object...
This is a bad idea (tm). You shouldn't share a stateful object between processes like this (I know it's tempting) because all kinds of bad things can happen since lock primitives are not intended to work across multiple python runtimes. I suggest taking the attributes you need out of that object, jamming them into a ...
Plotting implicit equations in 3d
4,680,525
19
2011-01-13T13:25:10Z
4,687,582
29
2011-01-14T03:00:36Z
[ "python", "numpy", "matplotlib", "plot" ]
I'd like to plot implicit equation F(x,y,z) = 0 in 3D. Is it possible in Matplotlib?
You can trick matplotlib into plotting implicit equations in 3D. Just make a one-level contour plot of the equation for each z value within the desired limits. You can repeat the process along the y and z axes as well for a more solid-looking shape. ``` from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot ...
In lxml, how do I remove a tag but retain all contents?
4,681,317
16
2011-01-13T14:46:55Z
4,681,377
27
2011-01-13T14:53:01Z
[ "python", "xml", "lxml" ]
The problem is this: I have an XML fragment like so: ``` <fragment>text1 <a>inner1 </a>text2 <b>inner2</b> <c>t</c>ext3</fragment> ``` For the result, I want to remove all `<a>`- and `<c>`-Tags, but retain their (text)-contents, and childnodes just as they are. Also, the `<b>`-Element should be left untouched. The re...
Try this: <http://lxml.de/api/lxml.etree-module.html#strip_tags> ``` >>> etree.strip_tags(fragment,'a','c') >>> etree.tostring(fragment) '<fragment>text1 inner1 text2 <b>inner2</b> text3</fragment>' ```
another switch case with functions
4,681,556
3
2011-01-13T15:09:54Z
4,681,607
9
2011-01-13T15:15:53Z
[ "python", "function", "case", "switch-statement" ]
Diving deeper in the interesting python language, so there is no switch in the language as a construct. So using dictionaries is the first place choice by reading learning python first edition. So I tried sth like, ``` cases = { 2 : readt3(e,t,off, partElems, partsNodes), # to read the triangular elements ...
when you are doing something like this: ``` ... 2 : readt3(e,t,off, partElems, partsNodes) ... ``` actually you are evaluating (calling) the function `readt3` with the arguments `e,t,off, partElems, partsNodes` what i think you want to do is something like this (to emulate switch case statement ) : ``` def readt3( ...
OSError's filename attribute unavailable?
4,681,603
4
2011-01-13T15:15:32Z
4,682,215
18
2011-01-13T16:08:17Z
[ "python", "exception-handling", "errno" ]
I have the following code: ``` except(OSError) as (errno, strerror, filename): print "OSError [%d]: %s at %s" % (errno, strerror, filename) ``` It runs great unless it meets OSError num. 123 (`The file name, directory name, or volume label syntax is incorrect`). then I get the following error at the except code line:...
I have not seen this kind of Exception handling where you are passing the Exception object's attributes to the as clause. Normally you handle `except ExceptionObject as e` and handle the attributes as one would normally handle the attributes of an object. OSError contains a errno attribute is a numeric error code fro...
How to calculate the area of a polygon on the earth's surface using python?
4,681,737
15
2011-01-13T15:26:29Z
4,682,656
15
2011-01-13T16:46:29Z
[ "python", "geometry", "geolocation", "geospatial" ]
The title basically says it all. I need to calculate the area inside a polygon on the Earth's surface using Python. [Calculating area enclosed by arbitrary polygon on Earth's surface](http://stackoverflow.com/questions/1340223/calculating-area-enclosed-by-arbitrary-polygon-on-earths-surface) says something about it, bu...
The easiest way to do this (in my opinion), is to project things into (a very simple) equal-area projection and use one of the usual planar techniques for calculating area. First off, I'm going to assume that a spherical earth is close enough for your purposes, if you're asking this question. If not, then you need to ...
How to calculate the area of a polygon on the earth's surface using python?
4,681,737
15
2011-01-13T15:26:29Z
4,683,144
19
2011-01-13T17:31:10Z
[ "python", "geometry", "geolocation", "geospatial" ]
The title basically says it all. I need to calculate the area inside a polygon on the Earth's surface using Python. [Calculating area enclosed by arbitrary polygon on Earth's surface](http://stackoverflow.com/questions/1340223/calculating-area-enclosed-by-arbitrary-polygon-on-earths-surface) says something about it, bu...
Let's say you have a representation of the state of Colorado in GeoJSON format ``` {"type": "Polygon", "coordinates": [[ [-102.05, 41.0], [-102.05, 37.0], [-109.05, 37.0], [-109.05, 41.0] ]]} ``` All coordinates are longitude, latitude. You can use [pyproj](http://pypi.python.org/pypi/pyproj/) to pr...
Call Perl script from Python
4,682,088
7
2011-01-13T15:56:00Z
4,682,150
12
2011-01-13T16:01:49Z
[ "python", "perl" ]
I've got a Perl script that I want to invoke from a Python script. I've been looking all over, and haven't been successful. I'm basically trying to call the Perl script sending 1 variable to it, but don't need the output of the Perl script, as it is a self contained program. What I've come up with so far is: ``` var ...
Just do: ``` var = "/some/file/path/" pipe = subprocess.Popen(["perl", "uireplace.pl", var]) ```
Parfor for Python
4,682,429
28
2011-01-13T16:28:55Z
4,682,600
12
2011-01-13T16:41:25Z
[ "python", "matlab", "parallel-processing" ]
I am looking for a definitive answer to MATLAB's parfor for Python (Scipy, Numpy). Is there a solution similar to parfor? If not, what is the complication for creating one? UPDATE: Here is a typical numerical computation code that I need speeding up ``` import numpy as np N = 2000 output = np.zeros([N,N]) for i in ...
There are many [Python frameworks for parallel computing](http://wiki.python.org/moin/ParallelProcessing). The one I happen to like most is [IPython](http://ipython.scipy.org/), but I don't know too much about any of the others. In IPython, one analogue to parfor would be `client.MultiEngineClient.map()` or some of the...
Parfor for Python
4,682,429
28
2011-01-13T16:28:55Z
4,682,723
20
2011-01-13T16:51:21Z
[ "python", "matlab", "parallel-processing" ]
I am looking for a definitive answer to MATLAB's parfor for Python (Scipy, Numpy). Is there a solution similar to parfor? If not, what is the complication for creating one? UPDATE: Here is a typical numerical computation code that I need speeding up ``` import numpy as np N = 2000 output = np.zeros([N,N]) for i in ...
The one built-in to python would be `multiprocessing` docs are [here](http://docs.python.org/library/multiprocessing.html). I always use `multiprocessing.Pool` with as many workers as processors. Then whenever I need to do a for-loop like structure I use `Pool.imap` As long as the body of your function does not depend...