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 |
|---|---|---|---|---|---|---|---|---|---|
Assigning same session ID for returning users with Python Flask app | 39,925,702 | <p>I have a simple Flask webapp that does not require users to log in. However, I would like to assign an identifier to a user so that same users can be identified without user's log-in id. Is there a way to achieve this? </p>
| -1 | 2016-10-07T20:58:00Z | 39,926,465 | <p>You can put information in the session and recover it in server-side using flask session:</p>
<pre><code>from flask import Flask, session, redirect, url_for, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
session['cookie-paramete... | 1 | 2016-10-07T22:08:27Z | [
"python",
"flask"
] |
Error Installing PySCIPOpt on Mac OSX | 39,925,751 | <p>After installing SCIP Optimization Suite on OS X by compiling the source and installing Cython, </p>
<pre><code>make
make install INSTALLDIR="/usr/local/"
make SHARED=true GMP=false READLINE=false scipoptlib
pip install Cython
</code></pre>
<p>the installation of <code>PySCIPOpt</code> was attempted</p>
<pre><cod... | 0 | 2016-10-07T21:01:21Z | 39,925,979 | <p>When you set the SCIPOPTDIR environment variable, it looks for directories of the form ${SCIPOPTDIR}/scip-*/src.</p>
<p>You get that error because you do not have any directories that match that form in a freshly cloned checkout of PySCIPopt.git. You need to set that environment variable to the directory where you ... | 0 | 2016-10-07T21:21:20Z | [
"python",
"osx",
"python-2.7",
"scip",
"pyscipopt"
] |
Error Installing PySCIPOpt on Mac OSX | 39,925,751 | <p>After installing SCIP Optimization Suite on OS X by compiling the source and installing Cython, </p>
<pre><code>make
make install INSTALLDIR="/usr/local/"
make SHARED=true GMP=false READLINE=false scipoptlib
pip install Cython
</code></pre>
<p>the installation of <code>PySCIPOpt</code> was attempted</p>
<pre><cod... | 0 | 2016-10-07T21:01:21Z | 39,925,987 | <p>You need to have SCIP installed first. The shared library of the SCIP Optimization Suite to be precise. The environment variable SCIPOPTDIR must then be set to its root directory - not the directory of the Python interface. Please follow the instructions in the INSTALL file carefully: <a href="https://github.com/SCI... | 0 | 2016-10-07T21:21:57Z | [
"python",
"osx",
"python-2.7",
"scip",
"pyscipopt"
] |
Flask-peewee to Flask-sqlalchmey - Operand should contain 1 column(s) | 39,925,767 | <p>I am having an issue with this error Operand should contain 1 column(s), I get that is about their being two fields in the subquery but from my code and using flask-sqlalchemy I can't work out what is going wrong. I am converting my application from flask-peewee to flask-sqlalchemy and it is this one issue that I ca... | 0 | 2016-10-07T21:03:28Z | 39,925,998 | <blockquote>
<p>OperationalError: (_mysql_exceptions.OperationalError) (1241, 'Operand
should contain 1 column(s)')</p>
</blockquote>
<p>tells you that you're trying to compare a list of columns to one user id column.</p>
<pre><code>return UserBeer.query.filter(or_( UserBeer.id < self.following(), UserBeer.use... | 1 | 2016-10-07T21:23:28Z | [
"python",
"mysql",
"flask-sqlalchemy",
"flask-peewee"
] |
Flask-peewee to Flask-sqlalchmey - Operand should contain 1 column(s) | 39,925,767 | <p>I am having an issue with this error Operand should contain 1 column(s), I get that is about their being two fields in the subquery but from my code and using flask-sqlalchemy I can't work out what is going wrong. I am converting my application from flask-peewee to flask-sqlalchemy and it is this one issue that I ca... | 0 | 2016-10-07T21:03:28Z | 39,965,552 | <p>Switching from Peewee to SQLAlchemy? Why on earth would you do such a thing!</p>
<p>Honestly, if you've run into what you believe is a bug in Peewee, or find things overly difficult or un-intuitive, that is exactly the most useful kind of feedback for me as the maintainer. Sure, it's nice hearing from people who sa... | 0 | 2016-10-10T19:39:10Z | [
"python",
"mysql",
"flask-sqlalchemy",
"flask-peewee"
] |
False iteration over list | 39,925,817 | <p>I have a function that's suppose to minimize the quantity of a letter in a list if a given word contains that letter. That's the def of the function:</p>
<pre><code>word = 'better'
hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3}
def updateHand(hand, word):
handCopy = hand.copy()
for x in word:
pri... | 0 | 2016-10-07T21:07:45Z | 39,926,144 | <p>Let's consider this situation:</p>
<pre><code>hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3}
</code></pre>
<p>so we have hand as a dict. Now we do this one:</p>
<pre><code>x = hand.get('t',0) - 1
print x
</code></pre>
<p>result will be 1. Let's do it again:</p>
<pre><code>x = hand.get('t',0) - 1
print x
</co... | 0 | 2016-10-07T21:36:22Z | [
"python",
"list",
"dictionary",
"iteration"
] |
Kivy - hard to select Widgets | 39,925,847 | <p>I have written a simple application and deployed it on Sony Xperia Z and Galaxy Prime devices. On both it's really very hard (I've got to click many times before it reacts) to:</p>
<ul>
<li>put focus on a TextInput</li>
<li>select a ToggleButton</li>
<li>click a Button</li>
<li>etc.</li>
</ul>
<p>The same time a S... | 0 | 2016-10-07T21:09:51Z | 39,929,515 | <p>You should update to kivy 1.9.2-dev, the problem is fixed there. In <code>buildozer.spec</code> file, write requirement <code>kivy==master</code>.</p>
| 3 | 2016-10-08T06:41:41Z | [
"android",
"python",
"kivy"
] |
How to use distancematrix function from Biopython? | 39,925,865 | <p>I would like to calculate the distance matrix (using genetic distance function) on a data set using <a href="http://biopython.org/DIST/docs/api/Bio.Cluster.Record-class.html#distancematrix" rel="nofollow">http://biopython.org/DIST/docs/api/Bio.Cluster.Record-class.html#distancematrix</a>, but I seem to keep getting ... | 1 | 2016-10-07T21:11:15Z | 39,932,031 | <p>The short answer: You don't.</p>
<p>From the <a href="http://biopython.org/DIST/docs/api/Bio.Cluster.Record-class.html" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>A Record stores the gene expression data and related information</p>
</blockquote>
<p>The <code>Cluster</code> object is used for gene exp... | 0 | 2016-10-08T11:55:04Z | [
"python",
"biopython"
] |
Pandas bar graph using original dataframe | 39,925,873 | <p>I have a pandas dataframe and I'm attempting to plot the number of subscription types purchased by gender the original dataframe resemblems</p>
<pre><code>df =
Memb_ID Gender 1_Month 3_Month 6_Month 1_Year
1 Male 6 0 3 0
2 Male 0 0 0 ... | 1 | 2016-10-07T21:12:04Z | 39,926,013 | <p>You can use <code>groupby().sum()</code> to replace the <code>temp_df</code>:</p>
<pre><code>ax = df.groupby('Gender')['1_Year','1_Month','3_Month','6_Month'].sum().plot.bar(grid=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/2hzw9.png" rel="nofollow"><img src="http://i.stack.imgur.com/2hzw9.png" alt="en... | 4 | 2016-10-07T21:24:36Z | [
"python",
"pandas",
"plot"
] |
How to avoid to manually set the initial value of a variable in a recursive function? | 39,925,931 | <p>I found this solution for the Euler project 5 (What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?) with a variable range of integer values to divide evenly by: </p>
<pre><code>def Euler5(start, end, counter):
x = counter
while start <= end:
if x%coun... | 4 | 2016-10-07T21:17:08Z | 39,926,039 | <p>If I understood you right, you want that <code>counter == start</code> for the initial call without specifying the <code>counter</code> manually in the first call.</p>
<p>For this, you can set <code>counter</code> to a default value of <code>None</code> and check for this at the beginning of the function, setting <... | 3 | 2016-10-07T21:26:43Z | [
"python"
] |
Login system with infinite loop error | 39,925,960 | <p>I'm coding myself a "simple" login system everything works ok up until the <code>LOGIN</code> part.</p>
<p>The <code>while</code> loop at the end only happens once even though I put another user rather than what I created when I ran the program. I got it to work at some point, but then there was another issue where... | 0 | 2016-10-07T21:19:55Z | 39,967,978 | <p>Try this:</p>
<pre><code>def login():
username = input("Username: ")
if username not in users:
print("User unregistered! Please register!")
register()
return
password = input("Password: ")
if users[username] != password
print("Password invalid")
</code></pre>
<p>I... | 1 | 2016-10-10T22:56:42Z | [
"python"
] |
Login system with infinite loop error | 39,925,960 | <p>I'm coding myself a "simple" login system everything works ok up until the <code>LOGIN</code> part.</p>
<p>The <code>while</code> loop at the end only happens once even though I put another user rather than what I created when I ran the program. I got it to work at some point, but then there was another issue where... | 0 | 2016-10-07T21:19:55Z | 39,967,987 | <p>First, <code>"^[a-z]*$"</code> tests for no lowercase letters, it does not mean "no blank spaces", so I have corrected that for you with <code>"\\s+"</code></p>
<p>You really need to learn about methods and break your problem down. </p>
<p>1) Ask for the username</p>
<pre><code>def get_username():
while True:... | 1 | 2016-10-10T22:57:33Z | [
"python"
] |
function using dictionary as argument | 39,925,976 | <p>I have created a dictionary with values for Velocity, temperature and altitude:</p>
<pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[])
</code></pre>
<p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p>
<pre><code>mach_dict = {'velocity': [0, 300, 495, 500... | 0 | 2016-10-07T21:21:02Z | 39,926,078 | <p>You can <code>zip</code> the list values in the dictionary and compute the new key <code>mach_number</code> using a <em>list comprehension</em>:</p>
<pre><code>import math
def compute_mach(velocity, altitude, temperature):
return velocity/math.sqrt(1.4*286*(temperature-altitude*0.05))
mach_dict['mach_number']... | 0 | 2016-10-07T21:30:16Z | [
"python",
"function",
"dictionary",
"arguments"
] |
function using dictionary as argument | 39,925,976 | <p>I have created a dictionary with values for Velocity, temperature and altitude:</p>
<pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[])
</code></pre>
<p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p>
<pre><code>mach_dict = {'velocity': [0, 300, 495, 500... | 0 | 2016-10-07T21:21:02Z | 39,926,088 | <p>You'd zip together the 3 lists to produce <code>velocity, altitude, temperature</code> tuples:</p>
<pre><code>mach_dict['mach'] = mach_per_section = []
for vel, alt, temp in zip(
mach_dict['velocity'], mach_dict['altitude'], mach_dict['temperature']):
mach = vel / sqrt(1.4 * 286 * (temp - alt * 0.05))
... | 0 | 2016-10-07T21:31:02Z | [
"python",
"function",
"dictionary",
"arguments"
] |
function using dictionary as argument | 39,925,976 | <p>I have created a dictionary with values for Velocity, temperature and altitude:</p>
<pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[])
</code></pre>
<p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p>
<pre><code>mach_dict = {'velocity': [0, 300, 495, 500... | 0 | 2016-10-07T21:21:02Z | 39,926,108 | <p>Technically, this is modifying the passed in dictionary, and the <code>return</code> is unnecessary. </p>
<pre><code>from math import sqrt
def func(d):
machs = []
for v, a, t in zip(d['velocity', d['altitude'], d['temperature']):
mach = v / sqrt(1.4 * 286 * (t - a * 0.05))
machs.append(mac... | 0 | 2016-10-07T21:32:25Z | [
"python",
"function",
"dictionary",
"arguments"
] |
function using dictionary as argument | 39,925,976 | <p>I have created a dictionary with values for Velocity, temperature and altitude:</p>
<pre><code>mach_dict = dict(velocity=[], altitude=[], temperature=[])
</code></pre>
<p>Which I use to store values for a flying plain at climb, cruise and descent segments.</p>
<pre><code>mach_dict = {'velocity': [0, 300, 495, 500... | 0 | 2016-10-07T21:21:02Z | 39,926,129 | <p>And you can use pandas and numpy to do that as well</p>
<pre><code>import pandas as pd
import numpy as np
def compute(mach_dict):
df = pd.DataFrame.from_dict(mach_dict)
r = df.velocity / np.sqrt(1.4 * 286 * (df.temperature - df.altitude * 0.05))
return list(r)
mach_dict={'velocity':[0, 300, 495, 500, 3... | 0 | 2016-10-07T21:34:24Z | [
"python",
"function",
"dictionary",
"arguments"
] |
define variables in the txt file using python script | 39,926,118 | <p>i have one .txt file and i want to create python script with <code>sys.argv</code> or <code>argparse</code> or other package to define some variables in the txt file and i take some result.</p>
<p>i want to update the variables in the text file based on arguments passed to the python script</p>
<p>txt file maybe l... | 0 | 2016-10-07T21:33:11Z | 39,926,522 | <p>There's almost certainly a better way to do this but it sounded like an interesting problem so I decided to give it a try. I defined a text file with variable names listed as such:</p>
<p><strong>newfile.txt:</strong></p>
<pre><code>x = 1
y = 2
z = 3
</code></pre>
<p>By reading one line at a type and conforming t... | 0 | 2016-10-07T22:14:22Z | [
"python",
"python-2.7",
"parameter-passing",
"argparse",
"sys"
] |
define variables in the txt file using python script | 39,926,118 | <p>i have one .txt file and i want to create python script with <code>sys.argv</code> or <code>argparse</code> or other package to define some variables in the txt file and i take some result.</p>
<p>i want to update the variables in the text file based on arguments passed to the python script</p>
<p>txt file maybe l... | 0 | 2016-10-07T21:33:11Z | 39,926,621 | <p>This is a different way using <code>regex</code> and a dictionary, and taking input using <code>sys.argv</code>:</p>
<pre><code>import sys,re
v1 = sys.argv[1]
v2 = sys.argv[2]
with open('file.txt','r') as f:
content = f.read()
repl = {'var1':v1, 'var2':v2}
repl_pattern = re.compile(r'(' + '|'.join(repl.keys(... | 1 | 2016-10-07T22:27:21Z | [
"python",
"python-2.7",
"parameter-passing",
"argparse",
"sys"
] |
Access Functions via Dictionary | 39,926,137 | <p>I have a function like this:</p>
<pre><code>def abc(a,b):
return a+b
</code></pre>
<p>And I want to assign it to a dictionary like this:</p>
<pre><code>functions = {'abc': abc(a,b)}
</code></pre>
<p>The trouble is, when assigning it to the dictionary, since the arguments are not yet defined, I get the error:... | 2 | 2016-10-07T21:35:08Z | 39,926,170 | <blockquote>
<p>I need to define them in a loop (and then call the function based on locating it in a list)</p>
</blockquote>
<p>Then what's the issue with simply saving the function object in the dictionary:</p>
<pre><code>functions = {'abc':abc}
</code></pre>
<p>and <em>then</em> applying <code>a</code> and <cod... | 3 | 2016-10-07T21:38:31Z | [
"python",
"list",
"function",
"python-3.x",
"dictionary"
] |
Access Functions via Dictionary | 39,926,137 | <p>I have a function like this:</p>
<pre><code>def abc(a,b):
return a+b
</code></pre>
<p>And I want to assign it to a dictionary like this:</p>
<pre><code>functions = {'abc': abc(a,b)}
</code></pre>
<p>The trouble is, when assigning it to the dictionary, since the arguments are not yet defined, I get the error:... | 2 | 2016-10-07T21:35:08Z | 39,926,177 | <p>You assign a reference to the function <strong>without</strong> any arguments, and then supply them when calling it:</p>
<pre><code>functions = {'abc':abc} # Assignment: no arguments!
functions_to_call = ['abc']
for f in functions_to_call:
a=3
b=4
if f in functions:
functions[f](a, b) # call... | 3 | 2016-10-07T21:38:52Z | [
"python",
"list",
"function",
"python-3.x",
"dictionary"
] |
Python 3: Getting two user inputs from a single line in a text file | 39,926,210 | <p>I am working on a program that asks the user to enter a username and password and the program checks if the username and password is in the text file. If the username and password is not in the text file, it asks if the user wants to create a new user. If the username and password matches one in the text file, it re... | 1 | 2016-10-07T21:42:56Z | 39,926,342 | <p>You may know the <code>open()</code> function. With this function you can open a file like this: </p>
<pre><code>open('text.txt', 'a')
</code></pre>
<p>Parameter 1 is the file and parameter 2 is the mode (r for read only, w for write only and a for both and appending)</p>
<p>So to read the open file line by line ... | 1 | 2016-10-07T21:56:24Z | [
"python",
"python-3.x"
] |
pygame screen failing to dislpay | 39,926,302 | <p>I have the following code in Python 3 (and pygame), but the white surface fails to display and I don't understand why. Has it got something to do with where it has been placed? I tried de-indenting, but that didn't work either? The code is as below:</p>
<pre><code>import pygame
from pygame.locals import*
pygame.ini... | 1 | 2016-10-07T21:52:32Z | 39,926,843 | <p>So it does appear that your indentation is wrong.</p>
<p>You need to define the surface and update the screen etc. outside of the event loop.</p>
<p>At the very least you must move the <code>screen.blit(surf, (400, 300))</code> and <code>pygame.display.flip()</code> outside of the event loop.</p>
<p>This is it fi... | 0 | 2016-10-07T22:56:52Z | [
"python",
"pygame",
"surface"
] |
Syntax Error near "CHANGE" in sqlite3 | 39,926,421 | <p>I am attempting to execute the following (move a column to be the first one)</p>
<pre><code>import sqlite3
db = sqlite3.connect('adatabase.sqlite')
c = db.cursor()
c.execute('ALTER TABLE tab1 CHANGE COLUMN r r def FIRST')
</code></pre>
<p>Unfortunately I get this error</p>
<pre><code>Traceback (most recent call l... | 1 | 2016-10-07T22:03:18Z | 39,926,576 | <p><em>SQLite</em> does not support the <code>CHANGE COLUMN</code> feature.</p>
<blockquote>
<p>Only the <code>RENAME TABLE</code> and <code>ADD COLUMN</code> variants of the <code>ALTER TABLE</code>
command are supported</p>
</blockquote>
<p>See all missing features: <a href="http://www.sqlite.org/omitted.html" ... | 1 | 2016-10-07T22:21:42Z | [
"python",
"mysql",
"database",
"sqlite",
"sqlite3"
] |
Access Functions in Dictionary Part 2 | 39,926,423 | <p>As a follow-up to <a href="http://stackoverflow.com/questions/39926137/access-functions-via-dictionary">this question</a>:
I have 2 functions that look like this:</p>
<pre><code>def abc(a,b):
return a+b
def cde(c,d):
return c+d
</code></pre>
<p>And I want to assign it to a dictionary like this:</p>
<pre>... | 1 | 2016-10-07T22:03:38Z | 39,926,532 | <p>Make a seperate sequence of <code>args</code> and use the splat operator (<code>*</code>):</p>
<pre><code>>>> def ab(a,b):
... return a + b
...
>>> def cde(c,d,e):
... return c + d + e
...
>>> funcs = {'ab':ab, 'cde':cde}
>>> to_call = ['ab','cde']
>>> args = [(1,2... | 2 | 2016-10-07T22:15:42Z | [
"python",
"list",
"function",
"python-3.x",
"dictionary"
] |
Python Slider Value | 39,926,455 | <p>I have a Scale in my GUI which I'm trying to get continuous values from. Below is my code. </p>
<pre><code>from Tkinter import *
class Application(Frame):
def getVoltage(self):
print self.voltage_scale.get()
def createWidgets(self):
self.voltage_scale = Scale(self)
self.voltage_scale["from_"... | 0 | 2016-10-07T22:07:35Z | 39,926,487 | <p><code>def getVoltage(self, event_arg):</code> will fix that. The command of some tk controls is passed some event data as an extra argument</p>
| 2 | 2016-10-07T22:10:39Z | [
"python",
"user-interface",
"tkinter",
"tk"
] |
Appending (hstack) a comformable array to a matrix returns error | 39,926,466 | <p>I am trying to <code>np.hstack</code> an array to a matrix. The array has <code>.shape</code> <code>(a,)</code>, the matrix has <code>.shape</code> <code>(a,b)</code>, with <code>a</code> and <code>b</code> integers. I get the error that dimensions do not match (<code>all the input arrays must have same number of di... | 0 | 2016-10-07T22:08:28Z | 39,926,500 | <p>I think the problem is that what you are calling array is 1-dimensional whereas the matrix is 2-dimensional.</p>
<p>Let's say they are called <code>M</code> and <code>N</code>. <code>M.shape</code> gives <code>(a,)</code> (being what you called "an array") and <code>N.shape</code> gives <code>(a,b)</code> (being wh... | 1 | 2016-10-07T22:11:54Z | [
"python",
"append"
] |
Appending (hstack) a comformable array to a matrix returns error | 39,926,466 | <p>I am trying to <code>np.hstack</code> an array to a matrix. The array has <code>.shape</code> <code>(a,)</code>, the matrix has <code>.shape</code> <code>(a,b)</code>, with <code>a</code> and <code>b</code> integers. I get the error that dimensions do not match (<code>all the input arrays must have same number of di... | 0 | 2016-10-07T22:08:28Z | 39,926,526 | <p>Add an <em>extra axis</em> to the first array using <code>None</code> or <code>np.newaxis</code>:</p>
<pre><code>>>> import numpy as np
>>> a= np.array([1,2,3])
>>> a.shape
(3,)
>>> b = np.array([[1], [2], [3]])
>>> b.shape
(3, 1)
>>> np.hstack((a[:, None], b))... | 1 | 2016-10-07T22:14:48Z | [
"python",
"append"
] |
Appending (hstack) a comformable array to a matrix returns error | 39,926,466 | <p>I am trying to <code>np.hstack</code> an array to a matrix. The array has <code>.shape</code> <code>(a,)</code>, the matrix has <code>.shape</code> <code>(a,b)</code>, with <code>a</code> and <code>b</code> integers. I get the error that dimensions do not match (<code>all the input arrays must have same number of di... | 0 | 2016-10-07T22:08:28Z | 39,926,546 | <p>Another option is </p>
<pre><code>np.transpose(np.asmatrix(a))
</code></pre>
<p>before appending.</p>
| 0 | 2016-10-07T22:17:30Z | [
"python",
"append"
] |
Python graphing with numpy | 39,926,473 | <p>Okay so I'm trying to plot a function with an e to some expression but I keep getting an error at the lines that I have put (##) @ where the error message is</p>
<p>TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'float'</p>
<pre><code>#!C:\Users\msawe\Anaconda3 or C:\Anaconda3\python
import numpy... | -1 | 2016-10-07T22:09:06Z | 39,926,593 | <p>Assuming that I'm interpreting your equation correctly, there's a bug in your implementation of <code>np.cos()</code> in your definition of h(x): you wrote <code>np.cos*(...)</code> rather than <code>np.cos(...)</code>. After fixing that, the code is able to plot- hopefully it's giving the right result!</p>
<p>This... | 0 | 2016-10-07T22:23:30Z | [
"python",
"numpy"
] |
multi-core efficiency when doing big computations? | 39,926,579 | <p>I have a code to find big primes, as it is it checks every odd number, but I wanted to know if I could have it check, for example, every other odd number and have the numbers it skips be checked on a different core.</p>
| 0 | 2016-10-07T22:22:01Z | 39,927,481 | <p>EDIT, added multiprocess and still didn't see a speedup over unthreaded. I don't understand why multiprocessing didn't speed up the code, I'd appreciate feedback. Maybe I didn't write it correctly. You can try playing with it yourself.</p>
<p>Code:</p>
<pre><code>from multiprocessing import Process, Queue
from thr... | 0 | 2016-10-08T00:33:42Z | [
"python",
"multithreading",
"python-2.7"
] |
Sum up the index value in multiple array with pyspark | 39,926,603 | <p>I have 50 array with float values (<code>50*7</code>). How am I suppose to sum up the 50 arrays on same index to one with PySpark map-reducer function.</p>
<p>Example:</p>
<pre><code>array1 = {1,2,3,4,5,6,7}
array2 = {3,4,2,3,5,6,7}
....
</code></pre>
<p>the result should be <code>array3 = {4,6,5,7,10,12,14}</cod... | 0 | 2016-10-07T22:24:35Z | 39,928,625 | <p>Edit: I think it's easier to use DataFrame.</p>
<pre><code>from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.getOrCreate()
arrays = [
[1,2,3,4,5,6,7],
[3,4,2,3,5,6,7],
[1,2,3,4,5,6,7],
]
df = spark.createDataFrame(arrays)
s = df.groupBy().sum().collect()
print s
print l... | 0 | 2016-10-08T04:16:46Z | [
"python",
"mapreduce",
"pyspark"
] |
Numpy reshape acts different on copied vs. uncopied arrays | 39,926,628 | <p>I've come across seemingly inconsistent results when flattening certain numpy arrays with numpy.reshape. Sometimes if I reshape an array it returns a 2D array with one row, whereas if I first copy the array then do the exact same operation, it returns a 1D array. </p>
<p>This seems to happen primarily when combinin... | 3 | 2016-10-07T22:28:31Z | 39,926,675 | <p>You added together a sparse matrix object and a normal ndarray:</p>
<pre><code>X = I+A
</code></pre>
<p>The result is a dense <em>matrix</em> object, an instance of <code>np.matrix</code>, not a normal ndarray.</p>
<p>This:</p>
<pre><code>np.reshape(X, -1)
</code></pre>
<p>ends up returning a matrix, which can'... | 5 | 2016-10-07T22:36:20Z | [
"python",
"arrays",
"numpy",
"scipy"
] |
Create an instance of a class from a type class string like 'containers.Room'? | 39,926,638 | <p>I'm new to programming and I've chosen Python. I've gone through all of learn python the hard way, I've coded my own 'choose your own adventure game' and now I'm moving on to creating something more akin to a MOO. </p>
<p>I've structured my objects database to be very simple (everything in the game will be an obj... | -1 | 2016-10-07T22:29:33Z | 39,927,259 | <p>So I figured out that my issue was due to trying to import modules from siblings when I was directly running my db.py script to test it.</p>
<p>I created a main.py file in my root directory for the project, allowing me to do something like this:</p>
<pre><code> typeclass = args['typeclass'].split('.')
impor... | 0 | 2016-10-07T23:53:34Z | [
"python",
"python-2.7"
] |
UnboundLocalError: local variable 'number1' referenced before assignment | 39,926,640 | <p>I am getting an error in line 2 saying that i have an unboundLocal error. can anyone explain to me how to fix this?</p>
<pre><code> def main():
number1=getNumber1(number1)
number2=getNumber2(number2)
userIntro=''
printInfo=0.0
answer=0.0
#intro module ... | -2 | 2016-10-07T22:29:56Z | 39,926,677 | <p><code>number1</code> isn't defined until you create it - you can't pass it to another function while defining it. Seems like you need a simpler function that gets the <strong>name</strong> you want to assign to:</p>
<pre><code>def main():
number1 = getNumber('number1')
number2 = getNumber('number2')
def ge... | 1 | 2016-10-07T22:36:34Z | [
"python",
"python-2.7",
"python-3.x"
] |
if statement in subprocess.Popen | 39,926,662 | <p>I'm trying to run bash code via python. Normal statements (netstat, for example) work. If functions like the one below, however, don't. What should I change in order to run the following code correctly?
Thanks in advance</p>
<pre><code>>>> import os
>>> import subprocess
>>>
>>>... | 0 | 2016-10-07T22:33:30Z | 39,927,295 | <p>The command you are trying to run in the subprocess is following the <code>bash</code> shell syntax, where the string equality test is performed via <code>==</code>. Now, on Unix with shell=True, the shell defaults to <code>/bin/sh</code> where instead the equality test is performed via a simple <code>=</code>. The ... | 1 | 2016-10-07T23:58:26Z | [
"python",
"bash",
"if-statement",
"subprocess"
] |
Python2.7 how do I use multiples variables in a loop? | 39,926,676 | <p>I'm making my own game with Python2.7 through the pygame libraby.
It's a 1v1 combat game where players use the same keyboard.</p>
<p>The game works in a main loop that is repeated 60times per second, every time the loop is executed, it calculates lots of things e.g the position, problem is that I have 2 players, so... | 0 | 2016-10-07T22:36:32Z | 39,926,733 | <p>Create a class player.
Then add the attributes of each player to the class.
Instantiate your class with player 1 and 2. </p>
<pre><code>class Player():
direction = "right"
etc.
def shoot(self):
if self.direction == "right"
shoot_right()
playerOne = Player()
playerTwo = Player()
di... | 2 | 2016-10-07T22:43:12Z | [
"python",
"loops",
"variables",
"pygame"
] |
Python2.7 how do I use multiples variables in a loop? | 39,926,676 | <p>I'm making my own game with Python2.7 through the pygame libraby.
It's a 1v1 combat game where players use the same keyboard.</p>
<p>The game works in a main loop that is repeated 60times per second, every time the loop is executed, it calculates lots of things e.g the position, problem is that I have 2 players, so... | 0 | 2016-10-07T22:36:32Z | 39,926,778 | <p>How about storing your variables(for example p1direction and p2direction) in a vector(player_directions) indexed by the player number and using a loop access it, for example:</p>
<pre><code>number_of_players = 2
playersXS = function_that_fills_playersXS() # return a vector containing your p1XS and p2XS variables ... | 0 | 2016-10-07T22:50:24Z | [
"python",
"loops",
"variables",
"pygame"
] |
How do I add mass comments into Windows Command prompt? | 39,926,717 | <p>I have a lot of text I would like to add as a comment. For example, I want to put the enitre help section of CHKDSK:</p>
<pre>
Checks a disk and displays a status report.
CHKDSK [volume[[path]filename]]] [/F] [/V] [/R] [/X] [/I] [/C] [/L[:size]] [/B] [/scan] [/spotfix]
volume Specifies the drive ... | 0 | 2016-10-07T22:41:08Z | 39,927,903 | <p>This is easy to do if you use Vim:</p>
<ol>
<li>Move to the first column of the first line you want to comment.</li>
<li>Press <code><C-v></code> (<kbd>Ctrl</kbd>+<kbd>V</kbd>) to enter block select mode.</li>
<li>Move the selection to the first column of the last line you want to comment.</li>
<li>Type <code... | 0 | 2016-10-08T01:52:31Z | [
"python",
"windows",
"comments",
"command-prompt"
] |
Python can't find setuptools | 39,926,760 | <p>I got the following ImportError as i tried to setup.py install a package:</p>
<pre><code>Traceback (most recent call last):
File "setup.py", line 4, in <module>
from setuptools import setup, Extension
ImportError: No module named setuptools
</code></pre>
<p>This happens although setuptools is already ... | 0 | 2016-10-07T22:48:03Z | 39,926,820 | <p>It's possible you have multiple python versions installed on your system. For example if you installed your python from source, and then again with apt-get. Apt-get will install to the default python version. Make sure you are being consistent. </p>
<p>Potentially using pip install setuptools could solve your probl... | 1 | 2016-10-07T22:55:03Z | [
"python",
"python-2.7",
"setuptools"
] |
"only length-1 arrays can be converted to Python scalars"-error with float conversion-function | 39,926,825 | <p>When running this program, I receive the error "TypeError: only length-1 arrays can be converted to Python scalars", specifically referring to line 9, where the x1-variable is assigned. </p>
<p>I'm kind of clueless here what it means in this context. I worked with a very similar piece of code for a previous assignm... | 0 | 2016-10-07T22:55:30Z | 39,926,878 | <p>Drop all of those <code>float</code> calls and your code should work (as <em>floats</em>). You're trying to coerce numpy arrays into single float values which isn't going to work.</p>
| 2 | 2016-10-07T23:01:19Z | [
"python",
"arrays",
"numpy",
"vector"
] |
Error running endpointscfg.py get_swagger_spec | 39,926,853 | <p>I am trying to build a project using Google Cloud Endpoints, following this guide: <a href="https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python" rel="nofollow">Quickstart for Cloud Endpoints Frameworks on App Engine</a>.</p>
<p>I am stuck at the step of generating the OpenAPI conf... | 1 | 2016-10-07T22:58:05Z | 39,926,959 | <p>Rather than running it directly, try running it with Python, a la:</p>
<pre><code>python lib/endpoints/endpointscfg.py get_swagger_spec main.EchoApi --hostname your-service.appspot.com
</code></pre>
<p>Tried that and it just worked for me. I'll try and make this better (either by fixing the docs or applying some f... | 0 | 2016-10-07T23:11:55Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"google-cloud-endpoints",
"google-cloud-sdk"
] |
Error running endpointscfg.py get_swagger_spec | 39,926,853 | <p>I am trying to build a project using Google Cloud Endpoints, following this guide: <a href="https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python" rel="nofollow">Quickstart for Cloud Endpoints Frameworks on App Engine</a>.</p>
<p>I am stuck at the step of generating the OpenAPI conf... | 1 | 2016-10-07T22:58:05Z | 40,112,797 | <p>I had the exact same problem and tried the same things. What worked for me was:</p>
<pre><code>chmod +x lib/endpoints/endpointscfg.py
</code></pre>
<p>Then running the command again.</p>
| 0 | 2016-10-18T15:52:36Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"google-cloud-endpoints",
"google-cloud-sdk"
] |
How do I split this into maybe 2 or 3 functions? | 39,926,911 | <p>I was just wondering how do I split this into different functions say like maybe 2 or 3 functions? I'm not that good with passing parameters with functions yet. Would you recommend doing that or should I keep it the way it is in one function since it's a while loop? By the way it's for a beginner programming class s... | 0 | 2016-10-07T23:05:25Z | 39,927,114 | <p>Overall, I think this should be a single routine. However, you are taking a somewhat tortuous path to the solution. You're doing a <em>lot</em> of work to pull digits out of the integer version of the card number, when they're perfectly accessible in the original text.</p>
<p>Here's a start on accessing the strin... | 2 | 2016-10-07T23:32:48Z | [
"python",
"python-3.x"
] |
for loop iterates over first letter only | 39,926,952 | <p>My loop seems to iterate over the first letter and then breaks though it's supposed to iterate through each letter in the secretWord, for example, the code bellow is supposed to print out "_pp_e" but instead it only prints "_". I don't understand, what's the problem with that code??</p>
<pre><code>def getGuessedWor... | 0 | 2016-10-07T23:10:35Z | 39,926,974 | <p>You <code>return</code> from the function in the first iteration. <code>return</code> <strong>ends</strong> a function, there and then, so the <code>for</code> loop won't continue either.</p>
<p>You need to build up your return value <em>in the function itself</em>. Build up the resulting string one character at a ... | 2 | 2016-10-07T23:13:46Z | [
"python",
"debugging",
"for-loop"
] |
for loop iterates over first letter only | 39,926,952 | <p>My loop seems to iterate over the first letter and then breaks though it's supposed to iterate through each letter in the secretWord, for example, the code bellow is supposed to print out "_pp_e" but instead it only prints "_". I don't understand, what's the problem with that code??</p>
<pre><code>def getGuessedWor... | 0 | 2016-10-07T23:10:35Z | 39,927,010 | <p>The return keyword exits the calling function. This should do the trick: </p>
<pre><code>def getGuessedWord(secretWord, lettersGuessed):
result = ''
for letter in secretWord:
if letter in lettersGuessed:
result += letter
else:
result += '_'
return result
print(g... | 0 | 2016-10-07T23:17:53Z | [
"python",
"debugging",
"for-loop"
] |
Selecting multiple elements from array python | 39,927,044 | <p>this is a pretty basic question but here goes:</p>
<p>I would like to create an array and then would like to compare a user input to those elements within the array.</p>
<p>If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on... | 0 | 2016-10-07T23:21:50Z | 39,927,108 | <p>So I understand your question such that you want to know, how many of your <code>ingredients</code> are entered by the user:</p>
<pre><code>ingredients = {'beef','mushrooms','ale','onions','steak','burger'}
# assume for now the inputs are whitespace-separated:
choices = input("Please enter your preferred ingredien... | 0 | 2016-10-07T23:32:14Z | [
"python",
"arrays",
"python-3.x"
] |
Selecting multiple elements from array python | 39,927,044 | <p>this is a pretty basic question but here goes:</p>
<p>I would like to create an array and then would like to compare a user input to those elements within the array.</p>
<p>If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on... | 0 | 2016-10-07T23:21:50Z | 39,927,142 | <p>You may do something like:</p>
<pre><code># Dictionary to map function to execute with count of matching words
check_func = {
0: func_1,
1: func_2,
2: func_3,
}
ingredients = ['beef','mushrooms','ale','onions','steak','burger']
user_input = input()
# Convert user input string to list of words
use... | 0 | 2016-10-07T23:36:48Z | [
"python",
"arrays",
"python-3.x"
] |
Selecting multiple elements from array python | 39,927,044 | <p>this is a pretty basic question but here goes:</p>
<p>I would like to create an array and then would like to compare a user input to those elements within the array.</p>
<p>If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on... | 0 | 2016-10-07T23:21:50Z | 39,928,296 | <p>Since you only can work with IF statements </p>
<pre><code>beef=input().split()
#this splits all the characters when they're space separated
#and makes a list of them
</code></pre>
<p>you can use your <code>"beef" in beef and "mushrooms" in beef</code> and it should run as you expected it to</p>
| 0 | 2016-10-08T03:10:45Z | [
"python",
"arrays",
"python-3.x"
] |
Indentation error - python | 39,927,079 | <p>I am unsure what is wrong with my code. I am trying to write a program that finds the prime factorization of a number, and iterates through numbers. My code is </p>
<pre><code>import math
import time
def primfacfind(n1,n2):
while n1 < n2:
n = n1
primfac=[]
time_start = time.clock()... | 0 | 2016-10-07T23:26:12Z | 39,927,131 | <p>I put that code in my editor and it compiled just fine. So I went to line 12 where you have <code>sieve = [True] * n</code> and got rid of the indentation so it was indented the same as the line above it <code>def primes(n):</code> and I was able to recreate your error. </p>
<p>Perhaps try and add an additional ind... | -1 | 2016-10-07T23:35:48Z | [
"python",
"compiler-errors",
"indentation"
] |
Indentation error - python | 39,927,079 | <p>I am unsure what is wrong with my code. I am trying to write a program that finds the prime factorization of a number, and iterates through numbers. My code is </p>
<pre><code>import math
import time
def primfacfind(n1,n2):
while n1 < n2:
n = n1
primfac=[]
time_start = time.clock()... | 0 | 2016-10-07T23:26:12Z | 39,927,143 | <p>Download something like <a href="https://www.sublimetext.com/" rel="nofollow">Sublime</a> and highlight the code. Spaces will be dots and tabs will be dashes.</p>
| 2 | 2016-10-07T23:36:54Z | [
"python",
"compiler-errors",
"indentation"
] |
Need read some data from JSON | 39,927,140 | <p>I need to make a get (id, name, fraction id) for each deputy in this json </p>
<pre><code>{
"id": "75785",
"title": "(за оÑновÑ)",
"asozdUrl": null,
"datetime": "2011-12-21T12:20:26+0400",
"votes": [
{
"deputy": {
"id": "99111772",
"nam... | -2 | 2016-10-07T23:36:28Z | 39,927,172 | <p>You can access the list containing the deputies with <code>data['votes']</code>. Iterating through the list, you can access the keys you're interested in as you would with dict key lookups. Nested dicts imply you have to walk through the keys starting from the root to your point of interest: </p>
<pre><code>for d i... | 3 | 2016-10-07T23:41:13Z | [
"python",
"json"
] |
Convert pandas python data frame column values in place | 39,927,141 | <p>I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?</p>
<p>For example, in R, I would do:</p>
<pre><code>list = ifelse(list > ... | 0 | 2016-10-07T23:36:34Z | 39,927,166 | <p>you can use an indexer and .loc to change values such has</p>
<pre><code> indexer = df[df['col']>0].index
df.loc[indexer] = 1
indexer_2 = df[df['col']<0].index
df.loc[indexer_2] = 0
</code></pre>
<p>or you can look at numpy.where such has</p>
<pre><code>import numpy as np
import pandas as pd
pd.DataFr... | 0 | 2016-10-07T23:40:18Z | [
"python",
"pandas",
"dataframe"
] |
Convert pandas python data frame column values in place | 39,927,141 | <p>I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?</p>
<p>For example, in R, I would do:</p>
<pre><code>list = ifelse(list > ... | 0 | 2016-10-07T23:36:34Z | 39,927,177 | <p>You can return <code>boolean</code> values and use <code>astype(int)</code> to convert them to <code>1</code> and <code>0</code>. </p>
<pre><code>print((df['A'] > 0).astype(int))
</code></pre>
<p><strong>Example:</strong> </p>
<pre><code>df = pd.DataFrame({'A': [1,-1,2,-2,3,-3]})
print(df)
A
0 1
1 -1
2 2
3... | 1 | 2016-10-07T23:41:47Z | [
"python",
"pandas",
"dataframe"
] |
Convert pandas python data frame column values in place | 39,927,141 | <p>I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?</p>
<p>For example, in R, I would do:</p>
<pre><code>list = ifelse(list > ... | 0 | 2016-10-07T23:36:34Z | 39,927,384 | <p>You can use <code>DataFrame.apply</code> to apply a function to each row of your DataFrame. For instance:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'A': [1, -2, 3, -4]})
df['A'] = df.apply(lambda row:np.where(row['A'] > 0, 1, 0), axis=1)
</code></pre>
<p>The <code>lambda</code> fu... | 0 | 2016-10-08T00:13:52Z | [
"python",
"pandas",
"dataframe"
] |
Difference between Positional , keyword, optional and required argument? | 39,927,162 | <p>I am learning about functions in python and found many good tutorials and answers about functions and their types, but I am confused at some places. I have read the following:</p>
<p>If function has <code>"="</code> then it's a keyword argument i.e <code>(a,b=2)</code>
If function does not have <code>"="</code> the... | 0 | 2016-10-07T23:39:39Z | 39,927,217 | <ul>
<li>Optional arguments are those that have a default or those which are passed via *args and **kwargs. </li>
<li>Any argument can be a keyword argument, it just depends on how it's called.</li>
<li>these are used for passing variable numbers of args or keyword args</li>
<li>yes and yes</li>
</ul>
<p>For more info... | 0 | 2016-10-07T23:47:04Z | [
"python",
"python-2.7",
"python-3.x"
] |
Difference between Positional , keyword, optional and required argument? | 39,927,162 | <p>I am learning about functions in python and found many good tutorials and answers about functions and their types, but I am confused at some places. I have read the following:</p>
<p>If function has <code>"="</code> then it's a keyword argument i.e <code>(a,b=2)</code>
If function does not have <code>"="</code> the... | 0 | 2016-10-07T23:39:39Z | 39,927,275 | <h2>Default Values</h2>
<p>Let's imagine a function,</p>
<pre><code>def function(a, b, c):
print a
print b
print c
</code></pre>
<p>A positional argument is passed to the function in this way.</p>
<pre><code>function("position1", "position2", "position3")
</code></pre>
<p>will print</p>
<pre><code>pos... | 1 | 2016-10-07T23:55:39Z | [
"python",
"python-2.7",
"python-3.x"
] |
Alternative for the DYLD_LIBRARY_PATH-trick since Mac OS 10.11 El Capitan with System Integrity Protection | 39,927,235 | <p><strong>Here is what I have:</strong></p>
<ul>
<li>Mac OS 10.11 El Capitan</li>
<li>python 2.7.12, installed from python.org under <code>/Library/Frameworks/Python.framework/</code></li>
<li>PyCharm 2016.2.3</li>
<li>vtk 7.1.0</li>
</ul>
<p><strong>Here is what I do:</strong></p>
<ul>
<li><p>Build a python module... | 0 | 2016-10-07T23:50:11Z | 39,967,241 | <p>After a long struggle, I was able to solve the last bit of my problem.</p>
<p>By setting a <strong>fixed value for the RPATH <a href="https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/RunpathDependentLibraries.html" rel="nofollow">Run-Path dependent Li... | 0 | 2016-10-10T21:46:13Z | [
"python",
"osx",
"vtk",
"dyld"
] |
How to do iterations to change dummy variable in multiple columns from 1 to 0 in Python and Pandas? | 39,927,240 | <p>I have a dataframe that have over 200 columns of dummy variable:</p>
<pre><code>Row1 Feature1 Feature2 Feature3 Feature4 Feature5
A 0 1 1 1 0
B 0 0 1 1 1
C 1 0 1 0 1
D 0 1 0 1 0
</code></pre>... | -2 | 2016-10-07T23:50:38Z | 39,927,680 | <p>Here:</p>
<pre><code>df1 = df[df['Feature1'] == 1]
df1.iloc[:, :] = 0
df1.loc[:, 'Feature1'] = 1
df2 = df[df['Feature2'] == 1]
df2.iloc[:, :] = 0
df2.loc[:, 'Feature2'] = 1
df3 = df[df['Feature2'] == 1]
df3.iloc[:, :] = 0
df3.loc[:, 'Feature3'] = 1
</code></pre>
<p>That should be what you are looking for.</p>
| 0 | 2016-10-08T01:08:46Z | [
"python",
"pandas",
"for-loop"
] |
Nested conditional transformation | 39,927,244 | <p>I am trying to write a small parser that converts nested conditional statements into one-liners conditionals. A basic example would be:</p>
<pre><code>if age > 15:
if size == 3:
test = 1
if size == 4:
test = 2
</code></pre>
<p><strong>translates to:</strong></p>
<pre><code>'if age > ... | 2 | 2016-10-07T23:51:20Z | 39,927,730 | <p>Try using a stack:
(This program doesn't do any error checking, it assumes you code in the same way you did above, and tabs must be used, not 4 spaces)</p>
<pre><code>mystack=[]
toprint=[]
ins=input('Next line: ')
while ins!='':
level=0
while ins[0]=='\t':
ins=ins[1:]
level+=1
if ins[0:2... | 1 | 2016-10-08T01:17:41Z | [
"python"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,339 | <p>I think that what you want is a dic of lists.</p>
<pre><code>result_dict = {'1':[], '2':[], '3':[], '4':[], '5':[], '6' :[]}
for word in text.split():
if str(len(word)) in result_dict:
result_dict[str(len(word))].append(word)
return result_dict
</code></pre>
| 1 | 2016-10-08T00:06:21Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,356 | <p>Instead of defining the default value as <code>0</code>, assign it as <code>set()</code> and within <code>if</code> condition do, <code>result_dict[str(len(word))].add(word)</code>. </p>
<p><em>Also, instead of preassigning <code>result_dict</code>, you should use <a href="https://docs.python.org/2/library/collecti... | 1 | 2016-10-08T00:08:44Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,365 | <p>the problem here is you are <em>counting</em> the word by length, instead you want to <em>group</em> them. You can achieve this by storing a list instead of a int:</p>
<pre><code>def get_word_len_dict(text):
result_dict = {}
for word in text.split():
if len(word) in result_dict:
result_d... | 1 | 2016-10-08T00:10:05Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,367 | <p>You say you want the keys to be integers but then you convert them to strings before storing them as a key. There is no need to do this in Python; integers can be dictionary keys.</p>
<p>Regarding your question, simply initialize the values of the keys to empty lists instead of the number 0. Then, in the loop, appe... | 1 | 2016-10-08T00:10:10Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,394 | <p>Fixing Sabian's answer so that duplicates aren't added to the list:</p>
<pre><code>def get_word_len_dict(text):
result_dict = {1:[], 2:[], 3:[], 4:[], 5:[], 6 :[]}
for word in text.split():
n = len(word)
if n in result_dict and word not in result_dict[n]:
result_dict[n].append(wo... | 1 | 2016-10-08T00:15:36Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,424 | <p>Check out <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">list comprehensions</a></p>
<p>Integers are legal dictionaries keys so there is no need to make the numbers strings unless you want it that way for some other reason.
<code>if statement</code> in the <code>for loop</code> cont... | 1 | 2016-10-08T00:22:36Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,438 | <p>What you need is a map to list-construct (if not many words, otherwise a 'Counter' would be fine):
Each list stands for a word class (number of characters). Map is checked whether word class ('3') found before. List is checked whether word ('had') found before.</p>
<pre><code>def get_word_len_dict(text):
result... | 1 | 2016-10-08T00:24:30Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
Creating a dictionary where the key is an integer and the value is the length of a random sentence | 39,927,318 | <p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>
<p>So far I'm able to create a dictionary where the values are the tota... | 3 | 2016-10-08T00:02:11Z | 39,927,669 | <p>Your code is counting the occurrence of each word length - but not storing the words themselves.</p>
<p>In addition to capturing each word into a list of words with the same size, you also appear to want:</p>
<ol>
<li>If a word length is not represented, do not return an empty list for that length - just don't hav... | 1 | 2016-10-08T01:07:22Z | [
"python",
"list",
"python-3.x",
"dictionary"
] |
With matplotlib, how can I create a 2D histogram with polar projection and a symlog r-axis? | 39,927,348 | <p>I have been having trouble creating polar histograms with symlog axis. However this only breaks when there are negative r-values. What can I do to fix this?</p>
<p>I've included a minimal example which displays 5 plots. Plot 4 is the one which does not work (middle row right.) Plot 5 is to show it working with posi... | 1 | 2016-10-08T00:07:02Z | 39,927,516 | <p>This might be a bug in matplotlib, unfortunately polar plots have multiple <a href="https://github.com/matplotlib/matplotlib/issues/7130" rel="nofollow">scaling issues</a> and <a href="https://github.com/matplotlib/matplotlib/issues/7120#issuecomment-247460462" rel="nofollow">might have to go through some major revi... | 1 | 2016-10-08T00:39:17Z | [
"python",
"matplotlib",
"plot",
"polar-coordinates"
] |
MultiProcessing Lock() doesn't work | 39,927,405 | <p>I have a program that reads some input text files and write all of them into a list called <code>ListOutput</code> which is a shared memory between two processes used in my program (I used two processes so my program runs faster!) I also have a shared memory variable called <code>processedFiles</code> which stores t... | 0 | 2016-10-08T00:17:54Z | 39,927,566 | <p>Bingo! Thanks for including the imports. <em>Now</em> the problem is obvious ;-)</p>
<p>You need to use a <code>multiprocessing.Lock</code> to get a lock that works across processes. The <code>Lock</code> you're actually using is implicitly obtained along with a mountain of other stuff via your</p>
<pre><code>f... | 1 | 2016-10-08T00:48:04Z | [
"python",
"multithreading",
"multiprocessing"
] |
Forcing Unload/Deconstruction of Dynamically Imported File from Source | 39,927,422 | <p>Been a longtime browser of SO, finally asking my own questions!</p>
<p>So, I am writing an automation script/module that looks through a directory recursively for python modules with a specific name. If I find a module with that name, I load it dynamically, pull what I need from it, and then unload it. I noticed th... | 0 | 2016-10-08T00:22:08Z | 39,927,557 | <p>There is a <em>circular reference</em> here, the module object references objects that reference the module again.</p>
<p>This means the module is not cleared immediately (as the reference count never goes to 0 by itself). You need to wait for the circle to be broken by the garbage collector.</p>
<p>You can force ... | 0 | 2016-10-08T00:46:12Z | [
"python",
"python-3.x",
"python-importlib"
] |
Using forms with the Django outputs the token | 39,927,463 | <p>I would really appreciate if you can give a hand with this.
What I'm trying to do it's just to render the value of some text label, but it gives me the token.</p>
<p>I'm learning django I hope you can comprehend.</p>
<p>The result of this is:</p>
<p><strong>eee 12121 csrfmiddlewaretoken yYvl3neQZSP33vSRNto3FUFa88... | 0 | 2016-10-08T00:29:22Z | 39,927,570 | <p>You are looping over all the elements in the POST array in this snippet of code</p>
<pre><code>for key, value in request.POST.items():
response += '%s %s\n' % (key, value)
</code></pre>
<p>I believe, if i understand your question, that what you are after is simply <code>request.POST.get('eee')</code></p>
| 1 | 2016-10-08T00:48:33Z | [
"python",
"django",
"token",
"csrf"
] |
Pyevolve Score in Evaluation function | 39,927,468 | <p>Here is an example of pyevolve library of Python,</p>
<pre><code>from pyevolve import G1DList
from pyevolve import GSimpleGA
import time
def eval_func(chromosome):
score = 0.0
for value in chromosome:
if value == 50:
score += 1
return score
genome = G1DList.G1DList(20)
genome.evaluat... | 0 | 2016-10-08T00:30:23Z | 39,927,523 | <p>Have the evaluation function take every element of the list and add the value of every element of the list. Then subtract the desired value from the the value you get and take the absolute value of the result. Finally put this under a a fraction like 1/(value) to return the highest value for the smallest number.</p>... | 0 | 2016-10-08T00:39:55Z | [
"python",
"algorithm",
"artificial-intelligence",
"genetic-algorithm",
"pyevolve"
] |
using a while True loop | 39,927,504 | <p><strong>Problem 1.</strong></p>
<p>This problem provides practice using a <code>while True</code> loop. Write a function named
<code>twoWords</code> that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.</p>
<p>The function <code>tw... | -5 | 2016-10-08T00:37:17Z | 39,951,286 | <pre><code>def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please... | 0 | 2016-10-10T04:23:30Z | [
"python",
"while-loop"
] |
Django Project parsing parameters in request | 39,927,529 | <p>I have request to my django project from ExtJS application:</p>
<pre><code>GET /products/?page=1&start=0&limit=25&sort=%5B%7B%22property%22%3A%22id%22%2C%22direction%22%3A%22DESC%22%7D%5D
</code></pre>
<p>At the request contains 4 parameters, one of which is a complex, which is called <strong>sort</st... | 0 | 2016-10-08T00:40:45Z | 39,928,087 | <p>There is probably more elegant solution, by I just intercept all ajax requests and convert <code>sort</code> parameter to DRF-friendly <code>ordering</code>:</p>
<pre><code>Ext.Ajax.on('beforerequest', function (conn, options) {
if(options.params && options.params.sort) {
var ordering = options.... | 0 | 2016-10-08T02:27:18Z | [
"python",
"django",
"extjs",
"django-rest-framework"
] |
Django Project parsing parameters in request | 39,927,529 | <p>I have request to my django project from ExtJS application:</p>
<pre><code>GET /products/?page=1&start=0&limit=25&sort=%5B%7B%22property%22%3A%22id%22%2C%22direction%22%3A%22DESC%22%7D%5D
</code></pre>
<p>At the request contains 4 parameters, one of which is a complex, which is called <strong>sort</st... | 0 | 2016-10-08T00:40:45Z | 39,932,879 | <p>I solved the problem by using json package. Thanks for the advice <strong><em>furas</em></strong></p>
<pre><code>def get_queryset(self):
queryset = Products.objects.all()
sortParameter = self.request.query_params.get('sort', None)
parsed_sort=json.loads(sortParameter)
column_name=pa... | 0 | 2016-10-08T13:22:55Z | [
"python",
"django",
"extjs",
"django-rest-framework"
] |
How to make django server public in rasb? | 39,927,569 | <p>I use django server. First, I do port forwarding my raspberrypi ( my public ip : 12345) using my Sharer.</p>
<p>So, I can access my raspberrypi server using x-shell(putty) and then I want to access my dajngo web server. In my home I can access my django server (192.168.1.11:8000)</p>
<p>But I can't access my djang... | 0 | 2016-10-08T00:48:25Z | 39,928,486 | <p>Are you asking to host a webserver/django app from your home network, to the public internet?</p>
<p>If so, I do not have the technical detail on how to accomplish that - but from a security perspective that is not a great idea. You might want to look into some of the free/cheap hosts out there that support python ... | 1 | 2016-10-08T03:49:44Z | [
"python",
"django",
"raspberry-pi"
] |
memory error while performing matrix multiplication | 39,927,586 | <p>As part of a project I'm working on, I need to calculate the mean squared error between <code>2m</code> vectors.</p>
<p>Basically I two matrices <code>x</code> and <code>xhat</code>, both are size <code>m</code> by <code>n</code> and the vectors I'm interested in are the rows of these vectors.</p>
<p>I calculate t... | 1 | 2016-10-08T00:51:42Z | 39,928,411 | <p>The expression <code>np.dot(x-xhat,(x-xhat).T)</code> creates an array with shape (m, m). You say m is 60000, so that array is almost 29 gigabytes.</p>
<p>You take the trace of the array, which is just the sum of the diagonal elements, so most of that huge array is unused. If you look carefully at <code>np.trace(... | 5 | 2016-10-08T03:34:52Z | [
"python",
"numpy",
"math",
"memory",
"matrix"
] |
memory error while performing matrix multiplication | 39,927,586 | <p>As part of a project I'm working on, I need to calculate the mean squared error between <code>2m</code> vectors.</p>
<p>Basically I two matrices <code>x</code> and <code>xhat</code>, both are size <code>m</code> by <code>n</code> and the vectors I'm interested in are the rows of these vectors.</p>
<p>I calculate t... | 1 | 2016-10-08T00:51:42Z | 39,930,177 | <p>If you are going for performance as well, one alternative approach to compute sum of squared differences could be using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>, like so -</p>
<pre><code>subs = x-xhat
out = np.einsum('ij,ij',subs,subs)... | 1 | 2016-10-08T08:07:39Z | [
"python",
"numpy",
"math",
"memory",
"matrix"
] |
Decreasing brightness in the bottom half of a photo | 39,927,762 | <p>I have a questions thats stumping me right now.
I have to decrease the brightness of the bottom half of a picture.
This is what I'm using so far. Its decreasing the brightness of the TOP half of my photo. How can I get it to decrease the bottom half? I know tat its somewhere in the third line I just can't figure it... | 0 | 2016-10-08T01:24:14Z | 39,929,682 | <p>I believe you need to do half the pixels, <em>"but starting from half way through them rather than from the beginning"</em>, if I can put it like that!</p>
<p>So, replace this:</p>
<pre><code>for index in range(0,len(pixels)/2):
</code></pre>
<p>with this:</p>
<pre><code>for index in range(len(pixels)/2,len(pixe... | 1 | 2016-10-08T07:02:46Z | [
"python",
"image",
"jes"
] |
Why does my Python code fail unit testing? | 39,927,779 | <p>I have this challenge:</p>
<blockquote>
<p>Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents.</p>
<p>For any invalid input, return string Invalid input</p>
<p>Example: For number 5 return string... | 1 | 2016-10-08T01:27:36Z | 39,927,802 | <p>Comparing strings in Python cares cases.</p>
<pre><code>>>> 'invalid input' == 'Invalid input'
False
</code></pre>
<p>You need to adjust test code or implementation code so that string literals matches exactly.</p>
<pre><code>def test_no_negative_numbers(self):
result = binary_converter(-1)
self.... | 2 | 2016-10-08T01:31:42Z | [
"python",
"unit-testing"
] |
Write floating point numbers without any decimal places | 39,927,803 | <p>I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is</p>
<pre><code>htgm=31380.
print... | 1 | 2016-10-08T01:31:42Z | 39,927,829 | <p>It is not possible to do it Python keeping the type of <code>htgm</code> as <code>float</code>. However if you are OK with making it as <code>str</code>, you may do:</p>
<pre><code>htgm=31380.
'{0:.0f}.'.format(htgm)
# returns: '31380.'
# OR, even simply
'{}.'.format(int(htgm))
</code></pre>
| 1 | 2016-10-08T01:38:07Z | [
"python",
"string",
"format"
] |
Write floating point numbers without any decimal places | 39,927,803 | <p>I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is</p>
<pre><code>htgm=31380.
print... | 1 | 2016-10-08T01:31:42Z | 39,927,896 | <p>Python format language includes an 'alternate' form for floats which forces the decimal point by using a '#' in the format string:</p>
<pre><code>>>> htgm=31380.
>>> format(htgm, '#.0f')
'31380.'
</code></pre>
<p>Which is what I think you are looking for.<br>
I thought <code>#g</code> would be wh... | 2 | 2016-10-08T01:51:29Z | [
"python",
"string",
"format"
] |
Write floating point numbers without any decimal places | 39,927,803 | <p>I'm trying to have Python replicate some FORTRAN output of real values. My FORTRAN prints the real value as "31380.". I'm trying to replicate the same in Python--note that although I have no decimal places, I actually want the decimal point (period) to be printed. My current code is</p>
<pre><code>htgm=31380.
print... | 1 | 2016-10-08T01:31:42Z | 39,927,926 | <p>When you need to display the number, use:</p>
<pre><code>print(str(htgm)[:-1])
</code></pre>
<p>This notation will shave off the last '0'.</p>
| 0 | 2016-10-08T01:55:24Z | [
"python",
"string",
"format"
] |
When i try to scrape details page for image I get an error | 39,927,950 | <p>I am trying to get the image of the details page from a website. I am using the rss 'links' function to get the links. This is my code</p>
<pre><code>@app.task
def pan_task():
url = 'http://feeds.example.com/reuters/technologyNews'
name = 'noticiassin'
live_leaks = [i for i in feedparser.parse(url).entr... | 1 | 2016-10-08T01:59:28Z | 39,928,098 | <p>You need to do something like this:</p>
<pre><code>@app.task
def pan_task():
url = 'http://feeds.example.com/reuters/technologyNews'
name = 'noticiassin'
live_leaks = [i for i in feedparser.parse(url).entries][:10]
the_count = len(live_leaks)
ky = feedparser.parse(url).keys()
oky = [i.keys()... | -1 | 2016-10-08T02:28:46Z | [
"python",
"parsing",
"beautifulsoup",
"screen-scraping",
"feedparser"
] |
What is the loss function that use the DNNRegressor? | 39,928,035 | <p>I am using <strong>DNNRegressor</strong> to train my model. I search in the documentation what is the loss function used by this wrapper but i don't find it. On the other hand, it is possible to change that loss function?.</p>
<p>Thank you for your suggestions.</p>
| 0 | 2016-10-08T02:17:15Z | 39,964,849 | <p>It uses L2 loss (mean squared error) as defined in <a href="https://github.com/tensorflow/tensorflow/blob/754048a0453a04a761e112ae5d99c149eb9910dd/tensorflow/contrib/layers/python/layers/target_column.py" rel="nofollow">target_column.py</a>: </p>
<pre><code>def regression_target(label_name=None,
... | 1 | 2016-10-10T18:48:50Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow",
"deep-learning"
] |
"TypeError: can only concatenate tuple (not "float") to tuple" | 39,928,048 | <p>I am writing a program to open and read a txt file and go through loops each line. multiply values in 2nd column and 4th column and assign it to 5th column.</p>
<pre><code>A 500.00 A 84.15 ?
B 648.80 B 77.61 ?
C 342.23 B 39.00 ?
</code></pre>
<p>this is part of codes I wrote, </p>
<pre><code>for line in infi... | 0 | 2016-10-08T02:19:55Z | 39,928,077 | <p>Looking at this information, I could only tell that the value returned by <code>eval</code> of <code>b</code> and <code>d</code> are of <code>float</code> and <code>tuple</code> type. And you can not do <code>+</code> on <code>float</code> and <code>tuple</code>. For example:</p>
<pre><code>>>> 5.0 + (2 ,3... | 0 | 2016-10-08T02:25:06Z | [
"python"
] |
Install Python 3 to /usr/bin/ on macOS | 39,928,053 | <p>I installed python2.x and python3.x using homebrew and the executable python paths are listed below:</p>
<pre><code>$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
</code></pre>
<p><br>
It's quite too long an... | 0 | 2016-10-08T02:20:53Z | 39,931,634 | <p>Create a symbolic link in <code>/usr/bin/</code></p>
<p>Open terminal and do:</p>
<pre>$ sudo ln /Library/Frameworks/Python.framework/Versions/2.7/bin/python /usr/bin/python
$ sudo ln /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 /usr/bin/python3
</pre>
<p>You can now do what you wanted to do.</p>... | 1 | 2016-10-08T11:07:39Z | [
"python",
"osx",
"python-3.x",
"path"
] |
How do I the value for a foreign key to show up in Django Rest | 39,928,055 | <p>I want my output json to show the value of a the record that the foreign key is pointing to instead of the key instead.</p>
<p>For example i want this to show up:</p>
<pre><code>[
{
"id": 1,
"brand": "ATL Motors",
"package": "Full Page",
"newspaper": "Gleaner",
"cost": 2... | 0 | 2016-10-08T02:21:09Z | 39,928,830 | <p>You can use <a href="http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield" rel="nofollow">StringRelatedField</a></p>
<blockquote>
<p>StringRelatedField may be used to represent the target of the
relationship using its <strong>unicode</strong> method.</p>
</blockquote>
<pre><code>class P... | 0 | 2016-10-08T04:59:12Z | [
"python",
"django",
"django-rest-framework"
] |
Verification of ssl certificates failed after compiling .py to .exe | 39,928,062 | <p>I have a script that reads to a URL. It works fine if I run it to cmd using <code>python app.py</code>. But after compiling it using py2exe and running the <code>.exe</code> I am getting this error</p>
<pre><code>entering main now.....
Traceback (most recent call last):
File "strtojson.py", line 257, in <modul... | 0 | 2016-10-08T02:22:09Z | 39,928,824 | <p>My guess is that Python will not find the trusted CA (needed to validate the server certificates) anymore because they are not included in the exe. In this case using <code>requests.get</code> with <code>verify=False</code> should work. </p>
<p>But this should only be done to verify that this is really the cause of... | 0 | 2016-10-08T04:58:27Z | [
"python",
"ssl",
"ssl-certificate",
"python-requests"
] |
Karatsuba Infinite Recursion - Python | 39,928,083 | <p>Beginner here. I've spent most of the day working on the Karatsuba Algorithm just because I thought it would be fruitful. I've seen similar questions on here, but they are in other languages and seem strangely complex. The following is my code. The minute it hits the recursive call to ac, it just keeps on recursing... | 0 | 2016-10-08T02:26:15Z | 39,928,285 | <p>Do you want integer division? In this case, you should use:</p>
<pre><code>a = x // 10 ** (n / 2)
</code></pre>
<p>and</p>
<pre><code>c = y // 10 ** (n / 2)
</code></pre>
<p>Otherwise, your program will be feeding through decimals to your function which I assume is not intended.</p>
<p>I'm also a beginner, feel... | 1 | 2016-10-08T03:07:29Z | [
"python",
"algorithm",
"recursion",
"karatsuba"
] |
Karatsuba Infinite Recursion - Python | 39,928,083 | <p>Beginner here. I've spent most of the day working on the Karatsuba Algorithm just because I thought it would be fruitful. I've seen similar questions on here, but they are in other languages and seem strangely complex. The following is my code. The minute it hits the recursive call to ac, it just keeps on recursing... | 0 | 2016-10-08T02:26:15Z | 39,928,519 | <p>Just fixing your code with integer divisions made it work correctly but here's a slight different version using 3 recursive calls (in base 10):</p>
<pre><code>def karatsuba(x, y):
if x < 10 or y < 10:
return x * y
n = max(len(str(x)), len(str(y))) // 2
p = 10**n
a, b = divmod(x, p)
... | 1 | 2016-10-08T03:57:39Z | [
"python",
"algorithm",
"recursion",
"karatsuba"
] |
Is there a more recursive way to do this? | 39,928,220 | <p>I have the following code:</p>
<pre><code>{% if thing.parent.parent.parent.link %}
<a href="/y/{{ thing.parent.parent.parent.link }}">{{ thing.parent.parent.parent.name }}</a>
{% endif %}
{% if thing.parent.parent.link %}
<a href="/y/{{ thing.parent.parent.link }}">{{ thing.parent.parent.... | 0 | 2016-10-08T02:53:52Z | 39,928,569 | <p>Return a list in your context and then you can use an iterative approach:</p>
<pre><code>{% for parent in parents %}
<a href="/y/{{ parent.link }}">{{ parent.name }}</a>
{% endfor %}
</code></pre>
<p>Since nothing special has to be done if it is a child (as you mentioned, the only difference is li... | 2 | 2016-10-08T04:07:02Z | [
"python",
"django",
"recursion",
"django-templates"
] |
How to extract number from text in python? | 39,928,255 | <p>I have the string listed below</p>
<pre><code>str = ['"Consumers_Of_Product": {"count": 13115}']
</code></pre>
<p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p>
<p>Most things I've done previously have not w... | 1 | 2016-10-08T03:01:26Z | 39,928,276 | <p>Use <code>ast.literal_eval</code> on the single element in that list (which you shouldn't call <code>str</code> because it masks the built-in, and it isn't a string anyway), within curly braces (as it seems to be a dictionary element):</p>
<pre><code>>>> import ast
>>> s = ['"Consumers_Of_Product"... | 2 | 2016-10-08T03:06:30Z | [
"python",
"string",
"python-2.7",
"integer"
] |
How to extract number from text in python? | 39,928,255 | <p>I have the string listed below</p>
<pre><code>str = ['"Consumers_Of_Product": {"count": 13115}']
</code></pre>
<p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p>
<p>Most things I've done previously have not w... | 1 | 2016-10-08T03:01:26Z | 39,928,323 | <p>If you just want to extract that number, provided there are no other numbers in that string, you can use <code>regex</code>. I renamed <code>str</code> to be <code>s</code> for the reason mentioned in @TigerhawkT3 answer.</p>
<pre><code>import re
s = ['"Consumers_Of_Product": {"count": 13115}']
num = re.findall('\d... | 1 | 2016-10-08T03:17:18Z | [
"python",
"string",
"python-2.7",
"integer"
] |
How to extract number from text in python? | 39,928,255 | <p>I have the string listed below</p>
<pre><code>str = ['"Consumers_Of_Product": {"count": 13115}']
</code></pre>
<p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p>
<p>Most things I've done previously have not w... | 1 | 2016-10-08T03:01:26Z | 39,928,352 | <p>You have <a href="http://stackoverflow.com/questions/9949533/python-eval-vs-ast-literal-eval-vs-json-decode">3 options</a></p>
<p>But it's recommended to use <code>json</code> lib </p>
<pre><code>import json
s = ['"Consumers_Of_Product": {"count": 13115}']
s[0] = '{' + s[0] + '}'
my_var = json.loads(s[0]) # this i... | 0 | 2016-10-08T03:22:39Z | [
"python",
"string",
"python-2.7",
"integer"
] |
How to extract number from text in python? | 39,928,255 | <p>I have the string listed below</p>
<pre><code>str = ['"Consumers_Of_Product": {"count": 13115}']
</code></pre>
<p>How can I extract the number 13115 as it will change, so that it will always equal var. In other words how do I extract this number from this string?</p>
<p>Most things I've done previously have not w... | 1 | 2016-10-08T03:01:26Z | 39,928,356 | <p>You can use <code>regular expression</code> to extract anything you want from a string. Here is a link about <a href="https://docs.python.org/2/howto/regex.html" rel="nofollow">HOW TO use Regular expression in python</a></p>
<p>sample code here:</p>
<pre><code>import re
m = re.search(r'(\d+)', s[0])
if m:
prin... | 0 | 2016-10-08T03:22:57Z | [
"python",
"string",
"python-2.7",
"integer"
] |
how to convert all columns in the .csv file from numeric to categorical in Python | 39,928,264 | <pre><code>data[].astype('categorical')
</code></pre>
<p>there are 51 columns in my csv file, do I need to add all 51 column namesin the square brackets?
I need all 51 columns which are in int64 to be categorical </p>
| 1 | 2016-10-08T03:03:09Z | 39,928,460 | <p>You can get the column names into a list, then loop to change the type of each column.</p>
<pre><code>import pandas as pd
import numpy as np
# create example dataframe
cats = ['A', 'B', 'C', 'D', 'E']
int_matrix = np.random.randint(10, size=(7,5))
df = pd.DataFrame(data = int_matrix, columns=cats)
print("Origin... | 0 | 2016-10-08T03:46:38Z | [
"python"
] |
How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python) | 39,928,273 | <p>I have the following data in a csv file:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
the_data = """
ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L]}
ABC,2016-6-10 0:00,0,{'//PurpleCar': [219L], '//YellowCar': [381L], '//BlueCar': [... | 1 | 2016-10-08T03:04:57Z | 39,930,002 | <p>this should do the trick</p>
<pre><code>s = pd.read_csv(StringIO(the_data), sep='|', header=None, squeeze=True)
left = s.str.split(',').str[:3].apply(pd.Series)
left.columns = ['Company', 'Date', 'Volume']
right = s.str.split(',').str[3:].str.join(',') \
.str.replace(r'[\[\]\{\}\']', '') \
.str.... | 0 | 2016-10-08T07:46:12Z | [
"python",
"regex",
"pandas"
] |
How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python) | 39,928,273 | <p>I have the following data in a csv file:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
the_data = """
ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L]}
ABC,2016-6-10 0:00,0,{'//PurpleCar': [219L], '//YellowCar': [381L], '//BlueCar': [... | 1 | 2016-10-08T03:04:57Z | 39,931,830 | <p>I think it's better to conver the strings into two columns:</p>
<pre><code>from io import StringIO
import pandas as pd
df = pd.read_csv(StringIO(the_data), sep=',', header=None)
df.columns = ['Company','Date','Volume','Car1','Car2','Car3','Car4']
cars = ["Car1", "Car2", "Car3", "Car4"]
pattern = r"//(?P<color... | 0 | 2016-10-08T11:30:58Z | [
"python",
"regex",
"pandas"
] |
How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python) | 39,928,273 | <p>I have the following data in a csv file:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
the_data = """
ABC,2016-6-9 0:00,95,{'//PurpleCar': [115L], '//YellowCar': [403L], '//BlueCar': [16L], '//WhiteCar-XYZ': [0L]}
ABC,2016-6-10 0:00,0,{'//PurpleCar': [219L], '//YellowCar': [381L], '//BlueCar': [... | 1 | 2016-10-08T03:04:57Z | 39,936,698 | <p><strong>Edit:</strong> The file seems to be actually an escaped CSV so we don't need a custom parsing for this part.</p>
<p><strike>As @Blckknght points out in the comment, the file is not a valid CSV. I'll make some assumptions in my answer. They are</p>
<ol>
<li>You don't control the data and thus can't properly... | 1 | 2016-10-08T19:49:58Z | [
"python",
"regex",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.