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 |
|---|---|---|---|---|---|---|---|---|---|
How to use xlwings or pandas to get all the non-null cell? | 38,254,927 | <p>Recently I need to write a python script to find out how many times the specific string occurs in the excel sheet.</p>
<p>I noted that we can use <code>*xlwings.Range('A1').table.formula*</code> to achieve this task only if the cells are continuous. If the cells are not continuous how can I accomplish that? </p>
| 0 | 2016-07-07T20:42:46Z | 38,255,348 | <p>It's a little hacky, but why not.
By the way, I'm assuming you are using python 3.x.</p>
<p>First well create a new boolean dataframe that matches the value you are looking for.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_excel('path_to_your_excel..')
b = df.applymap(lambda x: x == 'value_... | 1 | 2016-07-07T21:12:17Z | [
"python",
"excel",
"pandas",
"xlwings"
] |
How to use xlwings or pandas to get all the non-null cell? | 38,254,927 | <p>Recently I need to write a python script to find out how many times the specific string occurs in the excel sheet.</p>
<p>I noted that we can use <code>*xlwings.Range('A1').table.formula*</code> to achieve this task only if the cells are continuous. If the cells are not continuous how can I accomplish that? </p>
| 0 | 2016-07-07T20:42:46Z | 38,255,355 | <p>As clarified in the comments, if you already have a dataframe, you can simply use <code>count</code> (Note: there <strong>must</strong> be a better way of doing it):</p>
<pre><code>df = pd.DataFrame({'col_a': ['a'], 'col_b': ['ab'], 'col_c': ['c']})
string_to_search = '^a$' # should actually be a regex, in this ex... | 0 | 2016-07-07T21:12:43Z | [
"python",
"excel",
"pandas",
"xlwings"
] |
Reference a dictionary within itself | 38,254,969 | <p>Is it possible to get a value from a dictionary entry, within that same dictionary?
I'd like to build up a list of directories whilst referencing previously added directories..</p>
<pre><code>common_dirs = {
'root': '/var/tmp',
'java_path': os.path.join(dict.get('root'), 'java'),
'application_path': os.... | 0 | 2016-07-07T20:46:16Z | 38,255,006 | <p>Why not update the dictionary: </p>
<pre><code>my_dict = {'root': '/var/tmp'}
my_dict.update({'file': os.path.join(my_dict.get('root'), 'file')})
</code></pre>
<p>Don't use <code>dict</code> as a name. You may need the real <code>dict</code> builtin later on.</p>
| 4 | 2016-07-07T20:48:54Z | [
"python",
"dictionary"
] |
Reference a dictionary within itself | 38,254,969 | <p>Is it possible to get a value from a dictionary entry, within that same dictionary?
I'd like to build up a list of directories whilst referencing previously added directories..</p>
<pre><code>common_dirs = {
'root': '/var/tmp',
'java_path': os.path.join(dict.get('root'), 'java'),
'application_path': os.... | 0 | 2016-07-07T20:46:16Z | 38,255,024 | <p>You could also try using a class instead of a dictionary:</p>
<pre><code>import os
class Paths:
def __init__(self, root, filename):
self.root = root
self.file = os.path.join(self.root, filename)
root = '/var/tmp'
filename = 'file'
p = Paths(root, filename)
print(p.file)
# /var/tmp/file
</code... | 0 | 2016-07-07T20:50:18Z | [
"python",
"dictionary"
] |
Reference a dictionary within itself | 38,254,969 | <p>Is it possible to get a value from a dictionary entry, within that same dictionary?
I'd like to build up a list of directories whilst referencing previously added directories..</p>
<pre><code>common_dirs = {
'root': '/var/tmp',
'java_path': os.path.join(dict.get('root'), 'java'),
'application_path': os.... | 0 | 2016-07-07T20:46:16Z | 38,263,226 | <p>No. At the point at which you are filling in the dictionary initializer, the dictionary does not exist, so you cannot reference it!</p>
<p>But in principle there is no reason why a dictionary cannot contain itself as one of the values, as the other answers explain, but you just can't refer to it in its own initiali... | 0 | 2016-07-08T09:26:32Z | [
"python",
"dictionary"
] |
How to use .unionAll() in a reduce expression to create single dataframe | 38,254,978 | <p>I'm trying to learn to use functional programming constructs like <code>reduce</code>, and I'm trying to grok how to use it to <code>union</code> multiple <code>dataframes</code> together. I was able to accomplish it with a simple for loop. You can see the commented out <code>expr</code> which was my attempt, the ... | 0 | 2016-07-07T20:46:37Z | 38,255,189 | <p>You provide incorrect initial value for <code>reduce</code> what leads to a situations where you call </p>
<pre><code>''.unionAll(b)
</code></pre>
<p>and it should be obvious it doesn't make sense. Either drop <code>initial</code>:</p>
<pre><code>reduce(lambda acc, b: acc.unionAll(b), l) if l else None
</code></p... | 1 | 2016-07-07T21:00:37Z | [
"python",
"apache-spark",
"pyspark"
] |
Why are scipy's sparse solvers giving incorrect answers? | 38,254,991 | <p><strong>Note</strong>: I made a stupid mistake in the code I originally posted, as Warren Weckesser notes. When corrected, some of the solvers give correct answers, but others give NaN's or incorrect answers. I also forgot to include the runtime warnings in the output; they're there now. I've modified the question a... | 2 | 2016-07-07T20:47:38Z | 38,256,186 | <p>I get a bunch of warnings when I run your code (py3)</p>
<pre><code>Maximum error in solutions found by various other methods:
bicg: nan
/usr/lib/python3/dist-packages/scipy/sparse/linalg/isolve/iterative.py:197: RuntimeWarning: invalid value encountered in multiply
work[slice2] *= sclr2
bicgstab: nan
/usr/lib/p... | 1 | 2016-07-07T22:21:54Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] |
Pandas - write out and read back a single column (export/import) | 38,255,066 | <p>This feels like a vey basic operation that I'm missing? I want to write out a single column of a dataframe to a text file, manually clean it up a bit, and read the new version back into the dataframe (writing over the old data).</p>
<p>I wrote out the column data to CSV, with an index:</p>
<pre><code>df['Systems']... | 1 | 2016-07-07T20:53:00Z | 38,255,119 | <ol>
<li><p>You're using a lot of defaults (header, encoding, sep) that are unnecessary.</p></li>
<li><p>You should index from 0, not 1</p></li>
</ol>
<p><code>df = pd.read_csv('systems_clean.csv', index_col=0)</code></p>
| 1 | 2016-07-07T20:56:20Z | [
"python",
"pandas"
] |
Pandas - write out and read back a single column (export/import) | 38,255,066 | <p>This feels like a vey basic operation that I'm missing? I want to write out a single column of a dataframe to a text file, manually clean it up a bit, and read the new version back into the dataframe (writing over the old data).</p>
<p>I wrote out the column data to CSV, with an index:</p>
<pre><code>df['Systems']... | 1 | 2016-07-07T20:53:00Z | 38,255,126 | <p>indexing is zero based and in fact a lot of the params you passed are defaulted anyway so this should work:</p>
<pre><code>df = pd.read_csv('systems_clean.csv', encoding='utf-8', index_col=0)
In [3]:
import pandas as pd
import io
t=""",Systems
0,A
1,B
2,C
3,D
4,E"""
pd.read_csv(io.StringIO(t), index_col=0)
Out[3... | 1 | 2016-07-07T20:56:34Z | [
"python",
"pandas"
] |
Uploading a file to a form using python requests | 38,255,140 | <p>Trying to write a script that fills in an online form at this <a href="http://www.formstack.com/forms/?1455656-XG7ryB28LE" rel="nofollow">website</a> and uploads a zip file. I have looked at <a href="http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow">the document... | 0 | 2016-07-07T20:57:53Z | 38,255,461 | <p>With your specific url, you need to add some data:</p>
<pre><code>url = "http://www.formstack.com/forms/?1455656-XG7ryB28LE"
session = requests.session()
r = session.get(url) # This can be used to determine form and viewkey values
data = {
"form": "1455656", # Added
"viewkey": "XG7ryB28LE", # Added
"... | 1 | 2016-07-07T21:19:48Z | [
"python",
"post",
"file-upload",
"scripting",
"python-requests"
] |
Slack API "attachments" not showing | 38,255,143 | <p>Attachments aren't working in the following code and neither is the response_type showing as it should be. I've also tried using python's Slack Client and exactly the same is happening.</p>
<pre><code>def send_message(channel_id, text):
params = {
"token" : token,
"username" : "NEW BOT",
... | 1 | 2016-07-07T20:57:57Z | 38,270,492 | <p>The <code>response_type</code> field can only be set when producing a message in response to a slash command or message button action invocation. It can't be set directly with <code>chat.postMessage</code>, as there's no context on the target user for whom to display that ephemeral message.</p>
<p>Another quirk abo... | 2 | 2016-07-08T15:34:29Z | [
"python",
"slack-api"
] |
Slack API "attachments" not showing | 38,255,143 | <p>Attachments aren't working in the following code and neither is the response_type showing as it should be. I've also tried using python's Slack Client and exactly the same is happening.</p>
<pre><code>def send_message(channel_id, text):
params = {
"token" : token,
"username" : "NEW BOT",
... | 1 | 2016-07-07T20:57:57Z | 38,398,557 | <pre><code>attachments='[{"title": "Try these - ","text": " Text ", "mrkdwn_in":["text"]}]'
</code></pre>
<p>Add the title to the attachment. It worked in my case.</p>
| 0 | 2016-07-15T14:23:49Z | [
"python",
"slack-api"
] |
"Task not serializable" error in pySpark on unionAll | 38,255,145 | <p>I'm trying to stack two small dataframes of summary statistics, each with the same columns in the same order and matching dtypes. The first dataframe is simply the results of calling <code>describe</code> on (a subset of) my main dataframe; the second is two more types of summary statistics I assembled and want to ... | 0 | 2016-07-07T20:58:05Z | 38,273,717 | <p>As @zero323 suggested, this was opened as a bug on the Spark JIRA. Details at: <a href="https://issues.apache.org/jira/browse/SPARK-16449" rel="nofollow">https://issues.apache.org/jira/browse/SPARK-16449</a></p>
| 0 | 2016-07-08T19:02:50Z | [
"python",
"apache-spark",
"pyspark"
] |
django: same url but different verbs in Classed based view | 38,255,194 | <p>Is it good to write urls.py as following:</p>
<pre><code>urlpatterns = [
url(r'^v1/files/$', FileView.as_view(), name='api-upload'),
url(r'^v1/files/(?P<pk>\d+)$', FileView.as_view(), name='api-delete'),
url(r'^v1/files/$', FileView.as_view(), name='api-view-all'),
url(r'^v1/files/(?P<pk>... | 0 | 2016-07-07T21:00:59Z | 38,255,263 | <p>You don't need to write urls, you just need to define two methods in your view:</p>
<pre><code># views.py
class FileView(...):
def get(self, request, *args, **kwargs):
# This method will catch the GET call
def delete(self, request, *args, **kwargs):
# This method will catch the DELETE cal... | 0 | 2016-07-07T21:06:44Z | [
"python",
"django",
"django-rest-framework"
] |
mlabwrap setup Mac OS X | 38,255,203 | <p>I have been trying to install the mlabwrap Python library, but keep on running into the following error when I run the setup.py file using the command python setup.py install in the terminal: </p>
<pre><code>Traceback (most recent call last):
File "setup.py", line 130, in <module>
queried_version, queri... | 1 | 2016-07-07T21:01:48Z | 38,335,537 | <p>In order to install mlabwrap, you must modify the setup.py file to: </p>
<pre><code>MATLAB_COMMAND = '/Applications/MATLAB_R2015a.app/bin/matlab' # specify a full path if not in PATH
MATLAB_VERSION = 7.3 # e.g: 6 (one of (6, 6.5, 7, 7.3))
# 7.3 includes later versions as we... | 0 | 2016-07-12T17:33:31Z | [
"python",
"matlab",
"install",
"mlabwrap"
] |
list all files in a dir that includes image sequences? | 38,255,326 | <p>I have a folder that contains several files with different formats (.mpg, .jpg, .mov etc), in addition to several image sequences.</p>
<p>I also have a code that takes an image sequence like:</p>
<pre><code>img.000000.jpg
img.000001.jpg
img.000002.jpg
...
</code></pre>
<p>And turns it into:</p>
<pre><code>img.%0... | -2 | 2016-07-07T21:10:29Z | 38,255,392 | <p>You can use python <code>glob</code></p>
<pre><code>glob.glob("img*.jpg")
</code></pre>
<blockquote>
<p><strong>glob</strong>
Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefil... | 1 | 2016-07-07T21:15:01Z | [
"python"
] |
Why is my program giving "Wrong Answer" for this program? | 38,255,340 | <p>I was solving <a href="https://www.hackerrank.com/challenges/python-quest-1" rel="nofollow">this</a> question in Hackerrank and matched the result in my IDE.
But then the answer is not being accepted by Hackerrank. </p>
<p>My code is:</p>
<pre><code>for i in range(1,int(raw_input())):
print (str(i)*i)
</cod... | -1 | 2016-07-07T21:11:31Z | 38,255,601 | <p>The task says:</p>
<blockquote>
<p>Can you do it using only arithmetic operations, a single for loop and
print statement?</p>
<p>Use no more than two lines. The first line (the for statement) is
already written for you. You have to complete the print statement.</p>
<p>Note: Using anything related to... | 2 | 2016-07-07T21:29:28Z | [
"python"
] |
This configuration section cannot be used at this path | 38,255,368 | <p>I know this has been asked before and i have tried quite a few options but to no result. I just added my Django website to IIS and I'm in the process or trying to set the handler mappings.</p>
<p>However when I click on Handler Mappings for my site I get this error:
<a href="http://i.stack.imgur.com/Gav8E.png" rel=... | -1 | 2016-07-07T21:13:20Z | 38,268,651 | <p>Needed to install <code>ASP.NET 4.5</code> using the web platform installer</p>
| 0 | 2016-07-08T14:04:23Z | [
"python",
"django",
"windows-10",
"iis-8"
] |
Adding Row with Pandas | 38,255,374 | <p>I am trying to add a row that calculate the difference in percentage from the last two row.</p>
<p>This is my code :</p>
<pre><code>df = pd.DataFrame(data=DAU, columns=['Q', 'DAU'])
dfm = pd.DataFrame(data=MAU, columns=['Q', 'MAU'])
df['o_cat'] = pd.Categorical(df['Q'], Quarter_Order, ordered=True)
dfm['o_cat'] =... | 0 | 2016-07-07T21:13:34Z | 38,255,557 | <p>You can use <code>pd.concat</code> with <code>axis = 0</code> to bind them together:</p>
<pre><code>pd.concat([df, pd.DataFrame({'Q': '%','DAU': 0.41,'MAU': 50}, index=[5])], axis = 0)
</code></pre>
| 0 | 2016-07-07T21:26:07Z | [
"python",
"pandas",
"dataframe",
"append"
] |
Building Autocomplete with Flask, MongoDB, jQuery | 38,255,377 | <p>I am attempting to build an autocomplete search using Flask, MongoDB, and <a href="https://jqueryui.com/autocomplete/#remote" rel="nofollow">jQuery Autocomplete</a>. I want to show a list of addresses once a user starts to type them in a search bar. For example, if a user types <code>123 F</code>, I want to show the... | 0 | 2016-07-07T21:13:50Z | 38,255,424 | <p>This might not be the solution you are looking for, but the functionality is exactly what you want to do. Select2 has an autocomplete remote data loading function via ajax that is very simple to implement and might make your life easier.</p>
<p><a href="https://select2.github.io/examples.html" rel="nofollow">https:... | 0 | 2016-07-07T21:17:34Z | [
"jquery",
"python",
"mongodb",
"flask",
"autocomplete"
] |
How to keep dynamically sized text from hiding behind padding of Kivy TextInput | 38,255,378 | <p>I'm working on making a text input box resize the text so all characters are still visible as the length of the input grows. I've been able to resize the text using the code below. However, if I type to fast the first character gets pushed behind the padding of the <code>TextInput</code>. How could the text be reset... | 0 | 2016-07-07T21:13:56Z | 38,280,275 | <p>Text input uses an internal label to display its text, and labels have sizes. Each time the text changes, update the input width based on the label texture width. Example:</p>
<pre><code>#!/usr/bin/env python2
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.... | 0 | 2016-07-09T09:19:45Z | [
"python",
"kivy"
] |
Are str() and int() time consuming in python? | 38,255,420 | <p>I face myself using a lot of this kind of structure:</p>
<pre><code>for node in range(int(self.num_nodes)):
dists[str(node)] = -1
</code></pre>
<p>So, my questions is: what does python(3+) uses when <code>str()</code> or <code>int()</code>, for example, are called? It just casts? It converts? (something else?)... | 0 | 2016-07-07T21:17:00Z | 38,255,463 | <p>How expensive <code>str</code> and <code>int</code> are depend entirely on the objects that you pass to them. Ultimately, they just call the object's <a href="https://docs.python.org/3/reference/datamodel.html#object.__str__" rel="nofollow"><code>__str__</code></a> and <a href="https://docs.python.org/3/reference/d... | 3 | 2016-07-07T21:19:56Z | [
"python",
"performance"
] |
Parse XML with Python when multiple children share a name | 38,255,422 | <p>I currently have an XML file I am trying to parse. Here is my code thus far.</p>
<pre><code>from xml.etree import ElementTree
with open('data.xml', 'rt') as f:
tree = ElementTree.parse(f)
for node in tree.iter('Host'):
hostname = node.find('Name').text
ip = node.find('Networking/IP').text
print ho... | 0 | 2016-07-07T21:17:24Z | 38,256,460 | <p>The find method can accept some limited Xpath expressions, you can use this to extract only IPs which are marked as Primary:</p>
<pre><code>from xml.etree import ElementTree
tree = ElementTree.fromstring(sample)
for node in tree.iter('Host'):
hostname = node.find('Name').text
ips = node.findall("Networking... | 1 | 2016-07-07T22:49:42Z | [
"python",
"xml",
"parsing"
] |
Filter out key from dictionary | 38,255,436 | <p>Having dictionary (defined in <em>map.jinja</em>)</p>
<pre><code>{% set intellij = salt['grains.filter_by']({
'default': {
'orig_name': 'idea-IC-145.1617.8',
'download_url': 'www.example.com',
'archive_format': 'tar',
'archive_opts': 'xfz',
'owner': 'root',
... | 0 | 2016-07-07T21:18:26Z | 38,298,671 | <p>The problem you encountered is described <a href="http://stackoverflow.com/questions/13944751/args-kwargs-in-jinja2-macros">here</a>.<br>
There is a trick to work around which looks fine to me.</p>
<pre><code>{% macro some_macro(state_id, orig_name, download_url, archive_format, owner, archive_opts=None) -%}
{% if ... | 0 | 2016-07-11T03:19:00Z | [
"python",
"jinja2",
"salt-stack"
] |
complexity of set of nameduple lookup | 38,255,480 | <p>Hi in Python i have a namedtuple because i want to store a few values in the same object. </p>
<pre><code>A = namedtuple("A", "key1 key2 key3")
</code></pre>
<p>I store those A's in a registry class which holds a set()</p>
<pre><code>class ARegistry(object):
def __init__(self):
self._register = set()... | 0 | 2016-07-07T21:21:02Z | 38,255,658 | <p>Lookup in a set is only O(1) if you are looking for the item in the set. You are looking at each item in the set to see if it matches a particular criterion -- which is completely different (It'll be O(N) complexity on average).</p>
<p>A more efficient way to store this would be to put the tuple into a dict that m... | 3 | 2016-07-07T21:33:57Z | [
"python",
"dictionary",
"set",
"namedtuple"
] |
Wrapping stdin/stdout causes IPython to lose auto completion and history features | 38,255,591 | <p>I'm working on a script that uses the embedded shelling capabilities of IPython and as a requirement, it has to log all the data from stdin/stdout into a file. For this reason I decided to write wrappers for them; however, after switching out the streams my embedded IPython shell loses its auto completion and histor... | 0 | 2016-07-07T21:28:44Z | 38,276,173 | <p>@Carreau's (IPython core developer) response to this issue at <a href="https://github.com/ipython/ipython/issues/9720" rel="nofollow">Github</a>: </p>
<blockquote>
<p>The issue is that with prompt toolkit stdout in particular is more
than a stream, as you literally draw/erase/redraw on the screen, and
as it u... | 0 | 2016-07-08T22:22:25Z | [
"python",
"linux",
"ipython",
"getattr"
] |
Python Zeep Client request throws error in xml exception | 38,255,640 | <p>When I run the following code, I keep getting the following error: <code>here is an error in XML document (113, 25). ---> The string '' is not a valid Boolean value.</code> I do not understand why this is happening. <a href="http://resumeparsing.com/#ParseResume" rel="nofollow">Here</a> is the documentation and a... | 0 | 2016-07-07T21:33:18Z | 38,267,313 | <p>Author of zeep here; which version are you using? It seems that zeep generates XML which is not valid according to the server.</p>
<p>You can see which XML is sent by enabling the debug log level, see <a href="http://docs.python-zeep.org/en/latest/transport.html#debugging" rel="nofollow">http://docs.python-zeep.org... | 1 | 2016-07-08T12:57:25Z | [
"python",
"xml",
"api"
] |
Python: Make an absolute path relative to another path | 38,255,683 | <p>Suppose I have two file paths as strings in Python, as an example, let's say they are these two:</p>
<pre><code>C:/Users/testUser/Program/main.py
C:/Users/testUser/Program/data/somefile.txt
</code></pre>
<p>Is there a way, using the os module, to generate a relative URL based off of the first one? For example, fee... | 0 | 2016-07-07T21:36:01Z | 38,255,825 | <p>Thanks to MPlanchard in the comment below, here is the full answer:</p>
<pre><code>import os
string1 = "C:/Users/testUser/Program/main.py"
string2 = "C:/Users/testUser/Program/data/somefile.txt"
os.path.relpath(string2, os.path.dirname(string1))
</code></pre>
| 2 | 2016-07-07T21:47:39Z | [
"python",
"filepath"
] |
Python & pygame can't be installed | 38,255,696 | <p>I have tried (many, many, many) times now, installing pygame on my Mac (using brewer) but it always comes back with "No such file in directory". Then i tried installing python 2.7 via brewer, and the same error was output again. I am using OSX El Capitan 10.11. </p>
<p>What can be the cause for this? I am by no me... | 0 | 2016-07-07T21:37:17Z | 38,255,926 | <p>Why are you installing python with brew? Why not install it with pip?
<code>
pip install hg+<a href="http://bitbucket.org/pygame/pygame" rel="nofollow">http://bitbucket.org/pygame/pygame</a> </code></p>
| 0 | 2016-07-07T21:55:41Z | [
"python",
"pygame"
] |
Python & pygame can't be installed | 38,255,696 | <p>I have tried (many, many, many) times now, installing pygame on my Mac (using brewer) but it always comes back with "No such file in directory". Then i tried installing python 2.7 via brewer, and the same error was output again. I am using OSX El Capitan 10.11. </p>
<p>What can be the cause for this? I am by no me... | 0 | 2016-07-07T21:37:17Z | 38,279,159 | <p>I just installed pygame in OSX El Capitan. I had a similar problem. Did you install x-code developer tools? Also, two extremely straight forward directions I found were: </p>
<p><a href="http://www.alexsilcock.net/notes/installing-python-3-pygame-and-pyopengl-on-mac-os-x-el-capitan/" rel="nofollow">http://www.alexs... | 0 | 2016-07-09T06:45:26Z | [
"python",
"pygame"
] |
Django Allauth Error Using default_token_generator | 38,255,781 | <p>I'm trying to generate a default token to send a reset password email but when the code runs <strong>default_token_generator.make_token(user)</strong> the user has no <strong>last_login</strong> property. What am I doing wrong here?</p>
<p>AttributeError at /devices/0/forgot
'QuerySet' object has no attribute 'last... | 0 | 2016-07-07T21:43:53Z | 38,255,875 | <p>In your MIDDLEWARE_CLASSES section provide</p>
<pre><code>django.contrib.auth.middleware.AuthenticationMiddleware',
</code></pre>
<p>is listed, as this is what provides Django user with this property, so the resulting MIDDLEWARE_CLASSES is something like </p>
<pre><code>MIDDLEWARE_CLASSES = [
'django.middlewa... | 0 | 2016-07-07T21:51:12Z | [
"python",
"django",
"django-allauth"
] |
Django Allauth Error Using default_token_generator | 38,255,781 | <p>I'm trying to generate a default token to send a reset password email but when the code runs <strong>default_token_generator.make_token(user)</strong> the user has no <strong>last_login</strong> property. What am I doing wrong here?</p>
<p>AttributeError at /devices/0/forgot
'QuerySet' object has no attribute 'last... | 0 | 2016-07-07T21:43:53Z | 38,255,913 | <p>In <code>user = User.objects.filter(email__iexact=email)</code> - <code>filter()</code> returns QuerySet, <code>make_token()</code> expects User model instance. Try <code>user = User.objects.get(email__iexact=email)</code> instead.</p>
| 0 | 2016-07-07T21:54:53Z | [
"python",
"django",
"django-allauth"
] |
Pandas round is not working for DataFrame | 38,255,796 | <p>Round works on a single element but not the DataFrame, tried DataFrame.round() but didn't work... any idea? Thanks.</p>
<p>Have code below:</p>
<pre><code>print "Panda Version: ", pd.__version__
print "['5am'][0]: ", x3['5am'][0]
print "Round element: ", np.round(x3['5am'][0]*4) /4
print "Round Dataframe: \r\n", n... | 0 | 2016-07-07T21:45:06Z | 38,255,831 | <p>I've tried to reproduce your situation. and it seems to work nicely.</p>
<pre><code>import pandas as pd
import numpy as np
from io import StringIO
s = """Date 5am 6am 7am 8am 9am 10am 11am
2016-07-11 0.279915 0.279915 2.85256 4.52778 6.23291 9.01496 8.53632
2016-07-12 0.339744... | 0 | 2016-07-07T21:47:56Z | [
"python",
"pandas",
"dataframe",
"rounding"
] |
Pandas round is not working for DataFrame | 38,255,796 | <p>Round works on a single element but not the DataFrame, tried DataFrame.round() but didn't work... any idea? Thanks.</p>
<p>Have code below:</p>
<pre><code>print "Panda Version: ", pd.__version__
print "['5am'][0]: ", x3['5am'][0]
print "Round element: ", np.round(x3['5am'][0]*4) /4
print "Round Dataframe: \r\n", n... | 0 | 2016-07-07T21:45:06Z | 38,255,922 | <p><strong>Explanation of your code:</strong></p>
<pre><code>In [166]: np.round(df * 4, decimals=2)
Out[166]:
a b c d
0 0.11 0.45 1.65 3.38
1 3.97 2.90 1.89 3.42
2 1.46 0.79 3.00 1.44
3 3.48 2.33 0.81 1.02
4 1.03 0.65 1.94 2.92
5 1.88 2.21 0.59 0.39
6 0.08 2.09 4.00 1.02
7... | 1 | 2016-07-07T21:55:31Z | [
"python",
"pandas",
"dataframe",
"rounding"
] |
Connection pooling in a streaming pyspark application | 38,255,924 | <p>âWhat is the proper way of using connection pools in a streaming pyspark application ?</p>
<p>I read through <a href="https://forums.databricks.com/questions/3057/how-to-reuse-database-session-object-created-in-fo.html" rel="nofollow">https://forums.databricks.com/questions/3057/how-to-reuse-database-session-obje... | 1 | 2016-07-07T21:55:39Z | 38,268,367 | <p>Long story short connection pools will be less useful in Python than on JVM due to PySpark architecture. Unlike its Scala counterpart Python executors use separate processes. It means there is no shared state between executors and since by default each partition is processed sequentially you can have only one active... | 1 | 2016-07-08T13:50:14Z | [
"python",
"apache-spark",
"pyspark",
"connection-pooling",
"spark-streaming"
] |
python - launch media on browser then quit | 38,255,972 | <p>I have a python cgi/html that takes url and launches on epiphany-browser.
However, after the media/video is over, I need the browser to terminate.
On other posts, it seems there are ways to do this with vlc-media and other players. But I haven't found one with a browser.</p>
<p>Basic framework around the command l... | 1 | 2016-07-07T22:00:37Z | 38,256,234 | <p>The simplest way to do this would be to use <code>pkill</code>. As you're looking to kill an instance of <code>epiphany</code>, a browser in the Unix family of operating systems, you'd use something like:</p>
<pre><code>import os
os.system("pkill epiphany-browser")
</code></pre>
<p>If you executable is named some... | -1 | 2016-07-07T22:25:49Z | [
"python",
"ubuntu",
"epiphany"
] |
Python Subprocess communicate fails after terminate | 38,256,011 | <p>I'm experiencing an issue where a call to <code>proc.communicate()</code> still hangs even after calling <code>proc.terminate()</code>.</p>
<p>I create tasks to be run in the background with the call</p>
<pre><code>import subprocess as sub
p = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=False)
</cod... | 0 | 2016-07-07T22:04:01Z | 38,256,362 | <p>You don't need the first two statements. Just call <code>communicate()</code>. </p>
| 1 | 2016-07-07T22:38:26Z | [
"python",
"subprocess"
] |
Why are the bottom two else if statements not executing? | 38,256,135 | <p>The last two elif statements won't work; it simply redirects me to either of the previous two. And for the else statement, it won't print the number of points. Why is this code not working? Thanks!</p>
<pre><code>def match_duel():
print "do you want to swing right or left"
print "and for how many points?"... | -2 | 2016-07-07T22:15:53Z | 38,256,339 | <p>Only one <code>elif</code> statement here can be executed. The first one that satisfies the condition will be the one that gets executed - the rest are ignored. </p>
<p>"left" will <strong>always</strong> be in "hard left", no matter what. Same with "hard right". As such, the bottom 2 <code>elif</code> statements w... | 0 | 2016-07-07T22:35:56Z | [
"python",
"conditional"
] |
How to break "for" loop in python and pygame? | 38,256,178 | <p>We're currently programming a robot using pygame lib, python, raspberryPI, and adafruit motor hat. Here is example of what we do to increase the speed of the motors from 0 to 100:</p>
<p><code>for i in range(100):
motor.run(i)</code></p>
<p>This code is inside definitions for moving forward, backward and arou... | -1 | 2016-07-07T22:20:43Z | 38,256,209 | <p>You actually hit the solution on the head with the word 'break':</p>
<pre><code>for i in range(100):
motor.run(i)
if ...: #key is released
break
</code></pre>
| 0 | 2016-07-07T22:23:40Z | [
"python",
"pygame",
"robot",
"adafruit"
] |
Python if function across a vector | 38,256,212 | <p>I'm new to Python and trying to work out how to do the following.</p>
<h2>I have a data array, X, which looks something like:</h2>
<pre><code>X = [ 1 2 3
4 5 6
7 8 9
10 11 12];
</code></pre>
<p>Such that the first column <code>X[0]</code> is,</p>
<pre><code>X[0] =[1
4
7
... | 1 | 2016-07-07T22:23:54Z | 38,256,364 | <pre><code># inverted your rows and columns and got them in a list of list
X = [[1,4,7,10],
[2,5,8,11],
[3,6,9,12]]
# lets generate random number k between 0 and 1000
import random
k = random.randint(0, 1000)
# the conditional
for n in X[0]:
if n > k:
X[2] = your_function(X[2])
if n < ... | 1 | 2016-07-07T22:38:47Z | [
"python",
"function",
"if-statement",
"vector",
"indexing"
] |
Python if function across a vector | 38,256,212 | <p>I'm new to Python and trying to work out how to do the following.</p>
<h2>I have a data array, X, which looks something like:</h2>
<pre><code>X = [ 1 2 3
4 5 6
7 8 9
10 11 12];
</code></pre>
<p>Such that the first column <code>X[0]</code> is,</p>
<pre><code>X[0] =[1
4
7
... | 1 | 2016-07-07T22:23:54Z | 38,256,459 | <pre><code>X = [
[ 1, 4, 7, 10 ],
[ 2, 5, 8, 11 ],
[ 3, 6, 9, 12 ] ]
def mapping(x):
if x[0] < K: return x[1]*2*K
elif x[0] > K: return x[1]*2*x[0]
else: return x[1]
K = 2
X[2] = map(mapping, zip(X[0], X[2]))
</code></pre>
| 0 | 2016-07-07T22:49:37Z | [
"python",
"function",
"if-statement",
"vector",
"indexing"
] |
Reading columns of data into arrays in Python | 38,256,231 | <p>I am new to Python. I use Fortran to generate the data file I wish to read. For many reasons I would like to use python to calculate averages and statistics on the data rather than fortan.</p>
<p>I need to read the entries in the the first three rows as strings, and then the data which begins in the fourth row onwa... | 0 | 2016-07-07T22:25:33Z | 38,256,314 | <p>I would use pandas module for this task:</p>
<pre><code>import pandas as pd
In [9]: df = pd.read_csv('a.csv', delim_whitespace=True,
comment='#', skiprows=3,header=None,
names=['MC_STEP','Density','Pressure','Energy_Total'])
</code></pre>
<p>Data Frame:</p>
<pre... | 0 | 2016-07-07T22:33:41Z | [
"python",
"arrays",
"list"
] |
Reading columns of data into arrays in Python | 38,256,231 | <p>I am new to Python. I use Fortran to generate the data file I wish to read. For many reasons I would like to use python to calculate averages and statistics on the data rather than fortan.</p>
<p>I need to read the entries in the the first three rows as strings, and then the data which begins in the fourth row onwa... | 0 | 2016-07-07T22:25:33Z | 38,262,549 | <p>You can consider a <code>list</code> in Python like an <code>array</code> in other languages and it's very optimised. If you have some special needs there is an array type available but rarely used, alternatively the <code>numpy.array</code> that is designed for scientific computation; you have to install the <a hre... | 0 | 2016-07-08T08:50:21Z | [
"python",
"arrays",
"list"
] |
Reading columns of data into arrays in Python | 38,256,231 | <p>I am new to Python. I use Fortran to generate the data file I wish to read. For many reasons I would like to use python to calculate averages and statistics on the data rather than fortan.</p>
<p>I need to read the entries in the the first three rows as strings, and then the data which begins in the fourth row onwa... | 0 | 2016-07-07T22:25:33Z | 38,317,896 | <p>You can also use the csv module's DictReader to read each row into a dictionary, as follows:</p>
<pre><code>with open('filename', 'r') as f:
reader = csv.DictReader(f, delimiter=r'\s+', fieldnames=('MC_STEP', 'DENSITY', 'PRESSURE', 'ENERGY_TOTAL')
for row in reader:
Density.append(float(row['DENSITY... | 0 | 2016-07-11T23:45:27Z | [
"python",
"arrays",
"list"
] |
NameError: name 'static_url' is not defined | 38,256,235 | <p>I am trying to upgrade <a href="https://github.com/summernote/django-summernote" rel="nofollow">django-summernote</a> to version 0.8.5 in my django 1.9 project, but using the settings given, I get this error: </p>
<pre><code> File "my_project/settings/base.py", line 314, in <module>
static_url('djan... | 0 | 2016-07-07T22:26:02Z | 38,256,316 | <p>Try looking at the source. You'll see that the function <code>static_url</code> is defined in <code>django_summernote.settings</code>. </p>
<p>So, to use it in your settings module you'll either need to be importing it, or defining it yourself as something like:</p>
<pre><code>def static_url(url):
return os.... | 1 | 2016-07-07T22:33:50Z | [
"python",
"django",
"summernote",
"static-files"
] |
Python - how to change this list to dictionary | 38,256,257 | <p>I want to get rid of the first "pts", and 2 as the key of loc and pts and imsize, loc, pts, imsize are the key of their values.</p>
<p>This is my list:</p>
<pre><code>test = [{'pts': u"""{"2": {"loc": [11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32], "pts": [[
238.123582313... | 0 | 2016-07-07T22:28:31Z | 38,256,383 | <p>Instead try</p>
<pre><code>print test[0]['pts']
</code></pre>
<p>as you need to use the key here.</p>
| 1 | 2016-07-07T22:40:44Z | [
"python",
"list",
"dictionary"
] |
Python - how to change this list to dictionary | 38,256,257 | <p>I want to get rid of the first "pts", and 2 as the key of loc and pts and imsize, loc, pts, imsize are the key of their values.</p>
<p>This is my list:</p>
<pre><code>test = [{'pts': u"""{"2": {"loc": [11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32], "pts": [[
238.123582313... | 0 | 2016-07-07T22:28:31Z | 38,256,582 | <p>I think it's a little unclear what you're asking.</p>
<p>It looks like you have a list of dictionaries, and you only care about the first element of the list, whose key is <code>pts</code>. Then you want to do something with the dictionary key. The dictionary key appears ti be a JSON string, so you'll need to decod... | 0 | 2016-07-07T23:01:00Z | [
"python",
"list",
"dictionary"
] |
Python - how to change this list to dictionary | 38,256,257 | <p>I want to get rid of the first "pts", and 2 as the key of loc and pts and imsize, loc, pts, imsize are the key of their values.</p>
<p>This is my list:</p>
<pre><code>test = [{'pts': u"""{"2": {"loc": [11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32], "pts": [[
238.123582313... | 0 | 2016-07-07T22:28:31Z | 38,256,594 | <p>If you want to change the value of points into a dict that you can parse try:</p>
<pre><code>points = eval(test[0]['pts'])
</code></pre>
<p>this will make <code>points</code> equal to: </p>
<pre><code>{'47': {'loc': [34, 35, 36],
'pts': [[1393.0609259457722, 1700.979369842461], [1193.01805808595, 1746.234... | 1 | 2016-07-07T23:02:09Z | [
"python",
"list",
"dictionary"
] |
How to compile mod_wsgi 4.5.3 with Python3.5.2 under centos7, Apache/2.4.6 | 38,256,266 | <p>I tried ./configure for mod_wsgi 4.5.3 like below:</p>
<p>./configure --with-python=/opt/Python352/bin</p>
<p>Where /opt/Python352 folder is installed with python3.5.2.</p>
<p>However in CentOS 7 the "configure" always builds the mod_wsgi with binary "python"(corresponding to python2.75) not with binary "python3"... | 1 | 2016-07-07T22:29:20Z | 38,287,125 | <p>Here's an exact dump of what I use for CentOS 7.2. You can probably do without a lot of the pre-reqs, but I figured I'd include them since many are handy to have:</p>
<pre><code>echo 'Python 3.5.2 is not installed, installing Python 3 pre-requisites...'
yum -y groupinstall development
echo 'Installing extra packag... | 1 | 2016-07-09T23:12:56Z | [
"python",
"mod-wsgi",
"wsgi",
"python-3.5"
] |
what is the handle_connection in tornado module ioloop simple tcpserver's connection_ready? | 38,256,277 | <p>Tornado ioloop.py give a example usage for a simple TCP server,through this simple can run,but what is handle_connection in function connection_ready(the end line) or need define by myself?</p>
<pre><code> import errno
import functools
import tornado.ioloop
import socket
def connection_ready(soc... | 0 | 2016-07-07T22:29:58Z | 38,265,514 | <p>Yes, <code>handle_connection</code> is a function that you would write for your application. </p>
<p>Also see the <a href="http://www.tornadoweb.org/en/stable/tcpserver.html" rel="nofollow"><code>tornado.tcpserver.TCPServer</code></a> class, which is a little easier to use than building on the <code>IOLoop</code> d... | 0 | 2016-07-08T11:28:18Z | [
"python",
"tornado"
] |
Distinct List of Lists With Set | 38,256,281 | <p>I created a list of lists and then tried to get a distinct list of the lists using set(), but it appears as though i cant use list on a set. </p>
<p>Is there another way to accomplish this with a concise statement that performs well?</p>
<p><strong>CODE</strong></p>
<pre><code>x = [1,2]
y = [1,2]
z = [2,3]
xyz ... | 3 | 2016-07-07T22:30:25Z | 38,256,353 | <p>If the list members are hashable, it will work</p>
<pre><code>x = [1,2]
y = [1,2]
z = [2,3]
xyz = []
xyz.append(tuple(x))
xyz.append(tuple(y))
xyz.append(tuple(z))
print xyz
xyz_set = set(xyz)
print xyz_set
</code></pre>
| 2 | 2016-07-07T22:37:26Z | [
"python",
"list",
"python-3.x"
] |
Distinct List of Lists With Set | 38,256,281 | <p>I created a list of lists and then tried to get a distinct list of the lists using set(), but it appears as though i cant use list on a set. </p>
<p>Is there another way to accomplish this with a concise statement that performs well?</p>
<p><strong>CODE</strong></p>
<pre><code>x = [1,2]
y = [1,2]
z = [2,3]
xyz ... | 3 | 2016-07-07T22:30:25Z | 38,256,541 | <p>It's a little bit convoluted, but this will do the trick in a single line:</p>
<pre><code>xyz=[list(x) for x in list(set((tuple(x),tuple(y),tuple(z))))]
</code></pre>
| 1 | 2016-07-07T22:56:14Z | [
"python",
"list",
"python-3.x"
] |
Distinct List of Lists With Set | 38,256,281 | <p>I created a list of lists and then tried to get a distinct list of the lists using set(), but it appears as though i cant use list on a set. </p>
<p>Is there another way to accomplish this with a concise statement that performs well?</p>
<p><strong>CODE</strong></p>
<pre><code>x = [1,2]
y = [1,2]
z = [2,3]
xyz ... | 3 | 2016-07-07T22:30:25Z | 38,256,572 | <p>if you want to preserve order and keep your lists, you could use generator function to remove the dupes from your list:</p>
<pre><code>xyz = [x, y, z]
def remove_dupe_subs(l):
seen = set()
for sub in l:
tup = tuple(sub)
if tup not in seen:
yield sub
seen.add(tup)
x... | 4 | 2016-07-07T22:59:40Z | [
"python",
"list",
"python-3.x"
] |
Fill blank cells from previous columns pandas python | 38,256,369 | <p>If I have a simple dataframe such as:</p>
<pre><code>q_1 q_1_mark q_2 q_2_mark
TRUE a 1 c
FALSE b 2
TRUE c 3
</code></pre>
<p>How could I fill in the blank values of the q_2_mark column, so they matched with q_1_mark? So the steps would be:</p>
<ol>
<li>L... | 1 | 2016-07-07T22:39:04Z | 38,256,388 | <p>Assuming your dataframe is <code>df</code>, Try:</p>
<pre><code>df.q_2_mark = df.q_2_mark.combine_first(df.q_1_mark)
q_1 q_1_mark q_2 q_2_mark
0 True a 1 c
1 False b 2 b
2 True c 3 c
</code></pre>
| 3 | 2016-07-07T22:41:32Z | [
"python",
"pandas"
] |
Fill blank cells from previous columns pandas python | 38,256,369 | <p>If I have a simple dataframe such as:</p>
<pre><code>q_1 q_1_mark q_2 q_2_mark
TRUE a 1 c
FALSE b 2
TRUE c 3
</code></pre>
<p>How could I fill in the blank values of the q_2_mark column, so they matched with q_1_mark? So the steps would be:</p>
<ol>
<li>L... | 1 | 2016-07-07T22:39:04Z | 38,256,396 | <pre><code>df.q_2_mark.fillna(df.q_1_mark, inplace=True)
df
q_1 q_1_mark q_2 q_2_mark
0 True a 1 c
1 False b 2 b
2 True c 3 c
</code></pre>
| 3 | 2016-07-07T22:42:20Z | [
"python",
"pandas"
] |
How can I make Python speak with mbrola? | 38,256,373 | <p>I need to create a Python program, which will speak the numbers chosen randomly. Like, Python gives me number 11, and with mbrola, it says "eleven". It's very simple, I've created almost everything, but the only thing I need is - make Python speaks it using mbrola!</p>
<p>Please, could you give me some examples?</p... | -1 | 2016-07-07T22:39:35Z | 38,256,406 | <p>There is a python module called <code>pyttsx</code> which speaks things. You can install it by using <code>pip install pyttsx</code> and then use it as such</p>
<pre><code>import pyttsx as tts
engine = tts.init()
engine.say('Eleven')
engine.runAndWait()
</code></pre>
| 0 | 2016-07-07T22:43:16Z | [
"python"
] |
Python Array Addition recursion | 38,256,375 | <p>So I was doing coderbyte's challenge and I have problems with one:
ArrayAdditionI, here's the statement of the problem:</p>
<p>'''
Using the Python language, have the function ArrayAdditionI(arr) take the array of numbers stored in arr
and return the string true if any combination of numbers in the array can be ad... | 2 | 2016-07-07T22:39:49Z | 38,256,532 | <p>Alright - here are the calls. Child calls are indented with respect to their parents:</p>
<ul>
<li>Call <code>countFor([4, 6, 10, 1, 3], 23, 0)</code>
<ul>
<li>Call <code>countFor([6, 10, 1, 3], 23, 4)</code> from the first <code>if</code></li>
<li>Call <code>countFor([10, 1, 3], 23, 10)</code> from the first <cod... | 2 | 2016-07-07T22:55:38Z | [
"python",
"arrays",
"recursion"
] |
Python Array Addition recursion | 38,256,375 | <p>So I was doing coderbyte's challenge and I have problems with one:
ArrayAdditionI, here's the statement of the problem:</p>
<p>'''
Using the Python language, have the function ArrayAdditionI(arr) take the array of numbers stored in arr
and return the string true if any combination of numbers in the array can be ad... | 2 | 2016-07-07T22:39:49Z | 38,256,579 | <p>You haven't traced all of the logic, just the input and update at the top of the routine.</p>
<p>At <strong>[] 23 24</strong>, let's follow the logic:</p>
<pre><code>if sw == m:
</code></pre>
<p>Nope ... that's 24 vs 23 ...</p>
<pre><code>if countFor(ar, m, sw):
</code></pre>
<p>This produces your <strong>[] 23... | 0 | 2016-07-07T23:00:29Z | [
"python",
"arrays",
"recursion"
] |
(GPS & MySQL) No module error in python 2.7 with virtualenv running on Lubuntu | 38,256,380 | <p>I have installed the gps packages and the mysql packages using :
sudo apt-get install gpsd gpsd-clients
sudo dpkg-reconfigure gpsd
&
sudo apt-get install python2.7-mysqldb
it shows that the packages have been successfully installed but when i run my python code which has :</p>
<pre><code>import gps
import MySQ... | -1 | 2016-07-07T22:40:37Z | 38,276,444 | <p>% SOLVED, if python is running in a virtual env then there is a issue with the path of the modules. need to change path :</p>
<p>export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages % this command has to be made everytime the terminal window is closed
and for permanently implementing this change//
sourc... | 0 | 2016-07-08T22:52:12Z | [
"python",
"mysql"
] |
ValueError: only single character unicode strings can be converted to Py_UCS4, got length 0 | 38,256,402 | <p>while running the following code I found an error as shown below</p>
<pre><code>data= pd.read_csv("Filtered Data.csv", sep='', encoding='latin-1')
</code></pre>
<p>Error shown: <code>ValueError: only single character unicode strings can be converted to Py_UCS4, got length 0</code></p>
<p>How to get rid of this e... | 0 | 2016-07-07T22:43:11Z | 38,491,579 | <p>The error is thrown because of <code>sep=''</code> It's missing a space. You can use <code>sep=' '</code>.
Sep takes a string argument (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">according to Panda documentation</a>). So it's complaining about an empty string... | 0 | 2016-07-20T22:00:22Z | [
"python",
"pandas"
] |
Executing multiple adb shell commands using Python | 38,256,420 | <p>I want to use ADB shell to access my device internal storage and then access information using Python. I know how to execute single adb command from Python using:</p>
<pre><code>cmd1 = 'adb shell ls'
s1 = subprocess.check_output(cmd1.split())
</code></pre>
<p>Also I found out that we can use <code>&& or ||... | -1 | 2016-07-07T22:45:18Z | 38,523,478 | <p>You can use communicate() method to do this</p>
<pre><code>procId = subprocess.Popen('adb shell',stdin = subprocess.PIPE)
procId.communicate('cd /dev/block\nfind -name boot\n')
</code></pre>
| 0 | 2016-07-22T09:56:52Z | [
"python",
"linux",
"shell",
"adb"
] |
How to Reorder Python List For Every N Item | 38,256,504 | <p>I have a list like ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']</p>
<p>How do I reorder it based on every n item (e.g. every 4 items), so that it has the 1st item, then 5th item, then the 9th item, then the 2nd item, then the 6th item, then the 10th item, then the 3rd item, the 7th item, and the 11th ite... | 2 | 2016-07-07T22:53:29Z | 38,256,552 | <p>I doubt this is the most performant or elegant solution, but it does work:</p>
<pre><code>>>>lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
>>>lst[::4] + lst[1::4] + lst[2::4] + lst[3::4]
['a', 'e', 'i', 'b', 'f', 'j', 'c', 'g', 'k', 'd', 'h']
</code></pre>
| 2 | 2016-07-07T22:57:32Z | [
"python",
"list",
"list-comprehension"
] |
How to Reorder Python List For Every N Item | 38,256,504 | <p>I have a list like ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']</p>
<p>How do I reorder it based on every n item (e.g. every 4 items), so that it has the 1st item, then 5th item, then the 9th item, then the 2nd item, then the 6th item, then the 10th item, then the 3rd item, the 7th item, and the 11th ite... | 2 | 2016-07-07T22:53:29Z | 38,256,567 | <p><strong>Updated</strong>:</p>
<p>Mark Tolonen is correct that the original solution only works in a few situations. Here is a corrected version:</p>
<pre><code>>>> flatten = lambda x: reduce(lambda a,b: a+b, x)
>>> everyN = lambda N,l: flatten([l[s:][::N] for s in range(N)])
</code></pre>
<p>Not... | 5 | 2016-07-07T22:58:23Z | [
"python",
"list",
"list-comprehension"
] |
How to Reorder Python List For Every N Item | 38,256,504 | <p>I have a list like ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']</p>
<p>How do I reorder it based on every n item (e.g. every 4 items), so that it has the 1st item, then 5th item, then the 9th item, then the 2nd item, then the 6th item, then the 10th item, then the 3rd item, the 7th item, and the 11th ite... | 2 | 2016-07-07T22:53:29Z | 38,257,973 | <p>You could do this:</p>
<pre><code> l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
f = []
n = 4
for i in range(n):
f.extend(l[i::n])
</code></pre>
| 1 | 2016-07-08T02:12:36Z | [
"python",
"list",
"list-comprehension"
] |
How to Reorder Python List For Every N Item | 38,256,504 | <p>I have a list like ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']</p>
<p>How do I reorder it based on every n item (e.g. every 4 items), so that it has the 1st item, then 5th item, then the 9th item, then the 2nd item, then the 6th item, then the 10th item, then the 3rd item, the 7th item, and the 11th ite... | 2 | 2016-07-07T22:53:29Z | 38,258,102 | <p>This supports any length list with any N step:</p>
<pre><code>from itertools import islice
def reorder(L,N):
return [x for n in range(N) for x in islice(L,n,None,N)]
L = list(range(16))
for N in range(1,9):
print(N,reorder(L,N))
L = list('abcdefghijk')
for N in range(1,9):
print(N,reorder(L,N))
</cod... | 1 | 2016-07-08T02:31:15Z | [
"python",
"list",
"list-comprehension"
] |
How to Reorder Python List For Every N Item | 38,256,504 | <p>I have a list like ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']</p>
<p>How do I reorder it based on every n item (e.g. every 4 items), so that it has the 1st item, then 5th item, then the 9th item, then the 2nd item, then the 6th item, then the 10th item, then the 3rd item, the 7th item, and the 11th ite... | 2 | 2016-07-07T22:53:29Z | 38,296,134 | <p>You can do it with a simple one-liner:</p>
<pre><code>lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
every4 = [s for i in range(4) for s in lst[i::4]]
</code></pre>
<p>This is a simple rewriting of James Moriarty's solution.</p>
| 1 | 2016-07-10T20:20:04Z | [
"python",
"list",
"list-comprehension"
] |
Finding correct package versions using standalone Python 2.7 and Anaconda/Python 3.5 on same computer (Mac) | 38,256,590 | <p>I have been using Python 2.7 for some time on this machine; I needed to install the Anaconda distribution with Python 3.5 for a team project. </p>
<p>I successfully installed Python 3.5, and now <code>python</code> points to Python 3.5, but when I try <code>import numpy</code>, my system goes looking for numpy in t... | 0 | 2016-07-07T23:01:44Z | 38,257,622 | <p>First, ensure you have the proper path for the anaconda installation. Then add ' ~//bin' to your PYTHONPATH instead.</p>
| 0 | 2016-07-08T01:21:59Z | [
"python",
"osx",
"python-2.7",
"python-3.x",
"anaconda"
] |
Python Borg design pattern, running method on creation of class | 38,256,609 | <p>I'm trying to implement the Borg design pattern found here (recreated below): <a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html" rel="nofollow">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html</a>. </p>
<pre><code>class Borg:
_shared_state = {}
... | 1 | 2016-07-07T23:03:28Z | 38,257,678 | <p>I think your solution isn't that bad with the caveat being that you have absolutely have to populate that <code>__dict__</code> before next <code>init</code> is called again or <code>firstInitializationMethod()</code> will be called more than once. It's guaranteed to happen in your example because of <code>self.val ... | 0 | 2016-07-08T01:29:03Z | [
"python",
"variables",
"design-patterns"
] |
Pool Multiprocessing Python | 38,256,620 | <p>Basically the issue is as follows: I have a bunch of workers that have a function prescribed to each (the function is worker(alist) ) and am trying to process 35 workers at the same time. Each worker reads their line from the file (the modulo part) and should process the line using the "worker" function. I've pen-te... | 0 | 2016-07-07T23:05:30Z | 38,256,934 | <pre><code>import multiprocessing
def worker(arg):
print 'doing work "%s"' % arg
return
NUM_WORKERS=35
with open('test.csv', 'w') as test:
for i in xrange(100):
if i % 10 == 0:
test.write('\n')
test.write('"%s 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23",' % i)
... | 0 | 2016-07-07T23:43:22Z | [
"python",
"multiprocessing",
"pool",
"worker"
] |
Pool Multiprocessing Python | 38,256,620 | <p>Basically the issue is as follows: I have a bunch of workers that have a function prescribed to each (the function is worker(alist) ) and am trying to process 35 workers at the same time. Each worker reads their line from the file (the modulo part) and should process the line using the "worker" function. I've pen-te... | 0 | 2016-07-07T23:05:30Z | 38,257,012 | <p>I suggest you put the calculation of <code>raw</code> into a generator function, and then use <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.imap_unordered" rel="nofollow"><code>Pool.imap_unordered()</code></a> or <code>Pool.map()</code> to run <code>worker(... | 0 | 2016-07-07T23:53:17Z | [
"python",
"multiprocessing",
"pool",
"worker"
] |
Pool Multiprocessing Python | 38,256,620 | <p>Basically the issue is as follows: I have a bunch of workers that have a function prescribed to each (the function is worker(alist) ) and am trying to process 35 workers at the same time. Each worker reads their line from the file (the modulo part) and should process the line using the "worker" function. I've pen-te... | 0 | 2016-07-07T23:05:30Z | 38,271,784 | <p>So I found out it wasn't throwing an error that was occurring inside the worker as a result of a mismatched number of inputs into a child function (AKA worker was calling another function dosomething(a1,a2,...a20) and was only giving it 19 inputs). It seems async won't throw error outputs about issues happening insi... | 0 | 2016-07-08T16:45:28Z | [
"python",
"multiprocessing",
"pool",
"worker"
] |
Why are my `binaryFiles` empty when I collect them in pyspark? | 38,256,631 | <p>I have two zip files on hdfs in the same folder : <code>/user/path-to-folder-with-zips/</code>.</p>
<p>I pass that to "binaryfiles" in pyspark:</p>
<pre><code>zips = sc.binaryFiles('/user/path-to-folder-with-zips/')
</code></pre>
<p>I'm trying to unzip the zip files and do things to the text files in them, so I t... | 1 | 2016-07-07T23:06:36Z | 38,257,024 | <p>I'm assuming that each zip file contains a single text file (code is easily changed for multiple text files). You need to read the contents of the zip file first via <code>io.BytesIO</code> before processing line by line. Solution is loosely based on <a href="http://stackoverflow.com/a/36511190/234233">http://stacko... | 1 | 2016-07-07T23:54:33Z | [
"python",
"hadoop",
"zip",
"pyspark",
"binaryfiles"
] |
How do I validate an implementation of python's IOBase? | 38,256,689 | <p>Is there an existing test suite I can make use of to test an implementation of <code>IOBase</code>? If possible, I would like to exhaustively test a new implementation, but there are a lot of tests that would need to be manually written.</p>
<p>For instance, say I have a non-seekable, non-writeable stream. I want t... | 0 | 2016-07-07T23:13:20Z | 38,262,646 | <ul>
<li><p>Python docs are the only official, authoritative source containing promises/guarantees about the stock implementation's behaviour - there's just nothing else officially published. If something is not documented, it <s>doesn't exist</s> should not be relied upon.</p>
<ul>
<li>There's a unit test for the <co... | 1 | 2016-07-08T08:56:00Z | [
"python",
"testing",
"io"
] |
Make a Scatter Plot in matplotlib with dates on x axis and values on y | 38,256,750 | <p>I am having trouble making a scatter plot that has from a date array and a bunch of PM 2.5 values. My lists would look like the following: </p>
<pre><code>dates = ['2015-12-20','2015-09-12']
PM_25 = [80, 55]
</code></pre>
| 0 | 2016-07-07T23:21:14Z | 38,273,117 | <pre><code>import pandas as pd
dates = ['2015-12-20','2015-09-12']
PM_25 = [80, 55]
dates = [pd.to_datetime(d) for d in dates]
plt.scatter(dates, PM_25, s =100, c = 'red')
</code></pre>
<p><code>s</code> sets the size
<code>c</code> sets the color</p>
<p>There are a whole bunch of other args as well:
<a href="http... | -1 | 2016-07-08T18:20:28Z | [
"python",
"list",
"statistics",
"scatter"
] |
Python OpenCV: Conversion from float to int for using cv2.line() | 38,256,789 | <p>I'm working on the <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_video/py_lucas_kanade/py_lucas_kanade.html#goal" rel="nofollow">optical flow tutorial of openCV</a> using Python 2.7 with OpenCV 3.1.0 and have a question concerning the use of cv2.line(). Here is the original code wit... | 1 | 2016-07-07T23:25:40Z | 38,275,874 | <p>It seems that cv2.line() treats differently two types of floats: "standard" Python floats and numpy floats. See the minimum working example using Python 2.7 with OpenCV 3.1.0:</p>
<pre><code>import numpy as np, cv2
mask = np.zeros([10, 20, 3], dtype=np.uint8)
color = [0, 0, 0]
# Using Numpy
a = np.float32(12.34)
m... | 1 | 2016-07-08T21:51:44Z | [
"python",
"python-2.7",
"opencv",
"opencv3.0"
] |
cannot access excel file using Pandas Python | 38,256,792 | <p>Hi i am trying to run my python code through several excel files and get the data from each file and save into a data frame. Here is my code..</p>
<pre><code>import os
import glob
import pandas as pd
path =r'C:\Users\user1\Desktop\test'
files = os.listdir(path)
files_xls = [f for f in files if f[-3:] == 'xls'] ... | 0 | 2016-07-07T23:25:52Z | 38,257,095 | <pre><code>import os
import pandas as pd
path =r'C:\Users\user1\Desktop\test'
os.chdir(path)
files = os.listdir(path)
files_xls = [f for f in files if f[-3:] == 'xls']
df = pd.DataFrame()
for f in files_xls:
data = pd.read_excel(f)
df = df.append(data)
a = df.describe()
print (a)
</code></pre>
| 0 | 2016-07-08T00:02:27Z | [
"python",
"excel",
"python-3.x",
"pandas",
"dataframe"
] |
cannot access excel file using Pandas Python | 38,256,792 | <p>Hi i am trying to run my python code through several excel files and get the data from each file and save into a data frame. Here is my code..</p>
<pre><code>import os
import glob
import pandas as pd
path =r'C:\Users\user1\Desktop\test'
files = os.listdir(path)
files_xls = [f for f in files if f[-3:] == 'xls'] ... | 0 | 2016-07-07T23:25:52Z | 38,258,380 | <p>File is not found because you are calling a relative reference to Excel file and the Python script may not reside in same folder as the file. Hence, use absolute reference which is not contigent to location of called script. You can do so by concatenating the path to file name using <code>os.path.join()</code>:</p>
... | 0 | 2016-07-08T03:11:12Z | [
"python",
"excel",
"python-3.x",
"pandas",
"dataframe"
] |
How to create a unit test to check the response of an API made in Flask? | 38,256,810 | <p>I'm trying to test a JSON API I implemented in Flask</p>
<p>Here's my view function</p>
<pre><code>@app.route("/dummy")
def dummy():
return {"dummy":"dummy-value"}
</code></pre>
<p>And in my Unittest I'm testing using</p>
<pre><code>def setUp(self):
self.app = my_app.app.test_client()
def test_dummy(se... | 1 | 2016-07-07T23:28:23Z | 38,256,854 | <p>You should return a string, not a dictionary object!</p>
<pre><code>@app.route("/dummy")
def dummy():
return flask.jsonify(dummy="dummy-value")
</code></pre>
<p>And in your test, parse the JSON using <code>json.loads(..)</code> and then assert.</p>
| 0 | 2016-07-07T23:33:21Z | [
"python",
"flask"
] |
How to create a unit test to check the response of an API made in Flask? | 38,256,810 | <p>I'm trying to test a JSON API I implemented in Flask</p>
<p>Here's my view function</p>
<pre><code>@app.route("/dummy")
def dummy():
return {"dummy":"dummy-value"}
</code></pre>
<p>And in my Unittest I'm testing using</p>
<pre><code>def setUp(self):
self.app = my_app.app.test_client()
def test_dummy(se... | 1 | 2016-07-07T23:28:23Z | 38,256,857 | <p>Using <code>jsonify()</code> fixes the error <code>'dict' object is not callable</code></p>
<pre><code>from flask import jsonify
@app.route("/dummy")
def dummy():
return jsonify({"dummy":"dummy-value"})
</code></pre>
<p>And for the test, you'll have to pull the JSON out of the HTTP response</p>
<pre><code>im... | 3 | 2016-07-07T23:33:29Z | [
"python",
"flask"
] |
Why does my python TCP server need to bind to 0.0.0.0 and not localhost or it's IP address? | 38,256,851 | <p>I'm making a Python TCP server and a C# client, and I got it to work, but I don't understand <em>why</em> it's working and I'm hoping someone can explain to me what I'm missing. I'm trying to connect from within my own network, so there are no firewalls involved.</p>
<p>In my python script, if I bind to <code>127.0... | 0 | 2016-07-07T23:33:04Z | 38,256,943 | <p>If I'm not mistaken, 127.0.0.1 and localhost (which are basically the same), are 'local loopback' addresses. This means that they can only be accessed from your computer. Any other computer (even on your own network), cannot connect to them. This might also also depend on your operating system.</p>
<p>To be able to... | 3 | 2016-07-07T23:44:39Z | [
"c#",
"python",
"sockets",
"tcp"
] |
When submitting a post via praw, how do I return the url of that post? | 38,256,964 | <p>I'm using the following code to submit a self post. Once that is submitted I would like the url to that post to be stored in a variable. I'm new to python and praw so i'm probably missing something obvious. </p>
<pre><code>import praw
sub_reddit = 'test'
user_agent = 'user agent info'
post_title = 'post title text... | 2 | 2016-07-07T23:47:18Z | 38,257,129 | <p>return the response and assign it to a variable:</p>
<pre><code>def self_post():
return r.submit(sub_reddit, post_title, text=post_body)
login()
resp = self_post()
</code></pre>
| 1 | 2016-07-08T00:06:55Z | [
"python",
"bots",
"praw"
] |
When submitting a post via praw, how do I return the url of that post? | 38,256,964 | <p>I'm using the following code to submit a self post. Once that is submitted I would like the url to that post to be stored in a variable. I'm new to python and praw so i'm probably missing something obvious. </p>
<pre><code>import praw
sub_reddit = 'test'
user_agent = 'user agent info'
post_title = 'post title text... | 2 | 2016-07-07T23:47:18Z | 38,257,136 | <p>After you submit the link, you can use <a href="http://praw.readthedocs.io/en/stable/pages/code_overview.html#praw.objects.Submission.short_link" rel="nofollow"><code>.short_link</code></a> to get the URL to the submission:</p>
<pre><code>submission = r.submit(sub_reddit, post_title, text=post_body)
submission.shor... | 1 | 2016-07-08T00:08:33Z | [
"python",
"bots",
"praw"
] |
Python if loop doesn't function/repeats ineffectively | 38,257,006 | <pre><code>print("Guess a number between 1 and 100")
userGuess = int(input("Your guess: "))
import random
randomNumber = (random.randint(1,100))
found = False
while userGuess in range(1,100):
if userGuess > randomNumber:
int(input("Guess lower: "))
found = False
elif userGuess < randomN... | 0 | 2016-07-07T23:51:56Z | 38,257,047 | <p>Your <strong>while</strong> loop has no body. Indent the compound <strong>if</strong> statement to make it the body of the loop, i.e.</p>
<pre><code>while userGuess in range(1,100):
if userGuess > randomNumber:
int(input("Guess lower: "))
found = False
elif userGuess < randomNum... | 0 | 2016-07-07T23:56:49Z | [
"python",
"loops",
"python-3.x",
"if-statement"
] |
Python if loop doesn't function/repeats ineffectively | 38,257,006 | <pre><code>print("Guess a number between 1 and 100")
userGuess = int(input("Your guess: "))
import random
randomNumber = (random.randint(1,100))
found = False
while userGuess in range(1,100):
if userGuess > randomNumber:
int(input("Guess lower: "))
found = False
elif userGuess < randomN... | 0 | 2016-07-07T23:51:56Z | 38,257,109 | <p>you didn't assign input to userGuess in loop </p>
<pre><code>import random
print("Guess a number between 1 and 100")
randomNumber = random.randint(1,100)
userGuess = int(raw_input("Your guess: "))
print randomNumber
found = False
while 1:
if userGuess < 1 or userGuess >100:
userGuess = int(inp... | 0 | 2016-07-08T00:04:33Z | [
"python",
"loops",
"python-3.x",
"if-statement"
] |
PyCharm/IntelliJ enable package dependency inspection | 38,257,017 | <p>I was getting this warning automatically <code>Package requirements ....</code></p>
<p><a href="http://i.stack.imgur.com/73nsu.png" rel="nofollow"><img src="http://i.stack.imgur.com/73nsu.png" alt="enter image description here"></a></p>
<p>& things were working fine when I was clicking on the <code>Install req... | 1 | 2016-07-07T23:53:57Z | 38,260,277 | <p>Goto <code>File > Settings > Tools > Python Integrated Tools</code></p>
<p>set your requirements file with the <code>Package requirements file:</code> input box.
<a href="http://i.stack.imgur.com/wmB5M.png" rel="nofollow"><img src="http://i.stack.imgur.com/wmB5M.png" alt="PyCharm Integrated Tools settings ... | 1 | 2016-07-08T06:33:04Z | [
"python",
"python-2.7",
"intellij-idea",
"pycharm",
"intellij-14"
] |
Why does using tarfile.extract() result in error: no attribute 'extract'? | 38,257,054 | <p>I'm using Python 3.4.
Writing </p>
<pre><code>csv_f = tarfile.open('C:\\Users\\somefile.gz')
</code></pre>
<p>works fine but this</p>
<pre><code>csv_f = tarfile.extract('C:\\Users\\somefile.gz')
</code></pre>
<p>causes the response </p>
<pre><code>AttributeError: 'module' object has no attribute 'extract'
</c... | -2 | 2016-07-07T23:57:23Z | 38,257,068 | <p>Because they're methods of the object returned by <code>tarfile.open()</code>, not functions in the module itself.</p>
| 0 | 2016-07-07T23:59:25Z | [
"python",
"tarfile"
] |
Python Network Projects | 38,257,055 | <p>I originally posted on his on Network Engineering but it was suggested that o post it on here.
I've been learning Python and since I work in networking I'd like to start writing a few scripts that I can use in my day to day work tasks with switches. So my question is this, what network projects have you used python... | 0 | 2016-07-07T23:57:26Z | 38,258,777 | <p>Backing up and copying configs to server. Automate certain config changes to adhere to standards. Scripts to copy run start on all devices at will. Finding various config entries on all devices that may need to be altered.</p>
<p>There are so many possibilities.</p>
<p>Search github and pastebin and the overflow s... | 0 | 2016-07-08T04:07:31Z | [
"python",
"network-programming"
] |
Python for loop not running | 38,257,107 | <p>Im writing a simple command line program involving id's, i want to make it so that every time i run a function it should add a value to a CSV file. I have made a function that i thought worked, but apparently not. One of my for loops is not running correctly ;( Here is my code:</p>
<pre><code>def addId(id):
fil... | 1 | 2016-07-08T00:04:24Z | 38,257,168 | <p>You open the file with:</p>
<pre><code>file = open(ID_FILE_PATH, 'wb+')
</code></pre>
<p><a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">According to the documentation</a>:</p>
<blockquote>
<p>note that 'w+' truncates the file</p>
</blockquote>
<p>You truncate the file, so no won... | 2 | 2016-07-08T00:13:08Z | [
"python",
"python-2.7",
"csv",
"for-loop"
] |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u200f' with python script | 38,257,216 | <p>I am using python to copy part of a field and copy it to another field (in a table). It was working before but now I am getting this UnicodeEncodeError: </p>
<pre><code>Traceback (most recent call last):
File "O:\Projects\NetworkAnalyst\Scripts\python\FiretrailsNameToRoadName.py", line 73, in <module>
e... | 0 | 2016-07-08T00:18:11Z | 38,257,799 | <p>tldr: You can delete the character and hope there are no others lurking. But you really need to understand where that character and its ilk came from. Was it corrupted data, bad input, bad conversion?</p>
<h1>1: You should really try and use python 3. Its time.</h1>
<h1>2:This is similar to <a href="http://stac... | 0 | 2016-07-08T01:45:32Z | [
"python",
"encoding"
] |
Reshaping and grouping part of a dataframe | 38,257,218 | <p>I need help pivoting a dataframe</p>
<pre><code>data = [{'Start Date': '12/3/2016',
'End Date': '12/4/2016',
'Name':'John'},
{'Start Date':'12/3/2016',
'End Date': '12/4/2016',
'Name':'Karen'},
{'Start Date': '12/1/2016',
'End Date': '12/2/2016',
'Name':'John'},
{'Start Date':'12/1/... | 0 | 2016-07-08T00:18:30Z | 38,258,725 | <p>Consider a merge approach with data frame on itself (akin to SQL's self join) and then filter for non-matched names and first pairing with group count:</p>
<pre><code>mdf = pd.merge(df, df, on='End Date')
mdf['grp'] = mdf.groupby('End Date').cumcount()
# End Date Name_x Start Date_x Name_y Start Date_y gr... | 0 | 2016-07-08T04:01:27Z | [
"python",
"pandas"
] |
TypeError: Can't convert 'int' object to string implicitly | 38,257,222 | <pre><code>title = link.string
amount = title.strip().lstrip("$")
try:
print(type(float(amount)))
check = "True"
print(amount + 30) #This doesnt work
except ValueError:
print(type(amount))
check = "False"
</code></pre>
<p>I dont know what im doing wrong any help will be appreciated </p>
<p>Print... | -2 | 2016-07-08T00:19:18Z | 38,257,318 | <p>If the variable <em>amount</em> comes from a <em>lstrip</em> result, that means that the type of <em>amount</em> is <em>str</em>.
So, given this, the sentence</p>
<pre><code>amount + 30
</code></pre>
<p>will return an exception.
You should parse amount before trying to add a number (type <em>int</em> in that case)... | 2 | 2016-07-08T00:34:16Z | [
"python",
"int"
] |
How to get matrix of indices of N maximum values in each row of an numpy matrix? | 38,257,228 | <p>Related to <a href="http://stackoverflow.com/q/6910641/297797">How to get indices of N maximum values in a numpy array?</a>, I have a numpy matrix <code>a</code>, and I would like to produce the array whose <em>i</em>-th row is the column indices of the top <em>N</em> elements of the <em>i</em>-th row of <code>a</co... | 0 | 2016-07-08T00:20:16Z | 38,257,333 | <p>Slicing the last four elements of the order index by row seems to be working:</p>
<pre><code>a.argsort(axis = 1)[:, -4:]
# array([[7, 8, 0, 5],
# [2, 5, 8, 3]])
</code></pre>
<p>The tie method is not defined, so there will be some difference between <code>1</code> and <code>7</code> as well as the order of... | 1 | 2016-07-08T00:37:04Z | [
"python",
"numpy"
] |
Why won't it expand both tar.gz files? | 38,257,300 | <p>I have two tar.gz files, 2014_SRS.tar.gz and 2013_SRS.tar.gz. Each of the files contains a folder called SRS, which is full of text files. I downloaded these from an ftp server. I want to unzip them automatically in Python. This is my code: </p>
<pre><code>import re
import ftplib
import os
import time
import tarfil... | 1 | 2016-07-08T00:32:11Z | 38,257,568 | <p>While this may not answer your specific question as to why both files could not be unzipped with your code , the following is one way to unzip a list of tar.gz files.</p>
<pre><code>import tarfile, glob
srcDir = "/your/src/directory"
dstDir = "/your/dst/directory"
for f in glob.glob(srcDir + "/*.gz"):
t = t... | 0 | 2016-07-08T01:13:40Z | [
"python",
"tar"
] |
an efficient way to speed up some numpy operations | 38,257,306 | <p>I am trying to find an efficient code instead of the following piece of code (that is only one part of my code), to increase the speed:</p>
<pre><code>for pr in some_list:
Tp = T[partition[pr]].sum(0)
Tpx = np.dot(Tp, xhat)
hp = h[partition[[pr]].sum(0)
up = (uk[partition[pr][:]].sum(0))/len(partiti... | 1 | 2016-07-08T00:33:31Z | 38,296,929 | <p>If your partitions are few and have many elements each, you should consider swapping around the indices of your objects. Summing an array of shape <code>(30,1000)</code> along its second dimension should be faster than summing an array of shape <code>(1000,30)</code> along its first dimension, since in the former ca... | 3 | 2016-07-10T22:19:09Z | [
"python",
"numpy"
] |
.annotate() is not plotting all labels | 38,257,335 | <p>I've created a dataframe with stock information. When I go to create a scatter plot and annotate labels, not all of the labels are included. I'm only getting 3 labels out of 50 or so points. I can't figure out why it's not plotting all labels. </p>
<p>My Table:</p>
<pre><code> Dividend ExpenseRatio Net_As... | 0 | 2016-07-08T00:37:35Z | 38,257,635 | <p>ticker here is going to have the value of the ticker of the last row; e.g., "FENY". When you call enumerate(ticker), it will generate an item for each char, so it sounds like your last ticker has 3 entries. </p>
<p>I think you can annotate points in the same loop as the scatter plot:</p>
<p><div class="snippet" da... | 2 | 2016-07-08T01:23:18Z | [
"python",
"pandas",
"matplotlib",
"scatter-plot"
] |
What are the best practices for sharing a Python module between subpackages? | 38,257,342 | <p>Suppose you're creating a python package with four subpackages, and there is a module <code>generic_stuff.py</code> which is required by exactly two of them. To make it concrete, perhaps <code>generic_stuff.py</code> contains some custom functions for reading from and writing to a database and subpackages 1 and 2 c... | 2 | 2016-07-08T00:39:07Z | 38,257,642 | <p>Maybe I'm something, but it seems like you're overthinking the problem. Simply put <code>generic_stuff.py</code> at the highest level of your package and import it in both sub1 and sub2. You can use absolute or relative imports, no name pollution no messing with sys.path. For example:</p>
<p>Package structure:</p>
... | 1 | 2016-07-08T01:23:51Z | [
"python",
"packages"
] |
Score system in game. PYTHON 3.5 | 38,257,358 | <pre><code>def LoginScreen():
global User_Points
User_Points = 5
print("Welcome to Area Trainer")
print("Please enter the username for your account")
global user_name
user_name = str(input())
save = open(user_name + '.txt', 'w')
points = open(user_name + 'Score' + '.txt', 'w+')
point... | 0 | 2016-07-08T00:42:00Z | 38,258,432 | <p>This is because Python automatically overrides data in a file every time it is being opened. You are opening the file multiple times by calling the function multiple times.</p>
| 0 | 2016-07-08T03:20:03Z | [
"python",
"global-variables",
"counting"
] |
Expression evaluation mechanism of Python | 38,257,390 | <p>I used to believe for the Python expression <code>f(g)(x)</code>, the evaluation process is: </p>
<ol>
<li>Evaluate <code>f(g)</code>, return function <code>h</code>;</li>
<li>Evaluate <code>h(x)</code>, return the final result.</li>
</ol>
<p>But the code below shows this is not true:</p>
<pre><code>def double(x)... | 0 | 2016-07-08T00:46:24Z | 38,257,480 | <p>Why do you think that python can see the parameter when the first part is evaluated, it can't. This example might make what's happening more clear. Your example works the same way.</p>
<pre><code>def double(x):
return 2 * x
def f_or_zero(this_f):
def this_f_or_zero(x):
if x > 0:
retu... | 3 | 2016-07-08T01:01:25Z | [
"python",
"expression",
"evaluation"
] |
Django Rest Framework get a parameter from the URL, ignore the one in body | 38,257,414 | <p>I am using Django 1.9 and Django Rest Framework 3.3. I have incoming POST requests that can either be a <code>dict</code> or a <code>list</code>, hitting the same API endpoint. The endpoint URL looks like this: <code>/api/children/3/classes</code>. This <code>3</code> denotes the ID of the child. </p>
<p>My incomin... | 0 | 2016-07-08T00:49:44Z | 38,257,895 | <p>If I'm understanding you correctly, you want to override the <code>child</code> value on the request body using the parameter provided by the url. </p>
<pre><code>def post(self, request, *args, **kwargs):
# django passes params from url in kwargs
# e.g. {id: 3} or {child: 3}, not sure what your url calls it... | 2 | 2016-07-08T02:01:04Z | [
"python",
"django",
"django-rest-framework"
] |
Need help creating and plotting a list | 38,257,489 | <p>This is a meaty question, but it could be useful to other people working with list and tuples. I need to take the list <code>CALC_RECORD</code> and just pull the third element from the list. The output currently looks something like this: <code>[('calculation', 1467938304.345363, 1.2636651992797852)]</code>. The ... | 0 | 2016-07-08T01:02:40Z | 38,257,565 | <p>If you have a list of tuples, and you want to pull out the third element of each tuple into a new list, then the following should work:</p>
<pre><code>new_list = [t[2] for t in old_list]
</code></pre>
<p>Or you can use <code>map</code> and <code>lambda</code> :</p>
<pre><code>new_list = list(map(lambda t: t[2], o... | 0 | 2016-07-08T01:13:18Z | [
"python",
"list",
"python-3.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.