title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,522,170
10
2013-05-13T12:34:09Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
This returns `True` if one and only one of the three conditions is `True`. Probably what you wanted in your example code. ``` if sum(1 for x in (a,b,c) if x) == 1: ```
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,522,194
205
2013-05-13T12:35:35Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
If you mean a minimal form, go with this: ``` if (not a or not b or not c) and (a or b or c): ``` Which translates the title of your question. UPDATE: as correctly said by Volatility and Supr, you can apply De Morgan's law and obtain equivalent: ``` if (a or b or c) and not (a and b and c): ``` My advice is to use...
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,522,290
32
2013-05-13T12:39:31Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
I'd go for: ``` conds = iter([a, b, c]) if any(conds) and not any(conds): # okay... ``` I think this should short-circuit fairly efficiently **Explanation** By making `conds` an iterator, the first use of `any` will short circuit and leave the iterator pointing to the next element if any item is true; otherwise...
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,522,608
9
2013-05-13T12:55:56Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
What about: (unique condition) ``` if (bool(a) + bool(b) + bool(c) == 1): ``` Notice, if you allow two conditions too you could do that ``` if (bool(a) + bool(b) + bool(c) in [1,2]): ```
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,524,600
109
2013-05-13T14:31:05Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
This question already had many highly upvoted answers and an accepted answer, but all of them so far were distracted by various ways to express the boolean problem and missed a crucial point: > I have a python script that can receive either zero or three command > line arguments. (Either it runs on default behavior or...
Python syntax for "if a or b or c but not all of them"
16,522,111
111
2013-05-13T12:30:20Z
16,528,977
21
2013-05-13T18:45:19Z
[ "python", "if-statement" ]
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: ``` if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ``` ?
The English sentence: > “if a or b or c but not all of them” Translates to this logic: ``` (a or b or c) and not (a and b and c) ``` The word "but" usually implies a conjunction, in other words "and". Furthermore, "all of them" translates to a conjunction of conditions: this condition, **and** that condition, *...
reading text file back into a dictionary using json.loads
16,522,278
3
2013-05-13T12:39:01Z
16,522,299
8
2013-05-13T12:39:51Z
[ "python", "json" ]
I piped the output of my Python script which accesses live twitter tweets to a file output.txt using: ``` $python scriptTweet.py > output.txt ``` Originally, the output returned by the script was a dictionary which got written to a text file. Now i want to use the output.txt file to access tweets stored in it. But w...
`'tweetfile.read()'` is a string as you see it. You want to call this function: ``` with open("output.txt") as tweetfile: pyresponse = json.loads(tweetfile.read()) ``` or read it directly using `json.load` and let `json` `read` on the `tweetfile` itself: ``` with open("output.txt") as tweetfile: pyresponse =...
Concatenate elements of a list
16,522,362
4
2013-05-13T12:43:13Z
16,522,369
11
2013-05-13T12:43:38Z
[ "python", "string", "concatenation" ]
I have a list like `l=['a', 'b', 'c']` I want a String like 'abc'. So in fact the result is `l[0]+l[1]+l[2]`, which can also be writte as ``` s = '' for i in l: s += i ``` Is there any way to do this more elegantly?
Use [`str.join()`](http://docs.python.org/2/library/stdtypes.html#str.join): ``` s = ''.join(l) ``` The string on which you call this is used as the delimiter between the strings in `l`: ``` >>> l=['a', 'b', 'c'] >>> ''.join(l) 'abc' >>> '-'.join(l) 'a-b-c' >>> ' - spam ham and eggs - '.join(l) 'a - spam ham and egg...
Python pandas plot is a no-show
16,522,380
25
2013-05-13T12:44:17Z
16,522,626
66
2013-05-13T12:56:58Z
[ "python", "matplotlib", "pandas" ]
When I run this code ``` import pandas as pd import numpy as np def add_prop(group): births = group.births.astype(float) group['prop'] = births/births.sum() return group pieces = [] columns = ['name', 'sex', 'births'] for year in range(1880, 2012): path = 'yob%d.txt' % year frame = pd.read_csv(pa...
Put ``` import matplotlib.pyplot as plt ``` at the top, and ``` plt.show() ``` at the end.
Python pandas plot is a no-show
16,522,380
25
2013-05-13T12:44:17Z
20,334,902
12
2013-12-02T18:06:50Z
[ "python", "matplotlib", "pandas" ]
When I run this code ``` import pandas as pd import numpy as np def add_prop(group): births = group.births.astype(float) group['prop'] = births/births.sum() return group pieces = [] columns = ['name', 'sex', 'births'] for year in range(1880, 2012): path = 'yob%d.txt' % year frame = pd.read_csv(pa...
In the IPython notebook you could also use `%matplotlib inline` at the top of the notebook to automatically display the created plots in the output cells.
ffmpeg hangs when run in background
16,523,746
2
2013-05-13T13:49:30Z
16,527,559
10
2013-05-13T17:16:13Z
[ "python", "ffmpeg", "centos" ]
If I run ffmpeg as follows: ``` ffmpeg -i H264-media-4.264 4.avi ``` It works OK (i.e. 4.avi created OK). However, if I try to run it in background: ``` ffmpeg -i H264-media-4.264 4.avi & ``` it hangs! (and 4.avi never created) Any Idea? --- Note: The problem is an isolation of of similar problem in python when t...
It hangs because after a certain point it can not write to it's output pipe any longer. When you run a process it has 3 opened pipes for: stdin, stdout and stderr. A pipe has a memory buffer ( 4KB on Linux ) that can hold up to a certain amount of data and the next write operation will pause until some data is read fr...
python naming conflict with built-in function
16,523,789
11
2013-05-13T13:51:58Z
16,523,813
17
2013-05-13T13:53:23Z
[ "python", "list", "built-in" ]
I have made a mistake as below: ``` >>> list = ['a', 'b', 'c'] ``` But now I wanan use the built-in function `list()`. As you can see, that is naming conflict between listname `list` and built-in function `list()`. How can I use list as a built-in function not a list variable without restart the Python shell?
Use `__builtins__.list`, or simply delete `list` again (`del list`). No imports needed: ``` >>> __builtins__.list <type 'list'> ``` The presence of `__builtins__` is a CPython implementation detail; Jython, IronPython and PyPy may opt to not make this available. Use the [`__builtin__` module](http://docs.python.org/...
python naming conflict with built-in function
16,523,789
11
2013-05-13T13:51:58Z
16,523,985
22
2013-05-13T14:01:49Z
[ "python", "list", "built-in" ]
I have made a mistake as below: ``` >>> list = ['a', 'b', 'c'] ``` But now I wanan use the built-in function `list()`. As you can see, that is naming conflict between listname `list` and built-in function `list()`. How can I use list as a built-in function not a list variable without restart the Python shell?
*Step one*: rebind the list to a different name ``` lst = list ``` *Step two*: delete the `list` variable ``` del list ``` *Step three*: **don't do it again** --- I prefer this over `__builtins__.list` simply because it saves the typing, and you aren't still left with a variable named `list`. However, it is alway...
How to write and save html file in python?
16,523,939
9
2013-05-13T13:59:42Z
16,525,943
17
2013-05-13T15:37:57Z
[ "python" ]
This is what I know how to write and save it ``` Html_file= open"(filename","w") Html_file.write() Html_file.close ``` But how do I save to the file if I want to write a really long codes like this: ``` 1 <table border=1> 2 <tr> 3 <th>Number</th> 4 <th>Square</th> 5 </tr> 6 ...
You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to `write()`: ``` html_str = """ <table border=1> <tr> <th>Number</th> <th>Square</th> </tr> <indent> <% for i in range(10): %> <tr> <td><%...
check two dictionaries that have similar keys but different values
16,524,548
3
2013-05-13T14:28:50Z
16,524,585
11
2013-05-13T14:30:22Z
[ "python", "dictionary" ]
I have two dictionaries. dict1 and dict2. dict 2 is always of the same length but dict1 varies in length. Both dictionaries are as follows: ``` dict2 = {"name":"martin","sex":"male","age":"97","address":"blablabla"} dict1 = {"name":"falak", "sex":"female"} ``` I want to create a third dictionary that is based on bot...
Have you tried: ``` dict3 = dict(dict2, **dict1) ``` Or: ``` dict3 = dict2.copy() dict3.update(dict1) ```
While reading file on Python, I faced the error that said UnicodeDecodeError. What can I do to resolve this error?
16,528,468
6
2013-05-13T18:12:23Z
16,529,599
12
2013-05-13T19:22:57Z
[ "python", "file-io", "python-3.x" ]
This is one of my own project. This will later help benefits other people in game I am playing (AssaultCube). Its purpose is to break down the log file and make it more easier to read for users. I kept getting this issue. Anyone know how to fix this? Currently, I am not planning to write/create the file. I just want...
Try: ``` enc='utf-8' log = open('/Users/Owner/Desktop/Exodus Logs/DIRTYLOGS/serverlog_20130430_00.15.21.txt', 'r', encoding=enc) ``` if it won't work try: ``` enc='utf-16' log = open('/Users/Owner/Desktop/Exodus Logs/DIRTYLOGS/serverlog_20130430_00.15.21.txt', 'r', encoding=enc) ``` you could also try it with ...
split a list into three lists with a stepsize and a starting point
16,528,958
2
2013-05-13T18:43:51Z
16,529,023
7
2013-05-13T18:48:35Z
[ "python", "list" ]
I have a list which looks like below. ``` list = [1, 2, 3, 4, 5, 6, 7, 8, 9 .....] ``` and i want to split it into three lists which will have below values. ``` first_list = [1, 4, 7, ...] second_list = [2, 5, 8,....] third_list = [3, 6, 9, ...] ``` I do not want to split it into three equal sized chunks and want t...
Use the slice notation by changing the start value and setting a step value: ``` l[start:end:step] ``` --- ``` In [1]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9] In [2]: [l[start::3] for start in range(3)] Out[2]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]] ``` --- To assign the lists to variables: ``` first_list, second_list, third...
why can't x[:,0] = x[0] for a single row vector?
16,529,276
2
2013-05-13T19:02:35Z
16,529,417
8
2013-05-13T19:10:37Z
[ "python", "vector", "numpy" ]
I'm relatively new to python but I'm trying to understand something which seems basic. Create a vector: ``` x = np.linspace(0,2,3) Out[38]: array([ 0., 1., 2.]) ``` now why isn't x[:,0] a value argument? ``` IndexError: invalid index ``` It must be x[0]. I have a function I am calling which calculates: ``` np.s...
Perhaps you are looking for this: ``` np.sqrt(x[...,0]**2 + x[...,1]**2 + x[...,2]**2) ``` There can be any number of dimensions in place of the ellipsis `...` See also [What does the Python Ellipsis object do?](http://stackoverflow.com/q/772124/222914), and [the docs of NumPy basic slicing](http://docs.scipy.org/do...
why can't x[:,0] = x[0] for a single row vector?
16,529,276
2
2013-05-13T19:02:35Z
16,530,937
7
2013-05-13T20:52:52Z
[ "python", "vector", "numpy" ]
I'm relatively new to python but I'm trying to understand something which seems basic. Create a vector: ``` x = np.linspace(0,2,3) Out[38]: array([ 0., 1., 2.]) ``` now why isn't x[:,0] a value argument? ``` IndexError: invalid index ``` It must be x[0]. I have a function I am calling which calculates: ``` np.s...
It looks like the ellipsis as described by @JanneKarila has answered your question, but I'd like to point out how you might make your code a bit more "numpythonic". It appears you want to handle an n-dimensional array with the shape (d\_1, d\_2, ..., d\_{n-1}, 3), and compute the magnitudes of this collection of three-...
Adding water flow arrows to Matplotlib Contour Plot
16,529,892
6
2013-05-13T19:43:13Z
16,531,438
13
2013-05-13T21:28:04Z
[ "python", "matplotlib", "contour" ]
I am generating a groundwater elevation contour with Matplotlib. See below Here is what I have now; how can I add water flow arrows like the image below? ![enter image description here](http://i.stack.imgur.com/nVYBf.png) I want to add arrows to make it look like this: ![Groundwater Contour with Arrows](http://i.stac...
You'll need a recent (>= 1.2) version of matplotlib, but [`streamplot`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.streamplot) does this. You just need to take the negative gradient of your head (a.k.a. "water table" for surface aquifers) grid. As a quick example generated from random point observatio...
Python => ValueError: unsupported format character 'Y' (0x59)
16,531,116
2
2013-05-13T21:04:29Z
16,531,144
9
2013-05-13T21:06:41Z
[ "python", "mysql" ]
I don't understand the ValueError with Y. I escape with %... ``` table = town+"_history" db.execute("SELECT DATE_FORMAT(snapdate,'%%Y-%%m-%%d') AS date, SUM( population ) AS accountpopulation, count( blockid ) AS number_block FROM %s WHERE blockid =%%s GROUP BY snapdate ORDER BY snapdate DESC LIMIT 7" % table, (blocki...
You escape the `%%` but then use the string as a formatter *first*: ``` "...." % table, ``` that returns a new string with the `%%` escaped percentages replaced by single `%` characters. The MySQL database adapter (ab)uses string formatting with `%` *too*, so it'll take that output and expect to be able to fill `%s` ...
Dereferencing lists inside list in Python
16,531,580
5
2013-05-13T21:37:19Z
16,531,612
10
2013-05-13T21:40:01Z
[ "python", "list", "reference" ]
When I define a list in a "generic" way: ``` >>>a=[[]]*3 >>>a [[],[],[]] ``` and then try to append only to the second element of the outer list: ``` >>>a[1].append([0,1]) >>>a [[[0,1]], [[0,1]], [[0,1]]] ``` it appends to all elements of the outer list as can be seen above, probably due to the fact that the elemen...
You are correct, they are all references to one list. ``` [[] for _ in range(3)] ``` is a common way to create a list of independent empty lists. You can use `xrange` on Python 2.x, but it won't make a difference if the length is actually as small as in your example. Not sure how to explain *the reason* for this (th...
Static files application_readable usage
16,531,982
6
2013-05-13T22:09:09Z
16,541,092
11
2013-05-14T10:42:52Z
[ "python", "google-app-engine" ]
I've been trying to understand how the application\_readable static url handler field works. I'm using SDK version 1.7.7 and I've set this to true on an application in my dev environment, but I can't seem to actually read the file: ``` # app.yaml - url: /test static_dir: application/static/test application_readab...
# Overview It's somewhat difficult to reason about what *exactly* is going on on your system, but I can tell you what works on mine. We can speculate all day about what could be wrong, but implementing something that works and working backwards is usually more productive than guessing; it could be anything. If I were...
How to insert a datetime into a Cassandra 1.2 timestamp column
16,532,566
8
2013-05-13T23:03:28Z
16,535,830
9
2013-05-14T05:34:37Z
[ "python", "cassandra", "cql" ]
**IMPORTANT** If you are dealing with this problem today, use the new cassandra-driver from datastax (i.e. import cassandra) since it solves most of this common problems and don't use the old cql driver anymore, it is obsolete! This question is old from before the new driver was even in development and we had to use an...
I can tell you how to do it in cqlsh. Try this ``` update test set last_sent =1368438171000 where id = 'someid' ``` Equivalent long value for date time `2013-05-13 15:12:51` is `1368438171000`
Clone an image in cv2 python
16,533,078
13
2013-05-14T00:05:07Z
16,535,453
21
2013-05-14T05:01:20Z
[ "python", "opencv" ]
I'm new to opencv, here is a question, what is the python function which act the same as cv::clone() in cpp? I just try to get a rect by ``` rectImg = img[10:20, 10:20] ``` but when I draw a line on it ,I find the line appear both on img and the rectImage,so , how can I get this done?
If you use `cv2`, correct method is to use `.copy()` method in Numpy. It will create a copy of the array you need. Otherwise it will produce only a view of that object. eg: ``` In [1]: import numpy as np In [2]: x = np.arange(10*10).reshape((10,10)) In [4]: y = x[3:7,3:7].copy() In [6]: y[2,2] = 1000 In [8]: 1000...
How to convert tuple in string to tuple object?
16,533,270
3
2013-05-14T00:29:27Z
16,533,318
8
2013-05-14T00:34:55Z
[ "python", "tuples" ]
In Python 2.7, I have the following string: ``` "((1, u'Central Plant 1', u'http://egauge.com/'), (2, u'Central Plant 2', u'http://egauge2.com/'))" ``` **How can I convert this string back to tuples?** I've tried to use `split` a few times but it's very messy and makes a list instead. Desired output: ``` ((1, 'Cent...
You should use the `literal_eval` method from the `ast` module which you can read more about [**here**](http://docs.python.org/2/library/ast.html#ast.literal_eval). ``` >>> import ast >>> s = "((1, u'Central Plant 1', u'http://egauge.com/'),(2, u'Central Plant 2', u'http://egauge2.com/'))" >>> ast.literal_eval(s) ((1,...
How to handle empty (none) tuple returned from python function
16,533,672
6
2013-05-14T01:20:51Z
16,533,692
10
2013-05-14T01:22:54Z
[ "python" ]
I have a function that either returns a tuple or None. How is the Caller supposed to handle that condition? ``` def nontest(): return None x,y = nontest() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' object is not iterable ```
[EAFP](http://docs.python.org/2/glossary.html#term-eafp): ``` try: x,y = nontest() except TypeError: # do the None-thing here or pass ``` or without try-except: ``` res = nontest() if res is None: .... else: x, y = res ```
"Docstring processing tools" following PEP 257?
16,534,246
11
2013-05-14T02:37:42Z
22,723,555
13
2014-03-28T21:31:08Z
[ "python", "documentation", "docstring" ]
[PEP 257](http://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation) says: > Docstring processing tools will strip a uniform amount of indentation from the second and further lines of the docstring, equal to the minimum indentation of all non-blank lines after the first line. Any indentation in the first...
In looking for an answer to a related question, I managed to find the answer to this one. The `trim` algorithm is implemented in [`inspect.cleandoc`](http://docs.python.org/2/library/inspect.html#inspect.cleandoc), of all places.
Python: String will not convert to float
16,534,501
2
2013-05-14T03:11:11Z
16,534,526
7
2013-05-14T03:13:16Z
[ "python", "string" ]
I wrote this program up a few hours ago: ``` while True: print 'What would you like me to double?' line = raw_input('> ') if line == 'done': break else: float(line) #doesn't seem to work. Why? result = line*2 print type(line) #prints as string? ...
`float()` returns a float, not converts it. Try: ``` line = float(line) ```
Why doesn't Python always require spaces around keywords?
16,535,440
15
2013-05-14T04:59:41Z
16,535,467
12
2013-05-14T05:03:22Z
[ "python", "pypy", "cpython" ]
Why can spaces sometimes be omitted before and after key words? For example, why is the expression `2if-1e1else 1` valid? Seems to work in both CPython 2.7 and 3.3: ``` $ python2 Python 2.7.3 (default, Nov 12 2012, 09:50:25) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Type "help",...
Identifiers in python are described as: ``` identifier ::= (letter|"_") (letter | digit | "_")* ``` Hence, `2if` can't be an identifier hence if must be `2`,`if`. Similar logic applies to the rest of the expression. Basically interpreting `2if-1e1else 1` would go something like this (the full parsing would be quite ...
How to copy a list which will not be changed in function call in Python
16,536,071
4
2013-05-14T05:55:37Z
16,536,081
7
2013-05-14T05:56:26Z
[ "python", "python-2.7", "nested-lists" ]
I was working on these functions (see [this](http://stackoverflow.com/questions/16525224/how-to-breakup-a-list-of-list-in-a-given-way-in-python)): ``` def removeFromList(elementsToRemove): def closure(list): for element in elementsToRemove: if list[0] != element: return ...
Use `copy.deepcopy`: ``` from copy import deepcopy new_list = deepcopy([[1], [1, 2], [1, 2, 3]]) ``` Demo: ``` >>> lis = [[1], [1, 2], [1, 2, 3]] >>> new_lis = lis[:] # creates a shallow copy >>> [id(x)==id(y) for x,y in zip(lis,new_lis)] [True, True, True] #inner lists are sti...
Is Python dangerous for dealing with binary files?
16,536,101
7
2013-05-14T05:58:12Z
16,536,129
14
2013-05-14T06:00:01Z
[ "python", "file", "binaryfiles" ]
I read this on Python tutorial: (<http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files>) > Python on Windows makes a distinction between text and binary files; > the end-of-line characters in text files are automatically altered slightly > when data is read or written. This behind-the-scenes mo...
You just have to take care to open files on windows as binary (`open(filename, "rb")`) and not as text files. After that there is no problem using the data. Particularly the end-of-line on Windows is `'\r\n'`. And if you read a binary file as text file and write it back out, then single `'\n'` are transformed in `'\r\...
How to run ipython with pypy?
16,536,683
21
2013-05-14T06:42:24Z
16,541,602
11
2013-05-14T11:07:35Z
[ "python", "ipython", "pypy" ]
How do I use ipython on top of a pypy interpreter rather than a cpython interpreter? ipython website just says it works, but is scant on the details of how to do it.
You can create a PyPy virtualenv : ``` virtualenv -p /path/to/pypy <venv_dir> ``` Activate the virtualenv ``` source <venv_dir>/bin/activate ``` and install ipython ``` pip install ipython ```
How to validate Amazon access key and secret key is correct?
16,538,860
5
2013-05-14T08:53:53Z
16,542,039
9
2013-05-14T11:30:27Z
[ "python", "amazon-web-services", "boto" ]
I wrote a function to validate the AWS keys by just creating the ec2 connection object ``` import boto.ec2 try: ec2Conn = boto.ec2.connect_to_region(region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) return ec2Conn except boto.exception.EC2ResponseError as e: print e ``` But even if t...
The only way to verify AWS credentials is to actually use them to sign a request and see if it works. You are correct that simply creating the connection object tells you nothing because it doesn't perform a request. So you have to pick some request that should always work, won't return a huge amount of data, and doesn...
sorting list of dictionnaries in python
16,539,917
2
2013-05-14T09:44:47Z
16,539,941
9
2013-05-14T09:45:59Z
[ "python", "list" ]
i have this list : ``` L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}] ``` How to sort this list by `country` (or by `status`) elements, ASC/DESC.
Use `list.sort()` to sort the list in-place or `sorted` to get a new list: ``` >>> L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}] >>> L.sort(key= lambda x:x['country']) >>> L [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status...
sorting list of dictionnaries in python
16,539,917
2
2013-05-14T09:44:47Z
16,539,942
7
2013-05-14T09:45:59Z
[ "python", "list" ]
i have this list : ``` L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}] ``` How to sort this list by `country` (or by `status`) elements, ASC/DESC.
``` >>> from operator import itemgetter >>> L = [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}] >>> sorted(L, key=itemgetter('country')) [{'status': 1, 'country': 'France'}, {'status': 1, 'country': 'canada'}, {'status': 1, 'country': 'usa'}] >>> sorted(L, key=i...
How do I put a constraint on SciPy curve fit?
16,541,171
12
2013-05-14T10:46:45Z
16,632,712
15
2013-05-19T08:24:51Z
[ "python", "optimization", "scipy", "curve-fitting" ]
I'm trying to fit the distribution of some experimental values with a custom probability density function. Obviously, the integral of the resulting function should always be equal to 1, but the results of simple scipy.optimize.curve\_fit(function, dataBincenters, dataCounts) never satisfy this condition. What is the be...
You can define your own residuals function, including a penalization parameter, like detailed in the code below, where it is known beforehand that the integral along the interval must be `2.`. If you test without the penalization you will see that what your are getting is the conventional `curve_fit`: ![enter image de...
Perform a reverse cumulative sum on a numpy array
16,541,618
11
2013-05-14T11:08:21Z
16,541,726
19
2013-05-14T11:14:13Z
[ "python", "arrays", "numpy", "cumsum" ]
Can anyone recommend a way to do a reverse cumulative sum on a numpy array? Where 'reverse cumulative sum' is defined as below (I welcome any corrections on the name for this procedure): if ``` x = np.array([0,1,2,3,4]) ``` then ``` np.cumsum(x) ``` gives ``` array([0,1,3,6,10]) ``` However, I would like to get...
This does it: ``` np.cumsum(x[::-1])[::-1] ```
How to reuse / clone an sqlalchemy query
16,543,573
2
2013-05-14T12:46:41Z
16,553,503
14
2013-05-14T21:56:06Z
[ "python", "caching", "sqlalchemy" ]
It seems to me like going through the whole process of creating the expression tree and then creating a query from it again is a wasted time when using sqlalchemy. Apart from an occasional dynamic query, almost everything will be exactly the same during the whole life of an application (apart from the parameters of cou...
> It seems to me like going through the whole process of creating the expression tree and then creating a query from it again is a wasted time when using sqlalchemy. Do you have any estimates on how much time is wasted, compared to the rest of the application? Profiling here is extremely important before making your p...
Using OR in Python for a yes/no?
16,544,393
2
2013-05-14T13:21:59Z
16,544,421
8
2013-05-14T13:23:29Z
[ "python" ]
I'm wanting to have a "y/n" in Python, which i've successfully done, but I want the user to be able to input a "y" or a "Y" and it accepts both. Here's a short if statement ``` if yn == "y": break ``` I'm wanting to make it be something like this ``` if yn == "y" || "Y": break ``` But "||" is the OR operat...
You're looking for ``` if yn in ("y", "Y"): ``` Or better: ``` if yn.lower() == 'y': ```
Using OR in Python for a yes/no?
16,544,393
2
2013-05-14T13:21:59Z
16,544,444
7
2013-05-14T13:24:52Z
[ "python" ]
I'm wanting to have a "y/n" in Python, which i've successfully done, but I want the user to be able to input a "y" or a "Y" and it accepts both. Here's a short if statement ``` if yn == "y": break ``` I'm wanting to make it be something like this ``` if yn == "y" || "Y": break ``` But "||" is the OR operat...
choose: ``` if yn in ["y","Y"]: break if yn.lower() == "y": break ```
why there are two process when i run python manage.py runserver
16,546,176
9
2013-05-14T14:41:27Z
16,546,382
15
2013-05-14T14:50:33Z
[ "python", "django", "osx", "process" ]
``` wenzhixue 80384 0.4 1.1 2464788 22584 s001 S+ 10:37AM 0:01.06 /usr/bin/python manage.py runserver 0.0.0.0:8000 wenzhixue 80383 0.0 0.8 2451208 17300 s001 S+ 10:37AM 0:00.62 python manage.py runserver 0.0.0.0:8000 ``` Every time when I run python manage.py runserver, it brings up two p...
Maybe because of the autoreload option Try to run it with [--noreload](https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-option---noreload) ``` django-admin.py runserver --noreload ```
Can't get django urls to work
16,547,846
3
2013-05-14T16:04:47Z
16,547,875
11
2013-05-14T16:06:09Z
[ "python", "django", "django-urls" ]
I've got a simple django setup in which I have one app called '*lists*'. I now want `http://127.0.0.1:8000/lists` to show this app. So I changed my main urls.py to the following: ``` from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', ...
You're missing the empty string at the start of your `patterns` in lists `urls.py`. Try this: ``` urlpatterns = patterns('', url(r'^$', views.index, name='index') ) ``` The blank string is a [view prefix](https://docs.djangoproject.com/en/dev/ref/urls/#django.conf.urls.patterns) that you can use to assist with t...
Adding two tuples elementwise
16,548,584
3
2013-05-14T16:44:35Z
16,548,738
7
2013-05-14T16:54:52Z
[ "python", "tuples" ]
I was just wondering if there was an especially pythonic way of adding two tuples elementwise? So far (a and b are tuples), I have ``` map(sum, zip(a, b)) ``` My expected output would be: ``` (a[0] + b[0], a[1] + b[1], ...) ``` And a possible weighing would be to give a 0.5 weight and b 0.5 weight, or so on. (I'm ...
Zip them, then sum each tuple. ``` [sum(x) for x in zip(a,b)] ``` **EDIT :** Here's a better, albeit more complex version that allows for weighting. ``` from itertools import starmap, islice, izip a = [1, 2, 3] b = [3, 4, 5] w = [0.5, 1.5] # weights => a*0.5 + b*1.5 products = [m for m in starmap(lambda i,j:i*j, [...
Python 3: How to specify stdin encoding
16,549,332
13
2013-05-14T17:30:58Z
16,549,381
19
2013-05-14T17:33:34Z
[ "python", "python-3.x", "input", "unicode", "stdin" ]
While porting code from Python 2 to Python 3, I run into this problem when reading UTF-8 text from standard input. In Python 2, this works fine: ``` for line in sys.stdin: ... ``` But Python 3 expects ASCII from *sys.stdin*, and if there are non-ASCII characters in the input, I get the error: > UnicodeDecodeErro...
Python 3 does *not* expect ASCII from `sys.stdin`. It'll open `stdin` in text mode and make an educated guess as to what encoding is used. That guess may come down to `ASCII`, but that is not a given. See the [`sys.stdin` documentation](http://docs.python.org/3/library/sys.html#sys.stdin) on how the codec is selected. ...
Is it possible to include command line options in the python shebang?
16,549,357
7
2013-05-14T17:32:16Z
16,549,517
8
2013-05-14T17:42:33Z
[ "python", "linux", "command-line" ]
I have the canonical shebang at the top of my python scripts. ``` #!/usr/bin/env python ``` However, I still often want to export unbuffered output to a log file when I run my scripts, so I end up calling: ``` $ python -u myscript.py &> myscript.out & ``` Can I embed the -u option in the shebang like so... ``` #!/...
You can have arguments on the shebang line, but most operating systems have a very small limit on the number of arguments. POSIX only requires that one argument be supported, and this is common, including Linux. Since you're using the `/usr/bin/env` command, you're already using up that one argument with `python`, so ...
Django nested URLs
16,550,568
3
2013-05-14T18:47:29Z
16,550,765
10
2013-05-14T18:57:51Z
[ "python", "django", "django-urls" ]
How do I nest url calls in django? For example, if I have two models defined as ``` class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() created = models.DateTimeField(auto_now_add=True, editable=False) def __unicode__(self): return self.title @prop...
I think is probably because you're finishing the regex with the dollar sign `$`. Try this line without the dollar sign: ``` ... url(r'^(?P<pk>[0-9]+)/comments/', include('comment.urls')), ... ``` Hope it helps!
delete items from a set while iterating over it
16,551,334
13
2013-05-14T19:30:09Z
16,551,546
9
2013-05-14T19:42:57Z
[ "python", "python-2.7", "set" ]
I have a set `myset`, and I have a function which iterates over it to perform some operation on its items and this operation ultimately deletes the item from the set. Obviously, I cannot do it while still iterating over the original set. I can, however, do this: ``` mylist = list(myset) for item in mylist: # do s...
First, using a set, as Zero Piraeus told us, you can ``` myset = set([3,4,5,6,2]) while myset: myset.pop() print myset ``` I added a print method giving these outputs ``` >>> set([3, 4, 5, 6]) set([4, 5, 6]) set([5, 6]) set([6]) set([]) ``` If you want to stick to your choice for a list, i suggest you deep...
Using pip in windows
16,551,998
4
2013-05-14T20:11:48Z
16,552,470
12
2013-05-14T20:42:17Z
[ "python", "windows", "pip" ]
I installed [distribute](http://www.lfd.uci.edu/~gohlke/pythonlibs/#distribute) and [pip](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip) using the links I have just given. I also installed the [Microsoft Visual C++ 2008 redistributable package](http://www.microsoft.com/download/en/details.aspx?id=29). However when I ...
Installing the Microsoft Visual C++ 2008 Redistributable Package is not sufficient to compile packages. You need to install a *compiler*, not just the support files. There are three ways to do this: 1. Install Visual C++. 2. Use mingw's port of gcc instead of Visual C++. 3. Use cygwin's port of gcc instead of either,...
Python OrderedDict iteration
16,553,506
25
2013-05-14T21:56:16Z
16,553,551
30
2013-05-14T22:00:11Z
[ "python", "ordereddictionary" ]
Why does my python OrderedDict get initialized 'out of order'? The solution here is less intriguing than the explanation. There's something here I just don't get, and perhaps an expanation would help others as well as me. ``` >>> from collections import OrderedDict >>> spam = OrderedDict(s = (1, 2), p = (3, 4), a = ...
From [the docs](http://docs.python.org/3/library/collections.html#ordereddict-objects): > The OrderedDict constructor and `update()` method both accept keyword arguments, but their order is lost because Python’s function call semantics pass-in keyword arguments using a regular unordered dictionary. So initializatio...
Python OrderedDict iteration
16,553,506
25
2013-05-14T21:56:16Z
16,554,551
17
2013-05-14T23:45:59Z
[ "python", "ordereddictionary" ]
Why does my python OrderedDict get initialized 'out of order'? The solution here is less intriguing than the explanation. There's something here I just don't get, and perhaps an expanation would help others as well as me. ``` >>> from collections import OrderedDict >>> spam = OrderedDict(s = (1, 2), p = (3, 4), a = ...
@Chris Krycho gave a good explanation of why things fail. If you look at the repr() of an OrderedDict you get a hint at how to impart order from the beginning: You need to use a list of (key, value) pairs to preserve the order of the keys given by the list. Here's one I did earlier: ``` >>> from collections import O...
How can I slow down a loop in Python?
16,555,120
6
2013-05-15T00:58:09Z
16,555,131
11
2013-05-15T00:59:32Z
[ "python" ]
If I have a list l: ``` l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` Is there a way to control the following *for* loop so that the next element in the list is only printed one second after the previous? ``` for i in l: print i ``` In other words, is there a way to elegantly slow down a loop in Python?
You can use `time.sleep` ``` import time for i in l: print i time.sleep(1) ```
How can I slow down a loop in Python?
16,555,120
6
2013-05-15T00:58:09Z
16,555,184
8
2013-05-15T01:07:04Z
[ "python" ]
If I have a list l: ``` l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` Is there a way to control the following *for* loop so that the next element in the list is only printed one second after the previous? ``` for i in l: print i ``` In other words, is there a way to elegantly slow down a loop in Python?
If you use `time.sleep(1)`, your loops will run a little over a second since the looping and printing also takes some time. A better way is to sleep for the remainder of the second. You can calculate that by using `-time.time()%1` ``` >>> import time >>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for i in L: ... time....
How to convert string to dictionary, and count the number of each word
16,557,900
3
2013-05-15T06:01:04Z
16,557,907
11
2013-05-15T06:01:52Z
[ "python", "string", "dictionary", "python-3.x" ]
I am just wondering how i would convert a string, such as "hello there hi there", and turn it into a dictionary, then using this dictionary, i want to count the number of each word in the dictionary, and return it in alphabetic order. So in this case it would return: ``` [('hello', 1), ('hi', 1), ('there', 2)] ``` an...
``` >>> from collections import Counter >>> text = "hello there hi there" >>> sorted(Counter(text.split()).items()) [('hello', 1), ('hi', 1), ('there', 2)] ``` > [`class collections.Counter([iterable-or-mapping])`](http://docs.python.org/2.7/library/collections.html#collections.Counter) > > A `Counter` is a `dict` sub...
How to print the character from a variable with unicode string?
16,559,056
3
2013-05-15T07:20:55Z
16,559,118
8
2013-05-15T07:24:16Z
[ "python" ]
``` print u'\u0D05' a='\u0D05' print a ``` print a gives \u0D05 as out put but I need the character it represents as output,which is à´
The `\u` escape is not meaningful inside a non-unicode string. You need to do `a = u'\u0D05'`. If you're saying you're getting the string from somewhere else and need to interpret unicode escapes in it, then do `print a.decode('unicode-escape')`
Invalid syntax python starred expressions
16,563,623
8
2013-05-15T11:17:02Z
16,563,646
8
2013-05-15T11:18:09Z
[ "python", "iterable-unpacking" ]
I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet ``` >>> record = ('Dave','[email protected]','773-555-1212','847-555-1212') >>> name,email,*phone-numbers=record SyntaxError: invalid syntax >>> ``` Please e...
This new syntax was [introduced in Python 3](https://docs.python.org/3.0/whatsnew/3.0.html#new-syntax). So, it'll raise error in Python 2. Related PEP: [PEP 3132 -- Extended Iterable Unpacking](https://www.python.org/dev/peps/pep-3132/) ``` name, email, *phone_numbers = user_record ``` Python 3: ``` >>> a, b, *c = ...
Invalid syntax python starred expressions
16,563,623
8
2013-05-15T11:17:02Z
16,563,648
12
2013-05-15T11:18:17Z
[ "python", "iterable-unpacking" ]
I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet ``` >>> record = ('Dave','[email protected]','773-555-1212','847-555-1212') >>> name,email,*phone-numbers=record SyntaxError: invalid syntax >>> ``` Please e...
You are using Python 3 specific syntax in Python 2. The `*` syntax for extended iterable unpacking in assignments is not available in Python 2. See [Python 3.0, new syntax](http://docs.python.org/3/whatsnew/3.0.html#new-syntax) and [PEP 3132](http://www.python.org/dev/peps/pep-3132/). Use a function with `*` splat a...
Invalid syntax python starred expressions
16,563,623
8
2013-05-15T11:17:02Z
16,563,675
7
2013-05-15T11:20:11Z
[ "python", "iterable-unpacking" ]
I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet ``` >>> record = ('Dave','[email protected]','773-555-1212','847-555-1212') >>> name,email,*phone-numbers=record SyntaxError: invalid syntax >>> ``` Please e...
That functionality is only available in Python 3, an alternative is: ``` name, email, phone_numbers = record[0], record[1], record[2:] ``` Or something like: ``` >>> def f(name, email, *phone_numbers): return name, email, phone_numbers >>> f(*record) ('Dave', '[email protected]', ('773-555-1212', '847-555-12...
Url decode UTF-8 in Python
16,566,069
96
2013-05-15T13:16:54Z
16,566,128
156
2013-05-15T13:19:03Z
[ "python", "encoding", "python-2.7", "utf-8", "urldecode" ]
I have spent plenty of time as far as I am newbie in Python. How could I ever decode such a URL: ``` example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0 ``` to this one in python 2.7: `example.com?title==правовая+защита` `url=urllib.unquote(url.enco...
The data is UTF-8 encoded bytes escaped with URL quoting, so you want to **decode**: ``` url=urllib.unquote(url).decode('utf8') ``` Demo: ``` >>> import urllib >>> url='example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0' >>> urllib.unquote(url).decode('utf8') u'...
Url decode UTF-8 in Python
16,566,069
96
2013-05-15T13:16:54Z
32,451,970
38
2015-09-08T07:42:15Z
[ "python", "encoding", "python-2.7", "utf-8", "urldecode" ]
I have spent plenty of time as far as I am newbie in Python. How could I ever decode such a URL: ``` example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0 ``` to this one in python 2.7: `example.com?title==правовая+защита` `url=urllib.unquote(url.enco...
If you are using Python 3 ``` >>> from urllib import parse >>> parse.unquote("""example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0""") 'example.com?title=правовая+защита' ```
Remove all line breaks from a long string of text
16,566,268
46
2013-05-15T13:25:01Z
16,566,351
12
2013-05-15T13:28:10Z
[ "python" ]
Basically, I'm asking the user to input a string of text into the console, but the string is very long and includes many line breaks. How would I take the user's string and delete all line breaks to make it a single line of text. My method for acquiring the string is very simple. ``` string = raw_input("Please enter s...
You can try using string replace: ``` string = string.replace('\n', '') ```
Remove all line breaks from a long string of text
16,566,268
46
2013-05-15T13:25:01Z
16,566,356
77
2013-05-15T13:28:30Z
[ "python" ]
Basically, I'm asking the user to input a string of text into the console, but the string is very long and includes many line breaks. How would I take the user's string and delete all line breaks to make it a single line of text. My method for acquiring the string is very simple. ``` string = raw_input("Please enter s...
How do you enter line breaks with `raw_input`? But, once you have a string with some characters in it you want to get rid of, just `replace` them. ``` >>> str = raw_input('please enter string: ') please enter string: hello world, how do i enter line breaks? >>> # pressing enter didn't work... ... >>> str 'hello world,...
Node size dependent on the node degree on NetworkX
16,566,871
6
2013-05-15T13:49:20Z
16,567,881
13
2013-05-15T14:31:07Z
[ "python", "python-2.7", "social-networking", "networkx" ]
I imported my Facebook data onto my computer in the form of a .json file. The data is in the format: ``` {"nodes":[{"name":"Alan"},{"name":"Bob"}],"links":[{"source":0,"target:1"}]} ``` Then, I use this function: ``` def parse_graph(filename): """ Returns networkx graph object of facebook social network in json form...
nx.degree(p) returns a dict while the [node\_size keywod argument](http://networkx.github.io/documentation/latest/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html) needs a scalar or an array of sizes. You can use the dict nx.degree returns like this: ``` import networkx as nx import matplotlib.pyplot a...
How can I train a Genetic Programming algorithm onto a variable sequence of descriptors?
16,566,930
20
2013-05-15T13:51:38Z
16,656,886
9
2013-05-20T19:27:03Z
[ "python", "genetic-programming" ]
I am currently trying to design a Genetic Programming algorithm that analyses a **sequence of characters** and **assigns a value to those characters**. Below I have made up an example set. Every line represents a data point. The values that are trained are real-valued. Example: For the word `ABCDE` the algorithm should...
Since you have not a fitness function, you will need to treat the genetic algorithm as it was a classifier. So you will need to come up with a way to evaluate a single chromosome. As others suggested you, this is a pure classification problem, not an optimization one, but, if you still want to go ahead with GA, here yo...
When and how to use Python's RLock
16,567,958
21
2013-05-15T14:34:55Z
16,568,426
22
2013-05-15T14:56:04Z
[ "python", "python-2.7", "locking" ]
Reading through the Python docs I came across `RLock`. Can someone explain to me (with example) a scenario in which [`RLock`](http://docs.python.org/2/library/threading.html#rlock-objects) would be preferred to [`Lock`](http://docs.python.org/2/library/threading.html#lock-objects)? With particular reference to: * `R...
This is one example where I see the use: **Useful when** 1. you want to have threadsave access from outside the class and use the same methods from inside the class: ``` class X: def __init__(self): self.a = 1 self.b = 2 self.lock = threading.RLock() def changeA(...
Python Nested List Comprehension with two Lists
16,568,056
9
2013-05-15T14:39:48Z
16,568,145
18
2013-05-15T14:44:01Z
[ "python", "nested", "list-comprehension" ]
I understand how the simple list comprehension works eg.: ``` [x*2 for x in range(5)] # returns [0,2,4,6,8] ``` and also I understand how the nested list comprehesion works: ``` w_list = ["i_have_a_doubt", "with_the","nested_lists_comprehensions"] # returns the list of strings without underscore and capitalized pri...
The reason it has 9 numbers is because python treats ``` [x + y for x in l2 for y in l1 ] ``` similarly to ``` for x in l2: for y in l1: x + y ``` ie, it is a nested loop
For loop - like Python range function
16,570,091
10
2013-05-15T16:13:50Z
16,570,113
7
2013-05-15T16:15:17Z
[ "java", "python", "function", "for-loop" ]
I was wondering if in Java there is a function like the python range function. ``` range(4) ``` and it would return ``` [0,1,2,3] ``` This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?
Um... `for (int i = 0; i < k; i++)`? You don't have to write enhanced for loops all day, you know, although they are cool... And just for the sake of argument: `for (int i : range(k))` char count: 22 `for (int i = 0; i < k; i++)` char count: 27 Discounting the implementation of `range`, it is pseudo even.
For loop - like Python range function
16,570,091
10
2013-05-15T16:13:50Z
16,570,171
10
2013-05-15T16:18:06Z
[ "java", "python", "function", "for-loop" ]
I was wondering if in Java there is a function like the python range function. ``` range(4) ``` and it would return ``` [0,1,2,3] ``` This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?
Use Apache Commons Lang ``` new IntRange(0, 3).toArray(); ``` I wouldn't normally advocate introducing external libraries for something so simple, but Apache Commons are so widely used that you probably already have it in your project! Edit: I know its not necessarily as simple or fast as a for loop, but its a nice ...
For loop - like Python range function
16,570,091
10
2013-05-15T16:13:50Z
16,570,509
15
2013-05-15T16:36:18Z
[ "java", "python", "function", "for-loop" ]
I was wondering if in Java there is a function like the python range function. ``` range(4) ``` and it would return ``` [0,1,2,3] ``` This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?
Without an external library, you can do the following. It will consume significantly less memory for big ranges than the current accepted answer, as there is no array created. Have a class like this: ``` class Range implements Iterable<Integer> { private int limit; public Range(int limit) { this.lim...
For loop - like Python range function
16,570,091
10
2013-05-15T16:13:50Z
31,867,991
9
2015-08-07T00:48:13Z
[ "java", "python", "function", "for-loop" ]
I was wondering if in Java there is a function like the python range function. ``` range(4) ``` and it would return ``` [0,1,2,3] ``` This was an easy way to make for enhanced loops. It would be great to do this in Java because it would make for loops a lot easier. Is this possible?
Java 8 has added [IntStream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html) (similar to apache commons IntRange), so you don't need external lib now. ``` IntStream.range(0, 3).forEachOrdered(n -> { //work on n here }); ``` `forEach` can be used in place of `forEachOrdered` too if order...
Optimizing K (ideal # of clusters) Using PyCluster
16,570,573
2
2013-05-15T16:39:18Z
16,574,265
7
2013-05-15T20:21:07Z
[ "python", "c", "machine-learning", "scipy", "k-means" ]
I'm using PyCluster's kMeans to cluster some data -- largely because SciPy's kMeans2() produced an insuperable error. [Mentioned here](http://stackoverflow.com/a/2224488/2058922). Anyhow the PyCluster kMeans worked well, and I am now attempting to optimize the number of kMeans clusters. PyCluster's accompanying literat...
The manual for PyCluster refers to a different optimization problem than the one you are asking about. While you ask how to determine the optimal number of clusters, the manual deals with how to find the optimal clusters given the total number of clusters. The concept to understand is that k-means, which is a type of a...
Auto indent doesn't work when using vim coding python
16,570,737
5
2013-05-15T16:47:17Z
16,570,836
7
2013-05-15T16:52:44Z
[ "python", "vim", "indentation" ]
I want to use vim to write python code but there is a problem on auto indention. First I downloaded the latest python.vim from <http://www.vim.org/scripts/script.php?script_id=790> and putted it in the correct dir. Then I edited my vimrc. ``` syntax on set nu set tabstop=4 set softtabstop=4 set shiftwidth=4 "set cinde...
I have this line in my vimrc for long time, don't know if there is better way nowadays. but you could at least give it a try. ``` set cindent autocmd FileType python setlocal foldmethod=indent smartindent shiftwidth=4 ts=4 et cinwords=if,elif,else,for,while,try,except,finally,def,class ``` and I have ``` filetype pl...
How to capture stdout output from a Python function call?
16,571,150
32
2013-05-15T17:13:30Z
16,571,630
70
2013-05-15T17:43:39Z
[ "python", "stdout", "capture" ]
I'm using a Python library that does something to an object ``` do_something(my_object) ``` and changes it. While doing so, it prints some statistics to stdout, and I'd like to get a grip on this information. The proper solution would be to change `do_something()` to return the relevant information, ``` out = do_som...
Try this context manager: ``` from cStringIO import StringIO import sys class Capturing(list): def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) ...
Python: print a variable in hex
16,572,008
6
2013-05-15T18:04:07Z
16,572,429
9
2013-05-15T18:26:49Z
[ "python", "string", "hex" ]
I'm trying to find a way to print a string in hex. For example I have this string which I then convert to its hex value. ``` my_string = "deadbeef" my_hex = my_string.decode('hex') ``` How can I print `my_hex` as `0xde 0xad 0xbe 0xef`? Thank you. To make my question clear... Let's say I have some data like `0x01, 0x...
You mean you have a string of *bytes* in `my_hex` which you want to print out as hex numbers, right? E.g., from your example: ``` >>> my_string = "deadbeef" >>> my_hex = my_string.decode('hex') # python 2 only >>> print my_hex Þ ­ ¾ ï ``` Here's one way to do it: ``` >>> print " ".join(hex(ord(n)) for n in my_h...
non-negative matrix factorization failing to converge
16,572,192
3
2013-05-15T18:13:57Z
16,574,535
7
2013-05-15T20:38:12Z
[ "python", "numpy", "machine-learning" ]
I'm trying to implement non-negative matrix factorization using the Kullback-Liebler divergence as a similarity measure. The algorithm is described in: <http://hebb.mit.edu/people/seung/papers/nmfconverge.pdf>. Below is my python / numpy implementation, with an example matrix to run it on. In a nutshell, the algorithm...
**How to eliminate the alternation effect:** The very last line of the Proof of Theorem 2 reads, > By reversing the roles of H and W, the update rule for W can similarly > be shown to be nonincreasing. Thus we can surmise that updating `H` can be done independently of updating `W`. That means after updating `H`: ``...
QuerySet, Object has no attribute id - Django
16,572,569
6
2013-05-15T18:34:36Z
16,572,685
10
2013-05-15T18:41:47Z
[ "python", "django", "django-models", "django-views", "django-queryset" ]
I'm trying to fetch the id of certain object in django but I keep getting the following error Exception Value: QuerySet; Object has no attribute id. my function in views.py ``` @csrf_exempt def check_question_answered(request): userID = request.POST['userID'] markerID = request.POST['markerID'] title=req...
The reason why you are getting the error is because `at` is a `QuerySet` ie: a list. You can do something like `at[0].id` or use `get` instead of `filter` to get the `at` object. Hope it helps!
QuerySet, Object has no attribute id - Django
16,572,569
6
2013-05-15T18:34:36Z
16,572,700
12
2013-05-15T18:42:20Z
[ "python", "django", "django-models", "django-views", "django-queryset" ]
I'm trying to fetch the id of certain object in django but I keep getting the following error Exception Value: QuerySet; Object has no attribute id. my function in views.py ``` @csrf_exempt def check_question_answered(request): userID = request.POST['userID'] markerID = request.POST['markerID'] title=req...
this line of code `at = AttachedInfo.objects.filter(attachedMarker=m.id, title=title)` returns a [queryset](https://docs.djangoproject.com/en/dev/ref/models/querysets//) and you are trying to access a field of it (that does not exist). what you probably need is ``` at = AttachedInfo.objects.get(attachedMarker=m.id...
Python: Sound alarm when code finishes
16,573,051
30
2013-05-15T19:04:57Z
16,573,188
12
2013-05-15T19:13:16Z
[ "python", "alarm", "audio" ]
I am in a situation where my code takes extremely long to run and I don't want to be staring at it all the time but want to know when it is done. How can I make the (Python) code sort of sound an "alarm" when it is done? I was contemplating making it play a .wav file when it reaches the end of the code... Is this eve...
This one seems to work on both Windows and Linux\* ([from this question](http://stackoverflow.com/questions/4467240/play-simple-beep-with-python-without-external-library)): ``` def beep(): print "\a" beep() ``` In Windows, can put at the end: ``` import winsound winsound.Beep(500,1000) where 500 is the frequenc...
Python: Sound alarm when code finishes
16,573,051
30
2013-05-15T19:04:57Z
16,573,339
37
2013-05-15T19:23:23Z
[ "python", "alarm", "audio" ]
I am in a situation where my code takes extremely long to run and I don't want to be staring at it all the time but want to know when it is done. How can I make the (Python) code sort of sound an "alarm" when it is done? I was contemplating making it play a .wav file when it reaches the end of the code... Is this eve...
So it depends on your system, the following will work for windows: ``` import winsound winsound.Beep(300,2000) ``` where a is the frequency and b is the duration in miliseconds this is for linux: ``` import os os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % ( a, b)) ``` where a is the du...
Python: Sound alarm when code finishes
16,573,051
30
2013-05-15T19:04:57Z
29,590,673
11
2015-04-12T14:42:46Z
[ "python", "alarm", "audio" ]
I am in a situation where my code takes extremely long to run and I don't want to be staring at it all the time but want to know when it is done. How can I make the (Python) code sort of sound an "alarm" when it is done? I was contemplating making it play a .wav file when it reaches the end of the code... Is this eve...
ubuntu speech dispatcher can be used: ``` import subprocess subprocess.call(['speech-dispatcher']) #start speech dispatcher subprocess.call(['spd-say', '"your process has finished"']) ```
Python: Sound alarm when code finishes
16,573,051
30
2013-05-15T19:04:57Z
30,220,552
7
2015-05-13T16:32:36Z
[ "python", "alarm", "audio" ]
I am in a situation where my code takes extremely long to run and I don't want to be staring at it all the time but want to know when it is done. How can I make the (Python) code sort of sound an "alarm" when it is done? I was contemplating making it play a .wav file when it reaches the end of the code... Is this eve...
``` print('\007') ``` plays the bell sound
Case Insensitive Flask-SQLAlchemy Query
16,573,095
45
2013-05-15T19:08:15Z
16,573,690
80
2013-05-15T19:44:13Z
[ "python", "flask", "flask-sqlalchemy" ]
I'm using Flask-SQLAlchemy to query from a database of users; however, while ``` user = models.User.query.filter_by(username="ganye").first() ``` will return ``` <User u'ganye'> ``` doing ``` user = models.User.query.filter_by(username="GANYE").first() ``` returns ``` None ``` I'm wondering if there's a way to ...
You can do it by using either the `lower` or `upper` functions in your filter: ``` from sqlalchemy import func user = models.User.query.filter(func.lower(User.username) == func.lower("GaNyE")).first() ``` Another option is to do searching using `ilike` instead of `like`: ``` .query.filter(Model.column.ilike("ganye")...
How to get user permissions?
16,573,174
9
2013-05-15T19:12:27Z
27,624,324
9
2014-12-23T16:31:46Z
[ "python", "django", "django-authentication" ]
I want to retrieve all permission for user as list of premission id's but: ``` user.get_all_permissions() ``` give me list of permission names. How to do it?
to get all the permissions of a given user, also the permissions associated with a group this user is part of: ``` def get_user_permissions(user): if user.is_superuser: return Permission.objects.all() return user.user_permissions.all() | Permission.objects.filter(group__user=user) ```
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
16,573,332
27
2013-05-15T19:22:44Z
16,575,064
28
2013-05-15T21:13:19Z
[ "python", "json", "api", "curl" ]
I am getting error `Expecting value: line 1 column 1 (char 0)` when trying to decode JSON. The URL I use for the API call works fine in the browser, but gives this error when done through a curl request. The following is the code I use for the curl request. The error happens at `return simplejson.loads(response_json)...
To summarize the conversation in the comments: * There is no need to use `simplejson` library, the same library is included with Python as the `json` module. * There is no need to decode a response from UTF8 to unicode, the `simplejson` / `json` `.loads()` method can handle UTF8 encoded data natively. * `pycurl` has a...
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
16,573,332
27
2013-05-15T19:22:44Z
18,460,958
13
2013-08-27T08:48:36Z
[ "python", "json", "api", "curl" ]
I am getting error `Expecting value: line 1 column 1 (char 0)` when trying to decode JSON. The URL I use for the API call works fine in the browser, but gives this error when done through a curl request. The following is the code I use for the curl request. The error happens at `return simplejson.loads(response_json)...
Check the response data-body, whether actual data is present and a data-dump appears to be well-formatted. In most cases your `json.loads`- `JSONDecodeError: Expecting value: line 1 column 1 (char 0)` error is due to : * non-JSON conforming quoting * XML/HTML output (that is, a string starting with <), or * incompati...
How to run SVN commands from a python script?
16,573,474
14
2013-05-15T19:31:47Z
16,573,550
13
2013-05-15T19:35:51Z
[ "python", "svn" ]
Basically I want to write a python script that does several things and one of them will be to run a checkout on a repository using subversion (SVN) and maybe preform a couple more of svn commands. What's the best way to do this ? This will be running as a crond script.
Try [pysvn](http://pysvn.tigris.org/docs/pysvn.html) Gives you great access as far as i've tested it. Here's some examples: <http://pysvn.tigris.org/docs/pysvn_prog_guide.html> The reason for why i'm saying as far as i've tested it is because i've moved over to Git.. but if i recall pysvn is (the only and) the best l...
How to run SVN commands from a python script?
16,573,474
14
2013-05-15T19:31:47Z
16,574,107
14
2013-05-15T20:11:46Z
[ "python", "svn" ]
Basically I want to write a python script that does several things and one of them will be to run a checkout on a repository using subversion (SVN) and maybe preform a couple more of svn commands. What's the best way to do this ? This will be running as a crond script.
Would this work? ``` p = subprocess.Popen("svn info svn://xx.xx.xx.xx/project/trunk | grep \"Revision\" | awk '{print $2}'", stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() print "Revision is", output ```
How to load .ttf file in matplotlib using mpl.rcParams?
16,574,898
5
2013-05-15T21:00:39Z
16,574,948
8
2013-05-15T21:03:54Z
[ "python", "fonts", "matplotlib" ]
I have a matplotlib script that starts ... ``` import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.font_manager as fm mpl.rcParams['xtick.labelsize']=16 ... ``` I've used the command ``` fm.findSystemFonts() ``` to get a list of the fonts on my system. I've discovered the full path to a .tt...
**Specifying a font family:** If all you know is the path to the ttf, then you can discover the font family name using the `get_name` method: ``` import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager path = '/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf' ...
Efficiently creating additional columns in a pandas DataFrame using .map()
16,575,868
14
2013-05-15T22:12:30Z
16,576,030
19
2013-05-15T22:26:35Z
[ "python", "pandas", "dataframe" ]
I am analyzing a data set that is similar in shape to the following example. I have two different types of data (*abc* data and *xyz* data): ``` abc1 abc2 abc3 xyz1 xyz2 xyz3 0 1 2 2 2 1 2 1 2 1 1 2 1 1 2 2 2 1 2 2 2 3 1 2 1 ...
You can use [`applymap`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html) with the dictionary [`get`](http://docs.python.org/2/library/stdtypes.html#dict.get) method: ``` In [11]: df[abc_columns].applymap(categories.get) Out[11]: abc1 abc2 abc3 0 Good Bad Bad 1 Bad Goo...
Python: Name instance based on variable
16,575,883
2
2013-05-15T22:13:52Z
16,575,926
7
2013-05-15T22:17:48Z
[ "python" ]
I'm quite new to Python and programming in general. I'm making a terminal based game as a practice project. The game will a series of rooms and monsters. My plan was to make monsters and rooms instances of these classes. I'm creating several of these throughout the game and many of them a created on the fly, based on ...
This is a common question from newbies, and you're right, there is a "much smarter/elegant way of doing this". You use a data structure like a dictionary to hold your instances: ``` monsters = {} monsters['Monster1'] = Monster() monsters['Monster2'] = Monster() ``` Because the keys to the dictionary are strings, ther...
Python - intersect a dict and list
16,577,499
2
2013-05-16T01:13:44Z
16,577,524
7
2013-05-16T01:16:42Z
[ "python" ]
Given the following data structures ,what is the most efficient way to find out the intersection - keys which are common to both the data structures. ``` dict1 = {'2A':'....','3A':'....','4B':.....} list1 = [......,'2A','4B'.....] Expected output = ['2A','4B'] ``` I am fine to organize the list(not dict1) into any...
As suggested by @Blckknght ``` >>> dict1.viewkeys() & list1 set(['4B', '2A']) ``` This *has* to be the fastest and most efficient way. Note that `dict.viewkeys()` is `dict.keys` in Python 3 (don't confuse this with Python 2 where `dict.keys()` returns a `list` instead)
Convert string to JSON in Python?
16,577,632
2
2013-05-16T01:31:40Z
16,577,648
13
2013-05-16T01:32:43Z
[ "python", "json", "urllib3" ]
I'm trying to convert a string, generated from an http request with urllib3. ``` Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> data = json.load(data) File "C:\Python27\Lib\json\__init__.py", line 286, in load return loads(fp.read(), AttributeError: 'str' object has no attribut...
`json.load` loads from a file-like object. You either want to use `json.loads`: ``` json.loads(data) ``` Or just use `json.load` on the request, which is a file-like object: ``` json.load(request) ``` Also, if you use the [requests](http://docs.python-requests.org/en/latest/) library, you can just do: ``` import r...
Scrollbar not stretching to fit the Text widget
16,577,718
5
2013-05-16T01:42:28Z
16,577,903
7
2013-05-16T02:09:49Z
[ "python", "tkinter", "widget", "scrollbar" ]
I was able to get the `Scrollbar` to work with a `Text` widget, but for some reason it isn't stretching to fit the text box. Does anyone know of any way to change the height of the scrollbar widget or something to that effect? ``` txt = Text(frame, height=15, width=55) scr = Scrollbar(frame) scr.config(command=txt.yv...
In your question you're using `pack`. `pack` has options to tell it to grow or shrink in either or both the x and y axis. Vertical scrollbars should normally grow/shrink in the y axis, and horizontal ones in the x axis. Text widgets should usually fill in both directions. For doing a text widget and scrollbar in a fra...
threading.Timer()
16,578,652
13
2013-05-16T03:44:48Z
16,578,710
32
2013-05-16T03:50:59Z
[ "python", "python-2.7" ]
i have to write a program in network course that is something like selective repeat but a need a timer. after search in google i found that threading.Timer can help me, i wrote a simple program just for test how threading.Timer work that was this: ``` import threading def hello(): print "hello, world" t = thread...
You just need to put the arguments to `hello` into a separate item in the function call, like this, ``` t = threading.Timer(10.0, hello, [h]) ``` This is a common approach in Python. Otherwise, when you use `Timer(10.0, hello(h))`, the result of this function call is passed to `Timer`, which is `None` since `hello` d...
Python - verifying if one list is a subset of the other
16,579,085
48
2013-05-16T04:37:02Z
16,579,133
7
2013-05-16T04:41:16Z
[ "python", "list" ]
I need to verify if a list is a subset of another - a boolean return is all I seek. Is testing equality on the smaller list after an intersection the fastest way to do this? Performance is of utmost importance given the amount of datasets that need to be compared. Adding further facts based on discussions: 1. Wi...
Assuming the items are hashable ``` >>> from collections import Counter >>> not Counter([1, 2]) - Counter([1]) False >>> not Counter([1, 2]) - Counter([1, 2]) True >>> not Counter([1, 2, 2]) - Counter([1, 2]) False ``` If you don't care about duplicate items eg. `[1, 2, 2]` and `[1, 2]` then just use: ``` >>> set([1...
Python - verifying if one list is a subset of the other
16,579,085
48
2013-05-16T04:37:02Z
16,579,295
35
2013-05-16T04:59:10Z
[ "python", "list" ]
I need to verify if a list is a subset of another - a boolean return is all I seek. Is testing equality on the smaller list after an intersection the fastest way to do this? Performance is of utmost importance given the amount of datasets that need to be compared. Adding further facts based on discussions: 1. Wi...
The performant function Python provides for this is [set.issubset](http://docs.python.org/2/library/stdtypes.html#set.issubset). It does have a few restrictions that make it unclear if it's the answer to your question, however. A list may contain items multiple times and has a specific order. A set does not. To achiev...
Python - verifying if one list is a subset of the other
16,579,085
48
2013-05-16T04:37:02Z
27,116,142
20
2014-11-24T23:29:43Z
[ "python", "list" ]
I need to verify if a list is a subset of another - a boolean return is all I seek. Is testing equality on the smaller list after an intersection the fastest way to do this? Performance is of utmost importance given the amount of datasets that need to be compared. Adding further facts based on discussions: 1. Wi...
``` >>> a = [1, 3, 5] >>> b = [1, 3, 5, 8] >>> c = [3, 5, 9] >>> set(a) < set(b) True >>> set(c) < set(b) False >>> a = ['yes', 'no', 'hmm'] >>> b = ['yes', 'no', 'hmm', 'well'] >>> c = ['sorry', 'no', 'hmm'] >>> >>> set(a)<set(b) True >>> set(c)<set(b) False ```
Django: manage.py does not print stack trace for errors
16,581,572
19
2013-05-16T07:38:10Z
16,581,631
34
2013-05-16T07:41:50Z
[ "python", "django", "debugging", "stack-trace" ]
In Django, most of the time when I run `manage.py` and it encounters an error, I don't get the full stack trace for the error, just the text of the exception, making it very hard to debug. Example: ``` python manage.py graph_models -a -g -o my_project.png AttributeError: 'str' object has no attribute '__module__' ``` ...
Have you tried passing the `--traceback` argument? e.g: ``` python manage.py graph_models --traceback -a -g -o my_project.png ```
python: how to sort lists alphabetically with respect to capitalized letters
16,581,695
6
2013-05-16T07:44:55Z
16,581,759
7
2013-05-16T07:48:51Z
[ "python", "list", "sorting" ]
I'm trying to sort a list alphabetically, where capital letters should come before lower case letters. ``` l = ['a', 'b', 'B', 'A'] ``` `sorted(l)` should result in `['A','a','B','b']` I've tried these two forms, but to no avail; ``` >>> sorted(l, key=lambda s: s.lower()) ['a', 'A', 'b', 'B'] >>> sorted(l, key=str....
Create a tuple as your key instead: ``` >>> sorted(lst, key=lambda L: (L.lower(), L)) ['A', 'a', 'B', 'b'] ``` This means the sort order for lower-case doesn't change `('a', 'a')` but means the first key for upper case puts it level with the lower-case equivalent, then sorts before it: eg `('a', 'A')` < `('a', 'a')`
How to state in requirements.txt a direct github source
16,584,552
113
2013-05-16T10:06:42Z
16,584,935
107
2013-05-16T10:25:26Z
[ "python", "github", "pip", "requirements.txt" ]
I've installed a library using the command ``` pip install git+git://github.com/mozilla/elasticutils.git ``` which installs it directly from a Github repository. This works fine and I want to have that dependency in my `requirements.txt`. I've looked at other tickets like [this](http://stackoverflow.com/questions/902...
[“Editable” packages syntax](https://pip.readthedocs.org/en/1.1/requirements.html#requirements-file-format) can be used in `requirements.txt` to import packages from a variety of [VCS (git, hg, bzr, svn)](https://pip.readthedocs.org/en/1.1/requirements.html#version-control): ``` -e git://github.com/mozilla/elastic...