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 |
|---|---|---|---|---|---|---|---|---|---|
How to re-order my Pandas dataframe other than using the "columns.tolist()" method? I want a particular column to appear last always | 37,897,029 | <p>my dataframe is like this:</p>
<pre><code>In [57]: final_data
Out[57]:
monthyear Date Planned CCM1 CCM2
0 Dec 15 2015-12-01 0.0 0.000000 2550.000000
1 Feb 16 2016-02-01 0.0 0.000000 4250.000000
2 Jan 16 2016-01-01 0.0 1540.0000... | 1 | 2016-06-18T12:36:24Z | 37,921,529 | <p>Finally found a dumb way to solve my problem:</p>
<pre><code>In [99]: final_data
Out[99]:
Facility monthyear Date Planned CCM1 CCM2
0 Dec 15 2015-12-01 0.0 0.000000 2550.000000
1 Feb 16 2016-02-01 0.0 0.000000 4250.000000
2 Jan 16 2016-01-01 ... | 2 | 2016-06-20T11:35:28Z | [
"python",
"pandas"
] |
Tweepy Get Tweets in reply to a particular tweet | 37,897,064 | <p>So I've been doing a lot of work with Tweepy and Twitter data mining, and one of the things I want to do is to be able to get all Tweets that are replies to a particular Tweet. I've seen the Search api, but I'm not sure how to use it nor how to search specifically for Tweets in reply to a specific Tweet. Anyone have... | -1 | 2016-06-18T12:39:55Z | 37,902,045 | <p>I've created a workaround that kind of works. The best way to do it is to search for mentions of a user, then filter those mentions by in_reply_to_id .</p>
| 0 | 2016-06-18T22:03:18Z | [
"python",
"search",
"twitter",
"tweepy"
] |
Pandas make new column from substring slice based on the number in a substring of another column | 37,897,125 | <p>I have a dataframe called 'table' like this:</p>
<pre><code>import pandas as pd
import numpy as np
table = pd.read_csv(main_data, sep='\t')
</code></pre>
<p>And it produces this:</p>
<pre><code>NAME SYMBOL STRING
A blah A34SA
B foo BS2812D
...
</code></pre>
<p>How can I create a ne... | 1 | 2016-06-18T12:46:11Z | 37,897,264 | <p>You can try to use a regular expression to extract the number from the String:</p>
<pre><code>import re
def extNumber(row):
row['NUMBER'] = re.search("(\\d+)", row.STRING).group(1)
return row
df.apply(extNumber, axis=1)
</code></pre>
| 1 | 2016-06-18T13:02:51Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Pandas make new column from substring slice based on the number in a substring of another column | 37,897,125 | <p>I have a dataframe called 'table' like this:</p>
<pre><code>import pandas as pd
import numpy as np
table = pd.read_csv(main_data, sep='\t')
</code></pre>
<p>And it produces this:</p>
<pre><code>NAME SYMBOL STRING
A blah A34SA
B foo BS2812D
...
</code></pre>
<p>How can I create a ne... | 1 | 2016-06-18T12:46:11Z | 37,897,275 | <p>The following should work</p>
<pre><code>table['NUMBER'] = table.STRING.apply(lambda x: int(''.join(filter(str.isdigit, x))))
</code></pre>
| 2 | 2016-06-18T13:04:03Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Pandas make new column from substring slice based on the number in a substring of another column | 37,897,125 | <p>I have a dataframe called 'table' like this:</p>
<pre><code>import pandas as pd
import numpy as np
table = pd.read_csv(main_data, sep='\t')
</code></pre>
<p>And it produces this:</p>
<pre><code>NAME SYMBOL STRING
A blah A34SA
B foo BS2812D
...
</code></pre>
<p>How can I create a ne... | 1 | 2016-06-18T12:46:11Z | 37,897,276 | <p>You can use regular expressions.</p>
<pre><code>import re
table['NUMBER'] = table['STRING'].apply(lambda x: re.sub(r'[^0-9]','',x))
</code></pre>
| 2 | 2016-06-18T13:04:21Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Pandas make new column from substring slice based on the number in a substring of another column | 37,897,125 | <p>I have a dataframe called 'table' like this:</p>
<pre><code>import pandas as pd
import numpy as np
table = pd.read_csv(main_data, sep='\t')
</code></pre>
<p>And it produces this:</p>
<pre><code>NAME SYMBOL STRING
A blah A34SA
B foo BS2812D
...
</code></pre>
<p>How can I create a ne... | 1 | 2016-06-18T12:46:11Z | 37,897,515 | <p>I would do it this way:</p>
<pre><code>In [22]: df['NUMBER'] = df.STRING.str.extract('(?P<NUMBER>\d+)', expand=True).astype(int)
In [23]: df
Out[23]:
NAME SYMBOL STRING NUMBER
0 A blah A34SA 34
1 B foo BS2812D 2812
In [24]: df.dtypes
Out[24]:
NAME object
SYMBOL object
STR... | 2 | 2016-06-18T13:28:56Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Modify timestamps to sequence per ID | 37,897,249 | <p>I have a Pandas dataframe (Python 3.5.1) with a timestamp column and an ID column.</p>
<pre><code> Timestamp ID
0 2016-04-01T00:15:36.688 123
1 2016-04-01T00:12:52.688 123
2 2016-04-01T00:35:41.688 543
3 2016-04-01T00:01:12.688 543
4 2016-03-31T23:50:59.688 123
5 2016-04-01T... | 1 | 2016-06-18T13:01:05Z | 37,897,278 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow">sort_values()</a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby()</a> and <a href="http://pandas.pydata.org/pandas-docs/... | 2 | 2016-06-18T13:04:33Z | [
"python",
"pandas"
] |
Simple server/client monitoring tool through sockets in python | 37,897,393 | <p>I have many RPIs for IoT in pubs.<br>
I need to monitor my RPIs and monitor licenses, services, disk space etc...<br>
I have started to work on both server and client.<br><br>
I am stucked, that I don't know, what will be better:<br>
1) Client will have persistent connection with server<br>
2) Client will connect to... | 0 | 2016-06-18T13:17:13Z | 37,897,672 | <p>I would go with "Client will connect to the server only when some data is collected (for example with a cron job every five minutes that collects disk usage)"[edited].</p>
<p>Also, do not overcomplicate your problem: E.g. do not write your own message format or TCP equivalent.</p>
<p>Just use JSON, BSON or XML and... | 0 | 2016-06-18T13:45:26Z | [
"python",
"sockets",
"monitoring"
] |
Random time between given hours using epoch time format | 37,897,472 | <p>I would like to have a random time from given hours range, using epoch time format.
For example, I have this:</p>
<pre><code>start_time = int(time.time())
end_time = start_time + 5184000 # 60 days
random_time = random.randint(start_time, end_time)
</code></pre>
<p>And I want to get random time from 9am to 9pm o... | 0 | 2016-06-18T13:24:32Z | 37,897,885 | <p>If I understood OP right, this will get 3 random times for the next 60 days and each random time is between 9am and 9pm.</p>
<pre><code>import datetime
import random
d = datetime.datetime.today()
d = d.replace(hour=0, minute=0, second=0, microsecond=0)
for days in range(60):
for c in range(3): # OP wanted 3 t... | 1 | 2016-06-18T14:10:43Z | [
"python",
"time",
"epoch"
] |
Random time between given hours using epoch time format | 37,897,472 | <p>I would like to have a random time from given hours range, using epoch time format.
For example, I have this:</p>
<pre><code>start_time = int(time.time())
end_time = start_time + 5184000 # 60 days
random_time = random.randint(start_time, end_time)
</code></pre>
<p>And I want to get random time from 9am to 9pm o... | 0 | 2016-06-18T13:24:32Z | 37,897,917 | <p>Struct time is read only, so cannot be hacked. If random time does not fit, just randomly tweak the hour.</p>
<pre><code>import time,random
start_time = int(time.time())
end_time = start_time + 5184000 # 60 days
random_time = random.randint(start_time, end_time)
ts = time.localtime(random_time)
if 9 <= ts.... | 1 | 2016-06-18T14:13:41Z | [
"python",
"time",
"epoch"
] |
Random time between given hours using epoch time format | 37,897,472 | <p>I would like to have a random time from given hours range, using epoch time format.
For example, I have this:</p>
<pre><code>start_time = int(time.time())
end_time = start_time + 5184000 # 60 days
random_time = random.randint(start_time, end_time)
</code></pre>
<p>And I want to get random time from 9am to 9pm o... | 0 | 2016-06-18T13:24:32Z | 37,903,085 | <blockquote>
<p><strong>Q:</strong> Do you mean you want to get a list of 60 days (the range is given from context) of random minutes from 9am to 9pm?<br>
<strong>A:</strong>
Let's say, yes. Actually, I want 3 random times per day.</p>
</blockquote>
<pre><code>#!/usr/bin/env python
import random
import time
HOU... | 1 | 2016-06-19T01:13:49Z | [
"python",
"time",
"epoch"
] |
How to display a changing value? (Python) | 37,897,483 | <p>I have a Raspberry Pi set up with an Analogue to Digital converter and have a two potentiometer joystick wired to the input.</p>
<p>I can get the values of each potentiometer to display on screen using 'Print' however it displays thousands of lines per minute as the values change when the potentiometers move so it ... | 1 | 2016-06-18T13:25:34Z | 37,908,735 | <p>You could try something like the snippet below. Assuming <code>MCP3008</code> is your converter, it will read the value every 0.1 secs (<code>sleep(0.1)</code>) and if the values are different by 5% (<code>threshold = 0.05</code>) it will <code>print</code> the new value and overwrite the old line (<code>end = '\r'<... | 0 | 2016-06-19T15:14:41Z | [
"python",
"raspberry-pi",
"microcontroller"
] |
get python pandas to_dict with orient='records' but without float cast | 37,897,527 | <p>I have a dataframe with one col int one col floats:</p>
<pre><code>df
# a b
# 0 3 42.00
# 1 2 3.14
df.dtypes
# a int64
# b float64
# dtype: object
</code></pre>
<p>I want a list of dicts like the one provide by <code>df.to_dict(orient='records')</code></p>
<pre><code>df.to_dict(orient='recor... | 3 | 2016-06-18T13:30:20Z | 37,897,753 | <p>Currently (as of Pandas version 0.18), <code>df.to_dict('records')</code> accesses the NumPy array <code>df.values</code>. This property upcasts the dtype of the <code>int</code> column to <code>float</code> so that the array can have a single common dtype. After this point there is no hope of returning the desired ... | 4 | 2016-06-18T13:55:16Z | [
"python",
"pandas"
] |
How to get values in list at incremental indexes in Python? | 37,897,602 | <p>I'm looking at getting values in a list with an increment.</p>
<pre><code>l = [0,1,2,3,4,5,6,7]
</code></pre>
<p>and I want something like: </p>
<pre><code>[0,4,6,7]
</code></pre>
<p>At the moment I am using <code>l[0::2]</code> but I would like sampling to be sparse at the beginning and increase towards the en... | -2 | 2016-06-18T13:38:17Z | 37,897,686 | <p>I am not sure what exact algorithm you want to use, but if it is non-constant, as your example appears to be, then you should consider creating a generator function to yield values:
<a href="https://wiki.python.org/moin/Generators" rel="nofollow">https://wiki.python.org/moin/Generators</a></p>
<p>Depending on what ... | 0 | 2016-06-18T13:47:00Z | [
"python",
"list",
"python-2.7"
] |
How to get values in list at incremental indexes in Python? | 37,897,602 | <p>I'm looking at getting values in a list with an increment.</p>
<pre><code>l = [0,1,2,3,4,5,6,7]
</code></pre>
<p>and I want something like: </p>
<pre><code>[0,4,6,7]
</code></pre>
<p>At the moment I am using <code>l[0::2]</code> but I would like sampling to be sparse at the beginning and increase towards the en... | -2 | 2016-06-18T13:38:17Z | 37,897,846 | <p>Use the <a href="https://docs.python.org/3.5/library/functions.html#slice" rel="nofollow"><code>slice</code></a> function to create a range of indices. You can then extend your sliced list with other slices.</p>
<pre><code>k = [0,1,2,3,4,5,6,7]
r = slice(0,len(k)//2,4)
t = slice(r.stop,None,1)
j = k[r]
j.extend(k[t... | 0 | 2016-06-18T14:05:56Z | [
"python",
"list",
"python-2.7"
] |
How to get values in list at incremental indexes in Python? | 37,897,602 | <p>I'm looking at getting values in a list with an increment.</p>
<pre><code>l = [0,1,2,3,4,5,6,7]
</code></pre>
<p>and I want something like: </p>
<pre><code>[0,4,6,7]
</code></pre>
<p>At the moment I am using <code>l[0::2]</code> but I would like sampling to be sparse at the beginning and increase towards the en... | -2 | 2016-06-18T13:38:17Z | 37,898,161 | <p>What I would do is just use list comprehension to retrieve the values. It is not possible to do it just by indexing. This is what I came up with:</p>
<pre><code>l = [0, 1, 2, 3, 4, 5, 6, 7]
m = [l[0]] + [l[1+sum(range(3, s-1, -1))] for s in [x for x in range(3, 0, -1)]]
</code></pre>
<p>and here is a breakdown of ... | 0 | 2016-06-18T14:39:11Z | [
"python",
"list",
"python-2.7"
] |
How to get values in list at incremental indexes in Python? | 37,897,602 | <p>I'm looking at getting values in a list with an increment.</p>
<pre><code>l = [0,1,2,3,4,5,6,7]
</code></pre>
<p>and I want something like: </p>
<pre><code>[0,4,6,7]
</code></pre>
<p>At the moment I am using <code>l[0::2]</code> but I would like sampling to be sparse at the beginning and increase towards the en... | -2 | 2016-06-18T13:38:17Z | 37,899,168 | <p>This can be more complicated than it sounds... You need a list of indices starting at zero and ending at the final element position in your list, presumably with no duplication (i.e. you don't want to get the same points twice). A generic way to do this would be to define the number of points you want first and then... | 1 | 2016-06-18T16:26:52Z | [
"python",
"list",
"python-2.7"
] |
Set of matrices | 37,897,737 | <p>I have lots of matrices (as result of rotations, etc.), but I would be sure to store them only once. I thought about <em>using a set</em> :</p>
<pre><code>print set([np.matrix([[0, 0],[0, 1],[1, 1],[2, 1]]),
np.matrix([[0, 0],[1, 0],[1, -1],[1, -2]])])
</code></pre>
<p>Unfortunately, I get :</p>
<blockquote>
... | 2 | 2016-06-18T13:52:56Z | 37,899,761 | <pre><code>In [299]: m1
Out[299]:
matrix([[0, 0],
[0, 1],
[1, 1],
[2, 1]])
In [300]: m2
Out[300]:
matrix([[ 0, 0],
[ 1, 0],
[ 1, -1],
[ 1, -2]])
In [297]: set([tuple(m1.A1),tuple(m2.A1)])
Out[297]: {(0, 0, 0, 1, 1, 1, 2, 1), (0, 0, 1, 0, 1, -1, 1, -2)}
</code></pre>... | 0 | 2016-06-18T17:26:34Z | [
"python",
"numpy",
"matrix"
] |
Python 3.5.1 - Give user 3 invalid attempts then terminate pgm (Simple FOR loop) | 37,897,766 | <p>I need assistance (new student - 2 weeks). I'd like to get the most minimal changes possible to this code that allows a user 3 chances at typing in the incorrect values for each conversion in the program. After typing in an incorrect value 3 times, the program should terminate. The only requirement is that the co... | 0 | 2016-06-18T13:56:37Z | 37,898,753 | <p>The easiest for you is probably to make a loop for each prompt like in the following pseudo Python code:</p>
<pre><code># Beginning of prompt
i = 0
while i < 3:
result = float(input(<question>))
if <isok>:
print(<result>)
break
else:
print(<error>)
... | 0 | 2016-06-18T15:40:47Z | [
"python",
"loops",
"for-loop",
"python-3.5"
] |
Embedding album cover in MP4 file using Mutagen | 37,897,801 | <p>I'd like to be able to add album cover into the file using mutagen, however when I add it as a file it returns with:</p>
<blockquote>
<pre><code>File "D:\Download\pandora\renamingMETAEFF.pyw", line 71, in <module>
meta['covr'] = image
File "C:\Users\AMD\AppData\Local\Programs\Python\Python35\lib\site-pack... | 1 | 2016-06-18T14:00:42Z | 37,898,147 | <p>From the <a href="http://mutagen.readthedocs.io/en/latest/api/mp4.html" rel="nofollow">mutagen docs</a>:</p>
<p><code>MP4 meta 'covr' â cover artwork, list of MP4Cover objects (which are tagged strs)</code>.</p>
<p><code>MP4Cover imageformat â format of the image (either FORMAT_JPEG or FORMAT_PNG)</code></p>
... | 0 | 2016-06-18T14:37:43Z | [
"python",
"m4a",
"albumart",
"mutagen"
] |
Sum all xml tag values? | 37,897,822 | <p>This code is supposed to sum the count of comments in this xml document.</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = 'http://python-data.dr-chuck.net/comments_42.xml'
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
print data
for... | 1 | 2016-06-18T14:03:20Z | 37,897,937 | <p>Note the subtle changes.
Because <code><comments></code> contains several <code><comment></code> tags, we first need to find all of them ,only then we can iterate over them and find the <code><count></code> tag.</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = 'http://python-... | 1 | 2016-06-18T14:15:42Z | [
"python",
"elementtree"
] |
Sum all xml tag values? | 37,897,822 | <p>This code is supposed to sum the count of comments in this xml document.</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = 'http://python-data.dr-chuck.net/comments_42.xml'
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
print data
for... | 1 | 2016-06-18T14:03:20Z | 37,897,940 | <p>Your loop logic is wrong. Instead of </p>
<pre><code>for line in data:
tree = ET.fromstring(data)
comments = tree.findall('comments')
name = comments[0].find('comment').find('name').text
count = comments[0].find('comment').find('count').text
count = int(count)
count = count + count
</code>... | 2 | 2016-06-18T14:16:04Z | [
"python",
"elementtree"
] |
return data on_message in python paho mqtt | 37,897,834 | <p>I am implementing a paho mqtt client. Here is my code:</p>
<pre><code>import paho.mqtt.client as mqtt
def mess(client, userdata, message):
print("{'" + str(message.payload) + "', " + str(message.topic) + "}")
def subscribe(c_id, topic, server, port):
cl = mqtt.Client(c_id)
cl.connect(server, port)
c... | 0 | 2016-06-18T14:04:27Z | 37,898,224 | <p>With what you have shown you need to use the <code>global</code> flag to update the <code>data</code> variable outside the function.</p>
<pre><code>data = ''
def mess(client, userdata, message):
global data
data = "{'" + str(message.payload) + "', " + str(message.topic) + "}"
</code></pre>
<p>Also the <code>s... | 1 | 2016-06-18T14:46:35Z | [
"python",
"mqtt",
"paho"
] |
find a method sort NSArray on obj-C what equivalent python sort (timsort) | 37,897,839 | <p>The python server api will check the request signature, and the mechanism is get all values, and sort, then append a secret and md5 hash. But I don't know how to simulate the sort() function in obj-C. There's the python make_sign code:</p>
<pre><code>def make_sign(api_secret, params=[]):
"""
>>> make_s... | 0 | 2016-06-18T14:05:11Z | 37,898,076 | <p>You can sort an instance of <code>NSArray</code> with the <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/#//apple_ref/doc/uid/20000137-SW12" rel="nofollow"><code>-sortedArrayâ¦</code> methods</a>. This starts from simple sorting on a key (for the obje... | 1 | 2016-06-18T14:29:14Z | [
"python",
"objective-c",
"sorting"
] |
Python 3 sorting ignores __lt__ and __eq__ | 37,897,851 | <p>I am using Python 3.5.1 on 64 bit windows. My problem is Python seems to ignore <code>__eq__</code> and <code>__lt__</code> operators on a user-defined class when sorting. Using a <strong>custom sorting key is a workaround that doesn't work</strong> when trying to sort tuples containing instances of this class.</p>
... | 1 | 2016-06-18T14:06:58Z | 37,897,959 | <p>Python does <strong>not</strong> ignore <code>__eq__</code> and <code>__lt__</code>, at least not if you actually used <code>@functools.total_ordering</code>:</p>
<pre><code>>>> from functools import total_ordering
>>> @total_ordering
... class Symbol:
... def __init__(self, name, is_terminal=... | 4 | 2016-06-18T14:17:28Z | [
"python",
"sorting",
"python-3.x"
] |
How to replace all matched (regex) back to the list to remove them without TypeError: expected a string or other character buffer object | 37,897,865 | <p>My file has differents urls:</p>
<pre><code>www.example.com
www.example.com/validagain
www.example.com/search?q=jsdajasj;kdas --> trying to get rid off
www.example.com/anothervalid
</code></pre>
<p>I was able to isolate the <code>/search</code> using regex:</p>
<pre><code>import re
generate_links = re.com... | 0 | 2016-06-18T14:08:12Z | 37,898,129 | <p>If you want to get rid of url containing 'search?' try :</p>
<pre><code>from __future__ import print_function
with open() as in, open() as out:
cured_url = [l for l in in.readlines() if 'search?' not in l]
for url in cured_url:
print(url, file=out)
</code></pre>
| 1 | 2016-06-18T14:35:35Z | [
"python",
"regex",
"python-2.7",
"replace"
] |
Shorter version of this numpy array indexing | 37,897,894 | <p>I have the following code in python (numpy array or scipy.sparse.matrices), it works:</p>
<pre><code>X[a,:][:,b]
</code></pre>
<p>But it doesn't look elegant. 'a' and 'b' are 1-D boolean mask.</p>
<p>'a' has the same length as X.shape[0] and 'b' has the same length as X.shape[1]</p>
<p>I tried <code>X[a,b]</code... | 5 | 2016-06-18T14:11:18Z | 37,898,273 | <p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ix_.html" rel="nofollow"><code>np.ix_</code></a> for such a <code>broadcasted indexing</code>, like so -</p>
<pre><code>X[np.ix_(a,b)]
</code></pre>
<p>Though this won't be any shorter than the original code, but hopefully shou... | 5 | 2016-06-18T14:52:11Z | [
"python",
"numpy",
"matrix",
"indexing"
] |
How to keep Werkzeug from crashing after NGINX closes pipe? | 37,897,926 | <p>I have a Werkzeug server running behind NGINX. When a client disconnects while waiting for the Werkzeug server to respond, NGINX closes the pipe to Werkzeug. When the python program writes the response to Werkzeug, the following exception occurs and Werkzeug crashes:</p>
<blockquote>
<p>Traceback (most recent cal... | 0 | 2016-06-18T14:14:35Z | 37,899,492 | <p>As far as I can guess from the debug trace and without reading the source code, you are probably closing the socket prematurely.</p>
<blockquote>
<p>Your server process has received a SIGPIPE writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might b... | 0 | 2016-06-18T16:59:17Z | [
"python",
"flask",
"werkzeug"
] |
Missing DB table for django-background-tasks | 37,898,013 | <p>I'd like to regularly run a backend task in my Django app and found django-background-tasks (<a href="https://pypi.python.org/pypi/django-background-tasks" rel="nofollow">https://pypi.python.org/pypi/django-background-tasks</a>).</p>
<p>Following the page, I</p>
<ul>
<li>pip installed the package</li>
<li>added it... | 0 | 2016-06-18T14:23:18Z | 37,898,181 | <p>As Moses and Ravi suggested, <code>python manage.py makemigrations background_task</code> needs to be ran first so that <code>python manage.py migrate</code> can create the table.</p>
| 2 | 2016-06-18T14:41:12Z | [
"python",
"django"
] |
Memory issues while parsing json file in ijson | 37,898,065 | <p>This tutorial <a href="https://www.dataquest.io/blog/python-json-tutorial/" rel="nofollow">https://www.dataquest.io/blog/python-json-tutorial/</a> has a 600MB file that they work with, however when I run their code</p>
<pre><code>import ijson
filename = "md_traffic.json"
with open(filename, 'r') as f:
object... | 2 | 2016-06-18T14:27:45Z | 37,898,352 | <p>This looks like a direct copy/paste of the tutorial found here:</p>
<p><a href="https://www.dataquest.io/blog/python-json-tutorial/" rel="nofollow">https://www.dataquest.io/blog/python-json-tutorial/</a></p>
<p>The reason it's taking so long is the <code>list()</code> around the output of the <code>ijson.items</co... | 0 | 2016-06-18T14:59:54Z | [
"python",
"json"
] |
Memory issues while parsing json file in ijson | 37,898,065 | <p>This tutorial <a href="https://www.dataquest.io/blog/python-json-tutorial/" rel="nofollow">https://www.dataquest.io/blog/python-json-tutorial/</a> has a 600MB file that they work with, however when I run their code</p>
<pre><code>import ijson
filename = "md_traffic.json"
with open(filename, 'r') as f:
object... | 2 | 2016-06-18T14:27:45Z | 37,898,629 | <p>I tried running your code and I killed the program after 25 minutes. So yes 10 minutes it's reasonable fast.</p>
| 0 | 2016-06-18T15:28:42Z | [
"python",
"json"
] |
python: boolean array to polygon | 37,898,113 | <p>I have a boolean array with one connected component of <code>True</code> values, the border of which I would like to convert to a polygon, e.g. in shapely. </p>
<p>Assuming my array is <code>img</code>, I can get the border indices like this</p>
<pre><code>import numpy as np
from skimage.morphology binary_erosion
... | 1 | 2016-06-18T14:33:28Z | 39,694,069 | <p>It sounds like <code>rasterio.features.shapes</code> is what you are looking for. A simple example that should illustrate the procedure:</p>
<pre><code>import rasterio.features
import shapely.geometry
import numpy as np
im = np.zeros([5, 5], dtype=np.uint8)
im[1:-1, 1:-1] = 1
shapes = rasterio.features.shapes(im)... | 0 | 2016-09-26T02:56:05Z | [
"python",
"shapely"
] |
pydbus: How to publish an object? | 37,898,144 | <p>I want to publish a python object on a session bus, using <strong>pydbus</strong> and <strong>python 2.7</strong>. I'm new to pydbus, so I stick to the example and did the tutorial. However, I did not manage to launch a simply test server with pydbus. </p>
<p>I wrote a simple class, with only one method, which retu... | 0 | 2016-06-18T14:37:26Z | 37,898,177 | <p>To register a dbus object :</p>
<pre><code>import dbus
bus = dbus.SessionBus()
class Foo(dbus.service.Object):
"""
"""
def __init__(self, path):
super(Foo, self).__init__(bus, path)
# A method
@dbus.service.method(<dbus_interface_name>,
in_signature="", out_signa... | 0 | 2016-06-18T14:40:49Z | [
"python",
"python-2.7",
"dbus"
] |
pydbus: How to publish an object? | 37,898,144 | <p>I want to publish a python object on a session bus, using <strong>pydbus</strong> and <strong>python 2.7</strong>. I'm new to pydbus, so I stick to the example and did the tutorial. However, I did not manage to launch a simply test server with pydbus. </p>
<p>I wrote a simple class, with only one method, which retu... | 0 | 2016-06-18T14:37:26Z | 37,901,583 | <p>As described in Readme:
"Since 0.5, it supports publishing objects on the bus - however this requires GLib 2.46 or newer."</p>
<p>Unfortunately there is no way to publish objects with older GLib.</p>
| 2 | 2016-06-18T21:01:38Z | [
"python",
"python-2.7",
"dbus"
] |
Extract substring between specific characters | 37,898,186 | <p>I have some strings like:</p>
<pre><code>\i{}Agrostis\i0{} <L.>
</code></pre>
<p>I would like to get rid of the '\i{}', '\io{}' characters, so that I could get just:</p>
<pre><code>Agrostis <L.>
</code></pre>
<p>I've tried the following code (adapted from <a href="https://stackoverflow.com/questions/... | 0 | 2016-06-18T14:41:35Z | 37,898,229 | <p>Use <code>s.replace('\i{}', '')</code> and <code>s.replace('\io{}', '')</code></p>
| 2 | 2016-06-18T14:47:01Z | [
"python",
"regex"
] |
Extract substring between specific characters | 37,898,186 | <p>I have some strings like:</p>
<pre><code>\i{}Agrostis\i0{} <L.>
</code></pre>
<p>I would like to get rid of the '\i{}', '\io{}' characters, so that I could get just:</p>
<pre><code>Agrostis <L.>
</code></pre>
<p>I've tried the following code (adapted from <a href="https://stackoverflow.com/questions/... | 0 | 2016-06-18T14:41:35Z | 37,898,274 | <p>You ca do this in different ways.</p>
<p>The simplest one is to use str.replace</p>
<pre><code>s = '''\i{}Agrostis\i0{} <L.>'''
s2 = s.replace('''\i{}''', '').replace('''\i0{}''', '')
</code></pre>
<p>Another way is to use <code>re.sub()</code></p>
| 1 | 2016-06-18T14:52:19Z | [
"python",
"regex"
] |
Extract substring between specific characters | 37,898,186 | <p>I have some strings like:</p>
<pre><code>\i{}Agrostis\i0{} <L.>
</code></pre>
<p>I would like to get rid of the '\i{}', '\io{}' characters, so that I could get just:</p>
<pre><code>Agrostis <L.>
</code></pre>
<p>I've tried the following code (adapted from <a href="https://stackoverflow.com/questions/... | 0 | 2016-06-18T14:41:35Z | 37,898,285 | <p>You can either use <code>s.replace('\i{}', '')</code> and <code>s.replace('\io{}', '')</code>, as Julien said, or, continuing with the regex approach, change your pattern to:</p>
<p><code>re.search('\i{}(.+?)\i0(.++)', item_name)</code></p>
<p>And use <code>m.group(1).strip('\\') + m.group(2).strip('\\')</code> as... | 0 | 2016-06-18T14:53:21Z | [
"python",
"regex"
] |
Extract substring between specific characters | 37,898,186 | <p>I have some strings like:</p>
<pre><code>\i{}Agrostis\i0{} <L.>
</code></pre>
<p>I would like to get rid of the '\i{}', '\io{}' characters, so that I could get just:</p>
<pre><code>Agrostis <L.>
</code></pre>
<p>I've tried the following code (adapted from <a href="https://stackoverflow.com/questions/... | 0 | 2016-06-18T14:41:35Z | 37,898,292 | <p>You need to use the <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> function.</p>
<pre><code>In [34]: import re
In [35]: s = "\i{}Agrostis\i0{} <L.>"
In [36]: re.sub(r'\\i\d*{}', '', s)
Out[36]: 'Agrostis <L.>'
</code></pre>
| 1 | 2016-06-18T14:53:56Z | [
"python",
"regex"
] |
Extract substring between specific characters | 37,898,186 | <p>I have some strings like:</p>
<pre><code>\i{}Agrostis\i0{} <L.>
</code></pre>
<p>I would like to get rid of the '\i{}', '\io{}' characters, so that I could get just:</p>
<pre><code>Agrostis <L.>
</code></pre>
<p>I've tried the following code (adapted from <a href="https://stackoverflow.com/questions/... | 0 | 2016-06-18T14:41:35Z | 37,898,487 | <p>You could use a <em>character class</em> along with <code>re.sub()</code></p>
<pre><code>import re
regex = r'\\i[\d{}]+'
string = "\i{}Agrostis\i0{} <L.>"
string = re.sub(regex, '', string)
print string
</code></pre>
<p>See <a href="http://ideone.com/6Nwctc" rel="nofollow"><strong>a demo on ideone.com</stro... | 1 | 2016-06-18T15:13:43Z | [
"python",
"regex"
] |
Django model instance custom method | 37,898,249 | <p>I'm trying to integrate a custom method on a Django model</p>
<pre><code>class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=200)
text = MarkdownField()
slug = models.SlugField(unique=True, blank=True)
created ... | 0 | 2016-06-18T14:49:28Z | 37,898,287 | <p>You're not updating the <code>slug</code> of your model. Add <code>self.slug = slug</code> at the end of <code>generate_unique_slug</code>:</p>
<pre><code>def generate_unique_slug(self):
# your code
self.slug = slug
</code></pre>
| 1 | 2016-06-18T14:53:28Z | [
"python",
"django",
"django-models"
] |
Django model instance custom method | 37,898,249 | <p>I'm trying to integrate a custom method on a Django model</p>
<pre><code>class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=200)
text = MarkdownField()
slug = models.SlugField(unique=True, blank=True)
created ... | 0 | 2016-06-18T14:49:28Z | 37,898,309 | <p><code>generate_unique_slug</code> neither change any instance attribute nor return anything.</p>
<p>You should change <code>slug</code> in <code>slug = "%s-%d" % (orig[:max_length - len(str(x)) - 1], x)</code> to <code>self.slug = ...</code>.</p>
| 0 | 2016-06-18T14:55:51Z | [
"python",
"django",
"django-models"
] |
Django model instance custom method | 37,898,249 | <p>I'm trying to integrate a custom method on a Django model</p>
<pre><code>class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=200)
text = MarkdownField()
slug = models.SlugField(unique=True, blank=True)
created ... | 0 | 2016-06-18T14:49:28Z | 37,898,422 | <p>This answer does not fix your code, but I think it is a good option as it covers multiple cases.</p>
<p>There is a library called <a href="https://github.com/un33k/django-uuslug" rel="nofollow">uuslug</a> designed to do exactly this. It might be worth checking out.</p>
<p>A example from the repository:</p>
<pre><... | 0 | 2016-06-18T15:06:36Z | [
"python",
"django",
"django-models"
] |
Convert a list of values to a time series in python | 37,898,295 | <p>I want to convert the foll. data:</p>
<pre><code>jan_1 jan_15 feb_1 feb_15 mar_1 mar_15 apr_1 apr_15 may_1 may_15 jun_1 jun_15 jul_1 jul_15 aug_1 aug_15 sep_1 sep_15 oct_1 oct_15 nov_1 nov_15 dec_1 dec_15
0 0 0 0 0 1 1 2 2 2 ... | 2 | 2016-06-18T14:54:38Z | 37,898,493 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a>:</p>
<pre><code>#add last value - 31 dec by value of last column of df
df['dec_31'] = df.iloc[:,-1]
#convert to datetime - see http://strftime.org/
df.columns = pd.to... | 1 | 2016-06-18T15:14:25Z | [
"python",
"datetime",
"numpy",
"pandas",
"time-series"
] |
Convert a list of values to a time series in python | 37,898,295 | <p>I want to convert the foll. data:</p>
<pre><code>jan_1 jan_15 feb_1 feb_15 mar_1 mar_15 apr_1 apr_15 may_1 may_15 jun_1 jun_15 jul_1 jul_15 aug_1 aug_15 sep_1 sep_15 oct_1 oct_15 nov_1 nov_15 dec_1 dec_15
0 0 0 0 0 1 1 2 2 2 ... | 2 | 2016-06-18T14:54:38Z | 37,898,587 | <p>IIUC you can do it this way:</p>
<pre><code>In [194]: %paste
# transpose DF, rename columns
x = df.T.reset_index().rename(columns={'index':'date', 0:'val'})
# parse dates
x['date'] = pd.to_datetime(x['date'], format='%b_%d')
# group resampled DF by the month and resample(`D`) each group
result = (x.groupby(x['date... | 2 | 2016-06-18T15:23:37Z | [
"python",
"datetime",
"numpy",
"pandas",
"time-series"
] |
Why does a frame keep a non null size when emptied? | 37,898,298 | <p>I have a list of tasks to do. That list has several subgroups, that I want to display together. To do so I created a frame for each subgroup and display each tasks in the corresponding frame with grid(). Once a task is done, I destroy the corresponding label.</p>
<p>When a subgroup is empty from the start, tkinter ... | 2 | 2016-06-18T14:54:45Z | 37,898,895 | <p>Tkinter will not resize a Frame if it contains no child widgets. So if you had a callback that removed all your labels at once the Frame wouldn't resize at all. A simple (if somewhat kludgy) workaround is to add a dummy Frame widget to <code>frame1</code>. Eg, add this line</p>
<pre><code>tk.Frame(frame1).grid()
</... | 3 | 2016-06-18T15:55:38Z | [
"python",
"tkinter"
] |
Convert GraphFrames ShortestPath Map into DataFrame rows in PySpark | 37,898,313 | <p>I am trying to find the most efficient way to take the Map output from the GraphFrames function shortestPaths and flatten each vertex's distances map into individual rows in a new DataFrame. I've been able to do it very clumsily by pulling the distances column into a dictionary and then convert from there into a pan... | 1 | 2016-06-18T14:56:03Z | 37,902,151 | <p>You can explode:</p>
<pre><code>>>> from pyspark.sql.functions import explode
>>> results.select("id", explode("distances"))
</code></pre>
| 0 | 2016-06-18T22:19:45Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe",
"graphframes"
] |
Python unittest skip particular step in main application | 37,898,366 | <p>I have a temperature application that takes user input (what units, temperature) to convert between different temperature units. It involves prompting the user for these units and numbers, through the normal str(input(xyz)) and float(input(123)) type of prompts, after which the rest of the application takes that dat... | 1 | 2016-06-18T15:01:36Z | 37,898,546 | <p>When you have a module with a function call like</p>
<pre><code>main()
</code></pre>
<p>it will be invoked on import of the module.</p>
<p>You can avoid that by wrapping it in the conditional</p>
<pre><code>if __name__ == '__main__':
main()
</code></pre>
<p>Then <code>main</code> will only be called when th... | 1 | 2016-06-18T15:19:07Z | [
"python",
"unit-testing",
"user-input"
] |
Python unittest skip particular step in main application | 37,898,366 | <p>I have a temperature application that takes user input (what units, temperature) to convert between different temperature units. It involves prompting the user for these units and numbers, through the normal str(input(xyz)) and float(input(123)) type of prompts, after which the rest of the application takes that dat... | 1 | 2016-06-18T15:01:36Z | 37,898,589 | <p>You have to mock your input methods to return mocked value. See <a href="https://docs.python.org/3/library/unittest.mock.html" rel="nofollow">unittest.mock</a> for reference of how to add mocking. Also consider reading <a href="http://alexmarandon.com/articles/python_mock_gotchas/" rel="nofollow">Python common mock ... | 0 | 2016-06-18T15:23:58Z | [
"python",
"unit-testing",
"user-input"
] |
Why can't I create a custom user in Django using the UserCreationForm? | 37,898,450 | <p>I am able to create a user from shell by importing the custom user model but when I apply the same method after submitting the form, the user is not created.
Below are the codes of my custom user model, <code>UserCreationForm</code> and view.</p>
<pre><code>//model.py
class MyUser(AbstractBaseUser):
email = mod... | 0 | 2016-06-18T15:09:01Z | 37,902,472 | <pre><code>def register(request):
# this is the logged-in user
user = request.user
if request.method == 'POST':
# this is the form with the submitted data
form = UserCreationForm(data=request.POST)
if form.is_valid():
# the submitted data is correct
my_u... | 0 | 2016-06-18T23:13:28Z | [
"python",
"django",
"forms",
"user",
"registration"
] |
Using while loop to find smallest user input number | 37,898,473 | <p>Hey guys I cannot figure out how to use a while loop to find the smallest number entered by a user. I know I have to assign a number entered to stop the program then print the smallest number that was entered. This is what I have so far:</p>
<pre><code>while(True):
A = int(input("Enter a Number (Use -1 to Stop)... | 1 | 2016-06-18T15:12:23Z | 37,898,504 | <p>You could easily store all the values in a list and then use <code>min</code>, but if you insist not to:</p>
<pre><code>min_val = None
while True:
A = int(input("Enter a Number (Use -1 to Stop): " ))
if A == -1:
break
if not min_val or A < min_val:
min_val = A
</code></pre>
<p>The ... | 1 | 2016-06-18T15:16:01Z | [
"python",
"input",
"while-loop"
] |
Using while loop to find smallest user input number | 37,898,473 | <p>Hey guys I cannot figure out how to use a while loop to find the smallest number entered by a user. I know I have to assign a number entered to stop the program then print the smallest number that was entered. This is what I have so far:</p>
<pre><code>while(True):
A = int(input("Enter a Number (Use -1 to Stop)... | 1 | 2016-06-18T15:12:23Z | 37,898,511 | <p>Initialize the number before the loop, then update its value if the new number is less. This should do:</p>
<pre><code># initialize minimum
minimum = int(input("Enter a Number: " ))
while(True):
A = int(input("Enter a Number (Use -1 to Stop): " ))
if(A == -1):
break
if minimum > A:
mi... | 1 | 2016-06-18T15:16:29Z | [
"python",
"input",
"while-loop"
] |
Using while loop to find smallest user input number | 37,898,473 | <p>Hey guys I cannot figure out how to use a while loop to find the smallest number entered by a user. I know I have to assign a number entered to stop the program then print the smallest number that was entered. This is what I have so far:</p>
<pre><code>while(True):
A = int(input("Enter a Number (Use -1 to Stop)... | 1 | 2016-06-18T15:12:23Z | 37,898,543 | <p>Code below would suit your need:</p>
<pre><code>b = -1
while(True):
A = int(input("Enter a Number (Use -1 to Stop): " ))
if(A == -1):
print b
break
b = b if A > b else A
</code></pre>
<p><strong>Good Luck !</strong></p>
| 1 | 2016-06-18T15:19:03Z | [
"python",
"input",
"while-loop"
] |
cannot use pexpect of python in cygwin | 37,898,514 | <p>I was trying to use pexpect in cygwin, but failed.
I try to install it like:
pexpect-4.1>python ./setup.py install</p>
<p>But when I run the examples inside pexpect-4.1. It outputs:</p>
<pre><code>Traceback (most recent call last):
File "./examples/uptime.py", line 54, in <module>
p = pexpect.spawnu('u... | 1 | 2016-06-18T15:16:53Z | 37,901,634 | <p>You probably use Windows version of python where <code>sys.platform == 'win32'</code> instead of <code>sys.platform == 'cygwin'</code>. There is no <code>spawnu</code> on Windows' <a href="https://github.com/pexpect/pexpect/blob/38ed591f830d575ac83640549820ce43c15ccb88/pexpect/__init__.py#L73-L75" rel="nofollow"><co... | 2 | 2016-06-18T21:07:07Z | [
"python",
"cygwin",
"pexpect"
] |
What's the difference between template include and static include in Django? | 37,898,559 | <p>I'm trying to learn Django at the moment and am trying to make sure I'm not doing anything stupid.</p>
<p>I'm in the process of making my web page more modular in the sense that I am removing hardcoded values in the template (base .html). Doing so, I'm trying to convert hardcoded CDN references (jquery, bootstrap, ... | 1 | 2016-06-18T15:19:55Z | 37,898,925 | <blockquote>
<p>Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as âstatic filesâ. </p>
</blockquote>
<p>We call them 'static' simply because they aren't dynamic i.e the contents of these files are relatively fixed, either by design or by i... | 1 | 2016-06-18T15:59:03Z | [
"python",
"django"
] |
Having problems feeding data to tensorflow graph | 37,898,617 | <p>I am trying to adjust the MNIST2 problem in tensorflow tutorial to train a neural network using my own images. But I am having problems feeding data to the graph.</p>
<pre><code>My code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
impo... | 0 | 2016-06-18T15:27:58Z | 37,901,033 | <p>You are trying to feed the <code>feed_dict</code> argument with TensorFlow tensors. TensorFlow then tries to convert these <code>tf.Tensor</code> to numpy arrays but cannot and returns your error.</p>
<p>As you use an input queue, you don't need a <code>feed_dict</code>.</p>
<p>Instead of:</p>
<pre class="lang-py... | 0 | 2016-06-18T19:48:41Z | [
"python",
"numpy",
"tensorflow",
"deep-learning"
] |
Create a Dropdown Menu on Tkinter with Data from excel | 37,898,655 | <p>I'd like to Create a Dropdown Menu on Tkinter via using Tkinter and xlrd.
The Values of the dropdown Menu shall be from an excel-list. So far I only have this:</p>
<pre><code>i = 0
while i < 96:
i = i+1
m=sheet.cell_value(i,1)
print(m)
mbuttonMaterial = Menubutton(tkFenster, text='Material')
pi... | 0 | 2016-06-18T15:31:41Z | 37,900,173 | <p>Assuming you are able to retrieve the items from your excel document, you can try adding them to a dictionary along their varType. Here is a modified example from <a href="http://www.tutorialspoint.com/python/tk_menubutton.htm" rel="nofollow">tutorialspoint</a>:</p>
<pre><code>from tkinter import Tk, Menubutton, Me... | 0 | 2016-06-18T18:13:29Z | [
"python",
"excel",
"tkinter",
"xlrd"
] |
Python regex: XOR operator | 37,898,679 | <p>Suppose I have strings like these:</p>
<ol>
<li><code>"DT NN IN NN"</code></li>
<li><code>"DT RB JJ NN"</code></li>
<li><code>"DT JJ JJ NN"</code></li>
<li><code>"DT RB RB NN NN"</code></li>
<li><code>"DT RB RB"</code></li>
</ol>
<p>So, I have a list of strings:</p>
<pre><code>list = ["DT NN IN NN", "DT RB JJ NN"... | 4 | 2016-06-18T15:34:32Z | 37,898,737 | <p><code>[...]</code> is a <em>character class</em>, you are matching a set of characters that include <code>?</code>, <code>:</code> and <code>+</code> and <code>|</code>, among others. Other than <code>-</code> to mark a series, there are no modifiers or special characters in a character class.</p>
<p>You need to ma... | 1 | 2016-06-18T15:40:01Z | [
"python",
"regex",
"python-2.7"
] |
Python regex: XOR operator | 37,898,679 | <p>Suppose I have strings like these:</p>
<ol>
<li><code>"DT NN IN NN"</code></li>
<li><code>"DT RB JJ NN"</code></li>
<li><code>"DT JJ JJ NN"</code></li>
<li><code>"DT RB RB NN NN"</code></li>
<li><code>"DT RB RB"</code></li>
</ol>
<p>So, I have a list of strings:</p>
<pre><code>list = ["DT NN IN NN", "DT RB JJ NN"... | 4 | 2016-06-18T15:34:32Z | 37,898,762 | <p>The problem is in how you define the presence of <code>RB</code> and <code>JJ</code>. You haven't mentioned that only either of them should be present. This can be achieved by separating them with a <code>|</code> (pipe) and letting either of them repeat one or more times (<code>+</code>). Try changing your pattern ... | 2 | 2016-06-18T15:41:12Z | [
"python",
"regex",
"python-2.7"
] |
Python regex: XOR operator | 37,898,679 | <p>Suppose I have strings like these:</p>
<ol>
<li><code>"DT NN IN NN"</code></li>
<li><code>"DT RB JJ NN"</code></li>
<li><code>"DT JJ JJ NN"</code></li>
<li><code>"DT RB RB NN NN"</code></li>
<li><code>"DT RB RB"</code></li>
</ol>
<p>So, I have a list of strings:</p>
<pre><code>list = ["DT NN IN NN", "DT RB JJ NN"... | 4 | 2016-06-18T15:34:32Z | 37,898,783 | <p>If I understand the question correctly, you can solve this problem by first splitting it into two separate problems:</p>
<ul>
<li><p>A regex that starts with <code>DT</code> followed by one or more <code>RB</code>s followed by one or more <code>NN</code>s:</p>
<pre><code>^DT(\s+DT)*(\s+RB)+(\s+NN)+$
</code></pre><... | 1 | 2016-06-18T15:42:58Z | [
"python",
"regex",
"python-2.7"
] |
changing datetime format with strptime | 37,898,695 | <p>I'm trying to add or minus time from a datetime object and then convert it to strptime but I'm getting an error message.</p>
<p>Here's an example of getting the 'hour' of a datetime object, adding + 1 to it and then trying to use strptime on it;</p>
<pre><code>time1 = datetime.datetime.strptime("09/Sep/2015:08:00:... | 0 | 2016-06-18T15:35:54Z | 37,898,767 | <p><code>time1.hour</code> is an <code>int</code>, <code>1</code> is an <code>int</code>, therfore <code>time3</code> is an <code>int</code>, which is why you are getting this error.</p>
<p>You should also use <code>strftime</code> in your last line, not <code>strptime</code>.</p>
<p>You can use <code>relativedelta</... | 1 | 2016-06-18T15:41:29Z | [
"python",
"datetime",
"formatting",
"strptime"
] |
Export Dictionary with Both Simple Values and Nested Dictionaries to CSV | 37,898,714 | <p>I'm accessing a third-party API that returns a dictionary that contains both simple values and nested (embedded?) dictionaries. I need to convert this to a CSV file, but I need help extracting and exporting specific values from the nested dictionaries.</p>
<p>Here's a simplified example of what I'm getting back:</p... | 0 | 2016-06-18T15:38:02Z | 37,898,847 | <p>If you don't need <code>accounts</code> for anything else you can do:</p>
<pre><code>for account in accounts:
account['LastModifiedBy'] = account['LastModifiedBy']['Name']
</code></pre>
<p>otherwise, <code>.copy()</code> it and do the same. </p>
| 1 | 2016-06-18T15:50:29Z | [
"python",
"csv",
"dictionary"
] |
Tensorflow accuracy at .99 but predictions awful | 37,898,795 | <p>Maybe I'm making predictions wrong?</p>
<p>Here's the project... I have a greyscale input image that I am trying to segment. The segmentation is a simple binary classification (think of foreground vs background). So the ground truth (y) is a matrix of 0's and 1's -- so there's 2 classifications. Oh and the input im... | 2 | 2016-06-18T15:43:48Z | 37,900,801 | <h2>Errors in the code</h2>
<p>There are multiple errors in your code:</p>
<ul>
<li>you shouldn't call <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#softmax_cross_entropy_with_logits" rel="nofollow"><code>tf.nn.sigmoid_cross_entropy_with_logits</code></a> with the output of a softmax layer... | 4 | 2016-06-18T19:21:33Z | [
"python",
"machine-learning",
"neural-network",
"artificial-intelligence",
"tensorflow"
] |
Better way to "copy only the comments from one file" and "prepend it into another file" using python | 37,898,936 | <p>Basically I want to copy comments from one file and add it to the another data.</p>
<p>The file <code>'data_with_comments.txt'</code> can be obtained from pastebin:
<a href="http://pastebin.com/Tixij2yG" rel="nofollow">http://pastebin.com/Tixij2yG</a> </p>
<p>And it looks like this:</p>
<pre><code># coating fil... | -1 | 2016-06-18T16:01:13Z | 37,899,202 | <p>You could use the <a href="http://stackoverflow.com/questions/519633/lazy-method-for-reading-big-file-in-python">lazy opening</a> of a file and then just process the first lines of the file until a non-comment is found if your files contain comments only at the start of them. After finding a line which starts withou... | 1 | 2016-06-18T16:29:21Z | [
"python",
"file-io",
"prepend"
] |
Better way to "copy only the comments from one file" and "prepend it into another file" using python | 37,898,936 | <p>Basically I want to copy comments from one file and add it to the another data.</p>
<p>The file <code>'data_with_comments.txt'</code> can be obtained from pastebin:
<a href="http://pastebin.com/Tixij2yG" rel="nofollow">http://pastebin.com/Tixij2yG</a> </p>
<p>And it looks like this:</p>
<pre><code># coating fil... | -1 | 2016-06-18T16:01:13Z | 37,899,253 | <p>Especially if the data file (test.txt here) is large (as stated by the OP) I would suggest to (where the file is only opened once for read and another file for write):</p>
<ol>
<li>create a temp folder, </li>
<li>prefill a temp file in there with the stripped(!) comment lines, </li>
<li>add the lines from the data ... | 2 | 2016-06-18T16:34:38Z | [
"python",
"file-io",
"prepend"
] |
Better way to "copy only the comments from one file" and "prepend it into another file" using python | 37,898,936 | <p>Basically I want to copy comments from one file and add it to the another data.</p>
<p>The file <code>'data_with_comments.txt'</code> can be obtained from pastebin:
<a href="http://pastebin.com/Tixij2yG" rel="nofollow">http://pastebin.com/Tixij2yG</a> </p>
<p>And it looks like this:</p>
<pre><code># coating fil... | -1 | 2016-06-18T16:01:13Z | 37,899,609 | <p>You already have a great answer using a temporary directory but it is also common to just create a temporary file in the same directory as the target file. On systems where <em>tmp</em> is a separate mount point, you avoid an additional copy of the data when renaming the temporary file. Notice that there is no inter... | 2 | 2016-06-18T17:11:32Z | [
"python",
"file-io",
"prepend"
] |
Better way to "copy only the comments from one file" and "prepend it into another file" using python | 37,898,936 | <p>Basically I want to copy comments from one file and add it to the another data.</p>
<p>The file <code>'data_with_comments.txt'</code> can be obtained from pastebin:
<a href="http://pastebin.com/Tixij2yG" rel="nofollow">http://pastebin.com/Tixij2yG</a> </p>
<p>And it looks like this:</p>
<pre><code># coating fil... | -1 | 2016-06-18T16:01:13Z | 37,900,375 | <p>Following the idea of Dilletant,</p>
<p>For multiple texts and only one comment file we can do this using shell script: </p>
<pre><code># in the directory i have one file called : comment
# and, other many files with file_extension : .txt
for file in *.txt; do cat comments "$file" > foo && mv foo "$... | 1 | 2016-06-18T18:35:13Z | [
"python",
"file-io",
"prepend"
] |
Trying to assign 2-D array of size 6 | 37,898,947 | <pre><code>for i in xrange(6):
arr[i]=map(int,raw_input().strip().split())
</code></pre>
<p>it is showing</p>
<pre><code>IndexError: list assignment index out of range
</code></pre>
| -2 | 2016-06-18T16:02:09Z | 37,899,010 | <p>You have two problems : </p>
<p>First, you do not initialize the list before using it. Thus, <code>arr</code> is used as a list, even though it may have been created as another type of variable. </p>
<p>Second, you want to change the value for index <code>i</code> when there is no value for this index.</p>
<p>You... | 0 | 2016-06-18T16:08:51Z | [
"python",
"python-2.7"
] |
Trying to assign 2-D array of size 6 | 37,898,947 | <pre><code>for i in xrange(6):
arr[i]=map(int,raw_input().strip().split())
</code></pre>
<p>it is showing</p>
<pre><code>IndexError: list assignment index out of range
</code></pre>
| -2 | 2016-06-18T16:02:09Z | 37,899,194 | <p>You could use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to do it:</p>
<pre><code>arr = [map(int, raw_input("enter values for row %d: " % i).strip().split())
for i in xrange(6)]
print arr
</code></pre>
| 1 | 2016-06-18T16:28:27Z | [
"python",
"python-2.7"
] |
Trying to assign 2-D array of size 6 | 37,898,947 | <pre><code>for i in xrange(6):
arr[i]=map(int,raw_input().strip().split())
</code></pre>
<p>it is showing</p>
<pre><code>IndexError: list assignment index out of range
</code></pre>
| -2 | 2016-06-18T16:02:09Z | 37,899,305 | <p>you can do it like this</p>
<pre><code>final=[]
for i in range(6):
final.append(list(map(int,input().split())))
</code></pre>
<p>Now you have all your inputs in a list final</p>
| 0 | 2016-06-18T16:40:10Z | [
"python",
"python-2.7"
] |
error explanation - 'statInter' object has no attribute 'tk' | 37,899,043 | <p>I am trying to create a simple timer in Python and am aiming to build the user interface using classes. I would like to use the classes to initialise user interface. Then in the main text of the body, I would like to add attributes using the .grid and .configure methods. But when I try to do this, the error: 'statIn... | 3 | 2016-06-18T16:11:51Z | 37,899,530 | <p>The reason you get this error is because you never invoke either of the constructors from the classes you're inheriting from (either <code>Button</code> or <code>Entry</code>).</p>
<p>If you change your <code>__init__</code> to be:</p>
<pre><code>def __init__(self, posx, posy):
Button.__init__(self)
self.p... | 1 | 2016-06-18T17:02:22Z | [
"python",
"class",
"python-3.x",
"tkinter",
"tk"
] |
error explanation - 'statInter' object has no attribute 'tk' | 37,899,043 | <p>I am trying to create a simple timer in Python and am aiming to build the user interface using classes. I would like to use the classes to initialise user interface. Then in the main text of the body, I would like to add attributes using the .grid and .configure methods. But when I try to do this, the error: 'statIn... | 3 | 2016-06-18T16:11:51Z | 37,899,815 | <p>The problem is your derived <code>StatInter</code> class (<a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow">CamelCasing</a> the class name as suggested in <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8 - Style Guide for Python Code</a>) doesn't ini... | 4 | 2016-06-18T17:32:53Z | [
"python",
"class",
"python-3.x",
"tkinter",
"tk"
] |
Render image as defined pixel squares HTML5 canvas? | 37,899,060 | <p>I have the following 6x5 image: </p>
<p><a href="http://i.stack.imgur.com/ItSCE.png" rel="nofollow"><img src="http://i.stack.imgur.com/ItSCE.png" alt="6x5 image"></a> </p>
<p>Which appears as so blown up on the canvas:</p>
<p><a href="http://i.stack.imgur.com/wnyJg.png" rel="nofollow"><img src="http://i.stack.img... | 1 | 2016-06-18T16:14:18Z | 37,899,137 | <p>Yes. This is related to how the images are rendered.</p>
<p>When you have an image with colors, you usually have the complete information of the color of every pixel. So a 100x100 image renders perfectly on a 100x100 pizel size.</p>
<p>But when you try to scale <em>UP</em> this image, you have more pixels availabl... | 2 | 2016-06-18T16:23:05Z | [
"python",
"html5",
"canvas",
"interpolation",
"factory"
] |
useing regular expression for column filter | 37,899,154 | <p>I have a <code>pandas</code> <code>DataFrame</code> that contains a year and a title. Some of <code>rows.name</code> are <code>Batman</code>, <code>Catman</code> etc. I am trying to get all rows of the format <code>.*man</code>, using the following expression:</p>
<pre>
t[t.title & re.search(r'.*man', t.title)]
</p... | 0 | 2016-06-18T16:25:25Z | 37,899,181 | <pre><code>t[t.title & (t.title[-3:] == 'man')]
</code></pre>
| 3 | 2016-06-18T16:27:38Z | [
"python",
"pandas"
] |
useing regular expression for column filter | 37,899,154 | <p>I have a <code>pandas</code> <code>DataFrame</code> that contains a year and a title. Some of <code>rows.name</code> are <code>Batman</code>, <code>Catman</code> etc. I am trying to get all rows of the format <code>.*man</code>, using the following expression:</p>
<pre>
t[t.title & re.search(r'.*man', t.title)]
</p... | 0 | 2016-06-18T16:25:25Z | 37,899,480 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow">str.contains</a>:<br>
<code>df[df['title'].str.contains('.man')]</code>.</p>
| 2 | 2016-06-18T16:57:29Z | [
"python",
"pandas"
] |
useing regular expression for column filter | 37,899,154 | <p>I have a <code>pandas</code> <code>DataFrame</code> that contains a year and a title. Some of <code>rows.name</code> are <code>Batman</code>, <code>Catman</code> etc. I am trying to get all rows of the format <code>.*man</code>, using the following expression:</p>
<pre>
t[t.title & re.search(r'.*man', t.title)]
</p... | 0 | 2016-06-18T16:25:25Z | 37,908,305 | <p>following solution worked </p>
<pre>
df.ix[[x for x in df.index if re.search(r'.*e.*', x)]]
</pre>
<p>Inspired from || by <a href="http://stackoverflow.com/questions/35638377/pandas-filter-and-regex-search-the-index-of-dataframe">Pandas - filter and regex search the index of DataFrame</a></p>
| 0 | 2016-06-19T14:30:35Z | [
"python",
"pandas"
] |
Global Variable across modules | 37,899,197 | <p>I faced this problem while i was expirementing with my project.My project is designed so it has multipule submoudles.</p>
<p>Now each submodule needs a position of an the same item on the screen,which is random each time the program ran.I thought it was a good idea to check once where is the position of the item (I... | -2 | 2016-06-18T16:28:55Z | 37,899,239 | <p>For each of your module, define your functions/class with a 'pos' argument.</p>
<p><strong>Module A.py</strong></p>
<pre><code>def foo(pos):
click(pos)
</code></pre>
<p><strong>Module main.py</strong></p>
<pre><code>def main():
position = get_pos()
A.foo(position)
</code></pre>
<p>In general, do not... | -1 | 2016-06-18T16:33:07Z | [
"python",
"python-module"
] |
Global Variable across modules | 37,899,197 | <p>I faced this problem while i was expirementing with my project.My project is designed so it has multipule submoudles.</p>
<p>Now each submodule needs a position of an the same item on the screen,which is random each time the program ran.I thought it was a good idea to check once where is the position of the item (I... | -2 | 2016-06-18T16:28:55Z | 37,899,969 | <p><code>Config.py</code> will only be initialized on import once in your application and <code>pos</code> will be initially <code>None</code>.</p>
<p><code>main.py</code> then sets it, and all other modules can access <code>pos</code> with <code>Config.pos</code>.</p>
<hr>
<h3><code>Config.py</code></h3>
<pre><cod... | 0 | 2016-06-18T17:51:05Z | [
"python",
"python-module"
] |
Global Variable across modules | 37,899,197 | <p>I faced this problem while i was expirementing with my project.My project is designed so it has multipule submoudles.</p>
<p>Now each submodule needs a position of an the same item on the screen,which is random each time the program ran.I thought it was a good idea to check once where is the position of the item (I... | -2 | 2016-06-18T16:28:55Z | 37,900,575 | <p>The problem is in <em>a.py</em>: <code>from mainPackage import Config</code>. You did an absolute import from a package and ended up importing <code>Config</code> twice. Python only imports a module once but in your case you used two different names (<code>Config</code> in some files, <code>mainPackage.Config</code>... | 1 | 2016-06-18T18:57:34Z | [
"python",
"python-module"
] |
Heroku Python Remote Rejected error | 37,899,247 | <p>I am making a Simple Python Bot which can be run like <code>python file.py</code> . I created a Folder in my PC having 3 files <code>file.py list.txt Procfile</code> . In Procfile i wrote <code>worker: python file.py</code> , I choosed worker as it a Command Line application and my plan is to run that Python File fo... | 1 | 2016-06-18T16:33:58Z | 37,952,631 | <p>Each Heroku buildpack applies different tests to determine if it applies. For Python, the buildpack looks for a 'requirements.txt' or 'setup.py' file (see <a href="https://github.com/heroku/heroku-buildpack-python/blob/master/bin/detect" rel="nofollow">https://github.com/heroku/heroku-buildpack-python/blob/master/bi... | 0 | 2016-06-21T19:05:12Z | [
"python",
"git",
"heroku",
"deployment"
] |
autoscaling not working on drawing arrow | 37,899,364 | <p>Trying to draw a simple arrow in Matplotlib using the following:</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.arrow(1, 1, 1, 1)
plt.show()
</code></pre>
<p>which results in an empty plot.</p>
<p>If the arrow specifications are changed to <code>ax.arrow(0, 0, 1, 1)</code> then I do se... | 1 | 2016-06-18T16:45:27Z | 37,909,853 | <p>The problem persists on Windows 10 and Ubuntu 14 with the latest version of matplotlib and Python 3.4/3.5. A simple workaround is to create a helper function <code>arrow_</code> which creates two invisible points at the beginning and end of the arrow.</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.sub... | 0 | 2016-06-19T17:20:45Z | [
"python",
"matplotlib"
] |
Circular Queue Structure ( array-backed) | 37,899,423 | <p>I need some help in writing a python program that will implement a circular queue data structure (array-backed). I've completed a few of the methods already but I'm a bit stumped when it comes to adding and taking things away from the queue, as well as checking the values within it. I believe this is of the first-in... | 2 | 2016-06-18T16:52:24Z | 37,899,518 | <blockquote>
<p>I'd get an error stating that the Queue class doesn't have a data attribute</p>
</blockquote>
<p>I don't have the error you mention when running your test on your code.</p>
| 1 | 2016-06-18T17:01:06Z | [
"python",
"queue"
] |
Circular Queue Structure ( array-backed) | 37,899,423 | <p>I need some help in writing a python program that will implement a circular queue data structure (array-backed). I've completed a few of the methods already but I'm a bit stumped when it comes to adding and taking things away from the queue, as well as checking the values within it. I believe this is of the first-in... | 2 | 2016-06-18T16:52:24Z | 37,899,686 | <p>I'm pretty sure that all the code using <code>self.queue</code> is wrong. That attribute isn't needed at all. The whole point of the <code>data</code> attribute is to use it to store the values. Use the indexes <code>head</code> and <code>tail</code> to figure out where in <code>data</code> to put things (and where ... | 2 | 2016-06-18T17:19:21Z | [
"python",
"queue"
] |
Pandas: Charting 3 months of quotes with a benchmark | 37,899,572 | <p>I have a df with the daily "Adj Close" (from Yahoo) for many stocks that I want to chart compared to the SPY.</p>
<pre><code> AAPL ABC ... SPY
Date
2016-03-10 100.56 85.79 198.52
2016-03-11 101.64 89.14 201.72
...
2016-06-09 99.65 76.17 212.08
2016-06-10 98.83 7... | 1 | 2016-06-18T17:07:11Z | 37,900,468 | <p>Are you looking for something along these lines - (divides all prices by the first row):</p>
<pre><code>stockData = DataReader(['AAPL', 'AMZN', 'FB', 'SPY'], 'yahoo', datetime(2015, 1, 1), datetime.today()).loc['Adj Close']
stockData = stockData.div(stockData.iloc[0], axis=1)
for stock in stockData.columns[:-1]:
... | 2 | 2016-06-18T18:45:54Z | [
"python",
"pandas",
"matplotlib"
] |
how to make console app from python module | 37,899,625 | <p>I've got a python module with <code>__main__.py</code> file and I want to make it an app, which I can call from anywhere. </p>
<p>Something like this:
<code>$my_app [args]</code> or <code>python3 my_app args</code><br>
How can I do this?
I suppose, that I need to write something in <code>setup.py</code>. Now it loo... | 2 | 2016-06-18T17:13:31Z | 37,900,023 | <p>I think the easiest way is to set up an alias (<a href="http://www.linfo.org/alias.html" rel="nofollow">http://www.linfo.org/alias.html</a>).
If you are using bash, you can add the line "alias myapp="python3 /path/to/your/app/myapp.py"" to you ~/.bashrc <br>
After that you can call your app from everywhere with $mya... | 1 | 2016-06-18T17:56:21Z | [
"python",
"linux",
"setup.py"
] |
Comparing password to hashed passwork using bcryt in Django | 37,899,719 | <p>I am trying to compare a user entered password field to a password that has been hashed. I have looked at the documentation and have not been able to find what I have been looking for. I hash the password using </p>
<pre><code>pw_bytes = password.encode('utf-8')
hashed = bcrypt.hashpw(pw_bytes, bcrypt.gensalt())
... | 0 | 2016-06-18T17:22:30Z | 37,899,796 | <p>You need to save the results of <code>bcrypt.gensalt()</code> <em>with</em> the encrypted password and pass it again to <code>bcrypt()</code> when you hash the later password attempt.</p>
<p>The point of the salt is to make your hashes unique per user - said another way, if two users use the same password the hashe... | 2 | 2016-06-18T17:30:55Z | [
"python",
"django",
"hash"
] |
Issue with a Kivy Spinner not updating text value right away | 37,899,786 | <p>I was running a quick little test to display the currently selected value of a spinner by printing the value to a TextInput.</p>
<p>When the spinner is clicked it opens the drop down like it should when I click on the Display All option it sets it as active like it should (meaning it's the currently selected value)... | 1 | 2016-06-18T17:29:28Z | 37,903,286 | <p>The behaviour is completely expected: <code>on_press</code> triggers at the time of clicking, not when the <code>text</code> property changes. Therefore, you should change <code>Pick</code> to something like:</p>
<pre><code>def Pick(sender, val):
if val == 'Display All':
Display_All(val)
</code></pre>
... | 2 | 2016-06-19T02:00:28Z | [
"python",
"spinner",
"kivy"
] |
How do I refactor a simple commandline script to be object oriented? | 37,899,798 | <p>I don't have a lot of experience with object-oriented Python and want to refactor a simple command-line tool. My current script simply imports needed libraries, has a few function definitions, uses global variables (which I know is bad practice) and uses argparse all in one .py file, e.g.:</p>
<pre><code>import arg... | 2 | 2016-06-18T17:31:13Z | 37,900,237 | <p>Let's create a single class that mimics our dict, and get's passed to these methods instead of operating on a global variable, and you can tell me if this is more what you're looking for. The fact of the matter is, you are already using a bit of object oriented programming and don't know it (the dict class)</p>
<h... | 3 | 2016-06-18T18:20:17Z | [
"python",
"oop",
"refactoring"
] |
How do I refactor a simple commandline script to be object oriented? | 37,899,798 | <p>I don't have a lot of experience with object-oriented Python and want to refactor a simple command-line tool. My current script simply imports needed libraries, has a few function definitions, uses global variables (which I know is bad practice) and uses argparse all in one .py file, e.g.:</p>
<pre><code>import arg... | 2 | 2016-06-18T17:31:13Z | 37,907,143 | <p>You will probably want to concentrate on dependency injection. Basically pass all the things you need to use into your objects/functions.</p>
<p>I like to have a <code>args_to_options()</code> factory function. It returns an <code>Options</code> class (in Python a dict would probably be fine) with the flags and pro... | 0 | 2016-06-19T12:18:13Z | [
"python",
"oop",
"refactoring"
] |
open fp = io.BytesIO(fp.read()) AttributeError: 'str' object has no attribute 'read' in PIL/image.py | 37,899,880 | <p>I'm a little new to Python especially Imaging library that I'm currently working with. I'm working with a facial recognition code and running it in my Raspberry Pi 2 B+ running Jessie. I'm using Opencv 2.4.9 and Python 2.7. The code that I'm currently working with worked till a few minutes ago but now I keep getting... | -3 | 2016-06-18T17:41:29Z | 37,900,277 | <p>Your subject line is confusing. You fixed that problem and then exposed a different bug.</p>
<pre><code>IOError: [Errno 2] No such file or directory: ''
</code></pre>
<p>The message shows that you are trying to open a file with no name and that means that the input file you are reading has at least one blank line.... | 1 | 2016-06-18T18:24:59Z | [
"python",
"python-2.7",
"opencv",
"python-imaging-library",
"face-recognition"
] |
Can re.fullmatch() eliminate the need for string anchors in regex | 37,899,892 | <p>Consider the following regex, which checks for password strength. It has the start and end string anchors, to ensure it's matching the entire string.</p>
<pre><code>pattern = re.compile(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[$@$!%*#?&.])[A-Za-z\d$@$!%*#?&.]{8,}$')
while True:
user_pass = input(... | 0 | 2016-06-18T17:42:28Z | 37,899,951 | <p>The <a href="https://docs.python.org/3/library/re.html#re.fullmatch" rel="nofollow"><code>fullmatch()</code></a> function and <a href="https://docs.python.org/3/library/re.html#re.regex.fullmatch" rel="nofollow"><code>regex.fullmatch()</code></a> method <a href="https://docs.python.org/3/whatsnew/3.4.html#re" rel="n... | 2 | 2016-06-18T17:48:45Z | [
"python",
"regex"
] |
Using .encode('utf-8') and still getting an Unicode-objects must be encoded before hashing error | 37,900,037 | <p>When I have searched for the error, all the answers point to using .encode('utf-8'). I added that to my code and I am still getting the same error. Here is my code </p>
<pre><code>def login(request):
password=request.POST['password']
email=request.POST['email']
try:
d2 = Register.objects.late... | 0 | 2016-06-18T17:57:14Z | 37,900,070 | <p>As soon as you save bytes to a text field in the database they become text, so you need to encode your salt as well.</p>
| 1 | 2016-06-18T18:01:09Z | [
"python",
"django",
"unicode",
"utf-8",
"bcrypt"
] |
Filter array by unique item in list? | 37,900,171 | <p>I want filter list by unique item in sublist </p>
<p>example:</p>
<pre class="lang-py prettyprint-override"><code># ---------
# v v
lst = [[1, 0], [1, 1], [2, 2]]
# result
[[1, 0], [2, 2]]
</code></pre>
<p>I am using, want:</p>
<pre class="lang-py prettyprint-override"><code>def setx0(arr):
... | 0 | 2016-06-18T18:13:19Z | 37,900,247 | <p>Assuming the list is already sorted, you could use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p>
<pre><code>>>> from itertools import groupby
>>> from operator import itemgetter
>>> lst = [[1, 0], [1,... | 1 | 2016-06-18T18:20:51Z | [
"python",
"list",
"dictionary",
"filter",
"unique"
] |
Filter array by unique item in list? | 37,900,171 | <p>I want filter list by unique item in sublist </p>
<p>example:</p>
<pre class="lang-py prettyprint-override"><code># ---------
# v v
lst = [[1, 0], [1, 1], [2, 2]]
# result
[[1, 0], [2, 2]]
</code></pre>
<p>I am using, want:</p>
<pre class="lang-py prettyprint-override"><code>def setx0(arr):
... | 0 | 2016-06-18T18:13:19Z | 37,900,294 | <p>I would go for straight forward:</p>
<pre><code>lst = [[1, 0], [1, 1], [2, 2]]
seen = set()
new_list = []
for ele in lst:
if ele[0] not in seen:
new_list.append(ele)
seen.add(ele[0])
print new_list
</code></pre>
<p>Result:</p>
<pre><code>[[1, 0], [2, 2]]
</code></pre>
| 1 | 2016-06-18T18:26:35Z | [
"python",
"list",
"dictionary",
"filter",
"unique"
] |
Filter array by unique item in list? | 37,900,171 | <p>I want filter list by unique item in sublist </p>
<p>example:</p>
<pre class="lang-py prettyprint-override"><code># ---------
# v v
lst = [[1, 0], [1, 1], [2, 2]]
# result
[[1, 0], [2, 2]]
</code></pre>
<p>I am using, want:</p>
<pre class="lang-py prettyprint-override"><code>def setx0(arr):
... | 0 | 2016-06-18T18:13:19Z | 37,900,511 | <p>Not the very efficient, but if you like one-liners:</p>
<pre><code>try:
reduce
except NameError: # Python 3
from functools import reduce
lst = [[1, 0], [1, 1], [2, 2]]
filtered = reduce(lambda a, b: a+[b] if b[0] not in set(x[0] for x in a) else a,
lst, [])
print(filtered) # -> [[1,... | 0 | 2016-06-18T18:51:02Z | [
"python",
"list",
"dictionary",
"filter",
"unique"
] |
Filter array by unique item in list? | 37,900,171 | <p>I want filter list by unique item in sublist </p>
<p>example:</p>
<pre class="lang-py prettyprint-override"><code># ---------
# v v
lst = [[1, 0], [1, 1], [2, 2]]
# result
[[1, 0], [2, 2]]
</code></pre>
<p>I am using, want:</p>
<pre class="lang-py prettyprint-override"><code>def setx0(arr):
... | 0 | 2016-06-18T18:13:19Z | 37,901,115 | <p>With sorted list, the easiest would be</p>
<pre><code>>>> lst = [[1, 0], [1, 1], [2, 2]]
>>> dict(reversed(lst)).items()
[(1, 0), (2, 2)]
</code></pre>
| 0 | 2016-06-18T19:59:27Z | [
"python",
"list",
"dictionary",
"filter",
"unique"
] |
Filter array by unique item in list? | 37,900,171 | <p>I want filter list by unique item in sublist </p>
<p>example:</p>
<pre class="lang-py prettyprint-override"><code># ---------
# v v
lst = [[1, 0], [1, 1], [2, 2]]
# result
[[1, 0], [2, 2]]
</code></pre>
<p>I am using, want:</p>
<pre class="lang-py prettyprint-override"><code>def setx0(arr):
... | 0 | 2016-06-18T18:13:19Z | 37,910,701 | <p>try this</p>
<pre><code>const lst = [[1, 0], [1, 1], [2, 2]],
foundItems = [],
result = []
for (let i in lst) {
const lstItem = lst[i]
if (foundItems.indexOf(lstItem[0]) === -1) {
foundItems.push(lstItem[0])
result.push(lstItem)
}
}
console.log(JSON.stringify(result)) // print [[1, 0], [... | 0 | 2016-06-19T18:54:26Z | [
"python",
"list",
"dictionary",
"filter",
"unique"
] |
Flask server cannot read file uploaded by POST request | 37,900,239 | <p>I have my React client post a file with the fetch api to the '/dataset' endpoint.</p>
<pre><code>import 'whatwg-fetch';
uploadData(csv) {
this.dataset = csv;
fetch('/dataset', {
method: 'POST',
body: this._fileToFormData(csv)
}).then(
(response) => {
console.log(... | 4 | 2016-06-18T18:20:34Z | 37,900,270 | <p>Uploaded files are available in <code>request.files</code>, not <code>request.form</code>. The values are file-like objects, so to get the data you need to read the file.</p>
<pre><code>data = request.files['file'].read()
</code></pre>
<p>See the Flask <a href="http://flask.pocoo.org/docs/0.11/patterns/fileupload... | 0 | 2016-06-18T18:24:05Z | [
"javascript",
"python",
"reactjs",
"flask",
"fetch-api"
] |
Making a class callable in python | 37,900,317 | <p>I came to know we can also make class as callable without implementing the <code>__call__()</code> function, and I am trying to write some thing like that but I got stuck: below is my code</p>
<pre><code>class neg:
def __init__(self): # Classes are callables too
self.val = 54545
def __repr__(self)... | -6 | 2016-06-18T18:29:33Z | 37,900,379 | <p>You need to create an instance of the class to run the <code>__init__</code> method. And you also need to make sure your program starts up. You call/instantiate a function by writing <code>do_something()</code>; you call a class by writing <code>neg()</code>.</p>
<pre><code>if __name__ == '__main__': # Fix the main... | 1 | 2016-06-18T18:35:49Z | [
"python"
] |
Making a class callable in python | 37,900,317 | <p>I came to know we can also make class as callable without implementing the <code>__call__()</code> function, and I am trying to write some thing like that but I got stuck: below is my code</p>
<pre><code>class neg:
def __init__(self): # Classes are callables too
self.val = 54545
def __repr__(self)... | -6 | 2016-06-18T18:29:33Z | 37,900,747 | <p>Classes are callable, only in the sense that you "call" a class to create an instance of the class. You call a class with the same syntax that you call functions, by using parenthesis and optional arguments. This is unrelated to <em>call</em>, which only affects instances.</p>
| 0 | 2016-06-18T19:16:22Z | [
"python"
] |
Quality of PCA in scikit-learn | 37,900,362 | <p>I use PCA to transform my features in oder to reduce the number of dimensions. In order to tune the number of dimensions I need to know how well the original features are described by the PCA. How can that be determined in scikit-learn?</p>
| 1 | 2016-06-18T18:33:37Z | 37,901,434 | <p>I think you can examine the <code>explained_variance_ratio_</code> attribute after fitting the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html" rel="nofollow"><code>PCA</code></a> object to see how much variance are captured by each PC.</p>
| 1 | 2016-06-18T20:38:27Z | [
"python",
"math",
"machine-learning",
"scikit-learn",
"pca"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.