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 to extract the key and get back the original byte code, but it should prevent most forms of âcasualâ tampering.</em></p>
<p>My basic understanding of AES-256 is that if no one has the encryption key you specify, they can't extract it "easily"</p>
<p>Does anyone have better understanding ?</p>
| 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 protected excel files for instance).</p>
<p>It means that the key lies somewhere embedded in the installed software. And since all this stuff is open source, looking at the source code tells you where PyInstaller embeds the key. Of course, it's not trivial, but not an encyption-breaking problem, just reverse engineering with, added, the source available.</p>
| 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 script to /usr/local/bin
Installing pip2.7 script to /usr/local/bin
Installing pip2 script to /usr/local/bin
Using /Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg
Processing dependencies for pip
Finished processing dependencies for pip
Rahul-MacBook-Air:~ rahul$ pip install beautifulsoup4
Collecting beautifulsoup4
Using cached beautifulsoup4-4.5.1-py2-none-any.whl
Installing collected packages: beautifulsoup4
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_set.py", line 742, in install
**kwargs
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/req/req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/wheel.py", line 317, in clobber
ensure_dir(destdir)
File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir
os.makedirs(path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/beautifulsoup4-4.5.1.dist-info'
</code></pre>
<p>Can somebody please tell me what am I doing wrong here ?</p>
<p>My next question is related to the previous one. I have installed Python 3.5.2</p>
<pre><code>>>> print(sys.version)
3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
>>>
</code></pre>
<p>However on the terminal it shows me a different version:</p>
<pre><code>Rahul-MacBook-Air:~ rahul$ python -V
Python 2.7.10
</code></pre>
<p>So when I try to install BeautifulSoup it starts pointing to Python 2.7 which I think is wrong. It should point to the latest Python version i.e. 3.5.2</p>
<p>Also I have Python 2.7 pre-installed at <code>/usr/bin/python</code> and Python 3.5.2 is installed at <code>/usr/local/bin/python</code>.
How do I default the Python version such that every time I open my terminal it is already pointing to Python 3.5.2</p>
<p>Thanks,
Rahul</p>
| 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 Python 3.5.2, but aren't showing the command you're using to run it. I'm pretty sure it's something like <code>python3</code> (in any case, <em>not</em> simply <code>python</code>), so what makes you wonder why <code>python -V</code> shows a different version number? The command <code>python</code> runs a different Python interpreter.</p>
<p>If you want to install anything for Python 3.5, you'll need <code>pip3</code>, not <code>pip</code>.</p>
<p>You can make <code>python</code> an alias (or a symbolic link) to <code>python3.5</code> and probably rename the Python 2.7 interpreter to something like <code>python2.7</code>, if it hasn't been done already.</p>
| 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 functioning:</p>
<pre><code>df = pd.read_csv(filename, header = None, error_bad_lines = False, usecols = [9], names =
['addresses'])
addresses = df['addresses'].tolist()
addresses = [x for x in addresses if str(x) != 'nan']
</code></pre>
| 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({'addresses':[4,8,7]})
print (df)
addresses
0 4
1 8
2 7
addresses = df.loc[1:, 'addresses'].tolist()
print (addresses)
[8, 7]
</code></pre>
<p>Another solution, thanks <a href="http://stackoverflow.com/questions/39559805/skip-first-row-in-pandas-dataframe-when-creating-list/39559825?noredirect=1#comment66430370_39559825">Nickil Maveli</a>:</p>
<pre><code>import pandas as pd
import io
temp=u"""10
20
30
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), header=None, skiprows=[0], names=['addresses'])
print (df)
addresses
0 20
1 30
</code></pre>
| 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 data attribute with 'one'
def __init__(self):
self.sideup='one'
def __init__(self):
self.twosides='one and two'
#the toss method generates a random number
#in the range of 1 through 6.
def toss(self):
if random.randint(1,6)==1:
self.sideup='one'
elif random.randint(1,6)==2:
self.sideup='two'
elif random.randint(1,6)==3:
self.sideup='three'
elif random.randint(1,6)==4:
self.sideup='four'
elif random.randint(1,6)==5:
self.sideup='five'
else:
self.sideup='six'
def get_sideup(self):
return self.sideup
def doubletoss(self):
if random.randint(1,6)==1 and random.randint(1,6)==2:
self.twosides='one and two'
elif random.randint(1,6)==1 and random.randint(1,6)==3:
self.twosides='one and three'
elif random.randint(1,6)==1 and random.randint(1,6)==4:
self.twosides='one and four'
elif random.randint(1,6)==1 and random.randint(1,6)==5:
self.twosides='one and five'
elif random.randint(1,6)==1 and random.randint(1,6)==6:
self.twosides='one and six'
elif random.randint(1,6)==1 and random.randint(1,6)==1:
self.twosides='one and one'
def get_twosides(self):
return self.twosides
#main function
def main():
#create an object from the Dice class
my_dice=Dice()
#Display the siide of the dice is factory
print('This side is up',my_dice.get_sideup())
#toss the dice
print('I am tossing the dice')
my_dice.toss()
#toss two dice
print('I am tossing two die')
my_dice.doubletoss()
#Display the side of the dice that is facing up
print('this side is up:',my_dice.get_sideup())
#display both dices with the sides of the dice up
print('the sides of the two dice face up are:',my_dice.get_twosides())
main()
</code></pre>
<p>Here is the output of my program when I run it:</p>
<blockquote>
<p>"Traceback (most recent call last):
File "C:/Users/Pentazoid/Desktop/PythonPrograms/DiceClass.py", line 79, in
main()
File "C:/Users/Pentazoid/Desktop/PythonPrograms/DiceClass.py", line 61, in main
print('This side is up',my_dice.get_sideup())
File "C:/Users/Pentazoid/Desktop/PythonPrograms/DiceClass.py", line 32, in get_sideup
return self.sideup</p>
<p>AttributeError: 'Dice' object has no attribute 'sideup'</p>
</blockquote>
<p>What am I doing wrong?</p>
| 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.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
else:
nums.append(int(num))
</code></pre>
<p>I don't know how to make the program perform the calculation to print out the average. I am very new to programming in python and I would appreciate any help I can get on fixing this program. Thanks in advance!</p>
| 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 inside the while loop
break
# Only append after testing for 'Done'
nums.append(float(num)) # Ensure valid input by convert it into the desired type.
print('average: %s' % (sum(nums) / len(nums)))
</code></pre>
<p>It is a good practice to give the user useful error messages, when some input is not as the program needs it. It can save the user lots of trouble. If you just want to tell the user what the problem was when an invalid input is given, you can do it with a try statement as below:</p>
<pre><code>nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
try:
nums.append(float(num))
except Exception:
print('Please enter a number. Input "%s" will be ignored.' % num)
print('average: %s' % (sum(nums) / len(nums)))
</code></pre>
| 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 65536</p>
</blockquote>
<p>I've been practicing with the example' data successfully. However, after introducing my own images which I resized to <code>128x128px</code> and generated ubytes idx files, I get the following error:</p>
<blockquote>
<pre>Traceback (most recent call last):
File "tensorimage.py", line 132, in
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/training/optimizer.py", line 196, in minimize
grad_loss=grad_loss)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/training/optimizer.py", line 253, in compute_gradients
colocate_gradients_with_ops=colocate_gradients_with_ops)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/ops/gradients.py", line 478, in gradients
in_grads = _AsList(grad_fn(op, *out_grads))
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/ops/array_grad.py", line 298, in _ReshapeGrad
return [array_ops.reshape(grad, array_ops.shape(op.inputs[0])), None]
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1758, in reshape
name=name)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op
op_def=op_def)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 2319, in create_op
set_shapes_for_outputs(ret)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/framework/ops.py", line 1711, in set_shapes_for_outputs
shapes = shape_func(op)
File "/home/ubuntu/tensorflow/python3/lib/python3.4/site-packages/tensorflow/python/ops/array_ops.py", line 1867, in _ReshapeShape
(num_elements, known_elements))
ValueError: input has 16384 elements, which isn't divisible by 65536</pre>
</blockquote>
<p>What's confusing to me is, I did indeed set the input to 16384 elements (128x128), however, I don't understand where 65536 came from. I combed through all of the code including the file <code>tensorflow/python3/lib/python3.4/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py</code>
but can't find where 65536 number came from.</p>
| 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 dimensions size, and spotting an error:</p>
<p><a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/array_ops.py#L1702" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/array_ops.py#L1702</a></p>
<p>What happens if you print the size of <code>input</code> just before this error?</p>
| 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.6628449915450776e-08 Ohm m
</code></pre>
<p>Now I want to reduce the number of decimal places that are printed to 3. I tried doing it with string formatting, like this:</p>
<pre><code>print("Mean resistivity: {res:.3f} Ohm m".format(res=np.mean(resistivity)))
</code></pre>
<p>However, this code prints:</p>
<pre><code>Mean resistivity: 0.000 Ohm m
</code></pre>
<p>What I actually want is this:</p>
<pre><code>Mean resistivity: 1.663e-8 Ohm m
</code></pre>
<p>How can I format <code>res</code> to only be displayed as scientific notation but with only 3 decimal places?</p>
| 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 before them and the specifics (blue, warm, male) have a space before them.</p>
<p>I would like to ignored the attributes and create a 2D list like</p>
<pre><code>newList = [["Blue", "Warm", "Male"], ["Green", "Warm", "Female"]]
</code></pre>
<p>but I cannot figure out how to do this using the <code>split()</code> or <code>strip()</code> string methods.</p>
| -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 testList])
[['Blue', 'Warm', 'Male'], ['Green', 'Warm', 'Female']]
</code></pre>
| 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 before them and the specifics (blue, warm, male) have a space before them.</p>
<p>I would like to ignored the attributes and create a 2D list like</p>
<pre><code>newList = [["Blue", "Warm", "Male"], ["Green", "Warm", "Female"]]
</code></pre>
<p>but I cannot figure out how to do this using the <code>split()</code> or <code>strip()</code> string methods.</p>
| -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) # -> [['Blue', 'Warm', 'Male'], ['Green', 'Warm', 'Female']]
</code></pre>
| 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 before them and the specifics (blue, warm, male) have a space before them.</p>
<p>I would like to ignored the attributes and create a 2D list like</p>
<pre><code>newList = [["Blue", "Warm", "Male"], ["Green", "Warm", "Female"]]
</code></pre>
<p>but I cannot figure out how to do this using the <code>split()</code> or <code>strip()</code> string methods.</p>
| -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 Warm Gender Male", "Color Green Temperature Warm Gender Female"]
items = re.findall(r'Color (\w+)\b Temperature (\w+)\b[\s\t]*?Gender (\w+)', ' '.join(testList), overlapped=True)
print([list(m) for m in items])
</code></pre>
<p>The output:</p>
<pre><code>[['Blue', 'Warm', 'Male'], ['Green', 'Warm', 'Female']]
</code></pre>
| 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>True</code> and <code>False</code> actually work and are interpreted as the integers <code>1</code> and <code>0</code>. Therefore the factorial function produces the expected results <code>1</code> and <code>1</code> when using <code>True</code> and <code>False</code>. The behavior of those booleans is clearly <a href="https://docs.python.org/3.5/library/stdtypes.html#numeric-types-int-float-complex" rel="nofollow">described in the python manual</a> and for the most part I can live with the fact that a boolean is a subtype of integer.</p>
<p>However, I was wondering: is there any clever way to wash away something like <code>True</code> as an actual parameter for the factorial function (or any other context which requires integers) in a way that it'll throw some kind of exception which the programmer can handle?</p>
| 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>:</p>
<pre><code>if type(n) is not int:
raise TypeError('input is not an integer')
</code></pre>
| 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>True</code> and <code>False</code> actually work and are interpreted as the integers <code>1</code> and <code>0</code>. Therefore the factorial function produces the expected results <code>1</code> and <code>1</code> when using <code>True</code> and <code>False</code>. The behavior of those booleans is clearly <a href="https://docs.python.org/3.5/library/stdtypes.html#numeric-types-int-float-complex" rel="nofollow">described in the python manual</a> and for the most part I can live with the fact that a boolean is a subtype of integer.</p>
<p>However, I was wondering: is there any clever way to wash away something like <code>True</code> as an actual parameter for the factorial function (or any other context which requires integers) in a way that it'll throw some kind of exception which the programmer can handle?</p>
| 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):
raise TypeError('input is not an integer')
return math.factorial(n)
print(func(True))
print(func(False))
print(func(1))
</code></pre>
| 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>
<p>Now I want to plot another column of the same dataframe as bar chart using</p>
<pre><code>ax=df.iloc[:,3].plot(kind='bar',width=1)
</code></pre>
<p>with the result:</p>
<p><a href="http://i.stack.imgur.com/92UxV.png" rel="nofollow"><img src="http://i.stack.imgur.com/92UxV.png" alt="enter image description here"></a></p>
<p>And finally I want to combine both by</p>
<pre><code>spy_price_data.iloc[:,1].plot(ax=ax)
</code></pre>
<p>which doesn't produce any plot.</p>
<p>Why are the x-ticks of the bar plot so different to the x-ticks of the line plot? How can I combine both plots in one plot?</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></pre>
<p>then we create an axes object (ax). Notice that we pass ax to both plots</p>
<pre><code>_, ax = plt.subplots()
df[0].plot(ax=ax)
df[1].plot(kind='bar', ax=ax)
</code></pre>
<p><a href="http://i.stack.imgur.com/GKVXm.png" rel="nofollow"><img src="http://i.stack.imgur.com/GKVXm.png" alt="enter image description here"></a></p>
| 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>
<p>Now I want to plot another column of the same dataframe as bar chart using</p>
<pre><code>ax=df.iloc[:,3].plot(kind='bar',width=1)
</code></pre>
<p>with the result:</p>
<p><a href="http://i.stack.imgur.com/92UxV.png" rel="nofollow"><img src="http://i.stack.imgur.com/92UxV.png" alt="enter image description here"></a></p>
<p>And finally I want to combine both by</p>
<pre><code>spy_price_data.iloc[:,1].plot(ax=ax)
</code></pre>
<p>which doesn't produce any plot.</p>
<p>Why are the x-ticks of the bar plot so different to the x-ticks of the line plot? How can I combine both plots in one plot?</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>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as mgrid
import pandas as pd
fig, tsax = plt.subplots(figsize=(12,5))
barax = tsax.twinx()
data = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'), index=pd.DatetimeIndex(freq='1M', start='2012-01-01', periods=10))
data['A'] **= 2
# the `width` is specified in days -- adjust for your data
barax.bar(data.index, data['A'], width=5, facecolor='indianred')
barax.set_ylabel('Miles')
tsax.set_ylabel('Miles/Gallon')
barax.xaxis.tick_top()
fig.tight_layout()
tsax.plot(data.index, data['B'])
tsax.plot(data.index, data['C'])
</code></pre>
<p>Which then gives me <a href="http://i.stack.imgur.com/jHOHW.png" rel="nofollow">http://i.stack.imgur.com/jHOHW.png</a></p>
</blockquote>
| 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 because I can see it in admin, so it is not a comment creation problem. They are simply not showing in my template.</p>
<p>My comments/models.py:</p>
<pre><code>from django.db import models
class Comment(models.Model):
post = models.ForeignKey('blog.Entry',related_name='post_comments', blank=True, null=True)
article = models.ForeignKey('articles.Article', related_name='article_comments', blank=True, null=True)
body = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body
</code></pre>
<p>My commments/views.py:</p>
<pre><code>from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from .forms import CommentForm
from .models import Comment
from blog.models import Entry
from articles.models import Article
from blog.views import post_detail
from articles.views import article_detail
def article_new_comment(request, pk):
article = get_object_or_404(Article, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.article = article
comment.created_date=timezone.now()
comment.save()
return redirect(article_detail, pk=article.pk)
else:
form=CommentForm()
return render(request, 'comments/add_new_comment.html', {'form': form})
def blog_new_comment(request, pk):
post = get_object_or_404(Entry, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.created_date = timezone.now()
comment.save()
return redirect(post_detail, pk=post.pk)
else:
form=CommentForm()
return render(request, 'comments/add_new_comment.html', {'form': form})
</code></pre>
<p>And here is my post_detail.html, where comments should be. I will not post article_detail.html because they are exactly the same:</p>
<pre><code>{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.modified_date %}
<div class="date">
{{ post.modified_date }}
</div>
{% else %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"> Edit Post </span></a>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
<hr>
<a class="btn btn-default" href="{% url 'new_blog_comment' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"> Add Comment </span></a>
{% for comment in post.comments.all %}
<div class="comment">
<div class="date">{{ comment.created_date }}</div>
<p>{{ comment.body|linebreaksbr }}</p>
</div>
{% empty %}
<p>No comments here yet</p>
{% endfor %}
</div>
{% endblock %}
</code></pre>
<p>Let me know if any other file would help you to help me, like blog/models, views, although I don't think the problem is there.</p>
| 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.</p>
| 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 function is:</p>
<pre><code>def obj_fct(x, alpha,beta,Al):
U = 0
x[1,0] = x0
for t in trange:
U = U - beta**t * ( (Al[t]*L)**(1-alpha) * x[1,t]**alpha - x[0,t])
return U
</code></pre>
<p>The constraints are defined over these two variables and one of them links the variables from one period (t) to another (t-1).</p>
<pre><code>def constr(x,alpha,beta,Al):
return np.array([
x[0,t],
x[1,0] - x0,
x[1,t] - x[0,t] - (1-delta)*x[1,t-1]
])
</code></pre>
<p>Finally, here is the use of fmin_slsqp:</p>
<pre><code>sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))
</code></pre>
<p>Leaving aside the fact that there are better ways to solve such dynamic problems, my question is about the syntax. When running this simple code, I get the following error:</p>
<pre><code> Traceback (most recent call last):
File "xxx", line 34, in <module>
sol = fmin_slsqp(obj_fct, x_init, f_eqcons=constr, args=(alpha,beta,Al))
File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 207, in fmin_slsqp
constraints=cons, **opts)
File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 311, in _minimize_slsqp
meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
File "D:\Anaconda3\lib\site-packages\scipy\optimize\slsqp.py", line 311, in <listcomp>
meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) for c in cons['eq']]))
File "xxx", line 30, in constr
x[0,t],
IndexError: too many indices for array
[Finished in 0.3s with exit code 1]
</code></pre>
<p>What am I doing wrong? </p>
<p>The initial part of the code, assigning values to the parameters, is:</p>
<pre><code> from scipy.optimize import fmin_slsqp
import numpy as np
T = 30
beta = 0.96
L = 1
x0 = 1
gl = 0.02
alpha = 0.3
delta = 0.05
x_init = np.array([1,0.1])
A_l0 = 1000
Al = np.zeros((T+1,1))
Al[1] = A_l0
trange = np.arange(1,T+1,1, dtype='Int8') # does not include period zero
for t in trange: Al[t] = A_l0*(1 + gl)**(t-1)
</code></pre>
| 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>
<blockquote>
<p>Create a python program named sumseries.py that does the following:
Put comments at the top of your program with your name, date, and
description of what the program does.</p>
<p>Write a program to calculate and display the sum of the series:</p>
<p>1 - 1/2 + 1/3 - 1/4 + ...</p>
<p>until a term is reached that is less than 0.0001.</p>
</blockquote>
<p>The answer with 10,000 iterations appears to be 0.6930971830599583</p>
<p>I ran the program with 1,000,000,000 (billion) iterations and came up with a number of 0.6931471810606472. I need to create a loop to programmably create the series.</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>
<blockquote>
<p>Create a python program named sumseries.py that does the following:
Put comments at the top of your program with your name, date, and
description of what the program does.</p>
<p>Write a program to calculate and display the sum of the series:</p>
<p>1 - 1/2 + 1/3 - 1/4 + ...</p>
<p>until a term is reached that is less than 0.0001.</p>
</blockquote>
<p>The answer with 10,000 iterations appears to be 0.6930971830599583</p>
<p>I ran the program with 1,000,000,000 (billion) iterations and came up with a number of 0.6931471810606472. I need to create a loop to programmably create the series.</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 the elements of a series 'on the fly'
<ul>
<li><code>1.0 / k if k % 2 else -1.0 / k</code> results in <code>1.0 / k</code> if <code>k</code> is odd and <code>-1.0 / k</code> otherwise (<code>a - b</code> is the same as <code>a + (-b)</code>)</li>
<li><code>for k in range(1, 10001)</code> goes through all <code>k</code>s in range from 1 (included) to 10001 (excluded)</li>
</ul></li>
<li><a href="https://docs.python.org/3/library/functions.html#sum" rel="nofollow"><code>sum</code></a> can compute the sum of any sequence (any <a href="http://stackoverflow.com/questions/9884132/what-exactly-are-pythons-iterator-iterable-and-iteration-protocols"><em>iterable</em></a>, to be precise), be it a list, a tuple, or a generator expression</li>
</ul>
<hr>
<h3>The same without generator expressions:</h3>
<pre><code>Answer = 0
for k in range(1, 10001):
if k % 2:
Answer += 1.0 / k
else:
Answer -= 1.0 / k
# or simply:
# Answer += 1.0 / k if k % 2 else -1.0 / k
</code></pre>
| 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>
<blockquote>
<p>Create a python program named sumseries.py that does the following:
Put comments at the top of your program with your name, date, and
description of what the program does.</p>
<p>Write a program to calculate and display the sum of the series:</p>
<p>1 - 1/2 + 1/3 - 1/4 + ...</p>
<p>until a term is reached that is less than 0.0001.</p>
</blockquote>
<p>The answer with 10,000 iterations appears to be 0.6930971830599583</p>
<p>I ran the program with 1,000,000,000 (billion) iterations and came up with a number of 0.6931471810606472. I need to create a loop to programmably create the series.</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-calculating a loop limit of 10000, but that was not the requested algorithm. Instead, one is to calculate successive terms (1, -1/2, 1/3, -1/4, ...) until reaching a term less than 0.0001.</p>
<p>The reason the problem was specified that way is that one ends up with a more generally useful program, applicable to a wide class of term formulas. Not a fragile one that gets the wrong answer if the term formula is changed from <code>(-1)**(k-1)/k</code>, to say <code>1/k</code> or <code>1/k^2</code>.</p>
<p>The teacher's wording "term less than 0.0001" is imprecise and assumed some math knowledge. They want the magnitude (absolute value) of the term to be less than 0.0001. Otherwise, iteration would stop at the second term -1/2, as someone pointed out.</p>
<p>So, this answer would not be complete without a pompous pedantic solution that skips ahead a chapter. ;) Note that previous some answers will not work in Python2.x without a conversion to float.</p>
<pre><code>def term(k):
return (-1)**(k - 1) / float(k)
err = 0.0001
def terms():
k = 1
t = term(k)
while abs(t) >= err:
yield t
k += 1
t = term(k)
print(sum(terms()))
</code></pre>
| 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>
<blockquote>
<p>Create a python program named sumseries.py that does the following:
Put comments at the top of your program with your name, date, and
description of what the program does.</p>
<p>Write a program to calculate and display the sum of the series:</p>
<p>1 - 1/2 + 1/3 - 1/4 + ...</p>
<p>until a term is reached that is less than 0.0001.</p>
</blockquote>
<p>The answer with 10,000 iterations appears to be 0.6930971830599583</p>
<p>I ran the program with 1,000,000,000 (billion) iterations and came up with a number of 0.6931471810606472. I need to create a loop to programmably create the series.</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 - 1.0/k
k = k + 1
print(sum)
</code></pre>
| 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.html</strong></p>
<pre><code><form action="{% url 'show:addseason' show=show %}" method="post">
{% csrf_token %}
<button class="btn btn-default" type="submit">+</button>
</form>
<form action="{% url 'show:subtractseason' show=show %}" method="post">
{% csrf_token %}
<button class="btn btn-default" type="submit">-</button>
</form>
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>class ShowDetail(DetailView):
model = Show
slug_field = "title"
slug_url_kwarg = "show"
template_name = 'show/show-detail.html'
class AddSeason(UpdateView):
model = Show
slug_field = 'title'
slug_url_kwarg = 'show'
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
instance.season += 1
instance.save()
return redirect('show:index')
class SubtractSeason(UpdateView):
model = Show
slug_field = 'title'
slug_url_kwarg = 'show'
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
if (instance.season >= 0):
instance.season -= 1
else:
instance.season = 0
instance.save()
return redirect('show:index')
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^about/$', views.AboutView.as_view(), name='about'),
# form to add show
url(r'^add/$', views.ShowCreate.as_view(), name='show-add'),
# edit show
#url(r'^(?P<show>[\w ]+)/edit/$', views.ShowUpdate.as_view(), name='show-update'),
# delete show
url(r'^(?P<show>[\w ]+)/delete/$', views.ShowDelete.as_view(), name='show-delete'),
# signup
url(r'^register/$', views.UserFormView.as_view(), name='register'),
# login
url(r'^login/$', views.LoginView.as_view(), name='login'),
# logout
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
url(r'^error/$', views.ErrorView.as_view(), name='error'),
url(r'^(?P<show>[\w ]+)/$', views.ShowDetail.as_view(), name='show-detail'),
url(r'^(?P<show>[\w ]+)/addseason/$', views.AddSeason.as_view(), name='addseason'),
url(r'^(?P<show>[\w ]+)/subtractseason/$', views.SubtractSeason.as_view(), name='subtractseason'),
url(r'^(?P<show>[\w ]+)/addepisode/$', views.AddEpisode.as_view(), name='addepisode'),
url(r'^(?P<show>[\w ]+)/subtractepisode/$', views.SubtractEpisode.as_view(), name='subtractepisode'),
</code></pre>
<p>I get an error when I try</p>
<pre><code>return redirect('show:detail')
</code></pre>
<p>This is the error</p>
<pre><code>NoReverseMatch at /Daredevil/addseason/
Reverse for 'detail' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
</code></pre>
| 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>SubtractSeason</code>. Try:</p>
<pre><code>redirect('show:detail', kwargs={'show': instance.pk})
</code></pre>
<p><strong>EDIT:</strong> the name of the detail url is <code>'show-detail'</code>, so the scoped viewname would be <code>'show:show-detail'</code> (if it is in the <code>show</code> namespace like the other urls). I still think it would need a kwarg though, try:</p>
<pre><code>redirect('show:show-detail', kwargs={'show': instance.pk})
</code></pre>
| 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.html</strong></p>
<pre><code><form action="{% url 'show:addseason' show=show %}" method="post">
{% csrf_token %}
<button class="btn btn-default" type="submit">+</button>
</form>
<form action="{% url 'show:subtractseason' show=show %}" method="post">
{% csrf_token %}
<button class="btn btn-default" type="submit">-</button>
</form>
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>class ShowDetail(DetailView):
model = Show
slug_field = "title"
slug_url_kwarg = "show"
template_name = 'show/show-detail.html'
class AddSeason(UpdateView):
model = Show
slug_field = 'title'
slug_url_kwarg = 'show'
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
instance.season += 1
instance.save()
return redirect('show:index')
class SubtractSeason(UpdateView):
model = Show
slug_field = 'title'
slug_url_kwarg = 'show'
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
if (instance.season >= 0):
instance.season -= 1
else:
instance.season = 0
instance.save()
return redirect('show:index')
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^about/$', views.AboutView.as_view(), name='about'),
# form to add show
url(r'^add/$', views.ShowCreate.as_view(), name='show-add'),
# edit show
#url(r'^(?P<show>[\w ]+)/edit/$', views.ShowUpdate.as_view(), name='show-update'),
# delete show
url(r'^(?P<show>[\w ]+)/delete/$', views.ShowDelete.as_view(), name='show-delete'),
# signup
url(r'^register/$', views.UserFormView.as_view(), name='register'),
# login
url(r'^login/$', views.LoginView.as_view(), name='login'),
# logout
url(r'^logout/$', views.LogoutView.as_view(), name='logout'),
url(r'^error/$', views.ErrorView.as_view(), name='error'),
url(r'^(?P<show>[\w ]+)/$', views.ShowDetail.as_view(), name='show-detail'),
url(r'^(?P<show>[\w ]+)/addseason/$', views.AddSeason.as_view(), name='addseason'),
url(r'^(?P<show>[\w ]+)/subtractseason/$', views.SubtractSeason.as_view(), name='subtractseason'),
url(r'^(?P<show>[\w ]+)/addepisode/$', views.AddEpisode.as_view(), name='addepisode'),
url(r'^(?P<show>[\w ]+)/subtractepisode/$', views.SubtractEpisode.as_view(), name='subtractepisode'),
</code></pre>
<p>I get an error when I try</p>
<pre><code>return redirect('show:detail')
</code></pre>
<p>This is the error</p>
<pre><code>NoReverseMatch at /Daredevil/addseason/
Reverse for 'detail' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
</code></pre>
| 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 least!)</p>
| 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 dfhghihg 154.56.2.6 fdhusdgv
aff fjhgdf
fdfdnfjgkpg
fdf hgj fdnbk gjdhgj
dfdfg raeh95@gmail.com efhidhg fdfuga reg@gmail.com
ergudfi rey@gmail.com iugftudfh dgufidjfdg
teeeee@gmail.comugfuhlfhs fgufif p
</code></pre>
<p>2.I want to extract the ssn number, date, e-mail line by line. I'm expecting code that loops through every line and returns the expected strings. </p>
<p>3.<strong>Correct the coding in Python</strong>:</p>
<pre><code>import re
def cfor_date(str):
t=re.search(r'(\d{4}-\d{2}-\d{2})',str)
return t
def cfor_ssn(str):
f=re.search(r'(\d{3}-\d{2}-\d{4})',str)
return f
def cfor_gm(str):
g=re.search(r'([\w\.-]+@gmail[\w{3}\.-]+)',str)
return g
f = open("rexp.txt","r").read()
lines = f.splitlines()
for line in iter(lines):
x=line.split(" ")
print x
if (cfor_date(x)) != None: # i feel problem here
r=cfor_ssn(x)
print r
</code></pre>
| -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 and then read file completely using <code>readlines()</code>. No need to split lines and no need to worry of closing file.</li>
<li>In your code, once you started iterating line by line, you are again splitting line on basis of single space and then you are passing the output of split which will be list to you functions to extract date/email/ssn. Here where the problem is.</li>
<li>No need to split line on basis of spaces. Pass the line directly to functions to extract the data.</li>
<li>Your regular expression are good. I didn't modify it.</li>
<li>I have replaced the <code>search</code> function with <code>findall</code> function. Difference between both is explained in below example.</li>
</ul>
<blockquote>
<pre><code> >>> import re
>>> a = "Dinesh 123"
>>> t = re.search(r"\d+",a)
>>> t <_sre.SRE_Match object at 0x01FE3918>
>>> t.group()
>>> '123'
>>> x = re.findall(r'\d+',a)
>>> x
>>> ['123']
</code></pre>
</blockquote>
<p>For more help, check this <a href="https://pymotw.com/2/re/" rel="nofollow">link</a> !!!</p>
<p>All above points are present in below code :</p>
<p><strong>Code:</strong></p>
<pre><code>import re
def cfor_date(tmp_line):
t=re.findall(r'(\d{4}-\d{2}-\d{2})',tmp_line)
return t
def cfor_ssn(tmp_line):
f=re.findall(r'(\d{3}-\d{2}-\d{4})',tmp_line)
return f
def cfor_gm(tmp_line):
g=re.findall(r'([\w\.-]+@gmail[\w{3}\.-]+)',tmp_line)
return g
with open("xyz.txt","r") as fh:
for line in fh.readlines():
date_list = cfor_date(line)
ssn_list = cfor_ssn(line)
gm_list = cfor_gm(line)
if len(ssn_list) != 0:
print ssn_list
if len(date_list) != 0:
print date_list
if len(gm_list) != 0 :
print gm_list
</code></pre>
<p><strong>Output :</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
['1995-11-23']
['2000-04-12', '2001-02-17']
['244-44-2255']
['455-44-6577']
['raeh95@gmail.com', 'reg@gmail.com']
['rey@gmail.com']
['teeeee@gmail.comugfuhlfhs']
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 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>
<pre><code>from django.contrib.auth.models import User
from myapp.models import mymodel
class MyModel(models.Model):
user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel')
username = models.CharField(max_length=145, blank=True, null=True)
name = models.CharField(max_length=45, blank=True, null=True)
</code></pre>
<p><strong>Editted Model.py:</strong> </p>
<pre><code>class MyModel(models.Model):
user = models.ForeignKey(User, blank=True, null=True, related_name='mymodel')
name = models.CharField(max_length=45, blank=True, null=True)
</code></pre>
<p>I deleted <em>migration folder</em> and my <strong>DB</strong> and recreated them anew but each time I try retrieving data from MyModel via <code>MyModel.objects.all()</code> or <code>User</code> object I get <strong>AttributeError: 'MyModel' object has no attribute 'username'</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 I have:</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)
ans = ans + temp
</code></pre>
<p>The code gives me the following error when compiling:</p>
<p>TypeError: 'list' object is not callable</p>
<p>I tried changing the above code to be more like</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)) and i in range(len(vector2)):
temp = vector1(i) * vector2(i)
ans = ans + temp
</code></pre>
<p>But that doesn't work either. What am I doing wrong here?</p>
<p>Edit: After running the code through Python Visualizer, the following line is giving me the specific problem here: </p>
<p>temp = vector1(i) * vector2(i)</p>
| 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 uneven length strings but if they should be the same length then a ValueError is probably the most appropriate response. </p>
<p>The error in your own code is how you are trying to index:</p>
<pre><code>temp = vector1(i) * vector2(i)
</code></pre>
<p>should be:</p>
<pre><code>temp = vector1[i] * vector2[i]
</code></pre>
<p><code>vector1(i)</code> is trying to call the list as if it were a reference to a function. The <code>[i]</code> actually indexes the list. This is tailor made for zip but if you were to use a for loop and index, you should use <em>enumerate:</em></p>
<pre><code>def func(s1, s2):
if len(s1) != len(s2):
raise ValueError("Strings must be the same length")
total = 0
for ind, ele in enumerate(s1):
total += int(ele) * int(s2[ind])
return total
</code></pre>
| 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 I have:</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)
ans = ans + temp
</code></pre>
<p>The code gives me the following error when compiling:</p>
<p>TypeError: 'list' object is not callable</p>
<p>I tried changing the above code to be more like</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)) and i in range(len(vector2)):
temp = vector1(i) * vector2(i)
ans = ans + temp
</code></pre>
<p>But that doesn't work either. What am I doing wrong here?</p>
<p>Edit: After running the code through Python Visualizer, the following line is giving me the specific problem here: </p>
<p>temp = vector1(i) * vector2(i)</p>
| 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]
ans += temp
print ans
</code></pre>
<p>All you have to do is change <code>vector1(i)</code> to <code>vector[i]</code>, to access the element at index <code>i</code> in the lists</p>
| -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')
except Exception, e:
print str(e)
</code></pre>
| -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><code>count = 0
for e in s:
count +=1
return count
</code></pre>
<p>It gives:</p>
<pre><code>(executing lines 1 to 17 of "e_count_103.py")
15
</code></pre>
| -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 to you. (For upper case you can use <code>s.upper().count('E')</code>).For detail read <a href="http://www.tutorialspoint.com/python/string_count.htm" rel="nofollow">String count() tutorial</a>.</p>
<p>Or if you want to use <code>for</code> loop then try this ( in python 3):</p>
<pre><code>def eCount(s):
count = 0
s = s.lower()
for i in s:
if i == 'e':
count+=1
return count
s = "helloEeeeeE"
print(eCount(s))
</code></pre>
<p>It gives same output:</p>
<pre><code>7
</code></pre>
<blockquote>
<p><strong>Note :</strong> <code>e</code> you used in your code in this statement : <code>for e in s:</code> is not character <code>'e'</code> but variable <code>e</code> so it iterate number of characters in
the string and every time incrementing the <code>count</code> variable.</p>
</blockquote>
<p>You can also use <em>list comprehension</em> :</p>
<pre><code>def eCount(s):
return sum([1 for i in s if i == 'e' or i == 'E'])
s = "helloEeeeeE"
print(eCount(s))
</code></pre>
<p>For details about list comprehension you can check this <a href="http://stackoverflow.com/questions/16632124/python-emulate-sum-using-list-comprehension">Python - emulate sum() using list comprehension</a>.</p>
| 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><code>count = 0
for e in s:
count +=1
return count
</code></pre>
<p>It gives:</p>
<pre><code>(executing lines 1 to 17 of "e_count_103.py")
15
</code></pre>
| -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><code> creating build\lib.win-amd64-3.5\cx_Freeze\samples\zope
copying cx_Freeze\samples\zope\qotd.py -> build\lib.win-amd64-3.5\cx_Freeze\samples\zope
copying cx_Freeze\samples\zope\setup.py -> build\lib.win-amd64-3.5\cx_Freeze\samples\zope
running build_ext
building 'cx_Freeze.util' extension
error: Unable to find vcvarsall.bat
----------------------------------------
Failed building wheel for cx-Freeze
Running setup.py clean for cx-Freeze
Failed to build cx-Freeze
Installing collected packages: cx-Freeze
Running setup.py install for cx-Freeze ... error
Complete output from command c:\users\rachin_doug\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\RACHIN~1\\AppData\\Local\\Temp\\pip-build-sllgirs1\\cx-Freeze\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\RACHIN~1\AppData\Local\Temp\pip-7d4trlig-record\install-record.txt --single-version-externally-managed --compile:
</code></pre>
<p>and</p>
<pre><code>creating build\lib.win-amd64-3.5\cx_Freeze\samples\zope
copying cx_Freeze\samples\zope\qotd.py -> build\lib.win-amd64-3.5\cx_Freeze\samples\zope
copying cx_Freeze\samples\zope\setup.py -> build\lib.win-amd64-3.5\cx_Freeze\samples\zope
running build_ext
building 'cx_Freeze.util' extension
error: Unable to find vcvarsall.bat
----------------------------------------
Command "c:\users\rachin_doug\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\RACHIN~1\\AppData\\Local\\Temp\\pip-build-sllgirs1\\cx-Freeze\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\RACHIN~1\AppData\Local\Temp\pip-7d4trlig-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\RACHIN~1\AppData\Local\Temp\pip-build-sllgirs1\cx-Freeze\
</code></pre>
<p>I have already installed Microsoft Visual Studio 2013 before I had tried to install cx_Freeze.</p>
<p>I have tried the following ideas I found in the Internet:</p>
<p>I modified the <code>msvc9compiler.py</code> on line 241 from <code>toolskey = "VS%0.f0COMNTOOLS" % version</code> to <code>toolskey = "VS120COMNTOOLS"</code>;</p>
<p>I creat the term <code>HKEY_CURRENT_USER\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VC</code> and the new string value(name=productdir, data=the path of 'vcvarsall.bat') under the term.</p>
<p>After trying those ideas I still got the same error.</p>
| -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 the case of python 3.5 Visual C++ version 14.0 (Visual Studio 2015) is needed.</p>
| 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>email1@email.com:test1
email2@email.com:test2
email3@gmail.com:test3
</code></pre>
<p>How can i add to the print "Trying with... bla bla" the current line of the account? An output like:</p>
<pre><code>Trying with: email1@email.com:test1 @1
Trying with: email2@email.com:test1 @2
Trying with: email3@email.com:test1 @3
</code></pre>
| -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))
</code></pre>
<p>You can also use unpacking to make the line more readable:</p>
<pre><code>for i, (mail, name) in enumerate(y, start=1):
print ("Trying with: %s:%s @%d" % (mail, name, i))
</code></pre>
<p>Finally, as @idjaw notified it, there is <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="nofollow">a better way to format string</a> which is recommended over the old style:</p>
<pre><code>for i, (mail, name) in enumerate(y, start=1):
print("Trying with: {}:{} @{}".format(mail, name, i))
</code></pre>
| 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>email1@email.com:test1
email2@email.com:test2
email3@gmail.com:test3
</code></pre>
<p>How can i add to the print "Trying with... bla bla" the current line of the account? An output like:</p>
<pre><code>Trying with: email1@email.com:test1 @1
Trying with: email2@email.com:test1 @2
Trying with: email3@email.com:test1 @3
</code></pre>
| -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>
<p><a href="http://i.stack.imgur.com/fzKX5.png" rel="nofollow"><img src="http://i.stack.imgur.com/fzKX5.png" alt="enter image description here"></a></p>
<p>and my wrong code:</p>
<pre><code>grouped=df.groupby('week')
def Range(x,y):
return x.max()-y.min()
grouped.agg(Range(grouped['high'],grouped['low']))
</code></pre>
| 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 113.845864 2015-09-18
2015-09-16 116.250000 116.540001 115.440002 116.410004 37173500 113.973148 2015-09-18
2015-09-17 115.660004 116.489998 113.720001 113.919998 64112600 111.535266 2015-09-18
2015-09-18 112.209999 114.300003 111.870003 113.449997 74285300 111.075104 2015-09-18
2015-09-21 113.669998 115.370003 113.660004 115.209999 50222000 112.798263 2015-09-25
2015-09-22 113.379997 114.180000 112.519997 113.400002 50346200 111.026155 2015-09-25
2015-09-23 113.629997 114.720001 113.300003 114.320000 35756700 111.926895 2015-09-25
2015-09-24 113.250000 115.500000 112.370003 115.000000 50219500 112.592660 2015-09-25
2015-09-25 116.440002 116.690002 114.019997 114.709999 56151900 112.308730 2015-09-25
In [68]: df.groupby('Week').apply(lambda x: x.High.max() - x.Low.min())
Out[68]:
Week
2015-09-18 5.019996
2015-09-25 4.319999
dtype: float64
</code></pre>
<p><strong>Setup DF:</strong></p>
<pre><code>In [75]: from pandas_datareader import data as web
In [76]: df = web.DataReader('aapl', 'yahoo', '2015-09-14', '2015-09-25')
In [77]: df.ix[:5, 'Week'] = df.index[df.index.weekday == 4][0]
In [78]: df.ix[5:, 'Week'] = df.index[df.index.weekday == 4][-1]
In [79]: df
Out[79]:
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 113.845864 2015-09-18
2015-09-16 116.250000 116.540001 115.440002 116.410004 37173500 113.973148 2015-09-18
2015-09-17 115.660004 116.489998 113.720001 113.919998 64112600 111.535266 2015-09-18
2015-09-18 112.209999 114.300003 111.870003 113.449997 74285300 111.075104 2015-09-18
2015-09-21 113.669998 115.370003 113.660004 115.209999 50222000 112.798263 2015-09-25
2015-09-22 113.379997 114.180000 112.519997 113.400002 50346200 111.026155 2015-09-25
2015-09-23 113.629997 114.720001 113.300003 114.320000 35756700 111.926895 2015-09-25
2015-09-24 113.250000 115.500000 112.370003 115.000000 50219500 112.592660 2015-09-25
2015-09-25 116.440002 116.690002 114.019997 114.709999 56151900 112.308730 2015-09-25
</code></pre>
| 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 number of objects worked with I want to make sure that this didn't vary significantly by condition (I don't expect it to have done, but need to confirm this statistically).</p>
<p>I think I want to run an ANOVA to compare the 3 conditions, but I can't figure out how to get the data I need for the ANOVA.</p>
<p>I currently have some pandas code to group the data and count the number of rows per participant per condition (so I can then use mean() and similar to summarise the data). An example with a subset of the data follows:</p>
<pre><code>>>> tmp = df.groupby([FIELD_PARTICIPANT, FIELD_CONDITION]).size()
>>> tmp
participant_id condition
1 a 576
2 b 367
3 a 703
4 c 309
dtype: int64
</code></pre>
<p>To calculate the ANOVA I would normally just filter these by the condition column, e.g.</p>
<pre><code>cond1 = tmp[tmp[FIELD_CONDITION] == CONDITION_A]
cond2 = tmp[tmp[FIELD_CONDITION] == CONDITION_B]
cond3 = tmp[tmp[FIELD_CONDITION] == CONDITION_C]
f_val, p_val = scipy.stats.f_oneway(cond1, cond2, cond3)
</code></pre>
<p>However, since <code>tmp</code> is a <code>Series</code> rather than the <code>DataFrame</code> I'm used to, I can't figure out how to achieve this in the normal way.</p>
<pre><code>>>> tmp[FIELD_CONDITION]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pandas/core/series.py", line 583, in __getitem__
result = self.index.get_value(self, key)
File "/Library/Python/2.7/site-packages/pandas/indexes/multi.py", line 626, in get_value
raise e1
KeyError: 'condition'
>>> type(tmp)
<class 'pandas.core.series.Series'>
>>> tmp.index
MultiIndex(levels=[[u'1', u'2', u'3', u'4'], [u'd', u's']],
labels=[[0, 1, 2, 3], [0, 0, 0, 1]],
names=[u'participant_id', u'condition'])
</code></pre>
<p>I feel sure this is a straightforward problem to solve, but I can't seem to get there without some help :) </p>
| 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></pre>
<p>Sample:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'participant_id': {0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 3, 8: 4, 9: 4},
'condition': {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b', 6: 'b', 7: 'a', 8: 'c', 9: 'c'}})
print (df)
condition participant_id
0 a 1
1 a 1
2 a 1
3 a 1
4 b 2
5 b 2
6 b 2
7 a 3
8 c 4
9 c 4
tmp = df.groupby(['participant_id', 'condition']).size().reset_index(name='count')
print (tmp)
participant_id condition count
0 1 a 4
1 2 b 3
2 3 a 1
3 4 c 2
</code></pre>
<p>If need working with <code>Series</code> you can use condition where select values of level <code>condition</code> of <code>Multiindex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow"><code>get_level_values</code></a>:</p>
<pre><code>tmp = df.groupby(['participant_id', 'condition']).size()
print (tmp)
participant_id condition
1 a 4
2 b 3
3 a 1
4 c 2
dtype: int64
print (tmp.index.get_level_values('condition'))
Index(['a', 'b', 'a', 'c'], dtype='object', name='condition')
print (tmp.index.get_level_values('condition') == 'a')
[ True False True False]
print (tmp[tmp.index.get_level_values('condition') == 'a'])
participant_id condition
1 a 4
3 a 1
dtype: int64
</code></pre>
| 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). It has a lot of strings and stuff I don't want to see when I'm working on the third script which is the program itself, i.e. the script that actually does something with all of the above.</p>
<p>The only way I got this to work was to add, in the 'setup.py' script:</p>
<pre><code>from classes import *
</code></pre>
<p>This allows me to write quickly in the setup file without having the namespace added everywhere. And, in the main script:</p>
<pre><code>import setup
</code></pre>
<p>This has the advantages of PyCharm giving me full code completion for classes and methods, which is nice.</p>
<p>What I'd like to achieve is having the main script import the classes, and then run the setup script to create the objects I need, with two simple commands. But I can't import the classes script into the main script because then the setup script can't do anything, having no class definitions. Should I import the classes into both scripts, or do something else entirely?</p>
| 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 possible to write a language where namespaces are stacked the way you expect them to: this is called dynamic scoping. Some languages like the original lisp, early versions of perl, postscript, etc. do use (or support) dynamic scoping.</p>
<p>Most languages use lexical scoping instead. It turns out this is a much nicer way for languages to work: this way a module can reason about how it will work based on its own code without having to worry about how it was called.</p>
<p>See this article for additional details: <a href="http://en.wikipedia.org/wiki/Scope_%28programming%29" rel="nofollow">http://en.wikipedia.org/wiki/Scope_%28programming%29</a></p>
</blockquote>
<p>Intuitively this feels nicer too, as you can immediately (in the file itself) see which dependencies the code has - this will allow you to understand your code much better, a month, or even a year from now.</p>
| 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>
<p>Lists are always of length 4. 1st is method, 2nd is its argument, 3rd is return value, 4th is always None. I already used regex to solve a similar problem (someone produced the parser) but I need help writing the formatting string:</p>
<p>See <a href="http://stackoverflow.com/questions/39131755/removing-six-b-from-multiple-files">Removing six.b from multiple files</a> . This is the code I used before, the formatting expression needs to be rewritten and I dont speak regex. :(</p>
<pre><code>import re
import os
indir = 'files'
for root, dirs, files in os.walk(indir):
for f in files:
fname = os.path.join(root, f)
with open(fname) as f:
txt = f.read()
txt = re.sub(r'six\.(b\("[^"]*"\))', r'\1', txt)
with open(fname, 'w') as f:
f.write(txt)
print(fname)
</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(map(str.strip, line.strip().strip(",[]").split(",")))
if len(items) == 4:
if items[1] == "None":
items[1] = ""
if items[3] == "None":
o = "assert {0}({1}) == {2}".format(*items)
else:
if items[1] == "":
o = "assert raises({0}) == {3}".format(*items)
else:
o = "assert raises({0}, {1}) == {3}".format(*items)
f.write(" "+o+"\n")
else:
f.write(line)
processfile(sys.argv[1])
</code></pre>
| 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 in s
if __name__ == "__main__":
val = 346
n = 100000
s = set([x for x in range(n)])
l = [x for x in range(n)]
list_timer = Timer("func_to_test(%s, %s)" % (val, l), "from __main__ import func_to_test")
set_timer = Timer("func_to_test(%s, %s)" % (val, s), "from __main__ import func_to_test")
print(list_timer.timeit(100))
print(set_timer.timeit(100))
</code></pre>
<p>The output is:</p>
<pre><code>0.1953735960000813
0.6675883569996586
</code></pre>
<p>But why <code>in</code> statement for <code>list</code> "has" better performance than <code>set</code>?
I know that it's not, but why there are these results with <code>timeit</code> module?</p>
| 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 in the setup statement, and the issue disappears:</p>
<pre><code>>>> import timeit
>>> timeit.timeit('346 in s', setup='s=list(range(100000))')
9.412489017458922
>>> timeit.timeit('346 in s', setup='s=set(list(range(100000)))')
0.08872845571155352
>>> timeit.timeit('346 in s', setup='s=set(range(100000))')
0.09335872296618675
</code></pre>
| 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 all the number from 0-9 which is divisible by 17. If I input n=2, it means that I need to check all the number between 0-99 inclusive which is divisible by 17. </p>
<p>I would not come up with a general formula which compute the length of n then take the right range of the number which is divisible by 17. </p>
<pre><code>def positive(n):
for n in range(0, 10**n):
if (n%17==0):
print n,
</code></pre>
<p>The above code work with me, but it just print it the number which is divisible by 17. I was wondering how would I count them, so I would know how many numbers are divisible by 17. </p>
| 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 the value 0, which is of course divisible by 17. You can check this with a longer version,</p>
<pre><code>def positive(n):
return len([x for x in range(10**n) if x % 17 == 0])
</code></pre>
| 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)</li>
<li>The else statement prints regardless if the user enters a value that
matches an if statement.</li>
</ol>
<p>What am I doing wrong here?</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? ')
if test1 == 'up':
brightness = brightness + 10
print brightness
if test1 == 'down':
brightness = brightness - 10
print brightness
if test1 == 'on':
brightness = 100
print brightness
if test1 == 'off':
brightness = 0
print brightness
else:
print 'Try again'
print "Good bye!"
</code></pre>
| 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
elif test1 == 'on':
brightness = 100
print brightness
elif test1 == 'off':
brightness = 0
print brightness
else:
print 'Try again'
print "Good bye!"
</code></pre>
| 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)</li>
<li>The else statement prints regardless if the user enters a value that
matches an if statement.</li>
</ol>
<p>What am I doing wrong here?</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? ')
if test1 == 'up':
brightness = brightness + 10
print brightness
if test1 == 'down':
brightness = brightness - 10
print brightness
if test1 == 'on':
brightness = 100
print brightness
if test1 == 'off':
brightness = 0
print brightness
else:
print 'Try again'
print "Good bye!"
</code></pre>
| 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? ')
if test1 == 'up':
brightness = brightness + 10
print brightness
elif test1 == 'down':
brightness = brightness - 10
print brightness
elif test1 == 'on':
brightness = 100
print brightness
elif test1 == 'off':
brightness = 0
print brightness
else:
print 'Try again'
print "Good bye!"
</code></pre>
<p>The code works great, thanks!</p>
| 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, cost):
self.__cost = cost
def get_item(self):
return self.__item
def get_quantity(self):
return self.__quantity
def get_cost(self):
return self.__cost
def get_inventory_value(self):
return (format(self.__quantity * self.__cost, '.2f'))
def __str__(self):
for i in merchandise:
print (self.__item+',', self.__quantity,'@ $'+(format (self.__cost,'.2f')))
import merchandise
def main(_):
def make_list():
for count in range (1,3):
merchandise.set_item("hammer")
merchandise.set_quantity(10)
merchandise.set_cost(14.95)
print(hammer)
hardware = float (input ('Enter a new quantity for hardware '))
jewelry = float (input ('Enter a new cost for jewelry '))
hammer = merchandise.merchandise()
stuff = make_list()
print (stuff)
main()
</code></pre>
<p>I don't know what I am doing wrong I get there error there is no set_item in merchandise. I have tried quite a few things and nothing has worked so far. Am I way off here or is it something stupid.</p>
| -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 is always (except if decorated) implicitly passed as the first argument.</p>
<p>In short, initialize a mechanize instance and then invoke the functions, i.e:</p>
<pre><code>m = merchandise('', 10, 0.0)
m.set_item("hammer")
m.set_quantity(10)
m.set_cost(14.95)
</code></pre>
<p>Note that setting isn't required, you can provide these during initialization:</p>
<pre><code>m = merchandise('hammer', 10, 14.95)
</code></pre>
<p>Also, you can't import in the module you're defining (if that is what you're doing), it will raise an error normally. If it is in different modules make sure you import the actual class too:</p>
<pre><code>from merchandise import merchandise
</code></pre>
| 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 tried multiple variations with solutions involving log and power functions):</p>
<p><strong>Exercise:</strong><br>
Your task is to check wheter a given integer is a perfect power. If it is a perfect power, return a pair m and k with m^k = n as a proof. Otherwise return Nothing, Nil, null, None or your language's equivalent.</p>
<p>Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2, so (3,4) and (9,2) are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it.</p>
<p>The exercise uses Python 3.4.3</p>
<p><strong>My code:</strong></p>
<pre><code>import math
def isPP(n):
for i in range(2 +n%2,n,2):
a = math.log(n,i)
if int(a) == round(a, 1):
if pow(i, int(a)) == n:
return [i, int(a)]
return None
</code></pre>
<p><strong>Question:</strong>
How is it possible that I keep getting incorrect answers for bigger numbers? I read that in Python 3, all ints are treated as "long" from Python 2, i.e. they can be very large and still represented accurately. Thus, since i and int(a) are both ints, shouldn't the pow(i, int(a)) == n be assessed correctly? I'm actually baffled.</p>
| 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>
<p>check this</p>
<pre><code>>>> math.log(170**3,3)
14.02441559235585
>>>
</code></pre>
<p>not even close, the correct method is described here <a href="https://en.wikipedia.org/wiki/Nth_root#Logarithmic_computation" rel="nofollow">Nth root</a></p>
<p>which is: </p>
<p>let x be the number to calculate the Nth root, n said root and r the result, then we get</p>
<p>r<sup>n</sup> = x</p>
<p>take the log in any base from both sides, and solve for r</p>
<p>log<sub>b</sub>( r<sup>n</sup> ) = log<sub>b</sub>( x )</p>
<p>n * log<sub>b</sub>( r ) = log<sub>b</sub>( x )</p>
<p>log<sub>b</sub>( r ) = log<sub>b</sub>( x ) / n</p>
<p>b<sup>log<sub>b</sub>( r ) </sup> = b<sup>log<sub>b</sub>( x ) / n </sup></p>
<p>r = b<sup>log<sub>b</sub>( x ) / n </sup></p>
<p>so for instance with log in base 10 we get</p>
<pre><code>>>> pow(10, math.log10(170**3)/3 )
169.9999999999999
>>>
</code></pre>
<p>that is much more closer, and with just rounding it we get the answer</p>
<pre><code>>>> round(169.9999999999999)
170
>>>
</code></pre>
<p>therefore the function should be something like this</p>
<pre><code>import math
def isPP(x):
for n in range(2, 1+round(math.log2(x)) ):
root = pow( 10, math.log10(x)/n )
result = round(root)
if result**n == x:
return result,n
</code></pre>
<p>the upper limit in range is to avoid testing numbers that will certainly fail</p>
<p>test </p>
<pre><code>>>> isPP(170**3)
(170, 3)
>>> isPP(6434856)
(186, 3)
>>> isPP(9**2)
(9, 2)
>>> isPP(23**8)
(279841, 2)
>>> isPP(279841)
(529, 2)
>>> isPP(529)
(23, 2)
>>>
</code></pre>
<p><strong>EDIT</strong></p>
<p>or as <strong>Tin Peters</strong> point out you can use <code>pow(x,1./n)</code> as the nth root of a number is also expressed as x<sup>1/n</sup></p>
<p>for example</p>
<pre><code>>>> pow(170**3, 1./3)
169.99999999999994
>>> round(_)
170
>>>
</code></pre>
<p>but keep in mind that that will fail for extremely large numbers like for example </p>
<pre><code>>>> pow(8191**107,1./107)
Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
pow(8191**107,1./107)
OverflowError: int too large to convert to float
>>>
</code></pre>
<p>while the logarithmic approach will success</p>
<pre><code>>>> pow(10, math.log10(8191**107)/107)
8190.999999999999
>>>
</code></pre>
<p>the reason is that 8191<sup>107</sup> is simple too big, it have 419 digits which is greater that the maximum float representable, but reducing it with a log produce a more reasonable number</p>
<p><strong>EDIT 2</strong> </p>
<p>now if you want to work with numbers ridiculously big, or just plain don't want to use floating point arithmetic altogether and use only integer arithmetic, then the best course of action is to use the <a href="https://en.wikipedia.org/wiki/Nth_root_algorithm" rel="nofollow">method of Newton</a>, that the helpful <a href="http://stackoverflow.com/questions/35254566/wrong-answer-in-spoj-cubert/35276426#35276426">link</a> provided by <strong>Tin Peters</strong> for the particular case for cube root, show us the way to do it in general alongside the wikipedia article </p>
<pre><code>def inthroot(A,n):
if A<0:
if n%2 == 0:
raise ValueError
return - inthroot(-A,n)
if A==0:
return 0
n1 = n-1
if A.bit_length() < 1024: # float(n) safe from overflow
xk = int( round( pow(A,1/n) ) )
xk = ( n1*xk + A//pow(xk,n1) )//n # Ensure xk >= floor(nthroot(A)).
else:
xk = 1 << -(-A.bit_length()//n) # power of 2 closer but greater than the nth root of A
while True:
sig = A // pow(xk,n1)
if xk <= sig:
return xk
xk = ( n1*xk + sig )//n
</code></pre>
<p>check the explanation by <strong><a href="http://stackoverflow.com/questions/35254566/wrong-answer-in-spoj-cubert/35276426#35276426">Mark Dickinson</a></strong> to understand the working of the algorithm for the case of cube root, which is basically the same for this </p>
<p>now lets compare this with the other one</p>
<pre><code>>>> def nthroot(x,n):
return pow(10, math.log10(x)/n )
>>> n = 2**(2**12) + 1 # a ridiculously big number
>>> r = nthroot(n**2,2)
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
nthroot(n**2,2)
File "<pyshell#47>", line 2, in nthroot
return pow(10, math.log10(x)/n )
OverflowError: (34, 'Result too large')
>>> r = inthroot(n**2,2)
>>> r == n
True
>>>
</code></pre>
<p>then the function is now</p>
<pre><code>import math
def isPPv2(x):
for n in range(2,1+round(math.log2(x))):
root = inthroot(x,n)
if root**n == x:
return root,n
</code></pre>
<p>test</p>
<pre><code>>>> n = 2**(2**12) + 1 # a ridiculously big number
>>> r,p = isPPv2(n**23)
>>> p
23
>>> r == n
True
>>> isPPv2(170**3)
(170, 3)
>>> isPPv2(8191**107)
(8191, 107)
>>> isPPv2(6434856)
(186, 3)
>>>
</code></pre>
<p>now lets check isPP vs isPPv2</p>
<pre><code>>>> x = (1 << 53) + 1
>>> x
9007199254740993
>>> isPP(x**2)
>>> isPPv2(x**2)
(9007199254740993, 2)
>>>
</code></pre>
<p>clearly, avoiding floating point is the best choice </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 correctly, I'm receiving the following error:</p>
<pre><code>line 41, in <module>
tom.sacrifice()
AttributeError: 'Samurai' object has no attribute 'sacrifice'
</code></pre>
<p>Here's the code from my <code>my_project/new_classes.py</code> file:</p>
<pre><code>from human.Human import Human
class Wizard(Human):
def __init__(self):
super(Wizard, self).__init__()
self.intelligence = 10
def heal(self):
self.health += 10
class Ninja(Human):
def __init__(self):
super(Ninja, self).__init__()
self.stealth = 10
def steal(self):
self.stealth += 5
class Samurai(Human):
def __init__(self):
super(Samurai, self).__init__()
self.strength = 10
def sacrifice(self):
self.health -= 5
# create new instance of Wizard, Ninja, and Samurai
harry = Wizard()
rain = Ninja()
tom = Samurai()
print harry.health
print rain.health
print tom.health
harry.heal()
print harry.health
rain.steal()
print rain.stealth
tom.sacrifice()
print tom.health
print tom.stealth
</code></pre>
<p>The code breaks when it gets to line <code>tom.sacrifice()</code> - any ideas why?</p>
<p>One other question I had was at first, when trying to import the parent class, I was using the statement <code>from human import Human</code>, which I thought would work (as I thought the formula was from <code>module_directory import ModuleFileName</code>, but was receiving an error as follows: <code>TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given)</code>. I resolved this by changing my import statement to, <code>from human.Human import Human</code> and was wondering <em>why</em> this worked while the other did not? I may be confused about correctly importing classes and was hoping someone also might be able to help clarify.</p>
<p>[EDIT] Removed comments.</p>
| 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 statement must be as you wrote last. You do not want to import the module, but the class.</p>
<p>As to your <code>AttributeError</code> problem, it's odd as your classes seem OK. It's probably something unusual inside the Human class. Can we have the code in it?</p>
<p><strong>EDIT</strong></p>
<p>I see you found the solution for the <code>AttributeError</code> problem so I'll leave the answer for the second problem only.</p>
| 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 correctly, I'm receiving the following error:</p>
<pre><code>line 41, in <module>
tom.sacrifice()
AttributeError: 'Samurai' object has no attribute 'sacrifice'
</code></pre>
<p>Here's the code from my <code>my_project/new_classes.py</code> file:</p>
<pre><code>from human.Human import Human
class Wizard(Human):
def __init__(self):
super(Wizard, self).__init__()
self.intelligence = 10
def heal(self):
self.health += 10
class Ninja(Human):
def __init__(self):
super(Ninja, self).__init__()
self.stealth = 10
def steal(self):
self.stealth += 5
class Samurai(Human):
def __init__(self):
super(Samurai, self).__init__()
self.strength = 10
def sacrifice(self):
self.health -= 5
# create new instance of Wizard, Ninja, and Samurai
harry = Wizard()
rain = Ninja()
tom = Samurai()
print harry.health
print rain.health
print tom.health
harry.heal()
print harry.health
rain.steal()
print rain.stealth
tom.sacrifice()
print tom.health
print tom.stealth
</code></pre>
<p>The code breaks when it gets to line <code>tom.sacrifice()</code> - any ideas why?</p>
<p>One other question I had was at first, when trying to import the parent class, I was using the statement <code>from human import Human</code>, which I thought would work (as I thought the formula was from <code>module_directory import ModuleFileName</code>, but was receiving an error as follows: <code>TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given)</code>. I resolved this by changing my import statement to, <code>from human.Human import Human</code> and was wondering <em>why</em> this worked while the other did not? I may be confused about correctly importing classes and was hoping someone also might be able to help clarify.</p>
<p>[EDIT] Removed comments.</p>
| 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
self.strength = 15
</code></pre>
<p>You have to initialize the variables. Make sure that every <code>Human</code> has the properties that you would want to change. You can probably set <code>=</code> the health, but not change <code>-=5</code> it if it was not initialized.</p>
| 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 correctly, I'm receiving the following error:</p>
<pre><code>line 41, in <module>
tom.sacrifice()
AttributeError: 'Samurai' object has no attribute 'sacrifice'
</code></pre>
<p>Here's the code from my <code>my_project/new_classes.py</code> file:</p>
<pre><code>from human.Human import Human
class Wizard(Human):
def __init__(self):
super(Wizard, self).__init__()
self.intelligence = 10
def heal(self):
self.health += 10
class Ninja(Human):
def __init__(self):
super(Ninja, self).__init__()
self.stealth = 10
def steal(self):
self.stealth += 5
class Samurai(Human):
def __init__(self):
super(Samurai, self).__init__()
self.strength = 10
def sacrifice(self):
self.health -= 5
# create new instance of Wizard, Ninja, and Samurai
harry = Wizard()
rain = Ninja()
tom = Samurai()
print harry.health
print rain.health
print tom.health
harry.heal()
print harry.health
rain.steal()
print rain.stealth
tom.sacrifice()
print tom.health
print tom.stealth
</code></pre>
<p>The code breaks when it gets to line <code>tom.sacrifice()</code> - any ideas why?</p>
<p>One other question I had was at first, when trying to import the parent class, I was using the statement <code>from human import Human</code>, which I thought would work (as I thought the formula was from <code>module_directory import ModuleFileName</code>, but was receiving an error as follows: <code>TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given)</code>. I resolved this by changing my import statement to, <code>from human.Human import Human</code> and was wondering <em>why</em> this worked while the other did not? I may be confused about correctly importing classes and was hoping someone also might be able to help clarify.</p>
<p>[EDIT] Removed comments.</p>
| 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__ method
self.strength = 10 # every Samurai starts off with 10 strength
def sacrifice(self):
self.health -= 5
</code></pre>
| 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:
return str("Wrong!")
print("Time for a quiz.")
print("What is ((((6^2 * 10) + sqrt((5000*3) - 600)) / 4! ) * 4 ) - log(1 * 10^11)?")
userAnswer = int(input())
question1 = Quiz(userAnswer, 69)
Quiz.yesno()
</code></pre>
| -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:
return str("Wrong!")
print("Time for a quiz.")
print("What is ((((6^2 * 10) + sqrt((5000*3) - 600)) / 4! ) * 4 ) - log(1 * 10^11)?")
userAnswer = int(input())
question1 = Quiz(userAnswer, 69)
Quiz.yesno()
</code></pre>
| -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):
if self.answer == self.question:
return str("Correct!")
else:
return str("Wrong!")
</code></pre>
<p>Should actually be:</p>
<pre><code>def yesno(self):
if self.answer == self.question:
return str("Correct!")
else:
return str("Wrong!")
</code></pre>
| 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(object):
""" Class provides a structure to store Movie information """
def __init__(self, imdb_id, title = None, release_year = None, rating = None, run_time = None, genre = None, director = None, actors = None, plot = None, awards = None, poster_image = None, imdb_votes = None, youtube_trailer = None):
self.imdb_id = imdb_id,
self.title = title,
self.release_year = release_year
self.rating = rating,
self.run_time = run_time,
self.genre = genre,
self.director = director,
self.actors = actors,
self.plot = plot,
self.awards = awards,
self.poster_image = poster_image,
self.imdb_votes = imdb_votes,
self.youtube_trailer = youtube_trailer
</code></pre>
<p>Here is how I am initiating the class:</p>
<pre><code>import media
toy_story=media.Movie("trtreter")
toy_story.imdb_id
</code></pre>
| -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 number of instruction the lesser will be the size of the image. So I have kept it minimal.</p>
<p>What am I doing wrong?? and what is the best way to create a light dockerimage for python.</p>
<pre><code>FROM ubuntu:14.04
RUN apt-get update && apt-get install -y -q curl \
build-essential \
python-dev \
python-pip \
vim \
wget && \
apt-get autoremove -y && \
apt-get clean && \
apt-get autoclean && \
echo -n > /var/lib/apt/extended_states && \
rm -rf /var/lib/apt/lists/* && \
rm -rf /usr/share/man/?? && \
rm -rf /usr/share/man/??_*
</code></pre>
| -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 virtual machines. They all share the kernel of the host machine. As @RobKielty states "Linux is Linux".</p>
<p>Fact is if your application has very few dependencies (for example go programs) then the extra size of the base image is simply redundancy. The use of alternative base images like Alpine is driven by a desire for faster downloads, but it also has security benefits too. It eliminates unused packages that would otherwise need to be patched. However... it's not a free lunch because using Alpine means more effort installing dependencies (that would already exist in a larger image like Ubuntu)</p>
<p>In conclusion I would refer you to the community python image. If you look carefully there are several available image tags, using python built on top of a variety of base images. Might save you a lot of effort.</p>
<p><a href="https://hub.docker.com/_/python/" rel="nofollow">https://hub.docker.com/_/python/</a></p>
<p>Hope this helps.</p>
| 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,)
</code></pre>
| 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)
</code></pre>
<p>and the result can be easily rearranged to be a column matrix.</p>
| 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,)
</code></pre>
| 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],
[9, 1, 5]])
</code></pre>
<p>If your array of indices to select is</p>
<pre><code>indices = numpy.array([2, 0, 1])
</code></pre>
<p>Then</p>
<pre><code>rowSelector = numpy.arange(myArray.shape[0])
myArray[rowSelector, indices]
</code></pre>
<p>returns the values of the selected elements of the array:</p>
<pre><code>array([4, 6, 1])
</code></pre>
| 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 shell, </p>
<pre><code>input tap 1000 1500
</code></pre>
<p>and it works great. But how do I achieve the same using the Python script?</p>
<p><a href="http://i.stack.imgur.com/YaOsU.png" rel="nofollow"><img src="http://i.stack.imgur.com/YaOsU.png" alt="enter image description here"></a> </p>
<p>Even just a way to execute this via the selenium script would be OK for me</p>
<pre><code>input tap 1000 1500
</code></pre>
<p>Something like self.driver.execute("adb shell input tap 1000 1500");</p>
| 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 how to click on a pair coordinates, as you can see, you need to use an element as reference.</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox() //Or whichever browser you prefer
driver.get("your url")
reference=driver.find_elements_by_xpath("Your xpath here")
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(reference, X, Y)
action.click()
action.perform()
</code></pre>
<p>Since you need to locate an element as reference anyway, why not simply click on this element directly without using coordinates?</p>
| 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 shell, </p>
<pre><code>input tap 1000 1500
</code></pre>
<p>and it works great. But how do I achieve the same using the Python script?</p>
<p><a href="http://i.stack.imgur.com/YaOsU.png" rel="nofollow"><img src="http://i.stack.imgur.com/YaOsU.png" alt="enter image description here"></a> </p>
<p>Even just a way to execute this via the selenium script would be OK for me</p>
<pre><code>input tap 1000 1500
</code></pre>
<p>Something like self.driver.execute("adb shell input tap 1000 1500");</p>
| 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 columns to record and plot data only for the required time span. </p>
<p>I already have some code which does the job for me for 0-70s:</p>
<pre><code>import matplotlib
matplotlib.use('Agg')
import os
import numpy as np
import matplotlib.pyplot as plt
import string
import math
# reads from flash.dat
def getQuantity(folder, basename, varlist):
# quantities[0] should contain only the quantities of varlist[0]
quantities =[]
for i in range(len(varlist)):
quantities.append([])
with open(folder + "/" + basename + ".dat", 'r') as f: # same as f = open(...) but closes the file afterwards.
for line in f:
if not ('#' or 'Inf') in line: # the first line and restarting lines look like this.
for i in range(len(varlist)):
if(varlist[i]==NUCLEAR_ENERGY and len(quantities[i])>0):
quantities[i].append(float(line.split()[varlist[i]])+quantities[i][-1])
else:
quantities[i].append(float(line.split()[varlist[i]]))
return quantities
# end def getQuantity
#create plot
plt.figure(1)
TIME = 0
NUCLEAR_ENERGY = 18
labels = ["time", "Nuclear Energy"]
flashFolder1 = '/home/trina/Pictures' # should be the flash NOT the flash/object folder.
lab1 = '176'
filename = 'flash' # 'flash' for flash.dat
nHorizontal = 1 # number of Plots in Horizontal Direction. Vertical Direction is set by program.
outputFilename = 'QuantityPlots_Nuclear.png'
variables = [NUCLEAR_ENERGY]
#Adjustments to set the size
nVertical = math.ceil(float(len(variables))/nHorizontal) # = 6 for 16 = len(variables) & nHorizontal = 3.
F = plt.gcf() #get figure
DPI = F.get_dpi()
DefaultSize = F.get_size_inches()
F.set_size_inches( DefaultSize[0]*nHorizontal, DefaultSize[1]*nVertical ) #build no of subplots in figure
variables.insert(0,TIME) # time as needed as well
data1 = getQuantity(flashFolder1, filename, variables)
time1 = np.array(data1[0]) #time is first column
for n in [n+1 for n in range(len(variables)-1)]: #starts at 1
ax=plt.subplot(nVertical, nHorizontal, n) #for example (6,3,0 to 15) inside loop for 16 variables
if (min(data1[n])<0.0 or abs((min(data1[n]))/(max(data1[n])))>=1.e-2):
plt.plot(time1, data1[n],label=lab1) #, label = labels[variables[n]])
legend = ax.legend(loc='upper right', frameon=False)
else:
plt.semilogy(time1, data1[n],label=lab1) #, label = labels[variables[n]])
legend = ax.legend(loc='upper right', frameon=False)
plt.savefig(outputFilename)
</code></pre>
<p>Here is the figure I can produce from this code:</p>
<p><a href="http://i.stack.imgur.com/23vmx.png" rel="nofollow"><img src="http://i.stack.imgur.com/23vmx.png" alt="enter image description here"></a></p>
<p>and for your convenience I am also sharing the <code>.dat</code> file:</p>
<p><a href="https://www.dropbox.com/s/w4jbxmln9e83355/flash.dat?dl=0" rel="nofollow">https://www.dropbox.com/s/w4jbxmln9e83355/flash.dat?dl=0</a></p>
<p>Your suggestions are most appreciated.</p>
| 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.stack.imgur.com/mhF6z.png" alt="enter image description here"></a></p>
<p><strong>Old answer:</strong></p>
<p>Using Pandas module</p>
<pre><code>import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
fn = r'D:\temp\.data\flash.dat'
df = pd.read_csv(fn, sep='\s+', usecols=[0, 18], header=None, skiprows=[0], na_values=['Infinity'])
df.columns=['time', 'Nuclear_Energy']
df.query('25 <= time <= 35').set_index('time').plot(figsize=(12,10))
plt.show()
plt.savefig('d:/temp/out.png')
</code></pre>
<p><strong>Result:</strong></p>
<p><a href="http://i.stack.imgur.com/uQkCt.png" rel="nofollow"><img src="http://i.stack.imgur.com/uQkCt.png" alt="enter image description here"></a></p>
<p>Explanation:</p>
<pre><code>In [43]: pd.options.display.max_rows
Out[43]: 50
In [44]: pd.options.display.max_rows = 12
In [45]: df
Out[45]:
time Nuclear_Energy
0 0.000000e+00 0.000000e+00
1 1.000000e-07 -4.750169e+29
2 2.200000e-07 -5.699325e+29
3 3.640000e-07 -6.838392e+29
4 5.368000e-07 -8.206028e+29
5 7.441600e-07 -9.837617e+29
... ... ...
10210 6.046702e+01 7.160630e+44
10211 6.047419e+01 7.038907e+44
10212 6.048137e+01 6.934600e+44
10213 6.048856e+01 6.847015e+44
10214 6.049577e+01 6.765220e+44
10215 6.050298e+01 6.661930e+44
[10216 rows x 2 columns]
In [46]: df.query('25 <= time <= 35')
Out[46]:
time Nuclear_Energy
4534 25.001663 1.559398e+43
4535 25.006781 1.567793e+43
4536 25.011900 1.575844e+43
4537 25.017021 1.583984e+43
4538 25.022141 1.592015e+43
4539 25.027259 1.600200e+43
... ... ...
6521 34.966427 8.181516e+41
6522 34.972926 8.538806e+41
6523 34.979425 8.913695e+41
6524 34.985925 9.304403e+41
6525 34.992429 9.731310e+41
6526 34.998941 1.019862e+42
[1993 rows x 2 columns]
In [47]: df.query('25 <= time <= 35').set_index('time')
Out[47]:
Nuclear_Energy
time
25.001663 1.559398e+43
25.006781 1.567793e+43
25.011900 1.575844e+43
25.017021 1.583984e+43
25.022141 1.592015e+43
25.027259 1.600200e+43
... ...
34.966427 8.181516e+41
34.972926 8.538806e+41
34.979425 8.913695e+41
34.985925 9.304403e+41
34.992429 9.731310e+41
34.998941 1.019862e+42
[1993 rows x 1 columns]
</code></pre>
| 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, the photos are inside a <code><div class "photo-list-photo-interaction"></code>. So above <code>soup.select</code> should have worked. But it doesn't. Any ideas?</p>
| -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_true__requiredToShowOnServer_true__subnavConfig_1"><div class="view photo-list-photo-view requiredToShowOnServer awake" style="transform: translate(0px, 4px); -webkit-transform: translate(0px, 4px); -ms-transform: translate(0px, 4px); width: 564px; height: 305px; background-image: url(//c6.staticflickr.com/9/8279/29103697453_ca811d0e07_z.jpg)" data-view-signature="photo-list-photo-view__UA_1__contextSuffix_explore-2016-09-17__engagementModelName_photo-lite-models__exploreId_2016-09-17__id_29103697453__interactionViewName_photo-list-photo-interaction-view__isMobile_false__isOwner_false__layoutItem_1__measureAFT_true__model_1__parentContainer_1__parentSignature_photolist-232__photoListLayoutStyle_justified__requiredToShowOnClient_true__requiredToShowOnServer_true__subnavConfig_1">
</code></pre>
<p>The urls you see in your browsers are dynamically created using css. Insoide the div you can see <code>background-image: url(//c6.staticflickr.com/9/8279/29103697453_ca811d0e07_z.jpg)</code> so that is what you need to get. </p>
<p>You can do it using a css selector with a regex:</p>
<pre><code>In [1]: import requests
In [2]: from bs4 import BeautifulSoup
In [3]: import re
In [4]: url_re = re.compile("url\(//(.*?)\)")
In [5]: res = requests.get('https://www.flickr.com/photos/')
In [6]: soup = BeautifulSoup(res.text, 'html.parser')
In [7]: urls = [url_re.search(d["style"]).group(1) for d in soup.select('div.view.photo-list-view div[style*=url(//]')]
In [8]: print(urls)
[u'c1.staticflickr.com/9/8385/29133157664_856aef9bc3_n.jpg', u'c5.staticflickr.com/9/8212/29128075804_0c166556c5_n.jpg', u'c3.staticflickr.com/9/8070/29138685794_984cf0a7f2.jpg', u'c3.staticflickr.com/9/8084/29465161650_4a1a160928.jpg', u'c5.staticflickr.com/9/8202/29642526492_357d7da694_n.jpg', u'c8.staticflickr.com/9/8164/29769287735_6523928d3d.jpg', u'c5.staticflickr.com/9/8313/29722500236_76d7bdbdd8.jpg', u'c8.staticflickr.com/9/8580/29776721935_f1ce85e967_n.jpg', u'c3.staticflickr.com/9/8364/29731556026_1f9d166845.jpg', u'c3.staticflickr.com/9/8178/29726200506_4439500c3d.jpg', u'c4.staticflickr.com/9/8405/29138108963_288aa48d06.jpg', u'c4.staticflickr.com/9/8565/29137949003_fb41535bd6.jpg', u'c5.staticflickr.com/9/8109/29735723636_0e494810a2.jpg', u'c3.staticflickr.com/9/8482/29662415042_5b0d05c8f3.jpg', u'c1.staticflickr.com/9/8346/29726788896_8c293fbdf7.jpg', u'c3.staticflickr.com/9/8524/29725439906_2b067f0212.jpg', u'c6.staticflickr.com/9/8303/29140293093_e355f8e8cd.jpg', u'c3.staticflickr.com/9/8011/29477607810_db00655d55.jpg', u'c1.staticflickr.com/9/8227/29465026920_36ab1c9637.jpg', u'c2.staticflickr.com/9/8014/29770085625_5163a499d1.jpg', u'c1.staticflickr.com/9/8090/29719718136_5f5ab26519.jpg', u'c1.staticflickr.com/9/8198/29645435472_f5284dedfd.jpg', u'c1.staticflickr.com/9/8692/29469829440_4481cea5e2.jpg', u'c4.staticflickr.com/9/8126/29142193643_f7a2100439.jpg', u'c3.staticflickr.com/9/8395/29646613162_8bbfcb4783.jpg', u'c1.staticflickr.com/9/8182/29482891560_66a7453201.jpg', u'c6.staticflickr.com/9/8078/29137768373_f8c8ebc474.jpg', u'c4.staticflickr.com/9/8142/29754486795_5517360b29.jpg', u'c1.staticflickr.com/9/8276/29138669944_c94fb64f7e.jpg', u'c7.staticflickr.com/9/8189/29658148142_44845e5842.jpg', u'c3.staticflickr.com/9/8168/29724488906_dd17d56015_n.jpg', u'c1.staticflickr.com/9/8450/29727877336_b9d852bc7b.jpg', u'c7.staticflickr.com/8/7471/29129926854_ceff45aaeb.jpg', u'c4.staticflickr.com/9/8298/29690071131_5a7589870d.jpg', u'c8.staticflickr.com/9/8003/29131670143_9cb629648a.jpg', u'c3.staticflickr.com/9/8022/29722826586_c07240a926_n.jpg', u'c3.staticflickr.com/9/8332/29663153602_c9364a94ac.jpg', u'c4.staticflickr.com/9/8219/29767151515_3c9c12d47a.jpg', u'c6.staticflickr.com/9/8475/29675880341_baa5c43403.jpg', u'c5.staticflickr.com/9/8246/29646906852_ff44a93f55_n.jpg', u'c2.staticflickr.com/9/8113/29141997673_64184d61fd_n.jpg', u'c7.staticflickr.com/9/8517/29131116894_1319f5a4af.jpg', u'c5.staticflickr.com/9/8169/29472205700_4930f81031_n.jpg', u'c3.staticflickr.com/9/8051/29466854090_804671e48d.jpg', u'c4.staticflickr.com/9/8459/29772050115_0d602920a9_n.jpg', u'c6.staticflickr.com/9/8413/29762049765_951f4c683c_n.jpg', u'c8.staticflickr.com/9/8480/29132401623_50619e22c5_n.jpg', u'c7.staticflickr.com/9/8410/29482793550_8b338c8432_z.jpg', u'c6.staticflickr.com/8/7501/29693717381_dd907ac02a.jpg']
</code></pre>
| 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 transforms the data in wide format. When I try to plot with matplotlib, I get an error </p>
<pre><code>ValueError: could not convert string to float: 'ZAF'
</code></pre>
<p>(where 'ZAF' is the label of one country)</p>
<p>What's the problem?</p>
<p>This is the code:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_excel('raw_emissions_energy.xls','raw data', index_col = None, thousands='.',parse_cols="A,C,F,M")
data['Year'] = data['Year'].astype(str)
data['COU'] = data['COU'].astype(str)
# generate sub-datasets for specific VARs
data_CO2PROD = pd.pivot_table(data[(data['VAR']=='CO2_PBPROD')], index='COU', columns='Year')
plt.plot(data_CO2PROD)
</code></pre>
<p>The xls file with raw data looks like:
<a href="http://i.stack.imgur.com/T1bom.png" rel="nofollow">raw data Excel view</a></p>
<p><a href="http://i.stack.imgur.com/5shnZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/5shnZ.png" alt="enter image description here"></a></p>
<p>This is what I get from data_CO2PROD.info()</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
Index: 105 entries, ARE to ZAF
Data columns (total 16 columns):
(Value, 1990) 104 non-null float64
(Value, 1995) 105 non-null float64
(Value, 2000) 105 non-null float64
(Value, 2001) 105 non-null float64
(Value, 2002) 105 non-null float64
(Value, 2003) 105 non-null float64
(Value, 2004) 105 non-null float64
(Value, 2005) 105 non-null float64
(Value, 2006) 105 non-null float64
(Value, 2007) 105 non-null float64
(Value, 2008) 105 non-null float64
(Value, 2009) 105 non-null float64
(Value, 2010) 105 non-null float64
(Value, 2011) 105 non-null float64
(Value, 2012) 105 non-null float64
(Value, 2013) 105 non-null float64
dtypes: float64(16)
memory usage: 13.9+ KB
None
</code></pre>
| 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','Year','VAL'])
data['VAR'] = ['CC','CC','KK']
data['COU'] =['ZAF','NL','DK']
data['Year']=['1987','1987','2006']
data['VAL'] = [32,33,35]
data['Year'] = data['Year'].astype(str)
data['COU'] = data['COU'].astype(str)
# generate sub-datasets for specific VARs
data_CO2PROD = pd.pivot_table(data=data[(data['VAR']=='CC')], index='COU', columns='Year')
data_CO2PROD.plot()
plt.show()
</code></pre>
| 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 transforms the data in wide format. When I try to plot with matplotlib, I get an error </p>
<pre><code>ValueError: could not convert string to float: 'ZAF'
</code></pre>
<p>(where 'ZAF' is the label of one country)</p>
<p>What's the problem?</p>
<p>This is the code:</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_excel('raw_emissions_energy.xls','raw data', index_col = None, thousands='.',parse_cols="A,C,F,M")
data['Year'] = data['Year'].astype(str)
data['COU'] = data['COU'].astype(str)
# generate sub-datasets for specific VARs
data_CO2PROD = pd.pivot_table(data[(data['VAR']=='CO2_PBPROD')], index='COU', columns='Year')
plt.plot(data_CO2PROD)
</code></pre>
<p>The xls file with raw data looks like:
<a href="http://i.stack.imgur.com/T1bom.png" rel="nofollow">raw data Excel view</a></p>
<p><a href="http://i.stack.imgur.com/5shnZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/5shnZ.png" alt="enter image description here"></a></p>
<p>This is what I get from data_CO2PROD.info()</p>
<pre><code><class 'pandas.core.frame.DataFrame'>
Index: 105 entries, ARE to ZAF
Data columns (total 16 columns):
(Value, 1990) 104 non-null float64
(Value, 1995) 105 non-null float64
(Value, 2000) 105 non-null float64
(Value, 2001) 105 non-null float64
(Value, 2002) 105 non-null float64
(Value, 2003) 105 non-null float64
(Value, 2004) 105 non-null float64
(Value, 2005) 105 non-null float64
(Value, 2006) 105 non-null float64
(Value, 2007) 105 non-null float64
(Value, 2008) 105 non-null float64
(Value, 2009) 105 non-null float64
(Value, 2010) 105 non-null float64
(Value, 2011) 105 non-null float64
(Value, 2012) 105 non-null float64
(Value, 2013) 105 non-null float64
dtypes: float64(16)
memory usage: 13.9+ KB
None
</code></pre>
| 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()
plt.show()
</code></pre>
| 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 (nullable = true)
</code></pre>
<p>I would like to add one more StructField to the schema, so the new schema would looks like:</p>
<pre><code>root
|-- field_1: double (nullable = true)
|-- 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 (nullable = true)
</code></pre>
<p>I know I can manually create a new_schema like below:</p>
<pre><code>new_schema = StructType([StructField("field_0", StringType(), True),
:
StructField("field_6", IntegerType(), True)])
</code></pre>
<p>This works for a small number of fields but couldn't generate if I have hundreds of fields. So I am wondering is there a more elegant way to add a new field to the beginning of the schema? Thanks!</p>
| 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 (rectangular form) and should be >= 0 and <= 5</li>
<li>values inside sublists cannot be more than or equal to the total number of sublists. In other words, each value inside a sublist is an integer >= 0 and < <code>N</code></li>
</ol>
<p>Sample valid inputs:</p>
<pre><code>[[0]]
[[2, 1], [2, 0], [3, 1], [1, 0]]
[[1], [0]]
</code></pre>
<p>Sample invalid inputs:</p>
<pre><code>[[2]] # 2 is more than N=1 (total number of sublists)
[[0, 1], [2, 0]] # 2 is equal to N=2 (total number of sublists)
</code></pre>
<p>I'm trying to approach it with <em>property-based-testing</em> and generate different valid inputs with <a href="http://hypothesis.readthedocs.io/en/latest/index.html"><code>hypothesis</code> library</a> and trying to wrap my head around <code>lists()</code> and <code>integers()</code>, but cannot make it work:</p>
<ul>
<li>the condition #1 is easy to approach with <code>lists()</code> and <code>min_size</code> and <code>max_size</code> arguments</li>
<li>the condition #2 is covered under <a href="http://hypothesis.readthedocs.io/en/latest/data.html#chaining-strategies-together"><code>Chaining strategies together</code></a></li>
<li>the condition #3 is what I'm struggling with - cause, if we use the <code>rectangle_lists</code> from the above example, we don't have a reference to the length of the "parent" list inside <code>integers()</code> </li>
</ul>
<p><strong>The Question:</strong></p>
<p>How can I limit the integer values inside sublists to be less than the total number of sublists?</p>
<hr>
<p>Some of my attempts:</p>
<pre><code>from hypothesis import given
from hypothesis.strategies import lists, integers
@given(lists(lists(integers(min_value=0, max_value=5), min_size=1, max_size=5), min_size=1, max_size=50))
def test(l):
# ...
</code></pre>
<p>This one was very far from meeting the requirements - list is not strictly of a rectangular form and generated integer values can go over the generated size of the list.</p>
<pre><code>from hypothesis import given
from hypothesis.strategies import lists, integers
@given(integers(min_value=0, max_value=5).flatmap(lambda n: lists(lists(integers(min_value=1, max_value=5), min_size=n, max_size=n), min_size=1, max_size=50)))
def test(l):
# ...
</code></pre>
<p>Here, the #1 and #2 are requirements were being met, but the integer values can go larger than the size of the list - requirement #3 is not met.</p>
| 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 don't quite work) to make it satisfy the constraints.</p>
<p>For your case, you could do something like the following:</p>
<pre><code>from hypothesis.strategies import builds, lists, integers
def prune_list(ls):
n = len(ls)
return [
[i for i in sublist if i < n][:5]
for sublist in ls
]
limited_list_strategy = builds(
prune_list,
lists(lists(integers(0, 49), average_size=5), max_size=50, min_size=1)
)
</code></pre>
<p>In this we:</p>
<ol>
<li>Generate a list that looks roughly right (it's a list of list of integers and the integers are in the same range as all <em>possible</em> indices that could be valid).</li>
<li>Prune out any invalid indices from the sublists</li>
<li>Truncate any sublists that still have more than 5 elements in them</li>
</ol>
<p>The result should satisfy all three conditions you needed.</p>
<p>The average_size parameter isn't strictly necessary but in experimenting with this I found it was a bit too prone to producing empty sublists otherwise. </p>
<p>ETA: Apologies. I've just realised that I misread one of your conditions - this doesn't actually do quite what you want because it doesn't ensure each list is the same length. Here's a way to modify this to fix that (it gets a bit more complicated, so I've switched to using composite instead of builds):</p>
<pre><code>from hypothesis.strategies import composite, lists, integers, permutations
@composite
def limisted_lists(draw):
ls = draw(
lists(lists(integers(0, 49), average_size=5), max_size=50, min_size=1)
)
filler = draw(permutations(range(50)))
sublist_length = draw(integers(0, 5))
n = len(ls)
pruned = [
[i for i in sublist if i < n][:sublist_length]
for sublist in ls
]
for sublist in pruned:
for i in filler:
if len(sublist) == sublist_length:
break
elif i < n:
sublist.append(i)
return pruned
</code></pre>
<p>The idea is that we generate a "filler" list that provides the defaults for what a sublist looks like (so they will tend to shrink in the direction of being more similar to eachother) and then draw the length of the sublists to prune to to get that consistency.</p>
<p>This has got pretty complicated I admit. You might want to use RecursivelyIronic's flatmap based version. The main reason I prefer this over that is that it will tend to shrink better, so you'll get nicer examples out of it.</p>
| 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 (rectangular form) and should be >= 0 and <= 5</li>
<li>values inside sublists cannot be more than or equal to the total number of sublists. In other words, each value inside a sublist is an integer >= 0 and < <code>N</code></li>
</ol>
<p>Sample valid inputs:</p>
<pre><code>[[0]]
[[2, 1], [2, 0], [3, 1], [1, 0]]
[[1], [0]]
</code></pre>
<p>Sample invalid inputs:</p>
<pre><code>[[2]] # 2 is more than N=1 (total number of sublists)
[[0, 1], [2, 0]] # 2 is equal to N=2 (total number of sublists)
</code></pre>
<p>I'm trying to approach it with <em>property-based-testing</em> and generate different valid inputs with <a href="http://hypothesis.readthedocs.io/en/latest/index.html"><code>hypothesis</code> library</a> and trying to wrap my head around <code>lists()</code> and <code>integers()</code>, but cannot make it work:</p>
<ul>
<li>the condition #1 is easy to approach with <code>lists()</code> and <code>min_size</code> and <code>max_size</code> arguments</li>
<li>the condition #2 is covered under <a href="http://hypothesis.readthedocs.io/en/latest/data.html#chaining-strategies-together"><code>Chaining strategies together</code></a></li>
<li>the condition #3 is what I'm struggling with - cause, if we use the <code>rectangle_lists</code> from the above example, we don't have a reference to the length of the "parent" list inside <code>integers()</code> </li>
</ul>
<p><strong>The Question:</strong></p>
<p>How can I limit the integer values inside sublists to be less than the total number of sublists?</p>
<hr>
<p>Some of my attempts:</p>
<pre><code>from hypothesis import given
from hypothesis.strategies import lists, integers
@given(lists(lists(integers(min_value=0, max_value=5), min_size=1, max_size=5), min_size=1, max_size=50))
def test(l):
# ...
</code></pre>
<p>This one was very far from meeting the requirements - list is not strictly of a rectangular form and generated integer values can go over the generated size of the list.</p>
<pre><code>from hypothesis import given
from hypothesis.strategies import lists, integers
@given(integers(min_value=0, max_value=5).flatmap(lambda n: lists(lists(integers(min_value=1, max_value=5), min_size=n, max_size=n), min_size=1, max_size=50)))
def test(l):
# ...
</code></pre>
<p>Here, the #1 and #2 are requirements were being met, but the integer values can go larger than the size of the list - requirement #3 is not met.</p>
| 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_and_length):
number, length = number_and_length
list_elements = st.integers(min_value=0, max_value=number - 1)
return st.lists(
st.lists(list_elements, min_size=length, max_size=length),
min_size=number, max_size=number)
mystrategy = st.tuples(number_of_lists, list_lengths).flatmap(build_strategy)
@settings(max_examples=5000)
@given(mystrategy)
def test_constraints(list_of_lists):
N = len(list_of_lists)
# condition 1
assert 1 <= N <= 50
# Condition 2
[length] = set(map(len, list_of_lists))
assert 0 <= length <= 5
# Condition 3
assert all((0 <= element < N) for lst in list_of_lists for element in lst)
</code></pre>
<p>As David mentioned, this does tend to produce a lot of empty lists, so some average size tuning would be required.</p>
<pre><code>>>> mystrategy.example()
[[24, 6, 4, 19], [26, 9, 15, 15], [1, 2, 25, 4], [12, 8, 18, 19], [12, 15, 2, 31], [3, 8, 17, 2], [5, 1, 1, 5], [7, 1, 16, 8], [9, 9, 6, 4], [22, 24, 28, 16], [18, 11, 20, 21], [16, 23, 30, 5], [13, 1, 16, 16], [24, 23, 16, 32], [13, 30, 10, 1], [7, 5, 14, 31], [31, 15, 23, 18], [3, 0, 13, 9], [32, 26, 22, 23], [4, 11, 20, 10], [6, 15, 32, 22], [32, 19, 1, 31], [20, 28, 4, 21], [18, 29, 0, 8], [6, 9, 24, 3], [20, 17, 31, 8], [6, 12, 8, 22], [32, 22, 9, 4], [16, 27, 29, 9], [21, 15, 30, 5], [19, 10, 20, 21], [31, 13, 0, 21], [16, 9, 8, 29]]
>>> mystrategy.example()
[[28, 18], [17, 25], [26, 27], [20, 6], [15, 10], [1, 21], [23, 15], [7, 5], [9, 3], [8, 3], [3, 4], [19, 29], [18, 11], [6, 6], [8, 19], [14, 7], [25, 3], [26, 11], [24, 20], [22, 2], [19, 12], [19, 27], [13, 20], [16, 5], [6, 2], [4, 18], [10, 2], [26, 16], [24, 24], [11, 26]]
>>> mystrategy.example()
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> mystrategy.example()
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> mystrategy.example()
[[6, 8, 22, 21, 22], [3, 0, 24, 5, 18], [16, 17, 25, 16, 11], [2, 12, 0, 3, 15], [0, 12, 12, 12, 14], [11, 20, 6, 6, 23], [5, 19, 2, 0, 12], [16, 0, 1, 24, 10], [2, 13, 21, 19, 15], [2, 14, 27, 6, 7], [22, 25, 18, 24, 9], [26, 21, 15, 18, 17], [7, 11, 22, 17, 21], [3, 11, 3, 20, 16], [22, 13, 18, 21, 11], [4, 27, 21, 20, 25], [4, 1, 13, 5, 13], [16, 19, 6, 6, 25], [19, 10, 14, 12, 14], [18, 13, 13, 16, 3], [12, 7, 26, 26, 12], [25, 21, 12, 23, 22], [11, 4, 24, 5, 27], [25, 10, 10, 26, 27], [8, 25, 20, 6, 23], [8, 0, 12, 26, 14], [7, 11, 6, 27, 26], [6, 24, 22, 23, 19]]
</code></pre>
| 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 throw the error and crash:</p>
<p>UnicodeEncodeError was unhandled by user code</p>
<p>'charmap' codec can't encode character '\xaf' in position 13: character maps to < undefined ></p>
<p>Now, I want my program to be able to handle these inputs, but I have no idea what to change or add to my code to enable this. This is my code:</p>
<p><a href="http://pastebin.com/EBTaqpbZ" rel="nofollow">http://pastebin.com/EBTaqpbZ</a> (I couldn't figure out how to use Stackoverflow code paste)</p>
<p>The main part of the code that I'm receiving the error on is:</p>
<pre><code>while True: #Main Loop
response = s.recv(1024).decode("utf-8")
if response == "PING :tmi.twitch.tv\r\n": #If Ping, return Pong
s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
print("Pong Successful")
else: #Else, Decode User Message
username = re.search(r"\w+", response).group(0) #Gets User
message = CHAT_MSG.sub("", response) #Gets Message
print (username + ": " + message) #Prints User Message
if message.find("!hello") != -1: #Simple Test command to see if Reading Chat Input
chat ("Hello! I'm speaking!\r\n")
time.sleep(1 / cfg.RATE)
</code></pre>
<p>The error always seems to happen on the line of code: <code>print (username + ": " + message)</code> </p>
<p>does anyone know how I should go about handling these unicode characters?</p>
| 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 used. For example, the code runs fine when ran from a linux console. One way to overcome this problem seems to be using <a href="https://github.com/Drekin/win-unicode-console" rel="nofollow">win-unicode-console</a> to enable unicode input and output from windows console. See <a href="http://stackoverflow.com/a/32176732/6845813">this answer</a> for a broader description of the problem and solution.</p>
<p>You can also just go around the problem if you just need the print for debugging purposes:</p>
<pre><code>msg = username + ": " + message
print (msg.encode("utf-8"))
</code></pre>
<p>However, that is not a real solution, and the output will be something like</p>
<blockquote>
<p>b'\xc2\xaf_(\xe3\x83\x84)_/\xc2\xaf\r\n'</p>
</blockquote>
<p>for your example string, so not very convenient. I recommend reading the answer I linked.</p>
| 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 |
--------------------------------------
| : |
--------------------------------------
| 1 | 2.1 | 3.2 |
--------------------------------------
| 0 | 1.1 | 2.1 |
--------------------------------------
</code></pre>
<p>I can create a scatter plot for field_1 vs. field_2 like below:</p>
<pre><code>%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
my_df.plot(x='field_1', y='field_2', kind = 'scatter')
</code></pre>
<p>However, I am wondering is it possible to include field_0 in the plot? So when field_0 = 0, the point is blue; when field_1 = 1, the point is red. </p>
<p>Thanks!</p>
| 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 specific location with the following statement:</p>
<p><code>zimmer = response.xpath('//*[@id="id316"]/span[2]').extract()</code></p>
<p>However I'm not getting anything but an empty string. I found out that the id value is different for each element in the list I'm interested in. Is there a way to write this expression such that it works for generic numbers?</p>
| 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 of the locator.</p>
| 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 plays it, in order to cancel it. </p>
<p>My problem now is that the program takes some time to do the math, so once it has calculated the inverted wave, the original one has already passed by the device, and I get an offset of aproximately 0.02 seconds. My goal is to reduce this offset as much as possible, and then compensate it by increasing the distance between the microphone and the speaker. Right now, as the offset is 0.02 seconds, and the speed of sound is 340 m/s, I would have to set that distance to 6.8 meters (0.02 * 340 = 6.8), and that's too much.</p>
<p>So how can I make the program run faster?
Here's the code:</p>
<pre><code>import pyaudio, math, struct
import numpy as np
import matplotlib.pyplot as plt
#INITIAL CONFIG
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = float(input('Seconds: '))
p = pyaudio.PyAudio()
guess = 0
integral = 0
kp = 0.5
ki = 200
kd = 9999
dt = RATE**(-1)
ddt = RATE
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=chunk)
total_error = 0
previous_e = 0
#Start processing
print ("* recording")
for i in range(0, int(RATE / chunk * RECORD_SECONDS)):
byted = (b'')
for element in np.fromstring(stream.read(chunk), 'Int16'):
error = -(guess - element)
integral += error*dt
derivative = (error - previous_e) / ddt
guess += int(round(kp*error + ki*integral + kd*derivative, 0))
byted += struct.pack('<h', -guess)
previous_e = error
stream.write(byted, chunk)
#Close
stream.stop_stream()
stream.close()
p.terminate()
input ('Press enter to exit...')
</code></pre>
<p>Please note: Do not only respond with a solution, please explain why does it improve the speed of the program, as not only I want this to work but I also want to learn.</p>
<p>Thanks</p>
| -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(struct.pack('<h', -guess))
...
stream.write(b''.join(byted_array), chunk)
</code></pre>
| 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 (accounts.txt) that is structured like this:</p>
<pre><code>email1@email.com:test1
email2@email.com:test2
email3@email.comtest3
email4@email.comtest4
</code></pre>
<p>Since I want to split the email and the password, I'd like, if the try doesn't work (so the ":" is not in the line of the file (and account[1] doesn't exist)), to add the ":" after the ".com" of each email on the file. Is that possible? </p>
<p>The output of the third and fourth accounts should be:</p>
<pre><code>email3@email.com:test3
email4@email.com:test4
</code></pre>
| -1 |
2016-09-18T18:56:54Z
| 39,561,584 |
<p>You can use regex for splitting your lines:</p>
<pre><code>In [37]: s1 = 'email2@email.com:test2'
In [38]: s2 = 'email3@email.comtest3'
In [42]: regex = re.compile(r'(.+\.com):?(.*)')
In [43]: regex.search(s1).groups()
Out[43]: ('email2@email.com', 'test2')
In [44]: regex.search(s2).groups()
Out[44]: ('email3@email.com', 'test3')
</code></pre>
<p>And in your code:</p>
<pre><code>regex = re.compile(r'(.+\.com):?(.*)')
with open("accounts.txt") as f:
for ind, line in enumerate(f):
try:
part1, part2 = regex.search(line.strip()).groups()
except:
pass
else:
print ("Trying with: {}:{} @{}".format(part1, part2, ind))
</code></pre>
| 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 (accounts.txt) that is structured like this:</p>
<pre><code>email1@email.com:test1
email2@email.com:test2
email3@email.comtest3
email4@email.comtest4
</code></pre>
<p>Since I want to split the email and the password, I'd like, if the try doesn't work (so the ":" is not in the line of the file (and account[1] doesn't exist)), to add the ":" after the ".com" of each email on the file. Is that possible? </p>
<p>The output of the third and fourth accounts should be:</p>
<pre><code>email3@email.com:test3
email4@email.com:test4
</code></pre>
| -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 [pos:])
else:
corr.append(x)
return corr
</code></pre>
<p>and call:</p>
<pre><code>y = [x.strip().split(":") for x in correct_accounts(accounts)]
</code></pre>
| 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 "Select All" and "Clear All". I understand that I will need some callback mechanism to do this, but after searching the examples, documentation and stackoverflow, was not able to figure out just how. I include a simplified version of my code below. My preference is to use the standard widget Callback rather than the JS callback.</p>
<p>Any help appreciated!</p>
<pre><code>from bokeh.plotting import curdoc, output_file
from bokeh.models.widgets import Button, CheckboxGroup
from bokeh.layouts import widgetbox, row
from bokeh.models import ColumnDataSource, Callback
output_file("states.html", title="states")
states = ["Alabama", "Alaska ", "Arizona", "Arkansas", "California", \
"Colorado", "Connecticut", "Delaware", "Florida", "Georgia", \
"Hawaii", "Idaho ", "Illinois", "Indiana", "Iowa", "Kansas", \
"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", \
"Michigan ", "Minnesota", "Mississippi", "Missouri", "Montana",\
"Nebraska", "Nevada ", "New Hampshire", "New Jersey",\
"New Mexico", "New York", "North Carolina", "North Dakota", \
"Ohio", "Oklahoma","Oregon", "Pennsylvania", "Rhode Island", \
"South Carolina", "South Dakota", "Tennessee", "Texas", "Utah",\
"Vermont", "Virginia","Washington", "West Virginia", \
"Wisconsin", "Wyoming"]
states = CheckboxGroup(
labels = states,
active=[0,1])
select_all = Button(label="select all")
# need some help here
group = widgetbox(select_all, states)
layout = row(group)
curdoc().add_root(layout)
curdoc().title = "states"
</code></pre>
| 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 the callback:</p>
<pre><code>from bokeh.plotting import curdoc, output_file
from bokeh.models.widgets import Button, CheckboxGroup
from bokeh.layouts import widgetbox, row
from bokeh.models import ColumnDataSource, Callback
output_file("states.html", title="states")
states_list = ["Alabama", "Alaska ", "Arizona", "Arkansas", "California", \
"Colorado", "Connecticut", "Delaware", "Florida", "Georgia", \
"Hawaii", "Idaho ", "Illinois", "Indiana", "Iowa", "Kansas", \
"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", \
"Michigan ", "Minnesota", "Mississippi", "Missouri", "Montana",\
"Nebraska", "Nevada ", "New Hampshire", "New Jersey",\
"New Mexico", "New York", "North Carolina", "North Dakota", \
"Ohio", "Oklahoma","Oregon", "Pennsylvania", "Rhode Island", \
"South Carolina", "South Dakota", "Tennessee", "Texas", "Utah",\
"Vermont", "Virginia","Washington", "West Virginia", \
"Wisconsin", "Wyoming"]
states = CheckboxGroup(
labels = states_list,
active=[0,1])
select_all = Button(label="select all")
def update():
states.active = list(range(len(states_list)))
select_all.on_click(update)
group = widgetbox(select_all, states)
layout = row(group)
curdoc().add_root(layout)
curdoc().title = "states"
</code></pre>
| 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. I know of the sort function, and that can be used in case of python but what about pseudocode.</p>
<p>To see the code: Lines[72:92] <a href="http://pastebin.com/MTnifkek" rel="nofollow">http://pastebin.com/MTnifkek</a></p>
<p>To see the python code: <a href="http://pastebin.com/fvqqstXW" rel="nofollow">http://pastebin.com/fvqqstXW</a></p>
<p>In python it's the same but instead I use nested ifs.
As you may notice, this was my first time, and apologies on any errors.
I tried think but other than nesting ifs I was blank.
I was thinking a for loop:</p>
<pre><code>for count in charity_value:
if count > max:
max == count
elif count < min:
min == count
</code></pre>
<p>Though how would I find the middle value ?</p>
| -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>
<p>1.1.1.1,0.0.0.0 2.2.2.2,0.0.0.0 </p>
<p>Is there a way to print the file in same format, instead printing all content in same line?</p>
<p>Thanks</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 reach declared earlier variable, but that variable returned from function and next calling same function should again switch my variable (X and O), just cut a piece of this code: got X or O (what I'm choosing), printing variable correct, but then function output is X X X and so on... (I'm just started to learn, but just stuck here!)</p>
<pre><code>def choice():
choice = input("You want to have x or o?: ")
if choice == 'x':
human = 'X'
computer = 'O'
else:
human = 'O'
computer = 'X'
return human, computer
human, computer = choice()
print("human is ", human)
print("computer is ", computer)
def next_player(turn):
if turn == 'X':
return 'O'
else:
return 'X'
turn = 'X'
print("turn is ", turn)
turn = next_player(turn) # was here: next_player(turn) and so below!!
print("after next player function turn is ", turn)
turn = next_player(turn)
print("after next player function turn is ", turn)
</code></pre>
| 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 = next_player(turn)
</code></pre>
<p>instead of:</p>
<pre><code>next_player(turn)
</code></pre>
| 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 reach declared earlier variable, but that variable returned from function and next calling same function should again switch my variable (X and O), just cut a piece of this code: got X or O (what I'm choosing), printing variable correct, but then function output is X X X and so on... (I'm just started to learn, but just stuck here!)</p>
<pre><code>def choice():
choice = input("You want to have x or o?: ")
if choice == 'x':
human = 'X'
computer = 'O'
else:
human = 'O'
computer = 'X'
return human, computer
human, computer = choice()
print("human is ", human)
print("computer is ", computer)
def next_player(turn):
if turn == 'X':
return 'O'
else:
return 'X'
turn = 'X'
print("turn is ", turn)
turn = next_player(turn) # was here: next_player(turn) and so below!!
print("after next player function turn is ", turn)
turn = next_player(turn)
print("after next player function turn is ", turn)
</code></pre>
| 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 reach declared earlier variable, but that variable returned from function and next calling same function should again switch my variable (X and O), just cut a piece of this code: got X or O (what I'm choosing), printing variable correct, but then function output is X X X and so on... (I'm just started to learn, but just stuck here!)</p>
<pre><code>def choice():
choice = input("You want to have x or o?: ")
if choice == 'x':
human = 'X'
computer = 'O'
else:
human = 'O'
computer = 'X'
return human, computer
human, computer = choice()
print("human is ", human)
print("computer is ", computer)
def next_player(turn):
if turn == 'X':
return 'O'
else:
return 'X'
turn = 'X'
print("turn is ", turn)
turn = next_player(turn) # was here: next_player(turn) and so below!!
print("after next player function turn is ", turn)
turn = next_player(turn)
print("after next player function turn is ", turn)
</code></pre>
| 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 as the variable "turn" outside the function! </li>
</ol>
<p>To get the correct value from next_player(turn): turn = next_player(turn)</p>
| 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'], "title": item['title']
}
data = json.dumps({"events": [item_attrs]})
poster = requests.post(
"http://localhost:3000/users/1/web_requests/69/supersecretstring",
data = data, headers = {'content-type': 'application/json'}
)
if poster.status_code != 200:
raise DropItem("error posting event %s code=%s" % (item, poster.status_code))
return item
</code></pre>
<p>The thing is, in another spider, I'd need to post to another url, and potentially use different attributes. Is it possible to specify instead of this:</p>
<pre><code>class Spider(scrapy.Spider):
name = "products"
start_urls = (
'some_url',
)
custom_settings = {
'ITEM_PIPELINES': {
'spider.pipelines.Poster': 300,
},
}
</code></pre>
<p>something like:</p>
<pre><code> custom_settings = {
'ITEM_PIPELINES': {
spider.pipelines.Poster(some_other_url, some_attributes): 300,
},
}
</code></pre>
<p>I know the URL I would need when I'm creating the spider, as well as the fields I would be extracting.</p>
| 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):
count = None
def open_spider(self, spider):
count = getattr(spider, 'pipeline_count')
self.count = int(count)
# or as starrify pointed out in the comment below
# access it directly in process_item
def process_item(self, item, spider):
count = getattr(spider, 'pipeline_count')
item['count'] = count
return item
<...>
</code></pre>
| 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 throughout. I've trained a simple Random Forest Classifier on this information, and it is so far pretty good at predicting whether the user will complete the goal.</p>
<p>I also have a day-by-day breakdown of completion percentage for all users who have already completed (or not completed). Two samples with one user who completed and one who didn't might look something like this for three days: <code>[[0., 0.58, 1.], [0.2, 0.5, .8]]</code> where each feature is the percentage through achieving the goal. The first user got to 100% within the timeframe, the second didn't. </p>
<p>I want to be able to make the predictions for goal completion on the fly. So if there's a new user who's 1 day through the time limit and 20% of the way to the goal, their data might look like this: <code>[[.2, NaN, NaN]]</code></p>
<p>The only way I can see integrating this data into the existing model is fitting a different model for each day (model for day 1, model for day 2, etc.). But this is not at all feasible for my production environment. I also thought about trying to impute the missing values (for the above, something like .2, .4, .6), but I know for a fact that the user goal completion tends not to be linear like this.</p>
<p>Is there a good way to train a model with this kind of data? Or an algorithm supported by scikit-learn or another python library that is built for this kind of task? Note that my model also needs to support probability estimates.</p>
| 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 can be used. For more details on this you can have a look at the sklearn RandomForest documentation here : <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html</a></p>
| 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]],
['Prints', [1]],
['Politics', [3]],
['Politics', [3]],
['Accounts', [2]],
['Accounts', [2]],
['Accounts', [2]],
['Features', [3]],
['Features', [2]]
]
</code></pre>
<p>I would therefore like the new structure to be:</p>
<pre><code>new_lists = [
['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]
</code></pre>
<p>How do I achieve this in Python?</p>
| 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', 8), ('Accounts', 6)])
</code></pre>
| 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]],
['Prints', [1]],
['Politics', [3]],
['Politics', [3]],
['Accounts', [2]],
['Accounts', [2]],
['Accounts', [2]],
['Features', [3]],
['Features', [2]]
]
</code></pre>
<p>I would therefore like the new structure to be:</p>
<pre><code>new_lists = [
['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]
</code></pre>
<p>How do I achieve this in Python?</p>
| 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 lists:
... d[key] += value[0]
...
>>> dict(d)
{'Gifts': 8, 'Prints': 3, 'Accounts': 6, 'Features': 5, 'Supply': 8, 'Politics': 9}
>>> list(d.items())
[('Prints', 3), ('Features', 5), ('Supply', 8), ('Gifts', 8), ('Accounts', 6), ('Politics', 9)]
</code></pre>
| 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]],
['Prints', [1]],
['Politics', [3]],
['Politics', [3]],
['Accounts', [2]],
['Accounts', [2]],
['Accounts', [2]],
['Features', [3]],
['Features', [2]]
]
</code></pre>
<p>I would therefore like the new structure to be:</p>
<pre><code>new_lists = [
['Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]
</code></pre>
<p>How do I achieve this in Python?</p>
| 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 key:</p>
<pre><code>from collections import Counter
c = Counter()
for i, j in lists:
c[i] += l[j]
</code></pre>
<p>Or, by providing a flat list of the expanded contents, <code>Counter</code> will then do the counting for you:</p>
<pre><code>c = Counter(sum([[i] * j[0] for i,j in lists], []))
</code></pre>
<p>In both cases, create the result list by using a list comprehension grabbing the contents of the counter with <code>c.items()</code>:</p>
<pre><code>r = [[i, j] for i, j in c.items()]
</code></pre>
<p>Result being:</p>
<pre><code>print(r)
[['Supply', 8], ['Features', 5], ['Prints', 3],
['Gifts', 8], ['Accounts', 6], ['Politics', 9]]
</code></pre>
| 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 pygame
from pygame.locals import *
import time
import random
import pyganim
import sys
import os
rects = [(0, 154, 94, 77),
(94, 154, 94, 77),
(188, 154, 94, 77),
(282, 154, 94, 77),
(376, 154, 94, 77),
(470, 154, 94, 77),
(564, 154, 94, 77),
(658, 154, 94, 77),]
file_name = ('explosion1.png')
images = pyganim.getImagesFromSpriteSheet(file_name, rects = rects)
frames = list (zip(images, [100] * len(images)))
animObj = pyganim.PygAnimation(frames)
animObj.play()
white = (255, 255, 255)
black = (0, 0, 0)
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('sprite animations')
clock = pygame.time.Clock()
def game_loop():
gameDisplay.fill(black)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
animObj.blit(gameDisplay,(100, 50))
pygame.display.update()
clock.tick(15)
game_loop()
pygame.quit()
quit()
</code></pre>
| 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 win the lotto: ")
def count_correct(list1,list2):
count = 0
for r in list2:
if list1 in list2:
count += 1
return count
</code></pre>
| -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 win the lotto: ")
def count_correct(list1,list2):
count = 0
for r in list2:
if list1 in list2:
count += 1
return count
</code></pre>
| -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))
</code></pre>
<p>Where only the non-duplicate common ones will be counted or fix your <code>for</code> loop like so:</p>
<pre><code>def count_correct(list1,list2):
count = 0
for r in list2:
if r in list1:
count += 1
return count
</code></pre>
| 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 win the lotto: ")
def count_correct(list1,list2):
count = 0
for r in list2:
if list1 in list2:
count += 1
return count
</code></pre>
| -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 True in the generator expression is coerced to int value 1
return sum(i in list1 for i in list2)
</code></pre>
<p><strong>Note</strong> that using <em>sets</em> will eliminate duplicates in your lists, if any, which will give incorrect results.</p>
<hr>
<p>To capture your list of inputs you can do:</p>
<pre><code>userask = input("Enter a few numbers to try win the lotto (separated by spaces): ")
list1 = map(int, userask.split())
</code></pre>
| 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 only 1 label for each sample. I formatted this text file so it can be consistent with the LSTM training as the latter requires a time-steps of the sequences or in general, LSTM training requires a 3D tensor (batch, num of time-steps, num of features).</p>
<p>My question: How should I use Numpy or <code>TensorFlow.TextReader</code> in order to reformat the 3x3 sequence vectors and the singleton Labels so it can become compatible with Tensorflow?</p>
<p>Edit: I saw many tutorials on reformatting text or CSV files that has vectors and labels but unfortunately they were for 1 to 1 relationships e.g.</p>
<pre><code>0.2, 4.3, 1.2, Class1
1.1, 2.2, 3.1, Class2
3.5, 4.1, 1.1, Class3
</code></pre>
<p>becomes:</p>
<pre><code>[0.2, 4.3, 1.2, Class1], [1.1, 2.2, 3.1, Class2], [3.5, 4.1, 1.1, Class3]
</code></pre>
<p>which clearly is readable by Numpy and can build vectors easily from it dedicated for simple Feed-Forward NN tasks. But this procedure doesn't actually build an LSTM friendly CSV.</p>
<p>EDIT: The TensorFlow tutorial on CSV formats, covers only 2D arrays as an example. The <code>features = col1, col2, col3</code> doesn't assume that there might be time-steps for each sequence array and hence my question.</p>
| 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:</strong></p>
<p>Here is a Pandas solution.</p>
<p>Assume we have the following text file:</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>Code:</p>
<pre><code>import pandas as pd
In [95]: fn = r'D:\temp\.data\data.txt'
In [96]: df = pd.read_csv(fn, sep=',', skipinitialspace=True, header=None, names=list('abcd'))
In [97]: df
Out[97]:
a b c d
0 0.2 4.3 1.2 NaN
1 1.1 2.2 3.1 NaN
2 3.5 4.1 1.1 4300.0
3 1.2 3.3 1.2 NaN
4 1.5 2.4 3.1 NaN
5 3.5 2.1 1.1 4400.0
In [98]: df.d = df.d.bfill()
In [99]: df
Out[99]:
a b c d
0 0.2 4.3 1.2 4300.0
1 1.1 2.2 3.1 4300.0
2 3.5 4.1 1.1 4300.0
3 1.2 3.3 1.2 4400.0
4 1.5 2.4 3.1 4400.0
5 3.5 2.1 1.1 4400.0
</code></pre>
<p>now you can save it back to CSV:</p>
<pre><code>df.to_csv('d:/temp/out.csv', index=False, header=None)
</code></pre>
<p>d:/temp/out.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>
| 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 only 1 label for each sample. I formatted this text file so it can be consistent with the LSTM training as the latter requires a time-steps of the sequences or in general, LSTM training requires a 3D tensor (batch, num of time-steps, num of features).</p>
<p>My question: How should I use Numpy or <code>TensorFlow.TextReader</code> in order to reformat the 3x3 sequence vectors and the singleton Labels so it can become compatible with Tensorflow?</p>
<p>Edit: I saw many tutorials on reformatting text or CSV files that has vectors and labels but unfortunately they were for 1 to 1 relationships e.g.</p>
<pre><code>0.2, 4.3, 1.2, Class1
1.1, 2.2, 3.1, Class2
3.5, 4.1, 1.1, Class3
</code></pre>
<p>becomes:</p>
<pre><code>[0.2, 4.3, 1.2, Class1], [1.1, 2.2, 3.1, Class2], [3.5, 4.1, 1.1, Class3]
</code></pre>
<p>which clearly is readable by Numpy and can build vectors easily from it dedicated for simple Feed-Forward NN tasks. But this procedure doesn't actually build an LSTM friendly CSV.</p>
<p>EDIT: The TensorFlow tutorial on CSV formats, covers only 2D arrays as an example. The <code>features = col1, col2, col3</code> doesn't assume that there might be time-steps for each sequence array and hence my question.</p>
| 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, 4400
</code></pre>
<p><code>savetxt</code> is not tricky. It opens a file for writing, and then iterates on the input array, writing it, one row at a time to the file. Effectively:</p>
<pre><code> for row in arr:
f.write(fmt % tuple(row))
</code></pre>
<p>where <code>fmt</code> has a <code>%</code> field for each element of the the <code>row</code>. In the simple case it constructs <code>fmt = delimiter.join(['fmt']*(arr.shape[1]))</code>. In other words repeating the simgle field <code>fmt</code> for the number of columns. Or you can give it a multifield <code>fmt</code>.</p>
<p>So you could use normal line/file writing methods to write a custom display. The simplest is to construct it using the usual <code>print</code> commends, and then redirect those to a file.</p>
<p>But having done that, there's the question of how to read that back into a <code>numpy</code> session. <code>np.genfromtxt</code> can handle missing data, but you still have to include the delimiters. It's also trickier to have it read blocks (3 lines separated by a blank line). It's not impossible, but you have to do some preprocessing.</p>
<p>Of course <code>genfromtxt</code> isn't that tricky either. It reads the file line by line, converts each line into a list of numbers or strings, and collects those lists in a master list. Only at the end is that list converted into an array.</p>
<p>I can construct an array like your text with:</p>
<pre><code>In [121]: dt = np.dtype([('lbl',int), ('block', float, (3,3))])
In [122]: A = np.zeros((2,),dtype=dt)
In [123]: A
Out[123]:
array([(0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
(0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])],
dtype=[('lbl', '<i4'), ('block', '<f8', (3, 3))])
In [124]: A['lbl']=[4300,4400]
In [125]: A[0]['block']=np.array([[.2,4.3,1.2],[1.1,2.2,3.1],[3.5,4.1,1.1]])
In [126]: A
Out[126]:
array([(4300, [[0.2, 4.3, 1.2], [1.1, 2.2, 3.1], [3.5, 4.1, 1.1]]),
(4400, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])],
dtype=[('lbl', '<i4'), ('block', '<f8', (3, 3))])
In [127]: A['block']
Out[127]:
array([[[ 0.2, 4.3, 1.2],
[ 1.1, 2.2, 3.1],
[ 3.5, 4.1, 1.1]],
[[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ]]])
</code></pre>
<p>I can load it from a txt that has all the block values flattened:</p>
<pre><code>In [130]: txt=b"""4300, 0.2, 4.3, 1.2, 1.1, 2.2, 3.1, 3.5, 4.1, 1.1"""
In [131]: txt
Out[131]: b'4300, 0.2, 4.3, 1.2, 1.1, 2.2, 3.1, 3.5, 4.1, 1.1'
</code></pre>
<p><code>genfromtxt</code> can handle a complex dtype, allocating values in order from the flat line list:</p>
<pre><code>In [133]: data=np.genfromtxt([txt],delimiter=',',dtype=dt)
In [134]: data['lbl']
Out[134]: array(4300)
In [135]: data['block']
Out[135]:
array([[ 0.2, 4.3, 1.2],
[ 1.1, 2.2, 3.1],
[ 3.5, 4.1, 1.1]])
</code></pre>
<p>I'm not sure about writing it. I have have to reshape it into a 10 column or field array, if I want to use <code>savetxt</code>.</p>
| 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 = f.ProcessPoolExecutor()
a = executor.submit(wait_on_b)
b = executor.submit(wait_5)
print(a.result()) # works fine if THREADS, BrokenProcessPool otherwise
</code></pre>
<p>The <a href="https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor" rel="nofollow">docs</a> do warn:</p>
<blockquote>
<p>Calling Executor or Future methods from a callable submitted to a ProcessPoolExecutor will result in deadlock.</p>
</blockquote>
<p>The docs don't seem to mention raising an exception, so does it mean <code>ProcessPoolExecutor</code> somehow discovered the deadlock and resolved it by killing both processes?</p>
<p>More importantly, why is this deadlock unavoidable with processes (and avoidable with threads), and what is the workaround if I want to use multiple processes with futures, without being so restricted?</p>
| 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 PIPE since it is not the <strong>real</strong> <em>b</em> (just a copy)</p>
<p>BTW: on windows there is <strong>no fork</strong>, so <em>b</em> (the memory is totally new) does not exists and you'll get a </p>
<pre><code>concurrent.futures.process._RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Anaconda3\lib\concurrent\futures\process.py", line 175, in _process_worker
r = call_item.fn(*call_item.args, **call_item.kwargs)
File "C:\Users\yglazner\My Documents\LiClipse Workspace\anaconda_stuff\mproc.py", line 5, in wait_on_b
print(b.result())
NameError: name 'b' is not defined
"""
</code></pre>
| 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 basic and, i suppose, very common client/server example on Python, but as you know - this pair is for single shot, and program is closing.</p>
<p>client.py</p>
<pre><code>import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFERSIZE = 1024
sock = socket.socket()
sock.connect((TCP_IP, TCP_PORT))
msg = input('Enter your text: ')
sock.send(msg.encode())
data = sock.recv(BUFFERSIZE).decode()
sock.close()
print('Recieved data: ',data)
</code></pre>
<p>server.py</p>
<pre><code>import socket
import sys
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
sock = socket.socket()
sock.bind((TCP_IP, TCP_PORT))
sock.listen(1)
conn, addr = sock.accept()
print('Connection address:\nIP:',addr[0])
print('Port:',addr[1])
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
msg = data.decode()
print('Recieved data: ', msg)
conn.send(data)
conn.close()
</code></pre>
<p>Any suggestions?</p>
| 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>KeyboardInterrupt</code> exception. When it does, the <code>finally</code> will be called, and safely close the socket.</p>
<p>The same can be done to the client in order to close it client-side:</p>
<pre><code>try:
msg = input('Enter your text: ')
sock.send(msg.encode())
data = sock.recv(BUFFERSIZE).decode()
finally:
sock.close()
</code></pre>
| 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
loader.write(buf)
glib.GError: Error interpreting JPEG image file (Unsupported marker type 0x05)
</code></pre>
<p>The same file can be loaded in eog (eye of gnome) and I can use <code>convert</code> (from image-magick) with out error.</p>
<p>It happens for all files, not just one, this leads me to the conclusion that the files are not broken.</p>
<p>What could be wrong?</p>
<p>Here is one of the files: <a href="http://thomas-guettler.de/20160627_163057-0.jpg">http://thomas-guettler.de/20160627_163057-0.jpg</a></p>
<p>Here is a snippet to reproduce the exception:</p>
<pre><code>from gtk.gdk import PixbufLoader
pixbufloader=PixbufLoader()
chunksize=130000
fd=open('20160627_163057-0.jpg', 'rb')
while True:
bytes=fd.read(chunksize)
if not bytes:
break
print pixbufloader.write(bytes)
pixbufloader.close()
</code></pre>
<p>If you set <code>chunksize</code> to <code>1</code>, then it works.</p>
<p>If I use <code>130000</code> as chunksize, then the first call to <code>write()</code> fails.</p>
| 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 particular file has some problem.
Please check,
Thanks.</p>
| 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 and second column appear as nameless and that shouldn't happen.</p>
<p><a href="http://i.stack.imgur.com/8ecey.png" rel="nofollow"><img src="http://i.stack.imgur.com/8ecey.png" alt="enter image description here"></a></p>
<p>Even when I use code of</p>
<pre><code>df2.columns
</code></pre>
<p>It only names TotalPay as a column</p>
<p>Problem 2: I try to rename, for instance, the first column as JobTitle and the code doesn't do anything</p>
<pre><code>df3=df2.rename(columns = {0:'JobTitle'},inplace=True)
</code></pre>
<p>So the solution that was given here does not apparently work: <a href="http://stackoverflow.com/questions/26098710/rename-unnamed-column-pandas-dataframe">Rename unnamed column pandas dataframe</a>.</p>
<p>I wish two possible solutions:
1) That the aggregate function respects the column naming AND/OR
2) Rename the empty dataframe's columns</p>
| 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()</code> is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">very flexible</a> with what it will let you do.<br>
If you import the data properly, you won't need to reindex, or relabel. </p>
| 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 and second column appear as nameless and that shouldn't happen.</p>
<p><a href="http://i.stack.imgur.com/8ecey.png" rel="nofollow"><img src="http://i.stack.imgur.com/8ecey.png" alt="enter image description here"></a></p>
<p>Even when I use code of</p>
<pre><code>df2.columns
</code></pre>
<p>It only names TotalPay as a column</p>
<p>Problem 2: I try to rename, for instance, the first column as JobTitle and the code doesn't do anything</p>
<pre><code>df3=df2.rename(columns = {0:'JobTitle'},inplace=True)
</code></pre>
<p>So the solution that was given here does not apparently work: <a href="http://stackoverflow.com/questions/26098710/rename-unnamed-column-pandas-dataframe">Rename unnamed column pandas dataframe</a>.</p>
<p>I wish two possible solutions:
1) That the aggregate function respects the column naming AND/OR
2) Rename the empty dataframe's columns</p>
| 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: ")
payRate = input("Enter the hourly pay rate: ")
calcPayWithOT(hours,payRate)
def calcPayWithOT(hours,payRate):
if hours <= BASE_HOURS:
theGrossPayNoOT = hours * payRate
print("The gross pay is $ ", theGrossPayNoOT)
if hours > BASE_HOURS:
theGrossPayOT = (hours - BASE_HOURS) * OT_MULTIPLIER + (hours * payRate)
print("The gross pay is $ ", theGrossPayOT)
main()
</code></pre>
<p><img src="http://i.stack.imgur.com/m2yru.png" alt="Error Message"></p>
| 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: "))
payRate = float(input("Enter the hourly pay rate: "))
</code></pre>
<p>Depending if you want to include only natural numbers or ones with figures after the decimal <code>.</code></p>
| 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 behaves as you defined in the class. They can have their own functions and have special attributes.</p>
<p>(<code>type</code> is also a class if you're interested but it's a special class. It's a bit complicated but you can read more on it if you'll search for metaclasses)</p>
| 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:
return the integer object pointed by the small integers array at the
offset (value + 5).
else:
if no free integer object available:
allocate new block of integer objects
set value of the next free integer object in the current block
of integers.
return integer object
</code></pre>
<p>If you really want to dig deeper into this, and know how <code>int</code> works in Python, visit <a href="http://www.laurentluce.com/posts/python-integer-objects-implementation/" rel="nofollow">Python integer objects implementation</a> which I referred for answering this.</p>
| 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 <code>type.__dict__['__call__']</code>; this is called with <code>(int, '123')</code> as arguments. The default <code>__call__</code> implementation of <code>type</code> tries to construct a new object of the type given as the first argument (here <code>int</code>, by calling the <code>__new__</code> method on that type class; thus the behaviour of <code>int('123')</code> indirectly comes from <code>int.__new__(int, '123')</code>, which constructs a new <code>int</code> instance that has the value of the given string parsed as an integer.</p>
| 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 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
</code></pre>
<p>However, on using open_mfdataset, I get this error:</p>
<pre><code>xr.open_mfdataset(path_file, decode_times=False)
*** ValueError: cannot infer dimension to concatenate: supply the ``concat_dim`` argument explicitly
</code></pre>
<p>How to fix this error? My dimensions are the same in all the files</p>
| 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>It looks like it needs you to give a <code>concat_dim</code> parameter. It's having problems inferring it from your data.</p>
<blockquote>
<p>Dimension to concatenate files along. This argument is passed on to xarray.auto_combine() along with the dataset objects. You only need to provide this argument if the dimension along which you want to concatenate is not a dimension in the original datasets, e.g., if you want to stack a collection of 2D arrays along a third dimension.</p>
</blockquote>
<p>Are these 3d arrays that you want to stack along a new, 4th, dimension?</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 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
OrderedDict([(u'lat', <type 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 720
), (u'lon', <type 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1440
), (u'time', <type 'netCDF4._netCDF4.Dimension'>: name = 'time', size = 96
), (u'nv', <type 'netCDF4._netCDF4.Dimension'>: name = 'nv', size = 2
)])
</code></pre>
<p>However, on using open_mfdataset, I get this error:</p>
<pre><code>xr.open_mfdataset(path_file, decode_times=False)
*** ValueError: cannot infer dimension to concatenate: supply the ``concat_dim`` argument explicitly
</code></pre>
<p>How to fix this error? My dimensions are the same in all the files</p>
| 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_mfdataset</code> with <code>concat_dim=None</code> disabled all attempts at concatenation. <a href="https://github.com/pydata/xarray/pull/1007" rel="nofollow">This change</a> should make it into the next release of xarray (v0.9.0).</p>
<p>In the meantime, you can work around this by opening the files individually and merging them explicitly, e.g.,</p>
<pre><code>def open_mfdataset_merge_only(paths, **kwargs):
if isinstance(paths, basestring):
paths = sorted(glob(paths))
return xr.merge([xr.open_dataset(path, **kwargs) for path in paths])
</code></pre>
<p>Under the covers, this is basically all that <code>open_mfdataset</code> is doing.</p>
| 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 render_template, jsonify
import os
from flask import Markup
from contextlib import suppress
from collections import defaultdict
import operator
import re
from collections import Counter
import random
import math
import collections
import pymongo
from pymongo import MongoClient
from flask_table import Table, Col
app = Flask(__name__)
#jsonify(result=str(test[0]))
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_foods')
def add_numbers():
connection = MongoClient('<connection string>')
db = connection.foodnutr
a = request.args.get('a', 0, type=str)
test=[]
for i in db.foods.find( {"Description":{'$regex': a}}):
test.append(i)
items = [test[0]["Description"]]
return jsonify(result=str(test[0]['Description']))
if __name__ == '__main__':
app.run(host='127.0.0.1', port=2490,debug=True)
</code></pre>
<p>and my HTML file is:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
<script type=text/javascript>
$(function() {
$('#calculate').bind('click', function() {
$.getJSON('/_foods', {
a: $('input[name="a"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Enter a food</h3>
</div>
<hr/>
<div>
<p>
<input type="text" size="5" name="a" >
<input type="submit" value="Submit" onclick="myFunction()" id="calculate">
</form>
</div>
</div>
<table id="result">
<tr>
<th>id</th>
<th>result</th>
</tr>
</table>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>currently, i have successfully managed to get the data from the mongoDB into flask in both json, dictionary formats.</p>
<p>What i need, is to get my data into HTML table.</p>
<p>How can i achieve it?</p>
| -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 + '</td><td>' + data[key] + '</td></tr>')
}
});
return false;
});
});
</code></pre>
<p>But actually this is not nice method to implement. It would be better to change your JSON and use <a href="http://json2html.com/" rel="nofollow">http://json2html.com/</a> jQuery plugin for building table.</p>
<p>Better JSON Schema:</p>
<pre><code>var data = [{
"name": "Protein(g)Per Measure",
"value": 22.6
}, {
"name": "Sugars, total(g)Per Measure",
"value": 5.72
} {
"name": "Vitamin E (alpha-tocopherol)(mg)Per Measure",
"value": 0.0
}]
</code></pre>
<p>In this case using JSON2HTML is recommended:</p>
<pre><code>var transform = {"tag":"table", "children":[
{"tag":"tbody","children":[
{"tag":"tr","children":[
{"tag":"td","html":"${name}"},
{"tag":"td","html":"${value}"}
]}
]}
]};
$('#result').html(json2html.transform(data,transform));
</code></pre>
| 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 the code in the future, is there a clean solution that can be used immediately (in run-time) to perhaps kill specific threads so that the others can resume?</p>
<p>Edit: I was thinking to add some "deadlock detection" loop (in its own thread) that sleeps for a bit, then checks all running threads, and if a few of them look suspiciously slow, it kills the least important one among them. At what point the thread is suspected of deadlocking, and which is the least important of them, is of course defined by the deadlock detection loop programmer.</p>
<p>Clearly, it won't catch all problems (most obviously if the deadlock detection thread itself is deadlocked). The idea is not to find a mathematically perfect solution (which is, of course, not to write code that can deadlock). Rather, I wanted to partially solve the problem in some realistic cases.</p>
| 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 interpreted language I doubt they'll be realistic to use.</p>
| 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') should help but variable length rows aren't suited to pandas so I am a little stuck. As my csv is large I am looking for an efficient solution however.</p>
<p>What is a good way to do this?</p>
| 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></pre>
<p>To write it to a CSV file, you can use</p>
<pre><code>df1 = df.id2.groupby(df.id1).apply(list).apply(lambda l: ','.join(l)).reset_index()
df1.id1.str.cat(df1.id2, sep=',').to_csv('stuff.csv', index=False)
</code></pre>
| 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') should help but variable length rows aren't suited to pandas so I am a little stuck. As my csv is large I am looking for an efficient solution however.</p>
<p>What is a good way to do this?</p>
| 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') should help but variable length rows aren't suited to pandas so I am a little stuck. As my csv is large I am looking for an efficient solution however.</p>
<p>What is a good way to do this?</p>
| 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.