title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python pip install module is not found. How to link python to pip location?
15,052,206
11
2013-02-24T13:30:45Z
15,052,360
16
2013-02-24T13:49:25Z
[ "python", "module", "path", "installation", "homebrew" ]
I'm a newbie and I needed the pySerial and feedparser module for my projects. I'm running Mountain lion. I followed the following tutorial so that I could upgrade to python 2.7.3 and then use the above mentioned modules. <http://hackercodex.com/guide/python-virtualenv-on-mac-osx-mountain-lion-10.8/> I followed this ...
As a quick workaround, and assuming that you are on a bash-like terminal (Linux/OSX), you can try to export the PYTHONPATH environment variable: ``` export PYTHONPATH="${PYTHONPATH}/usr/local/lib/python2.7/site-packages:/usr/lib/python2.7/site-packages" ``` For Python 2.7
python: lower() german umlauts
15,052,830
6
2013-02-24T14:43:44Z
15,052,871
8
2013-02-24T14:47:48Z
[ "python", "unicode", "diacritics", "lowercase", "case-folding" ]
I have a problem with converting uppercase letters with umlauts to lowercase ones. ``` print("ÄÖÜAOU".lower()) ``` The A, O and the U gets converted properly but the Ä,Ö and Ü stays uppercase. Any ideas? First problem is fixed with the .decode('utf-8') but I still have a second one: ``` # -*- coding: utf-8 -*...
You'll need to mark it as a unicode string unless you're working with plain ASCII; ``` > print(u"ÄÖÜAOU".lower()) äöüaou ``` It works the same when working with variables, it all depends on the type assigned to the variable to begin with. ``` > olle = "ÅÄÖABC" > print(olle.lower()) ÅÄÖabc > olle = u"Å...
Networkx: Overlapping edges when visualizing MultiGraph
15,053,686
7
2013-02-24T16:14:14Z
15,069,150
7
2013-02-25T14:21:51Z
[ "python", "python-2.7", "matplotlib", "graphviz", "networkx" ]
The following multigraph plots correctly (i.e. parallel edges do not overlap) using graphviz neato to generate a png (as shown in [this answer](http://stackoverflow.com/questions/14943439/how-to-draw-multigraph-in-networkx-using-matplotlib-or-graphviz)) ``` import networkx as nx nx.MultiGraph ([(1,2),(1,2),(1,2),(3,1)...
Unfortunately not. It is technically possible to do but so far nobody has written the code.
How does django's View class work
15,055,856
9
2013-02-24T19:47:09Z
15,056,525
11
2013-02-24T20:53:10Z
[ "python", "django", "python-2.7", "django-views", "django-generic-views" ]
I'm diving into Django's generic views, figuring out how they return a simple HttpResponse object, like a simple view function would. I have written a simple project for testing, and I added some logging commands to the basic View classed defined in the file django/views/generic/base.py, so that I can track what is h...
The underlying implementation of these views involves some fairly advanced Python, so if you're a relative beginner it's not surprising if you find some of this code confusing. 1. The main thing you should understand is what the `@classmethod` decorator does on the definition of `as_view()`. This means that this metho...
Python - Find text using beautifulSoup then replace in original soup variable
15,056,633
5
2013-02-24T21:02:15Z
15,056,692
7
2013-02-24T21:07:57Z
[ "python", "beautifulsoup" ]
``` commentary = soup.find('div', {'id' : 'live-text-commentary-wrapper'}) findtoure = commentary.find(text = re.compile('Gnegneri Toure Yaya')).replace('Gnegneri Toure Yaya', 'Yaya Toure') ``` Commentary contains various instances of Gnegneri Toure Yaya that need changing to Yaya Toure. `findAll()` doesn't work...
You cannot do what you want with *just* `.replace()`. From the [BeautifulSoup documentation on `NavigableString`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring): > You can’t edit a string in place, but you can replace one string with another, using [`replace_with()`](http://www.crummy.com/sof...
Assigning functions as attributes of an object, then calling without the implied 'self' arguement?
15,056,922
5
2013-02-24T21:36:04Z
15,056,930
8
2013-02-24T21:37:10Z
[ "python" ]
Python allows you to assign a pre-defined function to a class as an attribute, such as ``` def fish_slap(fish): # do something class dance(object): dance_move=fish_slap ``` However, if we try do say ``` d=dance() d.dance_move("Halibut") ``` we get the get the following error ``` TypeError: fish_slap() tak...
You can use a [staticmethod](http://docs.python.org/2/library/functions.html#staticmethod) ``` class dance(object): dance_move=staticmethod(fish_slap) ``` Note that you don't need to use `staticmethod` if you're assigning to an attribute of an *instance*: ``` >>> def move(): ... print "disco party!" ... >>>...
import Tkinter fails with python 2.7.3 Mac OSX 10.8.2
15,057,166
2
2013-02-24T22:01:28Z
15,057,191
8
2013-02-24T22:04:25Z
[ "python", "osx", "tkinter", "tcl", "tk" ]
I have read extensively on this problem, but not found a usable solution. Many of them suggest rebuilding python from scratch. That's a hurdle I'd like to avoid, if possible. So I am going to give this question one last, desperate shot. It shouldn't be a duplicate of the many similar questions on stackoverflow because ...
Based on the path, It seems like you probably installed python via macports. If that's the case, look for something like [`py-tkinter`](http://www.macports.org/ports.php?by=name&substr=Tkinter) -- e.g. ``` sudo port install py27-tkinter ```
Alternative for 'in' operator for nested lists
15,057,366
5
2013-02-24T22:22:07Z
15,057,380
8
2013-02-24T22:23:26Z
[ "python", "nested-lists", "in-operator" ]
If I want to find something in a list in python I can use the 'in' operator: ``` list = ['foo', 'bar'] 'foo' in list #returns True ``` But what should I do if I want to find something in a nested list? ``` list = [('foo', 'bar'), ('bar', 'foo')] 'foo' in list #returns False ``` Is it possible to do it in one row wi...
You probably want `any`: ``` >>> list = [('foo', 'bar'), ('bar', 'foo')] >>> any('foo' in e for e in list) True ``` Some sort of loop is inevitable though.
How do I tokenize a string sentence in NLTK?
15,057,945
6
2013-02-24T23:26:12Z
15,057,966
55
2013-02-24T23:28:02Z
[ "python", "nlp", "tokenize", "nltk" ]
I am using nltk, so I want to create my own custom texts just like the default ones on nltk.books. However, I've just got up to the method like ``` my_text = ['This', 'is', 'my', 'text'] ``` I'd like to discover any way to input my "text" as: ``` my_text = "This is my text, this is a nice way to input text." ``` Wh...
This is actually on the [main page of nltk.org](http://nltk.org/): ``` >>> import nltk >>> sentence = """At eight o'clock on Thursday morning ... Arthur didn't feel very good.""" >>> tokens = nltk.word_tokenize(sentence) >>> tokens ['At', 'eight', "o'clock", 'on', 'Thursday', 'morning', 'Arthur', 'did', "n't", 'feel',...
How to save and load cookies using python selenium webdriver
15,058,462
20
2013-02-25T00:33:38Z
15,058,521
44
2013-02-25T00:41:08Z
[ "python", "selenium", "webdriver" ]
How can I save all cookies in python's selenium webdriver to a txt file, then load them later? The documentation doesn't say much of anything about the getCookies function.
you can save the current cookies as a python object using pickle - for example ``` import pickle import selenium.webdriver driver = selenium.webdriver.Firefox() driver.get("http://www.google.com") pickle.dump( driver.get_cookies() , open("cookies.pkl","wb")) ``` and later to add them back: ``` import pickle import...
why using multiple threading to get the sum is correct?
15,058,925
5
2013-02-25T01:46:23Z
15,059,014
8
2013-02-25T02:01:12Z
[ "python" ]
my code is ``` import threading counter = 0 def worker(): global counter counter += 1 if __name__ == "__main__": threads = [] for i in range(1000): t = threading.Thread(target = worker) threads.append(t) t.start() for t in threads: t.join() print counter ``` ...
Don't count on `x += 1` being thread-safe. Here is [an example](http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm) where it does not work (see Josiah Carlson's comment): ``` import threading x = 0 def foo(): global x for i in xrange(1000000): x += 1 threads = [threading.Th...
Jinja2 template with extension .html on pyramid?
15,059,124
3
2013-02-25T02:17:37Z
15,059,915
17
2013-02-25T04:05:35Z
[ "python", "pyramid", "jinja2" ]
How can I use a jinja2 template with a .html extension in pyramid? For instance, I want the view configuration to look like, ``` @view_config(context=MyModel, renderer='templates/index.html') def home_view(request): ... ``` Is it possible?
``` config.add_renderer('.html', 'pyramid_jinja2.renderer_factory') ```
Check if a character equals quotes in python
15,059,478
2
2013-02-25T03:08:39Z
15,059,486
8
2013-02-25T03:09:55Z
[ "python" ]
I am iterating through a string in python and I want to check each character to see if it equals `"`. How do I go about doing this?
Like this: ``` for c in theString: if c == '"': print 'Aha!' ``` You can also directly get the index of the first quote like so: ``` theString.index('"') ```
What is the nature of the round off error here?
15,059,529
11
2013-02-25T03:15:30Z
15,059,839
9
2013-02-25T03:56:53Z
[ "python", "floating-point" ]
Can someone help me unpack what exactly is going on under the hood here? ``` >>> 1e16 + 1. 1e+16 >>> 1e16 + 1.1 1.0000000000000002e+16 ``` I'm on 64-bit Python 2.7. For the first, I would assume that since there is only a precision of 15 for float that it's just round-off error. The true floating-point answer might b...
It's just rounding as close as it can. 1e16 in floating hex is `0x4341c37937e08000`. 1e16+2 is `0x4341c37937e08001`. At this level of magnitude, the smallest difference in precision that you can represent is 2. Adding 1.0 exactly rounds down (because typically IEEE floating point math will round to an even number). ...
Getting the length of a ogg track from s3 without downloading the whole file
15,059,902
9
2013-02-25T04:04:03Z
15,109,265
9
2013-02-27T10:06:06Z
[ "python", "ogg" ]
How do I get the play length of an ogg file without downloading the whole file? I know this is posible because both the HTML5 tag and VLC can show the entire play length immediately after loading the URL, without downloading the entire file. Is there a header or something I can read. Maybe even the bitrate, which I ca...
Unfortunately there does not appear to be a way to achieve this. Mozilla's [Configuring servers for Ogg media](https://developer.mozilla.org/en-US/docs/Configuring_servers_for_Ogg_media) is very instructive. Basically: 1. Gecko uses the `X-Content-Duration` header - sent by *the web server* if it has it. This explain...
python collections.defaultdict with list of length two
15,060,530
3
2013-02-25T05:11:50Z
15,060,569
10
2013-02-25T05:14:42Z
[ "python", "defaultdict" ]
I have a situation where a key will have two values which will be updated during the program. More conretely, starting from a empty dictionary d = {}, I would like to do some thing like this: `d[a][0] += 1` or `d[a][1] += 1` where *a* is a float type which is also found while the program is running. Can I do something ...
Just read [the documentation](http://docs.python.org/2/library/collections.html#collections.defaultdict): > If `default_factory` is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned. That is, the argument to defaul...
twisted websockets import error
15,060,984
4
2013-02-25T06:00:21Z
15,064,966
7
2013-02-25T10:35:54Z
[ "python", "websocket", "twisted", "importerror" ]
I'm trying to get WebSocket working in Python with Twisted using this example: <http://twistedmatrix.com/trac/export/29073/branches/websocket-4173-2/doc/web/howto/websocket.xhtml>. Unfortunately, I'm running into an ImportError. I'm not sure what to do here. I've installed/uninstalled Twisted several times using severa...
You're linking to an example HOWTO from the `websocket-4173-2` branch. Obviously, that branch contains WebSockets code. On the other hand, Twisted trunk or any released versions do not. Read <http://twistedmatrix.com/trac/ticket/4173> for more details on how it's progressing. To work with the development code, you cou...
Maximum sum sublist?
15,062,844
20
2013-02-25T08:27:43Z
15,063,394
43
2013-02-25T09:06:07Z
[ "python", "algorithm" ]
I'm getting confused with this question at what it's trying to ask. > Write function `mssl()` (minimum sum sublist) that takes as input a list > of integers. It then computes and returns the sum of the maximum sum > sublist of the input list. The maximum sum sublist is a sublist > (slice) of the input list whose sum o...
There's actually a very elegant, very efficient solution using *dynamic programming*. It takes **O(1) space**, and **O(n) time** -- this can't be beat! Define `A` to be the input array (zero-indexed) and `B[i]` to be the maximum sum over all sublists ending at, but not including position `i` (i.e. all sublists `A[j:i]...
_csv.Error: field larger than field limit (131072)
15,063,936
68
2013-02-25T09:38:02Z
15,063,941
102
2013-02-25T09:38:02Z
[ "python", "csv" ]
I have a script reading in a csv file with very huge fields: ``` # example from http://docs.python.org/3.3/library/csv.html?highlight=csv%20dictreader#examples import csv with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) ``` However, this throws the following...
The csv file might contain very huge fields, therefore increase the `field_size_limit`: ``` import sys import csv csv.field_size_limit(sys.maxsize) ``` `sys.maxsize` works for Python 2.x and 3.x. `sys.maxint` would only work with Python 2.x ([SO: what-is-sys-maxint-in-python-3](http://stackoverflow.com/questions/137...
_csv.Error: field larger than field limit (131072)
15,063,936
68
2013-02-25T09:38:02Z
18,408,911
62
2013-08-23T17:52:10Z
[ "python", "csv" ]
I have a script reading in a csv file with very huge fields: ``` # example from http://docs.python.org/3.3/library/csv.html?highlight=csv%20dictreader#examples import csv with open('some.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(row) ``` However, this throws the following...
This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as: ``` c = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE) ```
Python: is thread still running
15,063,963
5
2013-02-25T09:39:06Z
15,064,436
12
2013-02-25T10:05:25Z
[ "python", "multithreading" ]
How do I see whether a thread has completed? I tried the following, but threads\_list does not contain the thread that was started, even when I know the thread is still running. ``` import thread import threading id1 = thread.start_new_thread(my_function, ()) #wait some time threads_list = threading.enumerate() # Wan...
The key is to start the thread using threading, not thread: ``` t1 = threading.Thread(target=my_function, args=()) t1.start() ``` Then use ``` z = t1.isAlive() ``` or ``` l = threading.enumerate() ``` You can also use join(): ``` t1 = threading.Thread(target=my_function, args=()) t1.start() t1.join() # Will only...
How to increase connection timeout using sqlalchemy with sqlite in python
15,065,037
4
2013-02-25T10:39:32Z
15,066,553
11
2013-02-25T12:04:21Z
[ "python", "sqlite", "sqlalchemy", "operationalerror" ]
I am using sqlite (v2.6.0) as database backend and using sqlalchemy(v0.7.9) to operate it. Recently I got a error `OperationalError: (OperationalError) database is locked` By searching stackoverflow a possible solution is to increase the timeout of a connection. Referece: [OperationalError: database is locked](http://...
SQLAlchemy's `create_engine()` takes an argument `connect_args` which is a dictionary that will be passed to `connect()` of the underlying DBAPI (see [Custom DBAPI `connect()` arguments](http://docs.sqlalchemy.org/en/rel_0_8/core/engines.html#custom-dbapi-connect-arguments)). [`sqlite3.connect()`](http://docs.python.or...
Imbalance in scikit-learn
15,065,833
12
2013-02-25T11:23:09Z
18,901,446
17
2013-09-19T17:39:12Z
[ "python", "scikit-learn" ]
I'm using scikit-learn in my Python program in order to perform some machine-learning operations. The problem is that my data-set has severe imbalance issues. Is anyone familiar with a solution for imbalance in scikit-learn or in python in general? In Java there's the SMOTE mechanizm. Is there something parallel in py...
In Scikit learn there are some imbalance correction techniques, which vary according with which learning algorithm are you using. Some one of them, like [Svm](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html) or [logistic regression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_...
Imbalance in scikit-learn
15,065,833
12
2013-02-25T11:23:09Z
26,980,098
12
2014-11-17T19:10:47Z
[ "python", "scikit-learn" ]
I'm using scikit-learn in my Python program in order to perform some machine-learning operations. The problem is that my data-set has severe imbalance issues. Is anyone familiar with a solution for imbalance in scikit-learn or in python in general? In Java there's the SMOTE mechanizm. Is there something parallel in py...
I found one other library here which implements undersampling and also multiple oversampling techniques including multiple SMOTE implementations and another which uses SVM: <https://github.com/fmfn/UnbalancedDataset>
How to get a matplotlib Axes instance to plot to?
15,067,668
17
2013-02-25T13:05:06Z
15,067,854
23
2013-02-25T13:14:46Z
[ "python", "matplotlib", "finance", "axes" ]
I need to make a candlestick chart (something like this) using some stock data. For this I want to use the function [matplotlib.finance.candlestick()](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/finance.py). To this function I need to supply quotes and "*an Axes instance to plot to*". I created ...
Use the "get current axes" helper function: ``` ax = plt.gca() ``` Example: ``` import matplotlib.pyplot as plt import matplotlib.finance quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)] ax = plt.gca() h = matplotlib.finance.candlestick(ax, quotes) plt.show() ``` ![e...
Calculate the difference between two times in python
15,067,710
3
2013-02-25T13:07:24Z
15,067,787
13
2013-02-25T13:11:06Z
[ "python", "time" ]
I am using python, and want to calculate the difference between two times. Actually i had scenario to calculate the difference between login and logout times, for example in organizations there is some particular limit for working hours, so if a user login at `9:00 AM` in the morning and if he logs out at `6:00 PM` in...
``` >>> start = datetime.datetime(year=2012, month=2, day=25, hour=9) >>> end = datetime.datetime(year=2012, month=2, day=25, hour=18) >>> diff = end - start >>> diff datetime.timedelta(0, 32400) >>> diff.total_seconds() 32400 >>> diff.total_seconds() / 60 / 60 9 >>> ```
LDA model generates different topics everytime i train on the same corpus
15,067,734
6
2013-02-25T13:08:28Z
15,069,580
19
2013-02-25T14:44:31Z
[ "python", "nlp", "lda", "topic-modeling", "gensim" ]
I am using python `gensim` to train an Latent Dirichlet Allocation (LDA) model from a small corpus of 231 sentences. However, each time i repeat the process, it generates different topics. **Why does the same LDA parameters and corpus generate different topics everytime?** **And how do i stabilize the topic generatio...
> Why does the same LDA parameters and corpus generate different topics everytime? Because LDA uses randomness in both training and inference steps. > And how do i stabilize the topic generation? By resetting the `numpy.random` seed to the same value every time a model is trained or inference is performed, with `num...
Flask-SQLAlchemy not creating tables using create_all()
15,068,988
3
2013-02-25T14:14:27Z
15,069,233
10
2013-02-25T14:26:16Z
[ "python", "flask", "flask-sqlalchemy" ]
I have a Flask app that is using Flask-SQLAlchemy. In my unit tests, I initialise the app and the DB, then call `db.create_all()` and for some reason it looks like it's not picking up any of my models so isn't creating any tables. I'm using both `__tablename__` and `__bind_key__` in my models as I have two databases. ...
In your unit tests you shouldn't create a new instance of the SQLAlchemy object ('db'), you should import the instance from which your models descend: models.py: ``` from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() class Contact(db.Model): ... ``` tests.py: ``` from models import db from flask imp...
Formatting latex (to_latex) output
15,069,814
11
2013-02-25T14:55:21Z
15,070,110
16
2013-02-25T15:10:52Z
[ "python", "latex", "pandas" ]
I've read [about the `to_latex`](http://stackoverflow.com/questions/14380371/export-a-latex-table-from-pandas-dataframe/14383654#14383654) method, but it's not clear **how to use the formatters argument**. I have some numbers which are **too long** and some which I want **thousand separators**. *A side [issue](https:...
For a simple data frame. First, without formatters: ``` In [11]: df Out[11]: c1 c2 first 0.821354 0.936703 second 0.138376 0.482180 In [12]: print df.to_latex() \begin{tabular}{|l|c|c|c|} \hline {} & c1 & c2 \\ \hline first & 0.821354 & 0.936703 \\ second & 0.138376 & 0.4...
Speeding up outliers check on a pandas Series
15,070,279
4
2013-02-25T15:20:31Z
15,070,735
12
2013-02-25T15:44:30Z
[ "python", "pandas", "outliers" ]
I am running an outlier check on a pandas Series object with two passes using different standard deviation criteria. However, I use two loops for that and it run extremely slow. I wonder if there is any pandas "tricks" to speed-up this step. Here is the code I am using (warning really ugly code!): ``` def find_outlie...
I'm not sure what you're doing with that block piece, but finding outliers in a Series should be as easy as: ``` In [1]: s > s.std() * 3 ``` Where s is your series and 3 ishow many standard deviations to exceed for outlier status. This expression will return a series of boolean values that you can then index the seri...
keep/slice specific columns in pandas
15,072,005
9
2013-02-25T16:48:56Z
15,073,977
8
2013-02-25T18:37:44Z
[ "python", "pandas" ]
I know about these column slice methods: `df2 = df[["col1", "col2", "col3"]]` and `df2 = df.ix[:,0:2]` but I'm wondering if there is a way to slice columns from the front/middle/end of a dataframe in the same slice without specifically listing each one. For example, a dataframe `df` with columns: col1, col2, col3, c...
IIUC, the simplest way I can think of would be something like this: ``` >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame(np.random.randn(5, 10)) >>> df[list(df.columns[:2]) + [7]] 0 1 7 0 0.210139 0.533249 1.780426 1 0.382136 0.083999 -0.392809 2 -0.237868 0.493646 -...
Get group id back into pandas dataframe
15,072,626
9
2013-02-25T17:20:46Z
15,074,395
18
2013-02-25T19:00:54Z
[ "python", "pandas", "group-by" ]
For dataframe ``` In [2]: df = pd.DataFrame({'Name': ['foo', 'bar'] * 3, ...: 'Rank': np.random.randint(0,3,6), ...: 'Val': np.random.rand(6)}) ...: df Out[2]: Name Rank Val 0 foo 0 0.299397 1 bar 0 0.909228 2 foo 0 0.517700 3 bar 0 0.929...
A lot of handy things are stored in the `DataFrameGroupBy.grouper` object. For example: ``` >>> df = pd.DataFrame({'Name': ['foo', 'bar'] * 3, 'Rank': np.random.randint(0,3,6), 'Val': np.random.rand(6)}) >>> grouped = df.groupby(["Name", "Rank"]) >>> grouped.grouper. grouped.group...
Extracting a region from an image using slicing in Python, OpenCV
15,072,736
19
2013-02-25T17:26:20Z
15,074,748
48
2013-02-25T19:21:15Z
[ "python", "opencv", "image-processing" ]
I have an image and I want to extract a region from it. I have coordinates of left upper corner and right lower corner of this region. In gray scale I do it like this: ``` I = cv2.imread("lena.png") I = cv2.cvtColor(I, cv2.COLOR_RGB2GRAY) region = I[248:280,245:288] tools.show_1_image_pylab(region) ``` I can't figure...
There is a slight difference in pixel ordering in OpenCV and Matplotlib. OpenCV follows BGR order, while matplotlib likely follows RGB order. So when you display an image loaded in OpenCV using pylab functions, you may need to convert it into RGB mode. ( I am not sure if any easy method is there). Below method demons...
Pythonic way of comparing multiple elements in a list of dictionaries
15,073,415
2
2013-02-25T18:05:05Z
15,073,441
8
2013-02-25T18:06:20Z
[ "python" ]
I have a list of dictionaries in **Python**. Each element of the list has a `type` key with the element's type. Something like this: ``` e1 = {"type": 1, "value": 23.1} e2 = {"type": 1, "value": 21.1} e3 = {"type": 2, "value": -10.1} e4 = {"type": 1, "value": -2.59} l = [e1, e2, e3, e4] ``` I would like to know if al...
First thing that comes into my head: ``` all(e['type'] == L[0]['type'] for e in L) ``` The length of set of types: ``` len(set(e['type'] for e in L)) == 1 ``` is more efficient than `all` with a generator, but not with a list: ``` >>> %timeit all(e['type'] == l[0]['type'] for e in l) 1000000 loops, best of 3: 784 ...
Python: Passing parameters by name along with kwargs
15,074,821
12
2013-02-25T19:25:53Z
15,074,848
10
2013-02-25T19:27:35Z
[ "python", "function", "arguments", "kwargs", "pass-by-name" ]
In python we can do this: ``` def myFun1(one = '1', two = '2'): ... ``` Then we can call the function and pass the arguments by their name: `myFun1(two = 'two', one = 'one')` Also we can do this: ``` def myFun2(**kwargs): print kwargs.get('one', 'nothing here') ``` `myFun2(one='one')` So i was wondering ...
The general idea is: ``` def func(arg1, arg2, ..., kwarg1=default, kwarg2=default, ..., *args, **kwargs): ... ``` You can use as many of those as you want. The `*` and `**` will 'soak up' any remaining values not otherwise accounted for. Positional arguments (provided without defaults) can't be given by keyword,...
How do I fill two (or more) numpy arrays from a single iterable of tuples?
15,075,715
8
2013-02-25T20:18:16Z
15,076,830
7
2013-02-25T21:28:58Z
[ "python", "arrays", "numpy", "iteration" ]
The actual problem I have is that I want to store a long sorted list of `(float, str)` tuples in RAM. A plain list doesn't fit in my 4Gb RAM, so I thought I could use two `numpy.ndarray`s. The source of the data is an iterable of 2-tuples. `numpy` has a `fromiter` function, but how can I use it? The number of items in...
Perhaps build a single, structured array using `np.fromiter`: ``` import numpy as np def gendata(): # You, of course, have a different gendata... for i in xrange(N): yield (np.random.random(), str(i)) N = 100 arr = np.fromiter(gendata(), dtype='<f8,|S20') ``` Sorting it by the first column, using ...
Format Python Decimal object to a specified precision
15,076,310
10
2013-02-25T20:54:25Z
15,076,346
17
2013-02-25T20:56:38Z
[ "python", "python-2.7", "python-3.x", "decimal" ]
I've spent countless hours researching, reading, testing, and ultimately confused and dismayed at Python's Decimal object's lack of the most fundamental concept: Formatting a Decimal's output to a string. Let's assume we have some strings or Decimal objects with the following values: ``` 0.0008 11.1111 222.2222...
Just use [string formatting](http://docs.python.org/2/library/stdtypes.html#str.format) or the [`format()` function](http://docs.python.org/2/library/functions.html#format): ``` >>> for dec in decimals: ... print format(dec, '.2f') ... 0.00 11.11 222.22 3333.33 1234.57 ``` `decimal.Decimal` supports the same [for...
Sorting by date with a DB in Django
15,076,691
3
2013-02-25T21:20:37Z
15,076,851
10
2013-02-25T21:30:05Z
[ "python", "django" ]
I have the following model.py. ``` from django.db import models class Address(models.Model): addr = models.CharField(max_length=150) def __unicode__(self): return u'%s' % (self.addr) class Anniversary(models.Model): date = models.DateField() def __unicode__(self): return u'%s' % (se...
You can add default ordering in a model's meta class, e.g. ``` class Person(models.Model): # fields class Meta: ordering = ('anniversary__date',) ``` then in your template it's as easy as: ``` <ul> {% for person in persons %} <li>{{ person.anniversary.date|date:"M d, Y" }} - {{ person.nam...
matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey"
15,077,364
7
2013-02-25T22:03:21Z
15,123,907
9
2013-02-27T22:38:49Z
[ "python", "matplotlib", "whitespace" ]
I have a problem which is similar to the one posted [here](http://stackoverflow.com/questions/9120749/matplotlib-limits-when-using-plot-and-imshow-in-same-axes). The difference is that I get unwanted white spaces inside the plot area when I plot two subplots which share axes via the `sharex` and `sharey` attributes. Th...
As suggested [here](https://github.com/matplotlib/matplotlib/issues/1789#issuecomment-14203547), adding: ``` ax.set_adjustable('box-forced') ax2.set_adjustable('box-forced') ``` solves the problem. ([documentation](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect))
Python: os.path.exists vs os.path.isdir
15,077,424
23
2013-02-25T22:06:56Z
15,077,441
47
2013-02-25T22:07:59Z
[ "python" ]
I'm checking to see if a directory exists, but I noticed I'm using path.exists instead of path.isdir. Both work just fine, but I'm curious as to what the advantages are for using isdir instead of exists.
`os.path.exists` will also return `True` if there's a regular file with that name. `os.path.isdir` will only return `True` if that path exists and is a directory.
Received "UnboundLocalError: local variable 'e' referenced before assignment" when the variable was initialized
15,077,506
2
2013-02-25T22:12:51Z
15,078,295
8
2013-02-25T23:08:39Z
[ "python", "exception", "exception-handling", "python-3.x", "while-loop" ]
**[Community edit to give reproducible example:]** ``` def main(): e = None print(locals()) while not e: try: raise Exception except Exception as e: pass main() ``` produces ``` ~/coding$ python3.3 quiz2.py {'e': None} Traceback (most recent call last)...
This error is caused by the new `try...except...` scope, which is a Python 3 feature. See [PEP-3110](http://www.python.org/dev/peps/pep-3110/) In Python 3, the following block ``` try: try_body except E as N: except_body ... ``` gets translated to (in Python 2.5 terms) ``` try: try_body except E, N: ...
python dictionary passed as an input to a function acts like a global in that function rather than a local
15,078,519
11
2013-02-25T23:27:28Z
15,078,615
13
2013-02-25T23:34:47Z
[ "python", "variables", "dictionary", "global", "local" ]
I am very confused by the behaviour below. Cases 1, 3, and 4 perform as I would expect, but case 2 does not. Why does case 2 allow the function to change the value of the dictionary entry globally, even though the dictionary is never returned by the function? A main reason I am using functions is to isolate everything ...
[Python's parameter passing acts a bit different than the languages you're probably used to](http://lucumr.pocoo.org/2011/7/9/python-and-pola/#pass-by-what-exactly). Instead of having explicit pass by value and pass by reference semantics, python has pass by name. You are essentially always passing the object itself, a...
JS dataTables from pandas
15,079,118
8
2013-02-26T00:20:22Z
30,087,487
9
2015-05-06T21:04:21Z
[ "python", "datatables", "pandas" ]
I want to use pandas dataFrames with dataTables. I cannot figure out how to initialize the table without an id. Is there any way to set the id in the table tag when I call df.to\_html()?
You could try this: ``` df.to_html(classes = 'my_class" id = "my_id') ``` It's like a SQL injection basically. Pandas' to\_html function uses double quotes around the class. You can use single quotes to define the classes argument, and put double quotes inside them to end pandas' class. Then put opening double quot...
Should django model object instances be passed to celery?
15,079,176
12
2013-02-26T00:26:30Z
23,847,298
7
2014-05-24T16:28:16Z
[ "python", "django", "celery" ]
``` # models.py from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) text_blob = models.CharField(max_length=50000) # tasks.py import celery @celery.task def my_task(person): # example operation: does somethin...
I believe it is better and safer to pass PK rather than the whole model object. Since PK is just a number, serialization is also much simpler. Most importantly, you can use a safer sarializer (json/yaml instead of pickle) and have a peace of mind that you won't have any problems with serializing your model. As [this](...
How can I include a folder with cx_freeze?
15,079,268
9
2013-02-26T00:36:06Z
15,429,850
13
2013-03-15T10:23:57Z
[ "python", "cx-freeze" ]
I am using cx\_freeze to deploy my application. I would like to include a entire directory since including individual files doesn't put them in a folder. How can I include a folder?
You have to set up an include files argument for the building options. You can do this in different ways, but I will show a part of my configuration. The thing I describe here is for one specific file and one specific destination. I think you can also set a path like this, but I don't have tested this yet. **Edit:** T...
'NoneType' object has no attribute 'group'
15,080,078
4
2013-02-26T02:00:23Z
15,080,093
10
2013-02-26T02:02:20Z
[ "python", "youtube", "download" ]
Can somebody help me with this code? I'm trying to make a python script that will play videos and I found this file that download's Youtube videos. I am not entirely sure what is going on and I can't figure out this error. Error: ``` AttributeError: 'NoneType' object has no attribute 'group' ``` Traceback: ``` Trac...
The error is in your line 11, your `re.search` is returning no results, ie `None`, and then you're trying to call `fmtre.group` but `fmtre` is `None`, hence the `AttributeError`. You could try: ``` def getVideoUrl(content): fmtre = re.search('(?<=fmt_url_map=).*', content) if fmtre is None: return Non...
How can I send a signal from a python program?
15,080,500
7
2013-02-26T02:50:41Z
20,972,299
8
2014-01-07T13:00:18Z
[ "python", "linux", "signals" ]
I have this code which listens to USR1 signals ``` import signal import os import time def receive_signal(signum, stack): print 'Received:', signum signal.signal(signal.SIGUSR1, receive_signal) signal.signal(signal.SIGUSR2, receive_signal) print 'My PID is:', os.getpid() while True: print 'Waiting...' ...
You can use os.kill(): ``` os.kill(os.getpid(), signal.SIGUSR1) ``` Put this anywhere in your code that you want to send the signal from.
How to post data structure like json to flask?
15,080,672
12
2013-02-26T03:08:04Z
15,088,136
15
2013-02-26T11:36:30Z
[ "python", "json", "post", "flask" ]
I have a data structure like this: ![enter image description here](http://i.stack.imgur.com/sWOtn.gif) I'm try to send it to server by $.ajax: ``` $.ajax({ type: 'POST', data: post_obj, //this is my json data dataType: 'json', url: '', success: function(e){ console.log(e); } }); ``` a...
You are sending your data encoded as query string instead of JSON. Flask is capable of processing JSON encoded data, so it makes more sense to send it like that. Here's what you need to do on the client side: ``` $.ajax({ type: 'POST', // Provide correct Content-Type, so that Flask will know how to process it....
How about 'empty if statement' in python
15,081,516
9
2013-02-26T04:45:12Z
15,081,560
9
2013-02-26T04:48:56Z
[ "python", "if-statement" ]
It's very common in C: hacking 'empty if statement' like this: ``` if(mostlyhappencondition) ;#empty statement else{ dosomething; } ``` It's working in Python? I mean, can we improve the app's performance by using that? I'd also like to know why.
I can only guess you're looking for the `pass` statement, sometimes needed to create an empty code block to prevent a syntax error. ``` if mostlyhappencondition: pass else: do_something() ``` It would be much more usual to just do this, which is logically equivalent: ``` if not mostlyhappencondition: do_...
How about 'empty if statement' in python
15,081,516
9
2013-02-26T04:45:12Z
15,081,801
15
2013-02-26T05:11:02Z
[ "python", "if-statement" ]
It's very common in C: hacking 'empty if statement' like this: ``` if(mostlyhappencondition) ;#empty statement else{ dosomething; } ``` It's working in Python? I mean, can we improve the app's performance by using that? I'd also like to know why.
There is a performance improvement if there isn't an else case in the "if", since the bytecodes don't pass execution into the "if" case. Here's some functions and the output of `dis.dis(foo)` The following sample app: ``` def foo(x): if x: pass else: return x+2 ``` Disassembles to: ``` 5 ...
Python, creating objects
15,081,542
44
2013-02-26T04:47:18Z
15,081,588
23
2013-02-26T04:51:35Z
[ "python" ]
I'm trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances. I can't seem to understand this practice problem: Create and return a student object whose name, age, and major are the same as those given as input ``` def make_student(name, age, major) ``` I jus...
Create a class and give it an `__init__` method: ``` class Student: def __init__(self, name, age, major): self.name = name self.age = age self.major = major def is_old(self): return self.age > 100 ``` Now, you can initialize an instance of the `Student` class: ``` >>> s = Stu...
Python, creating objects
15,081,542
44
2013-02-26T04:47:18Z
15,081,667
72
2013-02-26T04:58:29Z
[ "python" ]
I'm trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances. I can't seem to understand this practice problem: Create and return a student object whose name, age, and major are the same as those given as input ``` def make_student(name, age, major) ``` I jus...
``` class Student(object): name = "" age = 0 major = "" # The class "constructor" - It's actually an initializer def __init__(self, name, age, major): self.name = name self.age = age self.major = major def make_student(name, age, major): student = Student(name, age, ma...
Python, creating objects
15,081,542
44
2013-02-26T04:47:18Z
15,081,741
7
2013-02-26T05:05:04Z
[ "python" ]
I'm trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances. I can't seem to understand this practice problem: Create and return a student object whose name, age, and major are the same as those given as input ``` def make_student(name, age, major) ``` I jus...
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition - ``` # Note the added (object) - this is the preferred way of creating new classes class Student(object): name = "Unknown name" age = 0 major = "Unknown major" ``` You can create a `make_student`...
matplotlib diagrams with 2 y-axis
15,082,682
3
2013-02-26T06:21:39Z
15,082,759
7
2013-02-26T06:26:43Z
[ "python", "matplotlib" ]
In matplolib for a time line diagram can I set to y-axis different values on the left and make another y-axis to the right with other scale? I am using this: ``` import matplotlib.pyplot as plt plt.axis('normal') plt.axvspan(76, 76, facecolor='g', alpha=1) plt.plot(ts, 'b',linewidth=1.5) plt.ylabel("name",fontsize=...
You want `twinx` [example](http://matplotlib.org/examples/api/two_scales.html). The gist if it is: ``` ax = plt.gca() ax2 = ax.twinx() ``` You can then plot to the first axes with ``` ax.plot(...) ``` and the second with ``` ax2.plot(...) ``` In your case (I think) you want: ``` import matplotlib.pyplot as plt ...
loading modules by imp.load_source with same name resulting merger of the modules
15,082,857
8
2013-02-26T06:34:30Z
15,083,897
10
2013-02-26T07:44:21Z
[ "python" ]
I would like to know if the following behavior is expected or a bug. I'm using CPython2.7 Create a file x.py ``` def funcA(): print "funcA of x.py" def funcB(): print "funcB of x.py" ``` Create a file y.py ``` def funcB(): print "funcB of y.py" ``` Create a file test.py ``` import sys, imp # load x.py...
This is an expected behavior. See <http://docs.python.org/2/library/imp.html> > imp.load\_source(name, pathname[, file]) > > > Load and initialize a module implemented as a Python source file and return its module object. If the module was already initialized, it will be initialized again. The name argument is used ...
python - find the occurrence of the word in a file
15,083,119
8
2013-02-26T06:53:25Z
15,083,177
7
2013-02-26T06:57:13Z
[ "python", "file", "count", "word" ]
I am trying to find the count of words that occured in a file. I have a text file (`TEST.txt`) the content of the file is as follows: ``` ashwin programmer india amith programmer india ``` The result I expect is: ``` { 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1} ``` The code I am using is: ``` for line in o...
``` from collections import Counter; cnt = Counter (); for line in open ('TEST.txt', 'r'): for word in line.split (): cnt [word] += 1 print cnt ```
python - find the occurrence of the word in a file
15,083,119
8
2013-02-26T06:53:25Z
15,083,210
12
2013-02-26T06:59:37Z
[ "python", "file", "count", "word" ]
I am trying to find the count of words that occured in a file. I have a text file (`TEST.txt`) the content of the file is as follows: ``` ashwin programmer india amith programmer india ``` The result I expect is: ``` { 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1} ``` The code I am using is: ``` for line in o...
Use the `update` method of Counter. Example: ``` from collections import Counter data = '''\ ashwin programmer india amith programmer india''' c = Counter() for line in data.splitlines(): c.update(line.split()) print(c) ``` Output: ``` Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1}) ```
When should Flask.g be used?
15,083,967
65
2013-02-26T07:49:46Z
15,101,229
53
2013-02-26T23:06:46Z
[ "python", "flask" ]
I [saw](https://github.com/mitsuhiko/flask/blob/master/CHANGES) that `g` will move from the request context to the app context in Flask 0.10, which made me confused about the intended use of `g`. My understanding (for Flask 0.9) is that: * `g` lives in the request context, i.e., created afresh when the requests start...
[Advanced Flask Patterns](https://speakerdeck.com/mitsuhiko/advanced-flask-patterns-1), as linked by Markus, explains some of the changes to `g` in 0.10: * `g` now lives in the application context. * [Every request pushes a new application context](https://github.com/mitsuhiko/flask/blob/1949c4a9abc174bf29620f6dd8ceab...
When should Flask.g be used?
15,083,967
65
2013-02-26T07:49:46Z
33,382,823
16
2015-10-28T04:17:24Z
[ "python", "flask" ]
I [saw](https://github.com/mitsuhiko/flask/blob/master/CHANGES) that `g` will move from the request context to the app context in Flask 0.10, which made me confused about the intended use of `g`. My understanding (for Flask 0.9) is that: * `g` lives in the request context, i.e., created afresh when the requests start...
As an addendum to the information in this thread: I've been a bit confused by the behavior of `flask.g` too, but some quick testing has helped me to clarify it. Here's what I tried out: ``` from flask import Flask, g app = Flask(__name__) with app.app_context(): print('in app context, before first request context...
PrettyPrint python into a string, and not stdout
15,085,118
18
2013-02-26T09:09:15Z
15,085,269
41
2013-02-26T09:17:43Z
[ "python" ]
I'd like to use prettyprint to print out a dictionary, but into a string and not to console. This string is to be passed on to other functions. I know I can use the "stream" parameter to specify a file instead of sys.out but I want a string. How do I do that?
You should simply call the pformat function from the pprint module: ``` import pprint s = pprint.pformat(aDict) ```
TypeError: object of type 'instancemethod' has no len()
15,085,190
4
2013-02-26T09:13:01Z
15,085,215
9
2013-02-26T09:14:37Z
[ "python", "django" ]
I'm finish cleaning my project. I remove not useful apps and codes then I arrange them. After this I encountered error ``` TypeError: object of type 'instancemethod' has no len() ``` so I change it to count() but I encountered error again ``` AttributeError: 'function' object has no attribute 'count' ``` Here is my...
You forgot to put () ``` envelopes = Envelope.objects.filter(user=request.user).exclude_unallocated() ```
Is there any way to have output piped line-by-line from a currently executing python program?
15,085,237
6
2013-02-26T09:15:46Z
15,085,298
8
2013-02-26T09:19:23Z
[ "python", "bash", "grep", "pipe" ]
When piping printed output from a python script to a command like grep, the output from the script seems to only be piped to the follow-up command after completion of the entire script. For example, in a script `test_grep.py` like the following: ``` #!/usr/bin/env python from time import sleep print "message1" sleep...
You can do it: * By flushing every `print` in python * By setting stdout to be unbuffered * By setting stdout to be line-buffered You can even call `python -u` to disable buffering. --- I would go for the line-buffering option as it seems most natural. ``` open(file, mode='r', buffering=-1 ....) ``` > buffering i...
what is the use of join() in python threading
15,085,348
53
2013-02-26T09:21:55Z
15,085,527
20
2013-02-26T09:31:12Z
[ "python", "multithreading" ]
I was studying the python threading and came across [`join()`](http://docs.python.org/2/library/threading.html#threading.Thread.join). The author told that if thread is in daemon mode then i need to use `join()` so that thread can finish itself before main thread terminates. but I have also seen him using `t.join()` ...
Straight from the [docs](http://docs.python.org/2/library/threading.html#threading.Thread.join) > join([timeout]) > Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional ...
what is the use of join() in python threading
15,085,348
53
2013-02-26T09:21:55Z
15,086,113
103
2013-02-26T10:00:20Z
[ "python", "multithreading" ]
I was studying the python threading and came across [`join()`](http://docs.python.org/2/library/threading.html#threading.Thread.join). The author told that if thread is in daemon mode then i need to use `join()` so that thread can finish itself before main thread terminates. but I have also seen him using `t.join()` ...
A somewhat clumsy ascii-art to demonstrate the mechanism: the join() is presumly called by the main-thread. it could also be called by another thread, but would needlessly complicate the diagram. join-calling should be placed in the track of the main-thread, but to express thread-relation and keep it as simple as poss...
how to upload a file to directory in S3 bucket using boto
15,085,864
26
2013-02-26T09:47:53Z
15,087,468
44
2013-02-26T11:04:56Z
[ "python", "amazon-web-services", "amazon-s3", "boto" ]
I want to copy a file in s3 bucket using python. Ex : I have bucket name = test. And in bucket the bucket, I have 2 folders name "dump" & "input". Now I want to copy a file from local directory to S3 "dump" folder using python..Can any one help me?
Try this... ``` import boto import boto.s3 import sys from boto.s3.key import Key AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' bucket_name = AWS_ACCESS_KEY_ID.lower() + '-dump' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(bucket_name, location=boto.s...
how to upload a file to directory in S3 bucket using boto
15,085,864
26
2013-02-26T09:47:53Z
27,634,080
18
2014-12-24T08:48:46Z
[ "python", "amazon-web-services", "amazon-s3", "boto" ]
I want to copy a file in s3 bucket using python. Ex : I have bucket name = test. And in bucket the bucket, I have 2 folders name "dump" & "input". Now I want to copy a file from local directory to S3 "dump" folder using python..Can any one help me?
I used this and it is very simple to implement ``` import tinys3 conn = tinys3.Connection('S3_ACCESS_KEY','S3_SECRET_KEY',tls=True) f = open('some_file.zip','rb') conn.upload('some_file.zip',f,'my_bucket') ``` <https://www.smore.com/labs/tinys3/>
how to upload a file to directory in S3 bucket using boto
15,085,864
26
2013-02-26T09:47:53Z
31,112,754
11
2015-06-29T10:00:18Z
[ "python", "amazon-web-services", "amazon-s3", "boto" ]
I want to copy a file in s3 bucket using python. Ex : I have bucket name = test. And in bucket the bucket, I have 2 folders name "dump" & "input". Now I want to copy a file from local directory to S3 "dump" folder using python..Can any one help me?
No need to make it that complicated: ``` s3_connection = boto.connect_s3() bucket = s3_connection.get_bucket('your bucket name') key = boto.s3.key.Key(bucket, 'some_file.zip') with open('some_file.zip') as f: key.send_file(f) ```
Inheriting from immutable types
15,085,917
2
2013-02-26T09:50:53Z
15,085,965
7
2013-02-26T09:52:47Z
[ "python", "string", "list", "inheritance", "int" ]
I'd like to know how inheritance works for `int`, `list`, `string` and other immutable types. Basically I'd just inherit a class like this: ``` class MyInt(int): def __init__(self, value): ?!?!? ``` I can't seem to figure out, how do I set the value like it's set for `int`? If I do `self.value = value` t...
You can subclass `int`, but because it is *immutable* you need to provide a [`.__new__()` constructor hook](http://docs.python.org/3/reference/datamodel.html#object.__new__): ``` class MyInt(int): def __new__(cls, value): new_myint = super(MyInt, cls).__new__(cls, value) return new_myint ``` You d...
Behavior of exec function in Python 2 and Python 3
15,086,040
14
2013-02-26T09:57:18Z
15,087,355
17
2013-02-26T10:59:11Z
[ "python", "python-2.7", "python-3.x", "exec" ]
Following code gives different output in `Python2` and in `Python3`: ``` from sys import version print(version) def execute(a, st): b = 42 exec("b = {}\nprint('b:', b)".format(st)) print(b) a = 1. execute(a, "1.E6*a") ``` `Python2` prints: ``` 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (...
There is a big difference between `exec` in Python 2 and `exec()` in Python 3. You are treating `exec` as a function, but it really is a *statement* in Python 2. Because of this difference, you cannot change local variables in function scope in Python 3 using `exec`, even though it was possible in Python 2. Not even p...
Python: os.path.isfile won't recognise files beginning with a number
15,088,166
3
2013-02-26T11:38:02Z
15,088,237
12
2013-02-26T11:41:55Z
[ "python", "operating-system" ]
So, I'm trying to incorporate `os.path.isfile` or `os.path.exists` into my code with success in finding certain regular files(pdf,png) when searching for filenames that begin with a letter. The file naming standard that I'm using (and can't change due to the user) starts with a number and subsequently can't be found u...
You need to use raw strings, or escape your backslashes. In the filename: ``` "D:\Users\spx9gs\Project Work\Data\21022013AA.txt" ``` the `\210` will be interpreted as an octal escape code so you won't get the correct filename. Either of these will work: ``` r"D:\Users\spx9gs\Project Work\Data\21022013AA.txt" "D:\\U...
How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?
15,090,039
3
2013-02-26T13:13:44Z
15,090,077
8
2013-02-26T13:16:17Z
[ "python", "list", "sorting", "duplicates", "tuples" ]
How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate? For example, I have a list sorted by 1st element that looks like this: ``` alist = [(0.7897897,'this is a foo bar sentence'), (0.653234, 'this is a foo bar sentence'), (0.353234, 'this is a foo bar sentence'), (0.325345, 'this ...
If your `alist` is already sorted by the first element from highest to lowest: ``` alist = [(0.7897897,'this is a foo bar sentence'), (0.653234, 'this is a foo bar sentence'), (0.353234, 'this is a foo bar sentence'), (0.325345, 'this is not really a foo bar'), (0.323234, 'this is a foo bar sentence'),] seen = set() ...
How to generate URL to view when using Traversal?
15,090,863
3
2013-02-26T13:52:40Z
15,093,393
8
2013-02-26T15:48:32Z
[ "python", "pyramid", "traversal" ]
When URL Dispatch is used, we can easily generate a URL to a view because every view has a distinct route\_name like: ``` login.py: @view_config(route_name='login') index.pt: <a href="${request.route_url('login')}">Login</a> ``` But how to do this in traversal? Since there is no instance of resources 'Login' availab...
In traversal you are required to know the structure of your tree, and you must be able to load context objects on demand. The URLs are generated with respect to a context, using its location-aware properties `__name__` and `__parent__` to build the URL. ``` / |- login |- users |- 1 |- edit ``` So let's say w...
How to generate Python documentation using Sphinx with zero configuration?
15,090,894
7
2013-02-26T13:54:08Z
15,091,333
12
2013-02-26T14:16:38Z
[ "python", "python-sphinx", "documentation-generation" ]
We don't want to be maintaining documentation as well as the source code, which is evolving rapidly at the moment, yet Sphinx seems to require a frustrating amount of setup and configuration. (We just need some basic API docs.) Is there not a single command you can run inside a python project that will just iterate ove...
The `sphinx-apidoc` tool will autogenerate stubs for your modules, which might be what you want. ## Instructions * Make sure the `autodoc` module was enabled during Sphinx configuration. ``` extensions = ['sphinx.ext.autodoc'] ``` within Sphinx's `conf.py` should do the trick. * Make sure `conf.py` adjusts ...
python encoding utf-8
15,092,437
22
2013-02-26T15:06:03Z
15,092,535
33
2013-02-26T15:10:34Z
[ "python", "unicode", "encoding", "utf-8" ]
I am doing some scripts in python. I create a string that I save in a file. This string got lot of data, coming from the arborescence and filenames of a directory. According to convmv, all my arborescence is in UTF-8. I want to keep everything in UTF-8 because I will save it in MySQL after. For now, in MySQL, which is...
You don't need to encode data that is *already* encoded. When you try to do that, Python will first try to *decode* it to `unicode` before it can encode it back to UTF-8. That is what is failing here: ``` >>> data = u'\u00c3' # Unicode data >>> data = data.encode('utf8') # encoded to UTF-8 >>> data '\xc3\x...
ImportError: No module named argparse
15,093,444
19
2013-02-26T15:50:46Z
20,787,376
16
2013-12-26T15:42:17Z
[ "python", "argparse" ]
I am trying to run a Python program but get the error ``` ImportError: No module named argparse ``` I found the question [“argparse Python modules in cli”](http://stackoverflow.com/questions/7473609/argparse-python-modules-in-cli) here on StackOverflow and tried the first comment, i.e. running the command ``` py...
Try installing `argparse`: ``` easy_install argparse ```
Python list of tuples to list of int
15,096,021
9
2013-02-26T17:59:23Z
15,096,454
11
2013-02-26T18:22:27Z
[ "python", "list", "tuples" ]
So, I have `x=[(12,), (1,), (3,)]` (list of tuples) and I want `x=[12, 1, 3]` (list of integers) in best way possible? Can you please help?
You didn't say what you mean by "best", but presumably you mean "most pythonic" or "most readable" or something like that. The list comprehension given by F3AR3DLEGEND is probably the simplest. Anyone who knows how to read a list comprehension will immediately know what it means. ``` y = [i[0] for i in x] ``` Howeve...
The fastest way to read input in Python
15,096,269
8
2013-02-26T18:13:52Z
15,097,561
19
2013-02-26T19:26:07Z
[ "python", "input", "python-3.x", "readfile" ]
I want to read a huge text file that contains list of lists of integers. Now I'm doing the following: ``` G = [] with open("test.txt", 'r') as f: for line in f: G.append(list(map(int,line.split()))) ``` However, it takes about 17 secs (via timeit). Is there any way to reduce this time? Maybe, there is a w...
numpy has the functions `loadtxt` and `genfromtxt`, but neither is particularly fast. One of the fastest text readers available in a widely distributed library is the `read_csv` function in `pandas` (<http://pandas.pydata.org/>). On my computer, reading 5 million lines containing two integers per line takes about 46 se...
Understanding Global Names and Python2 and 3
15,096,941
2
2013-02-26T18:49:13Z
15,096,986
7
2013-02-26T18:50:39Z
[ "python", "python-2.7", "python-3.x" ]
As a newbie to Python, I'm kind of learning some of the differences between Python2 and 3. In working through the Python course, it seems that there are some things that need to be changed in the code to make it work in 3. Here's the code; ``` def clinic(): print "In this space goes the greeting" print "Choose...
`raw_input()` has been renamed in Python 3, use [`input()`](http://docs.python.org/3/library/functions.html#input) instead (and the old Python 2 `input()` was removed). See [PEP 3111](http://www.python.org/dev/peps/pep-3111/). See [What's new in Python 3.0](http://docs.python.org/3/whatsnew/3.0.html) for an exhaustive...
Getting Table and Column names in PyOdbc
15,098,747
9
2013-02-26T20:35:28Z
16,328,498
7
2013-05-02T00:21:17Z
[ "python", "pyodbc" ]
I'd like to retrieve the fully referenced column name from a PyOdbc Cursor. For example, say I have 2 simple tables: * `Table_1(Id, < some other fields >)` * `Table_2(Id, < some other fields >)` and I want to retrieve the joined data ``` select * from Table_1 t1, Table2 t2 where t1.Id = t2.Id ``` using pyodbc, like...
## The ***PyOdbc*** docs offer ``` # columns in table x for row in cursor.columns(table='x'): print row.column_name ``` [www.PyOdbc wiki](https://code.google.com/p/pyodbc/wiki/) The API docs are useful
How to use Python left outer join using FOR/LIST/DICTIONARY comprehensions (not SQL)?
15,099,022
4
2013-02-26T20:52:00Z
15,099,141
8
2013-02-26T20:58:43Z
[ "python", "left-join", "list-comprehension", "dictionary-comprehension" ]
I have two tuples, details below: ``` t1 = [ ['aa'], ['ff'], ['er'] ] ``` ``` t2 = [ ['aa', 11,], ['er', 99,] ] ``` and I would like to get results like these below using python method similar to SQL's LEFT OUTER JOIN: ``` res = [ ['aa', 11,], ['ff', 0,], ['er', 99,] ] ``` Please help me with this.
``` d2 = dict(t2) res = [[k[0], d2.get(k[0], 0)] for k in t1] ```
checking diagonals in 2d list (Python)
15,100,735
2
2013-02-26T22:34:31Z
15,100,815
10
2013-02-26T22:40:15Z
[ "python", "2d" ]
The initial problem: for a given 3x3 tic tac toe board check if one of the players has won. The simplest solution I have come up so far is rotating the matrix and summing up each row: ``` board [[0, 1, 2], [3, 4, 5], [6, 7, 8]] pr(board) 0 1 2 3 4 5 6 7 8 pr(zip(*board)) 0 3 6 1 4 7 2 5 8 ``` 0..9 numbers above ar...
You can get one diagonal with: ``` [r[i] for i, r in enumerate(board)] # [0, 4, 8] ``` And the opposite diagonal with: ``` [r[-i-1] for i, r in enumerate(board)] # [2, 4, 6] ```
Is there a way to listen to multiple python sockets at once
15,101,333
4
2013-02-26T23:15:11Z
15,101,551
7
2013-02-26T23:33:53Z
[ "python", "sockets" ]
can i listen to multiple sockets at once The code i am using to monitor the sockets at the moment is: ``` while True: for sock in socks: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes print "received message:", data ``` but that waits at the line: ``` data, addr = sock.recvfrom(102...
Yes, there is. You need to use non-blocking calls to receive from the sockets. Check out the [select module](http://docs.python.org/2/library/select.html) If you are reading from the sockets here is how you use it: ``` while True: # this will block until at least one socket is ready ready_socks,_,_ = select.s...
Better/Faster to Loop through set or list?
15,102,052
18
2013-02-27T00:26:45Z
15,102,079
24
2013-02-27T00:29:28Z
[ "python", "list", "loops", "set" ]
If I have a python list that is has many duplicates, and I want to iterate through each item, but not through the duplicates, is it best to use a set (as in `set(mylist)`, or find another way to create a list without duplicates? I was thinking of just looping through the list and checking for duplicates but I figured t...
Just use a `set`. Its semantics are exactly what you want: a collection of unique items. Technically you'll be iterating through the list twice: once to create the set, once for your actual loop. But you'd be doing just as much work or more with any other approach.
Better/Faster to Loop through set or list?
15,102,052
18
2013-02-27T00:26:45Z
15,102,704
8
2013-02-27T01:38:36Z
[ "python", "list", "loops", "set" ]
If I have a python list that is has many duplicates, and I want to iterate through each item, but not through the duplicates, is it best to use a set (as in `set(mylist)`, or find another way to create a list without duplicates? I was thinking of just looping through the list and checking for duplicates but I figured t...
`set` is what you want, so you should use `set`. Trying to be clever introduces subtle bugs like forgetting to add one to`max(mylist)`! Code defensively. Worry about what's faster when you determine that it is too slow. ``` range(min(mylist), max(mylist) + 1) # <-- don't forget to add 1 ```
How to display special characters in Python with print
15,102,222
7
2013-02-27T00:45:10Z
15,102,300
11
2013-02-27T00:52:53Z
[ "python", "printing" ]
In a Python program that I am writing, I need to print the © (copyright) symbol. Is there an easy way to do this? Or is it not supported in Python? Here's an example. ``` print ("\(copyright symbol here\)") ``` Just a very simple problem. Thanks!
In Python, you can put Unicode characters inside strings in three ways. (If you're using 2.x instead of 3.x, it's simpler to use a Unicode string—as in `u"…"` instead of `"…"`—and you have to use `unichr` instead of `chr`, but otherwise everything is the same.) * '©': Type it directly. + This means you will...
How to get a color of a web element using Selenium WebDriver with python?
15,102,323
8
2013-02-27T00:54:51Z
15,117,720
9
2013-02-27T16:53:00Z
[ "python", "selenium", "automation", "selenium-webdriver" ]
How do I locate the background-color of a webelement in hexadecimal format? With my current selenium webdriver python code it is returning the background-color in RGB format. **This is the html element that I am looking at** ``` div class="bar" style="background-color: #DD514C; background-image: -moz-linear-gradient(...
You're looking for `value_of_css_property('background-color')`: ``` rgb = find_element_by_class_name("bar").value_of_css_property('background-color') ``` However, this will return the string `rgb(221, 81, 76)`. In order to get the hex value of it, you can use @unutbu's answer: ``` import re ... rgb = find_element_by...
How to update Python?
15,102,943
75
2013-02-27T02:07:40Z
17,954,487
65
2013-07-30T18:20:15Z
[ "python", "python-2.7", "installation", "upgrade", "windows-7-x64" ]
I have version 2.7 installed from early 2012. I can't find any consensus on whether I should completely uninstall and wipe this version before putting on the latest version. "Soft"-removing old versions? Hard-removing/wiping old versions? Installing over top? I've seen somewhere a special install/upgrade process usin...
### **UPDATES**: 2016-05-16 * [Anaconda](https://docs.continuum.io/anaconda/install#windows-install) and [MiniConda](http://conda.pydata.org/docs/install/quick.html#windows-miniconda-install) can be used with an existing Python installation by disabling the options to alter the Windows `PATH` and Registry. After extra...
What does the comma in this assignment statement do?
15,103,786
2
2013-02-27T03:43:42Z
15,103,796
7
2013-02-27T03:44:24Z
[ "python", "matplotlib" ]
I was looking through an interesting example script I found (at [this site](http://jakevdp.github.com/blog/2012/08/18/matplotlib-animation-tutorial/), last example line 124), and I'm struggling to understand what the comma after `particles` achieves in this line: ``` particles, = ax.plot([], [], 'bo', ms=6) ``` The s...
It is needed to unpack the 1-tuple (or any other length-1 sequence). Example: ``` >>> a,b = (1,2) >>> print a 1 >>> print b 2 >>> c, = (3,) >>> print c 3 >>> d = (4,) >>> print d (4,) ``` Notice the difference between c and d. Note that: ``` a, = (1,2) ``` fails because you need the same number of items on the lef...
Compare only time part in datetime - Python
15,105,112
9
2013-02-27T05:51:13Z
15,105,365
16
2013-02-27T06:11:06Z
[ "python", "datetime", "python-2.x" ]
I want to compare only time part in datetime. I have different dates with only time field to compare. Since dates are different and only time part i want to consider So i think creating two datetime object will not help. my string as ``` start="22:00:00" End="03:00:00" Tocompare="23:30:00" ``` Above are strings when ...
Just call the time() *method* of the datetime objects to get their hours, minutes, seconds and microseconds. ``` dt=datetime.strptime(start,"%H:%M:%S").time() ```
++i operator in Python
15,105,892
5
2013-02-27T06:51:42Z
15,105,924
13
2013-02-27T06:53:46Z
[ "java", "python" ]
I'm trying to translate one of my Java projects to Python and I'm having trouble with one certain line. The Java code is: ``` if (++j == 9) return true; ``` What I think this is supposed to be in python is ``` if (j += 1) ==9: return True ``` ...but I am getting an error `SyntaxError: invalid syntax`. ...
Yes, that is indeed a syntax error. You probably want: ``` j += 1 if j == 9: return True ``` The reason is because python requires an *expression* after the `if` keyword ([docs](http://docs.python.org/2/reference/compound_stmts.html#the-if-statement)), whereas `j += 1` is a *statement*. --- And congratulations, ...
Very Very Large Number Python
15,106,713
3
2013-02-27T07:49:56Z
15,106,806
8
2013-02-27T07:54:54Z
[ "python", "biginteger" ]
I've searched the databases and cookbooks but can't seem to find the right answer. I have a very simple python code which sums up self powers in a range. I need the last ten digits of this very, very large number and I've tried the getcontext().prec however I'm still hitting a limit. Here's the code: ``` def SelfPowe...
If you want the *last ten digits* of a number, don't compute the whole thing (it will take too much memory and time). Instead, consider using the "three-argument" form of `pow` to compute powers mod a specific base, and you will find the problem is much easier.
Parameterized reusable blocks with Jinja2 (Flask) templating engine
15,106,741
5
2013-02-27T07:51:14Z
15,107,360
10
2013-02-27T08:30:50Z
[ "python", "flask", "jinja2" ]
In Jinja2 templating engine (using Flask), I want to achieve something like that: ``` {% reusable_block avatar(user) %} <img src='{{ user.avatar }}' title='{{ user.name }}'/> {% reusable_block %} ``` and then in various places: ``` {% for u in users %} {% call avatar(u) %} {% endfor %} ``` However I can't...
You can use macros. ``` {% macro input(name, value='', type='text', size=20) -%} <input type="{{ type }}" name="{{ name }}" value="{{value|e }}" size="{{ size }}"> {%- endmacro %} <p>{{ input('username') }}</p> <p>{{ input('password', type='password') }}</p> ``` More documentation [here](http://jinja.pocoo.org/...
Loading a dataset from file, to use with sklearn
15,109,165
3
2013-02-27T10:02:13Z
15,109,783
7
2013-02-27T10:31:17Z
[ "python", "dataset", "scikit-learn" ]
I saw that with sklearn we can use some predefined datasets, for example `mydataset = datasets.load_digits()` the we can get an array (a numpy array?) of the dataset `mydataset.data` and an array of the corresponding labels `mydataset.target`. However I want to load my own dataset to be able to use it with sklearn. How...
You can use numpy's genfromtext function (<http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html>) ``` import numpy as np mydata = np.genfromtext(filename, delimiter=",") ``` However, if you have textual columns, using genfromtxt is trickier, since you need to specify the data types. It will be m...
set pythonpath before import statements
15,109,548
14
2013-02-27T10:20:21Z
15,109,660
17
2013-02-27T10:24:43Z
[ "python", "path", "pythonpath" ]
My code is: ``` import scriptlib.abc import scriptlib.xyz def foo(): ... some operations ``` but the scriptlib is in some other directory, so I will have to include that directory in environment variable "PYTHONPATH". Is there anyway in which I can first add the scriptlib directory in environment variable "PYTHON...
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are...
subprocess.call using string vs using list
15,109,665
10
2013-02-27T10:25:05Z
15,109,975
16
2013-02-27T10:40:40Z
[ "python", "subprocess" ]
I am trying to use rsync with subprocess.call. Oddly, it works if I pass subprocess.call a string, but it won't work with a list (ala, Python's doc). ### calling sp.call with a string: ``` In [23]: sp.call("rsync -av content/ writings_raw/", shell=True) sending incremental file list sent 6236 bytes received 22 byte...
`subprocess`'s rules for handling the command argument are actually a bit complex. From [the docs](http://docs.python.org/2/library/subprocess.html): > `args` should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in `args` if `args` is a sequence. If `...
Why is my astronomy simulation inaccurate?
15,111,229
2
2013-02-27T11:42:30Z
15,111,343
10
2013-02-27T11:48:03Z
[ "python", "floating-point", "simulation", "astronomy" ]
I've made a program that simulates movement of bodies in the solar system, however, I'm getting various inaccuracies in my results. I believe that it probably has something to do with my integration method. --- tl;dr there's a slight difference between the position and velocity of Earth between my simulation and NAS...
The integration method is *very* important. You are using Euler explicit method, which is of low order precision, too low for proper physics simulation. Now, you get choices * General behaviour matters most : [Verlet method](http://en.wikipedia.org/wiki/Verlet_integration), or [Beeman method](http://en.wikipedia.org/w...
what is a reason to use ndarray instead of python array
15,111,230
4
2013-02-27T11:42:34Z
15,111,278
7
2013-02-27T11:44:37Z
[ "python", "numpy", "multidimensional-array" ]
I build a class with some iteration over coming data. The data are in an array form without use of numpy objects. On my code I often use `.append` to create another array. At some point I changed one of the big array 1000x2000 to numpy.array. Now I have an error after error. I started to convert all of the arrays into ...
NumPy and Python arrays share the property of being efficiently stored in memory. NumPy arrays can be added together, multiplied by a number, you can calculate, say, the sine of all their values in one function call, etc. As HYRY pointed out, they can also have more than one dimension. You cannot do this with Python a...
what is a reason to use ndarray instead of python array
15,111,230
4
2013-02-27T11:42:34Z
15,111,407
7
2013-02-27T11:50:53Z
[ "python", "numpy", "multidimensional-array" ]
I build a class with some iteration over coming data. The data are in an array form without use of numpy objects. On my code I often use `.append` to create another array. At some point I changed one of the big array 1000x2000 to numpy.array. Now I have an error after error. I started to convert all of the arrays into ...
There are at least two main reasons for using NumPy arrays: * NumPy arrays require less space than Python lists. So you can deal with more data in a NumPy array (in-memory) than you can with Python lists. * NumPy arrays have a vast library of functions and methods unavailable to Python lists or Python arrays. Yes, ...
How does sklearn.svm.svc's function predict_proba() work internally?
15,111,408
21
2013-02-27T11:50:57Z
15,112,563
43
2013-02-27T12:49:19Z
[ "python", "svm", "scikit-learn" ]
I am using [sklearn.svm.svc](http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html) from [scikit-learn](http://scikit-learn.org/stable/) to do binary classification. I am using its predict\_proba() function to get probability estimates. Can anyone tell me how predict\_proba() internally calculates the p...
Scikit-learn uses LibSVM internally, and this in turn uses [Platt scaling](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639), as detailed in [this note by the LibSVM authors](http://www.csie.ntu.edu.tw/~cjlin/papers/plattprob.pdf), to calibrate the SVM to produce probabilities in addition to class predic...
How do I test one variable against multiple values?
15,112,125
190
2013-02-27T12:26:23Z
15,112,149
261
2013-02-27T12:27:40Z
[ "python", "if-statement", "comparison", "match", "boolean-logic" ]
I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say: ``` x = 0 y = 1 z = 3 Mylist = [] if x or y or z == 0 : Mylist.append("c") elif x or y or z == 1 : Mylist.append("d")...
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for: ``` if x == 1 or y == 1 or z == 1: ``` `x` and `y` are otherwise evaluated on their own (`False` if `0`, `True` otherwise). You ca...