title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Most efficient way to search in list of dicts | 38,865,201 | <p>I have the following list of dicts.</p>
<pre><code>people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
</code></pre>
<p>Which would be the most optimized way in terms of performance to search in list of dicts. Following are different some methods:</p>
<pre><code>next((it... | -1 | 2016-08-10T05:50:07Z | 38,865,327 | <p>If you are searching for a single item then this is the "best" approach</p>
<pre><code>def search(name):
for p in people:
if p['name'] == name:
return p
</code></pre>
<p>All the other implementations will iterate over all the items in the list, whereas this one will stop once the item is fo... | 0 | 2016-08-10T05:59:30Z | [
"python",
"list",
"dictionary"
] |
Most efficient way to search in list of dicts | 38,865,201 | <p>I have the following list of dicts.</p>
<pre><code>people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
</code></pre>
<p>Which would be the most optimized way in terms of performance to search in list of dicts. Following are different some methods:</p>
<pre><code>next((it... | -1 | 2016-08-10T05:50:07Z | 38,865,437 | <p>Doing a quick timeit on the functions show that using filter seems to be the fastest of all the methods</p>
<p><code>%timeit filter(lambda person: person['name'] == 'Pam', people)</code></p>
<p>1000000 loops, best of 3: 263 ns per loop</p>
<ul>
<li>Using next produces a time of 731ns</li>
<li>Using the search met... | 1 | 2016-08-10T06:06:19Z | [
"python",
"list",
"dictionary"
] |
How to insert app-level constants into a django template | 38,865,279 | <p>Suppose I have a constant defined in my <code>models.py</code> as <code>NUM_IMAGES</code> and I want to access that in a template within the same app. How would I go about doing this? I certainly don't want to put it in the project's <code>settings.py</code>, exposing it to the entire project, nor do I particularly ... | 0 | 2016-08-10T05:55:45Z | 38,865,597 | <p>You can easily expose your constants to view by just wrapping them in context.
so if you want to access NUM_IMAGES in view
first import it into views.py file</p>
<pre><code>from models import NUM_IMAGES
</code></pre>
<p>then pass it to required view</p>
<pre><code>def myview(request):
#something to do
re... | 1 | 2016-08-10T06:16:54Z | [
"python",
"django"
] |
Are f-strings supposed to work in Python 3.4? | 38,865,348 | <p>Is this supposed to work in Python 3.4:</p>
<p><code>>>> a='tttt'</code></p>
<p><code>>>> print(f'The value of a is {a}')</code></p>
| 0 | 2016-08-09T23:58:21Z | 38,865,359 | <p>No, <code>f</code> strings <a href="https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew-fstrings" rel="nofollow">were introduced in Python 3.6</a> which is currently (as of August 2016) in alpha.</p>
| 1 | 2016-08-10T06:01:46Z | [
"python",
"string",
"python-3.x"
] |
Are f-strings supposed to work in Python 3.4? | 38,865,348 | <p>Is this supposed to work in Python 3.4:</p>
<p><code>>>> a='tttt'</code></p>
<p><code>>>> print(f'The value of a is {a}')</code></p>
| 0 | 2016-08-09T23:58:21Z | 38,866,741 | <p>You could at least emulate them if really needed</p>
<pre><code>def f(string):
# (!) Using globals is bad bad bad
return string.format(**globals())
# Use as follows:
ans = 'SPAM'
print(f('we love {ans}'))
</code></pre>
<p>Or maybe some other ways, like a class with reloaded <code>__getitem__</code> if you... | 1 | 2016-08-10T07:23:29Z | [
"python",
"string",
"python-3.x"
] |
Input to the fit method in scikit-learn | 38,865,377 | <p>I'm reading the scikit-learn documentation's Type Casting <a href="http://scikit-learn.org/stable/tutorial/basic/tutorial.html#type-casting" rel="nofollow">example</a>. </p>
<p>My question is about an ndarray operation which is given as an input to the <code>fit</code> method. (Refer the code below)</p>
<pre><code... | 0 | 2016-08-10T06:02:42Z | 38,865,654 | <p><code>iris.target</code> is used as an <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#index-arrays" rel="nofollow">index array</a> in that operation. </p>
<p>Consider the following array:</p>
<pre><code>arr = np.array(['a', 'b', 'c'])
arr
Out:
array(['a', 'b', 'c'],
dtype='<U1... | 0 | 2016-08-10T06:20:15Z | [
"python",
"numpy",
"scikit-learn"
] |
Or statements for complex regex formation in python | 38,865,480 | <p>I need to formulate a regex to pick up only the first part of a particular string rather than the second part. For example: </p>
<pre><code> (part1) (Part2)
SAI Table
Cloth
DARA ... | 0 | 2016-08-10T06:09:59Z | 38,866,178 | <p>Using named capturing groups you are able to distinguish between captured parts:</p>
<pre><code>(?: +(?P<one>(?:\w+)?))?(?: +(?P<two>(?:\w+)?))
</code></pre>
<p><a href="https://regex101.com/r/uB7wV6/2" rel="nofollow">Live demo</a></p>
| 0 | 2016-08-10T06:50:13Z | [
"python",
"regex",
"string"
] |
Or statements for complex regex formation in python | 38,865,480 | <p>I need to formulate a regex to pick up only the first part of a particular string rather than the second part. For example: </p>
<pre><code> (part1) (Part2)
SAI Table
Cloth
DARA ... | 0 | 2016-08-10T06:09:59Z | 38,868,005 | <p>If the first column (<em>part1</em>) is <strong>always</strong> followed by 2 spaces, whereas the second (<em>part2</em>) is not, you can rely on that condition to prevent a match in the last column. We can use the <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookahead</a> <code>(?=[\... | 1 | 2016-08-10T08:28:14Z | [
"python",
"regex",
"string"
] |
how to inquire an iterator in python without changing its pre-inquire state | 38,865,601 | <p>I built an iterable object A that holds a list of other objects B. I want to be able to automatically skip a particular object B on the list if it is flagged bad when the object A is used in a for loop.</p>
<pre><code>class A():
def __init__(self):
self.Blist = [B(1), B(2), B(3)] #where B(2).is_bad() is True,... | 5 | 2016-08-10T06:17:03Z | 38,865,761 | <p>How about:</p>
<pre><code>def __iter__(self):
nextB = iter(self.Blist)
for b_obj in nextB:
if b_obj.is_bad():
yield b_obj
</code></pre>
<p>A simplified example:</p>
<pre><code>class B:
def __init__(self, cond):
self.cond = cond
def is_bad(self):
return self.con... | 1 | 2016-08-10T06:26:54Z | [
"python",
"oop",
"iterator"
] |
how to inquire an iterator in python without changing its pre-inquire state | 38,865,601 | <p>I built an iterable object A that holds a list of other objects B. I want to be able to automatically skip a particular object B on the list if it is flagged bad when the object A is used in a for loop.</p>
<pre><code>class A():
def __init__(self):
self.Blist = [B(1), B(2), B(3)] #where B(2).is_bad() is True,... | 5 | 2016-08-10T06:17:03Z | 38,865,781 | <p>You can use a generator function:</p>
<pre><code> def __iter__(self):
for item in self.Blist:
if not item.is_bad():
yield item
</code></pre>
<p>A generator function is marked by the keyword <code>yield</code>. A generator function returns a generator object, which is an iterator. It ... | 1 | 2016-08-10T06:27:47Z | [
"python",
"oop",
"iterator"
] |
How can I run python scikit-learn on Raspberry Pi? | 38,865,708 | <p>I'm new in embedded programming, and would like to understand what I need to do to run python scikit-learn on a capable embedded processor.<br>
See Raspberry Pi as an example. </p>
| 0 | 2016-08-10T06:23:27Z | 38,866,597 | <p><code>scikit-learn</code> will run on a Raspberry Pi just as well as any other Linux machine.</p>
<p>To install it, make sure you have <code>pip3</code> (<code>sudo apt-get install python3-pip</code>), and use <code>sudo pip3 install scikit-learn</code>.</p>
<p>All Python scripts utilizing <code>scikit-learn</code... | 0 | 2016-08-10T07:16:20Z | [
"python",
"raspberry-pi",
"scikit-learn"
] |
match values of dictionaries | 38,865,743 | <p>I have a collection of records stored if several dictionaries:</p>
<pre><code>d1 = {'id':['223','444'],'value_1':['v1','x1']}
d2 = {'id': ['223','666'],'value_2':['v2','x2']}
d3 = {'id':['223','444'], 'value_3':['v3','x3']}
</code></pre>
<p>I want to search all the records that match the id of the first dictionary... | 0 | 2016-08-10T06:25:34Z | 38,868,600 | <p>Maybe this will help you:</p>
<p>Code:</p>
<pre><code>import sys
print(sys.version)
# you should use an iterable for your data
in_list = [{'id':['223','444'],'value_1':['v1','x1']},
{'id': ['223','666'],'value_2':['v2','x2']},
{'id':['223','444'], 'value_3':['v3','x3']}
]
print "Input:\n", in_list
#... | 1 | 2016-08-10T08:56:06Z | [
"python",
"dictionary"
] |
Script causing DevTools to crash | 38,865,750 | <p>I'm trying to write a chatbot for entertainment, and one of its primary functions is meme lookup. I first wrote this in Python, but I'm now rewriting it in JavaScript, as it can then run totally client side.</p>
<p>Here is my JavaScript <code>meme()</code> function:</p>
<pre><code>function meme(srch) {
reqUrl = ... | 0 | 2016-08-10T06:26:27Z | 38,865,917 | <p>There is an infinite loop:</p>
<pre><code>while (srch) {
...
}
</code></pre>
<p><code>srch.slice</code> does not change the originial array "srch".
Maybe this solves your issue: Instead of your while loop do the following:</p>
<pre><code>memesrch = (srch typeof Array)
? '+' + srch.join('+')
: '+' + sr... | 0 | 2016-08-10T06:36:23Z | [
"javascript",
"python",
"google-chrome",
"devtools"
] |
how to address zip list in sort lambda | 38,865,850 | <p>I have a class with 2 attributes which are lists themselves:</p>
<pre><code>class data...:
list1 = [["g1", 2.0], ["x1", 3.0]...] # n elements
list2 = [[2, 4, 5],[3, 2, 1]...] # n elements
</code></pre>
<p>I need to zip sort both lists, based on value of the second element of <code>list2</code>.</p>
<pre><... | 1 | 2016-08-10T06:31:45Z | 38,865,958 | <p><code>cmp</code> should be a reference to a function that compares two values. Instead, you need something much simpler - a <code>key</code> field.</p>
<p>The easiest way would be to reference the value directly from <code>zipped</code> instead of going back to the original value in <code>list2</code>. Note, BTW, t... | 2 | 2016-08-10T06:38:09Z | [
"python",
"sorting",
"lambda"
] |
strange with use request.args? | 38,865,858 | <p>submit an Ip to post1.py</p>
<pre><code>@main.route('/post1',methods=['GET','POST'])
@login_required
def post1():
Ip=request.form['Ip']
print Ip
return redirect(url_for('.post',Ip=Ip))
</code></pre>
<p>then redirect to post.py</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login_require... | -1 | 2016-08-10T06:32:24Z | 38,867,983 | <p>use request.args.get('Ip') solved this error,but do not know the reason because request.args['Ip'] still can get the data.</p>
| 0 | 2016-08-10T08:27:04Z | [
"python",
"forms",
"flask",
"request"
] |
strange with use request.args? | 38,865,858 | <p>submit an Ip to post1.py</p>
<pre><code>@main.route('/post1',methods=['GET','POST'])
@login_required
def post1():
Ip=request.form['Ip']
print Ip
return redirect(url_for('.post',Ip=Ip))
</code></pre>
<p>then redirect to post.py</p>
<pre><code>@main.route('/post', methods=['GET', 'POST'])
@login_require... | -1 | 2016-08-10T06:32:24Z | 38,868,384 | <p>This post points out the <a href="http://stackoverflow.com/questions/8552675/form-sending-error-flask">Form sending error</a>:</p>
<blockquote>
<p>Flask raises an HTTP error when it fails to find a key in the args and form dictionaries. What Flask assumes by default is that if you are asking for a particular key ... | 0 | 2016-08-10T08:45:57Z | [
"python",
"forms",
"flask",
"request"
] |
Getting non string value as a json key in python | 38,866,023 | <p>I'm using "ODK" integeration in one of my django project.</p>
<p>I'm getting a json format from a response(request.body) in a django view which is in the way that all the keys in it are non-string.
ex : </p>
<pre><code>{
key1 : "value1",
key2 : "value2"
}
</code></pre>
<p>Since the keys in it are non string... | 0 | 2016-08-10T06:41:32Z | 38,866,455 | <p>As others have pointed out, this is not valid JSON, for two reasons: the unquoted key names and the trailing comma at the end.</p>
<p>Your best bet if possible would be to fix the server code that generates this to produce correct JSON instead. Perhaps that code is creating the "JSON" by manually pasting strings to... | 2 | 2016-08-10T07:07:51Z | [
"python",
"json",
"dictionary"
] |
how to run selective modules from a directory using nosetests? | 38,866,116 | <p>I have multiple modules in same directory and i'm running the below nosetests command:
nosetests --processes=2 --process-timeout=1500 -v --nocapture -a=attr --attr=api --exclude-dir-file=src/tests/externalapi/test_p0_security_tests.py --with-xunitmp</p>
<p>No luck tests in test_p0_security_tests.py still executed.<... | -1 | 2016-08-10T06:46:50Z | 38,870,038 | <p><code>nosetests</code> does not support <code>--exclude-dir-file</code> by default. Since you are not reporting getting an error about the option being invalid, and there is only one plugin I know that provides this option, I'm assuming you are using the <a href="https://pypi.python.org/pypi/nose-exclude" rel="nofol... | 0 | 2016-08-10T09:57:23Z | [
"python",
"nose"
] |
TypeError: framechange() missing 1 required positional argument: 'get' | 38,866,117 | <p>I'm trying to create a basic password storage program and am having trouble with the error code in the title</p>
<pre><code>class StartPage(tk.Frame):
entry = "password"
def framechange(self, get):
if self.entry.get() == "password":
controller.show_frame("PageOne")
def __init__(self,... | -1 | 2016-08-10T06:46:55Z | 38,866,182 | <p>The <code>framechange</code> method expects an argument, yet you are not providing it when it is called by the button's callback (<code>button1 = tk.Button(self, text="Login",command = self.framechange</code>).</p>
<p>It seems like you don't even need that argument, as you are not using it. </p>
<p>Try changing <c... | 0 | 2016-08-10T06:50:32Z | [
"python",
"get"
] |
Resize images to very small n x n dimensions | 38,866,162 | <p>I am resizing my images to 50 x 50 in python. Skimage transform and PIL thumbnail both resize the image while preserving the aspect ratio.
Whats the other way to do it?
I have tried:
For PIL thumbnail,</p>
<pre><code>im.thumbnail((50,50),Image.ANTIALIAS)
</code></pre>
<p>This gives me a (42,50) image not a (50,50... | 0 | 2016-08-10T06:49:15Z | 39,942,518 | <p>Use <code>im.resize((50,50), Image.ANTIALIAS)</code></p>
| 0 | 2016-10-09T10:25:31Z | [
"python",
"image",
"resize",
"python-imaging-library",
"skimage"
] |
pywinauto.findwindows.WindowNotFoundError in pywinauto | 38,866,272 | <p>I am new in pywinauto and have just started learning. I have installed pywinauto with pip in my local 32 bit Windows 7 OS.
So, I have this sample code to open an URL in chrome browser.</p>
<pre><code>from pywinauto import application
app=application.Application()
app.start(r'C:\Program Files\Google\Chrome\Applicati... | 3 | 2016-08-10T06:55:42Z | 38,868,466 | <p>The full answer would be long and complicated. Let's start from your small problem.</p>
<ol>
<li><p>Chrome spawns few more processes that is not connected with <code>app</code> object. Solution: use <code>Application().connect(title='New tab')</code> (or <code>title_re</code> or whatever possible for <a href="http:... | 3 | 2016-08-10T08:49:48Z | [
"python",
"pywinauto"
] |
pywinauto.findwindows.WindowNotFoundError in pywinauto | 38,866,272 | <p>I am new in pywinauto and have just started learning. I have installed pywinauto with pip in my local 32 bit Windows 7 OS.
So, I have this sample code to open an URL in chrome browser.</p>
<pre><code>from pywinauto import application
app=application.Application()
app.start(r'C:\Program Files\Google\Chrome\Applicati... | 3 | 2016-08-10T06:55:42Z | 38,872,473 | <p>To add to what Vasily said:</p>
<p>There might be another problem here.</p>
<p>If your Chrome is too slow to start, the connection might miss it.</p>
<p>I think this is somehow regulated in start method, but as chrome starts more than one process it may cause the problem.</p>
<p>I advise you to use Python's modu... | 0 | 2016-08-10T11:41:56Z | [
"python",
"pywinauto"
] |
the program stop run is caused by python udp stay in a place | 38,866,491 | <p>I have one question about <code>socket</code> in python.
I use <code>udp-protocol</code> in my program. There is the following error usually happening in the program. My program stay in a point. Using <code>pstack pid</code>, the detail message is as followsï¼</p>
<pre><code>$ pstack 12776
#0 0x000000318b20e9a3 i... | 0 | 2016-08-10T07:10:01Z | 39,116,233 | <p>I found a reason.I used udp protocol in my code.Sometimes because of net problem, client can't data that server send.
Final, I solved this problem by using select function in client.</p>
| 0 | 2016-08-24T06:48:35Z | [
"python",
"sockets",
"centos",
"udp"
] |
ExternalError: TypeError: Cannot read property 'innerHTML' of null with Skulpt runit() function | 38,866,526 | <p>I am getting an:</p>
<pre><code>ExternalError: TypeError: Cannot read property 'innerHTML' of null on line 2
</code></pre>
<p>in the console log from this code...</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet'... | 0 | 2016-08-10T07:12:15Z | 38,866,756 | <p>The 'mypre' element does not exist in your webpage.</p>
<pre><code>You should add a condition like this:
var mypre = document.getElementById("output");
if( mypre ) != null){
mypre.innerHTML = mypre.innerHTML + text; }
</code></pre>
| 1 | 2016-08-10T07:24:12Z | [
"javascript",
"jquery",
"python",
"html",
"skulpt"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code>... | 1 | 2016-08-10T07:13:58Z | 38,866,710 | <p>You just converted the integer value to big endian binary bytes.</p>
<p>This is useful mostly to embed in messages addressed to big-endian machines (PowerPC, M68K,...)</p>
<p>Converting to <code>long</code> like this means parsing the <code>ttm</code> string which should be <code>0x1869D</code> as ASCII.
(and the ... | 0 | 2016-08-10T07:22:06Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code>... | 1 | 2016-08-10T07:13:58Z | 38,866,733 | <p><strong>pack</strong> will return a string representation of the data you provide.</p>
<p>The string representation is different than a <strong>base 16</strong> of a long number. Notice the <strong>\x</strong> before each number.</p>
<p>Edit:</p>
<p>try this</p>
<pre><code>ttm = pack('>I',v)
final, = unpack('... | 1 | 2016-08-10T07:23:03Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code>... | 1 | 2016-08-10T07:13:58Z | 38,866,774 | <p>You have to use <code>struct.unpack</code> as a reverse operation to <code>struct.pack</code>.</p>
<pre><code>r, = unpack('<i', ttm)
</code></pre>
<p>this will <code>r</code> set to <code>-1652162304</code>.</p>
| 1 | 2016-08-10T07:25:11Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Convert Hexadecimal string to long python | 38,866,552 | <p>I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value</p>
<p>here is my code in python:</p>
<pre><code>v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
</code>... | 1 | 2016-08-10T07:13:58Z | 38,866,928 | <p>This is a nice question.</p>
<p>Here is what you are looking for.</p>
<pre><code>s = str(ttm)
for ch in r"\bx'":
s = s.replace(ch, '')
print(int(s, 16))
</code></pre>
<p>The problem is that <code>ttm</code> is similar to a string in some aspects. This is what is looks like: <code>b'\x00\x01\x86\x9d'</code>. ... | 0 | 2016-08-10T07:32:13Z | [
"python",
"struct",
"hex",
"long-integer",
"big-endian"
] |
Correct way to save an image in admin and showing it in a template in Django | 38,866,687 | <p>I am using MySql and Django. I need to select the image route stored in the database, I can't use the <code>url</code> property of an ImageField, It must be the route stored in the database.</p>
<p>First of all, this is my configuration in settings:</p>
<pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path... | 0 | 2016-08-10T07:20:55Z | 38,884,633 | <p>I have found a partial solution, reading this <a href="https://docs.djangoproject.com/en/1.8/ref/settings/#media-url" rel="nofollow">Settings Media URL</a> and after it redirected me to this <a href="https://docs.djangoproject.com/en/1.8/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="n... | 0 | 2016-08-10T22:34:45Z | [
"python",
"mysql",
"django"
] |
How to set the background color of part of the text in QTreeWidgetItem? | 38,866,696 | <p>For example, the text of QTreeWidgetItem is ["Hello world"], is there any way to set the background color of 'Hello'? The method <code>setBackground</code> seems to set the whole column.</p>
| 0 | 2016-08-10T07:21:09Z | 38,867,415 | <p>Set a custom Widget as default view of your QTreeWidgetItem, its easy with QLabel. This is an example with a QListWidget and QListWidgetItem: </p>
<pre><code>QListWidgetItem* MainWindow::addColoredItem(const QString& name, const QColor& backcolor, const QColor& textcolor) {
QListWidgetItem* item = n... | 0 | 2016-08-10T07:57:03Z | [
"python",
"qt",
"qtreewidgetitem"
] |
GridSearchCV not working? | 38,866,705 | <p>I am trying to use grid search to figure out the best value for n_components to use in PCA:</p>
<pre><code>from sklearn.decomposition import PCA
from sklearn.grid_search import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Linear... | 0 | 2016-08-10T07:21:55Z | 38,879,833 | <p><code>GridSearchCV</code>, spits out a <strong>cross_validation</strong> score. Adding a <code>cross_validation</code> to your for loop may give you a closer result. </p>
<p>Besides you are using different data. You have mentioned that you used <code>train_test_split</code>. In your for loop, you got the scores on ... | 2 | 2016-08-10T17:22:38Z | [
"python",
"machine-learning",
"scikit-learn"
] |
filename.whl is not a supported wheel on this platform | 38,866,758 | <p>I saw the same question but it didn't work for me.</p>
<pre><code>pip install PyOpenGL.3.1.1-cp34-cp34m-win_amd64.whl
</code></pre>
<p>also I have the same problem for Numpy</p>
<pre><code>pip install numpy-1.11.1+mkl-cp34-cp34m-win_amd64.whl
</code></pre>
<p>Then I get: </p>
<blockquote>
<p>numpy-1.11.1+mkl-... | 0 | 2016-08-10T07:24:14Z | 39,883,753 | <p>You'll probably have to rename your whl file like this <code>numpy-1.11.1+mkl-cp34-none-win_amd64.whl</code> before installing. Your <code>pip</code> has a finite number of tags it recognizes in wheel filenames.</p>
<p>See this answer for more on this: <a href="http://stackoverflow.com/a/28111899/4401501">http://st... | 0 | 2016-10-05T21:12:41Z | [
"python",
"numpy",
"module",
"pip",
"pyopengl"
] |
Filter column by value inside and get index | 38,866,792 | <p>I would like to get an other dataframe fill with columns which have value greater or equal to <code>1</code>.</p>
<pre><code>df = pd.DataFrame({'A': '0 1 0 0 1 2'.split(),
'B': '0.1 0.2 0 0.5 0 0.1'.split(),'C':'0.1 0.2 0 0.5 0 0.1'.split()})
A B C
0 0 0.1 0.1
1 1 0.2 0.2
2 0 0 ... | 3 | 2016-08-10T07:26:03Z | 38,866,922 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ge.html" rel="nofollow"><code>ge</code></a> what means get values <code>greater</code> or <code>equal</code>, then filter by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofol... | 3 | 2016-08-10T07:32:01Z | [
"python",
"pandas",
"dataframe",
"filter",
"multiple-columns"
] |
Filter column by value inside and get index | 38,866,792 | <p>I would like to get an other dataframe fill with columns which have value greater or equal to <code>1</code>.</p>
<pre><code>df = pd.DataFrame({'A': '0 1 0 0 1 2'.split(),
'B': '0.1 0.2 0 0.5 0 0.1'.split(),'C':'0.1 0.2 0 0.5 0 0.1'.split()})
A B C
0 0 0.1 0.1
1 1 0.2 0.2
2 0 0 ... | 3 | 2016-08-10T07:26:03Z | 38,867,200 | <p>I create a boolean mask where at least some value in a column is >= 1. Then I use this mask on both the data and the columns to produce a new dataframe.</p>
<p>I utilize numpy for the masking.</p>
<pre><code># convert to floats and define mask
v = df.values.astype(float)
mask = (v >= 1).any(0)
# assign new da... | 3 | 2016-08-10T07:46:23Z | [
"python",
"pandas",
"dataframe",
"filter",
"multiple-columns"
] |
python - Return value in different functions | 38,866,886 | <p>I am working on a Roomba robot (cleaning robot) and I have to print each time the robot bumps into something. I also have to take pictures every 10 seconds thanks to the Picamera. I would like to be able to print that a bump happens between pictures n and pictures n+1.
When a picture is taken, I increment the number... | 0 | 2016-08-10T07:30:11Z | 38,867,000 | <p>Add a variable that is only updated when count is?
What I mean is, in reactSensor(): </p>
<pre><code>reactSensor():
...
if array[3] == 1 or array[4] == 1:
count +=1
newvariable = PicturesNumber
global newvariable
def displayBumpings():
threading.Timer(1, displayBumpings).start()
... | 0 | 2016-08-10T07:35:57Z | [
"python",
"count"
] |
import another program as module | 38,866,980 | <p>i searched my problem on stack and i didt find the solution so i come here to asking u about that .im learnin python with the book 'OReilly.Introducing.Python' and in chapter 5 in module section .the author says u can save a program and use in in another program as module when the 2 programs are saved in 1 directory... | 0 | 2016-08-10T07:34:49Z | 38,867,024 | <p>Just as the error says, you must ident the docstring:</p>
<pre><code>def get_description(): # see the docstring below?
"""Return random weather, just like the pros"""
from random import choice
possibilities = ['rain', 'snow', 'sleet', 'fog', 'sun', 'who knows']
return choice(possibilities)
</code></... | 0 | 2016-08-10T07:37:07Z | [
"python"
] |
how to search for string inside chrome internal pages, using python and\or selenium | 38,867,008 | <p>I'm trying to write script, that would allow me to search for a string inside Chrome's internal pages (for example: "chrome://help").<br>
is there a simple way to do it, or does it require special tools, (like the Selenium webdriver API)?<br>
i know it's possible to use it for "normal" web pages, but what about "int... | 0 | 2016-08-10T07:36:12Z | 38,868,139 | <p>You can use selenium Webdriver to easily achieve this task, and in this case we will extract the version number of Google Chrome.</p>
<p>Here is the sample code with comments explaining every step:</p>
<pre><code>from selenium import webdriver
# executable path should be the place where chrome driver is on the co... | 1 | 2016-08-10T08:34:02Z | [
"python",
"google-chrome",
"selenium-webdriver"
] |
How to find neighbors in binary image with given horizontal and vertical distance (Python) | 38,867,092 | <p>I have an Image (or several hundreds of them) that need to be analyzed. The goal is to find all black spots close to each other.</p>
<p>For example all black spots with a Horizontal distance of 160 pixel and vertical 40 pixel.</p>
<p><a href="http://i.stack.imgur.com/hyKGh.png" rel="nofollow"><img src="http://i.st... | 2 | 2016-08-10T07:40:08Z | 38,871,169 | <p><em>Disclaimer</em>: I'm not proficient with the scikit image library at all, but I've tackled similar problems using MATLAB so I've searched for the equivalent methods in scikit, and I hope my findings below help you.</p>
<p>First you can use <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#skima... | 1 | 2016-08-10T10:43:40Z | [
"python",
"scikit-image",
"neighbours"
] |
How to find neighbors in binary image with given horizontal and vertical distance (Python) | 38,867,092 | <p>I have an Image (or several hundreds of them) that need to be analyzed. The goal is to find all black spots close to each other.</p>
<p>For example all black spots with a Horizontal distance of 160 pixel and vertical 40 pixel.</p>
<p><a href="http://i.stack.imgur.com/hyKGh.png" rel="nofollow"><img src="http://i.st... | 2 | 2016-08-10T07:40:08Z | 38,876,149 | <p>When you get the coordinates of the different black spots, rather than computing all distances between all pairs of black pixels, you can use a cKDTree (in scipy.spatial, <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy.spatial.cKDTree" rel="nofollow">http://docs.scipy.or... | 2 | 2016-08-10T14:23:52Z | [
"python",
"scikit-image",
"neighbours"
] |
How to find neighbors in binary image with given horizontal and vertical distance (Python) | 38,867,092 | <p>I have an Image (or several hundreds of them) that need to be analyzed. The goal is to find all black spots close to each other.</p>
<p>For example all black spots with a Horizontal distance of 160 pixel and vertical 40 pixel.</p>
<p><a href="http://i.stack.imgur.com/hyKGh.png" rel="nofollow"><img src="http://i.st... | 2 | 2016-08-10T07:40:08Z | 38,890,177 | <p>If your input image is binary, you could separate your regions of interest as follows:</p>
<ol>
<li>"grow" all the regions by the expected distance (actually half of it, as you grow from "both sides of the gap") with <code>binary_dilation</code>, where the <code>structure</code> is a kernel (e.g. rectangular: <a hr... | 1 | 2016-08-11T07:39:46Z | [
"python",
"scikit-image",
"neighbours"
] |
Not able to switch between two subprocess | 38,867,149 | <p>I am trying to work with two subprocess.
I open the first one and send him something, then i open the second one and send him something. In both cases I send with stdin.write</p>
<pre><code>process1 = subprocess.Popen([path], stdin = subprocess.PIPE,)
process1.stdin.write('some string1')
process2 = subprocess.Popen... | 1 | 2016-08-10T07:44:10Z | 38,867,514 | <p>It should just work.</p>
<p>For example:</p>
<pre><code>$ cat 1.py
import subprocess
process1 = subprocess.Popen("cat > file1", shell=True, stdin=subprocess.PIPE)
process1.stdin.write('some string1\n')
process2 = subprocess.Popen("cat > file2", shell=True, stdin=subprocess.PIPE)
process2.stdin.write('some s... | 0 | 2016-08-10T08:03:03Z | [
"python",
"python-2.7",
"subprocess"
] |
Django.core.validators MinMaxValueValidator ignored from shell | 38,867,167 | <p>I'm using django 1.10, created </p>
<pre><code>from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
class B(models.Model):
address = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(63)], blank=True, null=True)
</code></pr... | -2 | 2016-08-10T07:44:52Z | 38,867,392 | <p>This is correct.</p>
<p>From the <a href="https://docs.djangoproject.com/en/1.9/ref/validators/#how-validators-are-run" rel="nofollow">docs for How validators are run</a></p>
<blockquote>
<p>...Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run... | 1 | 2016-08-10T07:55:32Z | [
"python",
"django",
"custom-validators"
] |
Is there any way to know current url is in a specific blueprint in flask? | 38,867,248 | <p>in my flask app I can use a blueprint to register lots of routes..</p>
<pre><code>@myblueprint.route('/first')
@myblueprint.route('/two')
@myblueprint.route('/three')
</code></pre>
<p>my problem is that I need to know current url in in a specific blueprint.so I can give it a <code>class='active'</code> css effect ... | 1 | 2016-08-10T07:48:39Z | 38,875,225 | <p><a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request.blueprint" rel="nofollow"><code>request.blueprint</code></a> will be the current blueprint name if the request is being handled by a blueprint.</p>
| 1 | 2016-08-10T13:44:50Z | [
"python",
"url",
"flask",
"jinja2"
] |
How to retrieve wav file from API? | 38,867,272 | <p>I am working on Python3.4.4
I tried to use a Merriam-Webster API, and here is an example link:
<a href="http://www.dictionaryapi.com/api/v1/references/collegiate/xml/purple?key=bf534d02-bf4e-49bc-b43f-37f68a0bf4fd" rel="nofollow">http://www.dictionaryapi.com/api/v1/references/collegiate/xml/purple?key=bf534d02-bf4e-... | 0 | 2016-08-10T07:50:04Z | 38,868,684 | <p>Okay, I just sort it out.
Usually you need to look at the instructions for the API, I look it up on the official website and it tells you that how you are going to retrieve that. In this case you are going to another url, and then wala</p>
| 0 | 2016-08-10T09:00:22Z | [
"python",
"xml",
"api",
"audio",
"wav"
] |
'NoneType' object has no attribute 'sendall' PYTHON | 38,867,346 | <p>My current python script:</p>
<pre><code>import os
import ftplib
import hashlib
import glob
hashing = "123"
m = hashlib.md5()
m.update(hashing)
dd = m.hexdigest()
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
for image in glob.glob(os.path.join('Desktop/images/test*.png')):
... | 2 | 2016-08-10T07:53:06Z | 38,867,653 | <blockquote>
<p><strong>FTP.quit()</strong>
Send a QUIT command to the server and close the connection. This is the âpoliteâ way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance... | 1 | 2016-08-10T08:09:28Z | [
"python",
"python-2.7",
"ftp"
] |
Let telegram bot react while a document is sent to a group chat | 38,867,473 | <p>I want my bot to send a message when it detect documents is sent in a chat.<br>
I add a message handler with document filter.<br>
The code works for chat to the bot directly,<br>
but if I add the bot into a group,
the bot has no response if I sent a document in the group.</p>
<p>The code is:</p>
<pre class="lang-p... | 1 | 2016-08-10T08:01:10Z | 38,876,257 | <p>If code is working in private chat but not working( not receiving messages sent) in a group , the reason is you do NOT set <code>/setprivacy</code> in <code>BotFather</code>.</p>
<blockquote>
<p>Go to <code>BotFather</code> and disable <code>/setprivacy</code> for your bot. In this
state, your bot will receive ... | 1 | 2016-08-10T14:28:29Z | [
"python",
"telegram",
"telegram-bot"
] |
Sequential task execution in Celery | 38,867,489 | <p>I have some "heavy" requests to the database that I'm going to execute using Celery. Taking into account that they are "heavy" I want to execute them sequentially (one by one). One possible solution is to specify <code>--concurrency=1</code> in the command line to Celery. And it works. But there is a problem: while ... | 1 | 2016-08-10T08:01:49Z | 38,871,139 | <p>Celery's inspections are performed by broadcasting a query to anything that listens and then gathering the responses. Any worker that does not respond within the timeout (which I think is 1 second by default), is going to be ignored. It is as if it did not exist.</p>
<p>The fact that you use <code>--concurrency=1</... | 1 | 2016-08-10T10:42:00Z | [
"python",
"celery"
] |
Storing and using a trained neural network | 38,867,587 | <p>I am trying to develop a neural network to predict timeseries.</p>
<p>As far as I have understood, I am training my neural network with a training set and validate it with a test set.</p>
<p>When I am satisfied with my results, I can use my neural network to predict new values, and the neural network itself is bas... | 2 | 2016-08-10T08:06:20Z | 38,867,857 | <p>To make your Neural Network <em>persistent</em>, you can <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow"><code>pickle</code></a> it. You would not need to recompute the weights of the <em>trained-pickled</em> network, and all you need do is unpickle the network and use it to make new predictio... | 0 | 2016-08-10T08:20:09Z | [
"python",
"machine-learning",
"neural-network",
"recurrent-neural-network",
"heavy-computation"
] |
how can I make the celery task call back to flask when it is finished | 38,867,608 | <p>When integrating celery with a Flask app, i have a longtime task that needs to callback to flask when the task is finished</p>
<pre><code>@celery_app.task(bind=True)
def doSth(self):
rv = long_time_job()
return rv
@task_success.connect(sender=doSth)
def on_add_success(sender, result, **kwargs):
#tell f... | 1 | 2016-08-10T08:07:09Z | 38,867,829 | <p>A celery task is run indepently from the Flask server through a worker, they are two different process communicated with a message broker (rabbitmq?). So, when the task ends, that callback function should be done having the former in mind, two different process.</p>
<p>Here I give you two solutions:</p>
<ul>
<li>W... | 1 | 2016-08-10T08:18:45Z | [
"python",
"celery"
] |
How to create permission for specific rules in Django Rest Framework? | 38,867,688 | <p>I want to arrange permission like that each user can edit his own profile. Just super user can edit all profile. What I need to add <strong>permissions.py</strong> ? Thank you.</p>
<p><strong>views.py</strong></p>
<pre><code>class UserViewSet(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
... | 0 | 2016-08-10T08:11:39Z | 38,873,561 | <p>Write your own permission</p>
<pre><code>class IsObjectOwner(BasePermission):
message = "You must be the owner of this object."
my_safe_methods = ['GET', 'PUT', 'PATCH', 'DELETE']
def has_permission(self, request, view):
if request.method in self.my_safe_methods:
return True... | 1 | 2016-08-10T12:32:57Z | [
"python",
"django",
"django-rest-framework"
] |
A faster discrete Laplacian than scipy.ndimage.filters.laplace for small arrays | 38,867,689 | <p>My spends the vast bulk of its computational time in <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.filters.laplace.html" rel="nofollow"><code>scipy.ndimage.filters.laplace()</code></a></p>
<p>The main advantage of <code>scipy</code> and <code>numpy</code> is vectorised calculatio... | 1 | 2016-08-10T08:11:43Z | 38,872,821 | <p>The problem was rooted in <code>scipy</code>'s excellent error handling and debugging. However, in the instance the user knows what they're doing it just provides excess overhead.</p>
<p>This code below strips all the <code>python</code> clutter in the back end of <code>scipy</code> and directly accesses the <code>... | 1 | 2016-08-10T11:58:20Z | [
"python",
"c++",
"numpy",
"filter"
] |
Tough time understanding the below Python Script | 38,867,706 | <p>I am new to coding and I am having a hard understanding the below code which prints all the prime numbers below 10.</p>
<pre><code>N = 10
primes = []
for n in range(2,N+1):
for p in primes:
if n % p == 0: break
else: ... | -3 | 2016-08-10T08:12:21Z | 38,867,895 | <p>A <code>for..in</code> loop over an empty list basically does nothing; it says "for each element in this list, do something", and since there is nothing in the list, it does nothing. So on the first iteration of the outer loop, the <code>for p in primes</code> does nothing at all, and the <code>else</code> clause is... | 0 | 2016-08-10T08:22:25Z | [
"python",
"python-3.x"
] |
How to create image from numpy float32 array? | 38,867,869 | <p>I have a <code>numpy.ndarray</code> array which contains values of <code>float32</code>. The images should be dimensions 226×226. I tried to use <code>PIL.Image</code> to create the image but I got an error. I read that <code>PIL.Image.fromarray</code> require an object and mode, and for float I need to call <... | 2 | 2016-08-10T08:20:34Z | 38,869,210 | <p>I would agree with DavidG's answer being the a quick solution to plot image from numpy array. However, if you have some very good reason for sticking with <code>PIL.Image</code>. The closest approach to what you have already done would be something like this:</p>
<pre><code>from PIL import Image
import numpy as np
... | 0 | 2016-08-10T09:21:36Z | [
"python",
"numpy",
"python-imaging-library"
] |
How to create image from numpy float32 array? | 38,867,869 | <p>I have a <code>numpy.ndarray</code> array which contains values of <code>float32</code>. The images should be dimensions 226×226. I tried to use <code>PIL.Image</code> to create the image but I got an error. I read that <code>PIL.Image.fromarray</code> require an object and mode, and for float I need to call <... | 2 | 2016-08-10T08:20:34Z | 38,871,070 | <p>Thanks to <code>John Titus Jungao</code> the problem solved. The array was 1D so I did the following:</p>
<pre><code>from PIL import Image
import numpy as np
slice56 = slice56.reshape((226,226))
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.save('slice56.png')
<... | 0 | 2016-08-10T10:38:25Z | [
"python",
"numpy",
"python-imaging-library"
] |
How can I sum collection.Counter objects in a Python Pandas Dataframe using the update() method? | 38,867,901 | <p>I'm dealing with semi-structured data that doesn't fully fit into a pandas dataframe, so I have some columns containing collections.Counter objects (i.e. dictionaries) of vastly varying lengths.</p>
<p>I need to apply a groupby on another column and need to sum up these Counters, however without dropping zeros or i... | 2 | 2016-08-10T08:22:37Z | 38,868,104 | <p>consider the list of dicts <code>A</code></p>
<pre><code>A = [{'A': 1,'B':-1,'C': 1},
{'A':-1,'B': 1, 'D': 0,'E': 1},
{'A': 0, 'E': 0,'F': 1},
{ 'B': 0,'C':-1, 'E':-1,'F':-1}]
pd.DataFrame(A).stack().groupby(level=1).sum().to_dict()
{'A{'A': 0.0, 'B': 0.0, 'C'... | 3 | 2016-08-10T08:32:35Z | [
"python",
"python-2.7",
"pandas",
"dataframe",
"counter"
] |
Socket.io POST Requests from Socket.IO-Client-Swift | 38,868,061 | <p>I am running socket.io on an Apache server through Python Flask. We're integrating it into an iOS app (using the <a href="https://github.com/socketio/socket.io-client-swift" rel="nofollow">Socket.IO-Client-Swift</a> library) and we're having a weird issue.</p>
<p>From the client side code in the app (written in Swi... | 27 | 2016-08-10T08:30:41Z | 38,944,170 | <p>Are you using flask-socketio on the server side? If you are, there is a lot of debugging available in the constructor. </p>
<p>socketio = SocketIO(app, async_mode=async_mode, logger=True, engineio_logger=True)</p>
| 3 | 2016-08-14T16:22:57Z | [
"python",
"ios",
"linux",
"sockets",
"flask"
] |
Socket.io POST Requests from Socket.IO-Client-Swift | 38,868,061 | <p>I am running socket.io on an Apache server through Python Flask. We're integrating it into an iOS app (using the <a href="https://github.com/socketio/socket.io-client-swift" rel="nofollow">Socket.IO-Client-Swift</a> library) and we're having a weird issue.</p>
<p>From the client side code in the app (written in Swi... | 27 | 2016-08-10T08:30:41Z | 38,968,504 | <p>I assume you have verified that Apache does get the POST requests. That should be your first test, if Apache does not log the POST requests coming from iOS, then you have a different kind of problem.</p>
<p>If you do get the POST requests, then you can add some custom code in the middleware used by Flask-SocketIO a... | 3 | 2016-08-16T07:02:31Z | [
"python",
"ios",
"linux",
"sockets",
"flask"
] |
Picking a random element from a non-empty defaultdict | 38,868,130 | <p>Say I do:</p>
<pre><code>import collections, random
d = collections.defaultdict(list)
d['foo'].append('bar')
</code></pre>
<p>Then I pick a random element:</p>
<pre><code>random.choice(d)
</code></pre>
<p>Now let's print <code>d</code>:</p>
<pre><code>defaultdict(list, {0: [], 'foo': ['bar']})
</code></pre>
<p... | 3 | 2016-08-10T08:33:42Z | 38,868,252 | <p>Internally this is what <a href="https://hg.python.org/cpython/file/2.7/Lib/random.py#l273"><code>random.choice</code></a> does:</p>
<pre><code>def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
return seq[int(self.random() * len(seq))]
</code></pre>
<p>As in your case the leng... | 6 | 2016-08-10T08:39:50Z | [
"python",
"python-3.x",
"defaultdict"
] |
Picking a random element from a non-empty defaultdict | 38,868,130 | <p>Say I do:</p>
<pre><code>import collections, random
d = collections.defaultdict(list)
d['foo'].append('bar')
</code></pre>
<p>Then I pick a random element:</p>
<pre><code>random.choice(d)
</code></pre>
<p>Now let's print <code>d</code>:</p>
<pre><code>defaultdict(list, {0: [], 'foo': ['bar']})
</code></pre>
<p... | 3 | 2016-08-10T08:33:42Z | 38,868,488 | <p>I think the behavior is actually <em>undefined</em>, because according to the document(emphasis mine):</p>
<blockquote>
<p><code>random.choice(seq)</code> </p>
<p>Return a random element from the non-empty
<strong>sequence</strong> seq. If seq is empty, raises IndexError.</p>
</blockquote>
<p><code>seq</c... | 1 | 2016-08-10T08:50:32Z | [
"python",
"python-3.x",
"defaultdict"
] |
pandas fillna inplace with multiindex | 38,868,269 | <p>I have a dataframe with multiindex</p>
<pre><code> values observations
time x1 x2 x3 x4 ... x1 x2 x3 x4 ...
t1 v1_1 nan v3_1 v4_1 ... o1_1 nan o3_1 o4_1 ...
t2 v1_2 v2_2 nan v4_2 ... o1_2 o2_2 nan ... | 2 | 2016-08-10T08:40:37Z | 38,868,399 | <p>For me works:</p>
<pre><code>df['observations'] = df['observations'].fillna(0)
print (df)
values observations
time x1 x2 x3 x4 x1 x2 x3
t1 v1_1 NaN v3_1 v4_1 o1_1 0 o3_1 o4_1
t2 v1_2 v2_2 NaN v4_2 o1_2 o2_2 ... | 2 | 2016-08-10T08:46:42Z | [
"python",
"pandas"
] |
How to access global variables from a thread in Python | 38,868,341 | <p>Consider the following code: </p>
<pre><code>from threading import Thread
def main():
number = 5
class my_thread(Thread):
def __init__(self, range):
Thread.__init__(self)
self.range = range
def run(self):
global number
for i in self.range:
... | 0 | 2016-08-10T08:44:06Z | 38,868,438 | <p>You need to make <code>number</code> a global at its first definition, like this:</p>
<pre><code>def main():
global number
number = 5
...etc...
</code></pre>
| 2 | 2016-08-10T08:48:50Z | [
"python",
"multithreading",
"thread-safety"
] |
How to pass two same arguments via python subprocess? | 38,868,461 | <p>I wanted to pass two parameter in the subprocess call... like this...</p>
<pre><code>./buildbot sendchange --branch=poky --property=buildname:nice --property=machine:qemux86
</code></pre>
<p>So I wrote the below program...</p>
<pre><code># property_name = {'key': 'value'}
y = ['--property={}:{}'.format(key, value... | 0 | 2016-08-10T08:49:37Z | 38,868,826 | <p>In parent process save argument as environment variables. Child process can access it.</p>
| 0 | 2016-08-10T09:06:40Z | [
"python",
"django",
"subprocess",
"buildbot"
] |
Python: Pandas: Save Index of DataFrames in textfile as columns | 38,868,490 | <p>I have a list of DataFrames df_list. I want to write a tab delimited textfile: The first row is the index of the list. Each column is then the values in the DataFrame index. The index.values have not the same lenght.</p>
<pre><code>0 1 2 3
i i i i
n n n .
d d . .
e . . .
x . .
. ... | 1 | 2016-08-10T08:50:36Z | 38,869,139 | <pre><code>df_list = [pd.DataFrame(range(i)) for i in range(10, 15)]
df_master = pd.DataFrame({i: df.index.to_series() for i, df in enumerate(df_list)})
sorted_cols = df_master.notnull().sum().sort_values()[::-1].index
print df_master[sorted_cols].to_csv(sep='\t', index=None, float_format='%0.0f')
</code></pre>
<p><... | 2 | 2016-08-10T09:19:08Z | [
"python",
"pandas"
] |
from OpenGLContext import testingcontext i cant import testingcontext | 38,868,564 | <p>When i do this:</p>
<pre><code>import OpenGLContext
</code></pre>
<p>its importing, there is no problem. But when i write</p>
<pre><code>from OpenGLContext import testingcontext
</code></pre>
<p>its giving an error:</p>
<pre><code> Traceback (most recent call last):
File "<pyshell#0>", line 1, in <... | 0 | 2016-08-10T08:54:20Z | 38,871,406 | <p>The <code>vrml</code> phython module is missing. So the first step would be installing that.</p>
| 0 | 2016-08-10T10:54:10Z | [
"python",
"opengl",
"openglcontext"
] |
<FloatField'> is not JSON serializable | 38,868,583 | <p>I am currently learning Django, i tried creating a simple model and expose it in an API.</p>
<blockquote>
<p>FloatField' is not JSON serializable</p>
</blockquote>
<p>it only works if i change the float to string.</p>
<p>When i call the api to retreive the model object i receive error: </p>
<p>I defined the mo... | 0 | 2016-08-10T08:55:09Z | 38,868,617 | <p>You are passing the original field objects and not instantiating them. Do instantiate them:</p>
<pre><code>miles = models.FloatField(...)
# ^^^^^
</code></pre>
| 4 | 2016-08-10T08:56:40Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
Modify pandas group | 38,868,682 | <p>I have a DataFrame, which I group.
I would like to add another column to the data frame, that is a result of function diff, per group. Something like:</p>
<pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 't... | 5 | 2016-08-10T09:00:19Z | 38,868,729 | <p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html"><code>DataFrameGroupBy.diff</code></a>:</p>
<pre><code>df['D_diff'] = df.groupby('B')['D'].diff()
print (df)
A B C D D_diff
0 foo one 1.996084 0.580177 ... | 5 | 2016-08-10T09:02:31Z | [
"python",
"pandas",
"dataframe",
"group-by",
"difference"
] |
Calculate difference of two layers | 38,868,771 | <p>I want to merge two keras layers such that the merged layer has the difference of the two layers. For example if layer1 output is [0,1,2] and layer2 output is [1,2,3] the merged layer should be [-1,-1,-1]. I tried using the following</p>
<pre><code>from keras.layers import Input, merge
from keras.models import Mode... | 1 | 2016-08-10T09:04:06Z | 38,872,680 | <p>I was able to merge the layers in the above way using,</p>
<pre><code>diff = merge([a, b], mode=lambda (x, y): x - y, output_shape=(3,))
</code></pre>
| 1 | 2016-08-10T11:52:16Z | [
"python",
"theano",
"keras"
] |
How to use split from regex in python and keep your split word? | 38,868,800 | <p>Is there a way to use split function without losing the word or char, that you using to split with?</p>
<p>for example:</p>
<pre><code>import re
x = '''\
1.
abcde.
2.
fgh 2.5 ijk.
3.
lmnop
'''
print(x)
listByNum = re.split(r'\d\.\D', x)
print(listByNum)
</code></pre>
<p><a href="http://i.stack.imgur.com/5e... | 0 | 2016-08-10T09:05:28Z | 38,868,882 | <p>Not very well documented, but you can use parentheses around the expression in question:</p>
<pre><code>import re
x = '''\
1.
abcde.
2.
fgh 2.5 ijk.
3.
lmnop
'''
print(x)
listByNum = re.split(r'(\d\.\D)', x)
print(listByNum)
# ['', '1.\n', 'abcde.\n', '2.\n', 'fgh 2.5 ijk.\n', '3.\n', 'lmnop\n ']
</code><... | 2 | 2016-08-10T09:08:32Z | [
"python",
"regex",
"string",
"split"
] |
Python TripleDES decryption | 38,869,018 | <p>I'm trying to decrypt a string in python encrypted using 3DES. It is encrypted by VB.net by my formal mate. I have no idea what is going on. The partial code in VB.net is</p>
<pre><code>Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As By... | 0 | 2016-08-10T09:14:30Z | 38,908,168 | <p>How about something like this:</p>
<pre><code>from Crypto.Cipher import DES3
key = [
1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24
]
iv = [65, 110, 68, 26, 69, 178, 200, 219]
keyStr = ""
ivStr = ""
for i in key:
keyStr += chr(i)
for i in iv: ... | 0 | 2016-08-12T00:43:06Z | [
"python",
"vb.net",
"bytearray",
"tripledes"
] |
Empty file json as output in Scrapy | 38,869,099 | <p>I state that I've already read some answers about the same problem but the I couldn't solve my issue.
I'm new in Python, I'm trying to extract data from Aptoide about apps and stores, and I want an output result as .json file (or csv), but the file I get is empty, I don't know the reason.</p>
<p>This is my code:</p... | 0 | 2016-08-10T09:17:25Z | 38,872,644 | <p>Your code is full of errors, when you run the spider you can save the log and go through it with grep:</p>
<pre><code>scrapy crawl spidername 2>&1 | tee crawl.log
</code></pre>
<p>Few errors that I found:</p>
<ul>
<li>your <code>ApptoideItem</code> is missing fields like <code>store_name</code> and few oth... | 0 | 2016-08-10T11:50:46Z | [
"python",
"json",
"regex",
"scrapy",
"rule"
] |
converting tuples to lists in list | 38,869,124 | <p>I am attempting to convert tuples in lists of a list to lists. More accurately, I just would like to remove the tuples in lists. The original dataset looks like</p>
<pre><code>collections = [[None], [(u'John Demsey ', u' Cornelia Guest')], [(u'Andres White ', u' Margherita Missoni')], [(u'Bibi Monahan, Tuki Br', u'... | 0 | 2016-08-10T09:18:40Z | 38,869,357 | <p>Rather go for <code>chain</code> in <code>itertools</code> and list comprehension:</p>
<pre><code>from itertools import chain
[list(i) if i else [i] for i in chain.from_iterable(collections)]
#Out[110]:
#[[None],
# [u'John Demsey ', u' Cornelia Guest'],
# [u'Andres White ', u' Margherita Missoni']]
</code></pre>
| 1 | 2016-08-10T09:28:18Z | [
"python",
"list",
"tuples"
] |
converting tuples to lists in list | 38,869,124 | <p>I am attempting to convert tuples in lists of a list to lists. More accurately, I just would like to remove the tuples in lists. The original dataset looks like</p>
<pre><code>collections = [[None], [(u'John Demsey ', u' Cornelia Guest')], [(u'Andres White ', u' Margherita Missoni')], [(u'Bibi Monahan, Tuki Br', u'... | 0 | 2016-08-10T09:18:40Z | 38,869,425 | <p>Try to do it this way:</p>
<pre><code>def conv():
return [list(c[0]) if isinstance(c[0], tuple) else c for c in collections]
</code></pre>
<p>In your code you also return just the last element of list.</p>
| 2 | 2016-08-10T09:30:46Z | [
"python",
"list",
"tuples"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is ther... | 56 | 2016-08-10T09:19:40Z | 38,869,220 | <p>Write a generator expression which tests your custom condition. You're not bound to only the default <em>truthiness</em> test:</p>
<pre><code>any(not i for i in l)
</code></pre>
| 41 | 2016-08-10T09:21:59Z | [
"python",
"python-3.x",
"iterable"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is ther... | 56 | 2016-08-10T09:19:40Z | 38,869,246 | <p>There is also the <code>all</code> function which does the opposite of what you want, it returns <code>True</code> if all are <code>True</code> and <code>False</code> if any are <code>False</code>. Therefore you can just do:</p>
<pre><code>not all(l)
</code></pre>
| 102 | 2016-08-10T09:23:14Z | [
"python",
"python-3.x",
"iterable"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is ther... | 56 | 2016-08-10T09:19:40Z | 38,870,927 | <p>Well, the implementation of <code>any</code> is <a href="https://docs.python.org/3/library/functions.html#any"><em>equivalent</em></a> to:</p>
<pre><code>def any(iterable):
for element in iterable:
if element:
return True
return False
</code></pre>
<p>So, just switch the condition from ... | 14 | 2016-08-10T10:33:00Z | [
"python",
"python-3.x",
"iterable"
] |
Îpposite of any() function | 38,869,155 | <p>The Python built-in function <code>any(iterable)</code> can help to quickly check if any <code>bool(element)</code> is <code>True</code> in a iterable type.</p>
<pre><code>>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True
</code></pre>
<p>But is ther... | 56 | 2016-08-10T09:19:40Z | 38,884,821 | <p>You can do:</p>
<pre><code>>>> l = [True, False, True]
>>> False in map(bool, l)
True
</code></pre>
<p>Recall that <code>map</code> in Python 3 is a generator. For Python 2, you probably want to use <code>imap</code> </p>
<hr>
<p>Mea Culpa: After timing these, the method I offered is hands down... | 9 | 2016-08-10T22:52:17Z | [
"python",
"python-3.x",
"iterable"
] |
Why is condition.notify_all wakes only one waiter? | 38,869,205 | <p>I've tried to create a python async version of java's <code>CountDownLatch</code></p>
<pre><code>class CountDownLatch:
def __init__(self, count=1):
if count == 0:
raise ValueError('count should be more than zero')
self.count = count
self.countdown_over = aio.Condition()
... | 0 | 2016-08-10T09:21:25Z | 38,891,331 | <p>Let <code>f1</code> be <code>f</code> called as the first one and let <code>f2</code> be <code>f</code> called as the second. The thing that should be noted is that even though you've used <code>async</code> keyword <code>f</code> function is <strong>synchronous</strong> until it hits <code>latch.wait()</code>. So w... | 1 | 2016-08-11T08:38:32Z | [
"python",
"coroutine",
"python-asyncio"
] |
How to get time from Properties | 38,869,256 | <p>My python script:</p>
<pre><code>import ftplib
import hashlib
import httplib
import pytz
import datetime
import urllib
import os
import glob
def ftphttp():
localtime = datetime.datetime.now(tz=pytz.utc).isoformat()
cam = "002"
lscam = localtime + cam
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd... | 0 | 2016-08-10T09:23:46Z | 38,893,497 | <p>@Alvin, You cannot get <strong>ISOdatetime</strong> from <em>getmtime</em> directly, if you want to convert the output date from <em>getmtime</em>, you can do it in following manner:</p>
<pre><code>import os.path, time
from datetime import datetime
from pytz import timezone
import pytz
ts = os.path.getmtime(file_p... | 0 | 2016-08-11T10:15:05Z | [
"python",
"python-2.7"
] |
Flask, and valid json - ValueError: dictionary update sequence element #0 has length 3; 2 is required | 38,869,273 | <p>Here is my flask code using restful.</p>
<pre><code>def get(self):
data = [{"id": "2", "lags": [{"id": "GBPQ1"}, {"id": "GBPQ2"},{"id": "GBPQ3"}, {"id": "BPQ4"}], "name": "GBP"}]
return jsonify(data)
</code></pre>
<p>Here is my error: Why? Its valid json per jsoinlint. How do I resolve?</p>
<p>curl... | 0 | 2016-08-10T09:24:41Z | 38,869,493 | <p>Try to give a dictionary to jsonify :</p>
<pre><code>def get(self):
data = [{"id": "2", "lags": [{"id": "GBPQ1"}, {"id": "GBPQ2"},{"id": "GBPQ3"}, {"id": "BPQ4"}], "name": "GBP"}]
return jsonify({'data': data})
</code></pre>
<p>Or you can also do that if you prefer: <code>return jsonify(data=data)</code></... | 0 | 2016-08-10T09:33:15Z | [
"python",
"flask"
] |
Store database query result in an object in Python 3 | 38,869,356 | <p>In my python application I run a query which returns me a <strong>product</strong> from my product table. When I get the result and assign it in a variable, it is stored in a <strong>list</strong>. But I want to create a <strong>product class</strong> and want to store query result in an object of my product class w... | 0 | 2016-08-10T09:28:15Z | 38,871,880 | <p>Okay I think found out how to do it with some more searching.</p>
<p>Not sure it is the best way but it worked for me. </p>
<p><a href="http://stackoverflow.com/a/3287775/5528870">Convert database result into json</a> and than <a href="http://stackoverflow.com/a/15882054/5528870">convert json to python object.</a>... | 0 | 2016-08-10T11:13:30Z | [
"python",
"database",
"sqlite",
"python-3.x"
] |
Pandas: replace values in strings | 38,869,372 | <p>I have data frame and I try to replace it from other df</p>
<p>I use:</p>
<pre><code>df['term_code'] = df.search_term.map(rep_term.set_index('search_term')['code_action'])
</code></pre>
<p>But I get an error:</p>
<pre><code>File "C:/Users/����� �����������/Desktop/projects/find_ti... | 4 | 2016-08-10T09:28:53Z | 38,869,500 | <p>There is problem with duplicates in <code>DataFrame</code> <code>rep_term</code> column <code>search_term</code>.</p>
<p>I simulate it:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'search_term':[1,2,3]})
print (df)
search_term
0 1
1 2
2 3
</code></pre>
<p>For value ... | 4 | 2016-08-10T09:33:40Z | [
"python",
"string",
"pandas",
"dataframe",
"duplicates"
] |
Python convert xml to list | 38,869,381 | <p>I have the following xml dataset:</p>
<pre><code><cnode desc="" name="xyz">
<pnode name="word1"/>
<pnode name="word2"/>
<pnode name="word3"/>
...
<cnode desc="" name="abc">
<pnode name="word4"/>
<pnode name="word5"/>
<pnode name="word6"/>
...
</cod... | 1 | 2016-08-10T09:29:24Z | 38,869,712 | <p>firstly you should fix your demo xml there is a missing close quote</p>
<p>I would use xpath</p>
<pre><code>from lxml import etree
tree = etree.parse('data.xml')
root = tree.getroot()
xyzpnodes = root.xpath(".//cnode[@name='xyz']/pnode")
xyz = [p.attrib["name"] for p in xyzpnodes]
print xyz
</code></pre>
| 0 | 2016-08-10T09:42:31Z | [
"python",
"xml",
"list"
] |
Python convert xml to list | 38,869,381 | <p>I have the following xml dataset:</p>
<pre><code><cnode desc="" name="xyz">
<pnode name="word1"/>
<pnode name="word2"/>
<pnode name="word3"/>
...
<cnode desc="" name="abc">
<pnode name="word4"/>
<pnode name="word5"/>
<pnode name="word6"/>
...
</cod... | 1 | 2016-08-10T09:29:24Z | 38,869,812 | <p>You can go for:</p>
<pre><code>string = """
<nodes>
<cnode desc="" name="xyz">
<pnode name="word1"/>
<pnode name="word2"/>
<pnode name="word3"/>
</cnode>
<cnode desc="" name="abc">
<pnode name="word4"/>
<pnode name="w... | 1 | 2016-08-10T09:46:43Z | [
"python",
"xml",
"list"
] |
Execution of a Python Script from PHP | 38,869,507 | <p>I am making an android application in which I am first uploading the image to the server and on the server side, I want to execute a Python script from PHP. But I am not getting any output. When I access the Python script from the command prompt and run <code>python TestCode.py</code> it runs successfully and gives ... | 1 | 2016-08-10T09:34:07Z | 38,869,610 | <pre><code>exec('/usr/bin/python /var/www/html/Source/TestCode.py', $output);
var_dump($output);
</code></pre>
<p>2nd Parameter of <a href="http://php.net/manual/en/function.exec.php" rel="nofollow">exec</a> will give output</p>
<p><strong>EDIT:</strong></p>
<pre><code>exec('/usr/bin/python /var/www/html/Source/Tes... | 3 | 2016-08-10T09:39:05Z | [
"php",
"python",
"linux",
"exec"
] |
Execution of a Python Script from PHP | 38,869,507 | <p>I am making an android application in which I am first uploading the image to the server and on the server side, I want to execute a Python script from PHP. But I am not getting any output. When I access the Python script from the command prompt and run <code>python TestCode.py</code> it runs successfully and gives ... | 1 | 2016-08-10T09:34:07Z | 38,870,240 | <ol>
<li><p>First Check your python PATH using "which python" command and check result is /usr/bin/python. </p></li>
<li><p>Check your "TestCode.py" if you have written #!/usr/bin/sh than replace it with #!/usr/bin/bash.</p></li>
<li><p>Than run these commands
exec('/usr/bin/python /var/www/html/Source/TestCode.py', $... | 1 | 2016-08-10T10:04:38Z | [
"php",
"python",
"linux",
"exec"
] |
lxml xpath get text between two nested tables | 38,869,533 | <p>I have a html that has nested tables. I wish to find the text between a outside table and inside tables. I thought this is a classic question but so far hasn't find the answer. What I have come up with is
<code>tree.xpath(//p[not(ancestor-or-self::table)])</code>. But this isn't working but because all text descends... | 0 | 2016-08-10T09:35:26Z | 38,870,751 | <p>One of the XPaths that could do this, if the outer most table is the root element:</p>
<pre><code>/table/descendant::table[1]/preceding::p
</code></pre>
<p>Here, you traverse to the first descendant <code>table</code> of the outermost <code>table</code>, and then select all its preceding <code>p</code> elements.</... | 1 | 2016-08-10T10:26:01Z | [
"python",
"xpath",
"nested",
"lxml"
] |
Replicate CKAN instance (installation from source) to another server | 38,869,682 | <p><strong>Problem:</strong> I would like to replicate a CKAN instance which has been installed from source to another server. The aim is that the new server will be used for staging any updates developed into the development server (CKAN is already installed there) and will be pushed to the productions server to updat... | 0 | 2016-08-10T09:41:37Z | 38,892,330 | <p>Maybe you can check this <a href="https://github.com/govro/datagovro/blob/master/provisioning/playbook.yml" rel="nofollow">Ansible playbook</a> that sets up a new installation from source. It's based on the original docs.</p>
| 0 | 2016-08-11T09:24:45Z | [
"python",
"postgresql",
"ckan"
] |
python tkinter.ttk combobox down event on mouseclick | 38,869,807 | <p>I do not find a correct answer to my issue, despite intense research and a rather simple problem.
All I would like to do, is my comboboxes drop down when clicked on by 'Button-1'. But regardless of what I code, the combos don't behave as I wish.</p>
<p>following I prepared a simple code to demonstrate my problem:</... | 0 | 2016-08-10T09:46:30Z | 38,870,662 | <p>Why are you using <code>int(evt.type) is 4</code> instead of <code>int(evt.type) == 4</code> ?</p>
<p>Applying this change it works for me.</p>
<p><b>Edit 1</b></p>
<p>First of all, thank you for explaining to us what you really want to have. Did not expect this from your initial question.</p>
<p>If you want to ... | 0 | 2016-08-10T10:22:46Z | [
"python",
"events",
"combobox",
"tkinter",
"ttk"
] |
How to redirect to a URL binding multi routes in Flask | 38,869,853 | <p>Flask code:</p>
<pre><code>@app.route('/debug')
@app.route('/debug/sample')
def debug():
pass
</code></pre>
<p>Jinja2 code:</p>
<pre><code>{{ url_for('app.debug') }}
</code></pre>
<p>How to control the real url that Jinja2 will redirect?</p>
| 1 | 2016-08-10T09:48:27Z | 38,875,100 | <p>Give each rule a different endpoint value. The default is the name of the decorated function, so both currently have the same name and the last registered takes precedence.</p>
<pre><code>@app.route('/debug/sample', endpoint='debug_sample')
@app.route('/debug')
def debug():
pass
</code></pre>
<pre><code>url_... | 2 | 2016-08-10T13:39:14Z | [
"python",
"flask"
] |
Get latest object with filter in django rest framework | 38,869,894 | <p>When I request GET through DRF API, I want to return the latest object.
I tried this one in views.py: </p>
<pre><code>class ListCreateNodeConfig(generics.ListCreateAPIView):
queryset = models.NodeConfig.objects.all()
serializer_class = serializers.NodeConfigSerializer
def get_queryset(self):
re... | 0 | 2016-08-10T09:50:28Z | 38,879,437 | <p>The porblem here ist the <code>latest()</code> method. This does not return a queryset but a single model instance. (like <code>get(...)</code>)</p>
<p>so use:</p>
<pre><code>def get_queryset(self):
return self.queryset.filter(node_id=self.kwargs.get('node_pk')).order_by('-timestamp')
</code></pre>
<p>So if y... | 2 | 2016-08-10T16:58:11Z | [
"python",
"django",
"django-rest-framework"
] |
How to convert list of ints into list of lists? | 38,869,937 | <p>The problem is: how to convert properly (in "pythonic way") list of ints: <code>[1, 3, 7, 6]</code> into corresponding list of lists: <code>[[1], [3], [7], [6]]</code> with ints inside of them?</p>
<p>Tried to do it like: <code>unsorted_list = [list(str(x)) for x in unsorted_list]</code> but get <code>[['1'], ['3']... | 1 | 2016-08-10T09:52:34Z | 38,869,989 | <p>us like this</p>
<pre><code>unsorted_list = [[x] for x in unsorted_list]
</code></pre>
<p>or you can use:</p>
<pre><code>unsorted_list = map(lambda x:[x], unsorted_list)
</code></pre>
| -2 | 2016-08-10T09:54:54Z | [
"python",
"list"
] |
How to convert list of ints into list of lists? | 38,869,937 | <p>The problem is: how to convert properly (in "pythonic way") list of ints: <code>[1, 3, 7, 6]</code> into corresponding list of lists: <code>[[1], [3], [7], [6]]</code> with ints inside of them?</p>
<p>Tried to do it like: <code>unsorted_list = [list(str(x)) for x in unsorted_list]</code> but get <code>[['1'], ['3']... | 1 | 2016-08-10T09:52:34Z | 38,870,013 | <p>You shouldn't transform the integers to strings. Simply:</p>
<pre><code>[[x] for x in unsorted_list]
</code></pre>
| 5 | 2016-08-10T09:56:15Z | [
"python",
"list"
] |
How to convert list of ints into list of lists? | 38,869,937 | <p>The problem is: how to convert properly (in "pythonic way") list of ints: <code>[1, 3, 7, 6]</code> into corresponding list of lists: <code>[[1], [3], [7], [6]]</code> with ints inside of them?</p>
<p>Tried to do it like: <code>unsorted_list = [list(str(x)) for x in unsorted_list]</code> but get <code>[['1'], ['3']... | 1 | 2016-08-10T09:52:34Z | 38,870,050 | <p>Another aproach, using <code>map</code>:</p>
<pre><code>map(lambda x: [x], unsorted_list)
</code></pre>
| 1 | 2016-08-10T09:57:50Z | [
"python",
"list"
] |
Consuming from multiple queues at once with aioamqp | 38,869,959 | <p>Is it possible to consume multiple queues at once using one channel with aioamqp?</p>
<p>Disclaimer: I created an <a href="https://github.com/Polyconseil/aioamqp/issues/105" rel="nofollow">issue</a> in the project issue tracker but I'm really wondering if what I'm doing makes sense at all.</p>
| 0 | 2016-08-10T09:53:34Z | 38,870,898 | <p><s>I think that this feature is not available in AMQP protocol (assuming my understanding of the protocol is correct).</p>
<p>If you wish to consume from a queue you have to issue <code>basic.consume</code> call on a channel. The required argument for this call is <code>queue_name</code> and it's a "blocking" (not ... | 1 | 2016-08-10T10:31:46Z | [
"python",
"rabbitmq",
"python-asyncio"
] |
Why object is taking last value in list? | 38,870,007 | <p>Why object is taking last value in list </p>
<pre><code>ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; row_data = {} ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data['background-color'] = ddd[met... | 1 | 2016-08-10T09:55:34Z | 38,870,149 | <p>Just move row_data in inner loop.</p>
<pre><code>ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data = {}
row_data['background-color'] = ddd[me... | 0 | 2016-08-10T10:01:39Z | [
"python",
"list",
"loops",
"dictionary"
] |
update matrix values in python | 38,870,039 | <p>I need to update matrix values with elements in list. When i use for loop to iterate the index of matrix and include the elements in list. only the last value is updated as it is the last value of the iterator.</p>
<p>But i need the sequence of the list to be added in the matrix.
please let me know if there could b... | 0 | 2016-08-10T09:57:23Z | 38,870,299 | <p>In the most inside loop:</p>
<pre><code> for k in range(len(n)):
m[i][j]=n[k]
</code></pre>
<p><code>i</code> and <code>j</code> doesn't changes, so you assign <code>n[i][j]=n[0]</code> and then <code>n[i][j]=n[1]</code>, <code>n[i][j]=n[2]</code>, <code>n[i][j]=n[3]</code> and just the last o... | 0 | 2016-08-10T10:07:07Z | [
"python",
"matrix",
"iteration"
] |
Python 2.7: Extract values from same dictionary in multiple functions | 38,870,081 | <p>I have a dictionary which is going to be passed to multiple functions. In each of the functions, I need to extract all the values of the dictionary.</p>
<p>For example,</p>
<pre><code>def foo(mas_details):
# Extract mas details
if 'ip' in mas_details.keys():
mas_ip = mas_details['ip']
else:
... | 0 | 2016-08-10T09:58:44Z | 38,870,331 | <p>Well, if you simply need all the 6 variables in a function, you can destruct the dictionary, i.e.</p>
<pre><code>def f1(arg1, arg2, ..., arg6):
...
def f2(arg1, arg2, ..., arg6):
...
# initialize dictionary
d = {'arg1': 'val1', 'arg2': 'val2', ...}
# fill default values (or use defaultdict with appropriate... | 0 | 2016-08-10T10:08:50Z | [
"python",
"python-2.7",
"dictionary"
] |
Python 2.7: Extract values from same dictionary in multiple functions | 38,870,081 | <p>I have a dictionary which is going to be passed to multiple functions. In each of the functions, I need to extract all the values of the dictionary.</p>
<p>For example,</p>
<pre><code>def foo(mas_details):
# Extract mas details
if 'ip' in mas_details.keys():
mas_ip = mas_details['ip']
else:
... | 0 | 2016-08-10T09:58:44Z | 38,870,640 | <p>The code can be made a lot smaller:</p>
<pre><code>'username' in mas_details.keys():
</code></pre>
<p>The keys() is superfluous, it's equal to </p>
<pre><code>'username' in mas_details
</code></pre>
<p>But more importantly,</p>
<pre><code>if 'username' in mas_details.keys():
mas_username = mas_details['user... | 2 | 2016-08-10T10:21:26Z | [
"python",
"python-2.7",
"dictionary"
] |
filtering out some elements in matrix in python | 38,870,160 | <p>I have a list of lists (matrix). I want to filter out those lists in my matrix with even one 0 and export the results to a .txt file.</p>
<p>input example:</p>
<pre><code>[['ENSG00000137288.5', '0,803921621', '0', '0,435897439', '1,384615397', '0,894736842', '1,151515086', '1,25', '1,2'], ['ENSG00000116032.5', '1,... | -1 | 2016-08-10T10:01:59Z | 38,870,626 | <p>I found a method if helps:-</p>
<pre><code> a = [['ENSG00000137288.5', '0,803921621', '0', '0,435897439', '1,384615397', '0,894736842', '1,151515086', '1,25', '1,2'], ['ENSG00000116032.5', '1,531746311', '2,67857148', '2', '3,0250002', '1,758620722', '1,571428459', '1,028571488', '1,294117703'], ['ENSG0000016757... | 0 | 2016-08-10T10:20:51Z | [
"python"
] |
How can I sum integers line by line until a new line and then start again? | 38,870,200 | <p>I have a file like this:</p>
<pre><code>1
2
3
5
0
5
2
3
</code></pre>
<p>What I want to do is to sum the integers until the newline and then start to sum again, so the result would be:</p>
<pre><code>6
5
10
</code></pre>
<p>What I have so far is:</p>
<pre><code>import sys
def readText(filename):
sum = ... | 1 | 2016-08-10T10:03:16Z | 38,870,366 | <p>move <code>print (sum)</code> before the the <code>sum = 0</code> and you'll be fine</p>
<p>Note that the line <code>sum = 0</code> in the loop makes you sum from the start (and you "forget" all previous numbers...)</p>
<p><em>print sum is for python 2 and I use 3, hence the print (sum) in the print method</em></p... | 1 | 2016-08-10T10:10:13Z | [
"python",
"integer",
"sum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.