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
Convert a string key to int in a Dictionary
21,193,682
6
2014-01-17T18:56:07Z
21,193,744
14
2014-01-17T18:59:49Z
[ "python", "json", "dictionary" ]
My question is very similar to [this one](http://stackoverflow.com/questions/5316720/python-how-to-convert-a-list-of-dictionaries-values-into-int-float-from-string), except I have a dictionary of lists and I'm interested in changing both the key value and all elements in every list form `string` to `int`. So for insta...
``` d = {'1':'145' , '2':'254' , '3':'43'} d = {int(k):int(v) for k,v in d.items()} >>> d {1: 145, 2: 254, 3: 43} ``` for lists in values ``` >>> d = { '1':['1', '2', '3', '4'] , '2':['1', '4'] , '3':['43','176'] } >>> d = {int(k):[int(i) for i in v] for k,v in d.items()} ``` in your case: ``` coautorshipDictionary...
Is subprocess.Popen not thread safe?
21,194,380
9
2014-01-17T19:36:22Z
25,213,194
11
2014-08-08T22:33:19Z
[ "python", "concurrency", "thread-safety", "subprocess", "popen" ]
The following simple script hangs on the subprocess.Popen call intermittently (roughly 30% of the time). Unless use\_lock = True, and then it never hangs, leading me to believe subprocess is not thread safe! The expected behavior is script finishes within 5-6 seconds. To demonstrate the bug, just run "python bugPro...
On Python 2.x, there are various race conditions affecting subprocess.Popen. (e.g. on 2.7 it disables & restores garbage collection to prevent various timing issues, but this is not thread-safe in itself). See e.g. <http://bugs.python.org/issue2320>, <http://bugs.python.org/issue1336> and <http://bugs.python.org/issue1...
Installing Pydev for Eclipse throws error
21,194,902
3
2014-01-17T20:06:30Z
21,198,320
7
2014-01-18T00:13:38Z
[ "python", "eclipse", "ubuntu", "pydev" ]
I installed Eclipse. After which I started Eclipse clicked on menu *Help* -> *Install New software* and entered the Pydev repositories. I clicked the Pydev for Eclipse from the list of software and clicked "Next". Eclipse displayed the license information at which point I accepted the terms and clicked "Next". During i...
I solved the problem this way (running Eclipse 3.7 on [Ubuntu 12.04](http://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_12.04_LTS_.28Precise_Pangolin.29) (Precise Pangolin)): On the installation dialog, I unchecked the box "Show only the latest versions of available software" and selected the PyDev 2.8.2 versi...
Django rest framework api_view vs normal view
21,195,821
11
2014-01-17T21:03:16Z
21,246,945
7
2014-01-21T00:32:16Z
[ "python", "django", "api", "view", "django-rest-framework" ]
I have been looking everywhere to find a decent explanation for this, and they all come short...**When do you use the @api\_view decorator rather than a class based view with the [django rest framework app](http://www.django-rest-framework.org/)**
REST Framework aside, it's the same question of when to use class based views versus function based views in general. CBVs in Django are awesome, flexible and save loads of boilerplate code, but sometimes it's just faster, easier and clearer to use a function based view. Think about it with the same approach you'd take...
python how to print space per n'th char
21,196,761
2
2014-01-17T22:01:26Z
21,196,813
7
2014-01-17T22:05:15Z
[ "python" ]
I have a big number in a variable, what I want is that every 5'th is separated ba a space Code: ``` number = 123456789012345678901234567890 print "the number is:", number #Devide every 5'th ``` The output I want is: ``` The number is: 12345 67890 12345 67890 12345 67890 ```
``` In [1]: number = 123456789012345678901234567890 In [2]: num = str(number) In [3]: print ' '.join(num[i:i+5] for i in xrange(0,len(num),5)) 12345 67890 12345 67890 12345 67890 ```
Assign pandas dataframe column dtypes
21,197,774
28
2014-01-17T23:16:27Z
21,197,863
18
2014-01-17T23:26:04Z
[ "python", "pandas" ]
I want to set the `dtype`s of multiple columns in `pd.Dataframe` (I have a file that I've had to manually parse into a list of lists, as the file was not amenable for `pd.read_csv`) ``` import pandas as pd print pd.DataFrame([['a','1'],['b','2']], dtype={'x':'object','y':'int'}, c...
You can use [`convert_objects`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html) to infer better dtypes: ``` In [11]: df Out[11]: x y 0 a 1 1 b 2 In [12]: df.dtypes Out[12]: x object y object dtype: object In [13]: df.convert_objects(convert_numeric=True) O...
Assign pandas dataframe column dtypes
21,197,774
28
2014-01-17T23:16:27Z
36,184,396
8
2016-03-23T17:02:54Z
[ "python", "pandas" ]
I want to set the `dtype`s of multiple columns in `pd.Dataframe` (I have a file that I've had to manually parse into a list of lists, as the file was not amenable for `pd.read_csv`) ``` import pandas as pd print pd.DataFrame([['a','1'],['b','2']], dtype={'x':'object','y':'int'}, c...
For those coming from Google (etc.) such as myself: [`convert_objects`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.convert_objects.html) has been deprecated - if you use it, you get a warning like this one: ``` FutureWarning: convert_objects is deprecated. Use the data-type specific conve...
Python multiprocessing example not working
21,198,857
4
2014-01-18T01:16:15Z
21,199,005
8
2014-01-18T01:41:44Z
[ "python", "multiprocessing" ]
I am trying to learn how to use `multiprocessing`but I can't get it to work. Here is the code right out of the [documentation](http://docs.python.org/2/library/multiprocessing.html "documentation") ``` from multiprocessing import Process def f(name): print 'hello', name if __name__ == '__main__': p = Process...
My guess is that you are using IDLE to try to run this script. Unfortunately, this example will not run correctly in IDLE. Note the comment at the beginning of [the docs](http://docs.python.org/2.7/library/multiprocessing.html#introduction): > Note Functionality within this package requires that the **main** > module ...
Custom user model in django
21,199,735
11
2014-01-18T03:43:31Z
21,199,846
8
2014-01-18T04:02:47Z
[ "python", "django", "model-view-controller", "django-models" ]
I want to create a custom user model using `django.contrib.auth.models.AbstractUser` as stated in the djangodocs: > If you’re entirely happy with Django’s User model and you just want to > add some additional profile information, you can simply subclass > django.contrib.auth.models.AbstractUser and add your custom...
I did this in one of my project. I was surprised to see that you extended User because [the doc says something else](https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#extending-the-existing-user-model) :) You **can** extend Django User model, but if you only want to add new fields (not change its behavior)...
Anaconda not finding my packages installed with `pip`
21,201,003
15
2014-01-18T06:42:04Z
21,201,451
15
2014-01-18T07:40:20Z
[ "python", "pip", "anaconda" ]
I'm new to Anaconda version of Python, and already I'm running into unpleasant problems. I installed Anaconda per [the instructions here](http://continuum.io/downloads), and it worked like charm, with all the included packages imported properly when demanded. Then I went on to install some extra packages which Anacond...
In the comments, it was determined that the `pip` in use was `/usr/bin/pip`; in other words, the system `pip`. The system `pip` will install into the system `site-packages`, not Anaconda's `site-packages`. The solution is to make sure you're using Anaconda's `pip` when installing packages for use with Anaconda.
Twilio Python Module Errors After Compiling
21,201,238
4
2014-01-18T07:14:46Z
21,206,079
14
2014-01-18T15:28:05Z
[ "python", "sms", "twilio" ]
I have written a simple program that opens a csv file and text all the numbers in it. I am using Twilio ([twilio-python](https://www.twilio.com/docs/python/install)) as a service provider. My code works fine as a python script. However, when I compile the script (using py2exe), the exe file errors. This is the error I ...
It's happened because `self-signed certificate` file missed in bundle. This problem is same for `requests` and `httplib2` modules. For example, if you have a file named `req_example.py` that using `request` module: ``` import requests url = 'https://google.com/' requests.get(url) ``` It works when you run it as `py...
pandas.merge: match the nearest time stamp >= the series of timestamps
21,201,618
10
2014-01-18T08:00:49Z
21,204,417
19
2014-01-18T12:57:52Z
[ "python", "pandas" ]
I have two dataframes, both of which contain an irregularly spaced, millisecond resolution timestamp column. My goal here is to match up the rows so that for each matched row, 1) the first time stamp is always smaller or equal to the second timestamp, and 2) the matched timestamps are the closest for all pairs of times...
`merge()` can't do this kind of join, but you can use `searchsorted()`: Create some random timestamps: `t1`, `t2`, there are in ascending order: ``` import pandas as pd import numpy as np np.random.seed(0) base = np.array(["2013-01-01 00:00:00"], "datetime64[ns]") a = (np.random.rand(30)*1000000*1000).astype(np.int...
How to redirect the raw_input to stderr not stdout
21,202,403
5
2014-01-18T09:39:10Z
21,203,064
10
2014-01-18T10:48:08Z
[ "python", "python-2.x" ]
I want to redirect the `stdout` to a file. But This will affect the `raw_input`. I need to redirect the output of `raw_input` to `stderr` instead of `stdout`. How Can I do that thing
The only problem with `raw_input` is that it prints the prompt to stdout. Instead of trying to intercept that, why not just print the prompt yourself, and call `raw_input` with no prompt, which prints nothing to stdout? ``` def my_input(prompt=None): if prompt: sys.stderr.write(str(prompt)) return raw_...
Python string with space and without space at the end and immutability
21,203,212
8
2014-01-18T11:03:48Z
21,203,303
10
2014-01-18T11:13:06Z
[ "python", "string", "immutability", "python-internals" ]
I learnt that in immutable classes, `__new__` may return a cached reference to an existing object with the same value; this is what the int, str and tuple types do for small values. This is one of the reasons why their `__init__` does nothing. So, cached objects would be re-initialized over and over. But how the follo...
This is a quirk of how Python chooses to cache string literals. String literals with the same contents may refer to the same string object, but they don't have to. `'string'` happens to be automatically interned when `'string '` isn't because `'string'` contains only characters allowed in a Python identifier. I have no...
Generating random sequences of DNA
21,205,836
2
2014-01-18T15:06:21Z
21,205,929
7
2014-01-18T15:14:27Z
[ "python" ]
I am trying to generate random sequences of DNA in python using random numbers and random strings. But i am getting only one string as my output. For example : If i give DNA of length 5(String(5)) i should get an output "CTGAT".Similarly if I give String(4) it should give me "CTGT". But i am getting "G" or "C" or "T" o...
I'd generate the string all in one go, rather than build it up. Unless Python's being clever and optimising the string additions, it'll reduce the runtime complexity from quadratic to linear. ``` import random def DNA(length): return ''.join(random.choice('CGTA') for _ in xrange(length)) print DNA(5) ```
write to csv from DataFrame python pandas
21,206,395
5
2014-01-18T15:58:05Z
21,207,957
7
2014-01-18T18:15:15Z
[ "python", "python-2.7", "csv", "io", "pandas" ]
I wrote a program where i add two columns and write the answer to CSV file but I am getting error when I want to write only selection of columns . here is my logic: ``` import pandas as pd df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar'], 'B'...
A and B are no longer columns, since you called `groupby(['A', 'B'])`. Instead they are both an index. Try leaving out the `index=False`, like this: ``` a.to_csv("test.csv", cols=['sum']) ```
SQLAlchemy, Flask: get relationships from a db.Model
21,206,818
7
2014-01-18T16:36:40Z
21,209,747
13
2014-01-18T20:55:45Z
[ "python", "sqlalchemy", "flask" ]
I need to get a list of a model's properties which are actually relationships (that is, they were created by `relationship()`). Say I have a model `Foo` in a `models`: ``` class Thing(db.Model): id = db.Column(...) bar_id = db.Column(...) foo_id = db.Column(...) foo = db.relationship('Foo') bar = ...
There is indeed - take a look at [`sqlalchemy.inspection.inspect`](http://docs.sqlalchemy.org/en/rel_0_9/core/inspection.html). Calling `inspect` on a mapped class (for example, your `Thing` class) will return a [`Mapper`](http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper), which...
Insert and update with core SQLAlchemy
21,206,869
2
2014-01-18T16:41:53Z
21,216,455
14
2014-01-19T12:00:11Z
[ "python", "sql-server", "python-3.x", "sqlalchemy" ]
I have a database that I don't have metadata or orm classes for (the database already exists). I managed to get the select stuff working by: ``` from sqlalchemy.sql.expression import ColumnClause from sqlalchemy.sql import table, column, select, update, insert from sqlalchemy.ext.declarative import * from sqlalchemy....
As you can see from the [SQLAlchemy Overview](http://docs.sqlalchemy.org/en/rel_0_9/intro.html#id1) documentation, sqlalchemy is build with two layers: `ORM` and `Core`. Currently you are using only some constructs of the `Core` and building everything manually. In order to use `Core` you should let SQLAlchemy know so...
using google app engine SDK in pycharm
21,207,285
3
2014-01-18T17:16:45Z
27,746,073
13
2015-01-02T17:29:51Z
[ "python", "google-app-engine", "import", "sdk", "pycharm" ]
i'm using the PyCharm IDE, and I am trying to import webapp2 from the google app engine SDK. Since the module does not come with python, it doesn't recognize it "No module named webapp2".. I am using the pycharm community version, is there anyway around this? can I import the SDK somehow?
PyCharm Community Edition can be configured to work with Google App Engine python and hence webapp2. You won't get all the advantages of PyCharm Professional Edition such as deployment, but you'll be able to do step by step debugging and get code navigation and auto-completion working. To enable debugging, edit the Py...
Python: How can I include the delimiter(s) in a string split?
21,208,223
5
2014-01-18T18:36:06Z
21,208,277
7
2014-01-18T18:40:58Z
[ "python", "string", "parsing", "split" ]
I would like to split a string, with multiple delimiters, but keep the delimiters in the resulting list. I think this is a useful thing to do an an initial step of parsing any kind of formula, and I suspect there is a nice Python solution. Someone asked a similar question in Java [here](https://stackoverflow.com/quest...
You can do that with Python's `re` module. ``` import re s='(twoplusthree)plusfour' list(filter(None, re.split(r"(plus|[()])", s))) ``` You can leave out the list if you only need an iterator.
Converting Float to Dollars and Cents
21,208,376
11
2014-01-18T18:47:07Z
21,208,495
23
2014-01-18T18:57:37Z
[ "python", "python-3.x", "floating-point", "string-formatting", "currency" ]
First of all, I have tried this post (among others): [Currency formatting in Python](http://stackoverflow.com/questions/320929/currency-formatting-in-python). It has no affect on my variable. My best guess is that it is because I am using Python 3 and that was code for Python 2. (Unless I overlooked something, because ...
In Python 3.x and 2.7, you can simply do this: ``` >>> '${:,.2f}'.format(1234.5) '$1,234.50' ``` The `:,` adds a comma as a thousands separator, and the `.2f` limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
Signal handling in python-daemon
21,208,458
6
2014-01-18T18:53:49Z
21,210,668
7
2014-01-18T22:24:57Z
[ "python", "linux", "python-2.7", "signal-handling", "python-daemon" ]
I installed [`python-daemon`](https://pypi.python.org/pypi/python-daemon) and now I'm trying to get the signal handling right. My code: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import signal, time, syslog import daemon def runDaemon(): context = daemon.DaemonContext() context.signal_map = { signal....
Your code looks fine, except the signal handler is not called because it has the wrong signature. Make it like this: ``` def programCleanup(signum, frame): ``` Quoting the docs ([signal.signal()](http://docs.python.org/2/library/signal.html#signal.signal)): > The handler is called with two arguments: the signal numb...
Python regex, remove all punctuation except hyphen for unicode string
21,209,024
8
2014-01-18T19:48:01Z
21,209,161
10
2014-01-18T20:00:27Z
[ "python", "regex", "string" ]
I have this code for removing all punctuation from a regex string: ``` import regex as re re.sub(ur"\p{P}+", "", txt) ``` How would I change it to allow hyphens? If you could explain how you did it, that would be great. I understand that here, correct me if I'm wrong, P with anything after it is punctuation.
``` [^\P{P}-]+ ``` `\P` is the complementary of `\p` - not punctuation. So this matches anything that is *not* (not punctuation or a dash) - resulting in all punctuation except dashes. Example: <http://www.rubular.com/r/JsdNM3nFJ3> If you want a non-convoluted way, an alternative is `\p{P}(?<!-)`: match all punctioa...
Converting from RGB to LAB Colorspace - any insight into the range of L*A*B* values?
21,210,479
4
2014-01-18T22:05:27Z
21,211,247
7
2014-01-18T23:32:23Z
[ "python", "opencv", "color-space", "lab-color-space" ]
I was unable to find documentation on the range of L\*A\*B\* values when converting an image from RGB to LAB in OpenCV (Python). Looking for some confirmation that my insight is correct, as the numbers are rather peculiar. My results for lightness were from 0-255, but for a and b I got 42-226 and 20-223 respectively. I...
Looking at the OpenCV [documentation](http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor) (scroll down to where the conversion for RGB ↔ CIE L\*a\*b\* is defined), we can see that the values are rescaled into the 0-255 range: L ← L \* 255/100 ; a ← a + 128 ;...
Select check box using Selenium Python
21,213,417
10
2014-01-19T05:05:10Z
21,213,482
7
2014-01-19T05:15:46Z
[ "python", "selenium" ]
Would be nice if someone know how to select the checkbox using Selenium python. ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() url = 'any url' browser.get(url) browser.find_element_by_id("15 Minute Stream Flow Data: USGS (FIFE)").click() ``` I want t...
Use [`find_element_by_xpath`](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webdriver.WebDriver.find_element_by_link_text) with the xpath expression `.//*[contains(text(), 'txt')]` to find a element that contains `txt` as text. ``` browser.find_element_by_xpath( ".//*[contains...
Flask - run function every hour
21,214,270
9
2014-01-19T07:31:48Z
21,214,385
14
2014-01-19T07:49:42Z
[ "python", "flask" ]
I have a Flask web hosting with no access to `cron` command. How can I execute some Python function every hour?
You could make use of [`APScheduler`](http://pythonhosted.org/APScheduler/) in your Flask application and run your jobs via its interface: ``` import atexit from apscheduler.scheduler import Scheduler from flask import Flask app = Flask(__name__) cron = Scheduler(daemon=True) # Explicitly kick off the background th...
Read cookie text value in a Python Bottle application
21,215,904
2
2014-01-19T11:05:41Z
21,216,296
7
2014-01-19T11:45:11Z
[ "python", "cookies", "bottle" ]
I am trying to figure out how cookies work in a Python [Bottle](http://bottlepy.org/docs/dev/index.html) application. Please be kind as I am pretty new to Python. How do I read a value out of the cookie that I have set? Example: ``` @route('/cookie_setpage/') def settingcookie(): response.set_cookie('Cookie_name'...
## Your solution `bottle` does not send a path along with the cookie if you don't specify it, which means that the browser is in charge of deciding which `path` to use for the cookie (for some reason, the bottle docs state something else). (If you don't know what the path is, read the other title in this answer). [R...
timeit module in python does not recognize numpy module
21,216,208
4
2014-01-19T11:35:57Z
21,216,422
8
2014-01-19T11:57:06Z
[ "python", "numpy", "timeit" ]
I want to test the processing time between 2 identical lists, specifically for a normal list and a numpy list. My code is ``` import timeit import numpy as np t = timeit.Timer("range(1000)") print t.timeit() u = timeit.Timer("np.arange(1000)") print u.timeit() ``` Calculation for `t` is fine, but for `u` NameError:...
The [`timeit.Timer`](http://docs.python.org/2/library/timeit.html#timeit.Timer) class can be used in two different ways. It can either take source code to be compiled an executed—in which case, the code is executed in a fresh environment where only the `setup` code has been run, or it can take a callable, in which c...
PyQt4.QtCore.QVariant object instead of a string?
21,217,399
3
2014-01-19T13:31:26Z
21,223,060
10
2014-01-19T21:43:08Z
[ "python", "python-2.7", "pyqt", "pyqt4" ]
I followed this example [Key/Value pyqt QComboBox](http://stackoverflow.com/questions/2675296/key-value-pyqt-qcombobox), to store ID value to a combo-box item using the code below. ``` self.combox_widget.addItem('Apples', 'Green') indx = self.combox_widget.currentIndex() print self.combox_widget.itemData(indx) ``` ho...
Most Qt APIs that set and retrieve arbitrary "data" will store it as a QVariant. For **Python2**, by default, PyQt will automatically convert a python object *to* a QVariant when you set it, but it won't automatically convert them back again when you *retrieve* it. So you have to take an extra step to do that like thi...
What does abstraction mean in programming?
21,220,155
11
2014-01-19T17:32:50Z
21,220,945
50
2014-01-19T18:39:13Z
[ "python", "terminology" ]
I'm learning python and I'm not sure of understanding the following statement : "The function (including its name) can capture **our mental chunking, or abstraction, of the problem**." It's the part that is in bold that I don't understand the meaning in terms of programming. The quote comes from <http://www.openbookpr...
Abstraction is a core concept in all of computer science. Without abstraction, we would still be programming in machine code or worse not have computers in the first place. So IMHO that's a really good question. **What is *abstraction*** *Abstracting* something means to *give names* to things, so that the name captur...
Writing bits to a binary file
21,220,916
4
2014-01-19T18:37:05Z
21,220,966
13
2014-01-19T18:40:29Z
[ "python", "python-3.x" ]
I have 23 bits represented as a string, and I need to write this string to a binary file as 4 bytes. The last byte is always 0. The following code works (Python 3.3), but it doesn't feel very elegant (I'm rather new to Python and programming). Do you have any tips of making it better? It seems a for-loop might be usefu...
You can treat it as an int, then create the 4 bytes as follows: ``` >>> bits = "10111111111111111011110" >>> int(bits[::-1], 2).to_bytes(4, 'little') b'\xfd\xff=\x00' ```
Python: How to import all methods and attributes from a module dynamically
21,221,358
9
2014-01-19T19:15:27Z
21,221,452
7
2014-01-19T19:22:26Z
[ "python", "python-2.7", "python-import", "python-importlib" ]
I'd like to load a module dynamically, given its string name (from an environment variable). I'm using Python 2.7. I know I can do something like: ``` import os, importlib my_module = importlib.import_module(os.environ.get('SETTINGS_MODULE')) ``` This is roughly equivalent to ``` import my_settings ``` (where `SETT...
If you have your module object, you can mimic the logic `import *` uses as follows: ``` module_dict = my_module.__dict__ try: to_import = my_module.__all__ except AttributeError: to_import = [name for name in module_dict if not name.startswith('_')] globals().update({name: module_dict[name] for name in to_impo...
Drop some Pandas dataframe rows using group based condition
21,221,667
4
2014-01-19T19:40:51Z
21,222,214
7
2014-01-19T20:27:40Z
[ "python", "pandas" ]
I've got some data on sales, say, and want to look at how different post codes compare: do some deliver more profitable business than others? So I'm grouping by postcode, and can easily get various stats out on a per postcode basis. However, there are a few very high value jobs which distort the stats, so what I'd like...
In 0.13 you can use [cumcount](http://pandas.pydata.org/pandas-docs/stable/groupby.html#enumerate-group-items): ``` In [11]: df[df.sort('C').groupby('A').cumcount(ascending=False) >= 2] # use .sort_index() to remove UserWarning Out[11]: A C D 0 foo -0.536732 0.061055 4 foo -0.910537 -1.634047...
How do I install Python libraries?
21,222,114
16
2014-01-19T20:18:10Z
21,222,809
7
2014-01-19T21:18:03Z
[ "python", "module", "installation", "python-wheel" ]
I was looking for a tutorial on how to install Python libraries in the wheel format. It does not seem straightforward so I'd appreciate a simple step by step tutorial how to install the module named "requests" for CPython. I downloaded it from: <https://pypi.python.org/pypi/requests> and now I have a .whl file. I've ...
If you want to be relax for installing libraries for python. You should using `pip`, that is python installer package. To install pip: 1. Download [ez\_setup.py](https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py) and then run: ``` python ez_setup.py ``` 2. Then download [get-pip.py](https://r...
How do I install Python libraries?
21,222,114
16
2014-01-19T20:18:10Z
28,300,854
16
2015-02-03T14:05:06Z
[ "python", "module", "installation", "python-wheel" ]
I was looking for a tutorial on how to install Python libraries in the wheel format. It does not seem straightforward so I'd appreciate a simple step by step tutorial how to install the module named "requests" for CPython. I downloaded it from: <https://pypi.python.org/pypi/requests> and now I have a .whl file. I've ...
You want to install a downloaded wheel (.whl) file on Python under Windows? 1. [Install pip on your Python(s) on Windows](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) (on Python 3.4+ it is already included) 2. Upgrade pip if necessary ``` pip install -U pip ``` 3. Install a local...
Python Error: "ImportError: No module named six"
21,222,458
8
2014-01-19T20:48:37Z
21,222,511
13
2014-01-19T20:53:02Z
[ "python", "matplotlib", "six-python" ]
I am running Python 2.7 on a Windows 7 OS Here is what I run: ``` >>> import matplotlib.pyplot as plt ``` Then I get this: ``` Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> import matplotlib.pyplot as plt File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 29, in <mo...
You need to install it on your system. This basically means putting the zip file where Python can find it, but by far the easiest way is `pip install six`. This will download it a second time, though. Like the [matplotlib installation instructions](http://matplotlib.org/users/installing.html) mention, `six` is a depen...
Multiple assignments into a python dictionary
21,222,506
2
2014-01-19T20:52:39Z
21,222,526
10
2014-01-19T20:54:01Z
[ "python", "dictionary" ]
Is it possible to assign values to more than one keys of a dictionary in a more concise way than the one below? I mean, let `d` be a dictionary initialized as below: ``` d={'a':1,'b':2,'c':3} ``` To assign values to multiple keys I need to do this: ``` d['a']=10 d['b']=200 d['c']=30 ``` Can I achieve same with som...
You can use [dict.update](http://docs.python.org/2/library/stdtypes.html#dict.update): ``` d.update({'a': 10, 'c': 200, 'c': 30}) ``` This will overwrite the values for existing keys and add new key-value-pairs for keys that do not already exist.
Need to read string into a float array
21,222,702
3
2014-01-19T21:10:03Z
21,222,729
7
2014-01-19T21:11:50Z
[ "python" ]
I have a text file like below. I want to read given values as a float list. After that I am going to do some calculations. I used split function and convertion to float. But I cannot convert first one and last one because those two has square brackets. ([ ]). it gave an error as below. File format ``` [-1.504, 1.521,...
Use [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval) to parse each line into a list of floats: ``` import ast with open('XYZ.txt', 'r') as infh: for line in infh: row = ast.literal_eval(line) print row ``` The `ast.literal_eval()` interprets each line as containi...
Why is json.loads an order of magnitude faster than ast.literal_eval?
21,223,392
6
2014-01-19T22:16:33Z
21,223,411
8
2014-01-19T22:18:53Z
[ "python", "json", "parsing", "benchmarking" ]
After answering a question about [how to parse a text file containing arrays of floats](http://stackoverflow.com/q/21222702/343834), I ran the following benchmark: ``` import timeit import random line = [random.random() for x in range(1000)] n = 10000 json_setup = 'line = "{}"; import json'.format(line) json_work = ...
The two functions are parsing entirely different languages—JSON, and Python literal syntax.\* As [`literal_eval`](http://docs.python.org/3/library/ast.html#ast.literal_eval) says: > The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts,...
Install wxPython on Mac os Mavericks
21,223,717
11
2014-01-19T22:49:54Z
21,223,812
24
2014-01-19T23:00:09Z
[ "python", "osx", "wxpython", "osx-mavericks" ]
I am on a Macbook Air, running Mavericks. Today I downloaded wxPython via their website, however, when I click on the install package I get: ``` wxPython3.0-osx-cocoa-py2.7.pkg” is damaged and can’t be opened. You should eject the disk image. ``` Anyone have any ideas to get around this, thanks.
According to [#14523](http://trac.wxwidgets.org/ticket/14523), the problem is that the package is not signed (and it's an old-style package, which isn't fully supported anymore, which is why you get the wrong error message, and the usual workaround of context-clicking Open doesn't work). There are two workarounds: Fi...
Fast ping sweep in python
21,225,464
3
2014-01-20T02:42:35Z
21,225,866
9
2014-01-20T03:39:11Z
[ "python", "bash", "python-2.7", "ping" ]
So, I'm trying to get similar results using python as I do with a bash script. Code for the bash script: ``` #!/bin/bash for ip in $(seq 1 254); do ping -c 1 10.10.10.$ip | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 & done ``` The thing that I would like to do is get the same results ...
# [Multiprocessing](http://docs.python.org/2/library/multiprocessing.html) ``` #!/usr/bin/python2 import multiprocessing import subprocess import os def pinger( job_q, results_q ): DEVNULL = open(os.devnull,'w') while True: ip = job_q.get() if ip is None: break try: subpr...
Numpy quirk: Apply function to all pairs of two 1D arrays, to get one 2D array
21,226,610
8
2014-01-20T05:05:13Z
21,226,896
9
2014-01-20T05:35:59Z
[ "python", "python-2.7", "numpy" ]
Let's say I have 2 one-dimensional (1D) numpy arrays, `a` and `b`, with lengths `n1` and `n2` respectively. I also have a function, `F(x,y)`, that takes two values. Now I want to apply that function to each pair of values from my two 1D arrays, so the result would be a 2D numpy array with shape `n1, n2`. The `i, j` ele...
You can use [numpy broadcasting](http://scipy-lectures.github.io/intro/numpy/operations.html#broadcasting) to do calculation on the two arrays, turning `a` into a vertical 2D array using `newaxis`: ``` In [11]: a = np.array([1, 2, 3]) # n1 = 3 ...: b = np.array([4, 5]) # n2 = 2 ...: #if function is c(i, j) = a...
Superscript in Python plots
21,226,868
7
2014-01-20T05:33:14Z
21,236,820
17
2014-01-20T14:44:05Z
[ "python", "matplotlib" ]
I want to label my x axis at follows : ``` pylab.xlabel('metres 10^1') ``` But I don't want to have the ^ symbol included . ``` pylab.xlabel('metres 10$^{one}$') ``` This method works and will superscript letters but doesn't seem to work for numbers . If I try : ``` pylab.xlabel('metres 10$^1$') ``` It superscrip...
You just need to have the full expression inside the `$`. Basically, you need `"meters $10^1$"`. You don't need `usetex=True` to do this (or most any mathematical formula). You may also want to use a raw string (e.g. `r"\t"`, vs `"\t"`) to avoid problems with things like `\n`, `\a`, `\b`, `\t`, `\f`, etc. For example...
Error: Uncaught SyntaxError: Unexpected token &
21,230,459
2
2014-01-20T09:35:07Z
21,230,492
9
2014-01-20T09:36:43Z
[ "javascript", "python", "django", "json", "serialization" ]
I get an error when sending JSON data to JavaScript from the models. It looks like encoding is causing the error, but all the examples I have found work for other people. How can I properly send model data from my view to JavaScript? view code: ``` def home(request): import json info_obj = Info.objects.all() js...
You must use `"` instead of `&quot;` in the string. The string was automatically escaped by `render_to_response`. To avoid this you must mark `json_data` safe. Use `mark_safe` for it. ``` from django.utils.safestring import mark_safe return render_to_response( "pique/home.html", { 'json_data':mark_safe(json...
Creating a pandas DataFrame from columns of other DataFrames with similar indexes
21,231,834
13
2014-01-20T10:43:44Z
21,242,140
15
2014-01-20T19:08:12Z
[ "python", "pandas", "dataframe" ]
I have 2 DataFrames df1 and df2 with the same column names ['a','b','c'] and indexed by dates. The date index can have similar values. I would like to create a DataFrame df3 with only the data from columns ['c'] renamed respectively 'df1' and 'df2' and with the correct date index. My problem is that I cannot get how to...
You can use [concat](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.merge.concat.html): ``` In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2']) Out[11]: df1 df2 2014-01-01 NaN -0.978535 2014-01-02 -0.106510 -0.519239 2014-01-03 -0.846100 -0.313153 201...
Why is float() faster than int()?
21,232,733
21
2014-01-20T11:23:59Z
21,234,576
11
2014-01-20T12:47:53Z
[ "python", "python-2.7", "runtime", "benchmarking" ]
Experimenting with some code and doing some microbenchmarks I just found out that using the `float` function on a string containing an integer number is a factor 2 faster than using `int` on the same string. ``` >>> python -m timeit int('1') 1000000 loops, best of 3: 0.548 usec per loop >>> python -m timeit float('1'...
`int` has lots of bases. \*, 0\*, 0x\*, 0b\*, 0o\* and it can be long, it takes time to determine the base and other things if the base is set, it saves a lot of time ``` python -m timeit "int('1',10)" 1000000 loops, best of 3: 0.252 usec per loop python -m timeit "int('1')" 1000000 loops, best of 3: 0.59...
What's the purpose of the "__package__" attribute in Python?
21,233,229
15
2014-01-20T11:47:17Z
21,233,334
20
2014-01-20T11:52:26Z
[ "python", "python-3.x" ]
All I want to know is **what exactly does `__package__` mean**? Didn't find any explanation in the official doc, even on SO. If you could provide some examples I would be very happy.
See the [PEP 366](http://www.python.org/dev/peps/pep-0366/) and [import system reference documentation](http://docs.python.org/3/reference/import.html): > The major proposed change is the introduction of a new module level attribute, `__package__`. When it is present, relative imports will be based on this attribute r...
Python Tornado - disable logging to stderr
21,234,772
5
2014-01-20T12:57:04Z
21,235,133
9
2014-01-20T13:15:05Z
[ "python", "tornado" ]
I have minimalistic Tornado application: ``` import tornado.ioloop import tornado.web class PingHandler(tornado.web.RequestHandler): def get(self): self.write("pong\n") if __name__ == "__main__": application = tornado.web.Application([ ("/ping", PingHandler), ]) application.listen(8888) torna...
Its clear that "someone" is initializing logging subsystem when we start Tornado. Here is the code from `ioloop.py` that reveals the mystery: ``` def start(self): if not logging.getLogger().handlers: # The IOLoop catches and logs exceptions, so it's # important that log output be visible. However,...
How to read user input until EOF?
21,235,855
12
2014-01-20T13:53:43Z
21,235,913
14
2014-01-20T13:56:30Z
[ "python", "string", "input", "eof" ]
My current code reads user input until line-break. But I am trying to change that to a format, where the user can write input until strg+d to end his input. I currently do it like this: ``` input = raw_input ("Input: ") ``` But how can I change that to an EOF-Ready version?
Use [`file.read`](http://docs.python.org/2/library/stdtypes#file.read): ``` input_str = sys.stdin.read() ``` According to the documentation: > `file.read([size])` > > Read at most size bytes from the file (less if the read hits EOF > before obtaining size bytes). If the size argument is negative or > omitted, read a...
How to read user input until EOF?
21,235,855
12
2014-01-20T13:53:43Z
21,236,015
7
2014-01-20T14:02:24Z
[ "python", "string", "input", "eof" ]
My current code reads user input until line-break. But I am trying to change that to a format, where the user can write input until strg+d to end his input. I currently do it like this: ``` input = raw_input ("Input: ") ``` But how can I change that to an EOF-Ready version?
You could also do the following: ``` acc = [] out = '' while True: try: acc.append(raw_input('> ')) # Or whatever prompt you prefer to use. except EOFError: out = '\n'.join(acc) break ```
Unresolved reference issue in PyCharm
21,236,824
90
2014-01-20T14:44:29Z
21,240,209
9
2014-01-20T17:18:25Z
[ "python", "ide", "pycharm" ]
I have a directory structure ``` ├── simulate.py ├── src │   ├── networkAlgorithm.py │   ├── ... ``` And I can access the network module with `sys.path.insert()`. ``` import sys import os.path sys.path.insert(0, "./src") from networkAlgorithm import * ``` However, pycharm complains t...
Normally, [$PYTHONPATH is used to teach python interpreter to find necessary modules](http://jettify.net/2012/pythonpath/). PyCharm needs to add the path in Preference. ![enter image description here](http://i.stack.imgur.com/VHhw9.png)
Unresolved reference issue in PyCharm
21,236,824
90
2014-01-20T14:44:29Z
21,241,988
194
2014-01-20T18:59:32Z
[ "python", "ide", "pycharm" ]
I have a directory structure ``` ├── simulate.py ├── src │   ├── networkAlgorithm.py │   ├── ... ``` And I can access the network module with `sys.path.insert()`. ``` import sys import os.path sys.path.insert(0, "./src") from networkAlgorithm import * ``` However, pycharm complains t...
Manually adding it as you have done *is* indeed one way of doing this, but there is a simpler method, and that is by simply telling pycharm that you want to add the `src` folder as a source root, and then adding the sources root to your python path. This way, you don't have to hard code things into your interpreter's ...
Python a &= b meaning?
21,237,767
3
2014-01-20T15:25:46Z
21,238,517
9
2014-01-20T15:58:34Z
[ "python", "operators", "ampersand", "in-place" ]
What does the `&=` operator mean in Python, and can you give me a working example? [I am trying to understand the `__iand__` operator.](http://docs.python.org/2/library/operator.html#operator.iand) I just don't know what `&=` means and have looked online but couldn't find it. Thanks.
Contrary to some of the other answers, `a &= b` is *not* shorthand for `a = a & b`, though I admit it often behaves similarly for built-in immutable types like integers. `a &= b` can call the special method [`__iand__`](http://docs.python.org/2/reference/datamodel.html#object.__iand__) if available. To see the differe...
Python a &= b meaning?
21,237,767
3
2014-01-20T15:25:46Z
21,238,905
7
2014-01-20T16:15:03Z
[ "python", "operators", "ampersand", "in-place" ]
What does the `&=` operator mean in Python, and can you give me a working example? [I am trying to understand the `__iand__` operator.](http://docs.python.org/2/library/operator.html#operator.iand) I just don't know what `&=` means and have looked online but couldn't find it. Thanks.
## Explanation Understandable that you can't find much reference on it. [I find it hard to get references on this too, but they exist.](http://books.google.com/books?id=H9emM_LGFDEC&pg=PA251&lpg=PA251&dq=python%20%22__iand__%22&source=bl&ots=Z9cJbKJcnS&sig=1NCzV9lG_e6VFVK1J0MxeFG0LN8&hl=en&sa=X&ei=T3TdUtLzMvC1sASOt4H4...
Color coding cells in a table based on the cell value using Jinja templates
21,239,962
3
2014-01-20T17:04:00Z
21,240,889
9
2014-01-20T17:53:40Z
[ "python", "css", "flask", "jinja2", "jinja" ]
I have a simple flask app and need to display a table of values, with the cell backgrounds colour coded based on the cell value according to thresholds. I'm generating the table content as follows: ``` {% block dashboard_table2 %} <table> {% for row in data %} {% for item in row %} ...
The easiest way would be to put this display logic in your template: ``` <table> {% for row in data %} <tr> {% for item in row %} {% if item <= 10 %} <td class="under-limit">{{ item }}</td> {% else %} <td>{{ item }}</td> {% endif %} ...
How to install a package inside virtualenv?
21,240,653
4
2014-01-20T17:40:55Z
21,241,009
9
2014-01-20T18:00:42Z
[ "python", "virtualenv", "pip" ]
I created a virtualenv with the following command. ``` mkvirtualenv --distribute --system-site-packages "$1" ``` After starting the virtualenv with `workon`, I type `ipython`. It prompts me ``` WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv. ``` ...
Create your virtualenv with `--no-site-packages` if you don't want it to be able to use external libraries: ``` virtualenv --no-site-packages my-virtualenv . my-virtualenv/bin/activate pip install ipython ``` Otherwise, as in your example, it can see a library installed in your system Python environment as satisfying...
Django NoReverseMatch
21,240,680
21
2014-01-20T17:42:38Z
21,240,754
36
2014-01-20T17:46:42Z
[ "python", "django", "python-2.7", "django-1.6" ]
I'm making a simple login app in django 1.6 (and python 2.7) and I get an error at the beggining that is not letting me continue. This is the site's url.py ``` from django.conf.urls import patterns, include, url from django.contrib import admin import login admin.autodiscover() urlpatterns = patterns('', url(r'...
The problem is in the way you include the auth URLs in the main one. Because you use both ^ and $, only the empty string matches. Drop the $.
Most efficient way to calculate radial profile
21,242,011
2
2014-01-20T19:00:56Z
21,242,776
10
2014-01-20T19:45:48Z
[ "python", "optimization", "numpy", "scipy" ]
I need to optimize this part of an image processing application. It is basically the sum of the pixels binned by their distance from the central spot. ``` def radial_profile(data, center): y,x = np.indices((data.shape)) # first determine radii of all pixels r = np.sqrt((x-center[0])**2+(y-center[1])**2) ...
It looks like you could use [numpy.bincount](http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html) here: ``` import numpy as np def radial_profile(data, center): y, x = np.indices((data.shape)) r = np.sqrt((x - center[0])**2 + (y - center[1])**2) r = r.astype(np.int) tbin = np.binc...
Flask-SQLAlchemy - When are the tables/databases created and destroyed?
21,243,291
8
2014-01-20T20:14:49Z
21,243,503
10
2014-01-20T20:27:47Z
[ "python", "mysql", "flask", "flask-sqlalchemy" ]
I am a little confused with the topic alluded to in the title. So, when a Flask app is started, does the SQLAlchemy search the`SQLALCHEMY_DATABASE_URI` for the correct, in my case, MySQL database. Then, does it create the tables if they do not exist already? What if the database that is programmed into the`SQLALCHEMY...
Tables are not created automatically; you need to call the [`SQLAlchemy.create_all()` method](http://flask-sqlalchemy.pocoo.org/2.1/api/#flask.ext.sqlalchemy.SQLAlchemy.create_all) to explicitly to have it create tables for you: ``` db = SQLAlchemy(app) db.create_all() ``` You can do this with command-line utility, f...
Vertical bar in Python bitwise assignment operator
21,243,775
5
2014-01-20T20:42:50Z
21,243,811
9
2014-01-20T20:45:24Z
[ "python", "python-2.7", "operators" ]
There is a code and in class' method there is a line: ``` object.attribute |= variable ``` I can't understand what it means. I didn't find (|=) in the list of basic Python operators.
That is a `bitwise or` with assignment. It is equivalent to ``` object.attribute = object.attribute | variable ``` Read [more here](https://wiki.python.org/moin/BitwiseOperators).
Django Crispy Forms Add Div Around Submit Button
21,244,847
6
2014-01-20T21:49:54Z
21,313,578
11
2014-01-23T16:13:27Z
[ "python", "django", "django-crispy-forms" ]
Using [Django Crispy Forms](http://django-crispy-forms.readthedocs.org/en/latest/) I would like to add a class around my submit button like this: ``` <div class="col-lg-offset-3 col-lg-9"> <input type="submit" value="Log Me In" class="btn btn-default" /> </div> ``` This is what I have managed so far: ``` <input ...
You need to lay out all your fields, if you want to control the wrappers: ``` from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Div class AuthenticationForm(forms.Form): def __init__(self, *args, **kwargs): super(AuthenticationForm, self)....
Creating a list of all possible nested sequences from another list
21,245,589
3
2014-01-20T22:36:26Z
21,245,616
8
2014-01-20T22:37:55Z
[ "python" ]
``` List1=[0, 1, 2, 3, 4, 5] ``` I'd like to produce the following list2 containing four-element nested sequences from list1. ``` [0, 1, 2, 3] [0, 1, 2, 4] [0, 1, 2, 5] [0, 1, 3, 4] [0, 1, 3, 5] [0, 1, 4, 5] [0, 2, 3, 4] [0, 2, 3, 5] [0, 2, 4, 5] [0, 3, 4, 5] [1, 2, 3, 4] ...
Look up [`itertools.combinations`](http://docs.python.org/2/library/itertools.html#itertools.combinations) Basically, what you are looking for is: ``` import itertools itertools.combinations([0, 1, 2, 3, 4, 5], 4) ```
How can I make emacs-jedi use project-specific virtualenvs
21,246,218
10
2014-01-20T23:26:05Z
21,246,256
12
2014-01-20T23:28:32Z
[ "python", "emacs", "virtualenv", "jedi" ]
I would like emacs-jedi to detect when I am editing files in different projects, and use the corresponding virtualenv if it is available. By convention my virtualenvs have the same name as my projects. They are located in `$HOME/.virtualenvs/` I found [kenobi.el](http://yergler.net/blog/2013/07/28/emacs-jedi/) but it ...
I have now settled on a solution that uses the [virtualenvwrapper](https://github.com/porterjamesj/virtualenvwrapper.el) ELPA package to activate virtualenvs, allowing emacs-jedi to pick up the virtualenv path from the VIRTUAL\_ENV environment variable. Here is a complete, working, emacs-jedi initialisation: ``` (def...
How to make a pandas crosstab with percentages?
21,247,203
7
2014-01-21T00:57:56Z
21,247,312
12
2014-01-21T01:10:14Z
[ "python", "pandas", "crosstab" ]
Given a dataframe with different categorical variables, how do I return a cross-tabulation with percentages instead of frequencies? ``` df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 6, 'B' : ['A', 'B', 'C'] * 8, 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4, ...
``` pd.crosstab(df.A, df.B).apply(lambda r: r/r.sum(), axis=1) ``` Basically you just have the function that does `row/row.sum()`, and you use `apply` with `axis=1` to apply it by row. (If doing this in Python 2, you should use `from __future__ import division` to make sure division always returns a float.)
Reading output from child process using python
21,247,721
13
2014-01-21T01:56:23Z
21,307,708
10
2014-01-23T12:08:13Z
[ "python", "buffer", "subprocess", "pipe", "flush" ]
## The Context I am using the `subprocess` module to start a process from python. I want to be able to access the output (stdout, stderr) as soon as it is written/buffered. * The solution must support Windows 7. I require a solution for Unix systems too but I suspect the Windows case is more difficult to solve. * The...
At issue here is buffering by the *child* process. Your `subprocess` code already works as well as it could, but if you have a child process that buffers its output then there is nothing that `subprocess` pipes can do about this. I cannot stress this enough: the buffering delays you see are the responsibility of the c...
grouping pandas dataframe by two columns (or more)?
21,247,992
7
2014-01-21T02:25:11Z
21,248,050
10
2014-01-21T02:33:12Z
[ "python", "pandas", "dataframe" ]
I have the following dataframe: ``` mydf = pandas.DataFrame({"cat": ["first", "first", "first", "second", "second", "third"], "class": ["A", "A", "A", "B", "B", "C"], "name": ["a1", "a2", "a3", "b1", "b2", "c1"], "val": [1,5,1,1,2,10]}) ``` I want to create a dataframe that makes summary statistics about the `val` co...
Use `reset_index` ``` In [9]: mydf.groupby(['cat', "class"]).val.sum().reset_index() Out[9]: cat class val 0 first A 7 1 second B 3 2 third C 10 ``` ## EDIT set level=1 if you want to set `cat` as index ``` In [10]: mydf.groupby(['cat', "class"]).val.sum().reset_index(level=1) Out[1...
How to flashing a message with link using Flask flash?
21,248,718
5
2014-01-21T03:41:50Z
29,807,235
7
2015-04-22T19:37:07Z
[ "python", "flask", "openid", "flash-message" ]
I'm creating a web app using Flask to deal with GoogleOpenID, these codes are almost finished, except the flashing message contains a link: ``` @oid.after_login def create_or_login(resp): user = db_session.query(User).filter_by(email=resp.email).first() if user is not None: flash('Successfully signed i...
The other answers here focus on changing your template to allow all flash messages to be marked as safe, which may not be what you want. If you just want to mark certain flashed messages as safe, wrap the text passed to flash() in Markup(). ([Flask API Docs for Markup](http://flask.pocoo.org/docs/0.10/api/#flask.Marku...
How to configure display output in IPython pandas
21,249,206
17
2014-01-21T04:30:50Z
21,275,962
20
2014-01-22T06:41:55Z
[ "python", "terminal", "pandas", "ipython" ]
I'm trying to configure my IPython output in my OS X terminal, but it would seem that none of the changes I'm trying to set are taking effect. I'm trying to configure the display settings such that wider outputs like a big `DataFrame` will output without any truncation or as the summary info. After importing pandas in...
Just for completeness (I'll add my comment as an answer), you missed out: ``` pd.options.display.max_colwidth # default is 50 ``` *this restricted the maximum length of a single column.* There are quite a few options to configure here, if you're using ipython then tab complete to find the [full set of display optio...
Getting the `python setup.py test` syntax to work?
21,250,389
7
2014-01-21T06:05:52Z
21,250,977
8
2014-01-21T06:40:32Z
[ "python", "unit-testing", "distutils", "setup.py", "python-unittest" ]
How do I get `python setup.py test` to work? - Current output: ``` $ python setup.py test # also tried: `python setup.py tests` /usr/lib/python2.7/distutils/dist.py:267: \ UserWarning: Unknown distribution option: 'test_suite' warnings.warn(msg) usage: setup.py [global_opts] cmd1 [cmd1_op...
`test_suite` is a feature of [setuptools](http://pythonhosted.org/setuptools/setuptools.html#test). Replace distutils with it: ``` from setuptools import setup ```
How to handle an np.RankWarning in numpy?
21,252,541
4
2014-01-21T08:14:01Z
21,252,794
10
2014-01-21T08:27:56Z
[ "python", "numpy", "exception-handling" ]
I will try to phrase this as best as I can, though I am novice and beg for your lenience: I am using the code below to find the polynomial that best fits some data that I read dynamically from a physical temperature sensor: ``` coefficients = numpy.polyfit(x, y, 2) polynomial = numpy.poly1d(self.coefficients) #and t...
``` import numpy as np import warnings x = [1] y = [2] with warnings.catch_warnings(): warnings.filterwarnings('error') try: coefficients = np.polyfit(x, y, 2) except np.RankWarning: print "not enought data" ```
Google Groups API add Member
21,253,849
3
2014-01-21T09:21:19Z
21,262,115
7
2014-01-21T15:19:20Z
[ "python", "google-groups", "google-groups-api" ]
I have found lots of information on the internet about adding Members to a Group in Googlegroups, but I cant manage to get any of it to work. I am working in Python-DJango. Using a bussiness account, I manage to add them using Provisioning API, but I could not do it with the new Directory API. The problem is the gro...
The Provisioning API (deprecated) and the new Admin SDK are both designed to work with Google Apps for Business and EDU and only work against Google Groups for Business (groups with a custom @yourdomain.com address). You cannot use these APIs with consumer Google Groups that have @googlegroups.com email addresses. For...
How to install delete-project plugin in gerrit?
21,254,291
6
2014-01-21T09:40:04Z
21,722,062
11
2014-02-12T08:08:23Z
[ "java", "python", "build", "gerrit" ]
I want to install delete-project plugin to my gerrit server. As per the latest version, I should clone it from google source and use buck build. I cloned it and my buck is also ready. What are the steps to be followed to build the delete project plugin and add it to my gerrit server. I tried ``` buck build . ``` i...
I managed to install delete-project plugin after following this thread: <https://groups.google.com/forum/#!topic/repo-discuss/hbBc2TUhl7s> and then install according to: <https://gerrit-review.googlesource.com/Documentation/cmd-plugin-install.html> P.S. I build the jar following the below steps: 1. git clone --rec...
multiple plot in one figure in Python
21,254,472
11
2014-01-21T09:47:24Z
21,254,745
22
2014-01-21T09:58:02Z
[ "python", "matplotlib", "plot" ]
I am new to python and am trying to plot multiple lines in the same figure using matplotlib. Value of my Y axis is stored in a dictionary and I make corresponding values in X axis in my following code My code is like this: ``` for i in range(len(ID)): AxisY= PlotPoints[ID[i]] if len(AxisY)> 5: AxisX= [len(AxisY)]...
This is very simple to do: ``` import matplotlib.pyplot as plt plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here') plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here') plt.show() ``` You can keep adding `plt.plot` as many times as you like. As for `l...
Pandas dataframe hide index functionality?
21,256,013
2
2014-01-21T10:52:53Z
21,256,226
7
2014-01-21T11:02:27Z
[ "python", "pandas", "ipython-notebook" ]
Is it possible to hide the index when displaying pandas dataframes, so that only the column names appear at the top of the table? This would need to work for both the html representation in ipython notebook and to\_latex() function (which I'm using with nbconvert). Ta.
Set `index=False` For ipython notebook: ``` print df.to_string(index=False) ``` For to\_latex: ``` df.to_latex(index=False) ```
In CMD "python" starts Python 3.3, "py" starts Python 2.7, how do I change this?
21,257,203
4
2014-01-21T11:46:33Z
21,257,622
21
2014-01-21T12:03:25Z
[ "python", "windows", "python-2.7", "python-3.x", "path" ]
Brand new Python, just getting things set up and installed before I start messing around with things. My understanding is that there are some notable differences/incompatibilities between Python 2.7 and Python 3.3, though both versions are well used, so I thought it best to install *both* (In their own install director...
`py` is the [Windows Python launcher](http://docs.python.org/3/using/windows.html#launcher), and it can start *any* Python version. On most systems `py` is configured to launch Python 2.7 by default if present (this is the default except for Python 3.6 and newer, where Python 3 will be run instead). You have two optio...
Writing a csv file into SQL Server database using python
21,257,899
4
2014-01-21T12:16:15Z
21,261,532
11
2014-01-21T14:55:30Z
[ "python", "sql-server", "csv", "pyodbc" ]
Hi I am trying to write a csv file into a table in SQL Server database using python. I am facing errors when I pass the parameters , but I don't face any error when I do it manually. Here is the code I am executing. ``` cur=cnxn.cursor() # Get the cursor csv_data = csv.reader(file(Samplefile.csv')) # Read the csv for ...
Consider building the query dynamically to ensure the number of placeholders matches your table and CSV file format. Then it's just a matter of ensuring your table and CSV file are correct, instead of checking that you typed enough `?` placeholders in your code. The following example assumes 1. CSV file contains colu...
What happens if you write a variable name alone in python?
21,260,745
17
2014-01-21T14:21:58Z
21,260,897
9
2014-01-21T14:28:19Z
[ "python", "lighttable" ]
Recently I became curious about but what happens in line 2 of the following bogus python code: ``` def my_fun(foo,bar): foo return foo + bar ``` The reason I became interested is that I'm trying Light Table and tried to put a watch on "foo." It appeared to cause the python interpreter to hang. Am I correct i...
Nothing happens. It becomes equivalent to a pointless operation Looking at the `dis` output ``` In [3]: dis.dis(my_fun) 2 0 LOAD_FAST 0 (foo) 3 POP_TOP 3 4 LOAD_FAST 0 (foo) 7 LOAD_FAST 1 (bar) 1...
What happens if you write a variable name alone in python?
21,260,745
17
2014-01-21T14:21:58Z
21,260,905
27
2014-01-21T14:28:31Z
[ "python", "lighttable" ]
Recently I became curious about but what happens in line 2 of the following bogus python code: ``` def my_fun(foo,bar): foo return foo + bar ``` The reason I became interested is that I'm trying Light Table and tried to put a watch on "foo." It appeared to cause the python interpreter to hang. Am I correct i...
One can look at what is happening with a little help from the built-in [dis](http://docs.python.org/2/library/dis.html) module: ``` import dis def my_fun(foo,bar): foo return foo + bar dis.dis(my_fun) ``` The `dis.dis` function disassembles functions (yep, it can disassemble itself), methods, and classes. ...
Add a dynamic form to a django formset using javascript in a right way
21,260,987
8
2014-01-21T14:31:33Z
21,260,988
24
2014-01-21T14:31:33Z
[ "javascript", "python", "django", "django-forms", "django-templates" ]
How to add a dynamic form to a django formset in templates without annoying copies of html template output? I have a formset with unknown count of result forms, and I need to add a few forms directly in template by pressing on a button.
This self-answer is based on [this post](http://lab305.com/news/2012/jul/19/django-inline-formset-underscore/) by Nick Lang, but we are going to simplify this way and we don't need to copy/paste whole form html anymore. We have an inline formset which is created in a view like this: ``` items_formset = inlineformset_...
shutil.rmtree to remove readonly files
21,261,132
8
2014-01-21T14:38:28Z
21,263,493
12
2014-01-21T16:17:13Z
[ "python", "shutil" ]
I want to use `shutil.rmtree` in Python to remove a directory. The directory in question contains a `.git` control directory, which git marks as read-only and hidden. The read-only flag causes `rmtree` to fail. In Powershell, I would do "del -force" to force removal of the read-only flag. Is there an equivalent in Pyt...
After more investigation, the following appears to work: ``` def del_rw(action, name, exc): os.chmod(name, stat.S_IWRITE) os.remove(name) shutil.rmtree(path, onerror=del_rw) ``` In other words, actually remove the file in the onerror function. (You might need to check for a directory in the onerror handler an...
Splitting string and removing whitespace Python
21,261,330
4
2014-01-21T14:46:36Z
21,261,358
9
2014-01-21T14:47:54Z
[ "python", "regex", "split", "whitespace", "strip" ]
I would like to split a String by comma `','` and remove whitespace from the beginning and end of each split. For example, if I have the string: `"QVOD, Baidu Player"` I would like to split and strip to: `['QVOD', 'Baidu Player']` Is there an elegant way of doing this? Possibly using a list comprehension?
Python has a spectacular function called `split` that will keep you from having to use a regex or something similar. You can split your string by just calling `my_string.split(delimiter)` After that python has a `strip` function which will remove all whitespace from the beginning and end of a string. ``` [item.strip(...
Python - Declare two variable with the same values at the same time
21,262,037
3
2014-01-21T15:15:54Z
21,262,056
8
2014-01-21T15:17:02Z
[ "python", "python-3.x", "declaration", "declare" ]
``` a=[1,2,3] b=[1,2,3] ``` Is there a way to do this on one line? (obviously not with ";") ``` a,b=[1,2,3] ``` doesn't work because of ``` a,b,c=[1,2,3] ``` a=1 b=2 c=3
``` In [18]: a,b=[1,2,3],[1,2,3] In [19]: a Out[19]: [1, 2, 3] In [20]: b Out[20]: [1, 2, 3] ``` you may also want to do this: ``` In [22]: a=b=[1,2,3] In [23]: a Out[23]: [1, 2, 3] In [24]: b Out[24]: [1, 2, 3] ``` but be careful that, `a is b` is `True` in this case, namely, `a` is just a reference of `b`
Run Stata do file from Python
21,263,668
7
2014-01-21T16:24:47Z
21,277,704
7
2014-01-22T08:26:38Z
[ "python", "stata" ]
I have a `Python` script that cleans up and performs basic statistical calculations on a large panel dataset (`2,000,000+ observations`). I find that some of these tasks are better suited to `Stata`, and wrote a do file with the necessary commands. Thus, I want to run a .do file within my Python code. How would I go a...
I think @user229552 points in the correct direction. Python's `subprocess` module can be used. Below an example that works for me with Linux OS. Suppose you have a Python file called `pydo.py` with the following: ``` import subprocess ## Do some processing in Python ## Set do-file information dofile = "/home/robert...
Change file type in PyCharm
21,263,786
13
2014-01-21T16:30:13Z
21,281,563
32
2014-01-22T11:23:10Z
[ "python", "pycharm" ]
I created a text file, and renamed it into testTreeGen.py. ![enter image description here](http://i.stack.imgur.com/f5YJy.png) The problem is that PyCharm does not detect it as a python source so that I can't execute it. How can I teach PyCharm that this is python script? I tried remove the file and recreated it, an...
**Settings (Preferences on Mac) | Editor | File Types | Text** Check patterns there (bottom list) -- you must have had `testTreeGen` or similar pattern. Just remove it. --- This usually happens when creating new file and instead of using specific file template you use `New | File` and forgetting to enter file extens...
python easy_install fails with SSL certificate error for all packages
21,265,616
7
2014-01-21T17:54:28Z
30,728,558
8
2015-06-09T09:45:38Z
[ "python", "django", "ssl", "easy-install", "pypi" ]
**Goal:** I'm on RedHat 5 and trying to install the latest python and django for a web app. I successfully altinstalled python27 and easy\_install, and wget with openssl. **Problem:** However now that I try to get anything from pypi.python.org I get the following error: ``` $ sudo easy_install --verbose django Searc...
your curl cert is too old try to download new curl cert: ``` wget http://curl.haxx.se/ca/cacert.pem mv cacert.pem ca-bundle.crt sudo mv ca-bundle.crt /etc/pki/tls/certs ```
How do i read out Custom Properties in Blender with Python?
21,265,676
7
2014-01-21T17:57:21Z
21,272,360
9
2014-01-22T01:15:11Z
[ "python", "blender" ]
I want to read out Custom Properties of a Blender Object using the scripting mode in Blender itself. So far I found only possibilities to read out Custom Properties you created yourself in the scripting mode. But I want to read out Custom Properties which I tagged myself per hand. This means I dont have a local variabl...
Let's say we add a custom property called 'testprop' to object 'Cube' - you can access that property within python as `bpy.data.objects['Cube']['testprop']` If you don't know the property names you can get a list of available custom properties by calling keys() for the object. This leads to the following to print the...
Making Python 2.7 code run with Python 2.6
21,268,470
7
2014-01-21T20:30:48Z
21,268,586
14
2014-01-21T20:36:41Z
[ "python", "python-2.7", "compatibility", "python-2.6" ]
I have this simply python function that can extract a zip file (platform independent) ``` def unzip(source, target): with zipfile.ZipFile(source , "r") as z: z.extractall(target) print "Extracted : " + source + " to: " + target ``` This runs fine with Python 2.7 but fails with Python 2.6: ``` Attrib...
What about: ``` import contextlib def unzip(source, target): with contextlib.closing(zipfile.ZipFile(source , "r")) as z: z.extractall(target) print "Extracted : " + source + " to: " + target ``` `contextlib.closing` does exactly what the missing `__exit__` method on the `ZipFile` would be supposed ...
datetime dtypes in pandas read_csv
21,269,399
9
2014-01-21T21:24:17Z
37,453,925
11
2016-05-26T07:11:49Z
[ "python", "csv", "datetime", "pandas", "dataframe" ]
I'm reading in a csv file with multiple datetime columns. I'd need to set the data types upon reading in the file, but datetimes appear to be a problem. For instance: ``` headers = ['col1', 'col2', 'col3', 'col4'] dtypes = ['datetime', 'datetime', 'str', 'float'] pd.read_csv(file, sep='\t', header=None, names=headers,...
# Why it does not work There is no datetime dtype to be set for read\_csv as csv files can only contain strings, integers and floats. Setting a dtype to datetime will make pandas interpret the datetime as an object, meaning you will end up with a string. # Pandas way of solving this The [`pandas.read_csv()`](http:/...
Speed up nested for loop with elements exponentiation
21,269,833
6
2014-01-21T21:51:14Z
21,270,072
7
2014-01-21T22:07:49Z
[ "python", "performance", "numpy", "scipy" ]
I'm working on a large code and I find myself in the need to speed up a specific bit of it. I've created a `MWE` shown below: ``` import numpy as np import time def random_data(N): # Generate some random data. return np.random.uniform(0., 10., N).tolist() # Lists that contain all the data. list1 = [random_da...
You want to gradually convert this over from using lists and loops to using arrays and broadcasting, grabbing the easiest and/or most time-critical parts first until it's fast enough. The first step is to not do that `zip(*list2)` over and over (especially if this is Python 2.x). While we're at it, we might as well st...
Selecting Pandas Columns by dtype
21,271,581
9
2014-01-21T23:59:08Z
21,272,615
12
2014-01-22T01:42:30Z
[ "python", "pandas", "scipy" ]
I was wondering if there is an elegant and shorthand way in Pandas DataFrames to select columns by data type (dtype). i.e. Select only int64 columns from a DataFrame. To elaborate, something along the lines of ``` df.select_columns(dtype=float64) ``` Thanks in advance for the help
``` df.loc[:, df.dtypes == np.float64] ```
Selecting Pandas Columns by dtype
21,271,581
9
2014-01-21T23:59:08Z
24,828,425
8
2014-07-18T15:15:27Z
[ "python", "pandas", "scipy" ]
I was wondering if there is an elegant and shorthand way in Pandas DataFrames to select columns by data type (dtype). i.e. Select only int64 columns from a DataFrame. To elaborate, something along the lines of ``` df.select_columns(dtype=float64) ``` Thanks in advance for the help
``` df.select_dtypes(include=[np.float64]) ```
Selecting Pandas Columns by dtype
21,271,581
9
2014-01-21T23:59:08Z
29,442,936
16
2015-04-04T05:07:53Z
[ "python", "pandas", "scipy" ]
I was wondering if there is an elegant and shorthand way in Pandas DataFrames to select columns by data type (dtype). i.e. Select only int64 columns from a DataFrame. To elaborate, something along the lines of ``` df.select_columns(dtype=float64) ``` Thanks in advance for the help
Since 0.14.1 there's a [`select_dtypes`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html) method so you can do this more elegantly/generally. ``` In [11]: df = pd.DataFrame([[1, 2.2, 'three']], columns=['A', 'B', 'C']) In [12]: df.select_dtypes(include=['int']) Out[12]: A ...
Sorting in pandas for large datasets
21,271,727
11
2014-01-22T00:11:33Z
35,139,819
7
2016-02-01T20:36:12Z
[ "python", "pandas" ]
I would like to sort my data by a given column, specifically p-values. However, the issue is that I am not able to load my entire data into memory. Thus, the following doesn't work or rather works for only small datasets. ``` data = data.sort(columns=["P_VALUE"], ascending=True, axis=0) ``` Is there a quick way to so...
In the past, I've used Linux's pair of venerable [`sort`](http://man7.org/linux/man-pages/man1/sort.1.html) and [`split`](http://linux.die.net/man/1/split) utilities, to sort massive files that choked pandas. I don't want to disparage the other answer on this page. However, since your data is text format (as you indic...
LEFT JOIN Django ORM
21,271,835
7
2014-01-22T00:21:07Z
21,272,153
13
2014-01-22T00:54:28Z
[ "python", "sql", "django", "django-models", "django-orm" ]
I have the following models: ``` class Volunteer(models.Model): first_name = models.CharField(max_length=50L) last_name = models.CharField(max_length=50L) email = models.CharField(max_length=50L) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class Department(models.Model): n...
You can do this by following the backwards relation in the lookup. ``` >>> qs = Department.objects.filter(departmentvolunteer__isnull=True).values_list('name', flat=True) >>> print(qs.query) SELECT "app_department"."name" FROM "app_department" LEFT OUTER JOIN "app_departmentvolunteer" ON ( "app_department"."id" = "app...
Python getting meaningful results from cProfile
21,274,898
9
2014-01-22T05:26:18Z
21,275,812
12
2014-01-22T06:32:16Z
[ "python", "cprofile" ]
I have a Python script in a file which takes just over 30 seconds to run. I am trying to profile it as I would like to cut down this time dramatically. I am trying to profile the script using `cProfile`, but essentially all it seems to be telling me is that yes, the main script took a long time to run, but doesn't giv...
As I mentioned in a comment, when you can't get `cProfile` to work externally, you can often use it internally instead. It's not that hard. For example, when I run with `-m cProfile` in my Python 2.7, I get effectively the same results you did. But when I manually instrument your example program: ``` import fileinput...
Normalizing a random unending unknown series?
21,276,576
7
2014-01-22T07:19:58Z
21,276,695
8
2014-01-22T07:26:57Z
[ "python", "algorithm", "math", "normalization" ]
I have an unending series with no equation, and is random, something like this, ``` X = 1, 456, 555, 556, 557, 789 ... ``` Note that I'm getting this list as a stream, and I do not know future values, and I do not know min and max of `X`. How do I find out the inverted normal `N(X)` for any `x in X`, such that, ...
OK, so you're basically looking for a continuous monotone function *N*: [0,∞) → (0,1] such that: * lim*x* → 0 *N*(*x*) = 1, and * lim*x* → ∞ *N*(*x*) = 0. In that case, the "obvious" choice would be [*N*(*x*) = 1 / (*x* + 1)](http://www.wolframalpha.com/input/?i=1+%2F+%28x+%2B+1%29), or, in Python: ``` def invnorm (...
Python ternary operator and assigment in else
21,277,896
2
2014-01-22T08:36:26Z
21,277,920
10
2014-01-22T08:37:30Z
[ "python", "python-2.7", "dictionary", "conditional-operator" ]
Ternary operator is very useful, why it does not work in this particular case: ``` c="d" d={} d[c]+=1 if c in d else d[c]=1 ``` It gives: ``` d[c]+=1 if c in d else d[c]=1 ^ SyntaxError: invalid syntax ``` I don't see nothing wrong here since the same thing without the ternary operator wo...
The ternary operator works on expressions, not statements. Assignment is a statement. Use a regular `if`/`else`.
Why doesn't Python print return values?
21,278,736
2
2014-01-22T09:20:17Z
21,278,843
7
2014-01-22T09:25:21Z
[ "python", "printing", "return" ]
I'm taking a class in Algorithms and Data Structures (Python). In the book there is an example of a "stack" with methods that return certain values. In the book, these values are printed when the methods are called. However, when I run the program nothing is printed. I have to print the return value myself. Is this a d...
At the interactive interpreter, Python will print the `repr` of expression values (except `None`) as a convenience. In a script, you have to print manually, as automatic printing would be highly awkward to work around in a script.
Getting to interactive Django shell in PyDev
21,278,915
5
2014-01-22T09:28:47Z
22,152,776
8
2014-03-03T17:04:40Z
[ "python", "django", "eclipse", "shell", "pydev" ]
I can open an interactive shell from the command line, just not from PyDev inside Eclipse. Clicking through `Django --> Shell with django environment` I get the following output: ``` import sys; print('%s %s' % (sys.executable or sys.platform, sys.version)) C:\Python27\python.exe 2.7.5 (default, May 15 2013, 22:43:36)...
`setup_environ` has been deprecated in Django 1.6. See [here](https://docs.djangoproject.com/en/1.6/internals/deprecation/#id1). As far as I can tell, PyDev has hardcoded this method of starting a Django shell into the right click project -> "shell with Django environment" menu item. This is an issue that PyDev needs ...
any way to tell if user's python environment is anaconda
21,282,363
4
2014-01-22T12:01:09Z
21,318,941
8
2014-01-23T20:45:13Z
[ "python", "anaconda" ]
i'm distributing an in-house python lib where i'd like to make it such that if the user is using anaconda when running this file, that updates to the dependencies of the library will be made automatically. (this is by request. if it were up to me, i would let the users control their own packages.) so far, i've come up...
I'm from Continuum, so let me make a quick note: You'll get a different `sys.version` string depending on whether you used `conda` to install the *Anaconda Python Distribution* or simply *Python*. So from `conda create -n full_apd anaconda` you'd get a `sys.version` string as follows: ``` $ python -c "import sys; prin...