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
Can't View Complete Page Source in Selenium
39,047,079
<p>When I view the source HTML after manually navigating to the site via Chrome I can see the full page source but on loading the page source via selenium I'm not getting the complete page source.</p> <pre><code>from bs4 import BeautifulSoup from selenium import webdriver import sys,time driver = webdriver.Chrome(executable_path=r"C:\Python27\Scripts\chromedriver.exe") driver.get('http://www.magicbricks.com/') driver.find_element_by_id("buyTab").click() time.sleep(5) driver.find_element_by_id("keyword").send_keys("Navi Mumbai") time.sleep(5) driver.find_element_by_id("btnPropertySearch").click() time.sleep(30) content = driver.page_source.encode('utf-8').strip() soup = BeautifulSoup(content,"lxml") print soup.prettify() </code></pre>
0
2016-08-19T20:19:09Z
39,047,407
<p>The website is possibly blocking or restricting the user agent for selenium. An easy test is to change the user agent and see if that does it. More info at this question: </p> <p><a href="http://stackoverflow.com/questions/29916054/change-user-agent-for-selenium-driver">Change user agent for selenium driver</a></p> <p>Quoting:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options opts = Options() opts.add_argument("user-agent=whatever you want") driver = webdriver.Chrome(chrome_options=opts) </code></pre>
0
2016-08-19T20:45:03Z
[ "python", "selenium", "selenium-webdriver", "bs4" ]
Python IDLE not executing "for loop" print statements
39,047,127
<p>Can someone tell me why the simple "words" for loop shown below, and others like it (all of them copied from Python.org), didn't print in IDLE when I ran the print statements? When the print statement below and the others tested were run in the Python 2.7.12 shell, the function merely skipped to the next blank indented line without printing anything. (I tried running the print line both with and without indentation and parentheses.)</p> <pre><code>&gt;&gt;&gt; words = ['cat', 'window', 'defenestrate'] &gt;&gt;&gt; for w in words: print w, len(w) </code></pre>
0
2016-08-19T20:23:29Z
39,047,156
<p>Fix your indentation like so:</p> <pre><code>words = ['cat','window','defenstrate'] for w in words: print(w, len(w)) </code></pre>
0
2016-08-19T20:26:05Z
[ "python" ]
Python IDLE not executing "for loop" print statements
39,047,127
<p>Can someone tell me why the simple "words" for loop shown below, and others like it (all of them copied from Python.org), didn't print in IDLE when I ran the print statements? When the print statement below and the others tested were run in the Python 2.7.12 shell, the function merely skipped to the next blank indented line without printing anything. (I tried running the print line both with and without indentation and parentheses.)</p> <pre><code>&gt;&gt;&gt; words = ['cat', 'window', 'defenestrate'] &gt;&gt;&gt; for w in words: print w, len(w) </code></pre>
0
2016-08-19T20:23:29Z
39,047,162
<p>Indentation! 4 spaces in the next line after the for loop!</p> <pre><code>words = ['cat', 'window', 'defenestrate'] &gt;&gt;&gt; for w in words: ... print w ... cat window defenestrate &gt;&gt;&gt; </code></pre>
2
2016-08-19T20:26:36Z
[ "python" ]
Python IDLE not executing "for loop" print statements
39,047,127
<p>Can someone tell me why the simple "words" for loop shown below, and others like it (all of them copied from Python.org), didn't print in IDLE when I ran the print statements? When the print statement below and the others tested were run in the Python 2.7.12 shell, the function merely skipped to the next blank indented line without printing anything. (I tried running the print line both with and without indentation and parentheses.)</p> <pre><code>&gt;&gt;&gt; words = ['cat', 'window', 'defenestrate'] &gt;&gt;&gt; for w in words: print w, len(w) </code></pre>
0
2016-08-19T20:23:29Z
39,047,176
<p>You need a tab after any for loop.</p> <pre><code>words = ['cat', 'window', 'defenestrate'] for w in words: print w, len(w) </code></pre> <p>Your code works fine.</p>
0
2016-08-19T20:28:03Z
[ "python" ]
certificate verify failed (_ssl.c:645)>” for one particuar domain
39,047,406
<p>Every request to this one particular domain now ends in an certificate verify failed (_ssl.c:645)></p> <p>I am not sure what caused this.I've been searching for an answer since last night trying to figure out how to fix it, but somehow I cant get it running.</p> <p>I tried pip uninstall -y certifi &amp;&amp; pip install certifi==2015.04.28 but it did not help.</p> <p>Here is my code:</p> <pre><code>def trade_spider(max_pages): page = -1 partner_ID = 2 location_ID = 25 already_printed = set() for page in range(0,20): response = urllib.request.urlopen("http://www.getyourguide.de/s/search.json?q=" + str(Region) +"&amp;page=" + str(page)) jsondata = json.loads(response.read().decode("utf-8")) format = (jsondata['activities']) g_data = format.strip("'&lt;&gt;()[]\"` ").replace('\'', '\"') soup = BeautifulSoup(g_data) hallo = soup.find_all("article", {"class": "activity-card activity-card-horizontal "}) for item in hallo: headers = item.find_all("h3", {"class": "activity-card-title"}) for header in headers: header_final = header.text.strip() if header_final not in already_printed: already_printed.add(header_final) prices = item.find_all("span", {"class": "price"}) for price in prices: #itemStr += ("\t" + price.text.strip().replace(",","")[2:]) price_final = price.text.strip().replace(",","")[2:] #if itemStr2 not in already_printed: #print(itemStr2) #already_printed.add(itemStr2) deeplinks = item.find_all("a", {"class": "activity-card-link"}) for t in set(t.get("href") for t in deeplinks): #itemStr += "\t" + t deeplink_final = t if deeplink_final not in already_printed: #print(itemStr3) already_printed.add(deeplink_final) Language = "Deutsch" end_final = "Header: " + header_final + " | " + "Price: " + str(price_final) + " | " + "Deeplink: " + deeplink_final + " | " + "PartnerID: " + str(partner_ID) + " | " + "LocationID: " + str(location_ID)+ " | " + "Language: " + Language if end_final not in already_printed: print(end_final) already_printed.add(end_final) </code></pre> <p>trade_spider(int(Spider))</p> <p>This is the ouput:</p> <pre><code> Traceback (most recent call last): File "C:\Python34\lib\urllib\request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "C:\Python34\lib\http\client.py", line 1083, in request self._send_request(method, url, body, headers) File "C:\Python34\lib\http\client.py", line 1128, in _send_request self.endheaders(body) File "C:\Python34\lib\http\client.py", line 1079, in endheaders self._send_output(message_body) File "C:\Python34\lib\http\client.py", line 911, in _send_output self.send(msg) File "C:\Python34\lib\http\client.py", line 854, in send self.connect() File "C:\Python34\lib\http\client.py", line 1237, in connect server_hostname=server_hostname) File "C:\Python34\lib\ssl.py", line 376, in wrap_socket _context=self) File "C:\Python34\lib\ssl.py", line 747, in __init__ self.do_handshake() File "C:\Python34\lib\ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "C:\Python34\lib\ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Rj/Desktop/ crawling scripts/GetyourGuide_International_Final.py", line 84, in &lt;module&gt; trade_spider(int(Spider)) File "C:/Users/Raju/Desktop/scripts/GetyourGuide_International_Final.py", line 36, in trade_spider response = urllib.request.urlopen("http://www.getyourguide.com/s/search.json?q=" + str(Region) +"&amp;page=" + str(page)) File "C:\Python34\lib\urllib\request.py", line 162, in urlopen return opener.open(url, data, timeout) File "C:\Python34\lib\urllib\request.py", line 471, in open response = meth(req, response) File "C:\Python34\lib\urllib\request.py", line 581, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python34\lib\urllib\request.py", line 503, in error result = self._call_chain(*args) File "C:\Python34\lib\urllib\request.py", line 443, in _call_chain result = func(*args) File "C:\Python34\lib\urllib\request.py", line 686, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "C:\Python34\lib\urllib\request.py", line 465, in open response = self._open(req, data) File "C:\Python34\lib\urllib\request.py", line 483, in _open '_open', req) File "C:\Python34\lib\urllib\request.py", line 443, in _call_chain result = func(*args) File "C:\Python34\lib\urllib\request.py", line 1283, in https_open context=self._context, check_hostname=self._check_hostname) File "C:\Python34\lib\urllib\request.py", line 1242, in do_open raise URLError(err) </code></pre> <p>urllib.error.URLError: </p> <p>Can someone help me out? Any feedback is aprreciated:)</p>
0
2016-08-19T20:44:56Z
39,047,528
<p>I would investigate further by checking if openssl can verify the certificate:</p> <pre><code>openssl s_client -showcerts -connect www.getyourguide.de:443 </code></pre>
-1
2016-08-19T20:55:06Z
[ "python", "python-3.x", "ssl", "web-crawler", "python-requests" ]
How to refresh data in PyQt TableWidget?
39,047,408
<p>For example, I have a SQLite database and I grab data from this database and put it into <code>QTableWidget</code>. But then, I make some stuff with this data.</p> <p>So, how can I update data in this table without <code>setItem</code> method?</p>
0
2016-08-19T20:45:08Z
39,055,713
<p>Use a <a href="http://doc.qt.io/qt-5/qtableview.html" rel="nofollow"><code>QTableView</code></a> instead, where you can dynamically change the data in the underlying model (e.g. a <a href="http://doc.qt.io/qt-5/qstandarditemmodel.html" rel="nofollow"><code>QStandardItemModel</code></a>). In your case, you might even be able to simply use a <a href="http://doc.qt.io/qt-5/qsqlquerymodel.html" rel="nofollow"><code>QSqlQueryModel</code></a> or <a href="http://doc.qt.io/qt-5/qsqltablemodel.html" rel="nofollow"><code>QSqlTableModel</code></a> with your database.</p>
0
2016-08-20T15:20:50Z
[ "python", "sqlite", "pyqt" ]
Python: Use single login for multiple request
39,047,458
<p>There is some random website, <a href="http://www.example.com" rel="nofollow">http://www.example.com</a>. This website use HTTP basic authentication.</p> <p>I would like to make multiple requests to this site. But I don't want to login for each of the requests.</p> <p>I have written the following code:</p> <pre><code>def loginWeb(): global cookie homeURL = "https://www.example.com" request = urllib2.Request(homeURL) base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) response = urllib2.urlopen(request) cookie = response.headers.get('Set-Cookie') </code></pre> <p>The aforementioned code fetches the cookie and uses it for subsequent requests. </p> <p>The following code makes the subsequent request:</p> <pre><code>def getHTMLSourceCode(ID): opener = urllib2.build_opener() opener.addheaders.append(('Cookie', cookie)) response = opener.open('https://www.example.com/' + trID) sourceCode = response.read() </code></pre> <p>However, <code>opener.open</code> throws <code>urllib2.HTTPError: HTTP Error 401: Unauthorized</code>.</p> <p>I also tried the following code, but this also throws the same error:</p> <pre><code>def getHTMLSourceCode(trID): request = urllib2.Request("https://www.example.com/" + trID) request.add_header('cookie', cookie) response = urllib2.urlopen(request) sourceCode = response.read() return sourceCode </code></pre> <p><code>urllib2.urlopen(request)</code> throws <code>urllib2.HTTPError: HTTP Error 401: Unauthorized</code>.</p> <p>By the way, I went through following answers, but the problem still persists.</p> <p><a href="http://stackoverflow.com/questions/635113/python-urllib2-basic-http-authentication-and-tr-im">Python urllib2, basic HTTP authentication, and tr.im</a></p> <p><a href="http://stackoverflow.com/questions/923296/keeping-a-session-in-python-while-making-http-requests">Keeping a session in python while making HTTP requests</a></p> <p><a href="http://stackoverflow.com/questions/3334809/python-urllib2-how-to-send-cookie-with-urlopen-request">python: urllib2 how to send cookie with urlopen request</a></p>
1
2016-08-19T20:50:10Z
39,047,864
<p>You may want to try <code>requests</code> library and use it <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">Session object</a></p> <pre><code>s = requests.Session() s.auth = (username, password) s.get(homeURL) </code></pre> <p>The cookie will be set to your session cookie <code>s.cookies</code> and you can use this session for other requests.</p>
0
2016-08-19T21:23:45Z
[ "python", "session", "cookies", "urllib2", "urllib" ]
Replacing different characters in Python
39,047,474
<p>Suppose you have a string which you want to parse into a specific format. That means: replace <strong>all</strong> <code>' ', '.', '-', etc with '_'</code>.</p> <p>I know that I could do this:</p> <pre><code>&gt;s = "Hello----..... World" &gt;s = s.replace('-','_').replace('.', '_').replace(' ', '_') &gt;print s &gt;Hello_____________World </code></pre> <p>And get what I want. But, is there a cleaner way? A more <code>pythonic</code> way? I tried parsing a list in to the first argument of replace, but that didn't work very well.</p>
0
2016-08-19T20:51:31Z
39,047,518
<p>Use <a href="https://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code></a></p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; print re.sub(' |\.|-', '_',"Hello----..... World") Hello_____________World </code></pre> <p>Bonus solution <em>not</em> using regex:</p> <pre><code>&gt;&gt;&gt; keys = [' ', '.', '-'] &gt;&gt;&gt; print ''.join('_' if c in keys else c for c in "Hello----..... World") Hello_____________World </code></pre>
2
2016-08-19T20:54:26Z
[ "python", "string", "replace" ]
Replacing different characters in Python
39,047,474
<p>Suppose you have a string which you want to parse into a specific format. That means: replace <strong>all</strong> <code>' ', '.', '-', etc with '_'</code>.</p> <p>I know that I could do this:</p> <pre><code>&gt;s = "Hello----..... World" &gt;s = s.replace('-','_').replace('.', '_').replace(' ', '_') &gt;print s &gt;Hello_____________World </code></pre> <p>And get what I want. But, is there a cleaner way? A more <code>pythonic</code> way? I tried parsing a list in to the first argument of replace, but that didn't work very well.</p>
0
2016-08-19T20:51:31Z
39,047,530
<p>Use <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Regular Expressions</a>.</p> <p>Ex:</p> <pre><code>import re s = "Hello----..... World" print(re.sub(r"[ .-]", "_", s)) </code></pre> <p>Here is the <a href="https://docs.python.org/2/howto/regex.html" rel="nofollow">Python tutorial</a>.</p>
2
2016-08-19T20:55:17Z
[ "python", "string", "replace" ]
Replacing different characters in Python
39,047,474
<p>Suppose you have a string which you want to parse into a specific format. That means: replace <strong>all</strong> <code>' ', '.', '-', etc with '_'</code>.</p> <p>I know that I could do this:</p> <pre><code>&gt;s = "Hello----..... World" &gt;s = s.replace('-','_').replace('.', '_').replace(' ', '_') &gt;print s &gt;Hello_____________World </code></pre> <p>And get what I want. But, is there a cleaner way? A more <code>pythonic</code> way? I tried parsing a list in to the first argument of replace, but that didn't work very well.</p>
0
2016-08-19T20:51:31Z
39,047,688
<p><a href="http://stackoverflow.com/a/27086669">This answer</a> lays out a variety of different ways to accomplish this task, contrasting different functions and inputs by speed. </p> <p>If you are replacing few characters, the fastest way is the way in your question, by chaining multiple replaces, with regular expressions <strong>being the slowest</strong>. </p> <p>If you want to make this more 'pythonic', the best way to leverage both <strong>speed</strong> <em>and</em> <strong>readability</strong>, is to make a list of the characters you want to replace, and loop through them.</p> <pre><code>text = "Hello----..... World" for ch in [' ', '.', '-']: if ch in text: text = text.replace(ch,'_') </code></pre>
0
2016-08-19T21:07:26Z
[ "python", "string", "replace" ]
Replacing different characters in Python
39,047,474
<p>Suppose you have a string which you want to parse into a specific format. That means: replace <strong>all</strong> <code>' ', '.', '-', etc with '_'</code>.</p> <p>I know that I could do this:</p> <pre><code>&gt;s = "Hello----..... World" &gt;s = s.replace('-','_').replace('.', '_').replace(' ', '_') &gt;print s &gt;Hello_____________World </code></pre> <p>And get what I want. But, is there a cleaner way? A more <code>pythonic</code> way? I tried parsing a list in to the first argument of replace, but that didn't work very well.</p>
0
2016-08-19T20:51:31Z
39,055,899
<p>You can do it using <a href="https://docs.python.org/2/library/string.html#string.translate" rel="nofollow"><em>str.translate</em></a> and <a href="https://docs.python.org/2/library/string.html#string.maketrans" rel="nofollow">string.maketrans</a> which will be the most efficient approach not chaining calls etc..:</p> <pre><code>In [6]: from string import maketrans In [7]: s = "Hello----..... World" In [8]: table = maketrans(' .-',"___") In [9]: print(s.translate(table)) Hello_____________World </code></pre> <p>The timings:</p> <pre><code>In [12]: %%timeit ....: s = "Hello----..... World" ....: table = maketrans(' .-',"___") ....: s.translate(table) ....: 1000000 loops, best of 3: 1.14 µs per loop In [13]: timeit s.replace('-','_').replace('.', '_').replace(' ', '_') 100000 loops, best of 3: 2.2 µs per loop In [14]: %%timeit text = "Hello----..... World" for ch in [' ', '.', '-']: if ch in text: text = text.replace(ch,'_') ....: 100000 loops, best of 3: 3.51 µs per loop In [18]: %%timeit ....: s = "Hello----..... World" ....: re.sub(r"[ .-]", "_", s) ....: 100000 loops, best of 3: 11 µs per loop </code></pre> <p>Even pre-compiling the pattern leaves around <em>10µs</em> so the regex is by far the least efficient approach.</p> <pre><code>In [20]: patt= re.compile(r"[ .-]") In [21]: %%timeit s = "Hello----..... World" patt.sub( "_", s) ....: 100000 loops, best of 3: 9.98 µs per loop </code></pre> <p>Pre creating the table gets us down to nanoseconds:</p> <pre><code>In [22]: %%timeit s = "Hello----..... World" s.translate(table) ....: 1000000 loops, best of 3: 590 ns per loop </code></pre>
1
2016-08-20T15:38:47Z
[ "python", "string", "replace" ]
Append elements of an arbitrarily nested list in a depth first search-esque manner, without recursion
39,047,478
<p>The list can be deeper, or shallower, but say I have a list of depth 2 as follows:</p> <pre><code>a = [['a','b'],['c','d'],['e','f']] </code></pre> <p>I want to write a function, <code>f(a)</code>, such that it would return the following new list:</p> <pre><code>['acef', 'adef', 'bcef', 'bdef'] </code></pre> <p>Essentially I am mimicking depth first search, where the lists are nodes. I want the function to work with depth=n, where n is any arbitrary integer. What is the most pythonic way to achieve this?</p> <p>My recursive code is as follows:</p> <pre><code>def f(elems): curr, *rest = elems if not rest: return ''.join(curr) ret = [''.join(x + f(rest)) for x in curr] return ret </code></pre> <p>How would I go about solving this iteratively? </p>
-1
2016-08-19T20:51:48Z
39,047,671
<p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a>:</p> <pre><code>import itertools def f(elems): *branches, leaves = elems for path in itertools.product(*branches): yield ''.join(itertools.chain(path, leaves)) a = [['a','b'],['c','d'],['e','f']] print(list(f(a))) </code></pre> <p>This gives:</p> <pre><code>['acef', 'adef', 'bcef', 'bdef'] </code></pre>
1
2016-08-19T21:05:50Z
[ "python", "depth-first-search" ]
Open a text file with python as a form and know when it closes
39,047,571
<p>I want to make a python script that opens a text file that the user can update before continuing (for configurations) and then continue the script once the text editor closes. Is there something in python that will allow me to do this?</p>
1
2016-08-19T20:58:22Z
39,047,661
<p>on windows using notepad:</p> <pre><code>import os cf = "config.txt" # or full path if you like if not os.path.exists(cf): f = open(cf,"w"); f.close() # create to avoid notepad message os.system("notepad "+cf) # call waits until user closes the file # now the file has been edited by the user </code></pre>
1
2016-08-19T21:04:41Z
[ "python", "file" ]
MySQL db returns Decimal('number') values, how to convert datatype in python?
39,047,576
<p>Title says it all really. Making a call to a MySQL db and get a datatype that is not playing so well when I try and jsonify it. It's driving me crazy trying to convert this datatype to something useable for the front end. </p> <p>I've tried calling float, int, etc, etc. Either the Decimal type persists or I get an encoding error: </p> <pre><code>UnicodeDecodeError: 'utf8' codec can't decode byte 0xf4 in position 1: invalid continuation byte </code></pre> <p>Edit: </p> <pre><code>sample query result: (('Albania', '38521', '2011'), ('Algeria', '136964', '2011'), ('Antigua and Barbuda', '206', '2011'), ('Argentina', '86351', '2011'), ('Armenia', '3251', '2011'), ('Aruba', '11511', '2011'), ('Australia', '421690', '2011'), ('Azerbaijan', '31622', '2011'), top line of query: original: SELECT s.country_area AS country, SUM(s.quantity) AS quantity, m.maxyear AS maxyear v2: SELECT s.country_area AS country, CAST(SUM(s.quantity) AS CHAR) AS quantity, m.maxyear AS maxyear </code></pre> <p>edit2: </p> <pre><code>v3: SELECT s.country_area AS country, CAST(SUM(s.quantity) AS CHAR CHARACTER SET utf8) AS quantity, m.maxyear AS maxyear </code></pre> <p>original gets Decimal error when I use json.dumps on the object v2 get utf-8 encoding error.. v2 still get utf-8 encoding error..</p>
0
2016-08-19T20:58:48Z
39,047,848
<p>The problem may be caused by accentuated characters in the <em>country_area</em> field.</p> <p>If you get bytes strings from your SQL result, you must decoded it using the encoding of your table.</p> <p>By default, MySQL use the latin1_swedish_ci => ISO-8859-1 charset.</p> <p>So, you need to decode like this:</p> <pre><code>s = b"bytes string with accentuated characters" u = s.decode("ISO-8859-1") </code></pre> <p>You'll get unicode characters.</p>
-1
2016-08-19T21:22:06Z
[ "python", "mysql" ]
How to retrieve data from the Github API in a python script?
39,047,695
<p>I'm fairly new to any sort of web programming and need help with gathering data from the Github search API. How to I go get the array at <a href="https://api.github.com/search/users?q=tom+repos:%3E42+followers:%3E1000" rel="nofollow">https://api.github.com/search/users?q=tom+repos:%3E42+followers:%3E1000</a> from inside a script? or use a GET /search/user?</p> <p>Would I do something along the lines of Users[Num_users] = GET api.github.con/search/users?</p> <p>The github API returns a array of objects (JSON I believe?).</p> <p>Thank you so much!</p>
1
2016-08-19T21:07:57Z
39,047,960
<p>Why roll your own? Use a prebuilt module: </p> <pre><code>https://github.com/PyGithub/PyGithub </code></pre> <p>List of Python api's from <a href="https://developer.github.com/libraries/" rel="nofollow">https://developer.github.com/libraries/</a></p> <pre><code>PyGithub Pygithub3 libsaas github3.py sanction agithub githubpy octohub Github-Flask torngithub </code></pre>
2
2016-08-19T21:32:32Z
[ "python", "web", "github" ]
The matching columns from a data frame based on value in a column from other data Frame
39,047,720
<p>I have two data frames The first one is df1 has 485513 columns and 100 rows,</p> <pre><code>head(df1) sample cg1 cg2 cg3 cg4 cg5 cg6 cg7 cg8 cg9 cg10 cg11 AAD_1 33435 33436 33437 33438 33439 33440 33441 33442 33443 33444 33445 AAD_2 0.33 1.33 2.33 3.33 4.33 5.33 6.33 7.33 8.33 9.33 10.33 AAD_3 0.56 1.56 2.56 3.56 4.56 5.56 6.56 7.56 8.56 9.56 10.56 AAD_4 45.9 46.9 47.9 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 AAD_5 46.9 47.9 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 AAD_6 47.9 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 AAD_7 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 AAD_8 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 59.9 AAD_9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 59.9 60.9 AAD_10 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 59.9 60.9 61.9 </code></pre> <p>and the second one has df2 84 rows and single column. I am aiming to get a subset of df1 using the values in the column from the df2 data frame.</p> <pre><code>head(df2) ID cg1 cg2 cg3 cg4 cg5 </code></pre> <p>The values of df2 are the columns names of my interest from df1 and so I have tried the following one-liner in R.</p> <pre><code>&gt; UP=(df1 %&gt;% as.data.frame)[,df2$ID] </code></pre> <p>The Up data frame returns me with unmatched columns from my query df2</p> <p>And it resulted in a data frame UP with 84 columns and 100 rows but none of the columns the above command line returned is matching with the input query data frame df2.</p> <p>It would be great if someone suggests me an alternative solution</p>
2
2016-08-19T21:10:02Z
39,047,806
<p>Assuming <code>df2</code> is a Series:</p> <pre><code>&gt;&gt;&gt; df[df2.tolist()] cg1 cg2 cg3 cg4 cg5 0 33435.00 33436.00 33437.00 33438.00 33439.00 1 0.33 1.33 2.33 3.33 4.33 2 0.56 1.56 2.56 3.56 4.56 3 45.90 46.90 47.90 48.90 49.90 4 46.90 47.90 48.90 49.90 50.90 5 47.90 48.90 49.90 50.90 51.90 6 48.90 49.90 50.90 51.90 52.90 7 49.90 50.90 51.90 52.90 53.90 8 50.90 51.90 52.90 53.90 54.90 9 51.90 52.90 53.90 54.90 55.90 </code></pre> <p>If it is a dataframe, then this should work:</p> <pre><code>df[df2.ID.tolist()] </code></pre>
2
2016-08-19T21:17:42Z
[ "python", "pandas" ]
The matching columns from a data frame based on value in a column from other data Frame
39,047,720
<p>I have two data frames The first one is df1 has 485513 columns and 100 rows,</p> <pre><code>head(df1) sample cg1 cg2 cg3 cg4 cg5 cg6 cg7 cg8 cg9 cg10 cg11 AAD_1 33435 33436 33437 33438 33439 33440 33441 33442 33443 33444 33445 AAD_2 0.33 1.33 2.33 3.33 4.33 5.33 6.33 7.33 8.33 9.33 10.33 AAD_3 0.56 1.56 2.56 3.56 4.56 5.56 6.56 7.56 8.56 9.56 10.56 AAD_4 45.9 46.9 47.9 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 AAD_5 46.9 47.9 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 AAD_6 47.9 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 AAD_7 48.9 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 AAD_8 49.9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 59.9 AAD_9 50.9 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 59.9 60.9 AAD_10 51.9 52.9 53.9 54.9 55.9 56.9 57.9 58.9 59.9 60.9 61.9 </code></pre> <p>and the second one has df2 84 rows and single column. I am aiming to get a subset of df1 using the values in the column from the df2 data frame.</p> <pre><code>head(df2) ID cg1 cg2 cg3 cg4 cg5 </code></pre> <p>The values of df2 are the columns names of my interest from df1 and so I have tried the following one-liner in R.</p> <pre><code>&gt; UP=(df1 %&gt;% as.data.frame)[,df2$ID] </code></pre> <p>The Up data frame returns me with unmatched columns from my query df2</p> <p>And it resulted in a data frame UP with 84 columns and 100 rows but none of the columns the above command line returned is matching with the input query data frame df2.</p> <p>It would be great if someone suggests me an alternative solution</p>
2
2016-08-19T21:10:02Z
39,050,510
<p>In <code>R</code>, we can just do</p> <pre><code>df[as.character(df2$ID)] </code></pre> <p>assuming that 'ID' column is <code>factor</code>. In case it is <code>character</code> class, it is more easier</p> <pre><code>df[df2$ID] </code></pre> <p>But if there are elements in 'ID' that are not in the column names of 'df', it may be better to use <code>intersect</code></p> <pre><code>df[intersect(colnames(df), df2$ID)] </code></pre> <hr> <p>If the 'df' is a <code>data.table</code>, the usual way to subset columns will be to include the <code>with =FALSE</code>. It is mentioned in <code>?data.table</code></p> <p><strong>with</strong> </p> <blockquote> <p>By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables.</p> <p>When with=FALSE j is a character vector of column names, a numeric vector of column positions to select or of the form startcol:endcol, and the value returned is always a data.table. with=FALSE is often useful in data.table to select columns dynamically. Note that x[, cols, with=FALSE] is equivalent to x[, .SD, .SDcols=cols].</p> </blockquote> <p>Therefore, the above commands would be</p> <pre><code> df[, as.character(df2$ID), with = FALSE] </code></pre> <p>or</p> <pre><code> df[, df2$ID, with = FALSE] #if 'ID' is already character class. </code></pre> <p>Or</p> <pre><code> df[, intersect(colnames(df), df2$ID), with = FALSE] </code></pre>
1
2016-08-20T04:35:51Z
[ "python", "pandas" ]
Tkinter Entry returns float values regardless of input
39,047,766
<p>I have some pretty simple code right now that I am having issues with.</p> <pre><code>root = Tk() label1 = Label(root, text ="Enter String:") userInputString = Entry(root) label1.pack() userInputString.pack() submit = Button(root,text = "Submit", command = root.destroy) submit.pack(side =BOTTOM) root.mainloop() print(userInputString) </code></pre> <p>When I run the code everything operates as I would expect except</p> <pre><code>print(userInputString) </code></pre> <p>for an input asdf in the Entry print will return something like 0.9355325</p> <p>But it will never be the same value back to back always random.</p> <p>I am using python 3.5 and Eclipse Neon on a Windows 7 Machine.</p> <p>Ultimately the goal is to accept a string from the user in the box that pops up and then be able to use that value as string later on. For example, it might be a file path that needs to be modified or opened.</p> <p>Is Entry not the correct widget I should be using for this? Is there something inherently wrong with the code here? I am new to python and don't have a lot of strong programming experience so I am not even certain that this is set up right to receive a string.</p> <p>Thanks in advance if anyone has any ideas.</p>
-1
2016-08-19T21:14:26Z
39,048,759
<p>There are two things wrong with your print statement. First, you print the widget, not the text in the widget. print(widget) prints str(widget), which is the tk pathname of the widget. The '.' represents the root window. The integer that follows is a number that tkinter assigned as the name of the widget. In current 3.6, it would instead be '<code>entry', so you would see ".</code>entry".</p> <p>Second, you try to print the widget text after you destroy the widget. After root.destroy, the <em>python</em> tkinter wrapper still exists, but the <em>tk</em> widget that it wrapped is gone. The following works on 3.6, Win10.</p> <pre><code>import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Enter String:") entry = tk.Entry(root) def print_entry(event=None): print(entry.get()) entry.bind('&lt;Key-Return&gt;', print_entry) entry.focus_set() submit = tk.Button(root, text="Submit", command=print_entry) label.pack() entry.pack() submit.pack() root.mainloop() </code></pre> <p>Bonus 1: I set the focus to the entry box so one can start typing without tabbing to the box or clicking on it.</p> <p>Bonus 2: I bound the key to the submit function so one can submit without using the mouse. Note that the command then requires an 'event' parameter, but it must default to None to use it with the button.</p> <p>The <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html" rel="nofollow">NMT Reference</a>, which I use constantly, is fairly complete and mostly correct.</p>
1
2016-08-19T23:01:23Z
[ "python", "python-3.x", "tkinter" ]
Why the default argument behaved globally immutable?
39,047,785
<p>The <code>default arguments</code> in Python are intuitively the variables locally scoped but globally mutable. </p> <p>Below, why had the second call to <code>my_sum</code> the result <code>20</code> although I expected it <code>30</code> ?</p> <pre><code>def my_append(el, ar = []): ar.append(el) return ar print my_append(10) # =&gt; [10] print my_append(20) # =&gt; [10, 20] def my_sum(i, sum = 0): sum += i return sum print my_sum(10) # =&gt; 10 print my_sum(20) # =&gt; 20 </code></pre>
0
2016-08-19T21:16:04Z
39,047,879
<p>To help clarify this, consider this one-line change:</p> <pre><code>def my_append(el, ar=[]): ar = ar + [el] # ar.append(el) return ar print my_append(10) # =&gt; [10] print my_append(20) # =&gt; [20] </code></pre> <p>So the issue is not to do with mutability or immutability, but the fact that the second version rebinds the name. </p> <p>This is a more subtle issue than the commentators are suggesting. <code>int.__iadd__</code> doesn't exist, so in the case of integers that operation falls back to <code>sum = sum + i</code>, again rebinding the name. </p> <p>However, <code>list.__iadd__</code> does exist, and it mutates the existing object. This is why you see the changes to the default argument occur. </p>
3
2016-08-19T21:24:42Z
[ "python" ]
Python - Return list of dictionaries with unique Key:Value pair
39,047,790
<p>I have a long list of dictionaries that for the most part do not overlap. However, some of the dictionaries have the same 'Name' field and I'd only like unique names in the list of dictionaries. I'd like the first occurrence of the name to be the one that stays and any thereafter be deleted from the list.</p> <p>I've put a short list below to illustrate the scenario:</p> <pre><code>myList = [ {'Name':'John', 'Age':'50', 'Height':'70'}, {'Name':'Kathy', 'Age':'43', 'Height':'65'}, {'Name':'John','Age':'46','Height':'68'}, {'Name':'John','Age':'50','Height':'72'} ] </code></pre> <p>I'd like this list to return the <strong>first</strong> 'John' and Kathy, but not the second or third Johns and their related information.</p> <p>An acceptable, but not optimal solution would also be not having dictionaries with the same name next to each other.</p>
1
2016-08-19T21:16:24Z
39,047,919
<p>You could run over the list and keep a <code>set</code> of unique names. Every time you encounter a new name (i.e., a name that isn't in the set), you add it to the set and the respective dict to the result:</p> <pre><code>def uniqueNames(dicts): names = set() result = [] for d in dicts: if not d['Name'] in names: names.add(d['Name']) result.append(d) return result </code></pre>
2
2016-08-19T21:27:58Z
[ "python", "list", "python-3.x", "dictionary", "unique" ]
Python - Return list of dictionaries with unique Key:Value pair
39,047,790
<p>I have a long list of dictionaries that for the most part do not overlap. However, some of the dictionaries have the same 'Name' field and I'd only like unique names in the list of dictionaries. I'd like the first occurrence of the name to be the one that stays and any thereafter be deleted from the list.</p> <p>I've put a short list below to illustrate the scenario:</p> <pre><code>myList = [ {'Name':'John', 'Age':'50', 'Height':'70'}, {'Name':'Kathy', 'Age':'43', 'Height':'65'}, {'Name':'John','Age':'46','Height':'68'}, {'Name':'John','Age':'50','Height':'72'} ] </code></pre> <p>I'd like this list to return the <strong>first</strong> 'John' and Kathy, but not the second or third Johns and their related information.</p> <p>An acceptable, but not optimal solution would also be not having dictionaries with the same name next to each other.</p>
1
2016-08-19T21:16:24Z
39,047,931
<p>Initial list:</p> <pre><code>my_list = [ {'Name':'John', 'Age':'50', 'Height':'70'}, {'Name':'Kathy', 'Age':'43', 'Height':'65'}, {'Name':'John','Age':'46','Height':'68'}, {'Name':'John','Age':'50','Height':'72'} ] </code></pre> <p>The logical (potentially newbie-friendlier) way:</p> <pre><code>names = set() new_list = [] for d in my_list: name = d['Name'] if name not in names: new_list.append(d) names.add(d['Name']) print new_list # [{'Age': '50', 'Name': 'John', 'Height': '70'}, {'Age': '43', 'Name': 'Kathy', 'Height': '65'}] </code></pre> <p>A one-liner way:</p> <pre><code>new_list = {d['Name']: d for d in reversed(my_list)}.values() print new_list # [{'Age': '43', 'Name': 'Kathy', 'Height': '65'}, {'Age': '50', 'Name': 'John', 'Height': '70'}] </code></pre> <p><strong>Note</strong>: The one-liner will contain the first occurrence of each name, but it will return an arbitrarily ordered list.</p>
0
2016-08-19T21:29:36Z
[ "python", "list", "python-3.x", "dictionary", "unique" ]
Python - Return list of dictionaries with unique Key:Value pair
39,047,790
<p>I have a long list of dictionaries that for the most part do not overlap. However, some of the dictionaries have the same 'Name' field and I'd only like unique names in the list of dictionaries. I'd like the first occurrence of the name to be the one that stays and any thereafter be deleted from the list.</p> <p>I've put a short list below to illustrate the scenario:</p> <pre><code>myList = [ {'Name':'John', 'Age':'50', 'Height':'70'}, {'Name':'Kathy', 'Age':'43', 'Height':'65'}, {'Name':'John','Age':'46','Height':'68'}, {'Name':'John','Age':'50','Height':'72'} ] </code></pre> <p>I'd like this list to return the <strong>first</strong> 'John' and Kathy, but not the second or third Johns and their related information.</p> <p>An acceptable, but not optimal solution would also be not having dictionaries with the same name next to each other.</p>
1
2016-08-19T21:16:24Z
39,047,934
<p>You can easily write a for-loop for this.</p> <pre><code> def getName(name): '''Gets first occurence of name in list of dicts.''' for i in myList: if i['Name'] == name: return i </code></pre>
1
2016-08-19T21:29:55Z
[ "python", "list", "python-3.x", "dictionary", "unique" ]
Using function of sqlalchemy.sql multiple times in query
39,047,840
<p>I am using sqlalchemy version 0.7.8. I have come across an issue where my user can search a text in plain english but record in db can have special characters between text. So if user enters "<strong>please come early to the hospital</strong>" and in db i have "<strong>please, come early, to the hospital.</strong>" then my query must return exactly <strong>please, come early, to the hospital.</strong></p> <p>i have found this easy solution.</p> <pre><code>needle = func.replace(func.replace(Message.text, ',', ''), '.', '') Message.query.filter(needle==query_term.strip()).one() </code></pre> <p>But problem with this is that there can be many special characters in db like "<strong>! ; : ? &amp;</strong>" etc and needle will look very inefficient so please suggest me any efficient solution to avoid repeating func.replace function.</p> <p>I cannot find same question on stackoverflow let me know if someone has already answered it. </p>
1
2016-08-19T21:21:25Z
39,048,013
<p>Use a query with <a href="http://dev.mysql.com/doc/refman/5.7/en/regexp.html" rel="nofollow">RegEx</a></p> <p>There are examples in the <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#the-query-object" rel="nofollow">SqlAlchemy documentation</a>.</p> <p>See also this <a href="http://stackoverflow.com/questions/3325467/elixir-sqlalchemy-equivalent-to-sql-like-statement">question</a>.</p>
0
2016-08-19T21:37:23Z
[ "python", "mysql", "python-2.7", "sqlalchemy" ]
Using function of sqlalchemy.sql multiple times in query
39,047,840
<p>I am using sqlalchemy version 0.7.8. I have come across an issue where my user can search a text in plain english but record in db can have special characters between text. So if user enters "<strong>please come early to the hospital</strong>" and in db i have "<strong>please, come early, to the hospital.</strong>" then my query must return exactly <strong>please, come early, to the hospital.</strong></p> <p>i have found this easy solution.</p> <pre><code>needle = func.replace(func.replace(Message.text, ',', ''), '.', '') Message.query.filter(needle==query_term.strip()).one() </code></pre> <p>But problem with this is that there can be many special characters in db like "<strong>! ; : ? &amp;</strong>" etc and needle will look very inefficient so please suggest me any efficient solution to avoid repeating func.replace function.</p> <p>I cannot find same question on stackoverflow let me know if someone has already answered it. </p>
1
2016-08-19T21:21:25Z
39,051,641
<p>You can use this to remove all spacial character in python</p> <pre><code>&gt;&gt;&gt; impore re &gt;&gt;&gt; string = "please, come early# to the@ hospital" &gt;&gt;&gt; cleanString = re.sub('\W+',' ', string ) &gt;&gt;&gt; print cleanString please come early to the hospital </code></pre> <p>store your text as a string in a variable and then run your query with this variable.</p>
0
2016-08-20T07:27:43Z
[ "python", "mysql", "python-2.7", "sqlalchemy" ]
Using function of sqlalchemy.sql multiple times in query
39,047,840
<p>I am using sqlalchemy version 0.7.8. I have come across an issue where my user can search a text in plain english but record in db can have special characters between text. So if user enters "<strong>please come early to the hospital</strong>" and in db i have "<strong>please, come early, to the hospital.</strong>" then my query must return exactly <strong>please, come early, to the hospital.</strong></p> <p>i have found this easy solution.</p> <pre><code>needle = func.replace(func.replace(Message.text, ',', ''), '.', '') Message.query.filter(needle==query_term.strip()).one() </code></pre> <p>But problem with this is that there can be many special characters in db like "<strong>! ; : ? &amp;</strong>" etc and needle will look very inefficient so please suggest me any efficient solution to avoid repeating func.replace function.</p> <p>I cannot find same question on stackoverflow let me know if someone has already answered it. </p>
1
2016-08-19T21:21:25Z
39,053,346
<p>Thanks to all replies. I am able to improve it through this way.</p> <pre><code>IGNORE_CHARS = [',', '.', '!', '&amp;', ';', ':', '@'] needle = build_replace_func(IGNORE_CHARS, Message.text) record = Message.query.filter(needle == query_term.strip()).one() def build_replace_func(chars, attr, replace_with=''): for character in chars: attr = func.replace(attr, character, replace_with) return attr </code></pre>
1
2016-08-20T10:58:43Z
[ "python", "mysql", "python-2.7", "sqlalchemy" ]
Floating point numbers precision in python
39,047,856
<p>I have a variable <code>mn</code> whose value is 2.71989011072, I use round function of python to get a precision value of 2.720 but I get 2.72 only</p> <pre><code>mn=2.71989011072 print round(mn,3) </code></pre> <p>Gives 2.72 and not 2.720</p>
0
2016-08-19T21:22:44Z
39,047,914
<p>Yes, the <em>print</em> function apply a second rounding.</p> <pre><code>mn = 2.71989011072 mn = round(mn, 3) print(mn) </code></pre> <p>You'll get:</p> <pre><code>2.72 </code></pre> <p>You need to use a formatted string:</p> <pre><code>print("{0:.3f}".format(mn)) </code></pre> <p>You'll get:</p> <pre><code>2.720 </code></pre> <p>Notice that the formatted string can do the rounding for you. With this, you'll get the same output:</p> <pre><code>mn = 2.71989011072 print("{0:.3f}".format(mn)) # =&gt; 2.720 </code></pre>
3
2016-08-19T21:27:29Z
[ "python", "floating-point", "rounding" ]
Floating point numbers precision in python
39,047,856
<p>I have a variable <code>mn</code> whose value is 2.71989011072, I use round function of python to get a precision value of 2.720 but I get 2.72 only</p> <pre><code>mn=2.71989011072 print round(mn,3) </code></pre> <p>Gives 2.72 and not 2.720</p>
0
2016-08-19T21:22:44Z
39,047,918
<p>Function rounds it to three first digits which correctly results in 2.72. The zeros are matter of printing ans string formatting, not rounding.</p> <p>To print it with three zeros you will need to do the following:</p> <pre><code>print '{0:.3f}'.format(round(mn, 3)) </code></pre> <p>That will round number first and then print it, formatting it with three zeros.</p>
1
2016-08-19T21:27:51Z
[ "python", "floating-point", "rounding" ]
Floating point numbers precision in python
39,047,856
<p>I have a variable <code>mn</code> whose value is 2.71989011072, I use round function of python to get a precision value of 2.720 but I get 2.72 only</p> <pre><code>mn=2.71989011072 print round(mn,3) </code></pre> <p>Gives 2.72 and not 2.720</p>
0
2016-08-19T21:22:44Z
39,047,937
<p>You desire a particular string representation of the number, not another number.</p> <p>Use <code>format()</code> instead of <code>round()</code>:</p> <pre><code>&gt;&gt;&gt; mn = 2.71989011072 &gt;&gt;&gt; format(mn, '.3f') '2.720' </code></pre>
0
2016-08-19T21:30:06Z
[ "python", "floating-point", "rounding" ]
contour plot with non linear x scale
39,047,896
<p>I am working on two plots: a contour plot on the top and an x-y plot on the bottom <a href="http://i.stack.imgur.com/WoNcp.png" rel="nofollow"><img src="http://i.stack.imgur.com/WoNcp.png" alt="contour plot"></a></p> <p>The contour plot is done via the following line</p> <pre><code>plt.imshow(df, extent = [xmin, xmax, ymin, ymax]) </code></pre> <p>while the x, y plot is</p> <pre><code> xyplot = df.mean() plt.plot(x, xyplot) </code></pre> <p>And should be vertically aligned to the contour plot on the top, but the x-y plot has a non-linear x scale. The following picture show the x axis as a function of its index <a href="http://i.stack.imgur.com/Wajdt.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wajdt.png" alt="enter image description here"></a></p> <p>As I can not provide an array to the "extent" variable of the "imshow" method, I can't provide the some x scale at the contour plot. How can I make the some non-linear scale on the contour plot so that the two plots will result aligned on the vertical axis?</p>
0
2016-08-19T21:26:06Z
39,048,978
<p>You can use <code>scipy.interpolate.interp2d</code> to interpolate the image on a regular grid. Here is an example:</p> <pre><code>import numpy as np import pylab as pl x = np.linspace(0, 1, 100) x2 = x ** 2 y = np.linspace(0, 1, 200) X, Y = np.meshgrid(x, y) X2, Y2 = np.meshgrid(x2, y) Z = np.sin(10 * (X**2 + Y**2)) Z2 = np.sin(10 * (X2**2 + Y2**2)) from scipy import interpolate i2d = interpolate.interp2d(x2, y, Z2) Zi = i2d(x, y) fig, axes = pl.subplots(1, 3, figsize=(12, 4)) extent = [0, 1, 0, 1] axes[0].imshow(Z, extent=extent) axes[1].imshow(Z2, extent=extent) axes[2].imshow(Zi, extent=extent) </code></pre> <p>the output:</p> <p><a href="http://i.stack.imgur.com/vvD9i.png" rel="nofollow"><img src="http://i.stack.imgur.com/vvD9i.png" alt="enter image description here"></a></p> <p>left: array calculated on regular grid. center: array calculated on no regular grid. right: interpolate result of the center array on regular grid.</p>
1
2016-08-19T23:30:59Z
[ "python", "matplotlib" ]
Understanding python dict memory allocation
39,048,112
<pre><code>def func(bar): my_dict = { 'query1': 'select * from table1', 'query2': 'select * from table2' } my_dict[bar] func('query1') </code></pre> <p>My question is does my_dict executes both query and save it or it only executes query according to bar variable</p>
0
2016-08-19T21:46:54Z
39,048,151
<p>That will create the dictionary with two elements in memory, find the value associated with key <code>bar</code> and destroy the whole thing when the function is competed. </p>
0
2016-08-19T21:50:14Z
[ "python" ]
Understanding python dict memory allocation
39,048,112
<pre><code>def func(bar): my_dict = { 'query1': 'select * from table1', 'query2': 'select * from table2' } my_dict[bar] func('query1') </code></pre> <p>My question is does my_dict executes both query and save it or it only executes query according to bar variable</p>
0
2016-08-19T21:46:54Z
39,048,191
<p>In this specific case, no query are executed at all. It is only <code>str</code> objects which means that they actually don't do anything.</p> <p>Let's try to detail 2 other cases. Assuming you have a function <code>execute_query</code> that execute a query given as parameter:</p> <pre><code>def func(query): my_dict = { 'query1': execute_query('select * from table1'), 'query2': execute_query('select * from table2'), } return my_dict[query] func('query1') </code></pre> <p>In this case, both query will be executed because Python interpreter will analyse the dictionary composition. On the other hand, if you have a <em>reference</em> to this function, it won't call the function. Example:</p> <pre><code>def do_query1(): return execute_query('select * from table1') def do_query2(): return execute_query('select * from table2') def func(query): my_dict = { 'query1': do_query1, 'query2': do_query2, } return my_dict[query]() # &lt;-- appropriate function will be call here func('query1') </code></pre>
1
2016-08-19T21:54:43Z
[ "python" ]
Django ImportError: no module named 'shop'
39,048,114
<p>I tried searching for answers to this problem but, at least with my eyeballs, I did not find the same problem anywhere else.</p> <p>I started doing a django project from the book "Django by example'. I've been using a virtual environment. Following the book, I downloaded Django 1.8.6. </p> <p>I added the app 'shop' into the list of apps in the settings file. </p> <pre><code>INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', ) </code></pre> <p>I created the models according to the book.</p> <p>Then I tried "makingmigrations" but it gives me ImportError. Like this:</p> <pre><code>(myenv) C:\Users\Subject\djangoshop&gt;python manage.py runserver --traceback Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0000000003EEEB70&gt; Traceback (most recent call last): File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\utils\autorel oad.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\core\manageme nt\commands\runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\utils\autorel oad.py", line 252, in raise_last_exception six.reraise(*_exception) File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\utils\six.py" , line 658, in reraise raise value.with_traceback(tb) File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\utils\autorel oad.py", line 229, in wrapper fn(*args, **kwargs) File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\apps\registry .py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Subject\djangoshop\myenv\lib\site-packages\django\apps\config.p y", line 86, in create module = import_module(entry) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2224, in _find_and_load_unlocked ImportError: No module named 'shop' </code></pre> <p>There is a blank <code>__init__.py</code> file in the app shop/.</p> <p>This picture should show some of the tree. I took it from PyCharm. (I tried the tree command in the command prompt but it was terribly long.) <a href="http://i.stack.imgur.com/r09rC.png" rel="nofollow">tree</a></p> <p>I think I followed the directory structure given by the book:</p> <pre><code>django-admin startproject myshop cd myshop/ django-admin startapp shop </code></pre> <p>I was not able to create the virtual environment the way the book instructs, so I created it following this tutorial <a href="http://tutorial.djangogirls.org/en/django_installation/" rel="nofollow">http://tutorial.djangogirls.org/en/django_installation/</a></p>
0
2016-08-19T21:46:58Z
39,062,351
<p>Solution: I created the app in the wrong folder. Come to think of it, I think I used this command:</p> <pre><code>django-admin startproject myshop . </code></pre> <p>With the dot in the end, as some tutorials recommend. So that messed up the structure so it became incompatible with the book's instructions.</p> <p>So, as Alasdair recommended, I started the project again from the beginning, and the problem disappeared.</p>
0
2016-08-21T08:32:18Z
[ "python", "django" ]
Custom usage message for a single argument in argparse
39,048,139
<p>I have a parameter that can be specified by the user with either one or two arguments:</p> <pre><code>parser.add_argument("-s", "--start", required=True, metavar='START_TIME', nargs='+', help="The start time either in milliseconds or as MM/DD/YYYY HH:MM:SS.") </code></pre> <p>The help message shows this: </p> <pre><code>usage: foo -s START_TIME [START_TIME ...] Foo optional arguments: -s START_TIME [START_TIME ...], --start START_TIME [START_TIME ...] The start time of the query window either in milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr). </code></pre> <p>This is somewhat misleading because of the <code>[START_TIME ...]</code> part. Is there a way that I can modify the usage message for this one argument so that it shows something more like: </p> <pre><code>usage: foo -s START_TIME Foo optional arguments: -s START_TIME, --start START_TIME The start time of the query window either in milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr). </code></pre> <p>I know I can replace the entire usage message with argparse, but I have several other arguments that I don't want to mess with. I would like do do something like `nargs='1|2', but I'm afraid that might be wishful thinking... Other than restructuring my CLI, is there something I can do to fix the usage message for a single parameter? Thanks. </p>
0
2016-08-19T21:49:44Z
39,048,175
<p>I suggest removing <code>nargs</code> from your call to <code>add_argument</code>. <code>nargs='+'</code> indicates there may be more than one input for that argument, but in actuality you always want one argument. A string of <code>MM/DD/YYYY HH:MM:SS</code> is one argument conceptually and may be passed in with quotes:</p> <pre><code>python script.py -s 978370496000 python script.py -s "01/01/2001 12:34:56" python temp3.py -h usage: temp3.py [-h] -s START_TIME optional arguments: -h, --help show this help message and exit -s START_TIME, --start START_TIME The start time either in milliseconds or as MM/DD/YYYY HH:MM:SS. </code></pre> <p>This will produce your desired usage message, and I think will be less confusing to the caller.</p>
2
2016-08-19T21:52:26Z
[ "python", "argparse" ]
Custom usage message for a single argument in argparse
39,048,139
<p>I have a parameter that can be specified by the user with either one or two arguments:</p> <pre><code>parser.add_argument("-s", "--start", required=True, metavar='START_TIME', nargs='+', help="The start time either in milliseconds or as MM/DD/YYYY HH:MM:SS.") </code></pre> <p>The help message shows this: </p> <pre><code>usage: foo -s START_TIME [START_TIME ...] Foo optional arguments: -s START_TIME [START_TIME ...], --start START_TIME [START_TIME ...] The start time of the query window either in milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr). </code></pre> <p>This is somewhat misleading because of the <code>[START_TIME ...]</code> part. Is there a way that I can modify the usage message for this one argument so that it shows something more like: </p> <pre><code>usage: foo -s START_TIME Foo optional arguments: -s START_TIME, --start START_TIME The start time of the query window either in milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr). </code></pre> <p>I know I can replace the entire usage message with argparse, but I have several other arguments that I don't want to mess with. I would like do do something like `nargs='1|2', but I'm afraid that might be wishful thinking... Other than restructuring my CLI, is there something I can do to fix the usage message for a single parameter? Thanks. </p>
0
2016-08-19T21:49:44Z
39,048,215
<p>If you want to have zero, one or two arguments and not more, you can have two options <code>-s1</code> and <code>-s2</code>.</p> <p>It can be more obvious or clearer for the user to understand the usage of your application. </p>
-1
2016-08-19T21:58:07Z
[ "python", "argparse" ]
Custom usage message for a single argument in argparse
39,048,139
<p>I have a parameter that can be specified by the user with either one or two arguments:</p> <pre><code>parser.add_argument("-s", "--start", required=True, metavar='START_TIME', nargs='+', help="The start time either in milliseconds or as MM/DD/YYYY HH:MM:SS.") </code></pre> <p>The help message shows this: </p> <pre><code>usage: foo -s START_TIME [START_TIME ...] Foo optional arguments: -s START_TIME [START_TIME ...], --start START_TIME [START_TIME ...] The start time of the query window either in milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr). </code></pre> <p>This is somewhat misleading because of the <code>[START_TIME ...]</code> part. Is there a way that I can modify the usage message for this one argument so that it shows something more like: </p> <pre><code>usage: foo -s START_TIME Foo optional arguments: -s START_TIME, --start START_TIME The start time of the query window either in milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr). </code></pre> <p>I know I can replace the entire usage message with argparse, but I have several other arguments that I don't want to mess with. I would like do do something like `nargs='1|2', but I'm afraid that might be wishful thinking... Other than restructuring my CLI, is there something I can do to fix the usage message for a single parameter? Thanks. </p>
0
2016-08-19T21:49:44Z
39,048,513
<p>The default display for a <code>'+'</code> nargs is this <code>S [S ...]</code>. It's supposed to convey the idea that you have to give at least one value, but can have more. (look at what <code>*</code> produces).</p> <pre><code>In [306]: parser=argparse.ArgumentParser() In [307]: a1=parser.add_argument('-s',nargs='+') In [308]: parser.print_help() usage: ipython3 [-h] [-s S [S ...]] optional arguments: -h, --help show this help message and exit -s S [S ...] </code></pre> <p>In your case the <code>metavar</code> string is just replacing that default string derived from the <code>dest</code>.</p> <p>You can give a tuple metavar, which displays as:</p> <pre><code>In [309]: a1.metavar=('A','B') In [310]: parser.print_help() usage: ipython3 [-h] [-s A [B ...]] optional arguments: -h, --help show this help message and exit -s A [B ...] </code></pre> <p>empty metavar:</p> <pre><code>In [312]: parser.print_help() usage: ipython3 [-h] [-s [...]] optional arguments: -h, --help show this help message and exit -s [ ...] </code></pre> <p>To override this formatting</p> <pre><code>'%s [%s ...]' % get_metavar(2) </code></pre> <p>you'd have to create a custom <code>HelpFormatter</code> subclass with a modified <code>_format_args</code> method.</p> <p>=================</p> <p>As for <code>nargs='1|2'</code> I've explored adding a range option modeled on <code>regex</code> syntax. It's not hard to add, but you have to be familiar with the <code>argparse.py</code> code. There's a Python bug/issue on the topic.</p>
1
2016-08-19T22:29:20Z
[ "python", "argparse" ]
Groupby of splitted data (pandas)
39,048,181
<p>Imagine you have a large CSV file with several million rows that you process by chunks. <strong>The file is too large to be loaded in memory</strong>. What would be the best way to do groupby and apply a relatively "complex" function (like fillna), without letting the chunk size affect the results? I exemplify: </p> <pre><code>A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "A"], "value":[3,np.nan,4,5,np.nan]}) &gt;&gt;&gt; A ID value 0 A 2 1 A 3 2 C 4 3 B 5 4 A 6 </code></pre> <p>if the chunk size is 2 and I groupby 'ID', then I would group the first two A's but leave aside the last A, which would affect the results for a non-straightforward apply function,</p> <pre><code>A.groupby('ID').fillna(method='fill') </code></pre> <p>the output would be: </p> <pre><code> value 0 3.0 1 3.0 2 4.0 3 5.0 4 np.nan </code></pre> <p>Note that there is an np.nan in the last row where there should be a 3.</p> <p>Thank you and I appreciate your help,</p>
1
2016-08-19T21:53:23Z
39,048,271
<p>You need to set up a way to remember the last fill value. I use the dictionary <code>memory</code> below</p> <pre><code>memory = {} def fill(df): name = df.name df = df.copy() # fill from memory if name in memory.keys(): df.iloc[0, :] = df.iloc[0, :].fillna(memory[name]) # normal ffill df = df.fillna(method='ffill') # update memory memory.update({name: df.iloc[-1]}) return df </code></pre> <hr> <pre><code>memory {} </code></pre> <hr> <pre><code>A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "A"], "value":[3,np.nan,4,5,np.nan]}) A </code></pre> <p><a href="http://i.stack.imgur.com/YkXfC.png" rel="nofollow"><img src="http://i.stack.imgur.com/YkXfC.png" alt="enter image description here"></a></p> <p>Now I'll <code>update</code> <code>A</code> for only the first 4 rows</p> <pre><code>A.update(A.iloc[:4].groupby('ID', group_keys=False).apply(fill)) A </code></pre> <p><a href="http://i.stack.imgur.com/fkzTr.png" rel="nofollow"><img src="http://i.stack.imgur.com/fkzTr.png" alt="enter image description here"></a></p> <p>Notice that only the value in row 1 was filled. Row 4 was left alone. However, let's look at <code>memory</code></p> <pre><code>memory {'A': ID A value 3 Name: 1, dtype: object, 'B': ID B value 5 Name: 3, dtype: object, 'C': ID C value 4 Name: 2, dtype: object} </code></pre> <p>Or more specifically <code>memory['A']</code></p> <pre><code>ID A value 3 Name: 1, dtype: object </code></pre> <p>So let's now update <code>A</code> for only row 4</p> <pre><code>A.update(A.iloc[4:].groupby('ID', group_keys=False).apply(fill)) A </code></pre> <p><a href="http://i.stack.imgur.com/dineC.png" rel="nofollow"><img src="http://i.stack.imgur.com/dineC.png" alt="enter image description here"></a></p>
2
2016-08-19T22:03:46Z
[ "python", "pandas" ]
Groupby of splitted data (pandas)
39,048,181
<p>Imagine you have a large CSV file with several million rows that you process by chunks. <strong>The file is too large to be loaded in memory</strong>. What would be the best way to do groupby and apply a relatively "complex" function (like fillna), without letting the chunk size affect the results? I exemplify: </p> <pre><code>A = pd.DataFrame({"ID":["A", "A", "C" ,"B", "A"], "value":[3,np.nan,4,5,np.nan]}) &gt;&gt;&gt; A ID value 0 A 2 1 A 3 2 C 4 3 B 5 4 A 6 </code></pre> <p>if the chunk size is 2 and I groupby 'ID', then I would group the first two A's but leave aside the last A, which would affect the results for a non-straightforward apply function,</p> <pre><code>A.groupby('ID').fillna(method='fill') </code></pre> <p>the output would be: </p> <pre><code> value 0 3.0 1 3.0 2 4.0 3 5.0 4 np.nan </code></pre> <p>Note that there is an np.nan in the last row where there should be a 3.</p> <p>Thank you and I appreciate your help,</p>
1
2016-08-19T21:53:23Z
39,050,151
<p>I guess you want to read in chunk-by-chunk and then write to disk after processing. I think @piRSquared's idea of "keeping memory of previously seen values" should work if the function you want to apply is ffill, though I'm sure @Jeff is right about Dask (which I'm not familiar).</p> <p>I have made up a slightly longer file for testing. See below.</p> <pre><code>inputcsv = 'test.csv' outputcsv = 'test.output.csv' chunksize = 4 outfh = open(outputcsv, 'wb') memory = None len_memory = 0 #write file header to output file pd.read_csv(inputcsv, nrows=0).to_csv(outfh, index=False) for chunk in pd.read_csv(inputcsv, chunksize=chunksize): if memory is not None: len_memory = len(memory) #put memory in front of chunk chunk = pd.concat([memory.reset_index(), chunk], ignore_index=True) #ffill chunk['value'] = chunk.groupby('ID')['value'].fillna(method='ffill') #update memory memory = chunk.groupby('ID').last().dropna() #The first len_memory was from memory not input file. Get rid of them. chunk = chunk.iloc[len_memory:,:] chunk.to_csv(outfh, index=False, header=False) outfh.close() print pd.read_csv(inputcsv) ID value 0 A 3.0 1 A NaN 2 C 4.0 3 B 5.0 4 A NaN 5 F 2.0 6 D 2.0 7 A 1.0 8 C NaN 9 B 3.0 10 E NaN 11 D 4.0 12 A NaN 13 B NaN 14 B 5.0 15 C NaN 16 E 4.0 17 F NaN 18 F 1.0 19 E 0.0 print pd.read_csv(outputcsv) ID value 0 A 3.0 1 A 3.0 2 C 4.0 3 B 5.0 4 A 3.0 5 F 2.0 6 D 2.0 7 A 1.0 8 C 4.0 9 B 3.0 10 E NaN 11 D 4.0 12 A 1.0 13 B 3.0 14 B 5.0 15 C 4.0 16 E 4.0 17 F 2.0 18 F 1.0 19 E 0.0 </code></pre>
0
2016-08-20T03:23:24Z
[ "python", "pandas" ]
Python - s.recv hang timeout
39,048,225
<p>I have a script that I am currently writing to connect to a host via port 25. Once connected the following code is used to read a text file to gather each user and then issue the VRFY command along with the username. This works really well until I receive no response back from the host, it just hangs there. Towards the bottom of my code I have tried to break out if no response is received but this does not work. I have tried several ways to get it to work without any luck.</p> <p>Thanks in advance!</p> <pre><code>with open('usernames.txt') as f: for users in f: if users == '': break else: try: s.send('VRFY ' + users) result=s.recv(1024) print result except socket.timeout: print IPADDRESS + ' is not responding to VRFY commands' break </code></pre>
0
2016-08-19T21:58:44Z
39,048,557
<p>Yes thank you, settimeout worked a treat! I used a excempt to catch it too. Thanks everyone! </p>
0
2016-08-19T22:34:01Z
[ "python" ]
Spark Equivalent of IF Then ELSE
39,048,229
<p>I have seen this question earlier here and I have took learnings from that. However I am not sure why I am getting an error when I feel it should work. </p> <p>I want to create a new column in existing Spark Dataframe by some rules. Here is what I wrote. iris_spark is the data frame with a categorical variable iris_spark with three distinct categories. </p> <pre><code>from pyspark.sql import functions as F` iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1)).otherwise(2)) </code></pre> <p>Throws the following error. </p> <hr> <p>TypeError Traceback (most recent call last) in () ----> 1 iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1)))</p> <p>TypeError: when() takes exactly 2 arguments (3 given)</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-157-21818c7dc060&gt; in &lt;module&gt;() ----&gt; 1 iris_spark_df=iris_spark.withColumn("Class",F.when(iris_spark.iris_class=='Iris-setosa',0,F.when(iris_spark.iris_class=='Iris-versicolor',1))) TypeError: when() takes exactly 2 arguments (3 given) </code></pre> <p>Any idea why?</p>
-1
2016-08-19T21:59:06Z
39,048,475
<p>Correct structure is either:</p> <pre><code>(when(col("iris_class") == 'Iris-setosa', 0) .when(col("iris_class") == 'Iris-versicolor', 1) .otherwise(2)) </code></pre> <p>which is equivalent to</p> <pre><code>CASE WHEN (iris_class = 'Iris-setosa') THEN 0 WHEN (iris_class = 'Iris-versicolor') THEN 1 ELSE 2 END </code></pre> <p>or:</p> <pre><code>(when(col("iris_class") == 'Iris-setosa', 0) .otherwise(when(col("iris_class") == 'Iris-versicolor', 1) .otherwise(2))) </code></pre> <p>which is equivalent to:</p> <pre><code>CASE WHEN (iris_class = 'Iris-setosa') THEN 0 ELSE CASE WHEN (iris_class = 'Iris-versicolor') THEN 1 ELSE 2 END END </code></pre> <p>with general syntax:</p> <pre><code>when(condition, value).when(...) </code></pre> <p>or</p> <pre><code>when(condition, value).otherwise(...) </code></pre> <p>You probably mixed up things with Hive <code>IF</code> conditional:</p> <pre><code>IF(condition, if-true, if-false) </code></pre> <p>which can be used only in raw SQL with Hive support.</p>
1
2016-08-19T22:26:00Z
[ "python", "apache-spark" ]
'numpy.float64' object is not iterable - meanshift clustering
39,048,355
<p>python newbie here. I am trying to run this code but I get the error message that the object is not iterable. Would appreciate some advice on what I am doing wrong. Thanks.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd temp = pd.read_csv("file.csv", encoding='latin-1') xy = temp.ix[:,2:6] X = xy.values </code></pre> <hr> <pre><code>X array([[ nan, nan], [ nan, nan], [ 3.92144000e+00, nan], [ 4.42382000e+00, nan], [ 4.18931000e+00, 5.61562775e+02], [ nan, nan], [ 4.33025000e+00, 6.73123391e+02], [ 6.43775000e+00, nan], [ 3.12299000e+00, 2.21886627e+03], [ nan, nan], [ nan, nan]]) </code></pre> <hr> <pre><code>from itertools import cycle colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') class Mean_Shift: def __init__(self, radius=4): self.radius = radius def fit(self, data): centroids = {} for i in range(len(data)): centroids[i] = data[i] while True: new_centroids = [] for i in centroids: in_bandwidth = [] centroid = centroids[i] for featureset in data: if np.linalg.norm(featureset-centroid) &lt; self.radius: in_bandwidth.append(featureset) new_centroid = np.average(in_bandwidth, axis=0) new_centroids.append(tuple(new_centroid)) uniques = sorted(list(set(new_centroids))) prev_centroids = dict(centroids) centroids = {} for i in range(len(uniques)): centroids[i] = np.array(uniques[i]) optimized = True for i in centroids: if not np.array_equal(centroids[i], prev_centroids[i]): optimized = False if not optimized: break if optimized: break self.centroids = centroids def predict(self,data): pass clf = Mean_Shift() clf.fit(X) centroids = clf.centroids plt.scatter(X[:,0],X[:,1],s=50) for c in centroids: plt.scatter(centroids[c][0], centroids[c][1], color = 'k', marker='*', s=150) plt.show() </code></pre> <p>Here is the error code i get:</p> <pre><code>/Users/carla/anaconda/lib/python3.5/site-packages/numpy/core/_methods.py:59: RuntimeWarning: Mean of empty slice. warnings.warn("Mean of empty slice.", RuntimeWarning) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-11-e13932b6e72d&gt; in &lt;module&gt;() 50 51 clf = Mean_Shift() ---&gt; 52 clf.fit(X) 53 54 centroids = clf.centroids &lt;ipython-input-11-e13932b6e72d&gt; in fit(self, data) 22 23 new_centroid = np.average(in_bandwidth, axis=0) ---&gt; 24 new_centroids.append(tuple(new_centroid)) 25 26 uniques = sorted(list(set(new_centroids))) TypeError: 'numpy.float64' object is not iterable </code></pre>
1
2016-08-19T22:11:46Z
39,048,432
<pre><code>new_centroid = np.average(in_bandwidth, axis=0) </code></pre> <p>Is assigning a scalar to <code>new_centroid</code> then you are trying to <code>tuple(scalar)</code> which is throwing the error.</p> <pre><code>tuple(2.) </code></pre> <blockquote> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-51-4406f9e676cf&gt; in &lt;module&gt;() ----&gt; 1 tuple(2.) TypeError: 'float' object is not iterable </code></pre> </blockquote>
2
2016-08-19T22:20:35Z
[ "python", "pandas", "numpy", "cluster-analysis", "mean-shift" ]
Scikit-learn: error in fitting model - Input contains NaN, infinity or a value too large for float64
39,048,363
<p>My question appears to be the same as previous posts (<a href="https://stackoverflow.com/questions/36532497/standardscaler-valueerror-input-contains-nan-infinity-or-a-value-too-large-fo">post-1</a>, <a href="https://stackoverflow.com/questions/34779961/scikit-learn-error-in-fitting-model-input-contains-nan-infinity-or-a-value">post-2</a>, and <a href="https://stackoverflow.com/questions/31323499/sklearn-error-valueerror-input-contains-nan-infinity-or-a-value-too-large-for">post-3</a>). I did follow their solutions and still got the same errors. So, I am posting it here to seek for advices. </p> <p>I am using the basic functions from sklearn. The raw data contain missing value, so I use Imputer to fill the medians. Then, I use LabelEncoder to convert the nominal features from numerical ones. After that, I use StandardScaler to normalize the data set. </p> <p>The problem is at the LinearRegression stage. I got ''ValueError: Input contains NaN, infinity or a value too large for dtype('float64').'' But I indeed check the dataset and there is no NaN, infinity or value_too_large...</p> <p>Really have no idea why this error comes. Please feel free to comment if you have any clues. Thank you!</p> <p>The code I am using is:</p> <pre><code>import csv import numpy as np from sklearn import preprocessing from sklearn import linear_model from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler out_file = 'raw.dat' dataset = np.loadtxt(out_file, delimiter=',') data = dataset[:, 0:-1] # select columns 0 through -1 target = dataset[:, -1] # select the last column # to handle missing values imp = Imputer(missing_values='NaN', strategy='median', axis=0) imp.fit(data) data_imp = imp.transform(data) # label Encoder: converting nominal features le = preprocessing.LabelEncoder() le.fit(data_imp[:, 2]) print le.classes_ le.transform(data_imp[:, 2]) le.fit(data_imp[:, 3]) print le.classes_ le.transform(data_imp[:, 3]) print '# of data: ', len(target) scaler = preprocessing.StandardScaler().fit_transform(data_imp) scaler = scaler.astype(np.float64, copy=False) np.savetxt("newdata2.csv", scaler, delimiter=",") ols = linear_model.LinearRegression() for x in xrange(2, len(scaler)): print x scaler = scaler[:x, 1:] print scaler print np.isnan(scaler.any()) # False print np.any(np.isnan(scaler)) # False print np.isfinite(scaler.all()) # True print np.all(np.isfinite(scaler)) # True ols.fit(scaler, target) print ols </code></pre> <p>The error msg is shown as below. </p> <pre><code>Traceback (most recent call last): File ".\data_export.py", line 123, in prep ols.fit(scaler, target) File "C:\Python27\lib\site-packages\sklearn\linear_model\base.py", line 427, in fit y_numeric=True, multi_output=True) File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 513, in check_X_y dtype=None) File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 398, in check_array _assert_all_finite(array) File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 54, in _assert_all_finite" or a value too large for %r." % X.dtype) ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). </code></pre> <p>The raw data (raw.dat) is partly shown below: </p> <pre><code>1, 2.0, 14002, 1, 1965, 1, 1, 2, NaN, 771, 648.0, 4800.0 2, 2.8, 14002, 2, 1924, 3, 1, 4, NaN, 1400, 714.0, 999.0 3, 2.1, 14002, 1, 1965, 1, 1, 2, NaN, 725, 675.0, 4000.0 4, 1.6, 14002, 2, 1914, 2, 1, 3, 1, 1530, 620.0, 9950.0 5, 8.9, 14010, 1, 1973, 2, 1, 3, NaN, 1048, 705.0, 9000.0 6, 7.3, 14010, 1, 1982, 1, 1, 2, 1, 880, 656.0, 5000.0 ...... </code></pre> <p>After we fixed the missing value and normalize the numbers, the data from newdata2.csv are shown like the following: </p> <pre><code>-1.70 -2.23 -1.64 -1.15 -0.40 -1.80 -0.86 -1.78 0.05 -1.35 0.37 -1.70 -2.14 -1.64 0.28 -2.54 0.36 -0.86 -0.56 0.05 0.21 0.75 -1.70 -2.22 -1.64 -1.15 -0.40 -1.80 -0.86 -1.78 0.05 -1.46 0.52 -1.70 -2.28 -1.64 0.28 -3.06 -0.72 -0.86 -1.17 0.05 0.53 0.20 -1.70 -1.43 -1.62 -1.15 0.01 -0.72 -0.86 -1.17 0.05 -0.66 0.69 .... </code></pre>
0
2016-08-19T22:12:50Z
39,049,100
<p>You have <code>NaN</code> values in your <code>raw.dat</code> file. Drop that column or replace it with 0s.</p>
0
2016-08-19T23:46:53Z
[ "python", "numpy", "machine-learning", "scikit-learn" ]
Print large data to file with special format from Python
39,048,390
<p>I need to print some data to a txt file from Python 3.4/3.2.</p> <p>Each line in the file has this format:</p> <pre><code> col1 | col2 | col3 | id1 CT_TYPE value1 CT_TYPE value2 AR CT1 239 CT2 9.66 AR CT3 8.65 NY CT1 6.25 CT2 67.89 NY CT3 78.61 </code></pre> <p>For same id1, if there are more than 2 values of CT_TYPE, they must be printed in both of col2 and col3 and the only the last value of the id1 type can leave col3 empty. For example, the following print format is wrong. </p> <pre><code> col1 | col2 | col3 | id1 CT_TYPE value1 CT_TYPE value2 AR CT1 239 " this cannot be left as blank" AR CT2 9.66 CT3 8.65 </code></pre> <p>For different id1 value, a new line must be added. Fror example, id1 = NY can not be at the same line with AR: </p> <pre><code> AR CT3 8.65 NY CT1 6.25 // this is not allowed. </code></pre> <p>There hundreds of thousands of data lines that need to be printed. I do not want to use sorting because the data size is to large to be kept in a data structure in python. So, I have to load the data from database block by block and print them to file. I can make sure that each block loaded from database has the same id1 value.</p> <p>My question is how to make sure that the above format is kept when data is printed block by block ? In python, I used: </p> <pre><code> with open(fileName, 'a') as f: f.wite(aLine + "\n"); </code></pre> <p>How to change the current print position so that the CT_type values of the same id1 type are printed at the same row even enough a newline "\n" has been added after the last data line was printed. For example, if my file has these:</p> <pre><code> col1 | col2 | col3 | id1 CT_TYPE value1 CT_TYPE value2 AR CT1 239 </code></pre> <p>A new data line in a new block is like:</p> <pre><code> AR CT2 9.66 </code></pre> <p>I want :</p> <pre><code> col1 | col2 | col3 | id1 CT_TYPE value1 CT_TYPE value2 AR CT1 239 CT2 9.66 </code></pre> <p>Not :</p> <pre><code> col1 | col2 | col3 | id1 CT_TYPE value1 CT_TYPE value2 AR CT1 239 AR CT2 9.66 </code></pre> <p>Thanks</p>
0
2016-08-19T22:16:31Z
39,048,514
<p>If I understand the problem correctly, I would use something where it only stores the id and cttype until it finds a match on id, then output to file and del from memory. The below is to illust</p> <pre><code>fobj_in = open('file','r') fobj_out = open('output','a') unmatched = {} for line in fobj_in: elem = line.split('\t') id1, cttype = elem if id1 not in unmatched: unmatched[id1] = cttype else: cttype_ = unmatched.pop(id1) fobj.write('\t'.join([id1,cttype_, cttype])) for id in unmatched: fobj.write('\t'.join([id, unmatched.pop(id)])) fobj_in.close() fobj_out.close() </code></pre> <p>The above is for illustration only, and may have errors or other issues. </p>
0
2016-08-19T22:29:22Z
[ "python", "python-3.x", "pydev" ]
Python requests Library SSL error: [Errno 2] No such file or directory
39,048,446
<p>first ever question: I'm getting the following result:</p> <blockquote> <p>File "D:\Anaconda\Lib\site-packages\requests\api.py", line 70, in get return request('get', url, params=params, **kwargs)</p> <p>File "D:\Anaconda\Lib\site-packages\requests\api.py", line 56, in request return session.request(method=method, url=url, **kwargs)</p> <p>File "D:\Anaconda\Lib\site-packages\requests\sessions.py", line 475, in request resp = self.send(prep, **send_kwargs)</p> <p>File "D:\Anaconda\Lib\site-packages\requests\sessions.py", line 596, in send r = adapter.send(request, **kwargs)</p> <p>File "D:\Anaconda\Lib\site-packages\requests\adapters.py", line 497, in send raise SSLError(e, request=request)</p> <p>requests.exceptions.SSLError: [Errno 2] No such file or directory</p> </blockquote> <p>This traces back to one line of code here:</p> <pre><code>import requests, os, bs4, calendar #, sys import urllib.request while not year&gt;2016: print('Downloading page {}...'.format(url)) res = requests.get(loginpageURL, verify='false', auth=('username', 'password')) #this is the line that doesn't work res = requests.get(url, verify='false') #but I have tried it without that line and this line also doesn't work res.raise_for_status() soup = bs4.BeautifulSoup(res.text) print(soup) </code></pre> <p>I have researched the issue extensively, and come to the conclusion that it is actually an issue with the requests/urllib3 libraries themselves.</p> <p>At first, I tried the verify='false' fix <a href="http://stackoverflow.com/questions/10667960/python-requests-throwing-up-sslerror">here</a>. It didn't work. Someone <a href="https://stackoverflow.com/questions/30830901/python-requests-throwing-ssl-errors">here</a> said to install new openSSL and certifi, they appear to be installed and up to date on my system. Found the bug has a great writeup on <a href="https://github.com/kennethreitz/requests/issues/3058" rel="nofollow">here</a>. No solution from what I could see. It has been identified on github as a known issue <a href="https://github.com/kennethreitz/requests/issues/2863" rel="nofollow">here</a>.</p> <p>When, according to <a href="https://stackoverflow.com/questions/33137337/python-requests-ssl-error-with-combined-pem-file">this</a> answer, I tried to change verify='false' to verify='cacert.pem' (which I included in the project directory), it threw this error: requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)</p> <p>Now I'm sitting here just wanting to get this one code snippet to run - I'm trying to bulk download a few hundred zip files from a website - in spite of the known issue with the library. I'm relatively new to python, but especially new to web scraping, so this is a steep learning curve for me. Any help would be appreciated. Do I need to go so far as <a href="https://stackoverflow.com/questions/34310878/python-authentication-not-recognised-urllib2-requests-asp-net">scrapping requests</a>?</p> <p>Thanks!</p>
0
2016-08-19T22:21:36Z
39,050,680
<blockquote> <pre><code>res = requests.get(loginpageURL, verify='false', ... </code></pre> </blockquote> <p>Verify takes either a boolean (i.e. True or False) or a path which is then used as path for the trust store. Your specification <code>'false'</code> is a string and not a boolean and it will therefore try to use the file <code>false</code> as CA store. This file cannot be found and thus results in <code>No such file or directory</code>. </p> <p>To fix this you have to use <code>verify=False</code>, i.e. use the boolean value. </p> <p>Apart from that disabling the validation is a bad idea and should only be done for testing or when the security offered by TLS is completely irrelevant for the program. For a login page like in your case disabling validation is probably a bad thing because a man in the middle can thus easily sniff the username and password.</p>
0
2016-08-20T05:08:21Z
[ "python", "ssl", "python-requests" ]
Display HTML form data as JSON on new page using Flask
39,048,448
<p>I have made a simple HTML form on a page and I would like to gather all the data from the form, convert it to JSON, then display that JSON on a new page. I don't need or want a database to save this data, I just want it to spit out onto a new page in proper JSON format so that the person using it can copy/paste that data for something else. </p> <p>I'm using Flask, here is the HTML form I made that extends another basic layout page:</p> <pre><code>{% extends "layout.html" %} {% block content %} &lt;div class="container"&gt; &lt;form action="/display" method="post" id="employForm" &lt;fieldset&gt; &lt;label&gt;First Name &lt;input type="text" name="firstName" placeholder="Joe" required&gt; &lt;/label&gt; &lt;label&gt;Last Name &lt;input type="text" name="lastName" id="lastName" placeholder="Schmoe" required&gt; &lt;/label&gt; &lt;label&gt; Department &lt;select name="department" required&gt; &lt;option value="sales"&gt;Sales&lt;/option&gt; &lt;option value="marketing"&gt;Marketing&lt;/option&gt; &lt;option value="developer"&gt;Developer&lt;/option&gt; &lt;option value="business"&gt;Business Relations&lt;/option&gt; &lt;option value="sysAdmin"&gt;Systems Administration&lt;/option&gt; &lt;option value="drone"&gt;Drone&lt;/option&gt; &lt;/select&gt; &lt;/label&gt; ... goes on &lt;/fieldset&gt; &lt;button class="button-primary" type="submit" value="Submit" form="employForm"&gt;SUBMIT!&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; {% endblock %} </code></pre> <p>The form is a bit longer than that and contains several different types of form data. Here is the server side of things (the flask app I made):</p> <pre><code>from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route('/') def hello(): return render_template('home.html') @app.route('/display', methods=["GET", "POST"]) def display(): result = request.form return render_template('display.html', result=result) if __name__ == "__main__": app.run(host='0.0.0.0') </code></pre> <p>I feel like I'm close. At the moment, after I hit submit I get redirected to the display page and it prints out something like the following (specific data changes based on input answers, obviously): </p> <pre><code>ImmutableMultiDict([('startDate', u'2016-08-03'), ('employmentStatus', u'intern'), ('firstName', u'Hola'), ('lastName', u'Schmoe'), ('department', u'marketing'), ('location', u'SanFran'), ('inNYC', u'Yes'), ('requests', u'Blah blah try this.')]) </code></pre> <p>I've done quite a bit of searching on Stack Overflow and elsewhere... the problem I've encountered is that they all provide examples where a person only wants to collect one or two keys off of their form, not the whole form. </p> <p>Additionally, for my particular purposes I would strongly prefer that the data be returned as JSON and displayed as such on the display.html page. </p> <p>For reference, here are some of the questions I looked at that didn't quite help:</p> <p><a href="http://stackoverflow.com/questions/15080672/how-to-post-data-structure-like-json-to-flask">How to post data structure like json to flask?</a></p> <p><a href="http://stackoverflow.com/questions/24360684/getting-form-data-from-html-form-using-flask-and-python">Getting form data from html form using flask and python</a></p> <p><a href="http://stackoverflow.com/questions/14112336/flask-request-and-application-json-content-type">Flask request and application/json content type</a></p> <p><a href="http://stackoverflow.com/questions/12277933/send-data-from-a-textbox-into-flask">Send Data from a textbox into Flask?</a></p> <p>Any guidance is much appreciated. Thank you!</p>
0
2016-08-19T22:21:59Z
39,049,037
<p>I see you import jsonify... you could use that...</p> <pre><code>@app.route('/display', methods=["GET", "POST"]) def display(): return jsonify(request.form) </code></pre> <p>or you could use the tojson filter in your template</p> <p><code>{{ result | tojson }}</code></p> <p>or </p> <p><code>result = json.dumps(request.form)</code></p> <p>I think any of those will work.</p>
0
2016-08-19T23:38:03Z
[ "python", "html", "json", "flask" ]
replace multiple characters in string with value from dictionary python
39,048,559
<p>I'm trying to create a function that iterates through a string, finds characters that match to keys in a dictionary and replaces that character with the value in the dictionary for that key. However it currently only replaces first occurrence of a letter that is in the dictionary and stops there, where am I going wrong? </p> <pre><code>d = { 'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0', 'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0', } def cypher(string): for i in string: if i in d: a = string.replace(i,d[i]) return a </code></pre>
0
2016-08-19T22:34:02Z
39,048,589
<p>Your return statement is within the if statement, so if a character matches, your function replaces that single character and then returns.</p> <p>If you want all of your characters replaced, let it iterate through all characters of the string by moving your return statement outside of the for loop.</p> <pre><code>def cypher(string): result = string for i in string: if i in d: result = result.replace(i,d[i]) return result </code></pre>
2
2016-08-19T22:37:21Z
[ "python", "dictionary" ]
replace multiple characters in string with value from dictionary python
39,048,559
<p>I'm trying to create a function that iterates through a string, finds characters that match to keys in a dictionary and replaces that character with the value in the dictionary for that key. However it currently only replaces first occurrence of a letter that is in the dictionary and stops there, where am I going wrong? </p> <pre><code>d = { 'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0', 'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0', } def cypher(string): for i in string: if i in d: a = string.replace(i,d[i]) return a </code></pre>
0
2016-08-19T22:34:02Z
39,048,625
<p>You are prematurely ending your code with the call to <code>return</code> within the for loop. You can fix it by storing your new string outside of the loop, only returning once the loop is done:</p> <pre><code>def cypher(string): a = string # a new string to store the replaced string for i in string: if i in d: a = a.replace(i, d[i]) return a </code></pre> <p>There is something wrong about the logic too, though. If you have a value in your dictionary that is also a key in the dictionary, the key may get replaced twice. For example, if you have <code>d = {'I': 'i', 'i': 'a'}</code>, and the input is <code>Ii</code>, your output would be <code>aa</code>.</p> <p>Here's a much more concise implementation using <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> that does not have this problem.</p> <pre><code>def cypher(string): return ''.join(d.get(l, l) for l in string) </code></pre>
1
2016-08-19T22:42:52Z
[ "python", "dictionary" ]
replace multiple characters in string with value from dictionary python
39,048,559
<p>I'm trying to create a function that iterates through a string, finds characters that match to keys in a dictionary and replaces that character with the value in the dictionary for that key. However it currently only replaces first occurrence of a letter that is in the dictionary and stops there, where am I going wrong? </p> <pre><code>d = { 'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0', 'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0', } def cypher(string): for i in string: if i in d: a = string.replace(i,d[i]) return a </code></pre>
0
2016-08-19T22:34:02Z
39,048,656
<p>As zachyee pointed out, your <code>return</code> statement is inside the loop.</p> <p>You may want to take a look at <a href="https://docs.python.org/3.4/library/stdtypes.html#str.translate" rel="nofollow"><code>str.translate</code></a>, which does exactly what you want:</p> <pre><code>def cypher(string): return string.translate(str.maketrans(d)) </code></pre> <p>Note the use of <a href="https://docs.python.org/3.4/library/stdtypes.html#str.maketrans" rel="nofollow"><code>str.maketrans</code></a> that transforms your dict in something that <code>string.translate</code> can use. This method is however limited to mappings of single characters.</p>
0
2016-08-19T22:46:33Z
[ "python", "dictionary" ]
replace multiple characters in string with value from dictionary python
39,048,559
<p>I'm trying to create a function that iterates through a string, finds characters that match to keys in a dictionary and replaces that character with the value in the dictionary for that key. However it currently only replaces first occurrence of a letter that is in the dictionary and stops there, where am I going wrong? </p> <pre><code>d = { 'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0', 'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0', } def cypher(string): for i in string: if i in d: a = string.replace(i,d[i]) return a </code></pre>
0
2016-08-19T22:34:02Z
39,048,718
<p>One liner -> <code>print ''.join(d[c] if c in d else c for c in s)</code></p> <p><strong>Sample Output:</strong></p> <pre><code>&gt;&gt;&gt; s = 'Hello World' &gt;&gt;&gt; d = { 'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0', 'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0', } &gt;&gt;&gt; print ''.join(d[c] if c in d else c for c in s) H3110 W0r1d </code></pre>
1
2016-08-19T22:54:44Z
[ "python", "dictionary" ]
Why does it take forever to run my python code even for a small input?
39,048,562
<p>I am new to programming, and I am also new to this website. So sorry if my code is stupid, and I'm wasting your time. I have been trying to solve a Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">Problem 12</a>. With a little help of internet I've come up with an algorithm and wrote a code in python. I've tried to generalise it so that it works for all numbers not only 500. At first I had problems with getting the right output, but then when I thought I fixed it, it only got worse because the program took forever to run. Could you point out the misstakes I've made:</p> <pre><code>L = int(input("L=")) def number_of_divisors(n): global divisors global count global p divisors = 1 count = 0 if n%2 == 0: while n%2 == 0: count += 1 n=n/2 divisors = divisors * count count = 0 p = 3 while n != 1: while n%p == 0: count +=1 n = n/p p += 2 divisors *= (count + 1) return divisors def the_first_triangular_number_with_more_than_L_divisors(L): global total_divisors global n total_divisors , n = 1 , 1 while total_divisors &lt;= L: s = number_of_divisors(n+1) total_divisors *= s total_divisors = s n += 1 return (n*(n+1))/2 x = the_first_triangular_number_with_more_than_L_divisors(L) print(x) </code></pre>
0
2016-08-19T22:34:24Z
39,048,920
<p>This is likely an infinite loop. If it enters the loop and s &lt;= L, it will repeat indefinitely because of the last line (perhaps a typo).</p> <pre><code>while total_divisors &lt;= L: s = number_of_divisors(n+1) total_divisors *= s total_divisors = s </code></pre> <p>Here is an answer that mirrors yours quite closely, you can take a look if you're completely stumped:</p> <p><a href="http://code.jasonbhill.com/sage/project-euler-problem-12/" rel="nofollow">http://code.jasonbhill.com/sage/project-euler-problem-12/</a></p>
1
2016-08-19T23:24:10Z
[ "python" ]
How do I change x and y axes in matplotlib?
39,048,603
<p>I am using matplotlib to draw neuralnet. I found a code that draws neural net, but it is oriented from top to bottom. I would like to change the orientation from left to right. So basically I would like to change x and y axes after I already plotted all the shapes. Is there an easy way to do this? I also found an answer that said that you can change parameter "orientation" to horizontal (code below) but I don't really understand where in my code should I copy that. would that give me the same result?</p> <pre><code>matplotlib.pyplot.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=u'bar', align=u'mid', orientation=u'vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, **kwargs) </code></pre>
-1
2016-08-19T22:40:06Z
39,064,179
<p>What you have in your code is an example of how to launch an histogram in matplotlib. Notice you are using the pyplot default interface (and not necessarily building your own figure).</p> <p>As so this line:</p> <pre><code>orientation=u'vertical', </code></pre> <p>should be:</p> <pre><code>orientation=u'horizontal', </code></pre> <p>, if you want the bars to go from left to right. This however will not help you with the y axis. For you to invert the y axis you should use the command:</p> <pre><code>plt.gca().invert_yaxis() </code></pre> <p>The following example shows you how to build an histogram from random data (asymmetric to be easier to perceive modifications). The first plot is the normal histogram, the second I change the histogram orientation; in the last I invert the y axis. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.random.exponential(1, 100) # Showing the first plot. plt.hist(data, bins=10) plt.show() # Cleaning the plot (useful if you want to draw new shapes without closing the figure # but quite useless for this particular example. I put it here as an example). plt.gcf().clear() # Showing the plot with horizontal orientation plt.hist(data, bins=10, orientation='horizontal') plt.show() # Cleaning the plot. plt.gcf().clear() # Showing the third plot with orizontal orientation and inverted y axis. plt.hist(data, bins=10, orientation='horizontal') plt.gca().invert_yaxis() plt.show() </code></pre> <p>The result for plot 1 is (default histogram):</p> <p><a href="http://i.stack.imgur.com/gLXzY.png" rel="nofollow"><img src="http://i.stack.imgur.com/gLXzY.png" alt="default histogram in matplotlib"></a></p> <p>The second (changed bar orientation):</p> <p><a href="http://i.stack.imgur.com/l6zNb.png" rel="nofollow"><img src="http://i.stack.imgur.com/l6zNb.png" alt="default histogram in matplotlib with changed orientation"></a></p> <p>And finally the third (inverted y axis):</p> <p><a href="http://i.stack.imgur.com/biyvZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/biyvZ.png" alt="Histogram in matplotlib with horizontal bars and inverted y axis"></a></p>
0
2016-08-21T12:26:22Z
[ "python", "matplotlib" ]
Need to find the intersection point of two line segments iterated over multiple segments
39,048,648
<p>OK, here is the problem. I am trying to calculate the intersection of two lines by comparing multiple line segments that are read out of a series of csv files. I've already got the x,y coordinate pairs for each line segment into a list of tuples within tuples as follows:</p> <pre><code>continuousLine = [((x1,y1),(x2,y2)), ...] crossingLines = [((x1,y1),(x2,y2)), ...] </code></pre> <p><a href="http://i.stack.imgur.com/Iu0LQ.png" rel="nofollow">Line Problem</a></p> <p>I am trying to figure out how to iterate along the continuous line and through the crossing lines to find out where along the continuous line each crossing line intersects. </p> <p>Basically I want (pseudo-code listed below):</p> <pre><code>for segment in continuousLine: if segment in crossingLines intersect == True: return intersection else: move on to next crossing line segment and repeat test </code></pre> <p>I hate asking for help on this because I am too new to coding to help other people, but hopefully someone can work through this with me. </p> <p>I do have a method that I think will work to calculate the intersection once I've figured out the iterator:</p> <pre><code>line1 = () line2 = () def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(xdiff, ydiff) if div == 0: raise Exception('lines do not intersect') d = (det(*line1), det(*line2)) x = det(d, xdiff) / div y = det(d, ydiff) / div return x, y print line_intersection((A, B), (C, D)) </code></pre>
2
2016-08-19T22:45:28Z
39,049,367
<p>Suppose the function <code>line_intersection</code> would return False on <code>div == 0</code> instead of raising exeption.</p> <p><strong>The easy way:</strong></p> <pre><code>filter(None, [intersection(a, b) for a in continuousLine for b in crossingLines]) </code></pre> <p>However, using nested loop, it is slow when there are lots of segments in crossingLines.</p> <p><strong>A more efficient way:</strong></p> <p>To improve performance, have a try on <a href="https://pypi.python.org/pypi/intervaltree" rel="nofollow">intervaltree</a>, which will give you the intersect candidates for testing. In your case, first build a interval tree on crossingLines, then loop through continuousLine to find intersect candidates in that tree, and test to get the final result.</p>
0
2016-08-20T00:31:31Z
[ "python", "line-intersection" ]
Need to find the intersection point of two line segments iterated over multiple segments
39,048,648
<p>OK, here is the problem. I am trying to calculate the intersection of two lines by comparing multiple line segments that are read out of a series of csv files. I've already got the x,y coordinate pairs for each line segment into a list of tuples within tuples as follows:</p> <pre><code>continuousLine = [((x1,y1),(x2,y2)), ...] crossingLines = [((x1,y1),(x2,y2)), ...] </code></pre> <p><a href="http://i.stack.imgur.com/Iu0LQ.png" rel="nofollow">Line Problem</a></p> <p>I am trying to figure out how to iterate along the continuous line and through the crossing lines to find out where along the continuous line each crossing line intersects. </p> <p>Basically I want (pseudo-code listed below):</p> <pre><code>for segment in continuousLine: if segment in crossingLines intersect == True: return intersection else: move on to next crossing line segment and repeat test </code></pre> <p>I hate asking for help on this because I am too new to coding to help other people, but hopefully someone can work through this with me. </p> <p>I do have a method that I think will work to calculate the intersection once I've figured out the iterator:</p> <pre><code>line1 = () line2 = () def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]) ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(xdiff, ydiff) if div == 0: raise Exception('lines do not intersect') d = (det(*line1), det(*line2)) x = det(d, xdiff) / div y = det(d, ydiff) / div return x, y print line_intersection((A, B), (C, D)) </code></pre>
2
2016-08-19T22:45:28Z
39,049,383
<p>Since you haven't provided any sample input and expected output, I'm going to use the dummy version of the <code>line_intersection()</code> function shown below. All it does is print its input and returns a hardcoded result — but it will show you how to iterate through the input data and pass it to the real function.</p> <p>It should be clear from the output what it's doing.</p> <pre><code>def line_intersection(line1, line2): print('intersecting:') print(' ({}. {}), ({}, {})'.format(line1[0][0], line1[0][1], line1[1][0], line1[1][1])) print(' ({}. {}), ({}, {})'.format(line2[0][0], line2[0][1], line2[1][0], line2[1][1])) print('') return 100, 200 </code></pre> <p>All the looping has been put in a generator function named <code>find_intersections()</code> which returns successive intersections it finds, skipping any combinations that don't.</p> <pre><code>def find_intersections(continuous_line, crossing_lines): for cl_segment in continuous_line: for xl_segment in crossing_lines: try: x, y = line_intersection(cl_segment, xl_segment) except Exception: pass else: yield x, y </code></pre> <p>Here's a usage example with made-up input data:</p> <pre><code>continuous_line = [((1,2),(3,4)), ((5,6),(7,8)), ((9,10),(11,12))] crossing_lines = [((21,22),(23,24)), ((25,26),(27,28)), ((29,30),(31,32))] intersections = [(x, y) for x, y in find_intersections(continuous_line, crossing_lines)] print('intersections found:') print(intersections) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>intersecting: (1. 2), (3, 4) (21. 22), (23, 24) intersecting: (1. 2), (3, 4) (25. 26), (27, 28) intersecting: (1. 2), (3, 4) (29. 30), (31, 32) intersecting: (5. 6), (7, 8) (21. 22), (23, 24) intersecting: (5. 6), (7, 8) (25. 26), (27, 28) intersecting: (5. 6), (7, 8) (29. 30), (31, 32) intersecting: (9. 10), (11, 12) (21. 22), (23, 24) intersecting: (9. 10), (11, 12) (25. 26), (27, 28) intersecting: (9. 10), (11, 12) (29. 30), (31, 32) intersections found: [(100, 200), (100, 200), (100, 200), (100, 200), (100, 200), (100, 200), (100, 200), (100, 200), (100, 200)] </code></pre>
0
2016-08-20T00:35:24Z
[ "python", "line-intersection" ]
Learn Python the Hard Way (Exercise 20) has weird symbols when run
39,048,749
<p>Here's the code. </p> <pre><code>from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): print f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First, we'll print the whole file.\n" print_all(current_file) print "Now let's rewind." rewind(current_file) print "Let's print three lines." current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) </code></pre> <p>And here's the code when run through Terminal (OS X).</p> <pre><code>First, we'll print the whole file. {\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf470 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0 \f0\fs24 \cf0 example 1\ example 2\ example 3} Now let's rewind. None Let's print three lines. 1 {\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf470 2 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} 3 {\colortbl;\red255\green255\blue255;} </code></pre> <p>What seems to be going on here? I even copy and pasted the code from <a href="http://learnpythonthehardway.org/book/ex20.html" rel="nofollow">http://learnpythonthehardway.org/book/ex20.html</a> to see if I was doing something wrong but it did the same thing.</p>
-1
2016-08-19T23:00:37Z
39,048,806
<p>You created your input file using a word processor. Use a text editor (Notepad in Windows, I don't know what you'd have in OS X) to create your input file.</p>
0
2016-08-19T23:07:08Z
[ "python" ]
Learn Python the Hard Way (Exercise 20) has weird symbols when run
39,048,749
<p>Here's the code. </p> <pre><code>from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): print f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First, we'll print the whole file.\n" print_all(current_file) print "Now let's rewind." rewind(current_file) print "Let's print three lines." current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) </code></pre> <p>And here's the code when run through Terminal (OS X).</p> <pre><code>First, we'll print the whole file. {\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf470 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0 \f0\fs24 \cf0 example 1\ example 2\ example 3} Now let's rewind. None Let's print three lines. 1 {\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf470 2 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} 3 {\colortbl;\red255\green255\blue255;} </code></pre> <p>What seems to be going on here? I even copy and pasted the code from <a href="http://learnpythonthehardway.org/book/ex20.html" rel="nofollow">http://learnpythonthehardway.org/book/ex20.html</a> to see if I was doing something wrong but it did the same thing.</p>
-1
2016-08-19T23:00:37Z
39,048,881
<p>You edited your file in TextEdit - python is spitting out the bytes that reflect the RTF formatting of the file. Before saving from TextEdit, choose Format >> Make Text File</p>
1
2016-08-19T23:17:43Z
[ "python" ]
How can I convert a pyspark.sql.dataframe.DataFrame back to a sql table in databricks notebook
39,048,777
<p>I created a dataframe of type <code>pyspark.sql.dataframe.DataFrame</code> by executing the following line: <code>dataframe = sqlContext.sql("select * from my_data_table")</code></p> <p>How can I convert this back to a sparksql table that I can run sql queries on?</p>
5
2016-08-19T23:03:53Z
39,048,907
<p>You can create your table by using <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html?highlight=sql#pyspark.sql.DataFrame.createOrReplaceTempView" rel="nofollow">createReplaceTempView</a>. In your case it would be like:</p> <pre><code>dataframe.createOrReplaceTempView("mytable") </code></pre> <p>After this you can query your <code>mytable</code> using <em>SQL</em>.</p> <p>If your a spark version is ≤ 1.6.2 you can use <a href="http://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html?highlight=dataframe#pyspark.sql.DataFrame.registerTempTable" rel="nofollow">registerTempTable</a></p>
1
2016-08-19T23:21:54Z
[ "python", "sql", "apache-spark", "pyspark", "databricks" ]
Tor Browser with RSelenium in Linux/Windows
39,048,810
<p>Looking to use RSelenium and Tor using my Linux machine to return the Tor IP (w/Firefox as Tor Browser). This is doable with Python, but having trouble with it in R. Can anybody get this to work? Perhaps you can share your solution in either Windows / Linux.</p> <pre><code># library(devtools) # devtools::install_github("ropensci/RSelenium") library(RSelenium) RSelenium::checkForServer() RSelenium::startServer() binaryExtension &lt;- paste0(Sys.getenv('HOME'),"/Desktop/tor-browser_en-US/Browser/firefox") remDr &lt;- remoteDriver(dir = binaryExtention) remDr$open() remDr$navigate("http://myexternalip.com/raw") remDr$quit() </code></pre> <p>The error <code>Error in callSuper(...) : object 'binaryExtention' not found</code> is being returned.</p> <p>For community reference, this Selenium code works in Windows using Python3:</p> <pre><code>from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from os.path import expanduser # Finds user's user name on Windows # Substring inserted to overcome r requirement in FirefoxBinary binary = FirefoxBinary(r"%s\\Desktop\\Tor Browser\\Browser\\firefox.exe" % (expanduser("~"))) profile = FirefoxProfile(r"%s\\Desktop\\Tor Browser\\Browser\\TorBrowser\\Data\\Browser\\profile.default" % (expanduser("~"))) driver = webdriver.Firefox(profile, binary) driver.get('http://myexternalip.com/raw') html = driver.page_source soup = BeautifulSoup(html, "lxml") # lxml needed # driver.close() # line.strip('\n') "Current Tor IP: " + soup.text.strip('\n') # Based in part on # http://stackoverflow.com/questions/13960326/how-can-i-parse-a-website-using-selenium-and-beautifulsoup-in-python # http://stackoverflow.com/questions/34316878/python-selenium-binding-with-tor-browser # http://stackoverflow.com/questions/3367288/insert-variable-values-into-a-string-in-python </code></pre>
2
2016-08-19T23:08:22Z
39,048,970
<p>Something like the following should work:</p> <pre><code>browserP &lt;- paste0(Sys.getenv('HOME'),"/Desktop/tor-browser_en-US/Browser/firefox") jArg &lt;- paste0("-Dwebdriver.firefox.bin='", browserP, "'") selServ &lt;- RSelenium::startServer(javaargs = jArg) </code></pre> <p>UPDATE:</p> <p>This worked for me on windows. Firstly run the beta version:</p> <pre><code>checkForServer(update = TRUE, beta = TRUE, rename = FALSE) </code></pre> <p>Next open a version of the tor browser manually.</p> <pre><code>library(RSelenium) browserP &lt;- "C:/Users/john/Desktop/Tor Browser/Browser/firefox.exe" jArg &lt;- paste0("-Dwebdriver.firefox.bin=\"", browserP, "\"") pLoc &lt;- "C:/Users/john/Desktop/Tor Browser/Browser/TorBrowser/Data/Browser/profile.meek-http-helper/" jArg &lt;- c(jArg, paste0("-Dwebdriver.firefox.profile=\"", pLoc, "\"")) selServ &lt;- RSelenium::startServer(javaargs = jArg) remDr &lt;- remoteDriver(extraCapabilities = list(marionette = TRUE)) remDr$open() remDr$navigate("https://check.torproject.org/") &gt; remDr$getTitle() [[1]] [1] "Congratulations. This browser is configured to use Tor." </code></pre>
3
2016-08-19T23:30:20Z
[ "python", "selenium", "tor", "rselenium" ]
Python 3 IndentationError
39,048,844
<p>In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:</p> <pre><code>import random import copy import sys the_board = [" "]*10 def printboard(board): print(board[7] + " " + "|" + board[8] + " " + "|" + board[9]) print("--------") print(board[4] + " " + "|" + board[5] + " " + "|" + board[6]) print("--------") print(board[1] + " " + "|" + board[2] + " " + "|" + board[3]) def choose_player(): while True: player = input("What do you want to be; X or O?") if player == "X": print("You chose X") comp = "O" break elif player == "O": print("You chose O") comp = "X" break else: print("Invalid Selection") continue return [player, comp] def virtual_toss(): print("Tossing to see who goes first.....") x = random.randint(0,1) if x== 0: print("AI goes first") move = "comp" if x == 1: print("Human goes first") move = "hum" return move def win(board,le): if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le): return True else: return False def make_move(board,number,symbol): board[number] = symbol def board_full(board): count = 0 for item in board: if item in ["X","O"]: count+= 1 if count ==9 : return True else: return False def valid_move(board,num): if board[num] == " ": return True else: return False def player_move(board): number = int(input("Enter the number")) return number def copy_board(board): copied_board = copy.copy(board) return copied_board def check_corner(board): if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "): return True else: return False def check_center(board): if (board[5] == " "): return True else: return False while True: count = 0 loop_break = 0 print("welcome to TIC TAC TOE") pla,comp = choose_player() turn = virtual_toss() while True: printboard(the_board) if turn == "hum": if board_full() == True: again = input ("Game is a tie. Want to try again? Y for yes and N for No") if again == "Y": loop_break = 6 break else: system.exit() if loop_break == 6: continue while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break else: turn = "comp" printboard(the_board) continue else: if board_full() == True: again = input ("Game is a tie. Want to try again? Y for yes and N for No") if again == "Y": loop_break = 6 break else: system.exit() if loop_break = 6: continue copy_board(the_board) for i in range(0,9): make_move(copied_board,i,pla) if(win(copied_board,pla) == True): make_move(the_board,comp) turn = "hum" loop_break = 1 break else: continue if loop_break = 1: continue if (check_corner(the_board) == True) or (check_center(the_board)==True): for i in [7,9,1,3,5]: if(valid_move(copied_board,i)==True): make_move(copied_board,i,comp) if(win(copied_board,comp)==True): make_move(the_board,i,comp) print("The AI beat you") loop_break = 2 count = 1 break else: make_move(the_board,i,comp) turn = "hum" loop_break = 3 break if loop_break == 2: break elif loop_break == 3: continue else: for i in [8,4,6,2]: if(valid_move(copied_board,i)==True): make_move(copied_board,i,comp) if(win(copied_board,comp)): make_move(the_board,i,comp) print("The AI beat you") count = 1 loop_break = 4 break else: make_move(the_board,i,comp) turn = "hum" loop_break = 5 break if loop_break == 4: break elif loop_break == 5: continue if count == 1: again = input("Would you like to play again? y/n") if again == "y": continue else: system.exit() </code></pre> <p>I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:</p> <pre><code> Traceback (most recent call last): File "python", line 106 if (win(the_board,pla) == True): ^ IndentationError: unindent does not match any outer indentation level </code></pre> <p>More specifically, this part of the code:</p> <pre><code>while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break </code></pre> <p>Any help? I cannot get the code to work by any means!!</p>
-4
2016-08-19T23:12:42Z
39,048,872
<p>Try unindenting the previous seven lines of code by one level (the code in that <code>while</code> loop). This should make the indents work correctly. Also, it seems that there is an extra space before the <code>if</code> statement that is causing you errors. Remove this space as well. This would make that part of the code like this:</p> <pre><code>while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break </code></pre>
0
2016-08-19T23:16:27Z
[ "python", "python-3.x", "indentation" ]
Python 3 IndentationError
39,048,844
<p>In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:</p> <pre><code>import random import copy import sys the_board = [" "]*10 def printboard(board): print(board[7] + " " + "|" + board[8] + " " + "|" + board[9]) print("--------") print(board[4] + " " + "|" + board[5] + " " + "|" + board[6]) print("--------") print(board[1] + " " + "|" + board[2] + " " + "|" + board[3]) def choose_player(): while True: player = input("What do you want to be; X or O?") if player == "X": print("You chose X") comp = "O" break elif player == "O": print("You chose O") comp = "X" break else: print("Invalid Selection") continue return [player, comp] def virtual_toss(): print("Tossing to see who goes first.....") x = random.randint(0,1) if x== 0: print("AI goes first") move = "comp" if x == 1: print("Human goes first") move = "hum" return move def win(board,le): if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le): return True else: return False def make_move(board,number,symbol): board[number] = symbol def board_full(board): count = 0 for item in board: if item in ["X","O"]: count+= 1 if count ==9 : return True else: return False def valid_move(board,num): if board[num] == " ": return True else: return False def player_move(board): number = int(input("Enter the number")) return number def copy_board(board): copied_board = copy.copy(board) return copied_board def check_corner(board): if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "): return True else: return False def check_center(board): if (board[5] == " "): return True else: return False while True: count = 0 loop_break = 0 print("welcome to TIC TAC TOE") pla,comp = choose_player() turn = virtual_toss() while True: printboard(the_board) if turn == "hum": if board_full() == True: again = input ("Game is a tie. Want to try again? Y for yes and N for No") if again == "Y": loop_break = 6 break else: system.exit() if loop_break == 6: continue while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break else: turn = "comp" printboard(the_board) continue else: if board_full() == True: again = input ("Game is a tie. Want to try again? Y for yes and N for No") if again == "Y": loop_break = 6 break else: system.exit() if loop_break = 6: continue copy_board(the_board) for i in range(0,9): make_move(copied_board,i,pla) if(win(copied_board,pla) == True): make_move(the_board,comp) turn = "hum" loop_break = 1 break else: continue if loop_break = 1: continue if (check_corner(the_board) == True) or (check_center(the_board)==True): for i in [7,9,1,3,5]: if(valid_move(copied_board,i)==True): make_move(copied_board,i,comp) if(win(copied_board,comp)==True): make_move(the_board,i,comp) print("The AI beat you") loop_break = 2 count = 1 break else: make_move(the_board,i,comp) turn = "hum" loop_break = 3 break if loop_break == 2: break elif loop_break == 3: continue else: for i in [8,4,6,2]: if(valid_move(copied_board,i)==True): make_move(copied_board,i,comp) if(win(copied_board,comp)): make_move(the_board,i,comp) print("The AI beat you") count = 1 loop_break = 4 break else: make_move(the_board,i,comp) turn = "hum" loop_break = 5 break if loop_break == 4: break elif loop_break == 5: continue if count == 1: again = input("Would you like to play again? y/n") if again == "y": continue else: system.exit() </code></pre> <p>I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:</p> <pre><code> Traceback (most recent call last): File "python", line 106 if (win(the_board,pla) == True): ^ IndentationError: unindent does not match any outer indentation level </code></pre> <p>More specifically, this part of the code:</p> <pre><code>while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break </code></pre> <p>Any help? I cannot get the code to work by any means!!</p>
-4
2016-08-19T23:12:42Z
39,048,875
<p>You need to indent the block under <code>while (True):</code> consistently. E.g.:</p> <pre><code>while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break else: turn = "comp" printboard(the_board) continue </code></pre>
0
2016-08-19T23:16:45Z
[ "python", "python-3.x", "indentation" ]
Python 3 IndentationError
39,048,844
<p>In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:</p> <pre><code>import random import copy import sys the_board = [" "]*10 def printboard(board): print(board[7] + " " + "|" + board[8] + " " + "|" + board[9]) print("--------") print(board[4] + " " + "|" + board[5] + " " + "|" + board[6]) print("--------") print(board[1] + " " + "|" + board[2] + " " + "|" + board[3]) def choose_player(): while True: player = input("What do you want to be; X or O?") if player == "X": print("You chose X") comp = "O" break elif player == "O": print("You chose O") comp = "X" break else: print("Invalid Selection") continue return [player, comp] def virtual_toss(): print("Tossing to see who goes first.....") x = random.randint(0,1) if x== 0: print("AI goes first") move = "comp" if x == 1: print("Human goes first") move = "hum" return move def win(board,le): if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le): return True else: return False def make_move(board,number,symbol): board[number] = symbol def board_full(board): count = 0 for item in board: if item in ["X","O"]: count+= 1 if count ==9 : return True else: return False def valid_move(board,num): if board[num] == " ": return True else: return False def player_move(board): number = int(input("Enter the number")) return number def copy_board(board): copied_board = copy.copy(board) return copied_board def check_corner(board): if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "): return True else: return False def check_center(board): if (board[5] == " "): return True else: return False while True: count = 0 loop_break = 0 print("welcome to TIC TAC TOE") pla,comp = choose_player() turn = virtual_toss() while True: printboard(the_board) if turn == "hum": if board_full() == True: again = input ("Game is a tie. Want to try again? Y for yes and N for No") if again == "Y": loop_break = 6 break else: system.exit() if loop_break == 6: continue while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break else: turn = "comp" printboard(the_board) continue else: if board_full() == True: again = input ("Game is a tie. Want to try again? Y for yes and N for No") if again == "Y": loop_break = 6 break else: system.exit() if loop_break = 6: continue copy_board(the_board) for i in range(0,9): make_move(copied_board,i,pla) if(win(copied_board,pla) == True): make_move(the_board,comp) turn = "hum" loop_break = 1 break else: continue if loop_break = 1: continue if (check_corner(the_board) == True) or (check_center(the_board)==True): for i in [7,9,1,3,5]: if(valid_move(copied_board,i)==True): make_move(copied_board,i,comp) if(win(copied_board,comp)==True): make_move(the_board,i,comp) print("The AI beat you") loop_break = 2 count = 1 break else: make_move(the_board,i,comp) turn = "hum" loop_break = 3 break if loop_break == 2: break elif loop_break == 3: continue else: for i in [8,4,6,2]: if(valid_move(copied_board,i)==True): make_move(copied_board,i,comp) if(win(copied_board,comp)): make_move(the_board,i,comp) print("The AI beat you") count = 1 loop_break = 4 break else: make_move(the_board,i,comp) turn = "hum" loop_break = 5 break if loop_break == 4: break elif loop_break == 5: continue if count == 1: again = input("Would you like to play again? y/n") if again == "y": continue else: system.exit() </code></pre> <p>I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:</p> <pre><code> Traceback (most recent call last): File "python", line 106 if (win(the_board,pla) == True): ^ IndentationError: unindent does not match any outer indentation level </code></pre> <p>More specifically, this part of the code:</p> <pre><code>while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break </code></pre> <p>Any help? I cannot get the code to work by any means!!</p>
-4
2016-08-19T23:12:42Z
39,048,885
<p>The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.</p> <pre><code>while True: number = player_move(the_board) if (valid_move(the_board,number) == True) and not(board_full == False): make_move(the_board,number,pla) break else: print("Invalid Move, try again!") continue if (win(the_board,pla) == True): print ("Yay, you won!!!") printboard(the_board) count = 1 break </code></pre>
0
2016-08-19T23:18:31Z
[ "python", "python-3.x", "indentation" ]
Combine value of two column pandas into one
39,048,864
<p>I have data, and have to use pandas for processing, this is example the code:</p> <pre><code>d = [ (1,70399,0.988375133622), (1,33919,0.981573492596), (1,62461,0.981426807114), (579,1,0.983018778374), (745,1,0.995580488899), (834,1,0.980942505189) ] df = pd.DataFrame(d, columns=['source', 'target', 'weight']) source_old = df.source.copy() &gt;&gt;&gt; source_old source_old 0 1 1 1 2 1 3 579 4 745 5 834 </code></pre> <p>but i need source_old contain <code>target</code> too, like:</p> <pre><code>0 1 1 1 2 1 3 579 4 745 5 834 6 33919 7 62461 8 70399 </code></pre> <p>how can i do that with pandas ? thx</p>
1
2016-08-19T23:15:13Z
39,048,981
<pre><code>df[['source', 'target']].T.stack() source 0 1 1 1 2 1 3 579 4 745 5 834 target 0 70399 1 33919 2 62461 3 1 4 1 5 1 dtype: int64 </code></pre> <hr> <p><strong><em>or</em></strong></p> <pre><code>pd.concat([df[col] for col in ['source', 'target']]) 0 1 1 1 2 1 3 579 4 745 5 834 0 70399 1 33919 2 62461 3 1 4 1 5 1 dtype: int64 </code></pre> <hr> <p><strong><em>or</em></strong></p> <p>to get precisely what you asked for</p> <pre><code>pd.concat([df['source'], df['target'].iloc[:3]], ignore_index=True) 0 1 1 1 2 1 3 579 4 745 5 834 6 70399 7 33919 8 62461 dtype: int64 </code></pre>
3
2016-08-19T23:31:23Z
[ "python", "pandas" ]
Combine value of two column pandas into one
39,048,864
<p>I have data, and have to use pandas for processing, this is example the code:</p> <pre><code>d = [ (1,70399,0.988375133622), (1,33919,0.981573492596), (1,62461,0.981426807114), (579,1,0.983018778374), (745,1,0.995580488899), (834,1,0.980942505189) ] df = pd.DataFrame(d, columns=['source', 'target', 'weight']) source_old = df.source.copy() &gt;&gt;&gt; source_old source_old 0 1 1 1 2 1 3 579 4 745 5 834 </code></pre> <p>but i need source_old contain <code>target</code> too, like:</p> <pre><code>0 1 1 1 2 1 3 579 4 745 5 834 6 33919 7 62461 8 70399 </code></pre> <p>how can i do that with pandas ? thx</p>
1
2016-08-19T23:15:13Z
39,049,003
<p>Try this <code>source_old = df.source.append(df.target)</code></p>
2
2016-08-19T23:33:57Z
[ "python", "pandas" ]
Combine value of two column pandas into one
39,048,864
<p>I have data, and have to use pandas for processing, this is example the code:</p> <pre><code>d = [ (1,70399,0.988375133622), (1,33919,0.981573492596), (1,62461,0.981426807114), (579,1,0.983018778374), (745,1,0.995580488899), (834,1,0.980942505189) ] df = pd.DataFrame(d, columns=['source', 'target', 'weight']) source_old = df.source.copy() &gt;&gt;&gt; source_old source_old 0 1 1 1 2 1 3 579 4 745 5 834 </code></pre> <p>but i need source_old contain <code>target</code> too, like:</p> <pre><code>0 1 1 1 2 1 3 579 4 745 5 834 6 33919 7 62461 8 70399 </code></pre> <p>how can i do that with pandas ? thx</p>
1
2016-08-19T23:15:13Z
39,049,326
<p>Try this: </p> <pre><code>pd.melt(df[['source', 'target']])['value'][:-3].sort_values() 0 1 1 1 2 1 3 579 4 745 5 834 7 33919 8 62461 6 70399 </code></pre> <p>Melt gives you this:</p> <pre><code>pd.melt(df[['source', 'target']]) variable value 0 source 1 1 source 1 2 source 1 3 source 579 4 source 745 5 source 834 6 target 70399 7 target 33919 8 target 62461 9 target 1 10 target 1 11 target 1 </code></pre>
1
2016-08-20T00:24:30Z
[ "python", "pandas" ]
Missing X and Y axis when plotting using python
39,048,865
<p>I having some issue replicating the example code for scatter plots in python. The code I am trying to replicate: </p> <pre><code>x = np.random.rand(10) y = np.random.rand(10) z = np.sqrt(x**2 + y**2) plt.subplot(321) plt.scatter(x, y, s=80, c=z, marker="&gt;") plt.subplot(322) plt.scatter(x, y, s=80, c=z, marker=(5, 0)) verts = list(zip([-1., 1., 1., -1.], [-1., -1., 1., -1.])) plt.subplot(323) plt.scatter(x, y, s=80, c=z, marker=(verts, 0)) # equivalent: #plt.scatter(x,y,s=80, c=z, marker=None, verts=verts) plt.subplot(324) plt.scatter(x, y, s=80, c=z, marker=(5, 1)) plt.subplot(325) plt.scatter(x, y, s=80, c=z, marker='+') plt.subplot(326) plt.scatter(x, y, s=80, c=z, marker=(5, 2)) plt.show() </code></pre> <p>What I am expecting: <a href="http://i.stack.imgur.com/1I2Yd.png" rel="nofollow"><img src="http://i.stack.imgur.com/1I2Yd.png" alt="enter image description here"></a></p> <p>But this is what I am getting: <a href="http://i.stack.imgur.com/1Hbyy.png" rel="nofollow"><img src="http://i.stack.imgur.com/1Hbyy.png" alt="enter image description here"></a></p> <p>I can get the background to white by:</p> <pre><code>ax = plt.gca() ax.set_axis_bgcolor('white') </code></pre> <p>But I can not get to display X and Y axis. I have tried many solutions from other stackoverflow posts but none of them seems to be working. </p> <p>Could someone please help me solve this issue?</p>
0
2016-08-19T23:15:15Z
39,049,059
<p>It seems that you are using ggplot style. You can change the default style:</p> <pre><code>pl.style.use("ggplot") pl.rcParams['axes.edgecolor'] = "#777777" pl.rcParams['axes.facecolor'] = '#FFFFFF' </code></pre> <p>Here is the result:</p> <p><a href="http://i.stack.imgur.com/okW0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/okW0B.png" alt="enter image description here"></a></p>
1
2016-08-19T23:42:05Z
[ "python", "matplotlib" ]
Missing X and Y axis when plotting using python
39,048,865
<p>I having some issue replicating the example code for scatter plots in python. The code I am trying to replicate: </p> <pre><code>x = np.random.rand(10) y = np.random.rand(10) z = np.sqrt(x**2 + y**2) plt.subplot(321) plt.scatter(x, y, s=80, c=z, marker="&gt;") plt.subplot(322) plt.scatter(x, y, s=80, c=z, marker=(5, 0)) verts = list(zip([-1., 1., 1., -1.], [-1., -1., 1., -1.])) plt.subplot(323) plt.scatter(x, y, s=80, c=z, marker=(verts, 0)) # equivalent: #plt.scatter(x,y,s=80, c=z, marker=None, verts=verts) plt.subplot(324) plt.scatter(x, y, s=80, c=z, marker=(5, 1)) plt.subplot(325) plt.scatter(x, y, s=80, c=z, marker='+') plt.subplot(326) plt.scatter(x, y, s=80, c=z, marker=(5, 2)) plt.show() </code></pre> <p>What I am expecting: <a href="http://i.stack.imgur.com/1I2Yd.png" rel="nofollow"><img src="http://i.stack.imgur.com/1I2Yd.png" alt="enter image description here"></a></p> <p>But this is what I am getting: <a href="http://i.stack.imgur.com/1Hbyy.png" rel="nofollow"><img src="http://i.stack.imgur.com/1Hbyy.png" alt="enter image description here"></a></p> <p>I can get the background to white by:</p> <pre><code>ax = plt.gca() ax.set_axis_bgcolor('white') </code></pre> <p>But I can not get to display X and Y axis. I have tried many solutions from other stackoverflow posts but none of them seems to be working. </p> <p>Could someone please help me solve this issue?</p>
0
2016-08-19T23:15:15Z
39,051,183
<p>Thanks to @HYRY's solution. </p> <p>Some more references about style sheets in matplotlib for beginners like me:</p> <ol> <li><p><a href="http://matplotlib.org/users/style_sheets.html" rel="nofollow">Customizing plots with style sheets</a></p> <ul> <li>Defining your own style</li> <li>Composing styles</li> <li>Temporary styling</li> </ul></li> <li><p><a href="https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html" rel="nofollow">Matplotlib Style Gallery</a></p></li> </ol> <p><a href="http://i.stack.imgur.com/JZoMM.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/JZoMM.jpg" alt="enter image description here"></a></p>
0
2016-08-20T06:29:23Z
[ "python", "matplotlib" ]
Selenium Error (Django): http.client.BadStatusLine: ''
39,048,912
<p>When I try to run my functional tests, I get: <code>selenium http.client.BadStatusLine: ''</code> (full error below). The tests start to run, the first one returns an error, than it gets hung up and I have to manually interrupt. (The first error is an expected error, so don't worry about that.)</p> <p>This was working perfectly last night; I don't know what happened.</p> <p>I tried upgrading Selenium (said I already had the most recent), and I upgraded Firefox. Didn't make a difference.</p> <p>Any ideas?</p> <pre><code>Creating test database for alias 'default'... E^CE ====================================================================== ERROR: test_menu_displays (functional_tests.tests.EditorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/larapsodia/dict/dev/functional_tests/tests.py", line 52, in test_menu_displays quickadd_button_text = self.browser.find_element_by_id('id_quickadd').text File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 269, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element 'value': value})['value'] File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"id_quickadd"} Stacktrace: at FirefoxDriver.findElementInternal_ (file:///tmp/tmplqx8mg0p/extensions/fxdriver@googlecode.com/components/driver-component.js:10770) at fxdriver.Timer.setTimeout/&lt;.notify (file:///tmp/tmplqx8mg0p/extensions/fxdriver@googlecode.com/components/driver-component.js:625) ====================================================================== ERROR: test_page_displays (functional_tests.tests.EditorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/larapsodia/dict/dev/functional_tests/tests.py", line 32, in test_page_displays self.browser.get(EDITOR_DEV_SITE_URL) File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 248, in get self.execute(Command.GET, {'url': url}) File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/webdriver.py", line 234, in execute response = self.command_executor.execute(driver_command, params) File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/remote_connection.py", line 401, in exe cute return self._request(command_info[0], url, body=data) File "/home/larapsodia/.virtualenvs/django18/lib/python3.4/site-packages/selenium/webdriver/remote/remote_connection.py", line 433, in _re quest resp = self._conn.getresponse() File "/usr/lib/python3.4/http/client.py", line 1171, in getresponse response.begin() File "/usr/lib/python3.4/http/client.py", line 351, in begin version, status, reason = self._read_status() File "/usr/lib/python3.4/http/client.py", line 321, in _read_status raise BadStatusLine(line) http.client.BadStatusLine: '' </code></pre>
0
2016-08-19T23:22:37Z
39,055,262
<p>I still don't know what happened, but this morning it's working again. I didn't change any code or anything.</p> <p>Weird Selenium.</p>
0
2016-08-20T14:34:30Z
[ "python", "django", "selenium", "firefox", "pythonanywhere" ]
Failure to return variable after series of functions in Python
39,048,921
<p>I am trying to return a variable ('brand') which is manipulated through a series of functions. If I go through the first function (brandSelector) which find an intersection between the variable and array the variable is returned. However, if the secondary sub route is chosen in the event that the first fails then the variable arrives at brandDetectionFailure(), however it is not returned the start (Main() Function). I have tried using 'global brand' but it did not work. I would appreciate any suggestions on forcing the variable to be returned to the start, rather than receiving None when printing back at the main function.</p> <p>Note for flow control from main program: Returns here after following brandSelector() --> brandDetectionFailure() (from exception handler) --> defineBrand()</p> <pre><code>#Import Modules import sys, warnings, string #Define Globals brands = ["apple", "android", "windows"] brand = None def init(): #Define #warnings.filterwarnings("ignore") #Disable for debuggings #Main Menu print("--Welcome to Troubleshooting Applet--") print("In your query please include the brand of your device and the problem / symptom of your current issue. \n") def Main(): init() query = input("Enter your query: ").lower() brand = brandSelector(query) #Returns here after following brandSelector --&gt; brandDetectionFailure (from exception handler) --&gt; defineBrand print(brand) #secondaryMain(query) print("END") def secondaryMain(query): #Push required variables to next stage print(query) ##START Brand Selection Route def brandSelector(query): try: #Format Brands Query brand = set(brands).intersection(query.split()) brand = ', '.join(brand) #Check Condition After Setting int_cond = confirmIntersection(brand) if int_cond == False: raise NameError("No Intersection") #brandDetectionFailure() return brand except NameError: print("\nNo Intersection found between query defined brand and brands array\n") brandDetectionFailure() def confirmIntersection(brand): if brand in brands: return True else: return False ##END Brand Selection Route ##START Brand Selection Route | SUB: Failed Selection def brandDetectionFailure(): print("-Brand could not be found-") print("Query still stored for your issue") if userConfirm("Would you like to redefine a brand and continue?"): defineBrand() else: end() def defineBrand(): brand = input("Enter your device's brand: ") int_cond = confirmIntersection(brand) if int_cond == False: if userConfirm("Try again?"): defineBrand() else: end() else: print("End of Sub Route") #STILL NEEDS WORK return brand ##END Brand Selection Route | SUB: Failed Selection ##START Generic Functions def userConfirm(question): reply = str(input(question+' (y/n): ')).lower().strip() if reply[0] == 'y': return True if reply[0] == 'n': return False else: return userConfirm("Please confirm using yes or no") def end(): print("Have a good day. Bye.") sys.exit() ##END Generic Functions if __name__ == '__main__': Main() </code></pre> <p>Thanks,</p> <p>Sam</p>
0
2016-08-19T23:24:18Z
39,049,112
<p>With thanks to Barmar (<a href="http://stackoverflow.com/users/1491895/barmar">http://stackoverflow.com/users/1491895/barmar</a>),</p> <p>I followed his solution of:</p> <p>"brandDetectionFailure doesn't have a return statement. And your except block in brandSelector doesn't have a return statement. So nothing gets returned in that case."</p> <p>followed by a clarification of</p> <p>"It should be return brandDetectionFailure(). And brandDetectionFailure needs to have return defineBrand()."</p> <p>In summary, "Every function needs to return something."</p>
0
2016-08-19T23:48:28Z
[ "python", "function", "variables", "return-value" ]
Basic PyCharm questions
39,048,934
<p>I have a seemingly simple task to do. Run this ( print('Hello World') ) line of code in PyCharm. No, I'm serious. I wont bother complaining about what I've tried or how much I've coded in the past (spoiler alert, a lot) because I just want to get it running. The online tutorial wants me to do some kind of project structure thing before I can even start, which didn't even work to begin with. I really just want to be able to run code from a file, so if anyone who's figured it out can tell me in a</p> <p>" Do this</p> <p>then this</p> <p>finally this "</p> <p>type format that would be wonderful, because I cant even run a single line from a file.</p>
0
2016-08-19T23:26:05Z
39,049,021
<p>I did this:</p> <p>Create folder wherever you want your file to be</p> <p>Open this folder in pycharm as your project (if you have a project open, close it and open this folder as your new project)</p> <p>Open <code>Project</code> tab on the left</p> <p>Right click your folder -> New -> Python File -> Create <code>hello.py</code> with <code>print 'Hello World'</code> as contents</p> <p>From the top menus, go to <code>Run</code>-> from the drop-down click <code>Run</code></p> <p>Click <code>hello</code> so it knows to run that.</p> <p>If you don't want to deal with the <code>Run</code> stuff you can always invoke your script from the command line with <code>python hello.py</code>.</p> <p>Hello World! should appear in your console!</p>
0
2016-08-19T23:35:53Z
[ "python", "pycharm" ]
Basic PyCharm questions
39,048,934
<p>I have a seemingly simple task to do. Run this ( print('Hello World') ) line of code in PyCharm. No, I'm serious. I wont bother complaining about what I've tried or how much I've coded in the past (spoiler alert, a lot) because I just want to get it running. The online tutorial wants me to do some kind of project structure thing before I can even start, which didn't even work to begin with. I really just want to be able to run code from a file, so if anyone who's figured it out can tell me in a</p> <p>" Do this</p> <p>then this</p> <p>finally this "</p> <p>type format that would be wonderful, because I cant even run a single line from a file.</p>
0
2016-08-19T23:26:05Z
39,049,040
<p>Well it's really simple, if you used any code editor in the past you probably will understand what i'm doing here:</p> <p>File >> New >> Python File >> "name of the file" >> Create.</p> <p>To run the code simply click the play icon which is run 'project'. Then the output should appear in a console.</p>
1
2016-08-19T23:38:45Z
[ "python", "pycharm" ]
Tensorflow: How to write op with gradient in python?
39,048,984
<p>I would like to write a TensorFlow op in python, but I would like it to be differentiable (to be able to compute a gradient).</p> <p>This question asks how to write an op in python, and the answer suggests using py_func (which has no gradient): <a href="http://stackoverflow.com/questions/37924071/tensorflow-writing-an-op-in-python">Tensorflow: Writing an Op in Python</a></p> <p>The TF documentation describes how to add an op starting from C++ code only: <a href="https://www.tensorflow.org/versions/r0.10/how_tos/adding_an_op/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/adding_an_op/index.html</a></p> <p>In my case, I am prototyping so I don't care about whether it runs on GPU, and I don't care about it being usable from anything other than the TF python API.</p>
1
2016-08-19T23:31:33Z
39,049,106
<p>Here's an example of adding gradient to a specific <code>py_func</code> <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342</a></p> <p>Here's the issue <a href="https://github.com/tensorflow/tensorflow/issues/1095#issuecomment-239406220" rel="nofollow">discussion</a></p>
0
2016-08-19T23:47:26Z
[ "python", "neural-network", "tensorflow" ]
Tensorflow: How to write op with gradient in python?
39,048,984
<p>I would like to write a TensorFlow op in python, but I would like it to be differentiable (to be able to compute a gradient).</p> <p>This question asks how to write an op in python, and the answer suggests using py_func (which has no gradient): <a href="http://stackoverflow.com/questions/37924071/tensorflow-writing-an-op-in-python">Tensorflow: Writing an Op in Python</a></p> <p>The TF documentation describes how to add an op starting from C++ code only: <a href="https://www.tensorflow.org/versions/r0.10/how_tos/adding_an_op/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/adding_an_op/index.html</a></p> <p>In my case, I am prototyping so I don't care about whether it runs on GPU, and I don't care about it being usable from anything other than the TF python API.</p>
1
2016-08-19T23:31:33Z
39,984,513
<p>Yes, as mentionned in @Yaroslav's answer, it is possible and the key is the links he references: <a href="https://github.com/tensorflow/tensorflow/issues/1095" rel="nofollow">here</a> and <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">here</a>. I want to elaborate on this answer by giving a concret example. </p> <p><strong>Modulo opperation:</strong> Let's implement the element-wise modulo operation in tensorflow (it already exists but its gradient is not defined, but for the example we will implement it from scratch). </p> <p><strong>Numpy function:</strong> The first step is to define the opperation we want for numpy arrays. The element-wise modulo opperation is already implemented in numpy so it is easy:</p> <pre><code>import numpy as np def np_mod(x,y): return (x % y).astype(np.float32) </code></pre> <p>The reason for the <code>.astype(np.float32)</code> is because by default tensorflow takes float32 types and if you give it float64 (the numpy default) it will complain. </p> <p><strong>Gradient Function:</strong> Next we need to define the gradient function for our opperation for each input of the opperation as tensorflow function. The function needs to take a very specific form. It need to take the tensorflow representation of the opperation <code>op</code> and the gradient of the output <code>grad</code> and say how to propagate the gradients. In our case, the gradients of the <code>mod</code> opperation are easy, the derivative is 1 with respect to the first argument and 0 (almost everywhere, and infinite at a finite number of spots, but let's ignore that) with respect to the second argument. So we have</p> <pre><code>def modgrad(op, grad): x = op.inputs[0] # the first argument (normally you need those to calculate the gradient, like the gradient of x^2 is 2x. ) y = op.inputs[1] # the second argument return grad * 1, grad * 0 #the propagated gradient with respect to the first and second argument respectively </code></pre> <p>The grad function needs to return an n-tuple where n is the number of arguments of the operation. Notice that we need to return tensorflow functions of the input.</p> <p><strong>Making a TF function with gradients:</strong> As explained in the sources mentioned above, there is a hack to define gradients of a function using <code>tf.RegisterGradient</code> <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#RegisterGradient" rel="nofollow">[doc]</a> and <code>tf.Graph.gradient_override_map</code> <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html" rel="nofollow">[doc]</a>. </p> <p>Copying the code from <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">harpone</a> we can modify the <code>tf.py_func</code> function to make it define the gradient at the same time: import tensorflow as tf</p> <pre><code>def py_func(func, inp, Tout, stateful=True, name=None, grad=None): # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) # see _MySquareGrad for grad example g = tf.get_default_graph() with g.gradient_override_map({"PyFunc": rnd_name}): return tf.py_func(func, inp, Tout, stateful=stateful, name=name) </code></pre> <p>The <code>stateful</code> option is to tell tensorflow whether the function always gives the same output for the same input (stateful = False) in which case tensorflow can simply the tensorflow graph, this is our case and will probably be the case in most situations.</p> <p><strong>Combining it all together:</strong> Now that we have all the pieces, we can combine them all together:</p> <pre><code>from tensorflow.python.framework import ops def tf_mod(x,y, name=None): with ops.op_scope([x,y], name, "mod") as name: z = py_func(np_mod, [x,y], [tf.float32], name=name, grad=modgrad) # &lt;-- here's the call to the gradient return z[0] </code></pre> <p><code>tf.py_func</code> acts on lists of tensors (and returns a list of tensors), that is why we have <code>[x,y]</code> (and return <code>z[0]</code>). And now we are done. And we can test it.</p> <p><strong>Test:</strong></p> <pre><code>with tf.Session() as sess: x = tf.constant([0.3,0.7,1.2,1.7]) y = tf.constant([0.2,0.5,1.0,2.9]) z = tf_mod(x,y) gr = tf.gradients(z, [x,y]) tf.initialize_all_variables().run() print(x.eval(), y.eval(),z.eval(), gr[0].eval(), gr[1].eval()) </code></pre> <blockquote> <p>[ 0.30000001 0.69999999 1.20000005 1.70000005] [ 0.2 0.5 1. 2.9000001] [ 0.10000001 0.19999999 0.20000005 1.70000005] [ 1. 1. 1. 1.] [ 0. 0. 0. 0.]</p> </blockquote> <p><strong>Success!</strong></p>
1
2016-10-11T18:46:32Z
[ "python", "neural-network", "tensorflow" ]
python :: iterate through nested JSON results
39,048,994
<p>iterating through <code>JSON</code> <code>results</code> can get quite confusing at times. say I have a <code>function</code>like so:</p> <pre><code>def get_playlist_owner_ids(query): results = sp.search(q=query, type='playlist') id_ = results['playlists']['items'][0]['owner']['id'] return (id_) </code></pre> <p>I can fetch the <code>id_</code>, it works.</p> <p>but how do I iterate using a <code>for i in x</code> loop so I <code>return</code> ALL <code>ids_</code>?</p>
3
2016-08-19T23:32:31Z
39,049,019
<pre><code>results['playlists']['items'][0]['owner']['id'] ^___ this is a list index </code></pre> <p>Thus:</p> <pre><code>for item in results['playlists']['items']: print(item['owner']['id']) </code></pre> <p>It is often convenient to make intermediate variables in order to keep things more readable.</p> <pre><code>playlist_items = results['playlists']['items'] for item in playlist_items: owner = item['owner'] print(owner['id']) </code></pre> <p>This is assuming I have correctly guessed the structure of your object based on only what you have shown. Hopefully, though, these examples give you some better ways of thinking about splitting up complex structures into meaningful chunks.</p>
1
2016-08-19T23:35:46Z
[ "python", "json", "loops", "iteration" ]
python :: iterate through nested JSON results
39,048,994
<p>iterating through <code>JSON</code> <code>results</code> can get quite confusing at times. say I have a <code>function</code>like so:</p> <pre><code>def get_playlist_owner_ids(query): results = sp.search(q=query, type='playlist') id_ = results['playlists']['items'][0]['owner']['id'] return (id_) </code></pre> <p>I can fetch the <code>id_</code>, it works.</p> <p>but how do I iterate using a <code>for i in x</code> loop so I <code>return</code> ALL <code>ids_</code>?</p>
3
2016-08-19T23:32:31Z
39,049,025
<p>How about this? You can use generator to achieve your goal</p> <pre><code>def get_playlist_owner_ids(query): results = sp.search(q=query, type='playlist') for item in results['playlists']['items']: yield item['owner']['id'] </code></pre>
0
2016-08-19T23:36:16Z
[ "python", "json", "loops", "iteration" ]
python :: iterate through nested JSON results
39,048,994
<p>iterating through <code>JSON</code> <code>results</code> can get quite confusing at times. say I have a <code>function</code>like so:</p> <pre><code>def get_playlist_owner_ids(query): results = sp.search(q=query, type='playlist') id_ = results['playlists']['items'][0]['owner']['id'] return (id_) </code></pre> <p>I can fetch the <code>id_</code>, it works.</p> <p>but how do I iterate using a <code>for i in x</code> loop so I <code>return</code> ALL <code>ids_</code>?</p>
3
2016-08-19T23:32:31Z
39,049,026
<p>You could iterate over <code>results['playlists']['items']</code>, or, better yet, use list comprehension:</p> <pre><code>def get_playlist_owner_ids(query): results = sp.search(q=query, type='playlist') return [x['owner']['id'] for x in results['playlists']['items']] </code></pre>
0
2016-08-19T23:36:19Z
[ "python", "json", "loops", "iteration" ]
python :: iterate through nested JSON results
39,048,994
<p>iterating through <code>JSON</code> <code>results</code> can get quite confusing at times. say I have a <code>function</code>like so:</p> <pre><code>def get_playlist_owner_ids(query): results = sp.search(q=query, type='playlist') id_ = results['playlists']['items'][0]['owner']['id'] return (id_) </code></pre> <p>I can fetch the <code>id_</code>, it works.</p> <p>but how do I iterate using a <code>for i in x</code> loop so I <code>return</code> ALL <code>ids_</code>?</p>
3
2016-08-19T23:32:31Z
39,049,039
<p>In practice your document is something like this:</p> <pre><code>{ "playlists": { "items":[ {"owner":{"id":"1"},...}, {"owner":{"id":"2"},...}, {"owner":{"id":"3"},...}, ..., } </code></pre> <p>So you have to loop over the list of items. </p> <p>You can do something like this</p> <pre><code>ids = [] items = results['playlists']['items'] for item in items: ids.append(item['owner']['id']) return ids </code></pre> <p>Or if you want to a one line:</p> <pre><code>ids = [item['owner']['id'] for owner in results['playlists']['items']] </code></pre>
0
2016-08-19T23:38:35Z
[ "python", "json", "loops", "iteration" ]
What is the logic behind needing to convert a 1D array to 2D to concatenate?
39,049,028
<p>In order to concatenate a 1D array to a 2D array, the following fix is suggested:</p> <pre><code>A = np.array([1, 2, 3]) B = np.array([[4, 5],[6,7],[8,9]]) # np.hstack((A,B)) # throws "ValueError: all the input arrays must have same number of dimensions" np.hstack((A[:, None],B)) #works </code></pre> <p>Could someone please explain the logic behind this? (with link?)</p> <p>Coming from a matlab background, this requirement is unintuitive.</p> <p>Thanks!</p>
1
2016-08-19T23:37:00Z
39,049,108
<p>The document of <code>hstack()</code>:</p> <blockquote> <p>numpy.hstack(tup)[source] Stack arrays in sequence horizontally (column wise).</p> <p>Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by hsplit.</p> <p>Parameters: tup : sequence of ndarrays All arrays must have the same shape along all but the second axis. Returns: stacked : ndarray The array formed by stacking the given arrays.</p> </blockquote> <p><strong>sequence of ndarrays All arrays must have the same shape along all but the second axis.</strong></p> <p><code>A[:, None]</code> creates a new array with shape <code>(3, 1)</code>, it's a 2D array as <code>B</code>, so <code>hstack()</code> works.</p> <p>You can use instead:</p> <pre><code>np.c_[A, B] np.column_stack((A, B)) </code></pre>
1
2016-08-19T23:47:33Z
[ "python", "arrays", "numpy", "concatenation" ]
What is the logic behind needing to convert a 1D array to 2D to concatenate?
39,049,028
<p>In order to concatenate a 1D array to a 2D array, the following fix is suggested:</p> <pre><code>A = np.array([1, 2, 3]) B = np.array([[4, 5],[6,7],[8,9]]) # np.hstack((A,B)) # throws "ValueError: all the input arrays must have same number of dimensions" np.hstack((A[:, None],B)) #works </code></pre> <p>Could someone please explain the logic behind this? (with link?)</p> <p>Coming from a matlab background, this requirement is unintuitive.</p> <p>Thanks!</p>
1
2016-08-19T23:37:00Z
39,049,325
<p>Look at these arrays:</p> <pre><code>In [26]: A Out[26]: array([1, 2, 3]) In [27]: B Out[27]: array([[4, 5], [6, 7], [8, 9]]) In [28]: A[:,None] Out[28]: array([[1], [2], [3]]) In [31]: np.concatenate([A[:,None],B],axis=1) Out[31]: array([[1, 4, 5], [2, 6, 7], [3, 8, 9]]) </code></pre> <p>Doesn't it make sense that if you want to join the 3 items of <code>A</code> to the 3 rows of <code>B</code>, that <code>A</code> should also have 3 rows?</p> <p>The big difference between <code>numpy</code> and MATLAB is that in MATLAB everything is 2d (or higher). In numpy arrays may be 1d, and the difference maters.</p> <p>Octave comparison:</p> <pre><code>&gt;&gt; A=[1,2,3] A = 1 2 3 &gt;&gt; B=[4,5;6,7;8,9] B = 4 5 6 7 8 9 </code></pre> <p>The (1,3) cannot be joined with the (3,2) matrix in either direction:</p> <pre><code>&gt;&gt; cat(1,A,B) error: cat: dimension mismatch &gt;&gt; cat(2,A,B) error: cat: dimension mismatch </code></pre> <p>But it works if I transpose <code>A</code>:</p> <pre><code>&gt;&gt; cat(2,A.',B) ans = 1 4 5 2 6 7 3 8 9 </code></pre> <p>So even with the 2d baseline, dimensions still need to line up.</p> <p>All <code>hstack</code> adds to <code>concatenate</code> is <code>atleast_1d</code>, which doesn't help in this case. <code>np.column_stack</code> makes it 2d and .T, so it works. I recommend looking at the underlying code for functions like <code>hstack</code> and <code>column_stack</code> (you may already have the habit from MATLAB).</p> <p>==================</p> <p>You comment about the difference between <code>hstack</code> and <code>column_stack</code>. They don't have special restrictions, rather they just do different things to adjust the dimensions of their inputs. Neither is doing anything deep or mysterious.</p> <pre><code>def hstack(tup): arrs = [np.atleast_1d(m) for m in tup] return np.concatenate(arrs, 0) # used when A is first # return np.concatenate(arrs, 1) # used when B is first </code></pre> <p>Since both arrays are atleast 1d, the first step adds nothing. So it's just a matter of trying to do</p> <pre><code>np.concatenate((A,B), axis=0) # or axis=1 </code></pre> <p>In either case trying to concatenate a (3,) array to a (3,2) doesn't work - one is 1d, the other 2d. A (3,1) with a (3,2) does work if you want a (3,3).</p> <pre><code>def column_stack(tup): arrays = [] for v in tup: # arr = array(v, copy=False, subok=True) # already arrays if arr.ndim &lt; 2: arr = np.array(arr, copy=False, subok=True, ndmin=2).T arrays.append(arr) return np.concatenate(arrays, 1) </code></pre> <p>In this case <code>A.ndim&lt;2</code>; the <code>array</code> step turns <code>A</code> into a (1,3), and the <code>T</code> changes it to (3,1). That's the same as doing <code>A[:,None]</code>.</p> <p>So it's <code>np.concatenate</code> that's imposing the constraints - matching <code>ndim</code>, and matching size on the relevant dimension. The <code>stack</code> functions are just convenience tools, and don't do anything that you can't do directly.</p>
1
2016-08-20T00:24:29Z
[ "python", "arrays", "numpy", "concatenation" ]
What is the logic behind needing to convert a 1D array to 2D to concatenate?
39,049,028
<p>In order to concatenate a 1D array to a 2D array, the following fix is suggested:</p> <pre><code>A = np.array([1, 2, 3]) B = np.array([[4, 5],[6,7],[8,9]]) # np.hstack((A,B)) # throws "ValueError: all the input arrays must have same number of dimensions" np.hstack((A[:, None],B)) #works </code></pre> <p>Could someone please explain the logic behind this? (with link?)</p> <p>Coming from a matlab background, this requirement is unintuitive.</p> <p>Thanks!</p>
1
2016-08-19T23:37:00Z
39,050,328
<p>I think the reason for this difference between numpy and MATLAB is a difference in philosophy and design.</p> <p>The numpy package is designed with a focus more towards integrating with the python programming language and dealing with standard types of variables that are found in the python programming language. MATLAB, on the other hand, is designed around matrices.</p> <p>The basic type of data in MATLAB is the matrix, so that even what looks like a floating point number is really a 1 x 1 matrix. You can see evidence <a href="http://www.mathworks.com/help/matlab/math/empty-matrices-scalars-and-vectors.html?requestedDomain=www.mathworks.com" rel="nofollow">here</a> that MATLAB is designed with the matrix as its foundational type. </p> <p>In numpy, however, the arrays that are used are closer cousins to single-dimensional and multidimensional arrays in the python programming language. So numpy provides relatively generic methods like <code>concatenate</code> and <code>split</code> that support an argument defining which axis of a multidimensional array they should operate on. In recent enough versions (since 1.10), there is also the <code>stack</code> method that can add a dimension as it concatenates. The page <a href="http://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html" rel="nofollow">here</a> is the reference for a variety of array manipulation methods in version 1.11, including the three I've mentioned and the <code>hstack</code> and <code>column_stack</code> methods.</p> <p>By the way, there are other ways to get the same result matrix. Two possibilities that might appeal a little more to MATLAB users are</p> <pre><code>np.hstack((np.atleast_2d(A).T, B)) </code></pre> <p>and</p> <pre><code>np.hstack((A.reshape([A.size,1]), B)) </code></pre> <p>Also, it is technically possible to extract the columns from <code>B</code> as 1-dimensional arrays and build the matrix you want to build by stacking together 1-D arrays. With older versions of numpy, combining the 1-D arrays into a matrix uses <code>vstack</code> and a transpose. It could look like this</p> <pre><code>np.vstack([A] + [B[:,j] for j in xrange(B.shape[1])]).T </code></pre> <p>or, if you want to use more numpy array manipulation commands instead of slicing, it could be written</p> <pre><code>np.vstack([A] + [np.squeeze(c) for c in np.hsplit(B, B.shape[1])]).T </code></pre>
0
2016-08-20T03:56:50Z
[ "python", "arrays", "numpy", "concatenation" ]
GtkInfoBar doesn't show again after hide
39,049,060
<p>I'm hide Gtk widget, then try to show it, but none of the methods "show()", "show_all()" or "show_now()" does't work. If not call "hide()" widget shows.</p> <pre><code>python 3.5.2 gtk3 3.20.8 pygobject-devel 3.20.1 </code></pre> <p>test.py:</p> <pre><code>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk builder = Gtk.Builder() builder.add_from_file("gui.glade") infoBar = builder.get_object("infoBar") window = builder.get_object("window") window.show_all() infoBar.hide() infoBar.show() Gtk.main() </code></pre> <p>gui.glade: <a href="http://pastebin.com/xKFt1v84" rel="nofollow">http://pastebin.com/xKFt1v84</a></p>
2
2016-08-19T23:42:17Z
39,050,142
<p><a href="https://bugzilla.gnome.org/show_bug.cgi?id=710888" rel="nofollow">This is a long-standing bug in GTK+ specific to GtkInfoBar. Monitor the linked bug report for more details, some workarounds (including one in Python that you can use for the time being) and to find out when it's fixed for real.</a></p>
3
2016-08-20T03:21:40Z
[ "python", "gtk", "glade", "pygobject" ]
python: update dataframe to existing excel sheet without overwriting contents on the same sheet and other sheets
39,049,148
<p>Struggling for this for hours so I decided to ask for help from experts here:</p> <p>I want to modify existing excel sheet without overwriting content. I have other sheets in this excel file and I don't want to impact other sheets.</p> <p>I've created sample code, not sure how to add the second sheet that I want to keep though.</p> <pre><code>t=pd.date_range('2004-01-31', freq='M', periods=4) first=pd.DataFrame({'A':[1,1,1,1], 'B':[2,2,2,2]}, index=t) first.index=first.index.strftime('%Y-%m-%d') writer=pd.ExcelWriter('test.xlsx') first.to_excel(writer, sheet_name='Here') first.to_excel(writer, sheet_name='Keep') #how to update the sheet'Here', cell A5:C6 with following without overwriting the rest? #I want to keep the sheet "Keep" update=pd.DataFrame({'A':[3,4], 'B':[4,5]}, index=pd.date_range('2004-04-30', periods=2, freq='M')) </code></pre> <p>I've researched SO. But not sure how to write a dataframe into the sheet.</p> <p>Example I've tried:</p> <pre><code>import openpyxl xfile = openpyxl.load_workbook('test.xlsx') sheet = xfile.get_sheet_by_name('test') sheet['B5']='wrote!!' xfile.save('test2.xlsx') </code></pre>
0
2016-08-19T23:53:01Z
39,077,347
<p>I'd suggest you update to the 2.4 (either the beta or a checkout) of openpyxl and use the built in support fro dataframes. These can now easily be converted by openypxl into rows that you do what you want with.</p> <p>See <a href="http://openpyxl.readthedocs.io/en/latest/pandas.html" rel="nofollow">http://openpyxl.readthedocs.io/en/latest/pandas.html</a> for details.</p>
0
2016-08-22T10:37:03Z
[ "python", "pandas", "openpyxl", "xlrd" ]
python: update dataframe to existing excel sheet without overwriting contents on the same sheet and other sheets
39,049,148
<p>Struggling for this for hours so I decided to ask for help from experts here:</p> <p>I want to modify existing excel sheet without overwriting content. I have other sheets in this excel file and I don't want to impact other sheets.</p> <p>I've created sample code, not sure how to add the second sheet that I want to keep though.</p> <pre><code>t=pd.date_range('2004-01-31', freq='M', periods=4) first=pd.DataFrame({'A':[1,1,1,1], 'B':[2,2,2,2]}, index=t) first.index=first.index.strftime('%Y-%m-%d') writer=pd.ExcelWriter('test.xlsx') first.to_excel(writer, sheet_name='Here') first.to_excel(writer, sheet_name='Keep') #how to update the sheet'Here', cell A5:C6 with following without overwriting the rest? #I want to keep the sheet "Keep" update=pd.DataFrame({'A':[3,4], 'B':[4,5]}, index=pd.date_range('2004-04-30', periods=2, freq='M')) </code></pre> <p>I've researched SO. But not sure how to write a dataframe into the sheet.</p> <p>Example I've tried:</p> <pre><code>import openpyxl xfile = openpyxl.load_workbook('test.xlsx') sheet = xfile.get_sheet_by_name('test') sheet['B5']='wrote!!' xfile.save('test2.xlsx') </code></pre>
0
2016-08-19T23:53:01Z
39,086,153
<p>Figured it out by myself:</p> <pre><code>#Prepare the excel we want to write to t=pd.date_range('2004-01-31', freq='M', periods=4) first=pd.DataFrame({'A':[1,1,1,1], 'B':[2,2,2,2]}, index=t) first.index=first.index.strftime('%Y-%m-%d') writer=pd.ExcelWriter('test.xlsx') first.to_excel(writer, sheet_name='Here') first.to_excel(writer, sheet_name='Keep') #read the existing sheets so that openpyxl won't create a new one later book = load_workbook('test.xlsx') writer = pandas.ExcelWriter('test.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) #update without overwrites update=pd.DataFrame({'A':[3,4], 'B':[4,5]}, index=(pd.date_range('2004-04-30', periods=2, freq='M').strftime('%Y-%m-%d'))) update.to_excel(writer, "Here", startrow=1, startcol=2) writer.save() </code></pre>
1
2016-08-22T18:14:43Z
[ "python", "pandas", "openpyxl", "xlrd" ]
Iterating and averaging pandas data frame
39,049,202
<p>I have a database with a lot of rows such as:</p> <pre><code>timestamp name price profit bob 5 4 jim 3 2 jim 2 6 bob 6 7 jim 4 1 jim 6 3 bob 3 1 </code></pre> <p>The data base is sorted by a timestamp. I would like to be able to add a new column where it would take the last 2 values in the price column before the current value and average them into a new column. So that the first three rows would look something like this with a new column:</p> <pre><code>timestamp name price profit new column bob 5 4 4.5 jim 3 2 3 jim 2 6 5 (6+3)/2 = 4.5 (2+4)/2 = 3 (4+6)/2 = 5 </code></pre> <p>This isn't for a school project or anything this is just something I'm working on on my own. I've tried asking a similar question to this but I don't think I was very clear. Thanks in advance!</p>
2
2016-08-20T00:03:11Z
39,049,640
<p>By looking at the result you want, I'm guess you want average of the two prices following the current one instead of "2 values in the price column before the current value".</p> <p>I made up <code>timestamp</code> values that you omitted to be clear.</p> <pre><code>print df timestamp name price profit 0 2016-01-01 bob 5 4 1 2016-01-02 jim 3 2 2 2016-01-03 jim 2 6 3 2016-01-04 bob 6 7 4 2016-01-05 jim 4 1 5 2016-01-06 jim 6 3 6 2016-01-07 bob 3 1 #No need to sort if you already did. #df.sort_values(['name','timestamp'], inplace=True) df['new column'] = (df.groupby('name')['price'].shift(-1) + df.groupby('name')['price'].shift(-2)) / 2 print df.dropna() timestamp name price profit new column 0 2016-01-01 bob 5 4 4.5 1 2016-01-02 jim 3 2 3.0 2 2016-01-03 jim 2 6 5.0 </code></pre>
1
2016-08-20T01:28:53Z
[ "python", "pandas" ]
Iterating and averaging pandas data frame
39,049,202
<p>I have a database with a lot of rows such as:</p> <pre><code>timestamp name price profit bob 5 4 jim 3 2 jim 2 6 bob 6 7 jim 4 1 jim 6 3 bob 3 1 </code></pre> <p>The data base is sorted by a timestamp. I would like to be able to add a new column where it would take the last 2 values in the price column before the current value and average them into a new column. So that the first three rows would look something like this with a new column:</p> <pre><code>timestamp name price profit new column bob 5 4 4.5 jim 3 2 3 jim 2 6 5 (6+3)/2 = 4.5 (2+4)/2 = 3 (4+6)/2 = 5 </code></pre> <p>This isn't for a school project or anything this is just something I'm working on on my own. I've tried asking a similar question to this but I don't think I was very clear. Thanks in advance!</p>
2
2016-08-20T00:03:11Z
39,051,703
<pre><code>def shift_n_roll(df): return df.shift(-1).rolling(2).mean().shift(-1) df['new column'] = df.groupby('name').price.apply(shift_n_roll) df </code></pre> <p><a href="http://i.stack.imgur.com/0OBuy.png" rel="nofollow"><img src="http://i.stack.imgur.com/0OBuy.png" alt="enter image description here"></a></p>
2
2016-08-20T07:37:03Z
[ "python", "pandas" ]
Change dataframe pandas based one series
39,049,204
<p>I have data and have convert using dataframe pandas :</p> <pre><code>import pandas as pd d = [ (1,70399,0.988375133622), (1,33919,0.981573492596), (1,62461,0.981426807114), (579,1,0.983018778374), (745,1,0.995580488899), (834,1,0.980942505189) ] df_new = pd.DataFrame(e, columns=['source_target']).sort_values(['source_target'], ascending=[True]) </code></pre> <p>and i need build series for mapping column <code>source</code> and <code>target</code> into another</p> <pre><code>e = [] for x in d: e.append(x[0]) e.append(x[1]) e = list(set(e)) df_new = pd.DataFrame(e, columns=['source_target']) df_new.source_target = (df_new.source_target.diff() != 0).cumsum() - 1 new_ser = pd.Series(df_new.source_target.values, index=new_source_old).drop_duplicates() </code></pre> <p>so i get series :</p> <pre><code>source_target 1 0 579 1 745 2 834 3 33919 4 62461 5 70399 6 dtype: int64 </code></pre> <p>i have tried change dataframe <code>df_beda</code> based on <code>new_ser</code> series using :</p> <pre><code>df_beda.target = df_beda.target.mask(df_beda.target.isin(new_ser), df_beda.target.map(new_ser)).astype(int) df_beda.source = df_beda.source.mask(df_beda.source.isin(new_ser), df_beda.source.map(new_ser)).astype(int) </code></pre> <p>but result is :</p> <pre><code> source target weight 0 0 70399 0.988375 1 0 33919 0.981573 2 0 62461 0.981427 3 579 0 0.983019 4 745 0 0.995580 5 834 0 0.980943 </code></pre> <p>it's wrong, ideal result is :</p> <pre><code> source target weight 0 0 6 0.988375 1 0 4 0.981573 2 0 5 0.981427 3 1 0 0.983019 4 2 0 0.995580 5 3 0 0.980943 </code></pre> <p>maybe anyone can help me for show where my mistake</p> <p>Thanks</p>
1
2016-08-20T00:03:41Z
39,049,563
<p>If the order doesn't matter, you can do the following. Avoid <code>for</code> loop unless it's absolutely necessary.</p> <pre><code>uniq_vals = np.unique(df_beda[['source','target']]) map_dict = dict(zip(uniq_vals, xrange(len(uniq_vals)))) df_beda[['source','target']] = df_beda[['source','target']].replace(map_dict) print df_beda source target weight 0 0 6 0.988375 1 0 4 0.981573 2 0 5 0.981427 3 1 0 0.983019 4 2 0 0.995580 5 3 0 0.980943 </code></pre> <p>If you want to roll back, you can create an inverse map from the original one, because it is guaranteed to be 1-to-1 mapping.</p> <pre><code>inverse_map = {v:k for k,v in map_dict.iteritems()} df_beda[['source','target']] = df_beda[['source','target']].replace(inverse_map) print df_beda source target weight 0 1 70399 0.988375 1 1 33919 0.981573 2 1 62461 0.981427 3 579 1 0.983019 4 745 1 0.995580 5 834 1 0.980943 </code></pre>
2
2016-08-20T01:12:46Z
[ "python", "pandas" ]
Why does xml.etree.ElementTree.parse converts namespace elements in lowercase
39,049,210
<p>I want to instruct ET.parse to leave the namespace case in XML as it is</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse("mimeTypes.rdf") ET.dump(tree) &lt;rdf:RDF xmlns:ns1="http://home.netscape.com/NC-rdf#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"&gt; &lt;rdf:Description ns1:value="irc" rdf:about="urn:scheme:irc"&gt; &lt;ns1:handlerProp rdf:resource="urn:scheme:handler:irc" /&gt; &lt;/rdf:Description&gt; &lt;rdf:Description ns1:value="application/pdf" rdf:about="urn:mimetype:application/pdf"&gt; &lt;ns1:handlerProp rdf:resource="urn:mimetype:handler:application/pdf" /&gt; &lt;/rdf:Description&gt; </code></pre> <p>Original file looks like this:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;RDF:RDF xmlns:NC="http://home.netscape.com/NC-rdf#" xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#"&gt; &lt;RDF:Description RDF:about="urn:scheme:irc" NC:value="irc"&gt; &lt;NC:handlerProp RDF:resource="urn:scheme:handler:irc"/&gt; &lt;/RDF:Description&gt; &lt;RDF:Description RDF:about="urn:mimetype:application/pdf" NC:value="application/pdf"&gt; &lt;NC:handlerProp RDF:resource="urn:mimetype:handler:application/pdf"/&gt; &lt;/RDF:Description&gt; </code></pre>
0
2016-08-20T00:04:54Z
39,092,673
<p>Apparently I had to register the namespaces used in the XML:</p> <pre><code> import xml.etree.ElementTree as ET tree = ET.parse("mimeTypes.rdf") et.register_namespace('NC', 'http://home.netscape.com/NC-rdf#') et.register_namespace('RDF', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') tree.write("tmp.xml", xml_declaration=True, encoding='utf-8', method="xml") </code></pre>
0
2016-08-23T04:58:16Z
[ "python", "xml", "xml.etree" ]
Processing non-english text
39,049,294
<p>I have a python file that reads a file given by the user, processes it, and ask questions in flash card format. The program works fine with an english txt file but I encounter errors when trying to process a french file.</p> <p>When I first encountered the error, I was using the windows command prompt window and running <code>python cards.py</code>. When inputting the french file, I immediately got a <code>UnicodeEncodeError</code>. After digging around, I found that it may have something to do with the fact I was using the cmd window. So I tried using IDLE. I didn't get any errors but I would get weird characters like <code>œ</code> and <code>Ã</code> and <code>®</code>.</p> <p>Upon further research, I found some <a href="https://docs.python.org/3/howto/unicode.html" rel="nofollow">documentation</a> that instructs to use <code>encoding='insert encoding type'</code> in the <code>open(file)</code> part of my code. After running the program again in IDLE, it seemed to minimize the problem, but I would still get some weird characters. When running it in the cmd, it wouldn't break IMMEDIATELY, but would eventually when it encountered an unknown character.</p> <p>My question: what do I implement to ensure the program can handle ALL of the chaaracters in the file (given any language) and why does IDLE and the command prompt handle the file differently?</p> <p>EDIT: I forgot to mention that I ended up using utf-8 which gave the results I described.</p>
-2
2016-08-20T00:19:07Z
39,049,324
<p>It's common question. Seems that you're using cmd which doesn't support unicode, so error occurs during <strong>translation of output</strong> to the encoding, which your cmd runs. And as unicode has a wider charset, than encoding used in cmd, it gives an error</p> <p>IDLE is built ontop of tkinter's Text widget, which perfectly supports Python strings in unicode.</p> <p>And, finally, when you specify a file you'd like to open, the <code>open</code> function assumes that it's in platform default (per <code>locale.getpreferredencoding()</code>). So if your file encoding differs, you should exactly mention it in keyword arg <code>encoding</code> to <code>open</code> func.</p>
1
2016-08-20T00:24:22Z
[ "python", "python-3.x", "unicode", "utf-8" ]
Processing non-english text
39,049,294
<p>I have a python file that reads a file given by the user, processes it, and ask questions in flash card format. The program works fine with an english txt file but I encounter errors when trying to process a french file.</p> <p>When I first encountered the error, I was using the windows command prompt window and running <code>python cards.py</code>. When inputting the french file, I immediately got a <code>UnicodeEncodeError</code>. After digging around, I found that it may have something to do with the fact I was using the cmd window. So I tried using IDLE. I didn't get any errors but I would get weird characters like <code>œ</code> and <code>Ã</code> and <code>®</code>.</p> <p>Upon further research, I found some <a href="https://docs.python.org/3/howto/unicode.html" rel="nofollow">documentation</a> that instructs to use <code>encoding='insert encoding type'</code> in the <code>open(file)</code> part of my code. After running the program again in IDLE, it seemed to minimize the problem, but I would still get some weird characters. When running it in the cmd, it wouldn't break IMMEDIATELY, but would eventually when it encountered an unknown character.</p> <p>My question: what do I implement to ensure the program can handle ALL of the chaaracters in the file (given any language) and why does IDLE and the command prompt handle the file differently?</p> <p>EDIT: I forgot to mention that I ended up using utf-8 which gave the results I described.</p>
-2
2016-08-20T00:19:07Z
39,063,084
<p>The Windows console does not natively support Unicode (despite what people say about <code>chcp 65001</code>). It's designed to be backwards compatible so only supports 8bit character sets.</p> <p>Use <a href="https://github.com/Drekin/win-unicode-console" rel="nofollow">win-unicode-console</a> instead. It talks to the cmd at a lower level, which allows <strong>all</strong> Unicode characters to be printed, and importantly, inputted.</p> <p>The best way to enable it is in your <code>usercustomize</code> script, so that's enabled by default on your machine.</p>
0
2016-08-21T10:13:41Z
[ "python", "python-3.x", "unicode", "utf-8" ]
Removing only the numeric without affecting other numbers in the string
39,049,308
<p>I have a list of objects that goes as follows, for example:</p> <pre><code>['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] </code></pre> <p>And I wanted to remove the numeric that exists at the end of each item in the list, so that it should be like this:</p> <pre><code>['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj'] </code></pre> <p>However, if I tried using <code>.isdigit</code>, it will remove the other numbers that exists. And if I were to use <code>[:1]</code>, <code>[:2]</code> or <code>[:3]</code>, it also does not seems to be the ideal case as you can see in my example where there exists between 1-3 digits at the end..</p> <p>What is the best way to approach it?</p>
0
2016-08-20T00:21:55Z
39,049,327
<p>You can use <code>re.sub</code> to substitute the ending digits (if there exist any) with blanks.</p> <pre><code>import re a=['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] print ([re.sub(r'\d*$','',i) for i in a]) </code></pre>
2
2016-08-20T00:24:40Z
[ "python", "maya" ]
Removing only the numeric without affecting other numbers in the string
39,049,308
<p>I have a list of objects that goes as follows, for example:</p> <pre><code>['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] </code></pre> <p>And I wanted to remove the numeric that exists at the end of each item in the list, so that it should be like this:</p> <pre><code>['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj'] </code></pre> <p>However, if I tried using <code>.isdigit</code>, it will remove the other numbers that exists. And if I were to use <code>[:1]</code>, <code>[:2]</code> or <code>[:3]</code>, it also does not seems to be the ideal case as you can see in my example where there exists between 1-3 digits at the end..</p> <p>What is the best way to approach it?</p>
0
2016-08-20T00:21:55Z
39,049,351
<p>No need to use pattern matching (regular expressions) when <code>rstrip</code> is enough (it's faster, simpler and more readable) :</p> <pre><code>a=['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] print(i.rstrip("0123456789") for i in a) </code></pre>
4
2016-08-20T00:28:48Z
[ "python", "maya" ]
Removing only the numeric without affecting other numbers in the string
39,049,308
<p>I have a list of objects that goes as follows, for example:</p> <pre><code>['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] </code></pre> <p>And I wanted to remove the numeric that exists at the end of each item in the list, so that it should be like this:</p> <pre><code>['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj'] </code></pre> <p>However, if I tried using <code>.isdigit</code>, it will remove the other numbers that exists. And if I were to use <code>[:1]</code>, <code>[:2]</code> or <code>[:3]</code>, it also does not seems to be the ideal case as you can see in my example where there exists between 1-3 digits at the end..</p> <p>What is the best way to approach it?</p>
0
2016-08-20T00:21:55Z
39,054,478
<p>Since the format is always the same i.e <em>obj</em> then some digits you can could just <code>rindex</code> on <code>j</code> and slice:</p> <pre><code>In [5]: l = ['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] In [6]: [s[:s.rindex("j")+1] for s in l] Out[6]: ['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj'] </code></pre> <p>If you want to update the original list:</p> <pre><code>In [7]: l = ['ref_2537_1_obj1', 'ref_8953_1_obj32', 'ref_1120_1_obj', 'ref_8919_1_obj143'] In [8]: l[:] = (s[:s.rindex("j")+1] for s in l) In [9]: l Out[9]: ['ref_2537_1_obj', 'ref_8953_1_obj', 'ref_1120_1_obj', 'ref_8919_1_obj'] </code></pre>
-1
2016-08-20T13:06:32Z
[ "python", "maya" ]
Python comprehensions in function calls (PEP 448)
39,049,419
<p>(This is all on Python 3.5.2)</p> <p>At the bottom of <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>, I see:</p> <blockquote> <p>Unbracketed comprehensions in function calls, such as <code>f(x for x in it)</code> , are already valid.</p> </blockquote> <p>This is intriguing. If I define the following function:</p> <pre><code>def f(a, b, c): return a + b + c </code></pre> <p>then that wording makes me think that <code>f(thing for thing in [1, 2, 3]) == 6</code>. But actually, I get:</p> <pre><code>&gt;&gt;&gt; f(thing for thing in [1, 2, 3]) TypeError: f() missing 2 required positional arguments: 'b' and 'c' </code></pre> <p>i.e. the whole generator expression passed as <code>a</code>.</p> <p>So what does this sentence in PEP 448 mean? Just that you can pass a generator expression as an argument?</p>
0
2016-08-20T00:41:26Z
39,049,494
<p>This statement means only that in <strong>pre-PEP</strong> world <code>f(x for x in it)</code> was already valid and passed generator expression as first function argument.</p> <p>To make your example work, you need to explicitly unpack generator, as shown in PEP examples.</p> <pre><code>f(*(thing for thing in [1, 2, 3])) # returns 6 </code></pre>
3
2016-08-20T00:55:10Z
[ "python", "python-3.x", "language-lawyer" ]
Python comprehensions in function calls (PEP 448)
39,049,419
<p>(This is all on Python 3.5.2)</p> <p>At the bottom of <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>, I see:</p> <blockquote> <p>Unbracketed comprehensions in function calls, such as <code>f(x for x in it)</code> , are already valid.</p> </blockquote> <p>This is intriguing. If I define the following function:</p> <pre><code>def f(a, b, c): return a + b + c </code></pre> <p>then that wording makes me think that <code>f(thing for thing in [1, 2, 3]) == 6</code>. But actually, I get:</p> <pre><code>&gt;&gt;&gt; f(thing for thing in [1, 2, 3]) TypeError: f() missing 2 required positional arguments: 'b' and 'c' </code></pre> <p>i.e. the whole generator expression passed as <code>a</code>.</p> <p>So what does this sentence in PEP 448 mean? Just that you can pass a generator expression as an argument?</p>
0
2016-08-20T00:41:26Z
39,049,500
<p>What is happening is that on line <code>f(thing for thing in [1, 2, 3])</code> you are passing only the first argument, which is a generator. Arguments <code>b</code> and <code>c</code> are missing.</p> <p>Also, check the following part of the PEP:</p> <blockquote> <p>However, it wasn't clear if this was the best behaviour or if it should unpack into the arguments of the call to f . Since this is likely to be confusing and is of only very marginal utility, it is not included in this PEP. Instead, these will throw a SyntaxError and comprehensions with explicit brackets should be used instead.</p> </blockquote>
0
2016-08-20T00:56:47Z
[ "python", "python-3.x", "language-lawyer" ]
Python comprehensions in function calls (PEP 448)
39,049,419
<p>(This is all on Python 3.5.2)</p> <p>At the bottom of <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>, I see:</p> <blockquote> <p>Unbracketed comprehensions in function calls, such as <code>f(x for x in it)</code> , are already valid.</p> </blockquote> <p>This is intriguing. If I define the following function:</p> <pre><code>def f(a, b, c): return a + b + c </code></pre> <p>then that wording makes me think that <code>f(thing for thing in [1, 2, 3]) == 6</code>. But actually, I get:</p> <pre><code>&gt;&gt;&gt; f(thing for thing in [1, 2, 3]) TypeError: f() missing 2 required positional arguments: 'b' and 'c' </code></pre> <p>i.e. the whole generator expression passed as <code>a</code>.</p> <p>So what does this sentence in PEP 448 mean? Just that you can pass a generator expression as an argument?</p>
0
2016-08-20T00:41:26Z
39,049,505
<p>Actually <code>f(x for x in it)</code> is not a new feature that introduced by PEP 448 but by <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">PEP 289</a>. Noted not all features that discussed in PEP 448 are implemented in Python 3.5. The <a href="https://www.python.org/dev/peps/pep-0448/#variations" rel="nofollow">"Variations" section</a> mentioned in the question is not implemented:</p> <blockquote> <p>Since this is likely to be confusing and is of only very marginal utility, it is not included in this PEP. Instead, these will throw a <code>SyntaxError</code> and comprehensions with explicit brackets should be used instead.</p> </blockquote>
0
2016-08-20T00:57:45Z
[ "python", "python-3.x", "language-lawyer" ]
Python comprehensions in function calls (PEP 448)
39,049,419
<p>(This is all on Python 3.5.2)</p> <p>At the bottom of <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>, I see:</p> <blockquote> <p>Unbracketed comprehensions in function calls, such as <code>f(x for x in it)</code> , are already valid.</p> </blockquote> <p>This is intriguing. If I define the following function:</p> <pre><code>def f(a, b, c): return a + b + c </code></pre> <p>then that wording makes me think that <code>f(thing for thing in [1, 2, 3]) == 6</code>. But actually, I get:</p> <pre><code>&gt;&gt;&gt; f(thing for thing in [1, 2, 3]) TypeError: f() missing 2 required positional arguments: 'b' and 'c' </code></pre> <p>i.e. the whole generator expression passed as <code>a</code>.</p> <p>So what does this sentence in PEP 448 mean? Just that you can pass a generator expression as an argument?</p>
0
2016-08-20T00:41:26Z
39,049,533
<p>Python allows you to pass a single generator expression to a function you're calling without needing extra parentheses. For instance:</p> <pre><code>foo(x for x in range(10)) </code></pre> <p>is mostly equivalent to:</p> <pre><code>genexp = (x for x in range(10)) # parentheses are necessary here foo(genexp) </code></pre> <p>You do still need the parentheses when defining the generator expression if there are other arguments that you're passing to the function call (e.g. <code>foo(w, (x for x in range(10)), y, z)</code>, where the second argument is a generator expression of <code>x</code>'s).</p> <p>The PEP was mentioning in passing that a further extension of the unpacking syntax might be confusing in that context. If a new kind of generator expression <code>(*x for x in nested)</code> was legal (it is not part the final PEP, but was being considered for a while), how should <code>foo(*x for x in nested)</code> work? Would it be equivalent to <code>foo((*x for x in nested))</code> (calling with a single generator expression, that included the new "flattening" <code>*</code>), or would it mean <code>foo(*(x for x in nested))</code> (which is legal now)?</p>
1
2016-08-20T01:03:48Z
[ "python", "python-3.x", "language-lawyer" ]
Python: Call a class method from within a 'DIFFERENT class''s method
39,049,427
<p>I want to call a method from classB, in a method in classA and pass arguments:</p> <pre><code>class A: B.processAds(ad, cnx, renewableAds, adsToRenew, webdriver) class B: def processAds(self, ad, cnx, renewableAds, adsToRenew, webdriver): </code></pre> <p>How would I do this?</p>
0
2016-08-20T00:42:36Z
39,049,518
<p>Make the method in class B a <code>classmethod</code>:</p> <pre><code>class B: @classmethod def processAds(cls, ad, cnx, renewableAds, adsToRenew, webdriver): </code></pre> <p>then you'll be able to use it without instantiating class B, e.g.:</p> <pre><code>return_value = B.processAds(ad, cnx, renewableAds, adsToRenew, webdriver) </code></pre> <p>You can read more about <code>classmethod</code> in this <a href="http://stackoverflow.com/a/12179752/3570352">answer</a>.</p>
0
2016-08-20T01:01:01Z
[ "python", "oop" ]
Converting .txt file with tab seperation to xlsx via python3
39,049,466
<p>Level: super-noob</p> <p>I have been trying to convert a .txt file to .xlsx using a combination of csv &amp; openpyxl &amp; xlsxwriter modules.</p> <p>My first column is an identity that should be saved as a string Columns 2-21 are then all numbers.</p> <p>How can I load up my .txt file. Identify the proper columns as numbers and then save the file as an xlsx?</p> <p>So far I'm at:</p> <pre><code>import csv import openpyxl input_file = "C:/1.txt" output_file = "C:/1.xlsx" new_wb = openpyxl.Workbook() ws = new_wb.worksheets[0] read_file = csv.reader(input_file, delimitter="\t") </code></pre> <p>I have read people using enumerate to gun through an excel file online but I'm not sure how this function exactly works... but if someone can help me here it will be appreciated!</p>
1
2016-08-20T00:50:08Z
39,049,612
<p>You need to iterate over each row in csv file and append that row to excel worksheet. </p> <p>This could be helpful:</p> <pre><code>import csv import openpyxl input_file = 'path/to/inputfile.txt' output_file = 'path/to/outputfile.xls' wb = openpyxl.Workbook() ws = wb.worksheets[0] with open(input_file, 'rb') as data: reader = csv.reader(data, delimiter='\t') for row in reader: ws.append(row) wb.save(output_file) </code></pre>
2
2016-08-20T01:22:46Z
[ "python", "excel" ]
Flask static file giving 404
39,049,560
<h2>Code in <code>main.py</code> file:</h2> <pre><code>from flask import Flask, render_template, send_from_directory app = Flask(__name__, static_url_path="") app._static_folder = "static" @app.route("/") def root(): return app.send_static_file("index.html") @app.route("/about") def about(): return app.send_static_file("about/index.html") @app.route("/projects") def projects(): return app.send_static_file("projects/index.html") #snip if __name__ == "__main__": app.run(host="0.0.0.0") </code></pre> <p>When I go to the root directory or the <code>/about</code> directory it works fine, but when I try to go to the <code>/projects</code> directory, I got the error:</p> <h3>Error message:</h3> <blockquote> <p>Not Found</p> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p> </blockquote>
-1
2016-08-20T01:10:43Z
39,051,571
<p>There are two possible reasons.</p> <ol> <li>You mis-typed the path. Did you perhaps have a typo in <code>projects</code> (i.e., <code>project</code>) or <code>index.html</code>?</li> <li>The path doesn't exist. Unlike <code>render_template</code>, <code>app.send_static_file</code> just dies if the path doesn't exist. Since the <code>static_folder</code> is <code>static</code>, then the project page code should exist under <code>static/projects/index.html</code> (and not <code>projects/index.html</code>).</li> </ol> <p>To test if it's a rogue issue, replace the body of the projects view with <code>return 'some string'</code>. If that string doesn't show, then you have a different beast on your hands. If it does, then it's most definitely one of the two bugs I've identified above.</p> <p><em>On an un-related note, I would add <code>debug=True</code> to the list of <code>app.run(...)</code> kwargs, to make development more convenient. (The app refreshes whenever there's a file save)</em></p>
0
2016-08-20T07:16:44Z
[ "python", "nginx", "flask" ]
Python 3: How to extract url image?
39,049,574
<p>The urls I want to extract have same pattern:</p> <pre><code>"begin" : "url_I_want_extract" </code></pre> <p>They look like:</p> <pre><code>"begin" : "https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg" "begin" : "https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg" "begin" : "https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg" "begin" : "https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg" "begin" : "https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg" </code></pre> <p>And I used this code to extract but getting unexpected things. </p> <pre><code>r = re.findall('https://k(.?).website.com/images/0x0/0x0/0/(.*?).jpeg', response.text) </code></pre> <p>The output I got:</p> <pre><code> [('2', '16576946054146395951'), ('2', '9460365509030976330'), ('2', '9361112829030898475'), ('3', '14705723619301900580')] </code></pre> <p>The output I want:</p> <pre><code>https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg </code></pre> <p>How to use regex to scrape Urls after ""begin"" word ? Thank you :)</p>
3
2016-08-20T01:15:03Z
39,049,699
<p>The parenthesis surround the capturing groups that are returned by <code>findall</code>. Right now your capturing groups are <code>k(.&gt;)</code> and <code>(.*?).jpeg</code>. Remove those parenthesis and instead capture the entire url.</p> <p>Also, to match both the url's with "/0x0/0x0/0/" and "/8x36/922x950/0/", replace "/0x0/0x0/0/" in the regex with "/.*/.*/.*/":</p> <pre><code>r = re.findall('(https://k.?.website.com/images/.*/.*/.*/.*?.jpeg)', response.text) </code></pre>
2
2016-08-20T01:46:22Z
[ "javascript", "python", "regex", "web-scraping" ]
Python 3: How to extract url image?
39,049,574
<p>The urls I want to extract have same pattern:</p> <pre><code>"begin" : "url_I_want_extract" </code></pre> <p>They look like:</p> <pre><code>"begin" : "https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg" "begin" : "https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg" "begin" : "https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg" "begin" : "https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg" "begin" : "https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg" </code></pre> <p>And I used this code to extract but getting unexpected things. </p> <pre><code>r = re.findall('https://k(.?).website.com/images/0x0/0x0/0/(.*?).jpeg', response.text) </code></pre> <p>The output I got:</p> <pre><code> [('2', '16576946054146395951'), ('2', '9460365509030976330'), ('2', '9361112829030898475'), ('3', '14705723619301900580')] </code></pre> <p>The output I want:</p> <pre><code>https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg </code></pre> <p>How to use regex to scrape Urls after ""begin"" word ? Thank you :)</p>
3
2016-08-20T01:15:03Z
39,050,200
<p>This one may do the trick on a more general server path construction: </p> <pre><code>https?.*(jpeg|jpg|png|tiff|gif) </code></pre> <p>Start capturing the http ( with optional 's' for ssl servers ) and finish capture assuring a image file format. ( Please note that I included 5 types just as an example...)</p> <p><a href="http://i.stack.imgur.com/HmNjF.png" rel="nofollow"><img src="http://i.stack.imgur.com/HmNjF.png" alt="Demo"></a></p> <p>Hope that helps !!</p>
1
2016-08-20T03:33:42Z
[ "javascript", "python", "regex", "web-scraping" ]
Python 3: How to extract url image?
39,049,574
<p>The urls I want to extract have same pattern:</p> <pre><code>"begin" : "url_I_want_extract" </code></pre> <p>They look like:</p> <pre><code>"begin" : "https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg" "begin" : "https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg" "begin" : "https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg" "begin" : "https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg" "begin" : "https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg" </code></pre> <p>And I used this code to extract but getting unexpected things. </p> <pre><code>r = re.findall('https://k(.?).website.com/images/0x0/0x0/0/(.*?).jpeg', response.text) </code></pre> <p>The output I got:</p> <pre><code> [('2', '16576946054146395951'), ('2', '9460365509030976330'), ('2', '9361112829030898475'), ('3', '14705723619301900580')] </code></pre> <p>The output I want:</p> <pre><code>https://k2.website.com/images/0x0/0x0/0/16576946054146395951.jpeg https://k2.website.com/images/0x0/0x0/0/9460365509030976330.jpeg https://k2.website.com/images/0x0/0x0/0/9361112829030898475.jpeg https://k3.website.com/images/0x0/0x0/0/14705723619301900580.jpeg https://k3.website.com/images/8x36/922x950/0/1368601155311066426.jpeg </code></pre> <p>How to use regex to scrape Urls after ""begin"" word ? Thank you :)</p>
3
2016-08-20T01:15:03Z
39,050,224
<p>I think what you're asking for is to extract only the URLs after <code>begin :</code>. For this you'd want:</p> <pre><code>r = re.findall('"begin" : "(https://k.*?.jpeg)"', response.text) </code></pre>
1
2016-08-20T03:38:46Z
[ "javascript", "python", "regex", "web-scraping" ]
differences in computation outputs, theano, non theano
39,049,616
<p>I'm starting to play around with theano, and so I tried computing a simple function and testing the output, however when I test a theano compiled version versus a non theano version the outputs are a bit different....</p> <p>The code:</p> <pre><code>import numpy as np import theano.tensor as T from theano import function np.random.seed(1) S = np.random.rand(4,3) Q = np.random.rand(4,3) def MSE(a, b): n = min(a.shape[0], b.shape[0]) fhat = T.dvector('fhat') y = T.dvector('y') mse = ((y - fhat)**2).sum() / n mse_f = function([y, fhat], mse) return mse_f(a,b) for row in range(S.shape[0]): print(MSE(S[row], Q[row])) for i in range(S.shape[0]): print(((S[i] - Q[i])**2).sum() / S.shape[0]) </code></pre> <p>the outputs:</p> <pre><code># from MSE function 0.0623486922837 0.0652202301174 0.151698460419 0.187325204482 # non theano output 0.0467615192128 0.0489151725881 0.113773845314 0.140493903362 </code></pre> <p>What am I over looking here? </p>
0
2016-08-20T01:23:30Z
39,049,690
<p>In the expression in this statement</p> <pre><code> print(((S[i] - Q[i])**2).sum() / S.shape[0]) </code></pre> <p>you should divide by <code>S.shape[1]</code>, not <code>S.shape[0]</code>.</p> <p>You created <code>S</code> using <code>S = np.random.rand(4,3)</code>, which means <code>S</code> has shape (4, 3). That is, <code>S.shape</code> is <code>(4, 3)</code>. The length of each row in <code>S</code> is <code>S.shape[1]</code>.</p>
0
2016-08-20T01:43:26Z
[ "python", "numpy", "theano" ]