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 remove brackets from RDD output? | 39,430,416 | <p>When I print an RDD I get the following result:</p>
<pre><code>[(46, u'15910'), (43, u'15287'), (43, u'15237'), (42, u'15923'), (41, u'15298')]
</code></pre>
<p>I want to save the RDD output to a csv file without brackets or the 'u' sign, similar to below:</p>
<pre><code>46, 15910
43, 15287
43, 15237
42, 15923
41... | 0 | 2016-09-10T20:43:25Z | 39,430,739 | <p>Either write csv:</p>
<pre><code>>>> rdd.toDF().write.csv("path")
</code></pre>
<p>or format:</p>
<pre><code>>>> rdd.map(lambda (k, v): "{0},{1}".format(k, v)).saveAsTextFile("path")
</code></pre>
| 3 | 2016-09-10T21:29:31Z | [
"python",
"apache-spark",
"pyspark",
"rdd"
] |
Why is my function that I made getting the TypeError: f() takes 0 positional arguments but 1 was given | 39,430,440 | <p>I am working with pandas DataFrames and I am adding new columns for more advanced analysis. My f function is giving me an error TypeError: f() takes 0 positional arguments but 1 was given. I can't figure out why, I have my f function documented in the code if you need to know what it does. </p>
<pre><code>from pand... | 2 | 2016-09-10T20:46:38Z | 39,430,538 | <p>You're passing <code>f</code> as the function in <code>apply</code>. That function is called for each row in the dataframe, and needs to take the row as its parameter.</p>
<p>Note also that you're returning the function itself as the result; I'm pretty sure you meant to return <code>x</code> not <code>f</code>. Als... | 4 | 2016-09-10T21:02:02Z | [
"python",
"pandas",
"if-statement",
"dataframe"
] |
storing serialized data in postgres by SQLAlchemy | 39,430,466 | <p>I am building an App by using Flask with Postgress and SQLAlchemy.
There is a table column where I need to store serialized data (JSON). How do I define the field in the model class? </p>
<p>Can I just use string field for the column?</p>
<pre><code>from flask.ext.sqlalchemy import SQLAlchemy
from main import app... | 0 | 2016-09-10T20:50:37Z | 39,430,915 | <p>You need to import <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSON" rel="nofollow"><code>JSON</code></a> or <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB" rel="nofollow"><code>JSONB</code></a> fro... | 0 | 2016-09-10T21:50:18Z | [
"python",
"json",
"postgresql",
"sqlalchemy",
"flask-sqlalchemy"
] |
Pick random coordinates in Numpy array based on condition | 39,430,572 | <p>I have used convolution2d to generate some statistics on conditions of local patterns. To be complete, I'm working with images and the value 0.5 is my 'gray-screen', I cannot use masks before this unfortunately (dependence on some other packages). I want to add new objects to my image, but it should overlap at least... | 2 | 2016-09-10T21:06:19Z | 39,430,720 | <p><code>np.where</code> and <code>np.random.randint</code> should do the trick :</p>
<pre><code>#we grab the indexes of the ones
x,y = np.where(convoluted_image <=1)
#we chose one index randomly
i = np.random.randint(len(x))
random_pos = [x[i],y[i]]
</code></pre>
| 2 | 2016-09-10T21:27:25Z | [
"python",
"numpy"
] |
Python: Can't decode a json string | 39,430,752 | <pre><code>import json
from gfycat.client import GfycatClient
client = GfycatClient()
r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard")
robject = json.loads(r)
print robject['gifUrl']
</code></pre>
<p>This is my current source code. It's meant to get a gifurl in the json text, but it just doesn't. If I don't ... | -1 | 2016-09-10T21:30:53Z | 39,430,790 | <p><code>gifUrl</code> is inside <code>gfyItem</code>, so you should try <code>robject['gfyItem']['gifUrl']</code></p>
| 0 | 2016-09-10T21:35:04Z | [
"python",
"json",
"decode"
] |
Python: Can't decode a json string | 39,430,752 | <pre><code>import json
from gfycat.client import GfycatClient
client = GfycatClient()
r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard")
robject = json.loads(r)
print robject['gifUrl']
</code></pre>
<p>This is my current source code. It's meant to get a gifurl in the json text, but it just doesn't. If I don't ... | -1 | 2016-09-10T21:30:53Z | 39,430,792 | <pre><code>import json
from gfycat.client import GfycatClient
client = GfycatClient()
r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard")
print r['gfyItem']['gifUrl']
</code></pre>
| -1 | 2016-09-10T21:35:09Z | [
"python",
"json",
"decode"
] |
Python: Can't decode a json string | 39,430,752 | <pre><code>import json
from gfycat.client import GfycatClient
client = GfycatClient()
r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard")
robject = json.loads(r)
print robject['gifUrl']
</code></pre>
<p>This is my current source code. It's meant to get a gifurl in the json text, but it just doesn't. If I don't ... | -1 | 2016-09-10T21:30:53Z | 39,430,837 | <p>Your JSON sample is invalid with multiple different errors. Run it through the JSON validator linked below to get a detailed list.</p>
<p><a href="https://jsonformatter.curiousconcept.com/" rel="nofollow">https://jsonformatter.curiousconcept.com/</a></p>
| 0 | 2016-09-10T21:40:19Z | [
"python",
"json",
"decode"
] |
Use metaclass to allow forward declarations | 39,430,798 | <p>I want to do something decidedly unpythonic. I want to create a class that allows for forward declarations of its class attributes. (If you must know, I am trying to make some sweet syntax for parser combinators.)</p>
<p>This is the kind of thing I am trying to make:</p>
<pre><code>a = 1
class MyClass(MyBaseClass)... | 2 | 2016-09-10T21:36:08Z | 39,431,036 | <p>To start with:</p>
<pre><code> def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
...
</code></pre>
<p>But that won't allow you to retrieve the global variables outside the class body.
You can also use the <code>__missin__</code> method w... | 1 | 2016-09-10T22:09:25Z | [
"python",
"python-3.x",
"metaclass"
] |
How to detect screen rotation on Android in Kivy? | 39,430,824 | <p>I have been searching for a Kivy solution to capture the Android device rotation from one orientation to another. I have tried both of the window methods below but neither executes the <code>on_rotate</code> or <code>rotate_screen</code> routines when I rotate the device. I see there is an <code>onConfigurationChan... | 2 | 2016-09-10T21:38:43Z | 39,431,581 | <p>I think on_rotate only tracks Kivy's internal rotation (this is done in OpenGL and doesn't relate to the Android level rotation).</p>
<p>You can probably use pyjnius to work with the normal Java methods for this, but I don't know the details. A simple solution that may work just as well is to watch <code>Window.siz... | 0 | 2016-09-10T23:44:48Z | [
"android",
"python",
"rotation",
"kivy",
"onconfigurationchanged"
] |
subprocess.call and ending current program | 39,430,972 | <p>My main program checks if a new version of itself is available and if so it downloads the new installer file and runs it:
<code>subprocess.call(["installer.exe"], shell=True)</code>
But in order to overwrite the old files, it needs to exit itself after calling the subprocess. How can I achieve this?</p>
| 3 | 2016-09-10T21:58:36Z | 39,431,001 | <p>In Windows, just <code>start</code> your installer program instead of waiting for it.</p>
<pre><code>import subprocess
subprocess.call(["start","installer.exe"],shell=True)
print("out")
</code></pre>
<p>Running this will print <code>out</code> immediately and returns to the console if this is the last statement (... | 2 | 2016-09-10T22:02:59Z | [
"python",
"subprocess"
] |
Why GridSearchCV return score so different from the score returned by running model directly? | 39,430,998 | <p>I used GridSearchCV to find the best alpha for lasso model.</p>
<pre><code>alphas = np.logspace(-5, 2, 30)
grid = GridSearchCV(estimator=Lasso(),
param_grid=dict(alpha=alphas), cv=10, scoring='r2')
grid.fit(self.X, self.Y) # entire datasets were fed here
print grid.best_params_, grid.best_score_ # score -0.0470788... | 1 | 2016-09-10T22:02:45Z | 39,438,123 | <p>I found the reason. </p>
<p>cv should be set like this:</p>
<pre><code>cv = ShuffleSplit(n=len(X), n_iter=10, test_size=.3)
</code></pre>
<p>when cv equals to integer, it means how many folds there are in each iteration not the number of iterations. </p>
| 0 | 2016-09-11T16:13:43Z | [
"python",
"scikit-learn",
"linear-regression",
"grid-search",
"lasso"
] |
How do I use a different index for each row in a numpy array? | 39,431,085 | <p>I have a NxM numpy array filled with zeros and a 1D numpy array of size N with random integers between 0 to M-1. As you can see the dimension of the array matches the number of rows in the matrix. Each element in the integer array means that at that given position in its corresponding row must be set to 1. For examp... | 2 | 2016-09-10T22:18:20Z | 39,431,109 | <p>Use <code>np.arange(N)</code> in order to address the rows and indices for columns:</p>
<pre><code>>>> a[np.arange(2),indices] = 1
>>> a
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
</code></pre>
<p>Or:</p>
<pre><code>>... | 2 | 2016-09-10T22:22:36Z | [
"python",
"arrays",
"numpy",
"matrix-indexing"
] |
Updating label keeps previous text | 39,431,091 | <p>In the program I made, the user presses enter and the text typed is then shown as a label in the program. So the label keeps getting updated and then written on the next line. The problem is that in the textbox the previous line the user typed stays there, which means u have to keep manually deleting the string in t... | -1 | 2016-09-10T22:19:36Z | 39,431,135 | <p>Since you bind <code>evaluate</code> as a callback and you use it as a button command, when you use it in the button you have to use a lambda and pass <code>None</code> to the event. <code>event</code> argument is needed because of the binding, but there is no event when you call it from button click, so just pass <... | 1 | 2016-09-10T22:26:59Z | [
"python",
"python-3.x",
"tkinter",
"event-handling",
"label"
] |
Unable to remove objects from a list in another object | 39,431,106 | <p>Here is some test code to describe my problem. I have created two classes as follows...</p>
<pre><code>class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in... | 3 | 2016-09-10T22:22:07Z | 39,431,119 | <p>You didn't define when two <code>Card</code> instances are equal. Without such a definition, <code>list.remove()</code> can't find anything that is equal (<code>obj1 == obj2</code> is true). The default implementation for custom classes is to be equal only when the object is <em>identical</em> (the exact same object... | 5 | 2016-09-10T22:24:23Z | [
"python"
] |
Does the position of python import statements affect performance | 39,431,169 | <p>I was wondering if the position of import statements in a python program has any affect on performance. For example if I have this</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import requests
from flask import render_template, request, Flask, session, Markup, jsonify, sen... | 0 | 2016-09-10T22:32:24Z | 39,431,201 | <p>Importing does <em>two</em> things:</p>
<ol>
<li><p>If there is no <code>sys.modules</code> entry yet, find and load the module; if Python code, executing the top-level code produces the namespace for that module. This step is skipped if the module has already been loaded.</p></li>
<li><p>Bind a name in the current... | 6 | 2016-09-10T22:36:59Z | [
"python"
] |
How do I dynamically create instances of all classes in a directory with python? | 39,431,287 | <p>I'm trying to do something like this:</p>
<pre><code>from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U
objs = []
objs.append(Q())
objs.append(W())
objs.append(E())
objs.append(R())
objs.append(T())
# and so on...
</code></pre>
<p>The above code is very large, and would tak... | 0 | 2016-09-10T22:50:01Z | 39,431,379 | <p>If you want to instantiate all the imported objects, you can access them through the global name space with <code>global()</code> built-in function.</p>
<pre><code>from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U
instances = [obj() for name, obj in globals().items() if not... | 0 | 2016-09-10T23:08:49Z | [
"python",
"dynamic",
"constructor"
] |
How do I dynamically create instances of all classes in a directory with python? | 39,431,287 | <p>I'm trying to do something like this:</p>
<pre><code>from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U
objs = []
objs.append(Q())
objs.append(W())
objs.append(E())
objs.append(R())
objs.append(T())
# and so on...
</code></pre>
<p>The above code is very large, and would tak... | 0 | 2016-09-10T22:50:01Z | 39,431,683 | <p>So I managed to figure out how to do this.</p>
<p>Here's the code for it:</p>
<pre><code>import os
import imp
import inspect
obj_list = []
dir_path = os.path.dirname(os.path.realpath(__file__))
pattern = "*.py"
for path, subdirs, files in os.walk(dir_path):
for name in files:
if fnmatch(name, patter... | 0 | 2016-09-11T00:05:36Z | [
"python",
"dynamic",
"constructor"
] |
Django: TypeError: 'x' is an invalid keyword argument for this function | 39,431,318 | <p>The view below works, which is utilising the "update_or_create" feature, brilliantly when something exists and therefore updates a record. However, if it does not exist and has to use the create option to create a new record I get the following error:</p>
<pre><code>TypeError at /selectteams/1025/3/
'soccerseason... | 1 | 2016-09-10T22:56:05Z | 39,431,669 | <p>It looks like it is using your defaults where you have "soccerseasonid_id" specified instead of "soccerseason_id". "soccerseason_id" should work.</p>
| 2 | 2016-09-11T00:03:12Z | [
"python",
"mysql",
"django"
] |
Monkey Theorem - pick random letters until input string is generated | 39,431,322 | <p>I wanted to make a code resembles the infinite monkey theorem
<strong>the theorem states that:</strong> </p>
<blockquote>
<p>a monkey hitting keys at random on a typewriter keyboard for infinite
amount of time will almost surely type a given text such as the
complete works of Shakespeare.</p>
</blockquote>
<... | 1 | 2016-09-10T22:56:54Z | 39,431,414 | <p>In your code, you set <code>string_letters = 'abcdefghijklmnopqrstuvwxyz'</code>. Notice that there is no space in <code>string_letters</code>, so when you have matched the entire first word <code>'methinks'</code> it is impossible to match the space after that word. So your loop continues infinitely.</p>
<p>You ca... | 1 | 2016-09-10T23:15:19Z | [
"python"
] |
Monkey Theorem - pick random letters until input string is generated | 39,431,322 | <p>I wanted to make a code resembles the infinite monkey theorem
<strong>the theorem states that:</strong> </p>
<blockquote>
<p>a monkey hitting keys at random on a typewriter keyboard for infinite
amount of time will almost surely type a given text such as the
complete works of Shakespeare.</p>
</blockquote>
<... | 1 | 2016-09-10T22:56:54Z | 39,431,448 | <p>You can print something within the loop to see if it is infinite... For example, if <code>z</code> is never equal to the <code>sentence[x]</code>, then you won't increment it, and the loop never stops. </p>
<p>That will happen when you need to guess a space character because you have not put one into your string. T... | 1 | 2016-09-10T23:21:43Z | [
"python"
] |
how can i correct this Regex phone number extractor in python | 39,431,340 | <p>The results i'm getting when i run this after copying a set of UK phone numbers to the clipboard are coming out in a very bizarre kind of way.
(i have imported both modules before you ask)</p>
<pre><code>phoneRegex = re.compile(r'''(
(\d{5}|\(\d{5}\))? #area code
(\s|-|\.)? #separator
... | 0 | 2016-09-10T22:59:38Z | 39,435,853 | <p>I see three issues:</p>
<ol>
<li><p>the python code joins the two parts of the phone number together with a <code>-</code> and then adds a space and the third part again:</p>
<pre><code> phoneNum = '-'.join([groups[1], groups[3]])
if groups[3] != '':
phoneNum += ' ' + groups[3]
</code></pre>
<p>Sin... | 1 | 2016-09-11T12:02:16Z | [
"python",
"regex"
] |
Python boto: filter on tag and value | 39,431,353 | <p>Filtering by tag key works just fine:</p>
<pre><code>ec2.get_all_instances(filters={'tag-key': 'MachineType'})
</code></pre>
<p>How can I filter by key and value?</p>
<pre><code>"MachineType=DB"
</code></pre>
| 1 | 2016-09-10T23:03:39Z | 39,432,630 | <p><strong>Boto</strong></p>
<pre><code>ec2.get_all_instances(filters={"tag:MachineType" : "DB"})
</code></pre>
<p><strong>Boto3</strong></p>
<pre><code>import boto3
ec2 = boto3.resource('ec2')
inst_filter = [{'Name':'tag: MachineType', 'Values':['DB']}]
insts = list(ec2.instances.filter(Filters=inst_filter))
for i... | 1 | 2016-09-11T03:41:40Z | [
"python",
"amazon-web-services",
"boto"
] |
Angular2 and Django: CSRF Token Headache | 39,431,386 | <p><strong>The Issue I'm Having</strong></p>
<ul>
<li>I'm making an Ajax POST request from my <strong>Angular2</strong> client to my <strong>Django</strong> (v1.9) backend (both on localhost, different ports). I'm not yet using the Django REST framework, I'm just dumping the JSON in Django without any add-ons.</li>
<l... | 1 | 2016-09-10T23:10:03Z | 39,436,142 | <p>I think the problem is that your request only has the CSRF token header, but not the cookie (see the <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Double_Submit_Cookie" rel="nofollow">double submit</a> mitigation against CSRF, the header you're sending should be co... | 0 | 2016-09-11T12:33:39Z | [
"python",
"django",
"angular2",
"cors",
"csrf"
] |
Making a loop with lists | 39,431,455 | <p>I am new to Python and would like to create a print function that repeats itself for each item in a list (this is only an example my actual code will be for something else)</p>
<pre><code>cars.list = [Honda, Chevrolet, Suzuki, Ford]
price.list = [5600, 11500, 6600, 1020]
</code></pre>
<p>The prices and car lists ... | 0 | 2016-09-10T23:22:42Z | 39,431,512 | <p>You can use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to associate the cars and prices together in an iterator of tuples, then iterate over those tuples while printing what you want.</p>
<pre><code>cars = ['Honda', 'Chevrolet', 'Suzuki', 'Ford']
prices = [560... | 1 | 2016-09-10T23:32:09Z | [
"python",
"list",
"python-3.x",
"printing",
"count"
] |
Performing an operation on every document in a MongoDB instance | 39,431,475 | <p>I have a mongoDB collection with 1.5 million documents, all of which have the same fields, and I want to take the contents of Field A (which is unique in every document) and perform <code>f(A)</code> on it, then create and populate Field B. Pseudocode in Python:</p>
<pre><code>for i in collection.find():
x = i*... | 2 | 2016-09-10T23:25:27Z | 39,431,701 | <p>Database clients tend to be extremely abstracted from actual database activity, so observed delay behaviors can be deceptive. It's likely that you are actually hammering the database in that time, but the activity is all hidden from the Python interpreter.</p>
<p>That said, there are a couple things you can do to m... | 0 | 2016-09-11T00:10:44Z | [
"python",
"mongodb",
"performance",
"optimization"
] |
Performing an operation on every document in a MongoDB instance | 39,431,475 | <p>I have a mongoDB collection with 1.5 million documents, all of which have the same fields, and I want to take the contents of Field A (which is unique in every document) and perform <code>f(A)</code> on it, then create and populate Field B. Pseudocode in Python:</p>
<pre><code>for i in collection.find():
x = i*... | 2 | 2016-09-10T23:25:27Z | 39,431,878 | <p>Maybe you should do your updates in multiple threads. I think it may be better to load data in one thread, split it into multiple parts and pass that parts to parallel worker threads that will perform updates. It will be faster.</p>
<p>EDIT:</p>
<p>I suggest you doing paginated queries.
Python pseudocode: </p>
<... | 0 | 2016-09-11T00:48:47Z | [
"python",
"mongodb",
"performance",
"optimization"
] |
PyOpenCL Kronecker Product Kernel | 39,431,504 | <p>I have the following code for confirming a hand written method for computing the kronecker product of two square matrices. The first portion indeed validates that my method of repeating and tiling <code>a</code> and <code>b</code> respectively yields the same output.</p>
<pre><code>import pyopencl as cl
import nump... | 0 | 2016-09-10T23:31:10Z | 39,431,689 | <p>The issue is that the kernel does not take indices for the input and output memory addresses. The arguments should be <code>C[i+j*N]</code> in order to move throughout the whole block of memory appropriately.</p>
| 0 | 2016-09-11T00:07:09Z | [
"python",
"opencl",
"gpgpu",
"matrix-multiplication",
"pyopencl"
] |
Extracting text from find_next_sibling(), BeautifulSoup | 39,431,506 | <p>I am trying to extract the description of the Chinese character from this website: <a href="http://www.hsk.academy/en/hsk_1" rel="nofollow">http://www.hsk.academy/en/hsk_1</a></p>
<p>Example html:
</p>
<pre><code> <tr>
<td>
<span class="hanzi"><a href="/en/ch... | 0 | 2016-09-10T23:31:20Z | 39,431,819 | <p>Try this:</p>
<pre><code>english_descriptions = []
table = soup.find('table', id='flat_list')
for e in table.select('.hanzi'):
english_desc = e.parent.find_next_sibling().text
if not any(english_desc in s for s in english_descriptions):
english_descriptions.append(english_desc)
</code></pre>
<p>Thi... | 1 | 2016-09-11T00:36:30Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
Why is the execution time for my sorting code inconsistent? | 39,431,517 | <p>I'm learning python and I've implemented a quicksort algorithm (kind of). I do know that python's <code>sort()</code> method would be faster but I wanted to know by how much, so I've used the <code>timeit</code> module for comparison.</p>
<p>I created a 'wrapper' function for the <code>sort()</code> method so it wo... | 3 | 2016-09-10T23:33:14Z | 39,431,566 | <p>Your timing is horribly wrong in multiple ways. First, your <code>sort</code> wrapper still mutates its input instead of returning a new list:</p>
<pre><code>>>> x = [2, 1]
>>> sort(x)
[1, 2]
>>> x
[1, 2]
</code></pre>
<p>Second, you're not timing either sort at all. You're timing the ev... | 5 | 2016-09-10T23:41:20Z | [
"python",
"performance",
"sorting",
"time"
] |
Scapy - sending IPv6 Router Advertisement failing with lifetime > 0 | 39,431,563 | <p>I am attempting to create a tool using Scapy to discover link-local IPv6 hosts by sending a fake router advertisement to the FF02::1 multicast address.</p>
<pre><code>*SNIP*
router_advertisement = scapy.IPv6(src=ra_src_addr, dst='FF02::1')/scapy.ICMPv6ND_RA(routerlifetime=0, reachabletime=0)/scapy.ICMPv6NDOptSrcLLA... | 1 | 2016-09-10T23:40:45Z | 39,439,585 | <p>I would argue that <code>scapy</code> is a little dodgy in this respect. Your trackeback here:</p>
<pre><code>return struct.pack("HH",self.mladdr)+self.payload.hashret()
</code></pre>
<p>Should contain the following:</p>
<pre><code>return struct.pack("HH", 0, 0)+""
</code></pre>
<p>That <code>struct.pack</code>... | 1 | 2016-09-11T19:00:02Z | [
"python",
"networking",
"ipv6",
"scapy"
] |
Install pybrain in ubuntu 16.04 "ImportError: No module named pybrain.structure" | 39,431,684 | <p>I'm getting that error:</p>
<p><code>ImportError: No module named pybrain.structure</code></p>
<p>When executing:</p>
<p><code>
from pybrain.pybrain.structure import FeedForwardNetwork
</code></p>
<p>From the pybrain tutorial.</p>
<p>I installed pybrain running:</p>
<p><code>sudo python setup.py install</code>... | 1 | 2016-09-11T00:05:44Z | 39,431,699 | <p>The problem was resolved replacing <code>pybrain.pybrain</code> by <code>pybrain</code>.</p>
| 0 | 2016-09-11T00:09:24Z | [
"python",
"pybrain"
] |
Error in my function | 39,431,688 | <p>When I run my code, I get this error: </p>
<pre><code><function setDegreesAndMinutes at 0x10e7cf6e0>
</code></pre>
<p>My code is:</p>
<pre><code>def setDegreesAndMinutes(self, degrees,minutes):
self.degrees = int(input())
self.minutes = float(input())
if(not(isinstance(degrees, int))):
raise Value... | -2 | 2016-09-11T00:07:00Z | 39,432,052 | <p>That is not an error at all... You printed a <em>function object</em>. </p>
<p>You never <em>called</em> the function passing in <code>(self, degrees, minutes)</code> as parameters to <code>setDegreesAndMinutes</code>. </p>
<p>Also, typically <code>self</code> means you have defined that method in a class, so you ... | 2 | 2016-09-11T01:29:27Z | [
"python",
"function"
] |
How to make a python program run just by typing the name alone at the terminal? | 39,431,697 | <p>I am not sure what I am supposed to be searching, because everything I have been trying to look up has not really given me the answers that I need.</p>
<p>If anyone can point me in the right direction of exactly what I should be looking at, I would greatly appreciate it. Basically, I want to know the best way to go... | 1 | 2016-09-11T00:08:51Z | 39,431,730 | <p>On Unix like systems</p>
<pre><code>#! /usr/bin/env python
</code></pre>
<p>in the very first line of your chmod +x script file will make it executable from the current directory using ./filename</p>
<p>If you want completely straightforward execution from anywhere you can put it on the path somewhere however you... | 2 | 2016-09-11T00:16:35Z | [
"python",
"linux",
"bash",
"shell",
"scripting"
] |
werkzeug.routing.BuildError BuildError: ('oauth_authorize', {'provider': 'twitter'}, None) | 39,431,737 | <p>I'm trying to add Login with twitter redirect in my login page. Which is called login.html.</p>
<pre><code><li><a href="{{ url_for('oauth_authorize', provider='twitter') }}">Login with Twitter</a></li>
</code></pre>
<p>upon clicking that URL it throws me BUILDERROR.</p>
<pre><code>BuildErr... | 0 | 2016-09-11T00:17:47Z | 39,431,952 | <p>Because you're using Blueprints, in your Jinja template you'll need to call the endpoint like this</p>
<pre><code>url_for('user_blueprint.oauth_authorize', provider='twitter')
</code></pre>
| 1 | 2016-09-11T01:07:15Z | [
"python",
"redirect",
"flask"
] |
Is there any way to run .js scripts in phantomjs via Python+selenium? | 39,431,791 | <p>I'm currently using selenium in Python to create a session of Phantomjs browser and I was wondering if there is any way of running .js scripts on that browser (since I can't find anything on Phantomjs docs) or if I have to switch to Firefox and install an extension like Tampermonkey or such. Thanks for help and sorr... | -2 | 2016-09-11T00:30:01Z | 39,431,827 | <p>PhantomJS is essentially a headless browser and script runner. You can write and run any arbitrary Javascript and run it with PhantomJS. Here's a reference: <a href="http://phantomjs.org/page-automation.html" rel="nofollow">http://phantomjs.org/page-automation.html</a></p>
| 0 | 2016-09-11T00:38:23Z | [
"python",
"selenium",
"firefox",
"phantomjs"
] |
'float' object is not iterable error | 39,431,830 | <p>I am trying to get a a variable that reads out a load value (given in xml document) for a given length of a time (also a list of values). The list for t is from a value 'start' to 'end' with an interval of 15 min. Essentially what I want is that I want one load value to print for the entire length of its respective ... | -1 | 2016-09-11T00:39:26Z | 39,431,855 | <p><code>self.load</code> i an array of <code>float</code>s, so <code>self.load[j]</code> will be a float, which is what you are trying to iterate over; hence the error message.</p>
| 0 | 2016-09-11T00:43:07Z | [
"python",
"xml",
"list",
"floating-point"
] |
How to distribute code to be executed by an external command? Bash script? | 39,431,958 | <p>EDIT: Based on discussions below, I think my question really code apply to any language. Python naturally has a packaging system and installation procedure via <code>pip</code>. But let's say this was C code or a perl script. Users still would download the program files, and have a way to execute the code in the com... | 2 | 2016-09-11T01:09:39Z | 39,432,028 | <p>Add a "hash bang" at the top of the script file to tell bash to invoke the Python interpreter. Also make your script executable:</p>
<pre><code>#!/usr/bin/env python
import sys
inFile = sys.argv[1]
outFile = sys.argv[2]
...
</code></pre>
<p>Make the script file executable:</p>
<pre><code>$ cp file1.py capsall
$ ... | 1 | 2016-09-11T01:22:42Z | [
"python",
"bash",
"shell",
"unix",
"command"
] |
How to distribute code to be executed by an external command? Bash script? | 39,431,958 | <p>EDIT: Based on discussions below, I think my question really code apply to any language. Python naturally has a packaging system and installation procedure via <code>pip</code>. But let's say this was C code or a perl script. Users still would download the program files, and have a way to execute the code in the com... | 2 | 2016-09-11T01:09:39Z | 39,442,272 | <p>I would recommend using python packaging (e.g., [pip]) for this. You could use the OS specific packaging method as well, something like <em>apt</em>, <em>yum</em>, <em>msiexec</em>, whatever, but I wouldn't unless you have to. Your users already have python installed since they are used to explicitly passing your ... | 1 | 2016-09-12T01:27:47Z | [
"python",
"bash",
"shell",
"unix",
"command"
] |
Scrapy - Use proxy middleware but disable proxy for specific requests | 39,432,024 | <p>I want to use proxy middleware in my Scrapy but not every request needs a proxy. I don't want to abuse the proxy usage and make the proxy prone to get banned.</p>
<p>Is there a way for me to disable proxy in some requests when the proxy middleware is turned on?</p>
| -1 | 2016-09-11T01:22:25Z | 39,432,238 | <p>It's in the <a href="http://scrapy.readthedocs.io/en/latest/topics/downloader-middleware.html#module-scrapy.downloadermiddlewares.httpproxy" rel="nofollow">docs</a>. </p>
<p>You can set the meta key <code>proxy</code> per-request, to a value like <code>http://some_proxy_server:port</code>.</p>
| 0 | 2016-09-11T02:13:44Z | [
"python",
"web-scraping",
"scrapy",
"screen-scraping",
"scrapy-spider"
] |
How to use lists from a text file in python? | 39,432,057 | <p>i have been trying to read/write values(lists) in a .txt file and using them later, but i can't find a function or something to help me use these values as lists and not strings, since using the <code>readline</code> function doesn't help.</p>
<p>Also, im don't want to use multiple text files to make up 1 list</p>
... | 2 | 2016-09-11T01:29:53Z | 39,432,175 | <p>Sounds like you want to read it as comma separated values.</p>
<p>Try the following</p>
<pre><code>import csv
with open('test.txt', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
</code></pre>
<p>I believe that will put you on the right track. For more informati... | 1 | 2016-09-11T01:56:12Z | [
"python",
"list",
"file",
"python-3.x"
] |
How to use lists from a text file in python? | 39,432,057 | <p>i have been trying to read/write values(lists) in a .txt file and using them later, but i can't find a function or something to help me use these values as lists and not strings, since using the <code>readline</code> function doesn't help.</p>
<p>Also, im don't want to use multiple text files to make up 1 list</p>
... | 2 | 2016-09-11T01:29:53Z | 39,432,176 | <p>To me, it looks like you're trying to read a file, and split it by <code>,</code>.<br>
This can be accomplished by</p>
<pre><code>f = open("test.txt", "r+").read()
v = f.split(",")
print(v)
</code></pre>
<p>It should output</p>
<blockquote>
<p>['cat', ' dog', ' dinosaur', ' elephant\ncheese', ...]</p>
</blockqu... | 1 | 2016-09-11T01:56:31Z | [
"python",
"list",
"file",
"python-3.x"
] |
Can I include a for loop inside my print statement? | 39,432,063 | <p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p>
<pre><code> for items in winners:
print(items)
</code></pre>
<p>Can I include this in a print statement?
I want:</p>
<pre><code> ... | 2 | 2016-09-11T01:30:44Z | 39,432,094 | <p>If <code>winners</code> is a list of strings, you can concatenate them using <code>str.join</code>.</p>
<p>For example:</p>
<pre><code>>>> winners = ['John', 'Jack', 'Jill']
>>> ', '.join(winners)
'John, Jack, Jill'
</code></pre>
<p>So you can put <code>', '.join(winners)</code> in your print ca... | 0 | 2016-09-11T01:35:51Z | [
"python",
"python-3.x"
] |
Can I include a for loop inside my print statement? | 39,432,063 | <p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p>
<pre><code> for items in winners:
print(items)
</code></pre>
<p>Can I include this in a print statement?
I want:</p>
<pre><code> ... | 2 | 2016-09-11T01:30:44Z | 39,432,097 | <p>You can't include a for loop but you can join your list of winners into a string.</p>
<pre><code>winners = ['Foo', 'Bar', 'Baz']
print('the winners were {}.'.format(', '.join(winners)))
</code></pre>
<p>This would print</p>
<blockquote>
<p>the winners were Foo, Bar, Baz.</p>
</blockquote>
| 5 | 2016-09-11T01:36:44Z | [
"python",
"python-3.x"
] |
Can I include a for loop inside my print statement? | 39,432,063 | <p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p>
<pre><code> for items in winners:
print(items)
</code></pre>
<p>Can I include this in a print statement?
I want:</p>
<pre><code> ... | 2 | 2016-09-11T01:30:44Z | 39,432,198 | <p>A for loop can only be supplied to <code>print</code> in the form of a comprehension.</p>
<p>But, if the list contents are in the respective order you require you can simply do:</p>
<pre><code>print("The winners of {} were: {} with a score of {}".format(*winners))
</code></pre>
<p>This just matches each bracket w... | 0 | 2016-09-11T02:02:10Z | [
"python",
"python-3.x"
] |
Can I include a for loop inside my print statement? | 39,432,063 | <p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p>
<pre><code> for items in winners:
print(items)
</code></pre>
<p>Can I include this in a print statement?
I want:</p>
<pre><code> ... | 2 | 2016-09-11T01:30:44Z | 39,439,409 | <p>First note, in Python 3 <code>print</code> is a function, but it was a statement in Python 2. Also you can't use a <code>for</code> statement as an argument.
Only such weird solution comes to my mind, which only looks like a for loop:</p>
<pre><code>data = ['Hockey','Swiss', '3']
print("Sport is {}, winner is {}, ... | 0 | 2016-09-11T18:39:19Z | [
"python",
"python-3.x"
] |
I can't expand the template django | 39,432,090 | <p>I can't expand the template <code>base.html</code> template <code>header.html</code></p>
<p>Content <code>base.html</code></p>
<pre><code><div id="main-container">
<!-- HEADER -->
{% block header %}{% endblock %}
<!-- END HEADER -->
</div>
</code></pre>
<p>Content <code>header.html... | 4 | 2016-09-11T01:35:19Z | 39,433,889 | <p>I think you would have confused between the include and extend in django templates. </p>
<p>Based on your file names, I assume that <code>header.html</code> is the partial which is to be included in the base.html and you are rendering <code>base.html</code> . </p>
<p>Django templating engine does not work this way... | 0 | 2016-09-11T07:38:23Z | [
"python",
"django",
"templates"
] |
I can't expand the template django | 39,432,090 | <p>I can't expand the template <code>base.html</code> template <code>header.html</code></p>
<p>Content <code>base.html</code></p>
<pre><code><div id="main-container">
<!-- HEADER -->
{% block header %}{% endblock %}
<!-- END HEADER -->
</div>
</code></pre>
<p>Content <code>header.html... | 4 | 2016-09-11T01:35:19Z | 39,437,525 | <p>If you want to extend some template, you should render template with {% extends ... %} tag (in your case header.html), if you want to include something to renedered template, you should use {% include ... %} tag. You can make new template for particular page and ovreload {% block head %}, for example:</p>
<p>base.h... | 0 | 2016-09-11T15:11:54Z | [
"python",
"django",
"templates"
] |
pandas: Keep only every row that has cumulated change by a threshold? | 39,432,140 | <p>I'm interested to extract the rows where a column's value has either gone up cumulatively by at least 5 or gone down cumulatively by at least 5, then get the signs of these cumulative changes, <code>up_or_down</code>.</p>
<p>For example, let's say I want to apply this to column <code>y</code> in the following:</p>
... | 4 | 2016-09-11T01:47:12Z | 39,432,516 | <p>You can't get it vectorized through the standard functions pandas exposed: the nth point to find moving by +/-5 from n-1th is dynamically found and will depend on the position of n-1th, which itself depends on the n-2 first dynamically determined points. Thus there is no math associated to rolling or expanding set o... | 1 | 2016-09-11T03:17:45Z | [
"python",
"pandas",
"numpy"
] |
pandas: Keep only every row that has cumulated change by a threshold? | 39,432,140 | <p>I'm interested to extract the rows where a column's value has either gone up cumulatively by at least 5 or gone down cumulatively by at least 5, then get the signs of these cumulative changes, <code>up_or_down</code>.</p>
<p>For example, let's say I want to apply this to column <code>y</code> in the following:</p>
... | 4 | 2016-09-11T01:47:12Z | 39,433,126 | <p>see <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/19351/path-dependent-slicing#t=201609082151350926644">Path Dependent Slicing</a></p>
<p>This is the core of the solution</p>
<pre><code>def big_diff(y):
val = y.values
r = val[0]
for i, x in enu... | 3 | 2016-09-11T05:20:09Z | [
"python",
"pandas",
"numpy"
] |
How can I speed this up? (urllib2, requests) | 39,432,156 | <p>Problem: I am trying to validate a captcha can be anything from 0000-9999, using the normal requests module it takes around 45 minutes to go through all of them (0000-9999). How can I multithread this or speed it up? Would be really helpful if I can get the HTTP Status Code from the site to see if i successfully got... | -2 | 2016-09-11T01:52:39Z | 39,432,188 | <p><strong>You really shouldn't be trying to bypass a captcha programmatically!</strong></p>
<p>You could use several threads to make simultaneous requests but at that point the service you're attacking will most likely ban your IP. At the very least, they've probably got throttling on the service; There's a reason it... | 5 | 2016-09-11T01:59:01Z | [
"python",
"python-requests",
"urllib2"
] |
Optimizing Keras to use all available CPU resources | 39,432,170 | <p>Ok, I don't really know what I'm talking about here so bear with me. </p>
<p>I am running Keras with Theano backend to run a basic neural net (just a tutorial set up for now) on MNIST images. In the past, I have been using my old HP laptop because I have a dual boot setup with Windows and Ubuntu 16.06. I am trying ... | 2 | 2016-09-11T01:54:36Z | 39,432,216 | <p>Ok of course I figured it out right after I posted the question. Sorry if I wasted anyone's time. </p>
<p>I just reinstalled everything using apt-get instead of pip and that worked. Not sure why, maybe I missed something the first time. Anyway, </p>
<pre><code>sudo apt-get install python-numpy python-scipy python... | 2 | 2016-09-11T02:06:45Z | [
"python",
"multithreading",
"ubuntu",
"theano",
"keras"
] |
Finding the Dot Product of two different key-value lists within a single dictionary | 39,432,185 | <p>I am using this method to create a dictionary where the keys are Names which are paired with a list of values</p>
<pre><code>def create_voting_dict(strlist):
return {line.split()[0]:[int(x) for x in line.split()[3:]] for line in strlist}
</code></pre>
<p>However, now I have to take the dot product of the value... | 1 | 2016-09-11T01:58:49Z | 39,432,239 | <p>I hope this is what you need. </p>
<pre><code>def create_voting_dict(strlist):
return {line.split()[0]:[int(x) for x in line.split()[3:]] for line in strlist}
def dot(K, L):
if len(K) != len(L):
return 0
return sum(i[0] * i[1] for i in zip(K, L))
def policy_compare(sen_a, sen_b, voting_dict):
... | 0 | 2016-09-11T02:14:35Z | [
"python",
"list",
"dictionary",
"product",
"dot"
] |
Django Twitter clone. How to restrict user from liking a tweet more than once? | 39,432,191 | <p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p>
<p>models.py</p>
<pre><code>class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
published_date =... | 1 | 2016-09-11T01:59:33Z | 39,432,287 | <p>An idea could be adding a column to your table named <code>likers</code> and before incrementing like_counts check if the models.likers contains the new liker or not. If not increment the likes, if yes don't.</p>
| 0 | 2016-09-11T02:25:00Z | [
"python",
"django"
] |
Django Twitter clone. How to restrict user from liking a tweet more than once? | 39,432,191 | <p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p>
<p>models.py</p>
<pre><code>class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
published_date =... | 1 | 2016-09-11T01:59:33Z | 39,432,323 | <p>As well as tracking how many <code>Likes</code> a post has, you'll probably also want to track who has "Liked" each post. You can solve both of these problems by creating a joining table <code>Likes</code> with a unique key on <code>User</code> and <code>Howl</code>.</p>
<p>The unique key will prevent any <code>Us... | 1 | 2016-09-11T02:31:16Z | [
"python",
"django"
] |
Django Twitter clone. How to restrict user from liking a tweet more than once? | 39,432,191 | <p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p>
<p>models.py</p>
<pre><code>class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
published_date =... | 1 | 2016-09-11T01:59:33Z | 39,432,360 | <p>Changed liked_count in my models.py to </p>
<pre><code>liked_by = models.ManyToManyField(User, related_name="likes")
</code></pre>
<p>views.py </p>
<pre><code>class HowlLike(UpdateView):
model = Howl
fields = []
def form_valid(self, form):
instance = form.save(commit=False)
instance.... | 0 | 2016-09-11T02:41:55Z | [
"python",
"django"
] |
Python - How to find UUID of computer and set as variable | 39,432,305 | <p>I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python. </p>
<p>Some of the ways I tried doing didn't work.</p>
<p>Original idea:</p>
<pre><code>import os
x = os.system("wmic diskdrive get serialnumber")
print(x)
</code></pre>
<p>However th... | 0 | 2016-09-11T02:28:11Z | 39,432,381 | <p>You can use <a href="https://docs.python.org/2/library/uuid.html#uuid.uuid1" rel="nofollow"><code>uuid1</code></a> from the standard library <code>uuid</code> module:</p>
<pre><code>import uuid
myuuid = uuid.uuid1()
</code></pre>
<p>This can be used to:</p>
<blockquote>
<p>Generate a UUID from a host ID, seque... | 0 | 2016-09-11T02:46:48Z | [
"python",
"python-3.x",
"hwid"
] |
Python - How to find UUID of computer and set as variable | 39,432,305 | <p>I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python. </p>
<p>Some of the ways I tried doing didn't work.</p>
<p>Original idea:</p>
<pre><code>import os
x = os.system("wmic diskdrive get serialnumber")
print(x)
</code></pre>
<p>However th... | 0 | 2016-09-11T02:28:11Z | 39,432,621 | <p>The os.system function returns the exit code of the executed command, not the standard output of it.</p>
<p>According to <a href="https://docs.python.org/3.4/library/os.html#os.system" rel="nofollow">Python official documentation</a>:</p>
<blockquote>
<p>On Unix, the return value is the exit status of the proces... | 1 | 2016-09-11T03:38:46Z | [
"python",
"python-3.x",
"hwid"
] |
Python - How to find UUID of computer and set as variable | 39,432,305 | <p>I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python. </p>
<p>Some of the ways I tried doing didn't work.</p>
<p>Original idea:</p>
<pre><code>import os
x = os.system("wmic diskdrive get serialnumber")
print(x)
</code></pre>
<p>However th... | 0 | 2016-09-11T02:28:11Z | 39,432,627 | <p>If the aim is to get the serial number of the HDD, then one can do:</p>
<p>In Linux (replace /dev/sda with the block disk identifier for which you want the info):</p>
<pre><code>>>> import os
>>> os.popen("hdparm -I /dev/sda | grep 'Serial Number'").read().split()[-1]
</code></pre>
<p>In Windows... | 2 | 2016-09-11T03:41:29Z | [
"python",
"python-3.x",
"hwid"
] |
How do I calculate cosine similarity from TfidfVectorizer? | 39,432,350 | <p>I have two CSV files - train and test, with 18000 reviews each. I need to use the train file to do feature extraction and calculate the similarity metric between each review in the train file and each review in the test file. </p>
<p>I generated a vocabulary based on words from the train and test set - I eliminated... | 1 | 2016-09-11T02:39:21Z | 39,432,596 | <p>You are almost there. Using <code>vect.fit_transform</code> returns a sparse-representation of a <a href="https://en.wikipedia.org/wiki/Document-term_matrix" rel="nofollow">document-term matrix.</a> It is the document-term matrix representation of your training set. You would then need to transform the testing set w... | 1 | 2016-09-11T03:33:13Z | [
"python",
"numpy",
"scikit-learn",
"sparse-matrix",
"tf-idf"
] |
Installing flask extension: ext = Ext(app) versus Ext(app) | 39,432,374 | <p>I'm learning flask web development by following a tutorial. Currently, the first few lines of my app is:</p>
<pre><code>from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
</code></pre>
<p>However, when I change <code>bootstrap = Bootstr... | -1 | 2016-09-11T02:44:21Z | 39,433,780 | <p>With your current code, it's true there is no need to keep the instance into a variable, </p>
<p>But in practice, you would create the Bootstrap instance without passing the <code>app</code> instance, then on some initialization method, you would call the <code>init_app</code> method of the Bootstrap instance to in... | 1 | 2016-09-11T07:20:52Z | [
"python",
"flask",
"flask-extensions"
] |
Python: sorting sublist values in nested list | 39,432,385 | <p>I have a nested list:
<code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p>
<p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p>
<p><code>for i in list:
newList = sorted[i]</code></p>
<p>So for this example the for loop would lo... | 0 | 2016-09-11T02:48:21Z | 39,432,402 | <p>You are creating a new list and assigning it to a new name, then throwing it away. Use the <code>sort</code> method to sort each list reference to in-place. Also note that it doesn't make sense to use a list reference to index the main list, and that you should avoid naming variables with the same name as built-in f... | 1 | 2016-09-11T02:51:46Z | [
"python",
"python-2.7"
] |
Python: sorting sublist values in nested list | 39,432,385 | <p>I have a nested list:
<code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p>
<p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p>
<p><code>for i in list:
newList = sorted[i]</code></p>
<p>So for this example the for loop would lo... | 0 | 2016-09-11T02:48:21Z | 39,432,404 | <p>You are replacing the value of newList on each iteration in the for loop. Hence, after the for loop ends, the value of newList is equal to the sorted value of the last list in the original nested list. Do this:</p>
<pre><code>>>> list = [[3,2,1],[8,7,9],[5,6,4]]
>>> newlist = map(sorted, list)
>... | 1 | 2016-09-11T02:51:56Z | [
"python",
"python-2.7"
] |
Python: sorting sublist values in nested list | 39,432,385 | <p>I have a nested list:
<code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p>
<p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p>
<p><code>for i in list:
newList = sorted[i]</code></p>
<p>So for this example the for loop would lo... | 0 | 2016-09-11T02:48:21Z | 39,432,476 | <p>The reason your code is not working is because you are creating a new sorted list (<code>sorted()</code> creates a new list) and assigning it to a variable (<code>newList</code>). This variable goes unused.</p>
<p>Python lists have a <code>.sort()</code> method. So your loop code can work as follows</p>
<pre><code... | 0 | 2016-09-11T03:08:02Z | [
"python",
"python-2.7"
] |
issues with python virtual environment | 39,432,392 | <p><br>
I am facing following 2 issues:<br></p>
<ol>
<li>python command is not using the virtualenvwrapper python.<br>
After activating my virtual environment if I type python then the code still uses the native python libraries. I can easily install libraries etc with pip to my virtual environment but I cannot run an... | 0 | 2016-09-11T02:50:17Z | 39,432,512 | <ol>
<li><p>sounds like Python might be using the packages in site-packages, which means you should use the <code>--no-site-packages</code> flag when creating your virtualenv (although it seems like <a href="https://virtualenv.pypa.io/en/stable/reference/#cmdoption--no-site-packages" rel="nofollow">this is the default<... | 0 | 2016-09-11T03:16:54Z | [
"python",
"linux",
"django",
"osx"
] |
issues with python virtual environment | 39,432,392 | <p><br>
I am facing following 2 issues:<br></p>
<ol>
<li>python command is not using the virtualenvwrapper python.<br>
After activating my virtual environment if I type python then the code still uses the native python libraries. I can easily install libraries etc with pip to my virtual environment but I cannot run an... | 0 | 2016-09-11T02:50:17Z | 39,433,252 | <p>You could try install virtualenv and virtualenvwrapper from pip3.</p>
<pre><code>pip3 install virtualenv virtualenvwrapper
</code></pre>
<p>And then find where virtualenvwrapper.sh file is:</p>
<pre><code>find / -name 'virualenvwrapper.sh'
</code></pre>
<p>I have mine in <code>/usr/local/bin/virtualenvwrapper.sh... | 0 | 2016-09-11T05:48:59Z | [
"python",
"linux",
"django",
"osx"
] |
Mutability of lists in python | 39,432,396 | <p>Example one: Changing the value that has been appended to b changes the value in the original list l</p>
<pre><code>>>> l = [1 , 2, 3]
>>> b = []
>>> b.append(l)
>>> b[0].append(4)
>>> b
[[1, 2, 3, 4]]
>>> l
[1, 2, 3, 4]
</code></pre>
<p>Example 2: l1 is append... | 1 | 2016-09-11T02:50:35Z | 39,432,418 | <p>You are not mutating <code>l1</code>. You are assigning a new object to the same name, which makes that name point to a new object. You are moving a label, not modifying an object. The only remaining reference to the list that <code>l1</code> used to point to is now <code>ans[0]</code>.</p>
| 3 | 2016-09-11T02:54:44Z | [
"python",
"list",
"mutable"
] |
Mutability of lists in python | 39,432,396 | <p>Example one: Changing the value that has been appended to b changes the value in the original list l</p>
<pre><code>>>> l = [1 , 2, 3]
>>> b = []
>>> b.append(l)
>>> b[0].append(4)
>>> b
[[1, 2, 3, 4]]
>>> l
[1, 2, 3, 4]
</code></pre>
<p>Example 2: l1 is append... | 1 | 2016-09-11T02:50:35Z | 39,432,426 | <p>Replace </p>
<pre><code>>>> l1 = [2, 3, 4]
</code></pre>
<p>with</p>
<pre><code>>>> l1[:] = [2, 3, 4]
</code></pre>
<p>That will not assign a new list to l1.</p>
| 0 | 2016-09-11T02:56:41Z | [
"python",
"list",
"mutable"
] |
Mutability of lists in python | 39,432,396 | <p>Example one: Changing the value that has been appended to b changes the value in the original list l</p>
<pre><code>>>> l = [1 , 2, 3]
>>> b = []
>>> b.append(l)
>>> b[0].append(4)
>>> b
[[1, 2, 3, 4]]
>>> l
[1, 2, 3, 4]
</code></pre>
<p>Example 2: l1 is append... | 1 | 2016-09-11T02:50:35Z | 39,432,437 | <p>In your first example, <code>l</code> is a pointer, as well as <code>b</code>.</p>
<p><code>l</code> is then appended to b, so <code>b[0]</code> now refers to the pointer.</p>
<p>Next, you append 4 to <code>b[0]</code>, which is the same thing as <code>l</code>, so 4 is added to both <code>b[0]</code> <em>and</em>... | 2 | 2016-09-11T02:59:42Z | [
"python",
"list",
"mutable"
] |
Python tkinter checkbutton value always equal to 0 | 39,432,539 | <p>I put the <code>checkbutton</code> on the <code>text</code> widget, but everytime I select a <code>checkbutton</code>, the function <code>checkbutton_value</code> is called, and it returns 0.</p>
<p>Part of the code is :</p>
<pre><code>def callback():
file_name=askopenfilename()
column_1rowname,column_nam... | -2 | 2016-09-11T03:22:03Z | 39,452,648 | <p>The problem is that you have more than one root window. You should only ever create exactly one instance of <code>Tk</code>, and call <code>mainloop</code> exactly once. If you need additional windows, create instances of <code>Toplevel</code>.</p>
<p>Each root window (and all of its children, and all related <code... | 0 | 2016-09-12T14:24:41Z | [
"python",
"checkbox",
"tkinter"
] |
Why continue doesn't work while raising errors | 39,432,543 | <p>I'm trying to figure out why continue doesn't work when I'm rising errors:</p>
<pre><code>while True:
a = int(raw_input('Type integer with 9 numbers '))
if len(str(a)) < 9 or len(str(a)) >9:
raise NameError('Wrong Number. Try again...')
continue
if not i... | 1 | 2016-09-11T03:22:26Z | 39,432,565 | <p>Try <code>print 'Wrong Number. Try again...'</code> instead of <code>raise</code>.</p>
<p><code>raise</code> will trigger an exception, which basically means your program is interrupted when the instruction is reached, the the exception is propagated up the call stack until it is caught by a <code>try...except</cod... | 3 | 2016-09-11T03:28:02Z | [
"python"
] |
Why continue doesn't work while raising errors | 39,432,543 | <p>I'm trying to figure out why continue doesn't work when I'm rising errors:</p>
<pre><code>while True:
a = int(raw_input('Type integer with 9 numbers '))
if len(str(a)) < 9 or len(str(a)) >9:
raise NameError('Wrong Number. Try again...')
continue
if not i... | 1 | 2016-09-11T03:22:26Z | 39,432,763 | <p><code>raise</code> will trigger an exception and the program will terminate.</p>
<p>I find a few contradictions in your code: </p>
<blockquote>
<p>You are converting the user input to an int class, so <code>if isinstance(a, int)</code> is not at all required because <code>a</code> will point to an int class alre... | 1 | 2016-09-11T04:09:59Z | [
"python"
] |
Error: Unsupported Operand Types | 39,432,551 | <p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &: 'list' and 'list'. Why can't I use the '&a... | 0 | 2016-09-11T03:23:42Z | 39,432,663 | <p>I would probably do something like this:</p>
<pre><code>def dot(L, K):
if L + K == [] or len(L) != len(K): # this only needs to be checked once
return 0
return dot_recurse(L, K)
def dot_recurse(L, K):
if len(L) > 0:
return L[-1] * K[-1] + dot_recurse(L[:-1], K[:-1])
else:
... | 1 | 2016-09-11T03:48:16Z | [
"python",
"math"
] |
Error: Unsupported Operand Types | 39,432,551 | <p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &: 'list' and 'list'. Why can't I use the '&a... | 0 | 2016-09-11T03:23:42Z | 39,432,671 | <pre><code>def dot(L, K):
if len(L)!=len(K): # return 0 before the first recursion
return 0
elif not L: # test if L is [] - previous test implies K is [] so no need to retest
return 0
else:
return L[-1] * K[-1] + dot(L[:-1], K[:-1])
</code></pre>
| 0 | 2016-09-11T03:48:59Z | [
"python",
"math"
] |
Error: Unsupported Operand Types | 39,432,551 | <p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &: 'list' and 'list'. Why can't I use the '&a... | 0 | 2016-09-11T03:23:42Z | 39,432,675 | <p>If you check out python's <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">Operator Precedence</a> you will see that <code>&</code> has lower precedence than <code>==</code> and <code>and</code></p>
<p>This means you are doing the following:</p>
<pre class="lang... | 0 | 2016-09-11T03:49:44Z | [
"python",
"math"
] |
Error: Unsupported Operand Types | 39,432,551 | <p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &: 'list' and 'list'. Why can't I use the '&a... | 0 | 2016-09-11T03:23:42Z | 39,432,708 | <p>Your code is a bit more complicated than it really needs to be. It is not possible to take the dot product of two vectors which are not the same size. There are a couple of ways to deal with receiving vectors of different sizes.</p>
<p>1) Lop off the remaining unused numbers from the larger vector. Below is a modif... | 0 | 2016-09-11T03:57:49Z | [
"python",
"math"
] |
How to enter data in the form and go to the next page with cookie in python | 39,432,648 | <p>I would like to enter data in a form and login in the website, and then download the source of the current page.
With curl from the terminal I do the following commands:</p>
<pre><code>curl -c cookie.txt --data "[email protected]&pass=MyPass&submit=login" https://mywebsite.com/pageA
curl -b cookie.txt htt... | 0 | 2016-09-11T03:45:37Z | 39,437,904 | <p>Building up from the example in <a href="http://pycurl.io/docs/latest/quickstart.html#sending-form-data" rel="nofollow">docs</a>:</p>
<pre><code>from __future__ import print_function
import pycurl
try:
# python 3
from urllib.parse import urlencode
except ImportError:
# python 2
from urllib import ur... | 0 | 2016-09-11T15:51:08Z | [
"python",
"curl",
"cookies",
"pycurl"
] |
python os.walk returns nothing | 39,432,660 | <p>I have a problem with using <code>os.walk</code> on Mac. If I call it from <code>python terminal</code>, it works perfect, but if I call it via a <code>python script</code>, it returns empty list. For example:</p>
<pre><code> import os
path = "/Users/temp/Desktop/test/"
for _ ,_ , files in os.walk(path)... | 0 | 2016-09-11T03:47:42Z | 39,432,689 | <p>You most likely need to intantiate the test list outside the for loop, for this to work.</p>
<pre><code>import os
path = "/Users/temp/Desktop/test/"
test = []
for _ ,_ , files in os.walk(path):
test.extend([my_file for my_file in files])
print test
</code></pre>
| 1 | 2016-09-11T03:54:11Z | [
"python"
] |
Remove portion of plot that lies outside of circle | 39,432,735 | <p>I have written a python script that produces vector field plots of the electric and magnetic field vectors for EM waves in various modes of propagation in a cylindrical waveguide. I have used <code>streamplot</code> to produce the vector field plots. This question would be asked much more easily if I were able to po... | 0 | 2016-09-11T04:04:32Z | 39,432,752 | <p>You can use a clip path. Matplotib's documentation has a nice example: <a href="http://matplotlib.org/examples/images_contours_and_fields/image_demo_clip_path.html" rel="nofollow">http://matplotlib.org/examples/images_contours_and_fields/image_demo_clip_path.html</a></p>
| 0 | 2016-09-11T04:07:27Z | [
"python",
"matplotlib"
] |
String replace with re sub matching the exact string | 39,432,754 | <p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p>
<p>My code :</p>
<pre><code>input_file = "foo afooa"
input_file = re.sub(r'^foo$', 'bar', input_file)
print... | 0 | 2016-09-11T04:07:36Z | 39,432,825 | <p>Instead of ^ and $ , use \b to match boundary.</p>
<pre><code>>>> a="foo afooa"
>>> b= re.sub(r"\bfoo\b",'bar',a)
>>> b
'bar afooa'
>>>
</code></pre>
| 0 | 2016-09-11T04:20:58Z | [
"python",
"regex"
] |
String replace with re sub matching the exact string | 39,432,754 | <p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p>
<p>My code :</p>
<pre><code>input_file = "foo afooa"
input_file = re.sub(r'^foo$', 'bar', input_file)
print... | 0 | 2016-09-11T04:07:36Z | 39,432,835 | <p>From the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">doc</a>, you can set <code>count = 1</code> of <code>re.sub()</code>to just change the first occurrence of the pattern. Also, remove the <code>^</code> and <code>$</code> since you donot want to search for the whole line containing only the ... | 1 | 2016-09-11T04:24:10Z | [
"python",
"regex"
] |
String replace with re sub matching the exact string | 39,432,754 | <p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p>
<p>My code :</p>
<pre><code>input_file = "foo afooa"
input_file = re.sub(r'^foo$', 'bar', input_file)
print... | 0 | 2016-09-11T04:07:36Z | 39,433,082 | <p>Your regex is currently <code>r'^foo$'</code> which basically matches the string 'foo' <strong><em>only</em></strong>.</p>
<p>If you just changed it to <code>r'^foo'</code> it will match as long as 'foo' is found at the start of the string, but unlike your previous pattern it doesn't care about what follows foo.</p... | 1 | 2016-09-11T05:11:07Z | [
"python",
"regex"
] |
Python list insertion when iterating | 39,432,758 | <p>I'm working with python 3.5, and insert isn't behaving as I expect it to.</p>
<pre><code>scorelist = ["x","x"]
for q in range(0, len(scorelist)):
if scorelist[q] == "x":
scorelist.insert((q), " ")
</code></pre>
<p>I'd expect that to leave the least reading as follows</p>
<pre><code>scorelist = ["x", ... | 1 | 2016-09-11T04:08:52Z | 39,432,796 | <p>It's generally a Bad Idea to mutate any container while iterating over it.</p>
<p>In your case, <code>len(scorelist)</code> is evaluated once, at the time the <code>for</code> loop begins. The length is 2 at that time, so the range is just <code>[0, 1]</code>. Nothing later can possibly change that.</p>
<p>In th... | 6 | 2016-09-11T04:15:56Z | [
"python"
] |
working with "load more" button using scrapy | 39,432,791 | <p>I was working on ratemyprofessor which has a load more button to load more professor, and I use debugger to analyze network, it shows up a js request.
<a href="https://www.ratemyprofessors.com/campusRatings.jsp?sid=1273" rel="nofollow">ratemyprofessorwebsite</a></p>
<p>I was thinking, for the request URL, there is... | 0 | 2016-09-11T04:14:39Z | 39,436,426 | <p>Yes, you are correct - formdata is not required, and this is straight forward using GET method calls.</p>
<p>using the following parameters, grab the json response with:</p>
<pre><code>data = json.loads(response.body)
records = data['response']['docs']
</code></pre>
<hr>
<p>parameters to use : <strong>start, ro... | 0 | 2016-09-11T13:07:06Z | [
"python",
"scrapy"
] |
How to change the order of tables in a LEFT JOIN clause with SQLAlchemy | 39,432,853 | <p>I wish to execute the following SQL:</p>
<pre><code>SELECT c.name, count(1)
FROM post p LEFT JOIN category_post cp ON (p.id = cp.post_id)
LEFT JOIN category c ON (cp.category_id = c.id)
WHERE 1=1
AND post.is_published = 1
GROUP BY c.name;
</code></pre>
<p>A post has 0 or more categories. This post will r... | 0 | 2016-09-11T04:27:24Z | 39,433,307 | <p>Use <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.select_from" rel="nofollow"><code>select_from()</code></a>:</p>
<pre><code>session.query(Category.name, func.count(1)) \
.select_from(Post) \
.outerjoin(CategoryPost) \
.outerjoin(Category) \
...
... | 1 | 2016-09-11T06:01:03Z | [
"python",
"sqlalchemy"
] |
"list index out of range" exception (Python3) | 39,432,878 | <p>I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the <code>if</code> or <code>elif</code> part of the second <code>if</code> statement, depending on what the user inputs. I know that when the user input is split the list is created correctly becau... | 1 | 2016-09-11T04:33:42Z | 39,432,957 | <h2>Real issue:</h2>
<p>To solve your error you have to <strong>remove</strong> the <code>self</code> parameter of the <code>first</code> function </p>
<pre><code>def first(a=list())
</code></pre>
<p>Basically the <strong>self</strong> is only used for object orientation creating methods.
Function like yours can't... | 0 | 2016-09-11T04:48:39Z | [
"python",
"list"
] |
"list index out of range" exception (Python3) | 39,432,878 | <p>I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the <code>if</code> or <code>elif</code> part of the second <code>if</code> statement, depending on what the user inputs. I know that when the user input is split the list is created correctly becau... | 1 | 2016-09-11T04:33:42Z | 39,433,163 | <p>The problem seems to be the definition of <code>first()</code>. You invoke it as a function:</p>
<pre><code>if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)
</code></pre>
<p>But you define it as a method:</p>
<pre><code>def first(self, a = list()):
</code></pre>
<p>The array of command an... | 2 | 2016-09-11T05:28:11Z | [
"python",
"list"
] |
Matplotlib: make figure that has x and y labels square in aspect ratio | 39,432,931 | <p>The question is bettered explained with examples. Let's say below is a figure I tried to plot:
<a href="http://i.stack.imgur.com/15sdi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/15sdi.jpg" alt="in matlab"></a></p>
<p>So the figure region is square in shape, and there are axis labels explaining the meani... | 0 | 2016-09-11T04:43:27Z | 39,433,143 | <p>It doesn't explain the figures you obtain but here is one way to achieve square axes with the right axes limits. In this example, I just calculate the axes aspect ratio using the x and y range:</p>
<pre><code>plt.figure()
ax = plt.axes()
ax.plot(t, y)
xrange = (0, 2*pi)
yrange = (-1.1, 1.1)
plt.xlim(xrange)
plt.yli... | 0 | 2016-09-11T05:23:15Z | [
"python",
"matlab",
"matplotlib"
] |
Matplotlib: make figure that has x and y labels square in aspect ratio | 39,432,931 | <p>The question is bettered explained with examples. Let's say below is a figure I tried to plot:
<a href="http://i.stack.imgur.com/15sdi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/15sdi.jpg" alt="in matlab"></a></p>
<p>So the figure region is square in shape, and there are axis labels explaining the meani... | 0 | 2016-09-11T04:43:27Z | 39,433,186 | <p>I do not have a computer at hand right now but it seems this answer might work: <a href="http://stackoverflow.com/a/7968690/2768172">http://stackoverflow.com/a/7968690/2768172</a> Another solution might be to add the axis with a fixed size manually with: <code>ax=fig.add_axes(bottom, left, width, height)</code>. If ... | 0 | 2016-09-11T05:33:28Z | [
"python",
"matlab",
"matplotlib"
] |
(Errno 22) invalid argument when trying to run a python program from a bat file | 39,432,939 | <p>I'm following this exactly but it is not working <a href="https://youtu.be/qHcHUHF_Qfo?t=438" rel="nofollow">https://youtu.be/qHcHUHF_Qfo?t=438</a> </p>
<p>I type the location in the run window:</p>
<pre><code>C:\Users\Zachary lastName\mypythonscripts\hello.py
</code></pre>
<p>I get error message: </p>
<blockquo... | 0 | 2016-09-11T04:45:02Z | 39,432,958 | <p>You have to enclose the path name in quotes because the space means a new argument is expected, and it's not finding the file:</p>
<pre><code>@py "C:\Users\Zachary lastName\mypythonscripts\hello.py" %*
@pause
</code></pre>
<p>Now the file path should not interfere. Usernames with spaces can become a problem for pa... | 0 | 2016-09-11T04:48:45Z | [
"python",
"batch-file",
"errno"
] |
Adding "Invalid Entry" To Python Dice Roller | 39,432,951 | <p>I have a Python dice rolling simulator:</p>
<pre><code>from random import randint
play = True
while play:
roll = randint(1, 6)
print(roll)
answer = input("Roll again? (y/n)")
print(answer)
if answer == "y":
play = True
elif answer == "n":
break
</code></pre>
<p>If you inpu... | 0 | 2016-09-11T04:47:28Z | 39,433,030 | <p>You can validate the answer and ask again if it is invalid like</p>
<pre><code>from random import randint
play = True
while play:
roll = randint(1, 6)
print(roll)
ask = True
while ask:
answer = input("Roll again? (y/n)")
print(answer)
if (answer != "y") and (answer != "n"):... | 0 | 2016-09-11T05:01:10Z | [
"python",
"python-3.5"
] |
How do I preform a check only once? | 39,432,952 | <p>So I have this question that I have to do for homework.</p>
<p>Next, write ind( e, L ). Here is its description:</p>
<p>Write ind(e, L), which takes in a sequence L and an element e. L might be a string or, more generally, a list. Your function ind should return the index at which e is first found in L. Counting b... | 0 | 2016-09-11T04:47:43Z | 39,434,686 | <blockquote>
<p>And here it(!) once(!) of the many codes I have written for this problem.</p>
</blockquote>
<p>You should pay more attention to what you're writing and probably also to what you are coding.</p>
<p>Unless you are explicitly asked to write a recursive function for this task, I'd advise against it.</p>... | 0 | 2016-09-11T09:28:35Z | [
"python",
"python-2.7"
] |
How do I preform a check only once? | 39,432,952 | <p>So I have this question that I have to do for homework.</p>
<p>Next, write ind( e, L ). Here is its description:</p>
<p>Write ind(e, L), which takes in a sequence L and an element e. L might be a string or, more generally, a list. Your function ind should return the index at which e is first found in L. Counting b... | 0 | 2016-09-11T04:47:43Z | 39,434,893 | <p>When working with indicies in sequence, Python has great built-in named <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> which helps a lot with keeping track of index in consise and simple manner.</p>
<blockquote>
<p>Return an enumerate object. <code>s... | 1 | 2016-09-11T09:55:49Z | [
"python",
"python-2.7"
] |
Python: Inserting DataFrames into larger DataFrame at given index value | 39,432,964 | <p>I'm certain this is a trivial question but I cannot seem to find a solution. I have the following DataFrame: </p>
<pre><code>>>> df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [1, 2, 3, 4, 5],
'C': [1, 2, 3, 4, 5]})
>>> df
A B C
0 1 1 1
1 2 2 2
2 ... | 1 | 2016-09-11T04:49:10Z | 39,433,385 | <p>At least what you want can be achieved by slicing and concatenating:</p>
<pre><code>from collections import OrderedDict
idx_dict = OrderedDict(sorted(idx_dict.items()))
dfs = []
start_idx = 0
for idx in idx_dict:
dfs.append(df.iloc[start_idx:idx + 1])
dfs.append(idx_dict[idx])
start_idx = idx + 1
dfs.ap... | 3 | 2016-09-11T06:14:54Z | [
"python",
"pandas",
"dictionary",
"dataframe",
"insert"
] |
TypeError: expected a character buffer object (while writing dictionary keys to text file) | 39,432,965 | <p>Below code doesn't work:</p>
<pre><code>with open("testfile.txt",'w') as fw:
for key in a:
fw.write(a[key])
</code></pre>
<p>Below is the error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: expected a character buffer object`
</code></p... | 1 | 2016-09-11T04:49:11Z | 39,433,402 | <p>As the error message says: you can write only a character buffer object to a file. For example a <code>string</code>. However the entries in your dictionary are <code>int</code>s - which aren't character buffer objects. So you have first to convert the values to a string and than write it to a file, for example this... | 0 | 2016-09-11T06:18:46Z | [
"python",
"python-2.7",
"file",
"dictionary"
] |
how to use the split in Python | 39,432,991 | <pre><code>import xlrd
import urllib.request
workbook = xlrd.open_workbook('test.xlsx');
sheet = workbook.sheet_by_index(0);
num_rows = sheet.nrows -1;
print(num_rows);
print('\n');
inputI=str(300);
inputP=str(15);
inputF='d';
content=sheet.cell_value(0,0);
address='http://www.google.com/finance/getprices? q='+content... | 0 | 2016-09-11T04:54:00Z | 39,433,091 | <p>Response.readlines() provides a list of lines. So it means that you are trying to split the list, which is not possible.</p>
<p>Instead try to take each line and then perform any processing you want to.</p>
| 0 | 2016-09-11T05:12:54Z | [
"python",
"excel"
] |
how to use the split in Python | 39,432,991 | <pre><code>import xlrd
import urllib.request
workbook = xlrd.open_workbook('test.xlsx');
sheet = workbook.sheet_by_index(0);
num_rows = sheet.nrows -1;
print(num_rows);
print('\n');
inputI=str(300);
inputP=str(15);
inputF='d';
content=sheet.cell_value(0,0);
address='http://www.google.com/finance/getprices? q='+content... | 0 | 2016-09-11T04:54:00Z | 39,433,220 | <blockquote>
<p>The method readlines() reads until EOF using readline() and returns a list containing the lines.</p>
</blockquote>
<p>You can do something like:</p>
<pre><code>data = response.readlines()
for line in data:
# I guess you will get byte here, so you have to convert them to utf-8
print(line.deco... | 0 | 2016-09-11T05:42:23Z | [
"python",
"excel"
] |
Why are non integral builtin types allowed in python slices? | 39,433,018 | <p>I've just improving test coverage for a <a href="https://github.com/JaggedVerge/mmap_backed_array" rel="nofollow">library</a> that has to support slices and I've noticed that slices can contain non-integral types:</p>
<pre><code>>>> slice(1, "2", 3.0)
slice(1, '2', 3.0)
>>> sl = slice(1, "2", 3.0)... | 6 | 2016-09-11T04:59:21Z | 39,437,208 | <blockquote>
<p>Would I be right in assuming that arbitrary types are allowed in order to support duck typing for types that implement <code>__index__</code>?</p>
</blockquote>
<p>There's no actual reason as to why you should restrict the types passed when initializing <code>slice</code> objects. Exactly as stated i... | 2 | 2016-09-11T14:41:03Z | [
"python",
"python-3.x",
"slice",
"python-internals"
] |
Why are non integral builtin types allowed in python slices? | 39,433,018 | <p>I've just improving test coverage for a <a href="https://github.com/JaggedVerge/mmap_backed_array" rel="nofollow">library</a> that has to support slices and I've noticed that slices can contain non-integral types:</p>
<pre><code>>>> slice(1, "2", 3.0)
slice(1, '2', 3.0)
>>> sl = slice(1, "2", 3.0)... | 6 | 2016-09-11T04:59:21Z | 39,438,963 | <p>Third-party libraries may want to implement slicing for their own objects, and there's no reason for the core language to restrict those third-party libraries to only using integers or integer-like objects (i.e., objects whose type provides the <code>__index__</code> method) in their slices. Here are two notable exa... | 3 | 2016-09-11T17:48:57Z | [
"python",
"python-3.x",
"slice",
"python-internals"
] |
Pythonic way to access the shifted version of numpy array? | 39,433,019 | <p>What is a pythonic way to access the shifted, either right or left, of a <code>numpy</code> array? A clear example:</p>
<pre><code>a = np.array([1.0, 2.0, 3.0, 4.0])
</code></pre>
<p>Is there away to access:</p>
<pre><code>a_shifted_1_left = np.array([2.0, 3.0, 4.0, 1.0])
</code></pre>
<p>from the <code>numpy</c... | 4 | 2016-09-11T04:59:23Z | 39,433,047 | <p>You are looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html" rel="nofollow"><code>np.roll</code></a> -</p>
<pre><code>np.roll(a,-1) # shifted left
np.roll(a,1) # shifted right
</code></pre>
<p>Sample run -</p>
<pre><code>In [28]: a
Out[28]: array([ 1., 2., 3., 4.])
In [29]... | 4 | 2016-09-11T05:04:01Z | [
"python",
"arrays",
"numpy"
] |
Find when integral of an interpolated function is equal to a specific value (python) | 39,433,108 | <p>I have arrays <code>t_array</code> and <code>dMdt_array</code> of x and y points. Let's call <code>M = trapz(dMdt_array, t_array)</code>. I want to find at what value of t the integral of dM/dt vs t is equal to a certain value -- say <code>0.05*M</code>. In python, is there a nice way to do this?</p>
<p>I was think... | 0 | 2016-09-11T05:16:36Z | 39,433,909 | <p>One simple way is to use the CubicSpline class instead. Then it's <code>CubicSpline(x, y).antiderivative().solve(0.05*M)</code> or thereabouts.</p>
| 1 | 2016-09-11T07:41:29Z | [
"python",
"scipy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.