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
Numpy slice of arbitrary dimensions
12,116,830
14
2012-08-24T21:21:43Z
12,116,854
23
2012-08-24T21:24:33Z
[ "python", "numpy" ]
I would like to slice a numpy array to obtain the i-th index in the last dimension. For a 3D array, this would be: ``` slice = myarray[:,:,i] ``` But I am writing a function where I can take an array of arbitrary dimensions, so for a 4D array I'd need `myarray[:,:,:,i]`, and so on. Is there a way I can obtain this sl...
There is `...` or `Ellipsis`, which does exactly this: ``` slice = myarray[...,i] ``` Ellipsis is the python object, if you should want to use it outside the square bracket notation.
Python create dict from other dict
12,117,080
7
2012-08-24T21:46:22Z
12,117,094
13
2012-08-24T21:48:59Z
[ "python" ]
What is the best way to create a dict with some attributes from other dict with Python? Example: From this dict: ``` dict1 = { name: 'Jaime', last_name: 'Rivera', phone_number: '111111', email: 'test@gmail.com', password : 'xxxxxxx', token: 'xxxxxxx', sec...
For instance: ``` keys = ['name', 'last_name', 'phone_number', 'email'] dict1 = {x:dict1[x] for x in keys} ```
Python create dict from other dict
12,117,080
7
2012-08-24T21:46:22Z
12,117,097
7
2012-08-24T21:49:21Z
[ "python" ]
What is the best way to create a dict with some attributes from other dict with Python? Example: From this dict: ``` dict1 = { name: 'Jaime', last_name: 'Rivera', phone_number: '111111', email: 'test@gmail.com', password : 'xxxxxxx', token: 'xxxxxxx', sec...
Using dict comprehension: ``` required_fields = ['name', 'last_name', 'phone_number', 'email'] dict2 = {key:value for key, value in dict1.items() if key in required_fields} ```
Python 'hide' methods with __
12,117,087
3
2012-08-24T21:47:39Z
12,117,110
7
2012-08-24T21:50:28Z
[ "python", "oop", "inheritance" ]
Today I see that - python add `_$CLASSNAME$` to methods with name with `__`. Simple example: ``` >>> class A: ... def a(self): ... self.b() ... def b(self): ... print('A.b') ... >>> class B(A): ... def b(self): ... print('B.b') ... >>> B().a() ...
It's called name mangling and done to prevent accidental name collisions with parent and child classes. You cannot (and should not, a lot of perfectly fine code uses it) disable it. You can circumvent it, but you should not do that either (it's extremely ugly, you can avoid it, and when you need access to it you should...
Python 'hide' methods with __
12,117,087
3
2012-08-24T21:47:39Z
12,117,171
8
2012-08-24T21:57:56Z
[ "python", "oop", "inheritance" ]
Today I see that - python add `_$CLASSNAME$` to methods with name with `__`. Simple example: ``` >>> class A: ... def a(self): ... self.b() ... def b(self): ... print('A.b') ... >>> class B(A): ... def b(self): ... print('B.b') ... >>> B().a() ...
While none of this is strictly enforced by python, the naming convention of a double underscore means "private", while a single underscore means "protected". A double underscore is meant to protect subclasses from causing errors by using the same name. By namespacing them by class name, the defining class can be sure ...
How can I get the Dropbox folder location programmatically in Python?
12,118,162
14
2012-08-25T00:18:35Z
12,118,327
16
2012-08-25T00:54:23Z
[ "python", "folder", "dropbox" ]
I have a script that is intended to be run by multiple users on multiple computers, and they don't all have their Dropbox folders in their respective home directories. I'd hate to have to hard code paths in the script. I'd much rather figure out the path programatically. Any suggestions welcome. EDIT: I am not using ...
I found the answer [here](http://stackoverflow.com/questions/9660280/how-do-i-programmatically-locate-my-dropbox-folder-using-c?rq=1). Setting `s` equal to the 2nd line in `~\AppData\Roaming\Dropbox\host.db` and then decoding it with base64 gives the path. ``` def _get_appdata_path(): import ctypes from ctypes...
flaskr tutorial; can't import flaskr (initialize database)
12,118,192
9
2012-08-25T00:25:41Z
38,321,520
11
2016-07-12T06:31:43Z
[ "python", "import", "flask" ]
I'm new to programming, and tried to work through the flask tutorial. <http://flask.pocoo.org/docs/tutorial/> I'm stuck on this part (from the readme on github) when trying to run the app: <https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/> Fire up a python shell and run this: ``` from flaskr import in...
The thing that fixed it for me was changing ``` export FLASK_APP=flaskr ``` to ``` export FLASK_APP=flaskr.py ``` Taken from [here](https://github.com/pallets/flask/issues/1902)
Secure static files with flask
12,118,355
5
2012-08-25T01:02:16Z
12,118,485
9
2012-08-25T01:36:38Z
[ "python", "security", "static", "flask", "password-protection" ]
I am building a flask application, and I want it to serve some static files only if the user is authenticated. It's a very low-traffic application (for internal use only). How would I go about this? One thing I was thinking of is using serve\_static(), and putting that behind an authentication check but that uses the s...
Simply subclass `flask.Flask` and override the [`send_static_file`](http://flask.pocoo.org/docs/api/#flask.Flask.send_static_file) method: ``` class SecuredStaticFlask(Flask): def send_static_file(self, filename): # Get user from session if user.is_authenticated(): return super(SecuredS...
Efficient way to remove keys with empty values from a dict
12,118,695
52
2012-08-25T02:35:11Z
12,118,700
84
2012-08-25T02:36:42Z
[ "python", "dictionary" ]
I have a dict and would like to remove all the keys for which there are empty values. ``` metadata = {u'Composite:PreviewImage': u'(Binary data 101973 bytes)', u'EXIF:CFAPattern2': u''} ``` What is the best way to do this?
`dict((k, v) for k, v in metadata.iteritems() if v)` Note that all of your keys have values. It's just that some of those values are the empty string. There's no such thing as a key in a dict without a value; if it didn't have a value, it wouldn't be in the dict.
Efficient way to remove keys with empty values from a dict
12,118,695
52
2012-08-25T02:35:11Z
12,118,839
11
2012-08-25T03:09:03Z
[ "python", "dictionary" ]
I have a dict and would like to remove all the keys for which there are empty values. ``` metadata = {u'Composite:PreviewImage': u'(Binary data 101973 bytes)', u'EXIF:CFAPattern2': u''} ``` What is the best way to do this?
If you really need to modify the original dictionary: ``` empty_keys = [k for k,v in metadata.iteritems() if not v] for k in empty_keys: del metadata[k] ``` Note that we have to make a list of the empty keys because we can't modify a dictionary while iterating through it (as you may have noticed). This is less ex...
Efficient way to remove keys with empty values from a dict
12,118,695
52
2012-08-25T02:35:11Z
21,482,035
43
2014-01-31T14:07:19Z
[ "python", "dictionary" ]
I have a dict and would like to remove all the keys for which there are empty values. ``` metadata = {u'Composite:PreviewImage': u'(Binary data 101973 bytes)', u'EXIF:CFAPattern2': u''} ``` What is the best way to do this?
It can get even shorter than [BrenBarn's solution](http://stackoverflow.com/a/12118700/1641609) (and more readable I think) ``` {k: v for k, v in metadata.items() if v} ``` Tested with Python 2.7.3.
Python: tf-idf-cosine: to find document similarity
12,118,720
40
2012-08-25T02:41:26Z
12,124,981
13
2012-08-25T19:27:53Z
[ "python", "machine-learning", "nltk", "information-retrieval", "tf-idf" ]
I was following a tutorial which was available at [Part 1](http://blog.christianperone.com/?p=1589) & [Part 2](http://blog.christianperone.com/?p=1747) unfortunately author didn't have time for the final section which involves using cosine to actually find the similarity between two documents. I followed the examples i...
WIth the Help of @excray's comment, I manage to figure it out the answer, What we need to do is actually write a simple for loop to iterate over the two arrays that represent the train data and test data. First implement a simple lambda function to hold formula for the cosine calculation: ``` cosine_function = lambda...
Python: tf-idf-cosine: to find document similarity
12,118,720
40
2012-08-25T02:41:26Z
12,128,777
86
2012-08-26T08:45:15Z
[ "python", "machine-learning", "nltk", "information-retrieval", "tf-idf" ]
I was following a tutorial which was available at [Part 1](http://blog.christianperone.com/?p=1589) & [Part 2](http://blog.christianperone.com/?p=1747) unfortunately author didn't have time for the final section which involves using cosine to actually find the similarity between two documents. I followed the examples i...
First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with `TfidfVectorizer`: ``` >>> from sklearn.feature_extraction.text import TfidfVectorizer >>> from sklearn.datasets import fetch_20newsgroups >>> twenty = fetch_20newsgr...
Python: tf-idf-cosine: to find document similarity
12,118,720
40
2012-08-25T02:41:26Z
18,914,884
11
2013-09-20T10:48:00Z
[ "python", "machine-learning", "nltk", "information-retrieval", "tf-idf" ]
I was following a tutorial which was available at [Part 1](http://blog.christianperone.com/?p=1589) & [Part 2](http://blog.christianperone.com/?p=1747) unfortunately author didn't have time for the final section which involves using cosine to actually find the similarity between two documents. I followed the examples i...
I know its an old post. but I tried the <http://scikit-learn.sourceforge.net/stable/> package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that ``` from sklearn.feature_extraction.text import CountVectorizer from...
How to make a PyQT4 window jump to the front?
12,118,939
13
2012-08-25T03:30:14Z
12,119,488
9
2012-08-25T05:38:43Z
[ "python", "pyqt4" ]
I want to make a PyQT4 window(`QtGui.QMainWindow`) jump to the front when the application received a specified message from another machine. Usually the window is minimized. I tried the `raise_()` and `show()` method but it doesn't work.
This works: ``` # this will remove minimized status # and restore window with keeping maximized/normal state window.setWindowState(window.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) # this will activate the window window.activateWindow() ``` Both are required for me on Win7. `setWindowStat...
Nicer way to iterate to dictionary in python to avoid many nested for loops
12,119,612
7
2012-08-25T05:59:11Z
12,119,636
8
2012-08-25T06:03:36Z
[ "python", "python-2.6" ]
Is there a better way to iterate to my dictionary data without using 3 nested `for loops` like what I am currently doing given this data below? Btw, i am using python 2.6. ``` data = {'08132012': { 'id01': [{'code': '02343','status': 'P'},{'code': '03343','status': 'F'}], 'id02': [{...
Given the nested nature of the data, I don't think there's any way avoid some nested loops somewhere. However, you can avoid having to nest most of your program logic by writing a flattening generator for your data, like so: ``` def flatten(data): for date in data: for id in data[date]: for tr...
Simple example of retrieving 500 items from dynamodb using Python
12,122,006
8
2012-08-25T12:32:57Z
12,144,390
11
2012-08-27T14:52:01Z
[ "python", "amazon-dynamodb" ]
Looking for a simple example of retrieving 500 items from dynamodb minimizing the number of queries. I know there's a "multiget" function that would let me break this up into chunks of 50 queries, but not sure how to do this. I'm starting with a list of 500 keys. I'm then thinking of writing a function that takes this...
Depending on you scheme, There are 2 ways of efficiently retrieving your 500 items. ## 1 Items are under the same `hash_key`, using a `range_key` * Use the `query` method with the `hash_key` * you may ask to sort the `range_keys` A-Z or Z-A ## 2 Items are on "random" keys * You said it: use the `BatchGetItem` metho...
Python JSON encoder to support datetime?
12,122,007
9
2012-08-25T12:33:41Z
12,126,976
12
2012-08-26T01:21:10Z
[ "python", "mysql", "json", "ios5", "tornado" ]
is there any elegant way to make Python JSON encoder support datetime? some 3rd party module or easy hack? I am using tornado's database wrapper to fetch some raws from db to generate a json. The query result includes a regular MySQL timestamp column. It's quite annoying that Python's default json encoder doesn't sup...
[The docs suggest](http://docs.python.org/library/json.html#json.JSONEncoder.default) subclassing JSONEncoder and implementing your own default method. Seems like you're basically there, and it's not a "dirty hack". The reason dates aren't handled by the default encoder is there is no standard representation of a date...
How to determine from a python application if X server/X forwarding is running?
12,122,671
6
2012-08-25T14:05:56Z
12,123,396
7
2012-08-25T15:46:40Z
[ "python", "ssh", "pyqt4", "xserver" ]
I'm writing a linux application which uses PyQt4 for GUI and which will only be used during remote sessions (*ssh -XY* / *vnc*). So sometimes it may occur that a user will forget to run *ssh* with X forwarding parameters or X forwarding will be unavailable for some reason. In this case the application crashes badly...
Check to see that the `$DISPLAY` environment variable is set - if they didn't use `ssh -X`, it will be empty (instead of containing something like `localhost:10`).
How to run a wxPython GUI app in Sublime Text 2
12,122,980
6
2012-08-25T14:51:11Z
12,591,209
12
2012-09-25T21:19:13Z
[ "python", "wxpython", "sublimetext2" ]
I just started to use Sublime Text 2. I use Sublime for python, but when I use `CTRL`+`B` it does not run my wxPython GUI app. It *can* run a Tkinter app. Why is this? What do I need to do to run a wxPython app from Sublime?
To prevent the console window from popping up under Windows, it is suppressed in the `Packages\Default\exec.py` module. An unfortunate side effect is that wxPython gui's are also suppressed. Just comment out the last line in the following section of the `Packages\Default\exec.py` file like so: ``` if os.name == "nt":...
Python argparse required=True but --version functionality?
12,123,568
14
2012-08-25T16:08:54Z
12,123,598
30
2012-08-25T16:13:50Z
[ "python", "command-line-arguments", "argparse" ]
In all my scripts I use the standard flags `--help` and `--version` however I cannot seem to figure out how to make a `--version` with `parser.add_argument(..., required=True)`. ``` import sys, os, argparse parser = argparse.ArgumentParser(description='How to get --version to work?') parser.add_argument('--version',...
There is a special *version* `action` keyword argument to `add_argument` (As documented here: [argparse#action](http://docs.python.org/library/argparse.html#action)). Try this (copied from working code): ``` parser.add_argument('-V', '--version', action='version', ...
Print statements without new lines in python?
12,124,026
3
2012-08-25T17:10:35Z
12,124,059
13
2012-08-25T17:14:15Z
[ "python" ]
I was wondering if there is a way to print elements without newlines such as ``` x=['.','.','.','.','.','.'] for i in x: print i ``` and that would print `........` instead of what would normally print which would be ``` . . . . . . . . ``` Thanks!
This can be easily done with the [print()](http://docs.python.org/release/3.0.1/whatsnew/3.0.html) *function* with **Python 3**. ``` for i in x: print(i, end="") # substitute the null-string in place of newline ``` will give you ``` ...... ``` In **Python v2** you can use the `print()` function by including: ``...
Splitting a string by capital letters
12,124,275
2
2012-08-25T17:46:02Z
12,124,319
16
2012-08-25T17:52:09Z
[ "python" ]
I currently have the following code, which finds capital letters in a string 'formula': <http://pastebin.com/syRQnqCP> Now, my question is, how can I alter that code (Disregard the bit within the "if choice = 1:" loop) so that each part of that newly broken up string is put into it's own variable? For example, puttin...
I think there is a far easier way to do what you're trying to do. Use regular expressions. For instance: ``` >>> [a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a] ['Mg', u'S', u'O', u'4'] ``` If you want the number attached to the right element, just add a digit specifier in the regex: ``` >>> [a for a in re.spl...
Splitting a string by capital letters
12,124,275
2
2012-08-25T17:46:02Z
12,124,400
7
2012-08-25T18:05:39Z
[ "python" ]
I currently have the following code, which finds capital letters in a string 'formula': <http://pastebin.com/syRQnqCP> Now, my question is, how can I alter that code (Disregard the bit within the "if choice = 1:" loop) so that each part of that newly broken up string is put into it's own variable? For example, puttin...
You can use re.split to perform complex splitting on strings. ``` import re def split_upper(s): return filter(None, re.split("([A-Z][^A-Z]*)", s)) >>> split_upper("fooBarBaz") ['foo', 'Bar', 'Baz'] >>> split_upper("fooBarBazBB") ['foo', 'Bar', 'Baz', 'B', 'B'] >>> split_upper("fooBarBazBB4") ['foo', 'Bar', 'Baz'...
Super class of python
12,124,284
6
2012-08-25T17:47:26Z
12,124,352
11
2012-08-25T17:57:32Z
[ "python", "superclass" ]
Since type is the superclass of all classes,why `isinstance(1,type)` gives as `False`? Am I understanding the concept wrong?
`type` isn't the superclass of all classes. It is the type of all classes (that don't have a custom metaclass). Note the difference: ``` >>> isinstance(1, int) True >>> isinstance(1, type) False >>> isinstance(int, type) True ``` The number 1 is not an instance of type. Rather, the `int` type itself is an instance of...
changing default x range in histogram matplotlib
12,125,880
7
2012-08-25T21:42:57Z
12,126,513
19
2012-08-25T23:35:09Z
[ "python", "matplotlib", "histogram", "xrange" ]
I would like to change the default x range for the histogram plot. The range of the data is from 7 to 12. However, by default the histogram starts right at 7 and ends at 13. I want it to start at 6.5 and end at 12.5. However, the ticks should go from 7 to 12.How do I do it? ``` import asciitable import numpy as np im...
``` hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid') ```
Subtracting Dates With Python
12,126,318
7
2012-08-25T22:59:09Z
12,126,343
10
2012-08-25T23:04:17Z
[ "python", "date", "time" ]
I'm working on a simple program to tell an individual how long they have been alive. I know how to get the current date, and get their birthday. The only problem is I have no way of subtracting the two, I know a way of subtracting two dates, but unfortunately it does not include hours, minutes, or seconds. I am looki...
``` from datetime import datetime birthday = datetime(1988, 2, 19, 12, 0, 0) diff = datetime.now() - birthday print diff # 8954 days, 7:03:45.765329 ```
Run several python programs at the same time
12,126,655
6
2012-08-26T00:04:44Z
12,126,729
10
2012-08-26T00:20:07Z
[ "python", "bash" ]
I have python script **run.py**: ``` def do(i): # doing something with i, that takes time start_i = sys.argv[1] end_i = sys.argv[2] for i in range(start_i, end_i): do(i) ``` Then I run this script: ``` python run.py 0 1000000 ``` After 30 minutes script is completed. But, it's too long for me. So, I creat...
You're looking for the [multiprocessing](http://docs.python.org/library/multiprocessing.html) package, and especially the `Pool` class: ``` from multiprocessing import Pool p = Pool(5) # like in your example, running five separate processes p.map(do, range(start_i, end_i)) ``` Besides consolidating this into a singl...
Python constructor argument not random bug?
12,127,148
4
2012-08-26T02:16:13Z
12,127,165
13
2012-08-26T02:20:20Z
[ "python", "random" ]
I've just recently found this weird Python 'bug' and I wanted to see if anyone knew more about it! for instance take the python module: ``` import random class SaySomething: def __init__(self, value=random.randint(1, 3)): if value == 1: print 'one' elif value == 2: print 'two' elif value ...
The problem is that the default arguments in Python are evaluated once, when the function is created. To fix this, try: ``` def __init__(self, value = None): if value is None: value = random.randint(1, 3) if value == 1: print 'one' elif value == 2: print 'two' elif val...
Error: "MSVCP90.dll: No such file or directory" even though Microsoft Visual C++ 2008 Redistributable Package is installed
12,127,869
16
2012-08-26T05:37:46Z
12,153,700
11
2012-08-28T06:16:00Z
[ "python", "visual-c++", "python-2.7", "py2exe" ]
I'm trying to build a package from source by executing `python setup.py py2exe` This is the section of code from setup.py, I suppose would be relevant: ``` if sys.platform == "win32": # For py2exe. import matplotlib sys.path.append("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC...
I would recommend ignoring the dependency outright. Add `MSVCP90.dll` to the list of `dll_excludes` given as an option to `py2exe`. Users will have to install the Microsoft Visual C++ 2008 redistributable. An example: ``` setup( options = { "py2exe":{ ... "dll_excludes": ["MSVCP...
Why is this Python Borg / Singleton pattern working
12,127,925
2
2012-08-26T05:52:56Z
12,127,945
10
2012-08-26T05:58:00Z
[ "python", "singleton" ]
i just stumbled around the net and found these interesting code snipped: <http://code.activestate.com/recipes/66531/> ``` class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # and whatever else you want in your class -- that's all! ``` I understand what a singl...
Because the ~~class's~~ instance's `__dict__` is set equal to the `__share_state` dict. They point to the *same object*. (`Classname.__dict__` holds all of the class attributes) When you do: ``` b1.foo = "123" ``` You're modifying the `dict` that both `b1.__dict__` and `Borg.__shared_state` refer to.
Python random lines from subfolders
12,128,948
6
2012-08-26T09:17:47Z
12,134,726
14
2012-08-26T23:28:25Z
[ "python", "python-3.x", "random-sample" ]
I have many tasks in .txt files in multiple sub folders. I am trying to pick up a total 10 tasks randomly from these folders, their contained files and finally a text line within a file. The selected line should be deleted or marked so it will be not picked in the next execution. This may be too broad a question but I'...
Here's a simple solution that makes just one pass through the files per sample. If you know exactly how many items you will be sampling from the files, it is probably optimal. First off is the sample function. This uses the same algorithm that @NedBatchelder linked to in a comment on an earlier answer (though the Perl...
How to get resulting subprocess command string
12,130,163
4
2012-08-26T12:34:23Z
12,130,261
7
2012-08-26T12:49:37Z
[ "python", "subprocess" ]
I have Python subprocess calls which are formatted as a sequence of arguments (like `subprocess.Popen(['ls','-l'])` instead of a single string (i.e. `subprocess.Popen('ls -l')`). When using sequenced arguments like I did, is there a way to get the resulting string that is sent to the shell (for debugging purposes)? O...
As mentioned in a comment, `subprocess` comes with (not documented in the docs pages) `list2cmdline` that transforms a list of arguments into a single string. According to the source doc, `list2cmdline` is used mostly on Windows: > On Windows: the Popen class uses CreateProcess() to execute the child > program, which ...
Extracting number from string in Python with regex
12,130,742
2
2012-08-26T14:03:10Z
12,130,911
10
2012-08-26T14:28:03Z
[ "python", "regex" ]
I want to extract and print a variable number '-34.99' from the string: ``` myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09" ``` The values in the string will change. How can I do it with the regular expression in Python? Thanks in advance
Non-regex solution is: ``` myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09" print myString.split("/")[1] ``` Test this code [here](http://ideone.com/mjTmG). --- One of regex solutions would be: ``` import re myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09" print re.search(r'(?<=\/)[+-]?\d+(?:\.\d+)...
R expand.grid() function in Python
12,130,883
14
2012-08-26T14:24:14Z
12,131,385
9
2012-08-26T15:32:30Z
[ "python" ]
Is there a Python function similar to the expand.grid() function in R ? Thanks in advance. (EDIT) Below are the description of this R function and an example. ``` Create a Data Frame from All Combinations of Factors Description: Create a data frame from all combinations of the supplied vectors or factors....
Here's an example that gives output similar to what you need: ``` import itertools def expandgrid(*itrs): product = list(itertools.product(*itrs)) return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))} >>> a = [1,2,3] >>> b = [5,7,9] >>> expandgrid(a, b) {'Var1': [1, 1, 1, 2, 2, 2, 3, 3,...
R expand.grid() function in Python
12,130,883
14
2012-08-26T14:24:14Z
21,154,183
8
2014-01-16T05:44:02Z
[ "python" ]
Is there a Python function similar to the expand.grid() function in R ? Thanks in advance. (EDIT) Below are the description of this R function and an example. ``` Create a Data Frame from All Combinations of Factors Description: Create a data frame from all combinations of the supplied vectors or factors....
I've wondered this for a while and I haven't been satisfied with the solutions put forward so far, so I came up with my own, which is considerably simpler (but probably slower). The function uses numpy.meshgrid to make the grid, then flattens the grids into 1d arrays and puts them together: ``` def expand_grid(x, y): ...
Python - Date & Time Comparison using timestamps, timedelta
12,131,766
13
2012-08-26T16:24:22Z
12,131,800
17
2012-08-26T16:28:05Z
[ "python", "timedelta" ]
I've spent the past hour digging around the Python docs and many SO questions; please forgive me for being another Python newbie trapped by the mystery of time difference in Python. My goal is to **determine the difference between the current time and a certain date/time regardless of being in the past/future and retu...
You should be able to use ``` tdelta.total_seconds() ``` to get the value you are looking for. This is because `tdelta` is a [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) object, as is any difference between `datetime` objects. A couple of notes: 1. Using `strftime` followed by `strp...
Python regex: Matching bracket/parenthesis pairs
12,132,336
3
2012-08-26T17:31:49Z
12,132,349
7
2012-08-26T17:33:26Z
[ "python", "regex" ]
I want to catch bracket/parenthesis pairs that are next to each other and get hold of the words inside them. In the following text I want to catch `[oh](so)` and `[bad](things)`. ``` [oh](so)funny [all]the[bad](things) ``` If I use the regex `r'\[(.*?)\]\((.*?)\)'` it will catch `[oh](so)` and `[all]the[bad](things)`...
Don't use `.*?`. Instead use `[^\]]+` and `[^\)]+` In other words: `r'\[([^\]]+)\]\(([^\)]+)\)'`
Flattening a Python list without creating copies of any objects?
12,133,070
3
2012-08-26T19:09:32Z
12,133,164
7
2012-08-26T19:22:46Z
[ "python", "arrays", "list", "multidimensional-array", "flatten" ]
So I'm writing a game in Python, and a problem I'm trying to solve requires that I turn a 2D list (that is, a list of lists) into a 1D list. I've seen several ways to do this, but I don't know if any of them create copies of any objects held within or just new references. To be honest, the Python standard library confu...
While I can't speak for every way you might have seen, in general no copies will be made due to Python's object semantics. ``` >>> a = [[1,2.3,'3', object()], [None, [2,3], 4j]] >>> b = [v for row in a for v in row] >>> a [[1, 2.3, '3', <object object at 0x1002af090>], [None, [2, 3], 4j]] >>> b [1, 2.3, '3', <object o...
pandas - how to sort the result of DataFrame.groupby.mean()?
12,133,075
19
2012-08-26T19:10:01Z
12,133,235
27
2012-08-26T19:31:37Z
[ "python", "pandas" ]
I am trying to figure out how to sort a results of pandas.DataFrame.groupby.mean() in a smart way. I generate an aggregation of my DataFrame like this: ``` means = df.testColumn.groupby(df.testCategory).mean() ``` I now try to sort this by value, but get an error: ``` means.sort() ... -> Exception: This Series is a...
Try using `order`, i.e. `means = means.order()`
Tweepy SSLError
12,133,489
9
2012-08-26T20:08:13Z
13,191,469
7
2012-11-02T08:07:04Z
[ "python", "ssl", "twitter", "tweepy" ]
I have a Django management command, launched via supervisord, that uses tweepy to consume the twitter streaming API. The agent works quite well however I notice in the logs there's an SSLError every 10-15 minutes and supervisord is re-launching the agent. The tweepy package is latest, version 1.11. The server is ubun...
The certificate doesn't seem to be the problem. The error is just a timeout. Seems like an issue with tweepy's SSL handling to me. [The code](https://github.com/tweepy/tweepy/blob/master/tweepy/streaming.py#L118) is equipped to handle `socket.timeout` and reopen the connection, but not a timeout arriving through `SSLEr...
assertAlmostEqual in Python unit-test for collections of floats
12,136,762
25
2012-08-27T05:46:42Z
12,139,899
20
2012-08-27T10:04:01Z
[ "python", "unit-testing" ]
The [assertAlmostEqual(x, y)](http://docs.python.org/library/unittest.html#unittest.TestCase.assertAlmostEqual) method in [Python's unit testing framework](http://docs.python.org/library/unittest.html) tests whether `x` and `y` are approximately equal assuming they are floats. The problem with `assertAlmostEqual()` is...
if you don't mind using NumPy (which comes with your Python(x,y)), you may want to look at the `np.testing` module which defines, among others, a `assert_almost_equal` function. The signature is `np.testing.assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True)` ``` >>> x = 1.000001 >>> y = 1.00000...
Tab-delimited file using csv.reader not delimiting where I expect it to
12,136,850
9
2012-08-27T05:57:16Z
12,137,264
25
2012-08-27T06:39:29Z
[ "python", "csv", "python-requests" ]
I am trying to loop through a tab-delimited file of election results using Python. The following code does not work, but when I use a local file with the same results (the commented out line), it does work as expected. The only thing I can think of is some headers or content type I need to pass the url, but I cannot f...
so whats happening, well, a call to `help` may shed some light. ``` >>> help(csv.reader) reader(...) csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) The "iterable" argument can be any object that ret...
from list of integers, get number closest to a given value
12,141,150
60
2012-08-27T11:32:07Z
12,141,207
134
2012-08-27T11:37:05Z
[ "python", "list", "sorting", "integer" ]
Given a list of integers, I want to find which number is the closest to a number I give in input: ``` >>> myList = [4,1,88,44,3] >>> myNumber = 5 >>> takeClosest(myList, myNumber) ... 4 ``` Is there any quick way to do this?
If we are not sure that the list is sorted, we could use the [built-in `min()` function](http://docs.python.org/library/functions.html?highlight=min#min), to find the element which has the minimum distance from the specified number. ``` >>> min(myList, key=lambda x:abs(x-myNumber)) 4 ``` Note that it also works with ...
from list of integers, get number closest to a given value
12,141,150
60
2012-08-27T11:32:07Z
12,141,511
54
2012-08-27T11:56:07Z
[ "python", "list", "sorting", "integer" ]
Given a list of integers, I want to find which number is the closest to a number I give in input: ``` >>> myList = [4,1,88,44,3] >>> myNumber = 5 >>> takeClosest(myList, myNumber) ... 4 ``` Is there any quick way to do this?
If you mean quick-to-execute as opposed to quick-to-write, `min` should **not** be your weapon of choice, except in one very narrow use case. The `min` solution needs to examine every number in the list *and* do a calculation for each number. Using [`bisect.bisect_left`](http://docs.python.org/library/bisect.html#bisec...
How to get first element in a list of tuples?
12,142,133
46
2012-08-27T12:38:37Z
12,142,151
13
2012-08-27T12:39:22Z
[ "python", "django", "list" ]
I have a list like below where the first element is the id and the other is a string: ``` [(1, u'abc'), (2, u'def')] ``` I want to create a list of ids only from this list of tuples as below: ``` [1,2] ``` I'll use this list in `__in` so it needs to be a list of integer values. Please help!
do you mean something like this? ``` new_list = [ seq[0] for seq in yourlist ] ``` What you actually have is a list of `tuple` objects, not a list of sets (as your original question implied). If it is actually a list of sets, then *there is no first element* because sets have no order. Here I've created a flat list ...
How to get first element in a list of tuples?
12,142,133
46
2012-08-27T12:38:37Z
12,142,903
54
2012-08-27T13:25:51Z
[ "python", "django", "list" ]
I have a list like below where the first element is the id and the other is a string: ``` [(1, u'abc'), (2, u'def')] ``` I want to create a list of ids only from this list of tuples as below: ``` [1,2] ``` I'll use this list in `__in` so it needs to be a list of integer values. Please help!
``` >>>a = [(1, u'abc'), (2, u'def')] >>>b = [int(i[0]) for i in a] [1, 2] ```
How to get first element in a list of tuples?
12,142,133
46
2012-08-27T12:38:37Z
31,297,256
10
2015-07-08T15:32:57Z
[ "python", "django", "list" ]
I have a list like below where the first element is the id and the other is a string: ``` [(1, u'abc'), (2, u'def')] ``` I want to create a list of ids only from this list of tuples as below: ``` [1,2] ``` I'll use this list in `__in` so it needs to be a list of integer values. Please help!
Use the zip function to decouple elements. ``` >>> input = [(1, u'abc'), (2, u'def')] >>> unzipped = zip(*input) >>> print unzipped [(1, 2), (u'abc', u'def')] >>> print list(unzipped[0]) [1, 2] ```
Run a python script with arguments
12,142,174
18
2012-08-27T12:40:56Z
12,142,360
7
2012-08-27T12:51:53Z
[ "python", "c", "eclipse" ]
I want to call a Python script from C, passing some arguments that are needed in the script. The script I want to use is mrsync, or [multicast remote sync](http://sourceforge.net/projects/mrsync/). I got this working from command line, by calling: ``` python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/t...
You have two options. 1. Call ``` system("python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/targetdata") ``` in your C code. 2. Actually use the API that `mrsync` (hopefully) defines. This is more flexible, but much more complicated. The first step would be to work out how you would perfor...
Run a python script with arguments
12,142,174
18
2012-08-27T12:40:56Z
12,185,376
28
2012-08-29T19:42:51Z
[ "python", "c", "eclipse" ]
I want to call a Python script from C, passing some arguments that are needed in the script. The script I want to use is mrsync, or [multicast remote sync](http://sourceforge.net/projects/mrsync/). I got this working from command line, by calling: ``` python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/t...
Seems like you're looking for an answer using the python development APIs from Python.h. Here's an example for you that should work: ``` #My python script called mypy.py import sys if len(sys.argv) != 2: sys.exit("Not enough args") ca_one = str(sys.argv[1]) ca_two = str(sys.argv[2]) print "My command line args are...
List conversion
12,143,178
4
2012-08-27T13:41:18Z
12,143,327
13
2012-08-27T13:49:29Z
[ "python", "list" ]
I am looking for a way to convert a list like this ``` [[1.1, 1.2, 1.3, 1.4, 1.5], [2.1, 2.2, 2.3, 2.4, 2.5], [3.1, 3.2, 3.3, 3.4, 3.5], [4.1, 4.2, 4.3, 4.4, 4.5], [5.1, 5.2, 5.3, 5.4, 5.5]] ``` to something like this ``` [[(1.1,1.2),(1.2,1.3),(1.3,1.4),(1.4,1.5)], [(2.1,2.2),(2.2,2.3),(2.3,2.4),(2.4,2.5)] ......
The following line should do it: ``` [list(zip(row, row[1:])) for row in m] ``` where `m` is your initial 2-dimensional list **UPDATE for second question in comment** You have to [transpose](http://en.wikipedia.org/wiki/Transpose) (= exchange columns with rows) your 2-dimensional list. The python way to achieve a t...
Installing python modules through proxy
12,144,289
3
2012-08-27T14:47:04Z
12,144,756
12
2012-08-27T15:15:08Z
[ "python", "proxy", "urllib2" ]
I want to install a couple of python packages which use easy\_install. They use the urrlib2 module in their setup script. I tried using the company proxy to let easy\_install download the required packages. So to test the proxy conn I tried the following code. I dont need to supply any credentials for proxy in IE. ```...
Set the following environment variables: ``` HTTP_PROXY=http://user:password@your-company-proxy.com:8080 ``` as well as ``` HTTPS_PROXY=http://user:password@your-company-proxy.com:8080 ``` If your proxy port is not 8080, you should change 8080 with the appropriate port number too. If you don't have rights to modi...
Scrapy - Select specific link based on text
12,145,067
5
2012-08-27T15:37:48Z
12,145,164
10
2012-08-27T15:44:17Z
[ "python", "web-crawler", "scrapy" ]
This should be easy but I'm stuck. ``` <div class="paginationControl"> <a href="/en/overview/0-All_manufactures/0-All_models.html?page=2&amp;powerunit=2">Link Text 2</a> | <a href="/en/overview/0-All_manufactures/0-All_models.html?page=3&amp;powerunit=2">Link Text 3</a> | <a href="/en/overview/0-All_manufactur...
Use `a[contains(text(),'Link Text Next')]`: ``` nextPage = HtmlXPathSelector(response).select( "//div[@class='paginationControl']/a[contains(text(),'Link Text Next')]/@href") ``` Reference: Documentation on the XPath [contains](http://www.w3.org/TR/xpath/#function-contains) function --- PS. Your text `Link Text...
How to output loop.counter in python jinja template?
12,145,434
42
2012-08-27T16:02:20Z
12,147,197
84
2012-08-27T18:08:59Z
[ "python", "jinja2" ]
I want to be able to output the current loop iteration to my template. According to the docs: <http://wsgiarea.pocoo.org/jinja/docs/loops.html>, there is a loop.counter variable that I am trying to use. I have the following: ``` <ul> {% for user in userlist %} <li> {{ user }} {{loop.counter}} </li> {...
The counter variable inside the loop is called **loop.index** in jinja2. ``` >>> from jinja2 import Template >>> s = "{% for element in elements %}{{loop.index}} {% endfor %}" >>> Template(s).render(elements=["a", "b", "c", "d"]) 1 2 3 4 ``` See <http://jinja.pocoo.org/docs/templates/> for more.
How can I debug what is causing a connection refused or a connection time out?
12,145,536
15
2012-08-27T16:07:58Z
12,145,777
30
2012-08-27T16:23:26Z
[ "python", "networking" ]
I have the following code that has worked for about a year: ``` import urllib2 req = urllib2.Request('https://somewhere.com','<Request></Request>') data = urllib2.urlopen(req) print data.read() ``` Lately, there have been some random errors: * `urllib2.URLError: <urlopen error [Errno 111] Connection refused>` * `<u...
## The problem The problem is in the network layer. Here are the status codes explained: * `Connection refused`: The peer is not listening on the respective [network port](https://en.wikipedia.org/wiki/Port_%28computer_networking%29) you're trying to connect to. This usually means that either a firewall is actively d...
Using python, what is the most accurate way to auto determine a users current timezone
12,145,847
5
2012-08-27T16:27:08Z
12,146,049
7
2012-08-27T16:43:29Z
[ "python", "datetime", "timezone", "flask" ]
I have verified that dateutils.tz.tzlocal() does not work on heroku and even if it did, wouldn't it just get the tz from the OS of the computer its on, not necessarly the users? Short of storing a users timezone, is there any way to determine where a request is coming from? (I'm using flask) Twitter does have a setti...
You could use Javascript and set the client's time zone in a cookie. You could even use an AJAX request and then send the offset to the server and save in the client's session. ``` var offset = new Date().getTimezoneOffset(); ``` > Description > > The time-zone offset is the difference, in minutes, between UTC and lo...
Python while loop inconstancy
12,147,365
4
2012-08-27T18:20:34Z
12,147,408
10
2012-08-27T18:23:46Z
[ "python", "while-loop" ]
Never seen anything like this. Simple while loop: ``` t_end = 100.0 t_step= 0.1 time = 0 while time<=t_end: time+=t_step print time ``` Last 3 printed values: ``` ... 99.9 100.0 100.1 ``` Looks right to me. Now, I change t\_step to 0.01: ``` t_end = 100.0 t_step= 0.01 time = 0 while time<=t_end: ...
Because this 100.0 (result of a sum) can be bigger than 100.0 you write by hand. You should not compare float numbers for equality... You should read this: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) Possible solution: `...
pip install django timeout on MacOSX Lion
12,147,519
5
2012-08-27T18:31:42Z
15,238,742
11
2013-03-06T04:01:55Z
[ "python", "django", "osx-lion", "pip" ]
On a MBP, following instructions (http://techblog.rosedu.org/python-environment.html), I installed Xcode 4.4.1, brew (brew doctor says all set), and then python. Next, I tried to setup virtualenv: ``` > $MYPYTHON/bin/python distribute_setup.py > $MYPYTHON/bin/easy_install pip > $MYPYTHON/bin/pip install virtualenv ```...
Use: ``` pip --default-timeout=60 install django ```
dict.pop or dict.get and evaluation
12,147,788
3
2012-08-27T18:51:21Z
12,147,820
7
2012-08-27T18:53:25Z
[ "python", "short-circuiting" ]
Consider the following code: ``` >>> def default_answer(): ... print "Default was required!" ... return 100 ... >>> g = { 'name': 'Jordan', 'age': 35 } >>> result = g.get('age', default_answer()) Default was required! >>> result = g.pop('age', default_answer()) Default was required! ``` Notice that whether `...
No, this is not the best way to do this, since the result of `g.pop()` might be "falsy". Use `try`/`except` instead: ``` try: result = g.pop('age') except KeyError: result = default_answer() ``` This idiom is called [EAFP](http://docs.python.org//glossary.html#term-eafp) and is usually preferred over [LBYL](h...
Scheduling thousands of one-off (non-reoccuring) tasks for near-simultanious execution via Django-celery
12,147,861
5
2012-08-27T18:56:09Z
12,343,478
7
2012-09-09T22:21:25Z
[ "python", "django", "cron", "celery", "django-celery" ]
Some context: I'm building a Django App that allows a user to pre-save an action, and schedule the exact date/time in the future they want said action to execute. E.g, scheduling a post to be programmatically pushed to ones Facebook wall next week at 5:30am. I'm looking for a task scheduling system that could handle a...
**Edit 2:** For some reason, my head was originally stuck in the realm of recurring tasks. Here is a simpler solution. All you really need is to define one task for each user action. You can skip storing tasks to be executed in your database--that's what celery is here for! Reusing your facebook post example again, ...
Efficiently rotate a set of points with a rotation matrix in numpy
12,148,351
10
2012-08-27T19:30:57Z
12,148,508
15
2012-08-27T19:41:25Z
[ "python", "numpy", "rotation", "vectorization" ]
I have a list of 3D points stored in numpy array `A` with shape `(N,3)` and a rotation matrix `R` with shape `(3,3)`. I'd like to compute the dot product of `R.x` for each point `x` in `A` in-place. Naively I can do this: ``` for n in xrange(N): A[n,:] = dot(R, A[n,:]) ``` Is there a way to vectorize this with a ...
You can multiply A with the transpose of the rotation matrix: ``` A = dot(A, R.T) ```
Python if statement, cannot concatenate 'str' and 'instance' object
12,148,713
2
2012-08-27T19:56:38Z
12,148,779
8
2012-08-27T20:01:44Z
[ "python", "if-statement", "xml-parsing" ]
My question is I want to check a variable in a xml variable called `xmlauthor` and I want to check if there is just basically something written on it. How should I do it? This is what I have written so far: ``` for num in ic : xmlauthor = dom.getElementsByTagName("author")[0] if not xmlauthor: conte...
Assuming you're using [xml.dom](http://docs.python.org/library/xml.dom.html): the `getElementsByTagName` doesn't return a list of strings, it returns a list of [Element](http://docs.python.org/library/xml.dom.html#dom-element-objects) objects, so you can't concatenate `xmlauthor` to a string in the line ``` conten...
Python what's the difference between str(u'a') and u'a'.encode('utf-8')
12,149,567
8
2012-08-27T21:02:31Z
12,149,585
19
2012-08-27T21:04:50Z
[ "python", "unicode" ]
As title, is there a reason not to use str() to cast unicode string to str?? ``` >>> str(u'a') 'a' >>> str(u'a').__class__ <type 'str'> >>> u'a'.encode('utf-8') 'a' >>> u'a'.encode('utf-8').__class__ <type 'str'> >>> u'a'.encode().__class__ <type 'str'> ``` UPDATE: thanks for the answer, also didn't know if I create ...
When you write `str(u'a')` it converts the Unicode string to a bytestring using the **default encoding** which (unless you've gone to the trouble of [changing it](http://stackoverflow.com/questions/2276200/changing-default-encoding-of-python)) will be ASCII. The second version explicitly encodes the string as UTF-8. ...
change key in OrderedDict without loosing order
12,150,872
9
2012-08-27T23:22:30Z
12,150,917
7
2012-08-27T23:29:06Z
[ "python", "ordereddictionary" ]
Starting with ``` OrderedDict([('a', 1), ('c', 3), ('b', 2)]) ``` is it possible to end up with ``` OrderedDict([('a', 1), ('__C__', 3), ('b', 2)]) ``` making sure that the `'__C__'` item is before `'b'` and after `'a'` i.e. keeping order?
You could try: ``` >>> d = OrderedDict([('a', 1), ('c', 3), ('b', 2)]) >>> d OrderedDict([('a', 1), ('c', 3), ('b', 2)]) >>> d2 = OrderedDict([('__C__', v) if k == 'c' else (k, v) for k, v in d.items()]) >>> d2 OrderedDict([('a', 1), ('__C__', 3), ('b', 2)]) ```
Python @precondition / @postcondition for member function - how?
12,151,182
4
2012-08-28T00:06:29Z
12,151,531
8
2012-08-28T01:07:21Z
[ "python", "decorator" ]
I'm trying to use the @postcondition decorator on the value returned by a member function of a class, like this : ``` def out_gt0(retval, inval): assert retval > 0, "Return value < 0" class foo(object): def __init__(self, w, h): self.width = w self.height = h @postcondition(out_gt0) de...
You don't need to do anything special: ``` import functools def condition(pre_condition=None, post_condition=None): def decorator(func): @functools.wraps(func) # presever name, docstring, etc def wrapper(*args, **kwargs): #NOTE: no self if pre_condition is not None: asse...
Argparse: Way to include default values in '--help'?
12,151,306
105
2012-08-28T00:25:11Z
12,151,325
161
2012-08-28T00:27:58Z
[ "python", "argparse" ]
Suppose I have the following argparse snippet: ``` diags.cmdln_parser.add_argument( '--scan-time', action = 'store', nargs = '?', type = int, default = 5, help = "Wait SCAN-TIME seconds between status chec...
Use the [`argparse.ArgumentDefaultsHelpFormatter` formatter](http://docs.python.org/library/argparse.html#formatter-class): ``` parser = argparse.ArgumentParser( # ... other options ... formatter_class=argparse.ArgumentDefaultsHelpFormatter) ``` To quote the documentation: > The other formatter class availab...
Argparse: Way to include default values in '--help'?
12,151,306
105
2012-08-28T00:25:11Z
18,507,871
78
2013-08-29T10:01:22Z
[ "python", "argparse" ]
Suppose I have the following argparse snippet: ``` diags.cmdln_parser.add_argument( '--scan-time', action = 'store', nargs = '?', type = int, default = 5, help = "Wait SCAN-TIME seconds between status chec...
Add `'%(default)'` to the help parameter to control what is displayed. ``` parser.add_argument("--type", default="toto", choices=["toto","titi"], help = "type (default: %(default)s)") ```
Just Slightly Off for Project Euler #17
12,152,627
3
2012-08-28T04:06:07Z
12,152,686
7
2012-08-28T04:13:06Z
[ "python" ]
I posted this question a few hours ago but I think I deleted it! Really sorry... I am working on Project Euler Problem 17. Although there are other more obvious solutions, as a learning exercise, I approached the problem intending to solve it using recursion. I had also hoped that certain pieces of the code might late...
I think if someone gave me nine balloons, and then gave me one more, I would say that I had ten balloons. On the other hand, if I had ninety-nine balloons, and then I received one more, I would say "I have one hundred balloons", not "I have hundred balloons": ``` >>> int_to_words(10) 'ten' >>> int_to_words(100) 'hundr...
Python pandas equivalent for replace
12,152,716
15
2012-08-28T04:18:11Z
12,152,759
24
2012-08-28T04:25:10Z
[ "python", "pandas", "equivalent" ]
In R, there is a rather useful `replace` function. Essentially, it does conditional re-assignment in a given column of a data frame. It can be used as so: `replace(df$column, df$column==1,'Type 1');` What is a good way to achieve the same in pandas? Should I use a lambda with `apply`? (If so, how do I get a reference...
`pandas` has a `replace` method too: ``` In [25]: df = DataFrame({1: [2,3,4], 2: [3,4,5]}) In [26]: df Out[26]: 1 2 0 2 3 1 3 4 2 4 5 In [27]: df[2] Out[27]: 0 3 1 4 2 5 Name: 2 In [28]: df[2].replace(4, 17) Out[28]: 0 3 1 17 2 5 Name: 2 In [29]: df[2].replace(4, 17, inplace=True) ...
Fastest Way to Create a New Object Only if it Doesn't Already Exist (SQLAlchemy)
12,153,106
15
2012-08-28T05:09:16Z
12,370,612
13
2012-09-11T13:16:50Z
[ "python", "database", "postgresql", "sqlalchemy", "flask-sqlalchemy" ]
I'm looking for the *fastest* way to create a new SQLAlchemy object only if it doesn't already exist in the database. The way I'm doing it now is by first getting the count of the query to see if it exists, and if not--then I create it. EG: ``` if not User.query.filter(email=user.email).count(): db.session.add(us...
I've found that the get\_or\_create function outlined on [another SO answer](http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create) meets my needs.
best pythonic way to parse param string?
12,153,614
2
2012-08-28T06:09:09Z
12,153,786
8
2012-08-28T06:23:21Z
[ "python", "string", "parsing" ]
Receive a string from somewhere and the string is a sequence of params. Params are separated by whitespace. The task is parse the string to a param list, all params are type string. For example: ``` input : "3 45 5.5 a bc" output : ["3","45","5.5","a","bc"] ``` Things become little complicated if need to transfer a ...
Use the [`shlex.split()` function](http://docs.python.org/library/shlex.html#shlex.split): ``` >>> import shlex >>> shlex.split("3 45 5.5 a bc") ['3', '45', '5.5', 'a', 'bc'] >>> shlex.split("3 45 5.5 \"This is a sentence.\" bc") ['3', '45', '5.5', 'This is a sentence.', 'bc'] >>> shlex.split("3 45 5.5 \"\\\"Yes\\\\No...
how to specify which lettuce scenario to run
12,154,822
4
2012-08-28T07:42:40Z
16,784,748
10
2013-05-28T05:50:48Z
[ "python", "testing", "lettuce" ]
how to specify which lettuce scenario to run? in using python lettuce test framework, I ran frequently into this case, one scenario failed and then I want to zoom in to this scenario to fix this scenario can we specify which lettuce scenario to run in the feature file ?
You can use tags for the desired tests. For example: ``` Scenario: Set off time in free time slot Given I click first free time slot And I choose menu item "Off" And I enter time that is in free interval When I click button "Ok" Then I see offtime time slot with title that m...
Changing logging's 'basicConfig' which is already set
12,158,048
12
2012-08-28T11:12:31Z
12,158,233
23
2012-08-28T11:24:26Z
[ "python", "logging" ]
I am using the logging module in python as: ``` import logging, sys logger= logging.getLogger(__file__) logging.basicConfig(stream = sys.stderr, level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s') logger.debug("Hello World") ``` Now, after I have set the basic configuration on `line 3`, I...
If you look in the Python sources for `logging/__init__.py`, you'll see that `basicConfig()` sets the handlers on the root logger object by calling `addHandler()`. If you want to start from scratch, you could remove all existing handlers and then call `basicConfig()` again. ``` # Example to remove all root logger hand...
Python creates 2 times more threads than expected
12,158,859
2
2012-08-28T12:05:59Z
12,158,930
8
2012-08-28T12:10:25Z
[ "python", "multithreading" ]
I'm new to Python so my apologies if this is something obvious. I'm trying to build multi threaded application, however when I want to create a thread I get two instead of one. **MyThread.py** ``` from threading import Thread import time class MyThreadClass(Thread): def __init__(self): Thread.__init__(...
When you import `main.py` in `MyThread.py`, the line > MyThreadClass().start() gets executed once again (since the module gets loaded), hence a second thread is started. --- You could create a guard clause in `main.py` by replacing that line with ``` if __name__ == "__main__": MyThreadClass().run() ``` or bet...
Email datetime parsing with python
12,160,010
4
2012-08-28T13:10:52Z
12,160,056
18
2012-08-28T13:13:19Z
[ "python", "datetime" ]
I am trying to parse date time of an email using python script. In mail date value is like below when i am opening mail detils... ``` from: abcd@xyz.com to: def@xyz.com date: Tue, Aug 28, 2012 at 1:19 PM subject: Subject of that mail ``` I am using code like ``` mail = email.message_from_string(str1) #to...
When looking at an email in GMail, your local timezone is used when displaying the date and time an email was sent. The "Tue, 28 Aug 2012 02:49:13 -0500" is parsed, then updated to your local timezone, and formatted in a GMail-specific manner. ## Parsing and formatting the stdlib way The `email.utils` module includes...
Why is lxml.etree.iterparse() eating up all my memory?
12,160,418
11
2012-08-28T13:34:03Z
12,161,078
11
2012-08-28T14:06:48Z
[ "python", "xml", "memory", "lxml", "iterparse" ]
This eventually consumes all my available memory and then the process is killed. I've tried changing the tag from `schedule` to 'smaller' tags but that didn't make a difference. What am I doing wrong / how can I process this large file with `iterparse()`? ``` import lxml.etree for schedule in lxml.etree.iterparse('r...
As `iterparse` iterates over the entire file a tree is built and no elements are freed. The advantage of doing this is that the elements remember what their parent is, and you can form XPaths that refer to ancestor elements. The disadvantage is that it can consume a lot of memory. In order to free some memory as you p...
str object is not callable python
12,160,498
2
2012-08-28T13:38:39Z
12,160,522
11
2012-08-28T13:40:17Z
[ "python", "string", "python-3.x" ]
I have tried looking around for an answer however the questions on here either seemed to advanced (I'm new to Python) or because of redefining what something meant which I couldn't catch in my script. Here is the code- ``` a = float(input("Enter the length(in inches)")) b = float(input("Enter the width(in inches)")) p...
Assuming you're using Python 3, ``` print ("The area of your shape is: ", (a*b)) # ^ ``` You forgot a comma.
Can I make STATICFILES_DIR same as STATIC_ROOT in Django 1.3?
12,161,271
27
2012-08-28T14:15:47Z
12,161,409
64
2012-08-28T14:22:18Z
[ "python", "django", "django-views", "django-staticfiles" ]
I'm using Django 1.3 and I realize it has a **collectstatic** command to collect static files into **STATIC\_ROOT**. Here I have some other global files that need to be served using **STATICFILES\_DIR**. Can I make them use the same dir ? Thanks.
No. In fact, the file `django/contrib/staticfiles/finders.py` even checks for this and raises an `ImproperlyConfigured` exception when you do so: > "The STATICFILES\_DIRS setting should not contain the STATIC\_ROOT setting" The `STATICFILES_DIRS` can contain other directories (not necessarily app directories) with st...
How to get rid of maximum recursion depth error while plotting interactively?
12,162,328
5
2012-08-28T15:12:13Z
12,162,426
7
2012-08-28T15:17:07Z
[ "python", "matplotlib" ]
I'm trying to build an interactive plot. This one is supposed to clear the figure if clicked within axes and draw a circle at a random place. The code is as follows: ``` import matplotlib.pyplot as plt import random def draw_circle(event): if event.inaxes: print(event.xdata, event.ydata) plt.cla(...
Instead of `plt.show()`, from within your callback call `plt.draw()`. The problem is that `plt.show` runs a mainloop of the GUI library; you just want to update what is shown within the existing mainloop. Using the Qt backend, your code would show the error `QCoreApplication::exec: The event loop is already running`. ...
Using print() in Python2.x
12,162,629
23
2012-08-28T15:30:09Z
12,162,754
26
2012-08-28T15:37:19Z
[ "python", "python-2.x" ]
I understand the difference between a statement and an expression, and I understand that Python3 turned print() into a function. However I ran a print() statement surrounded with parenthesis on various Python2.x interpreters and it ran flawlessly, I didn't even have to import any module. My question: Is the following...
Consider the following expressions: ``` a = ("Hello SO!") a = "Hello SO!" ``` They're equivalent. In the same way, with a statement: ``` statement_keyword("foo") statement_keyword "foo" ``` are also equivalent. Notice that if you change your print function to: ``` print("Hello","SO!") ``` You'll notice a differe...
Using print() in Python2.x
12,162,629
23
2012-08-28T15:30:09Z
12,162,772
7
2012-08-28T15:38:37Z
[ "python", "python-2.x" ]
I understand the difference between a statement and an expression, and I understand that Python3 turned print() into a function. However I ran a print() statement surrounded with parenthesis on various Python2.x interpreters and it ran flawlessly, I didn't even have to import any module. My question: Is the following...
`print("Hello SO!")` is evaluated as the statement `print ("Hello SO!")`, where the argument to the `print` statement is the expression `("Hello SO!")`. This can make a difference if you are printing more than one value; for example `print("Hello", "world")` will print the 2-element tuple `('Hello', 'world')` instead ...
Where do I define the domain to be used by url_for() in Flask?
12,162,634
27
2012-08-28T15:30:28Z
12,162,726
40
2012-08-28T15:35:51Z
[ "python", "flask", "url-for" ]
When I call `url_for('index')` it will generate `'/'` but there are times where I'd like it to generate `'domain.tld/'` instead. I can't find in the documentation where I would specify this. Do I just need to do `'domain.tld/%s' % url_for('index')`?
[`url_for`](http://flask.pocoo.org/docs/api/#flask.url_for) takes an `_external` keyword argument that will return an absolute (rather than relative) URL. I believe you will need to set a `SERVER_NAME` config key with your root domain to make it work correctly.
How to (cross-)compile boost WITHOUT python?
12,162,793
10
2012-08-28T15:39:54Z
12,168,033
9
2012-08-28T21:51:25Z
[ "python", "boost", "cross-compiling" ]
I have a gcc 4.3.3 toolchain for my embedded device but I have no python (and don't need it). I'am looking for a way to configure boostbuild without python (compilation and cross-compilation). Is python mandatory ? Must I compile every single parts but boost-python ? (I hope not). Thanks in advance. **What I did t...
Look at --without-\* bjam option e.g. --without-python
How to maintain case-sensitive tags in BeautifulSoup.BeautifulStoneSoup?
12,163,251
8
2012-08-28T16:05:27Z
12,163,802
11
2012-08-28T16:40:56Z
[ "python", "xml", "beautifulsoup" ]
I am writing a script that edits an XML file with `BeautifulStoneSoup`, but the library converts all tags to lower case. Is there an option to conserve the case? ``` import BeautifulSoup xml = "<TestTag>a string</TestTag>" soup = BeautifulSoup.BeautifulStoneSoup(xml, markupMassage=False) print soup.prettif...
You could use [Beautiful Soup 4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-xml), as follows (requires the lxml XML library): ``` In [10]: from bs4 import BeautifulSoup In [11]: xml = "<TestTag>a string</TestTag>" In [12]: soup = BeautifulSoup(xml, "xml") In [13]: print soup <?xml version="1.0" e...
Passing variable to a macro in Jinja2
12,163,904
4
2012-08-28T16:49:09Z
12,163,925
10
2012-08-28T16:50:46Z
[ "python", "google-app-engine", "jinja2" ]
I have made some small macro that I am using to display text line and label for it: ``` {% macro input(name, text, help_text, value="", input_type) -%} <label for="id_{{name}}">{{text}}<span class="right">{{help_text}}</span></label> <input id="id_{{name}}" name="{{name}}" value="{{value}}" type="{{input_type}...
I believe ``` {{ input("username", "Korisničko ime:", "Pomoć", value_username, "text") }} ``` should work
Selenium selecting a dropdown option with for loop from dictionary
12,164,205
7
2012-08-28T17:08:45Z
12,164,413
13
2012-08-28T17:25:15Z
[ "python", "selenium", "web2py" ]
I have a form with inputs and dropdown lists: ``` [...] <select> <option></option> <option>Test User 1</option> <option>Test User 2</option> </select> [...] ``` I pass the values to Selenium as Dictionary: ``` dict = {'user':'Test User 1', [...]} ``` And I use a for loop to do this: ``` for key in dict.keys(): ...
``` from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_id("dropdown_menu")) select.select_by_visible_text("Test User 1") ```
Python FTP implicit TLS connection issue
12,164,470
7
2012-08-28T17:30:02Z
12,469,821
14
2012-09-18T03:01:09Z
[ "python", "ssl", "ftp", "ftplib", "ftps" ]
I have a need to connect to FTPS server to which I am able to connect successfully using lftp. However, when I try with Python ftplib.FTP\_TLS, it times out, the stack trace shows that it is waiting for the server to send welcome message or like. Does anyone know what the issue is and how to overcome? I wonder if there...
I've worked on the same problem for half a day and finally figured it out. For the implicit FTP TLS/SSL(defualt port 990), our client program must build a TLS/SSL connection right after the socket is created. But python's class `FTP_TLS` doesn't reload the **connect** function from class FTP. We need to fix it: ``` c...
'order' of unordered Python sets
12,165,200
23
2012-08-28T18:20:30Z
12,165,239
23
2012-08-28T18:23:18Z
[ "python", "python-internals" ]
Question from a noob (me): I understand that sets in Python are unordered, but I'm curious about the 'order' they're displayed in, as it seems to be consistent. They seem to be out-of-order in the same way every time: ``` >>> set_1 = set([5, 2, 7, 2, 1, 88]) >>> set_2 = set([5, 2, 7, 2, 1, 88]) >>> set_1 set([88, 1, ...
You should watch this [video](https://www.youtube.com/watch?v=C4Kc8xzcA68) (although it is CPython specific and about dictionaries -- but I assume it applies to sets as well). Basically, python hashes the elements and takes the last N bits (where N is determined by the size of the set) and uses those bits as array ind...
Parse Html using lxml and xpath
12,165,452
3
2012-08-28T18:40:42Z
12,165,570
8
2012-08-28T18:48:29Z
[ "python", "xpath", "html-parsing", "lxml" ]
I am trying to use lxml with python because after reading and doing google recommendation is to use lxml over other parsing packages. I have following dom structure and I manage write the correct xpath and I double check my xpath on xpath check to confirm the validity of it. Xpath works fine on Xpath Checker but when I...
appending a `[0].text` to the end of the print statement in your answer should give you what you want. Basically, what's being printed in your question are single-element lists of `lxml.etree._Element`s, which have attributes like `tag` and `text` that you can use to get different properties. So, try ``` tr.xpath("//t...
Django Aggregation: Summation of Multiplication of two fields
12,165,636
16
2012-08-28T18:54:51Z
19,888,120
44
2013-11-10T09:22:50Z
[ "python", "django", "django-models", "django-queryset" ]
I have a model some thing like this ``` class Task(models.Model): progress = models.PositiveIntegerField() estimated_days = models.PositiveIntegerField() ``` Now I would like to do a calculation `Sum(progress * estimated_days)` on the database level. Using Django Aggregation I can have the sum for each field bu...
it's possible using Django ORM: here's what you should do: ``` from django.db.models import Sum total = ( Task.objects .filter(your-filter-here) .aggregate( total=Sum('progress', field="progress*estimated_days") )['total'] ) ``` Note: if the two fields a...
Django Aggregation: Summation of Multiplication of two fields
12,165,636
16
2012-08-28T18:54:51Z
30,979,665
20
2015-06-22T12:09:19Z
[ "python", "django", "django-models", "django-queryset" ]
I have a model some thing like this ``` class Task(models.Model): progress = models.PositiveIntegerField() estimated_days = models.PositiveIntegerField() ``` Now I would like to do a calculation `Sum(progress * estimated_days)` on the database level. Using Django Aggregation I can have the sum for each field bu...
With Django 1.8 and above you can now pass an expression to your aggregate: ``` from django.db.models import F Task.objects.aggregate(total=Sum(F('progress') * F('estimated_days')))['total'] ``` Constants are also available, and everything is combinable: ``` from django.db.models import Value Task.objects.aggr...
python - datetime with timezone to epoch
12,165,691
4
2012-08-28T18:57:56Z
17,257,177
15
2013-06-23T02:22:41Z
[ "python", "datetime", "timezone", "epoch" ]
In the code below, I am calculating now epoch and beginning of current day epoch. ``` import time import pytz from datetime import datetime tz1 = pytz.timezone('CST6CDT') utc = pytz.timezone('UTC') now = pytz.UTC.localize(datetime.utcnow()) now_tz = now.astimezone(tz1) print now_tz print now_tz.strftime('%s') begin_...
To convert a datetime with timezone to epoch (POSIX timestamp): ``` from datetime import datetime import pytz tz = pytz.timezone('CST6CDT') # a datetime with timezone dt_with_tz = tz.localize(datetime(2012, 8, 28, 19, 33, 50), is_dst=None) # get timestamp ts = (dt_with_tz - datetime(1970, 1, 1, tzinfo=pytz.utc)).to...
django request.session.get("name", False) - What does this code mean?
12,166,368
4
2012-08-28T19:40:20Z
12,166,390
12
2012-08-28T19:41:33Z
[ "python", "django" ]
I am using the following code : ``` if request.session.get("name",False): ``` Can anyone please tell me what the above code does? What I assume is, if there is "name" in session it returns True, otherwise, it returns False. I'm confused with my code so I posted this question here. Thanks.
If `session` has a key in it with the value `"name"` it returns *the value associated with that key* (which might well be `False`), otherwise (if there is no key named "name") it returns `False`. The `session` is a dictionary-like type so the best place to get documenation on the [`get` method](http://docs.python.org/...
Django - Testing - Problems with @login_required decorator
12,166,568
6
2012-08-28T19:52:57Z
12,166,646
7
2012-08-28T19:57:51Z
[ "python", "django", "unit-testing", "testing", "django-authentication" ]
## Problem **UPDATE**: This issue, it turns out, has little to do with the `@login_required` decorator! I am getting finicky behavior when I try to test views that are decorated with `@login_required`. I have one test that is actually able to go to a view decorated with `@login_required` (a password change view). A ...
`user.password` is password hash. You can't log in with it. You need to use original password: ``` self.client.login(username=user.username, password='<user password>') ```
In python using Flask, how can I write out an object for download?
12,166,970
15
2012-08-28T20:22:26Z
12,170,482
20
2012-08-29T03:27:45Z
[ "python", "python-2.7", "file-io", "download", "flask" ]
I'm using Flask and running foreman. I data that I've constructed in memory and I want the user to be able to download this data in a text file. I don't want write out the data to a file on the local disk and make that available for download. I'm new to python. I thought I'd create some file object in memory and then ...
Streaming files to the client without saving them to disk is covered in the "pattern" section of Flask's docs - specifically, [in the section on streaming](http://flask.pocoo.org/docs/patterns/streaming/). Basically, what you do is return a fully-fledged [`Response`](http://flask.pocoo.org/docs/api/#flask.Response) obj...
pythonic way to create 3d dict
12,167,192
3
2012-08-28T20:39:38Z
12,167,243
10
2012-08-28T20:43:51Z
[ "python" ]
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: ...
You may want to consider using [`defaultdict`](http://docs.python.org/library/collections.html): For example: ``` json_dict = defaultdict(lambda: defaultdict(dict)) ``` will create a `defaultdict` of `defaultdict`s of `dict`s (I know..but it is right), to access it, you can simply do: ``` json_dict['context']['name...
Fastest way to compute k largest eigenvalues and corresponding eigenvectors with numpy
12,167,654
12
2012-08-28T21:16:18Z
12,168,664
9
2012-08-28T22:51:22Z
[ "python", "numpy", "scipy", "linear-algebra" ]
I have a large NxN dense symmetric matrix and want the eigenvectors corresponding to the k largest eigenvalues. What's the best way to find them (preferably using numpy but perhaps in general using blas/atlas/lapack if that's the only way to go)? In general N is much much larger then k (say N > 5000, k < 10). Numpy se...
In SciPy, you can use the [linalg.eigh](http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html) function, with the `eigvals` parameter. > eigvals : tuple (lo, hi) Indexes of the smallest and largest (in > ascending order) eigenvalues and corresponding eigenvectors to be > returned: 0 <= lo < hi <= ...
Big array with random numbers with python
12,167,863
4
2012-08-28T21:36:46Z
12,167,903
7
2012-08-28T21:39:26Z
[ "python", "arrays", "random" ]
I need to generate a big array (or list) with random numbers ( 10⁵ numbers) . I was trying like that: ``` vet = random.sample(range(10),100000) ``` But when I try to run : ``` vet = random.sample(range(10),10000) ``` File "/usr/lib/python2.7/random.py", line 320, in sample raise ValueError("sample larger than pop...
I think you're after something like this: ``` vet = [random.randint(1,10) for _ in range(100000)] ```
Big array with random numbers with python
12,167,863
4
2012-08-28T21:36:46Z
12,167,927
14
2012-08-28T21:41:22Z
[ "python", "arrays", "random" ]
I need to generate a big array (or list) with random numbers ( 10⁵ numbers) . I was trying like that: ``` vet = random.sample(range(10),100000) ``` But when I try to run : ``` vet = random.sample(range(10),10000) ``` File "/usr/lib/python2.7/random.py", line 320, in sample raise ValueError("sample larger than pop...
What you want is ``` [random.random() for _ in xrange(100000)] ``` From the [random module documentation](http://docs.python.org/library/random.html): > random.sample(population, k) Return a k length list of unique elements > chosen from the population sequence. Used for random sampling without > replacement. so wh...
Setting folder permissions in Windows using Python
12,168,110
9
2012-08-28T21:58:59Z
12,168,268
19
2012-08-28T22:13:43Z
[ "python", "permissions", "active-directory", "share" ]
I'm using Python to create a new personal folder when a users AD account is created. The folder is being created but the permissions are not correct. Can Python add the user to the newly created folder and change their permissions? I'm not sure where to begin coding this.
You want the `win32security` module, which is a part of [pywin32](http://sourceforge.net/projects/pywin32/). Here's [an example](http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html) of doing the sort of thing you want to do. The example creates a new DACL for the file and replaces the old one, but...