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 |
|---|---|---|---|---|---|---|---|---|---|
Changing password in Django Admin | 15,456,964 | 8 | 2013-03-17T02:43:34Z | 15,630,360 | 36 | 2013-03-26T06:01:08Z | [
"python",
"django",
"django-admin",
"django-1.5"
] | I recently created the admin.py based in the Django Project Document:
`https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.AbstractBaseUser`
But I really missed the functionality that allow the administrator the possibility to change the users passwords. How is possible to add th... | Put this in your UserChangeForm:
```
password = ReadOnlyPasswordHashField(label= ("Password"),
help_text= ("Raw passwords are not stored, so there is no way to see "
"this user's password, but you can change the password "
"using <a href=\"password/\">this form</a>."))
`... |
How to set the font size of a Canvas' text item? | 15,457,504 | 7 | 2013-03-17T04:23:56Z | 15,458,040 | 8 | 2013-03-17T06:03:11Z | [
"python",
"python-3.x",
"canvas",
"text",
"tkinter"
] | I have the following code:
```
canvas.create_text(x, y, font="Purisa", text= k)
```
How do I set the font size with a variable named `rndfont`? | For text items, the font size is part of the `font` keyword argument:
```
canvas.create_text(x, y, font=("Purisa", rndfont), text=k)
``` |
How to set the font size of a Canvas' text item? | 15,457,504 | 7 | 2013-03-17T04:23:56Z | 15,459,270 | 10 | 2013-03-17T09:28:23Z | [
"python",
"python-3.x",
"canvas",
"text",
"tkinter"
] | I have the following code:
```
canvas.create_text(x, y, font="Purisa", text= k)
```
How do I set the font size with a variable named `rndfont`? | `font` is an attribute which you can pass in tkinter objects. You pass a **tuple** indicating the font *name* and *size*, so your code should look more like:
```
canvas.create_text(x, y, font=("Purisa", 12), text= k)
```
But you're asking how to make the font size a variable. You should just be able to pass it as a v... |
Ctrl-C crashes Python after importing scipy.stats | 15,457,786 | 20 | 2013-03-17T05:14:46Z | 15,472,811 | 16 | 2013-03-18T08:56:12Z | [
"python",
"scipy",
"keyboardinterrupt"
] | I'm running 64-bit Python 2.7.3 on Win7 64-bit. I can reliably crash the Python interpreter by doing this:
```
>>> from scipy import stats
>>> import time
>>> time.sleep(3)
```
and pressing Control-C during the sleep. A KeyboardInterrupt is not raised; the interpreter crashes. The following is printed:
```
forrtl: e... | Here's a variation on your posted solution that may work. Maybe there's a better way to solve this problem -- or maybe even avoid it all together by setting an environment variable that tells the DLL to skip installing a handler. Hopefully this helps until you find a better way.
Both the [`time` module](http://hg.pyth... |
python - why is read-only property writable? | 15,458,613 | 14 | 2013-03-17T07:44:35Z | 15,458,662 | 22 | 2013-03-17T07:52:36Z | [
"python",
"properties",
"python-2.7",
"readonly",
"private-members"
] | I am trying to define a class with a read-only property in a Python; I followed Python documentation and came up with the following code:
```
#!/usr/bin/python
class Test:
def __init__(self, init_str):
self._prop = init_str
@property
def prop(self):
return self... | For this to work as you expect, `Test` needs to be a new-style class:
```
class Test(object):
^^^^^^^^
```
This is hinted at in the [documentation for `property()`](http://docs.python.org/2/library/functions.html#property):
> Return a property attribute for *new-style classes* (classes that derive from `ob... |
Loading a Neo4j subgraph into Networkx | 15,459,615 | 14 | 2013-03-17T10:13:50Z | 15,464,976 | 9 | 2013-03-17T19:07:05Z | [
"python",
"neo4j",
"networkx",
"graph-databases",
"subgraph"
] | I have been dealing with Neo4j through python's Bulbflow and now need a way to save/export subgraphs. I have seen Java and even Ruby approaches for doing this, however a simple Python approach seems to be hiding from me..
So far, I have found two potential paths:
1. Accessing [Geoff](http://nigelsmall.com/geoff) thro... | I didn't know the answer until you asked, but it seems like you can just export in gml, which networkx can read. Here are a few answers that might be useful:
[Neo4j export Tree](http://stackoverflow.com/questions/6871860/neo4j-export-tree)
[Convert Neo4j DB to XML?](http://stackoverflow.com/questions/2204440/convert-... |
How to get python dictionaries into a pandas time series dataframe where key is date object | 15,459,675 | 3 | 2013-03-17T10:21:45Z | 15,460,528 | 10 | 2013-03-17T12:06:01Z | [
"python",
"pandas"
] | I have a python dictionaries where the key is a dateobject and the value is the timeseires.
```
timeseries = {datetime.datetime(2013, 3, 17, 18, 19): {'t2': 400, 't1': 1000},
datetime.datetime(2013, 3, 17, 18, 20): {'t2': 300, 't1': 3000}
}
```
How to I get this time series into a ... | use `DataFrame.from_dict`:
```
import pandas as pd
import datetime
timeseries = {datetime.datetime(2013, 3, 17, 18, 19): {'t2': 400, 't1': 1000},
datetime.datetime(2013, 3, 17, 18, 20): {'t2': 300, 't1': 3000}
}
print pd.DataFrame.from_dict(timeseries, orient="index")
```
output:
```... |
Passing integer lists to python | 15,459,997 | 9 | 2013-03-17T10:58:25Z | 15,460,288 | 17 | 2013-03-17T11:33:00Z | [
"python",
"command-line",
"argparse"
] | I want to pass 2 lists of integers as input to a python program.
For e.g, (from command line)
```
python test.py --a 1 2 3 4 5 -b 1 2
```
The integers in this list can range from 1-50, List 2 is subset of List1.
Any help/suggestions ? Is `argparse` the right module ? Any concerns in using that ?
I have tried :
`... | `argparse` supports [`nargs`](http://docs.python.org/dev/library/argparse.html#nargs) parameter, which tells you how many parameters it eats.
When `nargs="+"` it accepts one or more parameters, so you can pass `-b 1 2 3 4` and it will be assigned as a list to `b` argument
```
# args.py
import argparse
p = argparse.Ar... |
Compute Gamma(x+1/2)/Gamma(x) | 15,460,414 | 2 | 2013-03-17T11:48:48Z | 15,460,463 | 7 | 2013-03-17T11:55:42Z | [
"python",
"math",
"scipy"
] | I need to compute Gamma(x+1/2)/Gamma(x) for reasonably large x. If I just use <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.gamma.html> it fails as the denominator and numerator are huge. However the fraction itself is around sqrt(x). How can I compute this fraction accurately? | you can use `beta(a, b) = gamma(a) * gamma(b) / gamma(a+b)`
```
from scipy.special import gamma, beta
x = 10
print gamma(x+0.5)/gamma(x)
print gamma(0.5)/beta(x, 0.5)
``` |
Issue setting max line length for PEP8 in Eclipse | 15,460,648 | 8 | 2013-03-17T12:22:50Z | 17,618,656 | 11 | 2013-07-12T15:37:40Z | [
"python",
"eclipse",
"pydev",
"pep8"
] | I am using `Eclipse Juno` on an `Ubuntu x64` machine.
I would like to change the default max line length for the `PyDev`'s PEP8, but I can't!
I go to Window/Preferences/PyDev/Editor/Code Analysis/pep8.py and set the following arguments:
```
--max-line-length=100
```
What I am doing wrong? After setting this, I have... | To set the maximum line length, go to:
```
Window/Preferences/PyDev/Editor/Code Analysis/pep8.py
```
Then, open the file at `Location of pep8.py`, search for `MAX_LINE_LENGTH` variable and set it to the length you want. You just have to restart Eclipse and that's it! :D
*Note: make sure PyDev's options `Do code anal... |
Issue setting max line length for PEP8 in Eclipse | 15,460,648 | 8 | 2013-03-17T12:22:50Z | 25,994,496 | 12 | 2014-09-23T11:56:26Z | [
"python",
"eclipse",
"pydev",
"pep8"
] | I am using `Eclipse Juno` on an `Ubuntu x64` machine.
I would like to change the default max line length for the `PyDev`'s PEP8, but I can't!
I go to Window/Preferences/PyDev/Editor/Code Analysis/pep8.py and set the following arguments:
```
--max-line-length=100
```
What I am doing wrong? After setting this, I have... | The current Pydev has a pep8.py that can set the `--max-line-length` parameter. You can just go to
```
Window â Preferences â Pydev â Editor â Code Analysis â pep8.py
```
and set Arguments to:
```
--max-line-length=99
``` |
Python : Running function in thread does not modify current_thread() | 15,460,677 | 6 | 2013-03-17T12:26:56Z | 15,460,731 | 9 | 2013-03-17T12:33:40Z | [
"python",
"multithreading"
] | I'm currently trying to figure out how threads work in python.
I have the following code:
```
def func1(arg1, arg2):
print current_thread()
....
class class1:
def __init__():
....
def func_call():
print current_thread()
t1 = threading.Thread(func1(arg1, arg2))
t1.st... | You're executing the function instead of passing it. Try this instead:
```
t1 = threading.Thread(target = func1, args = (arg1, arg2))
``` |
How to get the domainname (name+TLD) from a URL in python | 15,460,777 | 3 | 2013-03-17T12:38:38Z | 15,460,894 | 8 | 2013-03-17T12:50:33Z | [
"python",
"url",
"python-2.7",
"domain-name"
] | I want to extract the domain name(name of the site+TLD) from a list of URLs which may vary in their format.
for instance:
Current state---->what I want
```
mail.yahoo.com------> yahoo.com
account.hotmail.co.uk---->hotmail.co.uk
x.it--->x.it
google.mail.com---> google.com
```
Is there any python code that can help me ... | This is somewhat non-trivial, as there is no simple rule to determine what makes a for a valid public suffix (site name + TLD). Instead, what makes a public suffix is [maintained as a list at PublicSuffix.org](http://publicsuffix.org/).
A python package exists that queries that list (stored locally); it's called [`pub... |
Disable DTR in pyserial from code | 15,460,865 | 7 | 2013-03-17T12:48:19Z | 15,479,088 | 9 | 2013-03-18T14:21:17Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] | I'm trying to use pyserial to send data to an arduino. But when I open the COM port it sets DTR low and resets the board. However, I have my arduino code setup such that I have to put it into serial receive mode by holding two buttons for 1 second. I would rather not have to do the serial input on boot of the arduino, ... | You *ought* to be able to disable DTR before opening the port, like this:
```
com = serial.Serial()
com.port = port
com.baudrate = baud
com.timeout = 1
com.setDTR(False)
com.open()
```
However, doing so on the current release of pyserial (2.6) on Windows throws the following exception:
```
..., line 315, in setDTR
V... |
python overloading operators | 15,461,574 | 2 | 2013-03-17T14:00:19Z | 15,461,583 | 10 | 2013-03-17T14:01:54Z | [
"python",
"operator-overloading",
"string-length"
] | i need to implement a DNA class which has attribute a sequence which consists of a string of characters from the alphabet ('A,C,G,T') and i need to overload some operators like less than,greater than,etc..
here is my code:
```
class DNA:
def __init__(self,sequence):
self.seq=sequence
def __lt__(self,... | You probably want to compare `seq`s:
```
def __lt__(self, other):
return self.seq < other.seq
etc.
```
Not `self`'s `seq` with `other`, `self`'s `seq` with `other`'s `seq`.
`other` here is another DNA.
If you need to compare lengths:
```
def __lt__(self, other):
return len(self.seq) < len(other.seq)
etc.... |
Python Requests vs PyCurl Performance | 15,461,995 | 9 | 2013-03-17T14:41:25Z | 15,462,207 | 11 | 2013-03-17T14:59:57Z | [
"python",
"performance",
"benchmarking",
"python-requests",
"pycurl"
] | How does the Requests library compare with the PyCurl performance wise?
My understanding is that Requests is a python wrapper for urllib whereas PyCurl is a python wrapper for libcurl which is native, so PyCurl should get better performance, but not sure by how much.
I can't find any comparing benchmarks. | First and foremost, `requests` is built on top of the [`urllib3` library](http://urllib3.readthedocs.org/en/latest/), the stdlib `urllib` or `urllib2` libraries are not used at all.
There is little point in comparing `requests` with `pycurl` on performance. `pycurl` may use C code for it's work but like all network pr... |
Python Requests vs PyCurl Performance | 15,461,995 | 9 | 2013-03-17T14:41:25Z | 32,899,936 | 15 | 2015-10-02T03:01:31Z | [
"python",
"performance",
"benchmarking",
"python-requests",
"pycurl"
] | How does the Requests library compare with the PyCurl performance wise?
My understanding is that Requests is a python wrapper for urllib whereas PyCurl is a python wrapper for libcurl which is native, so PyCurl should get better performance, but not sure by how much.
I can't find any comparing benchmarks. | **[I wrote you a full benchmark](https://github.com/svanoort/python-client-benchmarks)**, using a trivial Flask application backed by gUnicorn/meinheld + nginx (for performance and HTTPS), and seeing how long it takes to complete 10,000 requests. Tests are run in AWS on a pair of unloaded c4.large instances, and the se... |
Modify the default font in Python Tkinter | 15,462,647 | 6 | 2013-03-17T15:39:43Z | 15,463,496 | 10 | 2013-03-17T16:58:02Z | [
"python",
"python-2.7",
"tkinter"
] | I'm working on a GUI in Python2.7, with Tkinter, and I have an annoying problem.
I would like to define the default font used by all the widgets, if possible in one line.
This line modify only the font used in Entry, or ComboBox:
```
root.option_add("*Font", "courier 10")
```
but not the label of checkbox by example... | Tkinter has several built-in fonts -- `TkDefaultFont`, `TkTextFont`, `TkFixedFont`, etc. These are all what are called "named fonts". They are remarkably powerful -- change one of these and all widgets that use them will change as well.
To change one of these fonts, get a handle to it and then use the `configure` meth... |
How can I send a GET request from my flask app to another site? | 15,463,004 | 15 | 2013-03-17T16:11:57Z | 15,463,141 | 18 | 2013-03-17T16:24:15Z | [
"python",
"ajax",
"flask"
] | Originally, I tried to post an ajax request from my client side to a third party url, but it seems that the browser have security issues with that. I thought about sending an ajax to the server side, from there to send a GET request to the third party, get the response and send it back to the client side. How can I do ... | Install the `requests` module (much nicer than using `urllib2`) and then define a route which makes the necessary request - something like:
```
import requests
from flask import Flask
app = Flask(__name__)
@app.route('/some-url')
def get_data():
return requests.get('http://example.com').content
```
Depending on ... |
python pickle - more than 1 object in a file | 15,463,387 | 11 | 2013-03-17T16:47:55Z | 15,463,472 | 37 | 2013-03-17T16:55:44Z | [
"python",
"file",
"pickle"
] | I have got a method which dumps a number of pickled objects (tuples, actually) into a file.
I do not want to put them into one list, I really want to dump several times into the same file.
My problem is, how do I load the objects again?
The first and second object are just one line long, so this works with readlines.
... | If you pass the filehandle directly into pickle you can get the result you want.
```
import pickle
# write a file
f = open("example", "w")
pickle.dump(["hello", "world"], f)
pickle.dump([2, 3], f)
f.close()
f = open("example", "r")
value1 = pickle.load(f)
value2 = pickle.load(f)
f.close()
```
`pickle.dump` will app... |
Easier way to add multiple list items? | 15,465,204 | 4 | 2013-03-17T19:29:41Z | 15,465,234 | 10 | 2013-03-17T19:32:25Z | [
"python"
] | Is there an easier way to sum together items from a list than the code I've written below? I'm new to this and this seems somewhat unwieldy.
```
n = [3,5,7]
o = [4,10,8]
p = [4,10,5]
lists = [n, o, p]
def sumList(x):
return sum(x)
def listAdder(y):
count = 0
for item in y:
count += sumList(item... | Something like:
```
from itertools import chain
n = [3,5,7]
o = [4,10,8]
p = [4,10,5]
print sum(chain(n, o, p))
# 56
```
This avoids creating an un-necessary list of items, since you pass them to `chain` directly... |
UPDATE or INSERT MySQL Python | 15,465,478 | 2 | 2013-03-17T19:57:13Z | 15,465,634 | 9 | 2013-03-17T20:11:37Z | [
"python",
"mysql",
"mysql-python"
] | I need to update a row if a record already exists or create a new one if it dosen't. I undersant ON DUPLICATE KEY will accomplish this using MYSQLdb, however I'm having trouble getting it working. My code is below
```
cursor = database.cursor()
cursor.execute("INSERT INTO userfan (user_id, number, roun... | A parenthesis was missiing. You can also use the `VALUES(column)` in the `ON DUPLICATE KEY UPDATE` section of the statement:
```
cursor = database.cursor()
cursor.execute("""
INSERT INTO userfan
(user_id, number, round)
VALUES
(%s, %s, %s)
ON DUPLICATE KEY UPD... |
How to group sentences of identical characters in python ( 'aabcdd' -> ['aa', 'b', 'c', 'dd'] )? | 15,465,519 | 2 | 2013-03-17T20:01:26Z | 15,465,566 | 12 | 2013-03-17T20:05:36Z | [
"python"
] | I have a string `'aabbababacccssdd'` from which I want to generate `['aa', 'bb', 'a', 'b', 'a', 'b', 'a', 'ccc', 'ss', 'dd']`
Here's my present solution:
```
def get_pats(n):
n = str(n) # to support integers
a = len(n)
p = []
pat_start = 0
prev = 0
for b in range(0, a):
if n[b] != n[pr... | This is what [itertools.groupby](http://docs.python.org/2/library/itertools.html#itertools.groupby) does for you:
```
text = 'aabbababacccssdd'
from itertools import groupby
print [''.join(g) for k, g in groupby(text)]
# # ['aa', 'bb', 'a', 'b', 'a', 'b', 'a', 'ccc', 'ss', 'dd']
``` |
Plotting results of Pandas GroupBy | 15,465,645 | 30 | 2013-03-17T20:12:23Z | 15,466,103 | 30 | 2013-03-17T20:52:57Z | [
"python",
"matplotlib",
"group-by",
"pandas",
"data-analysis"
] | I'm starting to learn Pandas and am trying to find the most Pythonic (or panda-thonic?) ways to do certain tasks.
Suppose we have a DataFrame with columns A, B, and C.
* Column A contains boolean values: each row's A value is either true or false.
* Column B has some important values we want to plot.
What we want to... | I think @herrfz hit all the high points. I'll just flesh out the details:
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
sin = np.sin
cos = np.cos
pi = np.pi
N = 100
x = np.linspace(0, pi, N)
a = sin(x)
b = cos(x)
df = pd.DataFrame({
'A': [True]*N + [False]*N,
'B': np.hstack((a,b... |
How to test if Python is running from a virtualenv during package installation | 15,466,253 | 4 | 2013-03-17T21:07:24Z | 15,469,948 | 7 | 2013-03-18T04:49:54Z | [
"python",
"virtualenv"
] | I have a Python software which includes a configuration file and a manpage. To install these, I have the following line in my `setup.py` (as described on <http://docs.python.org/2/distutils/setupscript.html#installing-additional-files>):
```
data_files = [('/etc/foo', ['foo.conf']), ('/usr/share/man/man1', ['foo.1'])]... | Ultimately it seems that your question is really about how to detect whether the running Python is in a virtualenv. To get to the bottom of this we must understand how `virtualenv` actually works.
When you run the `activate` script inside a virtualenv, it does two things:
* it updates the `PATH` environment variable ... |
Automation Excel from Python | 15,467,229 | 6 | 2013-03-17T22:50:28Z | 15,467,331 | 8 | 2013-03-17T23:01:43Z | [
"python",
"excel",
"pyxll"
] | In my company, we use Linux in development and production environment. But we have a machine running Windows and Excel because we use a third party application excel addin to get financial market data to the machine. The add-in provides some functions (just like Excel function) for getting these datas into the local ma... | You'll need the Python Win32 extensions - <http://sourceforge.net/projects/pywin32/>
Then you can use COM.
```
from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open(r'c:\path\to\file.xlsx')
ws = wb.Sheets('My Sheet')
# do other stuff, just like VBA
wb.Close()
excel.Quit(... |
Fastest way to remove all multiple occurrence items from a list? | 15,467,458 | 4 | 2013-03-17T23:15:05Z | 15,467,486 | 8 | 2013-03-17T23:18:13Z | [
"python"
] | What is the fastest way to remove all multiple occurrence items from a list of arbitrary items (in my example a list of lists)? In the result, only items that occur a single time in the list should show up, thus removing all duplicates.
input: [[1, 2], [1, 3], [1, 4], [1, 2], [1, 4], [1, 2]]
output: [[1, 3], ]
This ... | If you don't care about preserving ordering:
```
from collections import Counter
def only_uniques(seq):
return [k for k,n in Counter(seq).iteritems() if n == 1]
```
If you do care about preserving ordering:
```
from collections import Counter
def only_uniques_ordered(seq):
counts = Counter(seq)
return ... |
How can I vary a shape's alpha with Tkinter? | 15,468,327 | 3 | 2013-03-18T01:14:00Z | 15,468,503 | 8 | 2013-03-18T01:33:58Z | [
"python",
"tkinter",
"alpha"
] | I have the following code that uses Tkinter to create a window and draw shapes on a canvas inside it.
```
from Tkinter import *
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.t... | I am not completely sure, but I think it is not possible to set a RGBA color as a fill color of a canvas item. However, you can give a try to the `stipple` option:
```
canvas.create_rectangle(20, 50, 300, 100, outline="black", fill="red", width=2, stipple="gray50")
``` |
Replace multi-spacing in strings with single whitespace - Python | 15,469,665 | 2 | 2013-03-18T04:17:24Z | 15,469,683 | 11 | 2013-03-18T04:18:37Z | [
"python",
"string",
"whitespace",
"replace",
"removing-whitespace"
] | The overhead in looping through the string and replacing double spaces with single ones is taking too much time. Is a faster way of trying to replace multi spacing in strings with a single whitespace?
I've been doing it like this, but it's just way too long and wasteful:
```
str1 = "This is a foo bar sentence w... | look at this
```
In [1]: str1 = "This is a foo bar sentence with crazy spaces that irritates my program "
In [2]: ' '.join(str1.split())
Out[2]: 'This is a foo bar sentence with crazy spaces that irritates my program'
```
The method `split()` returns a list of all the words in the string, using str as the ... |
Python: list.extend without mutating original variable | 15,470,175 | 3 | 2013-03-18T05:16:32Z | 15,470,210 | 10 | 2013-03-18T05:20:39Z | [
"python",
"list",
"extend"
] | I am wondering whether there is a way in Python to use `.extend`, but not change the original list. I'd like the result to look something like this:
```
>> li = [1, 2, 3, 4]
>> li
[1, 2, 3, 4]
>> li.extend([5, 6, 7])
[1, 2, 3, 4, 5, 6, 7]
>> li
[1, 2, 3, 4]
```
I tried to google this a few different ways, but I... | The `+` operator in Python is overloaded to concatenate lists, so how about:
```
>>> li = [1, 2, 3, 4]
>>> new_list = li + [5, 6, 7]
>>> new_list
[1, 2, 3, 4, 5, 6, 7]
``` |
Accessing django project in LAN systems | 15,471,173 | 5 | 2013-03-18T06:51:58Z | 15,471,212 | 16 | 2013-03-18T06:55:26Z | [
"python",
"django",
"lan"
] | I used django and developed a site which is working fine, and its about to move to production and ready for deployment in a couple of weeks.
So before moving to production, i want to share the site with some of my employees to check the functionality and something else. Actually their systems are connected in LAN with... | You need to explicitly tell the development server to run on your IP rather than `localhost`.
Try `python manage.py runserver your_ip:port`.
Though it'll be accessible if you're running through apache or any other webservers other than the development server.
And to your 1st question, I would advice you to host and ... |
Accessing django project in LAN systems | 15,471,173 | 5 | 2013-03-18T06:51:58Z | 15,473,083 | 19 | 2013-03-18T09:11:34Z | [
"python",
"django",
"lan"
] | I used django and developed a site which is working fine, and its about to move to production and ready for deployment in a couple of weeks.
So before moving to production, i want to share the site with some of my employees to check the functionality and something else. Actually their systems are connected in LAN with... | If you run
> python manage.py runserver 0.0.0.0:8000
your development server will be available on port 8000 to anyone on your LAN and on localhost as well (and it does not depend on your ip address) |
Using virtualenv with spaces in a path | 15,472,430 | 17 | 2013-03-18T08:28:04Z | 15,475,004 | 14 | 2013-03-18T10:49:26Z | [
"python",
"osx",
"virtualenv",
"pip"
] | I set up a virtualenv environment on my Mac, but cannot get Pip to install packages. It fails with the following error:
```
/Volumes/Macintosh: bad interpreter: No such file or directory
```
I tracked the problem down to there being a space in the path, as is answered here: <http://stackoverflow.com/a/10873611/126564... | Trying this:
* editing `bin/activate`, change `VIRTUAL_ENV='/Volumes/Macintosh HD/Python/my_project'`, and change `PATH="$VIRTUAL_ENV/bin:$PATH"`, to make it work in your environment. using `echo $PATH` to check if it works.
* editing `bin/pip` and `bin/easy_install`, change first line in the two files to
`#!/usr/b... |
Make Python Program Wait | 15,472,707 | 4 | 2013-03-18T08:49:37Z | 15,472,738 | 12 | 2013-03-18T08:51:19Z | [
"python"
] | I need to make my python program wait for 200ms before polling for an input of some description. In C# for example, I could use `Thread.Sleep()` to achieve this. What is the simplest means of doing this in python? | Use [Time](http://docs.python.org/2/library/time.html) module.
For example, to delay 1 second :
```
import time
time.sleep(1) # delay for 1 seconds
```
In your case, if you want to get 200 ms, use this instead:
```
time.sleep(0.2)
```
time.sleep also works with float. |
Make a POST request while redirecting in flask | 15,473,626 | 12 | 2013-03-18T09:41:11Z | 15,480,983 | 35 | 2013-03-18T15:46:32Z | [
"python",
"redirect",
"flask"
] | I am working with flask.
I am in a situation where I need to redirect a post request to another url preserving the request method i.e. "POST" method. When I redirected a "GET" request to another url which accepts "GET" request method is fine.
Here is sample code with which I am trying the above..
```
@app.route('/star... | The `redirect` function provided in `Flask` sends a 302 status code to the client by default, and as mentionned on [Wikipedia](https://en.wikipedia.org/wiki/HTTP_302):
> Many web browsers implemented this code in a manner that violated this standard, changing
> the request type of the new request to GET, regardless of... |
shuffle vs permute numpy | 15,474,159 | 23 | 2013-03-18T10:09:25Z | 15,474,335 | 33 | 2013-03-18T10:18:21Z | [
"python",
"numpy",
"scipy",
"permutation",
"shuffle"
] | What is the difference between `numpy.random.shuffle(x)` and `numpy.random.permutation(x)`?
I have read the doc pages but I could not understand if there was any difference between the two when I just want to randomly shuffle the elements of an array.
To be more precise suppose I have an array `x=[1,4,2,8]`.
If I wa... | `np.random.permutation` has two differences from `np.random.shuffle`:
* if passed an array, it will return a shuffled *copy* of the array; `np.random.shuffle` shuffles the array inplace
* if passed an integer, it will return a shuffled range i.e. `np.random.shuffle(np.arange(n))`
> If x is an integer, randomly permut... |
shuffle vs permute numpy | 15,474,159 | 23 | 2013-03-18T10:09:25Z | 34,122,984 | 7 | 2015-12-06T21:26:20Z | [
"python",
"numpy",
"scipy",
"permutation",
"shuffle"
] | What is the difference between `numpy.random.shuffle(x)` and `numpy.random.permutation(x)`?
I have read the doc pages but I could not understand if there was any difference between the two when I just want to randomly shuffle the elements of an array.
To be more precise suppose I have an array `x=[1,4,2,8]`.
If I wa... | Adding on to what @ecatmur said, `np.random.permutation` is useful when you need to shuffle ordered pairs, especially for classification:
```
from np.random import permutation
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
# Data is currently unshuffled; we should shuffle
# e... |
python regex optional capture group | 15,474,741 | 5 | 2013-03-18T10:36:42Z | 15,474,798 | 22 | 2013-03-18T10:39:20Z | [
"python",
"regex"
] | I have the following problem matching the needed data from filenames like this:
```
miniseries.season 1.part 5.720p.avi
miniseries.part 5.720p.avi
miniseries.part VII.720p.avi # episode or season expressed in Roman numerals
```
The "season XX" chunk may or may not be present or may be written in short form, like ... | It is easy enough to make the season group optional:
```
(^.*?)(?:\Ws(?:eason )?(\d{1,2}|[ivxlcdm]{1,5}))?\Wp(?:art )?(\d{1,2}|[ivxlcdm]{1,5})\W(.*$)
```
using a non-capturing group (`(?:...)`) plus the 0 or 1 quantifier (`?`). I did have to make the first group non-greedy to prevent it from matching the `season` sec... |
List comprehension with if statement | 15,474,933 | 26 | 2013-03-18T10:46:35Z | 15,474,952 | 15 | 2013-03-18T10:47:26Z | [
"python",
"list-comprehension"
] | I want to compare 2 iterables and print the items which appear in both iterables.
```
>>> a = ('q', 'r')
>>> b = ('q')
# Iterate over a. If y not in b, print y.
# I want to see ['r'] printed.
>>> print([ y if y not in b for y in a])
^
```
But it gives me a invalid syntax error where th... | You put the `if` at the end:
```
[y for y in a if y not in b]
```
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
```
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
```
Your version tried to do... |
List comprehension with if statement | 15,474,933 | 26 | 2013-03-18T10:46:35Z | 15,474,969 | 47 | 2013-03-18T10:48:08Z | [
"python",
"list-comprehension"
] | I want to compare 2 iterables and print the items which appear in both iterables.
```
>>> a = ('q', 'r')
>>> b = ('q')
# Iterate over a. If y not in b, print y.
# I want to see ['r'] printed.
>>> print([ y if y not in b for y in a])
^
```
But it gives me a invalid syntax error where th... | You got the order wrong. The `if` should be after the `for` (unless it is unless in an `if-else` ternary operator)
```
[y for y in a if y not in b]
```
This would work however:
```
[y if y not in b else other_value for y in a]
``` |
Deserialize a json string to an object in python | 15,476,983 | 14 | 2013-03-18T12:34:38Z | 15,477,213 | 36 | 2013-03-18T12:47:00Z | [
"python",
"json"
] | I have the following string
```
{"action":"print","method":"onData","data":"Madan Mohan"}
```
I Want to deserialize to a object of class
```
class payload
string action
string method
string data
```
I am using python 2.6 and 2.7 | ```
>>> j = '{"action": "print", "method": "onData", "data": "Madan Mohan"}'
>>> import json
>>>
>>> class Payload(object):
... def __init__(self, j):
... self.__dict__ = json.loads(j)
...
>>> p = Payload(j)
>>> print p.action
print
>>> print p.method
onData
>>> print p.data
Madan Mohan
``` |
Deserialize a json string to an object in python | 15,476,983 | 14 | 2013-03-18T12:34:38Z | 16,826,012 | 13 | 2013-05-30T00:21:32Z | [
"python",
"json"
] | I have the following string
```
{"action":"print","method":"onData","data":"Madan Mohan"}
```
I Want to deserialize to a object of class
```
class payload
string action
string method
string data
```
I am using python 2.6 and 2.7 | To elaborate on Sami's answer:
From [the docs](http://docs.python.org/2/library/json.html):
```
class Payload(object):
def __init__(self, action, method, data):
self.action = action
self.method = method
self.data = data
import json
def as_payload(dct):
return Payload(dct['action'], d... |
Mean values depending on binning with respect to second variable | 15,477,857 | 4 | 2013-03-18T13:19:08Z | 15,478,137 | 10 | 2013-03-18T13:33:37Z | [
"python",
"numpy"
] | I am working with python / numpy. As input data I have a large number of value pairs `(x,y)`. I basically want to plot `<y>(x)`, i.e., the mean value of `y` for a certain data bin `x`. At the moment I use a plain `for` loop to achieve this, which is terribly slow.
```
# create example data
x = numpy.random.rand(1000)
... | You are complicating things unnecessarily. All you need to know is, for every bin in `x`, what are `n`, `sy` and `sy2`, the number of `y` values in that `x` bin, the sum of those `y` values, and the sum of their squares. You can get those as:
```
>>> n, _ = np.histogram(x, bins=xbins)
>>> sy, _ = np.histogram(x, bins=... |
pack a software in Python using py2exe with 'libiomp5md.dll' not found | 15,478,230 | 12 | 2013-03-18T13:38:13Z | 15,480,964 | 7 | 2013-03-18T15:45:35Z | [
"python",
"runtime-error",
"exe",
"executable",
"py2exe"
] | I have Python 2.7 on Window 7 OS. I wish to pack my project.py in an Executable using py2exe. Following the instruction i wrote a setup.py file
```
from distutils.core import setup
import py2exe
setup(console=["project.py"])
```
and I got this message

```
and I got this message

Y=np.array([ [ [12,14,15] ,[12,13,14] ] , [ [15,16], [16,16... | Instead of summing the dot product of each pair, which requires `n * m` operations, you can sum all of the vectors in each list and just do the final dot product, which will only take `n + m` operations.
Before:
```
def calc_slow(L1, L2):
result = 0
for n, m in itertools.product(L1, L2):
result += np.... |
Why is the order in dictionaries and sets arbitrary? | 15,479,928 | 79 | 2013-03-18T14:59:06Z | 15,479,974 | 147 | 2013-03-18T15:01:12Z | [
"python",
"dictionary",
"set",
"python-internals"
] | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
... | The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.
Keys are hashed, and ... |
Why is the order in dictionaries and sets arbitrary? | 15,479,928 | 79 | 2013-03-18T14:59:06Z | 19,749,013 | 9 | 2013-11-03T01:47:49Z | [
"python",
"dictionary",
"set",
"python-internals"
] | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
... | "Arbitrary" isn't the same thing as "non-determined".
What they're saying is that there are no useful properties of dictionary iteration order that are "in the public interface". There almost certainly are many properties of the iteration order that are fully determined by the code that currently implements dictionary... |
Why is the order in dictionaries and sets arbitrary? | 15,479,928 | 79 | 2013-03-18T14:59:06Z | 26,099,671 | 29 | 2014-09-29T12:13:10Z | [
"python",
"dictionary",
"set",
"python-internals"
] | I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.
I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on.
... | This is more a response to [Python 3.41 A set](http://stackoverflow.com/questions/26098775/python-3-41-a-set) before it was closed as a duplicate.
---
The others are right: don't rely on the order. Don't even pretend there is one.
That said, there is *one* thing you can rely on:
```
list(myset) == list(myset)
```
... |
How do I import data with different types from file into a Python Numpy array? | 15,481,523 | 6 | 2013-03-18T16:11:11Z | 15,481,761 | 9 | 2013-03-18T16:20:47Z | [
"python",
"numpy"
] | Say I have a file `myfile.txt` containing:
```
1 2.0000 buckle_my_shoe
3 4.0000 margery_door
```
**How do I import data from the file to a numpy array as an int, float and string?**
I am aiming to get:
```
array([[1,2.0000,"buckle_my_shoe"],
[3,4.0000,"margery_door"]])
```
I've been playing around with the f... | Use [`numpy.genfromtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html):
```
import numpy as np
np.genfromtxt('filename', dtype= None)
# array([(1, 2.0, 'buckle_my_shoe'), (3, 4.0, 'margery_door')],
# dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '|S14')])
``` |
Python threading and semaphore | 15,485,524 | 6 | 2013-03-18T19:45:42Z | 15,485,678 | 7 | 2013-03-18T19:54:09Z | [
"python",
"python-multithreading"
] | I have a python class let's call it AClass and another one MyThread which extends Thread. And in that AClass I make 2 objects of the class MyThread and I also have a semaphore which I give it as a parameter to the constructor of the MyThread class. My question is if I modify the semaphore in one MyThread object will th... | That's the purpose of semaphores, they allow you to safely synchronize concurrent processes.
Keep in mind that threads in Python won't *really* get you concurrency unless you're releasing the GIL (doing IO, calling libraries and so on). If that's what you're going for, you might want to consider the `multiprocessing` ... |
Making a tree structure in django models? | 15,486,520 | 6 | 2013-03-18T20:41:11Z | 15,487,405 | 13 | 2013-03-18T21:37:07Z | [
"python",
"django",
"activerecord",
"django-models"
] | I want to have a model with 2 fields, children and parent. How do I do this in django? I have something like this
```
from django.db import models
class FooModel(models.Model)
parent = models.ForeignKey('self', blank=True, null=True)
children = models.ManyToOneRel('self', blank=True, null=True)
def __init... | `ManyToOneRel` is an internal implementation class, it's not for use in your models.
But why do you think you need it anyway? As the documentation explains in detail, when you define a ForeignKey, you automatically get a reverse relation. So in your case, if you define `parent` then you automatically get `self.foomode... |
Customizing rolling_apply function in Python pandas | 15,487,022 | 3 | 2013-03-18T21:11:24Z | 15,487,647 | 7 | 2013-03-18T21:52:32Z | [
"python",
"group-by",
"pandas",
"aggregate",
"data-analysis"
] | ## Setup
I have a DataFrame with three columns:
* "Category" contains True and False, and I have done `df.groupby('Category')` to group by these values.
* "Time" contains timestamps (measured in seconds) at which values have been recorded
* "Value" contains the values themselves.
At each time instance, two values ar... | Let's work through an example:
```
import pandas as pd
import numpy as np
np.random.seed(1)
def setup(regular=True):
N = 10
x = np.arange(N)
a = np.arange(N)
b = np.arange(N)
if regular:
timestamps = np.linspace(0, 120, N)
else:
timestamps = np.random.uniform(0, 120, N)
d... |
Ruby optparse Limitations | 15,487,628 | 5 | 2013-03-18T21:51:02Z | 15,488,265 | 9 | 2013-03-18T22:34:17Z | [
"python",
"ruby",
"command-line-arguments",
"argparse",
"optparse"
] | I currently script in Python but I wish to try Ruby for several reasons. I've looked at a lot of sample code and read a lot of documentation over the last week. One point of concern I have is the lack of a proper command line argument parsing libraries in Ruby. Ruby experts, don't get mad at me â maybe I don't know. ... | There is [docopt](http://docopt.org/) library that has both Python and Ruby implementations. The specification for the `test` program is:
```
usage: test [-h] [-a | -b | -c] [-d] [<filename>]
```
a,b,c options are mutually exclusive (`-ab` produces an error), it supports combined options: `-ad`, `-da`, etc.
To make ... |
Python converting *args to list | 15,489,091 | 5 | 2013-03-18T23:49:43Z | 15,489,110 | 7 | 2013-03-18T23:51:38Z | [
"python",
"arrays",
"python-2.7",
"args"
] | This is what I'm looking for:
```
def __init__(self, *args):
list_of_args = #magic
Parent.__init__(self, list_of_args)
```
I need to pass \*args to a single array, so that:
```
MyClass.__init__(a, b, c) == Parent.__init__([a, b, c])
``` | Nothing too magic:
```
def __init__(self, *args):
Parent.__init__(self, list(args))
```
Inside of `__init__`, the variable `args` is just a tuple with any arguments that were passed in. In fact you can probably just use `Parent.__init__(self, args)` unless you really need it to be a list.
As a side note, using [`s... |
Producing PDFs in landscape orientation with ReportLab | 15,490,710 | 3 | 2013-03-19T02:52:53Z | 15,490,893 | 9 | 2013-03-19T03:16:38Z | [
"python",
"pdf",
"reportlab"
] | I am working on a Python script that produces a PDF report using ReportLab. I need to produce the pages in landscape orientation and I have already looked through the ReportLab manual but I can't find a way of doing this. Any ideas or suggestions? | Make sure you've imported
```
from reportlab.lib.pagesizes import letter, landscape
```
And then:
```
canvas.setPageSize(landscape(letter))
```
Or more generally,
```
canvas.setPageSize(width, height)
```
and you can set it to be any size you like. Remember reportlab uses points, where 1 point is 1/72 of an inch.... |
Create a random array with a particular average | 15,491,648 | 2 | 2013-03-19T04:44:41Z | 15,491,842 | 9 | 2013-03-19T05:05:15Z | [
"python",
"arrays",
"random",
"numpy",
"scipy"
] | I am using scipy and want to create an an array of legnth n with a particular average.
Suppose I want an random arrays of length 3 with an average of 2.5 hence the possible options could be:
[1.5, 3.5, 2.5]
[.25, 7.2, .05]
and so on and so forth...
I need to create many such arrays with varying lengths and different ... | Just generate numbers over the range you want (0...10 in this case)
```
>>> import random
>>> nums = [10*random.random() for x in range(5)]
```
Work out the average
```
>>> sum(nums)/len(nums)
4.2315222659844824
```
Shift the average to where you want it
```
>>> nums = [x - 4.2315222659844824 + 2.5 for x in nums]
... |
Have Emacs edit Python docstrings using rst-mode | 15,493,342 | 11 | 2013-03-19T06:59:32Z | 15,493,777 | 12 | 2013-03-19T07:31:12Z | [
"python",
"emacs",
"restructuredtext"
] | How to I get Emacs to use `rst-mode` inside of docstrings in Python files? I vaguely remember that different modes within certain regions of a file is possible, but I don't remember how it's done. | The Emacs package that supports that is `mmm-mode`. Ensure that's installed, and then code like this as part of your Emacs startup should do it:
```
(require 'mmm-mode)
(setq mmm-global-mode 'maybe)
(mmm-add-classes
'((python-rst
:submode rst-mode
:front "^ *[ru]?\"\"\"[^\"]*$"
:back "^ *\"\"\""
:incl... |
Why doesn't Python upcase special characters with upper()? | 15,494,142 | 4 | 2013-03-19T07:55:41Z | 15,494,180 | 10 | 2013-03-19T07:58:03Z | [
"python",
"unicode"
] | I don't get that:
```
'ô TRAM'.upper() != 'à TRAM'
'ô TRAM'.upper() == 'ô TRAM'
```
All text editors (including `vim` and `emacs`) convert 'ô TRAM'.upper() to 'à TRAM' when we ask for upcase. Why does Python seem to only upcase [a-zA-Z] characters? And what is the workaround? | In Python 3, which uses Unicode by default, it should works.
In Python 2, you have to force it, this will do the trick:
```
u'ô TRAM'.upper()
```
**`u`** prevents the text to translate to ASCII. *(remaining as unicode)* |
In python, how to store 'constants' for functions only once? | 15,495,376 | 7 | 2013-03-19T09:13:22Z | 15,495,472 | 7 | 2013-03-19T09:18:13Z | [
"python",
"design",
"global-variables",
"constants"
] | Some function need 'constant' values (ie. not designed to be redefined later) that are not to be parametrized. While default arguments are [stored only once](http://stackoverflow.com/a/10121437/611007) for [each function](http://effbot.org/zone/default-values.htm), some are just not very meaningful to be put as paramet... | Set it as an attribute on the function:
```
def foo(bar):
return foo.my_map.get(bar, defaultType)()
foo.my_map = {"rab": barType, "oof": fooType}
```
A callable class or a closure is not simple enough IMO. |
How to reduce number of connections using SQLAlchemy + postgreSQL? | 15,497,027 | 7 | 2013-03-19T10:32:22Z | 15,507,382 | 7 | 2013-03-19T18:17:02Z | [
"python",
"postgresql",
"heroku",
"sqlalchemy",
"flask"
] | I'm developing on **heroku** using their **Postgres** add-on with the Dev plan, which has a connection limit of `20`. I'm new to `python` and this may be trivial, but I find it difficult to abstract the database connection without causing `OperationalError: (OperationalError) FATAL: too many connections for role`.
Cur... | Within SQL Alchemy you should be able to create a connection pool. This pool is what the pool size would be for each Dyno. On the Dev and Basic plan since you could have up to 20, you could set this at 20 if you run 1 dyno, 10 if you run 2, etc. To configure your pool you can setup the engine:
```
engine = create_engi... |
Remove points which contains pixels fewer than (N) | 15,497,308 | 3 | 2013-03-19T10:46:53Z | 15,497,407 | 9 | 2013-03-19T10:51:52Z | [
"python",
"image-processing",
"numpy",
"filter",
"scipy"
] | I tried almost all filters in `PIL`, but failed.
Is there any function in numpy of scipy to remove the noise?
Like Bwareaopen() in Matlab()?
e.g:

PS: If there is a way to fill the letters into black, I will be grateful | Numpy/Scipy can do morphological operations just as well as Matlab can.
See [scipy.ndimage.morphology](http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html), containing, among other things, [`binary_opening()`](http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#binary_opening), the equivalent o... |
Kivy template with dynamic grid layout | 15,497,629 | 2 | 2013-03-19T11:00:43Z | 15,503,797 | 8 | 2013-03-19T15:34:42Z | [
"python",
"layout",
"widget",
"kivy"
] | I'm trying to create a template for a layout which looks like the following:
```
|----------|
| |
| IMAGE | <--- Just an image (square)
| |
|----------|
|[btn][btn]| <--- GridLayout cols=2 of buttons
|[btn][btn]|
|[btn][btn]|
|[btn][btn]|
|[btn][btn]|
|[btn][btn]|
|----------|
```
the ... | ```
#!/usr/bin/env python2
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
Builder.load_string('''
#:kivy 1.6
[SideBar@BoxLayout]:
content: content
orientation: 'vertical'
size_hint: ctx.size_hint if hasattr(ctx, 'size_h... |
Python Jinja error while comparing string | 15,498,027 | 10 | 2013-03-19T11:18:53Z | 15,498,106 | 19 | 2013-03-19T11:22:52Z | [
"python",
"flask",
"jinja2"
] | I'm getting a problem while comparing two string in python:
**this is working:**
```
{% for publication in publications %}
{{ publications[publication].pub_type }}
{% endfor %}
```
but not this:
```
{% for publication in publications %}
{% if publications[publication].pub_type equals "conference_pap... | perhaps you want:
```
{% if publication.pub_type == "conference_paper" %}
{# ^^ #}
```
`equals` is not [valid jinja2 syntax](http://jinja.pocoo.org/docs/switching/#conditions) |
Python pip error: "Cannot fetch index base URL https://pypi.python.org/simple/" | 15,501,133 | 11 | 2013-03-19T13:40:21Z | 15,501,181 | 24 | 2013-03-19T13:42:24Z | [
"python",
"proxy",
"pip"
] | I'm trying to install several packages using pip. When I do this using sudo, this error occurs: "Cannot fetch index base URL <https://pypi.python.org/simple/>". When I execute the command without sudo, the package downloads successfully, but I don't have enough permissions. What could be the reason for such different b... | Maybe try with `sudo -E`:
```
-E The -E (preserve environment) option indicates to the secuâ
rity policy that the user wishes to preserve their existing
environment variables. The security policy may return an
error if the -E option is specified and the user does not... |
Boto Execute shell command on ec2 instance | 15,501,845 | 9 | 2013-03-19T14:11:51Z | 15,503,965 | 18 | 2013-03-19T15:42:15Z | [
"python",
"amazon-ec2",
"boto"
] | I am newbie to EC2 and boto. I have an EC2 running instance and I want to execute a shell command like e.g. `apt-get update` through boto.
I searched a lot and found a solution using `user_data` in the [run\_instances](http://boto.s3.amazonaws.com/ref/ec2.html#boto.ec2.connection.EC2Connection.run_instances) command, ... | The boto.manage.cmdshell module can be used to do this. To use it, you must have the paramiko package installed. A simple example of it's use:
```
import boto.ec2
from boto.manage.cmdshell import sshclient_from_instance
# Connect to your region of choice
conn = boto.ec2.connect_to_region('us-west-2')
# Find the inst... |
Correctly reading text from Windows-1252(cp1252) file in python | 15,502,619 | 11 | 2013-03-19T14:45:50Z | 15,502,713 | 12 | 2013-03-19T14:50:12Z | [
"python",
"utf-8",
"python-unicode",
"windows-1252",
"cp1252"
] | so okay, as the title suggests the problem I have is with correctly reading input from a windows-1252 encoded file in python and inserting said input into SQLAlchemy-MySql table.
The current system setup:
Windows 7 VM with "Roger Access Control System" which outputs the file;
Ubuntu 12.04 LTS VM with a shared-fold... | CP1252 cannot represent Ä; your input contains the similar character â. `repr` just displays an ASCII representation of a unicode string in Python 2.x:
```
>>> print(repr(b'J\xe2nis'.decode('cp1252')))
u'J\xe2nis'
>>> print(b'J\xe2nis'.decode('cp1252'))
Jânis
``` |
Recursive version of 'reload' | 15,506,971 | 12 | 2013-03-19T17:57:23Z | 17,194,836 | 13 | 2013-06-19T15:08:46Z | [
"python",
"python-module",
"python-import"
] | When I'm developing Python code, I usually test it in an ad-hoc way in the interpreter. I'll `import some_module`, test it, find a bug, fix the bug and save, and then use the built-in `reload` function to `reload(some_module)` and test again.
However, suppose that in `some_module` I have `import some_other_module`, an... | I've run up against the same issue, and you inspired me to actually solve the problem.
```
from types import ModuleType
def rreload(module):
"""Recursively reload modules."""
reload(module)
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if type(attribute) is... |
How to get bag of words from textual data? | 15,507,172 | 6 | 2013-03-19T18:06:22Z | 16,449,035 | 11 | 2013-05-08T19:49:53Z | [
"python",
"machine-learning",
"text-processing"
] | I am working on prediction problem using a large textual dataset. I am implementing [Bag of Words Model.](http://en.wikipedia.org/wiki/Bag-of-words_model)
What should be the best way to get the bag of words? Right now, I have [tf-idf](http://en.wikipedia.org/wiki/Tf%E2%80%93idf) of the various words and the number of ... | Using the [collections.Counter class](http://docs.python.org/dev/library/collections#collections.Counter)
```
>>> import collections, re
>>> texts = ['John likes to watch movies. Mary likes too.',
'John also likes to watch football games.']
>>> bagsofwords = [ collections.Counter(re.findall(r'\w+', txt))
... |
Maximum value of first column | 15,508,460 | 4 | 2013-03-19T19:14:59Z | 15,508,550 | 7 | 2013-03-19T19:19:43Z | [
"python",
"max"
] | I have an array like this:
```
elements=[['1', '1', '2'], ['2', '2', '3'], ['3', '3', '4'], ['4', '4', '5'], ['5', '5', '6'], ['6', '6', '7'], ['7', '7', '8'], ['8', '8', '9'], ['9', '9', '10'], ['10', '10', '11'], ['11', '11', '12'], ['12', '12', '13'], ['13', '13', '14'], ['14', '14', '15'], ['15', '15', '16'], ['16... | Your elements are strings, and therefore the comparisons are lexicographic. You want to work with integers:
```
>>> elements=[['1', '1', '2'], ['99', '2', '3'],['360', '10', '11']]
>>> a = np.array(elements,dtype=int)
>>> a
array([[ 1, 1, 2],
[ 99, 2, 3],
[360, 10, 11]])
>>> a.max(axis=0)
arra... |
How to obtain the day of the week in a 3 letter format from a datetime object in python? | 15,509,617 | 4 | 2013-03-19T20:20:44Z | 15,509,654 | 8 | 2013-03-19T20:22:31Z | [
"python"
] | I am working on a script were I must work with datetime objects in Python. At some point I have one of those objects and I need to get the day of the week (which is a number value) in a 3-letter format (i.e. Tue, Wed, etc.). Here is a brief sample of the code, in dateMatch.group() all I am doing is getting pieces of a ... | <http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior>
> date, datetime, and time objects all support a `strftime(format)` method, to create a string representing the time under the control of an explicit format string.
>
> ...
>
> %a â Localeâs abbreviated weekday name.
```
>>> datetime.... |
What is a typical way to add a reverse feature to an insertion sort? | 15,509,639 | 6 | 2013-03-19T20:21:42Z | 15,509,897 | 8 | 2013-03-19T20:35:15Z | [
"python",
"algorithm"
] | I wrote the following insertion sort algorithm
```
def insertionSort(L, reverse=False):
for j in xrange(1,len(L)):
valToInsert = L[j]
i=j-1
while i>=0 and L[i] > valToInsert:
L[i+1] = L[i]
i-=1
L[i+1] = valToInsert
return L
```
Edit: All you need to do i... | You could use a variable for the less-than operator:
```
import operator
def insertionSort(L, reverse=False):
lt = operator.gt if reverse else operator.lt
for j in xrange(1,len(L)):
valToInsert = L[j]
i = j-1
while 0 <= i and lt(valToInsert, L[i]):
L[i+1] = L[... |
Pythonic way to do conditionally assign variables | 15,510,673 | 3 | 2013-03-19T21:21:34Z | 15,510,689 | 11 | 2013-03-19T21:22:40Z | [
"python"
] | Any suggestions on how to do that in Python?
```
if x():
a = 20
b = 10
else:
a = 10
b = 20
```
I can swap them as below, but it's not as clear (nor very pythonic IMO)
```
a = 10
b = 20
if x():
[a, b] = [b, a]
``` | ```
(a,b) = (20,10) if x() else (10,20)
``` |
Selenium: get coordinates or dimensions of element with Python | 15,510,882 | 25 | 2013-03-19T21:34:08Z | 15,511,365 | 33 | 2013-03-19T22:02:28Z | [
"python",
"selenium"
] | I see that there are methods for getting the screen position and dimensions of an element through various Java libraries for Selenium, such as `org.openqa.selenium.Dimension`, which offers `.getSize()`, and `org.openqa.selenium.Point` with `getLocation()`.
Is there any way to get either the location or dimensions of a... | Got it! The clue was on <http://selenium-python.readthedocs.org/en/latest/api.html>
WebElements have the properties `.size` and `.location`. Both are of type `dict`.
```
driver = webdriver.Firefox()
e = driver.find_element_by_xpath("//someXpath")
location = e.location
size = e.size
print(location)
print(size)
```
Re... |
Is it possible for a python function to ignore unused kwargs | 15,510,908 | 5 | 2013-03-19T21:35:33Z | 15,510,919 | 13 | 2013-03-19T21:36:24Z | [
"python",
"kwargs"
] | If I have a simple function:
```
def add(a, b, c):
return a + b + c
```
Is it possible for me to make it so that if I supply an unused kwarg, it is simply ignored?
```
kwargs = dict(a=1, b=2, c=3, d=4)
print add(**kwargs) #prints 6
``` | Sure. Just add `**kwargs` to the function signature:
```
def add(a, b, c, **kwargs):
return a + b + c
kwargs = dict(a=1, b=2, c=3, d=4)
print add(**kwargs)
#prints 6
``` |
Select 50 items from list at random to write to file | 15,511,349 | 17 | 2013-03-19T22:01:11Z | 15,511,372 | 49 | 2013-03-19T22:03:19Z | [
"python",
"file",
"list",
"select",
"random"
] | So far I have figured out how to import the file, create new files, and randomize the list.
I'm having trouble selecting only 50 items from the list randomly to write to a file?
```
def randomizer(input,output1='random_1.txt',output2='random_2.txt',output3='random_3.txt',output4='random_total.txt'):
#Input file
... | If the list is in random order, you can just take the first 50
otherwise use
```
random.sample(the_list, 50)
```
```
Help on method sample in module random:
sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containin... |
Why does -103/100 == -2 but 103/100 == 1 in Python? | 15,511,400 | 9 | 2013-03-19T22:05:08Z | 15,511,428 | 22 | 2013-03-19T22:06:37Z | [
"python",
"integer-division"
] | Why does `-103/100 == -2` but `103/100 == 1` in Python? I can't seem to understand why. | Integer division always rounds down (towards negative infinity).

> Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the *floor*1 function applied to the resul... |
Where does python open files to on a mac? | 15,511,709 | 2 | 2013-03-19T22:27:01Z | 15,511,734 | 8 | 2013-03-19T22:28:18Z | [
"python",
"file",
"text",
"file-io",
"filesystems"
] | I made a simple python script which creates a text file. The contents of the script are
```
f = open("New", "w")
f.close
```
Now I moved the script to the desktop (I'm on a mac) and ran it, and nothing shows up. No file is created on the desktop that is visible for me.
I actually made this little script because one ... | It'll be created in the current working directory, which is the directory from which you called the script. |
python: get all youtube video urls of a channel | 15,512,239 | 4 | 2013-03-19T23:07:34Z | 15,512,328 | 7 | 2013-03-19T23:16:55Z | [
"python",
"youtube",
"youtube-api"
] | I want to get all video url's of a specific channel. I think json with python or java would be a good choice. I can get the newest video with the following code, but how can I get ALL video links (>500)?
```
import urllib, json
author = 'Youtube_Username'
inp = urllib.urlopen(r'http://gdata.youtube.com/feeds/api/video... | Increase max-results from 1 to however many you want, but beware they don't advise grabbing too many in one call and will limit you at 50 (<https://developers.google.com/youtube/2.0/developers_guide_protocol_api_query_parameters>).
Instead you could consider grabbing the data down in batches of 25, say, by changing th... |
Is it possible for Python to read non-ascii text from file? | 15,512,741 | 3 | 2013-03-19T23:53:34Z | 15,512,760 | 7 | 2013-03-19T23:55:40Z | [
"python",
"ascii",
"decode"
] | I have a .txt file that is UTF-8 formatted and have problems to read it into Python. I have a large number of files and a conversion would be cumbersome.
So if I read the file in via
```
for line in file_obj:
...
```
I get the following error:
```
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/py... | There are two choices.
1. Specify the encoding when opening the file, instead of using the default.
2. Open the file in binary mode, and explicitly `decode` from `bytes` to `str`.
The first is obviously the simpler one. You don't show how you're opening the file, but assuming your code looks like this:
```
with open... |
How to change the table's fontsize with matplotlib.pyplot? | 15,514,005 | 6 | 2013-03-20T02:04:33Z | 15,514,091 | 14 | 2013-03-20T02:15:55Z | [
"python",
"matplotlib",
"pylot"
] | I'm drawing a table with pyplot like this:
```
sub_axes.table(cellText=table_vals,
colWidths = [0.15, 0.25],
rowLabels=row_labels,
loc='right')
```
I'd like to change the fontsize of table's content, and found there is a `fontsize` property,
please ref [definition of 'table'](http://... | I think the documentation is either hinting at a parameter-to-be (notice `fontsize` is not a link like the other parameters) or perhaps is a bit misleading at the moment. There is no `fontsize` parameter.
Digging through [the source code](https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/table.py#L37... |
"ImportError: No module named" when trying to run Python script | 15,514,593 | 33 | 2013-03-20T03:10:19Z | 15,622,021 | 49 | 2013-03-25T18:24:42Z | [
"python",
"ipython",
"importerror"
] | I'm trying to run a script that launches, amongst other things, a python script. I get a ImportError: No module named ..., however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted.
What's going on, and how can I fix it? I've tried to understand how python ... | **This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does** (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory.... |
Regarding the Fibonacci Sequence example in Python's function tutorial | 15,515,920 | 5 | 2013-03-20T05:18:33Z | 15,516,031 | 8 | 2013-03-20T05:29:41Z | [
"python",
"fibonacci"
] | This is what [they](http://docs.python.org/2/tutorial/controlflow.html) have:
```
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
```
This is what I have:
```
def fib(n):
a = 0
b = 1
while a < n:
print a
a = b
b = b+a
```
The first returns the ... | This is a tuple assignment:
```
a, b = 0, 1
```
You can also think of it as
```
(a, b) = (0, 1)
```
A temporary tuple is created with the values `0`, and `1` and then unpacked onto the variable `a` and `b`
This is also a tuple assignment
```
a, b = b, a+b
```
Again, you can think of it as
```
(a, b) = (b, a+b)
... |
dict.fromkeys all point to same list | 15,516,413 | 17 | 2013-03-20T06:02:24Z | 15,516,482 | 19 | 2013-03-20T06:08:14Z | [
"python"
] | This was causing me a bit of grief...
I created a dictionary from a list
```
l = ['a','b','c']
d = dict.fromkeys(l, [0,0]) # initializing dictionary with [0,0] as values
d['a'] is d['b'] # returns True
```
How can I make each value of the dictionary a seperate list? Is this possible without iterating over all keys ... | You could use a dict comprehension:
```
>>> keys = ['a','b','c']
>>> value = [0, 0]
>>> {key: list(value) for key in keys}
{'a': [0, 0], 'b': [0, 0], 'c': [0, 0]}
``` |
Write to robot framework console from Python | 15,518,298 | 9 | 2013-03-20T08:10:29Z | 23,809,416 | 10 | 2014-05-22T14:15:59Z | [
"python",
"console",
"robotframework"
] | I am a newbie using python and I wanted to ask for your help in showing me how can I print messages from Python into robot framework console. | There are several ways for a python function to send information to the robot logs or to the console. These are all documented in the Robot framework user's guide, in the section titled [Logging information](http://robotframework.googlecode.com/hg/doc/userguide/RobotFrameworkUserGuide.html?r=2.8.3#logging-information).... |
Python min/max on None type | 15,523,555 | 6 | 2013-03-20T12:27:49Z | 15,523,586 | 7 | 2013-03-20T12:29:16Z | [
"python",
"min",
"nonetype"
] | I noticed that while the 'max' function do well on None type:
```
In [1]: max(None, 1)
Out[1]: 1
```
'min' function doesn't return anything:
```
In [2]: min(None, 1)
In [3]:
```
Maybe it's because there is no definition for min(None, 1)?
So why in max case, it return the number?
Is None treated like '-infinity'? | It does return something, the python shell just doesn't print `None`
```
>>> min(None, 1)
>>> print min(None, 1)
None
``` |
Which is the best way to compress json to store in a memory based store like redis or memcache? | 15,525,837 | 7 | 2013-03-20T14:06:46Z | 15,529,390 | 7 | 2013-03-20T16:34:26Z | [
"python",
"json",
"redis",
"msgpack"
] | Requirement :
Python objects with 2-3 levels of nesting containing basic datypes like integers,strings, lists, and dicts.
( no dates etc), needs to be stored as json in redis against a key.
What are the best methods available for compressing json as a string for low memory footprint.
The target objects are not very lar... | We just use `gzip` as a compressor.
```
import gzip
import cStringIO
def decompressStringToFile(value, outputFile):
"""
decompress the given string value (which must be valid compressed gzip
data) and write the result in the given open file.
"""
stream = cStringIO.StringIO(value)
decompressor = gzip.GzipF... |
How to extend a class in python? | 15,526,858 | 32 | 2013-03-20T14:48:41Z | 15,526,901 | 32 | 2013-03-20T14:50:09Z | [
"python",
"class",
"interface"
] | In python how can you extend a class? For example if I have
color.py
```
class Color:
def __init__(self, color):
self.color = color
def getcolor(self):
return self.color
```
color\_extended.py
```
import Color
class Color:
def getcolor(self):
return self.color + " extended!"
```... | Use:
```
import color
class Color(color.Color):
...
```
If this were Python 2.x, you would also want to derive `color.Color` from `object`, to make it a [new-style class](http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python):
```
class Color(object):
...
```
This is not necess... |
Convert string (without any separator) to list | 15,526,883 | 14 | 2013-03-20T14:49:26Z | 15,526,914 | 50 | 2013-03-20T14:50:36Z | [
"python",
"string",
"list"
] | I have a phone number(string), e.g. "+123-456-7890", that I want to turn into a list that looks like: [+, 1, 2, 3, -, ...., 0].
Why? So I can go iterate through the list and remove all the symbols, so I'm left with a list of only digits, which I can then convert back to a string.
What's the best way to solve this pro... | Make a **list(your\_string)**.
```
>>> s = "mep"
>>> list(s)
['m', 'e', 'p']
``` |
RESTful API and Google Analytics | 15,530,487 | 10 | 2013-03-20T17:22:38Z | 15,537,490 | 8 | 2013-03-21T00:45:09Z | [
"python",
"rest",
"google-analytics",
"flask"
] | I'm running an *RESTful API* with Python ([Flask](http://flask.pocoo.org/)).
I want to be able to track:
* which requests have been made
* when did those requests happen
* how long did it take to send the response
I want to use *Google Analytics* for this, because of it's nice dashboard and extended functionalities.... | There are actually two ways to send server-side data to Google Analytics. The standard method is the GIF Image Request API, which is the same API that ga.js uses on the client-side. Google has started developing a new REST API known as the Measurement Protocol, but this is only in developer preview.
**Server-Side GA**... |
Python Multiprocessing using Queue to write to same file | 15,530,563 | 4 | 2013-03-20T17:25:57Z | 15,531,800 | 7 | 2013-03-20T18:26:04Z | [
"python",
"file-io",
"queue",
"multiprocessing"
] | I know there are many post on Stack Exchange related to writing results from multiprocessing to single file and I have developed my code after reading only those posts. What I am trying to achieve is that run 'RevMapCoord' function in parallel and write its result in one single file using multiprocess.queue. But I am h... | I think you should slim your example to the basics. For example:
```
from multiprocessing import Process, Queue
def f(q):
q.put('Hello')
q.put('Bye')
q.put(None)
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
with open('file.txt', 'w') as fp:
whi... |
Error in GAE with ndb - BadQueryError: Cannot convert FalseNode to predicate | 15,531,450 | 9 | 2013-03-20T18:07:52Z | 15,552,890 | 19 | 2013-03-21T16:22:23Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I have an application running on Google App Engine with python.
Model classes extend from ndb (google.appengine.ext.ndb) classes.
One of my views makes async calls to the database, something more or less like:
```
# ExerciseListLog is a ndb model class
# start_current, end_current are dates
# student_id is a string
#... | I suspect the problem is that contents is an empty list. That is pretty much the only reason FalseNode could ever appear. (The other is calling AND() without arguments.) Your observation that removing this line corroborates my hunch. You probably didn't expect this to happen, and in your local tests it never happened..... |
Attribute or Method? | 15,531,852 | 4 | 2013-03-20T18:29:03Z | 15,531,898 | 9 | 2013-03-20T18:31:32Z | [
"python",
"class",
"methods",
"attributes"
] | I am writing a python script which calculates various quantities based on two parameters, the long radius and short radius of a spheroid. It occurred to me that I could write a spheroid class to do this. However, I'm new to object oriented design and wonder if you more experienced chaps can help me.
An instance is ins... | You have a 3rd option: make it both an attribute and a method, by using a [property](http://docs.python.org/3/library/functions.html#property):
```
class Spheroid(object):
def __init__(self, a, b):
self.long = a
self.short = b
@property
def volume(self):
return 4 * pi / 3 * self.l... |
Controlling alpha value on 3D scatter plot using Python and matplotlib | 15,533,246 | 10 | 2013-03-20T19:45:42Z | 15,540,855 | 10 | 2013-03-21T06:28:31Z | [
"python",
"numpy",
"matplotlib"
] | I'm plotting a 3D scatter plot using the function scatter and mplot3d. I'm choosing a single color for all points in the plot, but when drawn by matplotlib the transparency of the points is set relative to the distance from the camera. Is there any way to disable this feature?
I've tried setting the alpha kwarg to Non... | There is no arguments that can control this. Here is some hack method.
Disable `set_edgecolors` and `set_facecolors` method, so that mplot3d can't update the alpha part of the colors:
```
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projec... |
Dictionary best data structure for train routes? | 15,534,438 | 3 | 2013-03-20T20:49:15Z | 15,534,662 | 9 | 2013-03-20T21:03:18Z | [
"python",
"dictionary",
"routing"
] | So I've been tasked with essentially reading in a file (notepad file) that has a bunch of train stops and the time it takes to get from one stop to another. For example it would look like:
```
Stop A 15
Stop B 12
Stop C 9
```
Now I need to go back and access these stops and their times. I was thinking of ... | I will go against the grain -- and say that a straight flat dict is not the best for this.
Let's say you have 100 stops and multiple routes that are non-alphabetical and non-numeric. Think the Paris subway:

Now try and use a straight Python dict to calculate the ti... |
Python Popen: Write to stdout AND log file simultaneously | 15,535,240 | 18 | 2013-03-20T21:37:48Z | 15,535,389 | 18 | 2013-03-20T21:46:35Z | [
"python",
"subprocess",
"popen"
] | I am using Popen to call a shell script that is continuously writing its stdout and stderr to a log file. Is there any way to simultaneously output the log file continuously (to the screen), or alternatively, make the shell script write to both the log file and stdout at the same time?
I basically want to do something... | You can use a pipe to read the data from the program's stdout and write it to all the places you want:
```
import sys
import subprocess
logfile = open('logfile', 'w')
proc=subprocess.Popen(['cat', 'file'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in proc.stdout:
sys.stdout.write(line)
logfil... |
How to emit SocketIO event on the serverside | 15,535,673 | 18 | 2013-03-20T22:04:33Z | 16,820,268 | 7 | 2013-05-29T17:25:21Z | [
"python",
"django",
"websocket",
"socket.io",
"gevent-socketio"
] | I'm running a gevent-socketio Django application.
I have something similar to this class
```
@namespace('/connect')
class ConnectNamespace(BaseNamespace):
def on_send(self, data):
# ...
```
However, if I receive the events from the javascript client, everything works and for instance `send` event is pro... | What you probably want to do is add a module variable to track connections, say `_connections`, like so:
```
_connections = {}
@namespace('/connect')
class ConnectNamespace(BaseNamespace):
```
and then add `initialize` and `disconnect` methods that use some happy identifier you can reference later:
```
def initiali... |
Python multiprocessing Process crashes silently | 15,536,295 | 5 | 2013-03-20T22:51:23Z | 15,537,163 | 11 | 2013-03-21T00:08:46Z | [
"python",
"python-2.7",
"parallel-processing",
"multiprocessing"
] | I'm using Python 2.7.3. I have parallelised some code using subclassed `multiprocessing.Process` objects. If there are no errors in the code in my subclassed Process objects, everything runs fine. But if there are errors in the code in my subclassed Process objects, they will apparently crash silently (no stacktrace pr... | What you really want is some way to pass exceptions up to the parent process, right? Then you can handle them however you want.
If you use [`concurrent.futures.ProcessPoolExecutor`](http://docs.python.org/dev/library/concurrent.futures.html), this is automatic. If you use [`multiprocessing.Pool`](http://docs.python.or... |
Modify dict values inplace | 15,536,623 | 4 | 2013-03-20T23:18:58Z | 15,536,673 | 12 | 2013-03-20T23:22:42Z | [
"python",
"map",
"dictionary",
"functional-programming"
] | I would like to apply a function to values of a `dict` inplace in the `dict` (like `map` in a functional programming setting).
Let's say I have this `dict`:
```
d = { 'a':2, 'b':3 }
```
I want to apply the function `divide by 2.0` to all values of the dict, leading to:
```
d = { 'a':1., 'b':1.5 }
```
What is the s... | You can loop through the keys and update them:
```
for key, value in d.items():
d[key] = value / 2
``` |
Modify dict values inplace | 15,536,623 | 4 | 2013-03-20T23:18:58Z | 15,536,698 | 7 | 2013-03-20T23:25:11Z | [
"python",
"map",
"dictionary",
"functional-programming"
] | I would like to apply a function to values of a `dict` inplace in the `dict` (like `map` in a functional programming setting).
Let's say I have this `dict`:
```
d = { 'a':2, 'b':3 }
```
I want to apply the function `divide by 2.0` to all values of the dict, leading to:
```
d = { 'a':1., 'b':1.5 }
```
What is the s... | Should work for you:
```
>>> d = {'a':2.0, 'b':3.0}
>>> for x in d:
... d[x]/=2
...
>>> d
{'a': 1.0, 'b': 1.5}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.