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 |
|---|---|---|---|---|---|---|---|---|---|
PyInstaller Encryption --key | 39,559,677 | <p>I'm trying to understand why PyInstaller documentation states that the --key argument to encrypt Python source code can be easily extracted:</p>
<p><em>Additionally, Python bytecode can be obfuscated with AES256 by specifying an encryption key on PyInstallerâs command line. Please note that it is still very easy ... | 1 | 2016-09-18T16:00:29Z | 39,559,759 | <p>Pyinstaller optionally encrypts the python sources with a very strong method.</p>
<p>Of course without the key it is nearly impossible to extract the files.</p>
<p>BUT the sources still need to be accessed at run time or the program couldn't work (or someone would have to provide the password each time, like prote... | 1 | 2016-09-18T16:08:35Z | [
"python",
"pyinstaller"
] |
Error while installing BeautifulSoup | 39,559,796 | <p>My question here is two fold. I am trying to install BeautifulSoup, but facing the below error:</p>
<pre><code>Rahul-MacBook-Air:~ rahul$ sudo easy_install pip
Password:
Searching for pip
Best match: pip 8.1.2
Processing pip-8.1.2-py2.7.egg
pip 8.1.2 is already the active version in easy-install.pth
Installing pip ... | 0 | 2016-09-18T16:11:35Z | 39,559,937 | <p>You have trouble installing BeautifulSoup because the user you're running he commands under doesn't have enough permissions to access a system directory. Try running the command with <code>sudo</code>:</p>
<pre><code>sudo pip install beautifulsoup4
</code></pre>
<p>Next, you're saying that you've installed Pytho... | 1 | 2016-09-18T16:22:50Z | [
"python",
"python-2.7",
"python-3.x"
] |
Skip first row in pandas dataframe when creating list | 39,559,805 | <p>I am currently creating a data frame from a specific column in my csv file. I am then creating a list from the values in the data frame, but I would look to skip over the first element in the data frame and not include it in my list. How can I go about doing that?</p>
<p>Here's the code that i'm using which is func... | 0 | 2016-09-18T16:12:56Z | 39,559,825 | <p>I think you can use <code>indexing</code> <code>[1:]</code> - select all values excluding first:</p>
<pre><code>addresses = [x for x in addresses[1:] if str(x) != 'nan']
</code></pre>
<p>Or:</p>
<pre><code>addresses = df.loc[1:, 'addresses'].tolist()
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'a... | 2 | 2016-09-18T16:14:09Z | [
"python",
"pandas"
] |
Python program using class programs to simulate the roll of two dice | 39,559,810 | <p>My program is supposed to simulate to both simulate the role of a single dice and the role of two dices but I am having issues. Here is what my code looks like: </p>
<pre><code>import random
#Dice class simulates both a single and two dice being rolled
#sideup data attribute with 'one'
class Dice:
#sideup dat... | 1 | 2016-09-18T16:13:13Z | 39,559,900 | <p>You have two <strong>init</strong> methods. The second replaces the first, which negates your definition of sideup.</p>
<p>change to:</p>
<pre><code>def __init__(self):
self.sideup='one'
self.twosides='one and two'
</code></pre>
| 4 | 2016-09-18T16:20:03Z | [
"python",
"class",
"dice"
] |
Having issues with a program to input multiple numbers from the user, till the user types âDone". To compute their average and print the results | 39,559,901 | <p>So here is how the program is supposed to work. The user would input something like this and the output would give them the answer.
Input:
1
2
2
1
Done</p>
<p>Output:
1.5</p>
<p>So far I was able to come up with the input question and got it to loop until you put Done.</p>
<pre><code>nums = [] # Empty list.
whil... | 0 | 2016-09-18T16:20:06Z | 39,560,187 | <p>Break while loop when 'Done' is the input, else save the number as float. This throws an error if you try to enter 'finish'. Finally calculate and print the Average.</p>
<pre><code>nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done": # This has to be tested in... | 0 | 2016-09-18T16:46:06Z | [
"python",
"python-3.x"
] |
My own data to tensorflow MNIST pipeline gives ValueError: input elements number isn't divisible by 65536 | 39,559,953 | <p>I'm using my own data with <a href="http://stackoverflow.com/questions/tags/tensorflow"><code>tensorflow</code></a> <a href="http://stackoverflow.com/questions/tagged/mnist"><code>MNIST</code></a> example pipeline but getting:</p>
<blockquote>
<p>ValueError: input has 16384 elements, which isn't divisible by 6553... | 1 | 2016-09-18T16:24:12Z | 39,577,595 | <p>It's hard to tell without seeing more of your code exactly what's going wrong, but the summary is that TensorFlow thinks that the other dimensions of <code>input</code> result in a stride of 65536 elements, and so it's trying to infer the missing dimension by dividing the number of elements present by the known dime... | 0 | 2016-09-19T16:13:00Z | [
"python",
"ubuntu",
"tensorflow",
"mnist"
] |
Python numpy scientific notation limit decimals | 39,559,960 | <p>I'm trying to reduce the number of decimals that I'm getting after some calculations. The <code>print()</code> where my problem arises looks like this:</p>
<pre><code>print("Mean resistivity: {res} Ohm m".format(res=np.mean(resistivity)))
</code></pre>
<p>And it outputs this:</p>
<pre><code>Mean resistivity: 1.66... | 6 | 2016-09-18T16:25:24Z | 39,559,994 | <p>It's python3? If so this should work: <code>{res:.3E}</code></p>
<p>@edit
It should work also with python2 - <a href="https://docs.python.org/2.7/library/string.html#formatspec" rel="nofollow">spec</a></p>
| 6 | 2016-09-18T16:27:42Z | [
"python",
"numpy",
"string-formatting",
"scientific-notation"
] |
Splitting up a list into a 2D list using tabs and spaces | 39,560,040 | <p>I am trying to split up a python list into a 2D list starting with the following</p>
<pre><code>testList = ["Color Blue»Temperature Warm»Gender Male",
"Color Green»Temperature Warm»Gender Female"]
</code></pre>
<p>Where » is a tab character and the attributes (color, temp, gender) have a tab befor... | -1 | 2016-09-18T16:31:18Z | 39,560,080 | <p>If the attribute names and values are always single-worded, you can get every odd (indexing starts from 0) word in the string:</p>
<pre><code>>>> testList = ["Color Blue Temperature Warm Gender Male", "Color Green Temperature Warm Gender Female"]
>>> print([item.split()[1::2] for item in te... | 2 | 2016-09-18T16:36:14Z | [
"python",
"list",
"split",
"strip"
] |
Splitting up a list into a 2D list using tabs and spaces | 39,560,040 | <p>I am trying to split up a python list into a 2D list starting with the following</p>
<pre><code>testList = ["Color Blue»Temperature Warm»Gender Male",
"Color Green»Temperature Warm»Gender Female"]
</code></pre>
<p>Where » is a tab character and the attributes (color, temp, gender) have a tab befor... | -1 | 2016-09-18T16:31:18Z | 39,560,493 | <p>Here's (another) way to do it:</p>
<pre><code>testList = ["Color Blue Temperature Warm Gender Male",
"Color Green Temperature Warm Gender Female"]
newList = [[subitem.split()[-1] for subitem in item.split('\t')]
for item in testList]
print(newList) # ->... | 0 | 2016-09-18T17:17:25Z | [
"python",
"list",
"split",
"strip"
] |
Splitting up a list into a 2D list using tabs and spaces | 39,560,040 | <p>I am trying to split up a python list into a 2D list starting with the following</p>
<pre><code>testList = ["Color Blue»Temperature Warm»Gender Male",
"Color Green»Temperature Warm»Gender Female"]
</code></pre>
<p>Where » is a tab character and the attributes (color, temp, gender) have a tab befor... | -1 | 2016-09-18T16:31:18Z | 39,560,588 | <p>The solution relying on attribute names ("<em>Color</em>", "<em>Temperature</em>", "<em>Gender</em>") and the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">Alternative regular expression module</a>(to allow overlapping matches):</p>
<pre><code>import regex as re
testList = ["Color Blue Temperature Wa... | 0 | 2016-09-18T17:26:08Z | [
"python",
"list",
"split",
"strip"
] |
Filter out boolean as non-integer? | 39,560,045 | <p>I have always wondered about the following code snippet: </p>
<pre><code>import math
def func(n):
if not isinstance(n, int):
raise TypeError('input is not an integer')
return math.factorial(n)
print(func(True))
print(func(False))
</code></pre>
<p>I'm always surprised at the result because <code... | 2 | 2016-09-18T16:32:08Z | 39,560,070 | <p>Type <code>bool</code> is a <em>subtype</em> of <code>int</code> and <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance</code></a> can walk through inheritance to pass <code>True</code> as an <code>int</code> type. </p>
<p>Use the more stricter <code>type</code>:</... | 4 | 2016-09-18T16:35:14Z | [
"python",
"integer",
"boolean"
] |
Filter out boolean as non-integer? | 39,560,045 | <p>I have always wondered about the following code snippet: </p>
<pre><code>import math
def func(n):
if not isinstance(n, int):
raise TypeError('input is not an integer')
return math.factorial(n)
print(func(True))
print(func(False))
</code></pre>
<p>I'm always surprised at the result because <code... | 2 | 2016-09-18T16:32:08Z | 39,560,154 | <p>This piece of code seems to distinguish between boolean and integer parameters in functions. What am I missing?</p>
<pre><code>import math
def func(n):
if type(n) == type(True):
print "This is a boolean parameter"
else:
print "This is not a boolean parameter"
if not isinstance(n, int):
... | 0 | 2016-09-18T16:43:09Z | [
"python",
"integer",
"boolean"
] |
Cannot combine bar and line plot using pandas plot() function | 39,560,099 | <p>I am plotting one column of a pandas dataframe as line plot, using plot() :</p>
<pre><code>df.iloc[:,1].plot()
</code></pre>
<p>and get the desired result:</p>
<p><a href="http://i.stack.imgur.com/6FFdq.png" rel="nofollow"><img src="http://i.stack.imgur.com/6FFdq.png" alt="enter image description here"></a></p>
... | 3 | 2016-09-18T16:38:01Z | 39,560,343 | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
</code></pre>
<p>some data</p>
<pre><code>df = pd.DataFrame(np.random.randn(5,2))
print (df)
0 1
0 0.008177 -0.121644
1 0.643535 -0.070786
2 -0.104024 0.872997
3 -0.033835 0.067264
4 -0.576762 0.571293
</code></pr... | 3 | 2016-09-18T17:02:19Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Cannot combine bar and line plot using pandas plot() function | 39,560,099 | <p>I am plotting one column of a pandas dataframe as line plot, using plot() :</p>
<pre><code>df.iloc[:,1].plot()
</code></pre>
<p>and get the desired result:</p>
<p><a href="http://i.stack.imgur.com/6FFdq.png" rel="nofollow"><img src="http://i.stack.imgur.com/6FFdq.png" alt="enter image description here"></a></p>
... | 3 | 2016-09-18T16:38:01Z | 39,560,806 | <p>The problem of getting right xticks was solved <a href="http://stackoverflow.com/a/22623488/6845924">here</a>.</p>
<blockquote>
<p>However, if you <em>really</em> need bars or you <em>really</em> want everything on
the same twin x-axes, then you have to plot with matplotlib's API like
this:</p>
<pre><code>im... | 2 | 2016-09-18T17:48:28Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Comments not showing in post_detail view | 39,560,120 | <p>I am doing a project in django 1.9.9/python 3.5, for exercise reasons I have a blog app, an articles app and a comments app. Comments app has to be genericly related to blog and articles. My problem is that the templates are not showing my comments. Comments are being created and related to their post/article becaus... | 0 | 2016-09-18T16:39:36Z | 39,560,196 | <p>You've explicitly set the related name of comments on your post to <code>post_comments</code>. So you would have to access them like:</p>
<pre><code>{% for comment in post.post_comments.all %}
</code></pre>
<p>This is assuming <code>post</code> in your template refers to an instance of the <code>Entry</code> model... | 2 | 2016-09-18T16:47:31Z | [
"python",
"django",
"python-3.x",
"django-templates",
"django-views"
] |
python fmin_slsqp - error with constraints | 39,560,137 | <p>I am practicing with SciPy and I encountered an error when trying to use fmin_slsqp. I set up a problem in which I want to maximize an objective function, U, given a set of constraints.</p>
<p>I have two control variables, x[0,t] and x[1,t] and, as you can see, they are indexed by t (time periods). The objective fu... | 1 | 2016-09-18T16:41:47Z | 39,560,182 | <p>The array <code>x</code> passed to your objective and constraint functions will be a <em>one-dimensional</em> array (just like your <code>x_init</code> is). You can't index a one-dimensional array with two indices, so expressions such as <code>x[1,0]</code> and <code>x[0,t]</code> will generate an error.</p>
| 0 | 2016-09-18T16:45:36Z | [
"python",
"dynamic",
"scipy",
"economics"
] |
Calculating the sum of a series? | 39,560,167 | <p>This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:</p>
<pre><code>sum = 0
k = 1
while k <= 0.0001:
if k % 2 == 1:
sum = sum + 1.0/k
else:
sum = sum - 1.0/k
k = k + 1
print()
</code></pre>
<p>This is my assignment :</p>
<... | 2 | 2016-09-18T16:44:29Z | 39,560,260 | <p>You're almost there, all you need to do is to replace </p>
<pre><code>while k <= 0.0001:
</code></pre>
<p>with:</p>
<pre><code> while term <= 0.0001:
</code></pre>
<p>term is naturally 1/k</p>
| 2 | 2016-09-18T16:53:39Z | [
"python",
"python-3.x"
] |
Calculating the sum of a series? | 39,560,167 | <p>This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:</p>
<pre><code>sum = 0
k = 1
while k <= 0.0001:
if k % 2 == 1:
sum = sum + 1.0/k
else:
sum = sum - 1.0/k
k = k + 1
print()
</code></pre>
<p>This is my assignment :</p>
<... | 2 | 2016-09-18T16:44:29Z | 39,560,327 | <p>Actually, you could write this shorter:</p>
<pre><code>Answer = sum(1.0 / k if k % 2 else -1.0 / k for k in range(1, 10001))
</code></pre>
<hr>
<h3>What this code does:</h3>
<ul>
<li>the innermost part is a <a href="https://wiki.python.org/moin/Generators" rel="nofollow">generator</a> expression, which computes ... | 2 | 2016-09-18T17:00:42Z | [
"python",
"python-3.x"
] |
Calculating the sum of a series? | 39,560,167 | <p>This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:</p>
<pre><code>sum = 0
k = 1
while k <= 0.0001:
if k % 2 == 1:
sum = sum + 1.0/k
else:
sum = sum - 1.0/k
k = k + 1
print()
</code></pre>
<p>This is my assignment :</p>
<... | 2 | 2016-09-18T16:44:29Z | 39,562,065 | <p>To make the teacher happy, you must follow the details of the problem, as well as the spirit of the problem. The problem clearly states to print the sum, not all the partial sums. You will anger the teacher by submitting a solution that spews 10000 lines of crap not requested.</p>
<p>Some have suggested pre-calcula... | 0 | 2016-09-18T19:56:43Z | [
"python",
"python-3.x"
] |
Calculating the sum of a series? | 39,560,167 | <p>This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:</p>
<pre><code>sum = 0
k = 1
while k <= 0.0001:
if k % 2 == 1:
sum = sum + 1.0/k
else:
sum = sum - 1.0/k
k = k + 1
print()
</code></pre>
<p>This is my assignment :</p>
<... | 2 | 2016-09-18T16:44:29Z | 39,564,538 | <p>Here is the answer your teacher is looking for for full credit.<br>
until < .0001 means while >= 0.0001 This modifies your code the least, so makes it a correction of what you wrote</p>
<pre><code>sum = 0
k = 1
while 1.0/k >= 0.0001:
if k % 2 == 1:
sum = sum + 1.0/k
else:
sum = sum - ... | 0 | 2016-09-19T02:25:46Z | [
"python",
"python-3.x"
] |
Django: Redirect to same page after POST method using class based views | 39,560,175 | <p>I'm making a Django app that keeps track of tv show episodes. This is for a page on a certain Show instance. When a user clicks to add/subtract a season, I want the page to redirect them to the same detail view, right now I have it on the index that shows the list of all Show instances.</p>
<p><strong>show-detail.h... | 0 | 2016-09-18T16:45:11Z | 39,560,355 | <p>I am guessing you need to provide a kwarg to identify the show when you redirect, although I can't see the code for your <code>DetailView</code> I would assume the kwarg is called either <code>pk</code> or possibly <code>show</code> going from the convention you've used in <code>AddSeason</code> and <code>SubtractSe... | 1 | 2016-09-18T17:03:44Z | [
"python",
"django"
] |
Django: Redirect to same page after POST method using class based views | 39,560,175 | <p>I'm making a Django app that keeps track of tv show episodes. This is for a page on a certain Show instance. When a user clicks to add/subtract a season, I want the page to redirect them to the same detail view, right now I have it on the index that shows the list of all Show instances.</p>
<p><strong>show-detail.h... | 0 | 2016-09-18T16:45:11Z | 39,561,256 | <p>to redirect to the <strong>same page</strong> (e.g. an http GET) after a POST, I like...</p>
<pre><code>return HttpResponseRedirect("") # from django.http import HttpResponseRedirect
</code></pre>
<p>it also avoids hardcoding the <code>show:detail</code> route name, and is clearer to me intention wise (for me at... | 0 | 2016-09-18T18:36:20Z | [
"python",
"django"
] |
Extraction of ssn no., date, e-mail address from a file using Python | 39,560,181 | <p>1.<strong>I have a file named <code>rexp.txt</code> with the following content:</strong></p>
<pre><code>adf fdsf hh h fg h 1995-11-23
dasvsbh 2000-04-12 gnym,mnbv 2001-02-17
dascvfbsn
bjhmndgfh
xgfdjnfhm244-44-2255 fgfdsg gfjhkh
fsgfdh 455-44-6577 dkjgjfkld
sgf
dgfdhj
sdg 192.6.8.02 fdhdlk dfnfghr
fisdhfih dfhgh... | -2 | 2016-09-18T16:45:25Z | 39,562,352 | <ul>
<li>You are opening file, reading it completely, then splitting what is read into list using <code>splitlines()</code> and then iterating over that list. Too much long and complicated process. Also, file is not closed after it was read.</li>
<li>Instead of this, why not open file using <code>with</code> construct ... | 1 | 2016-09-18T20:26:27Z | [
"python",
"fileparsing"
] |
Django AttributeError: 'MyModel' object has no attribute 'username' | 39,560,237 | <p>I have a model, <code>MyModel</code> that is linked via <em>ForeignKey</em> to Django's <code>User</code> model. MyModel was initially linked using <code>models.OneToOneField</code> but I later changed it to <code>models.ForeignKey</code> and also deleted some fields.</p>
<p><strong>Initial Models.py:</strong></p>
... | 0 | 2016-09-18T16:51:30Z | 39,561,870 | <p>Your updated model doesn't have an attribute <code>username</code>, because the field name is <code>user</code>.</p>
| 0 | 2016-09-18T19:39:20Z | [
"python",
"django"
] |
How to Multiply the numbers within a string with another string of equal length and then add each product in Python | 39,560,312 | <p>I am trying to write a function that takes each element within two strings of equal length and multiply them by each other and then add each product to get a single answer.
vector1 = [1, 2, 3]
vector2 = [4, 5, 6]</p>
<p>For example the above would be (1*4) + (2*5) + (3 * 6) = 32</p>
<p>So far this is what... | 0 | 2016-09-18T16:59:06Z | 39,560,346 | <p><em>zip</em> and <em>sum</em>, you also need to cast to int presuming you have strings of digits:</p>
<pre><code>def func(s1, s2):
if len(s1) != len(s2):
raise ValueError("Strings must be the same length")
return sum(int(i) * int(j) for i,j in zip(s1, s2))
</code></pre>
<p>zip would still work with... | 2 | 2016-09-18T17:02:41Z | [
"python",
"python-3.x"
] |
How to Multiply the numbers within a string with another string of equal length and then add each product in Python | 39,560,312 | <p>I am trying to write a function that takes each element within two strings of equal length and multiply them by each other and then add each product to get a single answer.
vector1 = [1, 2, 3]
vector2 = [4, 5, 6]</p>
<p>For example the above would be (1*4) + (2*5) + (3 * 6) = 32</p>
<p>So far this is what... | 0 | 2016-09-18T16:59:06Z | 39,560,361 | <p>The corrected version of your code.</p>
<pre><code>vector1 = [1, 2, 3]
vector2 = [4, 5, 6]
ans = 0
if len(vector1) == 0 or len(vector2) == 0:
print("Invalid vectors")
elif len(vector1) != len(vector2):
print("Invalid vectors")
else:
for i in range(len(vector1)):
temp = vector1[i] * vector2[i]
... | -1 | 2016-09-18T17:04:05Z | [
"python",
"python-3.x"
] |
Python Exception Syntax Handling | 39,560,354 | <p>I have a syntax error and I do not know what it is for. Is it an indent.</p>
<pre><code>import numpy as np
def main():
try:
Date, Open, High, Low, Last, Change, Settle, Volume, OpenInterest = np.loadtxt('C:\Users\RPH\Desktop\copper.csv',
delimiter =',', unpack = True , dtype='str')
exce... | -4 | 2016-09-18T17:03:41Z | 39,800,956 | <p>I'm not entirely sure as to the problem in this code but I know in python 3.5.1 you use:</p>
<pre><code>except Exception as e:
</code></pre>
<p>and not</p>
<pre><code>except Exception, e:
</code></pre>
| 0 | 2016-09-30T22:27:52Z | [
"python",
"exception",
"text",
"export-to-csv"
] |
count a character(both uppercase and lowercase) in a string, using a for loop in python | 39,560,387 | <pre><code>def eCount (s):
"""Count the e's in a string, using for loop.
Params: s (string)
Returns: (int) #e in s, either lowercase or uppercase
"""
# INSERT YOUR CODE HERE, replacing 'pass'
</code></pre>
<p>The professor asks not to change anything above.
I'm trying to accomplish:</p>
<pre><c... | -4 | 2016-09-18T17:06:42Z | 39,560,506 | <p>you can try <code>count()</code> like:
<code>return s.lower().count('e')</code></p>
<p>In python 3:</p>
<pre><code>def eCount(s):
return s.lower().count('e')
s = "helloEeeeeE"
print(eCount(s))
</code></pre>
<p>Output:</p>
<pre><code>7
</code></pre>
<p>You can either lowercase the string or uppercase it's up... | 2 | 2016-09-18T17:18:55Z | [
"python",
"loops",
"count"
] |
count a character(both uppercase and lowercase) in a string, using a for loop in python | 39,560,387 | <pre><code>def eCount (s):
"""Count the e's in a string, using for loop.
Params: s (string)
Returns: (int) #e in s, either lowercase or uppercase
"""
# INSERT YOUR CODE HERE, replacing 'pass'
</code></pre>
<p>The professor asks not to change anything above.
I'm trying to accomplish:</p>
<pre><c... | -4 | 2016-09-18T17:06:42Z | 39,560,531 | <p>Using for loop:</p>
<pre><code>def eCount(s):
count = 0
for c in s:
if c in ('e', 'E'):
count += 1
return count
</code></pre>
| 1 | 2016-09-18T17:20:38Z | [
"python",
"loops",
"count"
] |
Win10: pip install gives error: Unable to find vcvarsall.bat when I want to install cx_Freeze | 39,560,415 | <p>On Windows 10 I tried to install cx_Freeze with Python 3.5.0 |Anaconda 2.4.0 (64-bit) using:</p>
<pre><code>pip install cx_Freeze
</code></pre>
<p>However, I got this error:</p>
<pre><code> error: Unable to find vcvarsall.bat
</code></pre>
<p>This is the error and some lines above and below the error:</p>
<pre>... | -1 | 2016-09-18T17:08:38Z | 39,619,852 | <p>The combination of Python 3.5 and Microsoft Visual Studio 2013 is probably not supported. The compiler requirements are stated in <a href="https://wiki.python.org/moin/WindowsCompilers#Which_Microsoft_Visual_C.2B-.2B-_compiler_to_use_with_a_specific_Python_version_.3F" rel="nofollow">WindowsCompilers page</a>: in th... | 0 | 2016-09-21T14:47:33Z | [
"python",
"python-3.x",
"batch-file",
"pip",
"cx-freeze"
] |
Print the current number of item in a cycle for x in y | 39,560,444 | <p>I have this script:</p>
<pre><code>accounts = open("accounts.txt").readlines()
y = [x.strip().split(":") for x in accounts]
for account in y:
print ("Trying with: %s:%s" % (account[0], account[1]))
</code></pre>
<p>the file accounts.txt is structred like this:</p>
<pre><code>[email protected]:test1
email2@em... | -1 | 2016-09-18T17:11:45Z | 39,560,458 | <p>You can use <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a>, with the <code>start</code> argument as suggested by @JonClements:</p>
<pre><code>for i, account in enumerate(y, start=1):
print ("Trying with: %s:%s @%d" % (account[0], account[1], i))
... | 1 | 2016-09-18T17:12:59Z | [
"python",
"list",
"python-3.x",
"for-loop"
] |
Print the current number of item in a cycle for x in y | 39,560,444 | <p>I have this script:</p>
<pre><code>accounts = open("accounts.txt").readlines()
y = [x.strip().split(":") for x in accounts]
for account in y:
print ("Trying with: %s:%s" % (account[0], account[1]))
</code></pre>
<p>the file accounts.txt is structred like this:</p>
<pre><code>[email protected]:test1
email2@em... | -1 | 2016-09-18T17:11:45Z | 39,560,465 | <p>You're looking for <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p>
<pre><code>for position, account in enumerate(y):
print ("Trying with: %s:%s @%d" % (account[0], account[1], position))
</code></pre>
| 0 | 2016-09-18T17:13:39Z | [
"python",
"list",
"python-3.x",
"for-loop"
] |
Python - calculating the range(highest - lowest) in different group | 39,560,578 | <p>I have grouped my data. Now, what I am trying to do is to select the highest from the 'high' column and select the lowest from the 'low' column in each week, then use the highest to minus the lowest to get the range. But the code is always wrong. Somebody has an idea for me?</p>
<p>Here a part of my DataFrame:</p>... | 1 | 2016-09-18T17:24:44Z | 39,560,656 | <p>Is that what you want?</p>
<pre><code>In [67]: df
Out[67]:
Open High Low Close Volume Adj Close Week
Date
2015-09-14 116.580002 116.889999 114.860001 115.309998 58363400 112.896168 2015-09-18
2015-09-15 115.930000 116.529999 114.419998 116.279999 43341200... | 0 | 2016-09-18T17:34:05Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Working with the output of groupby and groupby.size() | 39,560,598 | <p>I have a pandas dataframe containing a row for each object manipulated by participants during a user study. Each participant participates in the study 3 times, one in each of 3 conditions (<code>a</code>,<code>b</code>,<code>c</code>), working with around 300-700 objects in each condition.</p>
<p>When I report the ... | 1 | 2016-09-18T17:28:07Z | 39,560,616 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and then output is <code>DataFrame</code>:</p>
<pre><code>tmp = df.groupby([FIELD_PARTICIPANT, FIELD_CONDITION]).size().reset_index(name='count')
</code></pr... | 0 | 2016-09-18T17:29:49Z | [
"python",
"pandas",
"group-by",
"scipy",
"condition"
] |
Proper way to use nested modules | 39,560,623 | <p>I've split a program into three scripts. One of them, 'classes.py', is a module defining all the classes I need. Another one is a sort of setup module, call it 'setup.py', which instantiates a lot of objects from 'classes.py' (it's just a bunch of variable assignments with a few for loops, no functions or classes). ... | 0 | 2016-09-18T17:30:34Z | 39,560,658 | <p>Import in each file. Consider <a href="http://stackoverflow.com/questions/3106089/python-import-scope">this SO post</a>. From the answer by Mr Fooz there,</p>
<blockquote>
<p>Each module has its own namespace. So for boo.py to see something from an external module, boo.py must import it itself.</p>
<p>It is ... | 0 | 2016-09-18T17:34:06Z | [
"python",
"python-3.x"
] |
Transforming declarative tests into pytest asserts | 39,560,637 | <p>I have a long script that is full of lines like this</p>
<pre><code>[UBInt8.parse, b"\x01", 0x01, None],
[UBInt8.build, 0x01, b"\x01", None],
</code></pre>
<p>I need to turn them through regular expressions into</p>
<pre><code>assert UBInt8.parse(b"\x01") == 0x01
assert UBInt8.build(0x01) == b"\x01"
</code></pre>... | 1 | 2016-09-18T17:31:46Z | 39,561,246 | <p>Here is the manual parsing that I came up with. No regex.</p>
<pre><code>#!/usr/bin/python3
import re, os, sys
def processfile(fname):
print(fname+'... ')
with open(fname, 'rt') as f:
txt = f.readlines()
with open(fname+"-trans", 'wt') as f:
for line in txt:
items = list(ma... | 1 | 2016-09-18T18:35:30Z | [
"python",
"regex",
"py.test"
] |
Strange results of evaluating in statement for list and set by means of timeit module | 39,560,670 | <p>Trying to evaluate performance of <code>in</code> statement for both: <code>set</code> and <code>list</code>. I know that I can do it with module <code>time</code>, but I want to try <code>timeit</code> module.
So my code is next:</p>
<pre><code>from timeit import Timer
def func_to_test(val, s):
return val i... | 0 | 2016-09-18T17:34:58Z | 39,560,747 | <p>Your setup statement imports <code>func_to_test</code>, but it doesn't do anything else. Therefore, the actual timing tests are timing not only the time it takes for a membership test, but also the time it takes to create a list (for the list test) or a list <em>and</em> a set (for the set test). Create the iterable... | 2 | 2016-09-18T17:41:44Z | [
"python",
"python-3.x",
"timeit"
] |
Write a function that input a positive integer n and return the number of n-digit positive integers that divisible by 17 | 39,560,861 | <p>I am working on Sage. Write a function that input a positive integer n and return the number of n-digit positive integers that divisible by 17. Be sure to account for the case where n=1. Test your program with inputs n=1,2,5.</p>
<p>What I understand that, for example, if I input n=1, it means that I need to check ... | 1 | 2016-09-18T17:54:33Z | 39,561,216 | <p>How about using number theory to simplify the problem, and use</p>
<pre><code>def positive(n):
return 10**n // 17 + 1
</code></pre>
<p>I believe Sage uses the caret rather than the double-asterisk for exponentiation, so you may instead use</p>
<pre><code>10^n // 17 + 1
</code></pre>
<p>The plus-one includes ... | 4 | 2016-09-18T18:31:56Z | [
"python",
"sage"
] |
Changing integer values from an if statement not working? (Python) | 39,560,879 | <p>Python newb here. I'm looking to write an if statement that changes an integer value based upon an input and then loops the code. Unfortunately, I have two problems:</p>
<ol>
<li>When the brightness printers after accepting an input, the value
that prints is 100 regardless of the input (-10, +10, set to 0, etc)</... | 0 | 2016-09-18T17:56:41Z | 39,560,992 | <pre><code>var = 1
brightness = 100
while var == 1 : # This constructs an infinite loop
print 'Brightness is ', brightness
test1 = raw_input('up, down, on or off? ')
if test1 == 'up':
brightness = brightness + 10
print brightness
elif test1 == 'down':
brightness = brightness - 10
print brightness
e... | 1 | 2016-09-18T18:09:07Z | [
"python",
"python-2.7"
] |
Changing integer values from an if statement not working? (Python) | 39,560,879 | <p>Python newb here. I'm looking to write an if statement that changes an integer value based upon an input and then loops the code. Unfortunately, I have two problems:</p>
<ol>
<li>When the brightness printers after accepting an input, the value
that prints is 100 regardless of the input (-10, +10, set to 0, etc)</... | 0 | 2016-09-18T17:56:41Z | 39,561,006 | <p>Andrew L. and Kalpesh Dusane answered this, thank you!!!</p>
<p>I needed to exchange my if for elif (else if).</p>
<pre><code># -*- coding: utf-8 -*-
var = 1
brightness = 100
while var == 1 : # This constructs an infinite loop
print 'Brightness is ', brightness
test1 = raw_input('up, down, on or off? ')
... | 0 | 2016-09-18T18:10:14Z | [
"python",
"python-2.7"
] |
calling a class function python | 39,560,887 | <pre><code>class merchandise:
def __init__(self, item, quantity, cost):
self.__item = item
self.__quantity = quantity
self.__cost = cost
def set_item(self, item):
self.__item = item
def set_quantity(self, quantity):
self.__quantity = quantity
def set_cost(self, co... | -1 | 2016-09-18T17:57:13Z | 39,561,283 | <p>The error isn't that there's no <code>set_item</code>; the error is caused by the fact that you haven't initialized and as a result the required positional argument <code>self</code> isn't implicitly passed.</p>
<p>When invoking functions class instances, they become bound methods on that instance and the instance ... | 0 | 2016-09-18T18:39:07Z | [
"python",
"class",
"python-3.x",
"import"
] |
Imprecise results of logarithm and power functions in Python | 39,560,902 | <p>I am trying to complete the following exercise:
<a href="https://www.codewars.com/kata/whats-a-perfect-power-anyway/train/python" rel="nofollow">https://www.codewars.com/kata/whats-a-perfect-power-anyway/train/python</a></p>
<p>I tried multiple variations, but my code breaks down when big numbers are involved (I tr... | 0 | 2016-09-18T17:59:39Z | 39,561,633 | <p>(edit note: also added integer nth root bellow)</p>
<p>you are in the right track with logarithm but you are doing the math wrong, also you are skipping number you should not and only testing all the even number or all the odd number without considering that a number can be even with a odd power or vice-versa</p>
... | 3 | 2016-09-18T19:14:41Z | [
"python"
] |
Practicing Inheritance in Python: Why AttributeError, despite my class and attribute seem setup correctly? | 39,560,935 | <p>I've got the following file/folder setup for my Python project (practicing inheritance) as follows:</p>
<pre><code>my_project/new_classes.py
my_project/human/Human.py
my_project/human/__init__.py (note, this is a blank file)
</code></pre>
<p>Although it appears that my <code>class Samurai(Human)</code> is setup co... | 1 | 2016-09-18T18:02:26Z | 39,561,065 | <blockquote>
<p>I resolved this by changing my import statement to, from human.Human import Human and was wondering why this worked while the other did not?</p>
</blockquote>
<p>This is because the first "Human" is your Python module (<code>Human.py</code>). The Human class is inside it, so that's why your import st... | 1 | 2016-09-18T18:16:45Z | [
"python",
"python-2.7",
"inheritance"
] |
Practicing Inheritance in Python: Why AttributeError, despite my class and attribute seem setup correctly? | 39,560,935 | <p>I've got the following file/folder setup for my Python project (practicing inheritance) as follows:</p>
<pre><code>my_project/new_classes.py
my_project/human/Human.py
my_project/human/__init__.py (note, this is a blank file)
</code></pre>
<p>Although it appears that my <code>class Samurai(Human)</code> is setup co... | 1 | 2016-09-18T18:02:26Z | 39,561,066 | <p>If you initialize the class in the same document, this code below runs. The reason you are receiving the error is because you are trying to change a variable that was never set during initialization.</p>
<pre><code>class Human(object):
def __init__(self):
self.health = 100
self.stealth = 0
... | 0 | 2016-09-18T18:16:50Z | [
"python",
"python-2.7",
"inheritance"
] |
Practicing Inheritance in Python: Why AttributeError, despite my class and attribute seem setup correctly? | 39,560,935 | <p>I've got the following file/folder setup for my Python project (practicing inheritance) as follows:</p>
<pre><code>my_project/new_classes.py
my_project/human/Human.py
my_project/human/__init__.py (note, this is a blank file)
</code></pre>
<p>Although it appears that my <code>class Samurai(Human)</code> is setup co... | 1 | 2016-09-18T18:02:26Z | 39,561,097 | <p>I found my solution, in my Samurai method, I had a spacing issue!</p>
<p>I reformatted my code with proper tabs and everything is working!</p>
<p>Correct code is as follows:</p>
<pre><code>class Samurai(Human):
def __init__(self):
super(Samurai, self).__init__() # use super to call the Human __init__... | 0 | 2016-09-18T18:20:17Z | [
"python",
"python-2.7",
"inheritance"
] |
Simple python class not working | 39,560,977 | <p>I'm having some trouble with this class in Python, why is it not working?</p>
<pre><code>class Quiz:
def __init__(self, answer, question):
self.answer = answer
self.question = question
def yesno(self):
if self.answer == self.question:
return str("Correct!")
else:
... | -2 | 2016-09-18T18:07:22Z | 39,561,011 | <p><code>question1.yesno()</code> would work. </p>
<p>The <code>yesno()</code> is a method which can be called by the object of the class. If it had been a static method, <code>Quiz.yesno()</code> would have worked.</p>
| 1 | 2016-09-18T18:10:45Z | [
"python"
] |
Simple python class not working | 39,560,977 | <p>I'm having some trouble with this class in Python, why is it not working?</p>
<pre><code>class Quiz:
def __init__(self, answer, question):
self.answer = answer
self.question = question
def yesno(self):
if self.answer == self.question:
return str("Correct!")
else:
... | -2 | 2016-09-18T18:07:22Z | 39,561,046 | <p>Yep, you need to instantiate the class. So, <code>question1.yesno()</code> is the right way to go when calling the method (you're calling a method on the instance of the object).</p>
<p>Also, you have a small indentation error that could cause some problems further down the road.</p>
<pre><code>def yesno(self):
... | 0 | 2016-09-18T18:14:35Z | [
"python"
] |
Python Class instance variables printing out as tuples instead of string | 39,560,990 | <p>I am creating the following <code>class</code> within python. But when I create an instance of the <code>class</code> and print out the <code>imdb_id</code> value. It prints it as a <em>tuple</em>. </p>
<p>What am I doing wrong? I would like it to simply print out the <em>string</em>.</p>
<pre><code>class Movie(ob... | -2 | 2016-09-18T18:09:01Z | 39,561,010 | <p>Why are you adding a comma at the end of most statements? That creates a tuple. Remove the trailing comma.</p>
<p>Really, why are you doing that?</p>
| 2 | 2016-09-18T18:10:43Z | [
"python",
"python-2.7"
] |
Docker Image Size a Concern - Best Practice to create a base python image with ubuntu | 39,561,044 | <p><strong>Need</strong>: I want to create a minimal size python docker image on top of ubuntu14.04. </p>
<p><strong>Problem</strong>: Ubuntu docker 14.04 image has 188MB size. On creating image with below Dockerfile, the image size becomes 486MB. Which is too much for such a small addition. I understand the less the ... | -3 | 2016-09-18T18:14:31Z | 39,562,280 | <p>There is no perfect answer here.</p>
<p>Using Ubuntu as a base image is a fine place to start, especially for legacy applications which expect to be deployed into an environment that needs to emulate a virtual machine. I would advise not letting this drive all your decision making, because containers are not virtua... | 0 | 2016-09-18T20:19:21Z | [
"python",
"image",
"ubuntu",
"docker"
] |
Selecting matrix elements from a column matrix | 39,561,056 | <p>I want to select a element from each row in a matrix according a column matrix.
The column matrix thus contains the indexes to pick. </p>
<pre><code>(Pdb) num_samples
15000
(Pdb) probs.shape
(15000, 26)
(Pdb) y.shape
(15000, 1)
(Pdb) (probs[np.arange(num_samples),y]).shape
(15000, 15000)
(Pdb) # this should (15000,... | 0 | 2016-09-18T18:16:00Z | 39,561,794 | <p>It may be that your <code>y</code> variable is a numpy matrix. Your code works fine when <code>y</code> is a list:</p>
<pre><code>>>> num_samples = 3
>>> data = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> y = [0, 1, 2]
>>> print((data[np.arange(num_samples), y]).shape)
(1, 3... | 0 | 2016-09-18T19:31:38Z | [
"python",
"numpy"
] |
Selecting matrix elements from a column matrix | 39,561,056 | <p>I want to select a element from each row in a matrix according a column matrix.
The column matrix thus contains the indexes to pick. </p>
<pre><code>(Pdb) num_samples
15000
(Pdb) probs.shape
(15000, 26)
(Pdb) y.shape
(15000, 1)
(Pdb) (probs[np.arange(num_samples),y]).shape
(15000, 15000)
(Pdb) # this should (15000,... | 0 | 2016-09-18T18:16:00Z | 39,562,031 | <p><a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.indexing.html#integer-array-indexing" rel="nofollow">integer array indexing</a> may be helpful.
Suppose you have this <code>numpy</code> array:</p>
<pre><code>myArray = numpy.array([[2, 3, 4],
[6, 7, 8],
[... | 1 | 2016-09-18T19:54:15Z | [
"python",
"numpy"
] |
How to click accept button after taking photo in selenium | 39,561,086 | <p>I have used</p>
<pre><code>self.driver.keyevent(27)
</code></pre>
<p>to capture an image in Python with <code>selenium</code>. However, the screen that I get is as shown below.</p>
<p>Basically I need to click the accept button (with red border) so that the image capture is complete. I know, that I can use in adb... | 0 | 2016-09-18T18:18:52Z | 39,561,252 | <p>In Python, it is uncommon to click on an element by its coordinates, can you please try looking for this accept buttons's Xpath or Css selector expression? </p>
<p>For Android testing, you may consider using <a href="http://selendroid.io/" rel="nofollow">this tool</a></p>
<p>Below is a Python code snippet about ho... | 0 | 2016-09-18T18:36:05Z | [
"android",
"python",
"selenium",
"adb"
] |
How to click accept button after taking photo in selenium | 39,561,086 | <p>I have used</p>
<pre><code>self.driver.keyevent(27)
</code></pre>
<p>to capture an image in Python with <code>selenium</code>. However, the screen that I get is as shown below.</p>
<p>Basically I need to click the accept button (with red border) so that the image capture is complete. I know, that I can use in adb... | 0 | 2016-09-18T18:18:52Z | 39,566,763 | <p>So i figured it out.</p>
<pre><code>import subprocess
subprocess.call(["adb", "shell", "input keyevent 27"]) # capture
subprocess.call(["adb", "shell", "input tap 1000 1500"]) # accept the captured image
</code></pre>
| 0 | 2016-09-19T06:36:20Z | [
"android",
"python",
"selenium",
"adb"
] |
manipulating a .dat file and plotting cumulative data | 39,561,090 | <p>I want to plot a quantity from a tedious-to-look-at <code>.dat</code> file, the #time column in the file extends from 0s to 70s, but I need to take a closer look at data (Nuclear Energy, in this case) from 25s to 35s.</p>
<p>I was wondering if there is a way I can manipulate the time column and corresponding other ... | 1 | 2016-09-18T18:19:46Z | 39,561,289 | <p><strong>UPDATE:</strong> plot cumulative nuclear energy:</p>
<pre><code>x = df.query('25 <= time <= 35').set_index('time')
x['cum_nucl_energy'] = x.Nuclear_Energy.cumsum()
x.cum_nucl_energy.plot(figsize=(12,10))
</code></pre>
<p><a href="http://i.stack.imgur.com/mhF6z.png" rel="nofollow"><img src="http://i.s... | 4 | 2016-09-18T18:39:47Z | [
"python",
"numpy",
"matplotlib",
"dataframe",
"data-manipulation"
] |
BS4 web scraping is not returning anything | 39,561,125 | <p>My code: </p>
<pre><code>res=requests.get('https://www.flickr.com/photos/')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
linkItem = soup.select('div.photo-list-photo-interaction
a[href^=/photos]')
print(linkItem)
</code></pre>
<p>is not returning any values.
After Inspecting element, ... | -2 | 2016-09-18T18:22:55Z | 39,563,107 | <p>If you look at the actual source you can see:</p>
<pre><code><div class="view photo-list-view requiredToShowOnServer" style="height: 4578px" data-view-signature="photo-list-view__UA_1__exploreId_2016-09-17__isMobile_false__isOwner_false__photoListConfig_1__photoListLayoutStyle_justified__requiredToShowOnClient_... | 1 | 2016-09-18T22:05:02Z | [
"python"
] |
Python, plotting Pandas' pivot_table from long data | 39,561,248 | <p>I have a xls file with data organized in long format. I have four columns: the variable name, the country name, the year and the value. </p>
<p>After importing the data in Python with pandas.read_excel, I want to plot the time series of one variable for different countries. To do so, I create a pivot table that tra... | 1 | 2016-09-18T18:35:40Z | 39,561,573 | <p>Using data_CO2PROD.plot() instead of plt.plot(data_CO2PROD) allowed me to plot the data. http://pandas.pydata.org/pandas-docs/stable/visualization.html.
Simple code:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data= pd.DataFrame(np.random.randn(3,4), columns=['VAR','COU','... | 1 | 2016-09-18T19:09:04Z | [
"python",
"pandas",
"matplotlib",
"panel-data"
] |
Python, plotting Pandas' pivot_table from long data | 39,561,248 | <p>I have a xls file with data organized in long format. I have four columns: the variable name, the country name, the year and the value. </p>
<p>After importing the data in Python with pandas.read_excel, I want to plot the time series of one variable for different countries. To do so, I create a pivot table that tra... | 1 | 2016-09-18T18:35:40Z | 39,561,827 | <p>I think you need add parameter <code>values</code> to <code>pivot_table</code>:</p>
<pre><code>data_CO2PROD = pd.pivot_table(data=data[(data['VAR']=='CC')],
index='COU',
columns='Year',
values='Value')
data_CO2PROD.plot()
... | 0 | 2016-09-18T19:34:33Z | [
"python",
"pandas",
"matplotlib",
"panel-data"
] |
Add one more StructField to schema | 39,561,272 | <p>My pyspark data frame has the following schema:</p>
<pre><code>schema = spark_df.printSchema()
root
|-- field_1: double (nullable = true)
|-- field_2: double (nullable = true)
|-- field_3 (nullable = true)
|-- field_4: double (nullable = true)
|-- field_5: double (nullable = true)
|-- field_6: double (nullab... | 0 | 2016-09-18T18:38:27Z | 39,561,527 | <p>You can copy existing fields and perpend:</p>
<pre><code>to_prepend = [StructField("field_0", StringType(), True)]
StructType(to_prepend + df.schema.fields)
</code></pre>
| 1 | 2016-09-18T19:04:39Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql",
"spark-dataframe"
] |
Generating list of lists with custom value limitations with Hypothesis | 39,561,310 | <p><strong>The Story:</strong></p>
<p>Currently, I have a function-under-test that expects a <em>list of lists of integers</em> with the following rules:</p>
<ol>
<li>number of sublists (let's call it <code>N</code>) can be from 1 to 50</li>
<li>number of values inside sublists is the same for all sublists (rectangul... | 7 | 2016-09-18T18:42:28Z | 39,593,883 | <p>There's a good general technique that is often useful when trying to solve tricky constraints like this: try to build something that looks a bit like what you want but doesn't satisfy all the constraints and then compose it with a function that modifies it (e.g. by throwing away the bad bits or patching up bits that... | 4 | 2016-09-20T12:16:15Z | [
"python",
"unit-testing",
"testing",
"property-based-testing",
"python-hypothesis"
] |
Generating list of lists with custom value limitations with Hypothesis | 39,561,310 | <p><strong>The Story:</strong></p>
<p>Currently, I have a function-under-test that expects a <em>list of lists of integers</em> with the following rules:</p>
<ol>
<li>number of sublists (let's call it <code>N</code>) can be from 1 to 50</li>
<li>number of values inside sublists is the same for all sublists (rectangul... | 7 | 2016-09-18T18:42:28Z | 39,606,087 | <p>You can also do this with <code>flatmap</code>, though it's a bit of a contortion.</p>
<pre><code>from hypothesis import strategies as st
from hypothesis import given, settings
number_of_lists = st.integers(min_value=1, max_value=50)
list_lengths = st.integers(min_value=0, max_value=5)
def build_strategy(number_a... | 3 | 2016-09-21T01:19:48Z | [
"python",
"unit-testing",
"testing",
"property-based-testing",
"python-hypothesis"
] |
UnicodeEncodeError with Twitch.tv IRC bot | 39,561,354 | <p>So I'm trying to program a simple Twitch.tv IRC bot. The bot reads incoming messages in the channel, and if the messages match certain patterns, the bot performs certain tasks. The problem that I'm getting is that if a user inputs certain unicode characters (i.e. if the user enters "¯_(ã)_/¯", the program will t... | 0 | 2016-09-18T18:46:07Z | 39,562,507 | <p>(Would comment with a link to an answer but I do not have enough reputation yet.)</p>
<p>So, I assume you are using windows? What happens is that the encoding your console uses cannot print the unicode characters, and that causes the crash. </p>
<p>So the problem is not so much in the code itself, just the tools u... | 1 | 2016-09-18T20:43:57Z | [
"python",
"unicode",
"bots",
"irc",
"twitch"
] |
pandas: Using color in a scatter plot | 39,561,364 | <p>I have a pandas dataframe:</p>
<pre><code>--------------------------------------
| field_0 | field_1 | field_2 |
--------------------------------------
| 0 | 1.5 | 2.9 |
--------------------------------------
| 1 | 1.3 | 2.6 |
--------------------------------------
|... | 0 | 2016-09-18T18:47:21Z | 39,561,457 | <p>you can do it this way:</p>
<pre><code>col = df.field_0.map({0:'b', 1:'r'})
df.plot.scatter(x='field_1', y='field_2', c=col)
</code></pre>
<p>Result:</p>
<p><a href="http://i.stack.imgur.com/TJItk.png" rel="nofollow"><img src="http://i.stack.imgur.com/TJItk.png" alt="enter image description here"></a></p>
| 2 | 2016-09-18T18:57:51Z | [
"python",
"pandas",
"dataframe"
] |
Scrapy SgmlLinkExtractor how to scrape li tags with changing id's | 39,561,437 | <p>How can I get an element at this specific location:</p>
<p><a href="http://i.stack.imgur.com/CkzTH.png" rel="nofollow">Check picture</a></p>
<p>The XPath is:</p>
<pre><code>//*[@id="id316"]/span[2]
</code></pre>
<p>I got this path from google chrome browser. I basically want to retreive the number at this specif... | 1 | 2016-09-18T18:56:05Z | 39,561,495 | <p>Use the corresponding label and get the <a href="https://developer.mozilla.org/en-US/docs/Web/XPath/Axes/following-sibling" rel="nofollow">following sibling</a> element containing the value:</p>
<pre><code>//span[. = 'Zimmer']/following-sibling::span/text()
</code></pre>
<p>And, note the bonus to the readability o... | 0 | 2016-09-18T19:01:35Z | [
"python",
"xpath",
"scrapy"
] |
Make python code run faster to reduce offset | 39,561,439 | <p>I am currently working on a project using python. My objective is to be able to make an active noise cancelling device using a Raspberry Pi.
For now, I've written this program, which starts recording the sound I'm trying to cancel, then uses a PID controler to calculate an inverted wave to the original one and play... | -1 | 2016-09-18T18:56:18Z | 39,581,128 | <p>My rough simulation indicates that you might gain some speed by not concatenating byte strings in your loop but instead collecting them in an array and joining them after your loop:</p>
<pre><code>byted_array = []
for element in np.fromstring(stream.read(chunk), 'Int16'):
...
byted_array.append(... | 0 | 2016-09-19T20:00:09Z | [
"python",
"performance",
"audio",
"pid"
] |
Add a character on a list if a situation presents | 39,561,445 | <p>I have this script:</p>
<pre><code>accounts = open("accounts.txt").readlines()
y = [x.strip().split(":") for x in accounts]
for position, account in enumerate(y):
try:
print ("Trying with: %s:%s @%d" % (account[0], account[1], position))
except:
pass
</code></pre>
<p>it opens a file (acco... | -1 | 2016-09-18T18:56:54Z | 39,561,584 | <p>You can use regex for splitting your lines:</p>
<pre><code>In [37]: s1 = '[email protected]:test2'
In [38]: s2 = '[email protected]'
In [42]: regex = re.compile(r'(.+\.com):?(.*)')
In [43]: regex.search(s1).groups()
Out[43]: ('[email protected]', 'test2')
In [44]: regex.search(s2).groups()
Out[44]: ('email3@em... | 1 | 2016-09-18T19:09:58Z | [
"python",
"list",
"python-3.x",
"for-loop",
"split"
] |
Add a character on a list if a situation presents | 39,561,445 | <p>I have this script:</p>
<pre><code>accounts = open("accounts.txt").readlines()
y = [x.strip().split(":") for x in accounts]
for position, account in enumerate(y):
try:
print ("Trying with: %s:%s @%d" % (account[0], account[1], position))
except:
pass
</code></pre>
<p>it opens a file (acco... | -1 | 2016-09-18T18:56:54Z | 39,561,620 | <p>You could add a <code>correct_accounts</code> function to your code.</p>
<pre><code>def correct_accounts(accounts):
corr = []
for x in accounts:
if ':' not in x:
# Assuming all mail addresses end with .com
pos = x.find ('.com') + 4
corr.append(x [:pos] + ':' + x [... | 0 | 2016-09-18T19:13:35Z | [
"python",
"list",
"python-3.x",
"for-loop",
"split"
] |
Bokeh widget callback to select all checkboxes | 39,561,553 | <p>I have run into a couple problems in trying to setup a Bokeh CheckboxGroup widget. The Checkbox group it self is large (50 states) and I would like to initialize the selection as all active. </p>
<p>Also (and more importantly) since this group is intended to be highly interactive, I would like to add buttons to "S... | 0 | 2016-09-18T19:06:26Z | 39,562,653 | <p>The basic function of the Bokeh server is to keep all Bokeh objects in sync on both the Python and JS sides. The <code>active</code> property of the <code>CheckboxGroup</code> specifies which boxed are checked, at all times, not just initialization. So to check all the boxes, you only need to set it appropriately in... | 1 | 2016-09-18T21:03:14Z | [
"python",
"bokeh"
] |
PSEUDO CODE & Python for finding the greatest, second greatest, and least number | 39,561,618 | <p>I am a student and for a task I have to write code for a task in both python and pseudocode. The task has been done but I don't really like ending lines of code which compares variables to find the greatest, 2nd greatest and least value. I am using if statements but was wondering if there was a better way to do this... | -2 | 2016-09-18T19:13:09Z | 39,562,050 | <p>Thats how you do it in pseudocode. Just watch out for the <code>==</code> and <code>=</code>. It's not the same, the first one is for equality testing and the other is assignment.</p>
<p>In python you might want to use <code>max(charity_value)</code> as well as <code>min(charity_value)</code></p>
| 0 | 2016-09-18T19:55:19Z | [
"python",
"pseudocode"
] |
Python CGI prints file content in same line of browser | 39,561,622 | <p>I have file "ip"</p>
<p>file IP content:</p>
<pre><code>1.1.1.1,0.0.0.0
2.2.2.2,0.0.0.0
</code></pre>
<p>When i try to print the file using python cgi</p>
<pre><code>f.open('ip'',r')
dat = f.read()
print (dat)
</code></pre>
<p>The browser displays it as below, by printing both 1st n 2nd line in one row.</p>
<... | 0 | 2016-09-18T19:13:52Z | 39,562,487 | <p>After having below, now o/p format is same as i/p. Thank You!</p>
<pre><code>f = open('ip', 'r')
line = f.read().replace('\n', "<br>")
f.close()
print line
</code></pre>
| 0 | 2016-09-18T20:42:11Z | [
"python",
"browser",
"cgi"
] |
Change turn in tic-tac-toe not working | 39,561,670 | <p>Just stuck in my code, was looking for others source, but there's other implementation, I must be blind or ... but it looks like functions are referring still to one variable, when in my beginning understanding if I call function which return 'change', and function return back to a place in code when it should not r... | 0 | 2016-09-18T19:17:53Z | 39,561,710 | <p>Youâre returning <code>turn</code> in <code>next_player()</code>:</p>
<pre><code>def next_player(turn):
if turn == 'X':
turn = 'O'
if turn == 'O':
turn = 'X'
return turn # <<< Here.
</code></pre>
<p>If you want to assign the new turn, try doing this:</p>
<pre><code>turn = ne... | 1 | 2016-09-18T19:21:15Z | [
"python",
"tic-tac-toe",
"turn"
] |
Change turn in tic-tac-toe not working | 39,561,670 | <p>Just stuck in my code, was looking for others source, but there's other implementation, I must be blind or ... but it looks like functions are referring still to one variable, when in my beginning understanding if I call function which return 'change', and function return back to a place in code when it should not r... | 0 | 2016-09-18T19:17:53Z | 39,561,714 | <pre><code>def next_player(turn):
if turn == 'X':
turn = 'O'
if turn == 'O':
turn = 'X'
return turn
</code></pre>
<p>Where is this variable return being saved? I don't believe it is updating your 'turn' variable, hence why you are just printing 'X' over and over.</p>
| 1 | 2016-09-18T19:21:28Z | [
"python",
"tic-tac-toe",
"turn"
] |
Change turn in tic-tac-toe not working | 39,561,670 | <p>Just stuck in my code, was looking for others source, but there's other implementation, I must be blind or ... but it looks like functions are referring still to one variable, when in my beginning understanding if I call function which return 'change', and function return back to a place in code when it should not r... | 0 | 2016-09-18T19:17:53Z | 39,561,796 | <ol>
<li>second "if" should be an "elif".
Look at your code, you are returning always "X" right now.</li>
<li>the variable "turn" is not a global variable. if you pass next_player "turn" as an argument, you are copying the value of the variable "turn" implicitly. The variable "turn" inside the function is not the same... | 0 | 2016-09-18T19:31:55Z | [
"python",
"tic-tac-toe",
"turn"
] |
Is it possible to have dynamically created pipelines in scrapy? | 39,561,735 | <p>I have a pipeline that posts data to a webhook. I'd like to reuse it for another spider. My pipeline is like this:</p>
<pre><code>class Poster(object):
def process_item(self, item, spider):
item_attrs = {
"url": item['url'], "price": item['price'],
"description": item['description'],... | 2 | 2016-09-18T19:23:48Z | 39,563,124 | <p>There are few ways of doing this, but the simpliest one would be to use <code>open_spider(self, spider)</code> in your pipeline.</p>
<p>Example of usecase:</p>
<p><code>scrapy crawl myspider -a pipeline_count=123</code></p>
<p>Then set up your pipeline to read this:</p>
<pre><code>class MyPipeline(object):
c... | 3 | 2016-09-18T22:07:08Z | [
"python",
"scrapy"
] |
Missing Values in Time Series Data Sklearn Random Forest | 39,561,787 | <p>I am trying to use scikit-learn to build a model, and I want to know what the best way is to deal with my particular type of missing features.</p>
<p>I have a base of users, who each need to complete a goal within a given time frame (for example 3 days). I have basic information about each user that is constant thr... | 0 | 2016-09-18T19:30:13Z | 39,562,200 | <p>If you are having a Time Series data, one way to deal it with efficiently is to break the time series into different parts. </p>
<p>Also, RandomForest have a very interesting property, the model can handle missing values. And for the probability estimates, the predict_proba() method of the RandomForestClassifier ca... | 0 | 2016-09-18T20:10:49Z | [
"python",
"scikit-learn"
] |
Sum list values where index 0 values match? | 39,561,806 | <p>I have a list of lists and I want to merge them to sum the inner <code>index[1]</code> values where the <code>index[0]</code> values match. My list looks like this:</p>
<pre><code>lists = [
['Gifts', [4]],
['Gifts', [4]],
['Politics', [3]],
['Supply', [4]],
['Supply', [4]],
['Prints', [1]],
['Prints', [1]],
['Print... | 0 | 2016-09-18T19:32:28Z | 39,561,833 | <p>Use a <code>defaultdict</code>:</p>
<pre><code>In [52]: from collections import defaultdict
In [53]: d = defaultdict(int)
In [54]: for name, (val,) in lists:
....: d[name] += val
....:
In [55]: d.items()
Out[55]: dict_items([('Politics', 9), ('Supply', 8), ('Prints', 3), ('Features', 5), ('Gifts',... | 1 | 2016-09-18T19:35:04Z | [
"python",
"list",
"python-3.x"
] |
Sum list values where index 0 values match? | 39,561,806 | <p>I have a list of lists and I want to merge them to sum the inner <code>index[1]</code> values where the <code>index[0]</code> values match. My list looks like this:</p>
<pre><code>lists = [
['Gifts', [4]],
['Gifts', [4]],
['Politics', [3]],
['Supply', [4]],
['Supply', [4]],
['Prints', [1]],
['Prints', [1]],
['Print... | 0 | 2016-09-18T19:32:28Z | 39,561,834 | <p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(int)</code></a> from <code>collections</code> module:</p>
<pre><code>>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for key, value in lis... | 3 | 2016-09-18T19:35:09Z | [
"python",
"list",
"python-3.x"
] |
Sum list values where index 0 values match? | 39,561,806 | <p>I have a list of lists and I want to merge them to sum the inner <code>index[1]</code> values where the <code>index[0]</code> values match. My list looks like this:</p>
<pre><code>lists = [
['Gifts', [4]],
['Gifts', [4]],
['Politics', [3]],
['Supply', [4]],
['Supply', [4]],
['Prints', [1]],
['Prints', [1]],
['Print... | 0 | 2016-09-18T19:32:28Z | 39,561,910 | <p>Or, use a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> from <a href="https://docs.python.org/3/library/collections.html" rel="nofollow"><code>collections</code></a>. You can initialize it either manually by incrementing the values for every ... | 3 | 2016-09-18T19:42:41Z | [
"python",
"list",
"python-3.x"
] |
Sprite sheet animations using pyganim, Why does my sprite not show? | 39,561,845 | <p>So if anyone has used pyganim to show sprite sheet animations and could tell me why my code is not showing the animation, I would thank you loads. ive tried moving coordinates and changing fill color. nothing is working and I'm not receiving any errors so I'm not sure what the problem is.</p>
<pre><code> import py... | 0 | 2016-09-18T19:36:30Z | 39,562,379 | <p>Sprite was bad, had to change the sheet, and my gameDisplay.fill(..) was outside of the while loop!</p>
| 1 | 2016-09-18T20:29:12Z | [
"python",
"python-3.x",
"pygame"
] |
Python function checking for common elements using function | 39,561,885 | <p>The goal is to take two lists see if any elements match and if they do add 1 to count every time. The first list is a list of 5 elements and the second is user input. It doesn't work , what am I doing wrong? It has to be done using a function please help.</p>
<pre><code>userask = input("Enter a few numbers to try w... | -3 | 2016-09-18T19:40:54Z | 39,561,942 | <p>Your code is incomplete here. But I think this change should help you.</p>
<p>Don't use <code>if list1 in list2:</code>, use <code>if r in list2:</code></p>
| -2 | 2016-09-18T19:45:48Z | [
"python"
] |
Python function checking for common elements using function | 39,561,885 | <p>The goal is to take two lists see if any elements match and if they do add 1 to count every time. The first list is a list of 5 elements and the second is user input. It doesn't work , what am I doing wrong? It has to be done using a function please help.</p>
<pre><code>userask = input("Enter a few numbers to try w... | -3 | 2016-09-18T19:40:54Z | 39,561,945 | <p>You first need to split the numbers by spaces (as you wish) and turn into a list:</p>
<pre><code>userask = input("Enter a few numbers to try win the lotto: ")
userlist = userask.split()
</code></pre>
<p>Then you can do it either using a set like so:</p>
<pre><code>result = len(set(list1) & set(userlist))... | 1 | 2016-09-18T19:46:08Z | [
"python"
] |
Python function checking for common elements using function | 39,561,885 | <p>The goal is to take two lists see if any elements match and if they do add 1 to count every time. The first list is a list of 5 elements and the second is user input. It doesn't work , what am I doing wrong? It has to be done using a function please help.</p>
<pre><code>userask = input("Enter a few numbers to try w... | -3 | 2016-09-18T19:40:54Z | 39,561,951 | <p>To implement your count function, you can use <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum</code></a> with a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow"><em>generator expression</em></a>. </p>
<pre><code>def count_correct(list1, list2):
# each T... | 0 | 2016-09-18T19:46:40Z | [
"python"
] |
Tensorflow: Passing CSV with 3D feature array | 39,561,893 | <p>My current text file that I intend to use for LSTM training in Tensorflow looks like this:</p>
<pre><code>> 0.2, 4.3, 1.2
> 1.1, 2.2, 3.1
> 3.5, 4.1, 1.1, 4300
>
> 1.2, 3.3, 1.2
> 1.5, 2.4, 3.1
> 3.5, 2.1, 1.1, 4400
>
> ...
</code></pre>
<p>There are 3 sequences 3 features vectors with... | 1 | 2016-09-18T19:41:34Z | 39,561,993 | <p><strong>UPDATE:</strong> addition to the previos answer:</p>
<pre><code>df.stack().to_csv('d:/temp/1D.csv', index=False)
</code></pre>
<p>1D.csv:</p>
<pre><code>0.2
4.3
1.2
4300.0
1.1
2.2
3.1
4300.0
3.5
4.1
1.1
4300.0
1.2
3.3
1.2
4400.0
1.5
2.4
3.1
4400.0
3.5
2.1
1.1
4400.0
</code></pre>
<p><strong>OLD answer:</... | 1 | 2016-09-18T19:50:03Z | [
"python",
"arrays",
"csv",
"numpy",
"tensorflow"
] |
Tensorflow: Passing CSV with 3D feature array | 39,561,893 | <p>My current text file that I intend to use for LSTM training in Tensorflow looks like this:</p>
<pre><code>> 0.2, 4.3, 1.2
> 1.1, 2.2, 3.1
> 3.5, 4.1, 1.1, 4300
>
> 1.2, 3.3, 1.2
> 1.5, 2.4, 3.1
> 3.5, 2.1, 1.1, 4400
>
> ...
</code></pre>
<p>There are 3 sequences 3 features vectors with... | 1 | 2016-09-18T19:41:34Z | 39,562,760 | <p>I'm a little confused as to whether you are more interested in the <code>numpy</code> array(s) structure, or the csv fomat.</p>
<p>The <code>np.savetxt</code> csv file writer can't readily produce text like:</p>
<pre><code>0.2, 4.3, 1.2
1.1, 2.2, 3.1
3.5, 4.1, 1.1, 4300
1.2, 3.3, 1.2
1.5, 2.4, 3.1
3.5, 2.1, 1.1, ... | 1 | 2016-09-18T21:16:26Z | [
"python",
"arrays",
"csv",
"numpy",
"tensorflow"
] |
Why can I not create / access futures in callables submitted to ProcessPoolExecutor? | 39,561,925 | <p>Why does this code work with threads but not processes?</p>
<pre><code>import concurrent.futures as f
import time
def wait_on_b():
time.sleep(2)
print(b.result())
return 5
def wait_5():
time.sleep(2)
return 6
THREADS = False
if THREADS:
executor = f.ThreadPoolExecutor()
else:
executor ... | 0 | 2016-09-18T19:44:27Z | 39,565,587 | <p>When using threads the <strong>memory is shared</strong> between all threads and that's why <em>wait_on_b</em> can access <em>b</em>.</p>
<p>Using processes, A <strong>new memory space</strong> is created for each process (copy of the old one <em>in fork mode</em>) so You will get a copy of <em>b</em> with a broken... | 0 | 2016-09-19T04:51:25Z | [
"python",
"python-3.x",
"python-multithreading",
"python-multiprocessing",
"concurrent.futures"
] |
Message transmission on TCP/IP server with ctrl+c int handling, Python3 | 39,561,956 | <p>i'm just started to learn Python, and i can't implement a good solution.</p>
<p>I want to write a client/server which allows you to send messages (like: texted, entered, texted, entered) on server until you press Ctrl+C interruption, and this int should close the socket both on server and client. </p>
<p>My very b... | 0 | 2016-09-18T19:47:07Z | 39,562,075 | <p>Add a <code>try...finally</code> to the bottom part like so:</p>
<pre><code>try:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
msg = data.decode()
print('Recieved data: ', msg)
conn.send(data)
finally:
conn.close()
</code></pre>
<p>Ctrl+C raises <code>Key... | 2 | 2016-09-18T19:57:51Z | [
"python",
"sockets"
] |
glib.GError: Error interpreting JPEG image file (Unsupported marker type 0x05) | 39,562,037 | <p>I am using <a href="http://www.pygtk.org/pygtk2reference/class-gdkpixbufloader.html">gtk.gdk.PixbufLoader</a> since several years.</p>
<p>Today, I try to load a jpg file from a new android device and get this exception:</p>
<pre><code>Traceback (most recent call last):
File "myscript.py", line 118, in next
l... | 8 | 2016-09-18T19:54:31Z | 39,747,570 | <p>I worked on your code and got to the conclusion that exactly after chunksize = 69632,i.e. at chunksize = 69633,This error is shown.
One more this I noticed is that this error is file related if I use any file other than this "20160627_163057-0.jpg" image,error does not occur.</p>
<p>So my conclusion is that this pa... | 4 | 2016-09-28T12:29:41Z | [
"python",
"jpeg",
"pygtk",
"glib"
] |
Rename several unnamed columns in a pandas dataframe | 39,562,069 | <p>I imported a csv as a dataframe from San Francisco Salaries database from Kaggle</p>
<pre><code>df=pd.read_csv('Salaries.csv')
</code></pre>
<p>I created a dataframe as an aggregate function from 'df'</p>
<pre><code>df2=df.groupby(['JobTitle','Year'])[['TotalPay']].median()
</code></pre>
<p>Problem 1: The first ... | 1 | 2016-09-18T19:57:18Z | 39,562,345 | <p>The problem isn't really that you need to rename the columns.<br>
What do the first few rows of the .csv file that you're importing look at, because you're not importing it properly. Pandas isn't recognising that <code>JobTitle</code> and <code>Year</code> are meant to be column headers. Pandas <code>read_csv()</cod... | 1 | 2016-09-18T20:25:58Z | [
"python",
"pandas",
"dataframe",
"aggregate-functions",
"series"
] |
Rename several unnamed columns in a pandas dataframe | 39,562,069 | <p>I imported a csv as a dataframe from San Francisco Salaries database from Kaggle</p>
<pre><code>df=pd.read_csv('Salaries.csv')
</code></pre>
<p>I created a dataframe as an aggregate function from 'df'</p>
<pre><code>df2=df.groupby(['JobTitle','Year'])[['TotalPay']].median()
</code></pre>
<p>Problem 1: The first ... | 1 | 2016-09-18T19:57:18Z | 39,563,811 | <p>Quoting answer by MaxU:</p>
<pre><code>df3 = df2.reset_index()
</code></pre>
<p>Thank you!</p>
| 0 | 2016-09-19T00:14:48Z | [
"python",
"pandas",
"dataframe",
"aggregate-functions",
"series"
] |
How to solve this `unorderable types` error | 39,562,078 | <p>I keep getting the following error and my program will not run. I need to make sure my program is modular and have the <code>if-then</code> statements to figure out what gross pay equation to use.</p>
<pre><code>BASE_HOURS = 40
OT_MULTIPLIER = 1.5
def main():
hours = input("Enter the number of hours worked: ")... | 0 | 2016-09-18T19:57:58Z | 39,562,175 | <p>You should convert the <code>hours</code> and <code>payRate</code> into integers or floats like so:</p>
<pre><code>hours = int(input("Enter the number of hours worked: "))
payRate = int(input("Enter the hourly pay rate: "))
</code></pre>
<p>or</p>
<pre><code>hours = float(input("Enter the number of hours worked: ... | 1 | 2016-09-18T20:08:54Z | [
"python",
"if-statement"
] |
Python: is 'int' a type or a function? | 39,562,080 | <p>I did this in Python 3.4:</p>
<pre><code>>>> type(int)
<class 'type'>
>>> int(0)
0
</code></pre>
<p>Now I am wondering what int actually is. Is it a type, or is it a function? Is it both? If it is both, is it also true that all types can be called like functions?</p>
| 2 | 2016-09-18T19:58:04Z | 39,562,101 | <p>It's both. In Python, the types have associated functions of the same name, that coerce their argument into objects of the named type, if it can be done. So, the type <code>int</code> <code><type 'int'></code>has a function <code>int</code> along with it.</p>
| 0 | 2016-09-18T20:00:21Z | [
"python"
] |
Python: is 'int' a type or a function? | 39,562,080 | <p>I did this in Python 3.4:</p>
<pre><code>>>> type(int)
<class 'type'>
>>> int(0)
0
</code></pre>
<p>Now I am wondering what int actually is. Is it a type, or is it a function? Is it both? If it is both, is it also true that all types can be called like functions?</p>
| 2 | 2016-09-18T19:58:04Z | 39,562,104 | <p><code>int</code> is a <strong><a href="https://docs.python.org/3.5/tutorial/classes.html">class</a></strong>. The type of a class is usually <code>type</code>.</p>
<p>And yes, <em>almost</em> all classes can be called like functions. You create what's called an <strong>instance</strong> which is an object that beha... | 8 | 2016-09-18T20:00:26Z | [
"python"
] |
Python: is 'int' a type or a function? | 39,562,080 | <p>I did this in Python 3.4:</p>
<pre><code>>>> type(int)
<class 'type'>
>>> int(0)
0
</code></pre>
<p>Now I am wondering what int actually is. Is it a type, or is it a function? Is it both? If it is both, is it also true that all types can be called like functions?</p>
| 2 | 2016-09-18T19:58:04Z | 39,562,404 | <p>What happens when an integer is defined in a Python script like this one?</p>
<pre><code>>>> a=1
>>> a
1
</code></pre>
<p>When you execute the first line, the function <code>PyInt_FromLong</code> is called and its logic is the following:</p>
<pre><code>if integer value in range -5,256:
retur... | 0 | 2016-09-18T20:32:01Z | [
"python"
] |
Python: is 'int' a type or a function? | 39,562,080 | <p>I did this in Python 3.4:</p>
<pre><code>>>> type(int)
<class 'type'>
>>> int(0)
0
</code></pre>
<p>Now I am wondering what int actually is. Is it a type, or is it a function? Is it both? If it is both, is it also true that all types can be called like functions?</p>
| 2 | 2016-09-18T19:58:04Z | 39,562,479 | <p><code>int</code> is a built-in class/type:</p>
<pre><code>>>> isinstance(int, type)
True
</code></pre>
<hr>
<p>When you invoke <code>int('123')</code>, Python finds out that <code>int</code> itself is nota function, but then attempts to call <code>int.__call__('123')</code>; this itself resolves to <cod... | 2 | 2016-09-18T20:41:26Z | [
"python"
] |
Error on using xarray open_mfdataset function | 39,562,113 | <p>I am trying to combine multiple netCDF files with the same dimensions, their dimensions are as follows:</p>
<pre><code>OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'net... | 1 | 2016-09-18T20:01:31Z | 39,562,794 | <p><a href="http://xarray.pydata.org/en/stable/generated/xarray.open_mfdataset.html" rel="nofollow">http://xarray.pydata.org/en/stable/generated/xarray.open_mfdataset.html</a></p>
<pre><code>xarray.open_mfdataset(paths, chunks=None, concat_dim=None, preprocess=None, engine=None, lock=None, **kwargs)
</code></pre>
<p>... | 1 | 2016-09-18T21:21:28Z | [
"python",
"numpy",
"netcdf",
"python-xarray",
"netcdf4"
] |
Error on using xarray open_mfdataset function | 39,562,113 | <p>I am trying to combine multiple netCDF files with the same dimensions, their dimensions are as follows:</p>
<pre><code>OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'net... | 1 | 2016-09-18T20:01:31Z | 39,564,104 | <p>This error message is probably arising because you have two files with the same variables and coordinate values, and xarray doesn't know whether it should stack them together along a new dimension or simply check to make sure none of the values conflict.</p>
<p>It would be nice if explicitly calling <code>open_mfda... | 1 | 2016-09-19T01:14:22Z | [
"python",
"numpy",
"netcdf",
"python-xarray",
"netcdf4"
] |
python with flask get and post methods using ajax | 39,562,161 | <p>i am currently developing a food calorie web app and i want to extract data from a mongoDB into an HTML table.</p>
<p>my python code is:</p>
<pre><code>from flask import Flask
from flask import request
import requests
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from flask import ... | -1 | 2016-09-18T20:07:08Z | 39,562,646 | <p>For your current JSON use this code:</p>
<pre><code> $(function() {
$('#calculate').bind('click', function() {
$.getJSON('/_foods', {
a: $('input[name="a"]').val()
}, function(data) {
for (key in data) {
$('#result').append('<tr><td>' + key + '... | 1 | 2016-09-18T21:02:51Z | [
"javascript",
"jquery",
"python",
"html",
"flask"
] |
How to resolve thread deadlocks in real-time? | 39,562,203 | <p>If a deadlock between python threads is suspected in run-time, is there any way to resolve it without killing the entire process?</p>
<p>For example, if a few threads take far longer than they should, a resource manager might suspect that some of them are deadlocked. While of course it should be debugged fixed in t... | 3 | 2016-09-18T20:11:05Z | 39,562,411 | <p>You may try using <a href="http://code.activestate.com/recipes/577334-how-to-debug-deadlocked-multi-threaded-programs/" rel="nofollow">this</a> code snippet ahead of time but during execution the program is stuck and you can't do much about it.</p>
<p>Debuggers like WinDbg or strace might help but as Python is an i... | 2 | 2016-09-18T20:32:43Z | [
"python",
"python-3.x",
"python-multithreading"
] |
How to create an adjacency list from an edge list efficiently | 39,562,253 | <p>I have a csv that looks like</p>
<pre><code>id1,id2
a,b
c,d
a,e
c,f
c,g
</code></pre>
<p>I read it in to a dataframe with df = pd.read_csv("file.csv").</p>
<p>I would like to convert it to an adjacency list. That is the output should be</p>
<pre><code>a,b,e
c,d,f,g
</code></pre>
<p>I feel that df.groupby('id1'... | 1 | 2016-09-18T20:16:23Z | 39,562,298 | <p>You can indeed <code>groupby</code>, then <code>apply</code> <code>list</code>:</p>
<pre><code>In [48]: df = pd.DataFrame({'id1': ['a', 'c', 'a', 'c', 'c'], 'id2': ['b', 'd', 'e', 'f', 'g']})
In [49]: df.id2.groupby(df.id1).apply(list)
Out[49]:
id1
a [b, e]
c [d, f, g]
Name: id2, dtype: object
</code></p... | 1 | 2016-09-18T20:20:36Z | [
"python",
"pandas",
"graph"
] |
How to create an adjacency list from an edge list efficiently | 39,562,253 | <p>I have a csv that looks like</p>
<pre><code>id1,id2
a,b
c,d
a,e
c,f
c,g
</code></pre>
<p>I read it in to a dataframe with df = pd.read_csv("file.csv").</p>
<p>I would like to convert it to an adjacency list. That is the output should be</p>
<pre><code>a,b,e
c,d,f,g
</code></pre>
<p>I feel that df.groupby('id1'... | 1 | 2016-09-18T20:16:23Z | 39,562,308 | <p>if you need CSV strings:</p>
<pre><code>In [107]: df.groupby('id1').id2.apply(lambda x: ','.join(x)).reset_index()
Out[107]:
id1 id2
0 a b,e
1 c d,f,g
</code></pre>
| 1 | 2016-09-18T20:21:11Z | [
"python",
"pandas",
"graph"
] |
How to create an adjacency list from an edge list efficiently | 39,562,253 | <p>I have a csv that looks like</p>
<pre><code>id1,id2
a,b
c,d
a,e
c,f
c,g
</code></pre>
<p>I read it in to a dataframe with df = pd.read_csv("file.csv").</p>
<p>I would like to convert it to an adjacency list. That is the output should be</p>
<pre><code>a,b,e
c,d,f,g
</code></pre>
<p>I feel that df.groupby('id1'... | 1 | 2016-09-18T20:16:23Z | 39,562,348 | <p>You can use:</p>
<pre><code>df.groupby('id1')['id2'].apply(','.join).reset_index()
</code></pre>
<p>Another solution where output is list:</p>
<pre><code>df.groupby('id1')['id2'].apply(lambda x: x.tolist())
</code></pre>
| 1 | 2016-09-18T20:26:10Z | [
"python",
"pandas",
"graph"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.