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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Pandas group given divide point | 38,461,901 | <p>I have a pandas dataframe, where I need do divide into several groups and do certain aggregation within each.</p>
<p>I have a column which is <code>datetime</code> where I need efficiently use a given list of cutting points to split the dataframe into different groups. </p>
<p>In plain english, I want to find toda... | 0 | 2016-07-19T14:50:20Z | 38,462,462 | <p>I fashioned this example for you:</p>
<pre><code>tidx = pd.date_range('2012-01-01', periods=4800, freq='H')
df = pd.DataFrame(np.exp(np.random.randn(4800, 2) / 100 + 0.0002) - 1, tidx, list('AB'))
</code></pre>
<h3>Gratuitous chart</h3>
<pre><code>df.add(1).cumprod().plot(legend=False)
</code></pre>
<p><a href="... | 0 | 2016-07-19T15:16:08Z | [
"python",
"pandas"
] |
Python Redis: DUMP payload version or checksum are wrong | 38,461,913 | <p>I'm trying to copy all keys from one redis database to my local machine. After setting up both connections and calling <code>flushdb</code> on the local copy to clear all of the keys, I run this:</p>
<pre><code>for key in src.keys('*'):
ttl = src.ttl(key)
# Handle TTL command returning -1 (no expire) or -2... | 0 | 2016-07-19T14:50:56Z | 38,464,472 | <p>Can you recreate the offending payload?</p>
| 0 | 2016-07-19T17:03:21Z | [
"python",
"redis"
] |
Retrieve and Rank Python: What kind of "Answer Data" to pass to rank method? | 38,461,937 | <p>I'm accessing the Retreive-And-Rank service using Python. So far I've uploaded my configuration and documents and have trained my ranker on the relevance file. All that is left, I presume, is to pass some query results (from Solr?) into the "rank" method of my R-A-R object.</p>
<p>My question: What exactly are thos... | -1 | 2016-07-19T14:52:12Z | 38,481,647 | <p>One workaround is to call pysolr's <code>_send_request</code> method:</p>
<pre><code>results = pysolr._send_request("GET", path="/fcselect?q=%s&ranker_id=%s&wt=json" %
(query_string, ranker_id))
for doc in json.loads(results)["response"]["docs"]:
print doc
</code></pre>
<p... | 0 | 2016-07-20T12:42:24Z | [
"python",
"ibm-bluemix",
"ibm-watson-cognitive",
"pysolr",
"retrieve-and-rank"
] |
Unknown error in python pptx module add_picture | 38,461,983 | <p>I've been trying to input a series of pictures onto every slide on a powerpoint presentation. I type in the image path, and the relevant dimensions, but I get an error which I don't understand.</p>
<pre><code> for k in xrange(0, len(prs.slides)):
img_path = os_path + str(k+1) + '.png'
left = Cm(1... | 1 | 2016-07-19T14:54:20Z | 38,462,444 | <p>I think I fixed this.</p>
<p>My img_path in my documents included an & in the file name - I changed where the image was located (to a folder without an &) and it worked.</p>
| 1 | 2016-07-19T15:15:05Z | [
"python",
"python-pptx"
] |
accessing characters of urdu script | 38,462,076 | <p>I have following string </p>
<pre><code>test="Ù Ú¯ ب ٠د Û Ú© ر ٠ا Ù "
</code></pre>
<p>what I want is that I want to access each character and save it in some variables for future access but when I looped over them I got weird output.Actually I am not aware of encoding schemes that much.</p>
<pre><code... | 0 | 2016-07-19T14:57:47Z | 38,462,143 | <p>For Python 2.x try this:</p>
<pre><code>test=u"Ù Ú¯ ب ٠د Û Ú© ر ٠ا Ù "
for i in test:
print(i)
</code></pre>
<p>Appending <code>u</code> makes it a <code>unicode</code> object.</p>
| 0 | 2016-07-19T15:00:35Z | [
"python",
"python-2.x",
"urdu"
] |
accessing characters of urdu script | 38,462,076 | <p>I have following string </p>
<pre><code>test="Ù Ú¯ ب ٠د Û Ú© ر ٠ا Ù "
</code></pre>
<p>what I want is that I want to access each character and save it in some variables for future access but when I looped over them I got weird output.Actually I am not aware of encoding schemes that much.</p>
<pre><code... | 0 | 2016-07-19T14:57:47Z | 38,462,222 | <p>Either define <code>test</code> as a unicode string, or use the <code>decode</code> method:</p>
<pre><code>test="Ù Ú¯ ب ٠د Û Ú© ر ٠ا Ù"
for i in test.decode('utf8'):
print(i)
# print unicode value
print(repr(i))
test=u"Ù Ú¯ ب ٠د Û Ú© ر ٠ا Ù"
for i in test:
print(i)
# print... | 3 | 2016-07-19T15:04:08Z | [
"python",
"python-2.x",
"urdu"
] |
In Pandas, generate DateTime index from Multi-Index with years and weeks | 38,462,214 | <p>I have a DataFrame <code>df</code> with columns <code>saledate</code> (in DateTime, dytpe <code><M8[ns]</code>) and <code>price</code> (dytpe <code>int64</code>), such if I plot them like</p>
<pre><code>fig, ax = plt.subplots()
ax.plot_date(dfp['saledate'],dfp['price']/1000.0,'.')
ax.set_xlabel('Date of sale')
a... | 1 | 2016-07-19T15:03:41Z | 38,462,499 | <p>Create a new index:</p>
<pre><code>i = pd.Index(pd.datetime(year, 1, 1) + pd.Timedelta(7 * weeks, unit='d') for year, weeks in df.index)
</code></pre>
<p>Then set this new index on the DataFrame:</p>
<pre><code>df.index = i
</code></pre>
| 1 | 2016-07-19T15:17:53Z | [
"python",
"datetime",
"pandas"
] |
In Pandas, generate DateTime index from Multi-Index with years and weeks | 38,462,214 | <p>I have a DataFrame <code>df</code> with columns <code>saledate</code> (in DateTime, dytpe <code><M8[ns]</code>) and <code>price</code> (dytpe <code>int64</code>), such if I plot them like</p>
<pre><code>fig, ax = plt.subplots()
ax.plot_date(dfp['saledate'],dfp['price']/1000.0,'.')
ax.set_xlabel('Date of sale')
a... | 1 | 2016-07-19T15:03:41Z | 38,462,592 | <p>If you group using <code>pd.TimeGrouper</code> you'll keep datetimes in your index.</p>
<pre><code>dfp.groupby(pd.TimeGrouper('W')).mean()
</code></pre>
| 1 | 2016-07-19T15:21:23Z | [
"python",
"datetime",
"pandas"
] |
In Pandas, generate DateTime index from Multi-Index with years and weeks | 38,462,214 | <p>I have a DataFrame <code>df</code> with columns <code>saledate</code> (in DateTime, dytpe <code><M8[ns]</code>) and <code>price</code> (dytpe <code>int64</code>), such if I plot them like</p>
<pre><code>fig, ax = plt.subplots()
ax.plot_date(dfp['saledate'],dfp['price']/1000.0,'.')
ax.set_xlabel('Date of sale')
a... | 1 | 2016-07-19T15:03:41Z | 38,463,653 | <p>For the sake of completeness, here are the details of how I implemented the solution suggested by piRSquared:</p>
<pre><code>fig, ax = plt.subplots()
ax.plot_date(dfp['saledate'],dfp['price']/1000.0,'.')
ax.set_xlabel('Date of sale')
ax.set_ylabel('Price (1,000 euros)')
dfp_week = dfp.groupby(pd.TimeGrouper(key='s... | 1 | 2016-07-19T16:12:01Z | [
"python",
"datetime",
"pandas"
] |
Is it safe practice to edit a list while looping through it? | 38,462,235 | <p>I was trying to execute a for loop like:</p>
<pre><code>a = [1,2,3,4,5,6,7]
for i in range(0, len(a), 1):
if a[i] == 4:
a.remove(a[i])
</code></pre>
<p>I end up having an <code>index error</code> since the <code>length</code> of the list becomes shorter but the iterator <code>i</code> does not become a... | 0 | 2016-07-19T15:04:42Z | 38,462,470 | <p>I don't know where you are going with that but this would do what I beleive you want :</p>
<pre><code>i=0
a = [1,2,3,4,5,6,7]
while boolean_should_i_stop_the_loop :
if i>=len(a) :
boolean_should_i_stop_the_loop = False
#here goes what you want to do in the for loop
print i;
a.append(4)
i += ... | 0 | 2016-07-19T15:16:28Z | [
"python",
"arrays",
"python-2.7",
"python-3.x",
"for-loop"
] |
Is it safe practice to edit a list while looping through it? | 38,462,235 | <p>I was trying to execute a for loop like:</p>
<pre><code>a = [1,2,3,4,5,6,7]
for i in range(0, len(a), 1):
if a[i] == 4:
a.remove(a[i])
</code></pre>
<p>I end up having an <code>index error</code> since the <code>length</code> of the list becomes shorter but the iterator <code>i</code> does not become a... | 0 | 2016-07-19T15:04:42Z | 38,462,493 | <p>If you want to delete elements from your list while iterating over it you should use list comprehension. </p>
<pre><code>a = [1,2,3,4,5,6,7]
a = [x for x in a if not check(x)]
</code></pre>
<p>You would need to write a "check" function that returns wether or not you want to keep the element in the list.</p>
| 1 | 2016-07-19T15:17:34Z | [
"python",
"arrays",
"python-2.7",
"python-3.x",
"for-loop"
] |
Is it safe practice to edit a list while looping through it? | 38,462,235 | <p>I was trying to execute a for loop like:</p>
<pre><code>a = [1,2,3,4,5,6,7]
for i in range(0, len(a), 1):
if a[i] == 4:
a.remove(a[i])
</code></pre>
<p>I end up having an <code>index error</code> since the <code>length</code> of the list becomes shorter but the iterator <code>i</code> does not become a... | 0 | 2016-07-19T15:04:42Z | 38,462,501 | <p>For the <code>.pop()</code> that you mention for example you can use a list comprehension to create a second list or even modify the original one in place. Like so:</p>
<pre><code>alist = [1, 2, 3, 4, 1, 2, 3, 5, 5, 4, 2]
alist = [x for x in alist if x != 4]
print(alist)
#[1, 2, 3, 1, 2, 3, 5, 5, 2]
</code></pre>
... | 2 | 2016-07-19T15:17:54Z | [
"python",
"arrays",
"python-2.7",
"python-3.x",
"for-loop"
] |
long integers division error in python while finding least common multiple | 38,462,288 | <p>Normally, program doesn't throw an error for small however when it comes to these numbers it returns wrong division result</p>
<pre><code>def leastCommonMultiple(n1, n2):
a=n1
b=n2
while n2!=0:
(n1, n2) = (n2, n1 % n2)
print (n1) # greatest common divisior for given input is 5
print(a*b) ... | 0 | 2016-07-19T15:07:18Z | 38,462,638 | <p>use // in python 3 for integer division. I just found out this </p>
| 3 | 2016-07-19T15:23:31Z | [
"python",
"python-3.x",
"lcm"
] |
A tkinter notebook with scrollbars if the contents are too large | 38,462,311 | <p>I am trying to create an interface with tkinter. It should have a control panel on the left, and a set of 3 tabs on the right.</p>
<p>The tabs will show images, which may be too large for the screen, however the exact size will only be known after they have been dynamically created by the program. So I want to have... | 0 | 2016-07-19T15:08:19Z | 38,465,446 | <p>The problem in your code is that you resize the canvas at the size of the picture, so the size of the canvas and of the scrollregion are the same. And it makes your canvas to big for your tab and your scrollbar useless.</p>
<p>I suppressed the lines</p>
<pre><code>self.actnet_canvas['width'] = width
self.actnet_ca... | 1 | 2016-07-19T17:58:37Z | [
"python",
"tkinter"
] |
Pandas merge DataFrames based on index/column combination | 38,462,329 | <p>I have two <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">DataFrames</a> that I want to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html#pandas.DataFrame.merge" rel="nofollow">merge</a>. I have read about <a href="http://... | 5 | 2016-07-19T15:08:59Z | 38,462,393 | <p>I'd suggest reseting the index (<code>reset_index</code>) and then merging the DataFrame, as you've read. Then you can set the index (<code>set_index</code>) to reproduce your desired MultiIndex.</p>
| 1 | 2016-07-19T15:12:17Z | [
"python",
"pandas",
"dataframe"
] |
How do I find a string in a list that matches a string or substring in another list | 38,462,524 | <p>How can I find a string in List1 that is a substring of any of the strings in List2? Both lists can be of different lengths.</p>
<p>Say I have:</p>
<pre><code>List1=['hello', 'hi', 'ok', 'apple']
List2=['okay', 'never', 'goodbye']
</code></pre>
<p>I need it to return 'ok', seeing as it was the only string in lis... | 0 | 2016-07-19T15:18:59Z | 38,462,596 | <p>If you want to know if a string from list1 is in list2 you can do</p>
<pre><code>for s in List1:
if s in List2:
print("found s in List2")
</code></pre>
| 1 | 2016-07-19T15:21:32Z | [
"python"
] |
How do I find a string in a list that matches a string or substring in another list | 38,462,524 | <p>How can I find a string in List1 that is a substring of any of the strings in List2? Both lists can be of different lengths.</p>
<p>Say I have:</p>
<pre><code>List1=['hello', 'hi', 'ok', 'apple']
List2=['okay', 'never', 'goodbye']
</code></pre>
<p>I need it to return 'ok', seeing as it was the only string in lis... | 0 | 2016-07-19T15:18:59Z | 38,462,607 | <p>You can use list comprehension as:</p>
<p><code>[x for x in List1 for y in List2 if x in y]</code></p>
| 8 | 2016-07-19T15:21:59Z | [
"python"
] |
How do I find a string in a list that matches a string or substring in another list | 38,462,524 | <p>How can I find a string in List1 that is a substring of any of the strings in List2? Both lists can be of different lengths.</p>
<p>Say I have:</p>
<pre><code>List1=['hello', 'hi', 'ok', 'apple']
List2=['okay', 'never', 'goodbye']
</code></pre>
<p>I need it to return 'ok', seeing as it was the only string in lis... | 0 | 2016-07-19T15:18:59Z | 38,462,646 | <p>I wrote this piece of code to implement the </p>
<pre><code>List1=['hello', 'hi', 'ok', 'apple']
List2=['ok', 'never', 'goodbye']
i=[]
for j in List1:
for k in List2:
if j==k:
i.append(j)
print i
</code></pre>
| 0 | 2016-07-19T15:23:50Z | [
"python"
] |
How to use For loop KEY to name DataFrame in Pandas | 38,462,558 | <p>I want to use the strings listed in List_ and pass them in my function lambda so that each iteration names changes for load or temp....ie. lambda x: x.<strong>load</strong>.reset_index().T </p>
<pre><code>List_ = {'load','Temp','Hum','Hum'}
list__ = []
for names in List_:
test = df.apply(lambda x: x.names.rese... | -5 | 2016-07-19T15:20:26Z | 38,481,737 | <p>When i understand this in the right way, this could be want you want:</p>
<pre><code>List_ = {'load','Temp','Hum','Hum'}
list__ = []
for names in List_:
test = df.apply(lambda x: x.names.reset_index().T)
list__.append(test)
</code></pre>
<p>When you change the last line you will get what you want. But i'm... | 0 | 2016-07-20T12:45:41Z | [
"python",
"pandas"
] |
How to use For loop KEY to name DataFrame in Pandas | 38,462,558 | <p>I want to use the strings listed in List_ and pass them in my function lambda so that each iteration names changes for load or temp....ie. lambda x: x.<strong>load</strong>.reset_index().T </p>
<pre><code>List_ = {'load','Temp','Hum','Hum'}
list__ = []
for names in List_:
test = df.apply(lambda x: x.names.rese... | -5 | 2016-07-19T15:20:26Z | 38,510,695 | <p>df4 is a dataframe with Date as index and columns with load, temp , hum and windspeed. </p>
<pre><code>Date Load Temp
1 100 1.1
1 200 1.2
1 300 2.4
2 400 1.7
2 500 4.3
3 600 2.2
</code></pre>
<p>What I wanted to do was using a loop for to apply my function to ... | 0 | 2016-07-21T17:28:01Z | [
"python",
"pandas"
] |
How can I filter information from a Django error message? | 38,462,581 | <p>When an error occurs on my Django site (typically a 500), I get a really long error message back from the server (as shown in this example):</p>
<pre><code>TypeError at /c/ajax/import_onboard/
argument of type 'NoneType' is not iterable
Request Method: POST
Request URL: http://127.0.0.1:8000/c/ajax/import_onboard/... | 0 | 2016-07-19T15:21:00Z | 38,463,292 | <p>You may redefine error view with own template:</p>
<pre><code>handler500 = 'mysite.views.my_custom_error_view'
</code></pre>
<p><a href="https://docs.djangoproject.com/en/1.9/topics/http/views/#customizing-error-views" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/http/views/#customizing-error-views<... | 1 | 2016-07-19T15:54:13Z | [
"python",
"django"
] |
selenium webdriver not working | 38,462,641 | <p>Selenium version: 2.53.6
Firefox version: 47.0.1
Chrome version: 51.0.2704.106 m</p>
<p>Now if I want to use them like that:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver2 = webdriver.Chrome()
</code></pre>
<p>i get an error:
FileNotFoundError: [WinError 2]</p>
<p>i even chec... | -1 | 2016-07-19T15:23:41Z | 38,948,432 | <p>I'm not sure about running two drivers at the same time, but for the chrome part at least you may need to point it to a chrome driver (which you can download from <a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/downloads</a>... | 0 | 2016-08-15T02:12:39Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver"
] |
Error when reading TFRecords with tensorflow: tensorflow.python.framework.errors.NotFoundError: FetchOutputs node ParseSingleExample/Squeeze | 38,462,666 | <p>I'm really new with tensorflow and I'm sure that I'm doing something wrong here. My problem is that when I'm reading records from file, code works some times, but most of the time it fails:</p>
<pre><code>import tensorflow as tf
import numpy as np
import time
def readFrame(inQueue, reader):
frameWidth = int(19... | 0 | 2016-07-19T15:24:30Z | 38,485,721 | <p>I got rid of that error by sleeping a while after starting threads and before starting to read records.</p>
<pre><code>threads = tf.train.start_queue_runners(sess=sess, coord=coord)
time.sleep(1)
</code></pre>
<p>If I added sleep, before starting threads, it had no effect... My best guess about what is happening... | 0 | 2016-07-20T16:15:09Z | [
"python",
"python-3.x",
"tensorflow"
] |
removing items from list (for loop) but gets a out of index error if not called list.copy() | 38,462,682 | <p>I am new to python and linux and to programming in general, sorry for noob questions. </p>
<p>I have a list of cifs shares as below,</p>
<pre><code>['Type', 'Sharename', 'Comment']
[['Disk', '3tb', ''], ['Disk', 'c$', 'Default share']]
</code></pre>
<p>I would like to remove all the shares which have a comment s... | 1 | 2016-07-19T15:25:06Z | 38,462,798 | <p>You are continuously doing <code>all_shares.copy()</code> because you are modifying the list while iterating over it. This <em>patch</em> prevents the <code>for</code> loop from changing with the list mutation; which is usually not desirable.</p>
<p>However, you can drop all the <code>copy</code> by iterating over ... | 2 | 2016-07-19T15:29:38Z | [
"python",
"list",
"iteration"
] |
removing items from list (for loop) but gets a out of index error if not called list.copy() | 38,462,682 | <p>I am new to python and linux and to programming in general, sorry for noob questions. </p>
<p>I have a list of cifs shares as below,</p>
<pre><code>['Type', 'Sharename', 'Comment']
[['Disk', '3tb', ''], ['Disk', 'c$', 'Default share']]
</code></pre>
<p>I would like to remove all the shares which have a comment s... | 1 | 2016-07-19T15:25:06Z | 38,462,922 | <p>Python uses, in part, concepts from functional programming. If you build a list of things you want to keep and return that to the context you wish to use it in you wont have to delete anything and you wont have to call list.copy() a bunch of times. </p>
| 0 | 2016-07-19T15:35:51Z | [
"python",
"list",
"iteration"
] |
removing items from list (for loop) but gets a out of index error if not called list.copy() | 38,462,682 | <p>I am new to python and linux and to programming in general, sorry for noob questions. </p>
<p>I have a list of cifs shares as below,</p>
<pre><code>['Type', 'Sharename', 'Comment']
[['Disk', '3tb', ''], ['Disk', 'c$', 'Default share']]
</code></pre>
<p>I would like to remove all the shares which have a comment s... | 1 | 2016-07-19T15:25:06Z | 38,463,116 | <p>There are a couple ways to do this. The most Pythonic is to use a list comprehension...</p>
<pre><code>special_comments = ['Remote Admin', 'Default share', 'Remote IPC']
filtered_shares = [x for x in all_shares if x not in special_comments]
</code></pre>
<p>This builds a new list keeping only the items from the o... | 0 | 2016-07-19T15:45:41Z | [
"python",
"list",
"iteration"
] |
Python cx_Oracle and csv extracts saved differently with different executions | 38,462,706 | <p>I'm working on a Python Script that runs queries against an Oracle Database and saves the results to csv. The greater plan is to use regular extracts with a separate application to check differences in the files through hashing.</p>
<p>The issue I've run into is that my script has so far saved some fields in the ex... | 0 | 2016-07-19T15:26:06Z | 38,484,485 | <p>Your code is simply using the default transformations for all data types. Note that an Oracle type of number(9) will be returned as an integer but number by itself will be returned as a float. You may wish to use an outputtypehandler in order to place this under your control a bit more firmly. :-) Examples for doing... | 0 | 2016-07-20T14:45:53Z | [
"python",
"csv",
"cx-oracle"
] |
Gevent hub raises exception on pool | 38,462,725 | <p>Running gevent pool gives me the following exception on <code>join</code>:</p>
<blockquote>
<p>return greenlet.switch(self)</p>
<p>gevent.hub.LoopExit: ('This operation would block forever', Hub at 0x105cbd190 select default pending=0 ref=0)</p>
</blockquote>
<p>Code is:</p>
<pre><code> queue = gevent.q... | 0 | 2016-07-19T15:26:55Z | 38,462,964 | <p>Using <a href="http://www.gevent.org/gevent.pool.html#gevent.pool.Group.map_async" rel="nofollow">map_async</a> on your sample code did resolved the issue on my side. I hope this is what you are looking for.</p>
| 0 | 2016-07-19T15:38:01Z | [
"python",
"gevent"
] |
Gevent hub raises exception on pool | 38,462,725 | <p>Running gevent pool gives me the following exception on <code>join</code>:</p>
<blockquote>
<p>return greenlet.switch(self)</p>
<p>gevent.hub.LoopExit: ('This operation would block forever', Hub at 0x105cbd190 select default pending=0 ref=0)</p>
</blockquote>
<p>Code is:</p>
<pre><code> queue = gevent.q... | 0 | 2016-07-19T15:26:55Z | 38,498,843 | <p>The error is raised because of the <code>gevent.queue.Queue</code> object. I replaced it with a default list and now it works. Not sure why the Queue is a problem, as it seems to be an iterable.</p>
| 0 | 2016-07-21T08:23:49Z | [
"python",
"gevent"
] |
Python - Find a specific mac address in a log file | 38,462,726 | <p>I want to extract specific Mac Address from a log file that can appear in different formats.</p>
<p>For example, on these three lines:</p>
<p><strong>Jun 16 10:24:28 (2248) Login OK: cli 88-c9-d0-fd-13-65 via TLS tunnel)</strong></p>
<p><strong>Jun 16 10:24:35 (2258) Login OK: cli f8:a9:d0:72:0a:dd via TLS tunn... | 0 | 2016-07-19T15:26:58Z | 38,468,484 | <p>You may use</p>
<pre><code>r'\b[a-f0-9]{2}(?:([:-]?)[a-f0-9]{2}(?:\1[a-f0-9]{2}){4}|(?:\.?[a-f0-9]{2}){5})\b'
</code></pre>
<p>See the <a href="https://regex101.com/r/xK3wZ7/1" rel="nofollow">regex demo</a> (compile the regex object with the <code>re.I</code> flag).</p>
<p><strong>Explanation</strong>:</p>
<ul>
... | 0 | 2016-07-19T21:02:59Z | [
"python",
"regex",
"linux",
"mac-address",
"logfile"
] |
Python add to url | 38,462,780 | <p>I have a URL as follows:</p>
<pre><code>http://www.example.com/boards/results/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01
</code></pre>
<p>I need to insert a node 'us' in this case, as follows:</p>
<pre><code>http://www.example.com/boards/results/us/current:entry1,current:... | 0 | 2016-07-19T15:28:41Z | 38,463,149 | <pre><code>path = "http://www.example.com/boards/results/current:entry1,current:entry2/modular/table/alltables/alltables/alltables/2011-01-01"
replace_start_word = 'results'
replace_word_length = len(replace_start_word)
replace_index = path.find(replace_start_word)
new_url = '%s/us%s' % (path[:replace_index + replace_w... | 0 | 2016-07-19T15:47:04Z | [
"python",
"url",
"urlparse"
] |
Python: Why do is the traceback getting printed? | 38,462,781 | <p>I have a function. The function get started in some more threads. I tried to print a own error message. But its not important what I do I get still the traceback printed. My function:</p>
<pre><code>def getSuggestengineResultForThree(suggestengine, seed, dynamoDBLocation):
results[seed][suggestengine] = getsugg... | 0 | 2016-07-19T15:28:46Z | 38,463,806 | <p>It's possible that <code>ProvisionedThroughputExceededException</code> is not actually the error. Try:</p>
<pre><code>except botocore.exceptions.ClientError as pe:
</code></pre>
<p>instead.</p>
<p>If that doesn't work, figure out what line the error is occurring on and put the <code>except</code> statement there.... | 0 | 2016-07-19T16:20:36Z | [
"python"
] |
plot that only shows most recent points | 38,462,784 | <p>I want to make a real time plot of temeperature vs. iteration but I will end up having so many points that it would not make sense to have them on the same plot. Does anyone know of any good ways to only show the most recent (lets say 100) data points so that after the first 100 the plot starts to replace the old da... | 0 | 2016-07-19T15:29:00Z | 38,463,219 | <p>you can use list of array to show the all data given for a while.
for example</p>
<p>tempaturelist=[]</p>
<pre><code>for i in range(50):
enter code here
tempaturelist.append(tempature)
print tempaturelist
</code></pre>
<p>There is a overwriting if you use same variable for all values.
Thats why you see o... | 0 | 2016-07-19T15:50:52Z | [
"python"
] |
plot that only shows most recent points | 38,462,784 | <p>I want to make a real time plot of temeperature vs. iteration but I will end up having so many points that it would not make sense to have them on the same plot. Does anyone know of any good ways to only show the most recent (lets say 100) data points so that after the first 100 the plot starts to replace the old da... | 0 | 2016-07-19T15:29:00Z | 38,486,971 | <h3>Edit:</h3>
<p>You might consider using a <a href="https://docs.python.org/2.7/library/collections.html#collections.deque" rel="nofollow"><code>deque</code></a> object to improve performance. It is like a stack/queue hybrid, which may be faster than numpy.roll. I left the old code in for example.. </p>
<pre><code>... | 0 | 2016-07-20T17:23:03Z | [
"python"
] |
How to set background color, title in Plotly (python)? | 38,462,844 | <p>Below is my code, could someone tell me how do I set background color, title, x-axis y-axis labels :</p>
<p><code>scatterplot = plot([Scatter(
x=x.index,
y=x['rating'],
mode='markers', marker=dict(size=10,
color=x['value'],
... | 1 | 2016-07-19T15:31:11Z | 38,466,386 | <p>You can <strong>set background color</strong> by creating a Layout object</p>
<pre><code>layout = Layout(
plot_bgcolor='rgba(0,0,0,0)'
)
data = Data([
Scatter( ... )
])
fig = Figure(data=data, layout=layout)
plot(fig, output_type='div')
</code></pre>
<p>If you want a transparent background see <a href=... | 0 | 2016-07-19T18:53:22Z | [
"python",
"django",
"plotly"
] |
lxml ignoring any tags the come between a spcific tag | 38,462,884 | <p>I am trying to extract some specific fields from a huge xml file. here is an example:</p>
<pre><code><?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
<article mdate="2009-09-24" key="journals/jasis/GianoliM09">
<author>Ernesto Gianoli</author... | 0 | 2016-07-19T15:34:09Z | 38,467,180 | <p>You need to be aware of the lxml data model for element content (in particular the <a href="http://lxml.de/api/lxml.etree._Element-class.html#tail" rel="nofollow"><code>tail</code></a> property). It is explained well here: <a href="http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html" rel="nofollow">http... | 1 | 2016-07-19T19:42:59Z | [
"python",
"xml",
"lxml"
] |
Pandas KeyError: value not in index | 38,462,920 | <p>I have the following code, </p>
<pre><code>df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]] = p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]]... | 3 | 2016-07-19T15:35:47Z | 38,463,068 | <p>use <code>reindex</code> to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.</p>
<pre><code>p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])
</code></pre>
<p>So your entire code example should look like this:</p>
<pre><cod... | 3 | 2016-07-19T15:42:59Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
Grouping numerical values in pandas | 38,463,019 | <p>In my <code>Dataframe</code> I have one column with numeric values, let say - distance. I want to find out which group of distance (range) have the biggest number of records (rows).</p>
<p>Doing simple:
<code>df.distance.count_values()</code> returns:</p>
<pre><code>74 1
90 1
94 1
893 ... | 1 | 2016-07-19T15:40:53Z | 38,463,186 | <p>I'd suggest doing the following, assuming your value column is labeled <code>val</code></p>
<pre><code>import numpy as np
df['bin'] = df['val'].apply(lambda x: 50*np.floor(x/50))
</code></pre>
<p>The result is the following:</p>
<pre><code>df.groupby('bin')['val'].count()
</code></pre>
| 1 | 2016-07-19T15:48:40Z | [
"python",
"pandas"
] |
Grouping numerical values in pandas | 38,463,019 | <p>In my <code>Dataframe</code> I have one column with numeric values, let say - distance. I want to find out which group of distance (range) have the biggest number of records (rows).</p>
<p>Doing simple:
<code>df.distance.count_values()</code> returns:</p>
<pre><code>74 1
90 1
94 1
893 ... | 1 | 2016-07-19T15:40:53Z | 38,464,281 | <p>Thanks to EdChum <a href="http://stackoverflow.com/questions/38463019/grouping-numerical-values-in-pandas?noredirect=1#comment64330006_38463019">suggestion</a> and based on <a href="http://chrisalbon.com/python/pandas_binning_data.html" rel="nofollow">this</a> example I've figured out, the best way (at least for me)... | 0 | 2016-07-19T16:50:43Z | [
"python",
"pandas"
] |
Calling a function within a function with python | 38,463,032 | <p>so here is my problem, I am trying to create a function in Python that refers to another function
Here is my code:</p>
<pre><code>def movies_creation():
for director in directors:
for i in range((int(director.age)-20)/random.randint(1,5)):
movie = MOVIE([], random.randint(1960, 2015),
... | -5 | 2016-07-19T15:41:19Z | 38,463,159 | <p>Problem in your code is that you should pass the <code>movie</code> variable to the method <code>title_colors</code>:</p>
<pre><code>title_colors(movie)
def title_colors(m):
m.name.append(random.choice(title_colors))
</code></pre>
| 0 | 2016-07-19T15:47:39Z | [
"python",
"function"
] |
Calling a function within a function with python | 38,463,032 | <p>so here is my problem, I am trying to create a function in Python that refers to another function
Here is my code:</p>
<pre><code>def movies_creation():
for director in directors:
for i in range((int(director.age)-20)/random.randint(1,5)):
movie = MOVIE([], random.randint(1960, 2015),
... | -5 | 2016-07-19T15:41:19Z | 38,463,334 | <p>Thanks for your help, my problem was my function had the same name than a list in my program. changed the name and everything works fine now</p>
| 0 | 2016-07-19T15:56:00Z | [
"python",
"function"
] |
Find Repeating Sublist Within Large List | 38,463,099 | <p>I have a large list of sub-lists (approx. 16000) that I want to find where the repeating pattern starts and ends. I am not 100% sure that there is a repeat, however I have a strong reason to believe so, due to the diagonals that appear within the sub-list sequence. The structure of a list of sub-lists is preferred, ... | 0 | 2016-07-19T15:44:46Z | 38,502,260 | <p>Here's some fairly simple code that scans a string for adjacent repeating subsequences. Set <code>minrun</code> to the length of the smallest subsequences that you want to check. For each match, the code prints the starting index of the first subsequence, the length of the subsequence, and the subsequence itself.</p... | 1 | 2016-07-21T10:50:46Z | [
"python",
"list",
"sequence",
"repeating",
"sublist"
] |
compare two list of files between different directories in python | 38,463,117 | <p>I am trying to compare two list of files from different directories. If there is a match found, the file should be written in a different directory. Below is my code. </p>
<pre><code>filelist= ['sample2\\output_1.txt','sample2\\output_2.txt','sample3\\asn_todlx_mf_output_3.txt']
filelist2 = ['sample\\output_1.txt',... | 0 | 2016-07-19T15:45:42Z | 38,463,288 | <p>That's how i would do it.</p>
<pre><code>filelist1 = ['sample2\\output_1.txt','sample2\\output_2.txt','sample3\\asn_todlx_mf_output_3.txt']
filelist2 = ['sample\\output_1.txt','sample\\output_3.txt','sample\\output_7.txt','sample\\output_2.txt','sample1\\output_3.txt']
dir1 = filelist1[0].split('\\')[:-1]
file... | 0 | 2016-07-19T15:54:08Z | [
"python",
"file",
"data-structures"
] |
Fetching a specific column from SQLAlchemy relationship | 38,463,207 | <p>I need to allow a user block other users in my app. My problem occurs when I want to check if a user has been blocked by the current (logged-in user). How do I check if a particular user is in the blocked list of the current user? My models are below:</p>
<pre><code>class User(db.Model):
__tablename__ = 'users'
id... | 0 | 2016-07-19T15:49:40Z | 38,469,957 | <p>You can use <code>.any</code> on a relationship, like so:</p>
<pre><code>alice = User(urid='alice', full_name='Alice')
bob = User(urid='bob', full_name='Bob')
session.add(Blacklist(owner=alice, blocked=bob))
session.commit()
bob_blocked_alice = (
session.query(User.blockedlist.any(blocked_id=alice.id))
.f... | 0 | 2016-07-19T23:09:48Z | [
"python",
"sqlalchemy"
] |
Correct way of computing a covariance matrix of two matrices with different number of features and same number of observations | 38,463,210 | <p>What is the proper way of computing the covariance matrix of two matices, X of shape <code>(n x p)</code> and Y of shape <code>(n x q)</code></p>
<pre><code>import numpy as np
X = np.array([np.random.normal(size=10),
np.random.normal(size=10),
np.random.normal(size=10)]).T
Y = np.array([np.rando... | 1 | 2016-07-19T15:50:08Z | 38,463,465 | <p>From the documentation:</p>
<pre><code>y : array_like, optional
An additional set of variables and observations.
y has the same form as that of m.
</code></pre>
<p>The shape of the matrices is not equal. I suppose the numpy authors forgot to check the dimensions in the first case. I have no other explanat... | 1 | 2016-07-19T16:02:07Z | [
"python",
"numpy"
] |
Modifying and writing data in an existing excel file using Python | 38,463,258 | <p>I have an Excel file(xlsx) that already has lots of data in it. Now I am trying to use Python to write new data into this Excel file. I looked at xlwt, xldd, xlutils, and openpyxl, all of these modules requires you to load the data of my excel sheet, then apply changes and save to a new Excel file. Is there any way ... | 0 | 2016-07-19T15:52:31Z | 38,463,454 | <p>This is not possible because XLSX files are zip archives and cannot be modified in place. In theory it might be possible to edit only a part of the archive that makes up an OOXML package but, in practice this is almost impossible because relevant data may be spread across different files.</p>
| 2 | 2016-07-19T16:01:36Z | [
"python",
"openpyxl",
"xlrd",
"xlwt",
"xlutils"
] |
Python with Selenium - Cannot find and click this specific element due to randomization of it's location on the site | 38,463,264 | <p>I've been creating a tool that plays through an online game using python 2.7 and selenium, and am very stuck on one particular element I need to select.</p>
<p>The UI looks as follows:</p>
<pre><code>1 2 3
a d g
b e h
c f i
</code></pre>
<p>The numbers one two and three represent a drop down menu,... | 2 | 2016-07-19T15:53:01Z | 38,464,848 | <p>If you are looking to locate an element by the text it contains you can use XPath. You stated that you tried XPath but no specifics were given. Did you try the below? It should work given the HTML you provided.</p>
<pre><code>//button[text()='Wait and See What They Do']
</code></pre>
<p>To read this XPath... find ... | 0 | 2016-07-19T17:24:29Z | [
"python",
"selenium",
"xpath",
"css-selectors",
"element"
] |
Prepending instead of appending NaNs in pandas using from_dict | 38,463,305 | <p>I have a pandas dataframe that I am reading from a <code>defaultdict</code> in Python, but some of the columns have different lengths. Here is what the data might look like:</p>
<pre><code>Date col1 col2 col3 col4 col5
01-01-15 5 12 1 -15 10
01-02-15 7 0 9 ... | 5 | 2016-07-19T15:54:35Z | 38,463,479 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow"><code>Series.shift</code></a> to induce the Series/DataFrame. Unfortunately you can't pass in array of periods - you must shift each column by an integer value.</p>
<pre><code>s = df.isnull().sum()
f... | 3 | 2016-07-19T16:02:40Z | [
"python",
"pandas"
] |
Prepending instead of appending NaNs in pandas using from_dict | 38,463,305 | <p>I have a pandas dataframe that I am reading from a <code>defaultdict</code> in Python, but some of the columns have different lengths. Here is what the data might look like:</p>
<pre><code>Date col1 col2 col3 col4 col5
01-01-15 5 12 1 -15 10
01-02-15 7 0 9 ... | 5 | 2016-07-19T15:54:35Z | 38,463,531 | <p>Reverse every list in the dictionary:</p>
<pre><code>for k, v in d.iteritems():
d[k] = v[::-1]
df = pd.DataFrame.from_dict(d, orient='index').T.set_index('Date').sort_index(1).sort_index().astype(float)
</code></pre>
<p><a href="http://i.stack.imgur.com/kBQqg.png" rel="nofollow"><img src="http://i.stack.imgur... | 3 | 2016-07-19T16:05:33Z | [
"python",
"pandas"
] |
Prepending instead of appending NaNs in pandas using from_dict | 38,463,305 | <p>I have a pandas dataframe that I am reading from a <code>defaultdict</code> in Python, but some of the columns have different lengths. Here is what the data might look like:</p>
<pre><code>Date col1 col2 col3 col4 col5
01-01-15 5 12 1 -15 10
01-02-15 7 0 9 ... | 5 | 2016-07-19T15:54:35Z | 38,463,748 | <p>A little modification on the itertools solution to your <a href="http://stackoverflow.com/q/38446457/2285236">earlier question</a>:</p>
<pre><code>pd.DataFrame(list(itertools.zip_longest(*[reversed(i) for i in d.values()]))[::-1], columns=d.keys()).sort_index(axis=1)
Out[143]:
Date col1 col2 col3 col4 ... | 4 | 2016-07-19T16:17:41Z | [
"python",
"pandas"
] |
Prepending instead of appending NaNs in pandas using from_dict | 38,463,305 | <p>I have a pandas dataframe that I am reading from a <code>defaultdict</code> in Python, but some of the columns have different lengths. Here is what the data might look like:</p>
<pre><code>Date col1 col2 col3 col4 col5
01-01-15 5 12 1 -15 10
01-02-15 7 0 9 ... | 5 | 2016-07-19T15:54:35Z | 38,465,701 | <p>Here's a vectorized approach that uses <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html" rel="nofollow"><code>pd.DataFrame.from_dict</code></a> to get the dataframe for the usual case. Once we have a regular <code>2D</code> data available, it becomes easy enough to flip ... | 0 | 2016-07-19T18:13:05Z | [
"python",
"pandas"
] |
How many arguments can be passed to filter() | 38,463,348 | <p>Can we pass two arguments in the function that returns true and filters a list?
I am trying to get divisor from user and dividend be picked up from the list.</p>
<pre><code> new_list=[1,2,3,4,5,6,7,8,9,10]
print "Get the divisor"
divisor=int(input())
h=lambda x,divisor: x%divisor==0
ans=filter(h(... | -1 | 2016-07-19T15:56:38Z | 38,463,434 | <p>Yes, you can, if you have <code>divisor</code> defined in the surrounding scope. </p>
<p>But then, you will not <em>need</em> to use it as an argument any longer:</p>
<pre><code>divisor = int(raw_input())
ans = filter(lambda x: x % divisor==0, new_list)
print ans
</code></pre>
| 2 | 2016-07-19T16:00:25Z | [
"python",
"lambda",
"filter"
] |
How many arguments can be passed to filter() | 38,463,348 | <p>Can we pass two arguments in the function that returns true and filters a list?
I am trying to get divisor from user and dividend be picked up from the list.</p>
<pre><code> new_list=[1,2,3,4,5,6,7,8,9,10]
print "Get the divisor"
divisor=int(input())
h=lambda x,divisor: x%divisor==0
ans=filter(h(... | -1 | 2016-07-19T15:56:38Z | 38,463,462 | <p>You have two errors in your approach:</p>
<p>(1) You don't need to define <code>divisor</code> as the second argument to <code>lambda</code> as it is initialized by your <code>input</code> statement.</p>
<p>(2) You should only pass the function reference to <code>filter</code>, not call the function.</p>
<pre><co... | 0 | 2016-07-19T16:02:02Z | [
"python",
"lambda",
"filter"
] |
How many arguments can be passed to filter() | 38,463,348 | <p>Can we pass two arguments in the function that returns true and filters a list?
I am trying to get divisor from user and dividend be picked up from the list.</p>
<pre><code> new_list=[1,2,3,4,5,6,7,8,9,10]
print "Get the divisor"
divisor=int(input())
h=lambda x,divisor: x%divisor==0
ans=filter(h(... | -1 | 2016-07-19T15:56:38Z | 38,463,498 | <p>You don't need to pass in <code>divisor</code> as an argument; it is simply available as a <em>closure</em>:</p>
<pre><code>new_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print "Get the divisor"
divisor = int(raw_input()) # on Python 2, you want to use raw_input
# divisor is taken from the parent scope here
h = lambd... | 0 | 2016-07-19T16:03:38Z | [
"python",
"lambda",
"filter"
] |
Selecting multiple specific columns in excel and exporting to CSV using Python | 38,463,349 | <p>I'm trying to extract 3 columns in a large excel spreadsheet and export it to CSV format. I have XLRD but have found that there are no column specific tools I can use (Or maybe I just overlooked it).</p>
<p>An example excel spreadsheet I have looks like the following</p>
<pre><code>Column1 Column2 C... | 0 | 2016-07-19T15:56:40Z | 38,464,265 | <p>Try that for exporting the 2nd and 3rd column as an example </p>
<pre><code>...
for rownum in xrange(sheet.nrows):
wr.writerow([sheet.cell(rownum, 1).value,
sheet.cell(rownum, 2).value])
</code></pre>
| 0 | 2016-07-19T16:49:52Z | [
"python",
"excel",
"csv",
"python-2.x"
] |
Subtitles within Matplotlib legend | 38,463,369 | <p>I am doing some plotting with matplotlib, and I have a legend which tells the viewer which sensors the points were recorded with. There are multiple sensors of multiple types, and I'd like to have subtitles within the legend to tell the viewer what kind of sensor each group is. I have a working solution, but it's a ... | 4 | 2016-07-19T15:57:21Z | 38,486,135 | <p>The best I could come up with is to make a custom handler for a string.</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.text as mtext
class LegendTitle(object):
def __init__(self, text_props=None):
self.text_props = text_props or {}
super(LegendTitle, self).__init__()
def... | 2 | 2016-07-20T16:37:29Z | [
"python",
"matplotlib",
"plot",
"legend",
"cartopy"
] |
how multiple processes effect the same Tkinter window in python? | 38,463,373 | <p>I am beginner in python and want to know can we run multiple processes on same tkinter window if yes, How ? What will be effects on tkinter windows during multiple processes?</p>
| -1 | 2016-07-19T15:57:36Z | 38,513,731 | <p>No, multiple processes cannot share a single window. You can certainly write a program using multiple processes which share data, but only one process can access the tkinter objects.</p>
| 0 | 2016-07-21T20:25:22Z | [
"python",
"tkinter",
"process"
] |
The program scss is not currently installed | 38,463,453 | <p>I have been trying to install scss from <a href="https://pythonhosted.org/scss/" rel="nofollow">here</a>. After sucessfully running <code>pip install scss</code>, I then tried to run scss as follows:</p>
<pre><code>scss -i
</code></pre>
<p>However, I then got the error that </p>
<pre><code>The program 'scss' is ... | 1 | 2016-07-19T16:01:35Z | 38,463,782 | <p>Make sure you have the original SCSS/SASS installed from <a href="http://sass-lang.com/install" rel="nofollow">here</a>.</p>
| 0 | 2016-07-19T16:19:09Z | [
"python",
"css",
"installation",
"sass"
] |
The program scss is not currently installed | 38,463,453 | <p>I have been trying to install scss from <a href="https://pythonhosted.org/scss/" rel="nofollow">here</a>. After sucessfully running <code>pip install scss</code>, I then tried to run scss as follows:</p>
<pre><code>scss -i
</code></pre>
<p>However, I then got the error that </p>
<pre><code>The program 'scss' is ... | 1 | 2016-07-19T16:01:35Z | 38,464,091 | <p>On Ubuntu, if I do the following, the python version of scss appears to work fine (mind you, I don't have experience with this module).</p>
<pre><code>$ virtualenv so1
New python executable in so1/bin/python
Installing setuptools, pip...done.
$ cd so1
$ source bin/activate
$ pip install scss
Downloading/unpacking s... | 0 | 2016-07-19T16:37:44Z | [
"python",
"css",
"installation",
"sass"
] |
How to query a PyTables frame_table saved via a Pandas Dataframe? | 38,463,570 | <p>I have the following pandas dataframe:</p>
<pre><code>import pandas as pd
df = pd.read_table('fname.dat')
</code></pre>
<p>So, I create/ open an existing HDFStore file:</p>
<pre><code>store = pd.HDFStore('store.h5')
</code></pre>
<p>To index a subset of columns, I simply use</p>
<pre><code>store.append('key_nam... | 0 | 2016-07-19T16:07:41Z | 38,464,681 | <p><code>frame_table</code> - means that it's a Data Frame saved in <code>table</code> format.</p>
<p>You have already "indexed" <code>['colA','colB','colZ']</code> columns, when used <code>data_columns=['colA','colB','colZ']</code> parameter.</p>
<p>So now you can query your HDFStore as follows:</p>
<pre><code>stor... | 2 | 2016-07-19T17:14:34Z | [
"python",
"pandas",
"hdf5",
"pytables",
"h5py"
] |
Tornado hello_world test returns 599 | 38,463,622 | <p>I am using Tornado 4.4 with CPython 2.7. </p>
<p>I copied:</p>
<pre><code>import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __na... | 0 | 2016-07-19T16:10:22Z | 38,463,795 | <p>It looks like you've mistakenly indented the code in <code>hello.py</code>. This line should not be indented at all:</p>
<pre><code>def make_app():
</code></pre>
<p>That is to say, in the Tornado docs <code>make_app</code> is a module-level function, but in your code you've made it a member of MainHandler.</p>
| 0 | 2016-07-19T16:19:57Z | [
"python",
"tornado"
] |
Tornado hello_world test returns 599 | 38,463,622 | <p>I am using Tornado 4.4 with CPython 2.7. </p>
<p>I copied:</p>
<pre><code>import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __na... | 0 | 2016-07-19T16:10:22Z | 38,506,669 | <p>I forgot to mention that I was executing this test in VirtualBox/Ubuntu 14.04. And it turns out this is very important since I am not getting that 599 when I run it directly in OSX or VirtualBox/Debian Jessie. I am still perplexed though since Ubuntu 14.04 is derived from Jessie and I was expecting similar behaviour... | 0 | 2016-07-21T14:14:49Z | [
"python",
"tornado"
] |
Ordering 2 symmetric matrices in the same fashion | 38,463,732 | <p>I have 2 symmetric matrices, one of them being a correlation matrix and the other one similar to a correlation matrix. Examples of these matrices are shown below:</p>
<p><strong>Correlation Matrix (c):</strong></p>
<pre><code> A B C D
A 1 0.5 0.1 0.4
B 0.5 1 0.9 0.3
C 0.1 0.9 1 0.3
... | 3 | 2016-07-19T16:16:31Z | 38,463,884 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow"><code>Series.reindex</code></a></p>
<pre><code>c_series = c.unstack().drop([(x, x) for x in c]).sort_values(ascending=False)
z_series = z.unstack().reindex(c_series.index)
</code></pre>
| 3 | 2016-07-19T16:25:05Z | [
"python",
"pandas",
"matrix",
"dataframe"
] |
Passing elements & performing computations on a list within dictionary within a dictionary | 38,463,887 | <p>I have a dictionary of the form:-</p>
<pre><code>DictName = {'A1': {'B': ['B1', 'B2'], 'C': ['C1', 'C2']}, 'A2': {'B': ['B3', 'B4'], 'C': ['C3', 'C4']}}
</code></pre>
<p>My attempts at performing calculations on the list elements have been futile</p>
<p>for eg:</p>
<pre><code>[B1, B2] - [B3 - B4]
</code></pre>
... | -1 | 2016-07-19T16:25:10Z | 38,464,343 | <p>The function <code>_calculate_distance</code> takes two lists.</p>
<p>If your dictionary looks like this:</p>
<pre><code>DictName = {'A1': {'B': [1, 2], 'C': [1, 1]}, 'A2': {'B': [1, 4], 'C': [3, 2]}}
</code></pre>
<p>and you want to pass the list in <code>'A1', 'B'</code> you can access that list with the follow... | 0 | 2016-07-19T16:54:55Z | [
"python",
"list",
"function",
"dictionary"
] |
Python: How to search for a multivalued field in a list WITHOUT more queries? | 38,463,902 | <p>I have two models in my Django app, Project and ProjectCategory, and Project has this multivalued field <em>category</em>. </p>
<pre><code>class ProjectCategory(models.Model):
name = models.CharField(max_length=200)
...
class Project(models.Model):
category = models.ManyToManyField(ProjectCategory)
... | 0 | 2016-07-19T16:25:58Z | 38,464,026 | <p>You can pass in multiple lookups to .prefetch_related()</p>
<pre><code>portfolio = Project.objects.all().order_by('name').prefetch_related()
</code></pre>
| 0 | 2016-07-19T16:33:58Z | [
"python",
"django",
"django-models"
] |
compose functions with map in python | 38,463,918 | <p>Compose map function in python</p>
<p>Hello </p>
<p>Today I use two map call to transform a mask on <code>0</code> <code>1</code> string to boolean:</p>
<pre><code>>>> a, b = '10'
>>> a, b = map(int, (a, b))
>>> a, b = map(bool, (a, b))
>>> a, b
(True, False)
</code></pre>
<p>... | 3 | 2016-07-19T16:26:56Z | 38,464,219 | <p>Python doesn't have a function composition operator, so there's not a built-in way to do that. In this specific case, the easiest way to reduce the <code>map</code> call to one line is with a lambda:</p>
<pre><code>a, b = map(lambda x: bool(int(x)), (a, b))
</code></pre>
<p>You could write a more general <a href="... | 4 | 2016-07-19T16:46:59Z | [
"python"
] |
compose functions with map in python | 38,463,918 | <p>Compose map function in python</p>
<p>Hello </p>
<p>Today I use two map call to transform a mask on <code>0</code> <code>1</code> string to boolean:</p>
<pre><code>>>> a, b = '10'
>>> a, b = map(int, (a, b))
>>> a, b = map(bool, (a, b))
>>> a, b
(True, False)
</code></pre>
<p>... | 3 | 2016-07-19T16:26:56Z | 38,465,720 | <p>You can get the job done in one line of code by using two list comprehensions instead of <code>map()</code> like this:</p>
<pre><code>>>> a, b = [bool(number) for number in [int(letter) for letter in '10']]
>>> a, b
(True, False)
</code></pre>
| 1 | 2016-07-19T18:13:54Z | [
"python"
] |
Find the difference between two dates/times | 38,463,944 | <p>I generate and insert a time and date into my SQLite3 database in Python with the following command:</p>
<pre><code>connection.execute("INSERT INTO ActiveTable (IDPK, time) VALUES (NULL, datetime('now', 'localtime'))")
</code></pre>
<p>The time is stored into the database in an INTEGER field with the format: </p>
... | 0 | 2016-07-19T16:28:36Z | 38,464,408 | <pre><code>from datetime import datetime
day1 = datetime.strptime("2016-07-18 08:58:48","%Y-%m-%d %H:%M:%S")
day2 = datetime.strptime("2016-02-18 07:58:48","%Y-%m-%d %H:%M:%S")
print(day1 -day2)
</code></pre>
<p>Output:</p>
<pre><code>151 days, 1:00:00
</code></pre>
| 1 | 2016-07-19T16:59:27Z | [
"python",
"datetime",
"sqlite3"
] |
Averaging between select varibles on an RLE list, having trouble with the last element | 38,463,950 | <p>So I have created a compressed list using run length encoding. Now I'm attempting to find averages within certain variables in the list (e.g. <code>450</code> and <code>180</code>). The code should work like this </p>
<pre><code> a=[[180,3],[140,1],[160,1],[150,2],[450,1][180,4]]
print mean(a)
>[[180,3],[150,4... | 0 | 2016-07-19T16:29:01Z | 38,467,909 | <p>Assuming you shouldn't have duplicate entries of 180 in your output, and your expected output is:</p>
<pre><code>[[180,7],[150,4],[450,1]]
</code></pre>
<p>I think this will do it:</p>
<pre><code>from collections import defaultdict
def mean(lst):
d = defaultdict(int)
sm, count = 0.0, 0
for [k, v] in l... | 0 | 2016-07-19T20:27:28Z | [
"python",
"list",
"run-length-encoding"
] |
Perform a function for x seconds on python | 38,464,028 | <p>I´m new in python programming. I´m trying to develop a software runing on <code>Raspy3</code>. The problem is, that I want a button to perform a function during x seconds (10 in this case). I tried using QTimer.singleshot, using Lambda, but it freezes my computer and windows console says something like:
<code>QEve... | 0 | 2016-07-19T16:34:09Z | 38,464,977 | <p>Without having your <code>ui_1</code> module, I can't really debug this further, but this may solve an error you're having or will have once you solve your current problem..</p>
<pre><code>import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtCore import (QTime)
from PyQt4.QtCore import pyqtSignal as Signa... | 0 | 2016-07-19T17:31:16Z | [
"python",
"user-interface"
] |
Perform a function for x seconds on python | 38,464,028 | <p>I´m new in python programming. I´m trying to develop a software runing on <code>Raspy3</code>. The problem is, that I want a button to perform a function during x seconds (10 in this case). I tried using QTimer.singleshot, using Lambda, but it freezes my computer and windows console says something like:
<code>QEve... | 0 | 2016-07-19T16:34:09Z | 38,465,103 | <p>In your function <code>blanco</code> cr never gets incremented. The value returned from crono function is not assigned anywhere. I never used PyQt(only Qt4 C++), but you can try this ( I don't know what your sliders are doing, so excuse me as I am gonna ignore them :) ):</p>
<p>Add your <code>__init__</code> this:<... | 0 | 2016-07-19T17:38:39Z | [
"python",
"user-interface"
] |
Differentiate local imports from system imports | 38,464,054 | <p>I just wrote this code:</p>
<pre><code>import os
import helpers
</code></pre>
<p>And immediately I realized that later when I read this, I'll be wondering if <code>helpers</code> is a system module or one that I have written and put in the project's dir (I can't remember that much! :)).</p>
<p><strong>Any Pythoni... | 2 | 2016-07-19T16:35:22Z | 38,464,992 | <p>In several companies I've worked at and several open source projects I've seen, this is simply done by coding convention of separating import statements into groups, with newlines splitting them. </p>
<p>The groups are always in this order: core library imports, followed by third-party imports, followed by first p... | 1 | 2016-07-19T17:32:16Z | [
"python",
"python-import"
] |
How to get rid of unattended breakpoints in Python library code? | 38,464,058 | <p>Every time I start a debugging process for Python code in Visual Studio 2015, I need to go through a lot of stops at several lines in Python library, which are executed before my code is loaded. For example, there are unattended breakpoints (which are not shown in interface) at line 143, 147 and 184 of <code>site.py... | 0 | 2016-07-19T16:35:33Z | 38,464,248 | <p>Select the <strong>Debug</strong> item in the menu, then select the <strong>Delete All Breakpoints</strong> option. The keyboard shortcut <strong>Ctrl+Shift+F9</strong> will accomplish the same. </p>
| 1 | 2016-07-19T16:48:59Z | [
"python",
"visual-studio-debugging"
] |
Python: Optimizing Module Imports | 38,464,124 | <p>This is a theoretical question that I have been looking for an answer to for sometime, but could never actually find it.</p>
<p>Suppose I have my main file <code>main.py</code> which has <code>import numpy as np</code> and <code>import helper</code>.</p>
<p>If I have a helper file <code>helper.py</code>, could I u... | 1 | 2016-07-19T16:40:13Z | 38,464,572 | <p>No. The <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">python documentation</a> states:</p>
<blockquote>
<p>The import statement combines two operations; it searches for the
named module, then it binds the results of that search to a name in
the local scope.</p>
</blockquote>
<p>If ... | 1 | 2016-07-19T17:08:28Z | [
"python",
"import",
"module"
] |
python pandas sorting by group | 38,464,142 | <p>Each row in my DataFrame is a user vote entry for a restaurant. The data look like </p>
<pre><code>id cuisine
91 american
3 american
91 american
233 cuban
233 cuban
2 cuban
</code></pre>
<p>where <code>id</code> refers to the restaurant. </p>
<p>I want to get something... | 1 | 2016-07-19T16:41:02Z | 38,464,365 | <p>is that what you want?</p>
<pre><code>In [2]: df
Out[2]:
id cuisine
0 91 american
1 3 american
2 91 american
3 233 cuban
4 233 cuban
5 2 cuban
In [3]: df.groupby(['cuisine', 'id']).size()
Out[3]:
cuisine id
american 3 1
91 2
cuban 2 1
233 ... | 2 | 2016-07-19T16:56:16Z | [
"python",
"pandas",
"group-by",
"pivot-table"
] |
python pandas sorting by group | 38,464,142 | <p>Each row in my DataFrame is a user vote entry for a restaurant. The data look like </p>
<pre><code>id cuisine
91 american
3 american
91 american
233 cuban
233 cuban
2 cuban
</code></pre>
<p>where <code>id</code> refers to the restaurant. </p>
<p>I want to get something... | 1 | 2016-07-19T16:41:02Z | 38,464,909 | <p>use <code>value_counts</code> after <code>group_by</code> followed by <code>sort_index</code></p>
<pre><code># ascending=[1, 0] says True for level[0], False for level[1]
df.groupby('cuisine').id.value_counts().sort_index(ascending=[1, 0])
cuisine id
american 91 2
3 1
cuban 233 2
... | 2 | 2016-07-19T17:27:51Z | [
"python",
"pandas",
"group-by",
"pivot-table"
] |
Creating a pandas.DataFrame wrapper that has a method to return a dataframe | 38,464,173 | <p>I'm trying to create a class that is a wrapper around <code>pandas.DataFrame</code> objects. After I write my own methods for this class, I would like pandas' methods to be also available, but in a way that explicitly tells me/the user that their are from pandas. It would work like this</p>
<pre><code>df = pd.DataF... | 1 | 2016-07-19T16:43:29Z | 38,465,607 | <p>You can not use <code>DataFrame</code> as the parent:</p>
<pre><code>class myData(object):
"""
Attempt to create a myData object
"""
def __init__(self, df):
self.df = df.copy()
df = pd.DataFrame(np.random.randn(100, 5), columns=list('ABCDE'))
mdf = myData(df)
mdf.df.describe()
</code></pre>... | 0 | 2016-07-19T18:08:21Z | [
"python",
"class",
"pandas",
"dataframe"
] |
Graph with graphviz | 38,464,180 | <p>I have df</p>
<pre><code> id, url, search_term
1, vkontakte.ru, vk
1, apple.com, iphone кÑпиÑÑ
1, asos.com, кÑпиÑÑ Ð¾Ð´ÐµÐ¶Ð´Ñ asos
2, facebook.com, facebook
2, twitter.com, twitter
2, stackoverflow.com, how to explore decision tree python
</code></pre>
<p>And I try to build chains with arrows
I t... | 3 | 2016-07-19T16:43:59Z | 38,464,339 | <p>You should take the creation of the graph and the view outside the loop:</p>
<pre><code>f = Digraph('finite_state_machine', filename='fsm.gv', encoding='utf-8')
f.body.extend(['rankdir=LR', 'size="5,5"'])
f.attr('node', shape='circle')
for i, (id, domain, search_term) in enumerate(zip(df['ID'], df['domain'], df['se... | 0 | 2016-07-19T16:54:37Z | [
"python",
"pandas",
"graphviz"
] |
Wrapping a python class around JSON data, which is better? | 38,464,302 | <p>
<strong>Preamble</strong>: I'm writing a python API against a service that delivers JSON.
The files are stored in JSON format on disk to cache the values.
The API should sport classful access to the JSON data, so IDEs and users can have a clue what (read-only) attributes there are in the object before runtime while... | 4 | 2016-07-19T16:51:56Z | 38,471,170 | <p>Have you considered using a meta-class?</p>
<pre><code>class JsonDataWrapper(object):
def __init__(self, json_data):
self._data = json_data
def get(self, name):
return self._data[name]
class JsonDataWrapperMeta(type):
def __init__(self, name, base, dict):
for mbr in self.member... | 1 | 2016-07-20T02:04:08Z | [
"python",
"json",
"class",
"wrapper",
"api-design"
] |
Saving exceptions in Tkinter using Python | 38,464,351 | <p>I have developed several Python programs for others that use Tkinter to receive input from the user. In order to keep things simple and user-friendly, the command line or python console are never brought up (ie. .pyw files are used), so I'm looking into using the logging library to write error text to a file when an... | 1 | 2016-07-19T16:55:32Z | 38,480,838 | <p>It's not very well documented, but tkinter calls a method for exceptions that happen as the result of a callback. You can write your own method to do whatever you want by setting the attribute <code>report_callback_exception</code> on the root window.</p>
<p>For example:</p>
<pre><code>import tkinter as tk
def ha... | 1 | 2016-07-20T12:06:17Z | [
"python",
"tkinter"
] |
Matching 2 large csv files by Fuzzy string matching in Python | 38,464,369 | <p>I am trying to approximately match 600,000 individuals names (Full name) to another database that has over 87 millions observations (Full name) !</p>
<p>My first attempt with <strong>fuzzywuzzy</strong> library was way too slow, so I decided to use the module <strong>fuzzyset</strong> which is much faster. Assuming... | 1 | 2016-07-19T16:56:26Z | 38,929,764 | <p>So I am going to answer my own question since I found a way that is pretty fast.</p>
<p>I saved both databases in HDF5 format, using the panda.HDFStore and panda.to_hdf methods.
I saved into one dataframe for each first letter of the last name.
Then, I created a function finding the closest match, based on the pyth... | 1 | 2016-08-13T06:04:52Z | [
"python",
"performance",
"string-matching",
"fuzzywuzzy"
] |
print out if two conditions are met | 38,464,431 | <p>What I want to do is modify the if statement that I have below for dT. Right now I have it printing out "Temperature" "dT" "Steady State" if dT is between -.5 and .5 but instead I want it to print out those three items only if the dT value is between -.5 and .5 for ten straight iterations. If not, it should just pri... | 1 | 2016-07-19T17:00:22Z | 38,464,646 | <p>You can use a count variable, set the count variable to 0 whenever the condition has been hit 10 times in a row or the streak is broken</p>
| 0 | 2016-07-19T17:11:50Z | [
"python"
] |
print out if two conditions are met | 38,464,431 | <p>What I want to do is modify the if statement that I have below for dT. Right now I have it printing out "Temperature" "dT" "Steady State" if dT is between -.5 and .5 but instead I want it to print out those three items only if the dT value is between -.5 and .5 for ten straight iterations. If not, it should just pri... | 1 | 2016-07-19T17:00:22Z | 38,464,699 | <p>Just use <code>if</code> instead of <code>for</code>. Also use <code>0.5</code> instead of <code>.5</code> for readability. Consider using <code>format</code> method for displaying strings, espesially if you're using Python 3x.</p>
| 1 | 2016-07-19T17:15:41Z | [
"python"
] |
print out if two conditions are met | 38,464,431 | <p>What I want to do is modify the if statement that I have below for dT. Right now I have it printing out "Temperature" "dT" "Steady State" if dT is between -.5 and .5 but instead I want it to print out those three items only if the dT value is between -.5 and .5 for ten straight iterations. If not, it should just pri... | 1 | 2016-07-19T17:00:22Z | 38,466,884 | <p>I think this is what you might want:</p>
<p>I am editing my answer with new code. If this is the wrong thing to do, I'll delete this answer and add a new one. My mind was close but kind of messy.</p>
<p>This code first finds all the places where the data is out of range and records their indices (stops). It the... | 1 | 2016-07-19T19:23:58Z | [
"python"
] |
Why evaluate self._initial_state when training RNN in Tensorflow | 38,464,519 | <p>In the RNN tutorial <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofollow">ptd_word_lm.py</a>. When training the RNN using run_epoch, why is it necessary to evaluate self._initial_state? </p>
<pre><code>def run_epoch(session, m, data, eval_op, verbose=... | 0 | 2016-07-19T17:06:14Z | 38,484,046 | <p>In the PTB example, the sentences are concatenated and split into batches (of size batch_size x num_steps). After each batch, the last state of the RNN is passed as the initial state of the next batch. This effectively allows you to train the RNN as if it was one very long chain over the entire PTB corpus (and this ... | 1 | 2016-07-20T14:28:02Z | [
"python",
"tensorflow",
"lstm",
"recurrent-neural-network"
] |
How to advance a for loop by 2 iterations? | 38,464,529 | <p>I'm reading a large text file and I need to read a number from a specific line. The file looks like this:</p>
<pre><code>....
unknown number of lines
....
ABCD
some random stuff
a number I want to read
....
....
</code></pre>
<p>I want to read the number from the line that is 2 lines after a "signature" line that'... | 2 | 2016-07-19T17:06:36Z | 38,464,686 | <p>If you don't need any information at all from the skipped line, you can advance the file manually by a line before <code>continue</code>ing:</p>
<pre><code>with open(filename,'r') as f:
for line in f:
if line.rstrip('\n') == 'ABCD':
next(f) # The next iteration of the for loop will skip ... | 0 | 2016-07-19T17:14:57Z | [
"python",
"python-3.x",
"for-loop",
"file-io"
] |
How to advance a for loop by 2 iterations? | 38,464,529 | <p>I'm reading a large text file and I need to read a number from a specific line. The file looks like this:</p>
<pre><code>....
unknown number of lines
....
ABCD
some random stuff
a number I want to read
....
....
</code></pre>
<p>I want to read the number from the line that is 2 lines after a "signature" line that'... | 2 | 2016-07-19T17:06:36Z | 38,464,738 | <p>You could explicitly call <code>next</code> on <code>f</code><sup>*</sup> (which the for loop usually does for you) and advance the iterator and then call <code>continue</code>:</p>
<pre><code>for line in f:
if line.rstrip('\n') == 'ABCD':
next(f)
continue
print(line)
</code></pre>
<p>This ... | 5 | 2016-07-19T17:18:11Z | [
"python",
"python-3.x",
"for-loop",
"file-io"
] |
How to advance a for loop by 2 iterations? | 38,464,529 | <p>I'm reading a large text file and I need to read a number from a specific line. The file looks like this:</p>
<pre><code>....
unknown number of lines
....
ABCD
some random stuff
a number I want to read
....
....
</code></pre>
<p>I want to read the number from the line that is 2 lines after a "signature" line that'... | 2 | 2016-07-19T17:06:36Z | 38,464,765 | <p>If you want to stick with this approach then do this:</p>
<pre><code>f = open(filename,'r'):
while f.readline().rstrip('\n') != 'ABCD': # this will advanced the pointer to the ABCD line
continue
f.next() # to skip over the unnecessary stuff
desiredNumber = f.readline() # desired line
</code></pre>
<p>I think ... | 1 | 2016-07-19T17:19:55Z | [
"python",
"python-3.x",
"for-loop",
"file-io"
] |
How to advance a for loop by 2 iterations? | 38,464,529 | <p>I'm reading a large text file and I need to read a number from a specific line. The file looks like this:</p>
<pre><code>....
unknown number of lines
....
ABCD
some random stuff
a number I want to read
....
....
</code></pre>
<p>I want to read the number from the line that is 2 lines after a "signature" line that'... | 2 | 2016-07-19T17:06:36Z | 38,467,089 | <p>I prefer @Jim's use of <code>next()</code>, but another option is to just use a flag:</p>
<pre><code>with open(filename,'r') as f:
skip_line = False
for line in f:
if line.rstrip('\n') == 'ABCD':
skip_line = True
continue
if skip_line == True:
skip_line = False
else:
print(line)
</co... | 0 | 2016-07-19T19:36:23Z | [
"python",
"python-3.x",
"for-loop",
"file-io"
] |
Passing argument from PHP to Python not working | 38,464,534 | <p>I have a python srcipt, called rainbow.py. I can run it optionally with an argument. From command line
<code>python rainbow.py</code>, <code>python rainbow.py 4</code> works well. When I call this script from php I am unable to pass the argument.
I tried:</p>
<pre><code>$argument=4;
exec("python rainbow.py 4")... | 1 | 2016-07-19T17:06:42Z | 38,467,243 | <p>I added sudo to the python call:</p>
<pre><code>exec("sudo python rainbow.py $argument")
</code></pre>
<p>and it works now properly. Can someone tell me why?
The python script ran without it too, but without considering the argument.</p>
| 0 | 2016-07-19T19:46:47Z | [
"php",
"python",
"raspberry-pi",
"parameter-passing"
] |
SWIG: %ignore keeps giving "Syntax error in input(1)" | 38,464,575 | <p>Forgive me if this question is silly, but I can't find a good example of %ignore being used around the web. I'm trying to generate a python wrapper for C++ code using the following command:</p>
<pre><code>swig -python -c++ sample.i
</code></pre>
<p>I have an interface file like the following:</p>
<pre><code>%modu... | 0 | 2016-07-19T17:08:30Z | 38,466,444 | <p>You certainly need a semicolon after the <code>%ignore</code>:</p>
<pre><code>%ignore vprint;
</code></pre>
| 3 | 2016-07-19T18:57:17Z | [
"python",
"c++",
"swig"
] |
Sum values against an item in 2-D python list | 38,464,608 | <p>I have a 2-D list like this:</p>
<pre><code>myList = [ ['A', 1], ['B', 1], ['C', 3], ['A', -1], ['B', 1], ['D', 2] ];
</code></pre>
<p>And I would like to have the following result:</p>
<pre><code>mySum = [ ['A', 0], ['B', 2], ['C', 3], ['D', 2] ];
</code></pre>
<p>Tried my best, but somehow can't find any reaso... | 0 | 2016-07-19T17:09:43Z | 38,464,665 | <p>This is a pretty straight forward binning operation. A <code>collections.defaultdict</code> will work beautifully:</p>
<pre><code>from collections import defaultdict
d = defaultdict(int)
for k, v in myList:
d[k] += v
print d.items() # print(list(d.items())) on python3.x
</code></pre>
<p>Basically, the dict... | 2 | 2016-07-19T17:12:58Z | [
"python",
"list"
] |
Sum values against an item in 2-D python list | 38,464,608 | <p>I have a 2-D list like this:</p>
<pre><code>myList = [ ['A', 1], ['B', 1], ['C', 3], ['A', -1], ['B', 1], ['D', 2] ];
</code></pre>
<p>And I would like to have the following result:</p>
<pre><code>mySum = [ ['A', 0], ['B', 2], ['C', 3], ['D', 2] ];
</code></pre>
<p>Tried my best, but somehow can't find any reaso... | 0 | 2016-07-19T17:09:43Z | 38,464,750 | <p>Give this code a try:</p>
<pre><code>In [69]: from itertools import groupby
In [70]: from operator import itemgetter
In [71]: myList = [['A', 1], ['B', 1], ['C', 3], ['A', -1], ['B', 1], ['D', 2]]
In [72]: [[letter, sum(map(itemgetter(1), group))] for letter, group in groupby(sorted(myList), key=itemgetter(0))]
... | -1 | 2016-07-19T17:19:00Z | [
"python",
"list"
] |
Executable using tkinter and multiprocessing creates multiple windows | 38,464,661 | <p>I have built a gui for a script using tkinter.</p>
<p>I have tried building an executable with both cx_freeze and pyinstaller.</p>
<p>I make extensive use of scipy, numpy, statsmodels and matplotlib</p>
<p>Whenever I click the "Run" button, it spawns another window and the window beneath it stops responding. This... | -1 | 2016-07-19T17:12:41Z | 38,465,776 | <p>Two processes or more can't share a single root window. Every process that creates a widget will get its own window.</p>
| 0 | 2016-07-19T18:17:48Z | [
"python",
"tkinter",
"pyinstaller",
"cx-freeze"
] |
Executable using tkinter and multiprocessing creates multiple windows | 38,464,661 | <p>I have built a gui for a script using tkinter.</p>
<p>I have tried building an executable with both cx_freeze and pyinstaller.</p>
<p>I make extensive use of scipy, numpy, statsmodels and matplotlib</p>
<p>Whenever I click the "Run" button, it spawns another window and the window beneath it stops responding. This... | -1 | 2016-07-19T17:12:41Z | 38,466,377 | <p>I managed to fix this with some experimentation.</p>
<p>It no longer launches multiple windows after I made the business logic launch within the same process.</p>
| 0 | 2016-07-19T18:52:42Z | [
"python",
"tkinter",
"pyinstaller",
"cx-freeze"
] |
Dereferencing a pointer created with ffi.addressof in Python CFFI (C *-operator equivalent?) | 38,464,789 | <pre><code>values = ffi.new( "int[]", 10 )
pValue = ffi.addressof( pInt, 0 )
</code></pre>
<p>With Python CFFI, the code above creates a pointer to the first element of <code>values</code> as <code>pValue</code>.</p>
<p>You can then access its content with <code>values[ 0 ]</code>, but this is not really transparent ... | 0 | 2016-07-19T17:21:11Z | 38,523,268 | <p>In C, the syntax <code>*pType</code> is always equivalent to <code>pType[0]</code>. So say you would like to do something like:</p>
<pre><code>print "Type: {0}, value: {1}".format( *pType, *pValue )
</code></pre>
<p>but of course this is not valid Python syntax. The solution is that you can always rewrite it lik... | 1 | 2016-07-22T09:46:04Z | [
"python",
"c",
"pointers",
"dereference",
"python-cffi"
] |
OrderedDict too many values to unpack | 38,464,795 | <p>My program is producing:</p>
<blockquote>
<p>ValueError: too many values to unpack. </p>
</blockquote>
<p>I copied the lines of code that works in other instances.</p>
<pre><code>new_dict = (("data", 0))
new_dict = collections.OrderedDict(new_dict) #the line producing the error
</code></pre>
<p>The only differ... | 1 | 2016-07-19T17:21:34Z | 38,464,816 | <pre><code>new_dict = (("data", 0))
</code></pre>
<p>This is supposed to be a tuple containing key-value pairs. To create a tuple with just one element, add a trailing comma.</p>
<pre><code>new_dict = (("data", 0),)
</code></pre>
| 5 | 2016-07-19T17:22:38Z | [
"python",
"ordereddictionary"
] |
File saving issue PYTHON - duplicate files? | 38,464,813 | <p>I am developing a program, and one of the options is to save the data. Although there is a thread similar to this, it was never fully resolved ( <a href="http://stackoverflow.com/questions/38294000/creating-file-loop">Creating file loop</a> ). The problem is, the program does not recognise duplicate files, and I don... | 3 | 2016-07-19T17:22:30Z | 38,465,469 | <pre><code>file_selected = False
file_path = ""
while not file_selected:
file_path = input("Enter a file name")
if os.path.isfile(file_path) and input("Are you sure you want to override the file? (y/n)") != 'y':
continue
file_selected = True
#Now you can open the file using open()
</code></pre>
<p>... | 1 | 2016-07-19T18:00:00Z | [
"python",
"file",
"while-loop",
"saving-data"
] |
File saving issue PYTHON - duplicate files? | 38,464,813 | <p>I am developing a program, and one of the options is to save the data. Although there is a thread similar to this, it was never fully resolved ( <a href="http://stackoverflow.com/questions/38294000/creating-file-loop">Creating file loop</a> ). The problem is, the program does not recognise duplicate files, and I don... | 3 | 2016-07-19T17:22:30Z | 38,467,194 | <p>Although the other answer works I think this code is more explicit about file name usage rules and easier to read:</p>
<pre><code>import os
# prompt for file and continue until a unique name is entered or
# user allows overwrite
while 1:
my_file = input("Enter a file name: ")
if not os.path.exists(my_file)... | 0 | 2016-07-19T19:44:14Z | [
"python",
"file",
"while-loop",
"saving-data"
] |
File saving issue PYTHON - duplicate files? | 38,464,813 | <p>I am developing a program, and one of the options is to save the data. Although there is a thread similar to this, it was never fully resolved ( <a href="http://stackoverflow.com/questions/38294000/creating-file-loop">Creating file loop</a> ). The problem is, the program does not recognise duplicate files, and I don... | 3 | 2016-07-19T17:22:30Z | 38,467,636 | <p>This is how I advise to do it, especially when you have event driven GUI app.</p>
<pre><code>
import os
def GetEntry (prompt="Enter filename: "):
fn = ""
while fn=="":
try: fn = raw_input(prompt)
except KeyboardInterrupt: return
return fn
def GetYesNo (prompt="Yes, No, Cancel? [Y/N/C]... | 0 | 2016-07-19T20:11:08Z | [
"python",
"file",
"while-loop",
"saving-data"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.