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
Python : How to avoid numpy RuntimeWarning in function definition?
10,519,237
11
2012-05-09T15:28:34Z
10,519,607
10
2012-05-09T15:52:13Z
[ "python", "numpy" ]
i designed a simple function to return a mathematical function which can be used to fit experimental data to it. The functions looks pretty much like the following: ``` def colecole_2(f,*p): term1=p[0] * ( 1 - 1 / (1 + numpy.power((0+1j) * 2 * numpy.pi * f * p[1], p[2]))) term2=p[3] * ( 1 - 1 / (1 + numpy.powe...
Use `numpy.seterr` to control what numpy does in this circumstance: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html> Use the warnings module to control how warnings are or are not presented: <http://docs.python.org/library/warnings.html>
Python : How to avoid numpy RuntimeWarning in function definition?
10,519,237
11
2012-05-09T15:28:34Z
14,822,364
20
2013-02-11T22:46:58Z
[ "python", "numpy" ]
i designed a simple function to return a mathematical function which can be used to fit experimental data to it. The functions looks pretty much like the following: ``` def colecole_2(f,*p): term1=p[0] * ( 1 - 1 / (1 + numpy.power((0+1j) * 2 * numpy.pi * f * p[1], p[2]))) term2=p[3] * ( 1 - 1 / (1 + numpy.powe...
You can use [numpy.errstate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html#numpy.errstate) which is a built-in context manager. This will let you set the err handing to be within the context of the with statement. ``` import numpy # warning is not logged here. Perfect for clean unit test outp...
python2.7: logging configuration with yaml
10,519,392
13
2012-05-09T15:38:11Z
10,519,480
10
2012-05-09T15:44:46Z
[ "python", "python-2.7" ]
I'm trying to configure a logger from a yaml file. On docs.python.org I found an example of how to create a yaml file, and the file I created looks like this: ``` formatters: simpleFormater: format: '%(asctime)s - %(levelname)s: %(message)s' datefmt: '%Y/%m/%d %H:%M:%S' handlers: console: ...
From reading the [python documentation](http://docs.python.org/dev/library/logging.config.html#dictionary-schema-details), we see that there is a required key in the configuration which says `version`. You need a line in your configuration which says ``` version: 1 ``` Or, you can do: ``` with open('logging.conf') ...
Syntax highlighting in <pre> tags
10,520,714
4
2012-05-09T17:02:03Z
10,520,765
10
2012-05-09T17:05:05Z
[ "python", "html", "css", "syntax-highlighting", "pre" ]
Are there any libraries that will allow me to display code in `<pre>` tags and highlight the syntax according to the language? I'm imagining something like this: ``` <pre class="python"> class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' </pre> ``` ...where the...
There's [SyntaxHighlighter](http://alexgorbatchev.com/SyntaxHighlighter/): ``` <pre class="brush: python"> # python code here </pre> ``` There's also [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) which has the option of automatically detecting the syntax and highlighting it appropriately; however, ...
Recursive function dies with Memory Error
10,521,189
5
2012-05-09T17:34:57Z
10,521,287
7
2012-05-09T17:42:50Z
[ "python", "algorithm", "recursion" ]
Say we have a function that translates the morse symbols: * `.` -> `-.` * `-` -> `...-` If we apply this function twice, we get e.g: `.` -> `-.` -> `...--.` Given an input string and a number of repetitions, want to know the length of the final string. (Problem 1 from the [Flemish Programming Contest](http://www.vl...
Consider that you don't actually have to output the resulting string, only the length of it. Also consider that the order of '.' and '-' in the string do not affect the final length (e.g. ".- 3" and "-. 3" produce the same final length). Thus, I would give up on storing the entire string and instead store the number o...
How to export sqlite to CSV in Python without being formatted as a list?
10,522,830
6
2012-05-09T19:28:51Z
10,522,863
14
2012-05-09T19:31:49Z
[ "python", "sqlite", "csv", "export-to-csv" ]
Here is what I currently have: ``` conn = sqlite3.connect(dbfile) conn.text_factory = str ## my current (failed) attempt to resolve this cur = conn.cursor() data = cur.execute("SELECT * FROM mytable") f = open('output.csv', 'w') print >> f, "Column1, Column2, Column3, Etc." for row in data: print >> f, row f.close(...
What you're currently doing is printing out the python string representation of a tuple, i.e. the return value of `str(row)`. That includes the quotes and 'u's and parentheses and so on. Instead, you want the data formatted properly for a CSV file. Well, try the [`csv` module](http://docs.python.org/library/csv.html)....
python syntax: how to return 0 instead of False when evaluating 0
10,522,880
4
2012-05-09T19:33:12Z
10,522,934
10
2012-05-09T19:36:49Z
[ "python", "syntax", "return", "return-value" ]
For an assignment we were asked to define a fibonacci function, which I accomplished with this: ``` def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) ``` However, I have seen recursive functions, such as the factorial function, defined in a one line return statement like so: ...
The `x and y or z` idiom doesn't work if `y` is [falsy](http://docs.python.org/reference/expressions.html#boolean-operations). You can swap the condition to make it work nonetheless: ``` def fibonacci(n): return n >= 2 and fibonacci(n-1) + fibonacci(n-2) or n ``` However, as of Python 2.5 (released 6 years ago), ...
Python watchdog script doesn't function properly
10,523,303
7
2012-05-09T20:04:06Z
10,531,778
14
2012-05-10T10:07:30Z
[ "python" ]
I am trying to use Python Watchdog to monitor a directory for changes. However, when I try to run the Quickstart example: ``` import time from watchdog.observers import Observer from watchdog.events import LoggingEventHandler if __name__ == "__main__": event_handler = LoggingEventHandler() observer = Observer...
Try the example on github: <https://github.com/gorakhargosh/watchdog> This example seems to work as opposed to the one on the docs site that does not.
Python Dictionary return requested key if value does not exist
10,524,142
4
2012-05-09T21:11:41Z
10,524,173
12
2012-05-09T21:13:58Z
[ "python", "python-2.7" ]
I am looking for an easy way to be able to get a value from a dictionary, and if its not there, return the key that the user passed in. E.g.: ``` >>> lookup = defaultdict(magic) >>> print lookup['DNE'] 'DNE' >>> print lookup.get('DNE') 'DNE' >>> print lookup['exists'] 'some other value' >>> print lookup.get('exists')...
I don't think `defaultdict` will help you here because the function that generates the default value does not have access to which key was requested. However you use an ordinary dictionary and use [`get`](http://docs.python.org/library/stdtypes.html#dict.get) with a default value: ``` >>> lookup = {} >>> key = 'DNE' ...
Python statistics package(s) for bootstrapping confidence intervals and non-parametric multiple dataset comparisons
10,524,269
10
2012-05-09T21:21:29Z
10,544,227
19
2012-05-11T01:22:21Z
[ "python", "statistics", "bootstrapping" ]
I'm looking for a Python package that can compute either/both bootstrapped confidence intervals and perform non-parametric multiple dataset comparisons. Does anyone know of one?
With the help of my lab mates, I found packages for all the statistics I would need. Bootstrapped CIs: <http://scikits.appspot.com/bootstrap> ANOVA: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.f_oneway.html> I hope this is helpful for anyone else who finds themselves in my shoes!
BeautifulSoup get_text does not strip all tags and JavaScript
10,524,387
7
2012-05-09T21:31:49Z
13,386,200
13
2012-11-14T19:48:38Z
[ "python", "html", "xml", "screen-scraping", "beautifulsoup" ]
I am trying to use BeautifulSoup to get text from web pages. Below is a script I've written to do so. It takes two arguments, first is the input HTML or XML file, the second output file. ``` import sys from bs4 import BeautifulSoup def stripTags(s): return BeautifulSoup(s).get_text() def stripTagsFromFile(inFile, o...
nltk's `clean_html()` is quite good at this! Assuming that your already have your html stored in a variable `html` like ``` html = urllib.urlopen(address).read() ``` then just use ``` import nltk clean_text = nltk.clean_html(html) ``` **UPDATE** Support for `clean_html` and `clean_url` will be dropped for future ...
Regex split a string and strip recurring character
10,524,453
4
2012-05-09T21:37:02Z
10,524,481
8
2012-05-09T21:39:15Z
[ "python", "regex" ]
Using python I'm parsing several strings. Sometimes the string has appended several semicolons to it. Example strings: ``` s1="1;Some text" s2="2;Some more text;;;;" ``` The number of appending semicolons varies, but if it's there it's never less than two. The following pattern matches s1, with s2 it includes th...
You can use the `str.rstrip([chars])` This method returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters). e.g. you can do: ``` s2 = s2.rstrip(";") ``` You can find more information [here](http://docs.python.org/library/stdtypes.html#str.rstrip).
Python threading. How do I lock a thread?
10,525,185
22
2012-05-09T22:44:33Z
10,525,433
24
2012-05-09T23:11:36Z
[ "python", "multithreading" ]
I'm trying to understand the basics of threading and concurrency. I want a simple case where two threads repeatedly try to access one shared resource. The code: ``` import threading class Thread(threading.Thread): def __init__(self, t, *args): threading.Thread.__init__(self, target=t, args=args) ...
You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock...
SQLAlchemy: Relation table with composite primary key
10,525,797
7
2012-05-09T23:57:55Z
10,550,839
8
2012-05-11T11:54:53Z
[ "python", "orm", "sqlalchemy", "foreign-key-relationship" ]
I have a set of tables that look like: ``` workflows = Table('workflows', Base.metadata, Column('id', Integer, primary_key=True), ) actions = Table('actions', Base.metadata, Column('name', String, primary_key=True), Column('workflow_id', Integer, Fore...
See below working code. The key points are those I mentioned in the comments: * proper composite `ForeignKey`s * correct `relationship` configuration using the FKs Code: ``` workflows = Table('workflows', Base.metadata, Column('id', Integer, primary_key=True), ) actions = Table('a...
numpy.array boolean to binary?
10,525,921
11
2012-05-10T00:17:21Z
10,526,664
13
2012-05-10T02:12:18Z
[ "python", "numpy" ]
I am trying to rewrite a matlab code in python27. There is a matlab line as follows: ``` vector_C = vector_A > vector_B; ``` If I try to write this in python using numpy it will be the same, but the result will be an array of booleans instead of binaries. I want the result to be in binaries. Is there a way to make it...
Even though `vector_C` may have `dtype=bool`, you can still do operations such as the following: ``` In [1]: vector_A = scipy.randn(4) In [2]: vector_B = scipy.zeros(4) In [3]: vector_A Out[3]: array([ 0.12515902, -0.53244222, -0.67717936, -0.74164708]) In [4]: vector_B Out[4]: array([ 0., 0., 0., 0.]) In [5]: ...
use scikit-learn to classify into multiple categories
10,526,579
29
2012-05-10T01:59:31Z
10,527,953
58
2012-05-10T05:23:46Z
[ "python", "classification", "scikit-learn" ]
Im trying to use on of scikit-learn's supervised learning methods to classify pieces of text into one or more categories. The predict function of all the algorithms i tried just returns one match. For example I have a piece of text "Theaters in New York compared to those in London" And I have trained the algorithm to ...
What you want is called multi-label classification. Scikits-learn can do that. See here: <http://scikit-learn.org/dev/modules/multiclass.html>. I'm not sure what's going wrong in your example, my version of sklearn apparently doesn't have WordNGramAnalyzer. Perhaps it's a question of using more training examples or tr...
use scikit-learn to classify into multiple categories
10,526,579
29
2012-05-10T01:59:31Z
19,172,087
22
2013-10-04T02:10:58Z
[ "python", "classification", "scikit-learn" ]
Im trying to use on of scikit-learn's supervised learning methods to classify pieces of text into one or more categories. The predict function of all the algorithms i tried just returns one match. For example I have a piece of text "Theaters in New York compared to those in London" And I have trained the algorithm to ...
I've been working on this as well, and made a slight enhancement to mwv's excellent answer that may be useful. It takes text labels as the input rather than binary labels and encodes them using LabelBinarizer. ``` import numpy as np from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import Coun...
Configuring gunicorn for Django on Heroku
10,527,512
4
2012-05-10T04:28:55Z
10,661,349
12
2012-05-19T00:32:02Z
[ "python", "django", "heroku", "gunicorn" ]
I'm trying to setup a test Django project on Heroku. Following the advice [here](http://blog.abhiomkar.in/2011/09/17/deploying-django-on-heroku-mac-os-x/) and in the [Heroku Getting Started](https://devcenter.heroku.com/articles/python#declare_process_types_with_foremanprocfile) I'm trying to use `gunicorn` instead of ...
I have just run into this same issue. In the procfile you copied from the Heroku guide, change `hellodjango.wsgi` to `yourproject.wsgi` Looks like we all fall victim to blindly copy-pasting now and then, but in your (and my) defense, it looks like there's no \*.wsgi file that's actually being opened, it's just how you...
Why do these two similar pieces of code produce different results?
10,527,593
7
2012-05-10T04:39:30Z
10,527,611
11
2012-05-10T04:41:15Z
[ "java", "python" ]
I've been experimenting with Python as a begninner for the past few hours. I wrote a recursive function, that returns recurse(x) as x! in Python and in Java, to compare the two. The two pieces of code are identical, but for some reason, the Python one works, whereas the Java one does not. In Python, I wrote: ``` x = i...
Two words - **integer overflow** While not an expert in python, I assume it may expand the size of the integer type according to its needs. In Java, however, the size of an `int` type is fixed - 32bit, and since `int` is signed, we actually have only 31 bits to represent positive numbers. Once the number you assign i...
how to send my game made with pygame to others?
10,527,678
7
2012-05-10T04:49:31Z
10,528,073
10
2012-05-10T05:35:43Z
[ "python", "pygame", "publish", "send" ]
I'm new to making games with pygame and my first attempt is still a work in progress, but I was wondering how to publish or send my game to my friends who don't have pygame so that they can play it. I looked online but haven't found anything useful.
You can package your project into a standalone distributable application that has its own python environment. OSX: py2app <http://pypi.python.org/pypi/py2app/> Linux: pyinstaller <http://www.pyinstaller.org/> Win: py2exe <http://www.py2exe.org/> Note, you can use pyinstaller cross platform. I just have had go...
Python 2.7 / App Engine - TypeError: is_valid() takes exactly 2 arguments (3 given)
10,527,921
2
2012-05-10T05:19:20Z
10,528,147
7
2012-05-10T05:43:02Z
[ "python", "google-app-engine", "python-2.7", "typeerror" ]
The following code is close to what I am using without getting too long. I get the error `TypeError: is_valid() takes exactly 2 arguments (3 given)`. To my eyes I am only passing 2 arguments. So where is the third argument coming from? models/MyModel.py ``` from google.appengine.ext import db class MyModel(db.model)...
change the code to `def is_valid(self, x, y)`
Using a psycopg2 converter to retrieve bytea data from PostgreSQL
10,529,351
6
2012-05-10T07:32:05Z
10,542,514
7
2012-05-10T21:37:22Z
[ "python", "postgresql", "psycopg2" ]
I want to store Numpy arrays in a PostgreSQL database in binary (bytea) form. I can get this to work fine in test #1 (see below), but I don't want to have to be manipulating the data arrays before inserts and after selects every time - I want to use psycopg2's adapters and converters. Here's what I have at the moment:...
The format you see in the debugger is easy to parse: it is PostgreSQL hex binary format (http://www.postgresql.org/docs/9.1/static/datatype-binary.html). psycopg can parse that format and return a buffer containing the data; you can use that buffer to obtain an array. Instead of writing a typecaster from scratch, write...
Can you recommend some python http client library?
10,530,217
12
2012-05-10T08:31:19Z
10,530,255
18
2012-05-10T08:33:56Z
[ "python", "httpclient" ]
I want to use python to capture info from some websites. I want the http client to meet this conditions: 1. supports https 2. will not use too much memory, should not generate a lot of processes or threads. 3. has clear documentation and is actively supported --- I know that `requests`, `tornado`, or the `gevent` -h...
Use [`requests`](http://docs.python-requests.org/en/latest/index.html). It has the most same API of the various libraries.
str performance in python
10,530,315
86
2012-05-10T08:38:01Z
10,530,376
14
2012-05-10T08:41:42Z
[ "python", "string", "performance", "python-3.x", "python-2.7" ]
While profiling a piece of python code (`python 2.6` up to `3.2`), I discovered that the `str` method to convert an object (in my case an integer) to a string is almost an order of magnitude slower than using string formatting. Here is the benchmark ``` >>> from timeit import Timer >>> Timer('str(100000)').timeit() 0...
One reason that comes to mind is the fact that `str(100000)` involves a global lookup, but `"%s"%100000` does not. The `str` global has to be looked up in the global scope. This does not account for the entire difference: ``` >>> Timer('str(100000)').timeit() 0.2941889762878418 >>> Timer('x(100000)', 'x=str').timeit()...
str performance in python
10,530,315
86
2012-05-10T08:38:01Z
10,530,415
104
2012-05-10T08:43:28Z
[ "python", "string", "performance", "python-3.x", "python-2.7" ]
While profiling a piece of python code (`python 2.6` up to `3.2`), I discovered that the `str` method to convert an object (in my case an integer) to a string is almost an order of magnitude slower than using string formatting. Here is the benchmark ``` >>> from timeit import Timer >>> Timer('str(100000)').timeit() 0...
`'%s' % 100000` is evaluated by the compiler and is equivalent to a constant at run-time. ``` >>> import dis >>> dis.dis(lambda: str(100000)) 8 0 LOAD_GLOBAL 0 (str) 3 LOAD_CONST 1 (100000) 6 CALL_FUNCTION 1 9 RETURN_VALUE ...
Django - Storing objects in Session
10,531,787
12
2012-05-10T10:07:51Z
10,532,658
19
2012-05-10T11:03:04Z
[ "python", "django", "django-templates", "pickle" ]
``` class Book(models.Model): author = models.ForeignKey(User) name = models.CharField(max_length=100) def view(request): book = Book.objects.get(pk=1) request.session['selected_book'] = book ``` Is it a good practice to store Objects in Session instead of their id ? Will it be "picklable" enough to be used...
This seems like a bad idea. Apart from anything else, if you store an object in the session, it won't change if/when the database version does.
Why is the same SQLite query being 30 times slower when fetching only twice as many results?
10,531,898
31
2012-05-10T10:15:00Z
10,616,984
7
2012-05-16T10:49:42Z
[ "python", "performance", "sqlite", "fetchall" ]
I have been working on speeding up a query I'm using for about a week now and asked several questions about it here ( [How can I speed up fetching the results after running an sqlite query?](http://stackoverflow.com/questions/10412604/how-can-i-speed-up-fetching-the-results-after-running-an-sqlite-query), [Is it normal...
The execution time geometrically proportional to the number of rows in each table rather than arithmetically e.g. ``` 3 tables with 10 rows each => 1,000 comparision 3 tables with 10, 10 and 40 rows => 4,000 comparisons 3 tables with 20 rows each => 8,000 comparisons ``` You could probably re-factor the query to av...
Dynamically add properties to instances in Python
10,532,321
2
2012-05-10T10:41:29Z
10,532,390
7
2012-05-10T10:45:47Z
[ "python", "dynamic", "properties" ]
I've got essentially an elaborate wrapper around a list of dictionaries: ``` class Wrapper(object): def __init__(self, data): self.data = data def get(self, attr): return [d[attr] for d in self.data] ``` So, ``` Wrapper([{'x': 23}, {'x': 42}, {'x': 5}]).get('x') ``` returns `[23, 42, 5]`. N...
You can actually do this easily by just changing the name of your function: ``` >>> class Wrapper(object): ... def __init__(self, data): ... self.data = data ... def __getattr__(self, attr): ... return [d[attr] for d in self.data] ... >>> Wrapper([{'x': 23}, {'x': 42}, {'x': 5}]).x [23, 42, 5]...
How to change background color of excel cell with python xlwt library?
10,532,367
12
2012-05-10T10:44:27Z
10,542,220
15
2012-05-10T21:12:43Z
[ "python", "xlwt" ]
I use [xlwt](http://www.python-excel.org/) Python library to write data in excel workbook. And now I have some problems with adding background color to excel cell. For example I have next color in RGB(10,20,30), what is the easiest way to do this? Is there any way to set this color to cell? I found only [this](http...
In this example, I have shown how to set background color for cells, you can run it for result: ``` from xlwt import Workbook import xlwt book = Workbook() sheet1 = book.add_sheet('Sheet 1') book.add_sheet('Sheet 2') for i in range(0, 100): st = xlwt.easyxf('pattern: pattern solid;') st.pattern.pattern_fore_co...
python head and tail in one line
10,532,473
39
2012-05-10T10:52:21Z
10,532,492
92
2012-05-10T10:53:20Z
[ "python", "list", "tail", "head" ]
Is there a pythonic way of unpack a list in the first element and the "tail" in a single command? For example: ``` >> head, tail = **some_magic applied to** [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55] ```
Under Python 3.x, you can do this nicely: ``` >>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55] ``` A new feature in 3.x is to use the `*` operator in unpacking, to mean any extra values. It is described in [PEP 3132 - Extended Iterable Unpacking](http://www.pyth...
python head and tail in one line
10,532,473
39
2012-05-10T10:52:21Z
10,532,515
24
2012-05-10T10:54:29Z
[ "python", "list", "tail", "head" ]
Is there a pythonic way of unpack a list in the first element and the "tail" in a single command? For example: ``` >> head, tail = **some_magic applied to** [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55] ```
``` >>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> head, tail = mylist[0], mylist[1:] >>> head 1 >>> tail [1, 2, 3, 5, 8, 13, 21, 34, 55] ```
Can matplotlib add metadata to saved figures?
10,532,614
19
2012-05-10T11:00:27Z
10,552,742
11
2012-05-11T13:53:27Z
[ "python", "matplotlib", "metadata" ]
I want to be able to ascertain the provenance of the figures I create using matplotlib, i.e. to know which version of my code and data created these figures. (See [this essay](http://software-carpentry.org/4_0/essays/provenance/) for more on provenance.) I imagine the most straightforward approach would be to add the ...
I don't know of a way using `matplotlib`, but you can [add metadata to png's with `PIL`](http://blog.client9.com/2007/08/python-pil-and-png-metadata-take-2.html): ``` f = "test.png" METADATA = {"version":"1.0", "OP":"ihuston"} # Create a sample image import pylab as plt import numpy as np X = np.random.random((50,50)...
How to get the url path of a view function in django
10,533,302
2
2012-05-10T11:45:24Z
10,533,354
8
2012-05-10T11:49:43Z
[ "python", "django" ]
for example: view.py ``` def view1( request ): return HttpResponse( "just a test..." ) ``` urls.py ``` urlpatterns = patterns('', url( r'^view1$', 'app1.view.view1'), ) ``` some where I have to get the url path of view1 How can I do it? Of course I don't want to hard code the url path "xxx/view1".
You need [`reverse`](https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse). ``` reverse('app1.view.view1') ``` If you want to find out URL and redirect to it, use [`redirect`](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect) ``` redirect('app1.view.view1') ``` If want to go further ...
UnboundLocalError: local variable 'full_path' referenced before assignment
10,534,566
4
2012-05-10T13:01:07Z
12,510,144
9
2012-09-20T09:53:05Z
[ "python", "windows", "django" ]
Using Window 7 64Bit with Python 2.7 and Django 1.4. ``` Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Django-1.4\django\bin\cms2>manage.py syncdb Creating tables ... Installing custom SQL ... Installing indexes ... Traceback (most recent call last): File "C...
I also had this problem. It was caused by (someone else) having added this to my `settings.py`: ``` SERIALIZATION_MODULES = { 'json': 'wadofstuff.django.serializers.json' } ``` And I didn't have that thing installed. You can install it using: ``` pip install wadofstuff-django-serializers ``` I imagine a similar...
Simple tutorial for Neo4J and using it with django + python
10,534,979
12
2012-05-10T13:25:44Z
15,298,278
8
2013-03-08T16:08:30Z
[ "python", "django", "neo4j" ]
Is there any simple tutorial for learning Neo4J. I went through its official manual and found very confusing for me since i am from mysql background. I just wanted to learn Neo4J but i am really finding a hard time. Also there is not much books available for Neo4J Please help me with this
I just updated [neo4django's documentation](http://neo4django.readthedocs.org/en/latest/), and like to think it reads like a tutorial. I'd appreciate feedback!
Creating a Windows installer for Python + a set of dependencies
10,535,088
14
2012-05-10T13:31:32Z
10,537,802
7
2012-05-10T15:54:19Z
[ "python", "windows", "installer", "bundle", "nsis" ]
I need to create an installer for Windows which should be able to install a specific version of the Python interpreter (2.7) plus a set a dependencies such as ipython, numpy, pandas, etc. Basically this is the same thing Active State did for their Active Python distribution: a single bundle including interpreter + dep...
I suggest to use the packaging tool that I also use to build the Python releases, which is in [Tools/msi/msi.py](http://hg.python.org/cpython/file/2.7/Tools/msi/msi.py). Unpack the additional dependencies on top of the Python source (or an installation), then adjust msi.py to pick up all additional files that you want ...
Most pythonic way of ensuring a list of objects contains only unique items
10,535,492
2
2012-05-10T13:54:08Z
10,535,772
8
2012-05-10T14:08:27Z
[ "python" ]
I have a list of objects (Foo). A Foo object has several attributes. An instance of a Foo object is equivalent (equal) to another instance of a Foo object iff (if and only if) all the attributes are equal. I have the following code: ``` class Foo(object): def __init__(self, myid): self.myid=myid def ...
First, I want to emphasize that using `set` is certainly not an anti-pattern. `set`s eliminate duplicates in O(n) time, which is the best you can do, and way better than the naive O(n^2) solution of comparing every item to every other item. It's even better than sorting -- and indeed, it seems your data structure *migh...
Cannot assign must be a instance. Django
10,535,604
7
2012-05-10T13:59:27Z
10,536,387
7
2012-05-10T14:39:16Z
[ "python", "django", "forms", "models" ]
Ive been trying to create a django project that has users and those users can add titles of books they have created. But each time I enter a book title (not on the admin page) I get this error ``` Cannot assign "u'Hello Wold'": "Scripter.title" must be a "Book" instance. ``` models.py ``` from django.db import model...
Of course. Not sure where the confusion here is. `Scripter.title` is a foreign key to `Book`, so you must give it an actual `Book`, not a string.
Write a raw binary file with NumPy array data
10,535,687
5
2012-05-10T14:04:18Z
10,536,046
14
2012-05-10T14:21:16Z
[ "python", "numpy", "binary" ]
I'd like to save the contents of a numpy float array into a raw binary file as signed 16 bit integers. I tried to accomplish this using [ndarray.tofile](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html) but I can't figure out the right format string. It seems that the file is saved in doubl...
I think the easiest way to do this is to first convert the array to int16, ``` array.astype('int16').tofile(filename) ```
Write a raw binary file with NumPy array data
10,535,687
5
2012-05-10T14:04:18Z
10,539,119
7
2012-05-10T17:18:45Z
[ "python", "numpy", "binary" ]
I'd like to save the contents of a numpy float array into a raw binary file as signed 16 bit integers. I tried to accomplish this using [ndarray.tofile](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html) but I can't figure out the right format string. It seems that the file is saved in doubl...
Take a look at the struct module, try this example: ``` import struct import numpy f=open("myfile","wb") mydata=numpy.random.random(10) print(mydata) myfmt='f'*len(mydata) # You can use 'd' for double and < or > to force endinness bin=struct.pack(myfmt,*mydata) print(bin) f.write(bin) f.close() ```
Python GAE: incoming mail handler error
10,537,659
2
2012-05-10T15:46:42Z
10,538,117
7
2012-05-10T16:11:24Z
[ "python", "google-app-engine", "email", "handler" ]
I'm writing application on GAE that can parse and store incoming mails. I've prepared some simple code for email parsing, but something goes wrong, when I try to simulate e-mail recieveing from admin dev console on local dev server: ``` /develop/google_appengine/google/appengine/runtime/wsgi.py", line 193, in Handle ...
i think what happens is that in your app.yaml you define the module/file as the script instead of an application, the module is not callable of course. change the `app.yaml` definition to: ``` handlers: - url: /_ah/mail/.+ script: email_handler.application login: admin ``` and add this line at the end of `email...
Can a virtualenv inherit from another?
10,538,675
9
2012-05-10T16:45:56Z
10,539,298
10
2012-05-10T17:30:37Z
[ "python", "virtualenv" ]
I want to create one `virtualenv` using another as the starting point, is this possible? I have to use cases in mind: 1. Let's say I have a two `virtualenv` one for production and one for development. The development environment requires the same packages as the production environment, but it requires others I don't ...
One solution is to use `virtualenvwrapper`'s [`add2virtualenv`](http://www.doughellmann.com/docs/virtualenvwrapper/command_ref.html#add2virtualenv) command. This > Adds the specified directories to the Python path for the > currently-active virtualenv. So if I have two `virtualenv`, `ENV1` and `ENV2`, and I want `ENV...
Python can't handle importing via command-line
10,540,605
5
2012-05-10T19:06:21Z
10,540,735
10
2012-05-10T19:16:19Z
[ "python", "windows", "import" ]
My python scripts run fine from IDLE, but when I try to run them from the command-line, things go wrong. First I had trouble importing pygame, but I added C:\Python27\Lib\site-packages to the PYTHONPATH environment variable and all was well, I thought. However, now when I attempt to run something from the command line,...
This sounds to me like you've got two different versions of Python on your computer. One is a more recent version that accepts Python's version of the ternary expression, and one is an older version. When you use IDLE, the newer version is called. When you use the command line, the older version is called. You can conf...
figure of imshow() is too small
10,540,929
15
2012-05-10T19:31:35Z
10,546,220
36
2012-05-11T06:05:24Z
[ "python", "numpy", "matplotlib" ]
I'm trying to visualize a numpy array using imshow() since it's similar to imagesc() in Matlab. ``` imshow(random.rand(8, 90), interpolation='nearest') ``` The resulting figure is very small at the center of the grey window, while most of the space is unoccupied. How can I set the parameters to make the figure larger...
If you don't give an `aspect` argument to `imshow`, it will use the value for `image.aspect` in your `matplotlibrc`. The default for this value in a new `matplotlibrc` is `equal`. So `imshow` will plot your array with equal aspect ratio. If you don't need an equal aspect you can set `aspect` to `auto` ``` imshow(rand...
Convert date format python
10,541,640
4
2012-05-10T20:29:31Z
10,541,716
8
2012-05-10T20:34:05Z
[ "python", "django", "python-datetime" ]
I have django form and I am receiving from POST a date formated like "%d/%m/%Y" and I would like to convert it to "%Y-%m-%d", How could I do it?
Use [strptime and strftime](http://docs.python.org/library/datetime.html#strftime-strptime-behavior): ``` In [1]: import datetime In [2]: datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d') Out[2]: '2012-05-10' ``` Likewise, in Django template syntax you can use the [date filter](https://docs.d...
Can I set the umask for tempfile.NamedTemporaryFile in python?
10,541,760
5
2012-05-10T20:36:49Z
10,541,972
18
2012-05-10T20:53:44Z
[ "python", "file", "permissions" ]
In Python (tried this in 2.7 and below) it looks like a file created using `tempfile.NamedTemporaryFile` doesn't seem to obey the umask directive: ``` import os, tempfile os.umask(022) f1 = open ("goodfile", "w") f2 = tempfile.NamedTemporaryFile(dir='.') f2.name Out[33]: '/Users/foo/tmp4zK9Fe' ls -l -rw------- 1 fo...
This is a security feature. The `NamedTemporaryFile` is always created with mode `0600`, hardcoded at [`tempfile.py`, line 235](http://hg.python.org/cpython/file/63bde882e311/Lib/tempfile.py#l235), because it is private to your process until you open it up with `chmod`. There is no constructor argument to change this b...
Easy way to test if each element in an numpy array lies between two values?
10,542,240
15
2012-05-10T21:13:50Z
10,542,347
21
2012-05-10T21:23:11Z
[ "python", "numpy" ]
I was wondering if there was a syntactically simple way of checking if each element in a numpy array lies between two numbers. In other words, just as `numpy.array([1,2,3,4,5]) < 5` will return `array([True, True, True, True, False])`, I was wondering if it was possible to do something akin to this: `1 < numpy.array(...
one solution would be: ``` a = numpy.array([1,2,3,4,5]) (a > 1).all() and (a < 5).all() ``` if you want the acutal array of truth vaues, just use: ``` (a > 1) & (a < 5) ```
Using Flask Blueprints, how to fix url_for from breaking if a subdomain is specified?
10,542,493
6
2012-05-10T21:35:33Z
11,694,171
10
2012-07-27T19:08:12Z
[ "python", "routes", "flask" ]
Inside of a flask blueprint, i have: ``` frontend = Blueprint('frontend', __name__) ``` and the route to my index function is: ``` @frontend.route('/') def index(): #code ``` This works fine but, I am trying to add a subdomain to the route, like so: ``` @frontend.route('/', subdomain='<var>') def index(var): ```...
First, to use subdomains you need to have a value for the SERVER\_NAME [configuration](http://flask.pocoo.org/docs/config/): ``` app.config['SERVER_NAME'] = 'example.net' ``` You have a view like this: ``` frontend = Blueprint('frontend', __name__) @frontend.route('/', subdomain='<var>') def index(var): return ....
Using Flask Blueprints, how to fix url_for from breaking if a subdomain is specified?
10,542,493
6
2012-05-10T21:35:33Z
16,585,583
8
2013-05-16T10:55:49Z
[ "python", "routes", "flask" ]
Inside of a flask blueprint, i have: ``` frontend = Blueprint('frontend', __name__) ``` and the route to my index function is: ``` @frontend.route('/') def index(): #code ``` This works fine but, I am trying to add a subdomain to the route, like so: ``` @frontend.route('/', subdomain='<var>') def index(var): ```...
Add blueprint name in `url_for`. Example: ``` url_for('pay_sermepa.sermepa_cancel', _external=True) ``` * `pay_sermepa`: blueprint name * `sermepa_cancel`: route
Bash or vim alias/command to use a certain template when creating Python files?
10,542,694
9
2012-05-10T21:53:26Z
10,542,757
9
2012-05-10T21:59:02Z
[ "python", "bash", "vim" ]
I was wondering if it is possible to insert something in `.bashrc` or `.vimrc` so that whenever I create a new Python file via `vim` it automatically creates a file with this already inserted before I edit it: ``` #!/usr/bin/env python import sys if __name__ == '__main__': ``` A vast majority of my Python scripts u...
Or if you want to avoid plugins: ``` autocmd bufnewfile *.py 0r /path/to/python_default.py ```
number of values in a list greater than a certain number
10,543,303
19
2012-05-10T23:01:31Z
10,543,316
53
2012-05-10T23:03:22Z
[ "python", "list" ]
I have a list of numbers and I want to get the number of times a number appears in a list that meets a certain criteria. I can use a list comprehension (or a list comprehension in a function) but I am wondering if someone has a shorter way. ``` # list of numbers j=[4,5,6,7,1,3,7,5] #list comprehension of values of j >...
You could do something like this: ``` >>> j = [4, 5, 6, 7, 1, 3, 7, 5] >>> sum(i > 5 for i in j) 3 ``` It might initially seem strange to add `True` to `True` this way, but I don't think it's unpythonic; after all, `bool` [is a subclass](http://stackoverflow.com/a/3175293/577088) of `int` in all versions since 2.3: ...
String splitting in Python using regex
10,543,480
6
2012-05-10T23:25:05Z
10,543,542
7
2012-05-10T23:34:30Z
[ "python", "regex" ]
I'm trying to split a string in Python so that I get everything before a certain regex. example string: `"Some.File.Num10.example.txt"` I need everything before this part: `"Num10"`, regex: `r'Num\d\d'` (the number will vary and possibly what comes after). Any ideas on how to do this?
``` >>> import re >>> text = "Some.File.Num10.example.txt" >>> re.split(r'Num\d{2}',text)[0] 'Some.File.' ```
String splitting in Python using regex
10,543,480
6
2012-05-10T23:25:05Z
10,543,589
8
2012-05-10T23:40:34Z
[ "python", "regex" ]
I'm trying to split a string in Python so that I get everything before a certain regex. example string: `"Some.File.Num10.example.txt"` I need everything before this part: `"Num10"`, regex: `r'Num\d\d'` (the number will vary and possibly what comes after). Any ideas on how to do this?
``` >>> import re >>> s = "Some.File.Num10.example.txt" >>> p = re.compile("Num\d{2}") >>> match = p.search(s) >>> s[:match.start()] 'Some.File.' ``` This would be more efficient that doing a split because search doesn't have to scan the whole string. It breaks on the first match. In your example it wouldn't make a di...
Why can't `virtualenv` find `pkg_resources`?
10,544,067
7
2012-05-11T00:57:46Z
18,193,870
8
2013-08-12T18:17:09Z
[ "python", "virtualenv", "pkg-resources", "python-wheel" ]
I'm trying to use virtualenv in Ubuntu to install a local virtual Python environment. When I run the shell command: ``` $ virtualenv ./virt_python ``` It throws an exception that it can't import `pkg_resources`. But when I open a Python shell and `from pkg_resources import load_entry_point` it runs fine. For referenc...
I had the same problem when trying to run virtualenv, found out the virtualenv was installed in /home/{user}/install/lib/python2.7/site-packages while the python was pointing to /home/{user}/install/bin/virtualenv - you should know this by running ``` which virtualenv ``` So I had to uninstall and reinstall virtualen...
Python: Using continue in a try-finally statement in a loop
10,544,928
7
2012-05-11T03:11:15Z
10,544,962
10
2012-05-11T03:15:36Z
[ "python", "continue", "try-finally" ]
Will the following code: ``` while True: try: print("waiting for 10 seconds...") continue print("never show this") finally: time.sleep(10) ``` Always print the message "waiting for 10 seconds...", sleep for 10 seconds, and do it again? In other words, do statements in `finally`...
From the [python docs](http://docs.python.org/reference/compound_stmts.html#finally): When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out.’ A continue statement is illegal in the finally clause. (The reason is a p...
Python: Use local variable in function, return variable from function
10,545,041
4
2012-05-11T03:29:12Z
10,545,156
13
2012-05-11T03:44:52Z
[ "python", "function", "variables", "return" ]
I am trying to create a script that sets a local variable, references it from a function, and can return the manipulated value back to the main scope (or whatever it's called; I'm new to Python) I have simplified my code to show the utmost basics of what I am trying to accomplish, which is to import a local from the m...
Functions shouldn't have to know what scope they're called from; the point of a function is to make a re-usable block of code that can be invoked multiple times from different places. You communicate information *to* a function by passing it through its input variables. The function communicates information back to it...
Mocking Django Model and save()
10,545,049
4
2012-05-11T03:30:11Z
10,585,114
7
2012-05-14T14:16:19Z
[ "python", "django", "unit-testing", "django-models", "mocking" ]
I have the following scenario: in my models.py ``` class FooBar(models.Model): description = models.CharField(max_length=20) ``` in my utils.py file. ``` from models import FooBar def save_foobar(value): '''acts like a helper method that does a bunch of stuff, but creates a FooBar object and saves it'...
Here is your problem, you currently have: ``` mock_foobar_class.save = save_mock ``` since `mock_foobar_class` is a mocked class object, and the `save` method is called on an instance of that class (not the class itself), you need to assert that save is called on the return value of the class (aka the instance). Try...
How to check if a variable is empty in python?
10,545,385
10
2012-05-11T04:18:15Z
10,545,399
14
2012-05-11T04:20:34Z
[ "python" ]
I am wondering if python has any function such as php empty function (http://php.net/manual/en/function.empty.php) which check if the variable is empty with following criteria ``` "" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) ```
Yes, [`bool`](http://docs.python.org/library/functions.html#bool). It's not exactly the same -- `'0'` is `True`, but `None`, `False`, `[]`, `0`, `0.0`, and `""` are all `False`. `bool` is used implicitly when you evaluate an object in a condition like an `if` or `while` statement, conditional expression, or with a boo...
How to check if a variable is empty in python?
10,545,385
10
2012-05-11T04:18:15Z
10,545,413
12
2012-05-11T04:23:07Z
[ "python" ]
I am wondering if python has any function such as php empty function (http://php.net/manual/en/function.empty.php) which check if the variable is empty with following criteria ``` "" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) ```
See also this previous answer which recommends the `not` keyword [How to check if a list is empty in Python?](http://stackoverflow.com/questions/1725517/how-to-check-if-a-list-is-empty-in-python) It generalizes to more than just lists: ``` >>> a = "" >>> not a True >>> a = [] >>> not a True >>> a = 0 >>> not a Tru...
creating pandas data frame from multiple files
10,545,957
9
2012-05-11T05:36:56Z
14,490,980
17
2013-01-23T22:58:43Z
[ "python", "pandas" ]
I am trying to create a pandas `DataFrame` and it works fine for a single file. If I need to build it for multiple files which have the same data structure. So instead of single file name I have a list of file names from which I would like to create the `DataFrame`. Not sure what's the way to append to current data fr...
The pandas `concat` command is your friend here. Lets say you have all you files in a directory, targetdir. You can: 1. make a list of the files 2. load them as pandas dataframes 3. and concatenate them together ` ``` import os import pandas as pd #list the files filelist = os.listdir(targetdir) #read them into pa...
python regular expression with utf8 issue
10,546,442
4
2012-05-11T06:25:06Z
10,546,691
14
2012-05-11T06:45:59Z
[ "python", "regex", "utf-8", "python-2.7" ]
I got a file which includes many lines of plain utf-8 text. Such as below, by the by, it's Chinese. ``` PROCESS:类型:关爱积分[NOTIFY] 交易号:2012022900000109 订单号:W12022910079166 交易金额:0.01元 交易状态:true 2012-2-29 10:13:08 ``` The file itself was saved in utf-8 format...
There are several issues with your code. First you should use `re.compile(ur'<unicode string>')`. Also it is nice to add re.UNICODE flag (not sure if really needed here though). Next one is that still you will not receive a match since `\d+` doesn't handle decimals just a series of numbers, you should use `\d+\.?\d+` i...
Install m2crypto on a virtualenv without system packages
10,547,332
14
2012-05-11T07:35:51Z
10,547,858
12
2012-05-11T08:18:51Z
[ "python", "ubuntu", "virtualenv", "m2crypto" ]
I have created a virtual environment without the system packages with python's virtualenv in Ubuntu and installed m2crypto, but when I execute a shell and I try to import M2Crypto i get the following error: ``` ImportError: /home/imediava/.virtualenvs/myenv/local/lib/python2.7/site- packages/M2Crypto/__m2cry...
You can install this lib in your global environment and then just copy from your global site-packages to virtualenv.
Install m2crypto on a virtualenv without system packages
10,547,332
14
2012-05-11T07:35:51Z
11,072,709
30
2012-06-17T15:55:16Z
[ "python", "ubuntu", "virtualenv", "m2crypto" ]
I have created a virtual environment without the system packages with python's virtualenv in Ubuntu and installed m2crypto, but when I execute a shell and I try to import M2Crypto i get the following error: ``` ImportError: /home/imediava/.virtualenvs/myenv/local/lib/python2.7/site- packages/M2Crypto/__m2cry...
There seems to be a regression bug from an earlier version of M2Crypto. After placing [M2Crypto's source](http://chandlerproject.org/Projects/MeTooCrypto#Downloads) in your virtualenv, you can try to [patch](http://linux.die.net/man/1/patch) it with the [diff](http://en.wikipedia.org/wiki/Diff) code below. You do thi...
add object into python's set collection and determine by object's attribute
10,547,343
2
2012-05-11T07:36:51Z
10,547,584
13
2012-05-11T07:57:28Z
[ "python", "set" ]
Here is my code: ``` #!/usr/bin/python class Person(): def __init__(self, name, age): self.name = name self.age = age def get_detail(self): print "I am %s , my age is %d" % (self.name, self.age) if __name__ == '__main__': tom = Person('tom', 18) jack = Person('jack', 20) ...
When a new object is being added to a python set, the hash code of the object is first computed and then, if one or more objects with the same hash code is/are already in the set, these objects are tested for equality with the new object. The upshot of this is that you need to implement the [`__hash__(...)`](http://do...
Rename python tempfile
10,547,859
3
2012-05-11T08:18:54Z
10,547,888
7
2012-05-11T08:21:37Z
[ "python" ]
What is the way to rename the following tempfile ``` pdf = render_me_some_pdf() #PDF RENDER f = tempfile.NamedTemporaryFile() f.write(pdf) f.flush() ``` I read somethings about os.rename but I don't really now how to apply it
You can access the filename via `f.name`. However, unless you use `delete=False` python will (try to) delete the temporary file automatically as soon as it is closed. Disabling auto deletion will keep the tempfile even if you do not save it - so that's not such a good idea. The best way is *copying* the file and letti...
authentication with http header in pyramid
10,548,236
2
2012-05-11T08:47:22Z
10,562,291
8
2012-05-12T08:54:10Z
[ "python", "http", "authentication", "pyramid" ]
I've been looking for a way to authenticate user by user and password passed in http header. ``` curl --user user1:pass1 http://localhost:6543/the_resource ``` The idea is to check if passed credentials allow user to view \*the\_resource\* and if not return 401 - Forbidden. I've found only examples of authentication...
In the end it became clear how to use authentication and authorization. Everything was actually written I just didn't catch the concept at once. I'll try to write how I got it working explaining in a noobish way, which I had to explain it to myself. I hope it will be useful to someone. Sources in the end may help to un...
Encrypting and Decrypting with python and nodejs
10,548,973
7
2012-05-11T09:39:59Z
10,550,004
15
2012-05-11T10:54:30Z
[ "python", "node.js", "encryption", "aes" ]
I'm trying to encrypt some content in Python and decrypt it in a nodejs application. I'm struggling to get the two AES implementations to work together though. Here is where I am at. In node: ``` var crypto = require('crypto'); var password = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; var input = 'hello world'; var encry...
OK, I've figured it out, node uses OpenSSL which uses [PKCS5](http://www.chilkatsoft.com/faq/PKCS5_Padding.html) to do padding. PyCrypto doesn't handle the padding so I was doing it myself just add ' ' in both. If I add PKCS5 padding in the python code and remove the padding in the node code, it works. So updated wor...
python dropbox api - save token file?
10,549,326
8
2012-05-11T10:04:08Z
10,549,706
20
2012-05-11T10:31:21Z
[ "python", "api", "authentication", "dropbox" ]
I want to avoid having to authorise this script over and over. In other words, when I launch the script from the terminal, it gives me a link I have to open in a browser then click on the 'Allow' button in the browser then go back to the terminal...I guess there's a way to save the authentication details but how? ``` ...
You can write the access\_token to a file: ``` TOKENS = 'dropbox_token.txt' token_file = open(TOKENS,'w') token_file.write("%s|%s" % (access_token.key,access_token.secret) ) token_file.close() ``` If you do that once, then afterwords you can use that token: ``` token_file = open(TOKENS) token_key,token_secret = toke...
Why can't Python execute java.exe via subprocess?
10,549,872
6
2012-05-11T10:44:38Z
10,557,891
8
2012-05-11T20:03:47Z
[ "java", "python", "windows", "subprocess" ]
After upgrading Java from 1.6 to 1.7 x64 (on Windows 7), I suddenly can't launch java.exe via Python 2.7's `subprocess` module anymore. The following script used to just work: ``` import subprocess subprocess.check_call([r"C:\Windows\system32\java.exe"]) ``` Now it fails like this: ``` Traceback (most recent call la...
Assuming that there is a java.exe at "C:\Windows\System32" is not a particularly safe assumption. Even the assumption there is a "C:\Windows\System32" on the system isn't safe: Windows could reside on *any* fixed drive on the computer. But even if there is a "C:\Windows\System32\java.exe", this might not be visible fo...
How do I set color to Rectangle in Matplotlib?
10,550,477
11
2012-05-11T11:28:07Z
10,551,413
14
2012-05-11T12:33:55Z
[ "python", "matplotlib" ]
How do I set color to Rectangle for example in matplotlib? I tried using argument color, but had no success. I have following code: ``` fig=pylab.figure() ax=fig.add_subplot(111) pylab.xlim([-400, 400]) pylab.ylim([-400, 400]) patches = [] polygon = Rectangle((-400, -400), 10, 10, color='y') patches.append(polyg...
I couldn't get your code to work, but hopefully this will help: ``` import matplotlib import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) rect1 = matplotlib.patches.Rectangle((-200,-100), 400, 200, color='yellow') rect2 = matplotlib.patches.Rectangle((0,150), 300, 20, color='red') rect3 = mat...
Setting options from environment variables when using argparse
10,551,117
11
2012-05-11T12:13:17Z
10,551,190
15
2012-05-11T12:17:53Z
[ "python", "argparse" ]
I have a script which has certain options that can either be passed on the command line, or from environment variables. The CLI should take precedence if both are present, and an error occur if neither are set. I could check that the option is assigned after parsing, but I prefer to let argparse to do the heavy liftin...
I use this pattern frequently enough that I have packaged a simple action class to handle it: ``` import argparse import os class EnvDefault(argparse.Action): def __init__(self, envvar, required=True, default=None, **kwargs): if not default and envvar: if envvar in os.environ: ...
Setting options from environment variables when using argparse
10,551,117
11
2012-05-11T12:13:17Z
10,551,389
14
2012-05-11T12:32:50Z
[ "python", "argparse" ]
I have a script which has certain options that can either be passed on the command line, or from environment variables. The CLI should take precedence if both are present, and an error occur if neither are set. I could check that the option is assigned after parsing, but I prefer to let argparse to do the heavy liftin...
I would just set the `default` variable when adding an argument to a get of os.environ with the Variable you want to grab. The 2nd Argument in the `.get()` call is the default value if `.get()` doesn't find an environment variable by that name. ``` import argparse import os parser = argparse.ArgumentParser(descriptio...
Python email module: form header "From" with some unicode name + email
10,551,933
8
2012-05-11T13:05:08Z
10,553,563
23
2012-05-11T14:41:46Z
[ "python", "email" ]
I'm generating email with the help of Python email module. Here are few lines of code, which demonstrates my question: ``` msg = email.MIMEMultipart.MIMEMultipart('alternative') msg['From'] = "somemail@somedomain.com" msg.as_string() Out[7]: 'Content-Type: multipart/alternative;\n boundary="===============9006870...
You need to encode the name part separately using `email.header.Header`: ``` from email.MIMEMultipart import MIMEMultipart from email.header import Header from email.utils import formataddr author = formataddr((str(Header(u'Alał', 'utf-8')), "somemail@somedomain.com")) msg = MIMEMultipart('alternative') msg['From'] ...
Python max() and min() values for bool
10,552,147
2
2012-05-11T13:18:33Z
10,552,172
9
2012-05-11T13:19:30Z
[ "python" ]
In python interpreter, ``` min(True,False)==False max(True,False)==True ``` is assured by design?
`True` is equal to `1` and `False` is `0`
Python split url to find image name and extension
10,552,188
7
2012-05-11T13:20:43Z
10,552,291
9
2012-05-11T13:27:37Z
[ "python", "django", "file-io" ]
I am looking for a way to extract a filename and extension from a particular url using Python lets say a URL looks as follows ``` picture_page = "http://distilleryimage2.instagram.com/da4ca3509a7b11e19e4a12313813ffc0_7.jpg" ``` How would I go about getting the following. ``` filename = "da4ca3509a7b11e19e4a12313813...
``` filename = picture_page.split('/')[-1].split('.')[0] file_ext = '.'+picture_page.split('.')[-1] ```
Python split url to find image name and extension
10,552,188
7
2012-05-11T13:20:43Z
10,552,304
10
2012-05-11T13:28:20Z
[ "python", "django", "file-io" ]
I am looking for a way to extract a filename and extension from a particular url using Python lets say a URL looks as follows ``` picture_page = "http://distilleryimage2.instagram.com/da4ca3509a7b11e19e4a12313813ffc0_7.jpg" ``` How would I go about getting the following. ``` filename = "da4ca3509a7b11e19e4a12313813...
Try with [urlparse.urlsplit](http://docs.python.org/library/urlparse.html?highlight=split%20url#urlparse.urlsplit) to split url, and then [os.path.splitext](http://docs.python.org/library/os.path.html#os.path.splitext) to retrieve filename and extension (use [os.path.basename](http://docs.python.org/library/os.path.htm...
Python split url to find image name and extension
10,552,188
7
2012-05-11T13:20:43Z
10,552,315
23
2012-05-11T13:29:10Z
[ "python", "django", "file-io" ]
I am looking for a way to extract a filename and extension from a particular url using Python lets say a URL looks as follows ``` picture_page = "http://distilleryimage2.instagram.com/da4ca3509a7b11e19e4a12313813ffc0_7.jpg" ``` How would I go about getting the following. ``` filename = "da4ca3509a7b11e19e4a12313813...
``` from urlparse import urlparse from os.path import splitext, basename picture_page = "http://distilleryimage2.instagram.com/da4ca3509a7b11e19e4a12313813ffc0_7.jpg" disassembled = urlparse(picture_page) filename, file_ext = splitext(basename(disassembled.path)) ``` Only downside with this is that your filename will...
How to apply function to elements of a list?
10,554,470
6
2012-05-11T15:36:16Z
10,554,620
7
2012-05-11T15:45:29Z
[ "python", "list", "map", "python-2.7" ]
I want to apply a function to all elements in the list, but I want to actually change the elements (which are objects), not view results. I think this is the problem with using `map()` or list comprehensions. ``` class Thing(object): pass # some collection of things my_things # they are all big... # produces Sy...
And what's wrong with ``` for i in my_things: i.size = "big" ``` You don't want to use neither `map` nor list comprehansion because they actually create new lists. And you don't need that overhead, do you?
How do I rethrow an exception that contains information about an original exception?
10,555,671
7
2012-05-11T17:04:11Z
10,555,838
8
2012-05-11T17:17:16Z
[ "python", "exception-handling", "wlst", "python-2.2" ]
So I basically have to isolate 2 layers of the application from one another by exceptions. I have this WLST 12c script (python 2.2), that goes like ``` try: something something... except java.lang.UnsuportedOpperationException, (a, b): pass except java.lang.reflect.UndeclaredThrowableException, (a, b): pa...
I hope I got the question right. I'm not sure about Python 2.2 specifics, but [this](http://rgruet.free.fr/PQR2.2.html#Statements) says you can handle exceptions the same way it's done in more recent versions: ``` try: do_stuff() except ErrorToCatch, e: raise ExceptionToThrow(e) ``` Or maybe the last line sh...
How do I rethrow an exception that contains information about an original exception?
10,555,671
7
2012-05-11T17:04:11Z
24,024,880
12
2014-06-03T21:03:27Z
[ "python", "exception-handling", "wlst", "python-2.2" ]
So I basically have to isolate 2 layers of the application from one another by exceptions. I have this WLST 12c script (python 2.2), that goes like ``` try: something something... except java.lang.UnsuportedOpperationException, (a, b): pass except java.lang.reflect.UndeclaredThrowableException, (a, b): pa...
Although this is an old post, there is a much more simple answer to the original question. To rethrow an exception after catching it, just use "raise" with no arguments. The original stack trace will be preserved.
Dynamically creating a class from file in Python
10,555,844
5
2012-05-11T17:17:42Z
10,555,930
10
2012-05-11T17:25:02Z
[ "python" ]
I've seen these "Dynamically create a class" questions which are answered saying, "use the type() function". I'm sure I'll have to at some point but right know I'm clueless. But from what I've seen you have to already know something about the class, such as a name. What I'm trying to do is parse an idl type of file an...
<http://docs.python.org/library/functions.html#type> It's a bit hard to Google for, but you can search for `python type(name, bases, dict) function examples` to get: <http://www.voidspace.org.uk/python/articles/metaclasses.shtml> An excerpt from the above, which gets to the heart of your question: --- *The followi...
Running a Tkinter form in a separate thread
10,556,479
3
2012-05-11T18:10:03Z
10,556,698
7
2012-05-11T18:28:01Z
[ "python", "multithreading", "tkinter" ]
I have written a short module that can be passed an image and simply creates a Tkinter window and displays it. The problem that I am having is that even when I instantiate and call the method that displays the image in a separate thread, the main program will not continue until the Tkinter window is closed. Here is my...
Tkinter isn't thread safe, and the general consensus is that Tkinter doesn't work in a non-main thread. If you rewrite your code so that Tkinter runs in the main thread, you can have your workers run in other threads. The main caveat is that the workers cannot interact with the Tkinter widgets. They will have to write...
send post request python
10,557,475
2
2012-05-11T19:29:27Z
10,557,522
15
2012-05-11T19:34:20Z
[ "python", "http", "networking", "post" ]
I've got a website that I want to check to see if it was updated since the last check (using hash). The problem is that I need to enter a username and password before I can visit the site. Is there a way to input the username and the password using python?
Check out the [`requests`](http://docs.python-requests.org/en/latest/index.html) library, which you can get via `pip` by typing `pip install requests`, either through the `cmd` prompt, or terminal, depending on your OS. ``` import requests payload = {'user' : 'username', 'pass' : 'PaSSwoRd'} r = requests.g...
Matplotlib: figlegend only printing first letter
10,557,614
5
2012-05-11T19:43:21Z
10,557,741
11
2012-05-11T19:52:26Z
[ "python", "matplotlib" ]
I try to print a figlegend with only one line, but I only get the first letter. I have the following script for making the plot: ``` from pylab import * k = plot((0, 1),(1, 1)) figlegend((k),('Limit'),loc='lower center') savefig('test.pdf') ``` The output is: ![output](http://i.stack.imgur.com/MBsLT.png) What am I d...
I haven't figured out whether it is a bug or intentional (for some reason) in matplotlib, but in order to get a full legend label you need to leave a trailing comma on your list of labels: ``` figlegend((k),('Limit',),loc='lower center') ``` change that line and your code: ``` from pylab import * k = plot((0, 1),(1,...
mod_wsgi error - class.__dict__ not accessible in restricted mode
10,557,930
7
2012-05-11T20:07:03Z
10,558,360
9
2012-05-11T20:42:02Z
[ "python", "apache", "mod-wsgi", "wsgi", "pyramid" ]
This started biting our ass on our production server really hard. We saw this occasionally (for 1 request per week). Back then we found out it is because of mod\_wsgi doing some funky stuff in some configs. As we could not track the reason for the bug, we decided that it did not require instant attention. However toda...
It has been known for ages that multiple subinterpreters don't play well along C extensions. However, what I did not realize is that the default settings are very unfortunate. [ModWSGI wiki](http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIApplicationGroup) clearly states that the default value for WSG...
Is mixing Clojure with Python a good idea?
10,558,044
8
2012-05-11T20:16:03Z
10,558,919
14
2012-05-11T21:32:07Z
[ "python", "clojure" ]
I am working on a big project that involves a lot of web based and AI work. I am extremely comfortable with Python, though my only concern is with concurrent programming and scaling this project to make it work on clusters. Thus, Clojure for AI and support for Java function calls and bring about concurrent programming....
I built an embarrassingly parallel number-crunching application with a backend in Clojure (on an arbitrary number of machines) and a frontend in Ruby on Rails. I don't particularly like RoR, but this was a zero-budget project at the time and we had a Rails programmer at hand who was willing to work for free. The Cloju...
Dictionary comprehension with conditional
10,558,567
3
2012-05-11T21:00:06Z
10,558,814
10
2012-05-11T21:21:44Z
[ "python", "python-2.7", "dictionary-comprehension" ]
So I'm wondering if anyone can help me out with this issue I'm having. Lets assume I have a dictionary: ``` d = {1: {2: 3}, 4: 5} ``` I want to create a dictionary of any contained dictionaries: ``` wanted_result = {2: 3} ``` what I am trying is this: ``` e = {inner_key: d[key][inner_key] for key in d.keys() for ...
``` d = {1: {2: 3}, 4: 5, 6: {7: 8}} s = {k: v for elem in d.values() if type(elem) is dict for k, v in elem.items()} >> {2: 3, 7: 8} ```
Replace items in list, python
10,559,018
4
2012-05-11T21:42:08Z
10,559,041
9
2012-05-11T21:44:42Z
[ "python", "replace" ]
I have a list of strings like this: ``` Item_has_was_updated_May_2010 Item_updated_Apr_2011 Item_got_updated_Sept_2011 ``` I want to iterate through the list of string and update the last 2 parts of the string. The month and the year. The rest of the string I want to remain the same. The month and year will be taken ...
You can do it without regular expressions by using `str.rsplit`: ``` yourlist = [s.rsplit('_', 2)[0] + '_' + x + '_' + y for s in yourlist] ``` See it working online: [ideone](http://ideone.com/WcvKY) --- If you want to use formatting instead of string concatenation, try this: ``` yourlist = ['{}_{}_{}'.format(s.r...
How to rotate a video with OpenCV
10,559,035
5
2012-05-11T21:43:54Z
10,560,448
9
2012-05-12T01:59:05Z
[ "python", "image-processing", "opencv" ]
How do you rotate all frames in a video stream using OpenCV? I tried using the code provided in a [similar question](http://stackoverflow.com/questions/9041681/opencv-python-rotate-image-by-x-degrees-around-specific-point), but it doesn't seem to work with the Iplimage image object returned cv.RetrieveFrame. This is t...
If you are just after a 180 degree rotation, you can use `Flip` on both axes, replace: ``` frame = rotateImage(frame, 180) ``` with: ``` cv.Flip(frame, flipMode=-1) ``` This is 'in place', so its quick, and you won't need your `rotateImage` function any more :) Example: ``` import cv orig = cv.LoadImage("rot.png...
Matplotlib suptitle prints over old title
10,559,144
10
2012-05-11T21:54:38Z
10,559,541
15
2012-05-11T22:52:45Z
[ "python", "matplotlib" ]
I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: ``` self.ui.canvas1.figure.suptitle(title) ``` where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for t...
`figure.suptitle` returns a `matplotlib.text.Text` instance. You can save it and set the new title: ``` txt = fig.suptitle('A test title') txt.set_text('A better title') plt.draw() ```
Matplotlib suptitle prints over old title
10,559,144
10
2012-05-11T21:54:38Z
12,449,783
7
2012-09-16T19:02:57Z
[ "python", "matplotlib" ]
I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: ``` self.ui.canvas1.figure.suptitle(title) ``` where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for t...
Resurrecting this old thread because I recently ran into this. There is a references to the Text object returned by the original setting of suptitle in figure.texts. You can use this to change the original until this is fixed in matplotlib.
Why is taking the mod of a number in python faster with exponents?
10,559,392
12
2012-05-11T22:27:54Z
10,559,423
18
2012-05-11T22:32:43Z
[ "python", "optimization", "profiling" ]
I was trying to optimize a program I'm tinkering with, when I noticed that doing `value = i % 65536` appeared to be running slower then doing `value = i % (2**16)`. To test this, I ran the following program: ``` import cProfile import pstats AMOUNT = 100000000 def test1(): for i in xrange(AMOUNT): value...
There is no difference in the generated bytecode, because the compiler does its job well and optimizes away the constant arithmetic expression. That means your test results are just a coincidence (try timing the functions in a different order!). ``` >>> import dis >>> dis.dis(test1) 2 0 SETUP_LOOP ...
Extracting a word plus 20 more from a section (python)
10,559,591
3
2012-05-11T23:00:15Z
10,559,717
7
2012-05-11T23:20:20Z
[ "python", "nltk", "extraction", "gensim" ]
Jep still playing around with Python. I decided to try out Gensim, a tool to find out topics for a choosen word & context. So I wondered how to find a word in a section of text and extract 20 words together with it (as in 10 words before that spectic word and 10 words after that specific word) then to save it togethe...
The process is called [Keyword in Context (KWIC)](http://en.wikipedia.org/wiki/Key_Word_in_Context). The first step is to split you input into words. There are many ways to do that using the [regular expressions module](http://docs.python.org/library/re.html#module-re), see [re.split](http://docs.python.org/library/re...
django: How do I hash a URL from the database object's primary key?
10,559,935
4
2012-05-11T23:55:51Z
10,560,185
10
2012-05-12T00:49:56Z
[ "python", "django", "design-patterns", "url", "hash" ]
I'm trying to generate URLs for my database objects. [I've read](http://agiliq.com/books/djangodesignpatterns/misc.html#do-not-use-primary-keys-in-urls) I should not use the primary key for URLs, and a stub is not a good option for this particular model. Based on the advice in that link, I played around with zlib.crc32...
First, "don't use primary keys in URLs" is only a very weak guideline. *If* you are using incremental integer IDs *and* you don't want to reveal those numbers, then you could obfuscate them a little bit. For example, you could use: `masked_id = entity.id ^ 0xABCDEFAB` and `unmasked_id = masked_id ^ 0xABCDEFAB`. Second...
Parsing namespaces with clang: AST differences in when including a header in another source file or parsing it directly
10,561,212
8
2012-05-12T04:59:59Z
10,575,936
9
2012-05-13T23:11:18Z
[ "c++", "python", "parsing", "clang" ]
Sorry for the verbose question, but I can't see any other way to make it clear. I am writing a tool to transform C++ header files to SWIG interface files as a starter for further fine-tuning. In the process of doing this, I've noticed some strange behavior by clang (v3.0). If I parse the header file I get a significan...
Since you aren't explicitly specifying a language, Clang determines the language from the file extension, resulting in `"example.h"` being parsed as C, not C++. Thus the file is largely ill-formed, and the indexer tries to recover as well as it can. `namespace Geom` is being treated as a variable declaration for `Geom`...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1
10,561,923
69
2012-05-12T07:39:52Z
10,561,979
15
2012-05-12T07:53:01Z
[ "python", "unicode", "utf-8" ]
I'm having a few issues trying to encode a string to UTF-8. I've tried numerous things, including using `string.encode('utf-8')` and `unicode(string)`, but I get the error: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1: ordinal not in range(128) This is my string: ``` (。・ω・。)ノ `...
try: ``` string.decode('utf-8') # or: unicode(string, 'utf-8') ``` edit: `'(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'.decode('utf-8')` gives `u'(\uff61\uff65\u03c9\uff65\uff61)\uff89'`, which is correct. so your problem must be at some oter place, possibly if you try to do something wi...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1
10,561,923
69
2012-05-12T07:39:52Z
10,563,157
49
2012-05-12T11:05:58Z
[ "python", "unicode", "utf-8" ]
I'm having a few issues trying to encode a string to UTF-8. I've tried numerous things, including using `string.encode('utf-8')` and `unicode(string)`, but I get the error: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1: ordinal not in range(128) This is my string: ``` (。・ω・。)ノ `...
This is to do with the encoding of your terminal not being set to UTF-8. Here is my terminal ``` $ echo $LANG en_GB.UTF-8 $ python Python 2.7.3 (default, Apr 20 2012, 22:39:59) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\x...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1
10,561,923
69
2012-05-12T07:39:52Z
10,563,401
15
2012-05-12T11:43:09Z
[ "python", "unicode", "utf-8" ]
I'm having a few issues trying to encode a string to UTF-8. I've tried numerous things, including using `string.encode('utf-8')` and `unicode(string)`, but I get the error: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1: ordinal not in range(128) This is my string: ``` (。・ω・。)ノ `...
My +1 to mata's comment at <http://stackoverflow.com/a/10561979/1346705> and to the Nick Craig-Wood's demonstration. You have decoded the string correctly. The problem is with the `print` command as it converts the Unicode string to the console encoding, and the console is not capable to display the string. Try to writ...
Replacing characters in a file
10,562,778
5
2012-05-12T10:08:11Z
10,562,812
8
2012-05-12T10:13:15Z
[ "python" ]
I want to replace characters using encoding instructions in a text file. My text file contains the line: ``` This is a message ``` I want to replace `a -> e`,`e -> a`,`s -> 3` So the line reads: ``` Thi3 i3 e massega ``` I have tried the following code but it only changes one character in the line at one time. `...
Replace this: ``` newcontents = contents.replace('a','e') newcontents = contents.replace('s', '3') ``` with this: ``` newcontents = contents.replace('a','e') newcontents = newcontents.replace('s', '3') ``` Or better yet: ``` newcontents = contents.replace('a','e').replace('s', '3') ``` Your code only appears to a...
Python IMAP Search from or to designated email address
10,563,218
5
2012-05-12T11:15:27Z
10,563,374
11
2012-05-12T11:38:47Z
[ "python", "imap", "imaplib" ]
I am using this with Gmail's SMTP server, and I would like to search via IMAP for emails either sent to or received from an address. This is what I have: ``` mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('user', 'pass') mail.list() mail.select("[Gmail]/All Mail") status, email_ids = mail.search(None, 'TO "t...
The error you are receiving is generated from the server because it can't parse the *search query* correctly. In order to generate a valid query follow the [RFC 3501](http://tools.ietf.org/html/rfc3501.html), in page 49 it is explained in detail the structure. For example your search string to be correct should be: `...