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 can I add a constant percentage to each wedge of a pie chart using matplotlib
39,262,783
<p>Code snippet looks like this</p> <pre><code>#df is dataframe with 6 rows, with each row index being the label of the sector plt.pie(df.iloc[:,0], labels= df.index) #plot the first column of dataframe as a pie chart </code></pre> <p>It generates a pie chart like this:</p> <p><a href="http://i.stack.imgur.com/z9PXx.png" rel="nofollow">Pie Chart with the 6 sectors.</a></p> <p>As you can see, the sectors kitchen &amp; entertainment are very small. I want to make each sector have a minimum value of 10 degree (1/36 %).</p> <p>This would effectively mean fitting the data over 300 degrees (10 degree to each sector and we have 6 - Lighting, Entertainment, Kitchen, Cooling, Fridge, Others)</p>
2
2016-09-01T04:36:33Z
39,333,937
<p>Disclaimer : This is my own question.</p> <p>What <a href="http://stackoverflow.com/users/3510736/ami-tavory">Ami Tavory</a> has answered is the correct approach. I was thinking it from the perspective of plotting (fitting the data to 300 degrees instead of 360) instead of manipulating the data (which is much simpler, thanks to pandas).</p> <p>I am just posting a much simpler form of his answer:</p> <pre><code>degree = 10 #The degree you want to offset each sector with # Let the number of sectors be N plt.pie((df.iloc[:,0]*((360 - degree*N)/360) + ((degree * df.iloc[:,0].sum())/360)), labels= df.index) #The above is simply scaling the data to fit 300 (degree = 10, N = 6) # and adding a constant value of degree/360 of the total sum to each sector. </code></pre>
1
2016-09-05T15:43:24Z
[ "python", "pandas", "matplotlib" ]
Python 2.7 TypeError: 'NoneType' object has no attribute '_getitem_'
39,262,830
<p>I'm pretty new to coding and have been trying some things out. I am getting this error when I run a python script I have. I have read that this error is because something is returning "None" but I'm having trouble figuring out what is causing it (still trying to learn all of this). </p> <p>The purpose of the script is pulling thumbnails from videos and searching the internet for other instances of the same thing. After running my python script, it returns a result of:</p> <pre><code> [*] Retrieving video ID: VIDEOID Traceback (most recent call last): File "VidSearch.py", line 40, in &lt;module&gt; thumbnails = video_data['items'][0]['snippet']['thumbnails'] TypeError: 'NoneType' object has no atribute '_getitem_' </code></pre> <p>The following is the script I am running (Youtube Key removed):</p> <pre><code>import argparse import requests import json from pytineye import TinEyeAPIRequest tineye = TinEyeAPIRequest('http://api.tineye.com/rest/','PUBLICKEY','PRIVATEKEY') youtube_key = "VIDEOID" ap = argparse.ArgumentParser() ap.add_argument("-v","--videoID", required=True,help="The videoID of the YouTube video. For example: https://www.youtube.com/watch?v=VIDEOID") args = vars(ap.parse_args()) video_id = args['videoID'] # # Retrieve the video details based on videoID # def youtube_video_details(video_id): api_url = "https://www.googleapis.com/youtube/v3/videos?part=snippet%2CrecordingDetails&amp;" api_url += "id=%s&amp;" % video_id api_url += "key=%s" % youtube_key response = requests.get(api_url) if response.status_code == 200: results = json.loads(response.content) return results return None print "[*] Retrieving video ID: %s" % video_id video_data = youtube_video_details(video_id) thumbnails = video_data['items'][0]['snippet']['thumbnails'] print "[*] Thumbnails retrieved. Now submitting to TinEye." url_list = [] # add the thumbnails from the API to the list for thumbnail in thumbnails: url_list.append(thumbnails[thumbnail]['url']) # build the manual URLS for count in range(4): url = "http://img.youtube.com/vi/%s/%d.jpg" % (video_id,count) url_list.append(url) results = [] # now walk over the list of URLs and search TinEye for url in url_list: print "[*] Searching TinEye for: %s" % url try: result = tineye.search_url(url) except: pass if result.total_results: results.extend(result.matches) result_urls = [] dates = {} for match in results: for link in match.backlinks: if link.url not in result_urls: result_urls.append(link.url) dates[link.crawl_date] = link.url print print "[*] Discovered %d unique URLs with image matches." % len(result_urls) for url in result_urls: print url oldest_date = sorted(dates.keys()) print print "[*] Oldest match was crawled on %s at %s" % (str(oldest_date[0]),dates[oldest_date[0]]) </code></pre> <p>I know it's probably something simple but I can't seem to figure it out for the life of me. Any help would be greatly appreciated.</p>
-1
2016-09-01T04:45:14Z
39,264,122
<p>In your <code>youtube_video_details</code> method. the response.status_code maybe is not <code>200</code>, so the method return the <code>None</code></p> <p>So you can do like this:</p> <pre><code>video_data = youtubo_video_details(video_id) if not video_data: thumbnails = video_data['items'][0]['snippet']['thumbnails'] </code></pre>
0
2016-09-01T06:28:29Z
[ "python", "python-2.7", "typeerror" ]
python not looping search on regexe
39,262,889
<p>Sample line from file1.txt</p> <pre><code>2016-04-30 02:03:55,417 INFO [http-nio-443-exec-51] xxxxxxxxxxxxxx (xxxxxxxxxxxxxx.java:1364) - TRX[160430120042]::paymentResult::xxxxxxxxxxxxx(Billing)Response::TRANSACTION[160450001042], REFERENCE_CODE[1461953034575], END_USER_ID[tel:+639422387059], OPERATION_RESULT[CHARGED] ERR[ERR_NONE], ERR_MSG[null], RAW_RESPONSE[{ "amountTransaction":{ "serverReferenceCode":"060601159083533", "serviceID":"OX036", "transactionOperationStatus":"Charged", "endUserId":"tel:+639422387059", "referenceCode":"30001-1461953034775", "paymentAmount":{ "totalAmountCharged":"130.00", "chargingInformation":{ "description":"Description of ChargeAmount Request", "currency":"USD", "amount":"130.00" } } } }] </code></pre> <p>I just started python few days ago and was looking around the stackoverflow. I can't seems to loop each line from the file it was only searching the first line.</p> <pre><code>import re with open('file1.txt') as f: my_text = f.read() re1='((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))' # Time Stamp 1 re2='.*?' # Non-greedy match on filler re3='\\[.*?\\]' # Uninteresting: sbraces re4='.*?' # Non-greedy match on filler re5='\\[.*?\\]' # Uninteresting: sbraces re6='.*?' # Non-greedy match on filler re7='(\\[.*?\\])' # Square Braces 1 re8='.*?' # Non-greedy match on filler re9='".*?"' # Uninteresting: string re10='.*?' # Non-greedy match on filler re11='".*?"' # Uninteresting: string re12='.*?' # Non-greedy match on filler re13='(".*?")' # Double Quote String 1 re14='.*?' # Non-greedy match on filler re15='".*?"' # Uninteresting: string re16='.*?' # Non-greedy match on filler re17='(".*?")' # Double Quote String 2 re18='.*?' # Non-greedy match on filler re19='".*?"' # Uninteresting: string re20='.*?' # Non-greedy match on filler re21='(".*?")' # Double Quote String 3 re22='.*?' # Non-greedy match on filler re23='".*?"' # Uninteresting: string re24='.*?' # Non-greedy match on filler re25='(".*?")' # Double Quote String 4 re26='.*?' # Non-greedy match on filler re27='".*?"' # Uninteresting: string re28='.*?' # Non-greedy match on filler re29='(".*?")' # Double Quote String 5 re30='.*?' # Non-greedy match on filler re31='".*?"' # Uninteresting: string re32='.*?' # Non-greedy match on filler re33='".*?"' # Uninteresting: string re34='.*?' # Non-greedy match on filler re35='(".*?")' # Double Quote String 6 rg = re.compile(re1+re2+re3+re4+re5+re6+re7+re8+re9+re10+re11+re12+re13+re14+re15+re16+re17+re18+re19+re20+re21+re22+re23+re24+re25+re26+re27+re28+re29+re30+re31+re32+re33+re34+re35,re.IGNORECASE|re.DOTALL) m = rg.search(my_text) if m: timestamp1 = m.group(1) sbraces1 = m.group(2) string1 = m.group(3) string2 = m.group(4) string3 = m.group(5) string4 = m.group(6) string5 = m.group(7) string6 = m.group(8) data = timestamp1 + ',' + sbraces1.strip('[]') + ',' + string1.strip('"') + ',' + string2.strip( '"') + ',' + string3.strip('"') + ',' + string4.replace('tel:+', '').strip('"') + ',' + string5.strip( '"') + ',' + string6.strip('"') print(data) </code></pre> <p>f.close()</p> <p>Output</p> <pre><code>2016-04-30 02:03:55,160430000042,060601159083533,OB056,Charged,639422387059,30001-1461953034575,130.00 </code></pre>
0
2016-09-01T04:50:31Z
39,263,013
<p>To loop through each line of your file:</p> <pre><code>import re with open('file1.txt') as f: for line in f: # do something with line </code></pre> <p>Note that there is no need to do <code>f.close()</code>, it is already handled by the context manager <code>with ...</code></p>
0
2016-09-01T05:03:29Z
[ "python", "regex", "loops" ]
Python - Elements of copy.copy() still share memory with the original one?
39,262,918
<p>I wanted to make a copy of a list (literally a separated clone that has nothing sharing with the original). I used copy.copy() and created 2 separated lists, but why does the elements of each copy still seem to share?</p> <p>It's hard to explain, please check out the following output.</p> <pre><code>&gt;&gt;&gt; a = [[0,1], [2,3]] &gt;&gt;&gt; import copy &gt;&gt;&gt; b = copy.copy(a) &gt;&gt;&gt; temp = b.pop() &gt;&gt;&gt; temp [2, 3] &gt;&gt;&gt; a [[0, 1], [2, 3]] &gt;&gt;&gt; b [[0, 1]] &gt;&gt;&gt; temp.append(4) &gt;&gt;&gt; temp [2, 3, 4] &gt;&gt;&gt; a [[0, 1], [2, 3, 4]] &gt;&gt;&gt; b [[0, 1]] </code></pre> <p>As you see, <strong>temp</strong> is popped from <strong>b</strong>, yet when I changed <strong>temp</strong> (aka append new stuff) then the data in <strong>a</strong> also changed.</p> <p>My question is: Is this an expecting behavior of deepcopy? How can I make a totally separate copy of a list then?</p> <p>P/S: As the above example, I guess I can do<br> <code>temp = copy.copy(b.pop())</code><br> but is this a proper way? Is there any other way to do what I want?</p> <p>P/S 2: This also happens when I use b = a[:]</p> <p>Thanks!</p>
1
2016-09-01T04:54:35Z
39,263,022
<p><strong><em>friendly dog</em></strong> commented under the OP and suggested me to use deepcopy(). It works. Thanks!</p>
2
2016-09-01T05:04:21Z
[ "python", "copy" ]
Python - Elements of copy.copy() still share memory with the original one?
39,262,918
<p>I wanted to make a copy of a list (literally a separated clone that has nothing sharing with the original). I used copy.copy() and created 2 separated lists, but why does the elements of each copy still seem to share?</p> <p>It's hard to explain, please check out the following output.</p> <pre><code>&gt;&gt;&gt; a = [[0,1], [2,3]] &gt;&gt;&gt; import copy &gt;&gt;&gt; b = copy.copy(a) &gt;&gt;&gt; temp = b.pop() &gt;&gt;&gt; temp [2, 3] &gt;&gt;&gt; a [[0, 1], [2, 3]] &gt;&gt;&gt; b [[0, 1]] &gt;&gt;&gt; temp.append(4) &gt;&gt;&gt; temp [2, 3, 4] &gt;&gt;&gt; a [[0, 1], [2, 3, 4]] &gt;&gt;&gt; b [[0, 1]] </code></pre> <p>As you see, <strong>temp</strong> is popped from <strong>b</strong>, yet when I changed <strong>temp</strong> (aka append new stuff) then the data in <strong>a</strong> also changed.</p> <p>My question is: Is this an expecting behavior of deepcopy? How can I make a totally separate copy of a list then?</p> <p>P/S: As the above example, I guess I can do<br> <code>temp = copy.copy(b.pop())</code><br> but is this a proper way? Is there any other way to do what I want?</p> <p>P/S 2: This also happens when I use b = a[:]</p> <p>Thanks!</p>
1
2016-09-01T04:54:35Z
39,263,827
<p>The <code>copy.copy()</code> was shallow copy. That means, it would create a new object as same as be copied. but the elements within copied object didn't be created, and them also is a reference. <code> -&gt; a = [[0,1], [2,3]] -&gt; import copy -&gt; b = copy.copy(a) # the b be created, but [0,1] [2,3] still are reference -&gt; temp = b.pop() -&gt; temp [2, 3] -&gt; a [[0, 1], [2, 3]] -&gt; b [[0, 1]] -&gt; temp.append(4) -&gt; temp [2, 3, 4] -&gt; a [[0, 1], [2, 3, 4]] -&gt; b [[0, 1]] </code> <a href="https://docs.python.org/2/library/copy.html" rel="nofollow">Docs</a></p>
1
2016-09-01T06:09:10Z
[ "python", "copy" ]
Python - Elements of copy.copy() still share memory with the original one?
39,262,918
<p>I wanted to make a copy of a list (literally a separated clone that has nothing sharing with the original). I used copy.copy() and created 2 separated lists, but why does the elements of each copy still seem to share?</p> <p>It's hard to explain, please check out the following output.</p> <pre><code>&gt;&gt;&gt; a = [[0,1], [2,3]] &gt;&gt;&gt; import copy &gt;&gt;&gt; b = copy.copy(a) &gt;&gt;&gt; temp = b.pop() &gt;&gt;&gt; temp [2, 3] &gt;&gt;&gt; a [[0, 1], [2, 3]] &gt;&gt;&gt; b [[0, 1]] &gt;&gt;&gt; temp.append(4) &gt;&gt;&gt; temp [2, 3, 4] &gt;&gt;&gt; a [[0, 1], [2, 3, 4]] &gt;&gt;&gt; b [[0, 1]] </code></pre> <p>As you see, <strong>temp</strong> is popped from <strong>b</strong>, yet when I changed <strong>temp</strong> (aka append new stuff) then the data in <strong>a</strong> also changed.</p> <p>My question is: Is this an expecting behavior of deepcopy? How can I make a totally separate copy of a list then?</p> <p>P/S: As the above example, I guess I can do<br> <code>temp = copy.copy(b.pop())</code><br> but is this a proper way? Is there any other way to do what I want?</p> <p>P/S 2: This also happens when I use b = a[:]</p> <p>Thanks!</p>
1
2016-09-01T04:54:35Z
39,264,932
<p>You should use deepcopy() there because the copy() makes shallow clone of the object that you are referencing not the object inside it.If you want the whole object(with the object inside it) use deepcopy() instead.</p> <p>Please refer the links for better understanding</p> <p><a href="http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy">What is the difference between a deep copy and a shallow copy?</a></p> <p><a href="https://docs.python.org/2/library/copy.html" rel="nofollow">https://docs.python.org/2/library/copy.html</a></p>
1
2016-09-01T07:12:22Z
[ "python", "copy" ]
Removing characters from indices within multiple lists
39,263,076
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p> <p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) </code></pre> <p>So now L is:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] </code></pre> <p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p> <p>I just want it to re-return L, without those \n's at the end of those last indices. </p>
2
2016-09-01T05:08:37Z
39,263,153
<pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) for i in range(len(L)): L[i][3] = L[i][3].rstrip('\n') # Use rstrip to strip the specified character(s) from the right side of the string. print L &gt;&gt;[['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']] </code></pre>
1
2016-09-01T05:15:30Z
[ "python", "list" ]
Removing characters from indices within multiple lists
39,263,076
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p> <p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) </code></pre> <p>So now L is:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] </code></pre> <p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p> <p>I just want it to re-return L, without those \n's at the end of those last indices. </p>
2
2016-09-01T05:08:37Z
39,263,167
<pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) #iterate through every element in the list and #apply simple slicing for x in L: x[-1] = x[-1][:-1] </code></pre> <p>Output - </p> <pre><code>[['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']] </code></pre>
1
2016-09-01T05:16:41Z
[ "python", "list" ]
Removing characters from indices within multiple lists
39,263,076
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p> <p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) </code></pre> <p>So now L is:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] </code></pre> <p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p> <p>I just want it to re-return L, without those \n's at the end of those last indices. </p>
2
2016-09-01T05:08:37Z
39,263,238
<p>As already mentioned in comments:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append([item.strip() for item in f]) L.append([item.strip() for item in p]) </code></pre> <p>Or in one step:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] for lst in [f, p]: L.append([item.strip() for item in lst]) </code></pre> <p>Or shorter:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [[item.strip() for item in l] for l in [f, p]] </code></pre> <p>Last but not least, literally answering your question; if you need to <em>specifically</em> strip certain indices from a list of lists:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] for lst in L: lst[3] = lst[3].strip() </code></pre> <p>By default, <code>strip()</code> strips from whitespace characters, see <a href="http://www.tutorialspoint.com/python/string_strip.htm" rel="nofollow">this</a>.</p>
0
2016-09-01T05:22:32Z
[ "python", "list" ]
Removing characters from indices within multiple lists
39,263,076
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p> <p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) </code></pre> <p>So now L is:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] </code></pre> <p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p> <p>I just want it to re-return L, without those \n's at the end of those last indices. </p>
2
2016-09-01T05:08:37Z
39,263,278
<pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) for i in L: i[3] = i[3].rstrip('\n') &gt;&gt;&gt; [['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']] </code></pre>
0
2016-09-01T05:24:59Z
[ "python", "list" ]
Removing characters from indices within multiple lists
39,263,076
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p> <p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) </code></pre> <p>So now L is:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] </code></pre> <p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p> <p>I just want it to re-return L, without those \n's at the end of those last indices. </p>
2
2016-09-01T05:08:37Z
39,263,357
<p>For getting each 4th element from the list use this part: <code>i[3::4]</code></p> <p>For removing last two symbols from item: <code>x[:-1]</code></p> <p>The output script:</p> <pre><code>for i in L: i[3::4] = [ x[:-1] for x in i[3::4]] </code></pre> <p>Result:</p> <blockquote> <p>[['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']]</p> </blockquote>
1
2016-09-01T05:31:19Z
[ "python", "list" ]
Removing characters from indices within multiple lists
39,263,076
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p> <p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p> <pre><code>f = ['yes', 'no', 'tot', 'foop\n'] p = ['ick', 'throw', 'tamp', 'lap\n'] L = [] L.append(f) L.append(p) </code></pre> <p>So now L is:</p> <pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']] </code></pre> <p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p> <p>I just want it to re-return L, without those \n's at the end of those last indices. </p>
2
2016-09-01T05:08:37Z
39,265,504
<p>If you want to remove new lines and white space only from the 4th index with list comprehension:</p> <pre><code>&gt;&gt;&gt; f = ['yes', 'no', 'tot', 'foop\n'] &gt;&gt;&gt; p = ['ick', 'throw', 'tamp', 'lap\n'] &gt;&gt;&gt; [x[0:3]+[x[3].rstrip()] for x in [f]+[p]] [['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']] </code></pre> <p>Or <code>map</code> equivalent:</p> <pre><code>&gt;&gt;&gt; list(map(lambda x: x[0:3]+[x[3].rstrip()],[f]+[p])) [['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']] </code></pre>
1
2016-09-01T07:40:17Z
[ "python", "list" ]
Python 3 + Selenium: Find element by Xpath and text() doesn't work
39,263,091
<p>This is html code:</p> <pre><code>&lt;td&gt; &lt;a href="https://www.facebook.com/n/?confirmemail.php&amp;amp;e=myemail%40gmail.com&amp;amp;c=77438&amp;amp;cuid=AYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA&amp;amp;medium=email&amp;amp;mid=53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1&amp;amp;bcode=1.1472715008.AbkQwPz9meBC88Kr&amp;amp;n_m=myemail%40gmail.com" style="color:#3b5998;text-decoration:none" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;amp;q=https://www.facebook.com/n/?confirmemail.php%26e%3Dmyemail%2540gmail.com%26c%3D77438%26cuid%3DAYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA%26medium%3Demail%26mid%3D53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1%26bcode%3D1.1472715008.AbkQwPz9meBC88Kr%26n_m%3Dmyemail%2540gmail.com&amp;amp;source=gmail&amp;amp;ust=1472802324130000&amp;amp;usg=AFQjCNH7AgCibBYBB8I6ECqWXnFcMbwhMw"&gt; &lt;table style="border-collapse:collapse" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #344c80;background:#4c649b;padding:7px 16px 11px 16px"&gt; &lt;a href="https://www.facebook.com/n/?confirmemail.php&amp;amp;e=myemail%40gmail.com&amp;amp;c=77438&amp;amp;cuid=AYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA&amp;amp;medium=email&amp;amp;mid=53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1&amp;amp;bcode=1.1472715008.AbkQwPz9meBC88Kr&amp;amp;n_m=myemail%40gmail.com" style="color:#3b5998;text-decoration:none;display:block" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;amp;q=https://www.facebook.com/n/?confirmemail.php%26e%3Dmyemail%2540gmail.com%26c%3D77438%26cuid%3DAYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA%26medium%3Demail%26mid%3D53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1%26bcode%3D1.1472715008.AbkQwPz9meBC88Kr%26n_m%3Dmyemail%2540gmail.com&amp;amp;source=gmail&amp;amp;ust=1472802324130000&amp;amp;usg=AFQjCNH7AgCibBYBB8I6ECqWXnFcMbwhMw"&gt; &lt;center&gt; &lt;font size="3"&gt; &lt;span style="font-family:Helvetica Neue,Helvetica,Lucida Grande,tahoma,verdana,arial,sans-serif;white-space:nowrap;font-weight:bold;vertical-align:middle;color:#ffffff;font-size:14px;line-height:14px"&gt;Confirm&amp;nbsp;Your&amp;nbsp;Account &lt;/span&gt; &lt;/font&gt; &lt;/center&gt; &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/a&gt; &lt;/td&gt; </code></pre> <p>This is my code which click a confirm FB link in gmail:</p> <pre><code>confirm = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, ".//*[text()='Confirm Your Account']"))) confirm.click() </code></pre> <p>It always show TimeOutException error in the first line. Can you fix my code ? Thank you :)</p>
0
2016-09-01T05:10:25Z
39,263,190
<p>Try to check if the element contains the text instead of exact match</p> <pre><code>((By.XPATH, ".//*[contains(text(), 'Confirm Your Account')]")) </code></pre> <p>Or</p> <pre><code>((By.XPATH, ".//*[contains(., 'Confirm Your Account')]")) </code></pre>
0
2016-09-01T05:19:36Z
[ "python", "selenium", "xpath" ]
Python 3 + Selenium: Find element by Xpath and text() doesn't work
39,263,091
<p>This is html code:</p> <pre><code>&lt;td&gt; &lt;a href="https://www.facebook.com/n/?confirmemail.php&amp;amp;e=myemail%40gmail.com&amp;amp;c=77438&amp;amp;cuid=AYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA&amp;amp;medium=email&amp;amp;mid=53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1&amp;amp;bcode=1.1472715008.AbkQwPz9meBC88Kr&amp;amp;n_m=myemail%40gmail.com" style="color:#3b5998;text-decoration:none" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;amp;q=https://www.facebook.com/n/?confirmemail.php%26e%3Dmyemail%2540gmail.com%26c%3D77438%26cuid%3DAYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA%26medium%3Demail%26mid%3D53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1%26bcode%3D1.1472715008.AbkQwPz9meBC88Kr%26n_m%3Dmyemail%2540gmail.com&amp;amp;source=gmail&amp;amp;ust=1472802324130000&amp;amp;usg=AFQjCNH7AgCibBYBB8I6ECqWXnFcMbwhMw"&gt; &lt;table style="border-collapse:collapse" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style="border-collapse:collapse;border-radius:2px;text-align:center;display:block;border:solid 1px #344c80;background:#4c649b;padding:7px 16px 11px 16px"&gt; &lt;a href="https://www.facebook.com/n/?confirmemail.php&amp;amp;e=myemail%40gmail.com&amp;amp;c=77438&amp;amp;cuid=AYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA&amp;amp;medium=email&amp;amp;mid=53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1&amp;amp;bcode=1.1472715008.AbkQwPz9meBC88Kr&amp;amp;n_m=myemail%40gmail.com" style="color:#3b5998;text-decoration:none;display:block" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;amp;q=https://www.facebook.com/n/?confirmemail.php%26e%3Dmyemail%2540gmail.com%26c%3D77438%26cuid%3DAYh3nbnRpQs3d3S9QQ4e74G2jZzOBE69YqYVaWlnPtcs-SOpgHEFilr-khC8FsPUB5zzR6rvBQmgU54QxWdjn2jW9A5OhSaUal_KMcpvARnfDzPrmaOE3ObQrn-cfMk0MYFiR8fT0z8HVc3fX328oMpA%26medium%3Demail%26mid%3D53b6ce57e8d3bG5af62793fe75G53b6d2f14900dG3c2Gf8c1%26bcode%3D1.1472715008.AbkQwPz9meBC88Kr%26n_m%3Dmyemail%2540gmail.com&amp;amp;source=gmail&amp;amp;ust=1472802324130000&amp;amp;usg=AFQjCNH7AgCibBYBB8I6ECqWXnFcMbwhMw"&gt; &lt;center&gt; &lt;font size="3"&gt; &lt;span style="font-family:Helvetica Neue,Helvetica,Lucida Grande,tahoma,verdana,arial,sans-serif;white-space:nowrap;font-weight:bold;vertical-align:middle;color:#ffffff;font-size:14px;line-height:14px"&gt;Confirm&amp;nbsp;Your&amp;nbsp;Account &lt;/span&gt; &lt;/font&gt; &lt;/center&gt; &lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/a&gt; &lt;/td&gt; </code></pre> <p>This is my code which click a confirm FB link in gmail:</p> <pre><code>confirm = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, ".//*[text()='Confirm Your Account']"))) confirm.click() </code></pre> <p>It always show TimeOutException error in the first line. Can you fix my code ? Thank you :)</p>
0
2016-09-01T05:10:25Z
39,304,414
<p>you can use following xpath</p> <pre><code>driver.find_element_by_xpath("//td/a[1]") </code></pre>
0
2016-09-03T07:28:05Z
[ "python", "selenium", "xpath" ]
Argparse - Custom Action update to an dest dict
39,263,156
<p>I want to collect some options as a dict using <code>argparse</code>. I have wrote a custom Action class as follows. The problem is that the <code>__call__</code> method is never invoked. </p> <pre><code>#!/usr/bin/env python3 import argparse class UpdateDict(argparse.Action): def __init__(self, option_strings, dest, nargs=None, **kwargs): print('UpdateDict', option_strings, dest, nargs) if nargs != 1: raise ValueError("nargs must be 1") super(UpdateDict, self).__init__(option_strings, dest, nargs=nargs, **kwargs) print(self) def __call__(self, parser, namespace, values, option_string=None): print('%r %r %r' % (namespace, values, option_string)) dest = getattr(namespace, self.dest) print(dest) key = option_string[1] dest.update(key = values[0]) def parse_args(): parser = argparse.ArgumentParser(description='formula alpha') parser.add_argument('formula', nargs=1, type=str, help='alpha formula') parser.set_defaults(mydict={}) parser.add_argument('-a', '--alpha', nargs=1, type=str, default=['alas'], action=UpdateDict, dest='mydict') parser.add_argument('-b', '--beta', nargs=1, type=int, default=[0], action=UpdateDict, dest='mydict') if __name__ == '__main__': args = parse_args() print(args) </code></pre>
0
2016-09-01T05:15:42Z
39,263,253
<p>Your <code>parse_args</code> function need to return the parser which it creates, as you need its <code>parse_args</code> method for the actual parsing. Also, you should source the arguments from <code>sys.argv[1:]</code>, basically the arguments except for the main program's argument (i.e. your script name). So you should rename <code>parse_args</code> to a more appropriate name. An incomplete example:</p> <pre><code>def make_parser(): # your ArgumentParser construction code ... return parser if __name__ == '__main__': import sys parser = make_parser() parser.parse_args(sys.argv[1:]) </code></pre> <p>Do note that you have some minor issues with your implementation of your Action which you will need to fix. When I threw all your code (with the <code>return parser</code> added) on the <code>ArgumentParser</code> that your code constructed, this was the issue:</p> <pre><code>&gt;&gt;&gt; parser.parse_known_args(['-b', '1']) Namespace(formula=None, mydict=['alas']) [1] '-b' ['alas'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.4/argparse.py", line 1769, in parse_known_args namespace, args = self._parse_known_args(args, namespace) File "/usr/lib/python3.4/argparse.py", line 1975, in _parse_known_args start_index = consume_optional(start_index) File "/usr/lib/python3.4/argparse.py", line 1915, in consume_optional take_action(action, args, option_string) File "/usr/lib/python3.4/argparse.py", line 1843, in take_action action(self, namespace, argument_values, option_string) File "&lt;stdin&gt;", line 13, in __call__ AttributeError: 'list' object has no attribute 'update' </code></pre>
0
2016-09-01T05:23:52Z
[ "python", "argparse" ]
Argparse - Custom Action update to an dest dict
39,263,156
<p>I want to collect some options as a dict using <code>argparse</code>. I have wrote a custom Action class as follows. The problem is that the <code>__call__</code> method is never invoked. </p> <pre><code>#!/usr/bin/env python3 import argparse class UpdateDict(argparse.Action): def __init__(self, option_strings, dest, nargs=None, **kwargs): print('UpdateDict', option_strings, dest, nargs) if nargs != 1: raise ValueError("nargs must be 1") super(UpdateDict, self).__init__(option_strings, dest, nargs=nargs, **kwargs) print(self) def __call__(self, parser, namespace, values, option_string=None): print('%r %r %r' % (namespace, values, option_string)) dest = getattr(namespace, self.dest) print(dest) key = option_string[1] dest.update(key = values[0]) def parse_args(): parser = argparse.ArgumentParser(description='formula alpha') parser.add_argument('formula', nargs=1, type=str, help='alpha formula') parser.set_defaults(mydict={}) parser.add_argument('-a', '--alpha', nargs=1, type=str, default=['alas'], action=UpdateDict, dest='mydict') parser.add_argument('-b', '--beta', nargs=1, type=int, default=[0], action=UpdateDict, dest='mydict') if __name__ == '__main__': args = parse_args() print(args) </code></pre>
0
2016-09-01T05:15:42Z
39,264,302
<p>With your script, simplified to focus on putting values in <code>mydict</code>:</p> <pre><code>import argparse class UpdateDict(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): adict = getattr(namespace, 'mydict') adict.update({self.dest: values}) def parse_args(): parser = argparse.ArgumentParser() parser.set_defaults(mydict={}) parser.add_argument('-a', '--alpha', default='alas', action=UpdateDict) parser.add_argument('-b', '--beta', type=int, default=0, action=UpdateDict) return parser.parse_args() # parse and return if __name__ == '__main__': args = parse_args() print(args) </code></pre> <p>I get</p> <pre><code>2333:~/mypy$ python3 stack39263156.py Namespace(alpha='alas', beta=0, mydict={}) 2337:~/mypy$ python3 stack39263156.py -a one Namespace(alpha='alas', beta=0, mydict={'alpha': 'one'}) 2337:~/mypy$ python3 stack39263156.py -a one -b 2 Namespace(alpha='alas', beta=0, mydict={'beta': 2, 'alpha': 'one'}) </code></pre> <p>You can restore the <code>nargs=1</code> test if you want, but the default <code>None</code> implies 1 argument. Most don't use <code>nargs=1</code>. It makes sure the value is a single element list; most people want multiple element lists (e.g. '+' or '*' nargs).</p> <p>I like your use of <code>set_defaults</code> to put <code>mydict</code> in the namespace. I then retrieve it from the namespace, and update it, using the argument's <code>dest</code> as the <code>key</code>. Your version confuses the <code>dest</code>, and overwrite the <code>mydict</code> attribute.</p> <p>The default <code>store_action</code> uses <code>setattr(namespace, self.dest, values)</code>, to do the same thing, but with the namespace object rather than the embedded <code>mydict</code>.</p> <p>The usual defaults handling fills the <code>alpha</code> and <code>beta</code> attributes (the <code>dest</code>). To put those in <code>mydict</code> instead, you'd have to use something like</p> <pre><code>parser.set_defaults(mydict={'alpha':'alas', 'beta':0}) </code></pre> <p><code>SUPPRESS</code> can be used to keep defaults out of the usual <code>dest</code> attributes</p> <pre><code>parser.add_argument('-a', '--alpha', action=UpdateDict, default=argparse.SUPPRESS) parser.add_argument('-b', '--beta', type=int, action=UpdateDict) </code></pre> <p>the no-argument run would produce:</p> <pre><code>2347:~/mypy$ python3 stack39263156.py Namespace(beta=None, mydict={'beta': 0, 'alpha': 'alas'}) </code></pre> <p>The use of an embedded dictionary is an interesting idea, though I'm not sure what it adds. <code>vars(args)</code> is recommended as a way of turning a <code>namespace</code> into a dictionary.</p> <pre><code>{'mydict': {'alpha': 'one', 'beta': 2}, 'beta': None} </code></pre>
0
2016-09-01T06:39:39Z
[ "python", "argparse" ]
C++ pointers in Cython
39,263,162
<p>I use Cython to wrap my C++ classes. Some of methods return sth. like <code>class_name*</code>. <code>class_name</code> may be some complicated class already described in pxd and pyx file (like it is mentioned here in extended answer <a href="http://stackoverflow.com/a/39116733/4881441">http://stackoverflow.com/a/39116733/4881441</a>). But Cython says in pyx defs that I am returning not a Python type. I want to be able to return c++-like pointers in python and then use methods of this objects and to pass them to c++ methods.</p>
1
2016-09-01T05:16:09Z
39,285,634
<p>You can't directly return a pointer from a <code>def</code> method (only from a <code>cdef</code>).</p> <p>You'll need to write a Cython Wrapper class that stores the pointer you want to pass and you can return this Wrapper Object. If you want to execute methods on the C++ object you also have to use your Cython Wrapper and delegate the method calls to the stored instance.</p>
1
2016-09-02T06:28:01Z
[ "python", "c++", "c++11", "pointers", "cython" ]
Make Some Tkinter Listbox Items Always Selected
39,263,298
<p>I have a tkinter listbox where some of the items in the listbox need to always be selected. In my app, these items are required by the user, whereas some other items in the listbox are optional (should be selectable/deselectable).</p> <p>Most examples bind a function using <code>'&lt;&lt;ListboxSelect&gt;&gt;'</code>.</p> <p>What I don't understand is, how do I get the exact single item the user selected from the bind event?</p> <p>In my example code, <code>apples</code>, <code>peaches</code>, <code>lettuce</code> are selected initially. Let's say I click on <code>apples</code>. Normally this event would unselect <code>apples</code> but I want my function to run and set the selection on <code>apples</code> so it looks artificially like it's not able to be unselected.</p> <pre><code>import tkinter as tk root = tk.Tk() requiredlb = tk.Listbox(root, exportselection=False, activestyle='none', selectmode=tk.MULTIPLE) for i,item in enumerate(['apples', 'oranges', 'peaches', 'carrots', 'lettuce', 'grapes']): requiredlb.insert(tk.END, item) if i % 2 == 0: requiredlb.selection_set(i) requiredlb.grid(row=6, column=1, sticky='ew') def always_selected(event): widget = event.widget ## What Goes Here? ## requiredlb.bind('&lt;&lt;ListboxSelect&gt;&gt;', func=always_selected) root.mainloop() </code></pre>
1
2016-09-01T05:26:13Z
39,263,723
<p>Ok, nice question. Here is a workaround I managed to come up with, and it seems to work.</p> <p>First, create a list of indices you want to always keep selected:</p> <pre><code>items = ['apples', 'oranges', 'peaches', 'carrots', 'lettuce', 'grapes'] special_items = [0, 2, 4] for i,item in enumerate(items): ... </code></pre> <p>As you can see I modified a bit your code</p> <p>Then in the event function always make sure those indices are selected by selecting them explicitly:</p> <pre><code>def always_selected(event): widget = event.widget for idx in special_items: widget.selection_set(idx) </code></pre>
2
2016-09-01T06:01:11Z
[ "python", "tkinter", "listbox", "bind" ]
yaml exception in google app server "unable to add testProject to attribute application" regex issue?
39,263,309
<p>first day with google app engine.</p> <p>my yaml file includes the following:</p> <pre><code>application: testProgram version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py libraries: - name: webapp2 version: "2.5.2" </code></pre> <p>my python file includes the following (just for giggles):</p> <pre><code>import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.reponse.headers['Content-Type'] = 'text/plain' self.response.out.write("Hurray for cake!") app = webapp2.WSGIApplication([('/', MainPage)],debug=True) </code></pre> <p>the error I am getting is the following:</p> <pre><code>ile "/home/rickus/google_appengine/google/appengine/api/yaml_listener.py", line 178, in _HandleEvents raise yaml_errors.EventError(e, event_object) google.appengine.api.yaml_errors.EventError: Unable to assign value 'testProgram' to attribute 'application': Value 'testProgram' for application does not match expression '^(?:(?:[a-z\d\-]{1,100}\~)?(?:(?!\-)[a-z\d\-\.]{1,100}:)?(?!-)[a-z\d\-]{0,99}[a-z\d])$' in "testProgram/app.yaml", line 1, column 14 </code></pre> <p>so it is complaining about the naming of my file? That can't be right? I any ideas?</p>
2
2016-09-01T05:27:11Z
39,263,364
<p>It is most likely complaining about your applicationId, look at the regex, it accepts lowercased chars only.</p> <p>Change your applicationId to "testprogram" or "test-program"</p>
0
2016-09-01T05:31:58Z
[ "python", "google-app-engine", "yaml" ]
Pandas pop last row
39,263,411
<p>Is there any way to get and remove last row like <code>pop</code> method of python native list?</p> <p>I know I can do like below. I just want to make it one line.</p> <pre><code>df.ix[df.index[-1]] df = df[:-1] </code></pre>
1
2016-09-01T05:35:57Z
39,264,351
<p>Suppose sample dataframe:</p> <pre><code>In[51]:df Out[51]: a b 0 1 5 1 2 6 2 3 7 3 4 8 </code></pre> <p>you can do using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow">df.drop</a>:</p> <pre><code>In[52]:df,last_row=df.drop(df.tail(1).index),df.tail(1) In[53]:df Out[53]: 0 1 0 1 5 1 2 6 2 3 7 In[54]:last_row Out[54]: a b 3 4 8 </code></pre> <p>or using <a href="http://www.numpy.org/" rel="nofollow">numpy</a> as <code>np</code>:</p> <pre><code>df,last_row=pd.Dataframe(np.delete(df.values,(-1),axis=0)),df.tail(1) </code></pre>
1
2016-09-01T06:42:31Z
[ "python", "pandas" ]
Sphinx custom template
39,263,486
<p>I want to add a "next" and "previous" button at the bottom of my page.</p> <p>I saw a similar question posted <a href="http://stackoverflow.com/questions/26260726/how-do-i-add-a-previous-chapter-and-next-chapter-link-in-documentation-gener">"here"</a></p> <p>But he doesn't explain which file to edit and where.</p> <p>Should I edit the conf.py file and copy paste the code in there?</p>
1
2016-09-01T05:42:05Z
39,263,666
<p>There are themes that provide that functionality out of the box. You could install Sphinx bootstrap theme, which is a nice looking theme with bootstrap integration. You can find it here: <a href="https://ryan-roemer.github.io/sphinx-bootstrap-theme/" rel="nofollow">https://ryan-roemer.github.io/sphinx-bootstrap-theme/</a></p> <p>Other solution: just follow the link you posted and do what the accepted answer suggests.</p>
2
2016-09-01T05:56:32Z
[ "python", "python-sphinx" ]
Django user login form user is none
39,263,527
<p>I'm having some trouble logging in users. I have the following views and template:</p> <p>views.py</p> <pre><code>def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return HttpResponseRedirect('/') else: return HttpResponseRedirect('disabled account') else: return HttpResponseRedirect('/invalid') else: return render(request, 'login_page.html', {}) </code></pre> <p>login_page.html</p> <pre><code>{% block content %} {% if form.errors %} &lt;p class="error"&gt; sorry, thats not a valid username or password&lt;/p&gt; {% endif %} &lt;form action="/login/" method="post"&gt; &lt;label for="username"&gt;User name:&lt;/label&gt; &lt;input type="text" name="username" value="" id="username"&gt; &lt;label for="password"&gt;Password:&lt;/label&gt; &lt;input type="text" name="password" value="" id="password"&gt; &lt;input type="submit" value="login" /&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>My problem is, whenever i hit submit in the login form, no matter what the values are, the page is redirected to the /invald/ url. I have a user set up using the admin function but i still keep getting this error. Does anyone know what the problem may be?</p> <p>Do i need a forms.py file with anything in it?</p> <p>Updated views:</p> <pre><code>def login(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('loggedin.html') else: return HttpResponse("Account deleted or disabled") return render(request, "login_page.html", {'form': form}) </code></pre> <p>updated form:</p> <pre><code>from django import forms from django.contrib.auth import authenticate, login, logout, get_user_model class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("User does not exist.") if not user.is_active: raise forms.ValidationError("User is no longer active.") return super(UserLoginForm, self).clean(*args, **kwargs) </code></pre> <p>updated login_page.html</p> <pre><code>{% block content %} {% if form.errors %} &lt;p class="error"&gt; sorry, thats not a valid username or password&lt;/p&gt; {% endif %} &lt;form action="{% url 'login' %}" method="post"&gt; {{ form }} &lt;input type="submit" value="login" /&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>urls:</p> <pre><code> url(r'^admin/', admin.site.urls), url(r'^login/', views.login, name='login'), url(r'^logout/', views.logout, name='logout'), url(r'^invalid/', views.invalid_login, name='invalid_login'), url(r'^loggedin/', views.loggedin, name='loggedin'), url(r'^$', views.index, name='index'), </code></pre>
0
2016-09-01T05:44:55Z
39,263,961
<p>I suggest you make a forms.py file and in here make a class like so:</p> <pre><code>from django import forms from django.contrib.auth import authenticate, login, logout, get_user_model class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("User does not exist.") if not user.is_active: raise forms.ValidationError("User is no longer active.") return super(UserLoginForm, self).clean(*args, **kwargs) </code></pre> <p>Then in your views import Login form. Create a view as such:</p> <pre><code>def my_login_view(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('someurl') else: return redirect('someotherurl') return render(request, "your_template_to_process_this_view", {'form': form}) </code></pre> <p>In your html template you can call the form using the convention below. For this shortcut to the url to work you need an app_name = "yourappname" at the top of your url file.</p> <pre><code>&lt;form method="POST" action="{% url 'yourappname:name_given_to_url_in_urls_file' %}"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" class="btn-success" value="Login"/&gt; &lt;/form&gt; </code></pre>
0
2016-09-01T06:17:55Z
[ "python", "html", "django", "forms", "login" ]
Display missing values of specific column based on another specific column
39,263,536
<p>this is my problem</p> <p>Let's say I have 2 columns on the dataframe which look like this:</p> <pre><code> Type | Killed _______ |________ Dog 1 Dog nan Dog nan Cat 4 Cat nan Cow 1 Cow nan </code></pre> <p>I would like to display all missing value in Killed according to the Type and count them</p> <p>My desire outcome would look something like this:</p> <pre><code>Type | Sum(isnull) Dog 2 Cat 1 Cow 1 </code></pre> <p>Is there anyway to display this?</p>
4
2016-09-01T05:45:42Z
39,263,575
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a>:</p> <pre><code>print (df.ix[df.Killed.isnull(), 'Type'].value_counts().reset_index(name='Sum(isnull)')) index Sum(isnull) 0 Dog 2 1 Cow 1 2 Cat 1 </code></pre> <p>Or aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>, it seems faster:</p> <pre><code>print (df[df.Killed.isnull()] .groupby('Type')['Killed'] .size() .reset_index(name='Sum(isnull)')) Type Sum(isnull) 0 Cat 1 1 Cow 1 2 Dog 2 </code></pre> <p><strong>Timings</strong>:</p> <pre><code>df = pd.concat([df]*1000).reset_index(drop=True) In [30]: %timeit (df.ix[df.Killed.isnull(), 'Type'].value_counts().reset_index(name='Sum(isnull)')) 100 loops, best of 3: 5.36 ms per loop In [31]: %timeit (df[df.Killed.isnull()].groupby('Type')['Killed'].size().reset_index(name='Sum(isnull)')) 100 loops, best of 3: 2.02 ms per loop </code></pre>
3
2016-09-01T05:48:47Z
[ "python", "pandas", "dataframe", "multiple-columns", null ]
Display missing values of specific column based on another specific column
39,263,536
<p>this is my problem</p> <p>Let's say I have 2 columns on the dataframe which look like this:</p> <pre><code> Type | Killed _______ |________ Dog 1 Dog nan Dog nan Cat 4 Cat nan Cow 1 Cow nan </code></pre> <p>I would like to display all missing value in Killed according to the Type and count them</p> <p>My desire outcome would look something like this:</p> <pre><code>Type | Sum(isnull) Dog 2 Cat 1 Cow 1 </code></pre> <p>Is there anyway to display this?</p>
4
2016-09-01T05:45:42Z
39,263,871
<p>I can get you both <code>isnull</code> and <code>notnull</code></p> <pre><code>isnull = np.where(df.Killed.isnull(), 'isnull', 'notnull') df.groupby([df.Type, isnull]).size().unstack() </code></pre> <p><a href="http://i.stack.imgur.com/qkD6N.png" rel="nofollow"><img src="http://i.stack.imgur.com/qkD6N.png" alt="enter image description here"></a></p>
1
2016-09-01T06:11:56Z
[ "python", "pandas", "dataframe", "multiple-columns", null ]
Python to open ADODB recordset and add new record
39,263,563
<p>in my wxPython app which I am developing I have written a method which will add a new record into an access database (.accdb). I have procured this code from online search however am not able to make it work. Below is the code:-</p> <pre><code>def Allocate_sub(self, event): pth = os.getcwd() myDb = pth + '\\myAccessDB.accdb' DRV = '{Microsoft Access Driver (*.mdb)}' PWD = 'pw' # connect to db con = win32com.client.Dispatch(r'ADODB.Connection') con.Open('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s' % (myDb)) cDataset = win32com.client.Dispatch(r'ADODB.Recordset') #cDataset.Open("Allocated_Subs", con, 3, 3, 1) cDataset.Open("Allocated_Subs", con, 3, 3, 1) cDataset.AddNew() cDataset.Fields.Item("Subject").Value = "abc" cDataset.Fields.Item("UniqueKey").Value = "xyzabc" cDataset.Update() cDataset.close() con.close() </code></pre> <p>However whenever I trigger this code by clicking the button to which I have Bind it I get error saying:-</p> <p>Can anyone please help me resolve this or let me know of a different way to open a recordset using ADODB and then add a new record into it.</p> <p>Many thanks.</p> <p>Regards, Premanshu</p>
0
2016-09-01T05:48:01Z
39,309,654
<p>I figured the solution, posting here just in case someone refers to it... it's a small correction in line</p> <pre><code>cDataset.Open("Allocated_Subs", con, 3, 3, 1) </code></pre> <p>it should be:-</p> <pre><code>cDataset.Open("Allocated_Subs", con, 1, 3) </code></pre> <p>Regards, Premanshu</p>
0
2016-09-03T17:40:23Z
[ "python", "adodb", "recordset" ]
How can I read tar.gz file using pandas read_csv with gzip compression option?
39,263,929
<p>I have a very simple csv, with the following data, compressed inside the tar.gz file. I need to read that in dataframe using pandas.read_csv. </p> <pre><code> A B 0 1 4 1 2 5 2 3 6 import pandas as pd pd.read_csv("sample.tar.gz",compression='gzip') </code></pre> <p>However, I am getting error:</p> <pre><code>CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2 </code></pre> <p>Following are the set of read_csv commands and the different errors I get with them:</p> <pre><code>pd.read_csv("sample.tar.gz",compression='gzip', engine='python') Error: line contains NULL byte pd.read_csv("sample.tar.gz",compression='gzip', header=0) CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2 pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ") CParserError: Error tokenizing data. C error: Expected 2 fields in line 94, saw 14 pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ", engine='python') Error: line contains NULL byte </code></pre> <p>What's going wrong here? How can I fix this?</p>
1
2016-09-01T06:15:12Z
39,264,156
<pre><code>df = pd.read_csv('sample.tar.gz', compression='gzip', header=0, sep=' ', quotechar='"', error_bad_lines=False) </code></pre> <p>Note: <code>error_bad_lines=False</code> will ignore the offending rows. </p>
1
2016-09-01T06:30:57Z
[ "python", "csv", "pandas", "gzip", "tar" ]
Read .mat file in Python. But the shape of the data changed
39,264,196
<pre><code> % save .mat file in the matlab train_set_x=1:50*1*51*61*23; train_set_x=reshape(train_set_x,[50,1,51,61,23]); save(['pythonTest.mat'],'train_set_x','-v7.3'); </code></pre> <p>The data obtained in the matlab is in the size of (50,1,51,61,23).</p> <p>I load the .mat file in Python with the instruction of this <a href="http://stackoverflow.com/questions/874461/read-mat-files-in-python">link</a>.</p> <p>The code is as follows:</p> <pre><code>import numpy as np, h5py f = h5py.File('pythonTest.mat', 'r') train_set_x = f.get('train_set_x') train_set_x = np.array(train_set_x) </code></pre> <p>The output of train_set_x.shape is <code>(23L, 61L, 51L, 1L, 50L)</code>. It is expected to be <code>(50L, 1L, 51L, 61L, 23L)</code>. So I changed the shape by </p> <pre><code>train_set_x=np.transpose(train_set_x, (4,3,2,1,0)) </code></pre> <p>I am curious about the change in data shape between Python and matlab. Is there some errors in my code?</p>
6
2016-09-01T06:33:06Z
39,264,426
<p>You do not have any errors in the code. There is a fundamental difference between Matlab and python in the way they treat multi-dimensional arrays.<br> Both Matalb and python store all the elements of the multi-dim array as a single contiguous block in memory. The difference is the order of the elements:<br> <strong>Matlab</strong>, (like fortran) stores the elements in a column-first fashion, that is storing the elements according to the dimensions of the array, for 2D:</p> <pre><code> [1 3; 2 4] </code></pre> <p>In contrast, <strong>Python</strong>, stores the elements in a row-first fashion, that is starting from the <em>last</em> dimension of the array:</p> <pre><code>[1 2; 3 4]; </code></pre> <p>So a block in memory with <em>size</em> <code>[m,n,k]</code> in Matlab is seen by python as an array of <em>shape</em> <code>[k,n,m]</code>.</p> <p>For more information see <a href="https://en.wikipedia.org/wiki/Row-major_order" rel="nofollow">this wiki page</a>.</p> <p>BTW, instead of transposing <code>train_set_x</code>, you might try setting its order to "Fortran" order (col-major as in Matlab):</p> <pre><code> train_set_x = np.array(train_set_x, order='F') </code></pre>
3
2016-09-01T06:47:02Z
[ "python", "matlab", "numpy", "file-io", "mat-file" ]
response.out.write in python, google app engine not displaying on local host
39,264,484
<p>my yaml file:</p> <pre><code>application: testprogram version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py </code></pre> <p>my python file:</p> <pre><code>import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.reponse.headers['Content-Type'] = 'text/plain' self.response.out.write("Hurray for cake!") app = webapp2.WSGIApplication([('/', MainPage)],debug=True) </code></pre> <p>from the sever:</p> <pre><code>$ dev_appserver.py testprogram WARNING 2016-09-01 05:42:36,253 application_configuration.py:165] The "python" runtime specified in "testprogram/app.yaml" is not supported - the "python27" runtime will be used instead. A description of the differences between the two can be found here: https://developers.google.com/appengine/docs/python/python25/diff27 INFO 2016-09-01 05:42:36,265 sdk_update_checker.py:229] Checking for updates to the SDK. INFO 2016-09-01 05:42:36,400 sdk_update_checker.py:257] The SDK is up to date. WARNING 2016-09-01 05:42:36,635 simple_search_stub.py:1146] Could not read search indexes from /tmp/appengine.testprogram.rickus/search_indexes INFO 2016-09-01 05:42:36,639 api_server.py:205] Starting API server at: http://localhost:40100 INFO 2016-09-01 05:42:36,642 dispatcher.py:197] Starting module "default" running at: http://localhost:8080 INFO 2016-09-01 05:42:36,643 admin_server.py:116] Starting admin server at: http://localhost:8000 INFO 2016-09-01 05:42:51,325 module.py:788] default: "GET / HTTP/1.1" 200 - </code></pre> <p>sever is up. Local host is up. But nothing is being written out. I am doing udacitys course so I have just began. What could the hang up be. Been checking the docs and still lost.</p>
1
2016-09-01T06:49:49Z
39,276,599
<p>In the <code>.yaml</code> file, point the routing handler to main.app (not main.py).</p> <p>You also have have typo in your python file. response is missing the first 's':</p> <pre><code>self.reponse.headers['Content-Type'] = 'text/plain' </code></pre> <p>should be</p> <pre><code>self.response.headers['Content-Type'] = 'text/plain' </code></pre>
0
2016-09-01T16:29:22Z
[ "python", "google-app-engine", "localhost", "yaml" ]
response.out.write in python, google app engine not displaying on local host
39,264,484
<p>my yaml file:</p> <pre><code>application: testprogram version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py </code></pre> <p>my python file:</p> <pre><code>import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.reponse.headers['Content-Type'] = 'text/plain' self.response.out.write("Hurray for cake!") app = webapp2.WSGIApplication([('/', MainPage)],debug=True) </code></pre> <p>from the sever:</p> <pre><code>$ dev_appserver.py testprogram WARNING 2016-09-01 05:42:36,253 application_configuration.py:165] The "python" runtime specified in "testprogram/app.yaml" is not supported - the "python27" runtime will be used instead. A description of the differences between the two can be found here: https://developers.google.com/appengine/docs/python/python25/diff27 INFO 2016-09-01 05:42:36,265 sdk_update_checker.py:229] Checking for updates to the SDK. INFO 2016-09-01 05:42:36,400 sdk_update_checker.py:257] The SDK is up to date. WARNING 2016-09-01 05:42:36,635 simple_search_stub.py:1146] Could not read search indexes from /tmp/appengine.testprogram.rickus/search_indexes INFO 2016-09-01 05:42:36,639 api_server.py:205] Starting API server at: http://localhost:40100 INFO 2016-09-01 05:42:36,642 dispatcher.py:197] Starting module "default" running at: http://localhost:8080 INFO 2016-09-01 05:42:36,643 admin_server.py:116] Starting admin server at: http://localhost:8000 INFO 2016-09-01 05:42:51,325 module.py:788] default: "GET / HTTP/1.1" 200 - </code></pre> <p>sever is up. Local host is up. But nothing is being written out. I am doing udacitys course so I have just began. What could the hang up be. Been checking the docs and still lost.</p>
1
2016-09-01T06:49:49Z
39,278,799
<p>You guys are going to laugh when you see this.</p> <p>Fixing the typo in self.response.headers was the fix.</p> <p>so originally my code was <code>self.reponse.headers['Content-Type'] = 'text/plain'</code></p> <p>and then I added this missing "s"</p> <p><code>self.response.headers['Content-Type'] = 'text/plain'</code></p> <p>and now everything works. Allow me to laugh and cry at the same time</p> <p>thanks to @Dan Cornilescu for pointing this out.</p>
-1
2016-09-01T18:46:08Z
[ "python", "google-app-engine", "localhost", "yaml" ]
response.out.write in python, google app engine not displaying on local host
39,264,484
<p>my yaml file:</p> <pre><code>application: testprogram version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py </code></pre> <p>my python file:</p> <pre><code>import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.reponse.headers['Content-Type'] = 'text/plain' self.response.out.write("Hurray for cake!") app = webapp2.WSGIApplication([('/', MainPage)],debug=True) </code></pre> <p>from the sever:</p> <pre><code>$ dev_appserver.py testprogram WARNING 2016-09-01 05:42:36,253 application_configuration.py:165] The "python" runtime specified in "testprogram/app.yaml" is not supported - the "python27" runtime will be used instead. A description of the differences between the two can be found here: https://developers.google.com/appengine/docs/python/python25/diff27 INFO 2016-09-01 05:42:36,265 sdk_update_checker.py:229] Checking for updates to the SDK. INFO 2016-09-01 05:42:36,400 sdk_update_checker.py:257] The SDK is up to date. WARNING 2016-09-01 05:42:36,635 simple_search_stub.py:1146] Could not read search indexes from /tmp/appengine.testprogram.rickus/search_indexes INFO 2016-09-01 05:42:36,639 api_server.py:205] Starting API server at: http://localhost:40100 INFO 2016-09-01 05:42:36,642 dispatcher.py:197] Starting module "default" running at: http://localhost:8080 INFO 2016-09-01 05:42:36,643 admin_server.py:116] Starting admin server at: http://localhost:8000 INFO 2016-09-01 05:42:51,325 module.py:788] default: "GET / HTTP/1.1" 200 - </code></pre> <p>sever is up. Local host is up. But nothing is being written out. I am doing udacitys course so I have just began. What could the hang up be. Been checking the docs and still lost.</p>
1
2016-09-01T06:49:49Z
39,280,433
<p>You have a problem in <code>app.yaml</code> file in the handlers section:</p> <p>Yours:</p> <pre><code>application: testprogram version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py </code></pre> <p>but you should have:</p> <pre><code>application: testprogram version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /.* script: main.app </code></pre>
0
2016-09-01T20:33:37Z
[ "python", "google-app-engine", "localhost", "yaml" ]
Find and shows the highest record of the name list
39,264,545
<p>I'm new to Python. I've been given a task to write a Python program to read a name list which consist of people names and their height.</p> <p>Any suggestion or idea for coding to find out the highest height and show the record?</p> <p>For examples, the highest height is 180 and the result will show "Adam,180"</p>
-5
2016-09-01T06:52:55Z
39,264,962
<p>We can use operator.itemgetter</p> <pre><code>import operator stats = {'Dave':179, 'Adam':180, 'Daniel': 170} max(stats.items(), key=operator.itemgetter(1)) </code></pre>
0
2016-09-01T07:13:48Z
[ "python" ]
Find and shows the highest record of the name list
39,264,545
<p>I'm new to Python. I've been given a task to write a Python program to read a name list which consist of people names and their height.</p> <p>Any suggestion or idea for coding to find out the highest height and show the record?</p> <p>For examples, the highest height is 180 and the result will show "Adam,180"</p>
-5
2016-09-01T06:52:55Z
39,265,488
<pre><code>names = {'jason': 5.8, 'daniel': 5.0, 'rizwan': 6} &gt;&gt;&gt; sorted(names.items(), key=lambda value: value[1], reverse=True) [('rizwan', 6), ('jason', 5.8), ('daniel', 5.0)] &gt;&gt;&gt; max(sorted(names.items(), key=lambda value: value[1])) ('rizwan', 6) &gt;&gt;&gt; min(sorted(names.items(), key=lambda value: value[1])) ('daniel', 5.0) </code></pre>
0
2016-09-01T07:39:19Z
[ "python" ]
Find and shows the highest record of the name list
39,264,545
<p>I'm new to Python. I've been given a task to write a Python program to read a name list which consist of people names and their height.</p> <p>Any suggestion or idea for coding to find out the highest height and show the record?</p> <p>For examples, the highest height is 180 and the result will show "Adam,180"</p>
-5
2016-09-01T06:52:55Z
39,265,618
<p>if you have separate lists:</p> <pre><code>names = ['alireza','sarah','maryam','muhammad'] heights = [180,172,178,182] print(names[heights.index(max(heights))]) </code></pre> <p>if you want use dictionary:</p> <pre><code>names = {'alireza':180,'sarah':172,'maryam':178,'muhammad':182} max(names.keys(), key=names.get) </code></pre> <p>and if you want use 2d lists:</p> <pre><code>names = [['alireza',180],['sarah',172],['maryam',178],['muhammad',182]] heights = list(zip(*names))[1] print(names[heights.index(max(heights))][0]) </code></pre>
0
2016-09-01T07:45:46Z
[ "python" ]
Encoding issues in python how to fix it
39,264,757
<p>I get this error while writing data to csv file</p> <pre><code>import csv a = [u'eaTfxfwz', u'Edward', u'O\u2019Connell', u'ejoconnell@sbcglobal.net', u'Santa Clara', u'CA', 'UNITED STATES', u'150 Saratoga Avenue #306', u'', u'Santa Clara, CA', u'95051', u'', u'408-835-2209', u'None', u'', '', u'2012-010', u'pjOjJfwT', u'Undefined', u'Import', u' ', ' San Jose HQ, CA ', '', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', u''] f3 = open('test.csv', 'at') writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL) writer.writerow(a) </code></pre> <p>error</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 1: ordinal not in range(128) </code></pre> <p>How to fix it</p>
0
2016-09-01T07:04:42Z
39,264,816
<p>You can use <code>utf-8</code> encoding.</p> <pre><code>import csv aenc=[] a = [u'eaTfxfwz', u'Edward', u'O\u2019Connell', u'ejoconnell@sbcglobal.net', u'Santa Clara', u'CA', 'UNITED STATES', u'150 Saratoga Avenue #306', u'', u'Santa Clara, CA', u'95051', u'', u'408-835-2209', u'None', u'', '', u'2012-010', u'pjOjJfwT', u'Undefined', u'Import', u' ', ' San Jose HQ, CA ', '', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', u''] for x in a: aenc.append(x.encode('utf-8')) with open('test.csv', 'wb') as f3: writer = csv.writer(f3,delimiter = ',', lineterminator='\n', quoting=csv.QUOTE_ALL) writer.writerow(aenc) </code></pre>
0
2016-09-01T07:07:11Z
[ "python", "encoding", "utf" ]
finding the LCM using python
39,264,780
<p>def multiple(a, b): """so I'm trying to return the smallest number n that is a multiple of both a and b.</p> <p>for example:</p> <blockquote> <blockquote> <blockquote> <p>multiple(3, 4) 12 multiple(14, 21) 42 """</p> </blockquote> </blockquote> </blockquote> <pre><code>def gcd (a,b): if a &lt; b : a , b = b,a while b: a , b = b , a % b return a def lcm (a , b): n= (a*b) / gcd(a,b) return n </code></pre> <p>it keeps throwing errors about indentation and logic. I don't understand why. I've tried changing the variables around too.</p>
-2
2016-09-01T07:05:36Z
39,264,825
<p>No need to find GCD, we can directly find LCM. Below code works</p> <pre><code>def lcmof(x,y): res=0 mx=max(x,y) mn=min(x,y) for i in range(1,mx+1,1): temp=mx*i try: if(temp%mn==0): res=temp break except ZeroDivisionError: res=0 break return res </code></pre>
1
2016-09-01T07:07:34Z
[ "python", "lcm" ]
how to repeat / expand expressions in python
39,264,957
<p>What is the most pythonic way to repeat an expression in Python. </p> <p><strong>Context :</strong> A function is getting passed a dictionary (with possibly 20 elements) and I need to extract and use values from this dictionary <strong>if they exist</strong>. Something like this :</p> <pre><code>x = dict_name['key1'] if dict_name['key1'] else '' </code></pre> <p>Now, instead of writing this logic 20 times for all 20 different keys, I would like to define this expression at one place and then use it repeatedly. It will be easier to maintain in future. In "C/C++" programming languages, it makes a good case of <code>#define</code> or <code>inline</code> functions. What would be Pythonic way to do this in Python?</p> <p>As you would have guessed, I am novice in Python. So I appreciate your help on this or pointers to constructs for this in Python.</p>
0
2016-09-01T07:13:46Z
39,265,147
<p>Whether there is an "equivalent" to <code>inline</code> in Python depends on who you ask, and what you check.</p> <p>For no equivalent, e.g.: <a href="http://stackoverflow.com/a/6442497/2707864">http://stackoverflow.com/a/6442497/2707864</a></p> <p>For equivalent, e.g.: <a href="https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html" rel="nofollow">https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html</a></p> <p>From a practical point of view, <code>lambda</code> would do the trick (<code>dict.get</code> replaces your ternary conditional operator)</p> <pre><code>dict_get = lambda key : dict_name.get(key, '') </code></pre> <p>Or you can always define a one-line function.</p> <pre><code>def dict_get( key ) : dict_name.get( key, '' ) </code></pre> <p>Pythonicity is quite often (always?) subjective.</p>
0
2016-09-01T07:22:06Z
[ "python", "inline" ]
How can I get more user information after allowing user sign up through Facebook in Django?
39,265,013
<p>I'm using <code>Python-social-auth</code>(<a href="https://github.com/omab/python-social-auth" rel="nofollow">https://github.com/omab/python-social-auth</a>) for user signing up through <code>Facebook</code>. </p> <p>Only defect is that I can't get more information about user if user sign up through <code>Facebook</code>. For example, <code>birth</code>, <code>job</code>, <code>hobby</code> are required field but <code>Facebook</code> doesn't give these information.</p> <p>What I want to know is here :</p> <ol> <li><p>In case of <code>birth</code>, <code>Facebook</code> could give this information. Is there any way to do this? Do I have to edit the code of <code>Python-social-auth</code>?</p></li> <li><p>I heard that there is a case where after signing up through <code>Facebook</code>, let new window show up for getting more infos about users. I want to see example site and how to do this.</p></li> </ol> <p>Need helps. Thanks.</p> <h1>Edit</h1> <p>This is what I talked about. (<a href="https://developers.facebook.com/docs/facebook-login/multiple-providers?locale=en_US#postfb" rel="nofollow">https://developers.facebook.com/docs/facebook-login/multiple-providers?locale=en_US#postfb</a>)</p> <blockquote> <p>Adding manual login info to a Facebook Login created account</p> <p>This situation occurs when someone creates their account in your app using Facebook Login, but later wants to also log in to the account using a unique credential and a password. For example, Netflix has a web app that uses Facebook Login alongside a regular login system, and also an Xbox 360 app where people can only use the regular login system.</p> <ol> <li>Ensure the Facebook Login email address is verified</li> </ol> <p>If you use an email address as the unique credential which identifies each account, your app should verify that the email address associated with the person's Facebook account (and obtained during Facebook Login) is valid. You can do this by creating code in your app to send a verification email to the address obtained after Facebook Login (you will probably need to have this step as part of your regular login system anyway).</p> <ol start="2"> <li>Ask the person to supply a new password (and other credentials)</li> </ol> <p>Once the email address is verified, you can now request that the person supplies a password, indicating to them that they can use this to log in to your app in future in conjunction with their email address. Once supplied, you can add this to the same part of your database where you are currently storing account information.</p> <p>If your app's login system doesn't use an email address as the identification and uses something user-generated like a username instead, then you should also request that the person supplies this at the same time as a password.</p> </blockquote> <p>I want to see example site about this. Thanks.</p>
1
2016-09-01T07:16:14Z
39,266,836
<p>Define in settings <code>SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS</code> with fields that interest you</p> <pre><code>SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'first_name, last_name, birthday' } </code></pre> <p>List of available fields you can see <a href="https://developers.facebook.com/docs/graph-api/reference/user" rel="nofollow">here</a>.</p>
0
2016-09-01T08:48:49Z
[ "python", "django", "python-social-auth" ]
How to get the length of repeated numbers column wise?
39,265,221
<p>I am trying to get the length of repeated numbers in Python Numpy. For example, let's consider a simple ndarray</p> <pre><code>import numpy as np a = np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 1, 1, 1, 1, 0, 0], ]) </code></pre> <p>The first column has <code>[0, 1, 0, 1]</code>, the position of <code>1</code> is <code>1</code>, now start counting from there, we get <code>ones = 2</code> and <code>zeros = 1</code>. So I have to start counting <code>ones</code> and <code>zeros</code> when <code>1</code> is encountered (starting position).</p> <p>so the answer for <code>a</code> would be</p> <pre><code>ones = [2, 2, 1, 1, 1, 3, 2, 2, 1, 1] zeros = [1, 0, 2, 1, 0, 0, 1, 1, 1, 2] </code></pre> <p>Can any one please help me out?</p> <p><strong>Update</strong></p> <p>3D array:</p> <pre><code>a = np.array([ [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 1, 1, 1, 1, 0, 0], ], [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 1, 1], [0, 1, 0, 1, 0, 0, 0, 1, 0, 0], [1, 1, 0, 1, 0, 1, 1, 1, 0, 0], ] ]) </code></pre> <p>The expected output should be</p> <pre><code>ones = [ [2, 3, 0, 0, 1, 3, 2, 2, 1, 0], [1, 3, 0, 2, 1, 1, 1, 2, 1, 1] ] zeros = [ [1, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 2, 0, 0, 0, 2, 2] ] </code></pre>
1
2016-09-01T07:24:57Z
39,265,360
<p>With focus on performance, here's one generic approach for ndarrays -</p> <pre><code>ones_count = a.sum(-2) zeros_count = (a.shape[-2] - ones_count - a.argmax(-2))*a.any(-2) </code></pre> <p>One alternative to get <code>zeros_count</code> with selections using <code>np.where</code>, would be -</p> <pre><code>zeros_count = np.where(a.any(-2),a.shape[-2] - ones_count - a.argmax(-2),0) </code></pre> <p><strong>Sample runs</strong></p> <p><code>2D</code> case :</p> <pre><code>In [60]: a Out[60]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 1, 1, 1, 1, 0, 0]]) In [61]: ones_count = a.sum(-2) ...: zeros_count = (a.shape[-2] - ones_count - a.argmax(-2))*a.any(-2) ...: In [62]: ones_count Out[62]: array([2, 2, 1, 1, 1, 3, 2, 2, 1, 1]) In [63]: zeros_count Out[63]: array([1, 0, 2, 1, 0, 0, 1, 1, 1, 2]) </code></pre> <p>3D case :</p> <pre><code>In [65]: a = np.array([ ...: [ ...: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ...: [1, 1, 0, 0, 0, 1, 1, 1, 0, 0], ...: [0, 1, 0, 0, 0, 1, 0, 0, 1, 0], ...: [1, 1, 0, 0, 1, 1, 1, 1, 0, 0], ...: ], ...: [ ...: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ...: [0, 1, 0, 0, 1, 0, 0, 0, 1, 1], ...: [0, 1, 0, 1, 0, 0, 0, 1, 0, 0], ...: [1, 1, 0, 1, 0, 1, 1, 1, 0, 0], ...: ] ...: ]) In [66]: ones_count = a.sum(-2) ...: zeros_count = (a.shape[-2] - ones_count - a.argmax(-2))*a.any(-2) ...: In [67]: ones_count Out[67]: array([[2, 3, 0, 0, 1, 3, 2, 2, 1, 0], [1, 3, 0, 2, 1, 1, 1, 2, 1, 1]]) In [68]: zeros_count Out[68]: array([[1, 0, 0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 2, 0, 0, 0, 2, 2]]) </code></pre> <p>and so on for higher dim arrays.</p>
4
2016-09-01T07:31:54Z
[ "python", "numpy" ]
How to send celery all logs to a custom handler . in my case python-logstash handler
39,265,344
<p>In my Celery application I am getting 2 types of logs on the console i.e celery application logs and task level logs (inside task I am using logger.INFO(str) syntax for logging)</p> <p>I wanted to send both of them to a custom handler (in my case python-logstash handler )</p> <p>For django logs I was successfull, by setting handler and logger in settings.py but I am helpless with celery</p>
2
2016-09-01T07:31:13Z
39,271,269
<pre><code>def initialize_logstash(logger=None,loglevel=logging.DEBUG, **kwargs): # logger = logging.getLogger('celery') handler = logstash.TCPLogstashHandler('localhost', 5959,tags=['worker']) handler.setLevel(loglevel) logger.addHandler(handler) # logger.setLevel(logging.DEBUG) return logger from celery.signals import after_setup_task_logger after_setup_task_logger.connect(initialize_logstash) from celery.signals import after_setup_logger after_setup_logger.connect(initialize_logstash) </code></pre> <p>using both after_setup_task_logger and after_setup_logger signals solved the problem </p>
0
2016-09-01T12:12:42Z
[ "python", "logging", "logstash", "django-celery", "celery-task" ]
How to specify metadata for dask.dataframe
39,265,396
<p>Providing metadata became very important in dask 0.11. The API provides some good examples, how to achieve that, but when it comes to picking the right dtypes for my dataframe, I still feel unsure.</p> <ul> <li>Could I do something like <code>meta={'x': int 'y': float, 'z': float}</code> instead of <code>meta={'x': 'i8', 'y': 'f8', 'z': 'f8'}</code>?</li> <li>Could somebody hint me to a list of possible values like 'i8'? What dtypes exist? </li> <li>How can I specify a column, that contains arbitrary objects? How can I specify a column, that contains only instances of one class?</li> </ul>
3
2016-09-01T07:33:58Z
39,266,754
<p>The available basic data types are the ones which are offered through numpy. Have a look at the <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html" rel="nofollow">documentation</a> for a list.</p> <p>Not included in this set are datetime-formats (e.g. <code>datetime64</code>), for which additional information can be found in the <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="nofollow">pandas</a> and <a href="http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html" rel="nofollow">numpy</a> documentation.</p> <p>The meta-argument for dask dataframes usually expects an empty pandas dataframe holding definitions for columns, indices and dtypes.</p> <p>One way to construct such a DataFrame is:</p> <pre><code>import pandas as pd import numpy as np meta = pd.DataFrame(columns=['a', 'b', 'c']) meta.a = meta.a.astype(np.int64) meta.b = meta.b.astype(np.datetime64) </code></pre> <p>There is also a way to provide a dtype to the constructor of the pandas dataframe, however, I am not sure how to provide them for individual columns each. As you can see, it is possible to provide not only the "name" for datatypes, but also the actual numpy dtype.</p> <p>Regarding your last question, the datatype you are looking for is "object". For example:</p> <pre><code>import pandas as pd class Foo: def __init__(self, foo): self.bar = foo df = pd.DataFrame(data=[Foo(1), Foo(2)], columns=['a'], dtype='object') df.a # 0 &lt;__main__.Foo object at 0x00000000058AC550&gt; # 1 &lt;__main__.Foo object at 0x00000000058AC358&gt; </code></pre>
2
2016-09-01T08:44:50Z
[ "python", "pandas", "dask" ]
How to specify metadata for dask.dataframe
39,265,396
<p>Providing metadata became very important in dask 0.11. The API provides some good examples, how to achieve that, but when it comes to picking the right dtypes for my dataframe, I still feel unsure.</p> <ul> <li>Could I do something like <code>meta={'x': int 'y': float, 'z': float}</code> instead of <code>meta={'x': 'i8', 'y': 'f8', 'z': 'f8'}</code>?</li> <li>Could somebody hint me to a list of possible values like 'i8'? What dtypes exist? </li> <li>How can I specify a column, that contains arbitrary objects? How can I specify a column, that contains only instances of one class?</li> </ul>
3
2016-09-01T07:33:58Z
39,271,481
<p>Both Dask.dataframe and Pandas use NumPy dtypes. In particular, anything within that you can pass to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html" rel="nofollow">np.dtype</a>. This includes the following:</p> <ol> <li>NumPy dtype objects, like <code>np.float64</code></li> <li>Python type objects, like <code>float</code></li> <li>NumPy dtype strings, like <code>'f8'</code></li> </ol> <p>Here is a more extensive list taken from the NumPy docs: <a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#specifying-and-constructing-data-types" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#specifying-and-constructing-data-types</a></p>
2
2016-09-01T12:23:01Z
[ "python", "pandas", "dask" ]
Call RPC from component with different role Crossbar.io
39,265,582
<p>I need to call procedure in Crossbar component, with it everything ok. But I have such configuration:</p> <pre><code> { "name": "somerole", "permissions": [ { "uri": "com.example.api.sender", "match": "exact", "allow": { "call": true, "register": true, "publish": false, "subscribe": false }, }, { "uri": "wamp.", "match": "prefix", "allow": { "call": true, "register": false, "publish": false, "subscribe": false } } ] } </code></pre> <p>But with this configuration I can call build in procedure such as 'wamp.subscription.list' and so on, via HTTP from other service. </p> <p>I want to disable to call build in procedure via HTTP and call such procedures inside component, how can I implement this?</p> <p>Configuration of component:</p> <pre><code> { "type": "class", "classname": "backend.api.APISession", "realm": "example.com", "role": "somerole" } </code></pre> <p>and transport:</p> <pre><code> "call": { "type": "caller", "realm": "example.com", "role": "somerole", "options": { "debug": true } }, "callsigned": { "type": "caller", "realm": "example.com", "role": "somerole", "options": { "post_body_limit": 8192, "timestamp_delta_limit": 10, "require_ip": [ "192.168.1.1/255.255.255.0", "127.0.0.1" ], "require_tls": false } } </code></pre>
0
2016-09-01T07:44:02Z
39,266,999
<p>I found a solution. Created additional class </p> <pre><code>class APIBaseSession(ApplicationSession): instance = None @inlineCallbacks def onJoin(self, details): if not APIBaseSession.instance: APIBaseSession.instance = self else: raise ValueError("Instance of API base was already set") @staticmethod @inlineCallbacks def wamp_subscription_lookup(topic): session_id = yield APIBaseSession.instance.call('wamp.subscription.lookup', topic) returnValue(session_id) </code></pre> <p>then I just call:</p> <pre><code>APIBaseSession.wamp_subscription_lookup('some_topic') </code></pre> <p>And set configuration of two components with different roles as a result we cannot call build in function via HTTP.</p>
0
2016-09-01T08:56:04Z
[ "python", "python-3.x", "autobahn", "crossbar" ]
How to display json value in django template?
39,265,646
<p>This is my View.py code... </p> <pre><code>import requests from django.http import HttpResponse from django.shortcuts import render import json def book(request): if request.method == 'POST': r = requests.post('http://api.railwayapi.com/cancelled/date/01-09-2016/apikey/mezxa1595/', params=request.POST) book=r.json() else: r = requests.get('http://api.railwayapi.com/cancelled/date/01-09-2016/apikey/mezxa1595/', params=request.GET) book=r.json() js=json.dumps(book) if r.status_code == 200: return render(request,'book.html', {'js':js}) return HttpResponse('Could not save data') </code></pre> <p>and question is that how to display <code>return render(request,'book.html', {'js':js})</code> in Html?</p>
0
2016-09-01T07:47:26Z
39,266,753
<p>That "js" should be a python dict not json object. You may need to:</p> <pre><code>return render(request,'book.html', {'js': json.loads(js)}) </code></pre> <p>Then you can use the variables in <code>book.html</code> template.</p>
-1
2016-09-01T08:44:50Z
[ "javascript", "python", "json", "django" ]
How to convert tar.gz file to zip using Python only?
39,265,680
<p>Does anybody has any code for converting tar.gz file into zip using only Python code? I have been facing many issues with tar.gz as mentioned in the <a href="http://stackoverflow.com/questions/39263929/how-can-i-read-tar-gz-file-using-pandas-read-csv-with-gzip-compression-option">How can I read tar.gz file using pandas read_csv with gzip compression option?</a></p>
0
2016-09-01T07:48:49Z
39,265,752
<p>You would have to use the <a href="https://docs.python.org/3/library/tarfile.html" rel="nofollow">tarfile</a> module, with mode <code>'r|gz'</code> for reading. Then use <a href="https://docs.python.org/3/library/zipfile.html#module-zipfile" rel="nofollow">zipfile</a> for writing.</p> <pre><code>import tarfile, zipfile tarf = tarfile.open( name='mytar.tar.gz', mode='r|gz' ) zipf = ZipFile.open( name='myzip.zip', mode='a', compress_type=ZIP_DEFLATED ) for m in tarf.getmembers(): f = tarf.extractfile( m ) fl = f.read() fn = m.name zipf.writestr( fn, fl ) # or zipf.writestr( fn, f ) ? tarf.close() zipf.close() </code></pre> <p>You can use <code>is_tarfile()</code> to check for a valid tar file.</p> <p>Perhaps you could also use <a href="https://docs.python.org/3/library/shutil.html#archiving-operations" rel="nofollow"><code>shutil</code></a>, but I think it cannot work on memory.</p> <p>PS: I do not have python in this PC, so there may be a few things to tune.</p>
1
2016-09-01T07:52:46Z
[ "python", "zip", "tar" ]
asyncio "Task was destroyed but it is pending!" in pysnmp sample program
39,265,772
<p>I am testing pysnmp asyncio module and as the start used the <a href="http://pysnmp.sourceforge.net/_downloads/multiple-sequential-queries.py" rel="nofollow">sample program</a> provided along with the documentation. When I run the sample program, it gives the <code>Task was destroyed but it is pending!</code> error. I checked SO for similar questions and could not find what is wrong with my (inexperienced) eyes. I am using Python 3.4.2 and asyncio that came with it and pysnmp (4.3.2) on Debian 8.5</p> <p>The program I using (the same as the sample program in pysnmp documentation)</p> <pre class="lang-py prettyprint-override"> <code> import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def getone(snmpEngine, hostname): errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData('public'), UdpTransportTarget(hostname), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ) ) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) @asyncio.coroutine def getall(snmpEngine, hostnames): for hostname in hostnames: yield from getone(snmpEngine, hostname) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete(getall(snmpEngine, [('demo.snmplabs.com', 1161), ('demo.snmplabs.com', 2161), ('demo.snmplabs.com', 3161)])) </code> </pre> <p>Error is:</p> <pre> <code> Executing wait_for= cb=[_raise_stop_error() at /usr/lib/python3.4/asyncio/base_event s.py:101] created at /usr/lib/python3.4/asyncio/base_events.py:264> took 0.460 seconds SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m Task was destroyed but it is pending! source_traceback: Object created at (most recent call last): File "multiple-sequential-queries.py", line 58, in ('demo.snmplabs.com', 3161)])) File "/usr/lib/python3.4/asyncio/base_events.py", line 271, in run_until_complete self.run_forever() File "/usr/lib/python3.4/asyncio/base_events.py", line 244, in run_forever self._run_once() File "/usr/lib/python3.4/asyncio/base_events.py", line 1075, in _run_once handle._run() File "/usr/lib/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib/python3.4/asyncio/tasks.py", line 237, in _step result = next(coro) File "/usr/lib/python3.4/asyncio/coroutines.py", line 79, in __next__ return next(self.gen) File "multiple-sequential-queries.py", line 50, in getall yield from getone(snmpEngine, hostname) File "/usr/lib/python3.4/asyncio/coroutines.py", line 79, in __next__ return next(self.gen) File "multiple-sequential-queries.py", line 31, in getone ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) File "/usr/lib/python3.4/asyncio/coroutines.py", line 79, in __next__ return next(self.gen) File "/usr/lib/python3.4/asyncio/coroutines.py", line 141, in coro res = func(*args, **kw) File "/usr/local/lib/python3.4/dist-packages/pysnmp/hlapi/asyncio/cmdgen.py", line 138, in getCmd addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) File "/usr/local/lib/python3.4/dist-packages/pysnmp/hlapi/lcd.py", line 87, in configure transport File "/usr/local/lib/python3.4/dist-packages/pysnmp/entity/config.py", line 308, in addTransport transport) File "/usr/local/lib/python3.4/dist-packages/pysnmp/carrier/asyncio/dispatch.py", line 70, in registerTransport self.loopingcall = asyncio.async(self.handle_timeout()) task: :4> wait_for= created at /usr/local/lib/python3.4/dist-packages/pysnmp/carrier/asyncio/dispatch.py:70> </code> </pre> <p>Any help to figure this out is much appreciated!</p> <p>Thanks.</p>
0
2016-09-01T07:53:56Z
39,437,074
<p>There is an internal timer function in pysnmp which is used for handling caches, retries etc. With asyncio transport that timer is driven by asyncio <code>Future</code>. The message you observe warns you about that Future object is still pending right before main loop is shut down.</p> <p>To fix that you need to cancel pending timer task once you are done with all the SNMP I/O. A [hackerish] way to do that would be to append the following snippet to the example script you mentioned:</p> <pre><code>... snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete(getall(snmpEngine, [('demo.snmplabs.com', 1161), ('demo.snmplabs.com', 2161), ('demo.snmplabs.com', 3161)])) # run a coroutine to cancel pending timer task from pysnmp.hlapi.asyncore.cmdgen import lcd @asyncio.coroutine def unconfigure(snmpEngine, authData=None): lcd.unconfigure(snmpEngine, authData) loop.run_until_complete(unconfigure(snmpEngine)) </code></pre> <p>I am working on adding similar coroutine into pysnmp so you could run it out-of-the-box.</p>
0
2016-09-11T14:26:21Z
[ "python", "python-3.x", "python-asyncio", "pysnmp" ]
Comparing previous and next values in a list or in a dataframe
39,265,798
<p>I am new here and have, after a lot of research, not been able to crack this one.</p> <p>My List looks somewhat like this:</p> <pre><code>lister=["AB1","AB2","AB3","AB3-2","AB3-3","AB3-4","AB4","AB4-2","AB5"] </code></pre> <p>It is a list of existing folders and cannot be changed into something more practical. I also have this list as a pandas df column along with some other values.</p> <p>The goal is for elements which have a "-2", "-3", "-#" to only use the element which has the biggest value. These "-#" values can go up to 10.</p> <p>A Result from the list above would be:</p> <pre><code>resulter=["AB1","AB2","AB3-4","AB4-2","AB5] </code></pre> <p>Thanks a lot for the help!</p> <p><strong>UPDATE:</strong></p> <p>The answer from John Zwinck is working for the lists. However, when I try to use it on a pandas dataframe it gives me errors. So to reframe my question would possible be more helpful:</p> <p>My Dataframe looks like this:</p> <pre><code> COL1 COL2 COL3 COL4 COL5 COL6 0 1 77 AB1 0.609856 2.145556 2.115333 1 2 77 AB2 0.603378 2.146333 2.125667 2 3 77 AB3 0.600580 2.150667 2.135000 3 4 89 AB1 0.609129 2.149056 2.097667 4 5 89 AB2 0.604061 2.175333 2.142667 5 6 89 AB3 0.606987 2.139944 2.107333 6 7 89 AB4 0.603696 2.122000 2.102000 7 8 94 AB1 0.606438 2.156444 2.142000 8 9 94 AB1-2 0.611260 2.133556 2.095000 9 10 94 AB2 0.596059 2.169056 2.137333 </code></pre> <p>My requirement in this case is to remove the row 7 based on the value of COL3 (AB1) because there exists an AB1-2 value in row 8. </p> <p>Thanks again!</p>
0
2016-09-01T07:54:59Z
39,266,032
<pre><code>gb = pd.Series(lister).str.split('-', 1, expand=True).groupby(0)[1].last().fillna('') </code></pre> <p>Gives you:</p> <pre><code>AB1 AB2 AB3 4 AB4 2 AB5 </code></pre> <p>Then:</p> <pre><code>gb.index + np.where(gb, '-' + gb, '') </code></pre> <p>Gives you:</p> <pre><code>['AB1', 'AB2', 'AB3-4', 'AB4-2', 'AB5'] </code></pre>
5
2016-09-01T08:07:13Z
[ "python", "string", "list", "pandas" ]
Comparing previous and next values in a list or in a dataframe
39,265,798
<p>I am new here and have, after a lot of research, not been able to crack this one.</p> <p>My List looks somewhat like this:</p> <pre><code>lister=["AB1","AB2","AB3","AB3-2","AB3-3","AB3-4","AB4","AB4-2","AB5"] </code></pre> <p>It is a list of existing folders and cannot be changed into something more practical. I also have this list as a pandas df column along with some other values.</p> <p>The goal is for elements which have a "-2", "-3", "-#" to only use the element which has the biggest value. These "-#" values can go up to 10.</p> <p>A Result from the list above would be:</p> <pre><code>resulter=["AB1","AB2","AB3-4","AB4-2","AB5] </code></pre> <p>Thanks a lot for the help!</p> <p><strong>UPDATE:</strong></p> <p>The answer from John Zwinck is working for the lists. However, when I try to use it on a pandas dataframe it gives me errors. So to reframe my question would possible be more helpful:</p> <p>My Dataframe looks like this:</p> <pre><code> COL1 COL2 COL3 COL4 COL5 COL6 0 1 77 AB1 0.609856 2.145556 2.115333 1 2 77 AB2 0.603378 2.146333 2.125667 2 3 77 AB3 0.600580 2.150667 2.135000 3 4 89 AB1 0.609129 2.149056 2.097667 4 5 89 AB2 0.604061 2.175333 2.142667 5 6 89 AB3 0.606987 2.139944 2.107333 6 7 89 AB4 0.603696 2.122000 2.102000 7 8 94 AB1 0.606438 2.156444 2.142000 8 9 94 AB1-2 0.611260 2.133556 2.095000 9 10 94 AB2 0.596059 2.169056 2.137333 </code></pre> <p>My requirement in this case is to remove the row 7 based on the value of COL3 (AB1) because there exists an AB1-2 value in row 8. </p> <p>Thanks again!</p>
0
2016-09-01T07:54:59Z
39,266,432
<p>this is <strong>not best</strong> answer and i think has <strong>bad performance</strong> but if someone need pure python without any module or use Cython(typed variables) this may help:</p> <pre><code>lister=["AB1","AB2","AB3","AB3-2","AB3-3","AB3-4","AB4","AB4-2","AB5"] resulter = list() i=0 while i&lt; len(lister)-1: if '-' not in lister[i] and '-' not in lister[i+1]: resulter.append(lister[i]) elif '-' not in lister[i] and '-' in lister[i+1]: j=i+1 tmp = lister[j] while '-' in tmp and j&lt;len(lister)-1 and lister[i][2] == lister[j+1][2]: j += 1 tmp = lister[j] i=j resulter.append(tmp) i+=1 if lister[-1] not in resulter: resulter.append(lister[-1]) print(resulter) </code></pre>
1
2016-09-01T08:28:32Z
[ "python", "string", "list", "pandas" ]
Python sys._getframe
39,265,823
<p>/mypath/test.py</p> <pre><code>import sys def test(): frame = sys._getframe(0) f = frame.f_code.co_filename print('f:', f) print('co_filename1:', frame.f_code.co_filename) while frame.f_code.co_filename == f: frame = frame.f_back print('co_filename2:', frame.f_code.co_filename) test() </code></pre> <p>run it and get:</p> <pre><code>f: /mypath/test.py co_filename1: /mypath/test.py Traceback (most recent call last): File "/mypath/test.py", line 13, in &lt;module&gt; test() File "/mypath/test.py", line 9, in test while frame.f_code.co_filename == f: AttributeError: 'NoneType' object has no attribute 'f_code' </code></pre> <p>Why frame.f_code get a NoneType Error in while loop but can print as usual?Thanks~</p>
1
2016-09-01T07:56:09Z
39,266,128
<p>Whenever you run <code>frame = frame.f_back</code> you go back to the previous code frame. When you are on the topmost frame, however, <code>f_back</code> attribute contains None (as in "there is no previous frame") - so you should just break off the while loop at that point. Just add an extra condition to that, for example:</p> <pre><code>while frame and frame.f_code.co_filename == f: frame = frame.f_back </code></pre>
0
2016-09-01T08:11:57Z
[ "python" ]
Regex on bytestring in Python 3
39,265,923
<p>I am using RegEx to match BGP messages in a byte string. An example byte string is looking like this:</p> <p><code>b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x13\x04\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x13\x04'</code></p> <p>\xff (8 times) is used as "magic marker" to start a single message. Now I want to split the messages to parse each of them.</p> <pre><code>messages = re.split(b'\xff{8}', payload) </code></pre> <p>Matching works fine but I got some empty fields in my messages array.</p> <pre><code>b'' b'' b'001304' b'' b'' b'001304' </code></pre> <p>Can someone explain this behavior? Why are there two empty fields between each (correct splitted) message. In larger byte strings sometimes there is just one empty field between each messages.</p>
3
2016-09-01T08:01:41Z
39,265,986
<p>I think you want to match 8 occurrences of <code>\xff</code>, not just 8 trailing <code>f</code>s (e.g. <code>\xfffffffff</code>):</p> <pre><code>messages = re.split(b'(?:\xff){8}', payload) ^^^ ^ </code></pre> <p>Also, there are just more than one 8 consecutive <code>\xff</code>s in your string on end. You might want to use</p> <pre><code>messages = re.split(b'(?:(?:\xff){8})+', payload) </code></pre> <p>However, that will still result in having an empty first element if the match is found at the start of the data. You may remove the part at the beginning before splitting:</p> <pre><code>messages = re.split(b'(?:(?:\xff){8})+', re.sub(b'^(?:(?:\xff){8})+', b'', payload)) </code></pre> <p><strong>HOWEVER</strong>, the best idea is to just remove the empty elements with a list comprehension or with <code>Filter</code> (<a href="http://stackoverflow.com/questions/39265923/regex-on-bytestring-in-python-3/39265986?noredirect=1#comment65915808_39265986">kudos for testing goes to you</a>):</p> <pre><code>messages = [x for x in re.split(b'(?:\xff){8}', payload) if x] # Or, the fastest way here as per the comments messages = list(filter(None, messages)) </code></pre> <p><strong>See an updated <a href="https://ideone.com/RxJ4Ln" rel="nofollow">Python 3 demo</a></strong></p>
1
2016-09-01T08:04:50Z
[ "python", "regex", "python-3.x", "bytestring" ]
How to draw recursive tree on tkinter
39,266,081
<p>I tried to draw recursive tree on python tkinter based on depth enter by user, here is my code so far:</p> <pre><code>from tkinter import * # Import tkinter import math #angleFactor = math.pi/5 #sizeFactor = 0.58 class Main: def __init__(self): window = Tk() # Create a window window.title("Recursive Tree") # Set a title self.width = 200 self.height = 200 self.canvas = Canvas(window, width = self.width, height = self.height,bg="white") self.canvas.pack() # Add a label, an entry, and a button to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() Label(frame1, text = "Enter the depth: ").pack(side = LEFT) self.depth = StringVar() entry = Entry(frame1, textvariable = self.depth, justify = RIGHT).pack(side = LEFT) Button(frame1, text = "Display Recursive Tree", command = self.display).pack(side = LEFT) self.angleFactor = math.pi/5 self.sizeFactor = 0.58 window.mainloop() # Create an event loop def drawLine(self, x1,x2,y1,y2): self.canvas.create_line(x1,y1,x2,y2, tags = "line") def display(self): self.canvas.delete("line") return self.paintBranch(int(self.depth.get()),self.width/2, self.height /2 , self.height/3, math.pi/2) def paintBranch(self,depth, x1, y1, length, angle): if depth &gt;= 0: x2 = x1 +int( math.cos(angle) * length) y2 = y1 + int(math.sin(angle) * length) # Draw the line self.drawLine(x1,y1,x2,y2) # Draw the left branch self.paintBranch(depth - 1, x2, y2, length * self.sizeFactor, angle + self.angleFactor ) # Draw the right branch self.paintBranch(depth - 1, x2, y2, length * self.sizeFactor, angle - self.angleFactor ) Main() </code></pre> <p>when the user enter <code>depth=0</code> the code is working, but when recursive in <code>depth &gt;=1</code>, the code fail to draw a tree, I need help for my code, thanks before</p>
0
2016-09-01T08:10:00Z
39,267,844
<p>Your main problem is that you messed up the args to the <code>drawLine</code> method. You defined it as </p> <pre><code>drawLine(self, x1,x2,y1,y2) </code></pre> <p>but you call it as </p> <pre><code>self.drawLine(x1,y1,x2,y2) </code></pre> <p>so the <code>y1</code> arg you pass it gets used for the <code>x2</code> parameter, and the <code>x2</code> arg gets used for the <code>y1</code> parameter. </p> <p>You also need to change your initial <code>y1</code> value, and to change the sign when computing <code>y2</code> from <code>y1</code>, because Y coordinates in Tkinter increase as you go down the screen.</p> <p>Here's a repaired version of your code.</p> <pre><code>from tkinter import * # Import tkinter import math class Main: def __init__(self): window = Tk() # Create a window window.title("Recursive Tree") # Set a title self.width = 400 self.height = 400 self.canvas = Canvas(window, width = self.width, height = self.height,bg="white") self.canvas.pack() # Add a label, an entry, and a button to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() Label(frame1, text = "Enter the depth: ").pack(side = LEFT) self.depth = StringVar() Entry(frame1, textvariable = self.depth, justify = RIGHT).pack(side = LEFT) Button(frame1, text = "Display Recursive Tree", command = self.display).pack(side = LEFT) self.angleFactor = math.pi/5 self.sizeFactor = 0.58 window.mainloop() # Create an event loop def drawLine(self, x1,y1, x2,y2): self.canvas.create_line(x1,y1, x2,y2, tags = "line") def display(self): self.canvas.delete("line") depth = int(self.depth.get()) return self.paintBranch(depth, self.width/2, self.height, self.height/3, math.pi/2) def paintBranch(self, depth, x1, y1, length, angle): if depth &gt;= 0: depth -= 1 x2 = x1 + int(math.cos(angle) * length) y2 = y1 - int(math.sin(angle) * length) # Draw the line self.drawLine(x1,y1, x2,y2) # Draw the left branch self.paintBranch(depth, x2, y2, length * self.sizeFactor, angle + self.angleFactor ) # Draw the right branch self.paintBranch(depth, x2, y2, length * self.sizeFactor, angle - self.angleFactor ) Main() </code></pre>
1
2016-09-01T09:32:43Z
[ "python", "recursion", "tkinter" ]
auto increment - internal reference odoo9
39,266,106
<p>I want to change the type of the field 'ref' (Internal Reference) to be auto incremented (for example every time I create a new contact my Internal Reference should increase by 1). So first contact should have Internal Reference 1, the second 2, the third 3 and so on...</p> <p>There are no errors but still the reference field is empty. Have I missed some additional code? Can someone help me?</p> <pre><code>@api.model def create(self, vals): if vals.get('ref', 'New') == 'New': vals['ref'] = self.env['ir.sequence'].next_by_code( 'res.debt') or 'New' return super(Partner, self).create(vals) </code></pre> <p>And the xml file:</p> <pre><code> &lt;record id="your_sequence_id" model="ir.sequence"&gt; &lt;field name="name"&gt;Reference&lt;/field&gt; &lt;field name="padding"&gt;3&lt;/field&gt; &lt;field name="code"&gt;res.debt&lt;/field&gt; &lt;/record&gt; </code></pre> <p><img src="http://i.stack.imgur.com/EMIn7.png" alt="Example of current result"></p>
0
2016-09-01T08:11:08Z
39,266,450
<p>You don't need the unnecessary if statement, because as you stated in your question you want the reference to autoincrement every time a new user is created. the users can't change the field from the form, this is how you get the next reference in odoo.</p> <pre><code>@api.model def create(self, vals): vals['ref'] = self.env['ir.sequence'].get('res.debt') return super(Partner, self).create(vals) </code></pre>
0
2016-09-01T08:29:24Z
[ "python", "xml", "auto-increment", "odoo-9" ]
Suppose i have two lists in python a list of first names and a list of last names
39,266,197
<pre><code>firstName = ['abcd','efghi','jkl','mnopqr'] lastName = ['xyz','pqrst','uvw','klmn'] </code></pre> <p>my desired output is </p> <pre><code>abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre> <p>I have tried various methods and failed.The closest i could come up with was</p> <pre><code>for x,y in zip(firstName,lastName): print(x,y) </code></pre> <p>What should i do?</p>
-1
2016-09-01T08:15:12Z
39,266,259
<pre><code>for x, y in zip(firstName,lastName): print(x, y, "%s.%s@example.com"%(x[0], y)) </code></pre>
1
2016-09-01T08:19:09Z
[ "python" ]
Suppose i have two lists in python a list of first names and a list of last names
39,266,197
<pre><code>firstName = ['abcd','efghi','jkl','mnopqr'] lastName = ['xyz','pqrst','uvw','klmn'] </code></pre> <p>my desired output is </p> <pre><code>abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre> <p>I have tried various methods and failed.The closest i could come up with was</p> <pre><code>for x,y in zip(firstName,lastName): print(x,y) </code></pre> <p>What should i do?</p>
-1
2016-09-01T08:15:12Z
39,266,299
<pre><code>&gt;&gt;&gt; for x,y in zip(firstName,lastName): ... print("{0}\t{1}\t{2}".format(x,y,x[0]+'.'+y+'@example.com')) ... abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre>
1
2016-09-01T08:21:16Z
[ "python" ]
Suppose i have two lists in python a list of first names and a list of last names
39,266,197
<pre><code>firstName = ['abcd','efghi','jkl','mnopqr'] lastName = ['xyz','pqrst','uvw','klmn'] </code></pre> <p>my desired output is </p> <pre><code>abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre> <p>I have tried various methods and failed.The closest i could come up with was</p> <pre><code>for x,y in zip(firstName,lastName): print(x,y) </code></pre> <p>What should i do?</p>
-1
2016-09-01T08:15:12Z
39,266,311
<pre><code>firstName = ['abcd','efghi','jkl','mnopqr'] lastName = ['xyz','pqrst','uvw','klmn'] for index in range(0, len(firstName)): first = firstName[index] last = lastName[index] email = first[0] + '.' + last + '@example.com' print first, last, email </code></pre>
0
2016-09-01T08:21:41Z
[ "python" ]
Suppose i have two lists in python a list of first names and a list of last names
39,266,197
<pre><code>firstName = ['abcd','efghi','jkl','mnopqr'] lastName = ['xyz','pqrst','uvw','klmn'] </code></pre> <p>my desired output is </p> <pre><code>abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre> <p>I have tried various methods and failed.The closest i could come up with was</p> <pre><code>for x,y in zip(firstName,lastName): print(x,y) </code></pre> <p>What should i do?</p>
-1
2016-09-01T08:15:12Z
39,266,314
<pre><code>for i,j in zip(firstName,lastName): print (i+" "+j+" "+i[0]+"."+j+"@example.com") </code></pre> <p>output </p> <pre><code>abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre>
0
2016-09-01T08:21:55Z
[ "python" ]
Suppose i have two lists in python a list of first names and a list of last names
39,266,197
<pre><code>firstName = ['abcd','efghi','jkl','mnopqr'] lastName = ['xyz','pqrst','uvw','klmn'] </code></pre> <p>my desired output is </p> <pre><code>abcd xyz a.xyz@example.com efghi pqrst e.pqrst@example.com jkl uvw j.uvw@example.com mnopqr klmn m.klmn@example.com </code></pre> <p>I have tried various methods and failed.The closest i could come up with was</p> <pre><code>for x,y in zip(firstName,lastName): print(x,y) </code></pre> <p>What should i do?</p>
-1
2016-09-01T08:15:12Z
39,266,322
<p>This prints the output you're looking for. Did you really just want to print it ?</p> <pre><code>for x,y in zip(firstName,lastName): print (x,y, x[0] + r'.' + y + r'@example.com') </code></pre>
1
2016-09-01T08:22:07Z
[ "python" ]
Fit erf function to data
39,266,231
<p>So I have hysteresis loop. I want to use the erf function to fit it with my data.</p> <p>A portion of my loop is shown in black on the lower graph.</p> <p>I am trying to use the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow"><code>scipy.optimize.curve_fit</code></a> and <code>scipy.special.erf</code> function to fit the data with the following code:</p> <pre><code>import scipy.special import scipy.optimize def erfunc(x,a,b): return mFL*scipy.special.erf((x-a)/(b*np.sqrt(2))) params,extras = scipy.optimize.curve_fit(erfunc,x_data,y_data) x_erf = list(range(-3000,3000,1)) y_erf = erfunc(x_erf,params[0],params[1]) </code></pre> <p><code>mFL</code> is a constant, <code>a</code> controls the position of the erf curve and <code>b</code> the slope of the curve. (To my knowledge)</p> <p>However, when I plot the obtained x_erf and y_erf data (in blue). I get the following fitting, which is not ideal to say the least:</p> <p><img src="http://i.stack.imgur.com/BE4tM.png" alt="Data with erf fitting plot"></p> <p>Is there a way i can get a proper fit?</p> <p>Edit: Link to data file: <a href="https://www.dropbox.com/s/o0uoieg3jkliun7/xydata.csv?dl=0" rel="nofollow">https://www.dropbox.com/s/o0uoieg3jkliun7/xydata.csv?dl=0</a> Params[0] = 1.83289895, Params<a href="http://i.stack.imgur.com/LdUv0.png" rel="nofollow">1</a> = 0.27837306</p>
1
2016-09-01T08:17:12Z
39,267,369
<p>I suspect two things are needed for a good fit here. First, I believe you need to add <code>mFL</code> to your <code>erfunc</code> function, and second, as suggested by Glostas, you need to specify some initial guesses for your fitting parameters. I created some artificial data in an attempt to replicate your data. The plot on the left is before giving <code>curve_fit</code> some initial parameters and the plot on the right is after.</p> <p><a href="http://i.stack.imgur.com/iR16A.png" rel="nofollow"><img src="http://i.stack.imgur.com/iR16A.png" alt="enter image description here"></a></p> <hr> <p>Here is the code to reproduce the above plots</p> <pre><code>import numpy as np from scipy.special import erf from scipy.optimize import curve_fit import matplotlib.pyplot as plt def erfunc(x, mFL, a, b): return mFL*erf((x-a)/(b*np.sqrt(2))) x_data = np.linspace(-3000, 3000, 100) mFL, a, b = 0.0003, 500, 100 y_data = erfunc(x_data, mFL, a, b) y_noise = np.random.rand(y_data.size) / 1e4 y_noisy_data = y_data + y_noise params, extras = curve_fit(erfunc, x_data, y_noisy_data) # supply initial guesses to curve_fit through p0 arg superior_params, extras = curve_fit(erfunc, x_data, y_noisy_data, p0=[0.001, 100, 100]) fig = plt.figure() ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) ax1.plot(x_data, erfunc(x_data, *params)) ax1.plot(x_data, y_noisy_data, 'k') ax1.set_title('Before Guesses') ax2.plot(x_data, erfunc(x_data, *superior_params)) ax2.plot(x_data, y_noisy_data, 'k') ax2.set_title('After Guesses') </code></pre>
2
2016-09-01T09:11:34Z
[ "python", "python-3.x", "numpy", "scipy" ]
transcrypt import in import
39,266,262
<p>Using Transcrypt for python to javascript compiling I have 2 modules that need each other. For example: </p> <p>myTest.py:</p> <pre><code>import myTest2 def test(): myTest2.test() someConstant = 1 </code></pre> <p>and myTest2.py:</p> <pre><code>import myTest def test(): console.log(myTest.someConstant) </code></pre> <p>After compiling to javascript, and calling <code>myTest.test()</code> I get an RangeError: Maximum call stack size exceeded. How can I avoid this, but keep 2 modules which use each other? Thanks in advance.</p>
1
2016-09-01T08:19:18Z
39,266,474
<p>Try importing from <code>myTest</code> as and when you need it.</p> <p>In <code>mytest2.py</code></p> <pre><code>def test(): from myTest import someConstant console.log(someConstant) </code></pre>
0
2016-09-01T08:30:21Z
[ "javascript", "python", "transcrypt" ]
transcrypt import in import
39,266,262
<p>Using Transcrypt for python to javascript compiling I have 2 modules that need each other. For example: </p> <p>myTest.py:</p> <pre><code>import myTest2 def test(): myTest2.test() someConstant = 1 </code></pre> <p>and myTest2.py:</p> <pre><code>import myTest def test(): console.log(myTest.someConstant) </code></pre> <p>After compiling to javascript, and calling <code>myTest.test()</code> I get an RangeError: Maximum call stack size exceeded. How can I avoid this, but keep 2 modules which use each other? Thanks in advance.</p>
1
2016-09-01T08:19:18Z
39,280,920
<p>In Transcrypt imports are resolved at compile time rather than runtime, since the compiler must know which modules to include in the generated JavaScript. Moreover, import resolution happens in one pass. This fact that resolution happens in a single pass means that mutual (or in general cyclic) imports are not supported.</p> <p>So if you have two modules that require something of each other, the way to go is to factor that something out and put in in a third module, imported by both.</p> <p>The fact that resolution happens at compile time also means that there's no point in runtime conditional imports, using 'if'. For conditional imports use __pragma__ ('ifdef', ...) which does its work compile time.</p> <p>Restrictions like this are explained at:</p> <p><a href="http://sterlicht.alwaysdata.net/transcrypt.org/docs/html/special_facilities.html#transcrypt-s-module-mechanism" rel="nofollow">http://sterlicht.alwaysdata.net/transcrypt.org/docs/html/special_facilities.html#transcrypt-s-module-mechanism</a></p>
2
2016-09-01T21:12:04Z
[ "javascript", "python", "transcrypt" ]
write into file without reading all the file
39,266,351
<p>I have a template of a file (html) with the header and footer. I try to insert text into right after <code>&lt;trbody&gt;</code>. The way i'm doing it right now is with <code>fileinput.input()</code> </p> <pre><code>def write_to_html(self,path): for line in fileinput.input(path, inplace=1): line = re.sub(r'CURRENT_APPLICATION', obj, line) line = re.sub(r'IN_PROGRESS', time.strftime("%Y-%m-%d %H:%M:%S"), line) line = re.sub(r'CURRENT_VERSION', svers, line) print line, # preserve old content if "&lt;tbody&gt;" in line: print ("&lt;tr&gt;") ###PRINT MY STUFFS print ("&lt;/tr&gt;") </code></pre> <p>I call this for each Table-line I have to add in my html table. but I have around 5k table-lines to add (each line is about 30 lines of hmtl code). It starts fast, but each line takes more and more times to be added. It's because it has to write the file all over again for each line right ?</p> <p>Is there a way to speed up the process?</p> <p>EDIT thanks for the responses : I like the idee of creating my big string, and the just go through the file just once. I'll have to change some stuff because right now because the function I showed is in a Classe. and in my main programe, I just iterate on a folder containing .json.</p> <pre><code> for json in jsonfolder : Object_a = CLASS-A(json) #unserialization Object_a.write_to_html() (the function i showed) </code></pre> <p>I should turn that into :</p> <pre><code>block_of_lines='' for json in jsonfolder : Object_a = CLASS-A(json) #unserialization block_of_line += Object_a.to_html_sting() Create_html(block_of_line) </code></pre> <p>Would that be faster ?</p>
0
2016-09-01T08:23:21Z
39,266,661
<p>5000 lines is nothing. Read the entire file using <code>f.readlines()</code> to get a list of lines:</p> <pre><code>with open(path) as f: lines = f.readlines() </code></pre> <p>Then process each line, and eventually join them to one string and write the entire thing back to the file.</p>
-2
2016-09-01T08:40:16Z
[ "python", "python-2.7" ]
write into file without reading all the file
39,266,351
<p>I have a template of a file (html) with the header and footer. I try to insert text into right after <code>&lt;trbody&gt;</code>. The way i'm doing it right now is with <code>fileinput.input()</code> </p> <pre><code>def write_to_html(self,path): for line in fileinput.input(path, inplace=1): line = re.sub(r'CURRENT_APPLICATION', obj, line) line = re.sub(r'IN_PROGRESS', time.strftime("%Y-%m-%d %H:%M:%S"), line) line = re.sub(r'CURRENT_VERSION', svers, line) print line, # preserve old content if "&lt;tbody&gt;" in line: print ("&lt;tr&gt;") ###PRINT MY STUFFS print ("&lt;/tr&gt;") </code></pre> <p>I call this for each Table-line I have to add in my html table. but I have around 5k table-lines to add (each line is about 30 lines of hmtl code). It starts fast, but each line takes more and more times to be added. It's because it has to write the file all over again for each line right ?</p> <p>Is there a way to speed up the process?</p> <p>EDIT thanks for the responses : I like the idee of creating my big string, and the just go through the file just once. I'll have to change some stuff because right now because the function I showed is in a Classe. and in my main programe, I just iterate on a folder containing .json.</p> <pre><code> for json in jsonfolder : Object_a = CLASS-A(json) #unserialization Object_a.write_to_html() (the function i showed) </code></pre> <p>I should turn that into :</p> <pre><code>block_of_lines='' for json in jsonfolder : Object_a = CLASS-A(json) #unserialization block_of_line += Object_a.to_html_sting() Create_html(block_of_line) </code></pre> <p>Would that be faster ?</p>
0
2016-09-01T08:23:21Z
39,274,864
<p>Re-reading the question a couple more times, the following thought occurs. Could you split the writing into 3 blocks - one for the header, one for the table lines and another for the footer. It does rather seem to depend on what those three substitution lines are doing, but if I'm right, they can only update lines the first time the template is used, ie. while acting on the first json file, and then remain unchanged for the others.</p> <pre><code> file_footer = CLASS-A.write_html_header(path) for json in jsonfolder : Object_a = CLASS-A(json) #unserialization Object_a.write_to_html(path) #use the part of the function # that just handles the json file here CLASS-A.write_html_footer(path, footer) </code></pre> <p>Then in your class, define the two new functions to write the header and footer as static methods (which means they can be used from the class rather than just on an instance) i.e. (using a copy from your own code)</p> <pre><code>@staticmethod def write_html_header(path): footer = [] save_for_later = false for line in fileinput.input(path, inplace=1): line = re.sub(r'CURRENT_APPLICATION', obj, line) line = re.sub(r'IN_PROGRESS', time.strftime("%Y-%m-%d %H:%M:%S"), line) line = re.sub(r'CURRENT_VERSION', svers, line) # this blocks prints the header, and saves the # footer from your template. if save_for_later: footer.append(line) else: print line, # preserve old content if "&lt;tbody&gt;" in line: save_for_later = true return footer </code></pre> <p>I do wonder why you're editing 'inplace' doesn't that mean the template get's overwritten, and thus it's less of a template and more of a single use form. Normally when I use a template, I read in from the template, and write out to a new file an edited version of the template. Thus the template can be re-used time and time again.</p> <p>For the footer section, open your file in append mode, and then write the lines in the footer array created by the call to the header writing function.</p> <p>I do think not editing the template in place would be of benefit to you. then you'd just need to :</p> <pre><code>open the template (read only) open the new_file (in new, write mode) write the header into new_file loop over json files append table content into new_file append the footer into new_file </code></pre> <p>That way you're never re-reading the bits of the file you created while looping over the json files. Nor are you trying to store the whole file in memory if that is a concern.</p>
1
2016-09-01T14:55:30Z
[ "python", "python-2.7" ]
How to delete directory containing .git in python
39,266,408
<p>I am not able to override/delete the folder containing .git in python. I am working on the below configuration:</p> <ul> <li>OS - Windows 8</li> <li>Python - 3.5.2</li> <li>Git - 2.9.2</li> </ul> <p>Any Help would be appreciated.</p>
0
2016-09-01T08:26:55Z
39,266,507
<p>You should be using shutil to remove a directory that's not empty. If <code>os.rmdir</code> is used on a directory that's not empty an exception is raised. </p> <pre><code>import shutil shutil.rmtree('/.git') </code></pre>
0
2016-09-01T08:32:25Z
[ "python", "git" ]
How to delete directory containing .git in python
39,266,408
<p>I am not able to override/delete the folder containing .git in python. I am working on the below configuration:</p> <ul> <li>OS - Windows 8</li> <li>Python - 3.5.2</li> <li>Git - 2.9.2</li> </ul> <p>Any Help would be appreciated.</p>
0
2016-09-01T08:26:55Z
39,266,520
<p>try this code</p> <pre><code>import shutil shutil.rmtree('/path/to/your/dir/') </code></pre>
0
2016-09-01T08:32:59Z
[ "python", "git" ]
Dynamic framesize in Python Reportlab
39,266,415
<p>I tried to generate a shipping list with <a href="/questions/tagged/reportlab" class="post-tag" title="show questions tagged &#39;reportlab&#39;" rel="tag">reportlab</a> in Python. I was trying to put all parts (like senders address, receivers address, a table) in place by using Platypus <code>Frames</code>.</p> <p><strong>The first problem</strong> that I ran into was that I needed a lot of <code>Frames</code> to position everything the right way, is there a better way using Platypus? Because I want the senders address and my address to be on the same height and if I just add them to my <code>story = []</code> they get aligned one below the other.</p> <p><strong>The next problem</strong> is that the table I'm drawing is dynamic in size and when I reach the end of the <code>Frame</code> ( space I want the table to go) it just does a <code>FrameBreak</code> and continuous in the next frame. So how can I make the <code>Frame</code> (space for my table ) dynamic?</p>
1
2016-09-01T08:27:26Z
39,268,987
<p>Your use case is a really common one, so Reportlab has a system to help you out. </p> <p>If you read the user guide about <code>platypus</code> it will introduce you to 4 main concepts: </p> <blockquote> <p><code>DocTemplates</code> the outermost container for the document;</p> <p><code>PageTemplates</code> specifications for layouts of pages of various kinds;</p> <p><code>Frames</code> specifications of regions in pages that can contain flowing text or graphics.</p> <p><code>Flowables</code> Using <code>PageTemplates</code> you can combine "static" content with dynamic on a page in a sensible way like for example logo's, addresses and such.</p> </blockquote> <p>You already discovered the <code>Flowables</code> and <code>Frames</code> but propably you did not start on fancy<code>PageTemplates</code> or <code>DocTemplates</code> yet. This makes sense because it isn't necessary for most simple documents. Saddly a shippinglist isn't a simple document, it holds address, logos and important info that has to be on every page. This is where <code>PageTemplates</code> come in.</p> <p>So how do you use these templates? The concept is simple each page has a certain structure that might differ between pages, for example on page one you want to put the addresses and then start the table while on the second page you only want the table. This would be something like this:</p> <p><strong>Page 1:</strong> <a href="http://i.stack.imgur.com/M4t19.png" rel="nofollow"><img src="http://i.stack.imgur.com/M4t19.png" alt="enter image description here"></a></p> <p><strong>Page 2:</strong> <a href="http://i.stack.imgur.com/3T9HY.png" rel="nofollow"><img src="http://i.stack.imgur.com/3T9HY.png" alt="enter image description here"></a></p> <p>A example would look like this: </p> <p><em>(This would be perfect for the SO Documentation if there was one for Reportlab)</em></p> <pre><code>from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import cm from reportlab.lib import colors from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, NextPageTemplate, Paragraph, PageBreak, Table, \ TableStyle class ShippingListReport(BaseDocTemplate): def __init__(self, filename, their_adress, objects, **kwargs): super().__init__(filename, page_size=A4, _pageBreakQuick=0, **kwargs) self.their_adress = their_adress self.objects = objects self.page_width = (self.width + self.leftMargin * 2) self.page_height = (self.height + self.bottomMargin * 2) styles = getSampleStyleSheet() # Setting up the frames, frames are use for dynamic content not fixed page elements first_page_table_frame = Frame(self.leftMargin, self.bottomMargin, self.width, self.height - 6 * cm, id='small_table') later_pages_table_frame = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='large_table') # Creating the page templates first_page = PageTemplate(id='FirstPage', frames=[first_page_table_frame], onPage=self.on_first_page) later_pages = PageTemplate(id='LaterPages', frames=[later_pages_table_frame], onPage=self.add_default_info) self.addPageTemplates([first_page, later_pages]) # Tell Reportlab to use the other template on the later pages, # by the default the first template that was added is used for the first page. story = [NextPageTemplate(['*', 'LaterPages'])] table_grid = [["Product", "Quantity"]] # Add the objects for shipped_object in self.objects: table_grid.append([shipped_object, "42"]) story.append(Table(table_grid, repeatRows=1, colWidths=[0.5 * self.width, 0.5 * self.width], style=TableStyle([('GRID',(0,1),(-1,-1),0.25,colors.gray), ('BOX', (0,0), (-1,-1), 1.0, colors.black), ('BOX', (0,0), (1,0), 1.0, colors.black), ]))) self.build(story) def on_first_page(self, canvas, doc): canvas.saveState() # Add the logo and other default stuff self.add_default_info(canvas, doc) canvas.drawString(doc.leftMargin, doc.height, "My address") canvas.drawString(0.5 * doc.page_width, doc.height, self.their_adress) canvas.restoreState() def add_default_info(self, canvas, doc): canvas.saveState() canvas.drawCentredString(0.5 * (doc.page_width), doc.page_height - 2.5 * cm, "Company Name") canvas.restoreState() if __name__ == '__main__': ShippingListReport('example.pdf', "Their address", ["Product", "Product"] * 50) </code></pre>
1
2016-09-01T10:24:02Z
[ "python", "pdf", "pdf-generation", "reportlab" ]
Django Admin showing Object - not working with __unicode__ OR __str__
39,266,629
<p>my Django admin panel is showing <code>object</code> instead of <code>self.name</code> of the object.</p> <p>I went through several similar questions here yet couldn't seem to resolve this issue. <code>__unicode__</code> and <code>__str__</code> bear the same results, both for books and for authors. I've changed those lines and added new authors/books in every change but no change.</p> <p><strong>MODELS.PY</strong></p> <pre><code>from django.db import models from django.contrib.auth.models import User # Create your models here. class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): auto_increment_id = models.AutoField(primary_key=True) name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=False, null=False) contents = models.TextField('Contents', blank=False, null=False) def __unicode__(self): return self.name </code></pre> <blockquote> <p>I used both <strong>unicode</strong> &amp; <strong>str</strong> interchangeably, same result.</p> </blockquote> <p>Here are the screenshots of the admin panel by menu/action.</p> <blockquote> <p>1st screen</p> </blockquote> <p><a href="http://i.stack.imgur.com/V8dx3.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/V8dx3.jpg" alt="1st screen"></a></p> <blockquote> <p>Author List</p> </blockquote> <p><a href="http://i.stack.imgur.com/Ln6qZ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Ln6qZ.jpg" alt="Author List"></a></p> <blockquote> <p>Single Author</p> </blockquote> <p><a href="http://i.stack.imgur.com/mumdo.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/mumdo.jpg" alt="Single Author"></a></p>
1
2016-09-01T08:38:32Z
39,266,725
<p>Your indentation is incorrect. You need to indent the code to make it a method of your model. It should be:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name </code></pre> <p>If you are using Python 3, use <a href="https://docs.djangoproject.com/en/1.10/ref/models/instances/#str" rel="nofollow"><code>__str__</code></a>. If you are using Python 2, use <code>__unicode__</code>, or decorate your class with the <code>python_2_unicode_compatible</code> decorator. After changing the code, make sure you restart the server so that code changes take effect.</p>
3
2016-09-01T08:43:30Z
[ "python", "django", "postgresql" ]
Import module does not work through terminal, while it works through IDE
39,266,662
<p>I have a projects consisting of two packages like this:</p> <pre><code>MyProjectDir -Package1 --__init__.py --file1_1.py --file1_2.py --file1_3.py -Package2 --__init__.py --file2_1.py --file2_2.py --file2_3.py </code></pre> <p>Now, in the packages the files have some imports between files:</p> <p><strong>file2_3.py:</strong></p> <pre><code>from Package2.file2_1 import * run_some_code() </code></pre> <p>When I run file2_3.py directly from PyCharm, everything runs ok. But when I try to run the script in the terminal (I'm working on Windows 7):</p> <pre><code>D:\SVN Repo\MyProjectDir\Package2&gt; python file2_3.py </code></pre> <p>or alternatively</p> <pre><code>D:\SVN Repo\MyProjectDir&gt; python ./Package2/file2_3.py </code></pre> <p>It seems python can't see my packages and I get an error:</p> <pre><code>Traceback (most recent call last): File "./Package2/file2_3.py", line 1, in &lt;module&gt; from Package2.file2_1 import * ImportError: No module named 'Package2' </code></pre> <p>What is the reason?</p> <p><strong>EDIT: If in the import line I use <code>from file2_1.py import *</code> without the package name, the IDE underlines the import as "Unresolved Reference Package2" (though it can run), and the terminal works...</strong></p>
2
2016-09-01T08:40:17Z
39,267,022
<p>The issue is that the way in which you are running the program <em>is wrong</em>, PyCharm is aware on how to handle python submodules and thus executes the file correctly.</p> <p>If you have a package <code>package1</code> with a module <code>package1.my_module</code> you should run this using the <code>-m</code> switch:</p> <pre><code>python -m package1.my_module </code></pre> <p>Do <strong>not</strong> run it directly:</p> <pre><code>python package1/my_module.py &lt;-- NO! Incorrect </code></pre> <p>Also: you should run the file from <em>outside</em> the package. So if your project is:</p> <pre><code>MyProject | +- package1 | | | +- file1.py | +- package2 | +- file2.py </code></pre> <p>Your working directory should be <code>MyProject</code>.</p> <p>My personal advice: <strong>never</strong> run submodules directly. Instead put the code in a <em>separate</em> script that is outside the package. So I'd have:</p> <pre><code>MyProject | +- package1 | | | +- file1.py | +- package2 | | | +- file2.py | +- scripts | +- script1.py </code></pre> <p>Where <code>script1.py</code> imports the modules it needs:</p> <pre><code>from package1 import file1 from package2 import file2 # code </code></pre> <p>Then you can run that script from your <code>MyProject</code> directory:</p> <pre><code>python scripts/script1.py </code></pre> <p>When you want to deploy your code you'll write a <code>setup.py</code> scripts that adds <code>package1</code> and <code>package2</code> as packages while <code>script1.py</code> as a script and they will be installed in the correct directories so that you'll be able to import <code>package1</code> and <code>package2</code> from everywhere and run <code>script1.py</code> from everywhere.</p>
1
2016-09-01T08:57:14Z
[ "python", "windows", "import" ]
NameError: global name 'QContextMenuEvent' is not defined
39,266,682
<p>I want to add a right click menu.</p> <pre><code>def contextMenuEvent(self,event): global posX global posY global selections,scan_widget if event.reason() == QContextMenuEvent.Mouse: menu = QMenu(self) clear = menu.addAction('Clear') for i in selections: self.buttonLabels.append(menu.addAction(i)) deleteBox = menu.addAction('Delete Box') changeId = menu.addAction('Change Id') cancel = menu.addAction('Cancel') action = menu.exec_(self.mapToGlobal(event.pos())) for i,key in enumerate(self.buttonLabels): if action == key: self.annotClass = selections[i] self.annotEnabled = True if action == deleteBox: self.deleteEnabled = True elif action == changeId: #Call the textbox self.newBoxId = textBox() self.newBoxId.setGeometry(QRect(500, 100, 300, 100)) self.newBoxId.show() elif action == cancel: pass elif action == clear: self.annotClass = 'Clear' self.annotEnabled = True self.posX_annot = event.pos().x() self.posY_annot = event.pos().y() posX = event.pos().x() posY = event.pos().y() self.repaint() self.buttonLabels = [] self.annotEnabled = False </code></pre> <p>But give me back this error: </p> <blockquote> <p>NameError: global name 'QContextMenuEvent' is not defined</p> </blockquote> <p>Then, I added QContextMenuEvent as import:</p> <pre><code>from PyQt5.QtWidgets import (QApplication, QComboBox, QHBoxLayout, QPushButton,QSizePolicy, QVBoxLayout, QWidget,QLineEdit, QInputDialog, QMenu,QContextMenuEvent) </code></pre> <p>But,</p> <blockquote> <p>ImportError: cannot import name QContextMenuEvent</p> </blockquote> <p>What am I doing wrong?</p>
0
2016-09-01T08:41:39Z
39,267,282
<p>From what I googled, <code>QContextMenuEvent</code> class resides in the <code>QtGui</code> module which can be imported from <code>PyQt5</code></p> <pre><code>from PyQt5.QtGui import QContextMenuEvent </code></pre>
2
2016-09-01T09:07:52Z
[ "python", "menu", "pyqt5" ]
NameError: global name 'QContextMenuEvent' is not defined
39,266,682
<p>I want to add a right click menu.</p> <pre><code>def contextMenuEvent(self,event): global posX global posY global selections,scan_widget if event.reason() == QContextMenuEvent.Mouse: menu = QMenu(self) clear = menu.addAction('Clear') for i in selections: self.buttonLabels.append(menu.addAction(i)) deleteBox = menu.addAction('Delete Box') changeId = menu.addAction('Change Id') cancel = menu.addAction('Cancel') action = menu.exec_(self.mapToGlobal(event.pos())) for i,key in enumerate(self.buttonLabels): if action == key: self.annotClass = selections[i] self.annotEnabled = True if action == deleteBox: self.deleteEnabled = True elif action == changeId: #Call the textbox self.newBoxId = textBox() self.newBoxId.setGeometry(QRect(500, 100, 300, 100)) self.newBoxId.show() elif action == cancel: pass elif action == clear: self.annotClass = 'Clear' self.annotEnabled = True self.posX_annot = event.pos().x() self.posY_annot = event.pos().y() posX = event.pos().x() posY = event.pos().y() self.repaint() self.buttonLabels = [] self.annotEnabled = False </code></pre> <p>But give me back this error: </p> <blockquote> <p>NameError: global name 'QContextMenuEvent' is not defined</p> </blockquote> <p>Then, I added QContextMenuEvent as import:</p> <pre><code>from PyQt5.QtWidgets import (QApplication, QComboBox, QHBoxLayout, QPushButton,QSizePolicy, QVBoxLayout, QWidget,QLineEdit, QInputDialog, QMenu,QContextMenuEvent) </code></pre> <p>But,</p> <blockquote> <p>ImportError: cannot import name QContextMenuEvent</p> </blockquote> <p>What am I doing wrong?</p>
0
2016-09-01T08:41:39Z
39,268,067
<p>I replaced </p> <p><code>if event.reason() == QContextMenuEvent.Mouse:</code> </p> <p>with</p> <p><code>if event.button == Qt.RightButton:</code></p>
0
2016-09-01T09:42:52Z
[ "python", "menu", "pyqt5" ]
How to use sqlalchemy to query in many-to-many relation?
39,266,776
<p>To get a member list in current organization, i used following statement, </p> <pre><code>from ..members import members from flask.ext.login import current_user from app.common.database import db_session @members.route("/", methods=["GET"]) @login_required def index(): datas = db_session.query(Group_has_Person).filter(Group_has_Person.group.organization==current_user.organization).all() </code></pre> <p>but a exception threw out at runtime: AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Group_has_Person.group has an attribute 'organization'</p> <p>how to get the member list in a right way? the code below is about model definition:</p> <pre><code> class Organization(Base): __tablename__ = 'Organization' id = Column(Integer, primary_key = True) title = Column(String(45), nullable = False) logo = Column(String(256), nullable = False) contact_name = Column(String(45), nullable = False) contact_phone = Column(String(45), nullable = False) created_time = Column(DateTime, nullable = False, default = datetime.now()) User_id = Column(Integer, ForeignKey('User.id')) user = relationship("User", back_populates="organization") groups = relationship("Group", back_populates="organization") class Group(Base): __tablename__ = 'Group' id = Column(Integer, primary_key = True) title = Column(String(45), nullable = False) teacher = Column(String(45), nullable = True) contact = Column(String(45), nullable = True) created_time = Column(DateTime, nullable = False, default = datetime.now()) status = Column(Integer, nullable = False, default = 1) Organization_id = Column(Integer, ForeignKey('Organization.id')) organization = relationship("Organization", back_populates="groups") members = relationship("Group_has_Person", back_populates="group") class Person(Base): __tablename__ = 'Person' id = Column(Integer, primary_key = True) nickname = Column(String(45), nullable = False) avatar = Column(String(256), nullable = False) gender = Column(Integer, nullable = False) birthday = Column(DateTime, nullable = False) User_id = Column(Integer, ForeignKey('User.id')) user = relationship("User", back_populates="person") groups = relationship("Group_has_Person", back_populates="person") class Group_has_Person(Base): __tablename__ = 'Group_has_Person' Group_id = Column(Integer, ForeignKey('Group.id'), primary_key = True) Person_id = Column(Integer, ForeignKey('Person.id'), primary_key = True) created_time = Column(DateTime, nullable = False, default = datetime.now()) status = Column(Integer, nullable = False, default = 0) group = relationship("Group", back_populates="members") person = relationship("Person", back_populates="groups") </code></pre> <p>table scripts:</p> <pre><code>CREATE TABLE 'Group' ( 'id' int(11) NOT NULL AUTO_INCREMENT, 'title' varchar(45) NOT NULL DEFAULT '' COMMENT '班级名称', 'teacher' varchar(45) DEFAULT NULL COMMENT '辅导老师', 'contact' varchar(45) DEFAULT NULL COMMENT '联系方式', 'created_time' datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', 'status' int(11) NOT NULL COMMENT '状态:-1-删除 1-正常', 'Organization_id' int(11) NOT NULL, PRIMARY KEY ('id'), KEY 'fk_Classes_Organization1_idx' ('Organization_id'), CONSTRAINT 'fk_Classes_Organization1' FOREIGN KEY ('Organization_id') REFERENCES 'Organization' ('id') ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='班级'; CREATE TABLE 'Person' ( 'id' int(11) NOT NULL AUTO_INCREMENT, 'User_id' int(11) NOT NULL, 'nickname' varchar(45) NOT NULL COMMENT '', 'avatar' varchar(256) NOT NULL COMMENT '', 'gender' int(11) NOT NULL COMMENT '', 'birthday' datetime DEFAULT NULL COMMENT '', PRIMARY KEY ('id'), KEY 'fk_Person_User1_idx' ('User_id'), CONSTRAINT 'fk_Person_User1' FOREIGN KEY ('User_id') REFERENCES 'User' ('id') ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='个人'; CREATE TABLE 'Group_has_Person' ( 'Group_id' int(11) NOT NULL, 'Person_id' int(11) NOT NULL, 'created_time' datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '加入时间', 'status' int(11) NOT NULL DEFAULT '0' COMMENT '状态 0-申请 1-成功', PRIMARY KEY ('Group_id','Person_id'), KEY 'fk_Group_has_Person_Person1_idx' ('Person_id'), KEY 'fk_Group_has_Person_Group1_idx' ('Group_id'), CONSTRAINT 'fk_Group_has_Person_Group1' FOREIGN KEY ('Group_id') REFERENCES 'Group' ('id') ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT 'fk_Group_has_Person_Person1' FOREIGN KEY ('Person_id') REFERENCES 'Person' ('id') ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre>
0
2016-09-01T08:46:02Z
39,340,319
<p>I've resolved my question by the following statement:</p> <pre><code>datas = db_session.query(Group_has_Person).join(Group).filter(Group.organization==current_user.organization).all() </code></pre>
0
2016-09-06T03:43:53Z
[ "python", "sqlalchemy" ]
Python multiprocessing pool freezes without reason
39,266,816
<p>I am pretty new to python and I hope someone here can help me.</p> <p>I started learning python some weeks ago and I tried to build a webcrawler.</p> <p>The idea is the following: The first part crawls the domains from a website (for each letter). The second part checks if the domain is valid (reachable and not parked) and persists it in a database.</p> <p>Everything is doing well till the crawler reaches 'r'. After some minutes the program freezes without any error message etc. Also the letters after 'r' don't make any problems... The domain where the program freezes isn't the same.</p> <p>Here is my code:</p> <pre><code>import requests import re import logging import time from bs4 import BeautifulSoup from multiprocessing.pool import Pool """ Extract only the plain text of element """ def visible(element): if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: return False elif re.match('.*&lt;!--.*--&gt;.*', str(element), re.DOTALL): return False elif re.fullmatch(r"[\s\r\n]", str(element)): return False return True logging.basicConfig(format='%(asctime)s %(name)s - %(levelname)s: %(message)s', level=logging.ERROR) logger = logging.getLogger('crawler') hdlr = logging.FileHandler('crawler.log') formatter = logging.Formatter('%(asctime)s %(name)s - %(levelname)s: %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) """ Checks if a domain is parked. Returns true if a domain is not parked, otherwise false """ def check_if_valid(website): try: resp = requests.get("http://www." + website, timeout=10, verify=False) soup = BeautifulSoup(resp.text, 'html.parser') if len(soup.find_all('script')) == 0: # check for very small web pages if len(resp.text) &lt; 700: return None # check for 'park' pattern text = filter(visible, soup.find_all(text=True)) for elem in text: if 'park' in elem: return None return "http://www." + website + "/" except requests.exceptions.RequestException as e: # no logging -&gt; too many exceptions return None except Exception as ex: logger.exception("Error during domain validation") def persist_domains(nonParkedDomains): logger.info("Inserting domains into database") dbConn = mysqlDB.connect() for d in nonParkedDomains: mysqlDB.insert_company_domain(dbConn, d) mysqlDB.close_connection(dbConn) if __name__ =="__main__": dryrun = True if dryrun: logger.warning("Testrun! Data does not get persisted!") url = "http://www.safedomain.at/" # chars = ['0-9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u', 'v', 'w', 'x', 'y', 'z'] chars = ['r','s', 't','u', 'v', 'w', 'x', 'y', 'z'] payload = {'sub': 'domains', 'char': '', 'page': '1'} domains = list() cntValidDomains = 0 logger.info("Start collecting domains from \"http://www.safedomain.at\"....") try: for c in chars: payload['char'] = c payload['page'] = '1' response = requests.get(url, params=payload, verify=False) soup = BeautifulSoup(response.text, 'html.parser') while not soup.find_all('a', {'data-pagenumber': True}): time.sleep(5) response = requests.get(url, params=payload, verify=False) soup = BeautifulSoup(response.text, 'html.parser') maxPage = int(soup.find_all('a', {'data-pagenumber': True})[-1].getText()) domains = list() for page in range(1, maxPage + 1): payload['page'] = page logger.debug("Start crawling with following payload: char=%s page=%s", payload['char'], payload['page']) response = requests.get(url, params=payload) soup = BeautifulSoup(response.text, 'html.parser') for elem in soup.find_all('ul', {'class': 'arrow-list'}): for link in elem.find_all('a'): domains.append(link.getText()) logger.info("Finished! Collected domains for %s: %s",c, len(domains)) logger.info("Checking if domains are valid...") with Pool(48) as p: nonParkedDomains = p.map(check_if_valid, domains) p.close() p.join() nonParkedDomains = list(filter(None.__ne__, nonParkedDomains)) cntTemp = cntTemp + len(nonParkedDomains) # check if domains should get persisted if dryrun: logger.info("Valid domains for %s in domains", c) for elem in nonParkedDomains: logger.info(elem) else: persist_domains(nonParkedDomains) logger.info("Finished domain validation for %s!", c) cntValidDomains = cntTemp + cntValidDomains logger.info("Valid domains: %s", cntTemp) logger.info("Program finished!") except Exception as e: logger.exception("Domain collection stopped unexpectedly") </code></pre> <p>EDIT: After some hours debugging and testing I have an idea. Could it be that the requests module, which is used in the thread, causes troubles?</p>
0
2016-09-01T08:47:36Z
39,291,210
<p>After several hours debugging and testing I could fix the problem.</p> <p>Instead of the multiprocessing pool I've used the ThreadPoolExecutor (which is better for network applications)</p> <p>I've figured out that the requests.get() in the threaded function caused some troubles. I changed the timeout to 1.</p> <p>After these changes the program worked.</p> <p>I don't know the exact reason but I would be very interested in it. If someone knows it I would appreciate if he/she could post it.</p>
0
2016-09-02T11:25:37Z
[ "python", "web-crawler", "python-multiprocessing" ]
Multithreaded webserver in Python
39,266,927
<p>An example from a video lecture. Background: the lecturer gave a simplest web server in python. He created a socket, binded it, made listening, accepted a connection, received data, and send it back to the client in uppercase. Then he said that there is a drawback: this web server is single-threaded. Then let's fork.</p> <p>I can't understand the example well enough. But to start with, the program exits (sys.exit()). But I can't run it again: </p> <p><strong>socket.error: [Errno 98] Address already in use.</strong></p> <p>I try to find out which process is listening on port 8080: netstat --listen | grep 8080. Nothing.</p> <p><strong>Well, what is listening on 8080? And how to kill it?</strong></p> <p><strong>Added later:</strong> There is a feeling that if I wait for some time (say, 5-10 minutes), I can run the program again.</p> <pre><code>import os import socket import sys server_socket = socket.socket() server_socket.bind(('', 8080)) server_socket.listen(10) print "Listening" while True: client_socket, remote_address = server_socket.accept() print "PID: {}".format(os.getpid()) child_pid = os.fork() print "child_pid {}".format(child_pid) if child_pid == 0: request = client_socket.recv(1024) client_socket.send(request.upper()) print '(child {}): {}'.format(client_socket.getpeername(), request) client_socket.close() sys.exit() else: client_socket.close() server_socket.close() </code></pre>
0
2016-09-01T08:52:32Z
39,268,473
<p>The correct netstat usage is:</p> <pre><code>netstat -tanp </code></pre> <p>because you need the <code>-a</code> option to display listening sockets. Add grep to locate your program quickly:</p> <pre><code>netstat -tanp| grep 8080 </code></pre>
0
2016-09-01T10:00:41Z
[ "python", "multithreading", "webserver" ]
How can I use integer that I supply into tf.placeholder(tf.int32)?
39,266,944
<p>I need to initialize a dynamic list which has length given by an integer that I will put into a placeholder through feed_dict. </p> <p>I set up the graph through this code: </p> <pre><code>num_placeholder = tf.placeholder(tf.int32) input_data = list() for _ in range(num_placeholder): input_data.append(1) </code></pre> <p>But get the following error: <code>'Tensor' object cannot be interpreted as an integer</code></p> <p>How can I use the <code>int</code> that I put into the <code>num_placeholder</code>? </p>
0
2016-09-01T08:53:22Z
39,272,841
<p><code>num_placeholder</code> is a <code>Tensor</code> object, it can not be directly used as an <code>int</code>, it must be valuated first. See documentation on <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#placeholder" rel="nofollow"><code>placeholder</code></a> method.</p> <p>If you want to use <code>num_placeholder</code> object as <code>int</code> you must evaluate it as follows:</p> <pre><code># create a placeholder num_placeholder = tf.placeholder(tf.int32) # create an identity operation # because same Tensor can not be both fed and fetched num_op = tf.identity(num_placeholder) with tf.Session() as sess: # feed value to placeholder and fetch it num = sess.run([num_op], feed_dict={num_placeholder: 5}) </code></pre> <p>Now <code>num</code> will is a list <code>[5]</code> and you can use <code>num[0]</code> in your loop. I am not quite sure what you are trying to achieve, but if your goal is to create a vector of ones of some custom length that is fed during runtime, here is how it can be solved by means of Tensorflow:</p> <pre><code>num_placeholder = tf.placeholder(tf.int32) ones_op = tf.ones(shape=[num_placeholder], dtype=tf.int32) with tf.Session() as sess: ones = sess.run([ones_op], feed_dict={num_placeholder: 5}) </code></pre> <p><code>ones ==&gt; &lt;type 'list'&gt;: [array([1, 1, 1, 1, 1], dtype=int32)]</code>, see <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/constant_op.html#ones" rel="nofollow"><code>ones</code></a> </p>
1
2016-09-01T13:27:23Z
[ "python", "machine-learning", "tensorflow" ]
Python class inheritance - how to use this to connect to a mysql database
39,267,056
<p>I am using python 2.7 and I have written a set of python classes in order to upload data to my database. However I am not sure I am completely understanding how to use inheritance from class to class. What I have is a User and Database class - which searches for the users/ databases from a list:</p> <pre><code>class User(object): user_lst = ['user1', 'user2', 'user3'] def __init__(self, username): self.username = username def find_user(self): if self.username not in self.user_lst: print('User not found, script will exit') exit() else: pass class Database(object): db_lst = ['db1', 'db2', 'db3'] def __init__(self, database): self.database = database def find_db(self): if self.database not in self.user_lst: print('Database not found, script will exit') exit() else: pass </code></pre> <p>I get my values for user and database using raw_input() which returns:</p> <pre><code>un = 'user1' db = 'db1' </code></pre> <p>To instantiate these classes as I understand it, I need to pass these values through the class, at which time I can also call the methods -</p> <pre><code>User(un).find_user() Database(db).find_db() </code></pre> <p>I now want to use a third class to inherit these values in order to connect to the database:</p> <pre><code>class DatabaseConnect(User, Database): def __init__(self): User.__init__(self, username) Database.__init__(self, database) def connect(self, pw): try: connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1) cursor = connect.cursor() print('Connected to '+self.database) except: print('Did not connect to database') exit() </code></pre> <p>I then try and connect using:</p> <pre><code>DatabaseConnect().connect('password1') </code></pre> <p>However this doesn't work. I have tried to add to my DatabaseConnect class <strong>init</strong> function:</p> <pre><code>def __init__(self, username, database): User.__init__(self, username) Database.__init__(self, database) </code></pre> <p>I have also played around with creating object variables from these classes such as:</p> <pre><code>user_obj = User(un) user_obj.find_user() db_obj = Database(db) db_obj.find_user() </code></pre> <p>Do I need to create these object variables and then pass them through my DatabaseConnection class - if so do I even need to inherit? This is why I am confused. Say I use these object variables and use this class:</p> <pre><code>class DatabaseConnect(User, Database): def __init__(self, username, database): self.username = User.username self.database = Database.database def connect(self, pw): try: connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1) cursor = connect.cursor() print('Connected to '+self.database) except: print('Did not connect to database') exit() </code></pre> <p>and then I instantiate it using:</p> <pre><code>db_connect = DatabaseConnect(user_obj, db_obj) </code></pre> <p>How is this any different from simply using the variables themselves:</p> <pre><code>db_connect = DatabaseConnect(un, db) </code></pre> <p>and why do i have to use:</p> <pre><code>self.username = User.username </code></pre> <p>instead of simply:</p> <pre><code>self.username = username </code></pre> <p>I am struggling to get my head around this concept so any head would be appreciated. Thanks</p>
1
2016-09-01T08:58:48Z
39,267,256
<p>If you are inheriting you dont need to create a User and Database instance. You can just create a DatabaseConnect object:</p> <pre><code>class DatabaseConnect(User, Database): def __init__(self, username, database): User.__init__(self, username) Database.__init__(self, database) def connect(self, pw): try: connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1) cursor = connect.cursor() print('Connected to '+self.database) except: print('Did not connect to database') exit() dbConnect = new DatabaseConnect("username", "database") dbConnect.find_db() Database not found, script will exit dbConnect.find_user() User not found, script will exit </code></pre>
1
2016-09-01T09:06:56Z
[ "python", "mysql", "python-2.7", "class", "inheritance" ]
Python class inheritance - how to use this to connect to a mysql database
39,267,056
<p>I am using python 2.7 and I have written a set of python classes in order to upload data to my database. However I am not sure I am completely understanding how to use inheritance from class to class. What I have is a User and Database class - which searches for the users/ databases from a list:</p> <pre><code>class User(object): user_lst = ['user1', 'user2', 'user3'] def __init__(self, username): self.username = username def find_user(self): if self.username not in self.user_lst: print('User not found, script will exit') exit() else: pass class Database(object): db_lst = ['db1', 'db2', 'db3'] def __init__(self, database): self.database = database def find_db(self): if self.database not in self.user_lst: print('Database not found, script will exit') exit() else: pass </code></pre> <p>I get my values for user and database using raw_input() which returns:</p> <pre><code>un = 'user1' db = 'db1' </code></pre> <p>To instantiate these classes as I understand it, I need to pass these values through the class, at which time I can also call the methods -</p> <pre><code>User(un).find_user() Database(db).find_db() </code></pre> <p>I now want to use a third class to inherit these values in order to connect to the database:</p> <pre><code>class DatabaseConnect(User, Database): def __init__(self): User.__init__(self, username) Database.__init__(self, database) def connect(self, pw): try: connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1) cursor = connect.cursor() print('Connected to '+self.database) except: print('Did not connect to database') exit() </code></pre> <p>I then try and connect using:</p> <pre><code>DatabaseConnect().connect('password1') </code></pre> <p>However this doesn't work. I have tried to add to my DatabaseConnect class <strong>init</strong> function:</p> <pre><code>def __init__(self, username, database): User.__init__(self, username) Database.__init__(self, database) </code></pre> <p>I have also played around with creating object variables from these classes such as:</p> <pre><code>user_obj = User(un) user_obj.find_user() db_obj = Database(db) db_obj.find_user() </code></pre> <p>Do I need to create these object variables and then pass them through my DatabaseConnection class - if so do I even need to inherit? This is why I am confused. Say I use these object variables and use this class:</p> <pre><code>class DatabaseConnect(User, Database): def __init__(self, username, database): self.username = User.username self.database = Database.database def connect(self, pw): try: connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1) cursor = connect.cursor() print('Connected to '+self.database) except: print('Did not connect to database') exit() </code></pre> <p>and then I instantiate it using:</p> <pre><code>db_connect = DatabaseConnect(user_obj, db_obj) </code></pre> <p>How is this any different from simply using the variables themselves:</p> <pre><code>db_connect = DatabaseConnect(un, db) </code></pre> <p>and why do i have to use:</p> <pre><code>self.username = User.username </code></pre> <p>instead of simply:</p> <pre><code>self.username = username </code></pre> <p>I am struggling to get my head around this concept so any head would be appreciated. Thanks</p>
1
2016-09-01T08:58:48Z
39,267,266
<p>By doing:</p> <pre><code>def __init__(self, username, database): self.username = User.username self.database = Database.database </code></pre> <p>you are not properly initialising the <code>User</code> and <code>Database</code> instances. You need to call their <code>__init__</code> function. There are several ways to do so e.g.:</p> <pre><code>def __init__(self, username, database): User.__init__(self, username) Database.__init__(self, database) </code></pre> <p>after doing so you can use <code>self.username</code>, etc</p>
0
2016-09-01T09:07:14Z
[ "python", "mysql", "python-2.7", "class", "inheritance" ]
Pandas - Multiindex Division [i.e. Division by Group]
39,267,126
<p><strong>Aim:</strong> I'm trying to divide each row in a multilevel index by the total number in each group.</p> <p><strong>More specifically:</strong> Given the following data, I want to divide the number of Red and Blue marbles by the total number in each group (i.e. the sum across Date, Country and Colour) </p> <pre><code> Number Date Country Colour 2011 US Red 4 Blue 6 2012 IN Red 9 IE Red 5 Blue 5 2013 JP Red 15 Blue 25 </code></pre> <p>This would give the following answer:</p> <pre><code> Number Date Country Colour 2011 US Red 0.4 Blue 0.6 2012 IN Red 1.0 IE Red 0.5 Blue 0.5 2013 JP Red 0.375 Blue 0.625 </code></pre> <p>Here is the code to reproduce the data:</p> <pre><code>arrays = [np.array(['2011', '2011', '2012', '2012', '2012', '2013', '2013']), np.array(['US', 'US', 'IN', 'IE', 'IE', 'JP', 'JP', 'GB']), np.array(['Red', 'Blue', 'Red', 'Red', 'Blue', 'Red', 'Blue', 'Blue'])] df = pd.DataFrame(np.random.rand(7, 1)*10, index=arrays, columns=['number']) df.index.names = ['Date', 'Country', 'Colour'] </code></pre>
1
2016-09-01T09:01:15Z
39,269,086
<p>A shorter version would be:</p> <pre><code>df.groupby(level=['Date', 'Country']).transform(lambda x: x/x.sum()) number Date Country Colour 2011 US Red 0.400 Blue 0.600 2012 IN Red 1.000 IE Red 0.500 Blue 0.500 2013 JP Red 0.375 Blue 0.625 </code></pre>
2
2016-09-01T10:27:50Z
[ "python", "pandas" ]
Can't upload any data to bigquery using table.insertall()
39,267,210
<p>This is the portion of my code that I'm having issues with.</p> <pre><code>table_data_insert_all_request_body = { "kind": "bigquery#tableDataInsertAllRequest", "skipInvalidRows": True, "ignoreUnknownValues": True, "templateSuffix": 'suffix', "rows": [ { "json": { ("one"): ("two"), ("three"): ("four") } } ] } request = service.tabledata().insertAll(projectId=projectId, datasetId=datasetId, tableId=tableId, body=table_data_insert_all_request_body) response = request.execute() </code></pre> <p>If I print response, I get the response:</p> <pre><code>{u'kind': u'bigquery#tableDataInsertAllResponse'} </code></pre> <p>I can assess the project, dataset and even the table but I cant update the values in the table. What do I need to do differently? Obviously I don't want to enter two values but I cant get anything to upload. Once I can get something to upload I'll be able to get rows working.</p>
0
2016-09-01T09:05:19Z
39,290,878
<p>Even though its tough to tell without looking at your schema, I am pretty sure your json data is not correct. Here is what I use.</p> <pre><code>Bodyfields = { "kind": "bigquery#tableDataInsertAllRequest", "rows": [ { "json": { 'col_name_1': 'row 1 value 1', 'col_name_2': 'row 1 value 2' } }, { "json": { 'col_name_1': 'row 2 value 1', 'col_name_2': 'row 2 value 2' } } ] } </code></pre>
1
2016-09-02T11:04:58Z
[ "python", "json", "python-2.7", "google-bigquery" ]
How to split a string in python based on dots, ignoring decimal values?
39,267,292
<p>I have the following string:</p> <blockquote> <p>s = 'This .is sparta 1.2 version. Please check.'</p> </blockquote> <p>I want to split it based on dots, while ignoring decimal figures. So, Required Output :</p> <blockquote> <p>['This ','is sparta 1.2 version','Please check']</p> </blockquote> <p>I tried following:</p> <pre><code> re.split(r'\.(?!([\d+\.\d+]))',s) </code></pre> <p>The output I am getting is:</p> <blockquote> <p>['This ', None, 'is sparta 1.2 version', '', ' Please check', None, '']</p> </blockquote> <p>Why am I getting None and empty strings here? I just want the split strings, ie.</p> <blockquote> <p>['This ','is sparta 1.2 version','Please check']</p> </blockquote> <p>Please suggest the rectification here.</p>
1
2016-09-01T09:08:27Z
39,267,366
<p>Try splitting on</p> <pre><code>(?&lt;!\d)\.(?!\d) </code></pre> <p>It makes sure the dot isn't preceded, nor followed, by a digit.</p> <p><a href="https://regex101.com/r/iA0xQ2/1" rel="nofollow">See it here at regex101</a>.</p>
4
2016-09-01T09:11:29Z
[ "python", "regex" ]
How to split a string in python based on dots, ignoring decimal values?
39,267,292
<p>I have the following string:</p> <blockquote> <p>s = 'This .is sparta 1.2 version. Please check.'</p> </blockquote> <p>I want to split it based on dots, while ignoring decimal figures. So, Required Output :</p> <blockquote> <p>['This ','is sparta 1.2 version','Please check']</p> </blockquote> <p>I tried following:</p> <pre><code> re.split(r'\.(?!([\d+\.\d+]))',s) </code></pre> <p>The output I am getting is:</p> <blockquote> <p>['This ', None, 'is sparta 1.2 version', '', ' Please check', None, '']</p> </blockquote> <p>Why am I getting None and empty strings here? I just want the split strings, ie.</p> <blockquote> <p>['This ','is sparta 1.2 version','Please check']</p> </blockquote> <p>Please suggest the rectification here.</p>
1
2016-09-01T09:08:27Z
39,267,476
<p>Since almost have what you want, you could parse the current output to remove Nones and empty strings.</p> <p>This can be done in one line using list comprehension:</p> <pre><code>FilteredList = [ itm for itm in UnfilteredList if itm is not None and len(itm)&gt;0] </code></pre>
0
2016-09-01T09:16:15Z
[ "python", "regex" ]
Replace rows in a Pandas df with rows from another df
39,267,372
<p>I have 2 Pandas dfs, A and B. Both have 10 columns and the index 'ID'. Where the IDs of A and B match, I want to replace the rows of B with the rows of A. I have tried to use pd.update, but no success yet. Any help appreciated.</p>
0
2016-09-01T09:11:45Z
39,272,096
<p>below code should do the trick</p> <pre><code>s1 = pd.Series([5, 1, 'a']) s2 = pd.Series([6, 2, 'b']) s3 = pd.Series([7, 3, 'd']) s4 = pd.Series([8, 4, 'e']) s5 = pd.Series([9, 5, 'f']) df1 = pd.DataFrame([list(s1), list(s2),list(s3),list(s4),list(s5)], columns = ["A", "B", "C"]) s1 = pd.Series([5, 6, 'p']) s2 = pd.Series([6, 7, 'q']) s3 = pd.Series([7, 8, 'r']) s4 = pd.Series([8, 9, 's']) s5 = pd.Series([9, 10, 't']) df2 = pd.DataFrame([list(s1), list(s2),list(s3),list(s4),list(s5)], columns = ["A", "B", "C"]) df1.loc[df1.A.isin(df2.A), ['B', 'C']] = df2[['B', 'C']] print df1 </code></pre> <p>output </p> <pre><code> A B C 0 5 6 p 1 6 7 q 2 7 8 r 3 8 9 s 4 9 10 t </code></pre>
0
2016-09-01T12:53:08Z
[ "python", "pandas", "dataframe" ]
How to work with Django inline forms?
39,267,386
<p>I have two models (Receipt and Ingredient) and want to create ingredients when creating receipt.</p> <p><strong>forms.py</strong></p> <pre><code>from django import forms from django.forms import ModelForm from django.forms.models import inlineformset_factory from .models import Receipt, Ingredient, CookingStep class ReceiptForm(forms.ModelForm): class Meta: model = Receipt fields = ('name', 'description', 'hour', 'minute', 'multivarka',) ReceiptFormSet = inlineformset_factory(Receipt, Ingredient, fields=('name', 'count', 'value')) </code></pre> <p><strong>models.py</strong></p> <pre><code>from django.db import models class Receipt(models.Model): name = models.CharField(max_length=255) description = models.TextField(max_length=1024) hour = models.IntegerField(default=0) minute = models.IntegerField(default=1) multivarka = models.BooleanField(default=False) def __str__(self): return "%s" % (self.name) class Ingredient(models.Model): name = models.CharField(max_length=255) count = models.IntegerField(default=0) #200gr, 1kg etc value = models.CharField(max_length=255) #gramm, kg etc receipts = models.ForeignKey(Receipt) def __str__(self): return "%s" % (self.name) </code></pre> <p><strong>views.py</strong></p> <pre><code>def receipt_new(request): if request.method == "POST": formset = ReceiptForm(request.POST) if formset.is_valid(): created_receipt = formset.save(commit=False) new_formset = ReceiptFormSet(request.POST, instance=created_receipt) if new_formset.is_valid(): created_receipt.save() new_formset.save() return redirect('/receipts') else: formset = ReceiptForm() inline_form = ReceiptFormSet() return render(request, 'admin_site/receipt_edit.html', {'formset': formset}) </code></pre> <p><strong>receipt_edit.html</strong></p> <pre><code>{% block content %} &lt;h1&gt;New receipt&lt;/h1&gt; &lt;form method="POST" class="post-form"&gt;{% csrf_token %} {{ formset.as_p }} &lt;button type="submit" class="save btn btn-default"&gt;Save&lt;/button&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>Now only form for creating receipt is displayed. I want to have two forms on edit page: firstly form for receipt and then form for creating ingredient for this receipt (on one page).</p>
0
2016-09-01T09:12:21Z
39,268,006
<p>Firstly, use some consistent names for your variables. Your <code>ReceiptForm</code> instance is a form, not a formset, so call it <code>form</code>. Let's call your <code>ReceiptFormSet</code> instance <code>formset</code> everywhere.</p> <p>Next, you need to include your form and formset in the template context when you call <code>render</code>.</p> <pre><code>def receipt_new(request): if request.method == "POST": form = ReceiptForm(request.POST) if form.is_valid(): created_receipt = form.save(commit=False) formset = ReceiptFormSet(request.POST, instance=created_receipt) if formset.is_valid(): created_receipt.save() formset.save() return redirect('/receipts') else: form = ReceiptForm() formset = ReceiptFormSet(instance=Receipt()) return render(request, 'admin_site/receipt_edit.html', {'form': form, 'formset': formset}) </code></pre> <p>Finally, you need to include your form and formset in the template.</p> <pre><code>&lt;form method="POST" class="post-form"&gt;{% csrf_token %} {{ form }} {{ formset }} &lt;button type="submit" class="save btn btn-default"&gt;Save&lt;/button&gt; &lt;/form&gt; </code></pre>
0
2016-09-01T09:40:25Z
[ "python", "django" ]
Advanced mailto use in Python
39,267,464
<p>I'm trying to send an email with custom recipient, subject and body in Python. This means I don't want to use <a href="http://stackoverflow.com/questions/6270782/how-to-send-an-email-with-python">Python's smtp packages</a>, but something like <a href="https://docs.python.org/2.7/library/webbrowser.html?highlight=webbrowser#module-webbrowser" rel="nofollow">webbrowser</a> because I need this to open the default email client (Thunderbird in my case) with said arguments. </p> <pre><code>import webbrowser webbrowser.open("mailto:?to=aaa@email.com&amp;subject=mysubject", new=1) </code></pre> <p>works but I need it to get the recipient from a string I previously found and body from a text file I previously created.</p> <p>Is there any "simple" way to do it that I cannot find? Thanks in advance.</p>
1
2016-09-01T09:15:40Z
39,268,665
<p>Use string concatenation.</p> <pre><code>recipient = 'aaa@email.com' subject = 'mysubject' body = 'This is a message' webbrowser.open("mailto:?to='+ recipient + '&amp;subject=' + subject + "&amp;body=" + body, new=1) </code></pre>
0
2016-09-01T10:09:10Z
[ "python", "python-2.7", "email", "python-webbrowser" ]
Advanced mailto use in Python
39,267,464
<p>I'm trying to send an email with custom recipient, subject and body in Python. This means I don't want to use <a href="http://stackoverflow.com/questions/6270782/how-to-send-an-email-with-python">Python's smtp packages</a>, but something like <a href="https://docs.python.org/2.7/library/webbrowser.html?highlight=webbrowser#module-webbrowser" rel="nofollow">webbrowser</a> because I need this to open the default email client (Thunderbird in my case) with said arguments. </p> <pre><code>import webbrowser webbrowser.open("mailto:?to=aaa@email.com&amp;subject=mysubject", new=1) </code></pre> <p>works but I need it to get the recipient from a string I previously found and body from a text file I previously created.</p> <p>Is there any "simple" way to do it that I cannot find? Thanks in advance.</p>
1
2016-09-01T09:15:40Z
39,269,802
<p>I use the variables <strong>recipient</strong> and <strong>subject</strong> to store the relative values. Simply replace the example text between single quotes with your real value.</p> <pre><code>recipient = 'emailaddress' subject = 'mysubject' </code></pre> <p>The subject field can't contain white spaces, so they have to be url encoded using %20 ASCII code</p> <pre><code>subject = subject.replace(' ', '%20') </code></pre> <p>the function above replaces the white space with "%20" and assigns the modified subject to the same variable since you can reuse it, you really don't need another one in this case.</p> <p>It's possible to use also the <strong>urllib</strong> module for url encoding (see <strong>urllib.urlencode()</strong> method), but it can be done simply using the <strong>replace()</strong> method so you can avoid importing another module just for that.</p> <p>Now you need to load the text from a text file and store it in a variable. Imagine you have a text file called <strong>body.txt</strong>:</p> <pre><code>with open('body.txt', 'r') as b: body = b.read() </code></pre> <p>Note that I assumed <strong>body.txt</strong> is in the same directory of your Python script, otherwise in the filename parameter you have to include the full absolute or relative path to the file, followed by the file name.</p> <p>I used the <strong>open()</strong> function and I provide 2 parameters: the first one is the <strong>filename</strong>, the second one is the <strong>mode</strong> you want to open the file with. You want to read the file so you have to open it in <strong>read mode</strong> (<strong>'r'</strong>). Once you open the file you need to be able to identify the file with a variable in order to perform some operations on it. This kind of variable is technically called <strong>handle</strong>, in this case I called it <strong>b</strong>.</p> <p>Now for reading ALL the text you can use <strong>b.read()</strong> and then you can assign it to the variable <strong>body</strong>. (If you wanted to read it line by line, you would have done: <strong>b.readline()</strong> but you don't want this in this case.)</p> <p>Note that I used the <strong>with</strong> statement, this is the preferred way for opening and working with files, because it will automatically close the file at the end, else you would have to do it manually. Before <strong>with</strong> was available you would have to do something like this:</p> <pre><code>b = open('body.txt', 'r'): body = b.read() b.close() </code></pre> <p>Now it's better to url encode also the string contained in the variable <strong>body</strong>, so we do the same thing we did for the <strong>subject</strong>:</p> <pre><code>body = body.replace(' ', '%20') </code></pre> <p>Now it's time to use the <strong>webbrowser</strong> module and provide the data you got so far as parameter, concatenating the strings.</p> <pre><code>webbrowser.open('mailto:?to=' + recipient + '&amp;subject=' + subject + '&amp;body=' + body, new=1) </code></pre> <p>Obviously you also need to import the <strong>webbrowser</strong> module before using it. I'll rewrite the whole program without comments for clarity:</p> <pre><code>import webbrowser recipient = 'emailaddress' subject = 'mysubject' with open('body.txt', 'r') as b: body = b.read() body = body.replace(' ', '%20') webbrowser.open('mailto:?to=' + recipient + '&amp;subject=' + subject + '&amp;body=' + body, new=1) </code></pre>
1
2016-09-01T11:02:22Z
[ "python", "python-2.7", "email", "python-webbrowser" ]
Comparing list of tuples within dictionary
39,267,495
<p>I have been cracking my head over this problem... I have a simplified dataset like such:<br> <code>dict = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'B': [('b', 2, 2), ('a', 1, 1)], 'C': [('d', 4, 4)], 'D': [('c', 3, 3), ('e', 5, 5)]}</code><br> where the value represents a list of tuples. </p> <p>I need to find for each value in the dictionary, are the list elements found in that of another value? If yes, the keyvalue pair should be removed from the dictionary. For example, [('b', 2, 2), ('a', 1, 1)] is found in [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], so the keyvalue pair for 'B' should be removed. The final dictionary should look like: </p> <pre><code>dict = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'C': [('d', 4, 4)], 'D': [('c', 3, 3), ('e', 5, 5)]} </code></pre> <p>I have searched the forums but have not found a solution to this problem... Would greatly appreciate any help with this! Thank you! </p> <h2>Edit:</h2> <p>This dictionary does not contain duplicate values as I have previously removed them through mapping to another dictionary based on another set of conditions. However it may be useful to others if the solution can be extended to duplicates as well, for example keeping 1 out of all duplicates.<br> PS: Thanks for all the responses!</p>
0
2016-09-01T09:17:29Z
39,267,957
<p>You can use <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">sets</a> to check whether one value is contained (<code>set.issubset(otherset)</code>) within one another. The below code demonstrates how you could implement this very easily. For each value every other value is checked for inclusion. This can definitly be optimized.</p> <pre><code># input data d = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'B': [('b', 2, 2), ('a', 1, 1)], 'C': [('d', 4, 4)]} # convert each value to a set ds = { k: frozenset(v) for k,v in d.items() } # filter out contained values keys = [ k1 for k1,v1 in ds.items() if [k2 for k2,v2 in ds.items() if v1.issubset(v2)] == [k1] ] # map filtered keys to original dict df = dict(zip(keys, map(d.get, keys))) # df = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'C': [('d', 4, 4)]} </code></pre> <h3>Explanation</h3> <p>When calculating <code>keys</code> for each pair <code>(k1,v1)</code> the following is done. All other pairs <code>(k2,v2)</code> (including <code>(k1,v1)</code>) are checked for <code>v1.issubset(v2)</code>. For all pairs satisfying this condition, the key (<code>k2</code>) is recorded and stored in a list. If no <em>other</em> value does include our given value <code>v1</code> this list will only contain <code>k1</code>, as the <code>issubset</code>relation is reflexive (<code>v.issubset(v)</code> is always <code>True</code>). Thus, when the returned list is exactly <code>[k1]</code>, we are fine. If the list contains more values than <code>k1</code>, <code>v1</code> is contained in some other value and have to be filtered.</p> <h3>Duplicate values</h3> <p>The problem is not defined for duplicate values in the map. My solution keeps track of the original keys, thus for duplicate values both pairs are dropped. You can also introduce custom behavior here, like only keeping the pair with the 'smallest' key for all duplicates.</p> <p>Other solutions keep all pairs, thus the returned mapping still contains duplicate values.</p> <p>This modified version of <code>keys</code> can handle the case mentioned above:</p> <pre><code>keys = [ k1 for k1,v1 in ds.items() if not any(v1 &lt; v2 for v2 in ds.values()) and k1 == min(k2 for k2,v2 in ds.items() if v1 == v2) ] </code></pre>
0
2016-09-01T09:38:12Z
[ "python", "dictionary" ]
Comparing list of tuples within dictionary
39,267,495
<p>I have been cracking my head over this problem... I have a simplified dataset like such:<br> <code>dict = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'B': [('b', 2, 2), ('a', 1, 1)], 'C': [('d', 4, 4)], 'D': [('c', 3, 3), ('e', 5, 5)]}</code><br> where the value represents a list of tuples. </p> <p>I need to find for each value in the dictionary, are the list elements found in that of another value? If yes, the keyvalue pair should be removed from the dictionary. For example, [('b', 2, 2), ('a', 1, 1)] is found in [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], so the keyvalue pair for 'B' should be removed. The final dictionary should look like: </p> <pre><code>dict = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'C': [('d', 4, 4)], 'D': [('c', 3, 3), ('e', 5, 5)]} </code></pre> <p>I have searched the forums but have not found a solution to this problem... Would greatly appreciate any help with this! Thank you! </p> <h2>Edit:</h2> <p>This dictionary does not contain duplicate values as I have previously removed them through mapping to another dictionary based on another set of conditions. However it may be useful to others if the solution can be extended to duplicates as well, for example keeping 1 out of all duplicates.<br> PS: Thanks for all the responses!</p>
0
2016-09-01T09:17:29Z
39,268,173
<p>You could convert the values to set of frozensets, then filter out the duplicates and finally pick the dictionary items whose value is in the set:</p> <pre><code>d = { 'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'B': [('b', 2, 2), ('a', 1, 1)], 'C': [('d', 4, 4)] } sets = {frozenset(v) for v in d.values()} sets = {s for s in sets if not any(s &lt; s2 for s2 in sets)} res = {k: v for k, v in d.items() if set(v) in sets} # {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'C': [('d', 4, 4)]} </code></pre>
0
2016-09-01T09:47:41Z
[ "python", "dictionary" ]
Comparing list of tuples within dictionary
39,267,495
<p>I have been cracking my head over this problem... I have a simplified dataset like such:<br> <code>dict = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'B': [('b', 2, 2), ('a', 1, 1)], 'C': [('d', 4, 4)], 'D': [('c', 3, 3), ('e', 5, 5)]}</code><br> where the value represents a list of tuples. </p> <p>I need to find for each value in the dictionary, are the list elements found in that of another value? If yes, the keyvalue pair should be removed from the dictionary. For example, [('b', 2, 2), ('a', 1, 1)] is found in [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], so the keyvalue pair for 'B' should be removed. The final dictionary should look like: </p> <pre><code>dict = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'C': [('d', 4, 4)], 'D': [('c', 3, 3), ('e', 5, 5)]} </code></pre> <p>I have searched the forums but have not found a solution to this problem... Would greatly appreciate any help with this! Thank you! </p> <h2>Edit:</h2> <p>This dictionary does not contain duplicate values as I have previously removed them through mapping to another dictionary based on another set of conditions. However it may be useful to others if the solution can be extended to duplicates as well, for example keeping 1 out of all duplicates.<br> PS: Thanks for all the responses!</p>
0
2016-09-01T09:17:29Z
39,268,439
<p>Use <code>set</code> and <code>combinations</code>:</p> <pre><code>from itertools import combinations d = {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'B': [('b', 2, 2), ('a', 1, 1)], 'C': [('d', 4, 4)]} xs = set() for (ai, av), (bi, bv) in combinations(d.items(), 2): if set(av) &lt;= set(bv): xs.add(ai) if set(bv) &lt;= set(av): xs.add(bi) for x in xs: del d[x] print d # {'A': [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)], 'C': [('d', 4, 4)]} </code></pre>
0
2016-09-01T09:59:36Z
[ "python", "dictionary" ]
Filter list of dicts by highest value of dict and taking reversed values into account
39,267,554
<p>Let's say i have data looking like this:</p> <pre><code>filter_data = [ {'sender_id': 1, 'receiver_id': 2, 'order': 1}, {'sender_id': 2, 'receiver_id': 1, 'order': 3}, {'sender_id': 3, 'receiver_id': 2, 'order': 5}, {'sender_id': 2, 'receiver_id': 3, 'order': 2}, ] # there must be a better way to get max elements by reversed keys # in list of dicts, but I think this whole another question # so for now let this be this way. def get_data(): qs_data = [] for data in filter_data: for cmp_data in filter_data: if data['sender_id'] == cmp_data['receiver_id'] and\ data['receiver_id'] == cmp_data['sender_id']: if data['order'] &gt; cmp_data['order']: d = data else: d = cmp_data if d not in qs_data: qs_data.append(d) return qs_data </code></pre> <p>and desired output will be</p> <pre><code>[{'order': 3, 'receiver_id': 1, 'sender_id': 2}, {'order': 5, 'receiver_id': 2, 'sender_id': 3}] </code></pre> <p>What my code does it filters <code>filter_data</code> so I will get list of items with highest value of <code>order</code> for <code>sender_id</code> and <code>receiver_id</code> but for me <code>receiver_id=1, sender_id=2</code> is same as <code>sender_id=1, receiver_id=2</code></p> <p>So my question is is there more pythonic/faster way to do this? Or may be can someone point to direction of improvement.</p> <p><strong>P.S.</strong> I would much appreciate if someone can come up with understandable title. Sorry for my bad English.</p>
1
2016-09-01T09:19:41Z
39,267,938
<p>You can use a dictionary, mapping a <code>frozenset</code> of sender and receiver ID (so order does not matter) to the item with the currently highest order.</p> <pre><code>result = {} for item in filter_data: key = frozenset([item["sender_id"], item["receiver_id"]]) if key not in result or result[key]["order"] &lt; item["order"]: result[key] = item </code></pre> <p>Then, just extract the <code>values()</code> from the dictionary to get <code>[{'order': 3, 'receiver_id': 1, 'sender_id': 2}, {'order': 5, 'receiver_id': 2, 'sender_id': 3}]</code></p> <p>Or collect all the items, grouped by sender/receiver pair, and use a list comprehension with <code>max</code> to get those with the highest orders:</p> <pre><code>result = collections.defaultdict(list) for item in filter_data: key = frozenset([item["sender_id"], item["receiver_id"]]) result[key].append(item) max_values = [max(lst, key=lambda x: x["order"]) for lst in result.values()] </code></pre>
1
2016-09-01T09:37:07Z
[ "python" ]
Filter list of dicts by highest value of dict and taking reversed values into account
39,267,554
<p>Let's say i have data looking like this:</p> <pre><code>filter_data = [ {'sender_id': 1, 'receiver_id': 2, 'order': 1}, {'sender_id': 2, 'receiver_id': 1, 'order': 3}, {'sender_id': 3, 'receiver_id': 2, 'order': 5}, {'sender_id': 2, 'receiver_id': 3, 'order': 2}, ] # there must be a better way to get max elements by reversed keys # in list of dicts, but I think this whole another question # so for now let this be this way. def get_data(): qs_data = [] for data in filter_data: for cmp_data in filter_data: if data['sender_id'] == cmp_data['receiver_id'] and\ data['receiver_id'] == cmp_data['sender_id']: if data['order'] &gt; cmp_data['order']: d = data else: d = cmp_data if d not in qs_data: qs_data.append(d) return qs_data </code></pre> <p>and desired output will be</p> <pre><code>[{'order': 3, 'receiver_id': 1, 'sender_id': 2}, {'order': 5, 'receiver_id': 2, 'sender_id': 3}] </code></pre> <p>What my code does it filters <code>filter_data</code> so I will get list of items with highest value of <code>order</code> for <code>sender_id</code> and <code>receiver_id</code> but for me <code>receiver_id=1, sender_id=2</code> is same as <code>sender_id=1, receiver_id=2</code></p> <p>So my question is is there more pythonic/faster way to do this? Or may be can someone point to direction of improvement.</p> <p><strong>P.S.</strong> I would much appreciate if someone can come up with understandable title. Sorry for my bad English.</p>
1
2016-09-01T09:19:41Z
39,268,111
<p>Create an empty dictionary that will gather the new highest dictionary. We iterate through your <code>filter_data</code> and check the sum of <code>sender_id</code> and <code>receiver_id</code>, since you said that the order of those was irrelevant.</p> <pre><code>filter_data = [ {'sender_id': 1, 'receiver_id': 2, 'order': 1}, {'sender_id': 2, 'receiver_id': 1, 'order': 3}, {'sender_id': 3, 'receiver_id': 2, 'order': 5}, {'sender_id': 2, 'receiver_id': 3, 'order': 2}, ] new = {} for d in filter_data: total = d['sender_id'] + d['receiver_id'] if total in new: if d['order'] &gt; new[total]['order']: new[total] = d else: new[total] = d print new.values() </code></pre> <p>For example, it will go through the first dictionary and evaluate the sum of its <code>receiver_id</code> and <code>sender_id</code> (The sum is 3). Since we have not encountered a dictionary that has <code>sender_id</code> and <code>receiver_id</code> adding up to 3 yet, it is added to our new dictionary. </p> <p>However, the next dictionary also has a sum of 3. We check to see if its <code>order</code> value is greater than the previous dictionary. Since it is, it overrides that former dictionary.</p> <p>Then we print the values of our new dictionary since the keys only contain the sum of <code>sender_id</code> and <code>receiver_id</code>.</p>
0
2016-09-01T09:44:55Z
[ "python" ]
Filter list of dicts by highest value of dict and taking reversed values into account
39,267,554
<p>Let's say i have data looking like this:</p> <pre><code>filter_data = [ {'sender_id': 1, 'receiver_id': 2, 'order': 1}, {'sender_id': 2, 'receiver_id': 1, 'order': 3}, {'sender_id': 3, 'receiver_id': 2, 'order': 5}, {'sender_id': 2, 'receiver_id': 3, 'order': 2}, ] # there must be a better way to get max elements by reversed keys # in list of dicts, but I think this whole another question # so for now let this be this way. def get_data(): qs_data = [] for data in filter_data: for cmp_data in filter_data: if data['sender_id'] == cmp_data['receiver_id'] and\ data['receiver_id'] == cmp_data['sender_id']: if data['order'] &gt; cmp_data['order']: d = data else: d = cmp_data if d not in qs_data: qs_data.append(d) return qs_data </code></pre> <p>and desired output will be</p> <pre><code>[{'order': 3, 'receiver_id': 1, 'sender_id': 2}, {'order': 5, 'receiver_id': 2, 'sender_id': 3}] </code></pre> <p>What my code does it filters <code>filter_data</code> so I will get list of items with highest value of <code>order</code> for <code>sender_id</code> and <code>receiver_id</code> but for me <code>receiver_id=1, sender_id=2</code> is same as <code>sender_id=1, receiver_id=2</code></p> <p>So my question is is there more pythonic/faster way to do this? Or may be can someone point to direction of improvement.</p> <p><strong>P.S.</strong> I would much appreciate if someone can come up with understandable title. Sorry for my bad English.</p>
1
2016-09-01T09:19:41Z
39,268,327
<p>Did I understand you now?</p> <pre class="lang-py prettyprint-override"><code>from itertools import groupby grp = groupby(filter_data, lambda x: (min(x["sender_id"], x["receiver_id"]), max(x["sender_id"], x["receiver_id"]))) l = [sorted(g, key = lambda x: -x["order"])[0] for k, g in grp] </code></pre>
1
2016-09-01T09:54:19Z
[ "python" ]
"CSV file does not exist" - Pandas Dataframe
39,267,614
<p>I am currently learning Pandas for data analysis and having some issues reading a csv file in Atom editor. </p> <p>When I am running the following code:</p> <pre><code>import pandas as pd df = pd.read_csv("FBI-CRIME11.csv") print(df.head()) </code></pre> <p>I get an error message, which ends with </p> <blockquote> <p>OSError: File b'FBI-CRIME11.csv' does not exist</p> </blockquote> <p>Here is the directory to the file: /Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv".</p> <p>When i try to run it this way:</p> <pre><code>df = pd.read_csv(Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv") </code></pre> <p>I get another error:</p> <blockquote> <p>NameError: name 'Users' is not defined</p> </blockquote> <p>I have also put this directory into the "Project Home" field in the editor settings, though I am not quite sure if it makes any difference.</p> <p>I bet there is an easy way to get it to work. I would really appreciate your help! </p>
1
2016-09-01T09:22:26Z
39,267,665
<p>Have you tried?</p> <pre><code>df = pd.read_csv("Users/alekseinabatov/Documents/Python/FBI-CRIME11.csv") </code></pre> <p>or maybe</p> <pre><code>df = pd.read_csv('Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv"') </code></pre> <p>(If the file name has quotes)</p>
1
2016-09-01T09:24:56Z
[ "python", "csv", "pandas", "atom" ]
"CSV file does not exist" - Pandas Dataframe
39,267,614
<p>I am currently learning Pandas for data analysis and having some issues reading a csv file in Atom editor. </p> <p>When I am running the following code:</p> <pre><code>import pandas as pd df = pd.read_csv("FBI-CRIME11.csv") print(df.head()) </code></pre> <p>I get an error message, which ends with </p> <blockquote> <p>OSError: File b'FBI-CRIME11.csv' does not exist</p> </blockquote> <p>Here is the directory to the file: /Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv".</p> <p>When i try to run it this way:</p> <pre><code>df = pd.read_csv(Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv") </code></pre> <p>I get another error:</p> <blockquote> <p>NameError: name 'Users' is not defined</p> </blockquote> <p>I have also put this directory into the "Project Home" field in the editor settings, though I am not quite sure if it makes any difference.</p> <p>I bet there is an easy way to get it to work. I would really appreciate your help! </p>
1
2016-09-01T09:22:26Z
39,267,769
<p>Just referring to the filename like</p> <pre><code>df = pd.read_csv("FBI-CRIME11.csv") </code></pre> <p>generally only works if the file is in the same directory as the script.</p> <p>If you are using windows, make sure you specify the path to the file as follows:</p> <pre><code>PATH = "C:\\Users\\path\\to\\file.csv" </code></pre>
1
2016-09-01T09:29:43Z
[ "python", "csv", "pandas", "atom" ]
Why it is faster to return a tuple than multiple values in Python?
39,267,626
<p>I did a small test:</p> <pre><code>In [12]: def test1(): ...: return 1,2,3 ...: In [13]: def test2(): ...: return (1,2,3) ...: In [14]: %timeit a,b,c = test1() </code></pre> <p>The slowest run took 66.88 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 92.7 ns per loop</p> <pre><code>In [15]: %timeit a,b,c = test2() </code></pre> <p>The slowest run took 74.43 times longer than the fastest. This could mean that an intermediate result is being cached. 10000000 loops, best of 3: 80.1 ns per loop</p> <p><strong>Returning a tuple is about 15% faster than returning multiple values. Why is it so?</strong></p>
1
2016-09-01T09:22:53Z
39,267,734
<p>Both <code>test1</code> and <code>test2</code> results in same bytecode, so they have to perform in same speed. Your measurement conditions wasn't consistent (e.g. CPU load was increased for test2, due to additional background processes).</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; def test1(): ... return 1,2,3 ... &gt;&gt;&gt; def test2(): ... return (1,2,3) ... &gt;&gt;&gt; dis.dis(test1) 2 0 LOAD_CONST 4 ((1, 2, 3)) 3 RETURN_VALUE &gt;&gt;&gt; dis.dis(test2) 2 0 LOAD_CONST 4 ((1, 2, 3)) 3 RETURN_VALUE &gt;&gt;&gt; </code></pre>
7
2016-09-01T09:28:12Z
[ "python", "performance", "tuples", "return-value", "benchmarking" ]
How to customized inline model view/form of Flask-Admin module?
39,267,649
<p>Suppose I have this parent model:</p> <pre><code>class GoogleAccount(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String, index=True) class GoogleAccountApi(db.Model): id = db.Column(db.Integer, primary_key=True) client_secret = db.Column(db.String) token = db.Column(db.String) google_account_id = db.Column(db.Integer, db.ForeignKey(GoogleAccount.id)) google_account = db.relationship(GoogleAccount, backref=db.backref('google_account_id', cascade="all, delete-orphan", single_parent=True)) class GoogleAccountView(_ModelView): inline_models = (models.GoogleAccountApi,) column_descriptions = dict( email='Halooo' ) admin.add_view(GoogleAccountView(models.GoogleAccount, db.session, endpoint='google-account')) </code></pre> <p>I know I can add column description of parent model (GoogleAccount) using <code>column_descriptions</code>, but how do modify child model column description? Such that for <code>GoogleAccountAPI.client_secrets</code>, I can add info saying, <code>Click here to authenticate to Google</code> ?</p> <p>Not sure do I need to add child view for GoogleAcountApi</p> <p>Thanks!</p>
0
2016-09-01T09:23:59Z
39,273,457
<p>Found it <a href="http://stackoverflow.com/questions/34313253/flask-admin-inline-modelling-passing-form-arguments-throws-attributeerror">here</a>, so this is what you do:</p> <pre><code>inline_models = [(models.GoogleAccountApi, dict( column_descriptions=dict(client_secret='Retoken here') ))] </code></pre>
0
2016-09-01T13:55:11Z
[ "python", "flask", "flask-admin" ]
MongoDBForm error "ValueError:A document class must be provided"
39,267,793
<p>Hi i am creating a simple Sign Up form with django framework and mongodb. Following is my view:</p> <pre><code>class SignUpView(FormView): template_name='MnCApp/signup.html' form_class=EmployeeForm() succes_url='/success/' </code></pre> <p>Following is my model:</p> <pre><code>class Employee(Document): designation=StringField() department=StringField() emp_name=StringField(max_length=50) password=StringField(max_length=10) </code></pre> <p>Following is my <code>forms.py</code></p> <pre><code>class EmployeeForm(DocumentForm): class meta: desigs=( ('D','Director'), ('GM','General Manager'), ('AM','Assistant Manager'), ('A','Associates') ) deptts=( ('HR','Human Resources'), ('IT','IT Support'), ('TT','Technical Team'), ('SM','Sales and Marketting'), ('SS','Support Staff') ) document=Employee fields='__all__' widgets={ 'designation':Select(choices=desigs), 'department':Select(choices=deptts) } </code></pre> <p>Following is the traceback ValueError recieved on loading SignUpview Traceback:</p> <blockquote> <p>File "C:\Program Files\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request)</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request)</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs)</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs)</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\views\generic\edit.py" in get 174. return self.render_to_response(self.get_context_data())</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\views\generic\edit.py" in get_context_data 93. kwargs['form'] = self.get_form()</p> <p>File "C:\Program Files\Python35\lib\site-packages\django\views\generic\edit.py" in get_form 45. return form_class(**self.get_form_kwargs())</p> <p>File "C:\Program Files\Python35\lib\site-packages\mongodbforms\documents.py" in <strong>init</strong> 353. raise ValueError('A document class must be provided.')</p> <p>Exception Type: ValueError at /signup/ Exception Value: A document class must be provided.</p> </blockquote> <p>I am not able to find root of this problem. I am new to django and this is my first project. Also is their anyother way for creating model forms for mongo documents??</p>
-1
2016-09-01T09:30:42Z
39,268,611
<p>I suspect that your inner class should be called <code>Meta</code>, not <code>meta</code>.</p>
0
2016-09-01T10:06:55Z
[ "python", "django", "mongodb", "mongoengine" ]
Can I get a trimmed mean of all columns in a dataframe with nan values?
39,267,848
<p>I seem to be going around in circles trying to solve this problem. I'd be very grateful for any help from the stackoverflow brains trust.</p> <p>The problem is that I want to get the trimmed mean of all the columns in a pandas dataframe (i.e. the mean of the values in a given column, excluding the max and the min values). It's likely that some columns will have nan values. Basically, I want to get the exact same functionality as the pandas.DataFrame.mean function, except that it's the trimmed mean.</p> <p>The obvious solution is to use the scipy tmean function, and iterate over the df columns. So I did: </p> <pre><code>import scipy as sp trim_mean = [] for i in data_clean3.columns: trim_mean.append(sp.tmean(data_clean3[i])) </code></pre> <p>This worked great, until I encountered nan values, which caused tmean to choke. Worse, when I dropped the nan values in the dataframe, there were some datasets that were wiped out completely as they had an nan value in every column. This means that when I amalgamate all my datasets into a master set, there'll be holes on the master set where the trimmed mean should be.</p> <p>Does anyone know of a way around this? As in, is there a way to get tmean to behave like the standard scipy stats functions and ignore nan values? </p> <p>(Note that my code is calculating a big number of descriptive statistics on large datasets with limited hardware; highly involved or inefficient workarounds might not be optimal. Hopefully, though, I'm just missing something simple.)</p> <p>(<strong>EDIT</strong>: Someone suggested in a comment (that has since vanished?) that I should used the trim_mean scipy function, which allows you to top and tail a specific proportion of the data. This is just to say that this solution won't work for me, as my datasets are of unequal sizes, so I cannot specify a fixed proportion of data that will be OK to remove in every case; it must always just be the max and the min values.) </p>
1
2016-09-01T09:32:48Z
39,272,879
<p>you colud use df.mean(skipna =True) <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.mean.html" rel="nofollow">DataFrame.mean</a></p> <pre><code>df1 = pd.DataFrame([[5, 1, 'a'], [6, 2, 'b'],[7, 3, 'd'],[np.nan, 4, 'e'],[9, 5, 'f'],[5, 1, 'g']], columns = ["A", "B", "C"]) print df1 df1 = df1[df1.A != df1.A.max()] # Remove max values df1 = df1[df1.A != df1.A.min()] # Remove min values print "\nDatafrmae after removing max and min\n" print df1 print "\nMean of A\n" print df1["A"].mean(skipna =True) </code></pre> <p>output </p> <pre><code> A B C 0 5.0 1 a 1 6.0 2 b 2 7.0 3 d 3 NaN 4 e 4 9.0 5 f 5 5.0 1 g Datafrmae after removing max and min A B C 1 6.0 2 b 2 7.0 3 d 3 NaN 4 e Mean of A 6.5 </code></pre>
0
2016-09-01T13:28:44Z
[ "python", "pandas", "scipy", "code-statistics" ]
Can I get a trimmed mean of all columns in a dataframe with nan values?
39,267,848
<p>I seem to be going around in circles trying to solve this problem. I'd be very grateful for any help from the stackoverflow brains trust.</p> <p>The problem is that I want to get the trimmed mean of all the columns in a pandas dataframe (i.e. the mean of the values in a given column, excluding the max and the min values). It's likely that some columns will have nan values. Basically, I want to get the exact same functionality as the pandas.DataFrame.mean function, except that it's the trimmed mean.</p> <p>The obvious solution is to use the scipy tmean function, and iterate over the df columns. So I did: </p> <pre><code>import scipy as sp trim_mean = [] for i in data_clean3.columns: trim_mean.append(sp.tmean(data_clean3[i])) </code></pre> <p>This worked great, until I encountered nan values, which caused tmean to choke. Worse, when I dropped the nan values in the dataframe, there were some datasets that were wiped out completely as they had an nan value in every column. This means that when I amalgamate all my datasets into a master set, there'll be holes on the master set where the trimmed mean should be.</p> <p>Does anyone know of a way around this? As in, is there a way to get tmean to behave like the standard scipy stats functions and ignore nan values? </p> <p>(Note that my code is calculating a big number of descriptive statistics on large datasets with limited hardware; highly involved or inefficient workarounds might not be optimal. Hopefully, though, I'm just missing something simple.)</p> <p>(<strong>EDIT</strong>: Someone suggested in a comment (that has since vanished?) that I should used the trim_mean scipy function, which allows you to top and tail a specific proportion of the data. This is just to say that this solution won't work for me, as my datasets are of unequal sizes, so I cannot specify a fixed proportion of data that will be OK to remove in every case; it must always just be the max and the min values.) </p>
1
2016-09-01T09:32:48Z
39,274,068
<p>consider <code>df</code></p> <pre><code>np.random.seed() data = np.random.choice((0, 25, 35, 100, np.nan), (1000, 2), p=(.01, .39, .39, .01, .2)) df = pd.DataFrame(data, columns=list('AB')) </code></pre> <p>Construct your mean using sums and divide by relevant normalizer.</p> <pre><code>(df.sum() - df.min() - df.max()) / (df.notnull().sum() - 2) A 29.707674 B 30.402228 dtype: float64 </code></pre> <hr> <pre><code>df.mean() A 29.756987 B 30.450617 dtype: float64 </code></pre> <hr>
1
2016-09-01T14:19:55Z
[ "python", "pandas", "scipy", "code-statistics" ]
Why "TypeError: 'module' object is not callable" occurs on calling impala.dbapi.connect()?
39,267,946
<p>I am trying to connect to impala and I am following <a href="https://github.com/cloudera/impyla" rel="nofollow">impyla guide</a>. But I am getting this error as I execute connect(). The error is shown below:</p> <pre><code>In [27]: import impala.dbapi as connect In [28]: conn = connect(host="some798.xyz.something", ...: port=22, ...: user="username", ...: password="password") Traceback (most recent call last): File "&lt;ipython-input-28-c9f42dc37774&gt;", line 4, in &lt;module&gt; password="password") TypeError: 'module' object is not callable </code></pre> <p>What is the possible reason that I am not being able to connect? I can connect to the server using the above mentioned parameters and can also access the database of my interest (using Putty shell). I have been searching allot but couldn't resolve it so far. Thanks allot for your time in advance and looking forward to your suggestions.</p> <p><strong>UPDATE:</strong></p> <p>The above error has been resolved after this below change:</p> <pre><code>from impala.dbapi import connect </code></pre> <p>But now I am facing another error after executing this line of code:</p> <pre><code>cursor = conn.cursor() </code></pre> <p>and the error is as below:</p> <pre><code>. . . File "C:\Temp\Anaconda\lib\site-packages\thrift\transport\TSocket.py", line 105, in read buff = self.handle.recv(sz) MemoryError </code></pre> <p>Waiting for suggestions to resolve this issue. Thanks for your time :)</p>
0
2016-09-01T09:37:35Z
39,268,117
<p>I think what you wanted to do is: <code>from impala.dbapi import connect</code></p> <p>In your code you are using impala.dbapi (module) renamed as <code>connect</code>...</p>
2
2016-09-01T09:45:18Z
[ "python", "hadoop", "thrift", "impala" ]
Efficient use of numpy.random.choice with repeated numbers and alternatives
39,267,947
<p>I need to generate a large array with repeated elements, and my code is:</p> <pre><code>np.repeat(xrange(x,y), data) </code></pre> <p>However, data is a numpy array with type float64 (but it represent integeres, no 2.1 there) and I get the error</p> <pre><code>TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' </code></pre> <p>Exemple:</p> <pre><code>In [35]: x Out[35]: 26 In [36]: y Out[36]: 50 In [37]: data Out[37]: array([ 3269., 106., 5533., 317., 1512., 208., 502., 919., 406., 421., 1690., 2236., 705., 505., 230., 213., 307., 1628., 4389., 1491., 355., 103., 854., 424.]) In [38]: np.repeat(xrange(x,y), data) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-38-105860821359&gt; in &lt;module&gt;() ----&gt; 1 np.repeat(xrange(x,y), data) /home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in repeat(a, repeats, axis) 394 repeat = a.repeat 395 except AttributeError: --&gt; 396 return _wrapit(a, 'repeat', repeats, axis) 397 return repeat(repeats, axis) 398 /home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in _wrapit(obj, method, *args, **kwds) 46 except AttributeError: 47 wrap = None ---&gt; 48 result = getattr(asarray(obj), method)(*args, **kwds) 49 if wrap: 50 if not isinstance(result, mu.ndarray): TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' </code></pre> <p>I solve it by changing the code to</p> <pre><code>np.repeat(xrange(x,y), data.astype('int64')) </code></pre> <p>However, this is now one of the most expensive lines in my code!! Is there another alternative?</p> <p>By the way, I using this inside</p> <pre><code>np.random.choice(np.repeat(xrange(x,y), data.astype('int64')), z) </code></pre> <p>in order to get a sample without replacement with size z of the integers between x and y, with the number of each given in data. I guess this is the best approach for that also right?</p>
4
2016-09-01T09:37:36Z
39,271,543
<h2>Problem statement</h2> <p>Pretty interesting problem this one! Just to give the readers an idea about the problem without going into the minor data conversion issues, we have a range of values, let's say <code>a = np.arange(5)</code>, i.e.</p> <pre><code>a = np.array([0,1,2,3,4]) </code></pre> <p>Now, let's say we have another array with the number of repetitions listed for each of the <code>5</code> numbers in <code>a</code>. So, let those be :</p> <pre><code>reps = np.array([2,4,6,2,2]) </code></pre> <p>Next up, we are performing those repetitions :</p> <pre><code>In [32]: rep_nums = np.repeat(a,reps) In [33]: rep_nums Out[33]: array([0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4]) </code></pre> <p>Finally, we are looking to choose <code>z</code> number of elements out of those repeated numbers using <code>np.random.choice()</code> and without replacement.</p> <p>Let's say <code>z = 7</code> to choose <code>7</code> elements, so with <code>np.random.choice()</code>, we would have :</p> <pre><code>In [34]: np.random.choice(rep_nums,7,replace=False) Out[34]: array([2, 4, 0, 2, 4, 1, 2]) </code></pre> <p>Now, this <code>without replacement</code> term here might sound confusing, as we already have repeated numbers in <code>rep_nums</code>. But, what it essentially means is that, the output from <code>np.random.choice()</code> mustn't contain e.g. more than two <code>4's</code>, because <code>rep_nums</code> has two <code>4's</code>.</p> <p>So, the problem is we want to get rid of that <code>np.repeat</code> part, which might be a bottleneck for really huge arrays.</p> <h2>Proposed approach</h2> <p>Looking at the output from <code>rep_nums</code>, one idea would be to generate <code>z = 7</code> unique elements ranging across the length of <code>rep_nums</code> :</p> <pre><code>In [44]: np.random.choice(rep_nums.size,7,replace=False) Out[44]: array([ 7, 2, 4, 10, 13, 8, 3]) </code></pre> <p>These numbers represent indices for that length. So, we just need to look for the bin (out of the <code>5</code> bins) in <code>rep_nums</code> in which each of those <code>7</code> numbers would go in. For that, we can use <code>np.searchsorted</code>. Thus, we would have an implementation to handle generic <code>x</code>, <code>y</code>, like so -</p> <pre><code># Get the intervals of those bins intervals = data.astype(int).cumsum() # Decide length of array if we had repeated with `np.repeat` max_num = intervals[-1] # Get unique numbers (indices in this case) ids = np.random.choice(max_num,z,replace=False) # Use searchsorted to get bin IDs and add in `x` offset out = x+np.searchsorted(intervals,ids,'right') </code></pre> <p><strong>Runtime test</strong></p> <p>Functions :</p> <pre><code>def org_app(x,y,z,data): rep_nums = np.repeat(range(x,y), data.astype('int64')) out = np.random.choice(rep_nums, z,replace=False) return out def optimized_v1(x,y,z,data): intervals = data.astype(int).cumsum() max_num = intervals[-1] ids = np.random.choice(max_num,z,replace=False) out = x+np.searchsorted(intervals,ids,'right') return out </code></pre> <p>Timings on full functions -</p> <pre><code>In [79]: # Setup inputs ...: x = 100 ...: y = 10010 ...: z = 1000 ...: data = np.random.randint(100,5000,(y-x)).astype(float) ...: In [80]: %timeit org_app(x,y,z,data) 1 loop, best of 3: 7.17 s per loop In [81]: %timeit optimized_v1(x,y,z,data) 1 loop, best of 3: 6.92 s per loop </code></pre> <p>Doesn't look like we are getting good speedup. Let's dig deeper and find out how much are we saving on replacing <code>np.repeat</code>!</p> <p>First off the original approach -</p> <pre><code>In [82]: %timeit np.repeat(range(x,y), data.astype('int64')) 1 loop, best of 3: 227 ms per loop </code></pre> <p>Let's see how much improvement we got on this with the proposed approach. So, let's time everything except <code>np.random.choice()</code> in the proposed approach -</p> <pre><code>In [83]: intervals = data.astype(int).cumsum() ...: max_num = intervals[-1] ...: ids = np.random.choice(max_num,z,replace=False) ...: out = x+np.searchsorted(intervals,ids,'right') ...: In [84]: %timeit data.astype(int).cumsum() 10000 loops, best of 3: 36.6 µs per loop In [85]: %timeit intervals[-1] 10000000 loops, best of 3: 142 ns per loop In [86]: %timeit x+np.searchsorted(intervals,ids,'right') 10000 loops, best of 3: 127 µs per loop </code></pre> <p><strong>This is much better than <code>227ms</code> from <code>np.repeat</code>!!</strong></p> <p>So, we are hoping that at really huge arrays, the benefit from removing <code>np.repeat</code> would really shine, as otherwise <code>np.random.choice()</code> itself looks like the bottleneck.</p>
3
2016-09-01T12:25:46Z
[ "python", "python-2.7", "numpy", "casting", "repeat" ]
Efficient use of numpy.random.choice with repeated numbers and alternatives
39,267,947
<p>I need to generate a large array with repeated elements, and my code is:</p> <pre><code>np.repeat(xrange(x,y), data) </code></pre> <p>However, data is a numpy array with type float64 (but it represent integeres, no 2.1 there) and I get the error</p> <pre><code>TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' </code></pre> <p>Exemple:</p> <pre><code>In [35]: x Out[35]: 26 In [36]: y Out[36]: 50 In [37]: data Out[37]: array([ 3269., 106., 5533., 317., 1512., 208., 502., 919., 406., 421., 1690., 2236., 705., 505., 230., 213., 307., 1628., 4389., 1491., 355., 103., 854., 424.]) In [38]: np.repeat(xrange(x,y), data) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-38-105860821359&gt; in &lt;module&gt;() ----&gt; 1 np.repeat(xrange(x,y), data) /home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in repeat(a, repeats, axis) 394 repeat = a.repeat 395 except AttributeError: --&gt; 396 return _wrapit(a, 'repeat', repeats, axis) 397 return repeat(repeats, axis) 398 /home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in _wrapit(obj, method, *args, **kwds) 46 except AttributeError: 47 wrap = None ---&gt; 48 result = getattr(asarray(obj), method)(*args, **kwds) 49 if wrap: 50 if not isinstance(result, mu.ndarray): TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' </code></pre> <p>I solve it by changing the code to</p> <pre><code>np.repeat(xrange(x,y), data.astype('int64')) </code></pre> <p>However, this is now one of the most expensive lines in my code!! Is there another alternative?</p> <p>By the way, I using this inside</p> <pre><code>np.random.choice(np.repeat(xrange(x,y), data.astype('int64')), z) </code></pre> <p>in order to get a sample without replacement with size z of the integers between x and y, with the number of each given in data. I guess this is the best approach for that also right?</p>
4
2016-09-01T09:37:36Z
39,271,796
<p>For completion, I also have an alternative implementation. Given that we have <code>data</code>, we can use an hypergeometric sampling for each class:</p> <ul> <li>calculate reverse <code>data.cumsum()</code></li> <li>for each class draw <code>np.hypergeometric(data[pos], cumsum[pos]-data[pos], remain)</code></li> </ul> <p>However, when we have many classes with few units in each this takes a long time.</p>
1
2016-09-01T12:37:43Z
[ "python", "python-2.7", "numpy", "casting", "repeat" ]
Efficient use of numpy.random.choice with repeated numbers and alternatives
39,267,947
<p>I need to generate a large array with repeated elements, and my code is:</p> <pre><code>np.repeat(xrange(x,y), data) </code></pre> <p>However, data is a numpy array with type float64 (but it represent integeres, no 2.1 there) and I get the error</p> <pre><code>TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' </code></pre> <p>Exemple:</p> <pre><code>In [35]: x Out[35]: 26 In [36]: y Out[36]: 50 In [37]: data Out[37]: array([ 3269., 106., 5533., 317., 1512., 208., 502., 919., 406., 421., 1690., 2236., 705., 505., 230., 213., 307., 1628., 4389., 1491., 355., 103., 854., 424.]) In [38]: np.repeat(xrange(x,y), data) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-38-105860821359&gt; in &lt;module&gt;() ----&gt; 1 np.repeat(xrange(x,y), data) /home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in repeat(a, repeats, axis) 394 repeat = a.repeat 395 except AttributeError: --&gt; 396 return _wrapit(a, 'repeat', repeats, axis) 397 return repeat(repeats, axis) 398 /home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in _wrapit(obj, method, *args, **kwds) 46 except AttributeError: 47 wrap = None ---&gt; 48 result = getattr(asarray(obj), method)(*args, **kwds) 49 if wrap: 50 if not isinstance(result, mu.ndarray): TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' </code></pre> <p>I solve it by changing the code to</p> <pre><code>np.repeat(xrange(x,y), data.astype('int64')) </code></pre> <p>However, this is now one of the most expensive lines in my code!! Is there another alternative?</p> <p>By the way, I using this inside</p> <pre><code>np.random.choice(np.repeat(xrange(x,y), data.astype('int64')), z) </code></pre> <p>in order to get a sample without replacement with size z of the integers between x and y, with the number of each given in data. I guess this is the best approach for that also right?</p>
4
2016-09-01T09:37:36Z
39,277,021
<p>Lurking in the question is the <a href="https://en.wikipedia.org/wiki/Hypergeometric_distribution#Multivariate_hypergeometric_distribution" rel="nofollow">multivariate hypergeometric distribution</a>. In <a href="http://stackoverflow.com/questions/35734026/numpy-drawing-from-urn/35735195#35735195">Numpy drawing from urn</a>, I implemented a function that draws samples from this distribution. I suspect it is very similar to the solution @DiogoSantos described in an answer. Diogo says that using this approach is slow, but I find the following to be faster than Divakar's <code>optmized_v1</code>.</p> <p>Here is a function that uses <code>sample(n, colors)</code> from the linked answer to implement a function with the same signature as Divakar's functions.</p> <pre><code>def hypergeom_version(x, y, z, data): s = sample(z, data) result = np.repeat(np.arange(x, y), s) return result </code></pre> <p>(This returns the values in <em>sorted order</em>. If you need the values to be in random order, add <code>np.random.shuffle(result)</code> before the return statement. It does not change the execution time significantly.)</p> <p>Comparison:</p> <pre><code>In [153]: x = 100 In [154]: y = 100100 In [155]: z = 10000 In [156]: data = np.random.randint(1, 125, (y-x)).astype(float) </code></pre> <p>Divakar's <code>optimized_v1</code>:</p> <pre><code>In [157]: %timeit optimized_v1(x, y, z, data) 1 loop, best of 3: 520 ms per loop </code></pre> <p><code>hypergeom_version</code>:</p> <pre><code>In [158]: %timeit hypergeom_version(x, y, z, data) 1 loop, best of 3: 244 ms per loop </code></pre> <p>If the values in <code>data</code> are larger, the relative performance is even better:</p> <pre><code>In [164]: data = np.random.randint(100, 500, (y-x)).astype(float) In [165]: %timeit optimized_v1(x, y, z, data) 1 loop, best of 3: 2.91 s per loop In [166]: %timeit hypergeom_version(x, y, z, data) 1 loop, best of 3: 246 ms per loop </code></pre>
3
2016-09-01T16:54:32Z
[ "python", "python-2.7", "numpy", "casting", "repeat" ]
Python: decode 7bit or 8bit encoded email body
39,267,949
<p><a href="https://docs.python.org/2/library/email.encoders.html" rel="nofollow">https://docs.python.org/2/library/email.encoders.html</a> lists way to encode the email payload. Is there a way to decode the payload that was received over email?</p> <p>I need to decode the html body from the email encoded in base64 or 7/8bit or quoted printable formats and mine some data. Luckily there are modules that can deal with quoted printable(quopri) and base64 formats. </p> <p>I tried finding one for the 7/8bit encoded emails, but was unable to find anything satisfactory. What is the best way to decode such email payloads?</p>
0
2016-09-01T09:37:42Z
39,269,840
<p>Looks like the easiest way to decode 7bit data is to use the quopri module in python. Essentially quoted-printable is a format which is used to send 8bit data over a 7bit channel. The code below is working well for me:</p> <pre><code>import quopri quopri.decodestring(email_multipart_payload) # payload has 7bit encoded data </code></pre>
0
2016-09-01T11:04:08Z
[ "python", "email", "encoding", "html-email" ]