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
handling exception in reading data with pandas.read_csv()
39,057,333
<p>I would like to open a csv file in pieces with pd.read_csv(path, chunksize = N) until the end of it in a quite elegant and efficient way. The problem is that once the pointer is out of the file the following message of error takes place:</p> <pre><code>df.get_chunk() Traceback (most recent call last): File "&lt;ipython-input-115-061ea8dbcbad&gt;", line 1, in &lt;module&gt; df.get_chunk() File "C:\Users\fedel\Anaconda2\lib\site-packages\pandas\io\parsers.py", line 784, in get_chunk return self.read(nrows=size) File "C:\Users\fedel\Anaconda2\lib\site-packages\pandas\io\parsers.py", line 763, in read ret = self._engine.read(nrows) File "C:\Users\fedel\Anaconda2\lib\site-packages\pandas\io\parsers.py", line 1213, in read data = self._reader.read(nrows) File "pandas\parser.pyx", line 766, in pandas.parser.TextReader.read (pandas\parser.c:7988) File "pandas\parser.pyx", line 813, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:8629) StopIteration </code></pre> <p>and the code can't continue anymore!</p> <p>I believe that a try/except statement will avoid me that message hence the code will keep going with the next issues. Say that I have a python DataFrame like that one you can generate with the following lines of code</p> <pre><code>path = r"C:\Users\fedel\Desktop" + '\\fileName.csv' pd.DataFrame( np.random.randn(30, 3), columns = list('abc')).to_csv(path, index = False) df = pd.read_csv(path, chunksize = 6) </code></pre> <p>I think that a statement like the following one could avoid that error and let the code continue with the next issues</p> <pre><code>while True: try: df.get_chunk() except TypeOfError: funcyfunction() </code></pre> <p>could you fix this last exception handling lines of code, please?</p>
0
2016-08-20T18:16:16Z
39,058,046
<p>You could try:</p> <pre><code>df = pd.read_csv(path, chunksize=6) for chunk in df: print(chunk) </code></pre> <hr> <p>Incase you want to carry out operations inside each chunk, you can do:</p> <pre><code>for chunk in df: chunk['d'] = chunk[['a', 'b']].mean(axis=1) # Average of columns 'a' and 'b' print(chunk) </code></pre>
1
2016-08-20T19:41:24Z
[ "python", "pandas" ]
Multiple URL requests to API without getting error from urllib2 or requests
39,057,359
<p>I am trying to get data from different APIs. They are received in JSON format, stored in SQLite and afterwards parsed.</p> <p>The issue I am having is that when sending many requests I eventually receive an error, even if I am using <code>time.sleep</code> between requests.</p> <h1>Usual approach</h1> <p>My code looks like the one below, where this would be inside a loop and the url to be opened would be changing:</p> <pre><code>base_url = 'https://www.whateversite.com/api/index.php?' custom_url = 'variable_text1' + &amp; + 'variable_text2' url = base_url + custom_urls #url will be changing time.sleep(1) data = urllib2.urlopen(url).read() </code></pre> <p>This runs thousands of times inside the loop. The problem comes after the script has been running for a while (up to a couple of hours), then I get the following errors or similar ones:</p> <pre><code> data = urllib2.urlopen(url).read() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen return _opener.open(url, data, timeout) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open response = self._open(req, data) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open '_open', req) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain result = func(*args) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1222, in https_open return self.do_open(httplib.HTTPSConnection, req) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1184, in do_open raise URLError(err) urllib2.URLError: &lt;urlopen error [Errno 8] nodename nor servname provided, or not known&gt; </code></pre> <p>or</p> <pre><code> uh = urllib.urlopen(url) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 87, in urlopen return opener.open(url) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 208, in open return getattr(self, name)(url) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 437, in open_https h.endheaders(data) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 969, in endheaders self._send_output(message_body) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 829, in _send_output self.send(msg) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 791, in send self.connect() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1172, in connect self.timeout, self.source_address) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 553, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno 8] nodename nor servname provided, or not known </code></pre> <p>I believe this happens because the modules throw an error at some point if used too often in a short period of time.</p> <p>From what I've read in many different threads about <a href="http://stackoverflow.com/questions/2018026/what-are-the-differences-between-the-urllib-urllib2-and-requests-module">which module is better</a>, I think for my needs all would work and the main lever to choose one is that it can open as many url's as possible. In my experience, <code>urllib</code> and <code>urllib2</code> are better than <code>requests</code> for that, as <code>requests</code> crashed in less time.</p> <p>Assuming that I do not want to increase the waiting time used in <code>time.sleep</code>, these are the solutions I thought so far:</p> <h1>Possible solutions?</h1> <h2>A</h2> <p>I thought of combining all different modules. That would be: </p> <ul> <li>Start, for instance, with <code>requests</code>.</li> <li>After a specific time or when error is thrown, switch automatically to <code>urllib2</code> </li> <li>After a specific time or when error is thrown, switch automatically to other modules (such as <code>httplib2</code> or <code>urllib</code>) or back to <code>requests</code> </li> <li>And so on...</li> </ul> <h2>B</h2> <p>Use <code>try .. except</code> block to handle that exception, as suggested <a href="http://stackoverflow.com/questions/20568216/python-handling-socket-error-errno-104-connection-reset-by-peer">here</a>.</p> <h2>C</h2> <p>I've also read about <a href="http://stackoverflow.com/questions/34512646/how-to-speed-up-api-requests">sending multiple requests at once or in parallel</a>. I don't know how that exactly works and if it could actually be useful</p> <hr> <p>However, I am not convinced about any of these solutions.</p> <p>Can you think of any more elegant and/or efficient solution to deal with this error?</p> <p><em>I'm with Python 2.7</em></p>
0
2016-08-20T18:19:53Z
39,064,623
<p>Even if I was not convinced, I ended up trying to implement the <code>try .. except</code> block and I'm quite happy with the result:</p> <pre><code>for url in list_of_urls: time.sleep(2) try: response = urllib2.urlopen(url) data = response.read() time.sleep(0.1) response.close() #as suggested by zachyee in the comments #code to save data in SQLite database except urllib2.URLError as e: print '***** urllib2.URLError: &lt;urlopen error [Errno 8] nodename nor servname provided, or not known&gt; *****' #save error in SQLite cur.execute('''INSERT INTO Errors (error_type, error_ts, url_queried) VALUES (?, ?, ?)''', ('urllib2.URLError', timestamp, url)) conn.commit() time.sleep(30) #give it a small break </code></pre> <p>The script did run until the end. </p> <p>From thousands of requests I got 8 errors, that were saved in my database with its related URL. This way I can try to retrieve those url's again afterwards, if needed.</p>
0
2016-08-21T13:16:44Z
[ "python", "python-requests", "urllib2", "urllib", "httplib2" ]
Operations with numpy array elements
39,057,365
<p>Have a numpy array which was created from pandas values.</p> <p>It looks like this:</p> <pre><code>array([[ 230.1, 37.8, 69.2], [ 44.5, 39.3, 45.1], [ 17.2, 45.9, 69.3], [ 151.5, 41.3, 58.5], [ 180.8, 10.8, 58.4]]) </code></pre> <p>How can I subtract the np.mean() of it from every single entry of this array? </p> <p>Thanks in advance!</p>
0
2016-08-20T18:20:27Z
39,057,490
<p>With <code>-</code>:</p> <pre><code>a = array([[ 230.1, 37.8, 69.2], [ 44.5, 39.3, 45.1], [ 17.2, 45.9, 69.3], [ 151.5, 41.3, 58.5], [ 180.8, 10.8, 58.4]]) a -= a.mean() </code></pre>
1
2016-08-20T18:34:49Z
[ "python", "arrays", "pandas", "numpy" ]
Collatz function not exiting correctly
39,057,369
<p>Here's a program that is intended to count the length of a Collatz sequence recursively:</p> <pre><code>def odd_collatz ( n ): return (3 * n) + 1 def even_collatz ( n ): return int(n / 2) def collatz_counter ( initialNumber, initialLength ): length = initialLength while True: if initialNumber == 1: return length elif initialNumber != 1: length += 1 if initialNumber % 2 == 0: collatz_counter(even_collatz(initialNumber), length) else: collatz_counter(odd_collatz(initialNumber), length) print(collatz_counter(13, 1) </code></pre> <p>The expected answer should be 10. However, the program gets stuck in an infinite loop. At the second to last step of the sequence <code>initalNumber</code> equals 2. The program functions as expected: <code>collatz_counter</code> is called using <code>even_collatz</code> and the number 10.</p> <p>The expected action of the next step would be to run <code>collatz_counter</code> with an <code>initialNumber</code> of 1 and an <code>initialLength</code> of 10. What I would expect would happen is that the first if statement would evaluate to true, <code>collatz_counter</code> should return <code>length</code> and then exit. This is not, however, what happens:</p> <p>What actually happens is that the function evaluates the first if statement, runs the <code>return length</code> line, and then jumps to the line of code under <code>if initialNumber % 2...</code> and the whole process repeats itself over and over and over in an infinite loop.</p> <p>Any ideas as to why this might be happening?</p>
2
2016-08-20T18:21:03Z
39,057,404
<p>Looks like a typo to me. You define a function <code>collatz_counter</code> expecting two numbers.</p> <p>But you call it like this:</p> <pre><code>... print(collatz_counter(13), 1) </code></pre> <p>Just try to change the last line to:</p> <pre><code>print(collatz_counter(13, 1)) </code></pre> <p>And it should be fine.</p> <p>Hope this helps!</p>
2
2016-08-20T18:24:50Z
[ "python", "function", "recursion", "collatz" ]
Collatz function not exiting correctly
39,057,369
<p>Here's a program that is intended to count the length of a Collatz sequence recursively:</p> <pre><code>def odd_collatz ( n ): return (3 * n) + 1 def even_collatz ( n ): return int(n / 2) def collatz_counter ( initialNumber, initialLength ): length = initialLength while True: if initialNumber == 1: return length elif initialNumber != 1: length += 1 if initialNumber % 2 == 0: collatz_counter(even_collatz(initialNumber), length) else: collatz_counter(odd_collatz(initialNumber), length) print(collatz_counter(13, 1) </code></pre> <p>The expected answer should be 10. However, the program gets stuck in an infinite loop. At the second to last step of the sequence <code>initalNumber</code> equals 2. The program functions as expected: <code>collatz_counter</code> is called using <code>even_collatz</code> and the number 10.</p> <p>The expected action of the next step would be to run <code>collatz_counter</code> with an <code>initialNumber</code> of 1 and an <code>initialLength</code> of 10. What I would expect would happen is that the first if statement would evaluate to true, <code>collatz_counter</code> should return <code>length</code> and then exit. This is not, however, what happens:</p> <p>What actually happens is that the function evaluates the first if statement, runs the <code>return length</code> line, and then jumps to the line of code under <code>if initialNumber % 2...</code> and the whole process repeats itself over and over and over in an infinite loop.</p> <p>Any ideas as to why this might be happening?</p>
2
2016-08-20T18:21:03Z
39,057,480
<p>You are mixing recursion and looping in a bit of an odd way. The problem is <code>while True:</code>. Because you never return anything from within the loop there is nothing stopping it from going on forever. Your code reaches 1 then just keeps adding to the length. Here is a fixed version.</p> <pre><code>def odd_collatz ( n ): return (3 * n) + 1 def even_collatz ( n ): return int(n / 2) def collatz_counter ( initialNumber, initialLength ): length = initialLength if initialNumber == 1: return length elif initialNumber != 1: length += 1 if initialNumber % 2 == 0: return collatz_counter(even_collatz(initialNumber), length) else: return collatz_counter(odd_collatz(initialNumber), length) print(collatz_counter(13, 1)) </code></pre>
3
2016-08-20T18:33:52Z
[ "python", "function", "recursion", "collatz" ]
Collatz function not exiting correctly
39,057,369
<p>Here's a program that is intended to count the length of a Collatz sequence recursively:</p> <pre><code>def odd_collatz ( n ): return (3 * n) + 1 def even_collatz ( n ): return int(n / 2) def collatz_counter ( initialNumber, initialLength ): length = initialLength while True: if initialNumber == 1: return length elif initialNumber != 1: length += 1 if initialNumber % 2 == 0: collatz_counter(even_collatz(initialNumber), length) else: collatz_counter(odd_collatz(initialNumber), length) print(collatz_counter(13, 1) </code></pre> <p>The expected answer should be 10. However, the program gets stuck in an infinite loop. At the second to last step of the sequence <code>initalNumber</code> equals 2. The program functions as expected: <code>collatz_counter</code> is called using <code>even_collatz</code> and the number 10.</p> <p>The expected action of the next step would be to run <code>collatz_counter</code> with an <code>initialNumber</code> of 1 and an <code>initialLength</code> of 10. What I would expect would happen is that the first if statement would evaluate to true, <code>collatz_counter</code> should return <code>length</code> and then exit. This is not, however, what happens:</p> <p>What actually happens is that the function evaluates the first if statement, runs the <code>return length</code> line, and then jumps to the line of code under <code>if initialNumber % 2...</code> and the whole process repeats itself over and over and over in an infinite loop.</p> <p>Any ideas as to why this might be happening?</p>
2
2016-08-20T18:21:03Z
39,057,596
<p>The main error is the <code>while True:</code> loop, coupled with the missing returns.</p> <pre><code>def odd_collatz ( n ): return (3 * n) + 1 def even_collatz ( n ): return int(n / 2) def collatz_counter(initialNumber, length): if initialNumber == 1: return length elif initialNumber != 1: length += 1 if initialNumber % 2 == 0: return collatz_counter(even_collatz(initialNumber), length) else: return collatz_counter(odd_collatz(initialNumber), length) print(collatz_counter(13, 1)) </code></pre> <p>prints 10.</p>
0
2016-08-20T18:46:33Z
[ "python", "function", "recursion", "collatz" ]
How to calculate sum of two polynomials?
39,057,546
<p>For instance 3x^4 - 17x^2 - 3x + 5. Each term of the polynomial can be represented as a pair of integers (coefficient,exponent). The polynomial itself is then a list of such pairs like<br> <code>[(3,4), (-17,2), (-3,1), (5,0)]</code> for the polynomial as shown.</p> <p>Zero polynomial, 0, is represented as the empty list <code>[]</code>, since it has no terms with nonzero coefficients.</p> <p>I want to write two functions to add and multiply two input polynomials with the same representation of tuple (coefficient, exponent):</p> <ol> <li><code>addpoly(p1, p2)</code></li> <li><code>multpoly(p1, p2)</code></li> </ol> <p>Test Cases:</p> <ul> <li><p><code>addpoly([(4,3),(3,0)], [(-4,3),(2,1)])</code> <br> should give <code>[(2, 1),(3, 0)]</code></p></li> <li><p><code>addpoly([(2,1)],[(-2,1)])</code> <br> should give <code>[]</code></p></li> <li><p><code>multpoly([(1,1),(-1,0)], [(1,2),(1,1),(1,0)])</code> <br> should give <code>[(1, 3),(-1, 0)]</code></p></li> </ul> <p>Here is something that I started with but got completely struck!</p> <pre><code>def addpoly(p1, p2): (coeff1, exp1) = p1 (coeff2, exp2) = p2 if exp1 == exp2: coeff3 = coeff1 + coeff2 </code></pre>
0
2016-08-20T18:41:20Z
39,058,521
<p>As <a href="http://stackoverflow.com/questions/39057546/how-to-calculate-sum-of-two-polynomials#comment65465088_39057546">suggested</a> in the <a href="http://stackoverflow.com/questions/39057546/how-to-calculate-sum-of-two-polynomials#comment65466242_39057546">comments</a>, it is much simpler to represent polynomials as <a href="https://en.wikipedia.org/wiki/Multiset" rel="nofollow">multisets</a> of exponents. </p> <p>In Python, the closest thing to a multiset is the <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow">Counter</a> data structure. Using a <code>Counter</code> (or even just a plain dictionary) that maps exponents to coefficients will automatically coalesce entries with the same exponent, just as you'd expect when writing a simplified polynomial. </p> <p>You can perform operations using a <code>Counter</code>, and then convert back to your list of pairs representation when finished using a function like this:</p> <pre><code>def counter_to_poly(c): p = [(coeff, exp) for exp, coeff in c.items() if coeff != 0] # sort by exponents in descending order p.sort(key = lambda pair: pair[1], reverse = True) return p </code></pre> <p>To add polynomials, you group together like-exponents and sum their coefficients.</p> <pre><code>def addpoly(p, q): r = collections.Counter() for coeff, exp in (p + q): r[exp] += coeff return counter_to_poly(r) </code></pre> <p>(In fact, if you were to stick with the Counter representation throughout, you could just <code>return p + q</code>).</p> <p>To multiply polynomials, you multiply each term from one polynomial pairwise with every term from the other. And furthermore, to multiply terms, you add exponents and multiply coefficients.</p> <pre><code>def mulpoly(p, q): r = collections.Counter() for (c1, e1), (c2, e2) in itertools.product(p, q): r[e1 + e2] += c1 * c2 return counter_to_poly(r) </code></pre>
1
2016-08-20T20:40:25Z
[ "python", "python-3.x", "polynomials" ]
How to calculate sum of two polynomials?
39,057,546
<p>For instance 3x^4 - 17x^2 - 3x + 5. Each term of the polynomial can be represented as a pair of integers (coefficient,exponent). The polynomial itself is then a list of such pairs like<br> <code>[(3,4), (-17,2), (-3,1), (5,0)]</code> for the polynomial as shown.</p> <p>Zero polynomial, 0, is represented as the empty list <code>[]</code>, since it has no terms with nonzero coefficients.</p> <p>I want to write two functions to add and multiply two input polynomials with the same representation of tuple (coefficient, exponent):</p> <ol> <li><code>addpoly(p1, p2)</code></li> <li><code>multpoly(p1, p2)</code></li> </ol> <p>Test Cases:</p> <ul> <li><p><code>addpoly([(4,3),(3,0)], [(-4,3),(2,1)])</code> <br> should give <code>[(2, 1),(3, 0)]</code></p></li> <li><p><code>addpoly([(2,1)],[(-2,1)])</code> <br> should give <code>[]</code></p></li> <li><p><code>multpoly([(1,1),(-1,0)], [(1,2),(1,1),(1,0)])</code> <br> should give <code>[(1, 3),(-1, 0)]</code></p></li> </ul> <p>Here is something that I started with but got completely struck!</p> <pre><code>def addpoly(p1, p2): (coeff1, exp1) = p1 (coeff2, exp2) = p2 if exp1 == exp2: coeff3 = coeff1 + coeff2 </code></pre>
0
2016-08-20T18:41:20Z
39,101,960
<p>I have come up with a solution but I'm unsure that it's optimized!</p> <pre><code> def addpoly(p1,p2): for i in range(len(p1)): for item in p2: if p1[i][1] == item[1]: p1[i] = ((p1[i][0] + item[0]),p1[i][1]) p2.remove(item) p3 = p1 + p2 for item in (p3): if item[0] == 0: p3.remove(item) return sorted(p3) </code></pre> <p>and the second one:-</p> <pre><code> def multpoly(p1,p2): for i in range(len(p1)): for item in p2: p1[i] = ((p1[i][0] * item[0]), (p1[i][1] + item[1])) p2.remove(item) return p1 </code></pre>
0
2016-08-23T12:59:48Z
[ "python", "python-3.x", "polynomials" ]
Does Boto3 encrypt the payload during transmission when invoking a lambda function?
39,057,569
<p>I am using the Python AWS API. I would like to invoke a lambda function from client code, but I have not been able to find documentation on whether the payload sent during invocation is encrypted. </p> <p>Can someone watching the network potentially snoop on the AWS invocation payload? Or is the payload transmitted over a secure channel? </p>
0
2016-08-20T18:43:41Z
39,058,104
<p>If you turn on the debug logging you should see how exactly is data transmitted. Or try <code>netstat</code> or Wireshark to see if it makes connection to port 443 rather than 80.</p> <p>From my experience with <code>boto3</code> and S3 (not Lambda) it uses HTTPS, which I would consider somewhat secure. I hope the certificates are verified...</p>
0
2016-08-20T19:49:25Z
[ "python", "amazon-web-services", "encryption", "aws-lambda", "boto3" ]
Preserve existing tables in database when running Flask-Migrate
39,057,587
<p>I have a database with existing tables. My code has a <code>User</code> model. I generated a revision using Flask-Migrate and ran it, and it deleted my existing tables while creating the user table. How can I run migrations without removing the existing tables?</p> <pre><code>from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'my_data' db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128)) if __name__ == '__main__': manager.run() </code></pre>
2
2016-08-20T18:45:39Z
39,065,980
<p>If you have existing tables in your database, and they don't have a corresponding model in your code, Alembic (Flask-Migrate) only knows that there is a difference between your database and your code. It can't know (by default) that you meant to leave those tables untouched.</p> <p>Pass an <a href="http://alembic.zzzcomputing.com/en/latest/api/runtime.html#alembic.runtime.environment.EnvironmentContext.configure.params.include_object" rel="nofollow"><code>include_object</code></a> function to the environment to effect what database objects Alembic will generate commands for. The following example skips the listed table names, but allows everything else.</p> <pre><code>def include_object(object, name, type_, reflected, compare_to): if type_ == 'table' and name in ('table', 'names', 'to', 'skip'): return False return True # in env.py context.configure( # ... include_object=include_object ) </code></pre>
1
2016-08-21T15:43:37Z
[ "python", "flask", "alembic" ]
Django jquery autocomplete giving an error
39,057,611
<p>I am developing a django application where I am using jquery autocomplete. I know that this question has been asked several times here but none of the solution is working for me. I am following this tutorial: <a href="http://flaviusim.com/blog/AJAX-Autocomplete-Search-with-Django-and-jQuery/" rel="nofollow">http://flaviusim.com/blog/AJAX-Autocomplete-Search-with-Django-and-jQuery/</a></p> <p>I have included this in my header:</p> <pre><code> &lt;script src="//code.jquery.com/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /&gt; </code></pre> <p>in this exact same order</p> <p>Then in my page, I have used:</p> <pre><code>{% extends "account/base.html" %} {% load i18n %} {% load bootstrap %} {% block body_class %}applications{% endblock %} {% block head_title %}{% trans "Change password" %}{% endblock %} {% block body %} &lt;form action="/create_recipe_rule/{{ recipe_pk }}/" method="post"&gt; {% csrf_token %} &lt;div class="form-group ui-widget"&gt; &lt;label for="{{ form.content.label }}"&gt;{{ form.content.label }}:&lt;/label&gt; &lt;textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="recipe_rule_content"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;script&gt; $(function() { $("#recipe_rule_content").autocomplete({ source: "/api/get_RuleStatement/", minLength: 2, }); }); &lt;/script&gt; &lt;input class="btn btn-default" type="submit" value="submit"&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>Can anyone suggest where am I going wrong?</p> <p>This is the error that I get in console:</p> <blockquote> <p>uncaught TypeError: $(...).autocomplete is not a function</p> </blockquote>
0
2016-08-20T18:48:27Z
39,058,298
<p>It look like Your code is executed before <code>jQueryUI</code> is loaded.</p> <p>Move Your </p> <pre><code>&lt;script&gt; $(function() { $("#recipe_rule_content").autocomplete({ source: "/api/get_RuleStatement/", minLength: 2, }); }); &lt;/script&gt; </code></pre> <p>to <code>&lt;head&gt;</code> after </p> <pre><code>&lt;script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"&gt;&lt;/script&gt; </code></pre> <p><strong>EDIT</strong></p> <p><code>code.jquery.com</code> have a problem with certificate. Try <strong>cdnjs</strong></p> <pre><code>&lt;script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.8.18/themes/base/jquery-ui.css"&gt; </code></pre>
0
2016-08-20T20:11:32Z
[ "javascript", "jquery", "python", "django", "autocomplete" ]
How to set permissions on a file (key) in AWS S3 using Python Boto Library?
39,057,643
<p>I'm experiencing a problem with permissions on a file in AWS S3 after updating it with a Python script using the Boto library.</p> <p>Here is the command that I'm using to update the file in S3:</p> <pre><code>k.set_contents_from_string(json.dumps(parsed_json, indent=4)) </code></pre> <p>The file gets updated correctly, however the permissions get changed which is very strange to me.</p> <p>Before updating the file, the permissions are:</p> <p><em>Granteed: awsprod Open/Download(checked) View Permissions(checked) Edit Permissions(checked)</em></p> <p>After updating the file, the permissions are gone and nothing shows under permissions when looking it through the AWS Dashboard/Console.</p> <p>After the permissions are removed, downloading the file is no longer possible and it fails every time.</p> <p>Via aws cli:</p> <pre><code>A client error (403) occurred when calling the HeadObject operation: Forbidden Completed 1 part(s) with ... file(s) remaining </code></pre> <p>Via aws console:</p> <pre><code>&lt;Error&gt; &lt;Code&gt;AccessDenied&lt;/Code&gt; &lt;Message&gt;Access Denied&lt;/Message&gt; &lt;RequestId&gt;A6E4AA2E3A3B9429&lt;/RequestId&gt; &lt;HostId&gt; 47gMhTpdFRAYm1cP4noivQlNEeB/cxHr2QFRXewNERdYcGcan2QU/fOVQ/upOl7Zp9fNIXLUnkk= &lt;/HostId&gt; &lt;/Error&gt; </code></pre> <p>My access is via IAM, and my user has the "AmazonS3FullAccess" policy giving me full access to S3.</p> <p>What is even more intriguing is that I have 2 AWS accounts, and the same script works well in one of them without changing the file permissions, and on the other account I have the problem described above. Now, you might think that I might have different policy access to S3 between these 2 aws accounts. I already checked that, and both accounts have the "AmazonS3FullAccess" policy.</p> <p>So, even if this is a problem on the AWS account setup, I would like to add to my script a line to set the file permissions back to the way it was before updating it. I think that should do the trick and allow me to download the file after running the Python script.</p> <p>How can I set file permissions (not bucket) in S3 using Boto?</p>
0
2016-08-20T18:51:58Z
39,058,291
<p>Set the <a href="http://boto.cloudhackers.com/en/latest/ref/s3.html#boto.s3.key.Key.set_contents_from_string" rel="nofollow">policy</a>, with one of the <a href="http://boto.cloudhackers.com/en/latest/s3_tut.html#setting-getting-the-access-control-list-for-buckets-and-keys" rel="nofollow">canned acl strings</a>, something like:</p> <pre><code>k.set_contents_from_string(json.dumps(parsed_json, indent=4), policy=&lt;ACL STRING&gt;) </code></pre>
0
2016-08-20T20:10:36Z
[ "python", "amazon-s3", "boto" ]
How to name pandas dataframe column based on the column contents
39,057,714
<p>I have this text file that I have to load up into a pandas dataframe. On loading the text, I discovered there are no column names. There are about 23 columns and the content of each column are different letters of the English alphabet. I want to rename each column based on which alphabets are in the column. For example, if 's', 'b', 'd' and 'f' are in column 1, i want to rename it 'CapSize' and if 's', 'r', 'g', 'f' and 'k' are in column 2 I like to give it the name 'Root'. </p> <p>I tried something like this but no way out.</p> <pre><code>for i in range(23): if (X.columns[0] == 'b' &amp; X.columns[0] == 'c' &amp; X.columns[0] == 'x'&amp; X.columns[0] == 'f' &amp; X.columns[0] == 'k' &amp; X.columns[0] == 's'): X.columns[0] = 'Capshape' print X.columns[0] </code></pre>
0
2016-08-20T19:00:42Z
39,058,215
<p>I am not entirely sure I get your question right, since letter 's' are both in CapSize and root, and do you mean it has to be conditional for each column separately?</p> <p>Otherwise, if I get it correctly it is something like this:</p> <pre><code>dt = pd.DataFrame({0:['fb', 'bc'], 1:['baab', 'cbc'], 2:['kaab', 'cbc']}) dt 0 1 2 0 fb baab kaab 1 bc cbc cbc </code></pre> <p>Get first letters into pd.Series</p> <pre><code>letters = pd.Series(dt.apply(lambda x: x.head(1).map(lambda y: y[0])).loc[0,:].values) letters 0 f 1 b 2 k dtype: object </code></pre> <p>Create a dict for mapping</p> <pre><code>mp = {x:'CapSize' for x in ['s', 'b', 'd' , 'f'] } mp.update({x:'Root' for x in [ 'r', 'g', 'f' , 'k']}) mp {'b': 'CapSize', 'd': 'CapSize', 'f': 'Root', 'g': 'Root', 'k': 'Root', 'r': 'Root', 's': 'CapSize'} </code></pre> <p>Map first letters using a dict</p> <pre><code>letters = letters.map(mp).tolist() letters ['Root', 'CapSize', 'Root'] dt.columns = letters dt Root CapSize Root 0 fb baab kaab 1 bc cbc cbc </code></pre>
0
2016-08-20T20:02:07Z
[ "python", "pandas" ]
I am receiving an error saying Unexpected EOF while parsing?
39,057,729
<p>I am using a Book called Python programming: An introduction to computer programming and I am stuck in a programming exercise in chapter 10. It asks for a program that displays a playing card after the user inserts the value of the card and its suit. Also, I should be using 3 methods plus two constructors, here they are:</p> <pre><code>__init__(self, rank, suit): getRank(self) getSuit(self) BJValue(self) __str__(self) </code></pre> <p>However, as I run it an error is displayed..... Here is my work:</p> <pre><code>from random import randrange class Card: def __init__(self, rank, suit):# This constructor creates the corresponding card according to their ranks: self.rank = rank # "d"=diamonts, "c"=clubs, "h"=hearts, or "s"=spades self.suit = suit def getRank(self):# Returns the rank of the card. ranks = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "King", "Queen", "Jack"] self.rank = ranks[self.rank] return self.rank def getSuit(self):# Returns the suit of the card. suits = ["diamons", "heart", "club", "spades"] # TRY TO MAKE THIS PIECE OF CODE MORE ABSTRACT!!!! if self.suit[0] == "d": self.suit = suits[0] elif self.suit[0] == "h": self.suit = suits[1] elif self.suit[0] == "c": self.suit = suits[2] elif self.suit[0] == "s": self.suit = suits[3] return self.suit# A suit in Blackjack means the symbol of the card. def BJValue(self):# Returns the Blackjack value of a card. # For example Aces count as 1 and face cards count as 10. while 0 &lt; self.rank &lt;= 10: if self.rank == "Ace": self.rank = 1 self.bjvalue = self.rank elif self.rank[0] == "King" or self.rank[0] == "Queen" or self.rank[0] == "Jack": self.rank = 10 self.bjvalue = self.rank else: self.bjvalue = self.rank return self.bjvalue def __str__(self):# Returns a string that names the card. For example "Ace of Spade". print("{0} of {1}".format(self.rank, self.suit) </code></pre> <p>I'm sorry for my Englis but is not my first language.</p>
-4
2016-08-20T19:02:39Z
39,057,810
<p>You're missing the close parentheses in the final <code>print</code> call.</p>
1
2016-08-20T19:11:41Z
[ "python" ]
I am receiving an error saying Unexpected EOF while parsing?
39,057,729
<p>I am using a Book called Python programming: An introduction to computer programming and I am stuck in a programming exercise in chapter 10. It asks for a program that displays a playing card after the user inserts the value of the card and its suit. Also, I should be using 3 methods plus two constructors, here they are:</p> <pre><code>__init__(self, rank, suit): getRank(self) getSuit(self) BJValue(self) __str__(self) </code></pre> <p>However, as I run it an error is displayed..... Here is my work:</p> <pre><code>from random import randrange class Card: def __init__(self, rank, suit):# This constructor creates the corresponding card according to their ranks: self.rank = rank # "d"=diamonts, "c"=clubs, "h"=hearts, or "s"=spades self.suit = suit def getRank(self):# Returns the rank of the card. ranks = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "King", "Queen", "Jack"] self.rank = ranks[self.rank] return self.rank def getSuit(self):# Returns the suit of the card. suits = ["diamons", "heart", "club", "spades"] # TRY TO MAKE THIS PIECE OF CODE MORE ABSTRACT!!!! if self.suit[0] == "d": self.suit = suits[0] elif self.suit[0] == "h": self.suit = suits[1] elif self.suit[0] == "c": self.suit = suits[2] elif self.suit[0] == "s": self.suit = suits[3] return self.suit# A suit in Blackjack means the symbol of the card. def BJValue(self):# Returns the Blackjack value of a card. # For example Aces count as 1 and face cards count as 10. while 0 &lt; self.rank &lt;= 10: if self.rank == "Ace": self.rank = 1 self.bjvalue = self.rank elif self.rank[0] == "King" or self.rank[0] == "Queen" or self.rank[0] == "Jack": self.rank = 10 self.bjvalue = self.rank else: self.bjvalue = self.rank return self.bjvalue def __str__(self):# Returns a string that names the card. For example "Ace of Spade". print("{0} of {1}".format(self.rank, self.suit) </code></pre> <p>I'm sorry for my Englis but is not my first language.</p>
-4
2016-08-20T19:02:39Z
39,057,821
<p>You've missed to close parenthesis at the end of last line, there is one opening for print method, but not closing at the end.</p>
0
2016-08-20T19:13:04Z
[ "python" ]
Does anyone know how to get rid of the black 'y' axis to the left in Matplotlib plot?
39,057,822
<p>After moving all of my 'y' axes to subplots I get an unwanted axis. It's the black one on the left. Does anyone know how to get rid of it? I'm sure it's getting plotted when I call the figure, however I'm not sure how to get rid of it. </p> <p><a href="http://i.stack.imgur.com/rhsaw.png" rel="nofollow"><img src="http://i.stack.imgur.com/rhsaw.png" alt="enter image description here"></a></p> <pre><code>def mpl_plot(self, plot_page, replot = 0): #Data stored in lists if plot_page == 1: #Plot 1st Page #plt0 = self.mplwidget.axes fig = self.mplwidget.figure #Add a figure if plot_page == 2: #Plot 2nd Page #plt0 = self.mplwidget_2.axes fig = self.mplwidget_2.figure #Add a figure if plot_page == 3: #Plot 3rd Page #plt0 = self.mplwidget_3.axes fig = self.mplwidget_3.figure #Add a figure #Clears Figure if data is roplotted if replot == 1: fig.clf() par0 = fig.add_subplot(111) par1 = fig.add_subplot(111) par2 = fig.add_subplot(111) #Add Axes plt = par0.twinx() ax1 = par1.twinx() ax2 = par2.twinx() impeller = str(self.comboBox_impellers.currentText()) #Get Impeller fac_curves = self.mpl_factory_specs(impeller) fac_lift = fac_curves[0] fac_power = fac_curves[1] fac_flow = fac_curves[2] fac_eff = fac_curves[3] fac_max_eff = fac_curves[4] fac_max_eff_bpd = fac_curves[5] fac_ranges = self.mpl_factory_ranges() min_range = fac_ranges[0] max_range = fac_ranges[1] #Plot Chart plt.hold(True) plt.plot(fac_flow, fac_lift, 'b', linestyle = "dashed", linewidth = 1) ax1.plot(fac_flow, fac_power, 'r', linestyle = "dashed", linewidth = 1) ax2.plot(fac_flow, fac_eff, 'g', linestyle = "dashed", linewidth = 1) #Move spines ax2.spines["right"].set_position(("outward", 25)) self.make_patch_spines_invisible(ax2) ax2.spines["right"].set_visible(True) #Plot x axis minor tick marks minorLocatorx = AutoMinorLocator() ax1.xaxis.set_minor_locator(minorLocatorx) ax1.tick_params(which='both', width= 0.5) ax1.tick_params(which='major', length=7) ax1.tick_params(which='minor', length=4, color='k') #Plot y axis minor tick marks minorLocatory = AutoMinorLocator() plt.yaxis.set_minor_locator(minorLocatory) plt.tick_params(which='both', width= 0.5) plt.tick_params(which='major', length=7) plt.tick_params(which='minor', length=4, color='k') #Make Border of Chart White fig.set_facecolor('white') #Plot Grid plt.grid(b=True, which='both', color='k', linestyle='-') #set shaded Area plt.axvspan(min_range, max_range, facecolor='#9BE2FA', alpha=0.5) #Yellow rectangular shaded area #Set Vertical Lines plt.axvline(fac_max_eff_bpd, color = '#69767A') #BEP MARKER *** Can change marker style if needed bep = fac_max_eff * 0.90 #bep is 90% of maximum efficiency point bep_corrected = bep * 0.90 # We knock off another 10% to place the arrow correctly on chart ax2.annotate('BEP', xy=(fac_max_eff_bpd, bep_corrected), xycoords='data', #Subtract 2.5 shows up correctly on chart xytext=(-50, 30), textcoords='offset points', bbox=dict(boxstyle="round", fc="0.8"), arrowprops=dict(arrowstyle="-|&gt;", shrinkA=0, shrinkB=10, connectionstyle="angle,angleA=0,angleB=90,rad=10"), ) #Set Scales plt.set_ylim(0,max(fac_lift) + (max(fac_lift) * 0.40)) #Pressure #plt.set_xlim(0,max(fac_flow)) ax1.set_ylim(0,max(fac_power) + (max(fac_power) * 0.40)) #Power ax2.set_ylim(0,max(fac_eff) + (max(fac_eff) * 0.40)) #Effiency plt.yaxis.tick_left() # Set Axes Colors plt.tick_params(axis='y', colors='b') ax1.tick_params(axis='y', colors='r') ax2.tick_params(axis='y', colors='g') # Set Chart Labels plt.yaxis.set_label_position("left") plt.set_xlabel("BPD") plt.set_ylabel("Feet" , color = 'b') #ax1.set_ylabel("BHP", color = 'r') #ax1.set_ylabel("Effiency", color = 'g') # Set tight layout fig.set_tight_layout # Since we moved Feet Axis to subplot, extra unneeded axis was created. This Removes it # Refresh fig.canvas.update() fig.canvas.draw() </code></pre>
1
2016-08-20T19:13:14Z
39,058,414
<p>Well it looks like you have three y-axes, referencing the one you want to not be shown, you could try adding:</p> <pre><code>ax.yaxis.set_tick_params(labelsize=0, length=0, which='major') </code></pre> <p>to just make invisible the labels and ticks. I think it's ax2 you want gone? </p>
0
2016-08-20T20:24:15Z
[ "python", "python-2.7", "matplotlib" ]
Generate create table sql with comment from migrations
39,057,829
<p>I have searched Django's documentation, but I can't find any information about adding comments to the sql generated by Django's <code>makemigrations</code> and <code>migrate</code> commands. </p> <p>Does any way can generate sql like this. Because my college insists he can know what the field mean for without read my code but using <code>SHOW CREATE TABLE</code> syntax. And he is working on another project that just need to read data from same database.</p> <pre><code>CREATE TABLE `gateway_order` ( `id` int(11) NOT NULL AUTO_INCREMENT, /* Order id */ `updated_datetime` datetime NOT NULL, /* Latest update time of order */ `created_datetime` datetime NOT NULL, /* Created time of order */ `product_name` varchar(255) NOT NULL, `description` varchar(255) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), ) ENGINE=InnoDB AUTO_INCREMENT=34848 DEFAULT CHARSET=utf8; </code></pre>
0
2016-08-20T19:14:15Z
39,325,234
<p>I am just looking for a method do such a thing in Django, but found Django didn't and won't have this feature:see: <a href="https://code.djangoproject.com/ticket/13867" rel="nofollow">https://code.djangoproject.com/ticket/13867</a></p> <p>So just use the following command to output SQL generated by Django.</p> <pre><code>python manage.py sqlmigrate app 0001 &gt; app001.sql </code></pre> <p>And next, edit <code>app001.sql</code> add comment for SQL sentences as following:</p> <pre><code>CREATE TABLE `gateway_order` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT "Order id", `updated_datetime` datetime NOT NULL COMMENT "Latest update time of order", `created_datetime` datetime NOT NULL COMMENT "Created time of order", `product_name` varchar(255) NOT NULL, `description` varchar(255) DEFAULT NULL, `user_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), ) ENGINE=InnoDB AUTO_INCREMENT=34848 DEFAULT CHARSET=utf8; </code></pre> <p>Then import the SQL to your database. </p> <pre><code>mysql -h127.0.0.1 -uroot -p --database yourdb &lt; app001.sql </code></pre> <p>and run</p> <pre><code>python manage.py migrate app --fake </code></pre> <p>to told Django, you've already create the SQL in database.</p> <p>If a better method found, please told me.</p>
0
2016-09-05T06:54:12Z
[ "python", "django" ]
Bug in my quick sort algorithm implementation
39,057,893
<p>Recently I was trying to implement the quicksort algorithm in Python, and I couldn't make it work properly. Even though the program sorts the sub-arrays, it's not being reflected on the main list. I'm new to programming, so can anyone help me to understand what part or concept I didn't do right?</p> <pre><code>def swap(arr, right, left): temp = arr[right] arr[right] = arr[left] arr[left] = temp def split_array(arr, right): left_half = arr[:right] right_half = arr[right:] a = (left_half, right_half) return a def quick_sort(arr): if len(arr) &gt;= 2: pivot = 0 left_mark = pivot + 1 right_mark = len(arr) - 1 stop = True while stop: while arr[pivot] &gt; arr[left_mark] and left_mark &lt; right_mark: left_mark += 1 while arr[pivot] &lt; arr[right_mark] and left_mark &lt; right_mark: right_mark -= 1 if left_mark &lt; right_mark: swap(arr, right_mark, left_mark) right_mark -= 1 left_mark += 1 else: if arr[pivot] &gt; arr[right_mark]: swap(arr, right_mark, pivot) stop = False left, right = split_array(arr, right_mark) quick_sort(left) quick_sort(right) return arr array = [8, 6, 1, 7, 0, 5, 4, 3, 2, 1] print(quick_sort(array)) </code></pre>
-1
2016-08-20T19:21:47Z
39,057,916
<p>You are exactly right! <code>left</code> and <code>right</code> are separate entities after <code>split_array</code>, not parts of the original <code>arr</code>. After <code>quick_sort(right)</code>, say <code>arr=left+right</code>. I think that will do it. (Need to check the case when there is only one element in either <code>left</code> or <code>right</code>.)</p>
0
2016-08-20T19:24:28Z
[ "python", "python-2.7", "sorting", "quicksort" ]
Bug in my quick sort algorithm implementation
39,057,893
<p>Recently I was trying to implement the quicksort algorithm in Python, and I couldn't make it work properly. Even though the program sorts the sub-arrays, it's not being reflected on the main list. I'm new to programming, so can anyone help me to understand what part or concept I didn't do right?</p> <pre><code>def swap(arr, right, left): temp = arr[right] arr[right] = arr[left] arr[left] = temp def split_array(arr, right): left_half = arr[:right] right_half = arr[right:] a = (left_half, right_half) return a def quick_sort(arr): if len(arr) &gt;= 2: pivot = 0 left_mark = pivot + 1 right_mark = len(arr) - 1 stop = True while stop: while arr[pivot] &gt; arr[left_mark] and left_mark &lt; right_mark: left_mark += 1 while arr[pivot] &lt; arr[right_mark] and left_mark &lt; right_mark: right_mark -= 1 if left_mark &lt; right_mark: swap(arr, right_mark, left_mark) right_mark -= 1 left_mark += 1 else: if arr[pivot] &gt; arr[right_mark]: swap(arr, right_mark, pivot) stop = False left, right = split_array(arr, right_mark) quick_sort(left) quick_sort(right) return arr array = [8, 6, 1, 7, 0, 5, 4, 3, 2, 1] print(quick_sort(array)) </code></pre>
-1
2016-08-20T19:21:47Z
39,058,365
<p>Change this:</p> <pre><code>left, right = split_array(arr, right_mark) quick_sort(left) quick_sort(right) </code></pre> <p>to this:</p> <pre><code>left, right = split_array(arr, right_mark) arr = quick_sort(left) + quick_sort(right) </code></pre> <p>Quicksort is typically implemented "in-place" to avoid copying arrays around. Your implementation creates a full copy of the array at each step instead and returns it, so you need to reassemble the pieces yourself.</p> <p><strong>UPDATE</strong></p> <p>A small change to make your algorithm in-place instead:</p> <pre><code>def quick_sort(arr, start=0, end=None): if end is None: end = len(arr)-1 if end &gt; start: pivot = start left_mark = start + 1 right_mark = end stop = True while stop: while arr[pivot] &gt; arr[left_mark] and left_mark &lt; right_mark: left_mark += 1 while arr[pivot] &lt; arr[right_mark] and left_mark &lt; right_mark: right_mark -= 1 if left_mark &lt; right_mark: swap(arr, right_mark, left_mark) right_mark -= 1 left_mark += 1 else: if arr[pivot] &gt; arr[right_mark]: swap(arr, right_mark, pivot) stop = False quick_sort(arr, start, right_mark - 1) quick_sort(arr, right_mark, end) array = [8, 6, 1, 7, 0, 5, 4, 3, 2, 1] quick_sort(array) # in-place print(array) # now sorted </code></pre> <p>IMO, the following is clearer and more closely matches the typical description of the algorithm:</p> <pre><code>def quick_sort(arr, start=0, end=None): if end is None: end = len(arr) - 1 if end &lt;= start: return pivot = arr[start] left_mark = start - 1 right_mark = end + 1 while left_mark &lt; right_mark: left_mark += 1 while arr[left_mark] &lt; pivot: left_mark += 1 right_mark -= 1 while arr[right_mark] &gt; pivot: right_mark -= 1 if left_mark &lt; right_mark: arr[left_mark], arr[right_mark] = arr[right_mark], arr[left_mark] quick_sort(arr, start, right_mark) quick_sort(arr, right_mark + 1, end) </code></pre>
2
2016-08-20T20:17:41Z
[ "python", "python-2.7", "sorting", "quicksort" ]
Numpy Matrix inside Python class exhibiting linked behaviour?
39,057,896
<p>If you make a class as such in Python:</p> <pre><code> import numpy as np class Foo: def __init__(self, data): self.data = data self.data_copy = self.copy(self.data) def copy(self, data): a = [] for e in data: a.append(e) return a def change(self, val): for i in range(0, len(self.data_copy)): self.data_copy[i] += val </code></pre> <p>And then create an instance of the class such as:</p> <pre><code>a = Foo([np.matrix([1,2,3]), np.matrix([5,6,7])]) </code></pre> <p>Now if we call the <code>a.change(np.matrix([5,5,2]))</code> function, which should only modify the <code>self.data_copy</code> list, the <code>self.data</code> list also updates with the changes. It appears, even after making a new list, the Numpy matrices in the two lists remain linked. </p> <p>This is a nice feature in some respects, but does not work had I passed in an ordinary Python list of numbers. Is this a bug, or just a side-effect of how Numpy matrices are copied? And if so, what's the best way to replicate the behaviour with ordinary Python lists?</p>
3
2016-08-20T19:21:52Z
39,057,930
<p>When you make your "copy", you're just making a new list that contains the same objects as the old list. That is, when you iterate through <code>data</code> you're iterating through references to the objects in it, and when you append <code>e</code> you're appending a reference rather than a new or copied object. Thus any changes to those objects will be visible in any other list that references them. It seems like what you want is copies of the actual matrices. To do this, in your <code>copy</code> method, instead of appending <code>e</code> append something like <code>numpy.array(e, copy=True)</code>. This will create true copies of the matrices and not just new references to the old ones.</p> <p>More generally, Python objects are effectively always passed by reference. This doesn't matter for immutable objects (strings, integers, tuples, etc), but for lists, dictionaries, or user defined classes that can mutate, you will need to make explicit copies. Often the built in <code>copy</code> module, or simply constructing a new object directly from the old, is what you want to do.</p> <p>Edit: I now see what you mean. I had slightly misunderstood your original question. You're referring to <code>+=</code> mutating the matrix objects rather than truly being <code>= self + other</code>. This is simply a fact of how <code>+=</code> works for most Python collection types. <code>+=</code> is in fact a separate method, distinct from assigning the result of adding. You will still see this behavior with normal Python lists.</p> <pre><code>a = [1, 2, 3] b = a b += [4] &gt;&gt;&gt; print(a) [1, 2, 3, 4] </code></pre> <p>You can see that the <code>+=</code> is mutating the original object rather than creating a new one and setting <code>b</code> to reference it. However if you do:</p> <pre><code>b = b + [4] &gt;&gt;&gt; print(a) [1, 2, 3] &gt;&gt;&gt; print(b) [1, 2, 3, 4] </code></pre> <p>This will have the desired behavior. The <code>+</code> operator for collections (lists, numpy arrays) does indeed return a new object, however <code>+=</code> usually just mutates the old one.</p>
4
2016-08-20T19:26:02Z
[ "python", "class", "numpy", "matrix" ]
How to access parent class variable in python?
39,057,964
<p>I want to access a class variable defined in the parent class constructor. Here is the code.</p> <pre><code>class A(object): def __init__(self): x = 0 class B(A): def __init__(self): super(B, self).__init__() def func(self): print self.x s = B() s.func() </code></pre> <p>This gives me error:</p> <pre><code>AttributeError: 'B' object has no attribute 'x' </code></pre> <p>If I try changing the <code>func()</code> to</p> <pre><code>def func(self): print x </code></pre> <p>then I get error:</p> <pre><code>NameError: global name 'x' is not defined </code></pre> <p>If I try changing the <code>func()</code> to</p> <pre><code>def func(self): print A.x </code></pre> <p>Then I get the error</p> <pre><code>AttributeError: type object 'A' has no attribute 'x' </code></pre> <p>Now I am running out of ideas.. What's the correct way to access that class variable <code>x</code> in the parent class <code>A</code>? Thanks!</p> <p>NOTE: I am working only on the "class B" part of my project, hence I can't really go modify class A and change the way variables are defined. That's the only constraint.</p>
0
2016-08-20T19:31:30Z
39,057,981
<p>You need to set it as <code>self.x = 0</code> instead of <code>x = 0</code> - otherwise it's just a local variable.</p> <p>If you cannot modify <code>A</code>, what you are trying to do is impossible - there is absolutely no way to access that value, not even with black magic (if your method was <em>called</em> by that method, you could probably do nasty things with the stack to get its value)</p>
1
2016-08-20T19:33:25Z
[ "python", "inheritance" ]
How to access parent class variable in python?
39,057,964
<p>I want to access a class variable defined in the parent class constructor. Here is the code.</p> <pre><code>class A(object): def __init__(self): x = 0 class B(A): def __init__(self): super(B, self).__init__() def func(self): print self.x s = B() s.func() </code></pre> <p>This gives me error:</p> <pre><code>AttributeError: 'B' object has no attribute 'x' </code></pre> <p>If I try changing the <code>func()</code> to</p> <pre><code>def func(self): print x </code></pre> <p>then I get error:</p> <pre><code>NameError: global name 'x' is not defined </code></pre> <p>If I try changing the <code>func()</code> to</p> <pre><code>def func(self): print A.x </code></pre> <p>Then I get the error</p> <pre><code>AttributeError: type object 'A' has no attribute 'x' </code></pre> <p>Now I am running out of ideas.. What's the correct way to access that class variable <code>x</code> in the parent class <code>A</code>? Thanks!</p> <p>NOTE: I am working only on the "class B" part of my project, hence I can't really go modify class A and change the way variables are defined. That's the only constraint.</p>
0
2016-08-20T19:31:30Z
39,057,989
<p>It must be <code>self.x</code>, not just <code>x</code>:</p> <pre><code>class A(object): def __init__(self): self.x = 0 </code></pre> <hr> <p>Just a quick note - even from other methods of <code>A</code> would be the <code>x</code> not accessible:</p> <pre><code>class A(object): def __init__(self): x = 0 def foo(self): print(self.x) # &lt;- will not work print(x) # &lt;- will utimately not work </code></pre>
2
2016-08-20T19:34:15Z
[ "python", "inheritance" ]
Register variable input to another task script file using Ansible
39,058,005
<p>Example My code is like below:</p> <pre><code> tasks: - set_fact: var: "{{ out1.stdout }}" - script: do_echo.py {{var}} </code></pre> <p>How can we use output variable which we get from one task in the next created script file without any appending that.</p> <p>In the above script I need to give the output of <code>out1</code> value as the input to the Python script file, so that I can use that input for the further process in my script. How can I do this?</p> <p>I know my script module is somewhat wrong,but please consider <code>do_echo</code> as a Python script file which I need execute next task with the input of that <code>var</code> of the previous task.</p> <p>I have also generic this <a href="https://github.com/ansible/ansible/issues/3467" rel="nofollow">https://github.com/ansible/ansible/issues/3467</a>, but I don't understand it, since I am new to Ansible.</p>
0
2016-08-20T19:35:52Z
39,059,326
<p>Your example is correct (if it was only a part of the play):</p> <pre><code>tasks: - script: do_echo.py Hello register: echo1_result - script: do_echo.py {{echo1_result.stdout}} register: echo2_result - debug: msg="{{echo2_result.stdout}}" </code></pre> <p>The first task will run your <code>do_echo.py</code> script, the result will be registered in <code>echo_result</code> variable and stdout will be under <code>stdout</code>.</p> <p>The second task executes the script again with a registered stdout (effectively with <code>Hello</code>) as an argument.</p> <p>The third task prints the result of the second execution of the script.</p> <hr> <p>Side note 1: Depending on the script, the variable should probably be quoted:</p> <pre><code>tasks: - script: do_echo.py Hello world register: echo1_result - script: do_echo.py "{{echo1_result.stdout}}" </code></pre> <p>Side note 2: The issue you referenced is three years old and closed. It's completely irrelevant to the current Ansible version.</p>
0
2016-08-20T22:41:05Z
[ "python", "ansible", "ansible-playbook" ]
Pandas duration of drawdown
39,058,034
<p>I am trying to calculate the duration of the drawdowns and the time to recovery for a stock series. I can calculate the drawdowns but am struggling to the the durations and recovery time for each drawdown. So far I have this code:</p> <pre><code>import pandas as pd import pickle import xlrd import numpy as np np.random.seed(0) df = pd.Series(np.random.randn(2500)*0.7+0.05, index=pd.date_range('1/1/2000', periods=2500, freq='D')) df= 100*(1+df/100).cumprod() df=pd.DataFrame(df) df.columns = ['close'] df['ret'] = df.close/df.close[0] df['modMax'] = df.ret.cummax() df['modDD'] = 1-df.ret.div(df['modMax']) groups = df.groupby(df['modMax']) dd = groups['modMax','modDD'].apply(lambda g: g[g['modDD'] == g['modDD'].max()]) top10dd = dd.sort_values('modDD', ascending=False).head(10) top10dd </code></pre> <p>This gives the 10 highest drawdowns of the series but I also want the duration of the drawdown and time to recovery.</p>
2
2016-08-20T19:39:10Z
39,080,464
<p>I solved the problem as follows:</p> <pre><code>def drawdown_group(df,index_list): group_max,dd_date = index_list ddGroup = df[df['modMax'] == group_max] group_length = len(ddGroup) group_dd = ddGroup['dd'].max() group_dd_length = len(ddGroup[ddGroup.index &lt;= dd_date]) group_start = ddGroup[0:1].index[0] group_end = ddGroup.tail(1).index[0] group_rec = group_length - group_dd_length #print (group_start,group_end,group_dd,dd_date,group_dd_length,group_rec,group_length) return group_start,group_end,group_max,group_dd,dd_date,group_dd_length,group_rec,group_length dd_col = ('start','end','peak', 'dd','dd_date','dd_length','dd_rec','tot_length') df_dd = pd.DataFrame(columns = dd_col) for i in range(1,10): index_list = top10dd[i-1:i].index.tolist()[0] #print(index_list) start,end,peak,dd,dd_date,dd_length,dd_rec,tot_length = drawdown_group(df,index_list) #print(start,end,dd,dd_date,dd_length,dd_rec,tot_length) df_dd.loc[i-1] = drawdown_group(df,index_list) </code></pre> <p>Produces this table: <a href="http://i.stack.imgur.com/dhERd.png" rel="nofollow"><img src="http://i.stack.imgur.com/dhERd.png" alt="enter image description here"></a></p>
1
2016-08-22T13:09:26Z
[ "python", "pandas" ]
Wm attributes and '-zoomed' doesn't work?
39,058,038
<p>I tried the same codes in Python2 and Python3 to see if the wm attributes would work in Python3 (I generally use Python2)</p> <pre><code>root.call("wm", "attributes", ".", "-zoomed", "True") root.attributes('-zoomed', True) root.wm_attributes('-zoomed', True) </code></pre> <p>but it gives me this error:</p> <pre><code>_tkinter.TclError: wrong # args: should be "wm attributes window ?-alpha ?double?? ?-transparentcolor ?color?? ?-disabled ?bool?? ?-fullscreen ?bool?? ?-toolwindow ?bool?? ?-topmost ?bool??" </code></pre> <p>I also tried these:</p> <pre><code>root.wm_state('-zoomed', True) root.state('-zoomed', True) </code></pre> <p>but gave me this error:</p> <pre><code>TypeError: wm_state() takes at most 2 arguments (3 given) </code></pre> <p>I'm using Windows 7 although it seems to work for @ParvizKarimli who is also using windows 7.</p> <p>Am I doing it wrong ? And is there an alternate method to maximize the window ?</p>
0
2016-08-20T19:39:49Z
39,058,096
<p>If you want to get fullscreen <i>without</i> title bar:<br> <code>root.attributes('-fullscreen', True)</code><br> And if you want to get fullscreen <i>with</i> title bar:<br> <code>root.wm_state('zoomed')</code> or just <code>root.state('zoomed')</code></p>
2
2016-08-20T19:47:55Z
[ "python", "tkinter", "window" ]
Special shell characters when opening in a file Python
39,058,074
<p>I have an interesting problem that I couldn't solve by googling.</p> <p>I'm trying to process each file inside of the directory. Some of the file names include special shell characters (<code>$</code>, <code>(</code>, <code>)</code> etc). A good example of such file name:</p> <p><code>FOO.-6.BAR.(nil).$0BAZ</code></p> <p>When I try to open this file in bash without any escaping I get an error <code>No matches found</code> therefore I <strong>need</strong> to escape it in a following fashion:</p> <p><code>FOO.-6.BAR.\(nil\).\$0BAZ</code></p> <p>As such it does open in bash (e.g. <code>cat</code>ing works).</p> <p>However, the problem is that even when I escape the file name in exact same fashion in python's code I still get <code>IOError: [Errno 2] No such file or directory</code>. </p> <p>I've also noticed that when I escape special characters (e.g. <code>f.replace('$', '\$')</code>) the final file name used in <code>open</code> is double prepending my slashes (<code>IOError: [Errno 2] No such file or directory: 'FOO.-6.BAR.\\(nil\\).\\$0BAZ'</code>) even though when I print the file name by hand (<code>print f</code>) I get valid <code>FOO.-6.BAR.\(nil\).\$0BAZ</code>.</p> <p>At this point I'm slightly out of ideas.</p>
1
2016-08-20T19:44:59Z
39,058,217
<p>You can probably solve this by looking at your directory with <code>os.listfiles('/path/to/stuff')</code>. Your file in there will come back with the \x characters in there. Try to open that after it. </p> <p>Potentially, depending on your further files, you may also want to use Unicode to look at the files. Do this using <code>os.listfiles(u'/path/to/stuff')</code>. </p> <p>Also see <a href="http://stackoverflow.com/questions/16510562/python-unable-to-rename-a-file-with-special-characters-in-the-file-name">Python - Unable to rename a file with special characters in the file name</a> which is a post that has a similar problem.</p>
0
2016-08-20T20:02:10Z
[ "python", "bash", "shell", "escaping", "character" ]
Special shell characters when opening in a file Python
39,058,074
<p>I have an interesting problem that I couldn't solve by googling.</p> <p>I'm trying to process each file inside of the directory. Some of the file names include special shell characters (<code>$</code>, <code>(</code>, <code>)</code> etc). A good example of such file name:</p> <p><code>FOO.-6.BAR.(nil).$0BAZ</code></p> <p>When I try to open this file in bash without any escaping I get an error <code>No matches found</code> therefore I <strong>need</strong> to escape it in a following fashion:</p> <p><code>FOO.-6.BAR.\(nil\).\$0BAZ</code></p> <p>As such it does open in bash (e.g. <code>cat</code>ing works).</p> <p>However, the problem is that even when I escape the file name in exact same fashion in python's code I still get <code>IOError: [Errno 2] No such file or directory</code>. </p> <p>I've also noticed that when I escape special characters (e.g. <code>f.replace('$', '\$')</code>) the final file name used in <code>open</code> is double prepending my slashes (<code>IOError: [Errno 2] No such file or directory: 'FOO.-6.BAR.\\(nil\\).\\$0BAZ'</code>) even though when I print the file name by hand (<code>print f</code>) I get valid <code>FOO.-6.BAR.\(nil\).\$0BAZ</code>.</p> <p>At this point I'm slightly out of ideas.</p>
1
2016-08-20T19:44:59Z
39,059,171
<p>You don't need to escape anything when opening the file from Python, because you aren't executing a shell command at all.</p> <pre><code>f = open("FOO.-6.BAR.(nil).$0BAZ") </code></pre> <p>The same is true of any file name returned by <code>os.listdir</code>:</p> <pre><code>for fname in os.listdir('.'): f = open(fname) </code></pre>
0
2016-08-20T22:18:44Z
[ "python", "bash", "shell", "escaping", "character" ]
Python Tkinter TypeError: 'int' object is not callable
39,058,125
<p>I am trying to take user input from main.py and then use that information to produce an output on runAnalytics. The problem that I am running into is that sometimes, the user input will produce a value of None (maybe null, I don't know) when the dividen_yield is not available and then my whole program will stop. It works flawlessly when there is a dividend-yield though.</p> <p>main.py</p> <pre><code>import runAnalytics from tkinter import * import os import centerWindow loadApplication = Tk() loadApplication.title("Stock Analytics") loadApplication.geometry("1080x720") label1 = Label(loadApplication, text = "Ticker") input1 = Entry(loadApplication) loadAnalytics = Button(loadApplication, text = "Load Analytics", command=lambda: runAnalytics.run(input1)) centerWindow.center(loadApplication) label1.pack() input1.pack() loadAnalytics.pack() loadApplication.mainloop() </code></pre> <p>runAnalytics.py</p> <pre><code>from yahoo_finance import Share from tkinter import * import os import centerWindow def run(input1): ticker = Share(input1.get()) loadAnalytics = Tk() loadAnalytics.title("$" + "ticker" + "Data") loadAnalytics.geometry("1080x720") centerWindow.center(loadAnalytics) ticker.refresh() if ticker.get_dividend_yield() is None: ticker.get_dividend_yield == 0 share_price = Label(loadAnalytics, text = "Share Price: " + ticker.get_price()).pack() prev_open = Label(loadAnalytics, text = "Previous Open: " + ticker.get_open()).pack() prev_close = Label(loadAnalytics, text = "Previous CLose: " + ticker.get_prev_close()).pack() dividend_yield = Label(loadAnalytics, text = "Dividend Yield: " + ticker.get_dividend_yield()).pack() year_low = Label(loadAnalytics, text = "52 Week Low: " + ticker.get_year_low()).pack() year_high = Label(loadAnalytics, text = "52 Week High: " + ticker.get_year_high()).pack() volume = Label(loadAnalytics, text = "Volume: " + ticker.get_volume()).pack() loadAnalytics.mainloop() </code></pre> <p>[Error] </p> <blockquote> <p>Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\MyName\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init__.py", line 1550, in <strong>call</strong> return self.func(*args) File "C:\Users\MyName\Documents\Python Projects\DataAnalytics\main.py", line 13, in loadAnalytics = Button(loadApplication, text = "Load Analytics", command=lambda: runAnalytics.run(input1)) File "C:\Users\MyName\Documents\Python Projects\DataAnalytics\runAnalytics.py", line 21, in run dividend_yield = Label(loadAnalytics, text = "Dividend Yield: " + ticker.get_dividend_yield()).pack() TypeError: 'int' object is not callable</p> </blockquote>
0
2016-08-20T19:51:50Z
39,058,557
<p>I tried to execute your code and got a different error than you got:</p> <pre><code>Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__ return self.func(*args) File "./main.py", line 15, in &lt;lambda&gt; loadAnalytics = Button(loadApplication, text = "Load Analytics", command=lambda: runAnalytics.run(input1)) File "/Users/Sven/temp/stackexchange/python/runAnalytics.py", line 22, in run dividend_yield = Label(loadAnalytics, text = "Dividend Yield: " + ticker.get_dividend_yield()).pack() TypeError: Can't convert 'NoneType' object to str implicitly </code></pre> <p>So I was not able to reproduce the traceback you got, but I changed your <code>Label</code> declaration in the <code>runAnalytics.py</code> file using Python's <a href="https://docs.python.org/3/library/string.html#formatspec" rel="nofollow">Format Specification Mini-Language</a> giving (<em>double line indentation for direct copy and paste of the snippet</em>):</p> <pre><code> share_price = Label(loadAnalytics,text='Share Price: {}'.format(ticker.get_price())).pack() prev_open = Label(loadAnalytics,text='Previous Open: {}'.format(ticker.get_open())).pack() prev_close = Label(loadAnalytics,text='Previous CLose: {}'.format(ticker.get_prev_close())).pack() dividend_yield = Label(loadAnalytics,text='Dividend Yield: {}'.format(ticker.get_dividend_yield())).pack() year_low = Label(loadAnalytics,text='52 Week Low: {}'.format(ticker.get_year_low())).pack() year_high = Label(loadAnalytics,text='52 Week High: {}'.format(ticker.get_year_high())).pack() volume = Label(loadAnalytics,text='Volume: {}'.format(ticker.get_volume())).pack() </code></pre> <p>This made the code runnable without any errors on my system since the <code>.format()</code> statement does all type conversions to the desired string output if necessary:</p> <p><a href="http://i.stack.imgur.com/8C2H6.png" rel="nofollow"><img src="http://i.stack.imgur.com/8C2H6.png" alt="GUI working"></a></p> <p>Note that there is a small typo in the Label's text which I did not fix (<code>CLose</code> should be <code>Close</code>)</p>
1
2016-08-20T20:46:57Z
[ "python", "tkinter", "typeerror", "python-3.5", "yahoo-finance" ]
how to change the black color to Red with opencv python
39,058,177
<p>how can you make it in python? I faced a problem with this line</p> <pre><code>img_rgb.Set(mask,cv2.Scalar(0,0,255)) </code></pre> <p>and here is the code :</p> <pre><code>import numpy as np import imutils import cv2 img_rgb = cv2.imread('figi.jpg') Conv_hsv_Gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU) img_rgb.Set(mask,cv2.Scalar(0,0,255)) cv2.imshow("imgOriginal", img_rgb) # show windows cv2.imshow("output", res) # show windows cv2.imshow("mask", mask) # show windows cv2.waitKey(0) </code></pre>
-1
2016-08-20T19:56:35Z
39,062,266
<p>The API for <code>mat.setTo()</code> is not available in Opencv module for python, this is due to the reason that in <code>C++</code> Opencv uses <code>cv::Mat</code> object as basic entity for image manipulation, However in Python there is no such <code>cv::Mat</code> concept, instead Python API for Opencv uses the well known library <code>numpy</code> for image manipulation operations, and numpy has a very beautiful syntax to set the values using a mask:</p> <pre><code>img_rgb[mask == 255] = [0, 0, 255] </code></pre> <p>Simply replacing this line with the <code>img_rgb.Set(mask,cv2.Scalar(0,0,255))</code> would get your work done.</p>
0
2016-08-21T08:22:28Z
[ "python", "opencv" ]
cubic spline to get smooth python line curve
39,058,276
<p>I need to make a smooth line in python using cubic spline, I followed the scipy tutorial and got a little confused. I used the following code: </p> <pre><code>import matplotlib.pyplot as plt from scipy import interpolate tck = interpolate.splrep(time, ca40Mass) plt.semilogy(time,ca40Mass,label='$^{40}$Ca') plt.xlabel('time [s]') plt.ylabel('fallback mass [$M_\odot$]') plt.xlim(20,60) plt.ylim(1.0e-3, 2.0e-1) plt.legend(loc=3) </code></pre> <p>and my plot still didn't smooth out, maybe I missed something, please help me fix this. My plot output is this:</p> <p><a href="http://i.stack.imgur.com/s1azU.png" rel="nofollow"><img src="http://i.stack.imgur.com/s1azU.png" alt="enter image description here"></a></p>
1
2016-08-20T20:08:43Z
39,058,381
<p>You are not using the interpolation.</p> <pre><code>time_spline = numpy.linspace(min(time),max(time),1000) ca40Mass_spline = interpolate.splev(time_spline, tck) plt.semilogy(time_spline, ca40Mass_spline, label='$^{40}$Ca') </code></pre>
2
2016-08-20T20:18:48Z
[ "python", "cubic-spline" ]
How do I get IPython 5 to work with SublimeREPL?
39,058,283
<p>I followed (actually, I authored) the instructions in <a href="https://gist.github.com/MattDMo/6cb1dfbe8a124e1ca5af" rel="nofollow">this gist</a> in order to modify the <code>ipy_repl.py</code> file that ships with <a href="https://packagecontrol.io/packages/SublimeREPL" rel="nofollow">SublimeREPL</a> in order to get it working with more recent versions of IPython at the time. However, I recently <code>pip</code> upgraded my IPython and Jupyter packages</p> <pre><code>pip3 install -U ipython jupyter </code></pre> <p>to the latest versions, and now I'm getting this error when trying to start an IPython session from Sublime:</p> <pre><code>Traceback (most recent call last): File "/home/mattdmo/.config/sublime-text-3/Packages/SublimeREPL/config/Python/ipy_repl.py", line 66, in &lt;module&gt; embedded_shell.initialize() File "&lt;decorator-gen-113&gt;", line 2, in initialize File "/usr/local/lib/python3.5/dist-packages/traitlets/config/application.py", line 74, in catch_config_error return method(app, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/jupyter_console/app.py", line 137, in initialize self.init_shell() File "/usr/local/lib/python3.5/dist-packages/jupyter_console/app.py", line 110, in init_shell client=self.kernel_client, File "/usr/local/lib/python3.5/dist-packages/traitlets/config/configurable.py", line 412, in instance inst = cls(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/jupyter_console/ptshell.py", line 252, in __init__ self.init_prompt_toolkit_cli() File "/usr/local/lib/python3.5/dist-packages/jupyter_console/ptshell.py", line 404, in init_prompt_toolkit_cli self.pt_cli = CommandLineInterface(app, eventloop=self._eventloop) File "/usr/local/lib/python3.5/dist-packages/prompt_toolkit/interface.py", line 80, in __init__ self.output = output or create_output() File "/usr/local/lib/python3.5/dist-packages/prompt_toolkit/shortcuts.py", line 124, in create_output ansi_colors_only=ansi_colors_only, term=term) File "/usr/local/lib/python3.5/dist-packages/prompt_toolkit/terminal/vt100_output.py", line 425, in from_pty assert stdout.isatty() AssertionError </code></pre> <p>I did a little digging, and at some point after early February 2016, the <a href="https://pypi.python.org/pypi/prompt_toolkit" rel="nofollow"><code>prompt_toolkit</code></a> module came into use in <code>jupyter_console</code>. While I assume this gives some advantages to the overall project, one disadvantage is that all text interfaces communicating with <code>jupyter_console</code> must be TTYs (a rather silly requirement, IMO), which a Sublime view is not.</p> <p>I was unable to find a way around this <strike>bug</strike> feature. Does anyone know how to work around this? </p>
1
2016-08-20T20:09:47Z
39,058,284
<p>Through a fortuitous series of events, I came upon an old Win7 VM that I hadn't used in several months, and which had not been upgraded, so the IPython REPL still worked. Through a little experimentation, I found that if I downgraded <code>ipython</code> to version 4.1.1 and <code>jupyter_console</code> to 4.1.0, everything worked fine:</p> <pre><code>pip3 install -U ipython==4.1.1 jupyter_console==4.1.0 </code></pre> <p>This isn't a perfect solution, as I am unable to play with the new features of IPython 5, but it's definitely preferable to staring at tracebacks all the time. I've updated <a href="https://gist.github.com/MattDMo/6cb1dfbe8a124e1ca5af" rel="nofollow">my gist</a> mentioned in the question to reflect this finding, and wanted to post this Q&amp;A here to get the word out, but I'm still looking for a way to get IPython 5 working.</p>
1
2016-08-20T20:09:47Z
[ "python", "ipython", "sublimetext", "jupyter", "sublimerepl" ]
Python play mp3/wav file audio(Pygame mixer)
39,058,335
<p>What is the best way to play mp3/wav file audio with Python?</p> <p>I tried to use pygame, it play the sound, but don't close propertly the file. So when i try to remove the file i get errors.(Yes, i call pygame.mixer.quit() , but the file is still used in another process)</p>
0
2016-08-20T20:15:15Z
39,230,496
<p>If you are open to using libraries other than <code>pygame</code> then you can use <a href="https://github.com/jiaaro/pydub" rel="nofollow">pydub</a> which is clean and easy. Below is an working example.</p> <p>For <code>wav</code> files </p> <pre><code>from pydub import AudioSegment from pydub.playback import play song = AudioSegment.from_wav("your_wav_file.wav") play(song) </code></pre> <p>For <code>MP3</code> files </p> <pre><code>song = AudioSegment.from_mp3("your_mp3_file.mp3") play(song) </code></pre>
1
2016-08-30T14:38:10Z
[ "python", "audio", "pygame", "mp3", "wav" ]
Override importing module's built-in functions from imported module
39,058,351
<p>I have an application where I would like to override certain functions when a condition occurs, for example:</p> <p>condition_check.py:</p> <pre><code>Flag = True import ctypes # An included library with Python install. import inspect def MsgBox(msg): ctypes.windll.user32.MessageBoxA(0, msg, 'MsgBox', 1) def check(): global print if Flag: def print(msg): MsgBox(msg) else: pass </code></pre> <p>main.py:</p> <pre><code>## works from condition_check import * MsgBox('this is msgbox') print('this is a print') ## does not work import condition_check condition_check.MsgBox('this is msgbox') print('this is a print') </code></pre> <p>I understand that the <code>condition_check.py</code> is overriding its own <code>print</code> instead of the <code>main.py</code>'s <code>print</code>. I believe <strong>inspect</strong> library could be used for this purpose but I am not able to lookup an example.</p>
2
2016-08-20T20:16:38Z
39,060,016
<p>I am assuming that you are using Python 3. If you are, you need merely set an attribute of the built-in module.</p> <pre><code>import builtins import ctypes original = builtins.print Flag = True def MsgBox(msg): ctypes.windll.user32.MessageBoxA(0, msg, 'MsgBox', 1) def check(): if Flag: builtins.print = MsgBox else: builtins.print = original </code></pre> <p>I will note, however, a couple things:</p> <ol> <li><p><code>Flag</code> is not a good name for two reasons: <strong>1</strong>, it isn't at all descriptive. A flag merely means that it is <code>True</code> or <code>False</code>; it doesn't say anything about what it is for. <strong>2</strong>, the official style guide for Python (PEP 8) recommends snake_case, not PascalCase for regular variables. PascalCase should be used only for classes.</p></li> <li><p>Wildcard imports (<code>from &lt;module&gt; import *</code>) are not recommended by PEP 8 because they make it unclear which names are present in the namespace, confusing both readers and automated tools. (Almost an exact quotation from the section on <a href="http://legacy.python.org/dev/peps/pep-0008/#imports" rel="nofollow">Imports</a>.)</p></li> <li><p>You don't need to override the <code>print</code> function. A better way is to override <code>sys.stdout</code> to a stream that controls where it goes:</p> <pre><code>import ctypes import sys def MsgBox(msg): ctypes.windll.user32.MessageBoxA(0, msg, 'MsgBox', 1) class Printer: def __init__(self, original, alternate, use_alternate): self.original = original self.alternate = alternate self.use_alternate = use_alternate def write(self, msg): if self.use_alternate: return self.alternate(msg) return self.original(msg) sys.stdout = printer = Printer(sys.stdout.write, MsgBox, True) </code></pre> <p>Your flag is then <code>printer.use_alternate</code>. Besides being much easier to control, this is also compatible with Python 2, even though the Python 2 <code>print</code> is a statement. This does have the slight disadvantage of keeping the newline that <code>print</code> adds, but one can always use an <code>alternate</code> of something like <code>lambda msg: MsgBox(msg.strip())</code></p></li> </ol>
1
2016-08-21T01:05:38Z
[ "python", "python-import" ]
Django reverse ordering with ListView
39,058,384
<p>I have implemented ordering in a generic ListView:</p> <pre><code>class CarList(LoginRequiredMixin, ListView): model = Car paginate_by = 30 ordering = 'car_id_internal' def get_ordering(self): return self.request.GET.get('ordering', 'car_id_internal') def get_context_data(self, *args, **kwargs): context = super(CarList, self).get_context_data(*args, **kwargs) context['current_order'] = self.get_ordering() return context </code></pre> <p>And in my template:</p> <pre><code>&lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;a href="{% url 'car_list' %}?ordering=car_id_internal"&gt;Internal car ID&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;a href="{% url 'car_list' %}?ordering=type"&gt;Type&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;a href="{% url 'car_list' %}?ordering=brand"&gt;Brand&lt;/a&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; </code></pre> <p>This works fine, however I would like for user to be able to reverse the order from ascending to descending when they click on the column header again. Is that possible with Django? I'm using Django 1.9.</p> <p>I hope someone can help.</p>
0
2016-08-20T20:19:24Z
39,059,065
<p>You need to use another variable for determining the asc/desc ordering. Depending on which is currently selected the template should alternate the links. In the view, you reverse the ordering by <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#order-by" rel="nofollow">adding a dash</a> before the field's name. Try the following:</p> <pre><code>class CarList(ListView): model = Car paginate_by = 30 ordering = 'car_id_internal' def get_ordering(self): self.order = self.request.GET.get('order', 'asc') selected_ordering = self.request.GET.get('ordering', 'car_id_internal') if self.order == "desc": selected_ordering = "-" + selected_ordering return selected_ordering def get_context_data(self, *args, **kwargs): context = super(CarList, self).get_context_data(*args, **kwargs) context['current_order'] = self.get_ordering() context['order'] = self.order return context </code></pre> <p>And the template:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;&lt;a href="{% url 'car_list' %}?ordering=car_id_internal&amp;order={% if order == 'desc' %}asc{% else %}desc{% endif %}"&gt;Internal car ID&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;a href="{% url 'car_list' %}?ordering=type&amp;order={% if order == 'desc' %}asc{% else %}desc{% endif %}"&gt;Type&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;a href="{% url 'car_list' %}?ordering=brand&amp;order={% if order == 'desc' %}asc{% else %}desc{% endif %}"&gt;Brand&lt;/a&gt;&lt;/th&gt; &lt;/tr&gt; {% for car in object_list %} &lt;tr&gt; &lt;td&gt;{{car.id}}&lt;/td&gt; &lt;td&gt;{{car.type}}&lt;/td&gt; &lt;td&gt;{{car.brand}}&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p></p>
1
2016-08-20T22:01:53Z
[ "python", "django", "python-3.x", "listview", "django-views" ]
Every time I reconnect to a MySQL database, all the tables are empty
39,058,505
<p>I'm very new to MySQL, so I started by using www.freesqldatabase.com to set up a database. Whenever I connect to it, I can set up tables and databases that will persist over connections, but any data I input is unique to that connection. Even if I'm viewing the database via DataGrip, if I add a row to a table I can't view it when I refresh datagrip, but my Python program can retrieve the data it just created from the database. When I retrieve a new connection to the database, however, none of the rows in the tables exist.</p> <p>For example, on my auth table (which has two keys: "id" and "token"), I would do:</p> <pre><code>insert into auth values ('id', 'token') select id from auth where token = 'token' </code></pre> <p>And as a result I would get 'id'. But when I start a new connection to the database and do</p> <pre><code>select id from auth where token = 'token' </code></pre> <p>It get back that none exist. I do that same request in DataGrip, same username/password/ip/database, and I get the same error.</p> <p>I've also tried doing this on Google Cloud SQL service, but I get the same exact issues. So it's not an issue with the server I'm using.</p> <p>What could be causing this?</p>
1
2016-08-20T20:38:25Z
39,058,744
<p>I set autocommit to true when I connected to my database, and that solved my issue.</p>
2
2016-08-20T21:11:18Z
[ "python", "mysql", "sql", "database", "datagrip" ]
Every time I reconnect to a MySQL database, all the tables are empty
39,058,505
<p>I'm very new to MySQL, so I started by using www.freesqldatabase.com to set up a database. Whenever I connect to it, I can set up tables and databases that will persist over connections, but any data I input is unique to that connection. Even if I'm viewing the database via DataGrip, if I add a row to a table I can't view it when I refresh datagrip, but my Python program can retrieve the data it just created from the database. When I retrieve a new connection to the database, however, none of the rows in the tables exist.</p> <p>For example, on my auth table (which has two keys: "id" and "token"), I would do:</p> <pre><code>insert into auth values ('id', 'token') select id from auth where token = 'token' </code></pre> <p>And as a result I would get 'id'. But when I start a new connection to the database and do</p> <pre><code>select id from auth where token = 'token' </code></pre> <p>It get back that none exist. I do that same request in DataGrip, same username/password/ip/database, and I get the same error.</p> <p>I've also tried doing this on Google Cloud SQL service, but I get the same exact issues. So it's not an issue with the server I'm using.</p> <p>What could be causing this?</p>
1
2016-08-20T20:38:25Z
39,058,959
<p>Try to execute</p> <pre><code>insert into auth values ('id', 'token'); commit; </code></pre>
1
2016-08-20T21:44:19Z
[ "python", "mysql", "sql", "database", "datagrip" ]
How to insert each element of a character list into a matrix in python
39,058,538
<p>How can I insert each element of a character list into a matrix (mxn) I have this code in python</p> <pre><code>key = raw_input('Key: ') text = raw_input('Text: ') text_c = list(text) while ' ' in text_c: text_c.remove(' ') columns = len(key) rows = int(math.ceil(float(len(text_c)) / float(len(key))) ) matrix = [] for i in range(rows): matrix.append([]) for j in range(columns): matrix[i].append(None) </code></pre> <p>Now, I want to insert each element from the text_c to the matrix. No matter if that matrix does not fill. How can I do this. Thanks (sorry for my bad english)</p>
1
2016-08-20T20:43:41Z
39,059,472
<p>You can achieve this by combining some list comprehensions as follows:</p> <pre><code>number_columns = 6 sample_string = 'abcdefghijklmnopqrstuvwxyzabcdefgh' l = [list(sample_string[i:i+number_columns]) for i in range(0, len(sample_string), number_columns)] matrix = [s if len(s) == number_columns else s+[None]*(number_columns-len(s)) for s in l] </code></pre> <p>giving for <code>matrix</code>:</p> <pre><code>[['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p', 'q', 'r'], ['s', 't', 'u', 'v', 'w', 'x'], ['y', 'z', 'a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h', None, None]] </code></pre> <p>First of all we slice the <code>sample_string</code> to substrings of the desired length (number of columns) which are converted to lists after slicing.</p> <p>In the sample code I provided <code>sample_string</code> is not evenly divisible by the given <code>number_colums</code> meaning that the last list of the substring <code>efgh</code> does not have the desired length of <code>number_columns</code>. In order to get that fixed we need to check if the length of each list is as desired. If not, we are appending the needed amount of <code>None</code> elements.</p> <p>In order to get rid of any spaces we need to extend the code by</p> <pre><code>sample_string = sample_string.replace(' ', '') </code></pre> <p>which would replace any spaces with an empty string. So</p> <pre><code>number_columns = 6 sample_string = 'this is a sample string' sample_string = sample_string.replace(' ', '') l = [list(sample_string[i:i+number_columns]) for i in range(0, len(sample_string), number_columns)] matrix = [s if len(s) == number_columns else s+[None]*(number_columns-len(s)) for s in l] </code></pre> <p>would lead to</p> <pre><code>[['t', 'h', 'i', 's', 'i', 's'], ['a', 's', 'a', 'm', 'p', 'l'], ['e', 's', 't', 'r', 'i', 'n'], ['g', None, None, None, None, None]] </code></pre>
1
2016-08-20T23:05:47Z
[ "python", "list", "matrix" ]
How to select an element with selenium?
39,058,556
<p>I am trying to get the href. Its a next page button. I select element by <code>class_name = next</code>. This is my code:</p> <pre><code>elem = browser.find_element_by_class_name('next').click() </code></pre> <p>An error comes up saying <code>Element is not clickable at point (801, 553)</code> I think this is happening because the selected element is the <code>&lt;li&gt;</code> tag, and it has no <code>on_click()</code> method.</p> <p>How can I get the onclick of <code>&lt;a&gt;</code> tag? It has no id or class.</p> <p>This is the HTML:</p> <pre><code>&lt;li id="next_pag_1" class="next"&gt; &lt;a href="http://www.infoempleo.com/ofertas-internacionales/pagina_2/" onclick="paginarDatos($(this).parent('#pagination li').attr('id')); return false;"&gt; &lt;span class="icon-chevron-right"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt;` </code></pre> <p>I am trying to scrape this page: <a href="http://www.infoempleo.com/ofertas-internacionales/" rel="nofollow">http://www.infoempleo.com/ofertas-internacionales/</a> And want to click on the next page using selenium. Any help will be much appreciated. </p>
0
2016-08-20T20:46:47Z
39,058,587
<p>Try</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC element = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By. XPATH, '//li[@id="next_pag_1"]/a'))) element.click() </code></pre>
1
2016-08-20T20:50:27Z
[ "python", "selenium" ]
How to select an element with selenium?
39,058,556
<p>I am trying to get the href. Its a next page button. I select element by <code>class_name = next</code>. This is my code:</p> <pre><code>elem = browser.find_element_by_class_name('next').click() </code></pre> <p>An error comes up saying <code>Element is not clickable at point (801, 553)</code> I think this is happening because the selected element is the <code>&lt;li&gt;</code> tag, and it has no <code>on_click()</code> method.</p> <p>How can I get the onclick of <code>&lt;a&gt;</code> tag? It has no id or class.</p> <p>This is the HTML:</p> <pre><code>&lt;li id="next_pag_1" class="next"&gt; &lt;a href="http://www.infoempleo.com/ofertas-internacionales/pagina_2/" onclick="paginarDatos($(this).parent('#pagination li').attr('id')); return false;"&gt; &lt;span class="icon-chevron-right"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/li&gt;` </code></pre> <p>I am trying to scrape this page: <a href="http://www.infoempleo.com/ofertas-internacionales/" rel="nofollow">http://www.infoempleo.com/ofertas-internacionales/</a> And want to click on the next page using selenium. Any help will be much appreciated. </p>
0
2016-08-20T20:46:47Z
39,064,421
<p>Its Chrome browser that is causing the problem. To be fair to the user Chrome clicks the element right in the center. Some elements are not clickable in the center. So, this is what I did:</p> <pre><code>elem = browser.find_element_by_class_name('next') action = ActionChains(browser) action.move_to_element_with_offset(elem, 30, 20) action.click() action.perform() </code></pre> <p>I move to the element with offset <code>(elem, 30, 20)</code>. The element is 36x36 so 30x20 is not in the middle of the element. Then using ActionChains perform the click and it works.</p>
0
2016-08-21T12:55:01Z
[ "python", "selenium" ]
Group rows based on range python
39,058,574
<p>I have a large text file where I am trying to group the first column based on intervals of 200. In the example code below, the first four rows would be in a group, the next three rows in a different group, and the last row in a separate group. My thought is to group them based on a for loop with a condition that adds 200, but haven't been able to get it to work.</p> <pre><code>000008 34.576 -87.234 000025 34.825 -87.935 000123 35.935 -86.344 000154 34.395 -86.903 000234 35.219 -86.945 000322 34.240 -86.527 000359 34.893 -87.573 000412 35.291 -87.392 </code></pre> <p>Once I have them grouped, I would like to check to see if the last two columns are within a specified range. If so, then write those rows to a new output file. Any help would be appreciated!</p>
-1
2016-08-20T20:49:19Z
39,058,731
<p>You could divide the value by 200 to get a key for <code>groupby</code>:</p> <pre><code>&gt;&gt;&gt; rows = '''000008 34.576 -87.234 000025 34.825 -87.935 000123 35.935 -86.344 000154 34.395 -86.903 000234 35.219 -86.945 000322 34.240 -86.527 000359 34.893 -87.573 000412 35.291 -87.392'''.splitlines() &gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; for _, group in groupby(rows, key=lambda row: int(row.split()[0]) // 200): print(list(group)) ['000008 34.576 -87.234', '000025 34.825 -87.935', '000123 35.935 -86.344', '000154 34.395 -86.903'] ['000234 35.219 -86.945', '000322 34.240 -86.527', '000359 34.893 -87.573'] ['000412 35.291 -87.392'] </code></pre> <p>If the number always has six digits, you can use <code>int(row[:6]) // 200</code> instead.</p>
1
2016-08-20T21:08:56Z
[ "python", "rows" ]
How to write in txt file and find common words in message history from slack in Python?
39,058,596
<p>Please help me to write in txt file slack message history and find common words in it. In my code example I have to problems: 1) Only first message is written in the file. 2) Counter works for each message seperately not for all message history.</p> <pre><code>from slackclient import SlackClient from collections import Counter import re sc = SlackClient('token') channel = "C200SFJNR" def history(): history_call = sc.api_call("channels.history", channel=channel, count=1000) if history_call.get('ok'): return history_call['messages'] return None history = history() for c in history: text=(c['text']) with open("out.txt", 'w') as f: f.write(text) words = re.findall(r'\w+', text) common = Counter(words).most_common(10) print(common) </code></pre>
-1
2016-08-20T20:51:38Z
39,058,813
<p>Your second question is easily answered without a knowledge of slackclient. Your reference to Counter is in a loop. Hence, each time you reference it a new instance of it is created and the old one is lost. What you want is to create an instance of Counter before you enter the loop, add items to it within the loop and then after you exit the loop make the call on most_common to obtain that information.</p>
1
2016-08-20T21:21:14Z
[ "python", "counter", "slack-api" ]
Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?
39,058,641
<p>Let's say I want to implement Numpy's</p> <pre><code>x[:] += 1 </code></pre> <p>in Cython. I could write</p> <pre><code>@cython.boundscheck(False) @cython.wraparoundcheck(False) def add1(np.ndarray[np.float32_t, ndim=1] x): cdef unsigned long i for i in range(len(x)): x[i] += 1 </code></pre> <p>However, this only works with <code>ndim = 1</code>. I could use</p> <pre><code>add1(x.reshape(-1)) </code></pre> <p>but this only works with contiguous <code>x</code>.</p> <p><strong>Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?</strong></p> <p>(<em>Reimplementing this particular operation in Cython doesn't make sense, as the above Numpy's code should be as fast as it gets -- I'm just using this as a simple example</em>)</p> <p><strong>UPDATE:</strong></p> <p>I benchmarked the proposed solutions:</p> <pre><code>@cython.boundscheck(False) @cython.wraparound(False) def add1_flat(np.ndarray x): cdef unsigned long i for i in range(x.size): x.flat[i] += 1 @cython.boundscheck(False) @cython.wraparound(False) def add1_nditer(np.ndarray x): it = np.nditer([x], op_flags=[['readwrite']]) for i in it: i[...] += 1 </code></pre> <p>The second function requires <code>import numpy as np</code> in addition to <code>cimport</code>. The results are:</p> <pre><code>a = np.zeros((1000, 1000)) b = a[100:-100, 100:-100] %timeit b[:] += 1 1000 loops, best of 3: 1.31 ms per loop %timeit add1_flat(b) 1 loops, best of 3: 316 ms per loop %timeit add1_nditer(b) 1 loops, best of 3: 1.11 s per loop </code></pre> <p>So, they are 300 and 1000 times slower than Numpy.</p> <p><strong>UPDATE 2:</strong></p> <p>The <code>add11</code> version uses a <code>for</code> loop inside of a <code>for</code> loop, and so doesn't iterate the array as if it were flat. However, it is as fast as Numpy in this case:</p> <pre><code>%timeit add1.add11(b) 1000 loops, best of 3: 1.39 ms per loop </code></pre> <p>On the other hand, <code>add1_unravel</code>, one of the proposed solutions, fails to modify the contents of <code>b</code>.</p>
2
2016-08-20T20:57:13Z
39,058,684
<p>You could try using the <code>flat</code> attribute of the <code>ndarray</code>, which provides an iterator over the flattened array object. It always iterates in C-major ordering, with the last index varying the fastest. Something like:</p> <pre><code>for i in range(x.size): x.flat[i] += 1 </code></pre>
1
2016-08-20T21:03:32Z
[ "python", "performance", "numpy", "cython" ]
Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?
39,058,641
<p>Let's say I want to implement Numpy's</p> <pre><code>x[:] += 1 </code></pre> <p>in Cython. I could write</p> <pre><code>@cython.boundscheck(False) @cython.wraparoundcheck(False) def add1(np.ndarray[np.float32_t, ndim=1] x): cdef unsigned long i for i in range(len(x)): x[i] += 1 </code></pre> <p>However, this only works with <code>ndim = 1</code>. I could use</p> <pre><code>add1(x.reshape(-1)) </code></pre> <p>but this only works with contiguous <code>x</code>.</p> <p><strong>Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?</strong></p> <p>(<em>Reimplementing this particular operation in Cython doesn't make sense, as the above Numpy's code should be as fast as it gets -- I'm just using this as a simple example</em>)</p> <p><strong>UPDATE:</strong></p> <p>I benchmarked the proposed solutions:</p> <pre><code>@cython.boundscheck(False) @cython.wraparound(False) def add1_flat(np.ndarray x): cdef unsigned long i for i in range(x.size): x.flat[i] += 1 @cython.boundscheck(False) @cython.wraparound(False) def add1_nditer(np.ndarray x): it = np.nditer([x], op_flags=[['readwrite']]) for i in it: i[...] += 1 </code></pre> <p>The second function requires <code>import numpy as np</code> in addition to <code>cimport</code>. The results are:</p> <pre><code>a = np.zeros((1000, 1000)) b = a[100:-100, 100:-100] %timeit b[:] += 1 1000 loops, best of 3: 1.31 ms per loop %timeit add1_flat(b) 1 loops, best of 3: 316 ms per loop %timeit add1_nditer(b) 1 loops, best of 3: 1.11 s per loop </code></pre> <p>So, they are 300 and 1000 times slower than Numpy.</p> <p><strong>UPDATE 2:</strong></p> <p>The <code>add11</code> version uses a <code>for</code> loop inside of a <code>for</code> loop, and so doesn't iterate the array as if it were flat. However, it is as fast as Numpy in this case:</p> <pre><code>%timeit add1.add11(b) 1000 loops, best of 3: 1.39 ms per loop </code></pre> <p>On the other hand, <code>add1_unravel</code>, one of the proposed solutions, fails to modify the contents of <code>b</code>.</p>
2
2016-08-20T20:57:13Z
39,058,906
<p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html</a></p> <p>Is a nice tutorial on using <code>nditer</code>. It ends with a <code>cython</code> version. <code>nditer</code> is meant to be the all purpose array(s) iterator in numpy <code>c</code> level code.</p> <p>There are also good array examples on the Cython memoryview page:</p> <p><a href="http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html" rel="nofollow">http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html</a></p> <p><a href="http://docs.scipy.org/doc/numpy/reference/c-api.iterator.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/c-api.iterator.html</a></p> <p>The data buffer of an <code>ndarray</code> is a flat buffer. So regardless of the array's shape and strides, you can iterate over the whole buffer in a flat <code>c</code> pointer fashion. But things like <code>nditer</code> and <code>memoryview</code> take care of the element size details. So in <code>c</code> level coding it is actually easier to step through all the elements in a flat fashion than it is to step by rows - going by rows has to take into account the row stride.</p> <p>This runs in Python, and I think it will translate nicely into cython (I don't have that setup on my machine at the moment):</p> <pre><code>import numpy as np def add1(x): it = np.nditer([x], op_flags=[['readwrite']]) for i in it: i[...] += 1 return it.operands[0] x = np.arange(10).reshape(2,5) y = add1(x) print(x) print(y) </code></pre> <p><a href="https://github.com/hpaulj/numpy-einsum/blob/master/sop.pyx" rel="nofollow">https://github.com/hpaulj/numpy-einsum/blob/master/sop.pyx</a> is a sum-of-products script that I wrote a while back to simulate <code>einsum</code>.</p> <p>The core of its <code>w = sop(x,y)</code> calculation is:</p> <pre><code>it = np.nditer(ops, flags, op_flags, op_axes=op_axes, order=order) it.operands[nop][...] = 0 it.reset() for xarr, yarr, warr in it: x = xarr y = yarr w = warr size = x.shape[0] for i in range(size): w[i] = w[i] + x[i] * y[i] return it.operands[nop] </code></pre> <p>===================</p> <p>copying ideas from the <code>nditer.html</code> document, I got a version of <code>add1</code> that is only half the speed of the native <code>numpy</code> <code>a+1</code>. The naive <code>nditer</code> (above) isn't much faster in <code>cython</code> than in <code>python</code>. A lot of the speedup may be due to the <code>external loop</code>.</p> <pre><code>@cython.boundscheck(False) def add11(arg): cdef np.ndarray[double] x cdef int size cdef double value it = np.nditer([arg], flags=['external_loop','buffered'], op_flags=[['readwrite']]) for xarr in it: x = xarr size = x.shape[0] for i in range(size): x[i] = x[i]+1.0 return it.operands[0] </code></pre> <p>I also coded this <code>nditer</code> in python with a print of <code>size</code>, and found that it iterated on your <code>b</code> with 78 blocks of size 8192 - that's a buffer size, not some characteristic of <code>b</code> and its data layout.</p> <pre><code>In [15]: a = np.zeros((1000, 1000)) In [16]: b = a[100:-100, 100:-100] In [17]: timeit add1.add11(b) 100 loops, best of 3: 4.48 ms per loop In [18]: timeit b[:] += 1 100 loops, best of 3: 8.76 ms per loop In [19]: timeit add1.add1(b) # for the unbuffered nditer 1 loop, best of 3: 3.1 s per loop In [21]: timeit add1.add11(a) 100 loops, best of 3: 5.44 ms per loop </code></pre>
2
2016-08-20T21:33:06Z
[ "python", "performance", "numpy", "cython" ]
Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?
39,058,641
<p>Let's say I want to implement Numpy's</p> <pre><code>x[:] += 1 </code></pre> <p>in Cython. I could write</p> <pre><code>@cython.boundscheck(False) @cython.wraparoundcheck(False) def add1(np.ndarray[np.float32_t, ndim=1] x): cdef unsigned long i for i in range(len(x)): x[i] += 1 </code></pre> <p>However, this only works with <code>ndim = 1</code>. I could use</p> <pre><code>add1(x.reshape(-1)) </code></pre> <p>but this only works with contiguous <code>x</code>.</p> <p><strong>Does Cython offer any reasonably easy and efficient way to iterate Numpy arrays as if they were flat?</strong></p> <p>(<em>Reimplementing this particular operation in Cython doesn't make sense, as the above Numpy's code should be as fast as it gets -- I'm just using this as a simple example</em>)</p> <p><strong>UPDATE:</strong></p> <p>I benchmarked the proposed solutions:</p> <pre><code>@cython.boundscheck(False) @cython.wraparound(False) def add1_flat(np.ndarray x): cdef unsigned long i for i in range(x.size): x.flat[i] += 1 @cython.boundscheck(False) @cython.wraparound(False) def add1_nditer(np.ndarray x): it = np.nditer([x], op_flags=[['readwrite']]) for i in it: i[...] += 1 </code></pre> <p>The second function requires <code>import numpy as np</code> in addition to <code>cimport</code>. The results are:</p> <pre><code>a = np.zeros((1000, 1000)) b = a[100:-100, 100:-100] %timeit b[:] += 1 1000 loops, best of 3: 1.31 ms per loop %timeit add1_flat(b) 1 loops, best of 3: 316 ms per loop %timeit add1_nditer(b) 1 loops, best of 3: 1.11 s per loop </code></pre> <p>So, they are 300 and 1000 times slower than Numpy.</p> <p><strong>UPDATE 2:</strong></p> <p>The <code>add11</code> version uses a <code>for</code> loop inside of a <code>for</code> loop, and so doesn't iterate the array as if it were flat. However, it is as fast as Numpy in this case:</p> <pre><code>%timeit add1.add11(b) 1000 loops, best of 3: 1.39 ms per loop </code></pre> <p>On the other hand, <code>add1_unravel</code>, one of the proposed solutions, fails to modify the contents of <code>b</code>.</p>
2
2016-08-20T20:57:13Z
39,061,741
<p>With <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow">numpy.ravel</a></p> <blockquote> <p>numpy.ravel(a, order='C')</p> <p>Return a contiguous flattened array.</p> <p>A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.</p> </blockquote> <pre><code>@cython.boundscheck(False) @cython.wraparound(False) def add1_ravel(np.ndarray xs): cdef unsigned long i cdef double[::1] aview narray = xs.ravel() aview = narray for i in range(aview.shape[0]): aview[i] += 1 # return xs if the memory is shared if not narray.flags['OWNDATA'] or np.may_share_memory(xs, narray): return xs # otherwise new array reshaped shape = tuple(xs.shape[i] for i in range(xs.ndim)) return narray.reshape(shape) </code></pre>
0
2016-08-21T07:11:37Z
[ "python", "performance", "numpy", "cython" ]
wxPython : Adding an about box.
39,058,783
<p>I'm creating a wxPython soundboard and was wondering how to implement an About Box. The goal is to press an About button on the wxPython File menu and generate an About Box. </p> <p>This is my code so far: </p> <pre><code>import wx import os import pygame pygame.init() ##SOUNDS## goliathwav = pygame.mixer.Sound("goliath.wav") channelopen = pygame.mixer.Sound("channelopen.wav") ##SOUNDS## class windowClass(wx.Frame): def __init__(self, *args, **kwargs): super(windowClass,self).__init__(*args,**kwargs) self.__basicGUI() def __basicGUI(self): panel = wx.Panel(self) menuBar = wx.MenuBar() fileButton = wx.Menu() editButton = wx.Menu() aboutBox = wx.MessageDialog(None, "Created by Kommander000(cyrex)") answer=aboutBox.ShowModal() aboutBox.Destroy() aboutButton = wx.Menu() exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...') aboutItem = aboutButton.Append(wx.ID_ABOUT, "About") menuBar.Append(fileButton, 'File') menuBar.Append(editButton, 'Edit') menuBar.Append(aboutButton, 'About this program') self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.__quit, exitItem) self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, aboutBox) self.__sound_dict = { "Goliath" : "goliath.wav", "Goliath2" : "channelopen.wav" } self.__sound_list = sorted(self.__sound_dict.keys()) self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150)) for i in self.__sound_list: self.__list.Append(i) self.__list.Bind(wx.EVT_LISTBOX,self.__on_click) #wx.TextCtrl(panel,pos=(10,10), size=(250,150)) self.SetTitle("Soundboard") self.Show(True) def __on_click(self,event): event.Skip() name = self.__sound_list[self.__list.GetSelection()] filename = self.__sound_dict[name] if filename == "goliath.wav": print "[ NOW PLAYING ] ... %s" % filename pygame.mixer.Sound.play(goliathwav) if filename == "channelopen.wav": print "[ NOW PLAYING ] ... %s" % filename pygame.mixer.Sound.play(channelopen) def __quit(self, e): self.Close() def main(): app = wx.App() windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE) app.MainLoop() main() </code></pre> <p>This is the error I am receiving: </p> <pre><code>self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, aboutBox) AttributeError: 'windowClass' object has no attribute 'OnMenuHelpAbout' </code></pre> <p>Any suggestions? </p> <p>Thanks as always, </p> <p>kommander000</p>
0
2016-08-20T21:15:27Z
39,058,918
<p>you again :)</p> <p>The aboutBox needs to be created in your missing callback <code>OnMenuHelpAbout</code> (that I refactored to make private as stated in my previous answer)</p> <p>Also (not related) but I have changed the dictionary so it directly points to the sound object: no more <code>if/elif</code>, you can load 200 sounds the code will still be the same.</p> <p>Fixed code:</p> <pre><code>import wx import os import pygame pygame.init() ##SOUNDS## ##SOUNDS## class windowClass(wx.Frame): __goliathwav = pygame.mixer.Sound("goliath.wav") __channelopen = pygame.mixer.Sound("channelopen.wav") def __init__(self, *args, **kwargs): super(windowClass,self).__init__(*args,**kwargs) self.__basicGUI() def __basicGUI(self): panel = wx.Panel(self) menuBar = wx.MenuBar() fileButton = wx.Menu() editButton = wx.Menu() aboutButton = wx.Menu() exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...') aboutItem = aboutButton.Append(wx.ID_ABOUT, "About") menuBar.Append(fileButton, 'File') menuBar.Append(editButton, 'Edit') menuBar.Append(aboutButton, 'About this program') self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.__quit, exitItem) self.Bind(wx.EVT_MENU, self.__onmenuhelpabout, aboutItem) self.__sound_dict = { "Goliath" : self.__goliathwav, "Goliath2" : self.__channelopen } self.__sound_list = sorted(self.__sound_dict.keys()) self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150)) for i in self.__sound_list: self.__list.Append(i) self.__list.Bind(wx.EVT_LISTBOX,self.__on_click) #wx.TextCtrl(panel,pos=(10,10), size=(250,150)) self.SetTitle("Soundboard") self.Show(True) def __onmenuhelpabout(self,event): event.Skip() aboutBox = wx.MessageDialog(None, "Created by Kommander000(cyrex)") answer=aboutBox.ShowModal() aboutBox.Destroy() def __on_click(self,event): event.Skip() name = self.__sound_list[self.__list.GetSelection()] sound = self.__sound_dict[name] print("[ NOW PLAYING ] ... %s" % name) pygame.mixer.Sound.play(sound) def __quit(self, e): self.Close() def main(): app = wx.App() windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE) app.MainLoop() main() def __quit(self, e): self.Close() def main(): app = wx.App() windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE) app.MainLoop() main() </code></pre>
0
2016-08-20T21:36:03Z
[ "python", "wxpython" ]
wxPython : Adding an about box.
39,058,783
<p>I'm creating a wxPython soundboard and was wondering how to implement an About Box. The goal is to press an About button on the wxPython File menu and generate an About Box. </p> <p>This is my code so far: </p> <pre><code>import wx import os import pygame pygame.init() ##SOUNDS## goliathwav = pygame.mixer.Sound("goliath.wav") channelopen = pygame.mixer.Sound("channelopen.wav") ##SOUNDS## class windowClass(wx.Frame): def __init__(self, *args, **kwargs): super(windowClass,self).__init__(*args,**kwargs) self.__basicGUI() def __basicGUI(self): panel = wx.Panel(self) menuBar = wx.MenuBar() fileButton = wx.Menu() editButton = wx.Menu() aboutBox = wx.MessageDialog(None, "Created by Kommander000(cyrex)") answer=aboutBox.ShowModal() aboutBox.Destroy() aboutButton = wx.Menu() exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...') aboutItem = aboutButton.Append(wx.ID_ABOUT, "About") menuBar.Append(fileButton, 'File') menuBar.Append(editButton, 'Edit') menuBar.Append(aboutButton, 'About this program') self.SetMenuBar(menuBar) self.Bind(wx.EVT_MENU, self.__quit, exitItem) self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, aboutBox) self.__sound_dict = { "Goliath" : "goliath.wav", "Goliath2" : "channelopen.wav" } self.__sound_list = sorted(self.__sound_dict.keys()) self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150)) for i in self.__sound_list: self.__list.Append(i) self.__list.Bind(wx.EVT_LISTBOX,self.__on_click) #wx.TextCtrl(panel,pos=(10,10), size=(250,150)) self.SetTitle("Soundboard") self.Show(True) def __on_click(self,event): event.Skip() name = self.__sound_list[self.__list.GetSelection()] filename = self.__sound_dict[name] if filename == "goliath.wav": print "[ NOW PLAYING ] ... %s" % filename pygame.mixer.Sound.play(goliathwav) if filename == "channelopen.wav": print "[ NOW PLAYING ] ... %s" % filename pygame.mixer.Sound.play(channelopen) def __quit(self, e): self.Close() def main(): app = wx.App() windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE) app.MainLoop() main() </code></pre> <p>This is the error I am receiving: </p> <pre><code>self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, aboutBox) AttributeError: 'windowClass' object has no attribute 'OnMenuHelpAbout' </code></pre> <p>Any suggestions? </p> <p>Thanks as always, </p> <p>kommander000</p>
0
2016-08-20T21:15:27Z
39,062,433
<p>wx python has its own <code>wx.AboutBox()</code> used in conjunction with <code>wx.AboutDialogInfo()</code></p> <pre><code>def About(self, event): from platform import platform myos = platform() aboutInfo = wx.AboutDialogInfo() aboutInfo.SetName("My Application ") aboutInfo.SetVersion("1.0") aboutInfo.SetDescription("My Super App," \ " That does amazing things\nRunning on: "+myos) aboutInfo.SetCopyright("(C) Joe Bloggs-2016") aboutInfo.SetLicense("https://www.gnu.org/licenses/gpl-2.0.html") aboutInfo.AddDeveloper("Joe Bloggs") aboutInfo.AddDocWriter("Joe Bloggs") aboutInfo.SetWebSite('https://www.JoeBlogs.com') wx.AboutBox(aboutInfo) </code></pre> <p>See:<a href="https://wxpython.org/docs/api/wx-module.html#AboutBox" rel="nofollow">https://wxpython.org/docs/api/wx-module.html#AboutBox</a></p>
2
2016-08-21T08:44:26Z
[ "python", "wxpython" ]
Get field type in Django's login template
39,058,787
<p>I'm trying to create custom template for Django's build-in login view. At the moment it looks like (<code>registration/login.html</code>):</p> <pre><code>&lt;form method="post"&gt; {% csrf_token %} {% for field in form %} {% include 'registration/form_field.html' %} {% endfor %} &lt;input class="btn btn-primary btn-block" type="submit" value="{% trans "Log in" %}"&gt; &lt;/form&gt; </code></pre> <p>And <code>registration/form_field.html</code> file is:</p> <pre><code>&lt;div class="form-group {% if field.errors %}has-error{% endif %}"&gt; &lt;input class="form-control" name="{{ field.name }}" placeholder="{{ field.label }}" {% if field.data %}value="{{ field.data }}"{% endif %} /&gt; {% if field.errors %} &lt;span class='text-danger'&gt;{{ field.errors|join:'&lt;br&gt;' }}&lt;/span&gt; {% endif %} &lt;/div&gt; </code></pre> <p>Everything works as expected, only problem is that password is shown in clear text.</p> <p>To solve this <code>type="password"</code> should be set for <code>password</code> field (and <code>type="text"</code> for <code>username</code> field).</p> <p>Is it possible to implement this using <code>field</code> variable (i.e. something like <code>{{ field.type }}</code>)?</p>
0
2016-08-20T21:16:50Z
39,059,277
<p>You can implement a <a href="https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.PasswordInput" rel="nofollow">PasswordInput</a> widget in your form definition, that will render as a password field with type="password".</p> <pre><code>class ExampleForm(forms.Form): password = forms.CharField(label='Password', widget=forms.PasswordInput()) </code></pre> <p>In the templates,</p> <pre><code>{{form.password}} </code></pre> <p>will render this field, which is the cleanest solution.</p> <p>You may also access the type of the field (as you wanted), like this:</p> <pre><code>{{form.fields.password.widget.input_type}} </code></pre> <p>Note that if you'd like further customization beyond simply rendering the form, there's nothing wrong with just writing your own html for the fields.</p>
1
2016-08-20T22:35:16Z
[ "python", "django" ]
Event callback after a Tkinter Entry widget
39,058,817
<p>From the first answer here: <a href="http://stackoverflow.com/questions/6548837/how-do-i-get-an-event-callback-when-a-tkinter-entry-widget-is-modified">StackOverflow #6548837</a> I can call callback when the user is typing: </p> <pre><code>from Tkinter import * def callback(sv): print sv.get() root = Tk() sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: callback(sv)) e = Entry(root, textvariable=sv) e.pack() root.mainloop() </code></pre> <p>However, the event occurs on every typed character. How to call the event when the user is done with typing and presses enter, or the Entry widget loses focus (i.e. the user clicks somewhere else)?</p>
0
2016-08-20T21:21:27Z
39,059,073
<p>I think this does what you're looking for. I found relevant information <a href="http://docs.huihoo.com/tkinter/an-introduction-to-tkinter-1997/intro06.htm" rel="nofollow">here</a>. The <code>bind</code> method is the key.</p> <pre><code>from Tkinter import * def callback(sv): print sv.get() root = Tk() sv = StringVar() e = Entry(root, textvariable=sv) e.bind('&lt;Return&gt;', (lambda _: callback(e))) e.pack() root.mainloop() </code></pre>
2
2016-08-20T22:03:49Z
[ "python", "events", "tkinter", "callback" ]
AttributeError: 'int' object has no attribute 'sleep'
39,058,861
<p>I am fairly new to Python (and programming in general), so please excuse my lack of knowledge or understanding to something you may find obvious. I'm not stupid though, so hopefully I should be able to work it out.</p> <p>I am making a small text-based survival game, and I have encountered an issue which I cannot seem to solve, which is the:</p> <blockquote> <p>AttributeError: 'int' object has no attribute 'sleep'</p> </blockquote> <p>In the console when I try and run my program.</p> <pre><code>import time , sys , random , shelve # /gather command if '/gather' in Input and command_state == True: if 'wood' in Input: print('Collecting wood...') if tool != "Axe": time.sleep(random.randrange(5 , 10)) print("Test") else: time.sleep(random.randrange(5 , 10)) print("Test") </code></pre> <p>I really don't understand what is causing this and after looking through the advice given on similar topics I have found no solution. Any help would be appreciated! </p> <p>If you'd like me to put up the whole script, please just ask. I have only put up the block of code that was causing the issue (because none of the other code seemed to affect anything here).</p>
0
2016-08-20T21:28:25Z
39,058,967
<p>As commented above you are overwriting the <code>time</code> module by making a variable named time. Simply rename the <code>time</code> variable! </p>
0
2016-08-20T21:46:24Z
[ "python", "attributes" ]
Spotify - passing a list as parameter
39,058,952
<p>I have a function to be called later in a <code>for</code> loop.</p> <pre><code>def show_tracks(results): for i, item in enumerate(tracks['items']): track = item['track'] print(" %d %32.32s %s" % (i, track['artists'][0]['name'], track['name'])) </code></pre> <p>2nd snippet:</p> <pre><code>playlists = sp.user_playlists(username) #spotipy method for playlist in playlists['items']: if playlist['owner']['id'] == username: print() print(playlist['name']) print(' total tracks', playlist['tracks']['total']) results = sp.user_playlist(username, playlist['id'], fields="tracks,next") tracks = results['tracks'] show_tracks(tracks) while tracks['next']: tracks = sp.next(tracks) show_tracks(tracks) </code></pre> <p>but now I would like to pass a <code>list</code> of usernames, like so:</p> <pre><code> playlists = sp.user_playlists(#list of usernames) </code></pre> <p>I have tried to define the second snippet as a function, but in doing so an issue of global vs local variables showed up:</p> <p><code>NameError: global name 'tracks' is not defined</code> </p> <p>So, how do I pass a list of <code>usernames</code> and loop though each one of them?</p>
0
2016-08-20T21:43:04Z
39,059,479
<p>Check your <code>show_tracks(results)</code> function. You are not passing results anywhere. </p> <p>Additionally you are iterating over tracks which is not defined in that function. Simply replace <code>tracks</code> with <code>results</code>. Then you are good to go.</p>
0
2016-08-20T23:06:30Z
[ "python", "list", "parameters", "spotipy" ]
Python | Insert Two Items in a List per Iteration with One-Liner
39,059,001
<p>Is it possible to insert in a list 2 items with one-liner? For example, get <code>[1, 2, 3, 4]</code> by something like <code>[ x, x+1 for x in [1, 3]]</code></p>
2
2016-08-20T21:53:30Z
39,059,057
<p>No you can't do this. Instead you can use a generator expression within <code>itertools.chain.from_iterable</code> in order to chain the iterable items or use a nested list comprehension (which is not as optimized as <em><code>chain.from_iterable</code></em> since you have to create the items then unpack them with another loop).</p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; l = [(1, 2), (3, 5)] &gt;&gt;&gt; &gt;&gt;&gt; list(chain.from_iterable(i for i in l)) [1, 2, 3, 5] </code></pre> <p>In python 3.5+ you can unpack the iterables within a list like following but still not at iteration time.</p> <pre><code>&gt;&gt;&gt; a = (1, 2) &gt;&gt;&gt; b = (3, 5) &gt;&gt;&gt; &gt;&gt;&gt; [*a, *b] [1, 2, 3, 5] </code></pre>
1
2016-08-20T22:00:44Z
[ "python", "for-loop" ]
Python | Insert Two Items in a List per Iteration with One-Liner
39,059,001
<p>Is it possible to insert in a list 2 items with one-liner? For example, get <code>[1, 2, 3, 4]</code> by something like <code>[ x, x+1 for x in [1, 3]]</code></p>
2
2016-08-20T21:53:30Z
39,059,210
<pre><code>[item for sublist in [ [x, x+1] for x in [1, 3] ] for item in sublist] </code></pre>
1
2016-08-20T22:23:54Z
[ "python", "for-loop" ]
Python - Create set from string
39,059,029
<p>I have strings in the format <code>"1-3 6:10-11 7-9"</code> and from them I want to create number sets as follows <code>{1,2,3,6,10,11,7,8,9}</code>. </p> <p>For creating the set from the range of numbers, I have the following code:</p> <pre><code>def create_set(src): lset = [] if len(src) &gt; 0: pos = src.find('-') if pos != -1: first = int(src[:pos]) last = int(src[pos+1:]) else: return [int(src)] # Only one number for j in range (first, last+1): lset.append(j) return set(lset) </code></pre> <p>But I cannot figure out how to correctly treat the ':' when it appears in the string. Can someone help me?</p> <p>Thanks in advance! </p> <p>EDIT: By the way, is there a more compact way of parsing such strings, perhaps using regular expressions?</p>
1
2016-08-20T21:56:39Z
39,059,147
<p>Something like this might work for you:</p> <pre><code>s = '1-3 6:10-11 7-9' s = s.replace(':', ' ') lset = set() fs = s.split() for f in fs: r = f.split('-') if len(r)==1: # add a single number lset.add(int(r[0])) else: # add a range of numbers (inclusive of the endpoints) lset |= set(range(int(r[0]), int(r[1])+1)) print(lset) </code></pre>
5
2016-08-20T22:16:17Z
[ "python", "set" ]
Python - Create set from string
39,059,029
<p>I have strings in the format <code>"1-3 6:10-11 7-9"</code> and from them I want to create number sets as follows <code>{1,2,3,6,10,11,7,8,9}</code>. </p> <p>For creating the set from the range of numbers, I have the following code:</p> <pre><code>def create_set(src): lset = [] if len(src) &gt; 0: pos = src.find('-') if pos != -1: first = int(src[:pos]) last = int(src[pos+1:]) else: return [int(src)] # Only one number for j in range (first, last+1): lset.append(j) return set(lset) </code></pre> <p>But I cannot figure out how to correctly treat the ':' when it appears in the string. Can someone help me?</p> <p>Thanks in advance! </p> <p>EDIT: By the way, is there a more compact way of parsing such strings, perhaps using regular expressions?</p>
1
2016-08-20T21:56:39Z
39,062,399
<blockquote> <p>EDIT: By the way, is there a more compact way of parsing such strings, perhaps using regular expressions?</p> </blockquote> <p>Perhaps a cleaner (and slightly more efficient) way:</p> <pre><code>import re import itertools allGroups = re.findall(r"(\d+)(?:-(\d+)|:)", s) expanded = [range(int(x), (int(x) if y == '' else int(y)) + 1) for x, y in allGroups] print {x for x in itertools.chain.from_iterable(expanded)} </code></pre> <p>Explanations:</p> <p>Match all strings like 'a-b' or 'a:' and return a list of (a, b) and (a, '') pairs respectively:</p> <pre><code>allGroups = re.findall(r"(\d+)(?:-(\d+)|:)", s) </code></pre> <p>This produces:</p> <pre><code>[('1', '3'), ('6', ''), ('10', '11'), ('7', '9')] </code></pre> <p>Using list comprehension expand all pairs of (x, y) into the full list of numbers in the range (x, y + 1), taking care to handle the (x, '') case as (x, x+1):</p> <pre><code>expanded = [range(int(x), (int(x) if y == '' else int(y)) + 1) for x, y in allGroups] </code></pre> <p>This produces:</p> <pre><code>[[1, 2, 3], [6], [10, 11], [7, 8, 9]] </code></pre> <p>Use <code>itertools.chain.from_iterable()</code> to transform the list of lists into a single iterable which is iterated by a set comprehension into the final set:</p> <pre><code>print {x for x in itertools.chain.from_iterable(expanded)} </code></pre> <p>This produces:</p> <pre><code>set([1, 2, 3, 6, 7, 8, 9, 10, 11]) </code></pre>
1
2016-08-21T08:38:49Z
[ "python", "set" ]
Randomly insert NA's values in a pandas dataframe
39,059,032
<p>How can I randomly insert NA's in a pandas dataframe ? Let's say I want 10% of NA's in all the dataframe.</p> <p>My data looks like this : </p> <pre><code>df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'b', 'c', 'd', 'e'],columns=['one', 'two', 'three']) one two three a 0.695132 1.044791 -1.059536 b -1.075105 0.825776 1.899795 c -0.678980 0.051959 -0.691405 d -0.182928 1.455268 -1.032353 e 0.205094 0.714192 -0.938242 </code></pre>
0
2016-08-20T14:48:09Z
39,059,033
<p>Here's one way. I've interpreted your question as wanting to clear exactly 10% of cells (or rather, as close to 10% as can be achieved with the existing data frame's size), as opposed to, say, clearing cells independently with a marginal per-cell probability of 10%.</p> <pre class="lang-python prettyprint-override"><code>import random ix = [(row, col) for row in range(df.shape[0]) for col in range(df.shape[1])] for row, col in random.sample(ix, int(round(.1*len(ix)))): df.iat[row, col] = np.nan </code></pre> <p>Here's one way <code>df</code> can come out:</p> <pre><code> one two three a -0.805977 1.119504 -1.752176 b 0.140901 -0.650624 -1.173568 c 0.449119 0.530058 0.249335 d 0.823705 NaN 1.211498 e NaN -0.038198 -0.290931 </code></pre>
1
2016-08-20T15:13:45Z
[ "python", "missing-data" ]
What's the shortest way of converting list of lists to a string, one inner list per line?
39,059,052
<p>I have a list of lists and I'm looking for the shortest way of converting that data to a string where every inner list appears on a new line.</p> <p>Assuming my input list is:</p> <pre><code>l_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] </code></pre> <p>I want my output to be a string (let's call it l_2d_str), so that if i <code>print l_2d_str</code>, I get:</p> <pre><code>[1, 2, 3] [4, 5, 6] [7, 8, 9] </code></pre>
-1
2016-08-20T22:00:36Z
39,059,076
<p>How about this?</p> <pre><code>l_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] l_2d_str = '\n'.join(map(repr, l_2d)) </code></pre>
6
2016-08-20T22:04:41Z
[ "python" ]
PlaySound only plays default "SystemAsterisk" sound (Windows 10, C++, Python)
39,059,082
<p>I'm trying to use Windows' PlaySound function as mentioned here: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd743680(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/dd743680(v=vs.85).aspx</a></p> <p>However, nothing I try can change it from playing the default sound "SystemAsterisk."</p> <p>I've tried using both C++ and Python and get the same results:</p> <p>C++:</p> <pre><code>#include "stdafx.h" #include &lt;Windows.h&gt; #include &lt;playsoundapi.h&gt; int main() { PlaySound(TEXT("SystemWelcome"), NULL, SND_ALIAS); PlaySound(TEXT("C:\Users\Me\Downloads\sound1.wav"), NULL, SND_FILENAME); return 0; } </code></pre> <p>Both attempts above to play a different sound still return the default Asterisk sound.</p> <p>Python:</p> <pre><code>#!/usr/bin/python import winsound winsound.PlaySound("c:/Users/Me/Downloads/sound1.wav", winsound.SYN_ASYNC|winsound.SYN_FILENAME) </code></pre> <p>Again, I get the same results. </p> <p>Any ideas on what's going on? Perhaps this is a Windows 10 problem?</p>
0
2016-08-20T22:05:14Z
39,059,311
<p>This works for me in Windows 7 and in Windows 10:</p> <pre><code>#undef UNICODE #define UNICODE #include &lt;windows.h&gt; #include &lt;stdlib.h&gt; auto main() -&gt; int { bool const ok = !!PlaySound( L"c:/windows/media/ringout.wav", 0, SND_ALIAS ); return (ok? EXIT_SUCCESS : EXIT_FAILURE); } </code></pre> <hr> <p>One direct problem with your C++ code is the string literal</p> <pre><code>"C:\Users\Me\Downloads\sound1.wav" </code></pre> <p>where each <code>\</code> starts an invalid escape sequence. One simple fix is to use forward slashes, <code>/</code>, instead of <code>\</code> backslashes.</p> <p>One possible problem with your Python code is the <code>SYN_ASYNC</code> flag. This may cause the function to return immediately. And if the script then exits immediately, you may not necessarily hear any sound.</p> <hr> <p>In other news:</p> <ul> <li><code>#include "stdafx.h"</code> is a non-standard header, and prevents some readers from directly trying your code (they don't have that generated header).</li> <li><code>TEXT</code> is obsolete, use Unicode in modern Windows.</li> <li><code>return 0;</code> is unnecessary for <code>main</code>, it's the default.</li> </ul>
0
2016-08-20T22:39:14Z
[ "python", "c++", "audio", "windows-10", "playsound" ]
How to ensure data is written to geotiff using GDAL?
39,059,122
<p>I am working on a script that takes in a CSV file containing locations of measurements and creating a probability map based on those measurements. I am using GDAL to write the probabilities to a GeoTIFF, however, I am noticing that none of the data is properly written to the GeoTIFF. When generating the heatmap, I use numpy to store the data in an X by Y array, then write that array to the GeoTIFF. The current dataset I am testing on measure 260 x 262 meters, and the resulting GeoTIFF has the correct dimensions and is properly georeferenced. The heatmap data should have pixel values ranging from -51 to 0, however, when I load the GeoTIFF into QGIS, QGIS only has values ranging from -51 to -31.</p> <p>The GeoTIFF should be stored as 32 bit float data and lossless compression, so it's not a data range or compression issue.</p> <p>I've attached the relevant code below:</p> <pre><code>import sys import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plot # USING utm 0.4.0 from https://pypi.python.org/pypi/utm import utm import os import argparse import fileinput from osgeo import gdal import osr import math # finalLon and finalLat are 1-D arrays containing the UTM coordinates for each measurement tiffXSize = int(max(finalLon)) - int(min(finalLon)) + maxRange * 2 tiffYSize = int(max(finalLat)) - int(min(finalLat)) + maxRange * 2 pixelSize = 1 heatMapArea = np.zeros((tiffXSize, tiffYSize)) # y, x refLat = min(finalLat) - maxRange maxLat = max(finalLat) + maxRange refLon = max(finalLon) + maxRange minLon = min(finalLon) - maxRange # some code to set values in the heatMapArea array outputFileName = '%s/RUN_06d_COL_%06d.tiff' % (output_path, run_num, num_col) driver = gdal.GetDriverByName('GTiff') dataset = driver.Create( outputFileName, tiffYSize, tiffXSize, 1, gdal.GDT_Float32, ['COMPRESS=LZW']) spatialReference = osr.SpatialReference() spatialReference.SetUTM(zonenum, zone &gt;= 'N') spatialReference.SetWellKnownGeogCS('WGS84') wkt = spatialReference.ExportToWkt() retval = dataset.SetProjection(wkt) dataset.SetGeoTransform(( refLat, # 0 1, # 1 0, # 2 refLon, # 3 0, # 4 -1)) band = dataset.GetRasterBand(1) band.SetNoDataValue(100) print(tiffXSize) print(tiffYSize) print(np.amin(heatMapArea)) print(np.amax(heatMapArea)) print(np.mean(heatMapArea)) print(np.std(heatMapArea)) print((heatMapArea &gt; -30).sum()) band.WriteArray(heatMapArea) band.SetStatistics(np.amin(heatMapArea), np.amax(heatMapArea), np.mean(heatMapArea), np.std(heatMapArea)) dataset.FlushCache() dataset = None </code></pre>
0
2016-08-20T22:11:58Z
39,059,535
<p>Problem is in how QGIS computes the maximum and minimum of the GeoTIFF. If you go into the properties of the GeoTIFF layer, and open the Style tab, under Band Rendering, you can choose how to load the min/max values. By default, QGIS uses the 2% to 98% count as the minimum and maximum, however, for this, we want the min/max.</p>
1
2016-08-20T23:18:11Z
[ "python", "gis", "gdal", "qgis", "geotiff" ]
Django ORM - Adjust field value on return
39,059,129
<p>I have a model that stores user-entered database password. As my app needs to connect to these databases. The password is encrypted in the database. However, when it is retrieved I need to apply a <code>decrypt</code> function to the password field. Where can I do that so that it is only applied when querying the database, not when saving the field.</p> <p>Here is my model:</p> <pre><code>class Databases(models.Model): """ Handles the storing of database connections """ # Initialize the encryption class e = Encryption() # Our unique id for the database id = models.AutoField(primary_key=True) # Database name to display to the user database_display_name = models.CharField(max_length=128, db_index=True, unique=True) # Database name database_name = models.CharField(max_length=128, db_index=True) # Database status active = models.BooleanField(default=True, db_index=True) # The host name host = models.CharField(max_length=256) # The default port port = models.IntegerField(default=3306) # The username for the database username = models.CharField(max_length=128) # The password for the database password = models.CharField(max_length=256) # Set the database type database_type = models.CharField(max_length=64, db_index=True, default="mysql") # Timestamps created_at = models.DateTimeField(db_index=True) updated_at = models.DateTimeField(db_index=True) event_at = models.DateTimeField(db_index=True) def get_password(self, obj): print("Retrieving") return Databases.e.decrypt(obj.password) def save(self, *args, **kwargs): """ On save, update timestamps """ # If the record does not currently exist in the database if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() # Encrypt the password self.password = Databases.e.encrypt(self.password) return super(Databases, self).save(*args, **kwargs) class Meta: db_table = 'databases' </code></pre> <p>Here is my serializer:</p> <pre><code>class DatabasesSerializer(serializers.ModelSerializer): class Meta: model = Databases </code></pre>
0
2016-08-20T22:12:35Z
39,059,242
<p>You can make the get_password method a <code>property</code> of the <code>Databases</code> class:</p> <pre><code> @property def get_password(self): print("Retrieving") return self.e.decrypt(self.password) </code></pre> <p>then you'll be able to use it in your serializer:</p> <pre><code>class DatabasesSerializer(serializers.ModelSerializer): get_password = serializers.ReadOnlyField() class Meta: model = Databases fields = ('get_password', ...,) </code></pre>
0
2016-08-20T22:28:54Z
[ "python", "django", "orm" ]
PPrint not working (Python)?
39,059,195
<p>I'm trying to use Python's <code>pprint</code> on a dictionary but for some reason it isn't working. Here's my code (I'm using PyCharm Pro as my IDE):`</p> <pre><code>from pprint import pprint message = "Come on Eileen!" count = {} for character in message: count.setdefault(character, 0) count[character] += 1 pprint(count) </code></pre> <p>And here's my output:</p> <pre><code>{' ': 2, '!': 1, 'C': 1, 'E': 1, 'e': 3, 'i': 1, 'l': 1, 'm': 1, 'n': 2, 'o': 2} </code></pre> <p>Any help with this would be appreciated.</p>
-2
2016-08-20T22:22:01Z
39,059,212
<p>The output is entirely correct and expected. From the <a href="https://docs.python.org/3/library/pprint.html" rel="nofollow"><code>pprint</code> module documentation</a>:</p> <blockquote> <p>The formatted representation <strong>keeps objects on a single line if it can</strong>, and breaks them onto multiple lines if they don’t fit within the allowed width. </p> </blockquote> <p>Bold emphasis mine.</p> <p>You could set the <code>width</code> keyword argument to <code>1</code> to force every key-value pair being printed on a separate line:</p> <pre><code>&gt;&gt;&gt; pprint(count, width=1) {' ': 2, '!': 1, 'C': 1, 'E': 1, 'e': 3, 'i': 1, 'l': 1, 'm': 1, 'n': 2, 'o': 2} </code></pre>
1
2016-08-20T22:24:20Z
[ "python", "python-3.x", "pprint" ]
Trouble installing pyGObject on python3
39,059,217
<p>I keep getting error messages while trying to install PyGObject on python3 (Mac OS X 10.9)</p> <pre><code> Traceback (most recent call last): File "&lt;string&gt;", line 20, in &lt;module&gt; File "/private/var/folders/zh/hww3rvgx1rg62zwc8ct51r1r0000gn/T/pip-build-v5qjvi2y/pygobject/setup.py", line 272 raise SystemExit, 'ERROR: Nothing to do, gio could not be found and is essential.' ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/zh/hww3rvgx1rg62zwc8ct51r1r0000gn/T/pip-build-v5qjvi2y/pygobject </code></pre>
0
2016-08-20T22:24:45Z
39,059,320
<p>You are trying to install a python2 module with python 3. The syntax error occurs because there has been a change to the syntax for raising an exception. <code>raise SystemExit, 'Message'</code> has become <code>raise SystemExit('Message')</code></p> <p>You should make sure that you have the python3 versions of the module.</p>
0
2016-08-20T22:40:09Z
[ "python" ]
Servlet equivalent in Python?
39,059,225
<p>On client side , following android code would make the call to the local server :</p> <pre><code> String link = "http://localhost:8080/test/cgi-bin/test.py"; URL url = null; try { url = new URL(link); HttpURLConnection client = (HttpURLConnection) url.openConnection(); JSONObject jo = new JSONObject(); jo.put("desc","xyz"); String data2 = jo.toString(); client.setRequestMethod("Post"); // client.setRequestProperty("key","value"); client.setDoOutput(true); OutputStreamWriter outputPost = new OutputStreamWriter(client.getOutputStream()); outputPost.write(data2); outputPost.flush(); outputPost.close(); </code></pre> <p>Earlier I was using servlets to interact with DB as the code below : Using HttpServlet class , i could get the request and its parameters :</p> <pre><code>public class ServletXYZ extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); </code></pre> <p>Is there any way in python which allows me to do the same (getting parameter values from request) ?</p> <p>Thanks.</p>
0
2016-08-20T22:26:40Z
39,060,230
<p>I've used <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> as a general purpose HTTP server framework. Ultimately to do the same as the servlet, there are many links - <a href="http://stackoverflow.com/questions/6211381/how-to-read-parameters-from-get-request-in-cherrypy">this one</a> seems to be pretty much what you want.</p>
1
2016-08-21T02:02:35Z
[ "java", "android", "python", "servlets" ]
Troubles with XPath Plugin Python
39,059,338
<p>So i am getting the path id('page-content')/x:div[6]/x:div/x:div/x:div/x:a[1]/x:img</p> <p>How would i go about clicking the img?</p> <p>I've tried </p> <p>lol=find_element_by_xpath("//div[@class='emoji-items nano-content']//a[@title=':heart:']/img")</p> <p>as well as</p> <p>lol=find_element_by_xpath("//a[@title=':heart:']/img") which i believe should work, but it instead gives me an error</p>
1
2016-08-20T22:42:49Z
39,059,468
<p>What i did is: select all links elements (a) that contains heart in the title.</p> <p>I tried to avoid using @title= because sometimes you might have issues due syntax used in the methods for finding the element or in other methods due to special characters like :.</p> <p>The resulted path was:</p> <pre><code>//a[contains(@title, 'heart')] </code></pre> <p>If more elements are found you need to add another element in front of this to restrict the section that is searched in.</p>
0
2016-08-20T23:04:31Z
[ "python", "selenium" ]
Can numpy's argsort give equal element the same rank?
39,059,371
<p>I want to get the rank of each element, so I use <code>argsort</code> in <code>numpy</code>:</p> <pre><code>np.argsort(np.array((1,1,1,2,2,3,3,3,3))) array([0, 1, 2, 3, 4, 5, 6, 7, 8]) </code></pre> <p>it give the same element the different rank, can I get the same rank like:</p> <pre><code>array([0, 0, 0, 3, 3, 5, 5, 5, 5]) </code></pre>
3
2016-08-20T22:46:45Z
39,059,429
<p>If you don't mind a dependency on scipy, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rankdata.html" rel="nofollow"><code>scipy.stats.rankdata</code></a>, with <code>method='min'</code>:</p> <pre><code>In [14]: a Out[14]: array([1, 1, 1, 2, 2, 3, 3, 3, 3]) In [15]: from scipy.stats import rankdata In [16]: rankdata(a, method='min') Out[16]: array([1, 1, 1, 4, 4, 6, 6, 6, 6]) </code></pre> <p>Note that <code>rankdata</code> starts the ranks at 1. To start at 0, subtract 1 from the result:</p> <pre><code>In [17]: rankdata(a, method='min') - 1 Out[17]: array([0, 0, 0, 3, 3, 5, 5, 5, 5]) </code></pre> <hr> <p>If you don't want the scipy dependency, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>numpy.unique</code></a> to compute the ranking. Here's a function that computes the same result as <code>rankdata(x, method='min') - 1</code>:</p> <pre><code>import numpy as np def rankmin(x): u, inv, counts = np.unique(x, return_inverse=True, return_counts=True) csum = np.zeros_like(counts) csum[1:] = counts[:-1].cumsum() return csum[inv] </code></pre> <p>For example,</p> <pre><code>In [137]: x = np.array([60, 10, 0, 30, 20, 40, 50]) In [138]: rankdata(x, method='min') - 1 Out[138]: array([6, 1, 0, 3, 2, 4, 5]) In [139]: rankmin(x) Out[139]: array([6, 1, 0, 3, 2, 4, 5]) In [140]: a = np.array([1,1,1,2,2,3,3,3,3]) In [141]: rankdata(a, method='min') - 1 Out[141]: array([0, 0, 0, 3, 3, 5, 5, 5, 5]) In [142]: rankmin(a) Out[142]: array([0, 0, 0, 3, 3, 5, 5, 5, 5]) </code></pre> <hr> <p>By the way, a single call to <code>argsort()</code> does not give ranks. You can find an assortment of approaches to ranking in the question <a href="http://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy">Rank items in an array using Python/NumPy</a>, including how to do it using <code>argsort()</code>.</p>
5
2016-08-20T22:56:34Z
[ "python", "sorting", "numpy" ]
Can numpy's argsort give equal element the same rank?
39,059,371
<p>I want to get the rank of each element, so I use <code>argsort</code> in <code>numpy</code>:</p> <pre><code>np.argsort(np.array((1,1,1,2,2,3,3,3,3))) array([0, 1, 2, 3, 4, 5, 6, 7, 8]) </code></pre> <p>it give the same element the different rank, can I get the same rank like:</p> <pre><code>array([0, 0, 0, 3, 3, 5, 5, 5, 5]) </code></pre>
3
2016-08-20T22:46:45Z
39,059,720
<p>Alternatively, pandas series has a <code>rank</code> method which does what you need with the <code>min</code> method:</p> <pre><code>import pandas as pd pd.Series((1,1,1,2,2,3,3,3,3)).rank(method="min") # 0 1 # 1 1 # 2 1 # 3 4 # 4 4 # 5 6 # 6 6 # 7 6 # 8 6 # dtype: float64 </code></pre>
2
2016-08-20T23:58:32Z
[ "python", "sorting", "numpy" ]
Can numpy's argsort give equal element the same rank?
39,059,371
<p>I want to get the rank of each element, so I use <code>argsort</code> in <code>numpy</code>:</p> <pre><code>np.argsort(np.array((1,1,1,2,2,3,3,3,3))) array([0, 1, 2, 3, 4, 5, 6, 7, 8]) </code></pre> <p>it give the same element the different rank, can I get the same rank like:</p> <pre><code>array([0, 0, 0, 3, 3, 5, 5, 5, 5]) </code></pre>
3
2016-08-20T22:46:45Z
39,060,835
<p>With focus on performance, here's an approach -</p> <pre><code>def rank_repeat_based(arr): idx = np.concatenate(([0],np.flatnonzero(np.diff(arr))+1,[arr.size])) return np.repeat(idx[:-1],np.diff(idx)) </code></pre> <p>For a generic case with the elements in input array not already sorted, we would need to use <code>argsort()</code> to keep track of the positions. So, we would have a modified version, like so -</p> <pre><code>def rank_repeat_based_generic(arr): sidx = np.argsort(arr,kind='mergesort') idx = np.concatenate(([0],np.flatnonzero(np.diff(arr[sidx]))+1,[arr.size])) return np.repeat(idx[:-1],np.diff(idx))[sidx.argsort()] </code></pre> <p><strong>Runtime test</strong></p> <p>Testing out all the approaches listed thus far to solve the problem on a large dataset.</p> <p>Sorted array case :</p> <pre><code>In [96]: arr = np.sort(np.random.randint(1,100,(10000))) In [97]: %timeit rankdata(arr, method='min') - 1 1000 loops, best of 3: 635 µs per loop In [98]: %timeit rankmin(arr) 1000 loops, best of 3: 495 µs per loop In [99]: %timeit (pd.Series(arr).rank(method="min")-1).values 1000 loops, best of 3: 826 µs per loop In [100]: %timeit rank_repeat_based(arr) 10000 loops, best of 3: 200 µs per loop </code></pre> <p>Unsorted case :</p> <pre><code>In [106]: arr = np.random.randint(1,100,(10000)) In [107]: %timeit rankdata(arr, method='min') - 1 1000 loops, best of 3: 963 µs per loop In [108]: %timeit rankmin(arr) 1000 loops, best of 3: 869 µs per loop In [109]: %timeit (pd.Series(arr).rank(method="min")-1).values 1000 loops, best of 3: 1.17 ms per loop In [110]: %timeit rank_repeat_based_generic(arr) 1000 loops, best of 3: 1.76 ms per loop </code></pre>
2
2016-08-21T04:27:10Z
[ "python", "sorting", "numpy" ]
Python Sockets - how can I get the IP Address of a Socket after I bind it to an IP
39,059,418
<p>From the python library 'socket' is there a method that returns the IP of the socket that got binded to it?</p> <p>Suppose a socket was declared and initialized like:</p> <pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(ip, port) </code></pre> <p>And I wanted to find the IP of a received datagram from a socket:</p> <pre><code>while True: for s in socks: recv = s.recv(1024) #get ip of s or socket #print received data from s.gethostname() </code></pre> <p>How would I go on about this?</p>
0
2016-08-20T22:54:07Z
39,059,505
<p>Try with <a href="https://docs.python.org/2/library/socket.html#socket.socket.getpeername" rel="nofollow"><code>socket.getpeername()</code></a>.</p>
0
2016-08-20T23:10:56Z
[ "python", "python-sockets" ]
IMDbPY get the stars of a movie
39,059,530
<p>I was able to get the cast of the movie like this:</p> <pre><code>#!/usr/bin/env python import imdb ia = imdb.IMDb() s_result = ia.search_movie('The Untouchables') the_unt = s_result[0] print the_unt['cast'] </code></pre> <p>However, that gave all the <em>cast</em>, i am looking for just the <em>stars</em> of the movie. for example, al pacino is a star in god father</p>
-2
2016-08-20T23:16:51Z
39,059,696
<p>As stated in the comments, IMDb does not know the concept of a "star", but it does somewhat know the "top actors" from the cast lineup. </p> <p>It is probably based on the credits of the film, but even IMDb says <em>first billed only</em> for some movies. </p> <p>The cast ordering is entirely dependent on the movie and who verifies the data on IMDb. If it says "credits order", that means "in the order they were introduced in the film credits", <strong>but</strong>, the credit ordering could be some arbitrary ordering that the director of the film felt like placing them in. </p> <p>For example, some films say "And introducing... (some actor no one knows about)" or like a TV Show says "Special Guest Star... (someone most people recognize)". In both cases, those are either before / after the entire regular cast is introduced.</p> <hr> <p>So, if you wanted the top 5 actors for a given film, you could do something like this</p> <pre><code>import imdb ia = imdb.IMDb() search_results = ia.search_movie('The Godfather') if search_results: movieID = search_results[0].movieID movie = ia.get_movie(movieID) if movie: cast = movie.get('cast') topActors = 5 for actor in cast[:topActors]: print "{0} as {1}".format(actor['name'], actor.currentRole) </code></pre> <p>Output</p> <pre><code>Marlon Brando as Don Vito Corleone Al Pacino as Michael Corleone James Caan as Sonny Corleone Richard S. Castellano as Clemenza Robert Duvall as Tom Hagen </code></pre>
3
2016-08-20T23:53:49Z
[ "python", "movie", "imdb", "imdbpy" ]
pyximport with cgal build error: undefined symbol "__gmpq_equal"
39,059,539
<p>I am running Debian 8 with a packaged install of Cython (apt-get install cython).</p> <p>I am compiling my .pyx file with the CGAL (<a href="http://www.cgal.org" rel="nofollow">www.cgal.org</a>) but return the error:</p> <pre><code>import pyximport; pyximport.install() from spaces import spaces_rectangle </code></pre> <blockquote> <p>ImportError: Building module spaces failed: ['ImportError: /home/scootie/.pyxbld/lib.linux-x86_64-2.7/spaces.so: undefined symbol: __gmpq_equal\n']</p> </blockquote> <p>with the following files:</p> <p>spaces.pyx</p> <pre><code>from libcpp.vector cimport vector cdef extern from "cgal_spaces.hpp": cdef vector[vector[vector[double]]] wrap_spaces(vector[vector[double]]) def spaces_rectangle(vector[vector[double]] rect): return wrap_spaces(rect) </code></pre> <p>spaces.pyxbld:</p> <pre><code>def make_ext(modname, pyxfilename): from distutils.extension import Extension return Extension(name=modname, sources=[pyxfilename], include_dirs=['.'], libraries=['CGAL'], language='c++', extra_compile_args=['-std=c++11']) </code></pre> <p>and cgal_spaces.hpp:</p> <pre><code>#include &lt;CGAL/Exact_predicates_inexact_constructions_kernel.h&gt; #include &lt;CGAL/Partition_traits_2.h&gt; #include &lt;CGAL/Partition_is_valid_traits_2.h&gt; #include &lt;CGAL/polygon_function_objects.h&gt; #include &lt;CGAL/partition_2.h&gt; #include &lt;cassert&gt; #include &lt;list&gt; #include &lt;vector&gt; { *CODE HERE* } </code></pre> <p>Am I linking improperly or missing something obvious??</p> <p>Edit: If I compile the script outside of pyximport, it compiles with no problem. </p> <pre><code>cython -a spaces.pyx g++ -std=c++11 -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o spaces.so spaces.c </code></pre> <p>It seems there's a linking error in the pyximport with the gmp library. What's the proper way to linking to all external libraries?</p>
-1
2016-08-20T23:19:04Z
39,061,783
<p>gmp library may be missing from libraries,</p> <pre><code>strings -f /usr/lib/x86_64-linux-gnu/*.a |grep gmpq_equal </code></pre> <p>outputs</p> <pre><code>/usr/lib/x86_64-linux-gnu/libgmp.a: __gmpq_equal /usr/lib/x86_64-linux-gnu/libgmp.a: __gmpq_equal </code></pre>
0
2016-08-21T07:16:45Z
[ "python", "linux", "cython", "cgal" ]
pyximport with cgal build error: undefined symbol "__gmpq_equal"
39,059,539
<p>I am running Debian 8 with a packaged install of Cython (apt-get install cython).</p> <p>I am compiling my .pyx file with the CGAL (<a href="http://www.cgal.org" rel="nofollow">www.cgal.org</a>) but return the error:</p> <pre><code>import pyximport; pyximport.install() from spaces import spaces_rectangle </code></pre> <blockquote> <p>ImportError: Building module spaces failed: ['ImportError: /home/scootie/.pyxbld/lib.linux-x86_64-2.7/spaces.so: undefined symbol: __gmpq_equal\n']</p> </blockquote> <p>with the following files:</p> <p>spaces.pyx</p> <pre><code>from libcpp.vector cimport vector cdef extern from "cgal_spaces.hpp": cdef vector[vector[vector[double]]] wrap_spaces(vector[vector[double]]) def spaces_rectangle(vector[vector[double]] rect): return wrap_spaces(rect) </code></pre> <p>spaces.pyxbld:</p> <pre><code>def make_ext(modname, pyxfilename): from distutils.extension import Extension return Extension(name=modname, sources=[pyxfilename], include_dirs=['.'], libraries=['CGAL'], language='c++', extra_compile_args=['-std=c++11']) </code></pre> <p>and cgal_spaces.hpp:</p> <pre><code>#include &lt;CGAL/Exact_predicates_inexact_constructions_kernel.h&gt; #include &lt;CGAL/Partition_traits_2.h&gt; #include &lt;CGAL/Partition_is_valid_traits_2.h&gt; #include &lt;CGAL/polygon_function_objects.h&gt; #include &lt;CGAL/partition_2.h&gt; #include &lt;cassert&gt; #include &lt;list&gt; #include &lt;vector&gt; { *CODE HERE* } </code></pre> <p>Am I linking improperly or missing something obvious??</p> <p>Edit: If I compile the script outside of pyximport, it compiles with no problem. </p> <pre><code>cython -a spaces.pyx g++ -std=c++11 -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o spaces.so spaces.c </code></pre> <p>It seems there's a linking error in the pyximport with the gmp library. What's the proper way to linking to all external libraries?</p>
-1
2016-08-20T23:19:04Z
39,070,144
<p>Solution:</p> <pre><code>def make_ext(modname, pyxfilename): from distutils.extension import Extension return Extension(name=modname, sources=[pyxfilename], include_dirs=['.'], libraries=['CGAL','gmp'], language='c++', extra_compile_args=['-std=c++11','-DCGAL_ROOT="/path/to/CGAL-4.8.1"']) </code></pre> <p>I've added the gmp library to *.pyxbld, but the solution lies in placing the -DCGAL_ROOT after "-std=c++11".</p>
1
2016-08-22T00:58:42Z
[ "python", "linux", "cython", "cgal" ]
Using A For Loop to Return Unique Values in a Pandas Dataframe
39,059,631
<p>I know Pandas isn't really built to use with for-loops, but I have a specific task I'll have to do many times and it'd really save a lot of time if I could abstract some of it away with a function that I can call.</p> <p>A generic version of my dataframe looks like this: </p> <pre><code>df = pd.DataFrame({'Name': pd.Categorical(['John Doe', 'Jane Doe', 'Bob Smith']), 'Score1': np.arange(3), 'Score2': np.arange(3, 6, 1)}) Name Score1 Score2 0 John Doe 0 3 1 Jane Doe 1 4 2 Bob Smith 2 5 </code></pre> <p>What I want to do is take the method:</p> <pre><code>df.loc[df.Name == 'Jane Doe', 'Score2'] </code></pre> <p>Which should return 4, but iterate through it with a for-loop like so:</p> <pre><code>def pull_score(people, score): for i in people: print df.loc[df.Name == people[i], score] </code></pre> <p>So if I wanted to I could call:</p> <pre><code>the_names = ['John Doe', 'Jane Doe', 'Bob Smith'] pull_score(the_names, 'Score2') </code></pre> <p>And get:</p> <pre><code>3 4 5 </code></pre> <p>The error message I currently get is:</p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>I've looked at some of the other answers relating to this error message and Pandas such as this one: <a href="http://stackoverflow.com/questions/24708634/python-and-json-typeerror-list-indices-must-be-integers-not-str">Python and JSON - TypeError list indices must be integers not str</a> and this one: <a href="http://stackoverflow.com/questions/33066722/how-to-solve-typeerror-list-indices-must-be-integers-not-list">How to solve TypeError: list indices must be integers, not list?</a></p> <p>But didn't see the answer in either of them for what I'm trying to do and I don't believe <code>iterrows()</code> or <code>itertuple()</code> would apply since I need Pandas to find the values first.</p>
2
2016-08-20T23:39:35Z
39,059,685
<p>You can set the name as index and then search by index using <code>loc</code>:</p> <pre><code>the_names = ['John Doe', 'Jane Doe', 'Bob Smith'] df.set_index('Name').loc[the_names, 'Score2'] # Name # John Doe 3 # Jane Doe 4 # Bob Smith 5 # Name: Score2, dtype: int32 </code></pre>
3
2016-08-20T23:51:54Z
[ "python", "pandas" ]
Using A For Loop to Return Unique Values in a Pandas Dataframe
39,059,631
<p>I know Pandas isn't really built to use with for-loops, but I have a specific task I'll have to do many times and it'd really save a lot of time if I could abstract some of it away with a function that I can call.</p> <p>A generic version of my dataframe looks like this: </p> <pre><code>df = pd.DataFrame({'Name': pd.Categorical(['John Doe', 'Jane Doe', 'Bob Smith']), 'Score1': np.arange(3), 'Score2': np.arange(3, 6, 1)}) Name Score1 Score2 0 John Doe 0 3 1 Jane Doe 1 4 2 Bob Smith 2 5 </code></pre> <p>What I want to do is take the method:</p> <pre><code>df.loc[df.Name == 'Jane Doe', 'Score2'] </code></pre> <p>Which should return 4, but iterate through it with a for-loop like so:</p> <pre><code>def pull_score(people, score): for i in people: print df.loc[df.Name == people[i], score] </code></pre> <p>So if I wanted to I could call:</p> <pre><code>the_names = ['John Doe', 'Jane Doe', 'Bob Smith'] pull_score(the_names, 'Score2') </code></pre> <p>And get:</p> <pre><code>3 4 5 </code></pre> <p>The error message I currently get is:</p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>I've looked at some of the other answers relating to this error message and Pandas such as this one: <a href="http://stackoverflow.com/questions/24708634/python-and-json-typeerror-list-indices-must-be-integers-not-str">Python and JSON - TypeError list indices must be integers not str</a> and this one: <a href="http://stackoverflow.com/questions/33066722/how-to-solve-typeerror-list-indices-must-be-integers-not-list">How to solve TypeError: list indices must be integers, not list?</a></p> <p>But didn't see the answer in either of them for what I'm trying to do and I don't believe <code>iterrows()</code> or <code>itertuple()</code> would apply since I need Pandas to find the values first.</p>
2
2016-08-20T23:39:35Z
39,059,698
<p>You actually don't need the loop, you can just do this:</p> <pre><code>print(df.loc[df.Name == the_names, 'Score2']) 0 3 1 4 2 5 Name: Score2, dtype: int32 </code></pre>
2
2016-08-20T23:54:04Z
[ "python", "pandas" ]
Using A For Loop to Return Unique Values in a Pandas Dataframe
39,059,631
<p>I know Pandas isn't really built to use with for-loops, but I have a specific task I'll have to do many times and it'd really save a lot of time if I could abstract some of it away with a function that I can call.</p> <p>A generic version of my dataframe looks like this: </p> <pre><code>df = pd.DataFrame({'Name': pd.Categorical(['John Doe', 'Jane Doe', 'Bob Smith']), 'Score1': np.arange(3), 'Score2': np.arange(3, 6, 1)}) Name Score1 Score2 0 John Doe 0 3 1 Jane Doe 1 4 2 Bob Smith 2 5 </code></pre> <p>What I want to do is take the method:</p> <pre><code>df.loc[df.Name == 'Jane Doe', 'Score2'] </code></pre> <p>Which should return 4, but iterate through it with a for-loop like so:</p> <pre><code>def pull_score(people, score): for i in people: print df.loc[df.Name == people[i], score] </code></pre> <p>So if I wanted to I could call:</p> <pre><code>the_names = ['John Doe', 'Jane Doe', 'Bob Smith'] pull_score(the_names, 'Score2') </code></pre> <p>And get:</p> <pre><code>3 4 5 </code></pre> <p>The error message I currently get is:</p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>I've looked at some of the other answers relating to this error message and Pandas such as this one: <a href="http://stackoverflow.com/questions/24708634/python-and-json-typeerror-list-indices-must-be-integers-not-str">Python and JSON - TypeError list indices must be integers not str</a> and this one: <a href="http://stackoverflow.com/questions/33066722/how-to-solve-typeerror-list-indices-must-be-integers-not-list">How to solve TypeError: list indices must be integers, not list?</a></p> <p>But didn't see the answer in either of them for what I'm trying to do and I don't believe <code>iterrows()</code> or <code>itertuple()</code> would apply since I need Pandas to find the values first.</p>
2
2016-08-20T23:39:35Z
39,061,796
<p>First things first. You have an error in your logic in that when you establish your <code>for</code> loop, you use the things in <code>people</code> as if they are indices for the list <code>people</code> when they are the things in <code>people</code>. So instead, do</p> <pre><code>def pull_score(df, people, score): for i in people: print df.loc[df.Name == i, score] the_names = ['John Doe', 'Jane Doe', 'Bob Smith'] pull_score(df, the_names, 'Score2') 0 3 Name: Score2, dtype: int64 1 4 Name: Score2, dtype: int64 2 5 Name: Score2, dtype: int64 </code></pre> <hr> <p>Now that that has been said, I'll jump on the same band-wagon the other answerers are on in stating that there are better ways of doing this using built in pandas functionality. Below are my attempts at capturing what each of the solutions are trying to do in a function named after the user providing the solution. I'll propose that <strong><code>pir</code></strong> is the most efficient as it is using functionality designed to do exactly this task.</p> <pre><code>def john(df, people, score): s = pd.Series([]) for i in people: s = s.append(df.loc[df['Name'] == i, score]) return s def psidom(df, people, score): return df.set_index('Name').loc[people, score] def pir(df, people, score): return df.loc[df['Name'].isin(people), score] </code></pre> <h3>Timing</h3> <p><a href="http://i.stack.imgur.com/qZg43.png" rel="nofollow"><img src="http://i.stack.imgur.com/qZg43.png" alt="enter image description here"></a></p>
2
2016-08-21T07:18:39Z
[ "python", "pandas" ]
How can I connect multiple if statements when using regular expressions?
39,059,664
<p>Below is the code for a password verification process with at least one lowercase, one uppercase and one number.</p> <pre><code>import re password=raw_input('Enter the Password') x= (re.findall(r'[a-z]',password)) if len(x)==0: print " at least one 'a-z' requirment not completed" else: #(what should i write here to connect this to the next step?) y=(re.findall(r'[A-Z',password)) if len(y)==0: print "at least one 'A-Z' requirement not completed" else: #(what should i write here?) z=(re.findall(r'[0-9]',password)) if len(z)==0: print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre> <p>My desire is to let Python run in such a way that if <code>x</code> is not 0, then go ahead and verify if <code>y</code> is equal to 0. If not, verify <code>z</code> is not equal to 0. If not, tell the user that the password is good.</p>
1
2016-08-20T23:44:54Z
39,059,715
<p>Basically, your else clause is just going to be the next statement, like so. You pretty much wrote it, all you have to do is indent each of the check.</p> <pre><code> import re password=raw_input('Enter the Password') x= (re.findall(r'[a-z]',password)) if len(x)==0: print " at least one 'a-z' requirment not completed" else: y=(re.findall(r'[A-Z',password)) if len(y)==0: print "at least one 'A-Z' requirement not completed" else: z=(re.findall(r'[0-9]',password)) if len(z)==0: print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre> <p>option 2:</p> <pre><code> import re password=raw_input('Enter the Password') if not (re.findall(r'[a-z]',password)): print " at least one 'a-z' requirment not completed" elif not (re.findall(r'[A-Z',password)): print "at least one 'A-Z' requirement not completed" elif not (re.findall(r'[0-9]',password)): print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre>
0
2016-08-20T23:57:23Z
[ "python", "python-2.7" ]
How can I connect multiple if statements when using regular expressions?
39,059,664
<p>Below is the code for a password verification process with at least one lowercase, one uppercase and one number.</p> <pre><code>import re password=raw_input('Enter the Password') x= (re.findall(r'[a-z]',password)) if len(x)==0: print " at least one 'a-z' requirment not completed" else: #(what should i write here to connect this to the next step?) y=(re.findall(r'[A-Z',password)) if len(y)==0: print "at least one 'A-Z' requirement not completed" else: #(what should i write here?) z=(re.findall(r'[0-9]',password)) if len(z)==0: print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre> <p>My desire is to let Python run in such a way that if <code>x</code> is not 0, then go ahead and verify if <code>y</code> is equal to 0. If not, verify <code>z</code> is not equal to 0. If not, tell the user that the password is good.</p>
1
2016-08-20T23:44:54Z
39,059,721
<pre><code>import re password=raw_input('Enter the Password: ') problems = [] x = re.findall(r'[a-z]',password) if not x: problems.append("at least one 'a-z' requirment not completed") y = re.findall(r'[A-Z]',password) if not y: problems.append("at least one 'A-Z' requirement not completed") z = re.findall(r'[0-9]',password) if not z: problems.append("at least one '0-9' requirment not completed") if problems: print ' There were some problems with your password: ' + ', '.join(problems) else: print ' Good password!' </code></pre>
1
2016-08-20T23:59:13Z
[ "python", "python-2.7" ]
How can I connect multiple if statements when using regular expressions?
39,059,664
<p>Below is the code for a password verification process with at least one lowercase, one uppercase and one number.</p> <pre><code>import re password=raw_input('Enter the Password') x= (re.findall(r'[a-z]',password)) if len(x)==0: print " at least one 'a-z' requirment not completed" else: #(what should i write here to connect this to the next step?) y=(re.findall(r'[A-Z',password)) if len(y)==0: print "at least one 'A-Z' requirement not completed" else: #(what should i write here?) z=(re.findall(r'[0-9]',password)) if len(z)==0: print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre> <p>My desire is to let Python run in such a way that if <code>x</code> is not 0, then go ahead and verify if <code>y</code> is equal to 0. If not, verify <code>z</code> is not equal to 0. If not, tell the user that the password is good.</p>
1
2016-08-20T23:44:54Z
39,059,754
<p>Here is a way to do it only using string methods! </p> <pre><code>p = raw_input('enter password') if p.islower() or p.isupper() or not any(c.isdigit() for c in p): print('bad password') </code></pre>
1
2016-08-21T00:09:11Z
[ "python", "python-2.7" ]
How can I connect multiple if statements when using regular expressions?
39,059,664
<p>Below is the code for a password verification process with at least one lowercase, one uppercase and one number.</p> <pre><code>import re password=raw_input('Enter the Password') x= (re.findall(r'[a-z]',password)) if len(x)==0: print " at least one 'a-z' requirment not completed" else: #(what should i write here to connect this to the next step?) y=(re.findall(r'[A-Z',password)) if len(y)==0: print "at least one 'A-Z' requirement not completed" else: #(what should i write here?) z=(re.findall(r'[0-9]',password)) if len(z)==0: print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre> <p>My desire is to let Python run in such a way that if <code>x</code> is not 0, then go ahead and verify if <code>y</code> is equal to 0. If not, verify <code>z</code> is not equal to 0. If not, tell the user that the password is good.</p>
1
2016-08-20T23:44:54Z
39,059,811
<p>Use <code>if-elif</code> statement:</p> <pre><code>import re password=raw_input('Enter the Password') if len(re.findall(r'[a-z]',password))==0: print " at least one 'a-z' requirment not completed" elif len(re.findall(r'[A-Z]',password)) == 0: print "at least one 'A-Z' requirement not completed" elif len(re.findall(r'[0-9]',password)) == 0: print "at least one '0-9' requirment not completed" else: print ' Good password!' </code></pre> <p>A demo:</p> <pre><code>Enter the Password Axa3 Good password! Enter the Password aa3 at least one 'A-Z' requirement not completed Enter the Password A3443E at least one 'a-z' requirment not completed </code></pre>
2
2016-08-21T00:19:34Z
[ "python", "python-2.7" ]
Batch processing and breaking up an image
39,059,668
<p>I'm trying to segment each charm item in this collective image.</p> <p>The shapes are irregular and inconsistent:</p> <p><a href="https://i.imgur.com/sf8nOau.jpg" rel="nofollow">https://i.imgur.com/sf8nOau.jpg</a></p> <p>I have another image where there is some consistency with the top row of items, but ideally I'd be able to process and brake up all items in one go:</p> <p><a href="http://i.imgur.com/WiiYBay.jpg" rel="nofollow">http://i.imgur.com/WiiYBay.jpg</a></p> <p>I have no experience with opencv so I'm just looking for best possible tool or approach to take. I've read about background subtraction as well as color clustering, but I'm not sure about those either.</p> <p>Any ideas on how to best approach this? Thanks.</p>
1
2016-08-20T23:45:29Z
39,061,539
<h1>Code</h1> <pre><code>import cv2 import numpy as np im=cv2.imread('so1.jpg') gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) kernel = np.ones((3,3),np.uint8) res = cv2.dilate(thresh,kernel,iterations = 1) res = cv2.erode(res,kernel,iterations = 1) res = cv2.dilate(res,kernel,iterations = 1) cv2.imshow('thresh',res) _,contours, hierarchy = cv2.findContours(res.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2) cv2.imshow('image',im) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <h1>Output</h1> <p><a href="http://i.stack.imgur.com/Mrcx1.png" rel="nofollow"><img src="http://i.stack.imgur.com/Mrcx1.png" alt="enter image description here"></a></p> <p>Now having the contours you can crop them out</p> <h1>Code Update</h1> <pre><code>import cv2 import numpy as np im=cv2.imread('so.jpg') gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) kernel = np.ones((3,3),np.uint8) res = cv2.dilate(thresh,kernel,iterations = 1) res = cv2.erode(res,kernel,iterations = 1) res = cv2.dilate(res,kernel,iterations = 8) cv2.imshow('thresh',res) _,contours, hierarchy = cv2.findContours(res.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) count=0 for cnt in contours: blank=np.zeros(im.shape,dtype=np.uint8) x,y,w,h = cv2.boundingRect(cnt) epsilon = 0.001*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) cv2.fillConvexPoly(blank,approx,(255, 255, 255)) masked_image = cv2.bitwise_and(im, blank) cv2.imwrite('results_so/im'+str(count)+'.jpg',masked_image[y:y+h,x:x+w]) count+=1 cv2.imshow('image',im) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <h1>results</h1> <h2>good one</h2> <p><a href="http://i.stack.imgur.com/3dLH6.png" rel="nofollow"><img src="http://i.stack.imgur.com/3dLH6.png" alt="enter image description here"></a></p> <h2>bad one</h2> <p><a href="http://i.stack.imgur.com/Wf3QD.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wf3QD.png" alt="enter image description here"></a></p> <p>Some small noises are also detected as objects you can eliminate those by only taking contours whose area is greater than a certain value .</p>
3
2016-08-21T06:44:04Z
[ "python", "opencv" ]
Object orientated function parameter to alter variables
39,059,671
<p>I am trying convert my program to an object orientated style. Currently, I have a brandSelector() function which takes the query input and finds an intersection between the query and the brands array. However, I am trying to convert the brandSelector() to a generic Selector() or intersection finder. For example, I could call with type and the query (Selector(type, query)). In this instance you would type Selector(brand, query). That additional parameter defines which array is checked and which variable is set - alternatively, an if statement would suffice - but I am not sure how to implement such a system. I would appreciate any solutions or advice. Thanks,</p> <pre><code>brands = ["apple", "android", "windows"] brand = None def Main(): query = input("Enter your query: ").lower() brand = brandSelector(query) def brandSelector(query): try: 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") return brand except NameError: print("\nNo Intersection found between query defined brand and brands array\n") return brandDetectionFailure() </code></pre> <p>Full Code: <a href="https://github.com/KentCoding/phoneTroubleshooting/blob/master/phoneTroubleshooting.py" rel="nofollow">https://github.com/KentCoding/phoneTroubleshooting/blob/master/phoneTroubleshooting.py</a> Python Version: v3.5.2</p> <p>My Attempt:</p> <pre><code>def Main(): init() query = input("Enter your query: ").lower() brand = Selector(brand, brands, query) keywordSelection(query, brand) def Selector(var, array, query): try: #Format Brands Query var = set(array).intersection(query.split()) var = ', '.join(var) #Check Condition After Setting int_cond = confirmIntersection(var) if int_cond == False: raise NameError("No Intersection") return var except NameError: print("\nNo Intersection found between query defined brand and brands array\n") return brandDetectionFailure() </code></pre> <p>But gives the error: <code>UnboundLocalError: local variable 'brand' referenced before assignment</code></p>
1
2016-08-20T23:45:59Z
39,059,787
<p>From what I can see, there's no reason to have the argument named <code>var</code> being passed to <code>Selector()</code>, so just make it <code>def Selector(array, query):</code> and call it with <code>brand = Selector(brands, query)</code>.</p>
1
2016-08-21T00:14:18Z
[ "python", "function", "oop", "parameters" ]
confused about Python list syntax
39,059,714
<p>Here is the code and related document (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html#sklearn.datasets.load_iris" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html#sklearn.datasets.load_iris</a>), I am confused by this line, <code>data.target[[10, 25, 50]]</code>, confused why using double <code>[[]]</code>, if anyone could clarify, it will be great.</p> <pre><code>from sklearn.datasets import load_iris data = load_iris() print data.target[[10, 25, 50]] print list(data.target_names) </code></pre> <p>thanks in advance, Lin</p>
1
2016-08-20T23:57:14Z
39,059,758
<p>Your confusion is understandable: this isn't "standard" Python by any means.</p> <p><code>data.target</code> in this case is an <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow"><code>ndarray</code></a> from numpy:</p> <pre><code>In [1]: from sklearn.datasets import load_iris ...: data = load_iris() ...: print data.target[[10, 25, 50]] ...: print list(data.target_names) [0 0 1] ['setosa', 'versicolor', 'virginica'] In [2]: print type(data.target) &lt;type 'numpy.ndarray'&gt; </code></pre> <p>numpy's ndarray implementation allows you to create a new array by providing a list of indices of the items you want. For example:</p> <pre><code>In [13]: data.target Out[13]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]) In [14]: data.target[1] Out[14]: 0 In [15]: data.target[[1,2,3]] Out[15]: array([0, 0, 0]) In [16]: print type(data.target[[1,2,3]]) &lt;type 'numpy.ndarray'&gt; </code></pre> <p>and it likely does this by <a href="http://stackoverflow.com/questions/1957780/how-to-override-operator">overriding <code>__getitem__</code></a>.</p> <p>For more information, see <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">Indexing</a> in the NumPy array documentation:</p>
1
2016-08-21T00:09:29Z
[ "python", "python-2.7", "numpy", "scikit-learn" ]
confused about Python list syntax
39,059,714
<p>Here is the code and related document (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html#sklearn.datasets.load_iris" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html#sklearn.datasets.load_iris</a>), I am confused by this line, <code>data.target[[10, 25, 50]]</code>, confused why using double <code>[[]]</code>, if anyone could clarify, it will be great.</p> <pre><code>from sklearn.datasets import load_iris data = load_iris() print data.target[[10, 25, 50]] print list(data.target_names) </code></pre> <p>thanks in advance, Lin</p>
1
2016-08-20T23:57:14Z
39,059,812
<p>This is retrieving elements from a numpy array <code>A</code> using "integer indexing" syntax (as opposed to the usual subscripts), i.e. a list of integers <code>B</code> will be used to find elements at those particular indices in <code>A</code>. Your output is a numpy array with the same shape as the list <code>B</code> that you use as "input", and the values of the output elements are obtained from the values of <code>A</code> at those integer indices e.g.:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array([0,1,4,9,16,25,36,49,64,81]) &gt;&gt;&gt; a[[1,4,4,1,5,6,6,5]] array([ 1, 16, 16, 1, 25, 36, 36, 25]) </code></pre> <p>Integer indexing can be applied to more than one dimensions, e.g.:</p> <pre><code>&gt;&gt;&gt; b = numpy.array([[0,1,4,9,16],[25,36,49,64,81]]) # 2D array &gt;&gt;&gt; b[[0,1,0,1,1,0],[0,1,4,3,2,3]] # row and column integer indices array([ 0, 36, 16, 64, 49, 9]) </code></pre> <p>or, the same example but with an input list of <em>2</em> dimensions, affecting the <em>output</em> shape:</p> <pre><code>&gt;&gt;&gt; b[[[0,1,0],[1,1,0]],[[0,1,4],[3,2,3]]] # "row" and "column" 2D integer arrays array([[ 0, 36, 16], [64, 49, 9]]) </code></pre> <p>Also note that you can perform "integer indexing" using a numpy array as well, rather than a list, e.g.</p> <pre><code>&gt;&gt;&gt; a[numpy.array([0,3,2,4,1])] array([ 0, 9, 4, 16, 1]) </code></pre>
1
2016-08-21T00:19:37Z
[ "python", "python-2.7", "numpy", "scikit-learn" ]
using matplotlib on Mac for Python 2.7
39,059,732
<p>Wondering if anyone have met with similar issues on Mac OSX? If so, how do you resolve? Thanks.</p> <p>Here are document, code and error message,</p> <p><a href="http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html</a></p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Logistic Regression 3-class Classifier ========================================================= Show below is a logistic-regression classifiers decision boundaries on the `iris &lt;http://en.wikipedia.org/wiki/Iris_flower_data_set&gt;`_ dataset. The datapoints are colored according to their labels. """ print(__doc__) # Code source: Gaël Varoquaux # Modified for documentation by Jaques Grobler # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, datasets # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. Y = iris.target h = .02 # step size in the mesh logreg = linear_model.LogisticRegression(C=1e5) # we create an instance of Neighbours Classifier and fit the data. logreg.fit(X, Y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure(1, figsize=(4, 3)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show() </code></pre> <hr> <pre><code>Traceback (most recent call last): File "/Users/foo/personal/law/justech/featureExtraction/testLogisticRegression.py", line 22, in &lt;module&gt; import matplotlib.pyplot as plt File "/Users/foo/miniconda2/lib/python2.7/site-packages/matplotlib/pyplot.py", line 114, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/Users/foo/miniconda2/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/Users/foo/miniconda2/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 24, in &lt;module&gt; from matplotlib.backends import _macosx RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are Working with Matplotlib in a virtual enviroment see 'Working with Matplotlib in Virtual environments' in the Matplotlib FAQ </code></pre>
1
2016-08-21T00:02:06Z
39,059,779
<p>Are you using a virtual enviorment? Right now it thinks your python isn't a framework. in your terminal run </p> <pre><code>which python </code></pre> <p>and make sure it returns</p> <pre><code>/Library/Frameworks/Python.framework/Versions/2.7/bin/python </code></pre> <p>you can always intall python as a framework at python <a href="https://www.python.org/downloads/" rel="nofollow">https://www.python.org/downloads/</a></p>
1
2016-08-21T00:12:23Z
[ "python", "python-2.7", "matplotlib", "scikit-learn" ]
How to see the subscribers count of a youtube channel using the gdata api in python
39,059,797
<p>im trying to make a raspberry pi youtube sub monitor and im confused about how to get the sub count from youtube channel in python.an example code to do so would be much appreciated. </p>
-1
2016-08-21T00:17:08Z
39,066,043
<p>Please make yourself familiar with the <a href="https://developers.google.com/youtube/v3/getting-started" rel="nofollow">basic YouTube Data API v3 workflows</a> first.</p> <p>There are different ways to use the API with Python. Since your application does not seem to be very complex, you could <a href="https://developers.google.com/youtube/v3/docs/channels/list" rel="nofollow">directly perform a request to the API</a> with one of Python's HTTP libraries (depends on your Python version).</p> <p>Alternatively, you can use the <a href="https://developers.google.com/api-client-library/python/" rel="nofollow">Python client library</a> (<a href="https://developers.google.com/youtube/v3/code_samples/#python" rel="nofollow">examples</a>).</p> <p>In any case, you will need to register an application and <a href="https://console.cloud.google.com/apis/credentials" rel="nofollow">obtain an API key in the Google Cloud Console</a>.</p>
0
2016-08-21T15:50:48Z
[ "python", "google-api", "youtube-api", "youtube-data-api", "gdata" ]
How to see the subscribers count of a youtube channel using the gdata api in python
39,059,797
<p>im trying to make a raspberry pi youtube sub monitor and im confused about how to get the sub count from youtube channel in python.an example code to do so would be much appreciated. </p>
-1
2016-08-21T00:17:08Z
39,071,642
<p>Make a REST call in PYTHON using this URI request:</p> <pre><code>GET https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&amp;mySubscribers=true&amp;fields=pageInfo&amp;key={YOUR_API_KEY} </code></pre> <p>The totalResults key holds the number of subscribers. An example of response I got looked like this:</p> <pre><code>{ "pageInfo": { "totalResults": 2, "resultsPerPage": 5 } } </code></pre> <p>in this case, it's 2 subscribers.</p> <p>I suggest you study <a href="https://developers.google.com/drive/v3/web/quickstart/python" rel="nofollow">Python Quickstarts</a> code structure and learn how to make the REST call.</p> <p>Check <a href="https://developers.google.com/youtube/v3/docs/subscriptions/list" rel="nofollow">Subscriptions: list</a> for additional info, especially the Try-It section so you can see the results immediately.</p>
0
2016-08-22T04:55:27Z
[ "python", "google-api", "youtube-api", "youtube-data-api", "gdata" ]
Handling recursive error tracebacks in python
39,059,859
<p>I'm working on implementing a small programming languge in Python for the hell of it, and the language's execution basically consists of recursive calls to a function called <code>execute</code>. I've implemented my own error handling, but in order to have that error handling work I need to catch some exceptions and throw them as my own types, resulting in code that looks something like this:</p> <pre><code>def execute(...): try: try: # do stuff except IndexError: raise MyIndexError() except MyErrorBase as e: raise MyErrorBase(e, newTracebackLevel) # add traceback level for this depth </code></pre> <p>I really hate the nested <code>try</code> blocks... is there any way to fix this?</p>
1
2016-08-21T00:27:45Z
39,059,894
<p>You need to set try statements when ever needed. </p> <p>Put it only on start of execution.</p> <p>try statement is basically is a longjump. You want to do some long tasks which may fail at any place in the code it can be in inner calls. longjump helps you to catch fails.</p> <p>In lua language there's method called pcall. (protected call) Whenever it invokes at error the call returns error status and error message is taken as the second return value. </p>
0
2016-08-21T00:36:11Z
[ "python", "recursion", "error-handling" ]
Handling recursive error tracebacks in python
39,059,859
<p>I'm working on implementing a small programming languge in Python for the hell of it, and the language's execution basically consists of recursive calls to a function called <code>execute</code>. I've implemented my own error handling, but in order to have that error handling work I need to catch some exceptions and throw them as my own types, resulting in code that looks something like this:</p> <pre><code>def execute(...): try: try: # do stuff except IndexError: raise MyIndexError() except MyErrorBase as e: raise MyErrorBase(e, newTracebackLevel) # add traceback level for this depth </code></pre> <p>I really hate the nested <code>try</code> blocks... is there any way to fix this?</p>
1
2016-08-21T00:27:45Z
39,059,896
<p>If you <em>really</em> want to do this, try creating a mapping between base exception types and your new exception types:</p> <pre><code>exceptionMap = { IndexError: MyIndexError, # ... } def execute(...): try: # do stuff except tuple(exceptionMap) as e: raise exceptionMap[type(e)](e, newTracebackLevel) </code></pre> <p>Example:</p> <pre><code>In [33]: exceptionMap = {IndexError: RuntimeError} In [34]: a = [] In [35]: try: ...: a[1] ...: except tuple(exceptionMap) as e: ...: raise exceptionMap[type(e)](str(e)) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-35-bc6fdfc44fbe&gt; in &lt;module&gt;() 2 a[1] 3 except tuple(exceptionMap) as e: ----&gt; 4 raise exceptionMap[type(e)](str(e)) 5 6 RuntimeError: list index out of range </code></pre>
0
2016-08-21T00:36:23Z
[ "python", "recursion", "error-handling" ]
SciPy on Windows with Python 2.7 install issues
39,059,903
<p>Wondering if anyone met with similar issues and have solutions already? Using Windows 7.</p> <pre><code>C:\Python27\Scripts&gt;pip install SciPy Collecting SciPy Using cached scipy-0.18.0.tar.gz Installing collected packages: SciPy Running setup.py install for SciPy ... error Complete output from command c:\python27\python.exe -u -c "import setuptools , tokenize;__file__='c:\\users\\foo\\appdata\\local\\temp\\pip-build-r3jpxr\\ SciPy\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().r eplace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\foo\appda ta\local\temp\pip-efo9to-record\install-record.txt --single-version-externally-m anaged --compile: Note: if you need reliable uninstall behavior, then install with pip instead of using `setup.py install`: - `pip install .` (from a git repo or downloaded source release) - `pip install scipy` (last SciPy release on PyPI) lapack_opt_info: openblas_lapack_info: libraries openblas not found in ['c:\\python27\\lib', 'C:\\', 'c:\\python2 7\\libs'] NOT AVAILABLE lapack_mkl_info: mkl_info: libraries mkl,vml,guide not found in ['c:\\python27\\lib', 'C:\\', 'c:\\py thon27\\libs'] NOT AVAILABLE NOT AVAILABLE atlas_3_10_threads_info: Setting PTATLAS=ATLAS c:\python27\lib\site-packages\numpy\distutils\system_info.py:639: UserWarnin g: Specified path C:\projects\windows-wheel-builder\atlas-builds\atlas-3.11.38-s se2-64\lib is invalid. warnings.warn('Specified path %s is invalid.' % d) &lt;class 'numpy.distutils.system_info.atlas_3_10_threads_info'&gt; NOT AVAILABLE atlas_3_10_info: &lt;class 'numpy.distutils.system_info.atlas_3_10_info'&gt; NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS &lt;class 'numpy.distutils.system_info.atlas_threads_info'&gt; NOT AVAILABLE atlas_info: &lt;class 'numpy.distutils.system_info.atlas_info'&gt; NOT AVAILABLE c:\python27\lib\site-packages\numpy\distutils\system_info.py:1548: UserWarni ng: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) lapack_info: libraries lapack not found in ['c:\\python27\\lib', 'C:\\', 'c:\\python27\ \libs'] NOT AVAILABLE c:\python27\lib\site-packages\numpy\distutils\system_info.py:1559: UserWarni ng: Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable. warnings.warn(LapackNotFoundError.__doc__) lapack_src_info: NOT AVAILABLE c:\python27\lib\site-packages\numpy\distutils\system_info.py:1562: UserWarni ng: Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable. warnings.warn(LapackSrcNotFoundError.__doc__) NOT AVAILABLE Running from scipy source directory. Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\users\foo\appdata\local\temp\pip-build-r3jpxr\SciPy\setup.py", line 415, in &lt;module&gt; setup_package() File "c:\users\foo\appdata\local\temp\pip-build-r3jpxr\SciPy\setup.py", line 411, in setup_package setup(**metadata) File "c:\python27\lib\site-packages\numpy\distutils\core.py", line 135, in setup config = configuration() File "c:\users\foo\appdata\local\temp\pip-build-r3jpxr\SciPy\setup.py", line 335, in configuration config.add_subpackage('scipy') File "c:\python27\lib\site-packages\numpy\distutils\misc_util.py", line 10 03, in add_subpackage caller_level = 2) File "c:\python27\lib\site-packages\numpy\distutils\misc_util.py", line 97 2, in get_subpackage caller_level = caller_level + 1) File "c:\python27\lib\site-packages\numpy\distutils\misc_util.py", line 90 9, in _get_configuration_from_setup_py config = setup_module.configuration(*args) File "scipy\setup.py", line 15, in configuration config.add_subpackage('linalg') File "c:\python27\lib\site-packages\numpy\distutils\misc_util.py", line 10 03, in add_subpackage caller_level = 2) File "c:\python27\lib\site-packages\numpy\distutils\misc_util.py", line 97 2, in get_subpackage caller_level = caller_level + 1) File "c:\python27\lib\site-packages\numpy\distutils\misc_util.py", line 90 9, in _get_configuration_from_setup_py config = setup_module.configuration(*args) File "scipy\linalg\setup.py", line 20, in configuration raise NotFoundError('no lapack/blas resources found') numpy.distutils.system_info.NotFoundError: no lapack/blas resources found ---------------------------------------- Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\ \users\\foo\\appdata\\local\\temp\\pip-build-r3jpxr\\SciPy\\setup.py';exec(co mpile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __ file__, 'exec'))" install --record c:\users\foo\appdata\local\temp\pip-efo9to -record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\foo\appdata\local\temp\pip-build-r3jpxr\SciPy\ </code></pre> <p><strong>Edit 1</strong>, tried <code>pip install scipy-0.18.0-cp27-cp27m-win_amd64.whl</code>, but met with strange issues,</p> <pre><code>C:\Python27\Scripts&gt;pip install scipy-0.18.0-cp27-cp27m-win_amd64.whl Requirement 'scipy-0.18.0-cp27-cp27m-win_amd64.whl' looks like a filename, but t he file does not exist Processing c:\python27\scripts\scipy-0.18.0-cp27-cp27m-win_amd64.whl Exception: Traceback (most recent call last): File "c:\python27\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\python27\lib\site-packages\pip\commands\install.py", line 299, in run requirement_set.prepare_files(finder) File "c:\python27\lib\site-packages\pip\req\req_set.py", line 370, in prepare_ files ignore_dependencies=self.ignore_dependencies)) File "c:\python27\lib\site-packages\pip\req\req_set.py", line 587, in _prepare _file session=self.session, hashes=hashes) File "c:\python27\lib\site-packages\pip\download.py", line 798, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "c:\python27\lib\site-packages\pip\download.py", line 705, in unpack_file _url unpack_file(from_path, location, content_type, link) File "c:\python27\lib\site-packages\pip\utils\__init__.py", line 599, in unpac k_file flatten=not filename.endswith('.whl') File "c:\python27\lib\site-packages\pip\utils\__init__.py", line 482, in unzip _file zipfp = open(filename, 'rb') IOError: [Errno 2] No such file or directory: 'C:\\Python27\\Scripts\\scipy-0.18 .0-cp27-cp27m-win_amd64.whl' </code></pre>
0
2016-08-21T00:39:24Z
39,060,196
<p>Some packages, such as Scipy, require a compiler to be built using pip. Windows does not come with a compiler included, so you need to download a scipy binary file that windows can work with. </p> <p>A wonderful man named Christopher Gohlke from UC Irvine has developed these binaries for windows. You can find them <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy" rel="nofollow">here</a>. </p> <p>Note: If you do not have Numpy installed, you cannot install SciPy. you will also need to download the Numpy Binary (also found <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" rel="nofollow">here</a>). Just follow the subsequent steps to download the numpy module the same way you would download the scipy module. </p> <p>Which link you install depends on whether you have a 64 bit or a 32 bit version of python, which you can check by just using the python command on your command line if you have it installed onto your PATH. Here is it visualized:</p> <pre><code>C:\Users\Bobby&gt;python Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32 </code></pre> <p>You can find your version in the brackets. As you can see, I am running a 64 bit version of python. So I would downloaded the "scipy-0.18.0-cp27-cp27m-win_amd64.whl" file, which assumes that I am running python 2.7 (indicated byy cp27) on a 64 bit version of python (indicated by amd64). </p> <p>Note: Also make sure that pip is updated. You can update it by using the following command:</p> <pre><code>C:\Users\Bobby\Downloads&gt;pip install --upgrade pip </code></pre> <p>Once the SciPy binary downloaded, change your working directory to your downloads folder and run pip, but use the .whl file in your downloads. Here is it visualized:</p> <pre><code>C:\Users\Bobby&gt;cd Downloads C:\Users\Bobby\Downloads&gt;pip install scipy-0.18.0-cp27-cp27m-win_amd64.whl Processing c:\users\bobby\downloads\scipy-0.18.0-cp27-cp27m-win_amd64.whl Installing collected packages: scipy Successfully installed scipy-0.18.0 </code></pre>
2
2016-08-21T01:53:23Z
[ "python", "windows", "python-2.7", "windows-7", "scipy" ]
Best way to refer to other instances of a class or other objects?
39,059,915
<p>I have a Network(object) and Node(object) classes, and each node belongs to a different network (there are also link objects that connects nodes, etc, but let's ignore this). What is the best way to keep track which object is in which network and vice versa?</p> <p>What I am doing now is to have a dictionary attribute in the Network(object), the keys of which are names of Node objects, and the values are the objects themselves, and also a networkidx attribute in each node class, and global networks dictionary with networkidx's as keys, and the Network objects as values. </p> <p>Here's a minimal example. The network has an internal clock and when the node is activated it retrieves the time of the network and stores it as a timestamp on the node.</p> <pre><code>class Network(object): def __init__(self, networkidx): self.networkidx = networkidx self.nodes = {} self.internalclock = 1 def create_node(self, nodeidx): self.nodes[nodeidx] = Node(self.networkidx, nodeidx) def pass_time(self, time): self.internalclock = self.internalclock + time class Node(object): def __init__(self, networkidx, nodeidx): self.networkidx = networkidx self.nodeidx = nodeidx self.activation_timestamps = [] def activate(self): current_time = networks[self.networkidx].internalclock self.activation_timestamps.append(current_time) networks = {} networks['net1'] = Network('net1') networks['net1'].create_node('node1') networks['net1'].nodes['node1'].activate() networks['net1'].pass_time(10) networks['net1'].nodes['node1'].activate() print networks['net1'].nodes['node1'].activation_timestamps </code></pre> <p>Everything works just fine, and I have many more methods and references between nodes and the network, etc. What I am wondering if this is the best way to keep track of object relations, what are the best practices, etc.</p>
0
2016-08-21T00:41:43Z
39,060,004
<p>This is pretty good way to keep track of reasonable amount of entries at one execution. But not if you want it to be persistent.</p> <p>If you can order the nodes by some valuable property you got a even better way. +it can be easily persistent</p> <p>For example i had this issue myself. I was trying to implement javascript function setTimeout on lua.</p> <p>The way i thought is that return id is increasing by one on every call. So there's indirect method to refer to an entry.</p> <p>More importantly was my usage. I only needed to see which entry is the one to call. So i did sort the entries by the execution time.</p> <p>Another is to sort entries as you insert new one. When we have a ordered list. Adding new entry costs O(log(n)). By using bisection search and insert at appropriate place.</p>
0
2016-08-21T01:02:47Z
[ "python", "class" ]
ImportError: No module named services Django
39,060,020
<p>I installed python 2.7 alongside my mac. I have a project running using Django v1.9.4. Unfortunately <code>manage.py runserver</code> is throwing an error while running failed because it couldn't find module named services.</p> <p>From a shell:</p> <pre><code>Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/Library/Python/2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named services </code></pre> <p>I'm wondering what should be done here to install this module.</p>
0
2016-08-21T01:06:48Z
39,060,370
<p>It seems that 'services' is your project's module. Maybe you should set the PYTHONPATH environment to make python find your module. If the module is in current directory, you can run the project like this: export PYTHONPATH=.:$PYTHONPATH manage.py runserver</p>
1
2016-08-21T02:34:06Z
[ "python", "django", "python-2.7", "backend" ]
Graph only shows the data in 1 graph but not the other
39,060,073
<p>I'm having trouble with my code. It's only showing the data for one graph and the other graph is blank. I can't figure why it's not working.<br> I'm using the <code>subplot()</code> function and my guess is that the the reason might be the way my function are formatted.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import cvxopt as opt from cvxopt import blas, solvers import pandas as pd import mpld3 from mpld3 import plugins np.random.seed(123) solvers.options['show_progress'] = False n_assets = 4 n_obs = 1000 # original 1000 return_vec = np.random.randn(n_assets, n_obs) def rand_weights(n): k = np.random.rand(n) return k / sum(k) print(rand_weights(n_assets)) print(rand_weights(n_assets)) def random_portfolio(returns): p = np.asmatrix(np.mean(returns,axis=1)) w = np.asmatrix(rand_weights(returns.shape[0])) C = np.asmatrix(np.cov(returns)) mu = w * p.T sigma = np.sqrt(w * C * w.T) #this recursion reduces outlier to keep the graph nice if sigma &gt; 2: return random_portfolio(returns) return mu, sigma n_portfolios = 500 means, stds = np.column_stack([random_portfolio(return_vec) for _ in range(n_portfolios)]) plt.plot(return_vec.T, alpha=.4); plt.xlabel('time') plt.ylabel('returns') plt.figure(1) plt.subplot(212) plt.plot(stds, means, 'o', markersize = 5) plt.xlabel('std') plt.ylabel('mean') plt.title('Mean and standard deviation of returns of randomly generated portfolios') plt.subplot(211) plt.figure(1) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/oxvyB.png" rel="nofollow"><img src="http://i.stack.imgur.com/oxvyB.png" alt="my graph"></a></p>
1
2016-08-21T01:21:48Z
39,060,084
<p>You need to move the line <code>plt.subplot(211)</code> before your first call to <code>plt.plot</code>. This is because calls to <code>plt.subplot</code> must precede the actual plotting in that subplot.</p>
2
2016-08-21T01:25:31Z
[ "python", "python-3.x", "matplotlib" ]
How to do exception handling in python?
39,060,162
<pre><code>elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: elem.click() </code></pre> <p>In my code <code>elem.click()</code> gets gives an error sometimes. If it does, I need to call <code>elem = browser.find_element_by_xpath</code> again i.e. the first line of the code.</p> <p>Is there a way to achieve this using exception handling in python. Help will be much appreciated. </p>
-1
2016-08-21T01:44:38Z
39,060,176
<p>You need try/except statement there.</p> <pre><code>try: elem.click() except Exception: # you need to find out which exception type is raised pass # do somthing else ... </code></pre>
0
2016-08-21T01:49:34Z
[ "python", "python-2.7", "exception-handling" ]
How to do exception handling in python?
39,060,162
<pre><code>elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: elem.click() </code></pre> <p>In my code <code>elem.click()</code> gets gives an error sometimes. If it does, I need to call <code>elem = browser.find_element_by_xpath</code> again i.e. the first line of the code.</p> <p>Is there a way to achieve this using exception handling in python. Help will be much appreciated. </p>
-1
2016-08-21T01:44:38Z
39,060,185
<p>generic way to handle exception in python is</p> <pre><code>try: 1/0 except Exception, e: print e </code></pre> <p>So in your case it would give</p> <pre><code>try: elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") except Exception, e: elem = browser.find_element_by_xpath if ( elem.is_selected() ): print "already selected" else: elem.click() </code></pre> <p>It is better to use the more specific exception type. If you use the generic Exception class, you might catch other exception where you want a different handling</p>
0
2016-08-21T01:51:12Z
[ "python", "python-2.7", "exception-handling" ]
How to do exception handling in python?
39,060,162
<pre><code>elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: elem.click() </code></pre> <p>In my code <code>elem.click()</code> gets gives an error sometimes. If it does, I need to call <code>elem = browser.find_element_by_xpath</code> again i.e. the first line of the code.</p> <p>Is there a way to achieve this using exception handling in python. Help will be much appreciated. </p>
-1
2016-08-21T01:44:38Z
39,060,190
<p>Look at <code>try</code> and <code>except</code></p> <pre><code>while elem == None: try: elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: elem.click() except Exception, e: elem = None </code></pre> <p>Obviously using the specific exception that is raised from the click.</p>
0
2016-08-21T01:52:35Z
[ "python", "python-2.7", "exception-handling" ]
How to do exception handling in python?
39,060,162
<pre><code>elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: elem.click() </code></pre> <p>In my code <code>elem.click()</code> gets gives an error sometimes. If it does, I need to call <code>elem = browser.find_element_by_xpath</code> again i.e. the first line of the code.</p> <p>Is there a way to achieve this using exception handling in python. Help will be much appreciated. </p>
-1
2016-08-21T01:44:38Z
39,060,199
<p>From what I can understand this can be done with exception handling. you could try the following:</p> <pre><code>elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input") if ( elem.is_selected() ): print "already selected" else: while True: try: #code to try to run that might cause an error elem.click() except Exception: #code to run if it fails browser.find_element_by_xpath else: #code to run if it is the try is successful break finally: #code to run regardless </code></pre>
2
2016-08-21T01:54:06Z
[ "python", "python-2.7", "exception-handling" ]
Regex to Match Domain Name
39,060,217
<pre><code>^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$ </code></pre> <p>I tried the code above but it would not match any domain no matter how ugly.</p> <p>I am try to match only domain with words and ending in .com</p> <pre><code>Like google.com yahoo.com bing.com Not google.net google.con googl-e.com </code></pre>
-1
2016-08-21T01:59:28Z
39,060,272
<p>I often have problems with the $ in the end, so I'd add \s* after the ^ and before the $ operators, to detect leading/trailing separator-characters. Can't reason too much without knowing the context.</p> <pre><code>^\s*([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}\s*$ </code></pre>
-1
2016-08-21T02:10:25Z
[ "python", "regex" ]
Regex to Match Domain Name
39,060,217
<pre><code>^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$ </code></pre> <p>I tried the code above but it would not match any domain no matter how ugly.</p> <p>I am try to match only domain with words and ending in .com</p> <pre><code>Like google.com yahoo.com bing.com Not google.net google.con googl-e.com </code></pre>
-1
2016-08-21T01:59:28Z
39,060,708
<p>What's the purpose of the <code>-[a-z0-9]+</code> group? I got your six test cases to pass with:</p> <pre><code>import re r = re.compile("^([a-z0-9]+\.)com$") # Like assert r.match('google.com') assert r.match('yahoo.com') assert r.match('bing.com') # Not assert not r.match('google.net') assert not r.match('google.con') assert not r.match('googl-e.com') </code></pre>
1
2016-08-21T03:54:05Z
[ "python", "regex" ]
Regex to Match Domain Name
39,060,217
<pre><code>^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$ </code></pre> <p>I tried the code above but it would not match any domain no matter how ugly.</p> <p>I am try to match only domain with words and ending in .com</p> <pre><code>Like google.com yahoo.com bing.com Not google.net google.con googl-e.com </code></pre>
-1
2016-08-21T01:59:28Z
39,062,862
<p>Your code did not match any because it uses the <code>^</code> and <code>$</code>which matches the start and end of string. To make it match the start and end of a line, you have to enable the multiline option <code>re.M</code>. In addition, use <code>re.I</code> to make it case insensitive which I believe domain names are.</p> <h3>Based on your requirements:</h3> <ol> <li>Ends with <code>.com</code></li> <li>No dashes</li> <li>No numbers </li> </ol> <p><strong>Code</strong>:</p> <pre><code>import re regex = re.compile(r'^[a-z]+\.com$' , re.M | re.I) print(regex.findall("""\ google.com yahoo.com bing.com google.net google.con googl-e.com """)) # =&gt; ['google.com', 'yahoo.com', 'bing.com'] </code></pre> <p><strong>To break it down:</strong></p> <pre><code>^ # To mark the start of line/string [a-z]+ # One or more alphabet \. # match the `.` character com # match the `com` string </code></pre>
0
2016-08-21T09:42:22Z
[ "python", "regex" ]
Using Keras for text classification
39,060,283
<p>I am struggling to approach the bag of words / vocabulary method for representing my input data as one hot vectors for my neural net model in keras. </p> <p>I would like to build a simple 3 layer network but I need help in understanding and developing an approach to transform my labelled data in the form of text,sentinment which is has 7 labels, in the range of 0 - 1 in steps of 0.2. </p> <p>I have tried to use scikit's vectorisers but they are too rigid i.e they either tokenise words or characters, whereas I need a sentence to be compared to the vocabulary which includes words, characters, punctuation and emojis. When i use tfid on a test sentence it only counts the words and ignores everything else. I also need guidance on taking this one hot approach and how it will be implemented in keras.</p> <p>Really appreciate any help,</p> <p>Cheers</p>
0
2016-08-21T02:13:50Z
39,060,552
<p><a href="https://github.com/fchollet/keras/blob/master/examples/reuters_mlp.py" rel="nofollow">Here</a> is a Keras example where they have 8 output classes and use a bag of words.</p>
0
2016-08-21T03:18:47Z
[ "python", "nlp", "keras", "text-classification" ]
numpy issue on Python 2.7 -- numpy.dtype has the wrong size
39,060,353
<p>Wondering if anyone met with similar issues before and any solutions? Using Python 2.7 on Mac OSX.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, datasets # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features. Y = iris.target h = .02 # step size in the mesh logreg = linear_model.LogisticRegression(C=1e5) # we create an instance of Neighbours Classifier and fit the data. logreg.fit(X, Y) Traceback (most recent call last): File "/Users/foo/Downloads/PycharmProjects/testLogisticRegressionSimple.py", line 23, in &lt;module&gt; from sklearn import linear_model, datasets File "/Library/Python/2.7/site-packages/sklearn/__init__.py", line 57, in &lt;module&gt; from .base import clone File "/Library/Python/2.7/site-packages/sklearn/base.py", line 11, in &lt;module&gt; from .utils.fixes import signature File "/Library/Python/2.7/site-packages/sklearn/utils/__init__.py", line 10, in &lt;module&gt; from .murmurhash import murmurhash3_32 File "numpy.pxd", line 155, in init sklearn.utils.murmurhash (sklearn/utils/murmurhash.c:5029) ValueError: numpy.dtype has the wrong size, try recompiling </code></pre> <p><strong>Edit 1</strong>, met with errors when trying to re-install, here are the command and error message,</p> <pre><code>sudo /usr/local/bin/pip install --upgrade --force-reinstall numpy sklearn The directory '/Users/foo/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/foo/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting numpy Downloading numpy-1.11.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.9MB) 100% |████████████████████████████████| 3.9MB 296kB/s Collecting sklearn Collecting scikit-learn (from sklearn) Downloading scikit_learn-0.17.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.9MB) 100% |████████████████████████████████| 3.9MB 317kB/s Installing collected packages: numpy, scikit-learn, sklearn Found existing installation: numpy 1.8.0rc1 DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling numpy-1.8.0rc1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/tmp/pip-TDvKH6-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info' You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. </code></pre>
0
2016-08-21T02:30:23Z
39,060,378
<p>Your code works fine for me, which suggests it's an environment error.</p> <p>Try running <code>sudo pip install --upgrade --force-reinstall numpy sklearn</code> and see if that does the trick.</p> <p>If you installed via Homebrew: <code>brew install --force numpy</code> (there's no <code>sklearn</code> homebrew package)</p> <p>If you installed via MacPorts:</p> <pre><code>port -f uninstall py27-numpy port install py27-numpy </code></pre> <p>(But if you installed via either Homebrew or MacPorts, I recommend uninstalling (<code>port -f uninstall py27-numpy || brew uninstall numpy</code>) and installing via pip instead.</p>
2
2016-08-21T02:35:36Z
[ "python", "osx", "python-2.7", "numpy" ]
How can i install twilio package via pip?
39,060,397
<p>I have <strong>Python 2.7.12</strong> (64 bit) installed on my Windows machine. When I installed it, I added <strong>pip</strong> and the <strong>python.exe</strong> path. Now when I try to install <strong>Twilio</strong> with</p> <pre><code>pip install twilio </code></pre> <p>I get the error </p> <pre><code>pip is not recognized as an external or internal command </code></pre>
1
2016-08-21T02:40:35Z
39,060,534
<p>Please include c:\python27\Scripts in SYSTEM PATH</p> <p>Procedure to add c:\python27\Scripts to system path:</p> <ol> <li>From the desktop, right click the Computer icon.</li> <li>Choose Properties from the context menu.</li> <li>Click the Advanced system settings link.</li> <li>Click Environment Variables. In the Edit System Variable (or New System Variable) window, add c:\python27\Scripts to the value of the PATH environment variable.(don't delete the existing ones)</li> </ol> <p>Assumption: hoping your installation drive is C</p> <p>Once you have added it, please close all command prompts and open a new command prompt and try it</p> <p>Or in a new command prompt, type below command</p> <pre><code>C:\Python27\Scripts\pip.exe install twilio </code></pre> <p><strong>EDIT</strong>: If everything fails, try the below way:</p> <p>Open command prompt, type "python -m pip install twilio" (without quotes).</p>
1
2016-08-21T03:14:15Z
[ "python", "twilio" ]