title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Regex required or can BeautifulSoup refine output
39,378,971
<p>If I use the following function I can grab the text and link I need from a website:</p> <pre><code>def get_url_text(url): source = requests.get(url) plain_text = source.text soup = BeautifulSoup(plain_text) for item_name in soup.findAll('li', {'class': 'ptb2'}): print(item_name.string) ...
3
2016-09-07T21:03:38Z
39,379,018
<p>you can use <code>print(item_name.a['href'])</code> and (if needed) prepend the prefix <code>https://www.residentadvisor.net</code> (since the links in the webpage are used in a form without explicit scheme and netloc part - for example, <code>/podcast-episode.aspx?id=528</code>)</p>
3
2016-09-07T21:07:06Z
[ "python" ]
When running Neo4j Python Bolt Driver Example, error:"ImportError: No module named '_backend'"
39,378,987
<p>I am trying to switch over from Py2Neo to the new Neo4j <a href="https://neo4j.com/docs/developer-manual/current/drivers/" rel="nofollow">Bolt Driver</a>. After installing neo4j-driver v1.0.2 and I run the example code found on their <a href="https://github.com/neo4j/neo4j-python-driver" rel="nofollow">Github ReadMe...
0
2016-09-07T21:04:56Z
39,379,675
<p>There is no module called <code>neo4j.core</code> in the official driver. From where did you install this library?</p>
1
2016-09-07T22:01:48Z
[ "python", "neo4j" ]
When running Neo4j Python Bolt Driver Example, error:"ImportError: No module named '_backend'"
39,378,987
<p>I am trying to switch over from Py2Neo to the new Neo4j <a href="https://neo4j.com/docs/developer-manual/current/drivers/" rel="nofollow">Bolt Driver</a>. After installing neo4j-driver v1.0.2 and I run the example code found on their <a href="https://github.com/neo4j/neo4j-python-driver" rel="nofollow">Github ReadMe...
0
2016-09-07T21:04:56Z
39,417,917
<p>Just wanted to follow up with the answer so that it might benefit others coming across this in the future.</p> <p>With Nigel Small's help, I realized that I was not calling the correct package. I believe this is another python package on my system from previous work named neo4j which my PyCharm IDE was calling to ...
0
2016-09-09T18:43:11Z
[ "python", "neo4j" ]
Python Requests declined: "Due to the presence of characters known to be used in Cross Site Scripting attacks, access is forbidden."
39,379,045
<p>Dear fellow <code>requests</code> users,</p> <p><strong>Update:</strong></p> <p>Sorry, guys. My error came from a mistake:</p> <p>My goal was to do this:</p> <pre><code>r = requests.get('http://www.spdrs.com/product/fund.seam?ticker=SPY', stream=True, headers=hdr) </code></pre> <p>I did this: </p> <pre><code>r...
1
2016-09-07T21:09:22Z
39,380,709
<p>Drop the following key/value from your header:</p> <pre><code>'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', </code></pre> <p>It works for me after I did that.</p>
0
2016-09-08T00:07:28Z
[ "python", "python-requests" ]
Adding exception to "AttributeError" python
39,379,140
<p>So, I have some tweets with some special characters and shapes. I am trying to find a word in those tweets by converting them to lower case. The function throws an "AttributeError" when it encounters those special characters and hence, I want to change my function in a way that it skips those records and processes o...
0
2016-09-07T21:17:59Z
39,379,551
<p>You can use <code>re.IGNORECASE</code> flag when you <code>search()</code>.<br> That way you don't need to deal with <code>lower()</code> or exceptions.</p> <pre><code>def word_in_text(word, text): print text if re.search(word, text, re.IGNORECASE): return True else: return False </code>...
0
2016-09-07T21:51:05Z
[ "python", "python-2.7", "python-3.x" ]
fast way to put ones beetween ones in each row of a numpy 2d array
39,379,147
<p>I have a 2d array (Q) consisting of just zeros and ones. I wish to fill with 1 each position between 1's of each line Q. Here's an example:</p> <p><strong>Original matrix:</strong></p> <pre><code>[0 0 0 1 0 1] [1 0 0 0 0 0] [0 0 0 0 0 0] [1 1 0 1 0 0] [1 0 0 0 0 1] [0 1 1 0 0 1] [1 0 1 0 1 0] </code></pre> <p><st...
4
2016-09-07T21:18:25Z
39,379,263
<p>The function below looks at a single row and fills 1s between other 1s if they exist. It assumes that the array contains only 0s and 1s.</p> <pre><code>import numpy as np def ones_row(row): if np.sum(row) &gt;= 2: # Otherwise, not enough 1s inds = np.where(row == 1)[0] row[inds[0]:inds[-1]] =...
1
2016-09-07T21:27:27Z
[ "python", "arrays", "numpy", "matrix" ]
fast way to put ones beetween ones in each row of a numpy 2d array
39,379,147
<p>I have a 2d array (Q) consisting of just zeros and ones. I wish to fill with 1 each position between 1's of each line Q. Here's an example:</p> <p><strong>Original matrix:</strong></p> <pre><code>[0 0 0 1 0 1] [1 0 0 0 0 0] [0 0 0 0 0 0] [1 1 0 1 0 0] [1 0 0 0 0 1] [0 1 1 0 0 1] [1 0 1 0 1 0] </code></pre> <p><st...
4
2016-09-07T21:18:25Z
39,379,373
<p>Another option with <code>np.apply_along_axis</code>:</p> <pre><code>import numpy as np def minMax(A): idx = np.where(A == 1)[0] if len(idx) &gt; 1: A[idx.min():idx.max()] = 1 return A ​ np.apply_along_axis(minMax, 1, mat) # array([[0, 0, 0, 1, 1, 1], # [1, 0, 0, 0, 0, 0], # [0...
2
2016-09-07T21:35:38Z
[ "python", "arrays", "numpy", "matrix" ]
fast way to put ones beetween ones in each row of a numpy 2d array
39,379,147
<p>I have a 2d array (Q) consisting of just zeros and ones. I wish to fill with 1 each position between 1's of each line Q. Here's an example:</p> <p><strong>Original matrix:</strong></p> <pre><code>[0 0 0 1 0 1] [1 0 0 0 0 0] [0 0 0 0 0 0] [1 1 0 1 0 0] [1 0 0 0 0 1] [0 1 1 0 0 1] [1 0 1 0 1 0] </code></pre> <p><st...
4
2016-09-07T21:18:25Z
39,379,379
<p>Here's a one-liner:</p> <pre><code>In [25]: Q Out[25]: array([[0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 1, 0, 1, 0, 0], [1, 0, 0, 0, 0, 1], [0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 0]]) In [26]: np.maximum.accumulate(Q, axis=1) &amp; np.maximum.accumulate...
5
2016-09-07T21:35:50Z
[ "python", "arrays", "numpy", "matrix" ]
How do I use py2app with Anaconda python?
39,379,155
<p>I am using Python 3 from the Anaconda distribution, and trying to convert a simple python program into an OS X app (running on El Capitan). Following the instructions in <a href="https://pythonhosted.org/py2app/tutorial.html" rel="nofollow">the tutorial</a>, I ran </p> <pre><code>py2applet --make-setup my-script.py...
0
2016-09-07T21:19:08Z
39,392,214
<p>The suggestion by @l'L'l allowed me to identify the problem: While there were no errors when I generated my app in "alias mode" (using symlinks to the environment instead of copying binaries), building the app without alias mode flushed out the error: <code>py2app</code> looks for the <code>libpython</code> DLL unde...
0
2016-09-08T13:25:14Z
[ "python", "osx", "anaconda", "py2app" ]
Creating a list of 'N' pairs of a variable
39,379,197
<p>I have a variable <code>x</code>. I need to create a list such as </p> <pre><code>lst=[0,x,x,2*x,2*x,3*x,3*x,N*x,N*x] </code></pre> <p>up to any <code>N</code></p> <p>Seems like this should be straightforward but I'm kinda stuck. Any help is appreciated.</p> <p>Respectfully I don't see how this question is a dup...
-1
2016-09-07T21:22:15Z
39,381,084
<p>You can do this with a list comprehension. It isn't as clear as the code you started with though.</p> <pre><code>&gt;&gt;&gt; N=4 &gt;&gt;&gt; x=1.25 &gt;&gt;&gt; lst = [0] + [i//2 * x for i in range(2, 2*N+2)] &gt;&gt;&gt; lst [0, 1.25, 1.25, 2.5, 2.5, 3.75, 3.75, 5.0, 5.0] </code></pre>
0
2016-09-08T01:03:14Z
[ "python" ]
Creating a list of 'N' pairs of a variable
39,379,197
<p>I have a variable <code>x</code>. I need to create a list such as </p> <pre><code>lst=[0,x,x,2*x,2*x,3*x,3*x,N*x,N*x] </code></pre> <p>up to any <code>N</code></p> <p>Seems like this should be straightforward but I'm kinda stuck. Any help is appreciated.</p> <p>Respectfully I don't see how this question is a dup...
-1
2016-09-07T21:22:15Z
39,381,714
<p>you can do this like this</p> <pre><code>&gt;&gt;&gt; n=4 &gt;&gt;&gt; x=1.2 &gt;&gt;&gt; lst=[0,x,x] &gt;&gt;&gt; lst.extend( i*x for i in range(2,n+1) for _ in range(2) ) &gt;&gt;&gt; lst [0, 1.2, 1.2, 2.4, 2.4, 3.5999999999999996, 3.5999999999999996, 4.8, 4.8] &gt;&gt;&gt; </code></pre> <p>EDIT</p> <p>or with...
1
2016-09-08T02:30:20Z
[ "python" ]
Flask - uploadnotallowed error - when renaming a file to be saved
39,379,287
<p>I'm trying to upload an excel file in flask and give it a new name when saving, something like: <code>oldname.xlsx</code> to <code>newname.xlsx</code>.</p> <p>Here is my code so far:</p> <pre><code>from flask import Flask, render_template, send_file, request, redirect, url_for from flask_uploads import UploadSet, ...
2
2016-09-07T21:29:25Z
39,379,631
<p>Ok, found my error. The variable <code>file_new_name = 'dataexcel'</code> needs to have the extension, in this case the <code>.xlsx</code> ext. So the variable should be <code>file_new_name = 'dataexcel.xlsx'</code></p> <p>the <code>save</code> function should look like this -> <code>filename = docs.save(filestora...
0
2016-09-07T21:58:23Z
[ "python", "flask" ]
Python: exec() a code block and eval() the last line
39,379,331
<p>I have a string literal containing one or more lines of (trusted) Python code, and I would like to <code>exec()</code> the block, while capturing the results of the last line. More concretely, I would like a function <code>exec_then_eval</code> that returns the following:</p> <pre><code>code = """ x = 4 y = 5 x + y...
4
2016-09-07T21:32:42Z
39,381,428
<p>Based on @kalzekdor's suggestion of using the <code>ast</code> module, I came up with this solution which is similar in spirit to @vaultah's solution posted above:</p> <pre><code>import ast def exec_then_eval(code): block = ast.parse(code, mode='exec') # assumes last node is an expression last = ast.E...
4
2016-09-08T01:52:59Z
[ "python" ]
Changing __getattr__ during instantiation
39,379,351
<p>I am wanting to change <code>__getattr__</code> during instantiation of the class. For example:</p> <pre><code>class AttrTest(object): def __init__(self): self.__getattr__ = self._getattr def _getattr(self, attr): print("Getting {}".format(attr)) </code></pre> <p>I would have expected thi...
4
2016-09-07T21:34:26Z
39,379,402
<p>For special methods like <code>__getattr__</code>, Python searches in the base(s) <code>__dict__</code>, not in the instance <code>__dict__</code>.</p> <p>You can read more details about this in the <a href="https://docs.python.org/3/reference/datamodel.html#special-lookup" rel="nofollow">special lookup</a> section...
2
2016-09-07T21:37:34Z
[ "python" ]
Issue trying to install or update package using PIP
39,379,497
<p>For some reason I can't use PIP to install or update python packages in my system. I get this error.</p> <blockquote> <p>Exception:</p> <p>Traceback (most recent call last):</p> <p>File "/usr/local/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecommand.py", line 209, in main status = ...
0
2016-09-07T21:46:21Z
39,386,871
<p>You OpenSSL(not pyOpenSSL) is too old, you need to install an OpenSSL version that supports SNI.</p>
0
2016-09-08T09:07:38Z
[ "python", "pip", "sni" ]
Why does 11 not printed from a string in this Python script?
39,379,514
<p>There is a Python question like this:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; s = ‘mary11had a little lamb’ &gt;&gt;&gt; print s mary had a little lamb </code></pre> <p>Actually when I try it myself, the result is not that, but:</p> <pre><code>mary11had a little lamb </code></pre> <p>Is there ...
-2
2016-09-07T21:48:18Z
39,379,771
<p>As Padraic has pointed out in the comments - it looks like the leading backslash is missing before the 11 as a minor typo in the question.</p> <p>So it should read </p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; s = ‘mary\11had a little lamb’ &gt;&gt;&gt; print s mary had a little lamb </code></pre>...
1
2016-09-07T22:10:46Z
[ "python", "string" ]
How do I generate a random list in Python with duplicates numbers
39,379,515
<p>So I just started programming in Python a few days ago. And now, im trying to make a program that generates a random list, and then, choose the duplicates elements. The problem is, I dont have duplicate numbers in my list. </p> <p>This is my code: </p> <pre><code>import random def generar_listas (numeros, rango):...
0
2016-09-07T21:48:18Z
39,379,622
<p>What you want is fairly simple. You want to generate a random list of numbers that contain some duplicates. The way to do that is easy if you use something like numpy.</p> <ul> <li>Generate a list (range) of 0 to 10. </li> <li>Sample randomly (with replacement) from that list.</li> </ul> <p><strong>Like this:</str...
0
2016-09-07T21:57:37Z
[ "python", "list" ]
How do I generate a random list in Python with duplicates numbers
39,379,515
<p>So I just started programming in Python a few days ago. And now, im trying to make a program that generates a random list, and then, choose the duplicates elements. The problem is, I dont have duplicate numbers in my list. </p> <p>This is my code: </p> <pre><code>import random def generar_listas (numeros, rango):...
0
2016-09-07T21:48:18Z
39,379,745
<p>random.randrange is what you want.</p> <pre><code>&gt;&gt;&gt; [random.randrange(10) for i in range(5)] [3, 2, 2, 5, 7] </code></pre>
0
2016-09-07T22:08:36Z
[ "python", "list" ]
Twillo - how to handle no input on <gather>
39,379,541
<p>I'm building a simple Twillo (programmable voice) application using Python flask and the <a href="https://www.twilio.com/docs/libraries/python" rel="nofollow">twillo-python helper library</a>. There are several steps to the voice menu, but the first asks the caller to enter a pin number.</p> <p>I am trying to work...
1
2016-09-07T21:50:15Z
39,385,809
<p>Twilio developer evangelist here.</p> <p>That seems like a reasonable way to build this response. Redirecting round to play the <a href="https://www.twilio.com/docs/api/twiml/gather" rel="nofollow"><code>&lt;Gather&gt;</code></a> again until you reach a number of attempts is a great way of dealing with this situati...
0
2016-09-08T08:13:36Z
[ "python", "flask", "twilio", "twiml" ]
Twillo - how to handle no input on <gather>
39,379,541
<p>I'm building a simple Twillo (programmable voice) application using Python flask and the <a href="https://www.twilio.com/docs/libraries/python" rel="nofollow">twillo-python helper library</a>. There are several steps to the voice menu, but the first asks the caller to enter a pin number.</p> <p>I am trying to work...
1
2016-09-07T21:50:15Z
39,399,809
<p>I actually found a tidier way to do this, without the need for a helper function. In this approach, all the timeout logic (i.e. 'Please try again' or hang up) in a <code>/timeout</code> endpoint.</p> <p>This appears to be the implied suggestion for timeouts, having seen the example in the <a href="https://www.twili...
1
2016-09-08T20:38:14Z
[ "python", "flask", "twilio", "twiml" ]
How to Solve Numba Lowering error?
39,379,556
<p>I have a function, which I am trying to speed up using the @jit decorator from Numba module. For me it is essential to speed this up as much as possible, because my main code calls upon this function for millions of times. Here is my function:</p> <pre><code>from numba import jit, types import Sweep #My own modu...
0
2016-09-07T21:51:33Z
39,387,886
<p>I can't see from your code why this isn't vectorizable. Vectorizing can speed up this kind of Python code by around 100x. Not sure of how it does relative to jit.</p> <p>It looks like you could, for instance, take your dEdt out of the loop, and compute it in one step with something like :</p> <pre><code>dEdt = 0...
0
2016-09-08T09:55:59Z
[ "python", "numpy", "numba" ]
How to Solve Numba Lowering error?
39,379,556
<p>I have a function, which I am trying to speed up using the @jit decorator from Numba module. For me it is essential to speed this up as much as possible, because my main code calls upon this function for millions of times. Here is my function:</p> <pre><code>from numba import jit, types import Sweep #My own modu...
0
2016-09-07T21:51:33Z
39,389,193
<p>There may be other issues, but one is that referencing an array in a module namespace seems to currently be unsupported (simple repro below). Try importing <code>omega</code> as a name.</p> <pre><code>In [14]: %%file Sweep.py ...: import numpy as np ...: constant_val = 0.5 ...: constant_arr = np.array(...
0
2016-09-08T11:00:09Z
[ "python", "numpy", "numba" ]
How can I use regular expression when reading a text file in Python?
39,379,616
<p>I would like to give you an example. If I am trying to print lines that contain the integer <code>-9999</code> from a file.</p> <pre><code>19940325 78 -28 -9999 19940326 50 17 102 19940327 100 -11 -9999 19940328 56 -33 0 19940329 61 -39 -9999 1994033...
0
2016-09-07T21:57:07Z
39,379,635
<p>Regex is likely overkill for this, a simple substring check using the <code>in</code> operator seems sufficient</p> <pre><code>with open("USC00110072.txt") as f: for line in f: if '-9999' in line: print(line) </code></pre> <p>Or if you're concerned about that matching that as a "whole word"...
3
2016-09-07T21:58:53Z
[ "python", "python-2.7", "python-3.x" ]
How can I use regular expression when reading a text file in Python?
39,379,616
<p>I would like to give you an example. If I am trying to print lines that contain the integer <code>-9999</code> from a file.</p> <pre><code>19940325 78 -28 -9999 19940326 50 17 102 19940327 100 -11 -9999 19940328 56 -33 0 19940329 61 -39 -9999 1994033...
0
2016-09-07T21:57:07Z
39,379,719
<p>You can use <code>filter</code>:</p> <pre><code>with open(fn) as f: print filter(lambda line: '-9999' in line.split()[-1], f) </code></pre> <p>This is will check if '-9999' is in the final column of the line. </p> <p>If you want to use a regex:</p> <pre><code>with open(fn) as f: for line in f: if...
1
2016-09-07T22:06:06Z
[ "python", "python-2.7", "python-3.x" ]
How can I use regular expression when reading a text file in Python?
39,379,616
<p>I would like to give you an example. If I am trying to print lines that contain the integer <code>-9999</code> from a file.</p> <pre><code>19940325 78 -28 -9999 19940326 50 17 102 19940327 100 -11 -9999 19940328 56 -33 0 19940329 61 -39 -9999 1994033...
0
2016-09-07T21:57:07Z
39,379,742
<p>Alternatively, since you have a <code>csv</code> file you could use the <code>csv</code> module:</p> <pre><code>import csv import io file = io.StringIO(u''' 19940325\t78\t-28\t-9999 19940326\t50\t17\t102 19940327\t100\t-11\t-9999 19940328\t56\t-33\t0 19940329\t61\t-39\t-9999 19940330\t61\t-56\t0 19940331\t139\t-61...
1
2016-09-07T22:08:06Z
[ "python", "python-2.7", "python-3.x" ]
Why am I getting an empty list as my output using solve command?
39,379,624
<p>I am trying to solve an equation using sympy's solve command but my output is an empty list [ ]. The only reason I think this could be happening is because there is no solution but I doubt that is the reason. Anyone know why I am not getting an answer? Thanks!</p> <pre><code>from sympy import * class WaterModel: ...
3
2016-09-07T21:57:40Z
39,379,789
<p>I tried adding a few tracing statements to your function, just above the call to <strong>solve</strong>.</p> <pre><code> print "dWg\t", dWg, type(dWg) print "dWp\t", dWp, type(dWp) print "F\t", F, type(F) print "self.fp\t", self.fp self.fp = solve(F,self.fp) </code></pre> <p>Output:</p> <pre><c...
3
2016-09-07T22:12:57Z
[ "python", "sympy", "solver", "is-empty" ]
Why am I getting an empty list as my output using solve command?
39,379,624
<p>I am trying to solve an equation using sympy's solve command but my output is an empty list [ ]. The only reason I think this could be happening is because there is no solution but I doubt that is the reason. Anyone know why I am not getting an answer? Thanks!</p> <pre><code>from sympy import * class WaterModel: ...
3
2016-09-07T21:57:40Z
39,379,851
<p><code>self.fp</code> cancels out of your computation. The value of <code>F</code> is the same no matter what <code>self.fp</code> is, so <code>solve</code> can't help you.</p> <p>Are you sure you have your equations right?</p>
2
2016-09-07T22:18:48Z
[ "python", "sympy", "solver", "is-empty" ]
How to extract output of specific columns from groupby on pandas dataframe
39,379,634
<p><em>Need to extract output of groupBy pandas dataframe into expected output described below and write to a file:</em></p> <p><strong><em>Input file testdata.txt:</em></strong></p> <pre><code>id, distance 1,0.5 1,1.2 1,0.2 &lt;------------this row should be selected 1,1.5 2,2.5 2,0.5 &lt;------------this row s...
0
2016-09-07T21:58:53Z
39,386,961
<p>This is just a simple case of applying using the <code>.min()</code> method of a <code>DataFrameGroupBy</code> object:</p> <pre><code>data = [(1,0.5),(1,1.2),(1,0.2),(1,1.5),(2,2.5),(2,0.5),(2,1.0),(2,3.0)] df = pd.DataFrame(data) df.columns = ['id', 'distance'] results = df.groupby('id').min() </code></pre> <p><c...
0
2016-09-08T09:12:35Z
[ "python", "pandas", "apache-spark", "lambda" ]
Getting all HTML from requests.get()
39,379,646
<p>I just started with web scraping with Python and hit the wall. I am using the requests library to get the HTML code from a website. For example, the Google search result website: "<a href="https://www.google.com/?gws_rd=ssl#q=ball" rel="nofollow">https://www.google.com/?gws_rd=ssl#q=ball</a>"</p> <p>When I hit <kbd...
-1
2016-09-07T21:59:29Z
39,379,705
<p>Some HTML elements are generated by JavaScript.</p> <p>Use "show source code" from your browser to see the original code. It must be similar to the Request response text. </p>
-1
2016-09-07T22:04:28Z
[ "python", "html", "python-requests" ]
Getting all HTML from requests.get()
39,379,646
<p>I just started with web scraping with Python and hit the wall. I am using the requests library to get the HTML code from a website. For example, the Google search result website: "<a href="https://www.google.com/?gws_rd=ssl#q=ball" rel="nofollow">https://www.google.com/?gws_rd=ssl#q=ball</a>"</p> <p>When I hit <kbd...
-1
2016-09-07T21:59:29Z
39,379,850
<p>The HTML you see using the browser's development tools is what the browser is currently working with. This includes any changes performed via Javascript. The data you are getting when using Requests is before any Javascript has operated on the page. (Note that Requests doesn't process Javascript so you will be unabl...
1
2016-09-07T22:18:48Z
[ "python", "html", "python-requests" ]
Getting started with Coverity for python package
39,379,721
<p>I downloaded the coverity package for Python/PHP, and try to let it analyze my package:</p> <pre><code>./cov-build --dir cov-int --fs-capture-search /my/dir/ python mine.py </code></pre> <p>considering that 'my/dir' contains the package's root directory and the 'mine.py' implements the entry point.</p> <p>The I g...
1
2016-09-07T22:06:10Z
39,394,501
<pre><code>[WARNING] Build command python /tmp/trunk/quex-exe.py exited with code 255. Please verify that the build completed successfully. </code></pre> <p>This means that the command you specified on the cov-build line (<code>python mine.py</code>) didn't exit with zero. Probably because of this:</p> <pre><code>com...
2
2016-09-08T15:09:30Z
[ "python", "coverity" ]
Python is using the wrong version of Numpy module
39,379,728
<p>I'm trying to use Numpy 1.11.1 for Python 2.7. I have Mac El Capitan, so <code>sudo pip install</code> doesn't work.</p> <p>I decided to install Homebrew and do <code>brew install python</code> and that worked. If I use <code>pip show numpy</code> it shows that I have Numpy 1.11.1 now.</p> <p>But if I run <code>py...
0
2016-09-07T22:06:47Z
39,379,833
<p>It's better to use a <strong><a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a></strong> to install the required libraries version. Don't pollute your system Python.</p> <p>It will solve your problem…</p> <pre><code>mkdir $HOME/virtualenv cd $HOME/virtualenv virtualenv my_app source my...
0
2016-09-07T22:17:19Z
[ "python", "python-2.7", "numpy", "version" ]
How to run a def with multiple values only once and use values into another def?
39,379,735
<p>My problem is real simple but unfortunately i can't find a way to solve it.</p> <p>I would like to run a def A which returns multiple values from def B only once.</p> <p>I wrote this block of code :</p> <pre><code>def A(): x = 1 y = 2 z = 3 return a,b,c def B(): d = A[0] + A[1] e = A[2] -...
1
2016-09-07T22:07:36Z
39,379,769
<p>Simple, there are mistakes in your code, <code>A</code> is a function and you should call it with <code>A()</code> to get the returned values. Instead you use it like <code>A[0]</code> which is un-subscriptable, and you can assign a temp variable within <code>B</code> function so you can re-use the returned values, ...
1
2016-09-07T22:10:16Z
[ "python", "return" ]
How to run a def with multiple values only once and use values into another def?
39,379,735
<p>My problem is real simple but unfortunately i can't find a way to solve it.</p> <p>I would like to run a def A which returns multiple values from def B only once.</p> <p>I wrote this block of code :</p> <pre><code>def A(): x = 1 y = 2 z = 3 return a,b,c def B(): d = A[0] + A[1] e = A[2] -...
1
2016-09-07T22:07:36Z
39,379,781
<p>I would do this: </p> <pre><code>def B(): a, b, c = A() d = a + b e = c - a print d,e </code></pre> <p>But make sure your function <code>A()</code> is returning the same variables it is declaring (<code>x, y, z</code> not <code>a, b, c</code>).</p>
1
2016-09-07T22:11:45Z
[ "python", "return" ]
Pyspark: How to transform json strings in a dataframe column
39,379,775
<p>The following is more or less straight python code which functionally extracts exactly as I want. The data schema for the column I'm filtering out within the dataframe is basically a json string. </p> <p>However, I had to greatly bump up the memory requirement for this and I'm only running on a single node. Usin...
1
2016-09-07T22:11:19Z
39,380,110
<p>One possible solution:</p> <pre><code>(df .rdd # Convert to rdd .flatMap(lambda x: x) # Flatten rows # Parse JSON. In practice you should add proper exception handling .flatMap(lambda x: json.loads(x)) # Get values .map(lambda x: (x.get('val01_field_name'), x.get('val02_field_name'))) # Convert to f...
2
2016-09-07T22:47:18Z
[ "python", "json", "apache-spark", "pyspark" ]
AWS g2.8xlarge performance and out of memory issues when using tensorflow
39,379,805
<p>I am currently training a recurrent net on Tensorflow for a text classification problem and am running into performance and out of memory issues. I am on AWS g2.8xlarge with Ubuntu 14.04, and a recent nightly build of tensorflow (which I downloaded on Aug 25).</p> <p>1) Performance issue:</p> <p>On the surface, bo...
0
2016-09-07T22:14:21Z
39,396,466
<p>Re (1), to improve GPU utilization did you try increasing the batch size and / or shortening the sequences you use for training?</p> <p>Re (2), to use multiple GPUs you do need to manually assign the ops to GPU devices, I believe. The right way is to place ops on specific GPUs by doing</p> <pre><code>with g.Device...
0
2016-09-08T16:53:49Z
[ "python", "tensorflow", "deep-learning", "recurrent-neural-network" ]
Unordered set or similar in Spark?
39,379,889
<p>I have data of this format:</p> <blockquote> <p>(123456, (43, 4861))</p> <p>(000456, (43, 4861))</p> </blockquote> <p>where the first term is the point id, where the second term is a pair, where its first id is a cluster-centroid and the second id is another cluster-centroid. So that says that point 123456 ...
0
2016-09-07T22:23:55Z
39,380,113
<p>Judging from what you described (although I still don't quite get it), here is a naive approach using Python:</p> <pre><code>In [1]: from itertools import groupby In [2]: from random import randint In [3]: data = [] # create random samples as you did ...: for i in range(10): ...: data.append((randint(0...
1
2016-09-07T22:47:37Z
[ "python", "algorithm", "apache-spark", "data-structures", "bigdata" ]
Pulling table data with mixed element types
39,379,903
<p>I am trying to pull data from a table using Python and Selenium however a few of the columns have a mix between gif and text. When I print the text element it returns the text along with blanks were the gif elements are within the column. However when I prints the gif elements, it returns all the gifs from the table...
1
2016-09-07T22:24:43Z
39,379,931
<p>Find all <code>td</code> elements first, then, for every <code>td</code> decide if you want to get the text or the <code>src</code> attribute of the <code>img</code> element:</p> <pre><code>posts = driver.find_elements_by_css_selector("td.x") for post in posts: images = post.find_elements_by_tag_name("img") ...
2
2016-09-07T22:27:53Z
[ "python", "selenium", "selenium-webdriver" ]
Reverse translation dictionary Python
39,379,907
<p>This is what I have ended up with after suggestions were made it appears as if the Eng dictionary is identical to the Tuc one. This program will translate English words to Tuccin but I can not for the life of me get it to translate Tuccin to English Pleae tell me how to achieve this. In the event a non stored word i...
0
2016-09-07T22:24:55Z
39,379,938
<p>The way you have it currently set, <code>Eng</code> and <code>Tuc</code> are identical. It seems like what you want is </p> <pre><code>&gt;&gt;&gt; Eng = {e[0]: [t] for t, e in Tuc.items()} &gt;&gt;&gt; Eng {'yem': ['my'], 'ye': ['me'], 'uo': ['you'], 'o': ['i'], 'sia': 'are'], 'yeme': ['mine'], 'wau': ['love']} </...
0
2016-09-07T22:28:52Z
[ "python", "dictionary", "translation" ]
Reverse translation dictionary Python
39,379,907
<p>This is what I have ended up with after suggestions were made it appears as if the Eng dictionary is identical to the Tuc one. This program will translate English words to Tuccin but I can not for the life of me get it to translate Tuccin to English Pleae tell me how to achieve this. In the event a non stored word i...
0
2016-09-07T22:24:55Z
39,379,941
<p>You have a typo up there:</p> <pre><code>Eng = {e[0]: [t] for t, e in Tuc.items()} </code></pre>
0
2016-09-07T22:28:59Z
[ "python", "dictionary", "translation" ]
Reverse translation dictionary Python
39,379,907
<p>This is what I have ended up with after suggestions were made it appears as if the Eng dictionary is identical to the Tuc one. This program will translate English words to Tuccin but I can not for the life of me get it to translate Tuccin to English Pleae tell me how to achieve this. In the event a non stored word i...
0
2016-09-07T22:24:55Z
39,379,959
<p>You ought to do</p> <pre><code>eng = {v[0]: [k] for k, v in tuc.items()} </code></pre> <p>Or <code>iteritems()</code> with Python 2.</p> <p>Note, instead of:</p> <pre><code>while phrase == True </code></pre> <p>You should write:</p> <pre><code>while phrase </code></pre>
0
2016-09-07T22:31:01Z
[ "python", "dictionary", "translation" ]
Reverse translation dictionary Python
39,379,907
<p>This is what I have ended up with after suggestions were made it appears as if the Eng dictionary is identical to the Tuc one. This program will translate English words to Tuccin but I can not for the life of me get it to translate Tuccin to English Pleae tell me how to achieve this. In the event a non stored word i...
0
2016-09-07T22:24:55Z
39,379,989
<p>You can clean up your code quite a bit while fixing this error (you copied the dictionary instead of reversing it):</p> <pre><code>Tuc={"i":"o", "love":"wau", "you":"uo", "me":"ye", "my":"yem", "mine":"yeme", "are":"sia"} Eng = {e:t for t, e in Tuc.items()} print "ENG" print Eng print "TUC" print Tuc phrase=True w...
0
2016-09-07T22:34:14Z
[ "python", "dictionary", "translation" ]
Reverse translation dictionary Python
39,379,907
<p>This is what I have ended up with after suggestions were made it appears as if the Eng dictionary is identical to the Tuc one. This program will translate English words to Tuccin but I can not for the life of me get it to translate Tuccin to English Pleae tell me how to achieve this. In the event a non stored word i...
0
2016-09-07T22:24:55Z
39,380,008
<p>This version assumes each word will have multiple translations (that's the reason you're using lists on each word):</p> <pre><code>from collections import defaultdict tuc_dictionary = { "i": ["o"], "love": ["wau"], "you": ["uo"], "me": ["ye"], "my": ["yem"], "mine": ["yeme"], "are": ["s...
0
2016-09-07T22:35:23Z
[ "python", "dictionary", "translation" ]
Convert .py files to correct encoding for Python 3
39,379,969
<p>I just pulled from a git repo where the users are on Python 2. My system is running Python 3 and with no changes in the code, I am getting this error:</p> <pre><code>TabError: inconsistent use of tabs and spaces in indentation </code></pre> <p>It appears that the solution is to change the char set encoding of the ...
0
2016-09-07T22:32:11Z
39,379,998
<p>This is not a python 2/3 issue, it looks like something in that git repo has wrong indentation. The easiest fix would be to replace all tab characters in all the files with spaces using something like sed</p>
0
2016-09-07T22:34:43Z
[ "python", "encoding", "emacs" ]
Convert .py files to correct encoding for Python 3
39,379,969
<p>I just pulled from a git repo where the users are on Python 2. My system is running Python 3 and with no changes in the code, I am getting this error:</p> <pre><code>TabError: inconsistent use of tabs and spaces in indentation </code></pre> <p>It appears that the solution is to change the char set encoding of the ...
0
2016-09-07T22:32:11Z
39,383,808
<p>Exists a command <code>untabify</code>:</p> <p>Convert all tabs in region to multiple spaces, preserving columns. If called interactively with prefix ARG, convert for the entire buffer.</p> <p>I.e. call it with C-u to convert all TABs in buffer.</p> <p>As comment points out correctly: <code>tabify</code> does the...
1
2016-09-08T06:20:51Z
[ "python", "encoding", "emacs" ]
How can one replace missing values with median or mode in SFrame?
39,379,987
<p>I'm going through the Graphlab documentation and I am trying to figure out how to duplicate the pandas functionality were na values are replaced by the median, the mean, or the mode, etc... In pandas you simply do this by: df.dropna().median() or df.dropna().mean() etc....</p> <p>But the documentation on the dr...
1
2016-09-07T22:33:56Z
39,380,244
<p>There is one, but only the mean is available, not the median. Have a look at: <code>graphlab.toolkits.feature_engineering.NumericImputer</code> (<a href="https://turi.com/products/create/docs/generated/graphlab.toolkits.feature_engineering.NumericImputer.html" rel="nofollow">doc</a>)</p> <blockquote> <p>Impute mi...
1
2016-09-07T23:01:55Z
[ "python", "pandas", "graphlab" ]
Python script for finding keith numbers not working
39,380,002
<p>I am trying to make a python program that will find keith numbers. If you don't what keith numbers are, here is a link explaining them: <a href="http://mathworld.wolfram.com/KeithNumber.html" rel="nofollow">Keith Numbers - Wolfram MathWorld</a></p> <p>My code is</p> <pre><code>from decimal import Decimal from time...
0
2016-09-07T22:34:53Z
39,380,183
<p>You have it in front of you:</p> <pre><code>add1 = 18 add = 9 count = 9 numbers = [18] </code></pre> <p>You're in an infinite loop with no output. You get this for <em>once</em>. After this, <strong>i</strong> runs through the values 1, 2, and 3. Each time through the <strong>for</strong> loop, all three <st...
3
2016-09-07T22:56:07Z
[ "python", "python-2.7", "math", "numbers" ]
Python script for finding keith numbers not working
39,380,002
<p>I am trying to make a python program that will find keith numbers. If you don't what keith numbers are, here is a link explaining them: <a href="http://mathworld.wolfram.com/KeithNumber.html" rel="nofollow">Keith Numbers - Wolfram MathWorld</a></p> <p>My code is</p> <pre><code>from decimal import Decimal from time...
0
2016-09-07T22:34:53Z
39,380,287
<p>Prune has already given you good advices! Let's put a little example of what he meant though, let's say you got an algorithm which determine whether n is a keith number or not and also a test loop to print some keith numbers:</p> <pre><code>def keith_number(n): c = str(n) a = list(map(int, c)) b = sum(a...
0
2016-09-07T23:07:03Z
[ "python", "python-2.7", "math", "numbers" ]
python pip upgrade breaks
39,380,047
<p>I am using Ubuntu 16.04.1 LTS at work. I need to upgrade pip to latest version(8.1.2)</p> <p>When I run:</p> <pre><code>sudo pip install -U pip </code></pre> <p>I get following error. I checked the proxy, they look okay. </p> <pre><code>Exception: Traceback (most recent call last): File "/usr/lib/python...
5
2016-09-07T22:40:10Z
39,394,824
<p>This is the command i use:</p> <pre><code>pip install --upgrade pip </code></pre>
0
2016-09-08T15:24:00Z
[ "python", "linux", "pip", "upgrade" ]
Writing a source code in Python
39,380,093
<p>I have a Source code in C, I want to write it in Python. I have <code>.so</code> library files for my C code, is it possible to change <code>.so</code> files to <code>.py</code> lib files for execution? </p> <p>If so, how can I execute my python files? I mean in order to run C in python, we use something like belo...
-3
2016-09-07T22:45:28Z
39,380,120
<p>You can use Python's <a href="https://docs.python.org/3.5/library/ctypes.html" rel="nofollow">ctypes</a> module to load <code>so</code> files and use their functions.<br> Take a look at the second answer <a href="http://stackoverflow.com/questions/145270/calling-c-c-from-python?noredirect=1&amp;lq=1">here</a>.</p>
1
2016-09-07T22:48:14Z
[ "python" ]
pandas DataFrame and pandas.groupby to calculate Salaries
39,380,148
<p>For my assignment, I need to import baseball salary data into a pandas <code>DataFrame</code>.<br> From there, one of my objectives is to get the salaries of all the teams per year.</p> <p>I was successful however in order to move onto the next task, I need a pandas <code>DataFrame</code>. <code>sumofSalaries.dtype...
2
2016-09-07T22:51:49Z
39,380,440
<p><code>del</code> has a <a href="https://docs.python.org/3/reference/simple_stmts.html#del" rel="nofollow">very specific meaning</a> in python and has no use on a dataframe like that.</p> <p>You want to use <code>reset_index</code> to get rid of the <code>MultiIndex</code> after a groupby -- if you want to get rid o...
1
2016-09-07T23:29:12Z
[ "python", "pandas", "dataframe", "ipython" ]
pandas DataFrame and pandas.groupby to calculate Salaries
39,380,148
<p>For my assignment, I need to import baseball salary data into a pandas <code>DataFrame</code>.<br> From there, one of my objectives is to get the salaries of all the teams per year.</p> <p>I was successful however in order to move onto the next task, I need a pandas <code>DataFrame</code>. <code>sumofSalaries.dtype...
2
2016-09-07T22:51:49Z
39,382,899
<p>I think you need only add parameter <code>as_index=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a>, output is <code>DataFrame</code> without <code>MultiIndex</code>:</p> <pre><code>sumOfSalaries = salariesData.grou...
0
2016-09-08T05:00:42Z
[ "python", "pandas", "dataframe", "ipython" ]
Python assertIn test statement not finding string?
39,380,171
<p>I am using <code>assertIn</code> to test that a part of the result in JSON string is correct.</p> <pre><code>test_json = some_function_returning_a_dict() self.assertIn(expected_json, test_json, "did not match expected output") </code></pre> <p>The error is</p> <blockquote> <p>AssertionError: "'abc': '1.0012'," ...
0
2016-09-07T22:54:19Z
39,380,218
<p><code>"'abc': '1.0012',"</code> is a string and <code>{'abc': '1.0012', }</code> is an entry in dictionary</p> <p>You want to be checking for the dictionary entry in json, not a string</p>
1
2016-09-07T22:59:42Z
[ "python", "python-3.x" ]
Python assertIn test statement not finding string?
39,380,171
<p>I am using <code>assertIn</code> to test that a part of the result in JSON string is correct.</p> <pre><code>test_json = some_function_returning_a_dict() self.assertIn(expected_json, test_json, "did not match expected output") </code></pre> <p>The error is</p> <blockquote> <p>AssertionError: "'abc': '1.0012'," ...
0
2016-09-07T22:54:19Z
39,380,225
<p>Right. Python's <strong>in</strong> operator works on an iterable object. The clause <strong>in test_json</strong> means, "is the given item a key of the dictionary". It does <em>not</em> search the dictionary for a <em>key:value</em> pair.</p> <p>To do this, use a two-step process:</p> <pre><code>assertIn('abc...
3
2016-09-07T23:00:45Z
[ "python", "python-3.x" ]
Python assertIn test statement not finding string?
39,380,171
<p>I am using <code>assertIn</code> to test that a part of the result in JSON string is correct.</p> <pre><code>test_json = some_function_returning_a_dict() self.assertIn(expected_json, test_json, "did not match expected output") </code></pre> <p>The error is</p> <blockquote> <p>AssertionError: "'abc': '1.0012'," ...
0
2016-09-07T22:54:19Z
39,380,238
<p>It looks like you are attempting to find a string inside a dictionary, which will check to see if the string you are giving is a key of the specified dictionary. Firstly don't convert your first dictionary to a string, and secondly do something like <code>all(item in test_json.items() for item in expected_json.items...
1
2016-09-07T23:01:42Z
[ "python", "python-3.x" ]
How can tkinter justify align text
39,380,182
<p>I would like to know how can we make tkinter to align text justify.</p> <p>There's only <code>CENTER</code>, <code>LEFT</code>, and <code>RIGHT</code>.</p> <p>I would like something like <code>justify = "JUSTIFY"</code> And it seems that it is not implemented.</p> <p>Thank you. </p>
0
2016-09-07T22:56:00Z
39,381,246
<p>There is nothing built-in to Tkinter that will justify text to both the left and right margins at the same time.</p>
0
2016-09-08T01:26:11Z
[ "python", "python-3.x", "tkinter", "text-alignment" ]
Wrapped (circular) 2D interpolation in python
39,380,251
<p>I have angular data on a domain that is wrapped at pi radians (i.e. 0 = pi). The data are 2D, where one dimension represents the angle. I need to interpolate this data onto another grid in a wrapped way.</p> <p>In one dimension, the np.interp function takes a period kwarg (for numpy 1.10 and later): <a href="http:...
3
2016-09-07T23:03:05Z
39,382,154
<h2>An explanation of how <code>np.interp</code> works</h2> <p>Use the <a href="https://github.com/numpy/numpy/blob/v1.11.0/numpy/lib/function_base.py#L1570-L1692" rel="nofollow">source</a>, Luke!</p> <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow">numpy doc for <...
1
2016-09-08T03:29:23Z
[ "python", "numpy", "interpolation" ]
How to write a regex for a text including comma separated values in python?
39,380,275
<p>I'm trying to write a regex in python to get F1 to F8 fields from a line that looks like this:</p> <pre><code>LineNumber(digits): F1, F2, F3, ..., F8; </code></pre> <p><code>F1</code> to <code>F8</code> can have lowercase/uppercase letters and hyphens.</p> <p>For example:</p> <pre><code>Header Description 21: Ye...
0
2016-09-07T23:05:50Z
39,380,365
<p>When you have a construct like <code>(pattern){number}</code> then although it matches multiple instances, only the last one will be stored. In other words, you get one bucket per <code>()</code>, even if you parse it multiple times, in which case the last instance is the one kept. Note that you will get a bucket ...
0
2016-09-07T23:19:07Z
[ "python", "regex", "csv" ]
How to write a regex for a text including comma separated values in python?
39,380,275
<p>I'm trying to write a regex in python to get F1 to F8 fields from a line that looks like this:</p> <pre><code>LineNumber(digits): F1, F2, F3, ..., F8; </code></pre> <p><code>F1</code> to <code>F8</code> can have lowercase/uppercase letters and hyphens.</p> <p>For example:</p> <pre><code>Header Description 21: Ye...
0
2016-09-07T23:05:50Z
39,380,453
<pre><code>&gt;&gt;&gt; pat = re.compile("""\s+ # one or more spaces (.*?) # the shortest anything (capture) \s* # zero or more spaces [;,] # a semicolon or a colon """,re.X) &gt;&gt;&gt; pat.findall("LineNumber(digits): F1, F2, F...
1
2016-09-07T23:32:02Z
[ "python", "regex", "csv" ]
python normal distribution
39,380,316
<p>I have a list of numbers, with sample mean and SD for these numbers. Right now I am trying to find out the numbers out of mean+-SD,mean +-2SD and mean +-3SD. For example, in the part of mean+-SD, i made the code like this:</p> <pre><code>ND1 = [np.mean(l)+np.std(l,ddof=1)] ND2 = [np.mean(l)-np.std(l,ddof=1)] m...
1
2016-09-07T23:12:25Z
39,380,451
<p>This might help. We will use <code>numpy</code> to grab the values you are looking for. In my example, I create a normally distributed array and then use boolean slicing to return the elements that are outside of +/- 1, 2, or 3 standard deviations. </p> <pre><code>import numpy as np # create a random normally d...
2
2016-09-07T23:31:41Z
[ "python", "python-3.x" ]
python normal distribution
39,380,316
<p>I have a list of numbers, with sample mean and SD for these numbers. Right now I am trying to find out the numbers out of mean+-SD,mean +-2SD and mean +-3SD. For example, in the part of mean+-SD, i made the code like this:</p> <pre><code>ND1 = [np.mean(l)+np.std(l,ddof=1)] ND2 = [np.mean(l)-np.std(l,ddof=1)] m...
1
2016-09-07T23:12:25Z
39,380,538
<p>You are on the right track there. You know the mean and standard deviation of your list <code>l</code>, though I'm going to call it something a little less ambiguous, say, <code>samplePopulation</code>. </p> <p>Because you want to do this for several intervals of standard deviation, I recommend crafting a small fun...
1
2016-09-07T23:42:07Z
[ "python", "python-3.x" ]
Why no output using Word2Vec?
39,380,424
<p>I have a dataframe <code>DF</code> that looks like</p> <pre><code>index posts 0 &lt;div class="content"&gt;A number of &lt;br/&gt;&lt;br/&gt;three ... &lt;/div&gt; 1 &lt;div class="content"&gt;Stack ... &lt;br/&gt;&lt;br/&gt;overflow ... &lt;/div&gt; ... </code></pre> <p>I then try to tokenize each <cod...
0
2016-09-07T23:26:38Z
39,515,884
<p>The function <code>model.doesnt_match()</code> doesn't print anything out; it returns a value. <strong>Print</strong> the returned value to see the output. </p> <p>If you were copy-pasting from this <a href="http://rare-technologies.com/word2vec-tutorial/" rel="nofollow"><code>word2vec</code> tutorial</a>: It's sho...
0
2016-09-15T16:17:53Z
[ "python", "nltk", "word2vec" ]
How to interpolated irregularly distributed data on a non-linear grid in python?
39,380,436
<p>I got a dataset of around 80.000 points (x,y,z), while the points are irregularly distributed in the (x,y) \in [0,a]x[0,b] plane and at every point (x,y) the physical quantity z takes a certain value. To further evaluate the data I want to interpolate it on a grid.</p> <p>Before I used scipy.interpolate.griddata to...
-1
2016-09-07T23:28:31Z
39,380,757
<p>I think you have it backwards: your grid can be as regular as can be but each grid point should be evaluated using the same number of sample points, thus allowing for strong gradient changes in regions of high sample density, and imposing smoothness in data sparse regions. </p> <p>I use inverse-distance weighted tr...
0
2016-09-08T00:13:50Z
[ "python", "grid", "interpolation" ]
Python read from a text file and create/return dictionary values
39,380,501
<p>I am having trouble creating a program that reads from text which maps a word and returns values. How would I write a code to read a text file and spit back a dictionary data structure. The text file is a lot longer than 3, but here is an example.</p> <pre><code>Mary 21.0 25.0 Carson 25.0 ...
-4
2016-09-07T23:36:47Z
39,380,557
<p>You are looking for a simple snippet like this</p> <pre><code>dic = {} with open(filename, 'r') as f: for line in f: info = line.split('\t') dic[info[0]] = info[1:] </code></pre> <p>It is just a model, adapt that to your needs.</p>
-2
2016-09-07T23:45:25Z
[ "python", "file", "dictionary" ]
Python read from a text file and create/return dictionary values
39,380,501
<p>I am having trouble creating a program that reads from text which maps a word and returns values. How would I write a code to read a text file and spit back a dictionary data structure. The text file is a lot longer than 3, but here is an example.</p> <pre><code>Mary 21.0 25.0 Carson 25.0 ...
-4
2016-09-07T23:36:47Z
39,380,581
<p>If you text file is tab separated with one key/value pair per line you can use this (python 3.4+ only):</p> <pre><code>my_dict = {} with open('c:/path/to/file.txt', 'r') as fp: for line in fp: # grabs the first value as k and everything else a v k, *v = line.strip().split('\t') # turn th...
-1
2016-09-07T23:49:16Z
[ "python", "file", "dictionary" ]
Pygame: how to blit an image that follows another image
39,380,527
<p>I'm trying reproduce the game "Snake" in pygame, using the pygame.blit function, instead of pygame.draw. My question is how to make an image follow another image. I mean, make the snake's body photo follow your head. In the current state of my program the head moves on its own.</p>
0
2016-09-07T23:40:12Z
39,380,622
<p>Keep positions of snake segments on list (first segment is head).</p> <p>Later new position of head insert before first segment (and remove last segment). </p> <p>Use this list to blit snake segments.</p>
0
2016-09-07T23:55:22Z
[ "python" ]
z3Py: Cast BoolRef to one-bit BitVecRef
39,380,560
<p>Is it possible to cast <code>BoolRef</code> to a one-bit-long <code>BitVecRef</code> in z3Py? In my design, it is required that a <code>BitVecRef</code> is returned from a comparison between two other <code>BitVecRef</code>'s. This would be similar to casting a python <code>bool</code> to an <code>int</code>. Here i...
0
2016-09-07T23:45:55Z
39,396,652
<p>Bit-vectors can't be casted to Boolean automatically. The usual approach is to wrap them in if-then-elses, e.g., in this example, instead of </p> <pre><code>s.add(res == (bv1 &lt; bv2)) </code></pre> <p>we can say</p> <pre><code>c = If(bv1 &lt; bv2, BitVecVal(1, 1), BitVecVal(0, 1)) s.add(res == c) </code></pre>
0
2016-09-08T17:06:02Z
[ "python", "casting", "z3", "z3py", "bitvector" ]
Searching Dictionary in list
39,380,677
<p>I am working on my first project with API's and I am having trouble accessing the data. I am working off an example that calls its data with this loop:</p> <pre><code>for item in data['objects']: print item['name'], item['phone'] </code></pre> <p>This works great for data stored as nested dictionaries (the ou...
1
2016-09-08T00:02:32Z
39,380,694
<p>If I understood it correctly, your <code>data['objects']</code> is now an entry in a list, right?</p> <p>So just iterate the list and your logic will remain the same</p> <pre><code>for item in objects: print item['name'], item['phone'] </code></pre> <p>being </p> <pre><code>objects = [ { "key":"2014cama", "...
1
2016-09-08T00:06:06Z
[ "python", "list", "dictionary" ]
What is causing "TypeError: not all arguments converted during string formatting"
39,380,711
<p>This code produces the error:</p> <pre><code># -*- coding: utf-8 -*- amount = float(input("Enter the purchase price please.")) down_payment=amount *0.10 monthly_rate = (amount - down_payment) *.05 ending_balance=amount-down_payment print("|Ø-6s|Ø-16s|Ø-9s|Ø-8s|Ø-14s|" % ("Month" , "Current Balance" , "Intere...
0
2016-09-08T00:07:31Z
39,380,749
<p>You have to use <code>%</code> instead of <code>Ø</code> in your formating strings.</p> <pre><code>print("|%-6s|%-16s|%-9s|%-8s|%-14s|" % ("Month" , "Current Balance" , "Interest" , "Payment" , "Ending Balance")) </code></pre> <p>and</p> <pre><code>print("|%-6f|%-16f|%-9f|%-8f|%-14f|" % (month , starting_balance...
0
2016-09-08T00:13:19Z
[ "python" ]
Passing data to and from C++ code using a python driver
39,380,723
<p>I am trying to pass arrays to a c++ function from a python driver. One of the arrays I am passing to the c++ function is a results array. I know the data is passing to the code correctly, but seems to be truncating on the way back. I'm loosing my precision after the decimal. Any ideas where I went wrong? Below ...
2
2016-09-08T00:08:56Z
39,381,090
<blockquote> <p>I know the data is passing to the code correctly, but seems to be truncating on the way back. I'm losing my precision after the decimal. Any ideas where I went wrong?</p> </blockquote> <p>You are using integer division instead of floating-point division.</p> <p>You can fix this by using:</p> <pre><...
0
2016-09-08T01:03:49Z
[ "python", "c++", "floating-point", "ctypes" ]
Python: how to correctly convert from a string date in a particular time zone?
39,380,753
<p>I have input from a human in <code>YYYY-MM-DD HH:MM:SS</code> format that I know is supposed to be Los Angeles local time. In Python, how do I convert this to a <code>datetime.datetime</code> object that is unambiguous and correct? I am aware that the input is ambiguous during the autumn transition out of DST; I'm f...
1
2016-09-08T00:13:37Z
39,385,127
<p>I found <a href="https://artofsoftware.org/2012/04/17/dealing-with-daylight-savings-time-using-pytz/" rel="nofollow">This</a>, which may help. Chopping it up a bit, I got the -0700 that you're looking for. I have to admit I don't understand this module, so I can't point to where you can fix your code quickly (and I ...
0
2016-09-08T07:37:06Z
[ "python", "datetime", "python-datetime", "python-dateutil" ]
Python: how to correctly convert from a string date in a particular time zone?
39,380,753
<p>I have input from a human in <code>YYYY-MM-DD HH:MM:SS</code> format that I know is supposed to be Los Angeles local time. In Python, how do I convert this to a <code>datetime.datetime</code> object that is unambiguous and correct? I am aware that the input is ambiguous during the autumn transition out of DST; I'm f...
1
2016-09-08T00:13:37Z
39,757,224
<p>You can use <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow">dateparser</a> for that.</p> <p><pre></p> <code>import dateparser &gt;&gt;&gt; dateparser.parse('2016-08-01 00:00:00', settings={'TIMEZONE': 'US/Pacific', 'TO_TIMEZONE': 'UTC'}) datetime.datetime(2016, 8, 1, 7, 0) </code></pre> <p></p>
0
2016-09-28T20:38:32Z
[ "python", "datetime", "python-datetime", "python-dateutil" ]
How to set miterlimit when saving as svg with matplotlib
39,380,761
<p>Is there anyway to set the miterlimit when saving a matplotlib plot to svg? I'd like to programatically get around this bug:<a href="https://bugs.launchpad.net/inkscape/+bug/1533058" rel="nofollow">https://bugs.launchpad.net/inkscape/+bug/1533058</a> whereas I am having to manually change this in the ".svg" text fil...
2
2016-09-08T00:14:44Z
39,539,384
<p>This parameter is defined as <code>'stroke-miterlimit': '100000'</code> and is hard-set in backend_svg.py. There is no such parameter in matplotlibrc, so customizing with style sheet is unlikely to be possible.</p> <p>I used the following code to fix this issue:</p> <pre><code>def fixmiterlimit(svgdata, miterlimit...
1
2016-09-16T20:10:10Z
[ "python", "svg", "matplotlib" ]
How can I kill all threads?
39,380,811
<p>In this script:</p> <pre><code>import threading, socket class send(threading.Thread): def run(self): try: while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url,port)) s.send(b"He...
1
2016-09-08T00:20:31Z
39,380,886
<p>No. Individual threads can't be terminated forcibly (it's unsafe, since it could leave locks held, leading to deadlocks, among other things).</p> <p>Two ways to do something like this would be to either:</p> <ol> <li>Have all threads launched as <code>daemon</code> threads, with the main thread waiting on an <code...
0
2016-09-08T00:31:17Z
[ "python", "multithreading", "python-3.x", "kill", "terminate" ]
Find index of string_to_hash_bucket in linear weight index Tensorflow
39,380,823
<p>I am working with tensor flow on a binary classification model using a the LinearClassifier class. One of the features I'm basing the classification on is a column called hat:</p> <pre><code>hat = tf.contrib.layers.sparse_column_with_hash_bucket("hat", hash_bucket_size=1000) </code></pre> <p>After I have initializ...
0
2016-09-08T00:22:02Z
39,396,534
<p>Another way to inspect the weights which is black-box (and hence guaranteed to work) is to evaluate your entire model on an example which just has a single hat feature turned on. Then you can see the weight assigned by the model to each feature.</p>
0
2016-09-08T16:58:08Z
[ "python", "tensorflow" ]
How to update a HyperlinkedRelatedField in Django Rest Framework
39,380,874
<p>I'm trying to update a HyperlinkedRelatedField connected to a ManyToManyField in Django through Django Rest Framework and coming up with a successful PUT (status 200) that ignores my HyperlinkedRelatedField data. I'm obviously missing something, but what?</p> <pre><code>#models.py class Product(models.Model): ...
0
2016-09-08T00:28:58Z
39,381,917
<p>it seems like you didn't override the <strong>create()</strong> method of <strong>UserPrefsSerializer().</strong></p> <pre><code>class UserPrefsSerializer(serializers.HyperlinkedModelSerializer): favorite_products = serializers.HyperlinkedRelatedField( queryset = Product.objects.all(), many = T...
1
2016-09-08T02:58:20Z
[ "python", "json", "django", "django-rest-framework" ]
How to color leaves on `ete3` Tree? (Python 3)
39,380,907
<p>I just started using <code>ete3</code> and it is awesome. </p> <p><strong>How can I color the leaves of an <code>ete3</code> Tree object using a color dictionary?</strong> I made <code>"c":None</code> because I don't want the of <code>c</code> to show up. </p> <p>I want to have better control of the tree render bu...
2
2016-09-08T00:34:50Z
39,409,340
<p>I would do it like this:</p> <pre><code>from ete3 import Tree, TextFace, TreeStyle # Build Tree tree = Tree( "((a,b),c);" ) # Leaf mapping D_leaf_color = {"a":"red", "b":"green"} for node in tree.traverse(): # Hide node circles node.img_style['size'] = 0 if node.is_leaf(): color = D_leaf_color....
2
2016-09-09T10:21:56Z
[ "python", "colors", "tree", "etetoolkit", "ete3" ]
Compiler not understanding my optional argument in Python
39,381,004
<p>Hello I'm having issues with an exercise that is asking me to write code that contains a function, 3 dictionaries, and an optional argument.</p> <p><strong>Here is my code:</strong></p> <pre><code>def make_album(artist_name, album_title, num_tracks): """Return artist and album title name.""" CD1 = {'sonic...
1
2016-09-08T00:51:12Z
39,381,021
<p>You need to <code>def</code> the function with a <a href="https://docs.python.org/3/tutorial/controlflow.html#default-argument-values" rel="nofollow">default for the argument to be optional</a>, e.g.:</p> <pre><code># num_tracks=None means if not provided, num_tracks is set to None def make_album(artist_name, album...
2
2016-09-08T00:53:24Z
[ "python" ]
Simple PyQt5 QML application causes segmentation fault
39,381,009
<p>In trying to get a <a href="https://www.boxcontrol.net/beginners-pyqt5-and-qml-integration-tutorial.html" rel="nofollow">very basic PyQt5 QML example</a> to run, I found that I get a segmentation fault. I verified that it only seems deal with displaying QML since <a href="http://pyqt.sourceforge.net/Docs/PyQt5/qml....
0
2016-09-08T00:51:33Z
40,119,580
<p>The rabbit hole went deeper than I thought. There were a few problems.</p> <ol> <li>The version of SIP in the Linux Mint 18 (likely Ubuntu 16.04) repository was too old. I updated to 4.18.1 by <a href="http://pyqt.sourceforge.net/Docs/sip4/installation.html" rel="nofollow">installing from source</a>.</li> <li>Wit...
0
2016-10-18T23:18:57Z
[ "python", "qt", "qml", "pyqt5" ]
I am trying to sum a list by values in python and i am not having any luck
39,381,017
<p>Good day,</p> <p>I am trying to sum a list by values in python and i am not having any luck. what i would like to end up with is three summed values.</p> <p>lst = [100, -1, -2, -3, 100, -1, -2, -3, 100]</p> <p>100 -1-2-3 = 94</p> <p>100 -1-2-3 = 94</p> <p>100 = 100</p> <p>Any help you be greatly appreciated.</...
2
2016-09-08T00:52:37Z
39,381,261
<p>How about this?</p> <pre><code>s = [] for i in lst: if i &gt; 0 or len(s) == 0: s.append(i) # start a new element in s when element is larger than zero else: s[-1] += i # otherwise add it to the last element of s s # [94, 94, 100] </code></pre> <p>Or if you use pandas:</p>...
2
2016-09-08T01:27:53Z
[ "python", "list", "sum", "group" ]
Selenium Phyton Chrome open with def options
39,381,088
<p>I want open Google Chrome, like its self, the chromedriver open it without my cookies, my passwords, my history and all that staff. i tried to play with the option, and search all over the web for solution, didn't got one, plus i tried</p> <p>from selenium import webdriver from selenium.webdriver.common.keys import...
1
2016-09-08T01:03:41Z
39,381,844
<blockquote> <p>AttributeError: 'Options' object has no attribute 'add_arguments'</p> </blockquote> <p>It should be <code>add_argument</code> instead of <code>add_arguments</code>. You should try as :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options opt = webdriv...
1
2016-09-08T02:49:00Z
[ "python", "selenium", "selenium-webdriver" ]
Azure Webapp wheels --find-links does not work
39,381,114
<p>I have been struggling with --find-links for an entire day, and I will be very grateful if sb could help me out here.</p> <p>I have been developing using python3.4 and one of the new features I added uses Azure Storage( the most recent version) and it requires cryptograph, which requires cffi, idna, etc... However,...
1
2016-09-08T01:07:50Z
39,456,034
<p>You are not the only one in that situation: <a href="https://github.com/Azure/azure-storage-python/issues/219" rel="nofollow">https://github.com/Azure/azure-storage-python/issues/219</a></p> <p>It seems for an unknown reason that the version of pip on the WebApp machine does not detect the platform tag as "win32" (...
1
2016-09-12T17:54:14Z
[ "python", "azure", "pypi", "azure-web-app-service", "python-wheel" ]
How do i programmatically logout user?[Django]
39,381,137
<p>I know to logout user in Django. If i want to logout user, i would do</p> <pre><code>from django.contrib.auth import logout def logout_view(request): logout(request) </code></pre> <p>But what is the relevant way of logging out the user if i am using django oauth toolkit(DOT)? </p> <p>Should i follow the same...
1
2016-09-08T01:11:18Z
39,381,304
<p>You can check <a href="https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_04.html" rel="nofollow">Revoking an OAuth2 Token</a></p> <blockquote> <p>You’ve granted a user an Access Token, following part 1 and now you would like to revoke that token, probably in response to a client request (t...
2
2016-09-08T01:33:02Z
[ "python", "django", "python-3.x", "oauth", "django-rest-framework" ]
How to get rid of extra white space on subplots with shared axes?
39,381,162
<p>I'm creating a plot using python 3.5.1 and matplotlib 1.5.1 that has two subplots (side by side) with a shared Y axis. A sample output image is shown below:</p> <p><a href="http://i.stack.imgur.com/OK4ap.png" rel="nofollow"><img src="http://i.stack.imgur.com/OK4ap.png" alt="Sample Image"></a></p> <p>Notice the ext...
1
2016-09-08T01:14:33Z
39,381,449
<p>Autoscale tends to add a buffer to the data so that all of the data points are easily visible and not part-way cut off by the axes. </p> <p>Change:</p> <pre><code>ax1.autoscale(enable=True, axis='Y', tight=True) </code></pre> <p>to:</p> <pre><code>ax1.set_ylim(days.min(),days.max()) </code></pre> <p>and</p> <...
1
2016-09-08T01:56:26Z
[ "python", "matplotlib" ]
How to print/show an expression in rational number form in python
39,381,222
<p>I've been developing a Tkinter app and at some label i need to put formula that should look like a rational number(expression1/expression2, like a numerator and denominator and a bar between them). I did some digging and couldnt find anything related to it. Any suggestions on how this can be done ?</p> <p>I even co...
4
2016-09-08T01:22:22Z
39,381,318
<pre><code>print '%s'%Fraction(1.5) &gt;&gt;&gt; '3/2' </code></pre> <p>See: <a href="https://pymotw.com/2/fractions/" rel="nofollow">https://pymotw.com/2/fractions/</a></p>
0
2016-09-08T01:35:30Z
[ "python", "math", "tkinter" ]
How to print/show an expression in rational number form in python
39,381,222
<p>I've been developing a Tkinter app and at some label i need to put formula that should look like a rational number(expression1/expression2, like a numerator and denominator and a bar between them). I did some digging and couldnt find anything related to it. Any suggestions on how this can be done ?</p> <p>I even co...
4
2016-09-08T01:22:22Z
39,381,481
<pre><code>print('\n\033[4m'+'3' + '\033[0m'+'\n2') </code></pre> <p><code>\033[4m</code> enables underline</p> <p><code>\033[0m</code> resets it</p> <p>It will basically display something that looks like (with an underline under the 3):</p> <pre><code>3 2 </code></pre>
2
2016-09-08T01:59:35Z
[ "python", "math", "tkinter" ]
How to print/show an expression in rational number form in python
39,381,222
<p>I've been developing a Tkinter app and at some label i need to put formula that should look like a rational number(expression1/expression2, like a numerator and denominator and a bar between them). I did some digging and couldnt find anything related to it. Any suggestions on how this can be done ?</p> <p>I even co...
4
2016-09-08T01:22:22Z
39,472,345
<p>A high-tech solution would be to use <a href="http://matplotlib.org/1.4.1/index.html" rel="nofollow">matplotlib</a> in Tkinter. It provides a scaled-down version of <code>Latex</code> which it calls <a href="http://matplotlib.org/1.4.1/users/mathtext.html#mathtext-tutorial" rel="nofollow">mathtext</a>. This route do...
1
2016-09-13T14:19:10Z
[ "python", "math", "tkinter" ]
Compiling a dictionary by pulling data from other dictionaries
39,381,286
<p>I am doing a project in which I extract data from three different data sets and combine it to look at campaign contributions. To do this I turned the relevant data from two of the sets into dictionaries (canDict and otherDict) with ID numbers as keys and the information I need (party affiliation) as values. Then I w...
0
2016-09-08T01:31:01Z
39,381,709
<p>Suppose we simplify and rearrange things a bit:</p> <pre><code>import sys from collections import defaultdict employerDict = defaultdict(list) ID, EMPLOYER, AMOUNT = 0, 11, 14 with open(path3) as f: # path3 is a *.txt file for n, line in enumerate(f): if n % 10000 == 0: print(n) ...
0
2016-09-08T02:29:46Z
[ "python", "dictionary" ]
Compiling a dictionary by pulling data from other dictionaries
39,381,286
<p>I am doing a project in which I extract data from three different data sets and combine it to look at campaign contributions. To do this I turned the relevant data from two of the sets into dictionaries (canDict and otherDict) with ID numbers as keys and the information I need (party affiliation) as values. Then I w...
0
2016-09-08T01:31:01Z
39,422,088
<p>Thanks for all the input everyone - however, it looks like its a problem with my data file, not a problem with the program. Dangit.</p>
0
2016-09-10T03:01:26Z
[ "python", "dictionary" ]
Change character based off of its position? Python 2.7
39,381,399
<p>I have a string on unknown length, contain the characters a-z A-Z 0-9. I need to change each character using their position from Left to Right using a dictionary.</p> <p>Example:</p> <pre><code>string = "aaaaaaaa" def shift_char(text): for i in len(text): # Do Something for each character return ou...
-2
2016-09-08T01:47:56Z
39,432,369
<p>Alright, hopefully this is understandable, otherwise feel free to ask questions.</p> <pre><code>import random import string # Letter pool, these are all the possible characters # you can have in your string letter_pool = list(string.ascii_letters + string.digits) input_string = "HelloWorld" string_length = len(in...
0
2016-09-11T02:43:29Z
[ "python", "python-2.7" ]
Change character based off of its position? Python 2.7
39,381,399
<p>I have a string on unknown length, contain the characters a-z A-Z 0-9. I need to change each character using their position from Left to Right using a dictionary.</p> <p>Example:</p> <pre><code>string = "aaaaaaaa" def shift_char(text): for i in len(text): # Do Something for each character return ou...
-2
2016-09-08T01:47:56Z
39,433,530
<p>With the help of <a href="http://stackoverflow.com/users/235698/mark-tolonen">Mark Tolonen</a> in <a href="http://stackoverflow.com/questions/39433191/convert-int-into-str-while-in-getitem-python-2-7">this post</a>, I was able to come up with a solution. The following example only uses 4 dictionaries, while i intend...
0
2016-09-11T06:42:02Z
[ "python", "python-2.7" ]
GraphQL + Django: resolve queries using raw PostgreSQL query
39,381,436
<p><strong>What is the best way to use GraphQL with Django when using an external database to fetch data from multiple tables (i.e., creating a Django Model to represent the data would not correspond to a single table in my database)?</strong></p> <p>My approach was to temporarily abandon using Django models since I d...
1
2016-09-08T01:53:49Z
39,396,675
<p>Here is temporary workaround, although I'm hoping there is something cleaner to handle the snake_cased fieldnames.</p> <blockquote> <p>project/main/<strong>app/schema.py</strong></p> </blockquote> <pre class="lang-python prettyprint-override"><code>from graphene import ( ObjectType, ID, String, Int, Float, L...
0
2016-09-08T17:08:11Z
[ "python", "django", "postgresql", "graphql", "graphene-python" ]
GraphQL + Django: resolve queries using raw PostgreSQL query
39,381,436
<p><strong>What is the best way to use GraphQL with Django when using an external database to fetch data from multiple tables (i.e., creating a Django Model to represent the data would not correspond to a single table in my database)?</strong></p> <p>My approach was to temporarily abandon using Django models since I d...
1
2016-09-08T01:53:49Z
39,403,047
<p>Default resolvers on GraphQL Python / Graphene try to do the resolution of a given field_name in a root object using getattr. So, for example, the default resolver for a field named <code>order_items</code> will be something like:</p> <pre><code>def resolver(root, args, context, info): return getattr(root, 'ord...
2
2016-09-09T02:44:16Z
[ "python", "django", "postgresql", "graphql", "graphene-python" ]
pandas plot with different variable for subplots and colour?
39,381,540
<p>Currently this code:</p> <pre><code>count_df = (df[['rank', 'name', 'variable', 'value']] .groupby(['rank', 'variable', 'name']) .agg('count') .unstack()) count_df .head() # value # name 1lin STH_km27_lin ST_lin S_lin # rank variable ...
4
2016-09-08T02:08:41Z
39,381,765
<p>Hrm. I suspect this isn't doable in pandas by itself, but I found a way to do it in Seaborn:</p> <pre><code>import seaborn as sns cdf = (df[['rank', 'name', 'variable', 'value']] .groupby(['rank', 'variable', 'name']) .agg('count')) sns.factorplot(x="rank", y="value", row="variable", hue="nam...
2
2016-09-08T02:38:10Z
[ "python", "pandas", "matplotlib", "plot" ]
how to include tests in a distributable django app?
39,381,593
<p>I distribute a small django app that I wanted to write a test for. It uses some settings and I was importing </p> <p><code>from django.conf import settings</code> </p> <p>in the app file but this leaves me with a problem because the standalone app has no django project so how would one write and run tests on it?</...
0
2016-09-08T02:15:54Z
39,381,648
<p>In your app folder, create a folder named <code>tests</code>, and in that folder place your tests (in a single <code>.py</code> file or multiple files. </p> <p>You will end up with a folder structure like this:</p> <pre><code>my_app/ tests/ test_views.py test_other_stuff.py </code></pre> <p>Th...
0
2016-09-08T02:23:01Z
[ "python", "django" ]
how to include tests in a distributable django app?
39,381,593
<p>I distribute a small django app that I wanted to write a test for. It uses some settings and I was importing </p> <p><code>from django.conf import settings</code> </p> <p>in the app file but this leaves me with a problem because the standalone app has no django project so how would one write and run tests on it?</...
0
2016-09-08T02:15:54Z
39,386,036
<p>My solution was to create a django project with the name of the app and then put all the distribution files such as </p> <pre><code>setup.py MANIFEST.in </code></pre> <p>in the project level directory and then indicate only the files I want to include with the distribution in the MANIFEST.in file. </p> <p>MAINFES...
0
2016-09-08T08:25:34Z
[ "python", "django" ]
Python Regex Matching characters
39,381,651
<p>I am trying to learn Python regular expressions. I have a long string that contains many patterns that look like: <code>#v=xxxxxxxxxx</code> where x is the variable characters I want.</p> <p>I was thinking I could use <code>re.findall(r'...', myString)</code> where <code>...</code> is my pattern. That's the part I'...
1
2016-09-08T02:23:16Z
39,381,731
<p>You were close! Here's an RE that'll work: </p> <pre><code>In [1]: import re In [2]: s = "#v=yyyyyyyyyy #v=xxxxxxxxxx #v=zzzzzzzzzz" In [3]: re.findall(r'#v=(\w{10})', s) Out[3]: ['yyyyyyyyyy', 'xxxxxxxxxx', 'zzzzzzzzzz'] </code></pre>
1
2016-09-08T02:32:54Z
[ "python", "regex" ]
Python -Taking dot product of long list of arrays
39,381,727
<p>So I'm trying to to take the dot product of two arrays using numpy's dot product function.</p> <pre><code>import numpy as np MWFrPos_Hydro1 = subPos1[submaskFirst1] x = MWFrPos_Hydro1 MWFrVel_Hydro1 = subVel1[submaskFirst1] y = MWFrVel_Hydro1 MWFrPosMag_Hydro1 = [np.linalg.norm(i) for i in MWFrPos_Hydro1] np.dot(...
0
2016-09-08T02:31:59Z
39,381,781
<p>You can't take the dot product of two <code>n * m</code> matrices unless <code>m == n</code> -- when multiplying two matrices, A and B, B needs to have as many columns as A has rows. (So you <em>can</em> multiply an <code>n * m</code> matrix with an <code>m * n</code> matrix.) </p> <p>See <a href="http://mathinsigh...
2
2016-09-08T02:40:15Z
[ "python", "numpy" ]
Python -Taking dot product of long list of arrays
39,381,727
<p>So I'm trying to to take the dot product of two arrays using numpy's dot product function.</p> <pre><code>import numpy as np MWFrPos_Hydro1 = subPos1[submaskFirst1] x = MWFrPos_Hydro1 MWFrVel_Hydro1 = subVel1[submaskFirst1] y = MWFrVel_Hydro1 MWFrPosMag_Hydro1 = [np.linalg.norm(i) for i in MWFrPos_Hydro1] np.dot(...
0
2016-09-08T02:31:59Z
39,383,113
<p>Some possible products for <code>(n,3)</code> arrays (here I'll just one)</p> <pre><code>In [434]: x=np.arange(12.).reshape(4,3) In [435]: x Out[435]: array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.], [ 9., 10., 11.]]) </code></pre> <p>element by element product, summed ac...
2
2016-09-08T05:22:53Z
[ "python", "numpy" ]
Removing List from List of Lists with condition
39,381,769
<p>I have this list of projects, and I want to remove it one by one start from last item to item-n until it reach some total value of budget = 325.000</p> <pre><code>from collections import namedtuple Item = namedtuple('Item', 'region sector name budget target performance'.split()) sorted_KP = [Item(region='H', sect...
3
2016-09-08T02:39:17Z
39,382,456
<p>Updating the answer as when I actually tried to run it I found a few other problems:</p> <ul> <li>the inner <code>for item in sorted_KP</code> uses the same <code>item</code> counter as the outer loop and overwrites it - always attempting to remove the <code>A30</code> (last) item</li> <li>when switching to <code>i...
1
2016-09-08T04:09:53Z
[ "python", "list", "condition" ]