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 |
|---|---|---|---|---|---|---|---|---|---|
How to check whether SQLAlchemy session is dirty or not | 16,256,777 | 5 | 2013-04-27T20:54:08Z | 16,286,946 | 7 | 2013-04-29T19:44:46Z | [
"python",
"sqlalchemy"
] | I have a SQLAlchemy `Session` object and would like to know whether it is dirty or not. The exact question what I would like to (metaphorically) ask the `Session` is: "If at this point I issue a `commit()` or a `rollback()`, the effect on the database is the same or not?".
The rationale is this: I want to ask the user... | you're looking for a net count of actual flushes that have proceeded for the whole span of the session's transaction; while there are some clues to whether or not this has happened (called the "snapshot"), this structure is just to help with rollbacks and isn't strong referencing. The most direct route to this would be... |
python boolean key for a dictionary | 16,256,818 | 3 | 2013-04-27T20:59:25Z | 16,256,861 | 7 | 2013-04-27T21:05:32Z | [
"python",
"dictionary",
"boolean",
"boolean-logic"
] | I want to use a group of booleans as a key for a dictionary so (weather == sunny and temp == warm) would be 11 or True,True while (weather == sunny and weather == cold) would be 10 and (weather == cloudy and weather == cold) True,False would be 00 where clothing = {11:"shorts", 10:"jeans", 00:"jacket"} Is there a way t... | If you don't actually need to do bitwise operations on the individual conditions (i.e., you don't need to AND/OR two conditions together), it may be simpler to just use a tuple of booleans as the key:
```
clothing = {
(True, True): "shorts",
(True, False): "jeans",
(False, False): "jacket"
}
``` |
Improving performance of very large dictionary in Python | 16,256,913 | 28 | 2013-04-27T21:12:41Z | 16,257,260 | 60 | 2013-04-27T21:56:13Z | [
"python",
"performance",
"dictionary",
"hashtable"
] | I find that if I initialize an empty dictionary at the beginning, and then adding elements to the dictionary in a for loop (about 110,000 keys, the value for each key is a list, also increasing in the loop), the speed goes down as for loop goes.
I suspect that the problem is, the dictionary does not know the number of... | > If I know the number of keys and exactly what are those keys, is there
> any way in python to make a dict (or a hashtable) work more
> efficiently? I vaguely remember that if you know the keys, you can
> design the hash function smartly (perfect hash?) and allocate the
> space beforehand.
Python doesn't expose a pre... |
Recursively decrement a list by 1 | 16,257,858 | 13 | 2013-04-27T23:14:50Z | 16,257,940 | 14 | 2013-04-27T23:27:15Z | [
"python",
"recursion"
] | Very quick and easy homework question. I have it running ok but I think there's a better
way to do it. A more Pythonic way.
Here's my code to recursively decrement each element of a list by 1.
```
l = range(30)
def recurseDecrMap(l, x = []):
if len(l) == 0:
return []
else:
x.appen... | You can use only one argument, in my opinion it is simpler:
```
def recurseDecrMap(l):
if not l:
return []
else:
return [l[0]-1] + recurseDecrMap(l[1:])
```
But as @jamylak pointed out, the complexity of this algorithm is O(N^2), since `l[1:]` creates a new list with references to the re... |
Recursively decrement a list by 1 | 16,257,858 | 13 | 2013-04-27T23:14:50Z | 16,257,991 | 24 | 2013-04-27T23:33:49Z | [
"python",
"recursion"
] | Very quick and easy homework question. I have it running ok but I think there's a better
way to do it. A more Pythonic way.
Here's my code to recursively decrement each element of a list by 1.
```
l = range(30)
def recurseDecrMap(l, x = []):
if len(l) == 0:
return []
else:
x.appen... | Probably *less* pythonic, but there:
```
def recurseDecrMap(l):
return [l[0]-1] + recurseDecrMap(l[1:]) if l else []
``` |
Recursively decrement a list by 1 | 16,257,858 | 13 | 2013-04-27T23:14:50Z | 16,258,786 | 9 | 2013-04-28T02:02:01Z | [
"python",
"recursion"
] | Very quick and easy homework question. I have it running ok but I think there's a better
way to do it. A more Pythonic way.
Here's my code to recursively decrement each element of a list by 1.
```
l = range(30)
def recurseDecrMap(l, x = []):
if len(l) == 0:
return []
else:
x.appen... | For what it's worth, this is a terrible way to learn about recursion, because you're using it to do something that is not inherently recursive. If your teacher really is asking you to write a program that decrements the elements of a list like `[1, 2, 3, 4]` *recursively*, then shame on him/her.
As Haidro noted, the m... |
Python Error: Global Name not Defined | 16,258,199 | 2 | 2013-04-28T00:09:49Z | 16,258,215 | 8 | 2013-04-28T00:11:35Z | [
"python",
"class"
] | I'm trying to teach myself Python, and doing well for the most part. However, when I try to run the code
```
class Equilateral(object):
angle = 60
def __init__(self):
self.angle1, self.angle2, self.angle3 = angle
tri = Equilateral()
```
I get the following error:
```
Traceback (most recent call last... | ```
self.angle1, self.angle2, self.angle3 = angle
```
should be
```
self.angle1 = self.angle2 = self.angle3 = self.angle
```
just saying `angle` makes python look for a global `angle` variable which doesn't exist. You must reference it through the `self` variable, or since it is a class level variable, you could als... |
Best way to define algebraic data types in Python? | 16,258,553 | 13 | 2013-04-28T01:15:44Z | 16,888,198 | 12 | 2013-06-02T23:15:55Z | [
"python",
"algebraic-data-types",
"macropy"
] | I know that Python is NOT Haskell or Ocaml, but which is the best way to define algebraic data types in Python (2 or 3)? Thanks! | [Macropy](https://github.com/lihaoyi/macropy) provides algebraic data types, pattern matching and more! |
Stop Python code without an error | 16,258,971 | 3 | 2013-04-28T02:35:25Z | 16,259,181 | 8 | 2013-04-28T03:09:09Z | [
"python",
"python-3.3"
] | I have a piece of code which is not in a function, say
```
x = 5
y = 10
if x > 5:
print("stopping")
```
What can I put after the print statement to stop the code from running further? Sys.exit() works, but raises an error that I don't want in the program. I want it to quietly stop the code as if it had reached th... | As JBernardo pointed out, **`sys.exit()` raises an exception**. This exception is [SystemExit](http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit). When it is not handled by the user code, the interpreter exits cleanly (a debugger debugging the program can catch it and keep control of the program, t... |
Django: python manage.py runserver gives RuntimeError: maximum recursion depth exceeded in cmp | 16,259,729 | 10 | 2013-04-28T04:50:15Z | 21,834,988 | 20 | 2014-02-17T17:00:09Z | [
"python",
"django"
] | I am trying to learn Django form the 1st tutorial on the Django project website. I might be missing something obvious but, after following all the instructions when I come to run the command
```
python manage.py runserver
```
I get the error posted at the end of this plea for help (I have posted only the first few li... | The problem is in *functools.py* file. This file is from Python. I have just installed a new version of python 2.7.5 and this file is wrong (I have another - older installation of python 2.7.5 and there the file functools.py is correct)
To fix the problem replace this (about line 56 in python\Lib\fuctools.py):
```
co... |
Reading a file with a specified delimiter for newline | 16,260,061 | 7 | 2013-04-28T05:51:22Z | 16,260,159 | 11 | 2013-04-28T06:10:07Z | [
"python",
"file-io",
"python-2.7",
"io"
] | I have a file in which lines are separated using a delimeter say `.`. I want to read this file line by line, where lines should be based on presence of `.` instead of newline.
One way is:
```
f = open('file','r')
for line in f.read().strip().split('.'):
#....do some work
f.close()
```
But this is not memory effic... | You could use a generator:
```
def myreadlines(f, newline):
buf = ""
while True:
while newline in buf:
pos = buf.index(newline)
yield buf[:pos]
buf = buf[pos + len(newline):]
chunk = f.read(4096)
if not chunk:
yield buf
break
buf += chunk
with open('file') as f:
for... |
Emailing items and logs with Scrapy | 16,260,753 | 4 | 2013-04-28T07:41:51Z | 16,330,707 | 8 | 2013-05-02T05:09:26Z | [
"python",
"email",
"scrapy"
] | I'm trying to get Scrapy to send me an email when a crawler finishes or breaks. There's already a built-in extension for sending stats, but I'd like to attach the spider's errors as `<spidername>-errors.log` and the scraped items as `<spidername>-items.json`.
I've connected callbacks to each of the signals, but for so... | Well, it looks like the problem was much simpler than I had thought. You have to "rewind" `StringIO` instances after you're completely done writing to them:
```
def spider_closed(self, spider):
files = []
for name, contents in self.files.items():
contents.seek(0)
files.append((name, 'text/pla... |
Releasing memory of huge numpy array in IPython | 16,261,240 | 25 | 2013-04-28T08:54:51Z | 16,278,056 | 27 | 2013-04-29T11:55:50Z | [
"python",
"memory-management",
"numpy",
"ipython"
] | *UPDATE:- This problem solved itself after a machine reboot. Not yet able to figure out why this error was happening before.*
I have a function that loads a huge numpy array (~ 980MB) and returns it.
When I first start Ipython and call this function, it loads the array into the variable without any problem.
But if I... | Are you looking at the value? IPython caches output variables as e.g. `Out[8]`, so if you examine it, it will be kept in memory.
You can do `%xdel testcube` to delete the variable and remove it from IPython's cache. Alternatively, `%reset out` or `%reset array` will clear either all your output history, or only refere... |
How terminate Python thread without checking flag continuously | 16,262,132 | 4 | 2013-04-28T10:56:34Z | 16,262,217 | 8 | 2013-04-28T11:08:38Z | [
"python",
"multithreading",
"python-2.7",
"subprocess",
"python-multithreading"
] | ```
class My_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print "Starting " + self.name
cmd = [ "bash", 'process.sh']
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.ST... | For your particular example, it's probably easiest to terminate the thread by terminating the subprocess it spawns using the `Popen` object's [`terminate()`](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.terminate) method...
```
class My_Thread(threading.Thread):
def __init__(self)... |
Printing if different variables are True or False Python 3.3 | 16,262,515 | 2 | 2013-04-28T11:46:49Z | 16,262,538 | 10 | 2013-04-28T11:49:53Z | [
"python",
"python-3.3"
] | I'm having trouble printing a message after checking if variables are true or false. What I want to do is print variables that are true out of a selecton of variables. There must be an easier way of doing it than the below but this is all I can come up with. I need a better solution or a modification on the below to ma... | You are checking if a non-empty tuple is falsish - which is never true. Use [`any`](http://docs.python.org/2/library/functions.html#any) instead.
```
if quirk and not any([minor, creator, nature]):
print (quirk, item)
# and so on
```
`any([minor, creator, nature])` returns `True` if any of the elements in the col... |
Dynamically add legends to matplotlib plots in python | 16,264,748 | 5 | 2013-04-28T16:01:19Z | 16,269,530 | 7 | 2013-04-29T00:18:11Z | [
"python",
"matplotlib",
"plot",
"enthought"
] | I have a set of plots in python and want to add legends to each of them separately. I am generating the plots in a for loop and want to add the legends dynamically.
Im getting only the last legend shown. I want all 9 off them to be displayed
```
for q in range(1,10):
matplotlib.pylab.plot(s_A_approx, label = q)... | I can't reproduce your problem. With a few adjustments to your script, what you're expecting is working for me.
```
import matplotlib.pylab
import numpy as np
for q in range(1,10):
# create a random, 100 length array
s_A_approx = np.random.randint(0, 100, 100)
# note I had to make q a string to avoid an A... |
Converting the output of itertools.permutations from list of tuples to list of strings | 16,264,816 | 5 | 2013-04-28T16:07:40Z | 16,264,903 | 8 | 2013-04-28T16:16:21Z | [
"python",
"string",
"list",
"tuples",
"permutation"
] | Having some issues with a list after using the itertools permutations function.
```
from itertools import permutations
def longestWord(letters):
combinations = list(permutations(letters))
for s in combinations:
''.join(s)
print(combinations)
longestWord("aah")
```
The output looks like this:
``... | ```
from itertools import permutations
def longestWord(letters):
return [''.join(i) for i in permutations(letters)]
print(longestWord("aah"))
```
Result:
```
['aah', 'aha', 'aah', 'aha', 'haa', 'haa']
```
A few suggestions:
1. Don't print inside the function, return instead and print the returned value.
2. Yo... |
How would one add a colorbar to this example? | 16,264,837 | 6 | 2013-04-28T16:09:27Z | 16,290,508 | 7 | 2013-04-30T00:46:15Z | [
"python",
"matplotlib",
"colorbar",
"rose-diagram"
] | In [this example](http://matplotlib.org/examples/pylab_examples/polar_bar.html) the color is correlative to the radius of each bar. How would one add a colorbar to this plot?

My code mimics a "rose diagram" projection which is essentially a bar chart on a pola... | The easiest way is to use a `PatchCollection` and pass in your "z" (i.e. the values you want to color by) as the `array` kwarg.
As a simple example:
```
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
def ... |
NameError when using input() | 16,265,704 | 3 | 2013-04-28T17:37:03Z | 16,265,716 | 7 | 2013-04-28T17:38:17Z | [
"python",
"input",
"python-2.7"
] | So what am I doing wrong here?
```
answer = int(input("What is the name of Dr. Bunsen Honeydew's assistant?"))
if answer == ("Beaker"):
print("Correct!")
else:
print("Incorrect! It is Beaker.")
```
However, I only get
```
Traceback (most recent call last):
File "C:\Users\your pc\Desktop\JQuery\yay.py", l... | You are using `input` instead of `raw_input` with python 2, which evaluates the input as python code.
```
answer = raw_input("What is the name of Dr. Bunsen Honeydew's assistant?")
if answer == "Beaker":
print("Correct!")
```
`input()` is equivalent to `eval(raw_input())`
* [input](http://docs.python.org/2/librar... |
Merging 2 csv files | 16,265,831 | 11 | 2013-04-28T17:48:14Z | 16,266,144 | 25 | 2013-04-28T18:20:06Z | [
"python",
"csv",
"dictionary",
"merge",
"key"
] | OK I have read several threads here on stack overflow. I thought this would be fairly easy for me to do but I find that I still do not have a very good grasp of python. I tried the example located at [How to combine 2 csv files with common column value, but both files have different number of lines](http://stackoverflo... | When I'm working with `csv` files, I often use the [pandas](http://pandas.pydata.org) library. It makes things like this very easy. For example:
```
import pandas as pd
a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=Fals... |
Python Pandas: Group datetime column into hour and minute aggregations | 16,266,019 | 15 | 2013-04-28T18:07:33Z | 16,266,318 | 17 | 2013-04-28T18:36:18Z | [
"python",
"date",
"pandas"
] | This seems like it would be fairly straight forward but after nearly an entire day I have not found the solution. I've loaded my dataframe with read\_csv and easily parsed, combined and indexed a date and a time column into one column but now I want to be able to just reshape and perform calculations based on hour and ... | Can't you do, where `df` is your DataFrame:
```
times = pd.to_datetime(df.timestamp_col)
df.groupby([times.hour, times.minute]).value_col.sum()
``` |
Python Pandas: Group datetime column into hour and minute aggregations | 16,266,019 | 15 | 2013-04-28T18:07:33Z | 32,366,268 | 12 | 2015-09-03T03:00:52Z | [
"python",
"date",
"pandas"
] | This seems like it would be fairly straight forward but after nearly an entire day I have not found the solution. I've loaded my dataframe with read\_csv and easily parsed, combined and indexed a date and a time column into one column but now I want to be able to just reshape and perform calculations based on hour and ... | Wes' code didn't work for me either. But the DatetimeIndex function ([docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html)) did:
```
times = pd.DatetimeIndex(data.datetime_col)
grouped = df.groupby([times.hour, times.minute])
```
The DatetimeIndex object is a representation of times ... |
For Pylint, is it possible to have a different pylintrc file for each Eclipse project? | 16,266,452 | 11 | 2013-04-28T18:49:36Z | 16,273,555 | 16 | 2013-04-29T07:43:33Z | [
"python",
"pylint",
"pylintrc"
] | I saw I can change it per Eclipse instance using [this](https://stackoverflow.com/questions/7665579/permanent-config-file-in-pylint) solution.
I would like to set it per project. Is it possible? | This is not Eclipse specific, but it may help anyway. According to [pylint command line options](https://pylint.readthedocs.io/en/latest/user_guide/run.html#command-line-options):
> You can specify a configuration file on the command line using the `--rcfile` option. Otherwise, Pylint searches for a configuration file... |
Find out if matrix is positive definite with numpy | 16,266,720 | 13 | 2013-04-28T19:15:22Z | 16,266,736 | 19 | 2013-04-28T19:17:05Z | [
"python",
"matrix",
"numpy",
"scipy"
] | I need to find out if matrix is [positive definite](http://en.wikipedia.org/wiki/Positive-definite_matrix). My matrix is numpy matrix. I was expecting to find any related method in numpy library, but no success.
I appreciate any help. | You could try computing Cholesky decomposition ([`numpy.linalg.cholesky`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.cholesky.html)). This will raise `LinAlgError` if the matrix is not positive definite. |
Find out if matrix is positive definite with numpy | 16,266,720 | 13 | 2013-04-28T19:15:22Z | 16,270,026 | 21 | 2013-04-29T01:30:47Z | [
"python",
"matrix",
"numpy",
"scipy"
] | I need to find out if matrix is [positive definite](http://en.wikipedia.org/wiki/Positive-definite_matrix). My matrix is numpy matrix. I was expecting to find any related method in numpy library, but no success.
I appreciate any help. | You can also check if all the eigenvalues of matrix are positive, if so the matrix is positive definite:
```
import numpy as np
def is_pos_def(x):
return np.all(np.linalg.eigvals(x) > 0)
``` |
How to get the pythonpath in shell? | 16,269,903 | 18 | 2013-04-29T01:12:03Z | 16,269,941 | 30 | 2013-04-29T01:17:39Z | [
"python"
] | ```
debian@debian:~$ echo $PYTHONPATH
/home/qiime/lib/:
debian@debian:~$ python
Python 2.7.3 (default, Jan 2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.7/dist-packages/feedparser-... | The environment variable [`PYTHONPATH`](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH) is actually only added to the list of locations Python searches for modules. You can print out the full list in the terminal like this:
```
python -c "import sys; print sys.path"
```
Or if want the output in the UNI... |
How to make a shallow copy of a list in Python | 16,270,374 | 9 | 2013-04-29T02:25:20Z | 16,270,387 | 22 | 2013-04-29T02:26:59Z | [
"python",
"python-2.7"
] | I am trying to implement an algorithm in Python to generate all Permutations of a list. But I In my for loop I wish to keep the original prefix and rest lists intact, and therefore I am trying to make a copy of those lists using newprefix and newrest, however on printing the variable rest at each iteration, I see that ... | To make a shallow copy, you can slice the list:
```
newprefix = prefix[:]
```
Or pass it into the `list` constructor:
```
newprefix = list(prefix)
```
Also, I think you can simplify your code a little:
```
def perm(prefix, rest):
print prefix, rest
for i in range(len(rest)):
perm(prefix + [rest[i]... |
What's wrong with this Python function to solve cubic equations? | 16,270,941 | 3 | 2013-04-29T03:52:53Z | 16,271,613 | 7 | 2013-04-29T05:16:51Z | [
"python",
"math",
"cubic"
] | I am using Python 2 and the fairly simple method given in Wikipedia's article "Cubic function". This could also be a problem with the cube root function I have to define in order to create the function mentioned in the title.
```
# Cube root and cubic equation solver
#
# Copyright (c) 2013 user2330618
#
# This Source ... | [Wolfram Alpha confirms](http://www.wolframalpha.com/input/?i=2%2ax%5E3%20%2b%208%2ax%5E2%20-%208%2ax%20%20-%2032) that the roots to your last cubic are indeed
```
(-4, -2, 2)
```
and not as you say
> ... it should return `[4.0, -4.0, -2.0]`
Not withstanding that (I presume) typo, your program gives
```
[(-4+1.480... |
Python 3.3 CSV.Writer writes extra blank rows | 16,271,236 | 13 | 2013-04-29T04:35:45Z | 16,716,489 | 16 | 2013-05-23T14:23:18Z | [
"python",
"csv",
"python-3.x"
] | Using Python 3.3 on Windows 8, when writing to a CSV file, I get the error `TypeError: 'str' does not support the buffer interface` and `"wb"` flag was used. However when only the `"w"` flag was used, I get no errors, but every row is separated by a blank row!
## Problem Writing
**Code**
```
test_file_object = csv.r... | The `'wb'` mode was OK for Python 2. However, it is wrong in Python 3. In Python 3, the csv reader needs strings, not bytes. This way, you have to open it in text mode. However, the `\n` must not be interpreted when reading the content. This way, you have to pass `newline=''` when opening the file:
```
with open("./fi... |
Function printing in Print Function in Python | 16,272,350 | 2 | 2013-04-29T06:19:40Z | 16,272,366 | 11 | 2013-04-29T06:20:42Z | [
"python"
] | My question is for below code why None is getting print in place of function output and why function output is getting before its position.
```
def print_spam():
print('spam')
def do_twice(r,ps):
g = ps()
print(r,'is a',g)
print(r,'is a',ps())
do_twice('xyz',print_spam)
```
Output is
```
spam
xyz... | The function `print_spam()` does not `return` anything. It just `print`s a statement.
Change it to:
```
def print_spam():
print('spam')
return 'spam'
```
Because your function doesn't return anything, it defaults to `None`. Now when assigning the function output to `g`, it will contain the returned string of... |
How to pass a Numpy array into a cffi function and how to get one back out? | 16,276,268 | 16 | 2013-04-29T10:22:26Z | 16,290,289 | 12 | 2013-04-30T00:17:01Z | [
"python",
"arrays",
"numpy",
"python-cffi"
] | I am developing an audio algorithm using Python and Numpy. Now I want to speed up that algorithm by implementing a part of it in C. In the past, [I have done this using cython](http://bastibe.de/real-time-signal-processing-in-python.html). Now I want to do the same thing using the new [cffi](https://cffi.readthedocs.or... | The `ctypes` attribute of ndarray can interact with the ctypes module, for example, `ndarray.ctypes.data` is the data address of the array, you can cast it to a `float *` pointer,
and then pass the pointer to the C function.
```
import numpy as np
from cffi import FFI
ffi = FFI()
ffi.cdef("void copy(float *in, float ... |
How to pass a Numpy array into a cffi function and how to get one back out? | 16,276,268 | 16 | 2013-04-29T10:22:26Z | 16,393,809 | 10 | 2013-05-06T07:13:26Z | [
"python",
"arrays",
"numpy",
"python-cffi"
] | I am developing an audio algorithm using Python and Numpy. Now I want to speed up that algorithm by implementing a part of it in C. In the past, [I have done this using cython](http://bastibe.de/real-time-signal-processing-in-python.html). Now I want to do the same thing using the new [cffi](https://cffi.readthedocs.or... | the data in a numpy array can be accessed via it's array interface:
```
import numpy as np
import cffi
ffi = cffi.FFI()
a = np.zeros(42)
data = a.__array_interface__['data'][0]
cptr = ffi.cast ( "double*" , data )
```
now you have a cffi pointer type, which you can pass to your copy routine. note that this is a basi... |
Python's `concurrent.futures`: Iterate on futures according to order of completion | 16,276,423 | 9 | 2013-04-29T10:31:12Z | 16,376,753 | 17 | 2013-05-04T16:59:31Z | [
"python",
"multithreading",
"future"
] | I want something similar to `executor.map`, except when I iterate over the results, I want to iterate over them according to the order of completion, e.g. the work item that was completed first should appear first in the iteration, etc. This is so the iteration will block iff every single work item in the sequence is n... | [`executor.map()`](http://docs.python.org/dev/library/concurrent.futures.html#concurrent.futures.Executor.map), like the builtin [`map()`](http://docs.python.org/3.4/library/functions.html#map), only returns results in the order of the iterable, so unfortunately you can't use it to determine the order of completion. [`... |
Image.show() won't display the picture | 16,279,441 | 20 | 2013-04-29T13:07:40Z | 16,280,064 | 26 | 2013-04-29T13:36:39Z | [
"python",
"python-imaging-library"
] | I'm running a python script but it won't show the picture.
I have an apple.jpg image in a directory with this program and it should show the picture, but it doesn't. Here is the code:
```
#!/usr/bin/env python
from PIL import Image
Apple = Image.open("apple.jpg")
Apple.show()
```
My OS is Ubuntu and this program j... | It works for me on Ubuntu. It displays the image with Imagemagick. Try this:
```
sudo apt-get install imagemagick
``` |
Python: argparse taking a list of variable size | 16,280,941 | 2 | 2013-04-29T14:16:26Z | 16,280,979 | 7 | 2013-04-29T14:18:23Z | [
"python",
"input",
"argparse"
] | In Python, using `argparse`, I want an input argument to take a **variable number** of files, like:
```
$ myScript --aParameter file1 file2 file3 ... fileN
```
How can do it?
```
parser.add_argument( "--aParameter", nargs=????, type=str,
help="Provide a list of files to analyze",
... | Use the kwarg `nargs='+'`. That's pretty much all there is to it. |
flask unit test: send cookies after modifying the session | 16,282,576 | 6 | 2013-04-29T15:32:13Z | 16,283,067 | 10 | 2013-04-29T15:58:52Z | [
"python",
"session",
"cookies",
"flask",
"flask-login"
] | I'm writing some unit tests for my flask application and I need to simulate a request from a logged in user (I'm using flask login).
I learned [here](http://stackoverflow.com/questions/16238462/flask-unit-test-how-to-test-request-from-logged-in-user) that to do this I need to modify the session and add the user id and... | the solution was much easier than I thought.
The `test client` object has a method `set_cookie`, so the code should simply be:
```
with app.test_client() as c:
with c.session_transaction() as sess:
sess['user_id'] = 'myuserid'
sess['_fresh'] = True
c.set_cookie('localhost', 'MYCOOKIE', 'cookie... |
Assign value to multiple slices in numpy | 16,282,941 | 9 | 2013-04-29T15:52:18Z | 16,283,049 | 11 | 2013-04-29T15:57:46Z | [
"python",
"arrays",
"matlab",
"numpy",
"slice"
] | In Matlab, you can assign a value to multiple slices of the same list:
```
>> a = 1:10
a =
1 2 3 4 5 6 7 8 9 10
>> a([1:3,7:9]) = 10
a =
10 10 10 4 5 6 10 10 10 10
```
How can you do this in Python with a numpy array?
```
>>> a = np.arang... | You might also consider using `np.r_`:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html>
```
ii = np.r_[0:3,7:10]
a[ii] = 10
In [11]: a
Out[11]: array([ 10, 10, 10, 3, 4, 5, 6, 10, 10, 10])
``` |
how to read a csv file from a url python | 16,283,799 | 27 | 2013-04-29T16:36:43Z | 16,283,926 | 43 | 2013-04-29T16:42:42Z | [
"python",
"csv",
"curl",
"output"
] | when I do curl to a API call link <http://domain.com/passkey=wedsmdjsjmdd>
```
curl 'http://domain.com/passkey=wedsmdjsjmdd'
```
I get the employee output data on a csv file format, like:
```
"Steve","421","0","421","2","","","","","","","","","421","0","421","2"
```
how can parse through this using python.
I trie... | You need to replace `open` with [urllib.urlopen](http://docs.python.org/2/library/urllib.html#urllib.urlopen) or [urllib2.urlopen](http://docs.python.org/2/library/urllib2.html#urllib2.urlopen).
e.g.
```
import csv
import urllib2
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr =... |
how to read a csv file from a url python | 16,283,799 | 27 | 2013-04-29T16:36:43Z | 35,598,438 | 8 | 2016-02-24T09:41:13Z | [
"python",
"csv",
"curl",
"output"
] | when I do curl to a API call link <http://domain.com/passkey=wedsmdjsjmdd>
```
curl 'http://domain.com/passkey=wedsmdjsjmdd'
```
I get the employee output data on a csv file format, like:
```
"Steve","421","0","421","2","","","","","","","","","421","0","421","2"
```
how can parse through this using python.
I trie... | Using pandas it is very simple to read a csv file directly from a url
```
import pandas as pd
data = pd.read_csv('http://domain.com/passkey=wedsmdjsjmdd')
```
This will read your data in tabular format, which will be very easy to process |
Python: loop through several csv files | 16,285,500 | 2 | 2013-04-29T18:15:25Z | 16,285,596 | 7 | 2013-04-29T18:22:43Z | [
"python",
"file",
"loops",
"csv"
] | I was wondering if anybody knew how I could change a script in Python so it goes through a folder containing csv files and takes them in groups of three. The script is working when I type the file names in the command line, but I've got lots of files, so that would take forever. It looks like this now:
```
resultsdir ... | You could use the `glob` module (<http://docs.python.org/3.3/library/glob.html>) to get all `.csv` files in a directory and open them then.
**Example:**
```
import glob
resultsdir = "blah"
files = sorted(glob.glob(resultsdir+'/*.csv'))
while len(files) >= 3:
file1 = open(files.pop(0))
file2 = open(files.po... |
How is a REST response content "magically" converted from 'list' to 'string' | 16,286,363 | 6 | 2013-04-29T19:10:11Z | 16,286,566 | 8 | 2013-04-29T19:22:36Z | [
"python",
"rest"
] | ```
>>> print type(a)
<type 'list'>
>>> response.content = a
>>> print type(response.content)
<type 'str'>
```
Could you explain me this "magic?" How is `a` converted from `list` to `string`?
`response` is an instance of `rest_framework.response.Response`. | There are only a couple ways that you could have something like this happen. The most common reason is if `response.content` is implemented as some sort of descriptor, interesting things like this could happen. (The typical descriptor which would operate like this would be a [`property`](http://docs.python.org/2/librar... |
Converting (YYYY-MM-DD-HH:MM:SS) date time | 16,286,991 | 2 | 2013-04-29T19:48:05Z | 16,288,609 | 10 | 2013-04-29T21:32:51Z | [
"python",
"datetime",
"time"
] | I want to convert a string like this `"29-Apr-2013-15:59:02"`
into something more usable.
The dashes can be easily replaced with spaces or other characters. This format would be ideal: `"YYYYMMDD HH:mm:ss (20130429 15:59:02)"`.
**Edit:**
Sorry, I did not specifically see the answer in another post. But again, I'm ig... | Use [datetime.strptime()](http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime) to parse the `inDate` string into a date object, use [datetime.strftime()](http://docs.python.org/2/library/datetime.html#datetime.date.strftime) to output in whatever format you like:
```
>>> from datetime import date... |
A better way to express a multitude of dot products? | 16,287,366 | 3 | 2013-04-29T20:11:29Z | 16,287,740 | 8 | 2013-04-29T20:34:15Z | [
"python",
"numpy"
] | is there a better and faster way to express the following dot-products in numpy?
I have the following shapes:
```
>>> h.shape
(600L, 400L, 3L)
>>> c.shape
(400L, 3L)
```
I want to calculate the following, if possible without a loop:
```
ans = np.empty((600, 400))
for i in range(400):
ans[:, i] = h[:, i, :].dot(... | You can use `numpy.einsum`
```
ans = einsum('ijk,jk->ij', h, c)
``` |
Django Template Language: Using a for loop with else | 16,287,695 | 9 | 2013-04-29T20:32:01Z | 16,287,731 | 13 | 2013-04-29T20:33:44Z | [
"python",
"django",
"django-templates"
] | In the Django template language is there away to use the the else clause with a for loop? I relies I can use an if check before the for loop but that gets repetitive.
python for-else
```
list = []
for i in list:
print i
else:
print 'list is empty'
```
Django template for-else (my guess)
```
<h1>{{ game.tit... | Use [`for...empty`](https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#for-empty), which is basically the Django equivalent (replaces the `else` keyword with `empty`). |
Generate random number between 0.1 and 1.0. Python | 16,288,749 | 16 | 2013-04-29T21:43:18Z | 16,288,979 | 13 | 2013-04-29T22:01:35Z | [
"python",
"random",
"floating-point"
] | I'm trying to generate a random number between 0.1 and 1.0.
We can't use `rand.randint` because it returns integers.
We have also tried `random.uniform(0.1,1.0)`, but it returns a value >= 0.1 and < 1.0, we can't use this, because our search includes also 1.0.
Does somebody else have an idea for this problem? | How "accurate" do you want your random numbers? If you're happy with, say, 10 decimal digits, you can just round `random.uniform(0.1, 1.0)` to 10 digits. That way you will include both `0.1` and `1.0`:
```
round(random.uniform(0.1, 1.0), 10)
```
To be precise, `0.1` and `1.0` will have only half of the probability co... |
How do I prevent memory leak when I load large pickle files in a for loop? | 16,288,936 | 10 | 2013-04-29T21:58:16Z | 16,289,116 | 7 | 2013-04-29T22:12:54Z | [
"python",
"memory-leaks",
"python-3.x",
"garbage-collection",
"pickle"
] | I have 50 pickle files that are 0.5 GB each.
Each pickle file is comprised of a list of custom class objects.
I have no trouble loading the files individually using
the following function:
```
def loadPickle(fp):
with open(fp, 'rb') as fh:
listOfObj = pickle.load(fh)
return listOfObj
```
However, when... | You can fix that by adding `x = None` right after `for fp in l:`.
The reason this works is because it will dereferenciate variable `x`, hance allowing the python garbage collector to free some virtual memory before calling `loadPickle()` the second time. |
Why is creating a range from 0 to log(len(list), 2) so slow? | 16,289,354 | 9 | 2013-04-29T22:34:40Z | 16,290,128 | 12 | 2013-04-29T23:56:47Z | [
"python",
"performance",
"sage"
] | I don't have a clue why is this happening. I was messing with some lists, and I needed a `for` loop going from 0 to `log(n, 2)` where n was the length of a list. But the code was amazingly slow, so after a bit a research I found that the problem is in the range generation. Sample code for demonstration:
```
n = len([1... | Good grief -- I recognize this one. It's related to one of mine, [trac #12121](http://trac.sagemath.org/sage_trac/ticket/12121). First, you get extra overhead from using a Python `int` as opposed to a Sage `Integer` for boring reasons:
```
sage: log(8, 2)
3
sage: type(log(8, 2))
sage.rings.integer.Integer
sage: log(8r... |
Diff and intersection reporting between two text files | 16,289,458 | 2 | 2013-04-29T22:42:51Z | 16,289,528 | 7 | 2013-04-29T22:50:15Z | [
"python",
"list",
"shell",
"compare"
] | **Disclaimer: I am new to programming and scripting in general so please excuse the lack of technical terms**
So i have two text file data sets that contain names listed:
```
First File | Second File
bob | bob
mark | mark
larry | bruce
tom | tom
```
I would like to run a script (pref python)... | Unix shell solution-:
```
# duplicate lines
sort text1.txt text2.txt | uniq -d
# unique lines
sort text1.txt text2.txt | uniq -u
``` |
Diff and intersection reporting between two text files | 16,289,458 | 2 | 2013-04-29T22:42:51Z | 16,289,747 | 13 | 2013-04-29T23:12:26Z | [
"python",
"list",
"shell",
"compare"
] | **Disclaimer: I am new to programming and scripting in general so please excuse the lack of technical terms**
So i have two text file data sets that contain names listed:
```
First File | Second File
bob | bob
mark | mark
larry | bruce
tom | tom
```
I would like to run a script (pref python)... | sort | uniq is good, but comm might be even better. "man comm" for more information.
From the manual page:
```
EXAMPLES
comm -12 file1 file2
Print only lines present in both file1 and file2.
comm -3 file1 file2
Print lines in file1 not in file2, and vice versa.
```
You can ... |
Splitting large text file into smaller text files by line numbers using Python | 16,289,859 | 9 | 2013-04-29T23:25:07Z | 16,289,922 | 11 | 2013-04-29T23:31:46Z | [
"python",
"file",
"split",
"lines"
] | I have a text file say really\_big\_file.txt that contains:
```
line 1
line 2
line 3
line 4
...
line 99999
line 100000
```
I would like to write a Python script that divides really\_big\_file.txt into smaller files with 300 lines each. For example, small\_file\_300.txt to have lines 1-300, small\_file\_600 to have li... | Using [`itertools` grouper](http://docs.python.org/2/library/itertools.html#recipes) recipe:
```
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
retur... |
Splitting large text file into smaller text files by line numbers using Python | 16,289,859 | 9 | 2013-04-29T23:25:07Z | 16,290,885 | 7 | 2013-04-30T01:35:50Z | [
"python",
"file",
"split",
"lines"
] | I have a text file say really\_big\_file.txt that contains:
```
line 1
line 2
line 3
line 4
...
line 99999
line 100000
```
I would like to write a Python script that divides really\_big\_file.txt into smaller files with 300 lines each. For example, small\_file\_300.txt to have lines 1-300, small\_file\_600 to have li... | ```
lines_per_file = 300
smallfile = None
with open('really_big_file.txt') as bigfile:
for lineno, line in enumerate(bigfile):
if lineno % lines_per_file == 0:
if smallfile:
smallfile.close()
small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file)
... |
Python Saving JSON Files as UTF-8 | 16,291,358 | 2 | 2013-04-30T02:39:06Z | 16,291,378 | 7 | 2013-04-30T02:41:37Z | [
"python",
"json",
"utf-8",
"utf8-decode"
] | I'm trying to output some UTF-8 characters to a JSON file.
When I save the file they're being written like this:
{"some\_key": "Enviar invitaci\u00f3n privada"}
The above is valid and works. When I load the file and print 'some\_key' it displays "Enviar invitación privada" in the terminal.
Is there anyway to write... | Set `ensure_ascii` to `False`:
```
>>> print json.dumps(x, ensure_ascii=False)
{"some_key": "Enviar invitación privada"}
``` |
Why am I receiving a "no ordering relation defined for complex numbers" error? | 16,291,902 | 4 | 2013-04-30T03:55:42Z | 16,292,019 | 10 | 2013-04-30T04:10:38Z | [
"python",
"math",
"cubic"
] | See [this question](http://stackoverflow.com/questions/16270941/whats-wrong-with-this-python-function-to-solve-cubic-equations) for some background. My main problem on that question was solved, and it was suggested that I ask another one for a second problem I'm having:
```
print cubic(1, 2, 3, 4) # Correct solution:... | Python's error messages are pretty good, as these things go: unlike some languages I could mention, they don't feel like random collections of letters. So when Python complains of the comparison
```
if x > 0:
```
that
```
TypeError: no ordering relation is defined for complex numbers
```
you should take it at its w... |
Always Allow Geolocation in Firefox using Selenium | 16,292,634 | 4 | 2013-04-30T05:16:54Z | 17,238,478 | 7 | 2013-06-21T15:02:32Z | [
"python",
"selenium",
"geolocation"
] | I am creating some end-to-end tests for a web app using [Selenium](http://docs.seleniumhq.org/docs/ "Selenium Docs").
I am working in Python and using the Firefox driver
`driver = webdriver.Firefox()`
The problem is that my web app using HTML5 geolocation, and it seems that everytime I run my tests, I have to click ... | You can force browser to return some predefined location without permission requests.
Just execute the following JavaScript code:
```
"navigator.geolocation.getCurrentPosition = function(success) { success({coords: {latitude: 50.455755, longitude: 30.511565}}); }"
```
Tested in Firefox and Chrome. |
How to check if my Python has all required packages? | 16,294,819 | 9 | 2013-04-30T07:48:53Z | 16,294,888 | 9 | 2013-04-30T07:53:36Z | [
"python",
"pip",
"easy-install",
"requirements.txt"
] | I have a requirements.txt file with a list of packages that are required. Is it possible to find out whether all the packages mentioned in the file are present. If some packages are missing, how to find out which are the missing packages? | You can run `pip freeze` to see what you have installed and compare it to your requirements.txt file
If you want to install missing modules you can run `pip install -r requirements.txt` and that will install any missing modules and tell you at the end which ones were missing and installed |
How to check if my Python has all required packages? | 16,294,819 | 9 | 2013-04-30T07:48:53Z | 16,298,328 | 21 | 2013-04-30T11:04:50Z | [
"python",
"pip",
"easy-install",
"requirements.txt"
] | I have a requirements.txt file with a list of packages that are required. Is it possible to find out whether all the packages mentioned in the file are present. If some packages are missing, how to find out which are the missing packages? | The pythonic way of doing it is via the `pkg_resources` [API](https://pythonhosted.org/setuptools/pkg_resources.html). The requirements are written in a format understood by setuptools. E.g:
```
Werkzeug>=0.6.1,
Flask,
Django>=1.3,
```
The example code:
```
import pkg_resources
from pkg_resources import Distribution... |
Error using etree in lxml | 16,296,050 | 6 | 2013-04-30T09:04:03Z | 27,187,436 | 8 | 2014-11-28T11:10:41Z | [
"python",
"windows",
"python-2.7",
"lxml",
"xml.etree"
] | I want to use xpath in python . I tried
```
import xml.etree.ElementTree as ET
```
Since this library has limited usage I had to use lxml after a long session of search on google. I had several problems during installation and finally i installed lxml but when i use
```
from lxml import etree
```
it throws back an ... | I solved this by downloading the 64-bit version of lxml here:
<https://pypi.python.org/pypi/lxml/3.4.1>
lxml-3.4.1.win-amd64-py2.7.exe
It's the only one that worked to solve the win32 error. You might want to destroy the old version of lxml before you do this. |
Convert tuple to list and back | 16,296,643 | 49 | 2013-04-30T09:35:36Z | 16,296,668 | 16 | 2013-04-30T09:37:02Z | [
"python",
"list",
"tuples",
"pygame"
] | I'm currently working on a map editor for a game in pygame, using tile maps.
The level is built up out of blocks in the following structure(though much larger):
```
level1 = (
(1,1,1,1,1,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,1,1,1,1,1))
```
... | You can have a list of lists. Convert your tuple of tuples to a list of lists using:
```
level1 = [list(row) for row in level1]
```
or
```
level1 = map(list, level1)
```
and modify them accordingly.
But a [numpy array](http://www.numpy.org/) is cooler. |
Convert tuple to list and back | 16,296,643 | 49 | 2013-04-30T09:35:36Z | 16,296,703 | 36 | 2013-04-30T09:38:41Z | [
"python",
"list",
"tuples",
"pygame"
] | I'm currently working on a map editor for a game in pygame, using tile maps.
The level is built up out of blocks in the following structure(though much larger):
```
level1 = (
(1,1,1,1,1,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,1,1,1,1,1))
```
... | You have a tuple of tuples.
To convert every tuple to a list:
```
[list(i) for i in level] # list of lists
```
--- OR ---
```
map(list, level)
```
---
And after you are done editing, just convert them back:
```
tuple(tuple(i) for i in edited) # tuple of tuples
```
--- OR --- (Thanks @jamylak)
```
tuple(iterto... |
Convert tuple to list and back | 16,296,643 | 49 | 2013-04-30T09:35:36Z | 23,497,549 | 63 | 2014-05-06T14:27:56Z | [
"python",
"list",
"tuples",
"pygame"
] | I'm currently working on a map editor for a game in pygame, using tile maps.
The level is built up out of blocks in the following structure(though much larger):
```
level1 = (
(1,1,1,1,1,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,0,0,0,0,1)
(1,1,1,1,1,1))
```
... | Convert tuple to list:
```
>>> t = ('my', 'name', 'is', 'mr', 'tuple')
>>> t
('my', 'name', 'is', 'mr', 'tuple')
>>> list(t)
['my', 'name', 'is', 'mr', 'tuple']
```
Convert list to tuple:
```
>>> l = ['my', 'name', 'is', 'mr', 'list']
>>> l
['my', 'name', 'is', 'mr', 'list']
>>> tuple(l)
('my', 'name', 'is', 'mr', '... |
ubuntu ImportError: cannot import name MAXREPEAT | 16,297,892 | 34 | 2013-04-30T10:39:41Z | 16,299,628 | 36 | 2013-04-30T12:12:07Z | [
"python",
"ubuntu"
] | Upgrade to 13.04 has totally messed my system up .
I am having this issue when running
```
./manage.py runserver
Traceback (most recent call last):
File "./manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
File "/home/rats/rats/local/lib/python2.7/site-packages/django/... | If you are using virtualenvwrapper then you can recreate the virtualenv on top of the existing one (with no environment currently active):
`mkvirtualenv <existing name>`
which should pull in the latest (upgraded) python version from the system and fix any mismatch errors. |
ubuntu ImportError: cannot import name MAXREPEAT | 16,297,892 | 34 | 2013-04-30T10:39:41Z | 16,300,373 | 8 | 2013-04-30T12:51:33Z | [
"python",
"ubuntu"
] | Upgrade to 13.04 has totally messed my system up .
I am having this issue when running
```
./manage.py runserver
Traceback (most recent call last):
File "./manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
File "/home/rats/rats/local/lib/python2.7/site-packages/django/... | I have just solved that problem on my machine.
The problem was that Ubuntu 13.04 use python 2.7.4. That makes conflict with the Python version of the `virtualenv`.
What I do was to re-create the `virtualenv` with the new version of python. I think it's the simplest way, but you can try to upgrade the python version w... |
ubuntu ImportError: cannot import name MAXREPEAT | 16,297,892 | 34 | 2013-04-30T10:39:41Z | 16,543,611 | 30 | 2013-05-14T12:47:46Z | [
"python",
"ubuntu"
] | Upgrade to 13.04 has totally messed my system up .
I am having this issue when running
```
./manage.py runserver
Traceback (most recent call last):
File "./manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
File "/home/rats/rats/local/lib/python2.7/site-packages/django/... | You don't need to recreate the environment.
You can upgrade the virtualenv running this command:
> virtualenv /PATH/TO/YOUR\_OLD\_ENV
`YOUR_OLD_ENV` folder will be properly upgraded to the version 2.7.4. |
dynamic memory allocation in python | 16,299,546 | 6 | 2013-04-30T12:07:37Z | 16,300,177 | 10 | 2013-04-30T12:41:04Z | [
"python",
"memory",
"numpy",
"ram"
] | I created a big multidimensional array `M` with `np.zeros((1000,1000))`. After certain number of operations, I don't need it anymore. How can I free a RAM dynamically during program's execution? Does `M=0` do it for me? | In *general* you can't. Even if you remove all the references to an object, it is left to the python implementation to re-use or free the memory. On CPython you could call [`gc.collect()`](http://docs.python.org/2/library/gc.html#gc.collect) to force a garbage collection run. But while that may reclaim memory, it doesn... |
Adding to a dict using a list of key strings as path | 16,300,309 | 5 | 2013-04-30T12:46:59Z | 16,300,379 | 8 | 2013-04-30T12:51:50Z | [
"python",
"dictionary",
"path",
"key"
] | I have the following dict:
```
aDict = {
"a" : {
"b" : {
"c1" : {},
"c2" : {},
}
}
}
```
a second dict:
```
aSecondDict = {
"d1" : {},
"d2" : {},
"d3" : {},
}
```
and a "path" tuple:
```
path = ( "a", "b", "c2" )
```
I now want to add the second dict to... | You can use `reduce`1 to get the dictionary and `dict.update` to put the new stuff in there:
```
reduce(lambda d,key: d[key],path,aDict).update(aSecondDict)
```
You can even get a little more clever if you want:
```
reduce(dict.__getitem__,path,aDict).update(aSecondDict)
```
I suppose it should be noted that the tw... |
What exactly is Python's iterator protocol? | 16,301,253 | 5 | 2013-04-30T13:34:59Z | 16,301,581 | 7 | 2013-04-30T13:49:43Z | [
"python",
"iteration"
] | Is there an objective definition? Is it implemented as a fragment of python's source code? If so, could someone produce the exact code lines? Have all languages with, say, a 'for' statement iterator protocols of their own? | It's located [here](http://docs.python.org/2/library/stdtypes.html#iterator-types) in the docs:
One method needs to be defined for container objects to provide iteration support:
`container.__iter__()`
Return an iterator object. The object is required to support the iterator protocol described below. If a container ... |
what is the Python equivalent of Ruby's yield? | 16,301,706 | 11 | 2013-04-30T13:55:18Z | 16,301,981 | 9 | 2013-04-30T14:08:57Z | [
"python",
"ruby",
"closures"
] | I'm switching from Ruby to Python for a project. I appreciate the fact that Python has first-class functions and closures, so this question ought to be easy. I just haven't figured out what is idiomatically correct for Python:
In Ruby, I could write:
```
def with_quietude(level, &block)
begin
saved_gval = gval
... | Looking more into ruby's yield, it looks like you want something like [`contextlib.contextmanager`](http://docs.python.org/2/library/contextlib.html#contextlib.contextmanager):
```
from contextlib import contextmanager
def razz_the_jazz():
print gval
@contextmanager
def quietude(level):
global gval
saved... |
ImportError: cannot import name MAXREPEAT with cx_Freeze | 16,301,735 | 15 | 2013-04-30T13:56:28Z | 16,309,580 | 14 | 2013-04-30T21:53:19Z | [
"python",
"python-2.7",
"cx-freeze"
] | I'm running into an issue with `cx_Freeze` when running a frozen application (works fine unfrozen).
When running the program it results in the following traceback:
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/cx_Freeze/initscripts/Console.py", line 27, in <module>
exec cod... | `_sre` is a [built in module](http://docs.python.org/2.7/library/sys#sys.builtin_module_names), so there's no file to include for it, but it doesn't have a MAXREPEAT attribute in Python 2.7.3:
```
>>> import _sre
>>> _sre
<module '_sre' (built-in)>
>>> _sre.MAXREPEAT
Traceback (most recent call last):
File "<stdin>"... |
ImportError: cannot import name MAXREPEAT with cx_Freeze | 16,301,735 | 15 | 2013-04-30T13:56:28Z | 16,663,357 | 33 | 2013-05-21T06:17:38Z | [
"python",
"python-2.7",
"cx-freeze"
] | I'm running into an issue with `cx_Freeze` when running a frozen application (works fine unfrozen).
When running the program it results in the following traceback:
```
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/cx_Freeze/initscripts/Console.py", line 27, in <module>
exec cod... | I encountered this problem when I just upgraded from ubuntu 12.10 to 13.04, and I fixed this by copying the /usr/bin/python to /path/to/my/env/bin/, and it worked just fine
`cp /user/bin/python /path/to/my/env/bin/`
or, there's a more elegant way to fix this([reference](http://stackoverflow.com/questions/16297892/ubu... |
Classifiying a set of Images into Classes | 16,302,127 | 11 | 2013-04-30T14:16:50Z | 16,457,320 | 8 | 2013-05-09T08:12:55Z | [
"python",
"image",
"classification",
"descriptor",
"pca"
] | I have the problem that I get a set of pictures and need to classify those.
The thing is, i do not really have any knowledge of these images. So i plan on using as many descriptors as I can find and then do a PCA on those to identify only the descriptors that are of use to me.
I can do supervised learning on a lot of... | You can convert a picture to a vector of pixels, and perform PCA on that vector. This might be easier than trying to manually find descriptors. You can use numPy and sciPy in python.
For example:
```
import scipy.io
from numpy import *
#every row in the *.mat file is 256*256 numbers representing gray scale values
#for... |
Determine where a function was executed? | 16,305,867 | 5 | 2013-04-30T17:41:27Z | 16,305,905 | 11 | 2013-04-30T17:44:19Z | [
"python"
] | how should I define a function, `where`,which can tell where it was executed, with no arguments passed in?
all files in ~/app/
a.py:
```
def where():
return 'the file name where the function was executed'
```
b.py:
```
from a import where
if __name__ == '__main__':
print where() # I want where() to return '... | You need to look up the call stack by using [`inspect.stack()`](http://docs.python.org/2/library/inspect.html#inspect.stack):
```
from inspect import stack
def where():
caller_frame = stack()[1]
return caller_frame[0].f_globals.get('__file__', None)
```
or even:
```
def where():
caller_frame = stack()[1... |
How to integrate a standalone Python script into a Rails application? | 16,305,991 | 22 | 2013-04-30T17:49:47Z | 16,381,433 | 22 | 2013-05-05T04:33:59Z | [
"python",
"ruby-on-rails",
"ruby",
"heroku",
"rake"
] | I've got a program that has a small file structure going on and is then ran using
```
python do_work.py foo bar
```
I want my Rails users to press a button and have this happen for them, with the result either uploaded somewhere or just thrown to them as a download link or something of the sort - the output of `do_wo... | Your `index` method does not work because `python --version` outputs its version to STDERR, not STDOUT. If you don't need to separate these streams, you may just redirect STDERR to STDOUT:
```
value = %x(python --version 2>&1)
```
This call is synchronous, so after running the script (`python do_work.py foo bar 2>&1`... |
Python ImportError for strptime in spyder for windows 7 | 16,309,650 | 5 | 2013-04-30T21:57:36Z | 16,322,487 | 9 | 2013-05-01T16:43:35Z | [
"python",
"datetime",
"importerror",
"strptime",
"spyder"
] | I can't for the life of me figure out what is causing this very odd error.
I am running a script in python 2.7 in the spyder IDE for windows 7. It uses datetime.datetime.strptime at one point. I can run the code once and it seems fine (although I haven't finished debugging, so exceptions have been raised and it hasn't... | The solution, as noted by mfitzp, was to include a dummy call to datetime.datetime.strptime at the beginning of the script.
e.g.
```
# This is a throwaway variable to deal with a python bug
throwaway = datetime.datetime.strptime('20110101','%Y%m%d')
``` |
What does this mean: key=lambda x: x[1] ? | 16,310,015 | 6 | 2013-04-30T22:31:19Z | 16,310,027 | 11 | 2013-04-30T22:32:32Z | [
"python",
"python-2.7"
] | I see it used in sorting, but what do the individual components of this line of code actually mean?
```
key=lambda x: x[1]
```
What's `lambda`, what is `x:`, why `[1]` in `x[1]` etc...
**Examples**
```
max(gs_clf.grid_scores_, key=lambda x: x[1])
sort(mylist, key=lambda x: x[1])
``` | `lambda` effectively creates an inline function. For example, you can rewrite this example:
```
max(gs_clf.grid_scores_, key=lambda x: x[1])
```
Using a named function:
```
def element_1(x):
return x[1]
max(gs_clf.grid_scores_, key=element_1)
```
In this case, `max()` will return the element in that array whos... |
What does this mean: key=lambda x: x[1] ? | 16,310,015 | 6 | 2013-04-30T22:31:19Z | 16,310,039 | 9 | 2013-04-30T22:33:18Z | [
"python",
"python-2.7"
] | I see it used in sorting, but what do the individual components of this line of code actually mean?
```
key=lambda x: x[1]
```
What's `lambda`, what is `x:`, why `[1]` in `x[1]` etc...
**Examples**
```
max(gs_clf.grid_scores_, key=lambda x: x[1])
sort(mylist, key=lambda x: x[1])
``` | `lambda` signifies an [*anonymous function*](http://en.wikipedia.org/wiki/Anonymous_function#Python). In this case, this function takes the single argument `x` and returns `x[1]` (i.e. the item at index 1 in `x`).
Now, `sort(mylist, key=lambda x: x[1])` sorts `mylist` based on the value of `key` as applied to each ele... |
Python - json without whitespaces | 16,311,562 | 49 | 2013-05-01T01:42:00Z | 16,311,587 | 82 | 2013-05-01T01:45:32Z | [
"python",
"json"
] | I just realized that `json.dumps()` adds spaces in the JSON object
e.g.
```
{'duration': '02:55', 'name': 'flower', 'chg': 0}
```
how can remove the spaces in order to make the JSON more compact and save bytes to be sent via HTTP?
such as:
```
{'duration':'02:55','name':'flower','chg':0}
``` | ```
json.dumps(separators=(',', ':'))
``` |
Python - json without whitespaces | 16,311,562 | 49 | 2013-05-01T01:42:00Z | 35,013,643 | 7 | 2016-01-26T12:14:56Z | [
"python",
"json"
] | I just realized that `json.dumps()` adds spaces in the JSON object
e.g.
```
{'duration': '02:55', 'name': 'flower', 'chg': 0}
```
how can remove the spaces in order to make the JSON more compact and save bytes to be sent via HTTP?
such as:
```
{'duration':'02:55','name':'flower','chg':0}
``` | In some cases you may want to get rid of the **trailing whitespaces** only.
You can then use
```
json.dumps(separators=(',', ': '))
```
There is a space after `:` but not after `,`.
This is useful for diff'ing your JSON files (in version control such as `git diff`), where some editors will get rid of the trailing wh... |
Connect to a Database in Flask, Which Approach is better? | 16,311,974 | 36 | 2013-05-01T02:36:42Z | 16,534,727 | 23 | 2013-05-14T03:40:46Z | [
"python",
"sqlite",
"sqlite3",
"flask"
] | Method One: Using special g object from <http://flask.pocoo.org/docs/tutorial/dbcon/> and <http://flask.pocoo.org/docs/patterns/sqlite3/>
```
import sqlite3
from flask import g
DATABASE = '/path/to/database.db'
def connect_db():
return sqlite3.connect(DATABASE)
@app.before_request
def before_request():
g.db... | The difference between the two is that method one creates a connection on `g.db` whether you need it or not while method two only creates the connection when you call `get_db` for the first time in that application context.
If you compare the two, using this setup:
```
yourapp = Flask(__name__)
# setup g.db or app_c... |
Connect to a Database in Flask, Which Approach is better? | 16,311,974 | 36 | 2013-05-01T02:36:42Z | 16,601,526 | 10 | 2013-05-17T04:42:14Z | [
"python",
"sqlite",
"sqlite3",
"flask"
] | Method One: Using special g object from <http://flask.pocoo.org/docs/tutorial/dbcon/> and <http://flask.pocoo.org/docs/patterns/sqlite3/>
```
import sqlite3
from flask import g
DATABASE = '/path/to/database.db'
def connect_db():
return sqlite3.connect(DATABASE)
@app.before_request
def before_request():
g.db... | The first has the issue of acquiring connections even when they aren't needed. The second has the downside of playing with internals of a third party framework, plus it's pretty unreadable.
Of the two alone, the second is probably the better choice. Not only does it not acquire a connection for routes that don't need ... |
python: import csv file (delimiter ";" or ",") | 16,312,104 | 30 | 2013-05-01T02:55:16Z | 16,312,203 | 33 | 2013-05-01T03:09:47Z | [
"python",
"file",
"csv",
"import",
"delimiter"
] | I want to import two kinds of CSV files, some use ";" for delimiter and others use ",". So far I have been switching between the next two lines:
```
reader=csv.reader(f,delimiter=';')
```
or
```
reader=csv.reader(f,delimiter=',')
```
Is it possible not to specify the delimiter and to let the program check for the r... | The `csv` module seems to recommend using the [csv sniffer](http://docs.python.org/2/library/csv.html#csv.Sniffer) for this problem.
They give the following example, which I've adapted for your case.
```
with open('example.csv', 'rb') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=";,")
... |
python: import csv file (delimiter ";" or ",") | 16,312,104 | 30 | 2013-05-01T02:55:16Z | 18,901,943 | 8 | 2013-09-19T18:06:16Z | [
"python",
"file",
"csv",
"import",
"delimiter"
] | I want to import two kinds of CSV files, some use ";" for delimiter and others use ",". So far I have been switching between the next two lines:
```
reader=csv.reader(f,delimiter=';')
```
or
```
reader=csv.reader(f,delimiter=',')
```
Is it possible not to specify the delimiter and to let the program check for the r... | To solve the problem, I have created a function which reads the first line of a file (header) and detects the delimiter.
```
def detectDelimiter(csvFile):
with open(csvFile, 'r') as myCsvfile:
header=myCsvfile.readline()
if header.find(";")!=-1:
return ";"
if header.find(",")!=-... |
Comparing two lists and only printing the differences? (XORing two lists) | 16,312,730 | 4 | 2013-05-01T04:26:54Z | 16,312,772 | 7 | 2013-05-01T04:32:08Z | [
"python",
"python-2.7"
] | I'm trying to create a function that takes in 2 lists and returns the list that only has the differences of the two lists.
Example:
```
a = [1,2,5,7,9]
b = [1,2,4,8,9]
```
The result should print `[4,5,7,8]`
The function so far:
```
def xor(list1, list2):
list3=list1+list2
for i in range(0, len(list3)):
... | You basically want to add an element to your new list if it is present in one and not present in another. Here is a compact loop which can do it. For each element in the two lists (concatenate them with `list1+list2`), we add element if it is not present in one of them:
```
[a for a in list1+list2 if (a not in list1) ... |
Python - Removing overlapping lists | 16,312,871 | 13 | 2013-05-01T04:47:33Z | 16,314,541 | 10 | 2013-05-01T07:47:53Z | [
"python",
"algorithm",
"list"
] | Say I have a list of lists that has indexes `[[start, end], [start1, end1], [start2, end2]]`.
Like for example :
`[[0, 133], [78, 100], [25, 30]]`.
How would I get check for overlap between among the lists and remove the list with the longer length each time?
So:
```
>>> list = [[0, 133], [78, 100], [25, 30]]
>>> f... | To remove a minimal number of intervals from the list such that the intervals that are left do not overlap, `O(n*log n)` algorithm exists:
```
def maximize_nonoverlapping_count(intervals):
# sort by the end-point
L = sorted(intervals, key=lambda (start, end): (end, (end - start)),
reverse=True) ... |
Write PHP non blocking applications | 16,313,224 | 12 | 2013-05-01T05:29:21Z | 16,313,340 | 9 | 2013-05-01T05:43:54Z | [
"php",
"python",
"node.js",
"nginx",
"nonblocking"
] | I want to write non-blocking applications. I use apache2, but I was reading about nginx and its advantage with respect to apache processes. I am considering changing out apache for nginx. My question is, is it possible to write non-blocking web applications with php and nginx?.
Or is a better idea to try and do this w... | Writing non blocking applications in php is possible, but it's probably not the best environment to do so, as it wasn't created keeping that in mind! You get a pretty decent control over your child processes using the process control library [PCNTL](http://www.php.net/manual/en/book.pcntl.php) but it obviously won't ev... |
Consuming GAE Endpoints with a Python client | 16,315,131 | 4 | 2013-05-01T08:40:22Z | 16,319,590 | 12 | 2013-05-01T14:03:37Z | [
"python",
"google-app-engine",
"google-cloud-endpoints"
] | I am using Google AppEngine Endpoints to build a web API.
I will consume it with a client written in Python.
I know that scripts are provided to generate Android and iOS client API, but it doesn't seem that there is anything comparable for Python.
It does seem redundant to code everything again. For instance, the mess... | You can use the [Google APIs Client Library for Python](https://code.google.com/p/google-api-python-client/) which is compatible with endpoints.
Normally you would build a client using `service = build(api, version, http=http)` for example `service = build("plus", "v1", http=http)` to build a client to access to Googl... |
Python - List comprehension with multiple arguments in the for | 16,317,598 | 5 | 2013-05-01T11:49:35Z | 16,317,606 | 7 | 2013-05-01T11:50:31Z | [
"python",
"list",
"list-comprehension"
] | I have this current list comprehension:
```
...
cur = [[14, k, j] for j, k in rows[14], range(15)]
...
```
and it is giving me the following error:
```
...
cur = [[14, k, j] for j, k in rows[14], range(15)]
ValueError: too many values to unpack
```
Any help appreciated as in how I would fix this. I just... | You need to [`zip`](http://docs.python.org/2/library/functions.html#zip) them to iterate like that:
```
cur = [[14, k, j] for j, k in zip(rows[14], range(15))]
``` |
Can't pretty print json from python | 16,318,543 | 4 | 2013-05-01T12:59:02Z | 16,319,664 | 13 | 2013-05-01T14:07:53Z | [
"python",
"json"
] | Whenever I try to print out json from python, it ignores line breaks and prints the literal string "\n" instead of new line characters.
I'm generating json using jinja2. Here's my code:
```
print json.dumps(template.render(**self.config['templates'][name]))
```
It prints out everything in the block below (literally ... | This is what I use for pretty-printing json-objects:
```
def get_pretty_print(json_object):
return json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ': '))
print get_pretty_print(my_json_obj)
```
`json.dumps()` also accepts parameters for encoding, if you need non-ascii support. |
Disable webcam's Autofocus in Linux | 16,319,759 | 8 | 2013-05-01T14:13:38Z | 16,658,508 | 13 | 2013-05-20T21:12:34Z | [
"python",
"linux",
"opencv"
] | I'm working in embebed system in the beagleboard. The source code is in Python, but I import libraries from OpenCV to do image processing. Actually, I'm using the webcam Logitech c910, it's a excellent camera but it has autofocus. I would like to know if I can disable the autofocus from Python or any program in Linux? | Use program `v4l2-ctl` from your shell to control hardware settings on your webcam. To turn off autofocus, try:
```
v4l2-ctl -c focus_auto=0
```
Display all possible controls via:
```
v4l2-ctl -l
```
The above commands default to your first device, i.e. /dev/video0. If you got two webcams, use `-d` switch to select... |
Quantifying randomness | 16,320,412 | 10 | 2013-05-01T14:49:09Z | 16,320,469 | 9 | 2013-05-01T14:52:16Z | [
"python",
"random"
] | I've come up with 2 methods to generate relatively short random strings- one is much faster and simpler and the other much slower but I *think* more random. Is there a not-super-complicated method or way to measure *how* random the data from each method might be?
I've tried compressing the output strings (via zlib) fi... | You are using standard compression as a proxy for the uncomputable [Kolmogorov Complexity](http://en.wikipedia.org/wiki/Kolmogorov_complexity), which is the "right" mathematical framework for quantifying randomness (but, unfortunately, is not computable).
You might also try some measure of [entropy](http://en.wikipedi... |
Is it bad practice to write a whole Flask application in one file? | 16,320,603 | 10 | 2013-05-01T14:59:28Z | 16,321,371 | 15 | 2013-05-01T15:39:16Z | [
"python",
"flask",
"coding-style",
"standards",
"project-structure"
] | I'm currently writing a web application in Python using the Flask web framework. I'm really getting used to just putting everything in the one file, unlike many other projects I see where they have different directories for classes, views, and stuff. However, the Flask example just stuff everything into the one file, w... | Usually it's not a good practice to keep your app in a single file except that it's trivial or for educational purposes.
I don't want to reinvent the wheel, so here's links for sample flask project structures, skeletons and other info on the subject:
* <https://github.com/mitsuhiko/flask/wiki/Large-app-how-to>
* <htt... |
Beautiful Soup findAll doen't find them all | 16,322,862 | 8 | 2013-05-01T17:07:33Z | 16,323,809 | 28 | 2013-05-01T18:09:16Z | [
"python",
"python-3.x",
"beautifulsoup",
"findall"
] | i'm trying to parse a website and get some info with BeautifulSoup.findAll but it doesn't find them all.. I'm using python3
the code is this
```
#!/usr/bin/python3
from bs4 import BeautifulSoup
from urllib.request import urlopen
page = urlopen ("http://mangafox.me/directory/")
# print (page.read ())
soup = Beautifu... | Different HTML parsers deal differently with broken HTML. That page serves broken HTML, and the `lxml` parser is not dealing very well with it:
```
>>> import requests
>>> from bs4 import BeautifulSoup
>>> r = requests.get('http://mangafox.me/directory/')
>>> soup = BeautifulSoup(r.text, 'lxml')
>>> len(soup.findAll('... |
Simultaneous .replace functionality | 16,322,898 | 6 | 2013-05-01T17:10:05Z | 16,322,936 | 9 | 2013-05-01T17:12:06Z | [
"python",
"string",
"replace",
"python-3.3",
"simultaneous"
] | I have already converted user input of DNA code `(A,T,G,C)` into RNA code`(A,U,G,C)`. This was fairly easy
```
RNA_Code=DNA_Code.replace('T','U')
```
Now the next thing I need to do is convert the RNA\_Code into it's compliment strand. This means I need to replace A with U, U with A, G with C and C with G, but all si... | Use a translation table:
```
RNA_compliment = {
ord('A'): 'U', ord('U'): 'A',
ord('G'): 'C', ord('C'): 'G'}
RNA_Code.translate(RNA_compliment)
```
The [`str.translate()` method](http://docs.python.org/3/library/stdtypes.html#str.translate) takes a mapping from codepoint (a number) to replacement character. T... |
Try - Except python | 16,323,002 | 2 | 2013-05-01T17:17:03Z | 16,323,051 | 7 | 2013-05-01T17:20:05Z | [
"python"
] | I am currently trying to parse an HTML page. While doing so, I have to perform
1. Search a specific string and do some steps. (if this operation fails, go to step b)
2. Search a specific string using a different code and do some steps. (if this operation fails, go to step 3)
3. Search a specific string using a differe... | The structure would be
```
try:
step 1
except:
try:
step 2
except:
step 3
```
Two notes:
First, although using exceptions is a very "pythonic" way to accomplish tasks, you should check, if you couldn't use a nested `if`/`elif`/`else` structure.
Second, there is a [HTML Parser](http://doc... |
IPython.parallel not using multicore? | 16,323,743 | 11 | 2013-05-01T18:04:54Z | 16,330,197 | 15 | 2013-05-02T04:09:53Z | [
"python",
"mapreduce",
"ipython",
"ipython-notebook",
"ipython-parallel"
] | I am experimenting with `IPython.parallel` and just want to launch several shell command on different engines.
I have the following Notebook:
**Cell 0:**
```
from IPython.parallel import Client
client = Client()
print len(client)
5
```
And launch the commands:
**Cell 1:**
```
%%px --targets 0 --noblock
!python se... | Summary of the chat discussion:
[CPU affinity](http://en.wikipedia.org/wiki/CPU_affinity) is a mechanism for pinning a process to a particular CPU core,
and the issue here is that sometimes importing numpy can end up pinning Python processes to CPU 0,
as a result of linking against particular BLAS libraries. You can u... |
Python Alarm Clock | 16,325,039 | 4 | 2013-05-01T19:31:25Z | 16,635,346 | 7 | 2013-05-19T13:50:26Z | [
"python",
"nonblocking"
] | I've made this little alarm clock with a little help from my brother. I tried it last night, with out the `nonBlockingRawInput` and that worked fine, but with the `nonBlockingRawInput` it didn't work. Today I've tried it but neither of them work! I will post the code with the `nonBlockingRawInput` and the "non" file. I... | I've been looking at your code for a while now. As far as I can understand you want to be able to run an alarm while also being able to type "stop" in the shell to end the program, to this end you can make the alarm a thread. The thread will check if its time to say "ALARM!" and open the mp3. If the user hasn't typed s... |
Can't connect to local MySQL server through socket '/tmp/mysql.sock | 16,325,607 | 66 | 2013-05-01T20:06:17Z | 16,399,444 | 7 | 2013-05-06T13:06:53Z | [
"python",
"mysql",
"django"
] | When I attempted to connect to a local MySQL server during my test suite, it
fails with the error:
```
OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
```
However, I'm able to at all times, connect to MySQL by running the command line
`mysql` program. A `ps aux | g... | Check number of open files for the mysql process using lsof command.
Increase the open files limit and run again. |
Can't connect to local MySQL server through socket '/tmp/mysql.sock | 16,325,607 | 66 | 2013-05-01T20:06:17Z | 16,402,615 | 35 | 2013-05-06T16:04:38Z | [
"python",
"mysql",
"django"
] | When I attempted to connect to a local MySQL server during my test suite, it
fails with the error:
```
OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
```
However, I'm able to at all times, connect to MySQL by running the command line
`mysql` program. A `ps aux | g... | The relevant section of the MySQL manual is [here](http://dev.mysql.com/doc/refman/5.1/en/can-not-connect-to-server.html). I'd start by going through the debugging steps listed there.
Also, remember that localhost and 127.0.0.1 are not the same thing in this context:
* If host is set to `localhost`, then a socket or ... |
Can't connect to local MySQL server through socket '/tmp/mysql.sock | 16,325,607 | 66 | 2013-05-01T20:06:17Z | 16,466,698 | 19 | 2013-05-09T16:35:41Z | [
"python",
"mysql",
"django"
] | When I attempted to connect to a local MySQL server during my test suite, it
fails with the error:
```
OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
```
However, I'm able to at all times, connect to MySQL by running the command line
`mysql` program. A `ps aux | g... | I've seen this happen at my shop when my devs have a stack manager like MAMP installed that comes preconfigured with MySQL installed in a non standard place.
at your terminal run
```
mysql_config --socket
```
that will give you your path to the sock file. take that path and use it in your DATABASES HOST paramater.
... |
Can't connect to local MySQL server through socket '/tmp/mysql.sock | 16,325,607 | 66 | 2013-05-01T20:06:17Z | 18,842,834 | 101 | 2013-09-17T06:36:49Z | [
"python",
"mysql",
"django"
] | When I attempted to connect to a local MySQL server during my test suite, it
fails with the error:
```
OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
```
However, I'm able to at all times, connect to MySQL by running the command line
`mysql` program. A `ps aux | g... | ```
sudo /usr/local/mysql/support-files/mysql.server start
```
This worked for me. However, if this doesnt work then make sure that mysqld is running and try connecting. |
Can't connect to local MySQL server through socket '/tmp/mysql.sock | 16,325,607 | 66 | 2013-05-01T20:06:17Z | 30,359,831 | 22 | 2015-05-20T20:32:13Z | [
"python",
"mysql",
"django"
] | When I attempted to connect to a local MySQL server during my test suite, it
fails with the error:
```
OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
```
However, I'm able to at all times, connect to MySQL by running the command line
`mysql` program. A `ps aux | g... | For me the problem was I wasn't running mysql server.
Run server first and then execute `mysql`.
```
$ mysql.server start
$ mysql -h localhost -u root -p
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.