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
Basic http file downloading and saving to disk in python?
19,602,931
65
2013-10-26T04:49:27Z
19,603,003
62
2013-10-26T05:00:46Z
[ "python", "file", "download", "save" ]
I'm new to Python and I've been going through the Q&A on this site, for an answer to my question. However, I'm a beginner and I find it difficult to understand some of the solutions. I need a very basic solution. Could someone please explain a simple solution to 'Downloading a file through http' and 'Saving it to disk...
As mentioned [here](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python/22776#22776): ``` import urllib urllib.urlretrieve ("http://randomsite.com/file.gz", "file.gz") ``` `EDIT:` If you still want to use requests, take a look at [this question](http://stackoverflow.com/questions/...
Basic http file downloading and saving to disk in python?
19,602,931
65
2013-10-26T04:49:27Z
25,827,767
17
2014-09-13T21:13:57Z
[ "python", "file", "download", "save" ]
I'm new to Python and I've been going through the Q&A on this site, for an answer to my question. However, I'm a beginner and I find it difficult to understand some of the solutions. I need a very basic solution. Could someone please explain a simple solution to 'Downloading a file through http' and 'Saving it to disk...
I use [wget](https://pypi.python.org/pypi/wget). Simple and good library if you want to example? ``` import wget file_url = 'http://johndoe.com/download.zip' file_name = wget.download(file_url) ``` wget module support python 2 and python 3 versions
python: avoiding zip truncation of list
19,603,120
8
2013-10-26T05:19:35Z
19,603,142
13
2013-10-26T05:22:24Z
[ "python", "list", "truncation" ]
I have the following python code that uses zip() and it seems to cause unintended data truncation. ``` inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'], [u'Total Revenue\n', u'104,507,100\n', u'106,916,100\n', u'99,870,100\n'], [u'Cost of Revenue\n',u'56,000,000...
Use [izip\_longest](http://docs.python.org/2/library/itertools.html#itertools.izip_longest): ``` from itertools import izip_longest inc_data = [[u'Period Ending', u'Dec 31, 2012', u'Dec 31, 2011', u'Dec 31, 2010'], [u'Total Revenue\n', u'104,507,100\n', u'106,916,100\n', u'99,870,100\n'], [u'C...
threading a bottle app
19,604,648
4
2013-10-26T08:32:24Z
19,604,678
11
2013-10-26T08:37:13Z
[ "python", "multithreading", "bottle" ]
I have a simple bottle script that forwards button processes on a web page. Within the same script I was looking to have a continuous loop that among other tasks listened out for these button presses. I attempted to run the bottle script in a separate thread but it doesn't work as I expected. Is there a better (or sho...
It doesn't work because it's only seeing the local variable `pushed` defined inside of `method` as opposed to a globally visible and modifiable `pushed` variable. What you need instead is the following (but scroll down for a correct solution): ``` pushed = False @post('/button') def action(): global pushed # ne...
How to create lazy_evaluated dataframe columns in Pandas
19,605,537
8
2013-10-26T10:20:28Z
19,611,659
7
2013-10-26T20:39:47Z
[ "python", "pandas", "lazy-evaluation" ]
A lot of times, I have a big dataframe `df` to hold the basic data, and need to create many more columns to hold the derivative data calculated by basic data columns. I can do that in Pandas like: ``` df['derivative_col1'] = df['basic_col1'] + df['basic_col2'] df['derivative_col2'] = df['basic_col1'] * df['basic_col2...
Starting in 0.13 (releasing very soon), you can do something like this. This is using generators to evaluate a dynamic formula. In-line assignment via eval will be an additional feature in 0.13, see [here](https://github.com/pydata/pandas/pull/5343) ``` In [19]: df = DataFrame(randn(5, 2), columns=['a', 'b']) In [20]...
Why is Python 3.x's super() magic?
19,608,134
86
2013-10-26T14:58:32Z
19,609,168
118
2013-10-26T16:41:24Z
[ "python", "python-3.x", "super" ]
In Python 3.x, [`super()`](http://docs.python.org/3.3/library/functions.html#super) can be called without arguments: ``` class A(object): def x(self): print("Hey now") class B(A): def x(self): super().x() ``` ``` >>> B().x() Hey now ``` In order to make this work, some compile-time magic is...
The new magic `super()` behaviour was added to avoid violating the D.R.Y. (Don't Repeat Yourself) principle, see [PEP 3135](http://www.python.org/dev/peps/pep-3135/). Having to explicitly name the class by referencing it as a global is also prone to the same rebinding issues you discovered with `super()` itself: ``` c...
python: changing row index of pandas data frame
19,609,631
9
2013-10-26T17:22:43Z
19,609,945
22
2013-10-26T17:52:22Z
[ "python", "pandas" ]
I have a data frame called `followers_df` as below: ``` followers_df 0 0 oasikhia 0 LEANEnergyUS 0 _johannesngwako 0 jamesbreenre 0 CaitlinFecteau 0 mantequillaFACE 0 apowersb 0 ecoprinter 0 tsdesigns 0 GreenBizDoc 0 JimHarris 0 Jmarti11Julia 0 ...
you can do ``` followers_df.index = range(20) ```
python: changing row index of pandas data frame
19,609,631
9
2013-10-26T17:22:43Z
19,609,954
10
2013-10-26T17:53:51Z
[ "python", "pandas" ]
I have a data frame called `followers_df` as below: ``` followers_df 0 0 oasikhia 0 LEANEnergyUS 0 _johannesngwako 0 jamesbreenre 0 CaitlinFecteau 0 mantequillaFACE 0 apowersb 0 ecoprinter 0 tsdesigns 0 GreenBizDoc 0 JimHarris 0 Jmarti11Julia 0 ...
``` followers_df.reset_index() followers_df.reindex(index=range(0,20)) ```
TypeError: can only concatenate tuple (not "int") in Python
19,609,991
4
2013-10-26T17:57:28Z
19,610,042
10
2013-10-26T18:01:11Z
[ "python", "tuples", "typeerror" ]
I am going to need your help with this constant tuple error I keep getting. Seems that it is a common mathematical error that many have. I have read almost every instance of TypeError including 'not int', 'not list', 'not float' etc. Yet I have failed to figure out why I get it. I have written the below code that allo...
Your `checkAnswer()` function returns a *tuple*: ``` def checkAnswer(number1, number2, answer, right): if answer == number1+number2: print 'Right' right = right + 1 else: print 'Wrong' return right, answer ``` Here `return right, answer` returns a tuple of two values. Note that it...
Getting Google Spreadsheet CSV into A Pandas Dataframe
19,611,729
17
2013-10-26T20:46:51Z
19,611,857
24
2013-10-26T21:02:16Z
[ "python", "pandas", "google-spreadsheet", "google-apps" ]
I uploaded a file to Google spreadsheets (to make a publically accessible example IPython Notebook, with data) I was using the file in it's native form could be read into a Pandas Dataframe. So now I use the following code to read the spreadsheet, works fine but just comes in as string,, and I'm not having any luck try...
You can use read\_csv on a StringIO object. ``` from StringIO import StringIO # got moved to io in python3. import requests r = requests.get('https://docs.google.com/spreadsheet/ccc?key=0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc&output=csv') data = r.content In [10]: df = pd.read_csv(StringIO(data), index_col=0,p...
Getting Google Spreadsheet CSV into A Pandas Dataframe
19,611,729
17
2013-10-26T20:46:51Z
35,246,041
8
2016-02-06T20:23:08Z
[ "python", "pandas", "google-spreadsheet", "google-apps" ]
I uploaded a file to Google spreadsheets (to make a publically accessible example IPython Notebook, with data) I was using the file in it's native form could be read into a Pandas Dataframe. So now I use the following code to read the spreadsheet, works fine but just comes in as string,, and I'm not having any luck try...
Seems to work for me without the `StringIO`: ``` test = pd.read_csv('https://docs.google.com/spreadsheets/d/' + '0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc' + '/export?gid=0&format=csv', # Set first column as rownames in data frame index_co...
'forms.ContactForm object' has no attribute 'hidden_tag'
19,612,186
6
2013-10-26T21:39:50Z
20,577,177
24
2013-12-13T22:34:23Z
[ "python", "html" ]
I am trying to create a contact form using flask but keep getting this error when the page is rendered. ``` 'forms.ContactForm object' has no attribute 'hidden_tag' ``` Here are my files: **contact.html** ``` {% extends "layout.html" %} {% block content %} <h2>Contact</h2> <form action="{{ url_for('contact') }...
I just fixed this problem as well. Your problem is that you imported Form twice, rendering your flask-wtf `Form` import useless. ``` from flask_wtf import Form from wtforms import Form, TextField, TextAreaField, SubmitField, validators # ^^^ Remove ``` Only the flask-wtf extension has the special `...
Load all csv/txt files from one directory and merge them via python
19,613,716
3
2013-10-27T01:29:15Z
19,877,697
9
2013-11-09T15:35:53Z
[ "python", "file", "python-2.7", "csv", "directory" ]
I have a folder which contains hundreds (possibly over 1 k) of csv data files, of chronological data. Ideally this data would be in one csv, so that I can analyse it all in one go. What I would like to know is, is there a way to append all the files to one another using python. My files exist in folder locations like ...
For all files in folder with `.csv` suffix ``` import glob import os filelist = [] os.chdir("folderwithcsvs/") for counter, files in enumerate(glob.glob("*.csv")): filelist.append(files) print "do stuff with file:", files, counter print filelist for fileitem in filelist: print fileitem ``` Obviously t...
Python threads don't run simultaneously
19,614,224
5
2013-10-27T03:12:13Z
19,614,263
7
2013-10-27T03:19:31Z
[ "python", "multithreading" ]
I'm brand new to multi-threaded processing, so please forgive me if I butcher terms or miss something obvious. The code below doesn't offer any time advantage over different code that calls the same two functions one after the other. --- ``` import time import threading start_time = time.clock() def fibonacci(nth)...
There are good answers regarding the GIL you can look at. In short, if your tasks are CPU-bound (like the ones you posted), threads are not going to help you. Python threads are good for IO-bound tasks, like retrieving a web page.
How do I make pytest fixtures work with decorated functions?
19,614,658
13
2013-10-27T04:34:35Z
19,614,807
10
2013-10-27T05:03:52Z
[ "python", "decorator", "py.test" ]
py.test seems to fail when I decorate test functions which has a fixture as an argument. ``` def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @pytest.fixture def x(): return 0 @deco def test_something(x): assert x == 0 ```...
It looks like functools.wraps does not do the job well enough, so it breaks py.test's introspection. Creating the decorator using the [decorator](https://pypi.python.org/pypi/decorator) package seems to do the trick. ``` import decorator def deco(func): def wrapper(func, *args, **kwargs): return func(*ar...
Different indentation no error in python
19,615,180
2
2013-10-27T06:08:01Z
19,615,191
7
2013-10-27T06:11:02Z
[ "python", "python-2.7" ]
``` password = raw_input("Enter password: ") if password == "1234": print "You logged in correctly!" else: print "GTFO" ``` Though i give different indentations the code is working fine i'm unable to figure it out.
it will not be flagged as as IndentationError, sine any block of statement has to have at lease 1 space of indent here your `if` and `else` are two different blocks, so it was indented anyway so the interpreter throws no error ``` if True: print elif True: print elif True: print elif True: print else: ...
Running an Excel macro via Python?
19,616,205
12
2013-10-27T08:48:24Z
19,743,828
14
2013-11-02T16:01:33Z
[ "python", "excel", "vba", "python-2.7" ]
I'm trying to run a macro via python but I'm not sure how to get it working... I've got the following code so far, but it's not working. ``` import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1) xl.Application.Run("macrohere") xl.Workbooks(1).Clo...
I would except the error is to do with the macro you're calling, try the following bit of code: ### Code ``` import os import win32com.client if os.path.exists("excelsheet.xlsm"): xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm", ReadOnly=1) ...
Dynamically changing log level in python without restarting the application
19,617,355
14
2013-10-27T11:07:41Z
19,617,375
20
2013-10-27T11:09:44Z
[ "python", "logging", "gevent" ]
Is it possible to change the log level using fileConfig in python without restarting the application. If it cannot be achieved through fileConfig is there some other way to get the same result? Update: This was for an application running on a server, I wanted sys admins to be able to change a config file that would be...
`fileConfig` is a mechanism to configure the log level for you based on a file; you can dynamically change it at any time in your program. Call [`.setLevel()`](http://docs.python.org/2/library/logging.html#logging.Logger.setLevel) on the logging object for which you want to change the log level. Usually you'd do that ...
Trying to install pycrypto on Mac OSX mavericks
19,617,686
16
2013-10-27T11:44:52Z
22,424,999
32
2014-03-15T14:23:20Z
[ "python", "osx", "pycrypto" ]
I am currently trying to install pycrypto and when I execute python setup.py build I receive this following error: ``` cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.9-intel-2.7/src/_fastmath.o -lgmp -o build/lib.macosx-10.9-intel-2.7/Crypto/PublicKey/_fastmath.so ld: illegal...
This worked for me. (Should work if you are on Xcode 5.1) ``` ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install pycrypto ```
Trying to install pycrypto on Mac OSX mavericks
19,617,686
16
2013-10-27T11:44:52Z
22,868,650
12
2014-04-04T16:54:24Z
[ "python", "osx", "pycrypto" ]
I am currently trying to install pycrypto and when I execute python setup.py build I receive this following error: ``` cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.9-intel-2.7/src/_fastmath.o -lgmp -o build/lib.macosx-10.9-intel-2.7/Crypto/PublicKey/_fastmath.so ld: illegal...
This did it for me: ``` sudo port install gmp sudo ln -s /opt/local/lib/libgmp.dylib /usr/lib/libgmp.dylib ARCHFLAGS=-Wno-error CFLAGS=-I/opt/local/include sudo -E pip install pycrypto ```
Trying to install pycrypto on Mac OSX mavericks
19,617,686
16
2013-10-27T11:44:52Z
29,383,772
7
2015-04-01T05:56:07Z
[ "python", "osx", "pycrypto" ]
I am currently trying to install pycrypto and when I execute python setup.py build I receive this following error: ``` cc -bundle -undefined dynamic_lookup -arch x86_64 -arch i386 -Wl,-F. build/temp.macosx-10.9-intel-2.7/src/_fastmath.o -lgmp -o build/lib.macosx-10.9-intel-2.7/Crypto/PublicKey/_fastmath.so ld: illegal...
On Yosemite: ``` CC=clang sudo -E pip install pycrypto ```
Mocking not working with pytest and flexmock
19,617,873
3
2013-10-27T12:10:07Z
19,698,731
11
2013-10-31T04:56:37Z
[ "python", "unit-testing", "py.test", "flexmock" ]
I'm trying to use pytest fixtures to mock calls to `open()` and then reset it on test teardown, but for some reason the mock is not applied in the test function. Here's a sample of what I have: ``` # tests.py @pytest.fixture(scope='module') def mock_open(request): mock = flexmock(sys.modules['__builtin__']) m...
How about using [`mock`](https://pypi.python.org/pypi/mock)? --- tests.py: ``` import mock # import unittest.mock (Python 3.3+) import pytest from some_module import function_to_test @pytest.fixture(scope='function') def mock_open(request): m = mock.patch('__builtin__.open', mock.mock_open(read_data='file cont...
unicode_literals and type()
19,618,031
11
2013-10-27T12:29:17Z
19,618,122
12
2013-10-27T12:40:03Z
[ "python", "python-3.x", "python-2.x", "six-python" ]
I'm having problems supporting python2 and python3 on a `type()` call. This demonstrates the problem: ``` from __future__ import unicode_literals name='FooClass' type(name, (dict,), {}) ``` No problem on python3, but on python2: ``` Traceback (most recent call last): File "test.py", line 6, in <module> type(n...
`six.b` is written under the assumption that you won't use `unicode_literals` (and that you'll pass a string literal to it, as the documentation states), so the Python 2 implementation is just `def b(s): return s` as a Python 2 string literal is already a byte string. Either don't use `unicode_literals` in this module...
Finding common rows (intersection) in two Pandas dataframes
19,618,912
11
2013-10-27T14:03:18Z
30,535,957
16
2015-05-29T17:47:24Z
[ "python", "python-2.7", "pandas", "dataframe", "intersect" ]
Assume I have two dataframes of this format (call them `df1` and `df2`): ``` +------------------------+------------------------+--------+ | user_id | business_id | rating | +------------------------+------------------------+--------+ | rLtl8ZkDX5vH5nAx9C3q5Q | eIxSLxzIlfExI6vgAbn2JA | 4 ...
My understanding is that this question is better answered over in [this post](http://stackoverflow.com/questions/26921943/pandas-intersection-of-two-data-frames-based-on-column-entries). But briefly, the answer to the OP with this method is simply: ``` s1 = pd.merge(df1, df2, how='inner', on=['user_id']) ``` Which g...
Optimized code to check the element of list unique or not
19,619,702
4
2013-10-27T15:22:06Z
19,619,728
12
2013-10-27T15:24:44Z
[ "python", "optimization", "python-3.x" ]
python3 program that takes input a list and output if it is unique or not. The following is an example: ``` list_a = [1,2,3,4,5] #unique list_b = [1,2,2,3,4] #not unique ``` I have wrote a python3 script for this problem: ``` for i in range(len(list_a)): j = i+1 for j in range(len(list_a)): if list_a[i] ...
The easiest way to do this is compare length of set of given list with length of list: ``` if len(l) != len(set(l)): # not unique ```
Optimized code to check the element of list unique or not
19,619,702
4
2013-10-27T15:22:06Z
19,619,730
8
2013-10-27T15:24:46Z
[ "python", "optimization", "python-3.x" ]
python3 program that takes input a list and output if it is unique or not. The following is an example: ``` list_a = [1,2,3,4,5] #unique list_b = [1,2,2,3,4] #not unique ``` I have wrote a python3 script for this problem: ``` for i in range(len(list_a)): j = i+1 for j in range(len(list_a)): if list_a[i] ...
You can use `all()` and sets, this will short-circuit as soon as a repeated item is found. ``` >>> def solve(lis): ... seen = set() ... return all(item not in seen and not seen.add(item) for item in lis) ... >>> solve(range(5)) True >>> solve([1,2,2,3,4]) False ```
Why this four lines code gives 0.45<0.45 is True
19,620,610
3
2013-10-27T16:46:57Z
19,620,630
7
2013-10-27T16:48:52Z
[ "python", "floating-accuracy" ]
python code: ``` x=0.35 while (x<0.45): x=x+0.05 print x,"<",0.45, x<0.45 ``` below is the output: ``` 0.4 < 0.45 True 0.45 < 0.45 True 0.5 < 0.45 False ``` Why 0.45<0.45 is true?
Because you're actually comparing: ``` 0.44999999999999996 < 0.45 ``` **Demo:** ``` >>> x=0.35 >>> while (x<0.45): x = x+0.05 print repr(x),"<",0.45, x<0.45 ... 0.39999999999999997 < 0.45 True 0.44999999999999996 < 0.45 True 0.49999999999999994 < 0.45 False ``` `print` calls `str` on floats, wh...
Get list of attributes in class
19,620,631
3
2013-10-27T16:48:54Z
19,620,698
14
2013-10-27T16:54:14Z
[ "python" ]
How would I get a list of attributes in a class? For example: ``` class Test: def __init__(self,**kw): for k,v in kw.items(): setattr(self,k,v) x = Test(value="hello",valueTwo="world") print(dir(x)) ``` I've done that and it seems to print the keys but, it also prints extra stuff like: ``` ['...
Use `x.__dict__`: ``` >>> x.__dict__ {'value': 'hello', 'valueTwo': 'world'} ```
how to use promote to in qt designer in pyqt4?
19,622,014
3
2013-10-27T18:51:07Z
19,622,817
8
2013-10-27T19:59:20Z
[ "python", "qt", "pyqt4", "designer" ]
In the designer when I right click a widget, and i click promote to i get this window? see screenshot below. I have never used this feature basically the header file is confusing me. what is it for ? does that mean i can create a new class in this case inherit QLineEdit and add more methos to it ? what is promoted cla...
This allows you to use custom widgets defined elsewhere, which designer otherwise wouldn't know about. For example, if you've defined a widget `MyLabel` derived from `QLabel`, then you can define it here and then just insert a `QLabel` as placeholder in your ui and promote it to `MyLabel`. The uic compiler will then ...
Vertical Print String - Python3.2
19,622,169
3
2013-10-27T19:04:29Z
19,622,217
8
2013-10-27T19:07:58Z
[ "python", "string", "python-3.x", "vertical-text" ]
I'm writing a script that will take as user inputed string, and print it vertically, like so: ``` input = "John walked to the store" output = J w t t s o a o h t h l e o n k r e e d ``` I've written most of the code, which is as follows: ``` import sys def...
Use `itertools.zip_longest`: ``` >>> from itertools import zip_longest >>> text = "John walked to the store" for x in zip_longest(*text.split(), fillvalue=' '): print (' '.join(x)) ... J w t t s o a o h t h l e o n k r e e d ```
How to test if a table already exists?
19,622,341
9
2013-10-27T19:18:49Z
19,622,362
7
2013-10-27T19:20:44Z
[ "python", "sqlite" ]
I'm working on a scrabblecheat program Following some examples I have the following code below which uses SQLite for a simple database to store my words. However it tells me I can't recreate the database table. How do I write in a check for if there is already a table named `spwords`, then skip trying to create it? ...
The query you're looking for is: ``` SELECT name FROM sqlite_master WHERE type='table' AND name='spwords' ``` So, the code should read as follows: ``` tb_exists = "SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'" if not conn.execute(tb_exists).fetchone(): conn.execute(tb_create) ``` A conve...
ImportError: No module named Crypto.Cipher
19,623,267
37
2013-10-27T20:39:10Z
20,014,293
20
2013-11-16T03:28:52Z
[ "python", "virtualenv", "pip", "easy-install", "pycrypto" ]
When I try to run app.py (Python 3.3, PyCrypto 2.6) my virtualenv keeps returning the error listed above. My import statement is just `from Crypto.Cipher import AES`. I looked for duplicates and you might say that there are some, but I tried the solutions (although most are not even solutions) and nothing worked. You ...
I had the same problem (though on Linux). The solution was quite simple - add: ``` libraries: - name: pycrypto version: "2.6" ``` to my app.yaml file. Since this worked correctly in the past, I assume this is a new requirement.
ImportError: No module named Crypto.Cipher
19,623,267
37
2013-10-27T20:39:10Z
20,466,762
12
2013-12-09T09:02:22Z
[ "python", "virtualenv", "pip", "easy-install", "pycrypto" ]
When I try to run app.py (Python 3.3, PyCrypto 2.6) my virtualenv keeps returning the error listed above. My import statement is just `from Crypto.Cipher import AES`. I looked for duplicates and you might say that there are some, but I tried the solutions (although most are not even solutions) and nothing worked. You ...
type command: ``` sudo pip install pycrypto ```
ImportError: No module named Crypto.Cipher
19,623,267
37
2013-10-27T20:39:10Z
20,968,427
88
2014-01-07T09:48:21Z
[ "python", "virtualenv", "pip", "easy-install", "pycrypto" ]
When I try to run app.py (Python 3.3, PyCrypto 2.6) my virtualenv keeps returning the error listed above. My import statement is just `from Crypto.Cipher import AES`. I looked for duplicates and you might say that there are some, but I tried the solutions (although most are not even solutions) and nothing worked. You ...
I had the same problem on my Mac when installing with `pip`. I then removed `pycrypto` and installed it again with `easy_install`, like this: ``` pip uninstall pycrypto easy_install pycrypto ``` also as Luke commented: If you have trouble running these commands, be sure to run them as admin (sudo) Hope this helps!
ImportError: No module named Crypto.Cipher
19,623,267
37
2013-10-27T20:39:10Z
21,116,128
16
2014-01-14T14:32:29Z
[ "python", "virtualenv", "pip", "easy-install", "pycrypto" ]
When I try to run app.py (Python 3.3, PyCrypto 2.6) my virtualenv keeps returning the error listed above. My import statement is just `from Crypto.Cipher import AES`. I looked for duplicates and you might say that there are some, but I tried the solutions (although most are not even solutions) and nothing worked. You ...
On the mac... if you run into this.. try to see if you can import crypto instead? If so.. the package name is the issue `C` vs `c`. To get around this.. just add these lines to the top of your script. ``` import crypto import sys sys.modules['Crypto'] = crypto ``` You know should be able to import paramiko successfu...
ImportError: No module named Crypto.Cipher
19,623,267
37
2013-10-27T20:39:10Z
25,949,207
7
2014-09-20T13:17:59Z
[ "python", "virtualenv", "pip", "easy-install", "pycrypto" ]
When I try to run app.py (Python 3.3, PyCrypto 2.6) my virtualenv keeps returning the error listed above. My import statement is just `from Crypto.Cipher import AES`. I looked for duplicates and you might say that there are some, but I tried the solutions (although most are not even solutions) and nothing worked. You ...
I've had the same problem `'ImportError: No module named Crypto.Cipher'`, since using GoogleAppEngineLauncher (version > 1.8.X) with GAE Boilerplate on OSX 10.8.5 (Mountain Lion). In Google App Engine SDK with python 2.7 runtime, pyCrypto 2.6 is the suggested version. The solution that worked for me was... 1) Download...
Sort results non-lexicographically?
19,624,844
11
2013-10-27T23:16:18Z
19,624,925
11
2013-10-27T23:24:51Z
[ "python", "sorting" ]
I'm trying to display some results in a human-readable way. For the purposes of this question, some of them are numbers, some are letters, some are a combination of the two. I'm trying to figure out how I could get them to sort like this: ``` input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance'] sorted_inpu...
**1 - Install natsort module** ``` pip install natsort ``` **2 - Import natsorted** ``` >>> input = ['1', '10', '2', '0', '3', 'Hello', '100', 'Allowance'] >>> from natsort import natsorted >>> natsorted(input) ['0', '1', '2', '3', '10', '100', 'Allowance', 'Hello'] ``` Source: <https://pypi.python.org/pypi/natsor...
Understanding scipy's least square function with IRLS
19,624,997
6
2013-10-27T23:33:22Z
19,625,931
7
2013-10-28T01:32:32Z
[ "python", "numpy", "scipy" ]
I'm having a bit of trouble understanding how this function works. ``` a, b = scipy.linalg.lstsq(X, w*signal)[0] ``` I know that signal is the array representing the signal and currently `w` is just `[1,1,1,1,1...]` How should I manipulate `X` or `w` to imitate weighted least squares or iteratively reweighted least ...
If you product X and y with sqrt(weight) you can calculate weighted least squares. You can get the formula by following link: <http://en.wikipedia.org/wiki/Linear_least_squares_%28mathematics%29#Weighted_linear_least_squares> here is an example: Prepare data: ``` import numpy as np np.random.seed(0) N = 20 X = np.r...
Django JavaScript translation not working
19,625,102
5
2013-10-27T23:47:42Z
19,630,870
8
2013-10-28T09:15:53Z
[ "python", "django", "translation", "gettext" ]
I tried to [follow the guide](https://docs.djangoproject.com/en/1.5/topics/i18n/translation/#internationalization-in-javascript-code) but it's not clear enough. 1. I added this to my urls.py ``` urlpatterns = patterns('', (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'), ) ...
I don't know exactly how to solve your problem, but I can tell you, how things work for me: The `locale` folder is inside my `tickets` app. urls.py ``` js_info_dict = { 'domain': 'djangojs', 'packages': ('tickets',), } urlpatterns = patterns('', (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_...
matplotlib: change the current axis instance (i.e., gca())
19,625,563
8
2013-10-28T00:44:13Z
19,625,774
19
2013-10-28T01:11:09Z
[ "python", "python-2.7", "matplotlib" ]
I use a trick to [draw a colorbar whose height matches the master axes](http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes). The code is like ``` import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import nump...
Use [`plt.sca`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.sca) to set the current axes.
Python xticks in subplots
19,626,530
19
2013-10-28T02:56:14Z
19,626,667
40
2013-10-28T03:15:34Z
[ "python", "matplotlib", "imshow" ]
If I plot a single imshow plot I can use ``` fig, ax = plt.subplots() ax.imshow(data) plt.xticks( [4, 14, 24], [5, 15, 25] ) ``` to replace my xtick labels. Now, I am plotting 12 imshow plots using ``` f, axarr = plt.subplots(4, 3) axarr[i, j].imshow(data) ``` How can I change my xticks just for one of these subp...
There are two ways: 1. Use the axes methods of the subplot object (e.g. `ax.set_xticks` and `ax.set_xticklabels`) or 2. Use `plt.sca` to set the current axes for the pyplot state machine (i.e. the `plt` interface). As an example (this also illustrates using `setp` to change the properties of all of the subplots): ``...
How to See if a String Contains Another String in Django Template
19,627,911
13
2013-10-28T05:47:00Z
19,628,156
28
2013-10-28T06:08:44Z
[ "python", "django" ]
This is my code in template. ``` {% if 'index.html' in "{{ request.build_absolute_uri }}" %} 'hello' {% else %} 'bye' {% endif %} ``` now my url value currently is `"http://127.0.0.1:8000/login?next=/index.html"` Though 'index.html' is there in the string it prints bye. Though I run the same code in ...
Try removing the extra `{{...}}` tags and the `"..."` quotes around `request.build_absolute_uri`, it worked for me. Since you are already within an `{% if %}` tag, there is no need to surround `request.build_absolute_uri` with `{{...}}` tags. ``` {% if 'index.html' in request.build_absolute_uri %} hello {% else %...
How to check if __str__ is implemented by an object
19,628,421
6
2013-10-28T06:33:23Z
19,628,560
8
2013-10-28T06:44:03Z
[ "python" ]
I want to dynamically implement `__str__` method on a object if the object doesn't already implement it. I try using `hasattr(obj, '__str__')` it always returns me true as it picks it up from object class. Is there a way to determine if an object actually implements `__str__` ? I know I can use `inspect.getmembers(o...
Since what you want to check is if it has a `__str__` implementation that is *not* the default `object.__str__`. Therefore, you can do this: ``` Foo.__str__ is not object.__str__ ``` To check with instantiated objects you need to check on the class: ``` type(f).__str__ is not object.__str__ ``` This will also work ...
Django ModelForm Imagefield Upload
19,628,979
14
2013-10-28T07:14:31Z
19,639,286
36
2013-10-28T15:49:46Z
[ "python", "django", "modelform" ]
I am pretty new to Django and I met a problem in handling image upload using ModelForm. My model is as following: ``` class Project(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=2000) startDate = models.DateField(auto_now_add=True) photo = models.Image...
OK, thanks everyone. I found myself made a stupid mistake. I should add `enctype="multipart/form-data"` in the `<form>` Else, it won't upload the file.
django installation: cannot use pip to install django on linux(ubuntu)
19,629,685
4
2013-10-28T08:02:21Z
19,629,720
8
2013-10-28T08:04:48Z
[ "python", "django", "pip" ]
I tried to install django on ubuntu using pip. but unfortunately I got error like this. can someone explain this and tell me some ways to fix this? ``` error: could not create '/usr/local/lib/python2.7/dist-packages/django': Permission denied ---------------------------------------- Command /usr/bin/python -c "import...
Try `sudo pip install django` instead.
django installation: cannot use pip to install django on linux(ubuntu)
19,629,685
4
2013-10-28T08:02:21Z
19,630,200
11
2013-10-28T08:36:22Z
[ "python", "django", "pip" ]
I tried to install django on ubuntu using pip. but unfortunately I got error like this. can someone explain this and tell me some ways to fix this? ``` error: could not create '/usr/local/lib/python2.7/dist-packages/django': Permission denied ---------------------------------------- Command /usr/bin/python -c "import...
Don't use sudo use a virtual environment instead, like this: ``` $ sudo apt-get install python-virtualenv $ mkvirtualenv django_env $ source django_env/bin/activate (django_env) $ pip install django (django_env) $ cd $HOME (django_env) $ mkdir projects (django_env) $ cd projects (django_env)/projects $ django-admin.py...
Check if one value exists in any rows of any columns in pandas?
19,630,328
2
2013-10-28T08:44:34Z
19,630,449
8
2013-10-28T08:52:01Z
[ "python", "pandas" ]
Is there any function to check if a value exists in any rows of any columns in pandas, such as ``` columnA columnB columnC "john" 3 True "mike" 1 False "bob" 0 False ``` on the dataframe above, I want to know if there are any values named `"mike"` in any elements of the whole dataframe, and if it exists, I'd like to ...
Something like this: ``` df.apply(lambda x: 'mike' in x.values, axis=1).any() ``` or ``` df.applymap(lambda x: x == 'mike').any().any() ```
How to check is a string is a valid regex - python?
19,630,994
7
2013-10-28T09:21:50Z
19,631,067
12
2013-10-28T09:24:55Z
[ "python", "regex", "string", "validation" ]
In Java, i could use the following function to check if a string is a valid regex: (source:[How to check if the string is a regular expression or not](http://stackoverflow.com/questions/6341367/how-to-check-if-the-string-is-a-regular-expression-or-not)) ``` boolean isRegex; try { Pattern.compile(input); isRegex = ...
Similar to Java. Use [`re.error`](http://docs.python.org/2/library/re.html#re.error) exception: ``` import re try: re.compile('[') is_valid = True except re.error: is_valid = False ``` > exception `re.error` > > Exception raised when a string passed to one of the functions here is > not a valid regular e...
Reverting a URL in Flask to the endpoint + arguments
19,631,335
6
2013-10-28T09:38:07Z
19,637,175
10
2013-10-28T14:17:29Z
[ "python", "flask" ]
What would be the appropriate way of resolving a URL within Flask to retrieve a reference to the endpoint as well as a dictionary of all the arguments? To provide an example, given this route, I'd like to resolve `'/user/nick'` to `profile`,`{'username': 'nick'}`: ``` @app.route('/user/<username>') def profile(userna...
This is what I hacked for this purpose looking at `url_for()` and reversing it: ``` from flask.globals import _app_ctx_stack, _request_ctx_stack from werkzeug.urls import url_parse def route_from(url, method = None): appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: ra...
how to read file with space separated values
19,632,075
16
2013-10-28T10:14:45Z
19,632,099
7
2013-10-28T10:16:01Z
[ "python", "pandas" ]
I try to read the file into pandas. The file has values separated by space, but with different number of spaces I tried: ``` pd.read_csv('file.csv', delimiter=' ') ``` but it doesn't work
you can use regex as the delimiter: ``` pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+") ```
how to read file with space separated values
19,632,075
16
2013-10-28T10:14:45Z
19,633,103
26
2013-10-28T11:06:34Z
[ "python", "pandas" ]
I try to read the file into pandas. The file has values separated by space, but with different number of spaces I tried: ``` pd.read_csv('file.csv', delimiter=' ') ``` but it doesn't work
add `delim_whitespace=True` argument, it's faster than regex.
Python: How to Convert list multiple set of array
19,633,163
3
2013-10-28T11:09:52Z
19,633,179
7
2013-10-28T11:10:42Z
[ "python", "list", "numpy" ]
I have to change a list of values into multiple array set as shown below: ``` list_train_data = [u'Class 1', u'Class 2', u'Class 3', u'Class 4', u'Class 5'] ``` I need this value into an array like: ``` train_set = [['Class 1'],['Class 2'],['Class 3'],['Class 4'],['Class 5']] ``` If possible not use for loop.
Use a list comprehension: ``` train_set = [[x] for x in list_train_data] ``` **Demo:** ``` >>> list_train_data = [u'Class 1', u'Class 2', u'Class 3', u'Class 4', u'Class 5'] >>> [[x] for x in list_train_data] [[u'Class 1'], [u'Class 2'], [u'Class 3'], [u'Class 4'], [u'Class 5']] ```
Python: How to Convert list multiple set of array
19,633,163
3
2013-10-28T11:09:52Z
19,633,389
7
2013-10-28T11:19:48Z
[ "python", "list", "numpy" ]
I have to change a list of values into multiple array set as shown below: ``` list_train_data = [u'Class 1', u'Class 2', u'Class 3', u'Class 4', u'Class 5'] ``` I need this value into an array like: ``` train_set = [['Class 1'],['Class 2'],['Class 3'],['Class 4'],['Class 5']] ``` If possible not use for loop.
Scince you added numpy tag, here is a numpy solution: ``` list_train_data = [u'Class 1', u'Class 2', u'Class 3', u'Class 4', u'Class 5'] import numpy as np np.array(list_train_data, "O")[:, None] ``` the result is: ``` array([[u'Class 1'], [u'Class 2'], [u'Class 3'], [u'Class 4'], [u...
Using CX_Freeze with Scipy: scipy.special._ufuncs.py
19,633,757
6
2013-10-28T11:35:39Z
22,352,558
8
2014-03-12T13:07:24Z
[ "python", "scipy", "cx-freeze" ]
I am having problems freezing a programm of mine. I narrowed it down to the scipy module. The porgramm I am trying to freeze is: ``` from scipy import signal signal.hann(1000) ``` My setup script is: ``` import sys from cx_Freeze import setup, Executable build_exe_options = {} base = None if sys.platform == "win32...
I had a similar problem which could be solved by making sure that: 1 The build directory contains a file named \_ufunc.pyd (instead of scipy.special.\_ufuncs.pyd as mentioned above). You can achieve this by specifying the build\_exe\_options: ``` build_exe_options = { 'packages': ['scipy'], "incl...
Installation of pygame with Anaconda
19,636,480
5
2013-10-28T13:47:07Z
32,699,498
8
2015-09-21T15:50:20Z
[ "python", "python-2.7", "pygame", "anaconda" ]
I have `Anaconda 1.6.2`, which uses `Python 2.7.5`, installed on a `Windows 7 64-bit` system. I need to install `Pygame 1.9.1` and this is not part of the `conda repository`. I cannot run the `Windows installer` because `Anaconda` has not made registry entries for `Python` and the `.msi` does not recognize the Py...
The easiest way to install Python using conda is: `conda install -c https://conda.binstar.org/krisvanneste pygame` ## Edit (03 / 2016): Actually It seems to be unable, but you can use this instead: `conda install -c https://conda.anaconda.org/tlatorre python`
Python - Get computer's IP address and host name on network running same application
19,636,817
6
2013-10-28T14:02:16Z
19,638,229
10
2013-10-28T15:02:57Z
[ "python", "windows", "networking", "ip-address" ]
**Just to be clear: I just started Python 2 weeks ago but I'm a C#, ASP, PHP, JavaScript developer.** I just started a new project with Python and PyQt and I want my project to be a server that will be able to communicate with other instance of this server on other computers. So, I need to get computers IP address an...
For the hostname and ip of the localhost you could use the socket module and gethostname, and gethostbyname methods: ``` import socket hostname = socket.gethostname() IP = socket.gethostbyname(hostname) ```
Python "with" statement syntax
19,638,887
7
2013-10-28T15:32:30Z
19,638,952
8
2013-10-28T15:35:15Z
[ "python", "with-statement" ]
I have some python code that parse the csv file. Now our vendor decide to change the data file to gzip csv file. I was wondering what's the minimal/cleanest code change I have to make. Current function: ``` def load_data(fname, cols=()): ... ... with open(fname) as f: reader = csv.DictReader(f) ...
You can do this by assigning the function you want to use to open the file to a different variable, depending on the properties of the file name: ``` opener = gzip.open if fname.endswith('.csv.gz') else open with opener(fname) as f: ... # code to parse ```
In Python, how do you generate permutations of an array where you only have one element from each column and row?
19,640,525
8
2013-10-28T16:48:24Z
19,640,615
18
2013-10-28T16:53:08Z
[ "python", "arrays", "algorithm", "permutation" ]
For example: Say you have the following array: ``` [1,2,3] [4,5,6] [7,8,9] ``` and you want to generate this array: ``` [1,5,9] [1,6,8] [4,2,9] [4,8,3] [7,2,6] [7,5,3] ```
``` import itertools A=[[1,2,3], [4,5,6], [7,8,9]] for P in itertools.permutations(range(len(A))): print [A[p][i] for i,p in enumerate(P)] ``` Prints: ``` [1, 5, 9] [1, 8, 6] [4, 2, 9] [4, 8, 3] [7, 2, 6] [7, 5, 3] ```
Python convert tuple to string
19,641,579
20
2013-10-28T17:45:06Z
19,641,614
46
2013-10-28T17:46:57Z
[ "python", "string", "tuples" ]
I have a tuple of characters like such: ``` ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') ``` How do I convert it to a string so that it is like: ``` 'abcdgxre' ```
Use [`str.join`](http://docs.python.org/2.7/library/stdtypes.html#str.join): ``` >>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') >>> ''.join(tup) 'abcdgxre' >>> >>> help(str.join) Help on method_descriptor: join(...) S.join(iterable) -> str Return a string which is the concatenation of the strings in the ...
Python convert tuple to string
19,641,579
20
2013-10-28T17:45:06Z
19,641,708
8
2013-10-28T17:52:27Z
[ "python", "string", "tuples" ]
I have a tuple of characters like such: ``` ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') ``` How do I convert it to a string so that it is like: ``` 'abcdgxre' ```
here is an easy way to use join. ``` ''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')) ```
Sorting a list of tuples with multiple conditions
19,643,099
4
2013-10-28T19:08:10Z
19,643,145
12
2013-10-28T19:10:41Z
[ "python", "list", "sorting", "tuples" ]
I am currently trying to sort the following list: ``` list_ = [(1, '0101'), (1, '1010'), (1, '101'), (2, '01'), (2, '010'), (2, '10')] ``` These are the steps I want to take in order to sort it: 1. Sort the list by the value of the first element of the tuples 2. Next, sort the list by the **length** of the second el...
The key function can return a tuple. ``` sorted_by_length = sorted(list_, key=lambda x: (x[0], len(x[1]), float(x[1]))) ``` This works because tuples are sorted lexicographically: (the first element of the tuple is used for sorting first, then the second element is used for breaking ties, and...
Launching a python script via a symbolic link
19,643,223
4
2013-10-28T19:15:22Z
19,800,587
7
2013-11-05T22:45:34Z
[ "python", "linux", "symlink", "getcwd" ]
I have an executable python script that exists in a "scripts" directory, and there's a symbolic link to that script (used to launch the file) in a root directory. Something like: ``` . ├── scripts │ ├── const.py │ ├── fops.py │ ├── i_build.py │ └── i_Props.ini └── bu...
You can use `__file__`, but you have to take some precautions to get the real path: ``` import os base_dir = os.path.dirname(os.path.realpath(__file__)) ``` Then load your other files / resources relative to base\_dir: ``` some_subdir = 'my_subdir' some_file = 'my.ini' ini_path = os.path.join(base_dir, some_subdir,...
Trying to get PyCharm to work, keep getting "No Python interpreter selected"
19,645,527
11
2013-10-28T21:36:35Z
19,676,884
18
2013-10-30T08:08:32Z
[ "python", "pycharm" ]
I'm trying to learn Python and decided to use PyCharm. When I try to start a new project I get a dialog that says "No Python interpreter selected". It has a drop down to select a interpreter, but the drop down is empty.
Your problem probably is that you haven't *installed* python. Meaning that, if you are using Windows, you have not downloaded the installer for Windows, that you can find on the official Python website. In case you have, chances are that PyCharm cannot find your Python installation because its not in the default locat...
Nesting the ternary operator in Python
19,646,056
3
2013-10-28T22:14:28Z
19,647,393
11
2013-10-29T00:09:33Z
[ "python", "nested-statement" ]
In the Zen of Python, Tim Peters states that `Flat is better than nested.`. If I have understood that correctly, then in Python, this: ``` <statement-1> if <condition> else <statement-2> ``` is generally preferred over this: ``` if <condition>: <statement-1> else: <statement-2> ``` However, in other languag...
Your *first* example (the horrid one-liner) is nested too. Horizontally nested. Your second example is vertically nested. They're *both* nested. So which is better? The second one! Why? Because "sparse is better than dense" breaks the tie. It's easy when you're Tim Peters - LOL ;-)
Unsuccessful append to an empty NumPy array
19,646,726
11
2013-10-28T23:08:15Z
19,647,414
12
2013-10-29T00:10:57Z
[ "python", "arrays", "numpy", "append" ]
I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error: My code is as follows: ``` import numpy as np result=np.asarray([np.asarray([]),np.asarray([])]) result[0]=np.append([result[0]],[1,2]) ``` And I am getting: ``` ValueError: could not broadcast input array from shape (...
`numpy.append` is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. `numpy.append` is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example: ``` import numpy old = numpy.array([1, ...
Unsuccessful append to an empty NumPy array
19,646,726
11
2013-10-28T23:08:15Z
19,701,735
24
2013-10-31T08:38:52Z
[ "python", "arrays", "numpy", "append" ]
I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error: My code is as follows: ``` import numpy as np result=np.asarray([np.asarray([]),np.asarray([])]) result[0]=np.append([result[0]],[1,2]) ``` And I am getting: ``` ValueError: could not broadcast input array from shape (...
I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful: **Initialise empty array:** ``` >>> a = np.array([]).reshape(0,3) >>> a array([], shape=(0, 3), dtype=float64) ``` Now you can use this array to append rows of ...
Pip freeze gives me this error related with git
19,647,028
6
2013-10-28T23:32:40Z
19,652,542
7
2013-10-29T07:53:05Z
[ "python", "git", "heroku", "turbogears", "turbogears2" ]
I am working with python and git on a simple Turbogears2 project that I've built just for fun. In a certain moment I want to deploy it to Heroku, so I do the usual `pip freeze > requirements.txt` and I get this error: ``` Error when trying to get requirement for VCS system Command /usr/bin/git config remote.origin.url...
Your git repository doesn't have an "origin" so pip is unable to detect the remote url of the repository. This should have been already fixed in PIP as stated in <https://github.com/pypa/pip/issues/58> Try to upgrade pip or add a remote origin to your git repository
Django: Can you tell if a related field has been prefetched without fetching it?
19,649,370
7
2013-10-29T03:54:35Z
19,651,840
13
2013-10-29T07:10:12Z
[ "python", "django" ]
I was wondering if there is a way in Django to tell if a related field, specifically the "many" part of a one-to-many relationship, has been fetched via, say, `prefetch_related()` without actually fetching it? So, as an example, let's say I have these models: ``` class Question(Model): """Class that represents a qu...
Yes, Django stores the prefetched results in the `_prefetched_objects_cache` attribute of the parent model instance. So you can do something like: ``` instance = Parent.objects.prefetch_related('children').all()[0] try: instance._prefetched_objects_cache[instance.children.prefetch_cache_name] # Ok, it's pefe...
How can I escape the format string?
19,649,427
5
2013-10-29T04:01:59Z
19,649,434
11
2013-10-29T04:03:07Z
[ "python", "string", "string.format" ]
Is it possible to use Python's `str.format(key=value)` syntax to replace only certain keys. Consider this example: ``` my_string = 'Hello {name}, my name is {my_name}!' my_string = my_string.format(name='minerz029') ``` which returns ``` KeyError: 'my_name' ``` Is there a way to achieve this?
You can escape `my_name` using double curly brackets, like this ``` >>> my_string = 'Hello {name}, my name is {{my_name}}!' >>> my_string.format(name='minerz029') 'Hello minerz029, my name is {my_name}!' ``` As you can see, after formatting once, the outer `{}` is removed and `{{my_name}}` becomes `{my_name}`. If you...
Saving Image with PIL
19,651,055
7
2013-10-29T06:18:12Z
19,651,233
12
2013-10-29T06:30:10Z
[ "python", "python-imaging-library" ]
I am trying to save an image that I created from scratch with PIL ``` newImg1 = PIL.Image.new('RGB', (512,512)) pixels1 = newImg1.load() ... for i in range (0,511): for j in range (0,511): ... pixels1[i, 511-j]=(0,0,0) ... newImg1.PIL.save("img1.png") ``` and I get the following erro...
PIL isn't an attribute of newImg1 but newImg1 is an instance of PIL.Image so it has a save method, thus the following should work. ``` newImg1.save("img1.png","PNG") ``` Note that just calling a file .png doesn't make it one so you need to specify the file format as a second parameter. try: ``` type(newImg1) dir(ne...
What is a "runtime context"?
19,652,662
6
2013-10-29T07:59:56Z
19,652,828
7
2013-10-29T08:10:07Z
[ "c++", "python", "c" ]
(Edited for even more clarity) I'm reading the Python book (*Python Essential Reference by Beazley*) and he says: > The `with` statement allows a series of statements to execute inside a > *runtime context* that is controlled by an object that serves as a context manager. > > Here is an example: > > ``` > with open("...
The `with` statement was introduced in PEP 343. This PEP also introduced a new term, "context manager", and defined what that term means. Briefly, a "context manager" is an object that has special method functions `.__enter__()` and `.__exit__()`. The `with` statement guarantees that the `.__enter__()` method will be ...
Why does chardet say my UTF-8-encoded string (originally decoded from ISO-8859-1) is ASCII?
19,652,939
6
2013-10-29T08:17:49Z
19,653,131
7
2013-10-29T08:29:32Z
[ "python", "encoding", "utf-8", "ascii", "decoding" ]
I'm trying to convert ascii characters to utf-8. This little example below still returns ascii characters: ``` chunk = chunk.decode('ISO-8859-1').encode('UTF-8') print chardet.detect(chunk[0:2000]) ``` It returns: ``` {'confidence': 1.0, 'encoding': 'ascii'} ``` How come?
Quoting from Python's [documentation](http://docs.python.org/2/howto/unicode.html#encodings): > UTF-8 has several convenient properties: > > 1. It can handle any Unicode code point. > 2. A Unicode string is turned into a string of bytes containing no embedded zero bytes. This avoids byte-ordering issues, and means UTF...
Python UTC datetime object's ISO format dont include Z (Zulu or Zero offset)
19,654,578
26
2013-10-29T09:42:06Z
23,705,687
17
2014-05-16T22:54:38Z
[ "python", "python-2.7", "datetime", "timestamp", "iso8601" ]
Anybody knows why python 2.7 don't include Z character (Zulu or zero offset) at the end of UTC datetime object's isoformat string unlike JavaScript? ``` >>> datetime.datetime.utcnow().isoformat() '2013-10-29T09:14:03.895210' ``` Whereas in javascript ``` >>> console.log(new Date().toISOString()); 2013-10-29T09:38:...
Python `datetime` objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification ([if no time zone info is given, assumed to be local time](http://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators)). You can use the [pytz package](https://pypi.python.org/pypi/pytz/)...
How to get filename with argparse while specifying type=FileType(...) for this argument
19,656,426
6
2013-10-29T11:03:21Z
19,656,475
9
2013-10-29T11:05:32Z
[ "python", "argparse" ]
Using the `type` parameter of the `argparse.add_argument` method, you can require an argument to be a readable file: ``` parser.add_argument('--sqlite-file', type=argparse.FileType('r')) ``` As a benefit of specifying this type, argparse checks whether the file can be read and displays an error to the user if not. I...
Yes, use the [`.name` attribute](http://docs.python.org/3/library/io.html#io.FileIO.name) on the file object. Demo: ``` >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--sqlite-file', type=argparse.FileType('r')) _StoreAction(option_strings=['--sqlite-file'], dest='sqlite_file', na...
"Expected an indented block" error?
19,657,576
5
2013-10-29T11:57:44Z
19,657,678
16
2013-10-29T12:02:08Z
[ "python", "indentation", "docstring" ]
I can't understand why python gives an "Expected indentation block" error? ``` """ This module prints all the items within a list""" def print_lol(the_list): """ The following for loop iterates over every item in the list and checks whether the list item is another list or not. in case the list item is another list it...
You have to indent the docstring after the function definition there (line 3, 4): ``` def print_lol(the_list): """this doesn't works""" print 'Ain't happening' ``` Indented: ``` def print_lol(the_list): """this works!""" print 'Aaaand it's happening' ``` Or you can use `#` to comment instead: ``` def p...
Replace numbers in string by respective result of a substraction
19,660,224
4
2013-10-29T13:56:02Z
19,660,903
11
2013-10-29T14:22:34Z
[ "python", "regex", "string", "parsing", "replace" ]
I have a string like this: ``` "foo 15 bar -2hello 4 asdf+2" ``` I'd like to get: ``` "foo 14 bar -3hello 3 asdf+1" ``` I would like to replace every number (sequence of digits as signed base-10 integers) with the result of a subtraction executed on each of them, one for each number. I've written a ~50 LOC functio...
You could try using regex, and using [`re.sub`](http://docs.python.org/2.7/library/re.html#re.sub): ``` >>> pattern = "(-?\d+)|(\+1)" >>> def sub_one(match): return str(int(match.group(0)) - 1) >>> text = "foo 15 bar -2hello 4 asdf+2" >>> re.sub(pattern, sub_one, text) 'foo 14 bar -3hello 3 asdf+1' ``` The r...
AES Python encryption and Ruby encryption - different behaviour?
19,661,508
6
2013-10-29T14:48:08Z
19,663,901
8
2013-10-29T16:25:53Z
[ "python", "ruby", "encryption", "aes" ]
From [this](https://pypi.python.org/pypi/pycrypto) site I have this code snippet: ``` >>> from Crypto.Cipher import AES >>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456') >>> message = "The answer is no" >>> ciphertext = obj.encrypt(message) >>> list(bytearray(ciphertext)) [214, 131, 141, 100, 33,...
This is understandably confusing—PyCrypto has gone a bit off the rails here and broken with the usual implementation. If you're familiar enough with what encrypted data should normally look like, the Python output *looks* blatantly wrong and gives you a place to start. If you're not, it's easy to wonder what the heck...
Python prompt for user with echo and password without echo
19,661,956
2
2013-10-29T15:06:53Z
19,661,976
7
2013-10-29T15:07:59Z
[ "python", "python-2.7" ]
Following code prompts for user and password, when run in console: ``` import getpass user = getpass.getpass("Username:") passwd = getpass.getpass("Password for " + user + ":") print "Got", user, passwd ``` The obvious problem with above is, user name is not echoed as it is typed. Now [`getpass` documentation](htt...
Use [`raw_input`](http://docs.python.org/2/library/functions.html#raw_input) instead of `getpass.getpass` for username. ``` user = raw_input("Username:") ```
Python prompt for user with echo and password without echo
19,661,956
2
2013-10-29T15:06:53Z
19,662,005
7
2013-10-29T15:08:52Z
[ "python", "python-2.7" ]
Following code prompts for user and password, when run in console: ``` import getpass user = getpass.getpass("Username:") passwd = getpass.getpass("Password for " + user + ":") print "Got", user, passwd ``` The obvious problem with above is, user name is not echoed as it is typed. Now [`getpass` documentation](htt...
Why not just use [`raw_input`](http://docs.python.org/2.7/library/functions.html#raw_input) for the username: ``` import getpass user = raw_input("Username:") passwd = getpass.getpass("Password for " + user + ":") print("Got", user, passwd) ``` Demo: ``` Username:iCodez Password for iCodez: ('Got', 'iCodez', 'secr...
selenium how to get the content of href within some targeted class
19,664,253
10
2013-10-29T16:43:03Z
19,664,685
18
2013-10-29T17:03:20Z
[ "python", "html", "css", "xpath", "selenium" ]
I am trying to retrieve the data from the webpage has the html in below ``` <div class="someclass"> <p class="name"><a href="#/word/1/">helloworld</a></p> </div> ``` My goal is to parse "#/word/1/" What I did is ``` target = self.driver.find_element_by_class_name('someclass') pri...
As far as I am aware you can get the href by searching through the child elements ``` div = self.driver.find_element_by_class_name('someclass') div.find_element_by_css_selector('a').get_attribute('href') ```
Using empty tuple as default iterable argument in function
19,665,110
8
2013-10-29T17:24:00Z
19,665,231
8
2013-10-29T17:30:08Z
[ "python" ]
Are there any downsides to using an empty tuple as a default for an iterable argument to a function? Assuming that what you want in the function is an immutable iterable. e.g. ``` def foo(a, b=()): print a for x in b: print x ``` I can't seem to find many examples of this use case.
I can't think of any downsides, for when you need an immutable iterable. I think it just isn't used because the `default_list=None` and `default_list = default_list or None` pattern is what is used for mutable iterables, and people don't bother to change it (as there is no real need) in the less frequently occuring cas...
Replace all elements of Python NumPy Array that are greater than some value
19,666,626
43
2013-10-29T18:42:54Z
19,666,680
71
2013-10-29T18:46:06Z
[ "python", "arrays", "numpy", "replace", "condition" ]
I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be: ``` shape = arr.shape result = np.zeros(shape) for x in range(0, shape[0]): for y in range(0, shape[1]): if arr[x, y] >= T: r...
I think both the fastest and most concise way to do this is to use Numpy's builtin indexing. If you have a `ndarray` named `arr` you can replace all elements `>255` with a value `x` as follows: ``` arr[arr > 255] = x ``` I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it...
Replace all elements of Python NumPy Array that are greater than some value
19,666,626
43
2013-10-29T18:42:54Z
19,667,760
21
2013-10-29T19:47:26Z
[ "python", "arrays", "numpy", "replace", "condition" ]
I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be: ``` shape = arr.shape result = np.zeros(shape) for x in range(0, shape[0]): for y in range(0, shape[1]): if arr[x, y] >= T: r...
Since you actually want a different array which is `arr` where `arr < 255`, and `255` otherwise, this can be done simply: ``` result = np.minimum(arr, 255) ``` More generally, for a lower and/or upper bound: ``` result = np.clip(arr, 0, 255) ``` If you just want to access the values over 255, or something more comp...
Swapping numbers in lists
19,666,772
3
2013-10-29T18:51:54Z
19,666,782
15
2013-10-29T18:52:38Z
[ "python", "list", "python-2.7", "python-3.x", "swap" ]
How can I go about swapping numbers in a given list? For example: ``` list = [5,6,7,10,11,12] ``` I would like to swap `12` with `5`. Is there an built-in Python function that can allow me to do that?
``` >>> lis = [5,6,7,10,11,12] >>> lis[0], lis[-1] = lis[-1], lis[0] >>> lis [12, 6, 7, 10, 11, 5] ``` [Order of evaluation](http://docs.python.org/2/reference/expressions.html#evaluation-order) of the above expression: ``` expr3, expr4 = expr1, expr2 ``` First items on RHS are collected in a tuple, and then that [t...
Is there any reason to use dict instead of defaultdict?
19,666,783
3
2013-10-29T18:52:43Z
19,666,812
9
2013-10-29T18:54:15Z
[ "python", "dictionary" ]
The title says it all: **Is there any reason to use dict instead of [defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict)?** The only reason I can think of is "I really don't need it". But then I could ask if there is any reason why dict is not replaced by defaultdict. Possible rea...
Plenty of reasons **not** to use a `defaultdict`: * if your values are not homogenous and thus cannot be generated by a simple factory function. * if you *need* missing keys to raise an exception instead of creating a new value for you automatically. * If all your default values require more context than the factory f...
Python/Numpy: How do you assign the end+1 element of an array similar to how it's done in Matlab?
19,666,989
3
2013-10-29T19:03:46Z
19,667,038
7
2013-10-29T19:06:16Z
[ "python", "arrays", "matlab", "numpy" ]
For example, for a 1D array with n elements, if I want to do this in Matlab I can do: A(end+1) = 1 that assigns the value of 1 to the last element of array A which is now n+1 in length. Is there an equivalent in Python/Numpy?
You can just append a value to the end of an array/list using `append` or `numpy.append`: ``` # Python list a = [1, 2, 3] a.append(1) # => [1, 2, 3, 1] # Numpy array import numpy as np a = np.array([1, 2, 3]) a = np.append(a, 1) # => [1, 2, 3, 1] ``` Note, as pointed out by @BrenBarn, that the `numpy.append` approac...
Str.format() for Python 2.6 gives error where 2.7 does not
19,668,395
9
2013-10-29T20:26:11Z
19,668,429
15
2013-10-29T20:28:01Z
[ "python", "python-2.7", "python-2.6" ]
I have some code which works well in Python 2.7. ``` Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import stdout >>> foo = 'Bar' >>> numb = 10 >>> stdout.write('{} {}\n'.format(numb, foo)) 10 Bar >>> ``` But in ...
Python 2.6 and before (as well as Python 3.0) *require* that you number the placeholders: ``` '{0} {1}\n'.format(numb, foo) ``` The numbering, if omitted in Python 2.7 and Python 3.1 and up, is implicit, see the [documentation](http://docs.python.org/2/library/string.html#format-string-syntax): > *Changed in version...
Generating multiple random (x, y) coordinates, excluding duplicates?
19,668,463
18
2013-10-29T20:30:18Z
19,668,720
8
2013-10-29T20:44:28Z
[ "python", "math", "random", "coordinates" ]
I want to generate a bunch (x, y) coordinates from 0 to 2500 that excludes points that are within 200 of each other without recursion. Right now I have it check through a list of all previous values to see if any are far enough from all the others. This is really inefficient and if I need to generate a large number of...
This is a variant on Hank Ditton's suggestion that should be more efficient time- and memory-wise, especially if you're selecting relatively few points out of all possible points. The idea is that, whenever a new point is generated, everything within 200 units of it is added to a set of points to exclude, against which...
Python import from parent directory
19,668,729
12
2013-10-29T20:45:14Z
19,669,773
18
2013-10-29T21:44:03Z
[ "python" ]
I have the following: ``` ModuleFolder | |-->. ModuleFile.py . | '-->. TestsFolder . | '---> UnitTest1.py ``` I'm trying to import from the parent directory. In this case I am trying to run "UnitTest1.py...
Don't run the test from the tests folder. Run it from the root of your project, which is the module folder. You should very rarely need to muck with *either* `sys.path` or `PYTHONPATH`, and when you do, you're either causing bugs for other libraries down the road or making life harder on your users. ``` python -m Test...
Bundling Data files with PyInstaller 2.1 and MEIPASS error --onefile
19,669,640
10
2013-10-29T21:35:34Z
20,088,482
11
2013-11-20T05:56:23Z
[ "python", "build", "environment-variables", "exe", "pyinstaller" ]
This [question](http://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile/13790741#13790741) has been asked before and I can't seem to get my PyInstaller to work correctly. I have invoked the following code in my mainscript.py file: ``` def resource_path(relative_path): """ Get absolu...
I think I see the problem. You're not feeding data\_files into your Analysis object. Here's how I add my data files in my .spec file: ``` a = Analysis(....) a.datas += [('7z.dll', '7z.dll', 'DATA')] a.datas += [('7z.exe', '7z.exe', 'DATA')] a.datas += [('collection.xml', 'collection.xml', 'DATA')] a.datas += [('Licens...
Assign different tasks to different celery workers
19,670,534
7
2013-10-29T22:41:12Z
19,670,799
8
2013-10-29T23:04:49Z
[ "python", "celery" ]
I am running my server using this command: ``` celery worker -Q q1,q2 -c 2 ``` which shows that my server will handle all the tasks on queues `q1` and `q2`, and I have 2 workers running. My server should support 2 different tasks: ``` @celery.task(name='test1') def test1(): print "test1" time.sleep(3) @cele...
I found the answer and I am putting it here in case someone else wanted to do the same: Instead of using `celery worker -Q q1,q2 -c 2`, `celery multi` could be used: ``` celery multi start 2 -Q:1 q1 -Q:2 q2 -c:1 1 -c:2 1 ``` Which says that we have 2 queues: `-Q:1 q1` means queue #1 with name of `q1` and same for `q...
Trying to drop NaN indexed row in dataframe
19,670,904
4
2013-10-29T23:13:41Z
19,671,394
7
2013-10-29T23:57:13Z
[ "python", "pandas", "dataframe" ]
I'm using python 2.7.3 and Pandas version 0.12.0. I want to drop the row with the NaN index so that I only have valid site\_id values. ``` print df.head() special_name site_id NaN Banana OMG Apple df.drop(df.index[0]) TypeError: 'NoneType' object is not iterable ``` If I try dropping ...
I've found that the easiest way is to reset the index, drop the NaNs, and then reset the index again. ``` In [26]: dfA.reset_index() Out[26]: index special_name 0 NaN Apple 1 OMG Banana In [30]: df = dfA.reset_index().dropna().set_index('index') In [31]: df Out[31]: special_name index ...
Use tornado async code in a regular python script
19,671,084
4
2013-10-29T23:29:28Z
19,695,677
12
2013-10-30T23:21:38Z
[ "python", "asynchronous", "tornado", "coroutine" ]
I have some asynchronous functions using [tornado `gen.coroutine`](http://www.tornadoweb.org/en/stable/gen.html) that I normally use as part of a tornado-based web application. However, I want to call some of them from a plain old python script to do some administration tasks. How do I do this? ``` from tornado import...
There's a built-in method `run_sync` in `IOLoop` to run a single call and then stop the loop, so it's pretty trivial to just add an event loop to a plain python script provided you have tornado in the PYTHONPATH. With the concrete example: ``` from tornado import gen, ioloop @gen.coroutine def another_async_func(x):...
How to run python script with elevated privilege on windows
19,672,352
23
2013-10-30T01:41:19Z
19,719,292
35
2013-11-01T01:06:42Z
[ "python", "windows", "admin", "elevated-privileges" ]
I am writing a pyqt application which require to execute admin task. I would prefer to start my script with elevate privilege. I am aware that this question is asked many times in SO or in other forum. But the solution people are suggesting is to have a look at this SO question [Request UAC elevation from within a Pyth...
Thank you all for your reply. I have got my script working with the module/ script written by Preston Landers way back in 2010. After two days of browsing the internet I could find the script as it was was deeply hidden in pywin32 mailing list. With this script it is easier to check if the user is admin and if not then...
Error: No Commands supplied when trying to install pyglet
19,672,690
3
2013-10-30T02:21:44Z
19,672,752
13
2013-10-30T02:28:08Z
[ "python" ]
I have downloaded pyglet, but when I run the "setup.py" thing, it just says this in the command line: > Traceback (most recent call last): > > File "C:\PythonX\Include\pyglet\pyglet-1.1.4\setup.py", line 285, in > > ``` > setup(**setup_info) > ``` > > File "C:\Python27\lib\distutils\core.py", line 140, in setup > > ``...
If you just did `python setup.py`, you'll get this - you need to type `python setup.py build` followed by `python setup.py install`. As you are on Windows; even the above commands may not work correctly. In that case, you can [download the Windows installer version](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyglet) w...
How to write a cell with multiple columns in xlwt?
19,672,760
17
2013-10-30T02:28:46Z
19,673,269
35
2013-10-30T03:26:34Z
[ "python", "excel", "xlwt" ]
I'd like to write a table like this: ``` ---------------- | Long Cell | ---------------- | 1 | 2 | ---------------- ``` How to write the cell `Long Cell`? Thanks. I've tried to do it like this: ``` sheet.write(0, 0, 'Long Cell') sheet.write(1, 0, 1) sheet.write(1, 1, 2) ``` But it end up like: ``` -----...
As far as I can tell, this isn't documented - you have to read the source code to find it. There are two methods on the `Worksheet` class to do this, `write_merge` and `merge`. `merge` takes existing cells and merges them, while `write_merge` writes a label (just like `write`) and then does the same stuff `merge` does....
Can you set conditional dependencies for Python 2 and 3 in setuptools?
19,672,980
13
2013-10-30T02:52:26Z
19,719,657
12
2013-11-01T01:58:12Z
[ "python", "dependency-management", "setuptools" ]
When releasing a Python egg with support for both Python 2 and 3, can you specify dependencies that change depending on which version you're using? For example, if you use `dnspython` for Python 2, there is a Python 3 version that is called `dnspython3`. Can you write your `setuptools.setup()` function in such a way t...
Bogdan's comment helped point me on my way. I thought I'd post what I did in case anyone else has my problem. For the example in the question, I did exactly what Bogdan suggested: ## setup.py ``` import sys if sys.version_info[0] == 2: dnspython = "dnspython" elif sys.version_info[0] == 3: dnspython = "dnsp...
import error in celery
19,673,662
13
2013-10-30T04:09:16Z
20,548,252
24
2013-12-12T16:03:06Z
[ "python", "celery", "pycharm", "celery-task" ]
this is the code which i am running: ``` from __future__ import absolute_import from celery import Celery celery1 = Celery('celery',broker='amqp://',backend='amqp://',include=['tasks']) celery1.conf.update( CELERY_TASK_RESULT_EXPIRES=3600, ) if __name__ == '__main__': celery1.start() ``` when i execute th...
I ran into this same error as well and renaming the file fixed it. For anyone else encountering this, the reason WHY you get this issue, your local celery.py is getting imported instead of the actual celery package, hence the reason python can't find Celery(capital "C"), as in the class within the celery package, but ...
JSON serializing Mongodb
19,674,311
11
2013-10-30T05:09:45Z
19,674,373
19
2013-10-30T05:17:46Z
[ "python", "mongodb", "pymongo", "rpython" ]
I am using the python package pymongo to retrieve data from a mongodb database. ``` >>> r = collection.find() # returns an object of class 'Cursor' ``` Then I convert to a list ``` >>> l = list(r) # returns a 'list' of 'dict' ``` here is what print(l) returns: ``` >>> [{u'date': datetime.datetime(200...
The pymongo documentation you pointed is obsolete. If you're using version 1.7 I recommend updating. With a more recent version you can do this: ``` from bson.json_util import dumps dumps(l) ``` <http://api.mongodb.org/python/current/api/bson/json_util.html> **Side answer**: `u'name'`, `u'date'`, `u'_id'` etc are t...
Matplotlib output not showing up inline in IPython Notebook despite --pylab inline option
19,675,235
6
2013-10-30T06:23:25Z
19,676,283
7
2013-10-30T07:30:09Z
[ "python", "matplotlib", "ipython-notebook" ]
I'm starting an IPython Notebook and the matplotlib output does not appear inline, but instead like this: ``` <matplotlib.figure.Figure at 0x113035310> ``` Here's the code: ``` from pylab import * X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C,S = np.cos(X), np.sin(X) plot(X,C) plot(X,S) show() ``` The notebo...
It turns out that inline display (and probably even generating the image in the first place) was failing because matplotlib was unable to load the `Vera.ttf` font file. It attempted to load that file from the wrong file system location, one that wasn't accessible to the process, which was running in an OS X sandbox. `...