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
Regex in Python to find Rows in Table
39,580,495
<p>i`m using python to automate some test, and at one point i find a table with rows, but this rows are of two different clases:</p> <p>You have class name "gris-claro-tr" and "gris-oscuro-tr".</p> <p>I need to iterate the whole table, finding the text of every row. Until now, i have:</p> <pre><code> for row in driver.find_elements_by_class_name("gris-claro-tr"): cell = row.find_elements_by_tag_name("td")[1] print (cell.text) </code></pre> <p>But of course, only works for the rows with that class. I have to do the same thing for "gris-oscuro-tr". However, if i could find a regex that could find both row`s class, i would get the text of every row in that table, no matter if it is "gris-claro-td" or "gris-oscuro-td". </p> <p>The question is: how can i make that regex? </p> <p>Is it something like "gris-"+"*" ?</p> <p>Thank you very much!</p>
1
2016-09-19T19:16:11Z
39,580,588
<p>You can approach it with a <em>CSS selector</em>:</p> <pre><code>driver.find_elements_by_css_selector(".gris-claro-tr,.gris-oscuro-tr") </code></pre> <p><code>,</code> here means "or", dot defines a class name selector.</p> <hr> <p>Or, you can apply the partial matches as well, a little bit less explicit though:</p> <pre><code>driver.find_elements_by_css_selector("[class^=gris][class$=tr]") </code></pre> <p>where <code>^=</code> means "starts with", <code>$=</code> means "ends with".</p>
1
2016-09-19T19:22:44Z
[ "python", "regex", "webdriver" ]
Regex in Python to find Rows in Table
39,580,495
<p>i`m using python to automate some test, and at one point i find a table with rows, but this rows are of two different clases:</p> <p>You have class name "gris-claro-tr" and "gris-oscuro-tr".</p> <p>I need to iterate the whole table, finding the text of every row. Until now, i have:</p> <pre><code> for row in driver.find_elements_by_class_name("gris-claro-tr"): cell = row.find_elements_by_tag_name("td")[1] print (cell.text) </code></pre> <p>But of course, only works for the rows with that class. I have to do the same thing for "gris-oscuro-tr". However, if i could find a regex that could find both row`s class, i would get the text of every row in that table, no matter if it is "gris-claro-td" or "gris-oscuro-td". </p> <p>The question is: how can i make that regex? </p> <p>Is it something like "gris-"+"*" ?</p> <p>Thank you very much!</p>
1
2016-09-19T19:16:11Z
39,580,665
<p>If you insist on XPATH you can use</p> <pre><code>driver.find_elements_by_xpath("//*[@class='gris-claro-tr'] or [@class='gris-oscuro-td'] ") </code></pre> <p><code>*</code> can be replced by your tag name</p>
0
2016-09-19T19:28:55Z
[ "python", "regex", "webdriver" ]
Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article.
39,580,633
<p>I wrote this test code which uses BeautifulSoup.</p> <pre><code>url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html" html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html,"lxml") for n in soup.find_all('p'): print(n.get_text()) </code></pre> <p>It works fine but it also retrieves text that is not part of the news article, such as the time it was posted, number of comments, copyrights ect. </p> <p>I would wish for it to only retrieve text from the news article itself, how would one go about this? </p>
2
2016-09-19T19:26:14Z
39,580,690
<p>You'll need to target more specifically than just the <code>p</code> tag. Try looking for a <code>div class="article"</code> or something similar, then only grab paragraphs from there</p>
1
2016-09-19T19:30:33Z
[ "python", "html", "beautifulsoup" ]
Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article.
39,580,633
<p>I wrote this test code which uses BeautifulSoup.</p> <pre><code>url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html" html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html,"lxml") for n in soup.find_all('p'): print(n.get_text()) </code></pre> <p>It works fine but it also retrieves text that is not part of the news article, such as the time it was posted, number of comments, copyrights ect. </p> <p>I would wish for it to only retrieve text from the news article itself, how would one go about this? </p>
2
2016-09-19T19:26:14Z
39,581,216
<p>You might have much better luck with <a href="http://newspaper.readthedocs.io/en/latest/" rel="nofollow"><code>newspaper</code> library</a> which is focused on scraping articles.</p> <p>If we talk about <code>BeautifulSoup</code> only, one option to get closer to the desired result and have more relevant paragraphs is to find them in the context of <code>div</code> element with <code>itemprop="articleBody"</code> attribute:</p> <pre><code>article_body = soup.find(itemprop="articleBody") for p in article_body.find_all("p"): print(p.get_text()) </code></pre>
1
2016-09-19T20:05:43Z
[ "python", "html", "beautifulsoup" ]
Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article.
39,580,633
<p>I wrote this test code which uses BeautifulSoup.</p> <pre><code>url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html" html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html,"lxml") for n in soup.find_all('p'): print(n.get_text()) </code></pre> <p>It works fine but it also retrieves text that is not part of the news article, such as the time it was posted, number of comments, copyrights ect. </p> <p>I would wish for it to only retrieve text from the news article itself, how would one go about this? </p>
2
2016-09-19T19:26:14Z
39,581,286
<p>Be more specific, you need to catch the <code>div</code> with <code>class</code> <code>articleBody</code>, so :</p> <pre><code>import urllib.request from bs4 import BeautifulSoup url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html" html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html,"lxml") for n in soup.find_all('div', attrs={'itemprop':"articleBody"}): print(n.get_text()) </code></pre> <p>Responses on SO is not just for you, but also for people coming from google searches and such. So as you can see, <code>attrs</code> is a dict, it is then possible to pass more attributes/values if needed.</p>
1
2016-09-19T20:10:21Z
[ "python", "html", "beautifulsoup" ]
Python: Threading specific number of times
39,580,662
<p>I have the following code that uses <code>threading</code> and prints the current count.</p> <pre><code>import threading count = 0 def worker(): """thread worker function""" global count count += 1 print(count) threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() </code></pre> <p>It is currently set to 5 threads. How can I have it continue running the threads until it reaches a certain #. i.e. run at 5 threads until <code>worker()</code> has run 100 times.</p>
3
2016-09-19T19:28:47Z
39,580,940
<p>just do a while loop, but protect your counter and your test with a lock, otherwise the value tested will be different from the one you just increased.</p> <p>I have added the thread id so we see which thread is actually increasing the counter.</p> <p>Also: check first, increase after.</p> <p>And wait for the threads in the end.</p> <pre><code>import threading lck = threading.Lock() count = 0 def worker(): global count """thread worker function""" while True: lck.acquire() if count==100: lck.release() break count += 1 print(threading.current_thread() ,count) lck.release() threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join() </code></pre> <p>result:</p> <pre><code>(&lt;Thread(Thread-1, started 5868)&gt;, 1) (&lt;Thread(Thread-2, started 7152)&gt;, 2) (&lt;Thread(Thread-3, started 6348)&gt;, 3) (&lt;Thread(Thread-4, started 6056)&gt;, 4) (&lt;Thread(Thread-1, started 5868)&gt;, 5) (&lt;Thread(Thread-5, started 5748)&gt;, 6) (&lt;Thread(Thread-2, started 7152)&gt;, 7) (&lt;Thread(Thread-3, started 6348)&gt;, 8) (&lt;Thread(Thread-4, started 6056)&gt;, 9) (&lt;Thread(Thread-1, started 5868)&gt;, 10) (&lt;Thread(Thread-5, started 5748)&gt;, 11) (&lt;Thread(Thread-2, started 7152)&gt;, 12) (&lt;Thread(Thread-3, started 6348)&gt;, 13) (&lt;Thread(Thread-4, started 6056)&gt;, 14) (&lt;Thread(Thread-1, started 5868)&gt;, 15) (&lt;Thread(Thread-5, started 5748)&gt;, 16) (&lt;Thread(Thread-2, started 7152)&gt;, 17) (&lt;Thread(Thread-3, started 6348)&gt;, 18) (&lt;Thread(Thread-4, started 6056)&gt;, 19) (&lt;Thread(Thread-1, started 5868)&gt;, 20) (&lt;Thread(Thread-5, started 5748)&gt;, 21) (&lt;Thread(Thread-2, started 7152)&gt;, 22) (&lt;Thread(Thread-3, started 6348)&gt;, 23) (&lt;Thread(Thread-4, started 6056)&gt;, 24) (&lt;Thread(Thread-1, started 5868)&gt;, 25) (&lt;Thread(Thread-5, started 5748)&gt;, 26) (&lt;Thread(Thread-2, started 7152)&gt;, 27) (&lt;Thread(Thread-3, started 6348)&gt;, 28) (&lt;Thread(Thread-4, started 6056)&gt;, 29) (&lt;Thread(Thread-1, started 5868)&gt;, 30) (&lt;Thread(Thread-5, started 5748)&gt;, 31) (&lt;Thread(Thread-2, started 7152)&gt;, 32) (&lt;Thread(Thread-3, started 6348)&gt;, 33) (&lt;Thread(Thread-4, started 6056)&gt;, 34) (&lt;Thread(Thread-1, started 5868)&gt;, 35) (&lt;Thread(Thread-5, started 5748)&gt;, 36) (&lt;Thread(Thread-2, started 7152)&gt;, 37) (&lt;Thread(Thread-3, started 6348)&gt;, 38) (&lt;Thread(Thread-4, started 6056)&gt;, 39) (&lt;Thread(Thread-1, started 5868)&gt;, 40) (&lt;Thread(Thread-5, started 5748)&gt;, 41) (&lt;Thread(Thread-2, started 7152)&gt;, 42) (&lt;Thread(Thread-3, started 6348)&gt;, 43) (&lt;Thread(Thread-4, started 6056)&gt;, 44) (&lt;Thread(Thread-1, started 5868)&gt;, 45) (&lt;Thread(Thread-5, started 5748)&gt;, 46) (&lt;Thread(Thread-2, started 7152)&gt;, 47) (&lt;Thread(Thread-3, started 6348)&gt;, 48) (&lt;Thread(Thread-4, started 6056)&gt;, 49) (&lt;Thread(Thread-1, started 5868)&gt;, 50) (&lt;Thread(Thread-5, started 5748)&gt;, 51) (&lt;Thread(Thread-2, started 7152)&gt;, 52) (&lt;Thread(Thread-3, started 6348)&gt;, 53) (&lt;Thread(Thread-4, started 6056)&gt;, 54) (&lt;Thread(Thread-1, started 5868)&gt;, 55) (&lt;Thread(Thread-5, started 5748)&gt;, 56) (&lt;Thread(Thread-2, started 7152)&gt;, 57) (&lt;Thread(Thread-3, started 6348)&gt;, 58) (&lt;Thread(Thread-4, started 6056)&gt;, 59) (&lt;Thread(Thread-1, started 5868)&gt;, 60) (&lt;Thread(Thread-5, started 5748)&gt;, 61) (&lt;Thread(Thread-2, started 7152)&gt;, 62) (&lt;Thread(Thread-3, started 6348)&gt;, 63) (&lt;Thread(Thread-4, started 6056)&gt;, 64) (&lt;Thread(Thread-1, started 5868)&gt;, 65) (&lt;Thread(Thread-5, started 5748)&gt;, 66) (&lt;Thread(Thread-2, started 7152)&gt;, 67) (&lt;Thread(Thread-3, started 6348)&gt;, 68) (&lt;Thread(Thread-4, started 6056)&gt;, 69) (&lt;Thread(Thread-1, started 5868)&gt;, 70) (&lt;Thread(Thread-5, started 5748)&gt;, 71) (&lt;Thread(Thread-2, started 7152)&gt;, 72) (&lt;Thread(Thread-3, started 6348)&gt;, 73) (&lt;Thread(Thread-4, started 6056)&gt;, 74) (&lt;Thread(Thread-1, started 5868)&gt;, 75) (&lt;Thread(Thread-5, started 5748)&gt;, 76) (&lt;Thread(Thread-2, started 7152)&gt;, 77) (&lt;Thread(Thread-3, started 6348)&gt;, 78) (&lt;Thread(Thread-4, started 6056)&gt;, 79) (&lt;Thread(Thread-1, started 5868)&gt;, 80) (&lt;Thread(Thread-5, started 5748)&gt;, 81) (&lt;Thread(Thread-2, started 7152)&gt;, 82) (&lt;Thread(Thread-3, started 6348)&gt;, 83) (&lt;Thread(Thread-4, started 6056)&gt;, 84) (&lt;Thread(Thread-1, started 5868)&gt;, 85) (&lt;Thread(Thread-5, started 5748)&gt;, 86) (&lt;Thread(Thread-2, started 7152)&gt;, 87) (&lt;Thread(Thread-3, started 6348)&gt;, 88) (&lt;Thread(Thread-4, started 6056)&gt;, 89) (&lt;Thread(Thread-1, started 5868)&gt;, 90) (&lt;Thread(Thread-5, started 5748)&gt;, 91) (&lt;Thread(Thread-2, started 7152)&gt;, 92) (&lt;Thread(Thread-3, started 6348)&gt;, 93) (&lt;Thread(Thread-4, started 6056)&gt;, 94) (&lt;Thread(Thread-1, started 5868)&gt;, 95) (&lt;Thread(Thread-5, started 5748)&gt;, 96) (&lt;Thread(Thread-2, started 7152)&gt;, 97) (&lt;Thread(Thread-3, started 6348)&gt;, 98) (&lt;Thread(Thread-4, started 6056)&gt;, 99) (&lt;Thread(Thread-1, started 5868)&gt;, 100) </code></pre>
2
2016-09-19T19:46:15Z
[ "python", "multithreading", "python-multithreading" ]
Python: Threading specific number of times
39,580,662
<p>I have the following code that uses <code>threading</code> and prints the current count.</p> <pre><code>import threading count = 0 def worker(): """thread worker function""" global count count += 1 print(count) threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() </code></pre> <p>It is currently set to 5 threads. How can I have it continue running the threads until it reaches a certain #. i.e. run at 5 threads until <code>worker()</code> has run 100 times.</p>
3
2016-09-19T19:28:47Z
39,581,043
<p>Loop it, of course.</p> <pre><code>lock = threading.Lock() count = 0 def worker(): """thread worker function""" global count while True: with lock: if count &gt;= 100: break count += 1 print(count) </code></pre> <p>Notice the protected access to <code>count</code> with <code>threading.Lock</code>; relying on <a href="https://en.wikipedia.org/wiki/Global_interpreter_lock" rel="nofollow">GIL</a> is sketchy.</p>
2
2016-09-19T19:53:48Z
[ "python", "multithreading", "python-multithreading" ]
Python: Threading specific number of times
39,580,662
<p>I have the following code that uses <code>threading</code> and prints the current count.</p> <pre><code>import threading count = 0 def worker(): """thread worker function""" global count count += 1 print(count) threads = [] for i in range(5): t = threading.Thread(target=worker) threads.append(t) t.start() </code></pre> <p>It is currently set to 5 threads. How can I have it continue running the threads until it reaches a certain #. i.e. run at 5 threads until <code>worker()</code> has run 100 times.</p>
3
2016-09-19T19:28:47Z
39,581,415
<p>To be honest, if you want something like this, it means that you are going to wrong direction. Because this code is <code>stateful</code> and <code>stateful</code> processing is far away from real parallel execution. Also usually if you want to execute code in parallel in python, you need to use <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module.</p> <p>So, basically, if you goal is to tick 100 times in total, it's better to rewrite your code in stateless way:</p> <pre><code>import multiprocessing as mp def worker_1(x): for i in range(x) print i def worker_2(y): print y if __name__ == '__main__': p = mp.Pool(5) for x in p.pool(worker_1, [25, 25, 25, 25]): // process result pass for y in p.pool(worker_2, range(100)): // process result pass </code></pre>
1
2016-09-19T20:18:47Z
[ "python", "multithreading", "python-multithreading" ]
Using Cookies To Access HTML
39,580,705
<p>I'm trying to access a site (for which I have a login) through a <code>.get(url)</code> request. However, I tried passing the cookies that should authenticate my request but I keep getting a <code>401</code> error. I tried passing the cookies in the <code>.get</code> argument like so </p> <pre><code>requests.post('http://eventregistry.org/json/article?action=getArticles&amp;articlesConceptLang=eng&amp;articlesCount=25&amp;articlesIncludeArticleConcepts=true&amp;articlesIncludeArticleImage=true&amp;articlesIncludeArticleSocialScore=true&amp;articlesPage=1&amp;articlesSortBy=date&amp;ignoreKeywords=&amp;keywords=soybean&amp;resultType=articles', data = {"connect.sid': "long cookie found on chrome settings") </code></pre> <p>(Scroll over to see how cookies were used. Apologies for super long URL)</p> <p>Am I approaching the cookie situation the wrong way? Should I login in with my username or password instead of passing the cookies? Or did I misinterpret my Chrome's cookie?</p> <p>Thanks!</p>
0
2016-09-19T19:31:25Z
39,603,730
<p>Solved: </p> <pre><code>import requests payload = { 'email': '###@gmail.com', #find the right name for the forms from HTML of site 'pass': '###'} # Use 'with' to ensure the session context is closed after use. with requests.Session() as s: p = s.post('loginURL') r = s.get('restrictedURL') print(r) #etc </code></pre>
0
2016-09-20T21:07:19Z
[ "python", "post", "cookies" ]
Unable to download Python on Windows System
39,580,731
<p>I'm having trouble getting python to work on my Windows 10 computer. I downloaded 3.5.2 off the website and ran the exe, but when I try to use</p> <p><code>pip install nltk</code></p> <p>So I copied and ran get-pip.py, but it still tells me "pip" is not recognized as an internal or external command, operable program or batch file.</p> <p><code>python -m pip install pip</code></p> <p>tells me that python is also not recognized. What should I do?</p> <p>EDIT: Have tried reinstalling python, made sure the box to install pip was checked. Tried re-running the pip command in the Python command line (the one titled Python 3.5 (32-bit)) and it gave me an invalid syntax error on the word install.</p>
-1
2016-09-19T19:32:56Z
39,580,904
<p>When installing "the exe", make sure that you tick the checkbox labelled "Add Python 3.5 to PATH". That will solve the issue you mentionned.</p>
0
2016-09-19T19:44:14Z
[ "python", "windows", "pip", "windows-10", "python-3.5" ]
Unable to download Python on Windows System
39,580,731
<p>I'm having trouble getting python to work on my Windows 10 computer. I downloaded 3.5.2 off the website and ran the exe, but when I try to use</p> <p><code>pip install nltk</code></p> <p>So I copied and ran get-pip.py, but it still tells me "pip" is not recognized as an internal or external command, operable program or batch file.</p> <p><code>python -m pip install pip</code></p> <p>tells me that python is also not recognized. What should I do?</p> <p>EDIT: Have tried reinstalling python, made sure the box to install pip was checked. Tried re-running the pip command in the Python command line (the one titled Python 3.5 (32-bit)) and it gave me an invalid syntax error on the word install.</p>
-1
2016-09-19T19:32:56Z
39,584,316
<p>Frito's suggestion works, I had to manually add it to the path following the instructions on the website. Thank you all for the help.</p>
0
2016-09-20T01:19:20Z
[ "python", "windows", "pip", "windows-10", "python-3.5" ]
Python Tkinter Label in Frame
39,580,739
<p>I want to place a label inside a frame in tkinter, but I can't figure out how to actually get it inside.</p> <pre><code>import tkinter from tkinter import * W=tkinter.Tk() W.geometry("800x850+0+0") W.configure(background="lightblue") FRAME=Frame(W, width=100, height =50).place(x=700,y=0) LABEL=Label(FRAME, text="test").pack() </code></pre> <p>When I run this, it doesn't place the Label inside the frame, but just places it normally on the window. What am I doing wrong?</p>
1
2016-09-19T19:33:36Z
39,581,024
<p>I think it's because you're assigning <code>FRAME</code> to <code>Frame(W, width=100, height =50).place(x=700,y=0)</code>, as opposed to just the actual frame, and according to the <a href="http://effbot.org/tkinterbook/place.htm" rel="nofollow">Place Manager reference</a>, there doesn't seem to be a return value. Try this:</p> <pre><code>import tkinter from tkinter import * W=tkinter.Tk() W.geometry("800x850+0+0") W.configure(background="lightblue") FRAME=Frame(W, width=100, height =50) FRAME.place(x=700,y=0) LABEL=Label(FRAME, text="test").pack() W.mainloop() </code></pre>
1
2016-09-19T19:53:06Z
[ "python", "tkinter", "label", "frame" ]
Python Tkinter Label in Frame
39,580,739
<p>I want to place a label inside a frame in tkinter, but I can't figure out how to actually get it inside.</p> <pre><code>import tkinter from tkinter import * W=tkinter.Tk() W.geometry("800x850+0+0") W.configure(background="lightblue") FRAME=Frame(W, width=100, height =50).place(x=700,y=0) LABEL=Label(FRAME, text="test").pack() </code></pre> <p>When I run this, it doesn't place the Label inside the frame, but just places it normally on the window. What am I doing wrong?</p>
1
2016-09-19T19:33:36Z
39,581,091
<p>In the line</p> <pre><code>FRAME=Frame(W, width=100, height =50).place(x=700,y=0) </code></pre> <p>You think you are returning a tk frame, but you are not! You get the return value of the place method, which is <code>None</code></p> <p>So try</p> <pre><code>frame = Frame(W, width=100, height=50) frame.place(x=700, y=0) label = Label(frame, text="test").pack() </code></pre> <p>If you don't want the frame to shrink to fit the label, use (<a href="http://stackoverflow.com/questions/563827/how-to-stop-tkinter-frame-from-shrinking-to-fit-its-contents">How to stop Tkinter Frame from shrinking to fit its contents?</a>)</p> <pre><code>frame.pack_propagate(False) </code></pre> <p>Note: Either <code>import tkinter</code> or <code>from tkinter import *</code> but not both. Also, by convention, names of instances of objects are lowercase.</p>
1
2016-09-19T19:57:42Z
[ "python", "tkinter", "label", "frame" ]
Export MongoDB to CSV Using File Name Variable
39,580,809
<p>I have a MongoDB that houses data from a web scrape that runs weekly via Scrapy. I'm going to setup a cron job to run the scrape job weekly. What I would like to do is also export a CSV out of MongoDB using mongoexport however I would like to inject the current date into the file name. I've tried a few different methods without much success. Any help would be greatly appreciated! For reference, my current export string is: mongoexport --host localhost --db glimpsedb --collection scrapedata --csv --out scrape-export.csv --fields dealerid,unitid,seller,street,city,state,zipcode,rvclass,year,make,model,condition,price</p> <p>So, ideally the file name would be scrape-export-current date.csv</p> <p>Thanks again!</p>
0
2016-09-19T19:38:13Z
39,580,966
<p>Replace <code>--out scrape-export.csv</code> in your command with <code>--out scrape-export-$(date +"%Y-%m-%d").csv</code></p> <p>It'll create filenames in the format <code>scrape-export-2016-09-05</code></p>
1
2016-09-19T19:48:10Z
[ "python", "mongodb", "scrapy", "mongoexport" ]
Django Raw query usage
39,580,881
<p>I am struggling to use the output of a raw query. My code is as follows:</p> <pre><code>cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2") currentSelectedTeams = cursor.fetchone() if not currentSelectedTeams: currentSelectedTeam1 = 0 currentSelectedTeam2 = 0 else: currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid </code></pre> <p>I get the following error:</p> <pre><code>currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid AttributeError: 'long' object has no attribute 'teamselectionid' </code></pre> <p>Any help would be appreciated, many thanks in advance, Alan.</p> <p>PS</p> <p>In case it helps the result of my query in MySQL is as follows:</p> <pre><code>mysql&gt; select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2; +-----------------+-------------------+-----------------+---------+ | fixturematchday | teamselection1or2 | teamselectionid | user_id | +-----------------+-------------------+-----------------+---------+ | 6 | 1 | 31 | 349 | | 6 | 2 | 21 | 349 | +-----------------+-------------------+-----------------+---------+ 2 rows in set (0.00 sec) </code></pre>
0
2016-09-19T19:42:49Z
39,581,163
<p>Your issue is that you are <a href="http://currentSelectedTeams%20=%20cursor.fetchone()" rel="nofollow">using <code>cursor.fetchone()</code></a> and iterating through the result expecting it to return multiple rows. </p> <p>If you want the top 2 results, you might want to use <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchall.html" rel="nofollow"><code>fetchmany</code> and limit to 2 records instead</a>. </p> <p>This is what is happening under the hood:</p> <p>Since you are fetching only one record, <code>currentSelectedTeams[0]</code> is actually returning the <code>fixturematchday</code> column, which it looks like is of type <code>long</code> and you are unable to access the attribute from it. </p> <p>Another option would be to use the <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/" rel="nofollow">pretty powerful <code>Django ORM</code></a> to fetch this query result</p> <p>EDIT:</p> <p>If you really want to stick with <code>cursor</code> based implementation, try this:</p> <pre><code>cursor.execute("select f.fixturematchday, u.teamselection1or2, u.teamselectionid,u.user_id from straightred_fixture f, straightred_userselection u where u.user_id = 349 and f.fixtureid = u.fixtureid and f.fixturematchday=6 order by u.teamselection1or2 LIMIT 2") #Note the LIMIT 2 currentSelectedTeams = cursor.fetchall() if not currentSelectedTeams: currentSelectedTeam1 = 0 currentSelectedTeam2 = 0 else: currentSelectedTeam1 = currentSelectedTeams[0].teamselectionid currentSelectedTeam2 = currentSelectedTeams[1].teamselectionid </code></pre> <p>Note that, in an edge case scenario, where only one row is returned, this implementation would fail. (You need to check for the cursor return length, etc.. )</p> <p>If this were a django queryset implementation, it would look something like this:</p> <pre><code>qs = Fixture.objects.filter(..).values("fixturematchday", "userselection__ teamselection1or2", "userselection__teamselectionid", "userselection__userid")[:2] </code></pre>
2
2016-09-19T20:01:56Z
[ "python", "mysql", "django" ]
AWS DynamoDB Python Connection Error
39,580,929
<p>Unable to run sample code on AWS Dynamodb.</p> <p>I am trying to run the AWS sample python code that they provide on there website. Here is my python file:</p> <pre><code> from __future__ import print_function # Python 2/3 compatibility import boto3 dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000") table = dynamodb.create_table( TableName='Movies', KeySchema=[ { 'AttributeName': 'year', 'KeyType': 'HASH' #Partition key }, { 'AttributeName': 'title', 'KeyType': 'RANGE' #Sort key } ], AttributeDefinitions=[ { 'AttributeName': 'year', 'AttributeType': 'N' }, { 'AttributeName': 'title', 'AttributeType': 'S' }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 10, 'WriteCapacityUnits': 10 } ) print("Table status:", table.table_status) </code></pre> <p>I then I run the python file in terminal and I get the following error:</p> <pre><code>File "MoviesCreateTable.py", line 32, in &lt;module&gt; 'WriteCapacityUnits': 10 File "/home/name/.local/lib/python2.7/site-packages/boto3/resources/factory.py", line 520, in do_action response = action(self, *args, **kwargs) File "/home/name/.local/lib/python2.7/site-packages/boto3/resources/action.py", line 83, in __call__ response = getattr(parent.meta.client, operation_name)(**params) File "/home/name/.local/lib/python2.7/site-packages/botocore/client.py", line 159, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/name/.local/lib/python2.7/site-packages/botocore/client.py", line 483, in _make_api_call operation_model, request_dict) File "/home/name/.local/lib/python2.7/site-packages/botocore/endpoint.py", line 141, in make_request return self._send_request(request_dict, operation_model) File "/home/name/.local/lib/python2.7/site-packages/botocore/endpoint.py", line 170, in _send_request success_response, exception): File "/home/name/.local/lib/python2.7/site-packages/botocore/endpoint.py", line 249, in _needs_retry caught_exception=caught_exception, request_dict=request_dict) File "/home/name/.local/lib/python2.7/site-packages/botocore/hooks.py", line 227, in emit return self._emit(event_name, kwargs) File "/home/name/.local/lib/python2.7/site-packages/botocore/hooks.py", line 210, in _emit response = handler(**kwargs) File "/home/name/.local/lib/python2.7/site-packages/botocore/retryhandler.py", line 183, in __call__ if self._checker(attempts, response, caught_exception): File "/home/name/.local/lib/python2.7/site-packages/botocore/retryhandler.py", line 251, in __call__ caught_exception) File "/home/name/.local/lib/python2.7/site-packages/botocore/retryhandler.py", line 277, in _should_retry return self._checker(attempt_number, response, caught_exception) File "/home/name/.local/lib/python2.7/site-packages/botocore/retryhandler.py", line 317, in __call__ caught_exception) File "/home/name/.local/lib/python2.7/site-packages/botocore/retryhandler.py", line 223, in __call__ attempt_number, caught_exception) File "/home/name/.local/lib/python2.7/site-packages/botocore/retryhandler.py", line 359, in _check_caught_exception raise caught_exception botocore.vendored.requests.exceptions.ConnectionError: ('Connection aborted.', error(111, 'Connection refused')) </code></pre>
0
2016-09-19T19:45:33Z
39,581,605
<p>This happens when Dynamodb isn't running. Check <code>localhost:8000/shell</code> to verify it's running.</p> <p>Ensure all the <a href="http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.html" rel="nofollow">prerequisites</a> given in docs are satisfied.</p> <blockquote> <p>Before you begin this tutorial, you need to do the following:</p> <ul> <li>Download and run DynamoDB on your computer. For more information, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.JsShell.html#GettingStarted.JsShell.Prereqs.Download" rel="nofollow">Download and Run DynamoDB</a>.</li> <li>Sign up for Amazon Web Services and create access keys. You need these credentials to use AWS SDKs. To create an AWS account, go to <a href="http://aws.amazon.com/" rel="nofollow">http://aws.amazon.com/</a>, choose Create an AWS Account, and then follow the online instructions.</li> <li>Create an AWS credentials file. For more information, see Configuration in the Boto 3 documentation.</li> <li>Install Python 2.6 or later. For more information, see <a href="https://www.python.org/downloads" rel="nofollow">https://www.python.org/downloads</a>.</li> </ul> </blockquote>
0
2016-09-19T20:30:52Z
[ "python", "python-2.7", "ubuntu", "amazon-web-services", "amazon-dynamodb" ]
Bulk update Postgres column from python dataframe
39,581,003
<p>I am using the below python code to update postgres DB column <code>value</code>based on <code>Id</code>. This loop has to run for thousands of records and it is taking longer time. </p> <p>Is there a way where I can pass array of dataframe values instead of looping each row?</p> <pre><code> for i in range(0,len(df)): QUERY=""" UPDATE "Table" SET "value"='%s' WHERE "Table"."id"='%s' """ % (df['value'][i], df['id'][i]) cur.execute(QUERY) conn.commit() </code></pre>
0
2016-09-19T19:51:22Z
39,583,112
<p>Depends on a library you use to communicate with PostgreSQL, but usually bulk inserts are much faster via <a href="https://www.postgresql.org/docs/9.5/static/sql-copy.html" rel="nofollow">COPY FROM</a> command.</p> <p>If you use psycopg2 it is as simple as following:</p> <pre><code>cursor.copy_from(io.StringIO(string_variable), "destination_table", columns=('id', 'value')) </code></pre> <p>Where <strong>string_variable</strong> is tab and new line delimited dataset like <code>1\tvalue1\n2\tvalue2\n</code>.</p> <p>To achieve a performant bulk update I would do: </p> <ol> <li><p>Create a temporary table: <code>CREATE TEMPORARY TABLE tmp_table;</code>; </p></li> <li><p>Insert records with <strong>copy_from</strong>;</p></li> <li><p>Just update destination table with query <code>UPDATE destination_table SET value = t.value FROM tmp_table t WHERE id = t.id</code> or any <a href="https://www.postgresql.org/docs/9.5/static/sql-update.html" rel="nofollow">other preferred syntax</a></p></li> </ol>
0
2016-09-19T22:37:55Z
[ "python", "sql", "postgresql", "bulkupdate" ]
How to add more command arguments to python-daemon?
39,581,046
<p>I have a basic Python daemon created using older version of python-daemon and this code:</p> <pre><code>import time from daemon import runner class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/foo.pid' self.pidfile_timeout = 5 def run(self): while True: print("Howdy! Gig'em! Whoop!") time.sleep(10) app = App() daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() </code></pre> <p>Now everything works fine but I need to add one more possible command to my daemon. Current default commands are "start, stop, restart". I need fourth command "mycommand" that will only run this code when executed:</p> <pre><code>my_function() print "Function was successfully run!" </code></pre> <p>I have tried Googling and researching but couldn't figure it out on my own. I tried picking up arguments manually without sinking into python-daemon code, with <code>sys.argv</code> but couldn't make it work.</p>
2
2016-09-19T19:54:06Z
39,581,999
<p>Looking at the code of the runner module, the following should work... I have problems with defining the stdout and stderr... could you test it?</p> <pre><code>from daemon import runner import time # Inerith from the DaemonRunner class to create a personal runner class MyRunner(runner.DaemonRunner): def __init__(self, *args, **kwd): super().__init__(*args, **kwd) # define the function that execute your stuff... def _mycommand(self): print('execute my command') # tell to the class how to reach that function action_funcs = runner.DaemonRunner.action_funcs action_funcs['mycommand'] = _mycommand class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' self.pidfile_path = '/tmp/foo.pid' self.pidfile_timeout = 5 def run(self): while True: print("Howdy! Gig'em! Whoop!") time.sleep(10) app = App() # bind to your "MyRunner" instead of the generic one daemon_runner = MyRunner(app) daemon_runner.do_action() </code></pre>
0
2016-09-19T20:58:15Z
[ "python", "python-2.7", "daemon", "python-daemon" ]
Solving non linear system containing a sum
39,581,071
<p>I have several functions which comes from sympy.lambdify:</p> <pre><code>f_1 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_1, modules=['numpy', 'sympy']) f_2 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_2, modules=['numpy', 'sympy']) f_3 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_3, modules=['numpy', 'sympy']) f_4 = sym.lambdify((z, m_1, m_2, s_1, s_2), expression_4, modules=['numpy', 'sympy']) </code></pre> <p>where <code>m_1</code>, <code>m_2</code>, <code>s_1</code>, <code>s_2</code> are scalars and <code>z</code> is a known 1D array (not necessary the same for each <code>f_i</code>). The output of each <code>f_i</code> is a scalar.</p> <p>I would like to (numerically) find <code>m_1</code>, <code>m_2</code>, <code>s_1</code>, <code>s_2</code> so that,</p> <pre><code>sum(f_1(z_i, m_1, m_2, s_1, s_2)) = 0 sum(f_2(z_i, m_1, m_2, s_1, s_2)) = 0 sum(f_3(z_i, m_1, m_2, s_1, s_2)) = 0 sum(f_4(z_i, m_1, m_2, s_1, s_2)) = 0 </code></pre> <p>The sum being on i.</p> <p>Using scipy.optimize, I do not know how to implement it (using fsolve or root).</p>
0
2016-09-19T19:55:50Z
39,945,958
<p>To drive 4 functions F1, F2, F3, F4 all to 0, minimize the sum of squares F1^2 + F2^2 + F3^2 + F4^2: if the sum is small, each F must be small too. (For example, sum &lt; 0.000001 &rArr; each |F| &lt; 0.001 .) Use <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#least-squares-minimization-least-squares" rel="nofollow">scipy.optimize.least_squares</a> to do this:</p> <pre><code>import numpy as np from scipy.optimize import least_squares # http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#least-squares-minimization-least-squares # http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html # minimize F1**2 + F2**2 + F3**2 + F4**2 -- starting_guess = ... ret = least_squares( [F1, F2, F3, F4], x0=starting_guess, max_nfev=20, verbose=2 ) xmin = ret.x </code></pre> <p>(Do NOT square the F s -- <code>least_squares</code> does that for you.)</p> <p>In your case, you want to move the sum outside <code>lambdify</code>:</p> <pre><code>f1 = sym.lambdify((z, m1, m2, s1, s2) ... )) Z1 = numpy array whose rows are all the z_i for f1 def F1( m1, m2, s1, s2 ): sum = np.sum([ f( z, m1, m2, s1, s2 ) for z in Z1 ]) print "F1: %-10.3g at %-10.3g %-10.3g %-10.3g %-10.3g" % (sum, m1, m2, s1, s2) return sum # check a few values in ipython -- F1( 0, 0, 0, 0 ) for x in np.eye( 4 ): F1( *x ) </code></pre> <p>When that works, F2 F3 F4 are similar. Check them too. Then optimize:</p> <pre><code>starting_guess = ... ret = least_squares( [F1, F2, F3, F4], x0=starting_guess, max_nfev=10, verbose=2 ) xmin = ret.x </code></pre> <p>or more iterations, or use <code>xtol</code> <code>ftol</code>.<br> <code>least_squares</code> has lots of options, see the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html" rel="nofollow">full doc</a> .</p> <p>There are fancier ways of doing the above for any number of functions, not just 4, of any number of variables: more general, more obscure.</p> <p>(Avuncular advice for optimization:</p> <ul> <li>start small</li> <li>check every step, with print statements, and interactively in ipython.</li> </ul>
0
2016-10-09T16:39:47Z
[ "python", "optimization", "scipy" ]
Parsing a python file to find classes with certain label
39,581,138
<p>I have a python file with many classes in it. The file looks something like that:</p> <pre><code>some code, functions and stuff... class A(): some code... @label class B(A): some code... @label class C(A): some code... class D(A): some code... some extra code... </code></pre> <p>What I want to do is to make a list of all the classes that has the @label before their declaration, i.e in this example: [B,C]. (That will happen in another file, if it matters)</p> <p>What I tried so far is parsing the file like it was a regular text file (with read() and stuff), but what I get is a list of the classes name and not the classes themselves, i.e (['B','C']) and I don't know what to do next. I would really hope there's a more elegant way. My next step, after I get that classes list, is to activate for each of the classes a certain function they all have. That's why the name of the class isn't enough for me. </p>
1
2016-09-19T20:00:33Z
39,581,385
<p>You have two options:</p> <ul> <li><p>use the <a href="https://docs.python.org/3/library/tokenize.html" rel="nofollow"><code>tokenize</code> module</a> to look out for <code>token.OP</code> tokens with the value <code>@</code>, followed by <code>token.NAME</code> tokens for <code>label</code> and, after a newline token, <code>class</code>. This is the most light-weight.</p></li> <li><p>use the <a href="https://docs.python.org/3/library/ast.html" rel="nofollow"><code>ast</code> module</a> to parse the source into a tree, then use the <code>ast.walk()</code> function, looking for <code>ast.ClassDef</code> objects. If the object has a <code>ast.Name</code> object with <code>id == 'label'</code> in the <code>decorator_list</code> attribute, you can record the <code>name</code> attribute.</p></li> </ul> <p>The latter is probably easiest:</p> <pre><code>import ast def labelled_classnames(source): module = ast.parse(source) for node in ast.walk(module): if not isinstance(node, ast.ClassDef): continue if any(isinstance(n, ast.Name) and n.id == 'label' for n in node.decorator_list): yield node.name </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; demosource = ''' ... class A(): ... pass ... ... @label ... class B(A): ... pass ... ... @label ... class C(A): ... pass ... ... class D(A): ... pass ... ''' &gt;&gt;&gt; list(labelled_classnames(demosource)) ['B', 'C'] </code></pre>
2
2016-09-19T20:16:59Z
[ "python", "class", "parsing" ]
Difference between tables
39,581,252
<p>I have two list of dictionaries representing the rows of two tables, so:</p> <pre><code>tableA = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}] tableB = [{"id": 1, "name": "bar"}, {"id": 3, "name": "baz"}] </code></pre> <p>I want to obtain the difference in the following way:</p> <pre><code>added = [{"id": 3, "name": "baz"}] updated = [{"id": 1, "name": "bar"}] </code></pre> <p>I know, that <code>id</code> is unique.</p> <p>So, I am planning to loop over <code>tableB</code>, ask for the <code>id</code>, if they are equal then compare the dicts to know if it is <code>updated</code>, if not the id is new and it is <code>added</code>.</p> <pre><code>for x in tableA: idexists = false for y in tableY: if x["id"] == y["id"]: if x != y: updated.append(x) idexists = true if not idexists: added.append(x) </code></pre> <p>Is it correct? Can it be done in pythonic way?</p>
1
2016-09-19T20:08:04Z
39,581,310
<p>I would <em>restructure</em> the tables into a more conveninent form of <code>id</code>: <code>name</code> dictionaries and then <a href="http://stackoverflow.com/q/1165352/771848">diff</a>:</p> <pre><code>from deepdiff import DeepDiff tableA = [{"id": 1, "name": "foo"}, {"id": 2, "name": "bar"}] tableB = [{"id": 1, "name": "bar"}, {"id": 3, "name": "baz"}] tableA = {item["id"]: item["name"] for item in tableA} tableB = {item["id"]: item["name"] for item in tableB} print(DeepDiff(tableA, tableB)) </code></pre> <p>Prints:</p> <pre><code>{ 'dictionary_item_added': {'root[3]'}, 'dictionary_item_removed': {'root[2]'}, 'values_changed': { 'root[1]': { 'old_value': 'foo', 'new_value': 'bar' } } } </code></pre> <p>For calculating the differences used <code>deepDiff</code> module suggested <a href="http://stackoverflow.com/a/26079022/771848">here</a>, but you can use any of the suggested solutions from the linked thread.</p> <hr> <p>Another idea could be to transform the list of dictionaries into a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>pandas.DataFrame</code></a> and then diff:</p> <ul> <li><a href="http://stackoverflow.com/questions/17095101/outputting-difference-in-two-pandas-dataframes-side-by-side-highlighting-the-d">Outputting difference in two pandas dataframes side by side - highlighting the difference</a></li> <li><a href="http://stackoverflow.com/questions/20648346/computing-diffs-within-groups-of-a-dataframe">Computing diffs within groups of a dataframe</a></li> </ul>
2
2016-09-19T20:12:07Z
[ "python", "algorithm", "list", "dictionary", "set" ]
Python ImageIO Gif Set Delay Between Frames
39,581,300
<p>I am using ImageIO: <a href="https://imageio.readthedocs.io/en/latest/userapi.html" rel="nofollow">https://imageio.readthedocs.io/en/latest/userapi.html</a> , and I want to know how to set delay between frames in a gif.</p> <p>Here are the relevant parts of my code.</p> <pre><code>import imageio . . . imageio.mimsave(args.output + '.gif', ARR_ARR) </code></pre> <p>where <code>ARR_ARR</code> is an array of <code>numpy uint8</code> 2d array of couplets.</p> <p>To be clear, I have no problem writing the gif. I cannot, however, find any clarification on being able to write the amount of delay between frames.</p> <p>So, for example, I have frames 0 ... 9</p> <p>They always play at the same rate. I would like to be able to control the number of milliseconds or whatever unit between frames being played.</p>
0
2016-09-19T20:11:44Z
39,581,406
<p>Found it using <code>imageio.help("GIF")</code> you would pass in something like</p> <p><code>imageio.mimsave(args.output + '.gif', ARR_ARR, fps=$FRAMESPERSECOND)</code></p> <p>And that seems to work.</p>
0
2016-09-19T20:18:15Z
[ "python", "image", "numpy", "gif" ]
Find a substring in block of text, unless it is part of another substring
39,581,339
<p>I was looking for an efficient way to find a substring between two expressions, unless the expression is a part of another.</p> <p>For example:</p> <blockquote> <p>Once upon a time, in a time far far away, dogs ruled the world. The End.</p> </blockquote> <p>If I was searching for the substring between <strong>time</strong> and <strong>end</strong>, I would receive:</p> <blockquote> <p>in a time far far away, dogs ruled the world. The</p> </blockquote> <p>or </p> <blockquote> <p>far far away, dogs ruled the world. The</p> </blockquote> <p>I want to ignore if <strong>time</strong> is a part of <strong>Once upon a time</strong>. I didn't know if there was a pythonic method without using crazy for loops and if/else cases.</p>
1
2016-09-19T20:14:13Z
39,581,430
<p>Just remove 'Once upon a time' and check what's left.</p> <pre><code>my_string = 'Once upon a time, in a time far far away, dogs ruled the world. The End.' if 'time' in my_string.replace('Once upon a time', ''): pass </code></pre>
1
2016-09-19T20:19:15Z
[ "python", "python-2.7" ]
Find a substring in block of text, unless it is part of another substring
39,581,339
<p>I was looking for an efficient way to find a substring between two expressions, unless the expression is a part of another.</p> <p>For example:</p> <blockquote> <p>Once upon a time, in a time far far away, dogs ruled the world. The End.</p> </blockquote> <p>If I was searching for the substring between <strong>time</strong> and <strong>end</strong>, I would receive:</p> <blockquote> <p>in a time far far away, dogs ruled the world. The</p> </blockquote> <p>or </p> <blockquote> <p>far far away, dogs ruled the world. The</p> </blockquote> <p>I want to ignore if <strong>time</strong> is a part of <strong>Once upon a time</strong>. I didn't know if there was a pythonic method without using crazy for loops and if/else cases.</p>
1
2016-09-19T20:14:13Z
39,581,597
<p>The typical solution here is to use capturing and non-capturing regular expression groups. Since regex alternations get parsed from left to right, placing any <em>exceptions</em> to the rule first (as a non-capture) and end with the alternation that you want to select for.</p> <pre><code>import re text = "Once upon a time, in a time far far away, dogs ruled the world. The End." query = re.compile(r""" Once upon a time| # literally 'Once upon a time', # should not be selected time\b # from the word 'time' (.*) # capture everything \bend # until the word 'end' """, re.X | re.I) result = query.findall(text) # result = ['', ' far far away, dogs ruled the world. The '] </code></pre> <p>You can strip out the empty group (that got put in when we matched the unwanted string)</p> <pre><code>result = list(filter(None, result)) # or result = [r for r in result if r] # [' far far away, dogs ruled the world. The '] </code></pre> <p>and then strip the results</p> <pre><code>result = list(map(str.strip, filter(None, result))) # or result = [r.strip() for r in result if r] # ['far far away, dogs ruled the world. The'] </code></pre> <p>This solution is particularly useful when you have a number of phrases you're trying to dodge.</p> <pre><code>phrases = ["Once upon a time", "No time like the present", "Time to die", "All we have left is time"] querystring = r"time\b(.*)\bend" query = re.compile("|".join(map(re.escape, phrases)) + "|" + querystring, re.I) result = [r.strip() for r in query.findall(some_text) if r] </code></pre>
0
2016-09-19T20:30:08Z
[ "python", "python-2.7" ]
Find a substring in block of text, unless it is part of another substring
39,581,339
<p>I was looking for an efficient way to find a substring between two expressions, unless the expression is a part of another.</p> <p>For example:</p> <blockquote> <p>Once upon a time, in a time far far away, dogs ruled the world. The End.</p> </blockquote> <p>If I was searching for the substring between <strong>time</strong> and <strong>end</strong>, I would receive:</p> <blockquote> <p>in a time far far away, dogs ruled the world. The</p> </blockquote> <p>or </p> <blockquote> <p>far far away, dogs ruled the world. The</p> </blockquote> <p>I want to ignore if <strong>time</strong> is a part of <strong>Once upon a time</strong>. I didn't know if there was a pythonic method without using crazy for loops and if/else cases.</p>
1
2016-09-19T20:14:13Z
39,581,612
<p>This is possible in regex by using a negative lookahead</p> <pre><code>&gt;&gt;&gt; s = 'Once upon a time, in a time far far away, dogs ruled the world. The End.' &gt;&gt;&gt; pattern = r'time((?:(?!time).)*)End' &gt;&gt;&gt; re.findall(pattern, s) [' far far away, dogs ruled the world. The '] </code></pre> <p>With multiple matches:</p> <pre><code>&gt;&gt;&gt; s = 'a time b End time c time d End time' &gt;&gt;&gt; re.findall(pattern, s) [' b ', ' d '] </code></pre>
2
2016-09-19T20:31:19Z
[ "python", "python-2.7" ]
Live graph in matplotlib prevents Python to shutdown
39,581,416
<p>Long time ago I designed a little PyQt Gui that plots a live graph. A sensor signal enters the computer, and that signal gets plotted by my Gui in real-time.</p> <p><a href="http://i.stack.imgur.com/Mggq7.png" rel="nofollow"><img src="http://i.stack.imgur.com/Mggq7.png" alt="enter image description here"></a></p> <p>Back then I worked with <code>PyQt4</code> and <code>matplotlib 1.5</code>. Here is the code that generates such live graph (the sensor signal is emulated). Just copy-paste this code into a python file. Run it, and you will see nice dancing graphs:</p> <pre><code>################################################################### # # # PLOTTING A LIVE GRAPH # # ---------------------------- # # EMBED A MATPLOTLIB ANIMATION INSIDE YOUR # # OWN GUI! # # -&gt; Python 3.5.x # # -&gt; matplotlib: 1.5 # # -&gt; PyQt: 4 # # # ################################################################### import sys import os from PyQt4 import QtGui from PyQt4 import QtCore import functools import numpy as np import random as rd import matplotlib matplotlib.use("Qt4Agg") from matplotlib.figure import Figure from matplotlib.animation import TimedAnimation from matplotlib.lines import Line2D from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas import time import threading def setCustomSize(x, width, height): sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(x.sizePolicy().hasHeightForWidth()) x.setSizePolicy(sizePolicy) x.setMinimumSize(QtCore.QSize(width, height)) x.setMaximumSize(QtCore.QSize(width, height)) '''''' class CustomMainWindow(QtGui.QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # Define the geometry of the main window self.setGeometry(300, 300, 800, 400) self.setWindowTitle("my first window") # Create FRAME_A self.FRAME_A = QtGui.QFrame(self) self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(210,210,235,255).name()) self.LAYOUT_A = QtGui.QGridLayout() self.FRAME_A.setLayout(self.LAYOUT_A) self.setCentralWidget(self.FRAME_A) # Place the zoom button self.zoomBtn = QtGui.QPushButton(text = 'zoom') setCustomSize(self.zoomBtn, 100, 50) self.zoomBtn.clicked.connect(self.zoomBtnAction) self.LAYOUT_A.addWidget(self.zoomBtn, *(0,0)) # Place the matplotlib figure self.myFig = CustomFigCanvas() self.LAYOUT_A.addWidget(self.myFig, *(0,1)) # Add the callbackfunc to .. myDataLoop = threading.Thread(name = 'myDataLoop', target = dataSendLoop, args = (self.addData_callbackFunc,)) myDataLoop.start() self.show() '''''' def zoomBtnAction(self): print("zoom in") self.myFig.zoomIn(5) '''''' def addData_callbackFunc(self, value): # print("Add data: " + str(value)) self.myFig.addData(value) ''' End Class ''' class CustomFigCanvas(FigureCanvas, TimedAnimation): def __init__(self): self.addedData = [] print(matplotlib.__version__) # The data self.xlim = 200 self.n = np.linspace(0, self.xlim - 1, self.xlim) a = [] b = [] a.append(2.0) a.append(4.0) a.append(2.0) b.append(4.0) b.append(3.0) b.append(4.0) self.y = (self.n * 0.0) + 50 # The window self.fig = Figure(figsize=(5,5), dpi=100) self.ax1 = self.fig.add_subplot(111) # self.ax1 settings self.ax1.set_xlabel('time') self.ax1.set_ylabel('raw data') self.line1 = Line2D([], [], color='blue') self.line1_tail = Line2D([], [], color='red', linewidth=2) self.line1_head = Line2D([], [], color='red', marker='o', markeredgecolor='r') self.ax1.add_line(self.line1) self.ax1.add_line(self.line1_tail) self.ax1.add_line(self.line1_head) self.ax1.set_xlim(0, self.xlim - 1) self.ax1.set_ylim(0, 100) FigureCanvas.__init__(self, self.fig) TimedAnimation.__init__(self, self.fig, interval = 50, blit = True) def new_frame_seq(self): return iter(range(self.n.size)) def _init_draw(self): lines = [self.line1, self.line1_tail, self.line1_head] for l in lines: l.set_data([], []) def addData(self, value): self.addedData.append(value) def zoomIn(self, value): bottom = self.ax1.get_ylim()[0] top = self.ax1.get_ylim()[1] bottom += value top -= value self.ax1.set_ylim(bottom,top) self.draw() def _step(self, *args): # Extends the _step() method for the TimedAnimation class. try: TimedAnimation._step(self, *args) except Exception as e: self.abc += 1 print(str(self.abc)) TimedAnimation._stop(self) pass def _draw_frame(self, framedata): margin = 2 while(len(self.addedData) &gt; 0): self.y = np.roll(self.y, -1) self.y[-1] = self.addedData[0] del(self.addedData[0]) self.line1.set_data(self.n[ 0 : self.n.size - margin ], self.y[ 0 : self.n.size - margin ]) self.line1_tail.set_data(np.append(self.n[-10:-1 - margin], self.n[-1 - margin]), np.append(self.y[-10:-1 - margin], self.y[-1 - margin])) self.line1_head.set_data(self.n[-1 - margin], self.y[-1 - margin]) self._drawn_artists = [self.line1, self.line1_tail, self.line1_head] ''' End Class ''' # You need to setup a signal slot mechanism, to # send data to your GUI in a thread-safe way. # Believe me, if you don't do this right, things # go very very wrong.. class Communicate(QtCore.QObject): data_signal = QtCore.pyqtSignal(float) ''' End Class ''' def dataSendLoop(addData_callbackFunc): # Setup the signal-slot mechanism. mySrc = Communicate() mySrc.data_signal.connect(addData_callbackFunc) # Simulate some data n = np.linspace(0, 499, 500) y = 50 + 25*(np.sin(n / 8.3)) + 10*(np.sin(n / 7.5)) - 5*(np.sin(n / 1.5)) i = 0 while(True): if(i &gt; 499): i = 0 time.sleep(0.1) mySrc.data_signal.emit(y[i]) # &lt;- Here you emit a signal! i += 1 ### ### if __name__== '__main__': app = QtGui.QApplication(sys.argv) QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique')) myGUI = CustomMainWindow() sys.exit(app.exec_()) '''''' </code></pre> <p>Recently I had to switch to <code>matplotlib 2.0.0b4</code>. Earlier versions of matplotlib are not compatible with PyQt5. I want to plug a live graph into an existing PyQt5 application. So I had to switch to <code>matplotlib 2.0.0b4</code>.</p> <p>Here is the adapted code:</p> <pre><code>################################################################### # # # PLOTTING A LIVE GRAPH # # ---------------------------- # # EMBED A MATPLOTLIB ANIMATION INSIDE YOUR # # OWN GUI! # # -&gt; Python 3.5.2 # # -&gt; matplotlib: 2.0.0b4 # # -&gt; PyQt: 5 # # # ################################################################### import sys import os from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import functools import numpy as np import random as rd import matplotlib matplotlib.use("Qt5Agg") from matplotlib.figure import Figure from matplotlib.animation import TimedAnimation from matplotlib.lines import Line2D from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import time import threading def setCustomSize(x, width, height): sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(x.sizePolicy().hasHeightForWidth()) x.setSizePolicy(sizePolicy) x.setMinimumSize(QSize(width, height)) x.setMaximumSize(QSize(width, height)) '''''' class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # Define the geometry of the main window self.setGeometry(300, 300, 800, 400) self.setWindowTitle("my first window") # Create FRAME_A self.FRAME_A = QFrame(self) self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QColor(210,210,235,255).name()) self.LAYOUT_A = QGridLayout() self.FRAME_A.setLayout(self.LAYOUT_A) self.setCentralWidget(self.FRAME_A) # Place the zoom button self.zoomBtn = QPushButton(text = 'zoom') setCustomSize(self.zoomBtn, 100, 50) self.zoomBtn.clicked.connect(self.zoomBtnAction) self.LAYOUT_A.addWidget(self.zoomBtn, *(0,0)) # Place the matplotlib figure self.myFig = CustomFigCanvas() self.LAYOUT_A.addWidget(self.myFig, *(0,1)) # Add the callbackfunc to .. myDataLoop = threading.Thread(name = 'myDataLoop', target = dataSendLoop, args = (self.addData_callbackFunc,)) myDataLoop.start() self.show() '''''' def zoomBtnAction(self): print("zoom in") self.myFig.zoomIn(5) '''''' def addData_callbackFunc(self, value): # print("Add data: " + str(value)) self.myFig.addData(value) ''' End Class ''' class CustomFigCanvas(FigureCanvas, TimedAnimation): def __init__(self): self.addedData = [] print(matplotlib.__version__) # The data self.xlim = 200 self.n = np.linspace(0, self.xlim - 1, self.xlim) a = [] b = [] a.append(2.0) a.append(4.0) a.append(2.0) b.append(4.0) b.append(3.0) b.append(4.0) self.y = (self.n * 0.0) + 50 # The window self.fig = Figure(figsize=(5,5), dpi=100) self.ax1 = self.fig.add_subplot(111) # self.ax1 settings self.ax1.set_xlabel('time') self.ax1.set_ylabel('raw data') self.line1 = Line2D([], [], color='blue') self.line1_tail = Line2D([], [], color='red', linewidth=2) self.line1_head = Line2D([], [], color='red', marker='o', markeredgecolor='r') self.ax1.add_line(self.line1) self.ax1.add_line(self.line1_tail) self.ax1.add_line(self.line1_head) self.ax1.set_xlim(0, self.xlim - 1) self.ax1.set_ylim(0, 100) FigureCanvas.__init__(self, self.fig) TimedAnimation.__init__(self, self.fig, interval = 50, blit = True) def new_frame_seq(self): return iter(range(self.n.size)) def _init_draw(self): lines = [self.line1, self.line1_tail, self.line1_head] for l in lines: l.set_data([], []) def addData(self, value): self.addedData.append(value) def zoomIn(self, value): bottom = self.ax1.get_ylim()[0] top = self.ax1.get_ylim()[1] bottom += value top -= value self.ax1.set_ylim(bottom,top) self.draw() def _step(self, *args): # Extends the _step() method for the TimedAnimation class. try: TimedAnimation._step(self, *args) except Exception as e: self.abc += 1 print(str(self.abc)) TimedAnimation._stop(self) pass def _draw_frame(self, framedata): margin = 2 while(len(self.addedData) &gt; 0): self.y = np.roll(self.y, -1) self.y[-1] = self.addedData[0] del(self.addedData[0]) self.line1.set_data(self.n[ 0 : self.n.size - margin ], self.y[ 0 : self.n.size - margin ]) self.line1_tail.set_data(np.append(self.n[-10:-1 - margin], self.n[-1 - margin]), np.append(self.y[-10:-1 - margin], self.y[-1 - margin])) self.line1_head.set_data(self.n[-1 - margin], self.y[-1 - margin]) self._drawn_artists = [self.line1, self.line1_tail, self.line1_head] ''' End Class ''' # You need to setup a signal slot mechanism, to # send data to your GUI in a thread-safe way. # Believe me, if you don't do this right, things # go very very wrong.. class Communicate(QObject): data_signal = pyqtSignal(float) ''' End Class ''' def dataSendLoop(addData_callbackFunc): # Setup the signal-slot mechanism. mySrc = Communicate() mySrc.data_signal.connect(addData_callbackFunc) # Simulate some data n = np.linspace(0, 499, 500) y = 50 + 25*(np.sin(n / 8.3)) + 10*(np.sin(n / 7.5)) - 5*(np.sin(n / 1.5)) i = 0 while(True): if(i &gt; 499): i = 0 time.sleep(0.1) mySrc.data_signal.emit(y[i]) # &lt;- Here you emit a signal! i += 1 ### ### if __name__== '__main__': app = QApplication(sys.argv) QApplication.setStyle(QStyleFactory.create('Plastique')) myGUI = CustomMainWindow() sys.exit(app.exec_()) '''''' </code></pre> <p>The code runs just fine. The animated graph is displayed on my screen, and it runs smoothly. But when I close the GUI, python won't exit. It just hangs. As I always start my python programs from a Windows cmd shell, I hit the <code>Ctrl-C</code> buttons to kill the process. But that doesn't help either. I have to close the cmd shell completely to kill the Python process.</p> <p><strong>EDIT :</strong></p> <p>Apparently matplotlib 1.5 is compatible with PyQt5 (thank you Mr. Tacaswell to point that out). My main reason to stick to matplotlib v2 was the use of PyQt5. This argument holds no longer, so I decided to downgrade matplotlib to 1.5. I did a clean re-installation of anaconda to go back to matplotlib 1.5.3, and wipe out all traces from matplotlib 2.0.0b. My system is now as follows:</p> <ul> <li>OS: Windows 10 64-bit</li> <li>python: 3.5.2 |Anaconda custom (64-bit)|</li> <li>pyqt4: <ul> <li>Qt version: 4.8.7</li> <li>SIP version: 4.18.1</li> <li>PyQt version: 4.11.4</li> </ul></li> <li>pyqt5: <ul> <li>Qt version: 5.7.0</li> <li>SIP version: 4.18.1</li> <li>PyQt version: 5.7</li> </ul></li> <li>matplotlib: 1.5.3</li> </ul> <p><strong>TEST 1: Live graph with matplotlib 1.5.3 and PyQt4</strong></p> <p>I just run the code that I've given above - based on PyQt4. The live graph plots smoothly. But closing down the GUI is not enough to entirely stop the python process. There is still some zombie process running on the background. I have to dive into the Windows Task manager to kill it. Only after doing that, the cmd shell prompts again for new input. So, the problem is still the same. I am a bit puzzled, because I do remember that this code worked just fine on matplotlib 1.5 and PyQt4.</p> <p><strong>TEST 2: Live graph with matplotlib 1.5.3 and PyQt5</strong></p> <p>I get exactly the same problem.</p>
0
2016-09-19T20:18:49Z
39,701,853
<p>Apparently the problem is in the creation of the background thread:</p> <pre><code>myDataLoop = threading.Thread(name = ..., target = ..., args = ...) </code></pre> <p>To make sure that such background thread will terminate when the MainThread ends, you have to define it as <code>daemon</code>:</p> <pre><code>myDataLoop = threading.Thread(name = ..., daemon = True, target = ..., args = ...) </code></pre> <p>Now it closes down properly :-)</p>
0
2016-09-26T11:39:39Z
[ "python", "python-3.x", "matplotlib" ]
Can someone explain how this sort result is produced?
39,581,483
<p>Lets say that you have the given function:</p> <pre><code>def last(word): return word[-1] print (sorted(['apple','orange','banana','grape','watermelon'], key=last)) </code></pre> <p>This will return a list that is sorted by the last index in each string:</p> <pre><code>['banana', 'apple', 'orange', 'grape', 'watermelon'] </code></pre> <p>So now can someone explain what happens when we ask for user input to specify an index for each string that we are passing to our function <code>last</code>. For example if we change the code to be:</p> <pre><code>def last(word): index = int(input('Enter index:')) return word[index] print (sorted(['apple','orange','banana','grape','watermelon'], key=last)) </code></pre> <p>Which then if the user inputs the following sequence (1,1,2,2,-1) it results in the list:</p> <pre><code>['grape', 'banana', 'watermelon', 'apple', 'orange'] </code></pre> <p>Which doesn't appear to be sorted by indexes 1, 2 or -1.</p> <p>Can anyone explain what is going on behind the scenes and how Python is handling this case? I understand this a very strange question but I'd like to understand how Python is interpreting these instructions.</p>
-2
2016-09-19T20:22:19Z
39,581,578
<p>The sort is <em>exactly right</em>. You asked for the words to be sorted by indices <code>(1, 1, 2, 2, -1)</code>. Lets examine what characters those are:</p> <pre><code>&gt;&gt;&gt; for index, word in zip((1, 1, 2, 2, -1), ['apple', 'orange', 'banana', 'grape', 'watermelon']): ... print(word[index], word) ... p apple r orange n banana a grape n watermelon </code></pre> <p>So the correct sorted order by those letters would be <code>('a', 'grape'), ('n', 'banana'), ('n', 'watermelon'), ('p', 'apple')</code> and <code>('r', 'orange'</code>) (where <code>('n', 'banana')</code> and <code>('n', 'watermelon')</code> are kept in input order as they both are sorted on <code>'n'</code>). This is exactly result you got.</p>
2
2016-09-19T20:28:47Z
[ "python", "sorting", "key" ]
What is the equivalent of python 'in' but for sqlalchemy
39,581,531
<p>I have a dictionary that is being used to query the database for a match. I have one single query line that isn't working for me. If i have a list like this:</p> <pre><code>user['names']= [Alice, Bob, John] </code></pre> <p>Since this is a list I tried to use something like this:</p> <pre><code> q.filter(UserTable.firstname in user['firstnames']) </code></pre> <p>But for whatever reason this doesn't work. However, I know that Bob is in the database. When I manually pull down all the queries I can see the name is there in one of the rows. If I do this instead:</p> <pre><code>q.filter(UserTable.firstname == user['firstnames'][1]) #Only does Bob </code></pre> <p>It works. And when I pull all the queries manually, convert each row to a dictionary, and then do a </p> <pre><code>row[#row_that_matches].firstname in user['names'] </code></pre> <p>that also works. But for some reason using the "in" keyword in sqlalchemy doesn't work as expected. Does anyone know an alternative that can make an sqlalchemy query for something in a list of values?</p>
2
2016-09-19T20:25:54Z
39,581,819
<p>Use the <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/sqlelement.html#sqlalchemy.sql.operators.ColumnOperators.in_" rel="nofollow"><code>in_()</code> column method</a> to test a column against a sequence:</p> <pre><code>q.filter(UserTable.firstname.in_(user['firstnames']) </code></pre> <p>See the <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#common-filter-operators" rel="nofollow"><em>Common Filter Operations</em> section</a> of the Object Relational tutorial:</p> <blockquote> <p><code>IN</code>:</p> <pre><code>query.filter(User.name.in_(['ed', 'wendy', 'jack'])) # works with query objects too: query.filter(User.name.in_( session.query(User.name).filter(User.name.like('%ed%')) )) </code></pre> </blockquote>
1
2016-09-19T20:45:17Z
[ "python", "mysql", "list", "sqlalchemy" ]
why does python takes longer time to sort a copy of list?
39,581,621
<p>Why is there so much difference when sorting x and y and y is just a copy of x? Does python not copy the list right away? </p> <pre><code>python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=list(x); x.sort()' 100000 loops, best of 3: 19.5 usec per loop python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=list(x); y.sort()' 1000 loops, best of 3: 211 usec per loop python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'x.sort()' 100000 loops, best of 3: 15.9 usec per loop </code></pre>
1
2016-09-19T20:31:52Z
39,581,672
<p>Your first and last examples have to sort the list <strong>just once</strong>. After that, the sorting algorithm Python uses has an easy time of it as it is optimised to take advantage of <em>already sorted sequences</em>.</p> <p>From the <a href="https://en.wikipedia.org/wiki/Timsort" rel="nofollow">Wikipedia article on TimSort</a> (the Python sorting algorithm):</p> <blockquote> <p>The algorithm finds subsequences of the data that are already ordered, and uses that knowledge to sort the remainder more efficiently.</p> </blockquote> <p>In other words, the <code>list(y); y.sort()</code> case is <em>disadvantaged</em> because it is given a clean, unsorted list each time. The <code>x.sort()</code> case is given a fully sorted list (after the first iteration). After all, <code>list.sort()</code> sorts <em>in place</em>, altering the list. The <code>timeit</code> test does not create a copy for each test, so subsequent tests re-use the same list.</p> <p>If you switch to using the <code>sorted()</code> function, you'll see no time advantage anymore, as <code>sorted()</code> returns a <em>new, copied and sorted list</em> instead of sorting in-place:</p> <pre><code>python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=list(x); sorted(x)' 10000 loops, best of 3: 151 usec per loop python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'y=list(x); sorted(y)' 10000 loops, best of 3: 155 usec per loop python -mtimeit -s'import random; x=range(1000); random.shuffle(x)' 'sorted(x)' 10000 loops, best of 3: 152 usec per loop </code></pre>
3
2016-09-19T20:35:08Z
[ "python", "performance", "sorting", "timeit" ]
Python Script Loop
39,581,674
<p>I wrote the following python script to implement my version of the game nims/stones</p> <pre><code>def nims_stones(pile, max_stones): while pile != 0: move = 0 while move &lt; 1 or move &gt; max_stones: move = int(raw_input("Player 1 How Many Stones")) pile -= move if pile == 0: print "Player 1 wins" else: print "There are %s stones left." %(pile) move = 0 while move &lt; 1 or move &gt; max_stones: move = int(raw_input("Player 2 How Many Stones")) pile -= move if pile == 0: print "Player 2 wins" else: print "There are %s stones left." %(pile) print "Game Over" </code></pre> <p>When I call the function nims_stones(10,5) It seems to work but after player one or player two wins it doesn't exit the loop it doesn't print "Game Over" it just asks for the next move</p> <p>I don't know why it doesn't exit the loop after a player wins. Any help will be greatly appreciated.</p>
-1
2016-09-19T20:35:14Z
39,581,873
<p>You should stop the loop when player 1 has emptied the pile. As you have almost the same code for the second player, consider reusing the code. Then you'll also have the empty pile check at the end of the loop:</p> <pre><code>def nims_stones(pile, max_stones): player = 2 while pile != 0: player = 3 - player move = 0 while move &lt; 1 or move &gt; max_stones or move &gt; pile: move = int(raw_input("Player %i. How Many Stones" % (player))) pile -= move print ("There are %s stones left." %(pile)) print ("Player %i wins" % (player)) print ("Game Over") </code></pre> <p>NB/ I also added the condition <code>move &gt; pile</code> to avoid players taking more than available.</p>
2
2016-09-19T20:49:29Z
[ "python" ]
Python Script Loop
39,581,674
<p>I wrote the following python script to implement my version of the game nims/stones</p> <pre><code>def nims_stones(pile, max_stones): while pile != 0: move = 0 while move &lt; 1 or move &gt; max_stones: move = int(raw_input("Player 1 How Many Stones")) pile -= move if pile == 0: print "Player 1 wins" else: print "There are %s stones left." %(pile) move = 0 while move &lt; 1 or move &gt; max_stones: move = int(raw_input("Player 2 How Many Stones")) pile -= move if pile == 0: print "Player 2 wins" else: print "There are %s stones left." %(pile) print "Game Over" </code></pre> <p>When I call the function nims_stones(10,5) It seems to work but after player one or player two wins it doesn't exit the loop it doesn't print "Game Over" it just asks for the next move</p> <p>I don't know why it doesn't exit the loop after a player wins. Any help will be greatly appreciated.</p>
-1
2016-09-19T20:35:14Z
39,581,903
<p>Adding a break statement after each player wins will solve your problem. You should also consider adding logic for when the pile reaches a negative value.</p> <pre><code>while pile != 0: move = 0 while move &lt; 1 or move &gt; max_stones: move = int(raw_input("Player 1 How Many Stones")) pile -= move if pile == 0: print "Player 1 wins" break else: print "There are %s stones left." %(pile) move = 0 while move &lt; 1 or move &gt; max_stones: move = int(raw_input("Player 2 How Many Stones")) pile -= move if pile == 0: print "Player 2 wins" break else: print "There are %s stones left." %(pile) print "Game Over" </code></pre>
0
2016-09-19T20:51:49Z
[ "python" ]
django calling a python script shows the html code instead of a webpage
39,581,675
<p>my django app calls a python script(query.cgi). but when I run it, the website shows the html printout from that script instead of showing the output as a webpage.</p> <pre><code>def query(request): if request.method == 'GET': output = subprocess.check_output(['python', 'query.cgi']).decode('utf-8') return HttpResponse(output, content_type="text/plain") </code></pre> <p>The webpage shows:</p> <pre><code>Content-Type: text/html &lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="content-type" content="text/html; charset=utf-8"&gt; &lt;link type="text/css" rel="stylesheet" href="css/css_4.css" media="screen" /&gt; &lt;title&gt;....&lt;/title&gt; &lt;/head&gt;&lt;body&gt;.....&lt;/body&gt;&lt;/html&gt; </code></pre> <p>Thanks for any help!!</p>
0
2016-09-19T20:35:17Z
39,582,965
<blockquote> <pre><code>return HttpResponse(output, content_type="text/plain") </code></pre> </blockquote> <p>The reason it's returning escaped HTML is because you have <code>content_type='text/plain'</code>, which says you are just sending plain text.</p> <p>Try changing it to <code>'text/html'</code>.</p>
1
2016-09-19T22:20:45Z
[ "python", "django" ]
I think I'm misunderstanding how variables from other functions can be called
39,581,707
<p>I'll try with words first. Using Python 3, and I have a main function that sets arg as a variable. When the main() is run, it calls a copy function which calls other functions. After these other functions run, copy() needs that arg variable set by main() at the beginning to finish and allow the main() to complete. </p> <p>From what I understand, the arg variable is local to main(). Calling arg from outside the function returns a NameError.</p> <p>I am looking at this thinking "I should be able to call the arg variable from copy() because I am running main() which is calling copy().</p> <p>I keep arriving at a NameError. The final function I call before I want the main function to end wants to know what arg holds but doesn't recognize arg as defined.</p> <p>Assuming all other necessary stuff is working, what must one do to get the copy() to recognize arg as defined. </p> <pre><code>... def copy(): x = destination() if os.path.isdir(x): y = backup_destination() if not os.path.isdir(y): shutil.copytree(arg.source, backup_destination) shutil.rmtree(x) shutil.copytree(arg.source, x) def main(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', type = str) arg = parser.parse_args() if os.path.isdir(arg.source): copy() ... if __name__ == '__main__': main() </code></pre>
0
2016-09-19T20:37:57Z
39,581,741
<p>The variable is local to the <code>main</code> function, to use it in <code>copy</code> you have to pass it as an argument, or make it a global variable. try to avoid the latter at all costs except you're sure that you need it, using global variables can lead to a lot of problems that are hard to debug, because a function that you forgot about altered the variable.</p> <pre><code>def copy(arg): x = destination() if os.path.isdir(x): y = backup_destination() if not os.path.isdir(y): shutil.copytree(arg.source, backup_destination) shutil.rmtree(x) shutil.copytree(arg.source, x) def main(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', type = str) arg = parser.parse_args() if os.path.isdir(arg.source): copy(arg) if __name__ == '__main__': main() </code></pre> <p>Read <a href="http://python-textbok.readthedocs.io/en/latest/Variables_and_Scope.html" rel="nofollow">this</a> for more information on variable scopes in python.</p>
3
2016-09-19T20:41:01Z
[ "python", "python-3.x" ]
I think I'm misunderstanding how variables from other functions can be called
39,581,707
<p>I'll try with words first. Using Python 3, and I have a main function that sets arg as a variable. When the main() is run, it calls a copy function which calls other functions. After these other functions run, copy() needs that arg variable set by main() at the beginning to finish and allow the main() to complete. </p> <p>From what I understand, the arg variable is local to main(). Calling arg from outside the function returns a NameError.</p> <p>I am looking at this thinking "I should be able to call the arg variable from copy() because I am running main() which is calling copy().</p> <p>I keep arriving at a NameError. The final function I call before I want the main function to end wants to know what arg holds but doesn't recognize arg as defined.</p> <p>Assuming all other necessary stuff is working, what must one do to get the copy() to recognize arg as defined. </p> <pre><code>... def copy(): x = destination() if os.path.isdir(x): y = backup_destination() if not os.path.isdir(y): shutil.copytree(arg.source, backup_destination) shutil.rmtree(x) shutil.copytree(arg.source, x) def main(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source', type = str) arg = parser.parse_args() if os.path.isdir(arg.source): copy() ... if __name__ == '__main__': main() </code></pre>
0
2016-09-19T20:37:57Z
39,581,745
<p>Each function runs in a different frame. Try printing <code>locals()</code> in each of your functions to see the local variables.</p> <p>There are 2 ways to access args:</p> <p>First, the <strong>normal and correct way to do things</strong>: Give it to <code>copy()</code> as an argument:</p> <pre><code>def copy(arg): ... def main(): copy(arg) </code></pre> <p>Second, the bad way to do things: Analyze the top frame using <code>sys._getframe(1)</code>:</p> <pre><code>def copy(): args = sys._getframe(1).f_locals["args"] print(args()) def main(): args = 1234 copy() &gt;&gt;&gt; main() 1234 </code></pre> <p>Regarding getting a variable from a different scope, I believe you're mistaken with this code:</p> <pre><code>def main(): arg = 1234 def code(): print(arg) code() </code></pre> <p>In here, since the function was defined inside another function, it gets access to it's local variables.</p>
1
2016-09-19T20:41:15Z
[ "python", "python-3.x" ]
Two Sorted Arrays, sum of 2 elements equal a certain number
39,581,834
<p>I was wondering if I could get some help. I want to find an algorithm that is THETA(n) or linear time for determining whether 2 numbers in a 2 sorted arrays add up to a certain number.</p> <p>For instance, let's say we have 2 sorted arrays: X and Y</p> <p>I want to determine if there's an element of X and an element of Y that add up to exactly a certain number, let's say 50.</p> <p>I have been able to come up with these algorithms in Python so far, but I am pretty sure they are order of THETA(n^2) rather than THETA(n).</p> <pre><code>def arrayTestOne(X,Y): S =[1 for x in X for y in Y if x+y == 50] def arrayTestTwo(X,Y): for x in X: for y in Y: if x + y == 50: print("1") </code></pre> <p>I'm thinking it's the double for loops that break the linear time, but how else would you iterate through 2 lists? Any thoughts would be appreciated.</p>
0
2016-09-19T20:46:47Z
39,581,944
<p>Here is a 2n for you which doesn't even need sorting:</p> <pre><code>def check_array(x, y, needed_sum): y = set(y) return next(((i, needed_sum-i) for i in x if (needed_sum-i) in y), None) </code></pre>
3
2016-09-19T20:54:17Z
[ "python", "arrays", "algorithm", "big-o" ]
Two Sorted Arrays, sum of 2 elements equal a certain number
39,581,834
<p>I was wondering if I could get some help. I want to find an algorithm that is THETA(n) or linear time for determining whether 2 numbers in a 2 sorted arrays add up to a certain number.</p> <p>For instance, let's say we have 2 sorted arrays: X and Y</p> <p>I want to determine if there's an element of X and an element of Y that add up to exactly a certain number, let's say 50.</p> <p>I have been able to come up with these algorithms in Python so far, but I am pretty sure they are order of THETA(n^2) rather than THETA(n).</p> <pre><code>def arrayTestOne(X,Y): S =[1 for x in X for y in Y if x+y == 50] def arrayTestTwo(X,Y): for x in X: for y in Y: if x + y == 50: print("1") </code></pre> <p>I'm thinking it's the double for loops that break the linear time, but how else would you iterate through 2 lists? Any thoughts would be appreciated.</p>
0
2016-09-19T20:46:47Z
39,581,973
<p>What you can do is start with the highest in one list and the lowest in the other, and check the sum. </p> <p>If the sum is your target, you're done. </p> <p>If it's too high, go to the next highest value in the first list.</p> <p>If it's too low, go to the next lowest value in the second. </p> <p>If you go through both lists without reaching the target, you return false.</p>
6
2016-09-19T20:56:15Z
[ "python", "arrays", "algorithm", "big-o" ]
pandas: find percentile stats of a given column
39,581,893
<p>I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:</p> <pre><code>my_df['field_A'].mean() my_df['field_A'].median() my_df['field_A'].mode() </code></pre> <p>I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!</p>
1
2016-09-19T20:50:57Z
39,582,161
<p>I figured out below would work:</p> <pre><code>my_df.dropna().quantile([0.0, .9]) </code></pre>
0
2016-09-19T21:11:12Z
[ "python", "python-2.7", "pandas", "statistics" ]
pandas: find percentile stats of a given column
39,581,893
<p>I have a pandas data frame my_df, where I can find the mean(), median(), mode() of a given column:</p> <pre><code>my_df['field_A'].mean() my_df['field_A'].median() my_df['field_A'].mode() </code></pre> <p>I am wondering is it possible to find more detailed stats such as 90 percentile? Thanks!</p>
1
2016-09-19T20:50:57Z
39,583,179
<p>assume series <code>s</code></p> <pre><code>s = pd.Series(np.arange(100)) </code></pre> <p>Get quantiles for <code>[.1, .2, .3, .4, .5, .6, .7, .8, .9]</code></p> <pre><code>s.quantile(np.linspace(.1, 1, 9, 0)) 0.1 9.9 0.2 19.8 0.3 29.7 0.4 39.6 0.5 49.5 0.6 59.4 0.7 69.3 0.8 79.2 0.9 89.1 dtype: float64 </code></pre> <p>OR</p> <pre><code>s.quantile(np.linspace(.1, 1, 9, 0), 'lower') 0.1 9 0.2 19 0.3 29 0.4 39 0.5 49 0.6 59 0.7 69 0.8 79 0.9 89 dtype: int32 </code></pre>
1
2016-09-19T22:44:48Z
[ "python", "python-2.7", "pandas", "statistics" ]
PyQt Creates Additive Dialogs After Each Click
39,582,059
<p>The title pretty much sums this issue up. I have a GUI that I've coded already and I'm trying to modify my error handling to better take advantage of PyQt's signals and slots. However, I've ran into a bit of an issue. I am testing an error handling statement where if a use clicks on a specific button there get a dialog telling them they have not entered the correct information yet. This dialog is controlled by signals and slots and does appear when it is supposed to. However, if I close the dialog then click the button again, the dialog pop up twice. This occurs additively. That is, if I click the button a third time the dialog comes up three times and so on. I'm not sure what else to do. I tried checking to make sure that all the QThreads end. I've even go so far as to use QThread.terminate() which you should never do and I still ended up with the same outcome. Any ideas as to what is causing this? Code snipet is below.</p> <pre><code>def error_check_in_thread(self, method): self.connect(method, QtCore.SIGNAL("selenium_error"), lambda: self.error_launch("selenium_error")) self.connect(method, QtCore.SIGNAL("attribute_error"), lambda: self.error_launch("attribute_error")) self.connect(method, QtCore.SIGNAL("name_error"), lambda: self.error_launch("name_error")) self.connect(method, QtCore.SIGNAL("os_error"), lambda: self.error_launch("os_error")) self.connect(method, QtCore.SIGNAL("finished()"), lambda: self.append_log(0)) self.connect(method, QtCore.SIGNAL("terminated()"), lambda: self.append_log(1)) method.start() return def error_launch(self, error): dialog = ErrorDialogs() if error == "selenium_error": dialog.pipeline_pilot_automation_error() elif error == "attribute_error": dialog.attribute_error() elif error == "os_error": dialog.path_error() elif error == "session_info_error": dialog.session_info_error() self.error_counter += 1 return def append_log(self, exit_type): if exit_type == 0: self.log_edit_area.appendPlainText(str(MainGui.log_output[0])) elif exit_type == 1: self.log_edit_area.appendPlainText("THE METHOD WAS TERMINATED PREMATURELY\n" + "#"*50) MainGui.log_output = [] class WorkingThread(QtCore.QThread): def __init__(self, selector): QtCore.QThread.__init__(self) self.selector = selector self.method_info = None def __del__(self): self.wait() # Controls which function to launch in another thread based on button presses in MainGui def run(self): print("start") try: if self.selector == 1: self.method_info = "DIRECTORIES AND SUBDIRECTORIES CREATION " MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "SUCCESSFUL FOR: " + MainGui.da_batch_name + "\n" + "#"*50) asa.mkdirsda(MainGui.hdg_da_path, MainGui.da_batch_folder, MainGui.da_batch_subfolders) elif self.selector == 2: self.method_info = "LIMS SAMPLE SHEET MOVEMENT TO AUTOSCORE SUBDIRECTORY " MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "SUCCESSFUL FOR: " + MainGui.da_batch_name + "\n" + "#"*50) asa.mvlims(MainGui.needs_gs_lims_file, MainGui.subfolder_autoscore, MainGui.lims_samplesheet) elif self.selector == 3: self.method_info = "GENOMESTUDIO " MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "STARTED FOR: " + MainGui.da_batch_name + "\n" + "#"*50) asa.gsprocess(MainGui.subfolder_genomestudio, MainGui.da_batch_name, MainGui.lims_samplesheet_file) MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "SUCCESSFUL FOR: " + MainGui.da_batch_name + "\n" + "#"*50) elif self.selector == 4: self.method_info = "FINAL REPORT MOVEMENT TO AUTOSCORE SUBDIRECTORY " MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "SUCCESSFUL FOR: " + MainGui.da_batch_name + "\n" + "#"*50) asa.mvfinalreport(MainGui.subfolder_genomestudio, MainGui.da_batch_name, MainGui.finalreport_file, MainGui.subfolder_autoscore) elif self.selector == 5: self.method_info = "PIPELINE PILOT AUTOMATION " MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "STARTED FOR: " + MainGui.da_batch_name + "\n" + "#"*50) asa.pipelineas(MainGui.userid, MainGui.userpass, MainGui.da_batch_name, MainGui.raw_data_path) MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "SUCCESSFUL FOR: " + MainGui.da_batch_name + "\n" + "#"*50) elif self.selector == 6: self.method_info = "GBS SET DIRECTORIES CREATION" MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "SUCCESSFUL FOR: " + MainGui.gbs_set_name + "\n" + "#"*50) asa.mkdirsgbs(MainGui.gbs_path, MainGui.gbs_set_name) except (ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException, NoSuchWindowException, UnexpectedAlertPresentException): MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "FAILED DUE TO SELENIUM ERROR\n" + "#"*50) selenium_error = QtCore.pyqtSignal() self.emit(QtCore.SIGNAL("selenium_error")) return except AttributeError: MainGui.log_output.append("ACTION AT: " + "[[" + str(datetime.datetime.now()) + "]]" + "\n" + self.method_info + "FAILED DUE TO ATTRIBUTE ERROR\n" + "#"*50) attribute_error = QtCore.pyqtSignal() self.emit(QtCore.SIGNAL("attribute_error")) print("stop") return return </code></pre>
0
2016-09-19T21:03:14Z
39,601,100
<p>I've answered my own question. The issue wasn't caused by any of my error handling but rather how I was passing information to the QThread class instances I was creating to start new thread. I was creating instances of QThread objects within the <strong>init</strong> method of my script and this wasn't letting the instances be collected as garbage because they were constantly in use in the main GUI loop. The solution was just to move the creation of QThread objections into a separate function.</p>
0
2016-09-20T18:17:42Z
[ "python", "user-interface", "error-handling", "dialog", "pyqt4" ]
How do I override Django's default admin templates and layouts
39,582,087
<p>I am trying to override Django's default template. For now just the base_site.html. I'm trying to change the text django administration.</p> <p>I did the following:</p> <ol> <li>I created a folder in my app directory <code>/opt/mydjangoapp/templates/admin</code></li> <li>I then copied the original django admin templates folder contents into admin and here are the contents: <em>404.html auth change_list.html delete_selected_confirmation.html index.html pagination.html search_form.html 500.html base.html change_list_results.html edit_inline invalid_setup.html popup_response.html submit_line.html actions.html base_site.html date_hierarchy.html filter.html login.html prepopulated_fields_js.html app_index.html change_form.html delete_confirmation.html includes object_history.html related_widget_wrapper.html</em></li> <li>I changed the contents of <code>base_site.html</code>, so that I have the title '<em>My App Admin</em>' as opposed to '<em>Django Administration</em>'</li> <li><p>My settings file looks as follows: </p> <pre><code>INSTALLED_APPS = ( 'mydjangoapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', ) ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/opt/mydjangoapp/templates/'], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug':True, 'loaders': ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader' ), }, }, ] </code></pre></li> </ol> <p>But unfortunately, Django version 1.8 seems to be ignoring my template changes and loading the original template files. Any suggestions as to how I can override the original layout for the admin. Bare in mind changing the title is just the beginning of the changes that I want to perform?</p>
1
2016-09-19T21:05:13Z
39,603,518
<p>First, make sure your application is listed first, because Django always take the resources from the first application where it finds them, according to the order in <code>settings.INSTALLED_APPS</code>.</p> <p>In this case the app was listed first, but the override was not working because the templates were placed under the global template directories listed under <code>settings.TEMPLATES['DIRS']</code> which are not tied to any particular app and will have the least priority.</p> <p>If this is your case, you must move the template folder inside your app (for example, <code>/opt/mydjangoapp/mydjangoapp/templates/</code> instead of <code>/opt/mydjangoapp/templates/</code>) and wipe the reference at <code>settings.TEMPLATES['DIRS']</code>. </p>
0
2016-09-20T20:51:46Z
[ "python", "django" ]
Precise timing with serial write
39,582,088
<p>The code below sends a character over serial and waits 8 ms.</p> <pre><code>import serial import time from time import sleep ser = serial.Serial( port='/dev/cu.usbserial-AD01ST7I',\ writeTimeout = 0,\ baudrate=115200,\ parity=serial.PARITY_NONE,\ stopbits=serial.STOPBITS_ONE,\ bytesize=serial.EIGHTBITS,\ ) for z in range(5000): ser.write('C') time.sleep(.008) </code></pre> <p>Measuring the serial activity on the serial port with a scope shows that the message is sent every ~10 ms. It varies a little – sometimes the interval is 8.5 ms.</p> <p><a href="http://i.stack.imgur.com/5Jycb.png" rel="nofollow">Oscilloscope measurement</a></p> <p>Is there a way to send the message precisely every 8ms?</p>
0
2016-09-19T21:05:14Z
39,582,590
<p><strong>No</strong>, unless you use <a href="https://en.wikipedia.org/wiki/Real-time_operating_system" rel="nofollow" title="RTOS">RTOS</a>. There are many factors that will affect the precision:</p> <ul> <li>Serial buffering. You can force to write the data immediately by calling <code>flush</code></li> <li>Timer accuracy, which is different on each OS. Sometimes in the order of milliseconds. </li> <li>OS scheduling, see <a href="https://en.wikipedia.org/wiki/Scheduling_(computing)" rel="nofollow">https://en.wikipedia.org/wiki/Scheduling_(computing)</a></li> </ul>
0
2016-09-19T21:43:13Z
[ "python", "serial-port", "pyserial" ]
Establish if a document satisifies a query (without actually performing the query) in ElasticSearch
39,582,094
<p>I have a document (that I know is in the index), and a query. Is there a way of knowing if the document satisfies the query, without actually querying the index and looking into the results.</p> <p>So for example, I'd like to know if the document</p> <pre><code>{ "price" : 30, "productID" : "1937" } </code></pre> <p>satisifes the query </p> <pre><code>{'query': {'bool': { 'should': [{'bool': { 'must': [{'term': {'price': 30}}, {'term': {'productID': '1937'}}]}}, {'term': {'productID': '9947'}}] }}} </code></pre> <p>which is basically</p> <pre><code>productID = 9947 OR (productID = 1937 AND price = 30 ) </code></pre> <p>This is an easy case, but I need something for arbitrary queries.</p>
0
2016-09-19T21:05:29Z
39,582,892
<p>Unfortunately, I don't think there's a direct way of doing this. You could either:</p> <p>A) Issue a query, filtering by the document's ID using the <code>ids</code> query to avoid querying all of your documents:</p> <pre><code>{ "ids" : { "type" : "my_type", "values" : ["1", "4", "100"] } } </code></pre> <p>Example from: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-ids-query.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-ids-query.html</a></p> <p>B) Use ES's percolator to index the <em>query</em>, then query <em>by document</em>:</p> <p>Index the query:</p> <pre><code>curl -XPUT 'localhost:9200/my-index/.percolator/1' -d '{ "query" : { "match" : { "message" : "bonsai tree" } } }' </code></pre> <p>Query by document:</p> <pre><code>curl -XGET 'localhost:9200/my-index/my-type/_percolate' -d '{ "doc" : { "message" : "A new bonsai tree in the office" } }' </code></pre> <p>Response:</p> <pre><code>{ "took" : 19, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "total" : 1, "matches" : [ { "_index" : "my-index", "_id" : "1" } ] } </code></pre> <p>Examples from: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-percolate.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/search-percolate.html</a></p> <p>If the response has your query's ID, then your query applies to the document. The upside to this approach is that you can run it multiple times for different documents.</p>
1
2016-09-19T22:12:39Z
[ "python", "elasticsearch", "elasticsearch-2.0" ]
Establish if a document satisifies a query (without actually performing the query) in ElasticSearch
39,582,094
<p>I have a document (that I know is in the index), and a query. Is there a way of knowing if the document satisfies the query, without actually querying the index and looking into the results.</p> <p>So for example, I'd like to know if the document</p> <pre><code>{ "price" : 30, "productID" : "1937" } </code></pre> <p>satisifes the query </p> <pre><code>{'query': {'bool': { 'should': [{'bool': { 'must': [{'term': {'price': 30}}, {'term': {'productID': '1937'}}]}}, {'term': {'productID': '9947'}}] }}} </code></pre> <p>which is basically</p> <pre><code>productID = 9947 OR (productID = 1937 AND price = 30 ) </code></pre> <p>This is an easy case, but I need something for arbitrary queries.</p>
0
2016-09-19T21:05:29Z
39,586,802
<p>If you know the document's ID, you can use the "explain" api. <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/search-explain.html</a></p> <p>So assuming your documents id is <code>1234abc</code> you can do the following</p> <pre><code>curl -XGET 'your_es_server:9200/your_index/your_mapping/1234abc/_explain' -d '{'query': {'bool': { 'should': [{'bool': { 'must': [{'term': {'price': 30}}, {'term': {'productID': '1937'}}]}}, {'term': {'productID': '9947'}}] }}}' </code></pre> <p>And this should return something like this. </p> <pre><code> { "_index": "your_index", "_type": "your_mapping", "_id": "1234abc", "matched": true, "explanation": { "value": 0.06100826, "description": "sum of:", "details": [......... .... ... ... </code></pre> <p>You can just check if the <code>matched</code> variable in the above response is true or not.</p>
1
2016-09-20T06:06:18Z
[ "python", "elasticsearch", "elasticsearch-2.0" ]
Python dictionary lookup performance, get vs in
39,582,115
<p>This isn't premature optimization. My use case has the double-checking of dict's right in the inner-most of inner loops, running all the time. Also, it's intellectually irksome (see results).</p> <p>Which of these approaches is faster?</p> <pre><code>mydict = { 'hello': 'yes', 'goodbye': 'no' } key = 'hello' # (A) if key in mydict: a = mydict[key] do_things(a) else: handle_an_error() # vs (B) a = mydict.get(key,None) if a is not None: do_things(a) else: handle_an_error() </code></pre> <p>Edit: these are the same speed. Common sense tells me that (B) should be noticeably faster since it's only one dict lookup vs. 2, but the results are different. I'm scratching my head.</p> <p>Results of a benchmark averaged over 12 runs, 1/2 of which are hits, the other half are misses:</p> <pre><code>doing in switching to get total time for IN: 0.532250006994 total time for GET: 0.480916659037 times found: 12000000 times not found: 12000000 </code></pre> <p>And when a similar one is run (*10 more loops) without ever finding the key,</p> <pre><code>doing in switching to get total time for IN: 2.35899998744 total time for GET: 4.13858334223 </code></pre> <p>Why!?</p> <p>(correct) code</p> <pre><code>import time smalldict = {} for i in range(10): smalldict[str(i*4)] = str(i*18) smalldict["8"] = "hello" bigdict = {} for i in range(10000): bigdict[str(i*100)] = str(i*4123) bigdict["hello"] = "yes!" timetotal = 0 totalin = 0 totalget = 0 key = "hello" found= 0 notfound = 0 ddo = bigdict # change to smalldict for small dict gets print 'doing in' for r in range(12): start = time.time() a = r % 2 for i in range(1000000): if a == 0: if str(key) in ddo: found = found + 1 foo = ddo[str(key)] else: notfound = notfound + 1 foo = "nooo" else: if 'yo' in ddo: found = found + 1 foo = ddo['yo'] else: notfound = notfound + 1 foo = "nooo" timetotal = timetotal + (time.time() - start) totalin = timetotal / 12.0 print 'switching to get' timetotal = 0 for r in range(12): start = time.time() a = r % 2 for i in range(1000000): if a == 0: foo = ddo.get(key,None) if foo is not None: found = found + 1 else: notfound = notfound + 1 foo = "nooo" else: foo = ddo.get('yo',None) if foo is not None: found = found + 1 notfound = notfound + 1 else: notfound = notfound + 1 foo = "oooo" timetotal = timetotal + (time.time() - start) totalget = timetotal / 12 print "total time for IN: ", totalin print 'total time for GET: ', totalget print 'times found:', found print 'times not found:', notfound </code></pre> <p>(original) code import time smalldict = {} for i in range(10): smalldict[str(i*4)] = str(i*18)</p> <pre><code>smalldict["8"] = "hello" bigdict = {} for i in range(10000): bigdict[str(i*100)] = str(i*4123) bigdict["8000"] = "hello" timetotal = 0 totalin = 0 totalget = 0 key = "hello" found= 0 notfound = 0 ddo = bigdict # change to smalldict for small dict gets print 'doing in' for r in range(12): start = time.time() a = r % 2 for i in range(10000000): if a == 0: if key in ddo: foo = ddo[key] else: foo = "nooo" else: if 'yo' in ddo: foo = ddo['yo'] else: foo = "nooo" timetotal = timetotal + (time.time() - start) totalin = timetotal / 12.0 print 'switching to get' timetotal = 0 for r in range(12): start = time.time() a = r % 2 for i in range(10000000): if a == 0: foo = ddo.get(key,None) if foo is not None: # yaaay pass else: foo = "nooo" else: foo = ddo.get('yo',None) if foo is not None: #yaaay pass else: foo = "oooo" timetotal = timetotal + (time.time() - start) totalget = timetotal / 12 print "total time for IN: ", totalin print 'total time for GET: ', totalget </code></pre>
0
2016-09-19T21:07:15Z
39,582,288
<p>We can do some better timings:</p> <pre><code>import timeit d = dict.fromkeys(range(10000)) def d_get_has(d): return d.get(1) def d_get_not_has(d): return d.get(-1) def d_in_has(d): if 1 in d: return d[1] def d_in_not_has(d): if -1 in d: return d[-1] print timeit.timeit('d_get_has(d)', 'from __main__ import d, d_get_has') print timeit.timeit('d_get_not_has(d)', 'from __main__ import d, d_get_not_has') print timeit.timeit('d_in_has(d)', 'from __main__ import d, d_in_has') print timeit.timeit('d_in_not_has(d)', 'from __main__ import d, d_in_not_has') </code></pre> <p>On my computer, the "in" variants are faster than the <code>.get</code> variants. This is probably because <code>.get</code> is an attribute lookup on the dict and an attribute lookup is likely to be as expensive as a membership test on the dict. Note that <code>in</code> and item lookup using <code>dict[x]</code> can be done directly in bytecode so the normal method lookups can be bypassed...</p> <p>It also might be worth pointing out that I get a HUGE optimization if I just use pypy :-):</p> <pre><code>$ python ~/sandbox/test.py 0.169840812683 0.1732609272 0.122044086456 0.0991759300232 $ pypy ~/sandbox/test.py 0.00974893569946 0.00752687454224 0.00812077522278 0.00686597824097 </code></pre>
1
2016-09-19T21:19:08Z
[ "python", "performance", "dictionary" ]
Pandas check if row exist in another dataframe and append index
39,582,138
<p>I'm having one problem to iterate over my dataframe. The way I'm doing is taking a loooong time and I don't have that many rows (I have like 300k rows)</p> <p>What am I trying to do? </p> <ol> <li><p>Check if one DF (A) contains the value of two columns of the other DF (B). You can think this as a multiple key field</p></li> <li><p>If True, get the index of DF.B and assign to one column of DF.A</p></li> <li><p>If False, two steps:</p> <p>a. append to DF.B the two columns not found</p> <p>b. assign the new ID to DF.A (I couldn't do this one)</p></li> </ol> <p>This is my code, where:</p> <ol> <li><p>df is DF.A and df_id is DF.B:</p></li> <li><p>SampleID and ParentID are the two columns I am interested to check if they exist in both dataframes</p></li> <li><p>Real_ID is the column which I want to assign the id of DF.B (df_id)</p> <pre><code>for index, row in df.iterrows(): #check if columns exist in the other dataframe real_id = df_id[(df_id['SampleID'] == row['SampleID']) &amp; (df_id['ParentID'] == row['ParentID'])] if real_id.empty: #row does not exist, append to df_id df_id = df_id.append(row[['SampleID','ParentID']]) else: #row exists, assign id of df_id to df row['Real_ID'] = real_id.index </code></pre></li> </ol> <p>EXAMPLE:</p> <p>DF.A (df)</p> <pre><code> Real_ID SampleID ParentID Something AnotherThing 0 20 21 a b 1 10 11 a b 2 40 51 a b </code></pre> <p>DF.B (df_id)</p> <pre><code> SampleID ParentID 0 10 11 1 20 21 </code></pre> <p><strong>Result</strong>:</p> <pre><code> Real_ID SampleID ParentID Something AnotherThing 0 1 10 11 a b 1 0 20 21 a b 2 2 40 51 a b SampleID ParentID 0 20 21 1 10 11 2 40 51 </code></pre> <p>Again, this solution is very slow. I'm sure there is a better way to do this and that's why I'm asking here. Unfortunately this was what I got after some hours...</p> <p>Thanks</p>
1
2016-09-19T21:09:05Z
39,582,426
<p>you can do it this way:</p> <p>Data (pay attention at the index in the <code>B</code> DF):</p> <pre><code>In [276]: cols = ['SampleID', 'ParentID'] In [277]: A Out[277]: Real_ID SampleID ParentID Something AnotherThing 0 NaN 10 11 a b 1 NaN 20 21 a b 2 NaN 40 51 a b In [278]: B Out[278]: SampleID ParentID 3 10 11 5 20 21 </code></pre> <p><strong>Solution:</strong></p> <pre><code>In [279]: merged = pd.merge(A[cols], B, on=cols, how='outer', indicator=True) In [280]: merged Out[280]: SampleID ParentID _merge 0 10 11 both 1 20 21 both 2 40 51 left_only In [281]: B = pd.concat([B, merged.ix[merged._merge=='left_only', cols]]) In [282]: B Out[282]: SampleID ParentID 3 10 11 5 20 21 2 40 51 In [285]: A['Real_ID'] = pd.merge(A[cols], B.reset_index(), on=cols)['index'] In [286]: A Out[286]: Real_ID SampleID ParentID Something AnotherThing 0 3 10 11 a b 1 5 20 21 a b 2 2 40 51 a b </code></pre>
1
2016-09-19T21:29:24Z
[ "python", "pandas" ]
Selenium: Element is not currently visible and so may not be interacted
39,582,141
<p>I'm attempting to create an automated login script to netflix website: <a href="https://www.netflix.com/it/" rel="nofollow">https://www.netflix.com/it/</a></p> <p>That's the code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() while True: driver.get("https://www.netflix.com/it/") login = driver.find_element_by_css_selector(".authLinks.signupBasicHeader") login.click() element = driver.find_element_by_name("email") element.send_keys("[email protected]") submit = driver.find_element_by_css_selector(".btn.login-button.btn-submit.btn-small") submit.click() element2 = driver.find_element_by_name("password") element2.send_keys("test1") submit.click() </code></pre> <p>But sometimes it works and sometimes it doesn't and it raises this exception:</p> <pre><code>Traceback (most recent call last): File "netflix.py", line 35, in &lt;module&gt; submit.click() File "/home/user/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webelement.py", line 72, in click self._execute(Command.CLICK_ELEMENT) File "/home/user/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webelement.py", line 461, in _execute return self._parent.execute(command, params) File "/home/user/.local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/home/user/.local/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///tmp/tmp7otgskq8/extensions/[email protected]/components/command-processor.js:10092) at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmp7otgskq8/extensions/[email protected]/components/command-processor.js:12644) at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmp7otgskq8/extensions/[email protected]/components/command-processor.js:12661) at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmp7otgskq8/extensions/[email protected]/components/command-processor.js:12666) at DelayedCommand.prototype.execute/&lt; (file:///tmp/tmp7otgskq8/extensions/[email protected]/components/command-processor.js:12608) </code></pre> <p>The exception says that a part of the web page is invisible (even if that part IS in the page actually)... It's a sort of bug. How can I bypass this?</p>
0
2016-09-19T21:09:29Z
39,582,789
<p>No need to put the test code inside <code>while</code> loop, since login form should be submitted once. I guess when it works successfully, next iteration gives error since there is no form.</p> <p>You are also clicking the submit button before and after password entry. It is better to click after form is fully filled, if possible and not testing empty form. </p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.netflix.com/it/") login = driver.find_element_by_css_selector(".authLinks.signupBasicHeader") login.click() element = driver.find_element_by_name("email") element.send_keys("[email protected]") submit = driver.find_element_by_css_selector(".btn.login-button.btn-submit.btn-small") submit.click() element2 = driver.find_element_by_name("password") element2.send_keys("test1") submit = driver.find_element_by_css_selector(".btn.login-button.btn-submit.btn-small") submit.click() </code></pre>
0
2016-09-19T22:01:41Z
[ "python", "python-3.x", "selenium" ]
Trouble understanding function returns in "Functions" section of learnpython.org
39,582,166
<p>I'm working through the "Functions" exercise on learnpython.org and had a question about why my version of code is returning a "None" after every string that is output (where I first define the string list and then return it in that specific functions) as opposed to the solution (where they return the list of strings all in one line). Here is the code they gave me, the instructions, and what we expect to see:</p> <p><strong>Instructions:</strong></p> <ol> <li><p>Add a function named list_benefits() that returns the following list of strings: "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"</p></li> <li><p>Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"</p></li> <li><p>Run and see all the functions work together!</p></li> </ol> <p><strong>Code (given):</strong></p> <pre><code># Modify this function to return a list of strings as defined above def list_benefits(): pass # Modify this function to concatenate to each benefit - " is a benefit of functions!" def build_sentence(benefit): pass def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print build_sentence(benefit) name_the_benefits_of_functions() </code></pre> <p><strong>Expected Output:</strong></p> <pre><code>More organized code is a benefit of functions! More readable code is a benefit of functions! Easier code reuse is a benefit of functions! Allowing programmers to share and connect code together is a benefit of functions! </code></pre> <p>Now, this is my implementation of a solution - everything seems to be okay, except I'm getting a "None" every other line:</p> <p><strong>Code (mine):</strong></p> <pre><code># Modify this function to return a list of strings as defined above def list_benefits(): list = "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together" return list # Modify this function to concatenate to each benefit - " is a benefit of functions!" def build_sentence(benefit): print "%s is a benefit of functions!" % benefit def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print build_sentence(benefit) name_the_benefits_of_functions() </code></pre> <p><strong>Output (mine):</strong></p> <pre><code>More organized code is a benefit of functions! None More readable code is a benefit of functions! None Easier code reuse is a benefit of functions! None Allowing programmers to share and connect code together is a benefit of functions! None </code></pre> <p>This is what the actual solution is, which produces the Expected Output shown earlier:</p> <p><strong>Code (solution):</strong></p> <pre><code># Modify this function to return a list of strings as defined above def list_benefits(): return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together" # Modify this function to concatenate to each benefit - " is a benefit of functions!" def build_sentence(benefit): return "%s is a benefit of functions!" % benefit def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print build_sentence(benefit) name_the_benefits_of_functions() </code></pre> <p>As you can see, the only difference between my code and the solution is that in mine, I'm assigning the strings to a variable "list" and then returning that variable, where as with the solution code, they are returning the list of strings themselves. What exactly is the reason why my version is returning "None" every other line, but the correct version does not?</p> <p>Thanks!</p>
2
2016-09-19T21:11:34Z
39,582,253
<p>The difference is in your <code>build_sentence</code> return value, not your <code>list_benefits</code> return value.</p> <p>The line:</p> <pre><code> print build_sentence(benefit) </code></pre> <p>instructs the Python interpreter to print the <em>output</em> of the <code>build_sentence</code> function—but if you look at your <code>build_sentence</code> implementation, you'll see that you don't explicitly <code>return</code> any output from that function. So it returns <code>None</code>, and that is what is printed.</p> <p>Instead, your <code>build_sentence</code> takes on the job of <code>print</code>ing the result itself (which the solution code's <code>build_sentence</code> does not do). You have created an example of a function that has what's known as a "side effect"—an effect that a function has on the state of the system (or on the user) beyond just its delivery of a function output. In this case the side effect is the reason your code produces console output that looks <em>nearly</em> correct, and that misdirected you into thinking that <code>build_sentence</code> was working according to spec and focusing your attention on <code>list_benefits</code>.</p> <p>There's no problem with <code>list_benefits</code> itself, except that it uses <code>list</code> as a variable name, overshadowing the name of one of Python's basic types. This is allowed, but it's a bad habit which sooner or later may lead to problems with code maintainability. Conventionally people often use the name <code>lst</code> when tempted to call a variable <code>list</code>.</p>
0
2016-09-19T21:17:00Z
[ "python" ]
Python: Search a string for a variable repeating characters
39,582,192
<p>I'm trying to write a function that will search a string (all numeric, 0-9) for a variable sequence of 4 or more repeating characters. </p> <p>Here are some example inputs:</p> <p>"14888838": the function would return True because it found "8888". </p> <p>"1111": the function would return True because it found "1111". </p> <p>"1359": the function would return False because it didn't find 4 repeating characters in a row. </p> <p>My first inclination is to use re, so I thought the pattern :"[0-9]{4}" would work but that returns true as long as it finds any four numerics in a row, regardless of whether they are matching or not. </p> <p>Anyway, thanks in advance for your help.</p> <p>Dave</p>
4
2016-09-19T21:13:09Z
39,582,241
<p>You may rely on <a href="http://www.regular-expressions.info/brackets.html" rel="nofollow"><strong>capturing</strong></a> and <a href="http://www.regular-expressions.info/backref.html" rel="nofollow"><strong>backreferences</strong></a>:</p> <pre><code>if re.search(r'(\d)\1{3}', s): print(s) </code></pre> <p>Here, <code>(\d)</code> captures a digit into Group 1 and <code>\1{3}</code> matches 3 occurrences of the value captured that are immediately to the right of that digit.</p> <p>See the <a href="https://regex101.com/r/aP1gJ2/1" rel="nofollow">regex demo</a> and a <a href="http://ideone.com/Px7fvH" rel="nofollow">Python demo</a></p> <pre><code>import re values = ["14888838", "1111", "1359"] for s in values: if re.search(r'(\d)\1{3}', s): print(s) </code></pre> <p>Output:</p> <pre><code>14888838 1111 </code></pre>
4
2016-09-19T21:16:35Z
[ "python", "regex" ]
Command-line setting ignored using latexpdf
39,582,206
<p>I am using sphinx-build to create both html and latexpdf output. Output looks amazing in both cases. </p> <p>I would like to pass the <strong>project</strong> name on the command-line so the documentation can be titled e.g., <strong>TEST</strong>. This works great for the html option. In the example below (from a modified make.bat file), <strong>TEST</strong> overrides any <strong>project</strong> definition in the conf.py file.</p> <pre><code> %SPHINXBUILD% -b html -D project ="TEST" %ALLSPHINXOPTS% %BUILDDIR%/html </code></pre> <p>However, the command–line option is ignored when the tex file is created and whatever was in the conf.py is used for the definition of project in the generated PDF file.</p> <pre><code> %SPHINXBUILD% -b latexpdf -D project ="TEST" %ALLSPHINXOPTS% %BUILDDIR%/html </code></pre> <p>For example, if <strong>project</strong> is defined in conf.py: project = 'TEST' </p> <p>Then used in the preamble: \title{project}</p> <p>The document is titled TEST. I cannot seem to override the TEST value with a command-line argument.</p>
0
2016-09-19T21:14:11Z
39,626,449
<p>Thanks for the reference to latex_elements. I realize that what I was trying to do, override settings in conf.py on the fly by using command-line arguments, is not going to work.</p>
0
2016-09-21T20:56:49Z
[ "python", "pdf", "python-sphinx" ]
Modular Python output problems
39,582,289
<p>So i had to convert my pseudocode to python but my output isnt coming out the way it should be.</p> <p>i enter the 40 hours work and 20 pay rate but the gross pay isnt coming out (gross pay should be 800). can anyone tell me whats wrong?</p> <pre class="lang-python prettyprint-override"><code>BASE_HOURS = 40 OT_MULTIPLIER = 1.5 def main(): hours_worked = int(input('Enter the number of hours worked: ')) pay_rate = int(input('Enter the hourly pay rate: ')) if hours_worked &gt; BASE_HOURS: calc_pay_with_OT(hours_worked, pay_rate) else: calc_regular_pay(hours_worked, pay_rate) def calc_pay_with_OT(hours, pay_rate): overtime_hours = hours_worked - BASE_HOURS overtime_pay = overtime_hours * pay_rate + OT_MULTIPLIER gross_pay = BASE_HOURS * pay_rate + overtime_pay print('The gross pay is $ '), gross_pay def calc_regular_pay(hours, pay_rate): gross_pay = hours * pay_rate print('The gross pay is $ '), gross_pay main() </code></pre>
-1
2016-09-19T21:19:08Z
39,582,447
<p>The print statement should instead be <code>print('The gross pay is $'+str(gross_pay))</code> The <code>str()</code> function converts the integer gross_pay into a string so that it can be concatenated in the print function.</p>
0
2016-09-19T21:31:14Z
[ "python", "modular" ]
For loop not working without range() " string indices must be integers"
39,582,309
<p><code>i</code> is a string, so how can I make this work? </p> <p>How can I use <code>i</code> as index?</p> <pre><code>for i in s[1:]: if s[i] &lt;= s[i-1]: temp += s[i] else: subs.append(temp) temp = '' </code></pre> <p>I've tried to use </p> <pre><code>for i in s[1:]: if s.index(i) &gt;= s.index(i-1): temp += s[i] else: subs.append(temp) temp = '' </code></pre> <p>And I get</p> <blockquote> <p>TypeError: unsupported operand type(s) for -: 'str' and 'int'</p> </blockquote>
-1
2016-09-19T21:21:00Z
39,582,444
<p>the syntax you are using is corresponding to string iteration (see <a href="http://anandology.com/python-practice-book/iterators.html" rel="nofollow">http://anandology.com/python-practice-book/iterators.html</a>) so the <code>i</code> will iterate on the different characters of the string on note on their indices:</p> <pre><code>&gt;&gt;&gt; for i in "hello"[1:]: ... print i ... e l l o </code></pre> <p><del>in the initial faulty loop, note that access to respectively <code>s[i+1]</code> or <code>s[i-1]</code> are incorrect when <code>i</code> is pointing to respectively last and first character of the string.</del> (question modified)</p> <p>To iterate on the indices, use xrange (for instance between second and the one before the last character):</p> <pre><code>s='hello' for i in xrange(1,len(s)-1): print i,s[i] </code></pre> <p>Generates:</p> <pre><code>e l l </code></pre>
0
2016-09-19T21:30:59Z
[ "python", "for-loop" ]
For loop not working without range() " string indices must be integers"
39,582,309
<p><code>i</code> is a string, so how can I make this work? </p> <p>How can I use <code>i</code> as index?</p> <pre><code>for i in s[1:]: if s[i] &lt;= s[i-1]: temp += s[i] else: subs.append(temp) temp = '' </code></pre> <p>I've tried to use </p> <pre><code>for i in s[1:]: if s.index(i) &gt;= s.index(i-1): temp += s[i] else: subs.append(temp) temp = '' </code></pre> <p>And I get</p> <blockquote> <p>TypeError: unsupported operand type(s) for -: 'str' and 'int'</p> </blockquote>
-1
2016-09-19T21:21:00Z
39,582,470
<p>When you iterate through a string using "for i in s[1:]", it will assign i the value of each character in the string. You may want to use the iterator "enumerate" in the loop instead. It will assign a sequential numeric value to every byte in the string, while assigning s[i] to v.</p> <pre><code>for i, v in enumerate(s): if v &lt;= s[i-1]: temp += v else: stubs.append(temp) temp = '' </code></pre>
-1
2016-09-19T21:33:40Z
[ "python", "for-loop" ]
Insert python variable value into SQL table
39,582,340
<p>I have a password system that stores the password for a python program in an SQL table. I want the user to be able to change the password in a tkinter window but I am not sure how to use the value of a python variable as the value for the SQL table. Here is a sample code:</p> <pre><code>import tkinter from tkinter import * import sqlite3 conn = sqlite3.connect('testDataBase') c = conn.cursor() c.execute("INSERT INTO info Values('test')") c.execute("SELECT password FROM info") password = (c.fetchone()[0]) #Window setup admin = tkinter.Tk() admin.minsize(width=800, height = 600) admin.maxsize(width=800, height = 600) #GUI passwordChangeLabel = Label(admin, text="It is recommended to change your password after first login!", font=("Arial", 14)) passwordChangeLabel.pack() passwordChangeCurrentPasswordLabel = Label(admin, text="Current Password: ", font=("Arial", 11)) passwordChangeCurrentPasswordLabel.place(x=275, y=30) passwordChangeCurrentPasswordEntry = Entry(admin) passwordChangeCurrentPasswordEntry.place(x=405, y=32.5) passwordChangeNewPasswordLabel = Label(admin, text="New Password: ", font=("Arial", 11)) passwordChangeNewPasswordLabel.place(x=295, y=50) passwordChangeNewPasswordEntry = Entry(admin) passwordChangeNewPasswordEntry.place(x=405, y=52.5) passwordChangeButton = Button(admin, text="Submit", width=20) passwordChangeButton.place(x=350, y=80) def changePasswordFunction(event): newPassword = passwordChangeNewPasswordEntry.get() enteredPassword = passwordChangeCurrentPasswordEntry.get() if enteredPassword == password: c.execute("REPLACE INTO info(password) VALUES(newPassword)") else: wrong = tkinter.Toplevel() wrong.minsize(width=200, height = 100) wrong.maxsize(width=200, height = 100) Label(wrong, text="Sorry that password is incorrect!", font=("Arial", 24), anchor=W, wraplength=180, fg="red").pack() admin.bind('&lt;Return&gt;', changePasswordFunction) passwordChangeButton.bind('&lt;Button-1&gt;', changePasswordFunction) </code></pre> <p>This code will bring up an error:</p> <pre><code>sqlite3.OperationalError: no such column: newPassword </code></pre> <p>How can I properly replace the previous value in the password column with the new entered password?</p>
-1
2016-09-19T21:22:55Z
39,582,516
<p>There are two valid ways to use <code>VALUES()</code>: with a label or a string literal. A string literal is a string in single or double quotes.</p> <p>Since you didn't put <code>newPassword</code> in quotes, Sqlite assumes <code>newPassword</code> is a label, i.e. a column name. It goes looking for the value of the <code>newPassword</code> field in the current record, and throws an error since that field doesn't exist.</p> <p>What you want to do is, take the value of the <code>newPassword</code> python variable and put it in quotes. Here's a corrected query string (not tested):</p> <pre><code>"REPLACE INTO info(password) VALUES('" + newPassword + "')" </code></pre> <p>As someone mentions in the comments, updating your database directly with user inputs is highly insecure. Database interfaces generally provide easy ways to sanitize all inputs, and you should make it a point to follow those practices. A great resource with code examples from many popular languages is <a href="http://bobby-tables.com/" rel="nofollow">Bobby Tables</a>. (Also note that failing to include information about SQL security in your answers at SO can result in down-votes.)</p>
-1
2016-09-19T21:36:15Z
[ "python", "sqlite", "tkinter" ]
Assigning probabilities to items in python
39,582,504
<p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code>&lt;string&gt;:&lt;list of lists&gt;</code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p> <pre><code>"NP":[['A', 'B'], ['C', 'D', 'E'], ['F']] </code></pre> <p>I need to choose one of the lists on the right hand side randomly. Each list has it's own probability. Here are the input strings that would generate the above item in the map.</p> <pre><code>3 NP A B 1 NP C D E 1 NP F </code></pre> <p>Because the line <code>NP A B</code> has the number <code>3</code> next to it, <code>NP C D E</code> has <code>1</code> next to it, and <code>NP F</code> has <code>1</code> next to it, the probability ratio is 3:1:1, so <code>[A, B]</code> has 3/5 probability of being chosen, <code>[C, D, E]</code> has 1/5 of being chosen and same for <code>[F</code>. </p> <p>My question is, how do I simulate those probabilities? </p> <p>Before those numbers were introduced it was easy because I could count the length of the list (in the above example it would be 3) and then choose a random number between 0 and <code>len(list) - 1</code> inclusive with <code>random.randint()</code>, then choose that index from the list. To simulate bernoulli random variables, I know that one can check <code>if random.randint() &lt; p</code>. But that only works if you have 2 cases. I can't explicitly write if statements to check because a list might have <code>n</code> elements. </p>
0
2016-09-19T21:35:12Z
39,582,694
<p>So the way I would solve this is by creating a sparse table ranging from <code>0</code> to <code>total probability</code>. In your case, that's </p> <pre><code>0 -&gt; 0 3 -&gt; 1 4 -&gt; 2 </code></pre> <p>Then pick an int between 0 and 4, and pick the largest value >= the chosen value (in other words, 1 maps to 0, 2 maps to 0, 3 maps to 1). The 'value' in this mapping corresponds to the sublist in your original dictionary. That shouldn't take any additional libraries.</p>
0
2016-09-19T21:51:54Z
[ "python", "probability" ]
Assigning probabilities to items in python
39,582,504
<p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code>&lt;string&gt;:&lt;list of lists&gt;</code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p> <pre><code>"NP":[['A', 'B'], ['C', 'D', 'E'], ['F']] </code></pre> <p>I need to choose one of the lists on the right hand side randomly. Each list has it's own probability. Here are the input strings that would generate the above item in the map.</p> <pre><code>3 NP A B 1 NP C D E 1 NP F </code></pre> <p>Because the line <code>NP A B</code> has the number <code>3</code> next to it, <code>NP C D E</code> has <code>1</code> next to it, and <code>NP F</code> has <code>1</code> next to it, the probability ratio is 3:1:1, so <code>[A, B]</code> has 3/5 probability of being chosen, <code>[C, D, E]</code> has 1/5 of being chosen and same for <code>[F</code>. </p> <p>My question is, how do I simulate those probabilities? </p> <p>Before those numbers were introduced it was easy because I could count the length of the list (in the above example it would be 3) and then choose a random number between 0 and <code>len(list) - 1</code> inclusive with <code>random.randint()</code>, then choose that index from the list. To simulate bernoulli random variables, I know that one can check <code>if random.randint() &lt; p</code>. But that only works if you have 2 cases. I can't explicitly write if statements to check because a list might have <code>n</code> elements. </p>
0
2016-09-19T21:35:12Z
39,582,811
<p>Here is a crude approach that might suffice if your total weight remains small:</p> <pre><code>&gt;&gt;&gt; NP = [['A', 'B'], ['C', 'D', 'E'], ['F']] &gt;&gt;&gt; weights = (3,1,1) &gt;&gt;&gt; indx_list = [idx for idx,w in zip(range(len(NP)), weights) for _ in range(w)] &gt;&gt;&gt; indx_list [0, 0, 0, 1, 2] &gt;&gt;&gt; import random &gt;&gt;&gt; random.choice([0, 0, 0, 1, 2]) 1 &gt;&gt;&gt; sample = [random.choice([idx for idx,w in zip(range(len(NP)), weights) for _ in range(w)]) for _ in range(1000)] &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counts = Counter(sample) &gt;&gt;&gt; counts Counter({0: 600, 2: 213, 1: 187}) </code></pre>
0
2016-09-19T22:03:34Z
[ "python", "probability" ]
Assigning probabilities to items in python
39,582,504
<p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code>&lt;string&gt;:&lt;list of lists&gt;</code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p> <pre><code>"NP":[['A', 'B'], ['C', 'D', 'E'], ['F']] </code></pre> <p>I need to choose one of the lists on the right hand side randomly. Each list has it's own probability. Here are the input strings that would generate the above item in the map.</p> <pre><code>3 NP A B 1 NP C D E 1 NP F </code></pre> <p>Because the line <code>NP A B</code> has the number <code>3</code> next to it, <code>NP C D E</code> has <code>1</code> next to it, and <code>NP F</code> has <code>1</code> next to it, the probability ratio is 3:1:1, so <code>[A, B]</code> has 3/5 probability of being chosen, <code>[C, D, E]</code> has 1/5 of being chosen and same for <code>[F</code>. </p> <p>My question is, how do I simulate those probabilities? </p> <p>Before those numbers were introduced it was easy because I could count the length of the list (in the above example it would be 3) and then choose a random number between 0 and <code>len(list) - 1</code> inclusive with <code>random.randint()</code>, then choose that index from the list. To simulate bernoulli random variables, I know that one can check <code>if random.randint() &lt; p</code>. But that only works if you have 2 cases. I can't explicitly write if statements to check because a list might have <code>n</code> elements. </p>
0
2016-09-19T21:35:12Z
39,582,843
<p>Here is a simple prototype which uses <strong>linear-search</strong>. The only dependency is <strong>random.random()</strong> to obtain a float within [0,1).</p> <p>Despite the unoptimized approach, it only needs ~0.25 seconds for 100.000 samples on my PC. But keep in mind, that this performance is dependent on the statistics / probability-vector. The code could also be improved through presorting.</p> <p>For the general idea: check <a href="https://en.wikipedia.org/wiki/Pseudo-random_number_sampling" rel="nofollow">this</a>.</p> <h3>Code</h3> <pre><code>import random """ Discrete-sampling """ def cum_sum(xs): cum_sum = [] total = 0 for i in xs: total += i cum_sum.append(total) total_sum = sum(cum_sum) return cum_sum, cum_sum[-1] def discrete_sample(items, probs): cum_sum_, max_ = cum_sum(probs) random_val = random.random() * max_ for ind, i in enumerate(items): if random_val &lt; cum_sum_[ind]: return i return items[-1] # fail-safe def sample_from_dict(element, data, data_p): data_ = data[element] data_p_ = data_p[element] selection = discrete_sample(range(len(data_)), data_p_) return data_[selection] """ Data """ data = {'NP': [['A', 'B'], ['C', 'D', 'E'], ['F']]} data_p = {'NP': [3, 1, 1]} """ Try it """ samples = [] for i in range(100000): samples.append(sample_from_dict('NP', data, data_p)) counts = [0, 0, 0] for i in samples: if i == ['A', 'B']: counts[0] += 1 elif i == ['C', 'D', 'E']: counts[1] += 1 elif i == ['F']: counts[2] += 1 print(counts) </code></pre> <h3>Output</h3> <pre><code>[60130, 19867, 20003] </code></pre>
0
2016-09-19T22:07:41Z
[ "python", "probability" ]
Read in avro file with boto3 and convert to string (Python)
39,582,523
<p>I'm using boto3 to read in an avro file from my s3 bucket. However, I'm stuck on how to actually convert the avro to a string.</p> <pre><code>avro_file = file_from_s3.get()['Body'].read() </code></pre> <p>After getting to this step, I'm not sure what to do.</p>
0
2016-09-19T21:36:45Z
39,600,802
<p>I found a way. You need to use StringIO from python and download_fileobj() from boto3.</p> <pre><code>import boto3 import StringIO from avro.datafile import DataFileReader, DataFileWriter from avro.io import DatumReader, DatumWriter output = StringIO.StringIO() latest_file_object = s3_client.Object('bucket_name','latest_file') latest_file_object.download_fileobj(output) reader = DataFileReader(output, DatumReader()) for r in reader: print r </code></pre>
0
2016-09-20T17:59:00Z
[ "python", "boto", "avro", "boto3" ]
Prevent Travis Python environment from pre-installing packages
39,582,527
<p>Is there a way to prevent the Travis Python environment from pre-installing <code>pytest</code>, <code>nose</code>, <code>mock</code> etc.? The versions are old and causing order-dependent problems when upgrading. I want to specify my dependencies only in <code>setup.py</code>, but <code>pytest</code> and <code>py</code> require mutual upgrades, which seems to always fail.</p> <p>I see there is a <code>virtualenv</code> key for <code>.travis.yml</code> which is sometimes mentioned briefly, but I don't see proper documentation for it.</p>
0
2016-09-19T21:37:18Z
39,964,141
<p>I didn't find a way to do this, but I found a relatively clean workaround: <code>virtualenvwrapper.sh</code> has a <code>wipeenv</code> command I did not previously know. So now I setup a "modern and clean" virtualenv like this:</p> <pre><code>before_install: - pip install -U pip setuptools virtualenvwrapper - source $(which virtualenvwrapper.sh) - wipeenv </code></pre> <p>I don't have to worry about the exact list of packages or intersection of them with my own, and the <code>install</code>/<code>script</code> sections can proceed unhindered by whatever Travis setup for me.</p>
0
2016-10-10T18:02:04Z
[ "python", "pip", "travis-ci", "setup.py" ]
Openstack: Gerrit error with git rebase and merge
39,582,601
<p>I am working on fixing a bug in Openstack. I did my changes, since this was a documentation task, I did run the test as I would have usually. I submitted the change to Gerrit. It came back from the reviewers while I was working on a another bug. </p> <p>I switched branches and worked on the older bug. When I did a <code>git review</code>, it threw up the following error. </p> <pre><code> You are about to submit multiple commits. This is expected if you are </code></pre> <p>submitting a commit that is dependent on one or more in-review commits. Otherwise you should consider squashing your changes into one commit before submitting.</p> <pre><code> The outstanding commits are: cd6bbfa (HEAD -&gt; master) Documentation updated on panel definition using plugin files 5503c89 Merge branch 'master' of git://git.openstack.org/openstack/horizon 85b63be Change-ID:Ic0844d967d519f57246b8220f9a863faf85351d2 Closes-Bug:#1519386 74cc524 Merge branch 'master' of git://git.openstack.org/openstack/horizon 377fb7e Closes-Bug: #1597302 Do you really want to submit the above commits? Type 'yes' to confirm, other to cancel: </code></pre> <p>I thought I had to do yes, and I did yes. Then Gerrit threw this error again.</p> <pre><code>remote: Processing changes: refs: 1, done To ssh://[email protected]:29418/openstack/horizon.git ! [remote rejected] HEAD -&gt; refs/publish/master/bug/1597302 (you are not allowed to upload merges) error: failed to push some refs to 'ssh://[email protected]:29418/openstack/horizon.git' </code></pre> <p>I tried to fix it by doing a rebase.</p> <pre><code>$ git rebase -i 377fb7e The previous cherry-pick is now empty, possibly due to conflict resolution. If you wish to commit it anyway, use: git commit --allow-empty Otherwise, please use 'git reset' interactive rebase in progress; onto 377fb7e Last commands done (190 commands done): pick 15909be modify the home-page info with the developer documentation pick 5a39ad7 Update the home-page in setup.cfg Next commands to do (137 remaining commands): pick 21b723e Fix typo pick 41e9d62 Remove embedded CSS You are currently rebasing branch 'master' on '377fb7e'. nothing to commit, working directory clean Could not apply 5a39ad78233546a01ae3da6efd10b104231d1d8b... Update the home-page in setup.cfg </code></pre> <p>This is what I am trying to achieve. I want to change back to my old bug <code>1597302</code> and submit it to review and continue working on my current bug which is <code>1519386</code></p> <p>Thanks for anyone who can help me with this.!</p>
0
2016-09-19T21:44:08Z
39,592,765
<p>The error "you are not allowed to upload merges" is self explanatory: you can't upload your code because you don't have permission to push merge commits. Gerrit is referring to commits 5503c89 and/or 74cc524.</p> <p>The first thing you need to do is to verify if you should be pushing these commits to Gerrit or there's something wrong with your repository. Did you create these commits or were they created by someone else? Are you basing in the correct commit? Are you following the OpenStack develop process (I don't know it)?</p> <p>If you really need to push these merge commit to Gerrit then (maybe) you need to ask the admin for permission to push merge commits.</p>
0
2016-09-20T11:22:08Z
[ "python", "git", "openstack", "gerrit", "openstack-horizon" ]
using the map function with timeit in Python
39,582,616
<p>I am learning python and am looking at the difference in performance between using comprehension and the map function. </p> <p>So far, I have this code:</p> <pre><code>import timeit print timeit.timeit('[x for x in range(100)]',number = 10000) def mapFunc(i): print i print timeit.timeit('map(mapFunc,range(100))',number = 10000) </code></pre> <p>After trying this, I have managed to get the list comprehension method to work correctly using timeit, however, I would like to compare this to the map function. When doing this, I get the error that mapFunc is not defined, and I do not know how to fix this issue. Can someone please help?</p>
0
2016-09-19T21:45:10Z
39,582,668
<p>You should <em>setup</em> the function definition via the <code>setup</code> argument:</p> <pre><code>&gt;&gt;&gt; setup='def mapFunc(): print(i)' &gt;&gt;&gt; timeit.timeit('map(mapFunc,range(100))', number=10000, setup=setup) </code></pre> <p>See the <a href="https://docs.python.org/2/library/timeit.html#timeit.timeit" rel="nofollow"><code>timeit</code> doc reference</a></p> <p>P.S. Probably not a good idea to use <code>map</code> for printing.</p>
2
2016-09-19T21:49:21Z
[ "python", "performance", "function", "dictionary", "timeit" ]
Counting items inside tuples in Python
39,582,639
<p>I am fairly new to python and I could not figure out how to do the following. </p> <p>I have a list of (word, tag) tuples </p> <pre><code>a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')] </code></pre> <p>I am trying to find all tags that has been assigned to each word and collect their counts. For example, word "run" has been tagged twice to 'Noun' and once to 'Verb'. </p> <p>To clarify: I would like to create another list of tuples that contains (word, tag, count)</p>
2
2016-09-19T21:46:44Z
39,582,689
<p>Pretty easy with a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; output = defaultdict(defaultdict(int).copy) &gt;&gt;&gt; for word, tag in a: ... output[word][tag] += 1 ... &gt;&gt;&gt; output defaultdict(&lt;function copy&gt;, {'Run': defaultdict(int, {'Noun': 2, 'Verb': 1}), 'The': defaultdict(int, {'Article': 1, 'DT': 1})}) </code></pre>
2
2016-09-19T21:51:16Z
[ "python", "tuples" ]
Counting items inside tuples in Python
39,582,639
<p>I am fairly new to python and I could not figure out how to do the following. </p> <p>I have a list of (word, tag) tuples </p> <pre><code>a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')] </code></pre> <p>I am trying to find all tags that has been assigned to each word and collect their counts. For example, word "run" has been tagged twice to 'Noun' and once to 'Verb'. </p> <p>To clarify: I would like to create another list of tuples that contains (word, tag, count)</p>
2
2016-09-19T21:46:44Z
39,582,744
<p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>:</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')] &gt;&gt;&gt; counter = collections.Counter(a) Counter({('Run', 'Noun'): 2, ('Run', 'Verb'): 1, ... }) &gt;&gt;&gt; result = {} &gt;&gt;&gt; for (tag, word), count in counter.items(): ... result.setdefault(tag, []).append({word: count}) &gt;&gt;&gt; print(result) {'Run': [{'Noun': 2}, {'Verb': 1}], 'The': [{'Article': 1}, {'DT': 1}]} </code></pre>
2
2016-09-19T21:56:54Z
[ "python", "tuples" ]
403 Forbidden while trying to display image from url - Kivy
39,582,681
<p>I'm trying to display image in kivy application, but image loader returns error 403 forbidden.</p> <p>I noticed that I have to send User-Agent header to bypass this error, but i couldn't find any way to pass headers to image loader</p> <p>Is there any way to solve this problem?</p> <p>kv file</p> <pre><code>AsyncImage: source: 'url_to_image' keep_ratio: True </code></pre> <p>error:</p> <pre><code>[ERROR ] [Loader ] Failed to load image &lt;url_to_image&gt; urllib.error.HTTPError: HTTP Error 403: Forbidden </code></pre>
1
2016-09-19T21:49:57Z
39,610,264
<p>Currently you can't modify the User-Agent when using AsyncImage. The responsible code is <a href="https://github.com/kivy/kivy/blob/master/kivy/loader.py#L317" rel="nofollow">here</a>:</p> <pre><code>fd = urllib_request.urlopen(filename) </code></pre> <p>As you see there is no good way to pass a different UserAgent in there. </p> <p>Instead handle the download of the file yourself.</p> <p>I guess you could also try to pass an <code>urllib.request.Request</code> object with a modified <code>split</code> function so that the variable <code>filename</code> does not actually contain a string but a Request, but still survives the checks of <code>StringProperty</code> (in AsyncImage). But that would probably be very unstable and not a "proper" solution. </p>
1
2016-09-21T07:37:39Z
[ "python", "kivy", "kivy-language" ]
Using pre-trained inception_resnet_v2 with Tensorflow
39,582,703
<p>I have been trying to use the pre-trained inception_resnet_v2 model released by Google. I am using their model definition(<a href="https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py" rel="nofollow">https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py</a>) and given checkpoint(<a href="http://download.tensorflow.org/models/inception_resnet_v2_2016_08_30.tar.gz" rel="nofollow">http://download.tensorflow.org/models/inception_resnet_v2_2016_08_30.tar.gz</a>) to load the model in tensorflow as below [Download a extract the checkpoint file and download sample images dog.jpg and panda.jpg to test this code]-</p> <pre><code>import tensorflow as tf slim = tf.contrib.slim from PIL import Image from inception_resnet_v2 import * import numpy as np checkpoint_file = 'inception_resnet_v2_2016_08_30.ckpt' sample_images = ['dog.jpg', 'panda.jpg'] #Load the model sess = tf.Session() arg_scope = inception_resnet_v2_arg_scope() with slim.arg_scope(arg_scope): logits, end_points = inception_resnet_v2(input_tensor, is_training=False) saver = tf.train.Saver() saver.restore(sess, checkpoint_file) for image in sample_images: im = Image.open(image).resize((299,299)) im = np.array(im) im = im.reshape(-1,299,299,3) predict_values, logit_values = sess.run([end_points['Predictions'], logits], feed_dict={input_tensor: im}) print (np.max(predict_values), np.max(logit_values)) print (np.argmax(predict_values), np.argmax(logit_values)) </code></pre> <p>However, the results from this model code does not give the expected results (class no 918 is predicted irrespective of the input image). Can someone help me understand where I am going wrong?</p> <p>Thanks!</p>
2
2016-09-19T21:52:28Z
39,597,537
<p>The Inception networks expect the input image to have color channels scaled from [-1, 1]. As seen <a href="https://github.com/tensorflow/models/blob/master/slim/preprocessing/inception_preprocessing.py#L237-L275" rel="nofollow">here</a>.</p> <p>You could either use the existing preprocessing, or in your example just scale the images yourself: <code>im = 2*(im/255.0)-1.0</code> before feeding them to the network.</p> <p>Without scaling the input [0-255] is much larger than the network expects and the biases all work to very strongly predict category 918 (comic books).</p>
2
2016-09-20T15:01:52Z
[ "python", "computer-vision", "tensorflow", "deep-learning" ]
Running a Python function on Spark Dataframe
39,582,754
<p>I have a python function which basically does some sampling from the original dataset and converts it into training_test. </p> <p>I have written that code to work on pandas data frame. </p> <p>I was wondering if anyone knows how to implement the same on Spark DAtaframe in pyspark?. Instead of Pandas data frame or numpy array mentioned should I use Spark Dataframe and that's it?</p> <p>Please let me know</p> <pre><code>def train_test_split(recommender,pct_test=0.20,alpha=40): """ This function takes a ratings data and splits it into train, validation and test datasets This function will take in the original user-item matrix and "mask" a percentage of the original ratings where a user-item interaction has taken place for use as a test set. The test set will contain all of the original ratings, while the training set replaces the specified percentage of them with a zero in the original ratings matrix. parameters: ratings - the original ratings matrix from which you want to generate a train/test set. Test is just a complete copy of the original set. This is in the form of a sparse csr_matrix. pct_test - The percentage of user-item interactions where an interaction took place that you want to mask in the training set for later comparison to the test set, which contains all of the original ratings. returns: training_set - The altered version of the original data with a certain percentage of the user-item pairs that originally had interaction set back to zero. test_set - A copy of the original ratings matrix, unaltered, so it can be used to see how the rank order compares with the actual interactions. user_inds - From the randomly selected user-item indices, which user rows were altered in the training data. This will be necessary later when evaluating the performance via AUC. """ test_set = recommender.copy() # Make a copy of the original set to be the test set. test_set=(test_set&gt;0).astype(np.int8) training_set = recommender.copy() # Make a copy of the original data we can alter as our training set. nonzero_inds = training_set.nonzero() # Find the indices in the ratings data where an interaction exists nonzero_pairs = list(zip(nonzero_inds[0], nonzero_inds[1])) # Zip these pairs together of user,item index into list random.seed(0) # Set the random seed to zero for reproducibility num_samples = int(np.ceil(pct_test*len(nonzero_pairs))) # Round the number of samples needed to the nearest integer samples = random.sample(nonzero_pairs, num_samples) # Sample a random number of user-item pairs without replacement user_inds = [index[0] for index in samples] # Get the user row indices item_inds = [index[1] for index in samples] # Get the item column indices training_set[user_inds, item_inds] = 0 # Assign all of the randomly chosen user-item pairs to zero conf_set=1+(alpha*training_set) return training_set, test_set, conf_set, list(set(user_inds)) </code></pre>
0
2016-09-19T21:57:55Z
39,585,660
<p>You can use randomSplit function on Spark dataframe. </p>
0
2016-09-20T04:25:46Z
[ "python", "pandas", "apache-spark" ]
Checking the next object in Python list
39,582,797
<p>I have a <code>list</code> (from CSV) with the following information structure:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 3 Item 4 Item 5 NUMBER Random ID </code></pre> <p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 5 NUMBER Random ID </code></pre> <p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p> <p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p> <pre><code>raw_list = [] num = 0 list_with_dicts = [] for x in raw_list: num2 = num + 1 dict1 = {} dict1['index'] = num2 dict1['çontent'] = x list_with_dicts.append(dict1) for d in list_with_dicts: number_of_next_line = d['index'] + 1 if "NUMBER" in raw_list[number_of_next_line]: new_string = "%s %s" % (d[content], raw_list[number_of_next_line]) else: print("String without number") </code></pre> <p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>
0
2016-09-19T22:02:17Z
39,582,895
<pre><code>new_list=[] i=0 while i &lt; len(raw_list)-1: if raw_list[i+1][:len("NUMBER")] == "NUMBER": new_list.append("%s %s" % (raw_list[i], raw_list[i+1])) i=i+2 else: i=i+1 </code></pre>
0
2016-09-19T22:12:56Z
[ "python" ]
Checking the next object in Python list
39,582,797
<p>I have a <code>list</code> (from CSV) with the following information structure:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 3 Item 4 Item 5 NUMBER Random ID </code></pre> <p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 5 NUMBER Random ID </code></pre> <p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p> <p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p> <pre><code>raw_list = [] num = 0 list_with_dicts = [] for x in raw_list: num2 = num + 1 dict1 = {} dict1['index'] = num2 dict1['çontent'] = x list_with_dicts.append(dict1) for d in list_with_dicts: number_of_next_line = d['index'] + 1 if "NUMBER" in raw_list[number_of_next_line]: new_string = "%s %s" % (d[content], raw_list[number_of_next_line]) else: print("String without number") </code></pre> <p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>
0
2016-09-19T22:02:17Z
39,582,898
<p>With <code>enumerate(&lt;list&gt;)</code> you can iterate on indices and elements, so you can easily check the next element:</p> <pre><code>result = [] for i, val in enumerate(lst): if i == len(lst) - 1: break # to avoid IndexError if lst[i + 1][:3] == 'NUM': result.append('%s %s' % (val, lst[i + 1]) </code></pre> <p>Version with functional programming:</p> <pre><code>result = \ list( map( lambda i: '%s %s' % (lst[i - 1], lst[i]), filter( lambda i: lst[i][:3] == 'NUM', range(1, len(lst)) ) ) ) </code></pre>
1
2016-09-19T22:13:16Z
[ "python" ]
Checking the next object in Python list
39,582,797
<p>I have a <code>list</code> (from CSV) with the following information structure:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 3 Item 4 Item 5 NUMBER Random ID </code></pre> <p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 5 NUMBER Random ID </code></pre> <p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p> <p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p> <pre><code>raw_list = [] num = 0 list_with_dicts = [] for x in raw_list: num2 = num + 1 dict1 = {} dict1['index'] = num2 dict1['çontent'] = x list_with_dicts.append(dict1) for d in list_with_dicts: number_of_next_line = d['index'] + 1 if "NUMBER" in raw_list[number_of_next_line]: new_string = "%s %s" % (d[content], raw_list[number_of_next_line]) else: print("String without number") </code></pre> <p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>
0
2016-09-19T22:02:17Z
39,582,977
<p>With list comprehension:</p> <pre><code>result = ["%s %s" % (x,raw_list[i+1]) for i, x in enumerate(raw_list) if i &lt; len(raw_list)-1 and 'NUMBER' in raw_list[i+1]] </code></pre>
1
2016-09-19T22:22:39Z
[ "python" ]
Checking the next object in Python list
39,582,797
<p>I have a <code>list</code> (from CSV) with the following information structure:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 3 Item 4 Item 5 NUMBER Random ID </code></pre> <p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 5 NUMBER Random ID </code></pre> <p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p> <p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p> <pre><code>raw_list = [] num = 0 list_with_dicts = [] for x in raw_list: num2 = num + 1 dict1 = {} dict1['index'] = num2 dict1['çontent'] = x list_with_dicts.append(dict1) for d in list_with_dicts: number_of_next_line = d['index'] + 1 if "NUMBER" in raw_list[number_of_next_line]: new_string = "%s %s" % (d[content], raw_list[number_of_next_line]) else: print("String without number") </code></pre> <p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>
0
2016-09-19T22:02:17Z
39,583,009
<pre><code>result = [] i, l = 0, len(raw_input) while i &lt; l: if 'item' in raw_input[i]: result.append(raw_input[i]) else: result[-1] += raw_input[i] i += 1 return filter(lambda x: 'random' in x.lower(), result) </code></pre>
0
2016-09-19T22:26:54Z
[ "python" ]
Checking the next object in Python list
39,582,797
<p>I have a <code>list</code> (from CSV) with the following information structure:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 3 Item 4 Item 5 NUMBER Random ID </code></pre> <p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 5 NUMBER Random ID </code></pre> <p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p> <p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p> <pre><code>raw_list = [] num = 0 list_with_dicts = [] for x in raw_list: num2 = num + 1 dict1 = {} dict1['index'] = num2 dict1['çontent'] = x list_with_dicts.append(dict1) for d in list_with_dicts: number_of_next_line = d['index'] + 1 if "NUMBER" in raw_list[number_of_next_line]: new_string = "%s %s" % (d[content], raw_list[number_of_next_line]) else: print("String without number") </code></pre> <p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>
0
2016-09-19T22:02:17Z
39,583,045
<p>Fun question!</p> <pre><code>raw_list = ["Item 1", "NUMBER Random ID1", "Item 2", "NUMBER Random ID2", "Item 3", "Item 4", "Item 5", "NUMBER Random ID5"] clean_list = [raw_list[i]+" "+raw_list[i+1] for i in range(0,len(raw_list),2) if "Item" not in raw_list[i+1]] print clean_list </code></pre> <p>Output:</p> <pre><code>['Item 1 NUMBER Random ID1', 'Item 2 NUMBER Random ID2', 'Item 5 NUMBER Random ID5'] </code></pre> <p>You can also use zip to make it shorter but maybe less readable:</p> <pre><code>clean_list1 = [i1+" "+i2 for i1,i2 in zip(raw_list[::2],raw_list[1::2]) if "Item" not in i2] print clean_list1 </code></pre>
2
2016-09-19T22:30:50Z
[ "python" ]
Checking the next object in Python list
39,582,797
<p>I have a <code>list</code> (from CSV) with the following information structure:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 3 Item 4 Item 5 NUMBER Random ID </code></pre> <p>And I would like to create a new <code>list</code> (CSV) that looks like this:</p> <pre><code>Item 1 NUMBER Random ID Item 2 NUMBER Random ID Item 5 NUMBER Random ID </code></pre> <p>So I would like to create a string from <code>Item 1,2,3...</code> and the line under it, if the next line doesn't contain the string <code>NUMBER</code>. </p> <p>I can read the CSV and use it as a list, however I don't know how the track the lines. My first idea is to create a list of dicts where every dict contains the index number of the line and the content, and then I can loop through the <code>list_with_dicts</code> and check the next line from the original list.</p> <pre><code>raw_list = [] num = 0 list_with_dicts = [] for x in raw_list: num2 = num + 1 dict1 = {} dict1['index'] = num2 dict1['çontent'] = x list_with_dicts.append(dict1) for d in list_with_dicts: number_of_next_line = d['index'] + 1 if "NUMBER" in raw_list[number_of_next_line]: new_string = "%s %s" % (d[content], raw_list[number_of_next_line]) else: print("String without number") </code></pre> <p>However I'm not sure that it's the easiest and best way to do it, so I would really appreciate if somebody could show me a simpler workaround if it's possible.</p>
0
2016-09-19T22:02:17Z
39,583,590
<p>Here's a slightly different take on the problem - search for lines that contain the string <code>NUMBER</code> and then join that line with the previous one. This produces simpler code:</p> <pre><code>l = ['Item 1', 'NUMBER Random ID', 'Item 2', 'NUMBER Random ID', 'Item 3', 'Item 4', 'Item 5', 'NUMBER Random ID'] result = [] for i, s in enumerate(l[1:], 1): if 'NUMBER' in s: result.append('{} {}'.format(l[i-1], s)) </code></pre> <p>Or as a list comprehension:</p> <pre><code>result = ['{} {}'.format(l[i-1], s) for i,s in enumerate(l[1:], 1) if 'NUMBER' in s] </code></pre> <p>It's unclear what is expected as output - you mention CSV which implies that the output list should contain individual fields, in which case the result should be a list of lists. Something like this:</p> <pre><code>result = [[l[i-1], s] for i,s in enumerate(l[1:], 1) if 'NUMBER' in s] </code></pre> <p>which would create this list of lists:</p> <pre><code>[['Item 1', 'NUMBER Random ID'], ['Item 2', 'NUMBER Random ID'], ['Item 5', 'NUMBER Random ID']] </code></pre> <p>which can easily be saved to a CSV file with the <code>csv</code> module:</p> <pre><code>import csv with open('result.csv', 'w') as f: csv.writer(f).writerows(result) </code></pre>
2
2016-09-19T23:33:27Z
[ "python" ]
Python Regex remove numbers and numbers with punctaution
39,582,859
<p>I have the following string</p> <pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" </code></pre> <p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p> <p>I have this re nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " ", line)</p> <p>but it is not doing what i hoped it would be doing.</p> <p>Can anyone point me in the right direction?</p>
2
2016-09-19T22:09:22Z
39,582,894
<p>You can use:</p> <pre><code>&gt;&gt;&gt; line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" &gt;&gt;&gt; print re.sub(r'\b\d+(?:\.\d+)?\s+', '', line) https://en.wikipedia.org/wiki/Dictionary_(disambiguation) </code></pre> <p>Regex <code>\b\d+(?:\.\d+)?\s+</code> will match an integer or decimal number followed by 1 or more spaces. <code>\b</code> is for word boundary.</p>
2
2016-09-19T22:12:51Z
[ "python", "regex" ]
Python Regex remove numbers and numbers with punctaution
39,582,859
<p>I have the following string</p> <pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" </code></pre> <p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p> <p>I have this re nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " ", line)</p> <p>but it is not doing what i hoped it would be doing.</p> <p>Can anyone point me in the right direction?</p>
2
2016-09-19T22:09:22Z
39,582,949
<p>Here's a non-regex approach, if your regex requirement is not entirely strict, using <a href="https://docs.python.org/2/library/itertools.html#itertools.dropwhile" rel="nofollow"><code>itertools.dropwhile</code></a>:</p> <pre><code>&gt;&gt;&gt; ''.join(dropwhile(lambda x: not x.isalpha(), line)) 'https://en.wikipedia.org/wiki/Dictionary_(disambiguation)' </code></pre>
1
2016-09-19T22:18:30Z
[ "python", "regex" ]
Python Regex remove numbers and numbers with punctaution
39,582,859
<p>I have the following string</p> <pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" </code></pre> <p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p> <p>I have this re nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " ", line)</p> <p>but it is not doing what i hoped it would be doing.</p> <p>Can anyone point me in the right direction?</p>
2
2016-09-19T22:09:22Z
39,583,039
<p>I think this is what you want:</p> <pre><code>nline = re.sub("\d+\s\d+\.\d+", "", line) </code></pre> <p>It removes the numbers from line. If you want to keep the space in front of "http..." your second parameter should of course be " ".</p> <p>If you also want to record the individual number strings you could put them in groups like this:</p> <pre><code>&gt;&gt;&gt; result = re.search("(\d+)\s(\d+\.\d+)", line) &gt;&gt;&gt; print(result.group(0)) 1234567 7852853427.111 &gt;&gt;&gt; print(result.group(1)) 1234567 &gt;&gt;&gt; print(result.group(2)) 7852853427.111 </code></pre> <p>A great way to learn and practice regular expressions is <a href="http://regex101.com" rel="nofollow">regex101</a>.</p>
0
2016-09-19T22:29:47Z
[ "python", "regex" ]
Python Regex remove numbers and numbers with punctaution
39,582,859
<p>I have the following string</p> <pre><code> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" </code></pre> <p>I would like to remove the numbers 1234567 7852853427.111 using regular expresisions</p> <p>I have this re nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " ", line)</p> <p>but it is not doing what i hoped it would be doing.</p> <p>Can anyone point me in the right direction?</p>
2
2016-09-19T22:09:22Z
39,601,200
<p>Though you are asking for a regular expression, a better solution would be to use <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split</code></a>, assuming that your string will always be in the format <code>{number} {number} {hyperlink}</code>.</p> <p>As @godaygo <a href="http://stackoverflow.com/questions/39582859/python-regex-remove-numbers-and-numbers-with-punctaution#comment66476693_39582859">said</a>, you can use this:</p> <pre><code>line = line.split()[-1] </code></pre> <p>The string will be split on whitespace, and we select the last substring.</p> <p>If you want to access all parts (assuming there's always three), you can use this instead:</p> <pre><code>num1, num2, url = line.split() </code></pre>
0
2016-09-20T18:23:24Z
[ "python", "regex" ]
Pandas: Drop quasi-duplicates by column values
39,582,860
<p>I have a list that, let's say, looks like this (which I'm putting into a DF):</p> <pre><code>[ ['john', '1', '1', '2016'], ['john', '1', '10', '2016'], ['sally', '3', '5', '2016'], ['sally', '4', '1', '2016'] ] </code></pre> <p><code>columns</code> are <code>['name', 'month', 'day', 'year']</code></p> <p>I basically want to output a new DF with only the oldest row for each person. So it should contain two rows, one for john on 1/1/16 and one for sally on 3/5/16.</p> <p>I have always had a tough time with this sort of selection inside DF's and was hoping someone could offer some advice on how to accomplish the above.</p>
1
2016-09-19T22:09:27Z
39,582,963
<p>You can sort the data frame by <code>year, month, day</code> and then take the first row from each <code>name</code>:</p> <pre><code>df.sort_values(by = ['year', 'month', 'day']).groupby('name').first() # month day year # name # john 1 1 2016 #sally 3 5 2016 </code></pre> <p><em>Data</em>:</p> <pre><code>df = pd.DataFrame([['john', '1', '1', '2016'], ['john', '1', '10', '2016'], ['sally', '3', '5', '2016'], ['sally', '4', '1', '2016']], columns = ['name', 'month', 'day', 'year']) </code></pre>
4
2016-09-19T22:20:21Z
[ "python", "pandas" ]
Pandas: Drop quasi-duplicates by column values
39,582,860
<p>I have a list that, let's say, looks like this (which I'm putting into a DF):</p> <pre><code>[ ['john', '1', '1', '2016'], ['john', '1', '10', '2016'], ['sally', '3', '5', '2016'], ['sally', '4', '1', '2016'] ] </code></pre> <p><code>columns</code> are <code>['name', 'month', 'day', 'year']</code></p> <p>I basically want to output a new DF with only the oldest row for each person. So it should contain two rows, one for john on 1/1/16 and one for sally on 3/5/16.</p> <p>I have always had a tough time with this sort of selection inside DF's and was hoping someone could offer some advice on how to accomplish the above.</p>
1
2016-09-19T22:09:27Z
39,582,980
<p><strong><em>Option 1</em></strong><br> use <code>pd.to_datetime</code> to parse ['year', 'month', 'day'] columns.<br> <code>groupby('name')</code> then take <code>first</code></p> <pre><code>df['date'] = pd.to_datetime(df[['year', 'month', 'day']]) df.sort_values(['name', 'date']).groupby('name').first() </code></pre> <p><a href="http://i.stack.imgur.com/eDHDv.png" rel="nofollow"><img src="http://i.stack.imgur.com/eDHDv.png" alt="enter image description here"></a></p> <p><strong><em>Option 2</em></strong><br> Same <code>pd.to_datetime</code> usage.<br> <code>groupby('name')</code> take <code>idxmin</code> to locate smallest date.</p> <pre><code>df['date'] = pd.to_datetime(df[['year', 'month', 'day']]) df.ix[df.groupby('name').date.idxmin()] </code></pre> <p><a href="http://i.stack.imgur.com/Julzk.png" rel="nofollow"><img src="http://i.stack.imgur.com/Julzk.png" alt="enter image description here"></a></p>
0
2016-09-19T22:22:56Z
[ "python", "pandas" ]
"ImportError: No module named google.protobuf" but it's definitely installed
39,582,868
<p>I've installed the <code>protobuf</code> package but I'm unable to import it.</p> <pre><code>&gt; pip uninstall protobuf ... uninstalls &gt; pip install protobuf ... installs. confirm that it's installed: pip install protobuf Requirement already satisfied (use --upgrade to upgrade): protobuf in ./.venv/lib/python3.5/site-packages Requirement already satisfied (use --upgrade to upgrade): setuptools in ./.venv/lib/python3.5/site-packages (from protobuf) Requirement already satisfied (use --upgrade to upgrade): six&gt;=1.9 in ./.venv/lib/python3.5/site-packages (from protobuf) </code></pre> <p>Back in <code>ipython</code>:</p> <pre><code>In [1]: from google.protobuf import descriptor as _descriptor --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-1-3baca6afb060&gt; in &lt;module&gt;() ----&gt; 1 from google.protobuf import descriptor as _descriptor ImportError: No module named google.protobuf In [2]: </code></pre> <p>I'm really stumped.</p> <pre><code>&gt; python --version &gt; Python 3.5.1 &gt; which pip /Users/skyler/work/TemplateProcessor/.venv/bin/pip &gt; pip --version pip 8.1.2 from /Users/skyler/work/TemplateProcessor/.venv/lib/python3.5/site-packages (python 3.5) </code></pre>
0
2016-09-19T22:10:41Z
40,051,428
<p>I had the same issue and found a workaround suggested in <a href="https://github.com/tensorflow/tensorflow/issues/1415" rel="nofollow">this issue</a>: </p> <blockquote> <p>1.Adding a new file tensorflow/google/init.py:</p> <pre><code>try: import pkg_resources pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__) Add namespace_packages to tensorflow/google/protobuf/python/setup.py: setup( name='protobuf', namespace_packages=['google'], ... ) </code></pre> <ol start="2"> <li>Recompile / pip install. Good luck!</li> </ol> </blockquote>
-1
2016-10-14T20:23:06Z
[ "python", "protocol-buffers", "python-3.5" ]
QTimer isn't calling myfunction as expected
39,582,872
<p>In the code below the first function gets called but the second function doesn't. What am I doing wrong?</p> <pre><code>def time_cursor_plot(self): print 'function called' t = QtCore.QTimer() t.setInterval(1000) t.timeout.connect(self.start_timer) t.start() def start_timer(self): print ' this one too' </code></pre>
0
2016-09-19T22:11:07Z
39,585,244
<p>the method start_timer is in the same class? otherwise remove "self".</p> <pre><code>def time_cursor_plot(self): print 'function called' t = QtCore.QTimer() t.setInterval(1000) t.timeout.connect(start_timer) t.start() def start_timer(self): print ' this one too' </code></pre>
1
2016-09-20T03:26:24Z
[ "python", "pyqt4", "qtimer" ]
Django - Understanding RelatedManager remove method
39,582,888
<p>So here I will be using classic Django Blog and Entry models from the documentation (<a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/" rel="nofollow">link</a>). I added <code>null=True</code> to the Entry's blog attribute.</p> <pre><code>&gt;&gt;&gt; cb = Blog.objects.get(name__startswith="Cheese") &gt;&gt;&gt; gouda = Entry.objects.get(headline__startswith="Gouda") &gt;&gt;&gt; cb.entry_set.all() [&lt;Entry: Gouda&gt;, &lt;Entry: Emmentaler&gt;] &gt;&gt;&gt; cb.entry_set.remove(gouda) &gt;&gt;&gt; gouda.blog &lt;Blog: Cheese blog&gt; </code></pre> <p>I know that everything is fine and updated in database and if I query the second line from my example again that <code>gouda.blog</code> is gonna return <code>None</code>, but my question is why is <code>gouda.blog</code> not <code>None</code> without another query? </p> <p>EDIT:</p> <p>So if I understand everything correctly, this is how it works:</p> <pre><code>&gt;&gt;&gt; cb = Blog.objects.get(name__startswith="Cheese") &gt;&gt;&gt; gouda = Entry.objects.get(headline__startswith="Gouda") &gt;&gt;&gt; cb.entry_set.all() [&lt;Entry: Gouda&gt;, &lt;Entry: Emmentaler&gt;] &gt;&gt;&gt; cb.entry_set.remove(gouda) &gt;&gt;&gt; gouda.blog &lt;Blog: Cheese blog&gt; </code></pre> <p>So default value of the <code>bulk</code> argument for the <code>remove()</code> method is <code>True</code>. That means that <code>QuerySet.update()</code> will be used. Object <code>gouda</code> will not be altered at the Python level so the <code>blog</code> attribute will still hold primary key of the "Cheese blog" blog. When we query <code>gouda.blog</code>, we will still get the "Cheese blog" object. </p> <p>But what happens when <code>bulk=False</code> is passed to <code>remove()</code>? From documentation: If bulk=False, the save() method of each individual model instance is called instead.</p> <p>So then I override <code>save()</code> method of the <code>Entry</code> model like this:</p> <pre><code>def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.blog == None: print(id(self)) </code></pre> <p>and then:</p> <pre><code>&gt;&gt;&gt; cb = Blog.objects.get(name__startswith="Cheese") &gt;&gt;&gt; gouda = Entry.objects.get(headline__startswith="Gouda") &gt;&gt;&gt; cb.entry_set.all() [&lt;Entry: Gouda&gt;, &lt;Entry: Emmentaler&gt;] &gt;&gt;&gt; id(gouda) 139797518743592 &gt;&gt;&gt; cb.entry_set.remove(gouda, bulk=False) 139797518745552 &gt;&gt;&gt; gouda.blog &lt;Blog: Cheese blog&gt; </code></pre> <p>Now we see that <code>gouda</code> object that <code>save()</code> method is called on is not the same as the one in our shell, so our object in the shell still holds primary key of "Cheese blog" in its <code>blog</code> attribute. And when we query for the blog with <code>gouda.blog</code> we still get "Cheese blog" object.</p> <p>Is that correct and if it is, why is <code>save()</code> not called on the same object that we passed to <code>remove()</code>?</p>
0
2016-09-19T22:12:21Z
39,587,160
<p>You've said it yourself, you need to go back to the database to get the new information. The <code>gouda</code> object doesn't automatically keep a link to its database row; it only queries it when told to do so.</p>
1
2016-09-20T06:30:43Z
[ "python", "django" ]
Python script uses 100% CPU
39,582,899
<p>Hey I was working with python. In my python file I just have 2 lines like : </p> <pre><code>#!/usr/bin/env print("hello") </code></pre> <p>and I make my .py file executable and run it(./hello.py) on ubuntu server. With "top" command, i listed all processes. hello.py uses 100% CPU. Why it use 100% CPU(Server has 512MB 1 CPU)</p>
0
2016-09-19T22:13:20Z
39,583,053
<p>Your incorrect shebang line of</p> <pre><code>#!/usr/bin/env </code></pre> <p>causes the system to launch <code>/usr/bin/env</code> to handle the script, as follows:</p> <pre><code>/usr/bin/env ./hello.py </code></pre> <p><code>/usr/bin/env</code> treats the first argument not containing <code>=</code> and not starting with <code>-</code> as a program to run, so it tries to launch <code>./hello.py</code>. Due to the incorrect shebang line, this once again runs</p> <pre><code>/usr/bin/env ./hello.py </code></pre> <p>It's an infinite loop.</p>
4
2016-09-19T22:31:25Z
[ "python", "python-3.x" ]
regarding the tensor shape is (?,?,?,1)
39,582,974
<p>During debuging the Tensorflow code, I would like to output the shape of a tensor, say, <code>print("mask's shape is: ",mask.get_shape())</code> However, the corresponding output is <code>mask's shape is (?,?,?,1)</code> How to explain this kind of output, is there anyway to know the exactly value of the first three dimensions of this tensor?</p>
0
2016-09-19T22:21:53Z
39,583,123
<p>This output means that TensorFlow's shape inference has only been able to infer a <em>partial shape</em> for the <code>mask</code> tensor. It has been able to infer (i) that <code>mask</code> is a 4-D tensor, and (ii) its last dimension is 1; but it does not know statically the shape of the first three dimensions.</p> <p>If you want to get the actual shape of the tensor, the main approaches are:</p> <ol> <li>Compute <code>mask_val = sess.run(mask)</code> and print <code>mask_val.shape</code>.</li> <li>Create a symbolic <code>mask_shape = tf.shape(mask)</code> tensor, compute <code>mask_shape_val = sess.run(mask_shape)</code> and print `mask_shape.</li> </ol> <p>Shapes usually have unknown components if the shape depends on the data, or if the tensor is itself a function of some tensor(s) with a partially known shape. If you believe that the shape of the mask <strong>should be</strong> static, you can trace the source of the uncertainty by (recursively) looking at the inputs of the operation(s) that compute <code>mask</code> and finding out where the shape becomes partially known.</p>
0
2016-09-19T22:38:44Z
[ "python", "tensorflow" ]
pandas - Merging on string columns not working (bug?)
39,582,984
<p>I'm trying to do a simple merge between two dataframes. These come from two different SQL tables, where the joining keys are strings:</p> <pre><code>&gt;&gt;&gt; df1.col1.dtype dtype('O') &gt;&gt;&gt; df2.col2.dtype dtype('O') </code></pre> <p>I try to merge them using this:</p> <pre><code>&gt;&gt;&gt; merge_res = pd.merge(df1, df2, left_on='col1', right_on='col2') </code></pre> <p>The result of the inner join is empty, which first prompted me that there might not be any entries in the intersection:</p> <pre><code>&gt;&gt;&gt; merge_res.shape (0, 19) </code></pre> <p>But when I try to match a single element, I see this really odd behavior.</p> <pre><code># Pick random element in second dataframe &gt;&gt;&gt; df2.iloc[5,:].col2 '95498208100000' # Manually look for it in the first dataframe &gt;&gt;&gt; df1[df1.col1 == '95498208100000'] 0 rows × 19 columns # Empty, which makes sense given the above merge result # Now look for the same value as an integer &gt;&gt;&gt; df1[df1.col1 == 95498208100000] 1 rows × 19 columns # FINDS THE ELEMENT!?! </code></pre> <p>So, the columns are defined with the 'object' dtype. Searching for them as strings don't yield any results. Searching for them as integers does return a result, and I think this is the reason why the merge doesn't work above..</p> <p>Any ideas what's going on?</p> <p>It's almost as thought Pandas converts <code>df1.col1</code> to an integer just because it can, even though it <em>should</em> be treated as a string while matching. </p> <p>(I tried to replicate this using sample dataframes, but for small examples, I don't see this behavior. Any suggestions on how I can find a more descriptive example would be appreciated as well.)</p>
0
2016-09-19T22:23:30Z
39,605,926
<p>The issue was that the <code>object</code> dtype is misleading. I thought it mean that all items were strings. But apparently, while reading the file pandas was converting some elements to ints, and leaving the remainders as strings.</p> <p>The solution was to make sure that every field is a string:</p> <pre><code>&gt;&gt;&gt; df1.col1 = df1.col1.astype(str) &gt;&gt;&gt; df2.col2 = df2.col2.astype(str) </code></pre> <p>Then the merge works as expected.</p> <p>(I wish there was a way of specifying a <code>dtype</code> of <code>str</code>...)</p>
0
2016-09-21T00:54:45Z
[ "python", "mysql", "pandas", "merge" ]
If statement with multiple conditions using regex
39,582,988
<p>I would like to loop through pull requests in GitHub and if the pull request has the comments in the code below, do something (for now, print the pull request number). I have a pull request that has the comments I'm looking for (spread over multiple comments in the pull request), but it doesn't print the pull request number. I suspect it has something to do with the regex I'm using because if I break the if statement down to look for just the regex or the string values, it works fine, but when I try to combine them in one if statement, it doesn't work. </p> <p>I don't think this is a duplicate question as I've looked at all the suggestions under questions that may already have your answer.</p> <pre><code> for pr in repo.pull_requests(): #check to ensure pull request meets criteria before processing conflicts_base_branch = "This branch has no conflicts with the base branch" checks = "All checks have passed" sign_off_comment_present = re.compile(r"\B#sign-off\b", re.IGNORECASE) for comment in list(repo.issue(pr.number).comments()): if (conflicts_base_branch and checks in comment.body) and (sign_off_comment_present.search(comment.body)): print(pr.number) </code></pre>
0
2016-09-19T22:23:58Z
39,583,189
<p>Your solution requires all of the conditions to be met on the <em>same</em> comment, it won't work if they are on different comments. For that you need to keep track which conditions are met while iterating through the comments, e.g:</p> <pre><code>for pr in repo.pull_requests(): #check to ensure pull request meets criteria before processing conflicts_base_branch = "This branch has no conflicts with the base branch" checks = "All checks have passed" sign_off_comment_present = re.compile(r"\B#sign-off\b", re.IGNORECASE) passes_checks = False has_signoff = False has_no_conflicts = False for comment in list(repo.issue(pr.number).comments()): if checks in comment.body: passes_checks = True if conflicts_base_branch in comment.body: has_no_conflicts = True if sign_off_comment_present.search(comment.body): has_signoff = True if passes_checks and has_no_conflicts and has_signoff: print(pr.number) </code></pre>
1
2016-09-19T22:46:53Z
[ "python", "if-statement" ]
Update list in-place, converting 'True'/'False' elements to 1/0
39,583,016
<p>In python, supposed I have a list: </p> <pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] </code></pre> <p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p> <pre><code>l = [ 1, 0, 'myname', 1, 0, 'foo' ] </code></pre>
1
2016-09-19T22:27:10Z
39,583,055
<p>List comprehension is your friend:</p> <pre><code>&gt;&gt;&gt; l = [ 'True', 'False', 'myname', 1, 0, 'foo'] &gt;&gt;&gt; mapping = {"True": 1, "False": 0} &gt;&gt;&gt; [mapping.get(x, x) for x in l] </code></pre>
2
2016-09-19T22:31:29Z
[ "python", "list", "dictionary" ]
Update list in-place, converting 'True'/'False' elements to 1/0
39,583,016
<p>In python, supposed I have a list: </p> <pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] </code></pre> <p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p> <pre><code>l = [ 1, 0, 'myname', 1, 0, 'foo' ] </code></pre>
1
2016-09-19T22:27:10Z
39,583,056
<pre><code>&gt;&gt;&gt; replace = {'True':1, 'False':0} &gt;&gt;&gt; my_list = [ 'True', 'False', 'myname', 1, 0, 'foo' ] &gt;&gt;&gt; [replace.get(e,e) for e in my_list] [1, 0, 'myname', 1, 0, 'foo'] &gt;&gt;&gt; </code></pre>
1
2016-09-19T22:31:32Z
[ "python", "list", "dictionary" ]
Update list in-place, converting 'True'/'False' elements to 1/0
39,583,016
<p>In python, supposed I have a list: </p> <pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] </code></pre> <p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p> <pre><code>l = [ 1, 0, 'myname', 1, 0, 'foo' ] </code></pre>
1
2016-09-19T22:27:10Z
39,583,236
<p>Thought I would offer a more robust solution if your list's items are <code>on</code>, <code>off</code>, <code>yes</code>, <code>no</code> etc (<em>refer to <a href="https://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool" rel="nofollow">documentation</a></em>).</p> <pre><code>from distutils.util import strtobool def convert_str_to_bool(l): result = [] for item in l: try: result.append(strtobool(item)) except: result.append(item) return result </code></pre> <p><strong>Sample Output:</strong></p> <pre><code>&gt;&gt;&gt; l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] &gt;&gt;&gt; print convert_str_to_bool(l) [1, 0, 'myname', 1, 0, 'foo'] </code></pre>
1
2016-09-19T22:51:24Z
[ "python", "list", "dictionary" ]
Update list in-place, converting 'True'/'False' elements to 1/0
39,583,016
<p>In python, supposed I have a list: </p> <pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] </code></pre> <p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p> <pre><code>l = [ 1, 0, 'myname', 1, 0, 'foo' ] </code></pre>
1
2016-09-19T22:27:10Z
39,583,283
<p>You can use a for loop</p> <pre><code>for i in l: if i == 'True': a = l.index(i) b = l.remove(i) l.insert(a, 1) elif i == 'False': a = l.index(i) b = l.remove(i) l.insert(a, 0) print(l) </code></pre>
0
2016-09-19T22:56:45Z
[ "python", "list", "dictionary" ]
Update list in-place, converting 'True'/'False' elements to 1/0
39,583,016
<p>In python, supposed I have a list: </p> <pre><code>l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] </code></pre> <p>and I want to convert the <em>strings</em> <code>'True'</code> or <code>'False'</code> to <code>1</code> or <code>0</code>, what is the best way to do this and still retain the index that the value had originally? i.e. the output would look like: </p> <pre><code>l = [ 1, 0, 'myname', 1, 0, 'foo' ] </code></pre>
1
2016-09-19T22:27:10Z
39,583,922
<p>Your problem is similar to <code>switch</code> statement:</p> <pre><code>switch(ch): case "True": return 1 case "False": return 0 default: return ch </code></pre> <p>But since in Python we do not have switch statement but we can achieve similar functionality by creating the function as:</p> <pre><code>def check_for_value(value): return {'True': 1, 'False': 0, }.get(value, value) </code></pre> <p>This function will return <code>0</code> or <code>1</code> based on if the value passed is <code>False</code> or <code>True</code>. Else it will return back the <code>value</code> (similar to <code>default</code> case in <code>switch</code>).</p> <p>Now you can do list comprehension to achieve what you want:</p> <pre><code>&gt;&gt;&gt; l = [ 'True', 'False', 'myname', 1, 0, 'foo' ] &gt;&gt;&gt; [check_for_value(i) for i in l] [1, 0, 'myname', 1, 0, 'foo'] </code></pre> <p>OR, you may use <code>map()</code> instead of list comprehension as:</p> <pre><code>&gt;&gt;&gt; map(check_for_value, l) [1, 0, 'myname', 1, 0, 'foo'] </code></pre>
-1
2016-09-20T00:21:10Z
[ "python", "list", "dictionary" ]
Checksum for a list of numbers
39,583,070
<p>I have a large number of lists of integers. I want to check if any of the lists are duplicates. I was thinking a good way of doing this would be to calculate a basic checksum, then only doing an element by element check if the checksums coincide. But I can't find a checksum algorithm with good properties, namely:</p> <ul> <li>Verifies order effectively;</li> <li>Quick to calculate;</li> <li>Returns a small result, eg short integer;</li> <li>Has a fairly uniform distribution, giving a low probability of different lists coinciding.</li> </ul> <p>For example, a function check_sum which returned different numbers in the range [0,65536] for the following 5 calls would be ideal. </p> <pre><code>check_sum([1,2,3,4,5]) check_sum([1,2,3,5,4]) check_sum([5,4,3,2,1]) check_sum([1,2,3,4,4]) </code></pre> <p>I looked at the IPv4 header checksum algorithm which returns a result of about the right size but doesn't check order so isn't what I'm looking for.</p> <p>I'm going to implement it in python, but any format will do for algorithm, or pointer at a good reference material.</p>
2
2016-09-19T22:33:03Z
39,583,175
<p>Calculate the checksums with <code>hash()</code>:</p> <pre><code>checksums = \ list( map( lambda l: hash(tuple(l)), list_of_lists ) ) </code></pre> <p>To know how many duplicates you have:</p> <pre><code>from collections import Counter counts = Counter(checksums) </code></pre> <p>To compile a unique list:</p> <pre><code>unique_list = list(dict(zip(checksums, list_of_lists)).values()) </code></pre>
0
2016-09-19T22:44:22Z
[ "python", "algorithm", "checksum" ]
Checksum for a list of numbers
39,583,070
<p>I have a large number of lists of integers. I want to check if any of the lists are duplicates. I was thinking a good way of doing this would be to calculate a basic checksum, then only doing an element by element check if the checksums coincide. But I can't find a checksum algorithm with good properties, namely:</p> <ul> <li>Verifies order effectively;</li> <li>Quick to calculate;</li> <li>Returns a small result, eg short integer;</li> <li>Has a fairly uniform distribution, giving a low probability of different lists coinciding.</li> </ul> <p>For example, a function check_sum which returned different numbers in the range [0,65536] for the following 5 calls would be ideal. </p> <pre><code>check_sum([1,2,3,4,5]) check_sum([1,2,3,5,4]) check_sum([5,4,3,2,1]) check_sum([1,2,3,4,4]) </code></pre> <p>I looked at the IPv4 header checksum algorithm which returns a result of about the right size but doesn't check order so isn't what I'm looking for.</p> <p>I'm going to implement it in python, but any format will do for algorithm, or pointer at a good reference material.</p>
2
2016-09-19T22:33:03Z
39,599,425
<p>If you want something homespun, a version of a Fletcher checksum is possible.</p> <pre><code>def check_sum(l): sum1 = sum2 = 0 for v in l: sum1 = (sum1 + v) % 255 sum2 = (sum2 + sum1) % 255 return sum1*256 + sum2 print( check_sum([1,2,3,4,5]), check_sum([1,2,3,5,4]), check_sum([5,4,3,2,1]), check_sum([1,2,3,4,4]) ) </code></pre>
0
2016-09-20T16:32:44Z
[ "python", "algorithm", "checksum" ]
In Sikuli, How to find and click a minimum of 3 identical images?
39,583,103
<p>I'm trying to click no less than 3 of the same image, but with <code>findAll()</code> I am having difficulty with sikuli wanting to select only 1 image when I don't want it to select any if there is not 3 or more.</p> <pre><code>if exists(Pattern("1474201252795.png").similar(0.95)): wait(1) for x in findAll(Pattern("1474201252795.png").similar(0.95)): click(x) </code></pre>
1
2016-09-19T22:37:19Z
39,584,678
<p>So just count the images first and check if the count is higher than 3.</p> <pre><code>imageCount=0 images = [] # find all images and store them in a list to prevent additional search for image in findAll("Win7StartBtn.png"): images.append(image) #check list length and act accordingly if len(images) &gt;= 3: for image in images: image.click() </code></pre>
1
2016-09-20T02:09:14Z
[ "python", "automation", "jython", "sikuli" ]
Unexpected error while trying to find the longest string
39,583,131
<p>I failed to write a program that prints the longest substring of a string in which the letters occur in alphabetical order for my very first Python test. </p> <p>The comment read </p> <blockquote> <p>"Your program does meet what the question asks but also contradicts with rule number 4 and hence your answer will not be accepted"</p> </blockquote> <p>So here was my attempt of the code :</p> <pre><code>def obtain_longest_substring(string): current_substring = longest_substring = string[0] for letter in string[1:]: if letter &gt;= current_substring[-1]: current_substring += letter if len(current_substring) &gt; len(longest_substring): longest_substring = current_substring else: current_substring = letter return longest_substring def main(): s = input("Enter a string: ") print("Longest substring in alphabetical order is: " + obtain_longest_substring(s)) if __name__ == "__main__": main() </code></pre> <p>But the solution that was expected had some rules that I had to follow. Rule Number 4 said: </p> <blockquote> <p>For problems such as these, do not include input statements or define variables which are already mentioned. Our automated testing will provide values for you.</p> </blockquote> <p>I am new to Python. Can anyone tell me what I am doing wrong?</p>
0
2016-09-19T22:39:43Z
39,583,172
<p>The rule says "do not include input statements"; you included an input statement (in <code>main</code>).</p>
0
2016-09-19T22:44:02Z
[ "python", "python-3.x" ]
Unexpected error while trying to find the longest string
39,583,131
<p>I failed to write a program that prints the longest substring of a string in which the letters occur in alphabetical order for my very first Python test. </p> <p>The comment read </p> <blockquote> <p>"Your program does meet what the question asks but also contradicts with rule number 4 and hence your answer will not be accepted"</p> </blockquote> <p>So here was my attempt of the code :</p> <pre><code>def obtain_longest_substring(string): current_substring = longest_substring = string[0] for letter in string[1:]: if letter &gt;= current_substring[-1]: current_substring += letter if len(current_substring) &gt; len(longest_substring): longest_substring = current_substring else: current_substring = letter return longest_substring def main(): s = input("Enter a string: ") print("Longest substring in alphabetical order is: " + obtain_longest_substring(s)) if __name__ == "__main__": main() </code></pre> <p>But the solution that was expected had some rules that I had to follow. Rule Number 4 said: </p> <blockquote> <p>For problems such as these, do not include input statements or define variables which are already mentioned. Our automated testing will provide values for you.</p> </blockquote> <p>I am new to Python. Can anyone tell me what I am doing wrong?</p>
0
2016-09-19T22:39:43Z
39,583,191
<p>The rule clearly states <strong>not</strong> to include <code>input</code> statements or define variables (which you also did).</p> <p>You could try re-writing it as :</p> <pre><code>current_substring = longest_substring = s[0] for letter in s[1:]: if letter &gt;= current_substring[-1]: current_substring += letter if len(current_substring) &gt; len(longest_substring): longest_substring = current_substring else: current_substring = letter print("Longest substring in alphabetical order is: " + str(longest_substring)) </code></pre>
0
2016-09-19T22:47:15Z
[ "python", "python-3.x" ]
Pandas - is it possible to "rewind" read_csv with chunk= argument?
39,583,153
<p>I am dealing with a big dataset, therefore to read it in pandas I use <code>read_csv</code> with <code>chunk=</code> option.</p> <pre><code>data = pd.read_csv("dataset.csv", chunksize=2e5) </code></pre> <p>then I operate on the chunked DataFrame in the following way</p> <pre><code>any_na_cols = [chunk.do_something() for chunk in data] </code></pre> <p>the problem is, when I want to do something else in the same way as above, I will get an empty result because I have iterated over chunked DataFrame already. Therefore I would have to call <code>data = pd.read_csv("dataset.csv", chunksize=2e5)</code> again to perform next operation.</p> <p>Most likely there is no problem with that, but for some reason I feel that this approach is inelegant in some way. Isn't there a method like <code>data.rewind()</code> or something similar that would enable me to iterate through the chunks again? I could not find anything like that in the Documentation. Or maybe I am comitting some design mistake with that approach?</p>
0
2016-09-19T22:41:29Z
39,583,217
<p>I don't think it's a good idea to read your CSV <strong>again</strong> - you will double the number of IOs. It's better to "do something else" during the same iteration:</p> <pre><code>any_na_cols = pd.DataFrame() for chunk in pd.read_csv("dataset.csv", chunksize=2e5) any_na_cols = pd.concat([any_na_cols, chunk.do_something()], ignore_index=True) # do something else </code></pre>
1
2016-09-19T22:50:03Z
[ "python", "pandas", "chunks", "chunking" ]
how to pass realtime form arguments to a python script called by a django app
39,583,157
<p>my django app calls a python cgi script:</p> <pre><code>def query(request): if request.method == 'GET': output = subprocess.check_output(['python', 'query.cgi']).decode('utf-8') return HttpResponse(output, content_type="text/html") </code></pre> <p>The query.cgi will be called by a form. How do I pass form args like "name=one&amp;type=two" to the cgi. When I do subprocess.check_output(['python', 'query.cgi', 'name=one', 'type=two']). It works, but how do I pass the realtime online form input to cgi? Thanks a lot!</p>
0
2016-09-19T22:41:51Z
39,583,235
<p>They're passed in the <code>GET</code> dictionary from <code>request</code>:</p> <pre><code>foo = request.GET['foo'] subprocess.check_output(['python', 'query.cgi', 'foo=' + foo]) </code></pre> <p>You can also use</p> <pre><code>request.GET.get('foo', 'def') </code></pre> <p>to have a default value if the key is missing.</p>
0
2016-09-19T22:51:19Z
[ "python", "django" ]
What Is The Python 3 Equivalent to This
39,583,222
<p>What is the Python 3 equivalent to Python 2's statement:</p> <pre><code>print x, </code></pre> <p>I am aware of Python's 3</p> <pre><code>print(x,end=' ') </code></pre> <p>However this is not exactly the same as I will demonstrate.</p> <p>So lets say I had a list of items I wanted to print out all on one line with spaces in between each item BUT NOT after the last item.</p> <p>In Python 2 it is just simply:</p> <pre><code>for x in my_list: print x, </code></pre> <p>However if we use the Python 3 approach above it will produce the list of items on one line but will have trailing white space after the last item.</p> <p>Does Python 3 have a nice elegant solution to produce the same results as in the Python 2 statement?</p>
1
2016-09-19T22:50:33Z
39,583,261
<p>If you do not require the loop, you can just print it all at once:</p> <pre><code>print(" ".join(my_list.join)) </code></pre>
0
2016-09-19T22:53:59Z
[ "python", "printing", "trailing" ]
What Is The Python 3 Equivalent to This
39,583,222
<p>What is the Python 3 equivalent to Python 2's statement:</p> <pre><code>print x, </code></pre> <p>I am aware of Python's 3</p> <pre><code>print(x,end=' ') </code></pre> <p>However this is not exactly the same as I will demonstrate.</p> <p>So lets say I had a list of items I wanted to print out all on one line with spaces in between each item BUT NOT after the last item.</p> <p>In Python 2 it is just simply:</p> <pre><code>for x in my_list: print x, </code></pre> <p>However if we use the Python 3 approach above it will produce the list of items on one line but will have trailing white space after the last item.</p> <p>Does Python 3 have a nice elegant solution to produce the same results as in the Python 2 statement?</p>
1
2016-09-19T22:50:33Z
39,583,278
<p>Unless you need to print each element on their own, you can do:</p> <pre><code>print(' '.join(my_list)) </code></pre> <p>or</p> <pre><code>print(*my_list) </code></pre>
1
2016-09-19T22:55:54Z
[ "python", "printing", "trailing" ]
Pandas: strip numbers and parenthesis from string
39,583,264
<p>My pandas df:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3,4,5], 'B':['(AAAAA)2','(BCA)1','(CA)5','(DD)8','(ED)15']}) A B 0 1 (AAAAA)2 1 2 (BCA)1 2 3 (CA)5 3 4 (DD)8 4 5 (ED)15 </code></pre> <p>I want to strip parenthsis and numbers in the column <code>B</code> <br> Expected output is:</p> <pre><code> A B 0 1 AAAAA 1 2 BCA 2 3 CA 3 4 DD 4 5 ED </code></pre> <p>So far I tried, </p> <pre><code>df['B'] = df['B'].str.extract('([ABCDE])') </code></pre> <p>But I only got:</p> <pre><code> A B 0 1 A 1 2 B 2 3 C 3 4 D 4 5 E </code></pre>
2
2016-09-19T22:54:12Z
39,583,276
<p>you can do it this way:</p> <pre><code>In [388]: df Out[388]: A B 0 1 (AAAAA)2 1 2 (BCA)1 2 3 (CA)5 3 4 (DD)8 4 5 (ED)15 In [389]: df.B = df.B.str.replace(r'[\(\)\d]+', '') In [390]: df Out[390]: A B 0 1 AAAAA 1 2 BCA 2 3 CA 3 4 DD 4 5 ED </code></pre> <p>if you still want to use <code>.str.extract()</code> you can do it this way:</p> <pre><code>In [401]: df['B'].str.extract(r'.*?([A-Za-z]+).*?', expand=True) Out[401]: 0 0 AAAAA 1 BCA 2 CA 3 DD 4 ED </code></pre>
4
2016-09-19T22:55:53Z
[ "python", "regex", "pandas", "dataframe", "python-3.5" ]
How to handle microseconds with 7 decimal precision instead of 6
39,583,265
<p>I am processing a csv in <code>python</code> (3.5) that has a date field in it. The date contains a microsecond precision of 7 rather than 6, which I believe is the max that <code>strptime</code> can handle. </p> <p>Without stripping the field the last character, is there a way to make this a datetime object?</p> <p>Here is the specific code: </p> <pre><code>d = '2015-07-03 17:29:34.5940379' pd.datetime.strptime(d, '%Y-%m-%d %H:%M:%S.%f') ValueError: unconverted data remains: 9 </code></pre>
2
2016-09-19T22:54:26Z
39,583,462
<p>If that's the format your numbers are in, just use <code>pd.to_timestamp(d)</code></p> <p>datetime.datetime objects only have microsecond resolution (6 digits), but <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#converting-to-timestamps" rel="nofollow">Pandas Timestamps</a> are Numpy datetime64 objects.</p>
2
2016-09-19T23:16:06Z
[ "python", "strptime" ]