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 |
|---|---|---|---|---|---|---|---|---|---|
Perfect Square function that doesn't return | 40,089,750 | <p>I'm a beginner working with Python and I was given this task: <em>write a function which returns the highest perfect square which is less or equal to its parameter (a positive integer).</em></p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
... | 0 | 2016-10-17T15:00:53Z | 40,090,009 | <pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
xy = x*x <-- Here
if xy != n:
print (("%s is not a perfect square.") % (n))
x -= 1
xy = x*x <--Here
print (("%s is the next highes... | -1 | 2016-10-17T15:13:47Z | [
"python",
"loops",
"if-statement"
] |
Perfect Square function that doesn't return | 40,089,750 | <p>I'm a beginner working with Python and I was given this task: <em>write a function which returns the highest perfect square which is less or equal to its parameter (a positive integer).</em></p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
... | 0 | 2016-10-17T15:00:53Z | 40,090,355 | <p>your loop condition which is</p>
<pre><code>while xy < n:
</code></pre>
<p>this will be true always as xy is always 0 and n is always greater then zero if you will call the function with n = 0, it will print <code>0 is a perfect square of 0.</code> and will return None.</p>
<pre><code>for n > 0
</code></pre... | 0 | 2016-10-17T15:31:47Z | [
"python",
"loops",
"if-statement"
] |
Perfect Square function that doesn't return | 40,089,750 | <p>I'm a beginner working with Python and I was given this task: <em>write a function which returns the highest perfect square which is less or equal to its parameter (a positive integer).</em></p>
<pre><code>def perfsq(n):
x = 0
xy = x * x
if n >= 0:
while xy < n:
x += 1
... | 0 | 2016-10-17T15:00:53Z | 40,090,455 | <p>A simpler way of doing what you desire is below:</p>
<pre><code>def perfsq(n):
x = n
while True:
if x**2 <= n:
# display the result on the console using print function
print ("The highest perfect square of %s or less is %s" %(n,x**2))
return x**2 # return the ... | 0 | 2016-10-17T15:37:21Z | [
"python",
"loops",
"if-statement"
] |
Python: Where to put a one time initialization in a test case of unittest framework? | 40,089,787 | <p>My test is simple. I want to send two requests to two different servers then compare whether the results match.</p>
<p>I want to test the following things.</p>
<ol>
<li>send each request and see whether the return code is valid.</li>
<li>compare different portion of the outputs in each test method</li>
</ol>
<p>I... | 0 | 2016-10-17T15:02:54Z | 40,089,899 | <p>A class method called before tests in an individual class run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():</p>
<pre><code>@classmethod
def setUpClass(cls):
...
</code></pre>
<p>See: <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase... | 1 | 2016-10-17T15:09:28Z | [
"python",
"python-2.7",
"unit-testing",
"python-unittest"
] |
optimization for processing big data in pyspark | 40,089,822 | <p>Not a question->need a suggestion</p>
<p>I am operating on 20gb+6gb=26Gb csv file with 1+3 (1-master, 3-slave (each of 16 gb RAM).</p>
<p>This is how I am doing my ops</p>
<pre><code>df = spark.read.csv() #20gb
df1 = spark.read.csv() #6gb
df_merged= df.join(df1,'name','left') ###merging
df_merged.persists(Storag... | 1 | 2016-10-17T15:05:03Z | 40,092,736 | <p>I think your best bet is cutting the source data down to size. You mention that your source data has 90 cities, but you are only interested in 8 of them. Filter out the cities you don't want and keep the ones you do want in separate csv files:</p>
<pre><code>import itertools
import csv
city_list = [city1, city2,... | 1 | 2016-10-17T17:55:22Z | [
"python",
"python-2.7",
"apache-spark",
"pyspark",
"pyspark-sql"
] |
Error installing pyopenssl using pip | 40,089,841 | <p>I am trying to install different packages using python pip, but i get this error:</p>
<blockquote>
<p>File
"/usr/local/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg/pip/_vendor/
cnx.set_tlsext_host_name(server_hostname) AttributeError: '_socketobject' object has no attribute 'set_tlsext_host_name'</p>
<... | 0 | 2016-10-17T15:06:13Z | 40,090,080 | <pre><code>For Ubuntu:
sudo apt-get purge python-openssl
sudo apt-get install libffi-dev
sudo pip install pyopenssl
For RedHat:
sudo yum remove pyOpenSSL
sudo pip install pyopenssl
</code></pre>
<p>Method 2:</p>
<pre><code>easy_install http://pypi.python.org/packages/source/p/pyOpenSSL/pyOpenSSL-0.12.tar.gz
</code... | 0 | 2016-10-17T15:17:51Z | [
"python",
"linux",
"pip",
"redhat"
] |
How to JSON dump to a rotating file object | 40,090,057 | <p>I'm writing a program which periodically dumps old data from a RethinkDB database into a file and removes it from the database. Currently, the data is dumped into a single file which grows without limit. I'd like to change this so that the maximum file size is, say, 250 Mb, and the program starts to write to a new o... | 1 | 2016-10-17T15:16:04Z | 40,132,614 | <p>Following <a href="http://stackoverflow.com/users/4265407/stanislav-ivanov">Stanislav Ivanov</a>, I used <code>json.dumps</code> to convert each RethinkDB document to a string and wrote this to a <code>RotatingFileHandler</code>:</p>
<pre><code>import os
import sys
import json
import rethinkdb as r
import pytz
from... | 0 | 2016-10-19T13:20:37Z | [
"python",
"json"
] |
How to make make run the subtasks for periodic task with Celery? | 40,090,075 | <p>I would like to create <em>periodic</em> task which makes query to database, get's data from data provider, makes some API requests, formats documents and sends them using another API. </p>
<p>Result of the previous task should be chained to the next task. I've got from the documentation that I have to use <strong>... | 0 | 2016-10-17T15:17:40Z | 40,090,214 | <p>Something like this maybe?</p>
<pre><code>import time
while True:
my_celery_chord()
time.sleep(...)
</code></pre>
| 0 | 2016-10-17T15:24:39Z | [
"python",
"celery"
] |
Matplotlib: Gridspec not displaying bar subplot | 40,090,082 | <p>I have a 4x3 grid. I have 1 broken horizontal bar plot in the first row followed by 9 scatter plots. The height of the bar plot needs to be 2x height of the scatter plots. I am using gridspec to achieve this. However, it doesn't plot the bar plot completely. See picture below:</p>
<p><a href="https://i.stack.imgur.... | 0 | 2016-10-17T15:17:56Z | 40,090,337 | <p>In the block of code:</p>
<pre><code># Plot the bars, one by one
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1= plt.subplot(gs[1]).broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try ... | 1 | 2016-10-17T15:30:49Z | [
"python",
"python-2.7",
"matplotlib"
] |
Args and dictionary in render_to_response | 40,090,107 | <p>How to pass arguments and a dictionary in the query ?</p>
<p>My example does not work</p>
<pre><code>return render_to_response('bookmarks_add.html', {'categories': categories, 'args':args})
</code></pre>
<p>Separately work</p>
<pre><code>return render_to_response('bookmarks_add.html', args)
</code></pre>
<p>and... | 0 | 2016-10-17T15:19:13Z | 40,090,216 | <p>try this:</p>
<pre><code>args.update({
'categories': categories,
})
return render_to_response('bookmarks_add.html', args)
</code></pre>
| 1 | 2016-10-17T15:24:53Z | [
"python",
"django"
] |
Django Python Script | 40,090,167 | <p>I've been sifting through the documention but I don't feel like I'm getting a clear answer. Is it possible to run something python-like</p>
<pre><code>if company_name.startswith(('A')):
enter code here
</code></pre>
<p>from within a Django site or app? How would I go about it?</p>
<p>Currently the code I use is... | 1 | 2016-10-17T15:22:05Z | 40,090,333 | <p>Using <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#slice" rel="nofollow"><code>slice</code> filter</a>, you can get a substring; then compare the substring with the <code>'A'</code>:</p>
<pre><code>{% for TblCompanies in object_list %}
{% if TblCompanies.company_name|slice:':1' == 'A' %... | 2 | 2016-10-17T15:30:36Z | [
"python",
"django",
"django-templates",
"django-views",
"django-urls"
] |
How to retrieve a data requested by user from django models? | 40,090,229 | <p>I have a <em>model</em> and it has <strong>user</strong> table as "foreign key" in it . I need a query by which i can get user requested value . </p>
<p>Here is my models:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippe... | 0 | 2016-10-17T15:25:08Z | 40,090,690 | <p>In order to select all the records from <code>schedulesdb</code> model that relate to the current user, do the following.</p>
<pre><code>def new_job(request):
schedule_entries = schedulesdb.objects.filter(user=request.user)
return HttpResponse(schedule_entries)
</code></pre>
<p>P.S. It is always better... | 1 | 2016-10-17T15:49:55Z | [
"python",
"sql",
"django"
] |
Django multiple forms on one view | 40,090,233 | <p>I have a Django template that has data from a few different model types combining to make it. A dashboard if you will. And each of those has an edit form. </p>
<p>Is it best to process all those forms in one view as they are posted back to the same place and differentiating between them by a unique field like below... | 0 | 2016-10-17T15:25:19Z | 40,090,964 | <p>You can use mixins in order to solve your problem.</p>
<p>Example from the gist <a href="https://gist.github.com/michelts/1029336" rel="nofollow">https://gist.github.com/michelts/1029336</a></p>
<pre><code>class MultipleFormsMixin(FormMixin):
"""
A mixin that provides a way to show and handle several forms... | 1 | 2016-10-17T16:04:59Z | [
"python",
"django",
"forms"
] |
Joining string of a columns over several index while keeping other colums | 40,090,235 | <p>Here is an example data set:</p>
<pre><code>>>> df1 = pandas.DataFrame({
"Name": ["Alice", "Marie", "Smith", "Mallory", "Bob", "Doe"],
"City": ["Seattle", None, None, "Portland", None, None],
"Age": [24, None, None, 26, None, None],
"Group": [1, 1, 1, 2, 2, 2]})
>>> df1
Age ... | 3 | 2016-10-17T15:25:25Z | 40,090,310 | <p>try this:</p>
<pre><code>In [29]: df1.groupby('Group').ffill().groupby(['Group','Age','City']).Name.apply(' '.join)
Out[29]:
Group Age City
1 24.0 Seattle Alice Marie Smith
2 26.0 Portland Mallory Bob Doe
Name: Name, dtype: object
</code></pre>
| 3 | 2016-10-17T15:29:24Z | [
"python",
"pandas"
] |
Joining string of a columns over several index while keeping other colums | 40,090,235 | <p>Here is an example data set:</p>
<pre><code>>>> df1 = pandas.DataFrame({
"Name": ["Alice", "Marie", "Smith", "Mallory", "Bob", "Doe"],
"City": ["Seattle", None, None, "Portland", None, None],
"Age": [24, None, None, 26, None, None],
"Group": [1, 1, 1, 2, 2, 2]})
>>> df1
Age ... | 3 | 2016-10-17T15:25:25Z | 40,090,538 | <p>using <code>dropna</code> and <code>assign</code> with <code>groupby</code></p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">docs to assign</a></p>
<pre><code>df1.dropna(subset=['Age', 'City']) \
.assign(Name=df1.groupby('Group').Name.apply(' '.j... | 3 | 2016-10-17T15:41:07Z | [
"python",
"pandas"
] |
Convert a string into list of list | 40,090,375 | <p>I have a string, say:</p>
<p><code>s = "abcdefghi"</code></p>
<p>I need to create a list of lists of this such that the list formed will :-</p>
<p><code>list = [['a','b','c'],['d','e','f'],['g','h','i']]</code></p>
<p>Now the string can be anything but will always have length n * n</p>
<p>So if <code>n = 4.</co... | 0 | 2016-10-17T15:32:44Z | 40,090,427 | <p>Here's a list comprehension that does the job:</p>
<pre><code>[list(s[i:i+n]) for i in range(0, len(s), n)]
</code></pre>
<p>If <code>n * n == len(s)</code> is always true, then just put</p>
<pre><code>n = int(len(s) ** 0.5) # Or use math.sqrt
</code></pre>
<p>For the edit part here's another list comprehension:... | 3 | 2016-10-17T15:35:31Z | [
"python",
"string",
"list"
] |
Convert a string into list of list | 40,090,375 | <p>I have a string, say:</p>
<p><code>s = "abcdefghi"</code></p>
<p>I need to create a list of lists of this such that the list formed will :-</p>
<p><code>list = [['a','b','c'],['d','e','f'],['g','h','i']]</code></p>
<p>Now the string can be anything but will always have length n * n</p>
<p>So if <code>n = 4.</co... | 0 | 2016-10-17T15:32:44Z | 40,090,491 | <p>I'm a personal fan of numpy...</p>
<pre><code>import numpy as np
s = "abcdefghi"
n = int(np.sqrt(len(s)))
a = np.array([x for x in s], dtype=str).reshape([n,n])
</code></pre>
| 0 | 2016-10-17T15:38:47Z | [
"python",
"string",
"list"
] |
Convert a string into list of list | 40,090,375 | <p>I have a string, say:</p>
<p><code>s = "abcdefghi"</code></p>
<p>I need to create a list of lists of this such that the list formed will :-</p>
<p><code>list = [['a','b','c'],['d','e','f'],['g','h','i']]</code></p>
<p>Now the string can be anything but will always have length n * n</p>
<p>So if <code>n = 4.</co... | 0 | 2016-10-17T15:32:44Z | 40,090,542 | <pre><code>from math import sqrt
def listify(s):
n = sqrt(len(s))
g = iter(s)
return [[next(g) for i in range(n)] for j in range(n)]
</code></pre>
<p>I like using generators for problems like this</p>
| 0 | 2016-10-17T15:41:25Z | [
"python",
"string",
"list"
] |
How to get a graph to start a certain point? (matplotlib) | 40,090,383 | <p>I was just wondering if anyone could tell me how to start a graph at a certain height on the y axis? <a href="https://i.stack.imgur.com/qD217.png" rel="nofollow"><img src="https://i.stack.imgur.com/qD217.png" alt="enter image description here"></a></p>
<p>Like if I wanted to start my curve at 50? I am plotting the ... | 0 | 2016-10-17T15:33:16Z | 40,111,716 | <p>Is it what you're looking for? </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
print("\nTo calculate the components of a projectile fired at an angle")
print("We need the angle(degrees), the initial velocity(ms-1), and")
print("The gravity constant (9.81 on earth)\n")
angle_0 = float(input("Plea... | 0 | 2016-10-18T15:01:00Z | [
"python",
"matplotlib"
] |
paramiko.exec_command() not executing and returns "Extra params found in CLI" | 40,090,445 | <p>I am trying to ssh a server using Paramiko and execute a command. But the paramiko.exec_command() returns with an error.Why is this happening?</p>
<p>This is my Python script:</p>
<pre><code>import paramiko
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPoli... | 0 | 2016-10-17T15:36:40Z | 40,103,207 | <p>Based on your latest comment:</p>
<blockquote>
<p>I installed a Cygwin Terminal and SSH'd the server with the command...it came up with the <code>Extra params</code> error. Command I executed: <code>ssh [email protected] "show chassis"</code>, Output: <code>No entry for terminal type "dumb"; using dumb terminal... | 0 | 2016-10-18T08:27:04Z | [
"python",
"python-3.x",
"network-programming",
"paramiko"
] |
font-color of FileChooser | 40,090,453 | <p>I would like to know how to change the font-color (text-color) of both the FileChooserListView and the FileChooserIconView.</p>
<p>I could change the background color (to white), and I would like to change the font color to black.</p>
<p>How could I do that?</p>
| 0 | 2016-10-17T15:37:08Z | 40,093,899 | <p>Default style of Kivy widget is placed in <a href="https://github.com/kivy/kivy/blob/master/kivy/data/style.kv" rel="nofollow">kivy/data/style.kv</a> file. You can copy its entries and change it to your liking. For example:</p>
<pre><code>from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
f... | 2 | 2016-10-17T19:10:05Z | [
"python",
"kivy"
] |
Removing parts of a string after certain chars in Python | 40,090,472 | <p>New to Python.</p>
<p>I'd like to remove the substrings between the word AND and the comma character in the following string:</p>
<pre><code>MyString = ' x.ABC AND XYZ, \ny.DEF AND Type, \nSome Long String AND Qwerty, \nz.GHI AND Tree \n'
</code></pre>
<p>The result should be:</p>
<pre><code>MyString = ' x.ABC,\... | -2 | 2016-10-17T15:38:03Z | 40,090,631 | <p>You can split the string into lines, and further split the lines into words and use <a href="https://docs.python.org/2/library/itertools.html#itertools.takewhile" rel="nofollow"><code>itertools.takewhile</code></a> to drop all words after <code>AND</code> (itself included):</p>
<pre><code>from itertools import take... | 1 | 2016-10-17T15:46:37Z | [
"python",
"string"
] |
Removing parts of a string after certain chars in Python | 40,090,472 | <p>New to Python.</p>
<p>I'd like to remove the substrings between the word AND and the comma character in the following string:</p>
<pre><code>MyString = ' x.ABC AND XYZ, \ny.DEF AND Type, \nSome Long String AND Qwerty, \nz.GHI AND Tree \n'
</code></pre>
<p>The result should be:</p>
<pre><code>MyString = ' x.ABC,\... | -2 | 2016-10-17T15:38:03Z | 40,090,657 | <p>While Moses's answer is really good, I have a funny feeling this is a homework question and meant for you not to use any imports. Anyways here's an answer with no imports, it's not as efficient as other answers like Moses' or Regex but it works just not as well as others.</p>
<pre><code>MyString = 'x.ABC AND XYZ, \... | 1 | 2016-10-17T15:48:19Z | [
"python",
"string"
] |
Removing parts of a string after certain chars in Python | 40,090,472 | <p>New to Python.</p>
<p>I'd like to remove the substrings between the word AND and the comma character in the following string:</p>
<pre><code>MyString = ' x.ABC AND XYZ, \ny.DEF AND Type, \nSome Long String AND Qwerty, \nz.GHI AND Tree \n'
</code></pre>
<p>The result should be:</p>
<pre><code>MyString = ' x.ABC,\... | -2 | 2016-10-17T15:38:03Z | 40,090,829 | <p>Now it is working.. and probably avoiding the 'append' keyword makes it really fast... </p>
<pre><code>In [19]: ',\n'.join([x.split('AND')[0].strip() for x in MyString.split('\n')])
Out[19]: 'x.ABC,\ny.DEF,\nSome Long String,\nz.GHI,\n'
</code></pre>
<p>You can check this answer to understand why...</p>
<p><a h... | 0 | 2016-10-17T15:58:01Z | [
"python",
"string"
] |
Why the Pool class in multiprocessing lack the __exit__() method in Python 2? | 40,090,519 | <p>It is not clear to me why the <a href="http://fossies.org/dox/Python-2.7.12/pool_8py_source.html" rel="nofollow">Python 2.7 implementation</a> of <code>Pool</code> does not have the <code>__exit__()</code> method that is present in the <a href="http://fossies.org/dox/Python-3.5.2/pool_8py_source.html" rel="nofollow"... | 0 | 2016-10-17T15:40:02Z | 40,091,484 | <p>Doesn't seem like there's any reason to avoid it. Looking at it and testing it real quick didn't bring up any odd behavior. This was implemented in <a href="http://bugs.python.org/issue15064" rel="nofollow"><em>Issue 15064</em></a>, it just seems it wasn't added in <code>2.7</code> (probably because only bug-fixes w... | 2 | 2016-10-17T16:36:10Z | [
"python",
"python-2.7",
"python-3.x",
"threadpool",
"python-multiprocessing"
] |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | <p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>
<pre><code>for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
</code></pre>
<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>
<p>Is ther... | 5 | 2016-10-17T15:40:08Z | 40,090,688 | <p>use <code>loc</code> and <code>where</code></p>
<pre><code>cols = ['a', 'b', 'c']
df.loc[:, cols] = df[cols].where(df[cols].whwere.ge(0), np.nan)
</code></pre>
<p><strong><em>demonstration</em></strong></p>
<pre><code>df = pd.DataFrame(np.random.randn(10, 5), columns=list('abcde'))
df
</code></pre>
<p><a href="h... | 4 | 2016-10-17T15:49:49Z | [
"python",
"pandas"
] |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | <p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>
<pre><code>for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
</code></pre>
<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>
<p>Is ther... | 5 | 2016-10-17T15:40:08Z | 40,090,694 | <p>Here's a way:</p>
<pre><code>df[df.columns.isin(['a', 'b', 'c']) & (df < 0)] = np.nan
</code></pre>
| 5 | 2016-10-17T15:50:03Z | [
"python",
"pandas"
] |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | <p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>
<pre><code>for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
</code></pre>
<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>
<p>Is ther... | 5 | 2016-10-17T15:40:08Z | 40,090,735 | <p>You can use <code>np.where</code> to achieve this:</p>
<pre><code>In [47]:
df = pd.DataFrame(np.random.randn(5,5), columns=list('abcde'))
df
Out[47]:
a b c d e
0 0.616829 -0.933365 -0.735308 0.665297 -1.333547
1 0.069158 2.266290 -0.068686 -0.787980 -0.082090
2 1.2033... | 4 | 2016-10-17T15:51:51Z | [
"python",
"pandas"
] |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | <p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>
<pre><code>for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
</code></pre>
<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>
<p>Is ther... | 5 | 2016-10-17T15:40:08Z | 40,090,749 | <p>If it has to be a one-liner:</p>
<pre><code>df[['a', 'b', 'c']] = df[['a', 'b', 'c']].apply(lambda c: [x>0 and x or np.nan for x in c])
</code></pre>
| 1 | 2016-10-17T15:53:08Z | [
"python",
"pandas"
] |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | <p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>
<pre><code>for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
</code></pre>
<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>
<p>Is ther... | 5 | 2016-10-17T15:40:08Z | 40,090,781 | <p>I don't think you'll get much simpler than this:</p>
<pre><code>>>> df = pd.DataFrame({'a': np.arange(-5, 2), 'b': np.arange(-5, 2), 'c': np.arange(-5, 2), 'd': np.arange(-5, 2), 'e': np.arange(-5, 2)})
>>> df
a b c d e
0 -5 -5 -5 -5 -5
1 -4 -4 -4 -4 -4
2 -3 -3 -3 -3 -3
3 -2 -2 -2 -2 -2
4 -... | 9 | 2016-10-17T15:55:19Z | [
"python",
"pandas"
] |
Pandas: How to conditionally assign multiple columns? | 40,090,522 | <p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>
<pre><code>for col in ['a', 'b', 'c']:
df.loc[df[col ] < 0, col] = np.nan
</code></pre>
<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>
<p>Is ther... | 5 | 2016-10-17T15:40:08Z | 40,090,782 | <p>Sure, just pick your desired columns out of the mask:</p>
<pre><code>(df < 0)[['a', 'b', 'c']]
</code></pre>
<p>You can use this mask in <code>df[(df < 0)[['a', 'b', 'c']]] = np.nan</code>.</p>
| 3 | 2016-10-17T15:55:24Z | [
"python",
"pandas"
] |
Python type checking not working as expected | 40,090,600 | <p>I'm sure I'm missing something obvious here, but why does the following script actually work?</p>
<pre><code>import enum
import typing
class States(enum.Enum):
a = 1
b = 2
states = typing.NewType('states', States)
def f(x: states) -> states:
return x
print(
f(States.b),
f(3)
)
</code></pr... | 2 | 2016-10-17T15:44:41Z | 40,090,625 | <p>No checking is performed by Python itself. This is specified in the <a href="https://www.python.org/dev/peps/pep-0484/#non-goals" rel="nofollow">"Non- Goals" section</a> of PEP 484. When executed (i.e during run-time), Python completely ignores the annotations you provided and evaluates your statements as it usually... | 3 | 2016-10-17T15:46:21Z | [
"python",
"python-3.x",
"types",
"type-hinting"
] |
pandas: merge conditional on time range | 40,090,619 | <p>I'd like to merge one data frame with another, where the merge is conditional on the date/time falling in a particular range. </p>
<p>For example, let's say I have the following two data frames.</p>
<pre><code>import pandas as pd
import datetime
# Create main data frame.
data = pd.DataFrame()
time_seq1 = pd.DataF... | 2 | 2016-10-17T15:46:15Z | 40,091,177 | <p>Not very beautiful, but i think it works.</p>
<pre><code>data['specialID'] = None
foolist = list(data2['myID'])
for i in data.index:
if data.myID[i] in foolist:
if data.Timestamp[i]> list(data2[data2['myID'] == data.myID[i]].time)[0]:
data['specialID'][i] = list(data2[data2['myID'] == dat... | 1 | 2016-10-17T16:17:19Z | [
"python",
"datetime",
"pandas"
] |
pandas: merge conditional on time range | 40,090,619 | <p>I'd like to merge one data frame with another, where the merge is conditional on the date/time falling in a particular range. </p>
<p>For example, let's say I have the following two data frames.</p>
<pre><code>import pandas as pd
import datetime
# Create main data frame.
data = pd.DataFrame()
time_seq1 = pd.DataF... | 2 | 2016-10-17T15:46:15Z | 40,091,640 | <p>You can use <a href="https://pandas-docs.github.io/pandas-docs-travis/generated/pandas.merge_asof.html" rel="nofollow"><code>merge_asof</code></a>, which is new in Pandas 0.19, to do most of the work. Then, combine <code>loc</code> and <code>duplicated</code> to remove secondary matches:</p>
<pre><code># Data need... | 5 | 2016-10-17T16:46:00Z | [
"python",
"datetime",
"pandas"
] |
Program to add together a series of number | 40,090,659 | <blockquote>
<p>I am writing a program that will add together a series of
numbers a user inputs until the user enters a rogue value of 0. The
program will then display the total.</p>
</blockquote>
<pre><code>user_input = None
total_sum = 0
while user_input != 0:
user_input = input("Enter a number:")
tota... | 1 | 2016-10-17T15:48:25Z | 40,090,716 | <p>you need to cast the input to an int</p>
<pre><code>user_input = int(user_input )
</code></pre>
| 0 | 2016-10-17T15:50:41Z | [
"python",
"python-3.x",
"loops"
] |
Program to add together a series of number | 40,090,659 | <blockquote>
<p>I am writing a program that will add together a series of
numbers a user inputs until the user enters a rogue value of 0. The
program will then display the total.</p>
</blockquote>
<pre><code>user_input = None
total_sum = 0
while user_input != 0:
user_input = input("Enter a number:")
tota... | 1 | 2016-10-17T15:48:25Z | 40,090,722 | <p><code>input</code> returns a string, even if it's a string that contains a number (e.g., "5"). You need to explicitly convert it to an <code>int</code>:</p>
<pre><code>user_input = int(input("Enter a number: "))
</code></pre>
| 0 | 2016-10-17T15:51:18Z | [
"python",
"python-3.x",
"loops"
] |
Program to add together a series of number | 40,090,659 | <blockquote>
<p>I am writing a program that will add together a series of
numbers a user inputs until the user enters a rogue value of 0. The
program will then display the total.</p>
</blockquote>
<pre><code>user_input = None
total_sum = 0
while user_input != 0:
user_input = input("Enter a number:")
tota... | 1 | 2016-10-17T15:48:25Z | 40,090,772 | <p>You need to parse String value to Integer value.</p>
<p>In your case, <code>user_input</code> is String Value.</p>
<p>To parse String value to Integer you need to use <code>int(user_input)</code> instead of <code>user_input</code>.</p>
<p>total_sum = total_sum + int(user_input) //Like this</p>
| 0 | 2016-10-17T15:54:24Z | [
"python",
"python-3.x",
"loops"
] |
Program to add together a series of number | 40,090,659 | <blockquote>
<p>I am writing a program that will add together a series of
numbers a user inputs until the user enters a rogue value of 0. The
program will then display the total.</p>
</blockquote>
<pre><code>user_input = None
total_sum = 0
while user_input != 0:
user_input = input("Enter a number:")
tota... | 1 | 2016-10-17T15:48:25Z | 40,090,783 | <p>input("Enter a number") returns a string which means user_input is of type string.
So you need to cast user_input to int in order to add. i.e. <code>total_sum = total_sum + parseInt(user_input)</code></p>
| 0 | 2016-10-17T15:55:24Z | [
"python",
"python-3.x",
"loops"
] |
How I can use external stylesheet for PyQT4 project? | 40,090,669 | <p>I am just creating a remote app with pyqt4. So, there is lots of css on the UI. I was wondering how to use external stylessheets like in web apps.</p>
<p>For Example: </p>
<pre><code>button_one.setStyleSheet("QPushButton { background-color:#444444; color:#ffffff; border: 2px solid #3d3d3d; width: 15px; height: 25p... | 0 | 2016-10-17T15:48:56Z | 40,092,488 | <p>There's no need to set a stylesheet on each widget. Just set one stylesheet for the whole application:</p>
<pre><code>stylesheet = """
QPushButton#styleid {
background-color: yellow;
}
QPushButton.styleclass {
background-color: magenta;
}
QPushButton {
color: blue;
}
"""
QtGui.qApp.setStyleSheet(styles... | 1 | 2016-10-17T17:38:45Z | [
"python",
"qt",
"user-interface",
"pyqt4"
] |
How I can use external stylesheet for PyQT4 project? | 40,090,669 | <p>I am just creating a remote app with pyqt4. So, there is lots of css on the UI. I was wondering how to use external stylessheets like in web apps.</p>
<p>For Example: </p>
<pre><code>button_one.setStyleSheet("QPushButton { background-color:#444444; color:#ffffff; border: 2px solid #3d3d3d; width: 15px; height: 25p... | 0 | 2016-10-17T15:48:56Z | 40,103,604 | <p>Cool. Thank you so much for your answer. That helped me to separate my styles finally :) </p>
<p>Just defined all my apps styles on the external file and linked on the required page.
styleFile = "styles/remote.stylesheet"
with open(styleFile, "r") as fh:
self.setStyleSheet(fh.read()) </p>
| 0 | 2016-10-18T08:46:49Z | [
"python",
"qt",
"user-interface",
"pyqt4"
] |
How to recursively remove the first set of parantheses in string of nested parantheses? (in Python) | 40,090,673 | <p>EDIT:
Say I have a string of nested parentheses as follows: ((AB)CD(E(FG)HI((J(K))L))) (assume the parantheses are balanced and enclose dproperly
How do i recursively remove the first set of fully ENCLOSED parantheses of every subset of fully enclosed parentheses?</p>
<p>So in this case would be (ABCD(E(FG)HI(JK))... | -2 | 2016-10-17T15:49:04Z | 40,091,099 | <p>You need to reduce your logic to something clear enough to program. What I'm getting from your explanations would look like the code below. Note that I haven't dealt with edge cases: you'll need to check for None elements, hitting the end of the list, etc.</p>
<pre><code>def simplfy(parse_list):
# Find the f... | 0 | 2016-10-17T16:12:15Z | [
"python",
"string",
"algorithm",
"recursion"
] |
How to recursively remove the first set of parantheses in string of nested parantheses? (in Python) | 40,090,673 | <p>EDIT:
Say I have a string of nested parentheses as follows: ((AB)CD(E(FG)HI((J(K))L))) (assume the parantheses are balanced and enclose dproperly
How do i recursively remove the first set of fully ENCLOSED parantheses of every subset of fully enclosed parentheses?</p>
<p>So in this case would be (ABCD(E(FG)HI(JK))... | -2 | 2016-10-17T15:49:04Z | 40,091,154 | <p>If I understood the question correctly, this ugly function should do the trick:</p>
<pre><code>def rm_parens(s):
s2 = []
consec_parens = 0
inside_nested = False
for c in s:
if c == ')' and inside_nested:
inside_nested = False
consec_parens = 0
continue
... | 0 | 2016-10-17T16:15:35Z | [
"python",
"string",
"algorithm",
"recursion"
] |
Implementing __eq__ using numpy isclose | 40,090,734 | <p>I fear this might be closed as being a soft question,
but perhaps there is an obvious idiomatic way.</p>
<p>I have a class that contains a lot of information stored in floating point numbers.
I am thinking about implementing the <code>__eq__</code> method using not exact but numerical equivalence similar to <code>... | 0 | 2016-10-17T15:51:51Z | 40,095,109 | <p>One option would be to add a context manager to switch modes:</p>
<pre><code>from contextlib import contextmanager
class MyObject(object):
_use_loose_equality = False
@contextmanager
@classmethod
def loose_equality(cls, enabled=True):
old_mode = cls._use_loose_equality
cls._use_loose... | 1 | 2016-10-17T20:28:13Z | [
"python",
"python-3.x",
"numpy",
"floating-point",
"precision"
] |
Python convert json to python object and visit attribute using comma | 40,090,741 | <p>As title, A json object or convert to a python object like:</p>
<pre><code>u = {
"name": "john",
"coat": {
"color": "red",
"sex": "man",
},
"groups": [
{"name": "git"},
{"name": "flask"}
]
}
</code></pre>
<p>I want visit as:</p>
<pre><code>u.name
</code></pre>
... | -3 | 2016-10-17T15:52:04Z | 40,091,938 | <p>Python is not JavaScript. You need to refer to <code>u["groups"][0]["name"]</code>.</p>
| 1 | 2016-10-17T17:03:25Z | [
"python"
] |
Python convert json to python object and visit attribute using comma | 40,090,741 | <p>As title, A json object or convert to a python object like:</p>
<pre><code>u = {
"name": "john",
"coat": {
"color": "red",
"sex": "man",
},
"groups": [
{"name": "git"},
{"name": "flask"}
]
}
</code></pre>
<p>I want visit as:</p>
<pre><code>u.name
</code></pre>
... | -3 | 2016-10-17T15:52:04Z | 40,099,026 | <p>May be it's difficult, because integer as key is invalid.</p>
<p>I do like this </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>class Dict(dict):
def __init__... | 0 | 2016-10-18T03:29:40Z | [
"python"
] |
How to select by WEEK and count it in postgresql and Django | 40,090,744 | <p>I'm trying to select by week and counting how many tickets were sold on that week.</p>
<p>i select the tickets using EVENT ID.</p>
<pre><code>WHERE EVENT ID 148
SAMPLE DATA: TICKETS TABLE
-------------------------------------------------
"General";0;"2016-09-02 17:50:45.644381+00"
"General";0;"2016-09-03 ... | -2 | 2016-10-17T15:52:26Z | 40,093,032 | <p>Here is a solution that I used in a similar situation.
I used a Raw SQL query however.</p>
<pre><code>Ticket.objects.raw('''SELECT COUNT(app_ticket.id) as id, app_ticket.name, EXTRACT(WEEK FROM app_ticket.created) as week, EXTRACT(YEAR FROM app_ticket.created) as YEAR
FROM app_ticket
WHERE app_ticket.ev... | 1 | 2016-10-17T18:14:40Z | [
"python",
"django",
"postgresql",
"date"
] |
Check failed: error == cudaSuccess (2 vs. 0) out of memory | 40,090,892 | <p>I am trying to run a neural network with pycaffe on gpu.</p>
<p>This works when I call the script for the first time.
When I run the same script for the second time, CUDA throws the error in the title.</p>
<p>Batch size is 1, image size at this moment is 243x322, the gpu has 8gb RAM.</p>
<p>I guess I am missing a... | 2 | 2016-10-17T16:01:11Z | 40,091,765 | <p>This happens when you run out of memory in the GPU. Are you sure you stopped the first script properly? Check the running processes on your system (<code>ps -A</code> in ubuntu) and see if the python script is still running. Kill it if it is. You should also check the memory being used in your GPU (<code>nvidia-smi<... | 2 | 2016-10-17T16:53:48Z | [
"python",
"gpu",
"caffe"
] |
Check failed: error == cudaSuccess (2 vs. 0) out of memory | 40,090,892 | <p>I am trying to run a neural network with pycaffe on gpu.</p>
<p>This works when I call the script for the first time.
When I run the same script for the second time, CUDA throws the error in the title.</p>
<p>Batch size is 1, image size at this moment is 243x322, the gpu has 8gb RAM.</p>
<p>I guess I am missing a... | 2 | 2016-10-17T16:01:11Z | 40,092,858 | <p>Your GPU memory is not getting freed. This happens when the previous process is stopped but not terminated. See my answer <a href="http://stackoverflow.com/a/35748621/3579977">here</a>.</p>
| 3 | 2016-10-17T18:02:44Z | [
"python",
"gpu",
"caffe"
] |
Throw a NotImplementedError in Python | 40,090,907 | <p>when I try to run my code I face with this issue I have defined a real-time request for this scraping but still does not working. anyone knows how to deal with this issue in python?
How sitemap is important in this case?
Thanks in advance </p>
<pre><code>import logging
import re
from urllib.parse import urljoin,... | -2 | 2016-10-17T16:01:49Z | 40,094,130 | <p>The exception is being thrown because your class <code>CNNnewsSpider</code> does not override the method <code>parse()</code> from <code>scrapy.BaseSpider</code>. Although you are defining a <code>parse()</code> method in the code you pasted, it is not being included in <code>CNNnewsSpider</code> because of indenta... | 0 | 2016-10-17T19:24:51Z | [
"python",
"python-3.x",
"scrapy",
"web-crawler",
"webscarab"
] |
Gmail authentication error when sending email via django celery | 40,090,925 | <p><strong>TL;DR</strong>: I get a SMTPAuthenticationError from Gmail when trying to send emails using Celery/RabbitMQ tasks from my Django app, despite the credentials passed in are correct. This does not happen when the emails are sent normally, without Celery.</p>
<p>Hi,</p>
<p>I am trying to send email to a user ... | 0 | 2016-10-17T16:02:43Z | 40,090,979 | <p>Try to make an app password here <a href="https://security.google.com/settings/security/apppasswords" rel="nofollow">https://security.google.com/settings/security/apppasswords</a> and use it as your password in the STMP settings. </p>
| 0 | 2016-10-17T16:06:01Z | [
"python",
"django",
"smtp",
"gmail",
"celery"
] |
Extracting articles from New York Post by using Python and New York Post API | 40,090,962 | <p>I am trying to create a corpus of text documents via the New york Times API (articles concerning terrorist attacks) on Python.</p>
<p>I am aware that the NYP API do not provide the full body text, but provides the URL from which I can scrape the article. So the idea is to extract the "web_url" parameters from the A... | 0 | 2016-10-17T16:04:58Z | 40,091,026 | <p>The comma in the print statement separates what is printed. </p>
<p>You'll want something like this </p>
<pre><code>articles['response']['docs']['web_url']
</code></pre>
<p>But <code>'docs': []</code> is both an array and empty, so above line won't work, so you could try </p>
<pre><code>articles = articles['resp... | 0 | 2016-10-17T16:08:40Z | [
"python"
] |
Extracting articles from New York Post by using Python and New York Post API | 40,090,962 | <p>I am trying to create a corpus of text documents via the New york Times API (articles concerning terrorist attacks) on Python.</p>
<p>I am aware that the NYP API do not provide the full body text, but provides the URL from which I can scrape the article. So the idea is to extract the "web_url" parameters from the A... | 0 | 2016-10-17T16:04:58Z | 40,092,566 | <p>There seems to be an issue with the <code>nytimesarticle</code> module itself. For example, see the following:</p>
<pre><code>>>> articles = api.search(q="trump+women+accuse", begin_date=20161001)
>>> print(articles)
{'response': {'docs': [], 'meta': {'offset': 0, 'hits': 0, 'time': 21}}, 'status'... | 0 | 2016-10-17T17:43:55Z | [
"python"
] |
Dynamic create questions with inquirer | 40,091,057 | <p>i have the following object:</p>
<pre><code>questions = [
{ 'type': 'Text'
, 'name': 'input_file'
, 'message': 'Input file'
}
]
</code></pre>
<p>And i want transform into this:</p>
<pre><code>inquirer.Text(name = 'input_file', message = 'Input file')
</code></pre>
<p>So, i'm using the fol... | 0 | 2016-10-17T16:09:35Z | 40,091,102 | <p>You need to use <code>getattr</code>:</p>
<pre><code>for question in questions:
q.append(getattr(inquirer, question['type'])(question['name'], question['message']))
</code></pre>
<p>You can read more about it <a href="http://stackoverflow.com/questions/7119235/in-python-what-is-the-difference-between-an-object... | 0 | 2016-10-17T16:12:16Z | [
"python"
] |
How do I add several books to the bookstore in the admin form | 40,091,067 | <p>In django, imagine i have a model bookstore and a model book which has a foreign key to bookStore model . On the django admin,I added like 10 books, and on the bookstore I want to assign multiple books to this one bookstore. How do I do this ? Because even with foreignKey, while editing the bookstore, i can only cho... | 0 | 2016-10-17T16:10:00Z | 40,091,135 | <p>Your relationship is the wrong way around. If your bookstore has a fk to a book, you are saying that "each bookstore can only store one single book". Instead, you should have a fk from the book to the book store. This is saying "a book belongs to a bookstore (and only one bookstore)"</p>
<pre><code>class Book:
... | 4 | 2016-10-17T16:14:36Z | [
"python",
"django"
] |
Maximize Sharpe's ratio using scipy.minimze | 40,091,188 | <p>I'm trying to maximize Sharpe's ratio using scipy.minimize</p>
<p><img src="http://latex.codecogs.com/gif.latex?%5Cfrac%7BE_R%20-%20E_F%7D%7B%5Csigma_R%7D" alt="1"></p>
<p>I do this for finding CAPM's Security Market Line</p>
<p><img src="http://latex.codecogs.com/gif.latex?E%28R%29%20%3D%20E_F%20+%20%5Cfrac... | 1 | 2016-10-17T16:18:22Z | 40,091,485 | <p>I dont know why, but it works perfectly, when I replacing </p>
<pre><code>x = np.zeros(len(profits))
</code></pre>
<p>With</p>
<pre><code>x = np.ones(len(profits))
</code></pre>
| 0 | 2016-10-17T16:36:13Z | [
"python",
"scipy",
"mathematical-optimization",
"nonlinear-optimization"
] |
Troubleshooting item loaders between callbacks | 40,091,228 | <p>In order to understand the "Naive approach" example in <a href="http://oliverguenther.de/2014/08/almost-asynchronous-requests-for-single-item-processing-in-scrapy/" rel="nofollow">http://oliverguenther.de/2014/08/almost-asynchronous-requests-for-single-item-processing-in-scrapy/</a> </p>
<p>I am trying to replicate... | 1 | 2016-10-17T16:20:52Z | 40,093,685 | <p>The css selector is do definitely work. The problem resides in the itemloader variable <strong>l</strong> in which you are saving in the meta dict, it points to the response from <strong>firstRequest</strong> callback, not to the <strong>parseDescription1</strong> callback in which this css selector can work</p>
<p... | 0 | 2016-10-17T18:56:49Z | [
"python",
"csv",
"scrapy",
"web-crawler"
] |
Extract all characters between _ and .csv | 40,091,243 | <p>I am trying to extract the date from a series of files of the form:</p>
<p><code>costs_per_day_100516.csv</code></p>
<p>I have gotten to the point of extracting the <code>6</code>, but I don't understand why I can't extract more. What is wrong with the following:</p>
<pre><code>test_string = 'search_adwords_cost_... | 0 | 2016-10-17T16:21:36Z | 40,091,273 | <pre><code>m = re.search("_([^_]*)\.csv", test_string)
</code></pre>
<p>The repetition qualifier has to be inside the capture</p>
| 3 | 2016-10-17T16:23:27Z | [
"python",
"regex"
] |
Extract all characters between _ and .csv | 40,091,243 | <p>I am trying to extract the date from a series of files of the form:</p>
<p><code>costs_per_day_100516.csv</code></p>
<p>I have gotten to the point of extracting the <code>6</code>, but I don't understand why I can't extract more. What is wrong with the following:</p>
<pre><code>test_string = 'search_adwords_cost_... | 0 | 2016-10-17T16:21:36Z | 40,092,030 | <pre><code>Data_Frame_Name.join(filter(lambda x: x.isdigit(), Data_Frame_Name['Column_Name']))
</code></pre>
<p>This will extract just digits. This may not be applicable for your case but would work well for extracting digits from multiple rows in a column.</p>
| 0 | 2016-10-17T17:09:37Z | [
"python",
"regex"
] |
Cannot debug tensorflow using gdb on macOS | 40,091,310 | <p>I am trying to debug TensorFlow using GDB on macOS Sierra. I followed the instructions on the <a href="https://gist.github.com/Mistobaan/738e76c3a5bb1f9bcc52e2809a23a7a1#run-python-test" rel="nofollow">post</a>.After I installed developer version of tensorflow for debug I tried to use gdb to attach a python session.... | 0 | 2016-10-17T16:25:37Z | 40,120,761 | <p>Well, after I change to use <code>lldb</code> on macOS, everything works fine. So I guess the solution to this problem is "USING LLDB INSTEAD OF GDB".</p>
| 0 | 2016-10-19T01:49:18Z | [
"python",
"debugging",
"gdb",
"tensorflow"
] |
Getting 403 Error: Apache2 mod_wsgi | 40,091,341 | <p>Me, and a friend of mine are facing a problem getting a raw entity of <a href="https://github.com/PiJoules/atchannel/blob/master/PRODUCTION.md" rel="nofollow" title="Guide to Setting it up">PI Joule's @channel (Link to "Production" Readme)</a> to work, currently supposed to be running at the domain atchannel.cf, as ... | 0 | 2016-10-17T16:27:41Z | 40,094,843 | <p>Instead of:</p>
<pre><code><Directory /var/www-atchannel/atchannel/>
Order allow,deny
Allow from all
</Directory>
</code></pre>
<p>you should have:</p>
<pre><code><Directory /var/www-atchannel>
Order allow,deny
Allow from all
</Directory>
</code></pre>
<p>The directory did... | 0 | 2016-10-17T20:09:56Z | [
"python",
"mongodb",
"apache",
"virtualhost",
"wsgi"
] |
Call another click command from a click command | 40,091,347 | <p>I want to use some useful functions as commands. For that I am testing the <code>click</code> library. I defined my three original functions then decorated as <code>click.command</code>:</p>
<pre><code>import click
import os, sys
@click.command()
@click.argument('content', required=False)
@click.option('--to_stdou... | 0 | 2016-10-17T16:28:08Z | 40,094,408 | <p>When you call <code>add_name()</code> and <code>add_surname()</code> directly from another function, you actually call the decorated versions of them so the arguments expected may not be as you defined them (see the answers to <a href="http://stackoverflow.com/questions/1166118/how-to-strip-decorators-from-a-functio... | 2 | 2016-10-17T19:43:05Z | [
"python",
"command-line-arguments",
"stdout",
"piping",
"python-click"
] |
Call another click command from a click command | 40,091,347 | <p>I want to use some useful functions as commands. For that I am testing the <code>click</code> library. I defined my three original functions then decorated as <code>click.command</code>:</p>
<pre><code>import click
import os, sys
@click.command()
@click.argument('content', required=False)
@click.option('--to_stdou... | 0 | 2016-10-17T16:28:08Z | 40,096,967 | <p>Due to the click decorators the functions can no longer be called just by specifying the arguments.
The <a href="http://click.pocoo.org/6/api/#context" rel="nofollow">Context</a> class is your friend here, specifically:</p>
<ol>
<li>Context.invoke() - invokes another command with the arguments you supply</li>
<li>... | 1 | 2016-10-17T23:00:32Z | [
"python",
"command-line-arguments",
"stdout",
"piping",
"python-click"
] |
Given a binary tree, print all root-to-leaf paths using scipy | 40,091,369 | <p>I'm using the <code>hierarchy.to_tree</code> from scipy, and I'm interested in getting a print out of all root-to-leaf paths:</p>
<p><a href="https://i.stack.imgur.com/Nuzo8.gif" rel="nofollow"><img src="https://i.stack.imgur.com/Nuzo8.gif" alt="enter image description here"></a></p>
<p><code>
10.8.3
10.8.5
10.2.2... | 0 | 2016-10-17T16:29:32Z | 40,091,495 | <p>Without looking at your code, you should be doing something like:</p>
<pre><code>print_paths(tree, seen):
seen = seen
seen.append(tree.value)
if not tree.children:
print(seen)
else:
map(print_paths, tree.children)
</code></pre>
<p>Having now seen your code, try something like:</p>
... | 1 | 2016-10-17T16:36:37Z | [
"python",
"tree",
"scipy"
] |
Remove only double letters sequences in word with best speed with python | 40,091,435 | <p>Very popular task for finding/replacing double letters in a string. But exist solution, where you can make remove double letters through few steps. For example, we have string <code>"skalallapennndraaa"</code>, and after replacing double letters we need to get in output <code>"skalpendra"</code>. I tried solution wi... | 0 | 2016-10-17T16:33:23Z | 40,091,593 | <p>You can use this double replacement:</p>
<pre><code>>>> s = 'skalallapennndraaa'
>>> print re.sub(r'([a-z])\1', '', re.sub(r'([a-z])([a-z])\2\1', '', s))
skalpendra
</code></pre>
<p><code>([a-z])([a-z])\2\1</code> will remove <code>alla</code> type of cases and <code>([a-z])\1</code> will remove ... | 2 | 2016-10-17T16:43:33Z | [
"python",
"regex",
"string"
] |
How is base Exception getting initialized? | 40,091,472 | <p>I'm confused by how the following exception in Python 3 gets initialized.</p>
<pre><code>class MyException( Exception ):
def __init__(self,msg,foo):
self.foo = foo
raise MyException('this is msg',123)
</code></pre>
<p>In Python 3, this outputs:</p>
<pre><code>Traceback (most recent call last):
Fil... | 0 | 2016-10-17T16:35:39Z | 40,091,499 | <p>The Python <code>BaseException</code> class is special in that it has a <code>__new__</code> method that is put there specifically to handle this common case of errors.</p>
<p>So no, <code>BaseException.__init__</code> is not being called, but <code>BaseException.__new__</code> <em>is</em>. You can override <code>_... | 2 | 2016-10-17T16:37:08Z | [
"python",
"python-3.x",
"exception",
"python-2.x"
] |
Python HTML source code | 40,091,490 | <p>I would like to write a script that picks a special point from the source code and returns it. (print it)</p>
<pre><code>import urllib.request
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
print(html_code.read().decode('ISO-8859-1'))
</cod... | 0 | 2016-10-17T16:36:27Z | 40,091,626 | <p>You could use <a href="http://jsonip.com" rel="nofollow">jsonip</a> which returns a JSON object that you can easily parse using standard Python library</p>
<pre><code>import json
from urllib2 import urlopen
my_ip = json.load(urlopen('http://jsonip.com'))['ip']
</code></pre>
| 0 | 2016-10-17T16:44:54Z | [
"python",
"python-3.x"
] |
Python HTML source code | 40,091,490 | <p>I would like to write a script that picks a special point from the source code and returns it. (print it)</p>
<pre><code>import urllib.request
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
print(html_code.read().decode('ISO-8859-1'))
</cod... | 0 | 2016-10-17T16:36:27Z | 40,091,730 | <pre><code>import requests
from bs4 import BeautifulSoup
s = requests.Session()
r = s.get('http://myip.is/')
soup = BeautifulSoup(r.text, "html5lib")
myIP = mySoup.find('a', {'title': 'copy ip address'}).text
print(myIP)
</code></pre>
<p>This uses the requests library (which you should always use for HTTP requests) ... | 0 | 2016-10-17T16:51:40Z | [
"python",
"python-3.x"
] |
Python HTML source code | 40,091,490 | <p>I would like to write a script that picks a special point from the source code and returns it. (print it)</p>
<pre><code>import urllib.request
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
print(html_code.read().decode('ISO-8859-1'))
</cod... | 0 | 2016-10-17T16:36:27Z | 40,092,082 | <p>You can use a regular expression to find the IP addresses:</p>
<pre><code>import urllib.request
import re
Webseite = "http://myip.is/"
html_code = urllib.request.urlopen(Webseite)
content = html_code.read().decode('ISO-8859-1')
ip_regex = r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
ips_found = re.findall(ip_regex, content)... | 0 | 2016-10-17T17:12:35Z | [
"python",
"python-3.x"
] |
In pytesting, how to provide the link/pointer to the file/image for uploading the image in flask | 40,091,539 | <p>I am using flask with python 3.5 and try to test my code with pytest for uploading the image.I have gone through various answers but sadly couldn't get the point to solve my problem.In link of github, it explains how to use filename, file_field
<a href="https://gist.github.com/DazWorrall/1779861" rel="nofollow">http... | 0 | 2016-10-17T16:39:54Z | 40,100,812 | <p>res = test_client.post(
products_url,
content_type='multipart/form-data',
buffered=True,
data={
'file': (io.BytesIO(b'~/Downloads/images'), 'user4.jpg'),
})</p>
<p>Little bit change the way data is send.
It is working fine for me.</p>
| 0 | 2016-10-18T06:12:48Z | [
"python",
"flask",
"py.test"
] |
Flask+Gunicorn+Nginx occur AttributeError "NoneType" has no attribute | 40,091,571 | <p>I'm reading Flask Web Development book , and now I've deployed my app on VPS.
And I can visit my index page by using IP.
But when I tried to click Login button (The page which you can fill the inforamtion or register the account)
It occurred alarm as below.
I totally dunt get it...why it said the response of flask l... | -1 | 2016-10-17T16:42:00Z | 40,112,362 | <p>Finally I found the problem .
That was caused from another file /main/views.py
At the end of file , there is a function which was used to test the response time , and it return the response object , but I add one extra indentation in the line.
After I cancel one indentation , it works normally.</p>
<pre><code>@main... | 0 | 2016-10-18T15:32:26Z | [
"python",
"html",
"nginx",
"flask"
] |
Test for consecutive numbers in list | 40,091,617 | <p>I have a list that contains only integers, and I want to check if all the numbers in the list are consecutive (the order of the numbers does not matter).</p>
<p>If there are repeated elements, the function should return False.</p>
<p>Here is my attempt to solve this:</p>
<pre><code>def isconsecutive(lst):
"""... | 2 | 2016-10-17T16:44:30Z | 40,091,652 | <p>Here is another solution:</p>
<pre><code>def is_consecutive(l):
setl = set(l)
return len(l) == len(setl) and setl == set(range(min(l), max(l)+1))
</code></pre>
<p>However, your solution is probably better as you don't store the whole range in memory.</p>
<p>Note that you can always simplify</p>
<pre><cod... | 4 | 2016-10-17T16:46:29Z | [
"python",
"list",
"python-3.x"
] |
Test for consecutive numbers in list | 40,091,617 | <p>I have a list that contains only integers, and I want to check if all the numbers in the list are consecutive (the order of the numbers does not matter).</p>
<p>If there are repeated elements, the function should return False.</p>
<p>Here is my attempt to solve this:</p>
<pre><code>def isconsecutive(lst):
"""... | 2 | 2016-10-17T16:44:30Z | 40,092,012 | <p>A better approach in terms of how many times you look at the elements would be to incorporate finding the <em>min</em>, <em>max</em> and <em>short circuiting</em> on any dupe all in one pass, although would probably be beaten by the speed of the builtin functions depending on the inputs:</p>
<pre><code>def mn_mx(l)... | 1 | 2016-10-17T17:08:19Z | [
"python",
"list",
"python-3.x"
] |
What does this ImportError mean when importing my c++ module? | 40,091,698 | <p>I've been working on writing a Python module in C++. I have a C++ <a href="https://github.com/justinrixx/Asteroids2.0/blob/master/gameNNRunner.cpp" rel="nofollow">program</a> that can run on its own. It works great, but I thought it would be better if I could actually call it like a function from Python. So I took m... | 1 | 2016-10-17T16:49:32Z | 40,091,708 | <p>Most likely it means that you're importing a shared library that has a binary interface not compatible with your Python distribution. </p>
<p>So in your case: You have a 64-bit Python, and you're importing a 32-bit library, or vice-versa. (Or as suggested in a comment, a different compiler is used).</p>
| 1 | 2016-10-17T16:50:29Z | [
"python",
"c++"
] |
How can I create a mesh that can be changed without invalidating native sets in Abaqus? | 40,091,703 | <p>The nodesets I create "by feature edge" in Abaqus are invalidated if I change the mesh.
What are my options to prevent this from happening?</p>
<p>I am asking because I am trying to write a phython file in which to change the mesh as a parameter. That will not be possible if changing the mesh invalides the nodesets... | -1 | 2016-10-17T16:49:49Z | 40,138,337 | <p>As usual, there is more than one way. </p>
<p>One technique, if you know the coordinates of some point on or near the edge(s) of interest, is to use the EdgeArray.findAt() method, followed with the Edge.getNodes() method to return the Node objects, and then defining a new set from them. You can use the following co... | 0 | 2016-10-19T17:50:44Z | [
"python",
"mesh",
"abaqus"
] |
GET variables with Jade in Django templates | 40,091,704 | <p>I use Jade (pyjade) with my Django project. For now I need to use <code>static</code> template tag with GET variable specified - something like following: <code>link(rel="shortcut icon", href="{% static 'images/favicon.ico?v=1' %}")</code>. But I get <code>/static/images/favicon.ico%3Fv%3D1</code> instead of <code>/... | 0 | 2016-10-17T16:50:03Z | 40,091,767 | <p>You could try <code>href="{% static 'images/favicon.ico' %}"?v=1'</code></p>
| 0 | 2016-10-17T16:53:53Z | [
"python",
"django",
"jade"
] |
How to accept FormData sent via ajax in Flask? | 40,091,718 | <p>I'm trying to send an image file in a FormData using an Ajax POST request.
I am faced with 2 problems:</p>
<ol>
<li>I do not know how to extract the FormData on the flask part</li>
<li>I 500 internal server error when making an ajax POST request (not sure if this is because of 1) </li>
</ol>
<p>Thank you</p>
<p>F... | 0 | 2016-10-17T16:50:56Z | 40,094,189 | <p>The following code should work for you. <strong>You need to have the <code>static</code> folder in the same level as your <code>app.py</code> file</strong></p>
<p><strong>app.py</strong></p>
<pre><code>import os
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
app = Flask(__nam... | 0 | 2016-10-17T19:28:37Z | [
"python",
"ajax",
"flask"
] |
Can you write numpy slicing generically? | 40,091,727 | <p>I want to do something like</p>
<pre><code>x[i, :, :] = (rhs[i, :, :]-diag[i] * x[i+1, :, :])/diag[i]
</code></pre>
<p>where x and rhs are 3D numpy arrays of size (T,L,S). diag is a 1D array of size T.</p>
<p>This will broadcast properly. </p>
<p>But now I'd like to write a similar function to work on 2D arrays ... | 1 | 2016-10-17T16:51:33Z | 40,091,799 | <pre><code>x[i] = (rhs[i] - diag[i] * x[i+1])/diag[i]
</code></pre>
<p>Those colons are completely unnecessary.</p>
| 2 | 2016-10-17T16:55:30Z | [
"python",
"numpy"
] |
python os.walk and unicode error | 40,091,750 | <p>two questions:
1. why does </p>
<pre><code>In [21]:
....: for root, dir, file in os.walk(spath):
....: print(root)
</code></pre>
<p>print the whole tree but</p>
<pre><code>In [6]: for dirs in os.walk(spath): ... | 0 | 2016-10-17T16:52:43Z | 40,097,714 | <p>The console you're outputting to doesn't support non-ASCII by default. You need to use <code>str.encode('utf-8')</code>.</p>
<p>That works on strings not on lists. So <code>print(dirs).encode(âutf=8â)</code> won't works, and it's <code>utf-8</code>, not <code>utf=8</code>.</p>
<p>Print your lists with list com... | -1 | 2016-10-18T00:32:16Z | [
"python",
"unicode",
"encoding",
"utf-8",
"vscode"
] |
python os.walk and unicode error | 40,091,750 | <p>two questions:
1. why does </p>
<pre><code>In [21]:
....: for root, dir, file in os.walk(spath):
....: print(root)
</code></pre>
<p>print the whole tree but</p>
<pre><code>In [6]: for dirs in os.walk(spath): ... | 0 | 2016-10-17T16:52:43Z | 40,098,261 | <p>Here's a test case:</p>
<pre><code>C:\TEST
ââââdir1
â file1â¢
â
ââââdir2
file2
</code></pre>
<p>Here's a script (Python 3.x):</p>
<pre><code>import os
spath = r'c:\test'
for root,dirs,files in os.walk(spath):
print(root)
for dirs in os.walk(spath): ... | 2 | 2016-10-18T01:46:41Z | [
"python",
"unicode",
"encoding",
"utf-8",
"vscode"
] |
CSV prints blank column between each data column | 40,091,753 | <p>So, the title explains my question - please see the image for clarification. </p>
<p><a href="https://i.stack.imgur.com/gPJGV.png" rel="nofollow"><img src="https://i.stack.imgur.com/gPJGV.png" alt="enter image description here"></a></p>
<p>I have tried the fixes from a couple of questions on here to no avail, so h... | -1 | 2016-10-17T16:53:04Z | 40,091,911 | <p>I believe what is happening is that you are getting two <code>,</code> characters between each data item.</p>
<p>For example, in <code>['20,', 'start,', '1000,', '1002']</code>, each element is joined with a <code>,</code> because of the <code>delimiter=','</code> option. This means that the <code>,</code> is being... | 0 | 2016-10-17T17:01:30Z | [
"python",
"python-2.7",
"csv"
] |
Pandas: How to find the first valid column among a series of columns | 40,091,796 | <p>I have a dataset of different sections of a race in a pandas dataframe from which I need to calculate certain features. It looks something like this:</p>
<pre><code>id distance timeto1000m timeto800m timeto600m timeto400m timeto200m timetoFinish
1 1400m 10 21 ... | 2 | 2016-10-17T16:55:23Z | 40,091,913 | <p>You can do it like this, first filter the cols of interest and take a slice, then call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmin.html" rel="nofollow"><code>idxmin</code></a> on the cols of interest to return the columns where the boolean condition is met:</p>
<pre><code>... | 2 | 2016-10-17T17:01:42Z | [
"python",
"pandas",
"numpy",
"feature-extraction"
] |
Pandas: How to find the first valid column among a series of columns | 40,091,796 | <p>I have a dataset of different sections of a race in a pandas dataframe from which I need to calculate certain features. It looks something like this:</p>
<pre><code>id distance timeto1000m timeto800m timeto600m timeto400m timeto200m timetoFinish
1 1400m 10 21 ... | 2 | 2016-10-17T16:55:23Z | 40,091,914 | <p>use <code>idxmax(1)</code></p>
<pre><code>df.set_index(['id', 'distance']).ne(0).idxmax(1)
id distance
1 1400m timeto1000m
2 1200m timeto800m
3 1800m timeto400m
4 1000m timeto600m
dtype: object
</code></pre>
| 1 | 2016-10-17T17:01:56Z | [
"python",
"pandas",
"numpy",
"feature-extraction"
] |
Applying a matrix decomposition for classification using a saved W matrix | 40,091,833 | <p>I'm performing an NMF decomposition on a tf-idf input in order to perform topic analysis. </p>
<pre><code>def decomp(tfidfm, topic_count):
model = decomposition.NMF(init="nndsvd", n_components=topic_count, max_iter=500)
H = model.fit_transform(tfidfm)
W = model.components_
return W, H
</code></p... | 0 | 2016-10-17T16:57:07Z | 40,092,629 | <p>The initial equation is: <img src="https://i.stack.imgur.com/Vg05x.gif" alt="initial equation"> and we solve it for <img src="https://i.stack.imgur.com/yuuvq.gif" alt="H"> like this: <img src="https://i.stack.imgur.com/I4jLY.gif" alt="How to solve it for H">.</p>
<p>Here <img src="https://i.stack.imgur.com/ClqEe.gi... | 1 | 2016-10-17T17:47:35Z | [
"python",
"scikit-learn",
"tf-idf",
"matrix-decomposition",
"nmf"
] |
Applying a matrix decomposition for classification using a saved W matrix | 40,091,833 | <p>I'm performing an NMF decomposition on a tf-idf input in order to perform topic analysis. </p>
<pre><code>def decomp(tfidfm, topic_count):
model = decomposition.NMF(init="nndsvd", n_components=topic_count, max_iter=500)
H = model.fit_transform(tfidfm)
W = model.components_
return W, H
</code></p... | 0 | 2016-10-17T16:57:07Z | 40,134,433 | <p>For completeness, here's the rewritten <code>applyModel</code> function that takes into account the answer from ForceBru (uses an import of <code>scipy.sparse.linalg</code>)</p>
<pre><code>def applyModel(tfidfm,W):
H = tfidfm * linalg.inv(W)
return H
</code></pre>
<p>This returns (assuming an aligned vocab... | 0 | 2016-10-19T14:33:47Z | [
"python",
"scikit-learn",
"tf-idf",
"matrix-decomposition",
"nmf"
] |
Find the row number using the first element of the row | 40,091,864 | <p>I have a <code>numpy</code> matrix where I store some kind of key in the first element of the each row (or in another way all keys are in the first column). </p>
<pre><code>[[123,0,1,1,2],
[12,1,2,3,4],
[1,0,2,5,4],
[90,1,1,4,3]]
</code></pre>
<p>I want to get the row number searching by the key. I found that w... | 0 | 2016-10-17T16:59:03Z | 40,092,149 | <p>Compare the first column with <code>90</code> within <code>np.where</code>. It will return an array of the indices of items which are equal with <code>90</code>:</p>
<pre><code>In [3]: A = np.array([[123,0,1,1,2],
[12,1,2,3,4],
[1,0,2,5,4],
[90,1,1,4,3]])
In [6]: np.where(A[:,0]==90)[0]
Out[6]: array([3])
</code>... | 0 | 2016-10-17T17:16:36Z | [
"python",
"numpy"
] |
Find the row number using the first element of the row | 40,091,864 | <p>I have a <code>numpy</code> matrix where I store some kind of key in the first element of the each row (or in another way all keys are in the first column). </p>
<pre><code>[[123,0,1,1,2],
[12,1,2,3,4],
[1,0,2,5,4],
[90,1,1,4,3]]
</code></pre>
<p>I want to get the row number searching by the key. I found that w... | 0 | 2016-10-17T16:59:03Z | 40,092,227 | <p>According to the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html#numpy.where" rel="nofollow">online doc</a>, <code>numpy.where</code> if you give it only a boolean array will return lists of coordinates (one list per dimension) for the elements that are <code>True</code>.
So we can get ... | 1 | 2016-10-17T17:21:24Z | [
"python",
"numpy"
] |
How to find a sentence containing a phrase in text using python re? | 40,091,894 | <p>I have some text which is sentences, some of which are questions. I'm trying to create a regular expression which will extract only the questions which contain a specific phrase, namely 'NSF' :</p>
<pre><code>import re
s = "This is a string. Is this a question? This isn't a question about NSF. Is this one about NSF... | 3 | 2016-10-17T17:00:47Z | 40,094,792 | <p><em>DISCLAIMER</em>: The answer is not aiming at a generic interrogative sentence splitting solution, rather show how the strings supplied by OP can be matched with regular expressions. The best solution is to tokenize the text into sentences with <a href="http://www.nltk.org/" rel="nofollow"><code>nltk</code></a> a... | 1 | 2016-10-17T20:06:53Z | [
"python",
"regex",
"non-greedy"
] |
Deploying Django With AWS | 40,091,919 | <p>So I am trying to <strong>deploy</strong> my <strong>django</strong> app(which mostly has REST Apis) but when I use Amazon CLI, I end up having <strong>Fedora instance</strong>, while I <strong>want</strong> to use <strong>Ubuntu instance</strong>. </p>
<p>So I tried to do this, I made an ubuntu instance, made a re... | 0 | 2016-10-17T17:02:09Z | 40,091,976 | <p>Don't use the <code>runserver</code> command on production. It's meant for local development only. </p>
<p>On production, you need to setup an application server (uwsgi / gunicorn) and then use nginx as a reverse proxy. </p>
<p>Digital Ocean articles are pretty good - <a href="https://www.digitalocean.com/communit... | 3 | 2016-10-17T17:05:43Z | [
"python",
"django",
"git",
"amazon-web-services",
"ubuntu"
] |
Deploying Django With AWS | 40,091,919 | <p>So I am trying to <strong>deploy</strong> my <strong>django</strong> app(which mostly has REST Apis) but when I use Amazon CLI, I end up having <strong>Fedora instance</strong>, while I <strong>want</strong> to use <strong>Ubuntu instance</strong>. </p>
<p>So I tried to do this, I made an ubuntu instance, made a re... | 0 | 2016-10-17T17:02:09Z | 40,092,275 | <p>As mentioned in the other answer, <code>runserver</code> command is only meant for local development. You can, in fact, make it listen on external interfaces by running it as <code>python manage.py runserver 0.0.0.0:8000</code>, but it is a bad idea. Configuring nginx+uwsgi to run a Django app is very easy. There ar... | 0 | 2016-10-17T17:25:15Z | [
"python",
"django",
"git",
"amazon-web-services",
"ubuntu"
] |
z3py: simplify nested Stores with concrete values | 40,091,927 | <p>I'm using the python API of Z3 [version 4.4.2 - 64 bit] and I'm trying to understand why z3 simplifies the expression in this case:</p>
<pre><code>>>> a = Array('a', IntSort(), IntSort())
>>> a = Store(a, 0, 1)
>>> a = Store(a, 0, 3)
>>> simplify(a)
Store(a, 0, 3)
</code></pre>
... | 0 | 2016-10-17T17:02:40Z | 40,093,544 | <p>The simplifier only applies the cheapest rewrites on arrays.
So if it finds two adjacent stores for the same key, it knows to squash the inner most key.
There is generally a high cost of finding overlapping keys, and furthermore keys could be variables where it is not possible to determine whether they are overlapp... | 0 | 2016-10-17T18:47:49Z | [
"python",
"z3",
"z3py"
] |
Pandas/Python adding row based on condition | 40,091,963 | <p>I am looking to insert a row into a dataframe between two existing rows based on certain criteria.</p>
<p>For example, my data frame:</p>
<pre><code> import pandas as pd
df = pd.DataFrame({'Col1':['A','B','D','E'],'Col2':['B', 'C', 'E', 'F'], 'Col3':['1', '1', '1', '1']})
</code></pre>
<p>Which looks like:... | 1 | 2016-10-17T17:05:32Z | 40,093,920 | <p>UPDATE: memory saving method - first set a new index with a gap for a new row:</p>
<pre><code>In [30]: df
Out[30]:
Col1 Col2 Col3
0 A B 1
1 B C 1
2 D E 1
3 E F 1
</code></pre>
<p>if we want to insert a new row between indexes <code>1</code> and <code>2</code>, we split the ind... | 0 | 2016-10-17T19:11:31Z | [
"python",
"pandas"
] |
Inspect a TFRecordReader entry without launching a Session | 40,091,967 | <p>Lets assume I write a TFRecords file with MNIST examples (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/how_tos/reading_data/convert_to_records.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/how_tos/reading_data/convert_to_records.py</a... | 0 | 2016-10-17T17:05:35Z | 40,092,811 | <p>The <code>tf.train.Example.ParseFromString()</code> can be used to transform the string into a protobuf object:</p>
<pre><code>r = ... # String object from `tf.python_io.tf_record_iterator()`.
example_proto = tf.train.Example()
example_proto.ParseFromString(r)
</code></pre>
<p>The schema for this protocol buffer ... | 2 | 2016-10-17T18:00:08Z | [
"python",
"tensorflow"
] |
pandas transpose numeric column by group | 40,091,996 | <p>code to make test data</p>
<pre><code>import pandas as pd
dftest = pd.DataFrame({'Amt': {0: 60, 1: 35.0, 2: 30.0, 3: np.nan, 4: 25},
'Year': {0: 2012.0, 1: 2012.0, 2: 2012.0, 3: 2013.0, 4: 2013.0},
'Name': {0: 'A', 1: 'A', 2: 'C', 3: 'A', 4: 'B'}})
</code></pre>
<p>gi... | 4 | 2016-10-17T17:06:58Z | 40,092,170 | <p>use <code>groupby</code> and <code>apply</code></p>
<pre><code>f = lambda x: x.sort_values(ascending=True).reset_index(drop=True)
dftest.groupby(['Name', 'Year']).Amt.apply(f).unstack()
</code></pre>
<p><a href="https://i.stack.imgur.com/IsAFv.png" rel="nofollow"><img src="https://i.stack.imgur.com/IsAFv.png" alt=... | 4 | 2016-10-17T17:17:28Z | [
"python",
"pandas",
"pivot",
"pivot-table",
"transpose"
] |
Python - Count the duplicate seq element in array | 40,092,102 | <p>How to solve this</p>
<pre><code>Input: 2
Array = [2,1,3,2,2,2,1,2,2]
Result : 3 (Max of count of seq of 2)
</code></pre>
<p>I just simply used the for loop, it works fine. But is there any other efficient way?</p>
<pre><code>for i in array:
if i == input:
Cnt = Cnt + 1
if Cnt > Result:
... | 0 | 2016-10-17T17:13:30Z | 40,092,264 | <p>You can use <code>itertools.groupby</code> for this:</p>
<pre><code>from itertools import groupby
max(sum(1 for i in g) for k, g in groupby(array) if k == input)
</code></pre>
| 1 | 2016-10-17T17:24:15Z | [
"python",
"list"
] |
Python - Count the duplicate seq element in array | 40,092,102 | <p>How to solve this</p>
<pre><code>Input: 2
Array = [2,1,3,2,2,2,1,2,2]
Result : 3 (Max of count of seq of 2)
</code></pre>
<p>I just simply used the for loop, it works fine. But is there any other efficient way?</p>
<pre><code>for i in array:
if i == input:
Cnt = Cnt + 1
if Cnt > Result:
... | 0 | 2016-10-17T17:13:30Z | 40,092,319 | <p>What I think your're describing can be solved with <a href="https://en.wikipedia.org/wiki/Run-length_encoding" rel="nofollow">run length encoding.</a></p>
<p>Essentially, you take a sequence of numbers (most often used with characters or simply unsigned bytes) and condense it down into a list of tuples where one va... | 0 | 2016-10-17T17:28:13Z | [
"python",
"list"
] |
Python - Count the duplicate seq element in array | 40,092,102 | <p>How to solve this</p>
<pre><code>Input: 2
Array = [2,1,3,2,2,2,1,2,2]
Result : 3 (Max of count of seq of 2)
</code></pre>
<p>I just simply used the for loop, it works fine. But is there any other efficient way?</p>
<pre><code>for i in array:
if i == input:
Cnt = Cnt + 1
if Cnt > Result:
... | 0 | 2016-10-17T17:13:30Z | 40,093,495 | <p>You could seriously abuse side effects in a comprehension :-) :</p>
<pre><code>Input = 2
Array = [2,1,3,2,2,2,1,2,2]
r = []
Result = max([(r.append(1),len(r))[1] if x==Input else (r.clear(),0)[1] for x in Array])
</code></pre>
<p>.</p>
<p>That kind of rigamarole wouldn't be necessary if Python allowed assignments... | 1 | 2016-10-17T18:45:08Z | [
"python",
"list"
] |
Ranking Daily Price Changes | 40,092,105 | <p>I am writing an algo to rank the changes in price of a given list of stocks each day. Right now I'm working with two stocks: Apple and Amex. I would like to rank them from greatest change in price to least change in price, daily.</p>
<p>For example the data I have looks like this:</p>
<p>Day 1:</p>
<p>AAPL = 60.4... | 0 | 2016-10-17T17:13:50Z | 40,092,508 | <p>Say you have the prices in dictionaries, then you could do this:</p>
<pre><code>yesterday = {
'AAPL': 60.40,
'AMX': 15.50,
}
today = {
'AAPL': 61.00,
'AMX': 15.60,
}
change = {k: today[k] - yesterday[k] for k in today}
sorted_stocks = sorted(change, key=change.get, reverse=True)
for ss in sorted... | 0 | 2016-10-17T17:40:02Z | [
"python",
"sorting",
"order",
"ranking",
"rank"
] |
How to retain position values of original list after the elements of the list have been sorted into pairs (Python)? | 40,092,254 | <pre><code>sample = ['AAAA','CGCG','TTTT','AT$T','ACAC','ATGC','AATA']
Position = [0, 1, 2, 3, 4, 5, 6]
</code></pre>
<p>I have the above sample with positions associated with each element. I do several steps of filtering, the code of which is given <a href="https://eval.in/662091" rel="nofollo... | 0 | 2016-10-17T17:23:29Z | 40,092,314 | <p>You could convert the list to a list of tuples first</p>
<pre><code>xs = ['AAAA', 'CGCG', 'TTTT', 'AT$T', 'ACAC', 'ATGC', 'AATA']
ys = [(i, x) for i,x in enumerate(xs)]
print(ys)
=> [(0, 'AAAA'), (1, 'CGCG'), (2, 'TTTT'), (3, 'AT$T'), (4, 'ACAC'), (5, 'ATGC'), (6, 'AATA')]
</code></pre>
<p>Then work with that ... | 0 | 2016-10-17T17:28:02Z | [
"python",
"list",
"indexing",
"position"
] |
Python - Creating a text file converting Fahrenheit to Degrees | 40,092,290 | <p>I'm new to Python and I've been given the task to create a program which uses a text file which contains figures in Fahrenheit, and then I need to change them into a text file which gives the figures in Degrees... Only problem is, I have no idea where to start.
Any advice?</p>
| 0 | 2016-10-17T17:26:25Z | 40,092,355 | <p>Hope this help!</p>
<pre><code>#!/usr/bin/env python
Fahrenheit = int(raw_input("Enter a temperature in Fahrenheit: "))
Celsius = (Fahrenheit - 32) * 5.0/9.0
print "Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C"
</code></pre>
<p>The program asks for input as fahrenheit & converts in to celcius</p>
| 0 | 2016-10-17T17:31:14Z | [
"python"
] |
Python - Creating a text file converting Fahrenheit to Degrees | 40,092,290 | <p>I'm new to Python and I've been given the task to create a program which uses a text file which contains figures in Fahrenheit, and then I need to change them into a text file which gives the figures in Degrees... Only problem is, I have no idea where to start.
Any advice?</p>
| 0 | 2016-10-17T17:26:25Z | 40,092,381 | <p>First you need to create a Python function to read from a text file.</p>
<p>Second, create a method to convert the degrees.
Third, you will create a method to write to the file the results.</p>
<p>This is a very broad question, and you can't expect to get the full working code.
So start your way from the first mi... | 3 | 2016-10-17T17:32:31Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.