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 |
|---|---|---|---|---|---|---|---|---|---|
Getting the pk from a foreignkey relationship django | 37,595,205 | <p>I already ask about args and kwargs, but now i have this IntegrityError, if you guys can help me, i will be thankfull! I've added the traceback now.</p>
<p>I'm trying to build a blog, and this is the comments section.</p>
<blockquote>
<p>In <em>views.py</em></p>
</blockquote>
<pre><code>class createComment(View... | -1 | 2016-06-02T14:49:35Z | 37,595,454 | <p>You can't set the <code>pk</code> manually, just do without putting it in. The <code>pk</code> field is autoincremented as you create objects, and cannot be set manually unless you're using another field for a private key.</p>
<p>If you want to set your <code>Comment</code> object's ForeignKey for <code>Post</code>... | 1 | 2016-06-02T15:00:27Z | [
"python",
"django"
] |
Getting the pk from a foreignkey relationship django | 37,595,205 | <p>I already ask about args and kwargs, but now i have this IntegrityError, if you guys can help me, i will be thankfull! I've added the traceback now.</p>
<p>I'm trying to build a blog, and this is the comments section.</p>
<blockquote>
<p>In <em>views.py</em></p>
</blockquote>
<pre><code>class createComment(View... | -1 | 2016-06-02T14:49:35Z | 37,596,448 | <p>It doesn't make sense to set attributes like <code>user_comment</code> on the form class. You need to save the form first with <code>commit=False</code>, update the object, then save it.</p>
<pre><code>form = self.form_class(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.user_comment = ... | 0 | 2016-06-02T15:43:03Z | [
"python",
"django"
] |
Python and php using raspberry GPIO | 37,595,274 | <p>Hi with a little python script i'm able to detect a button state that is connected in my raspberry board. This is the script</p>
<pre><code>#!/usr/bin/env python
import os
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
try... | 0 | 2016-06-02T14:52:46Z | 37,595,478 | <p>It does not work because <code>shell_exec</code> waits for the python script to finish before it returns. However, the python script obviously does not reach the end because of the infinite loop.
The simplest fix would be to poll the button status once with the python script and do any looping in php. Alternatively ... | 0 | 2016-06-02T15:01:33Z | [
"php",
"python",
"raspberry-pi",
"gpio"
] |
Python regex wont match or escape backslashes | 37,595,376 | <p>So I'm trying to run through a file and match to a line in python, I understand regex but for some reason I can't get this one to work. </p>
<pre><code> p1 = re.compile("\s*(service_description)\s*([A-Z]:\\\s*Drive\s*Space)")
for x in cfg: #cfg is an array of everyline in the file
if p1.match(x):
... | -2 | 2016-06-02T14:57:05Z | 37,595,921 | <p>It looks like you are trying to match the literal \ without accounting for the number of times that the string gets escaped. It would be easier to use r"literal string" to avoid doing any escaping on your pattern, before it goes to the re module</p>
<pre><code>import re
line = "service_description M:\ Drive Sp... | 0 | 2016-06-02T15:19:59Z | [
"python",
"regex",
"python-2.7"
] |
How to obtain perfect fit from np.random.power function | 37,595,398 | <p>I have generated random data using:</p>
<pre><code>bkg= 240-140*np.random.power(3.5,50000)
</code></pre>
<p>I plotted the points into a histogram by using</p>
<pre><code>h_all = plt.hist(all,bins=binedges,histtype='step')
</code></pre>
<p>My question is, provided that I know the pdf (in this case called "bkg") c... | 0 | 2016-06-02T14:58:05Z | 37,610,109 | <p>First of all, remark that your <code>bkg</code> is NOT a probability density function (pdf). Rather, it is a list of <em>observations</em> from a pdf. By calling <code>matplotlib.pyplot.hist</code> on this list of observations, you get to see a curve that approximates the (offset and scaled version of the) probabili... | 0 | 2016-06-03T08:58:25Z | [
"python",
"optimization"
] |
mocking input with a generator | 37,595,414 | <p>The following code doesn't do the mocking of input, is there a way to do it with a generator ?</p>
<pre><code> inputlist = [5,1,2,3,4,5,6]
def mock_input(dummy_prompt=">>> "):
global inputlist
for u in inputlist:
yield str(u)
__builtins__.input = mock_input
... | 1 | 2016-06-02T14:58:43Z | 37,596,041 | <p>You are assigning a generator to <code>__builtins__.input</code> rather than iterating with a generator and returning a value, this is why it doesn't work.</p>
<p>Instead, create a generate with <code>iter</code> and iterate over it with <code>next(..)</code></p>
<pre><code>inputlist = [6,1,2,3,4,5,6]
gen = iter(i... | 0 | 2016-06-02T15:24:55Z | [
"python",
"mocking",
"yield"
] |
mocking input with a generator | 37,595,414 | <p>The following code doesn't do the mocking of input, is there a way to do it with a generator ?</p>
<pre><code> inputlist = [5,1,2,3,4,5,6]
def mock_input(dummy_prompt=">>> "):
global inputlist
for u in inputlist:
yield str(u)
__builtins__.input = mock_input
... | 1 | 2016-06-02T14:58:43Z | 37,609,850 | <p>Ok thank you i missed the moment where the generator is instantiated.</p>
<pre><code>def gg(l):
for u in l:
yield str(u)
def mockinput(thelist):
bob = gg(thelist)
__builtins__.input = lambda prompt="toto": str(next(bob))
inputlist = [6,1,2,3,4,5,6]
mockinput(inputlist)
l=[]
for u in ra... | 1 | 2016-06-03T08:44:42Z | [
"python",
"mocking",
"yield"
] |
Try except with If statements in Python | 37,595,452 | <p>If I'm trying to prompt a user for their street name and they enter a # symbol i want to return an error and loop back to the top until they have entered a valid name. </p>
<p>Code:</p>
<pre><code>def streetname():
while True:
try:
nameinput = str(input("Please enter a street name: "))
... | 0 | 2016-06-02T15:00:24Z | 37,595,541 | <p>First off, you're using a python's general Exception class. A string with a pound sign in it wouldn't trigger any of python's native exceptions, you have to write your own exception class and then call it.. or you can do something like this</p>
<pre><code>if '#' in nameinput: #pound sign was found in the string
... | 1 | 2016-06-02T15:04:10Z | [
"python"
] |
Try except with If statements in Python | 37,595,452 | <p>If I'm trying to prompt a user for their street name and they enter a # symbol i want to return an error and loop back to the top until they have entered a valid name. </p>
<p>Code:</p>
<pre><code>def streetname():
while True:
try:
nameinput = str(input("Please enter a street name: "))
... | 0 | 2016-06-02T15:00:24Z | 37,595,644 | <p>You probably shouldn't use <code>try...except</code> for such a simple input check, that can easily done with if alone.</p>
<pre><code>def streetname():
while True:
nameinput = input("Please enter a street name: ")
if "#" in nameinput:
print("Error: name contains #, please try again... | 2 | 2016-06-02T15:08:23Z | [
"python"
] |
Python Repeat Elements in One List Based on Elements from Another | 37,595,458 | <p>Given the following lists:</p>
<pre><code>a = [0, 5, 1]
b = [1, 2, 1]
</code></pre>
<p>I'd like to repeat each element of [a] by the number of its corresponding position in [b] to produce this:</p>
<pre><code>[0, 5, 5, 1]
</code></pre>
<p>i.e. 0 occurs 1 time, 5 occurs 2 times, and 1 occurs 1 time.</p>
| 1 | 2016-06-02T15:00:32Z | 37,595,586 | <p>Use the <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip()</code> function</a> with <a href="https://docs.python.org/3/library/itertools.html#itertools.repeat" rel="nofollow"><code>itertools.repeat()</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itert... | 4 | 2016-06-02T15:05:47Z | [
"python",
"python-3.x",
"repeat"
] |
Python Repeat Elements in One List Based on Elements from Another | 37,595,458 | <p>Given the following lists:</p>
<pre><code>a = [0, 5, 1]
b = [1, 2, 1]
</code></pre>
<p>I'd like to repeat each element of [a] by the number of its corresponding position in [b] to produce this:</p>
<pre><code>[0, 5, 5, 1]
</code></pre>
<p>i.e. 0 occurs 1 time, 5 occurs 2 times, and 1 occurs 1 time.</p>
| 1 | 2016-06-02T15:00:32Z | 37,595,590 | <pre><code>In [7]: a = [0, 5, 1]
In [8]: b = [1, 2, 1]
In [9]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
Out[9]: [0, 5, 5, 1]
In [10]: b = [2, 3, 4]
In [11]: list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(a, b))))
Out[11]: [0, 0, 5, 5, 5, 1, 1, 1, 1]
</code></... | 1 | 2016-06-02T15:05:50Z | [
"python",
"python-3.x",
"repeat"
] |
How to get one line from a print output in linux? | 37,595,502 | <p>I'm trying to pull one line from a subprocess.check_output but so far I have no luck. I'm running a Python script and this is my code:</p>
<pre><code>output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat", shell=True)
</code></pre>
<p>and this is what I get back when I run the s... | 1 | 2016-06-02T15:02:35Z | 37,595,578 | <p>What about grep-ing the line ?</p>
<pre><code>output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat 2>&1 | grep 'RMS amplitude:'",stderr= subprocess.STDOUT, shell=True)
</code></pre>
| 0 | 2016-06-02T15:05:27Z | [
"python",
"linux",
"python-2.7",
"sed",
"subprocess"
] |
How to get one line from a print output in linux? | 37,595,502 | <p>I'm trying to pull one line from a subprocess.check_output but so far I have no luck. I'm running a Python script and this is my code:</p>
<pre><code>output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat", shell=True)
</code></pre>
<p>and this is what I get back when I run the s... | 1 | 2016-06-02T15:02:35Z | 37,596,162 | <p>I think the problem might that you're matching for spaces, but <code>sox</code> is actually outputting a tab characters to do the column spacing. Your terminal is likely expanding the tab to spaces, so when you copy/paste the output, you see spaces. Try matching for <code>[[:space:]]</code> (any whitespace character... | 0 | 2016-06-02T15:30:11Z | [
"python",
"linux",
"python-2.7",
"sed",
"subprocess"
] |
How to get one line from a print output in linux? | 37,595,502 | <p>I'm trying to pull one line from a subprocess.check_output but so far I have no luck. I'm running a Python script and this is my code:</p>
<pre><code>output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat", shell=True)
</code></pre>
<p>and this is what I get back when I run the s... | 1 | 2016-06-02T15:02:35Z | 37,596,454 | <p>In order to fix your line, you need to remove the 0 at the end and escape the '\1':</p>
<pre><code>output = subprocess.check_output("sox /home/pi/OnoSW/data/opsoroassistant/rec.wav -n stat 2>&1 | sed -n 's#^RMS amplitude:[^0-9]*\([0-9.]*\)$#\\1#p'",stderr= subprocess.STDOUT, shell=True)
</code></pre>
<p... | 0 | 2016-06-02T15:43:24Z | [
"python",
"linux",
"python-2.7",
"sed",
"subprocess"
] |
Split a list with consecutive block items but discontinued blocks into sub-lists | 37,595,567 | <p>Suppose I have a list like this:</p>
<p><code>mylist = [2,3,4,7,8,9,0,1,2,3,10,11,12,20,19,18,17,17,18,19,20,21]</code></p>
<p>I want to split it into sub-lists like this:</p>
<pre><code>sublist_1 = [2,3,4]
sublist_2 = [7,8,9]
sublist_3 = [0,1,2,3]
sublist_4 = [10,11,12]
sublist_5 = [20,19,18,17]
sublist_5 = [17,... | 0 | 2016-06-02T15:04:59Z | 37,595,788 | <p>Code -</p>
<pre><code>mylist = [2, 3, 4, 7, 8, 9, 0, 1, 2, 3, 10, 11, 12, 20, 19, 18, 17, 17, 18, 19,
20, 21]
result = []
temp_list = [mylist[0]]
for i in range(1, len(mylist)):
if abs(mylist[i] - mylist[i - 1]) != 1:
result.append(temp_list)
temp_list = [mylist[i]]
else:
... | 1 | 2016-06-02T15:14:16Z | [
"python",
"algorithm",
"sorting"
] |
Split a list with consecutive block items but discontinued blocks into sub-lists | 37,595,567 | <p>Suppose I have a list like this:</p>
<p><code>mylist = [2,3,4,7,8,9,0,1,2,3,10,11,12,20,19,18,17,17,18,19,20,21]</code></p>
<p>I want to split it into sub-lists like this:</p>
<pre><code>sublist_1 = [2,3,4]
sublist_2 = [7,8,9]
sublist_3 = [0,1,2,3]
sublist_4 = [10,11,12]
sublist_5 = [20,19,18,17]
sublist_5 = [17,... | 0 | 2016-06-02T15:04:59Z | 37,596,238 | <p>This would do;</p>
<pre><code>mylist = [2,3,4,7,8,9,0,1,2,3,10,11,12,20,19,18,17,17,18,19,20,21]
index =0
for i in range(0, len(mylist)):
#print (mylist[i+1])
if (i+1 >= len(mylist)):
print (mylist[index:i+1])
break
if not( (mylist[i+1] - mylist[i] == 1) or (mylist[i+1] - mylist[i] ... | 0 | 2016-06-02T15:33:48Z | [
"python",
"algorithm",
"sorting"
] |
Split a list with consecutive block items but discontinued blocks into sub-lists | 37,595,567 | <p>Suppose I have a list like this:</p>
<p><code>mylist = [2,3,4,7,8,9,0,1,2,3,10,11,12,20,19,18,17,17,18,19,20,21]</code></p>
<p>I want to split it into sub-lists like this:</p>
<pre><code>sublist_1 = [2,3,4]
sublist_2 = [7,8,9]
sublist_3 = [0,1,2,3]
sublist_4 = [10,11,12]
sublist_5 = [20,19,18,17]
sublist_5 = [17,... | 0 | 2016-06-02T15:04:59Z | 37,596,457 | <p>This is the <code>numpy</code> approach. I'm using <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ediff1d.html" rel="nofollow">ediff1d</a>,
<a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.intersect1d.html" rel="nofollow">intersect1d</a>, <a href="http://docs.scipy... | 0 | 2016-06-02T15:43:26Z | [
"python",
"algorithm",
"sorting"
] |
One-line way to iterate over a list of classes and examine a single attribute | 37,595,820 | <p>I'd like to iterate over a list of classes and see if a target string is found within a particular attribute of the class. Here's how I can do it with a for loop:</p>
<pre><code># sample class
class Test(object):
def __init__(self, x):
self.x = x
# make a quick list of classes
mylist = []
for i in "ab... | 0 | 2016-06-02T15:15:31Z | 37,595,849 | <p>It may be easily achieved by using <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map</code></a> builtin function.</p>
<p>Sample code:</p>
<pre><code>if "b" in map(lambda o: o.x, my_list):
print "found"
</code></pre>
| 1 | 2016-06-02T15:17:12Z | [
"python"
] |
One-line way to iterate over a list of classes and examine a single attribute | 37,595,820 | <p>I'd like to iterate over a list of classes and see if a target string is found within a particular attribute of the class. Here's how I can do it with a for loop:</p>
<pre><code># sample class
class Test(object):
def __init__(self, x):
self.x = x
# make a quick list of classes
mylist = []
for i in "ab... | 0 | 2016-06-02T15:15:31Z | 37,595,857 | <pre><code>any(i.x == 'b' for i in mylist)
</code></pre>
| 4 | 2016-06-02T15:17:29Z | [
"python"
] |
How to recover original values after a model predict in keras? | 37,595,891 | <p>This is a more conceptual question, but I have to confess I have been dealing with it for a while. </p>
<p>Suppose you want to train a neural network (NN), using for instance keras. As it is recommended you perform previous to the training a normalization or standardization of the data, so, for instance, with a sta... | 2 | 2016-06-02T15:19:01Z | 37,597,041 | <p>Depending on if you standarize your outputs or not :</p>
<p><strong>1. If not :</strong> then your output values are not standarized and you don't have to worry about it.</p>
<p><strong>2. If yes:</strong> then you keep your <strong>mean/sd</strong> and <em>unstadarize your output</em> simply by <code>(output * s... | 1 | 2016-06-02T16:12:25Z | [
"python",
"neural-network",
"keras"
] |
How to recover original values after a model predict in keras? | 37,595,891 | <p>This is a more conceptual question, but I have to confess I have been dealing with it for a while. </p>
<p>Suppose you want to train a neural network (NN), using for instance keras. As it is recommended you perform previous to the training a normalization or standardization of the data, so, for instance, with a sta... | 2 | 2016-06-02T15:19:01Z | 37,620,168 | <p>You standarized your input/output values with the following formula:</p>
<pre><code>X_s = (X - mean) / std
</code></pre>
<p>To destandarize, you must have the mean and std values for input and outputs. Save them somewhere and then use the following equation:</p>
<pre><code>X = X_s * std + mean
</code></pre>
<p>F... | 1 | 2016-06-03T17:19:24Z | [
"python",
"neural-network",
"keras"
] |
How to recover original values after a model predict in keras? | 37,595,891 | <p>This is a more conceptual question, but I have to confess I have been dealing with it for a while. </p>
<p>Suppose you want to train a neural network (NN), using for instance keras. As it is recommended you perform previous to the training a normalization or standardization of the data, so, for instance, with a sta... | 2 | 2016-06-02T15:19:01Z | 37,624,555 | <p>Ok, I think that I got what is your problem correctly so I will try to explain you how to deal with data normalization :</p>
<p><strong>1. Assumption about distribiution of inputs and outputs :</strong> usually in neural network training - what you assume is that your data (both input and output) comes from some pr... | 2 | 2016-06-03T22:54:12Z | [
"python",
"neural-network",
"keras"
] |
where is _md5 module code located in the system? | 37,595,955 | <p>I was reading <a href="https://hg.python.org/cpython/file/2.7/Lib/hashlib.py" rel="nofollow">hashlib.py</a> code and I saw it <code>import _md5</code> on line 78.</p>
<p>I found the <code>hashlib.py</code> file in <code>/usr/lib/python2.7</code> but I can't find the <code>_md5</code> module.</p>
<p>Where can I fin... | 0 | 2016-06-02T15:21:24Z | 37,598,311 | <p>In python conventionally files that begin with an underscore are meant to be "special", here it means the file has been compiled through C and therefore there's no python code to be found for the "md5 hash algorithm".</p>
<p>If you want to inspect the source code of that module, check it out from here: <a href="htt... | 0 | 2016-06-02T17:19:28Z | [
"python"
] |
Python Flask Search MySQL database turns up () | 37,595,976 | <p>I have been working on a Python Flask app for some time now. I have got it to connect to a mysql database and do a search but all it throws up is ().</p>
<p>I am not sure if it is not finding anything or there is an error, but the Database has one item in it.</p>
<p>This is the main .py file</p>
<pre><code>from f... | 0 | 2016-06-02T15:22:26Z | 37,597,692 | <p>You'll at least want to iterate through the cursor</p>
<pre><code><ol>
{% for row in rows %}
<li> row data: {{ row }}</li>
{% endfor %}
</ol>
</code></pre>
<p>Even so it's not going to be very presentable as in each iteration you'll be getting a tuple <code>(value_1, value_2... | 2 | 2016-06-02T16:47:50Z | [
"python",
"mysql",
"database",
"search",
"flask"
] |
Python Flask Search MySQL database turns up () | 37,595,976 | <p>I have been working on a Python Flask app for some time now. I have got it to connect to a mysql database and do a search but all it throws up is ().</p>
<p>I am not sure if it is not finding anything or there is an error, but the Database has one item in it.</p>
<p>This is the main .py file</p>
<pre><code>from f... | 0 | 2016-06-02T15:22:26Z | 37,602,224 | <p>So after a few more hours I finally did it. I am not 100% on what was wrong.</p>
<p>But my final code is</p>
<pre><code>@app.route('/hello/', methods=['POST'])
def hello():
error = ""
rows = None
user_input = None
data = None
try:
c, conn = connection()
if request.method == "POS... | 0 | 2016-06-02T21:14:24Z | [
"python",
"mysql",
"database",
"search",
"flask"
] |
Parsing a JSON file with BeautifulSoup | 37,596,010 | <p>Fairly new to coding so bear with me for any fundamental mistakes. Simplified, I have this:</p>
<pre><code>url = "https://www.youtube.com/browse_ajax?action_continuation=1&continuation=4qmFsgIuEiRWTFBMbFRwZUhIS2o1TFNpRVpKbXJxZGg0MHlqZjBmdG4xak4aBkNHVSUzRA%253D%253D"
lm_json = requests.get(url).json()
</code></... | 0 | 2016-06-02T15:23:45Z | 37,596,197 | <p>The HTML content is wrapped in a JSON. For your example, you can try:</p>
<pre><code>url = "https://www.youtube.com/browse_ajax?action_continuation=1&continuation=4qmFsgIuEiRWTFBMbFRwZUhIS2o1TFNpRVpKbXJxZGg0MHlqZjBmdG4xak4aBkNHVSUzRA%253D%253D"
lm_json = requests.get(url).json()
soup = BeautifulSoup(lm_json["co... | 1 | 2016-06-02T15:32:04Z | [
"python",
"html",
"json",
"beautifulsoup"
] |
Nose test suite - passing a command argument | 37,596,067 | <p>was trying to pass a command argument into my nose suits script: </p>
<pre><code>from test_cases.test_quick_search import QuickSearchTest
args = ['-s --tc=url:https://our_dev_environment.co']
def run_suite():
all_tests = TestLoader().loadTestsFromTestCase(QuickSearchTest)
suite = LazySuite(all_tests)
... | 0 | 2016-06-02T15:25:52Z | 37,597,567 | <p>Is <code>QuickSearchTest</code> a unittest.TestCase subclass? <a href="http://nose.readthedocs.io/en/latest/api/loader.html#nose.loader.TestLoader.loadTestsFromTestCase" rel="nofollow">loadTestsFromTestCase</a> will only find tests that are in a <code>TestCase</code> subclass. You could have a look at the contents o... | 1 | 2016-06-02T16:40:33Z | [
"python",
"nose"
] |
Mongoengine 0.10.6 _data attribute of Document instance | 37,596,085 | <p>I have some troubles with the <code>_data</code> attribute of a mongoengine <code>Document</code>instance after upgrading from version 0.10.0 to 0.10.6</p>
<p>I define a class inheriting from <code>Document</code></p>
<pre><code>from mongoengine import *
__all__ = ('User',)
connect('mydb')
class User(Document):... | 2 | 2016-06-02T15:26:52Z | 37,655,499 | <p>You could use <code>json.loads</code> to transform your document into the dictionary:</p>
<pre><code>import json
user = User.objects.first()
json.loads(user.to_json())
</code></pre>
<p>PS. You shouldn't rely on private properties in the first place</p>
| 0 | 2016-06-06T10:50:28Z | [
"python",
"python-2.7",
"mongoengine"
] |
Mongoengine 0.10.6 _data attribute of Document instance | 37,596,085 | <p>I have some troubles with the <code>_data</code> attribute of a mongoengine <code>Document</code>instance after upgrading from version 0.10.0 to 0.10.6</p>
<p>I define a class inheriting from <code>Document</code></p>
<pre><code>from mongoengine import *
__all__ = ('User',)
connect('mydb')
class User(Document):... | 2 | 2016-06-02T15:26:52Z | 39,955,134 | <p>The <code>Document._data</code> becomes <code>mongoengine.base.datastructures.SpecificStrictDict</code>, through its repr is as the way you posted, but you can still use it as a dict.
<code>
some_document._data['id']
</code>
will get you a ObjectId object.</p>
<p>If you want an pure dict, you could convert it back ... | 0 | 2016-10-10T09:23:59Z | [
"python",
"python-2.7",
"mongoengine"
] |
Importing py4j using Eclipse | 37,596,091 | <p>I've read the first part of the py4j.org introduction, then I skipped down to the Eclipse section. I installed the Eclipse plugins found here: <a href="http://eclipse.py4j.org/" rel="nofollow">http://eclipse.py4j.org/</a> and restarted Eclipse afterwards.</p>
<p>I have a class in the pre-existing Java project known... | 1 | 2016-06-02T15:26:58Z | 37,596,529 | <p>You need to have the py4j JAR(s) on the project's build path. Easiest route is probably:</p>
<ol>
<li>Create a <code>lib</code> folder in your Eclipse project (if it doesn't already exist).</li>
<li>Copy the <code>py4j0.x.jar</code> from the p4yj installation into that <code>lib</code> folder.</li>
<li>Right-click ... | 2 | 2016-06-02T15:46:29Z | [
"java",
"python",
"eclipse",
"py4j"
] |
Pyodbc cursor to loop through a dataframe and insert in sql | 37,596,120 | <p>Below are my SQL TABLE and DATAFRAME:</p>
<pre><code> TXN_KEY SEND_AGENT Pay_Agent
13273870 ANO080012 NULL
13274676 AUK359401 NULL
13274871 ACL000105 NULL
13275398 AED420319 NULL
13278566 ARA030210 NULL
13278955 AYM003098 NULL
13280334 AJ5020114 NULL
13280512 A11171047 NU... | 0 | 2016-06-02T15:28:06Z | 37,596,621 | <p>Below is the way to loop through the dataframe:</p>
<pre><code> for index,rows in df.iterrows():
cursor.execute("""update result SET Pay_Agent = ? WHERE SEND_AGENT = ?""",df['PAY_AGENT'][rownum],df['SEND_AGENT'][rownum])
rownum+=1
</code></pre>
<p>I am sure this will help someone else trying to achi... | -1 | 2016-06-02T15:51:15Z | [
"python",
"sql-server-2008",
"pandas",
"dataframe",
"pyodbc"
] |
Pyodbc cursor to loop through a dataframe and insert in sql | 37,596,120 | <p>Below are my SQL TABLE and DATAFRAME:</p>
<pre><code> TXN_KEY SEND_AGENT Pay_Agent
13273870 ANO080012 NULL
13274676 AUK359401 NULL
13274871 ACL000105 NULL
13275398 AED420319 NULL
13278566 ARA030210 NULL
13278955 AYM003098 NULL
13280334 AJ5020114 NULL
13280512 A11171047 NU... | 0 | 2016-06-02T15:28:06Z | 37,596,824 | <p>i would recommend to do it differently:</p>
<p>save your <code>df</code> as SQL Server table (let's say: <code>tmp_result</code>) </p>
<pre><code>df.to_sql('tmp_result', conn, if_exists='replace')
</code></pre>
<p>and then update your table as follows:</p>
<pre><code>update result
set result.Pay_Agent = tmp_r... | 1 | 2016-06-02T16:00:07Z | [
"python",
"sql-server-2008",
"pandas",
"dataframe",
"pyodbc"
] |
Python regular expression for different words & number | 37,596,161 | <p>How can I match any of these words: <code>'true', 'yes', 'Yes', 'on', 'On', '1', 1, True</code> ?</p>
<p>I've tried with <code>'^[1][{t,T}rue]|[]{y,Y}es]|[{o,O}n]|['1']^$'</code> but I can't achieve it.</p>
| -1 | 2016-06-02T15:30:08Z | 37,596,231 | <pre><code>def is_yes(x):
return str(x).lower() in ('1', 'true', 'yes', 'on')
for x in ['true', 'yes', 'Yes', 'on', 'On', '1', 1, True, False, None, 0, 'no', 'random']:
print(is_yes(x))
</code></pre>
<p>Output:</p>
<pre><code>True
True
True
True
True
True
True
True
False
False
False
False
False
</code></pre>... | 1 | 2016-06-02T15:33:29Z | [
"python",
"regex"
] |
Python regular expression for different words & number | 37,596,161 | <p>How can I match any of these words: <code>'true', 'yes', 'Yes', 'on', 'On', '1', 1, True</code> ?</p>
<p>I've tried with <code>'^[1][{t,T}rue]|[]{y,Y}es]|[{o,O}n]|['1']^$'</code> but I can't achieve it.</p>
| -1 | 2016-06-02T15:30:08Z | 37,596,308 | <p>You can try this regexp :</p>
<pre><code>>>> import re
>>> string = "'true', 'yes', 'Yes', 'on', 'On', '1', 1, True"
>>> re.findall("yes|Yes|true|True|on|On|1", string)
['true', 'yes', 'Yes', 'on', 'On', '1', '1', 'True']
</code></pre>
<p>Hope it'll be helpful.</p>
| 1 | 2016-06-02T15:36:44Z | [
"python",
"regex"
] |
Python regular expression for different words & number | 37,596,161 | <p>How can I match any of these words: <code>'true', 'yes', 'Yes', 'on', 'On', '1', 1, True</code> ?</p>
<p>I've tried with <code>'^[1][{t,T}rue]|[]{y,Y}es]|[{o,O}n]|['1']^$'</code> but I can't achieve it.</p>
| -1 | 2016-06-02T15:30:08Z | 37,596,970 | <p>You appear to be conflating two problems ... not everything in your list is a string, so you cannot check all of them against a regular expression.</p>
<p>But assuming you're converting all of those to strings:</p>
<pre><code>tests = map(str, ['true', 'yes', 'Yes', 'on', 'On', '1', 1, True])
</code></pre>
<p>Then... | 0 | 2016-06-02T16:07:53Z | [
"python",
"regex"
] |
Does anybody have computed a Poisson-loss on Lasso/Ridge Regression? | 37,596,186 | <p>I am new with scikit learn, and I am looking for some code to compute the Poisson loss. Instead of the mean square error :</p>
<pre><code>(y_hat - y)**2
</code></pre>
<p>I would like :</p>
<pre><code>2*(y*log(y/y_hat) - (y-y_hat))
</code></pre>
<p>Can I find a Github or some stuff that does it ? </p>
| -4 | 2016-06-02T15:31:32Z | 37,596,400 | <p>I think he's searching an equivalent of R-package "penalized" but in Python. A penalized regression where you can specify that your residual follows a poisson distribution</p>
| 0 | 2016-06-02T15:40:56Z | [
"python",
"scikit-learn",
"regression"
] |
How to find fibonancci series through recursion | 37,596,223 | <p>For finding fibonanci series , i write this code:</p>
<pre><code>def fib(n):
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>this is absolutely ok. But my question is if i call fib() by fib(5) then how many times does it compute the value fib(2) ? And how ?</p>... | 0 | 2016-06-02T15:33:03Z | 37,596,659 | <blockquote>
<p>If I call fib(5) then how many times does it compute the value fib(2)?</p>
</blockquote>
<p>Three. You can see for yourself if you add a print statement.</p>
<pre><code>def fib(n):
if n == 1 or n == 0:
return 1
else:
print('Computing fib(%i)...' % n)
return fib(n-1) +... | 0 | 2016-06-02T15:52:41Z | [
"python",
"python-2.7",
"python-3.x",
"recursion"
] |
How to find fibonancci series through recursion | 37,596,223 | <p>For finding fibonanci series , i write this code:</p>
<pre><code>def fib(n):
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>this is absolutely ok. But my question is if i call fib() by fib(5) then how many times does it compute the value fib(2) ? And how ?</p>... | 0 | 2016-06-02T15:33:03Z | 37,596,667 | <p><code>fib(2)</code> is calculated 3 times:</p>
<pre><code>>>> fib(5)
computing fib(5)
computing fib(4)
computing fib(3)
computing fib(2)
computing fib(2)
computing fib(3)
computing fib(2)
8
</code></pre>
<p>To avoid this duplicate work, you can take an iterative approach to computing the <em>n</em>th Fibo... | 0 | 2016-06-02T15:52:59Z | [
"python",
"python-2.7",
"python-3.x",
"recursion"
] |
How to find fibonancci series through recursion | 37,596,223 | <p>For finding fibonanci series , i write this code:</p>
<pre><code>def fib(n):
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>this is absolutely ok. But my question is if i call fib() by fib(5) then how many times does it compute the value fib(2) ? And how ?</p>... | 0 | 2016-06-02T15:33:03Z | 37,596,725 | <p>As polku mentioned in the comments, it's simple enough to see how many times your function is being called:</p>
<pre><code>def fib(n):
print('Called fib({})'.format(n))
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
>>> fib(5)
Called fib(5)
Called fib(4)
Called fi... | 1 | 2016-06-02T15:55:38Z | [
"python",
"python-2.7",
"python-3.x",
"recursion"
] |
How to find fibonancci series through recursion | 37,596,223 | <p>For finding fibonanci series , i write this code:</p>
<pre><code>def fib(n):
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>this is absolutely ok. But my question is if i call fib() by fib(5) then how many times does it compute the value fib(2) ? And how ?</p>... | 0 | 2016-06-02T15:33:03Z | 37,596,738 | <p>it is more than once to compute each number and python is very week on recursion.<br>
if you pass 5 to recursion code you have, it would calculate 5 times fib(1), 3 times fib(2), 2 times fib(3), and 1 time fib(4)/fib(5)</p>
<p>faster way to find fib</p>
<pre><code>def fib(n):
... a, b = 0, 1
... for _ in x... | 0 | 2016-06-02T15:56:33Z | [
"python",
"python-2.7",
"python-3.x",
"recursion"
] |
How to find fibonancci series through recursion | 37,596,223 | <p>For finding fibonanci series , i write this code:</p>
<pre><code>def fib(n):
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>this is absolutely ok. But my question is if i call fib() by fib(5) then how many times does it compute the value fib(2) ? And how ?</p>... | 0 | 2016-06-02T15:33:03Z | 37,596,790 | <p>Another way to avoid recalculation is to use dynamic programming. You can save the amounts you calculate once in a list, and every time you want to calculate something, look for it in the list first. If you have it there you won't call the function again.
You can also put a counter when accessing that list to find ... | 0 | 2016-06-02T15:58:36Z | [
"python",
"python-2.7",
"python-3.x",
"recursion"
] |
How to find fibonancci series through recursion | 37,596,223 | <p>For finding fibonanci series , i write this code:</p>
<pre><code>def fib(n):
if n ==1 or n ==0:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p>this is absolutely ok. But my question is if i call fib() by fib(5) then how many times does it compute the value fib(2) ? And how ?</p>... | 0 | 2016-06-02T15:33:03Z | 37,597,534 | <p>you can use mutable types like lists and dicts</p>
<pre><code>dict_counts = {}
def fib(n,d):
v = d.get(n,0)
d[n]=v+1
if n ==1 or n ==0:
return 1
else:
return fib(n-1,d) + fib(n-2,d)
fib(5, dict_counts)
print "all counts: ", dict_counts
print "count of f(2) = ", dict_counts.get(2, 0)
</... | 1 | 2016-06-02T16:38:49Z | [
"python",
"python-2.7",
"python-3.x",
"recursion"
] |
Purge script with mutltiple conditions | 37,596,479 | <p>I'm writing yet another python purge script. This is replacing a very old bash script with tons of find -delete which take up to 9h to purge our video backend.</p>
<p>I know there is tons of those either on stack or right in google but thing is i have a few more constraints which left me to write what i find poor/... | 1 | 2016-06-02T15:44:18Z | 37,600,174 | <p>Here's a possible approach:</p>
<pre><code>import os
import glob
import time
class Purge(object):
removable_extensions = ['ts', 'm3u8']
def __init__(self, basedir, channel_pattern, debits,
older_than_days, test_mode=False):
self.basedir = basedir
self.channel_pattern = c... | 1 | 2016-06-02T19:04:53Z | [
"python",
"file",
"purge"
] |
PyQt5 destroy a program properly | 37,596,489 | <p>I'm using <code>self.setWindowFlags(Qt.Tool)</code> to hide the application on task bar. However, I realized that even I press <code>x</code> on the right-top corner of the program, it's still running on the background ( I see it on task manager/processes). So that means the program doesn't close properly. Is this b... | 2 | 2016-06-02T15:44:44Z | 37,596,896 | <p>In Qt an application will continue to run until the main event loop receives the signal to exit. In most applications this is provided when the last (or only) <code>QMainWindow</code> is destroyed (see <code>QApp.setQuitOnLastWindowClosed()</code>).</p>
<p>Setting the <code>Qt.Tool</code> flag on a <code>QMainWindo... | 0 | 2016-06-02T16:03:56Z | [
"python",
"pyqt5"
] |
PyQt5 destroy a program properly | 37,596,489 | <p>I'm using <code>self.setWindowFlags(Qt.Tool)</code> to hide the application on task bar. However, I realized that even I press <code>x</code> on the right-top corner of the program, it's still running on the background ( I see it on task manager/processes). So that means the program doesn't close properly. Is this b... | 2 | 2016-06-02T15:44:44Z | 37,719,093 | <p>I found the solution, make your own quit button and connect the signal like below</p>
<pre><code>self.xbutton = QPushButton(self)
self.xbutton.setText("Quit")
self.xbutton.clicked.connect(self.close)
</code></pre>
<p>This destroy the app properly. Also instead of <code>Qt.Tool</code> use <code>self.setWindowFlags(... | 0 | 2016-06-09T07:10:00Z | [
"python",
"pyqt5"
] |
ValueError: invalid literal for int() with base 10: '0.5' | 37,596,501 | <p>I am writing a program that gathers a GTIN number from the user so that they can purchase an item. However, when trying to multiply the price by the quantity, I get the error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: 'x'
</code></pre>
<p>With x being the price in the CSV.</p>
<p>My Code ... | -1 | 2016-06-02T15:45:18Z | 37,596,699 | <p>The only time you use <code>int()</code> in your code is in line 36,</p>
<pre><code>price = int(row[2]) * quantity
</code></pre>
<p>That row comes from the file <code>ChocolateCSV.csv</code> which you do not provide, so we cannot be specific on the cause of your error. But obviously there is an <code>'x'</code> ch... | 1 | 2016-06-02T15:54:09Z | [
"python",
"csv",
"integer",
"value"
] |
ValueError: invalid literal for int() with base 10: '0.5' | 37,596,501 | <p>I am writing a program that gathers a GTIN number from the user so that they can purchase an item. However, when trying to multiply the price by the quantity, I get the error:</p>
<pre><code>ValueError: invalid literal for int() with base 10: 'x'
</code></pre>
<p>With x being the price in the CSV.</p>
<p>My Code ... | -1 | 2016-06-02T15:45:18Z | 37,596,820 | <p>"0.5" is not a value that can be turned into an integer, because integers can only represent whole numbers, not fractions.</p>
<pre><code>>>> s = "0.5"
>>> int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10... | 0 | 2016-06-02T15:59:55Z | [
"python",
"csv",
"integer",
"value"
] |
warning LNK4197: export 'PyInit_python_module_name' specified multiple times; using first specification | 37,596,516 | <p>I created some <code>Cython</code> files, and import them in a <code>Python</code> file using,</p>
<pre><code>import pyximport
pyximport.install()
import Cython_Mod1
import Cython_Mod2
</code></pre>
<p>When I run the <code>py</code> file, the <code>C</code> compiler (<code>VC++14</code>) generated the following e... | 1 | 2016-06-02T15:46:03Z | 37,604,005 | <p><a href="https://support.microsoft.com/en-us/kb/835326" rel="nofollow"><code>LNK4197</code></a> is a warning, as such it shouldn't affect the compilation of your <code>.c</code> files, <code>Cython</code> probably just generates code that exports that function multiple times (for good reasons, I'd assume).</p>
<p>S... | 2 | 2016-06-03T00:05:18Z | [
"python",
"python-3.x",
"visual-c++",
"cython"
] |
Pandas two rows have the same index, how to change them | 37,596,596 | <p>python newbie here.
I need to add a row from Provider 2 to Provider 1, do some calculations, save the results and drop that last row. Again, add another row from Provider 2 to Provider 1 and so forth. I'm building a loop for the purpose and I have the logic down for appending. My problem is that both provider 1 and... | 0 | 2016-06-02T15:49:41Z | 37,596,687 | <p>It looks like you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> with parameter <code>drop=True</code> after appending:</p>
<pre><code>Provider1 = Provider1.reset_index(drop=True)
Provider2 = Provider2.reset_index(dr... | 1 | 2016-06-02T15:53:40Z | [
"python",
"pandas",
"indexing",
"dataframe",
"append"
] |
errors when dowloading mnist dataset using keras | 37,596,597 | <p>I reinstall new ubuntu 14:04 on my machine then I started to receive this error while in old installation the program works perfect without any annoying errors. Any help please.
BTW I found question here <a href="http://stackoverflow.com/questions/34690906/cant-load-mnist-dataset-in-keras">cant load mnist dataset in... | 0 | 2016-06-02T15:49:41Z | 37,597,222 | <p>WOW I found the answer, just use</p>
<pre><code> sudo mkdir -p /etc/pki/tls
sudo ln -s /etc/ssl/certs /etc/pki/tls/certs
</code></pre>
<p>I found the answer in the following link by the clue of @ Dilettant thanks
<a href="https://support.enthought.com/hc/en-us/articles/204646264-Linux-non-RHEL-Python-code-fai... | 2 | 2016-06-02T16:22:00Z | [
"python",
"python-2.7",
"theano",
"keras",
"theano-cuda"
] |
Error in appending matrices in python | 37,596,630 | <p>I have a set of features and labels for 6 different weeks stored in variable <code>FEATURES_DATA</code> and <code>TARGET</code> respectively. </p>
<p>What I want to do is to train a decision tree on growing features and labels. So, training on first week of data and testing on second week, then, training on first t... | 0 | 2016-06-02T15:51:38Z | 37,598,418 | <p>Consider the first iteration from line 7, i=0.</p>
<p>Your next statement extracts features[:0], which is empty: []</p>
<p>Thus, there is no element [0] to complete the expression features[:i][0] ... this is where you get the subscript error.</p>
<p>Perhaps try a range of 1, 5 ?</p>
| 0 | 2016-06-02T17:24:44Z | [
"python",
"numpy",
"scipy",
"scikit-learn"
] |
Error in appending matrices in python | 37,596,630 | <p>I have a set of features and labels for 6 different weeks stored in variable <code>FEATURES_DATA</code> and <code>TARGET</code> respectively. </p>
<p>What I want to do is to train a decision tree on growing features and labels. So, training on first week of data and testing on second week, then, training on first t... | 0 | 2016-06-02T15:51:38Z | 37,598,731 | <p>I got the solution to my problem. Initializing an empty matrix will solve the problem.</p>
<pre><code>Xtrain=np.empty(shape=[0, 40])
for i in xrange(5):
Xtrain=np.concatenate((Xtrain,FEATURES_DATA[i][0]))
print Xtrain.shape
</code></pre>
<p>which gives the output</p>
<pre><code>(463511L, 40L)
(955280L, 40... | 1 | 2016-06-02T17:42:27Z | [
"python",
"numpy",
"scipy",
"scikit-learn"
] |
{{ request }} var Empty | 37,596,690 | <p>I am running Django 1.9.6
If I try to use <code>{{ request.path }}</code> in my templates the var/tag is empty</p>
<p>Here is my settings.py</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, '_templates'),
],
'APP_D... | 1 | 2016-06-02T15:53:42Z | 37,596,932 | <p>Use the <code>render</code> method instead, it automatically uses a <code>RequestContext</code> to render the template.</p>
<pre><code> return render(request, 'admin-users/events.html', {})
</code></pre>
<p>The <code>render_to_response</code> shortcut is not recommended any more.</p>
| 2 | 2016-06-02T16:06:04Z | [
"python",
"django",
"templates",
"request",
"render-to-response"
] |
Compare multiple year data on a single plot python | 37,596,714 | <p>I have two time series from different years stored in pandas dataframes. For example:</p>
<pre><code>data15 = pd.DataFrame(
[1,2,3,4,5,6,7,8,9,10,11,12],
index=pd.date_range(start='2015-01',end='2016-01',freq='M'),
columns=['2015']
)
data16 = pd.DataFrame(
[5,4,3,2,1],
index=pd.date_range(start=... | 3 | 2016-06-02T15:54:45Z | 37,609,811 | <p>One way to do this would be to overlay a transparent axes over the first, and plot the 2nd dataframe in that one, but then you'd need to update the x-limits of both axes at the same time (similar to <code>twinx</code>). However, I think that's far more work and has a few more downsides: you can't easily zoom interac... | 1 | 2016-06-03T08:43:04Z | [
"python",
"pandas",
"matplotlib",
"plot",
"time-series"
] |
Compare multiple year data on a single plot python | 37,596,714 | <p>I have two time series from different years stored in pandas dataframes. For example:</p>
<pre><code>data15 = pd.DataFrame(
[1,2,3,4,5,6,7,8,9,10,11,12],
index=pd.date_range(start='2015-01',end='2016-01',freq='M'),
columns=['2015']
)
data16 = pd.DataFrame(
[5,4,3,2,1],
index=pd.date_range(start=... | 3 | 2016-06-02T15:54:45Z | 37,610,071 | <p>I see two options.</p>
<p><strong>Option 1</strong>: add a <code>month</code> column to your dataframes</p>
<pre><code>data15['month'] = data15.index.to_series().dt.strftime('%b')
data16['month'] = data16.index.to_series().dt.strftime('%b')
ax = data16.plot(x='month', y='2016')
ax = data15.plot(x='month', y='2015... | 1 | 2016-06-03T08:56:21Z | [
"python",
"pandas",
"matplotlib",
"plot",
"time-series"
] |
How to edit data in a text file using python? | 37,596,743 | <p>I am fairly new to Python(and handling files) , I am using pandas and storing a dataframe in a text file.</p>
<p>My program requires constant changes in the dataframe , which in turn requires to be updated in the text.</p>
<p>Writing the whole dataframe over and over again ,would not be efficient(i guess,given tha... | 0 | 2016-06-02T15:56:49Z | 37,691,191 | <p>Besides the discussion of whether or not you should use the database, it seems what you need is a quick way to save/read again the DataFrame.</p>
<p>You can do it with pickle. âPicklingâ is the process whereby a Python object hierarchy is converted into a byte stream, and âunpicklingâ is the inverse operati... | 1 | 2016-06-07T23:46:19Z | [
"python",
"pandas",
"dataframe",
"text-files",
"binaryfiles"
] |
Trouble converting data into datetime from a csv. in pandas | 37,596,940 | <p>I am trying to import a csv file into a pandas dataframe, merge four of its columns into a 'datetime' column, and set the datetime column as data type Datetime64.</p>
<p>This is a small sample of my raw data:</p>
<pre><code>0,1,2,3,4,5,6,7,8,9,10
0, 3001, 1, 1, 0, 0, 5, 4, 1.00, 0, 0, 0
1, 3001, 1, 1, 100, 0, ... | 1 | 2016-06-02T16:06:23Z | 37,614,713 | <blockquote>
<p>Since pandas represents timestamps in nanosecond resolution, the timespan that can be represented using a 64-bit integer is limited to approximately 584 years</p>
</blockquote>
<pre><code>In [55]: pd.Timestamp.min
Out[55]: Timestamp('1677-09-22 00:12:43.145225')
In [56]: pd.Timestamp.max
Out[56]: Ti... | 0 | 2016-06-03T12:43:02Z | [
"python",
"datetime",
"pandas"
] |
'MemoryError' when calling scipy.odeint twice | 37,596,956 | <p>I use scipy.odeint to solve a list of ode equations. In my code the solver will be called several times(for each calling a 40500*10001 array will be generated), at the first time of its calling the solver works just well, but then the MemoryError arises at the second calling. Can anyone help me with this problem?</p... | 1 | 2016-06-02T16:07:20Z | 37,605,001 | <p><code>solve</code> is an array of 64 bit floating point values, so it takes 3 gigabytes of memory. In the second call, <em>another</em> 3 gigabytes is allocated by <code>odeint</code> for the solution. This will eventually be assigned to <code>solve</code>, and the previously allocated 3 gigabytes will be recovere... | 0 | 2016-06-03T02:26:33Z | [
"python",
"scipy",
"odeint"
] |
rethinkdb: get rows created no later than two weeks from now with unique id | 37,597,074 | <p>I have a table with some rows that look like this:</p>
<pre><code>{
"id": "12345"
"created_date": Fri May 27 2016 22:06:25 GMT+00:00 ,
} {
"id": "6789"
"created_date": Mon May 30 2016 07:48:35 GMT+00:00 ,
}
etc...
</code></pre>
<ol>
<li><p>I am attempting to first filter the rows down by only getting ones... | 0 | 2016-06-02T16:13:40Z | 37,599,256 | <p>Here are two options for achieving the desired results.</p>
<p><strong>Using a filter and group</strong></p>
<p>You could use the following query to perform this lookup (the code is using Javascript API and tested on a table through the Data Explorer):</p>
<pre><code>r.table('the_table')
.group('the_id') // group... | 1 | 2016-06-02T18:11:01Z | [
"python",
"rethinkdb",
"reql"
] |
CSV download not showing exact values | 37,597,114 | <p>Output for my python code is as follows:</p>
<pre><code>Anger 0.129971
Disgust 0.119636
Fear 0.216546
Joy 0.301672
Sadness 0.54521
Analytical 0.0
Confident 0.0
Tentative 0.0
Openness 0.817
Conscientiousness 0.571
Extraversion 0.157
Agreeableness 0.012
Emotional Range 0.401
</code></pre>
<p>where text denotes the v... | 0 | 2016-06-02T16:15:36Z | 37,609,512 | <p>You've assigned <code>cat</code> to every element of <code>data['document_tone']['tone_categories']</code> in the for-loop. When you then exit the for-loop, <code>cat</code> will refer to the <strong>last</strong> element in that list. That means that <code>cat</code> is a subset of the data you want.</p>
<p>Next, ... | 0 | 2016-06-03T08:26:15Z | [
"python",
"csv"
] |
Python self takes args, self(args) | 37,597,268 | <p>I'm not quite understand what this code mean:</p>
<pre><code># instantiate the input layer
x = Input(batch_shape=batch_input_shape,
dtype=input_dtype, name=name)
# this will build the current layer
# and create the node connecting the current layer
# to the input layer we just created.
self(x)
</code></pr... | 1 | 2016-06-02T16:24:40Z | 37,597,371 | <p><a href="https://docs.python.org/3/reference/datamodel.html#object.__call__" rel="nofollow"><code>__call__()</code></a> is one of the special methods in Python. It allows classes to emulate function types.</p>
<p><code>self</code> is probably --as by convention-- the first argument to your member function, i.e. the... | 0 | 2016-06-02T16:30:17Z | [
"python",
"self"
] |
Python lognorm.cdf vs. formula based implementation not matching | 37,597,348 | <p>Okay I am converting the <code>scipy.stats.lognorm.cdf</code> function over to a Cython function and using the formula here: <a href="http://www.cs.unitn.it/~taufer/SR/P-LN.pdf" rel="nofollow">http://www.cs.unitn.it/~taufer/SR/P-LN.pdf</a> as 1/2 + 1/2* erf((ln(x)-mu)/sigma*sqrt(2). The results don't match, despite ... | 0 | 2016-06-02T16:29:20Z | 37,658,999 | <p>The original post was edited to reflect the correct formula.</p>
<pre><code>def lognormcdf(x, mu, sigma):
return 0.5 + 0.5*erf((np.log(x)-np.log(mu))/(np.sqrt(2.0)*sigma))
</code></pre>
<p>Pass <code>np.log(mu)</code> in for <code>mu</code> and it works.</p>
| 1 | 2016-06-06T13:38:51Z | [
"python",
"numpy",
"scipy",
"distribution"
] |
matplotlib colourbar custom colour 1 value | 37,597,408 | <p>I want a normal <code>colorbar</code> but with some differences in color for a specific value.</p>
<p>My data covers range <code>(0,1)</code> but I want to pass some values that are outside that range (because they are errors), and I want to see them with another color outside the main range. </p>
<p>So what I wan... | 0 | 2016-06-02T16:32:00Z | 37,599,196 | <p>Yes it is but you don't need to rebuild a colormap for your specific case (which takes some effort). You can keep those values aside using the <code>vmin</code> and <code>vmax</code> to say what are the limits for your data and than specify the color for all values below or over those limits (using <code>set_under</... | 0 | 2016-06-02T18:08:04Z | [
"python",
"matplotlib",
"colorbar"
] |
iteration: select a random element from random list | 37,597,430 | <p>I have a tree (or "matrix") containing a bunch of line position points:</p>
<pre><code>tree = [[[x,y],[x,y],[x,y]],
[[x,y],[x,y],[x,y]],
[[x,y],[x,y],[x,y]]]
</code></pre>
<p>My goal is to connect even more lines from random points on each "branch" to other random points on separate branches. Once a line i... | 0 | 2016-06-02T16:33:06Z | 37,603,866 | <p>Got it working.</p>
<p>I made a new list:</p>
<pre><code>rand_splines = [_ for _ in xrange(len(splines))]
</code></pre>
<p>then shuffled with <code>random.shuffle(rand_splines)</code> before my first and second iterations and used <code>for spline in rand_splines:</code> to iterate the shuffled list.</p>
| 0 | 2016-06-02T23:46:52Z | [
"python",
"random",
"graphics"
] |
How do I load JSON into Couchbase Headless Server in Python? | 37,597,522 | <p>I am trying to create a Python script that can take a JSON object and insert it into a headless Couchbase server. I have been able to successfully connect to the server and insert some data. I'd like to be able to specify the path of a JSON object and upsert that. </p>
<p>So far I have this:</p>
<pre><code>from... | 0 | 2016-06-02T16:37:55Z | 37,664,207 | <p>Figured it out:</p>
<pre><code>with open('myData.json', 'r') as f:
data = json.load(f)
try:
result = cb.upsert('healthRec', {'record': data})
</code></pre>
<p>I am looking into using cbdocloader, but this was my first step getting this to work. Thanks!</p>
| 1 | 2016-06-06T18:16:07Z | [
"python",
"json",
"couchbase"
] |
How do I load JSON into Couchbase Headless Server in Python? | 37,597,522 | <p>I am trying to create a Python script that can take a JSON object and insert it into a headless Couchbase server. I have been able to successfully connect to the server and insert some data. I'd like to be able to specify the path of a JSON object and upsert that. </p>
<p>So far I have this:</p>
<pre><code>from... | 0 | 2016-06-02T16:37:55Z | 37,818,387 | <p>I know that you've found a solution that works for you in this instance but I thought I'd correct the issue that you experienced in your initial code snippet.</p>
<p><a href="https://docs.python.org/2/library/json.html#json.loads" rel="nofollow"><code>json.loads()</code></a> takes a string as an input and decodes t... | 0 | 2016-06-14T17:19:13Z | [
"python",
"json",
"couchbase"
] |
swig C++->Python 2.X conversion and method's arguments | 37,597,558 | <p>I am using the Eric IDE for Python. It is using autocompletion and it should be very useful.
But, we develop python scripts that use objects from a C++ library that we convert using Swig. Unfortunately, swig create a .py file that maps each C++ object's method replacing all arguments with an <code>*args</code> uniqu... | 0 | 2016-06-02T16:40:18Z | 37,598,239 | <p>According the the <a href="https://github.com/swig/swig/blob/master/CHANGES#L772-L778" rel="nofollow">Swig Changelog</a>, Python named parameters are available from version 3.0.3.</p>
<p>One thing that may make autocompletion more intelligent is to have docstrings generated. I am not familiar with Eric so I don't k... | 1 | 2016-06-02T17:15:36Z | [
"python",
"c++",
"swig"
] |
swig C++->Python 2.X conversion and method's arguments | 37,597,558 | <p>I am using the Eric IDE for Python. It is using autocompletion and it should be very useful.
But, we develop python scripts that use objects from a C++ library that we convert using Swig. Unfortunately, swig create a .py file that maps each C++ object's method replacing all arguments with an <code>*args</code> uniqu... | 0 | 2016-06-02T16:40:18Z | 37,599,888 | <p>I just tried your example (with just this one function), and for me SWIG does preserve the argument names (SWIG 3.0.9).</p>
<p>However, if your function is an overloaded function, then SWIG will always create a wrapper taking <code>*args</code> as you describe, and perform the dispatching in C++.</p>
<p>Using the ... | 0 | 2016-06-02T18:46:59Z | [
"python",
"c++",
"swig"
] |
Why does django need psycopg2 when I use sqlite? | 37,597,735 | <p>The title says all. It sounds like a very weird/impossible bug, but I've spent a couple of hours and still puzzled.</p>
<p>My setup:</p>
<ul>
<li>Python 3.4</li>
<li>Django 1.9.5</li>
<li>Apache 2.4.10</li>
</ul>
<p>Everything was running smoothly until I've decided to deploy site on production. Despite I'm using... | 3 | 2016-06-02T16:50:01Z | 37,613,531 | <p>It turned out that I wasn't using absolute path for settings.py and thus the fallbacks from ConfigParser were coming to play. Solved by:</p>
<p><code>conf.read(os.path.join(BASE_DIR, 'settings.ini'))</code></p>
<p>Thank you all for feedback!</p>
| 0 | 2016-06-03T11:44:50Z | [
"python",
"django",
"postgresql",
"sqlite",
"mod-wsgi"
] |
How to put files in a zip archive using Python zipfile | 37,597,741 | <p>I wrote a python(3.5) script that creates backup of my files in zip archive and it works well. I use windows and I installed zip command from GnuWin32 for this project. But I want to use Python's Zipfile library instead. How can I modify my code?</p>
<pre><code>import os
import time
import sys
source = 'C:\\Exampl... | 1 | 2016-06-02T16:50:15Z | 37,598,199 | <p>This might be a good start:</p>
<pre><code>#!/usr/bin/python
import zipfile, os
def zipdir(path, fname="test.zip"):
zipf = zipfile.ZipFile(fname, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(path):
for file in files:
zipf.write(os.path.join(root, file))
zipf.close()
<... | 1 | 2016-06-02T17:13:33Z | [
"python",
"python-3.x",
"zipfile"
] |
How to put files in a zip archive using Python zipfile | 37,597,741 | <p>I wrote a python(3.5) script that creates backup of my files in zip archive and it works well. I use windows and I installed zip command from GnuWin32 for this project. But I want to use Python's Zipfile library instead. How can I modify my code?</p>
<pre><code>import os
import time
import sys
source = 'C:\\Exampl... | 1 | 2016-06-02T16:50:15Z | 37,598,222 | <p>Change <code>zip_command = "zip -r {0} {1}".format(target,''.join(source))</code>
to the python zip file. Something like <code>zip_command = "zip.py -r {0} {1}".format(target,''.join(source))</code></p>
| 0 | 2016-06-02T17:14:35Z | [
"python",
"python-3.x",
"zipfile"
] |
Python Pandas - something like ISIN but "contains" vs "exact" match | 37,597,836 | <p>I am using Python Pandas to work with two dataframes. The first dataframe contains records from a <strong>customer database</strong> (First Name, Last Name, Email, etc). The second dataframe contains a list of <strong>domain names</strong>, e.g. gmail.com, hotmail.com, etc.</p>
<p>I am trying to <em>exclude records... | 2 | 2016-06-02T16:54:53Z | 37,598,440 | <p>try this:</p>
<pre><code>customer[~customer.Email.str.endswith(invalid_emails)]
</code></pre>
<p>or</p>
<pre><code>customer[~customer.Email.str.replace(r'^[^@]*\@', '').isin(blacklist.Domain)]
In [399]: filtered_list
Out[399]:
Email First Name
0 bob@example.com Bob
1 jim@example.com ... | 3 | 2016-06-02T17:26:30Z | [
"python",
"pandas",
"dataframe"
] |
Python Pandas - something like ISIN but "contains" vs "exact" match | 37,597,836 | <p>I am using Python Pandas to work with two dataframes. The first dataframe contains records from a <strong>customer database</strong> (First Name, Last Name, Email, etc). The second dataframe contains a list of <strong>domain names</strong>, e.g. gmail.com, hotmail.com, etc.</p>
<p>I am trying to <em>exclude records... | 2 | 2016-06-02T16:54:53Z | 37,598,457 | <p>Code -</p>
<pre><code>import pandas as pd
customer = pd.DataFrame({'Email': [
"bob@example.com",
"jim@example.com",
"joe@gmail.com"], 'First Name': [
"Bob",
"Jim",
"Joe"]})
blacklist = pd.DataFrame({'Domain': ["gmail.com", "outlook.com"]})
invalid_emails = tuple(blacklist['Domain'])
... | 1 | 2016-06-02T17:27:16Z | [
"python",
"pandas",
"dataframe"
] |
Creating file in python indicating if integer in in another list | 37,597,920 | <p>I have a list of integers, say <code>[2, 4, 9]</code>, then I need to create a csv file like this:</p>
<pre><code>1,0
2,1
3,0
4,1
5,0
6,0
7,0
8,0
9,1
</code></pre>
<p>Basically, for each integer, I need to check if the integer is in the list, if it is I write <code>1</code>, otherwise <code>0</code>.</p>
<p>I cou... | 1 | 2016-06-02T16:58:58Z | 37,598,178 | <p>A linear time solution would be to simply check if the current number is literally "in" a list of integers.</p>
<p><em>example:</em></p>
<pre><code>sample_list = [2,4,9]
for i in range(5):
if (i in sample_list):
print("%d,1"%i)
else:
print("%d,0"%i)
</code></pre>
<p><em>Output:</em></p>
<... | 1 | 2016-06-02T17:12:39Z | [
"python",
"numpy"
] |
Creating file in python indicating if integer in in another list | 37,597,920 | <p>I have a list of integers, say <code>[2, 4, 9]</code>, then I need to create a csv file like this:</p>
<pre><code>1,0
2,1
3,0
4,1
5,0
6,0
7,0
8,0
9,1
</code></pre>
<p>Basically, for each integer, I need to check if the integer is in the list, if it is I write <code>1</code>, otherwise <code>0</code>.</p>
<p>I cou... | 1 | 2016-06-02T16:58:58Z | 37,598,182 | <p>Use <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a> to create your data and use the module <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> to write to a csv file.</p>
<pre><code>s = set([2, 4, 9])
lists = [(i, 1)... | 2 | 2016-06-02T17:12:53Z | [
"python",
"numpy"
] |
Creating file in python indicating if integer in in another list | 37,597,920 | <p>I have a list of integers, say <code>[2, 4, 9]</code>, then I need to create a csv file like this:</p>
<pre><code>1,0
2,1
3,0
4,1
5,0
6,0
7,0
8,0
9,1
</code></pre>
<p>Basically, for each integer, I need to check if the integer is in the list, if it is I write <code>1</code>, otherwise <code>0</code>.</p>
<p>I cou... | 1 | 2016-06-02T16:58:58Z | 37,598,376 | <p>Assuming the list is sorted, you can use a generator function, which might be quite efficient.</p>
<pre><code>def bitstream(sorted_list_of_integers):
index = 0
for number in sorted_list_of_integers:
while number > index:
yield (index, 0)
index += 1
yield (index, ... | 1 | 2016-06-02T17:23:07Z | [
"python",
"numpy"
] |
Python 2 : AttributeError: 'list' object has no attribute 'split' | 37,597,984 | <p>this is my program of LSA, in this fonction i want to tokenize all my text and then transform it to stem. i'm trying to integrate them program of stemming and then i get this: for word in titles.split(" "):
AttributeError: 'list' object has no attribute 'split'</p>
<p>this code lsa: </p>
<pre><code># -*- coding: u... | -1 | 2016-06-02T17:02:00Z | 37,598,082 | <p><code>titles</code> is already a list; do this instead:</p>
<pre><code>for sentence in titles:
for word in sentence.split(" "):
...
</code></pre>
| 2 | 2016-06-02T17:07:41Z | [
"python",
"arabic",
"stemming",
"lsa"
] |
Python 2 : AttributeError: 'list' object has no attribute 'split' | 37,597,984 | <p>this is my program of LSA, in this fonction i want to tokenize all my text and then transform it to stem. i'm trying to integrate them program of stemming and then i get this: for word in titles.split(" "):
AttributeError: 'list' object has no attribute 'split'</p>
<p>this code lsa: </p>
<pre><code># -*- coding: u... | -1 | 2016-06-02T17:02:00Z | 37,598,096 | <p>List objects don't have a <code>split</code> method like strings do. If you want to split every string that you have in a <code>titles</code> list, you could nest a loop and do something like this:</p>
<pre><code>def parse(self, doc):
for title in titles:
for word in title.split():
stem = a... | 1 | 2016-06-02T17:08:29Z | [
"python",
"arabic",
"stemming",
"lsa"
] |
Specify `next` url passed to login view by Django login_required decorator | 37,598,155 | <p>From <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.decorators.login_required" rel="nofollow">the Django documentation</a> I know that when you use the <code>@login_required</code> decorator on a view, if the user is not logged Django will:</p>
<blockquote>
<p>redirect to ... | 2 | 2016-06-02T17:11:26Z | 37,601,333 | <p>This limitation is only applicable to the <code>/admin/</code> section of Django. You could write your own login view that redirects to where ever you want (example at the bottom of this post).</p>
<p>The current <strong>admin</strong> functionality seems to be written around the idea that the admin should always g... | 2 | 2016-06-02T20:16:46Z | [
"python",
"django"
] |
Pandas error converting string to datetime | 37,598,212 | <p>I'm trying to convert a string dataframe column to dates in pandas. However, I'm getting this error. I'm guessing the time zone is looking for EST, not ET. Is there a way to fix this? </p>
<pre><code>ValueError: time data '07/15/2004 / 04:50PM ET' does not match format '%m/%d/%Y / %I:%M%p %Z' (match)
</code></pre>... | 0 | 2016-06-02T17:14:11Z | 37,598,630 | <p>It seems that there is a known issue, in which %Z does not match certain timezones (i.e. EST). You can read about it here in the <a href="http://bugs.python.org/issue22377" rel="nofollow">bug tracker</a>.</p>
| 0 | 2016-06-02T17:37:06Z | [
"python",
"pandas"
] |
Converting a dataframe in pandas to another one | 37,598,246 | <p>I have loaded a csv "Body Count dataset" from <a href="https://figshare.com/articles/On_screen_movie_kill_counts_for_hundreds_of_films/889719" rel="nofollow">https://figshare.com/articles/On_screen_movie_kill_counts_for_hundreds_of_films/889719</a> as a data frame to my jupyter notebook.<br>
My task is to do linear... | 0 | 2016-06-02T17:15:55Z | 37,599,333 | <p>Check out <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow">pandas.get_dummies</a></p>
<pre><code>df = pd.DataFrame({'genre': ['action', 'thriller', 'drama'], 'kills':[50,100,150]})
print(df)
dummies = pd.get_dummies(df['genre'])
df = pd.concat([df,dummies], axis... | 0 | 2016-06-02T18:16:14Z | [
"python",
"pandas",
"dataframe",
"logistic-regression"
] |
Converting a dataframe in pandas to another one | 37,598,246 | <p>I have loaded a csv "Body Count dataset" from <a href="https://figshare.com/articles/On_screen_movie_kill_counts_for_hundreds_of_films/889719" rel="nofollow">https://figshare.com/articles/On_screen_movie_kill_counts_for_hundreds_of_films/889719</a> as a data frame to my jupyter notebook.<br>
My task is to do linear... | 0 | 2016-06-02T17:15:55Z | 37,599,413 | <p>You can use </p>
<pre><code>genres = df.Genre.str.split('|', expand=True)
</code></pre>
<p>to create new columns for the various genre types. Then combine this with your data and use <code>pd.get_dummies()</code> with <code>.sum()</code>:</p>
<pre><code>df = pd.concat([df.drop('Genre', axis=1), genres], axis=1)
d... | 1 | 2016-06-02T18:20:17Z | [
"python",
"pandas",
"dataframe",
"logistic-regression"
] |
Selecting range limits of a scale in Python | 37,598,337 | <p>I want to apply a fee to an amount according with this scale:</p>
<pre><code>AMOUNT FEE
------- ---
0 24.04 â¬
6010.12 0.00450
30050.61 0.00150
60101.21 0.00100
150253.03 0.00050
601012.11 0.00030
</code></pre>
<p>From 0 to 6010.13⬠is a fix fee of 24.04â¬</p>
<p>My code: </p>
... | 0 | 2016-06-02T17:20:57Z | 37,598,481 | <p>You aren't handling that one case. You should just add another <code>if</code> statement outside the loop (similar to the <code>if ammount <= scale[1][0]</code> you used, because values in both of these ranges are not handled by the loop):</p>
<pre><code>if ammount >= scale[len(scale) - 1][0]:
fee = scale... | 1 | 2016-06-02T17:28:48Z | [
"python",
"list"
] |
Selecting range limits of a scale in Python | 37,598,337 | <p>I want to apply a fee to an amount according with this scale:</p>
<pre><code>AMOUNT FEE
------- ---
0 24.04 â¬
6010.12 0.00450
30050.61 0.00150
60101.21 0.00100
150253.03 0.00050
601012.11 0.00030
</code></pre>
<p>From 0 to 6010.13⬠is a fix fee of 24.04â¬</p>
<p>My code: </p>
... | 0 | 2016-06-02T17:20:57Z | 37,598,495 | <p>I think a better way would be to use a while loop to check if <code>amount</code> is lesser then <code>scale[i+1][0]</code> so that you may just use <code>scale[i][1]</code>. And also give an else to handle anything greater than <code>scale[len(scale)][0]</code>.</p>
| 1 | 2016-06-02T17:29:30Z | [
"python",
"list"
] |
Selecting range limits of a scale in Python | 37,598,337 | <p>I want to apply a fee to an amount according with this scale:</p>
<pre><code>AMOUNT FEE
------- ---
0 24.04 â¬
6010.12 0.00450
30050.61 0.00150
60101.21 0.00100
150253.03 0.00050
601012.11 0.00030
</code></pre>
<p>From 0 to 6010.13⬠is a fix fee of 24.04â¬</p>
<p>My code: </p>
... | 0 | 2016-06-02T17:20:57Z | 37,598,531 | <p>First of all, you should try to avoid naming different things the same. That makes harder to see what the problem is.</p>
<p>What happens is this: if the amount is below the second entry in the scale table, you return the first entry. If not, you look in the table and check if the amount is bigger than the current ... | 0 | 2016-06-02T17:30:59Z | [
"python",
"list"
] |
Python pandas read a csv from one column then seperate columns | 37,598,383 | <p>I have a csv that needs seperation based on number of issues, and im currently getting an error with my code</p>
<pre><code> dfcleancsv = pd.read_csv('InitialQuerydataOpen.csv', sep=",")
ValueError: Expected 1 fields in line 1609, saw 55
</code></pre>
<p>What I have</p>
<pre><code>Column1 Column2
1583 FIT-49... | 0 | 2016-06-02T17:23:32Z | 37,599,129 | <p>Here you go:</p>
<pre><code>with open('test.txt') as f:
data = {i:txt.strip().split(',') for i,txt in enumerate(f.readlines())}
df = pd.DataFrame.from_dict(data, orient='index')
print(df)
## -- End pasted text --
0 1 2 3 4 5 6
0 1583 FIT-491 ... | 1 | 2016-06-02T18:03:51Z | [
"python",
"csv",
"pandas"
] |
LLDB Python API call function in C code | 37,598,413 | <p>For example, while writing GDB Macros, I can give something like:</p>
<pre><code>list_iterate $arg0
</code></pre>
<p>If my list_iterate() function in the C code looks like </p>
<pre><code>list_iterate(list_node *)
</code></pre>
<p>In the LLDB Python API, how do I do the same thing, i.e call and execute a functio... | 0 | 2016-06-02T17:24:38Z | 37,600,075 | <p><code>SBFrame::EvaluateExpression</code> is the function you want. Something like:</p>
<pre><code>(lldb) script
>>> options = lldb.SBExpressionOptions()
>>> result = lldb.frame.EvaluateExpression('printf("Hello there.\\n");', options)
Hello there.
>>> print result
(int) $1 = 13
</code></... | 1 | 2016-06-02T18:59:51Z | [
"python",
"gdb",
"lldb"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,545 | <p>Try this -</p>
<pre><code>user_input = [10, 5, 3]
equation = '-'.join(map(str, user_input))
print(equation, '=', eval(equation))
</code></pre>
<p>Output -</p>
<pre><code>10-5-3 = 2
</code></pre>
| 1 | 2016-06-02T17:32:01Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,560 | <pre><code>l = [10,5,3]
s = reduce(lambda x, y: x - y, l)
</code></pre>
<p>s == 2</p>
| 1 | 2016-06-02T17:33:07Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,563 | <p>Replace the line <code>map(float, input.split('-'))</code> with the following code,</p>
<pre><code>import functools
import operator
l = map(float, input.split('-'))
r = functools.reduce(operator.sub, l) # 3
</code></pre>
| 1 | 2016-06-02T17:33:16Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,620 | <p>you need these two functions:</p>
<pre><code>from operator import sub
from functools import reduce
reduce(sub, map(float, input.split('-')))
</code></pre>
| 1 | 2016-06-02T17:36:14Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,641 | <p>try this</p>
<pre><code>l = [10,5,3]
if len(l) > 1:
ans = l[0] - sum(l[1:])
else:
ans = sum(l)
print(ans)
</code></pre>
<p>output: 2 </p>
| 1 | 2016-06-02T17:37:35Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,712 | <p>Other answers make use of standard functions, notably <code>functools.reduce</code>.</p>
<p>The following looks simpler to me, while it use only intention lists:</p>
<pre><code>head, *tail = [10, 5, 3]
r = sum(-x for x in tail, head)
print(r)
</code></pre>
| 0 | 2016-06-02T17:41:25Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
Subtract each value of a list Python | 37,598,414 | <p>I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far... | 0 | 2016-06-02T17:24:41Z | 37,598,780 | <p>It sounds like you could use a <strong>Sentinel</strong>. A sentinel basically allows you to keep track of an arbitrary condition in a loop. Addition works fine because your initial sum is 0 and you can just keep adding to increase that value. But with subtraction you need to initialize a sum variable with the first... | 0 | 2016-06-02T17:44:50Z | [
"python",
"python-2.7",
"calculator",
"subtraction"
] |
accessing all non zero entries of a csr_matrix | 37,598,419 | <p>I have a sparse matrix:</p>
<pre><code>from scipy.sparse import csr_matrix
M=csr_matrix((5,5))
M[2,3]=4
</code></pre>
<p>I would like to iterate all non-zero entries, something like:</p>
<pre><code>for x,y,v in M.non_zero_entries:
do_something()
</code></pre>
<p>I try to comprehend the values of <code>M.data<... | 1 | 2016-06-02T17:24:55Z | 37,598,835 | <p>You could use <code>M.tocoo()</code> which returns a "coordinate-format" version of the matrix, which has vectors <code>data</code>, <code>row</code> and <code>col</code> which you use in the "obvious" way.</p>
<p>Or you could do it by hand. Something like this (WARNING: tested on exactly one example, and I've give... | 4 | 2016-06-02T17:47:27Z | [
"python",
"scipy",
"sparse-matrix"
] |
Python Flask request.path loses its first path segment when deployed on Bluemix | 37,598,506 | <p>I have a Python Flask application that is deployed on Bluemix. When I run it locally, everything works as expected. However, when I make a request to the app on Bluemix, my request's path loses its first segment, which results in a <code>404</code>. </p>
<p>For instance, if I make a request to <code>/api/v1/items</... | 0 | 2016-06-02T17:29:48Z | 37,635,840 | <p>The issue ended up being that I was calling the API from a REST client (<a href="https://www.getpostman.com/" rel="nofollow">Postman</a>) and using an environment variable for my hostname. I had a forward slash in both the env var and the request URL, causing the final sent request URL to have a double slash after t... | 0 | 2016-06-04T22:59:54Z | [
"python",
"python-2.7",
"flask",
"ibm-bluemix",
"cloudfoundry"
] |
Is there an equivalent of Flask's `@app.errorhandler` in Django? | 37,598,538 | <p>I'm writing several views, and would like to validate the request bodies. The common case is that the body must be a JSON object with certain keys present. I wrote one view, and have this code:</p>
<pre><code>try:
body = json.loads(request.body)
except ValueError:
return InvalidInputResponse("Could not load... | 2 | 2016-06-02T17:31:29Z | 37,599,012 | <p>Django has custom exception handlers, too. They can be attached <a href="https://docs.djangoproject.com/en/1.9/topics/http/middleware/#process_exception" rel="nofollow">via middleware</a>.</p>
<pre><code>class InvalidInputMiddleware(object):
def process_exception(self, request, exception):
if isinstance... | 2 | 2016-06-02T17:58:03Z | [
"python",
"django",
"error-handling",
"flask"
] |
Python - List sub folder sizes in a specified folder | 37,598,555 | <p>I need to make room on a drive that has many files. I want to find which folders are taking up the most space in a specific location called C:\RS_Data. Once I determine which of the sufolders are taking up the most space I want to drill down into those subfolders and perform the same task. So Iw ould like to develop... | 1 | 2016-06-02T17:32:31Z | 37,598,673 | <p>There is a similar question at: <a href="http://stackoverflow.com/questions/1392413/calculating-a-directory-size-using-python">Calculating a directory size using Python?</a></p>
<pre><code>import os
def get_size(start_path = '.'):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
... | 0 | 2016-06-02T17:39:13Z | [
"python",
"operating-system"
] |
how to read a file from folder structure in s3 bucket using python | 37,598,562 | <p>I am new to python and trying to see how to access a file inside S3 bucket folder structure using python. Should i specify the bucket_key = "path/folder/file" to something like this? Please help</p>
<p>I am mainly trying to get a count on no.of rows from the csv file. But i am getting error reading the file.</p>
<... | -2 | 2016-06-02T17:33:12Z | 37,602,041 | <h2>High level access to S3 using safe operations</h2>
<p>Hi, let's define some fonctions to access and download a file from AWS S3.
First of all, you have to connect to Amazon.</p>
<h3>Connect to S3</h3>
<pre><code>import boto
from boto.s3.connection import S3Connection
def s3_conn(conf):
""" Connect to S3
:p... | -2 | 2016-06-02T21:01:26Z | [
"python",
"amazon-web-services",
"amazon-s3"
] |
pretty printing JSON with padding in python | 37,598,592 | <p>I'm trying to write a set of JSON key/values to a file with both pretty-print as well as padding like so:</p>
<pre><code>{
"k1DaySummary" : "1 day summary",
"k1HourSummary" : "1 hour summary",
"k1MonthSummary" : "1 month summary",
"k1WeekSummary" : "1 ... | 0 | 2016-06-02T17:34:24Z | 37,599,506 | <p>This version prints to stdout, which you can redirect into your new file:</p>
<pre><code>import json
w = 0
pairs = [] # holds the formatted data
for k,v in ki.iteritems():
k = json.dumps(k)
v = json.dumps(v) + ","
pairs.append((k, v))
w = max(w, len(k)) # find the widest key value, after ... | 0 | 2016-06-02T18:26:15Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.