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 |
|---|---|---|---|---|---|---|---|---|---|
Django rest framework, should be able to override get_queryset and not define queryset attribute? | 39,435,836 | <p>I am confused. Looking through the ViewSet source code it looks like I should be able to not define a queryset in a viewset and then just override the get queryset function to get whatever queryset I want. But my code fails with this error:</p>
<pre><code>AssertionError: `base_name` argument not specified, and coul... | 1 | 2016-09-11T12:01:09Z | 39,436,584 | <p>A DRF ModelViewSet uses the <code>queryset</code> to derive the URL base. If the <code>queryset</code> property is not set, DRF asks that you use the optional <code>base_name</code> property when registering the router to declare the base.</p>
<p>Check out this page in the DRF docs:</p>
<p><a href="http://www.dja... | 2 | 2016-09-11T13:25:58Z | [
"python",
"django",
"django-rest-framework"
] |
Not able to select value - error "Select only works on <select> elements, not on <a>" | 39,435,840 | <p>I am trying to retrieve all possible year, model and make from [<a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]" rel="nofollow">https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]</a></p>
<pre><code>from seleniu... | 1 | 2016-09-11T12:01:27Z | 39,435,870 | <p>The problem with your current approach is that you are finding the <code>a</code> element and trying to use it as a <code>select</code> element. <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.support.select.Select" rel="nofollow"><code>Select</code> class</a> will only work with <code>sel... | 1 | 2016-09-11T12:04:21Z | [
"python",
"selenium",
"web-scraping"
] |
Not able to select value - error "Select only works on <select> elements, not on <a>" | 39,435,840 | <p>I am trying to retrieve all possible year, model and make from [<a href="https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]" rel="nofollow">https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]</a></p>
<pre><code>from seleniu... | 1 | 2016-09-11T12:01:27Z | 39,436,211 | <p>You don't actually need <code>selenium</code> and automate any visual interactions to get the year+make+model data from the page and can approach the problem with <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> only making appropriate GET requests:</p>
<pre><code># -*- ... | 1 | 2016-09-11T12:41:44Z | [
"python",
"selenium",
"web-scraping"
] |
Nginx - Seems to be running old python scripts | 39,435,884 | <p>I have a website (panicselect.com), and I have made some changes to the python code which i pushed onto Github and then pulled onto my server, which seems to be successful. I have tried restarting the server, but it still seems to be running my older version of the code even though I have successfully pulled the new... | -2 | 2016-09-11T12:06:29Z | 39,441,234 | <p>To fully determine how to deploy changes to your production server, you must understand 2 things:</p>
<h1>1. Most WSGI servers (including uWSGI) will load code on start, not on each execution.</h1>
<p>That means, changes in your code won't be reflected immediately, because old code is still loaded into your WSGI s... | 1 | 2016-09-11T22:25:30Z | [
"python",
"git",
"nginx",
"github",
"uwsgi"
] |
Merged Sort Algorithm | 39,435,885 | <p>I have a merge algorithm which is really fast: it's currently set up to check unknown words between lists; this function checks common words, I need to change the function below to check if words are in vocab or wds or neither I don't properly understand the function so any comments about what specific lines do woul... | -4 | 2016-09-11T12:06:30Z | 39,437,246 | <p>Are you just trying to find words that appear in bigger_vocab and book_words? If so:</p>
<pre><code>both = list(set(bigger_vocab).intersection(book_words))
</code></pre>
| 0 | 2016-09-11T14:44:42Z | [
"python"
] |
Write a program that prints the number of times the string contains a substring | 39,435,988 | <pre><code>s = "bobobobobobsdfsdfbob"
count = 0
for x in s :
if x == "bob" :
count += 1
print count
</code></pre>
<p>i want to count how many bobs in string s, the result if this gives me 17
what's wrong with my code i'm newbie python.</p>
| 0 | 2016-09-11T12:16:44Z | 39,436,019 | <p>When you are looping overt the string, the throwaway variable will hold the characters, so in your loop <code>x</code> is never equal with <code>bob</code>.</p>
<p>If you want to count the non-overlaping strings you can simply use <code>str.count</code>:</p>
<pre><code>In [52]: s.count('bob')
Out[52]: 4
</code></p... | 3 | 2016-09-11T12:20:50Z | [
"python",
"python-2.7",
"python-3.x"
] |
Write a program that prints the number of times the string contains a substring | 39,435,988 | <pre><code>s = "bobobobobobsdfsdfbob"
count = 0
for x in s :
if x == "bob" :
count += 1
print count
</code></pre>
<p>i want to count how many bobs in string s, the result if this gives me 17
what's wrong with my code i'm newbie python.</p>
| 0 | 2016-09-11T12:16:44Z | 39,436,031 | <p>you can use string.count</p>
<p>for example:</p>
<pre><code>s = "bobobobobobsdfsdfbob"
count = s.count("bob")
print(count)
</code></pre>
| 1 | 2016-09-11T12:22:47Z | [
"python",
"python-2.7",
"python-3.x"
] |
Write a program that prints the number of times the string contains a substring | 39,435,988 | <pre><code>s = "bobobobobobsdfsdfbob"
count = 0
for x in s :
if x == "bob" :
count += 1
print count
</code></pre>
<p>i want to count how many bobs in string s, the result if this gives me 17
what's wrong with my code i'm newbie python.</p>
| 0 | 2016-09-11T12:16:44Z | 39,436,122 | <p>I'm not giving the best solution, just trying to correct your code. </p>
<p><strong>Understanding what <code>for each (a.k.a range for)</code> does in your case</strong> </p>
<pre><code>for c in "Hello":
print c
</code></pre>
<p>Outputs: </p>
<pre><code>H
e
l
l
o
</code></pre>
<p>In each iteration you ... | 0 | 2016-09-11T12:31:37Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to drop null values in Pandas? | 39,436,018 | <p>I try to drop null values of column 'Age' in dataframe, which consists of float values, but it doesn't work.
I tried</p>
<pre><code>data.dropna(subset=['Age'], how='all')
data['Age'] = data['Age'].dropna()
data=data.dropna(axis=1,how='all')
</code></pre>
<p>It works for other columns but not for 'Age'</p>
<pre><c... | 1 | 2016-09-11T12:20:45Z | 39,436,068 | <p><code>data.dropna(subset=['Age'])</code> would work, but you should either set <code>inplace=True</code> or assign it back to <code>data</code>:</p>
<pre><code>data = data.dropna(subset=['Age'])
</code></pre>
<p>or </p>
<pre><code>data.dropna(subset=['Age'], inplace=True)
</code></pre>
| 2 | 2016-09-11T12:26:47Z | [
"python",
"pandas"
] |
Python: Value of dictionary is list of strings | 39,436,055 | <pre><code>reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""
print reclist
data= {
"ids": [
reclist #"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"
]
}
print data
</code></pre>
<p>Output: `</p>
<pre><code>"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"`
{'ids': [' "MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ']}
</code></pre>
... | 3 | 2016-09-11T12:25:28Z | 39,436,095 | <p><code>reclist</code> is a string not an iterable, you can use <code>ast.literal_eval</code> in order to convert it to a tuple directly:</p>
<pre><code>In [60]: import ast
In [61]: reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""
In [62]: ast.literal_eval(reclist)
Out[62]: ('MOBEEVHDBBYSQFC8', 'MOBE9J587QGMXBB7... | 1 | 2016-09-11T12:29:25Z | [
"python",
"dictionary"
] |
Python: Value of dictionary is list of strings | 39,436,055 | <pre><code>reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""
print reclist
data= {
"ids": [
reclist #"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"
]
}
print data
</code></pre>
<p>Output: `</p>
<pre><code>"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"`
{'ids': [' "MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ']}
</code></pre>
... | 3 | 2016-09-11T12:25:28Z | 39,436,241 | <p>You can also <code>split()</code> and <code>strip()</code> the double quotes:</p>
<pre><code>>>> reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""
>>> [item.strip('"') for item in reclist.split(",")]
['MOBEEVHDBBYSQFC8', 'MOBE9J587QGMXBB7']
</code></pre>
| 1 | 2016-09-11T12:45:30Z | [
"python",
"dictionary"
] |
TypeError: unorderable types: str() <= int() error | 39,436,070 | <p>Could you guys help me out with finding the wrong part of the code? I tried some things and searched on this site, but I couldn't find the solution.. If you guys know something, please let it know :D</p>
<pre><code>print("Uw formule is ax**2+bx+c")
a= float(input("Geef getal a:" ))
b= float(input("Geef getal b:" ))... | 0 | 2016-09-11T12:26:58Z | 39,436,093 | <p>At the end of your for loop you reassign <code>D</code> to the result of calling <code>format</code>. That will always make it a string.</p>
<p>I'm not sure why you're doing that, but you should remove that line.</p>
| 0 | 2016-09-11T12:29:15Z | [
"python"
] |
TypeError: unorderable types: str() <= int() error | 39,436,070 | <p>Could you guys help me out with finding the wrong part of the code? I tried some things and searched on this site, but I couldn't find the solution.. If you guys know something, please let it know :D</p>
<pre><code>print("Uw formule is ax**2+bx+c")
a= float(input("Geef getal a:" ))
b= float(input("Geef getal b:" ))... | 0 | 2016-09-11T12:26:58Z | 39,436,154 | <p>Thanks! I solved it with:</p>
<pre><code>print("Uw formule is ax**2+bx+c")
a= float(input("Geef getal a:" ))
b= float(input("Geef getal b:" ))
c= float(input("Geef getal c:" ))
D=b**2-4*a*c
while (D<=0) or (a==0):
print("Voer nieuwe getallen in, de uitkomst is niet te berekenen")
a= float(input... | 0 | 2016-09-11T12:35:19Z | [
"python"
] |
I can't change the image using label.configure | 39,436,088 | <p>I am trying to create a GUI in which I can process images, so I have to change the default image to the one chosen by the browse button.
The default image disappears but the new image doesn't appear. Help Please!
Here is my code:</p>
<pre><code>from Tkinter import *
from tkFileDialog import askopenfilename
import ... | 0 | 2016-09-11T12:29:07Z | 39,436,552 | <p>Change <code>self.photo = PhotoImage(path)</code> to <code>self.photo = PhotoImage(file=path)</code>. The <code>file</code> parameter is required to define an image path in <a href="http://effbot.org/tkinterbook/photoimage.htm" rel="nofollow"><code>PhotoImage</code> class</a>.</p>
| 0 | 2016-09-11T13:22:24Z | [
"python",
"tkinter",
"photoimage"
] |
Python Tkinter TTK Treeview Find Selected Items' ID Or Row | 39,436,098 | <p>I am creating a program which uses a TTK Treeview as an item hierarchy.
So far, the user is able to insert their own values into the tree, but I need to have a check running for when the user clicks on an item in the tree. I need the check to find the selected items ID and return it.</p>
<p>The check I have running... | -2 | 2016-09-11T12:29:35Z | 39,436,297 | <p>You can call the <a href="https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview.selection" rel="nofollow">selection</a> method to get a list of all selected items:</p>
<pre><code>selected_items = self.tree.selection()
</code></pre>
| 0 | 2016-09-11T12:52:09Z | [
"python",
"tkinter",
"treeview",
"ttk"
] |
Pyparsing pulp error | 39,436,329 | <p>When I try installing ManPy I got the following error message:</p>
<blockquote>
<p>error: pyparsing 2.1.4 is installed but pyparsing<=1.9.9 is required
by set(['pulp'])</p>
</blockquote>
<p>I checked the Pyparsing setup, but I didn't find the solution.</p>
| 0 | 2016-09-11T12:56:36Z | 39,437,610 | <p>This is actually an error in the setup.py of PuLP (which apparently is used by ManPy):</p>
<pre><code>#hack because pyparsing made version 2 python 3 specific
if sys.version_info[0] <= 2:
pyparsing_ver = 'pyparsing<=1.9.9'
else:
pyparsing_ver = 'pyparsing>=2.0.0'
</code></pre>
<p>As of pyparsing 2... | 0 | 2016-09-11T15:20:10Z | [
"python",
"pyparsing",
"pulp"
] |
Having trouble playing music using IPython | 39,436,524 | <p>I have the lines of code</p>
<pre><code>import IPython
IPython.display.Audio(url="http://www.1happybirthday.com/PlaySong/Anna",embed=True,autoplay=True)
</code></pre>
<p>And I'm not really sure what's wrong. I am using try.jupyter.org to run my code, and this is within if statements. The notebook is also t... | 0 | 2016-09-11T13:18:45Z | 39,457,223 | <p>First you should try it without the <code>if</code> statement. Just the two lines you mention above. This will still not work, because your URL does point to an HTML page instead of a sound file. In your case the correct URL would be <code>'https://s3-us-west-2.amazonaws.com/1hbcf/Anna.mp3'</code>.</p>
<p>The <code... | 1 | 2016-09-12T19:16:02Z | [
"python",
"audio",
"ipython",
"jupyter-notebook"
] |
Issue in running hive udf written in python | 39,436,537 | <p>I have written a simple hive udf in python, but when I run it in hive shell, it throws below error: </p>
<pre><code>Diagnostic Messages for this Task:
Error: java.lang.RuntimeException: Hive Runtime Error while closing operators
at org.apache.hadoop.hive.ql.exec.mr.ExecMapper.close(ExecMapper.java:260)
... | 0 | 2016-09-11T13:20:05Z | 39,436,936 | <p>This solved the problem for others cases like yours: <a href="http://themrmax.github.io/2015/07/16/a-python-nltk-wordnet-udf-in-hive.html" rel="nofollow">here</a> </p>
<p>They are using a try catch block into the function, did you do the same? </p>
| 0 | 2016-09-11T14:09:41Z | [
"python",
"hive"
] |
Encoding issue when writing to CSV file in Python | 39,436,560 | <p>I have some encoding issue while writing an array to CSV.</p>
<p>Code:</p>
<pre><code>import csv
a = [u'eNTfxfwc', 'Pushkar', 'Waghulde', '[email protected]', 'Los Angeles', '', 'UNITED STATES', '2652 Ellendale Pl # 9', '', 'Los Angeles, UNITED STATES', u'90007', u'', u'(213)458-2091', u'None', u'', u'imp... | -1 | 2016-09-11T13:22:58Z | 39,437,076 | <p>Just encode the elements in a before writing them</p>
<pre><code>a = [i.encode('utf-8') for i in a]
f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',',lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
</code></pre>
| -1 | 2016-09-11T14:26:33Z | [
"python",
"csv",
"encoding"
] |
Lowest common ancestor, how to build the tree from command line input? | 39,436,570 | <pre><code># Python program to find LCA of n1 and n2 using one
# traversal of Binary tree
# def build_graph():
# n = input()
# ex1, ex2 = raw_input(), raw_input()
# d = {}
# for i in xrange(n-1):
# e1, e2 = map(str, raw_input().split())
# if e1 not in d:
# node = Node(e1)
#... | 2 | 2016-09-11T13:24:13Z | 39,437,136 | <p>I'd recommend you use a dictionary or some other way to keep track of the members of the tree. </p>
<p>According to the way you build the tree, this is what I came up with: When you parse each ordered pair, </p>
<ul>
<li>Check whether the parent is in the tree or not. If the parent is present, check if there alrea... | 1 | 2016-09-11T14:33:30Z | [
"python",
"algorithm",
"tree",
"binary-tree",
"lowest-common-ancestor"
] |
AWS Lambda subprocess OSError: [Errno 2] No such file or directory | 39,436,579 | <p>I'm trying to create a lambda function that makes collection of thumbnails from a video on amazon s3 using ffmpeg. ffmpeg binary is included into fuction package.</p>
<p>function code:</p>
<pre><code># -*- coding: utf-8 -*-
import stat
import shutil
import boto3
import logging
import subprocess as sp
import os
im... | 0 | 2016-09-11T13:25:30Z | 39,437,269 | <p>The problem is not because of <code>ffmpeg</code>. The error is for <code>sudo</code> not found. Lambda instances do not come with <code>sudo</code>. Why do you need <code>sudo</code>? Can you print whatever you pass to <code>sp.call()</code>?</p>
| 3 | 2016-09-11T14:46:42Z | [
"python",
"amazon-web-services",
"ffmpeg",
"aws-lambda"
] |
How can I get uploaded text file in view through Django? | 39,436,612 | <p>I'm now making web app. This app gets text file having not-organized data and organize it. I'm now using Django in Python3.</p>
<p>I already made form data in templates.</p>
<ul>
<li>Teplates</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="s... | 0 | 2016-09-11T13:29:43Z | 39,437,140 | <p><code>request.FILES['file']</code> is already a file handler, so you don't have to open it. Just use <code>request.FILES['file'].read()</code>.</p>
| 1 | 2016-09-11T14:34:16Z | [
"python",
"django",
"python-3.x"
] |
Wrap a function that takes a struct of optional arguments using kwargs | 39,436,632 | <p>In C it's not uncommon to see a function that takes a lot of inputs, many/most of which are optional group these up in a struct to make the interface cleaner for developers. (Even though you should be able to rely on a compiler accepting <a href="http://stackoverflow.com/questions/9034787/function-parameters-max-num... | 1 | 2016-09-11T13:32:49Z | 39,436,633 | <p>Normally in Python the way to modify function arguments and return values is to use a decorator. As a starting point I sketched out the following decorator, which solves the problem:</p>
<pre><code>def StructArgs(ty):
def wrap(f):
def _wrapper(*args, **kwargs):
arg=(ty(),) if len(kwargs) else tuple()
... | 2 | 2016-09-11T13:32:49Z | [
"python",
"c",
"swig"
] |
Numba Lowering error when iterating over 3D array | 39,436,719 | <p>I have a 3D array (n, 3,2) for holding groups of three 2D vectors and I'm iterating over them something like this:</p>
<pre><code>import numpy as np
for x in np.zeros((n,2,3), dtype=np.float64):
print(x) # for example
</code></pre>
<p>With normal numpy this works fine but when I wrap the function in question ... | 0 | 2016-09-11T13:44:28Z | 39,437,130 | <p>It looks like this is just not implemented. </p>
<pre><code>In [13]: @numba.njit
...: def f(v):
...: for x in v:
...: y = x
...: return y
In [14]: f(np.zeros((2,2,2)))
NotImplementedError Traceback (most recent call last)
<snip>
LoweringError: Failed at n... | 1 | 2016-09-11T14:32:59Z | [
"python",
"numpy",
"numba"
] |
Need to make code all modular. Goal is to calculate gross and bonus pay contributions based on user input | 39,436,720 | <pre><code>#global variable
CONTRIBUTION_RATE = 0.05
def main():
#if these are set to 0 they do not calculate contribution but it does run the program.
grossPay = 0
bonusPay = 0
#gets gross pay from input
GetGrossPay(grossPay)
#gets bonus pay from input
GetBonusPay(bonusPay)
#ta... | 1 | 2016-09-11T13:44:35Z | 39,436,954 | <p>Should be what you're looking for. Try this</p>
<pre><code>#global variable
CONTRIBUTION_RATE = 0.05
def main():
gross = GetGrossPay()
bonus = GetBonusPay()
sum = GetSumContribution(gross, bonus)
showGrossPayContrib(gross)
showBonusContrib(bonus)
showSumContrib(sum)
def GetGrossPay():
... | 0 | 2016-09-11T14:11:45Z | [
"python",
"python-3.x",
"module",
"global-variables"
] |
When accessing single element from list of float values, value get's rounded off | 39,436,802 | <p>My list contains values which are converted to float :</p>
<pre><code>time = [1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]
</code></pre>
<p>But when i do <code>time[0]</code>, the value gets rounded off to 2 decimal places like <cod... | 2 | 2016-09-11T13:53:16Z | 39,436,862 | <p>The list itself doesn't have rounded values. It is the default "print" that shows rounding:</p>
<pre><code>>>> time = [1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]
>>> time[0]
1472120400.107
>>> print time... | 4 | 2016-09-11T14:01:33Z | [
"python",
"python-2.7"
] |
Custom create method to prevent duplicates | 39,436,853 | <p>I would like to add some logic to my serializer.py.</p>
<p>Currently it creates duplicate tags (giving a new ID to the item, but often it will match a tag name already).</p>
<h1>In plain english</h1>
<pre><code>if exists:
# Find the PK that matches the "name" field
# "link" the key with Movie Class item
els... | 0 | 2016-09-11T14:00:28Z | 39,437,063 | <p>This will probably solve your issue:</p>
<pre><code>tag = Tag.objects.get_or_create(**tag_data)[0]
movie.tag.add(tag)
</code></pre>
<p><code>get_or_create</code> function returns tuple <code>(instance, created)</code>, so you have to get <code>instance</code> with <code>[0]</code>.</p>
<p>So the full code is:</p>... | 1 | 2016-09-11T14:25:22Z | [
"python",
"django",
"django-rest-framework"
] |
Making a list containing string sentences a 2 dimensional list | 39,437,036 | <p>In python 3, I have a list where each element of this list is a sentence string, for example</p>
<pre><code>list = ["the dog ate a bone", "the cat is fat"]
</code></pre>
<p>How do I split each sentence string into an individual list while keeping everything in the individual list, making it a 2 dimensional list <... | 0 | 2016-09-11T14:22:21Z | 39,437,735 | <p>You can simply do the following.Use split() method on each of the value and reassign the value of every index with new comma seperated text</p>
<pre><code>mylist=['the dog ate a bone', 'the cat is fat']
print(mylist)
def make_two_dimensional(list):
counter=0
for value in list:
list[counter]= value... | 0 | 2016-09-11T15:33:27Z | [
"python",
"list",
"dimensional"
] |
Making a list containing string sentences a 2 dimensional list | 39,437,036 | <p>In python 3, I have a list where each element of this list is a sentence string, for example</p>
<pre><code>list = ["the dog ate a bone", "the cat is fat"]
</code></pre>
<p>How do I split each sentence string into an individual list while keeping everything in the individual list, making it a 2 dimensional list <... | 0 | 2016-09-11T14:22:21Z | 39,438,208 | <p>You can use list comprehension:</p>
<pre><code>list2 = [s.split(' ') for s in list]
</code></pre>
| 2 | 2016-09-11T16:25:23Z | [
"python",
"list",
"dimensional"
] |
Supporting matplotlib for both python 2 and python 3 on Mac OS X | 39,437,057 | <p>We're building code that we want to run on both Python 2 & 3. It uses matplotlib. My local machine runs OS X Yosemite. </p>
<p>The <a href="http://matplotlib.org/faq/installing_faq.html#os-x-notes" rel="nofollow">matplotlib installation documentation</a> provides instructions for both python 2 & 3, but impl... | 0 | 2016-09-11T14:24:45Z | 39,455,644 | <p>This appears to work:</p>
<blockquote>
<p>python 3: install <a href="https://www.python.org/ftp/python/3.5.2/python-3.5.2-macosx10.6.pkg" rel="nofollow">https://www.python.org/ftp/python/3.5.2/python-3.5.2-macosx10.6.pkg</a></p>
</blockquote>
<pre><code>curl -O https://bootstrap.pypa.io/get-pip.py
python3 get-pi... | 0 | 2016-09-12T17:27:00Z | [
"python",
"osx",
"matplotlib"
] |
Supporting matplotlib for both python 2 and python 3 on Mac OS X | 39,437,057 | <p>We're building code that we want to run on both Python 2 & 3. It uses matplotlib. My local machine runs OS X Yosemite. </p>
<p>The <a href="http://matplotlib.org/faq/installing_faq.html#os-x-notes" rel="nofollow">matplotlib installation documentation</a> provides instructions for both python 2 & 3, but impl... | 0 | 2016-09-11T14:24:45Z | 39,455,725 | <p>I too find virtualenvs annoying for this sort of thing, and have run into strange issues on OSX virutalenvs with matplotlib in particular.
But there is a really nice tool for supporting parallel installations of different package & python versions: <code>conda</code>. It will manage parallel environments with an... | 1 | 2016-09-12T17:33:18Z | [
"python",
"osx",
"matplotlib"
] |
How to use chrome extensions with Selenium Webdriver | 39,437,064 | <p>I want to use one of chrome's extensions inside my python code, how could I do this?
Is it possible?</p>
| 0 | 2016-09-11T14:25:26Z | 39,447,351 | <p>I know the solution in Java, hope it will provide you a hint how it can be done in python.</p>
<pre><code>ChromeOptions options = new ChromeOptions();
String browserExtension = "path/to/the/extension/name.crx";
options.addExtensions(new File(browserExtension));
WebDriver driver = new ChromeDriver(options);
</code><... | 1 | 2016-09-12T09:36:13Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
Using proxy(private) in PhantomJs with python | 39,437,106 | <p>I am using a private poxy IP with PhatomJS and Python, My code below</p>
<pre><code>phantomjs_path = r"phantomjs.exe"
service_args = [
'--proxy=MY Private IP',
'--proxy-type=socks5',
'--proxy-auth=username:password', # I enter real user name and pass here
]
browser = webdriver.PhantomJS(executable_... | 0 | 2016-09-11T14:30:20Z | 39,447,962 | <p>The port number needs to be added here,</p>
<pre><code>service_args = [
'--proxy=MY Private IP:port', # See the difference
'--proxy-type=socks5',
'--proxy-auth=username:password', # I enter real user name and pass here
]
</code></pre>
| 0 | 2016-09-12T10:10:41Z | [
"python",
"selenium",
"phantomjs"
] |
Curve_fitting data (I'm close to the params values, but curve_fit says optimal parameters not found) | 39,437,133 | <p>I'm trying to fit the data in <a href="http://www.filedropper.com/aluminio33920umaire" rel="nofollow">this file</a> with <code>curve_fit</code> from scipy in Python. The file contains data points of temperature vs time in celsius and milliseconds. I convert them to kelvin and seconds:</p>
<pre><code>thefile = open(... | 2 | 2016-09-11T14:33:15Z | 39,437,586 | <p>Your dulong function is highly sensitive to changes in n because of its <code>n^n</code> dependancy. You might want set bounds for it or even keep it as a constant if thats good enough for you.</p>
<p>Also, if you are dealing with sufficient small timescales you could consider using a approximating function. If not... | 2 | 2016-09-11T15:17:31Z | [
"python",
"scipy",
"curve-fitting"
] |
Curve_fitting data (I'm close to the params values, but curve_fit says optimal parameters not found) | 39,437,133 | <p>I'm trying to fit the data in <a href="http://www.filedropper.com/aluminio33920umaire" rel="nofollow">this file</a> with <code>curve_fit</code> from scipy in Python. The file contains data points of temperature vs time in celsius and milliseconds. I convert them to kelvin and seconds:</p>
<pre><code>thefile = open(... | 2 | 2016-09-11T14:33:15Z | 39,437,625 | <p>When I call <code>curve_fit</code> using the <code>dulong</code> function I get the following warning:</p>
<blockquote>
<p><code>RuntimeWarning: invalid value encountered in power</code></p>
</blockquote>
<p>This suggests that, as <code>curve_fit</code> tests various values of the parameters, evaluation of <code... | 2 | 2016-09-11T15:21:59Z | [
"python",
"scipy",
"curve-fitting"
] |
Curve_fitting data (I'm close to the params values, but curve_fit says optimal parameters not found) | 39,437,133 | <p>I'm trying to fit the data in <a href="http://www.filedropper.com/aluminio33920umaire" rel="nofollow">this file</a> with <code>curve_fit</code> from scipy in Python. The file contains data points of temperature vs time in celsius and milliseconds. I convert them to kelvin and seconds:</p>
<pre><code>thefile = open(... | 2 | 2016-09-11T14:33:15Z | 39,438,046 | <p>Since i can't post comments yet, i will instead post another answer as reply to your comment: The big error from the third parameter is likely due to the algorithm not being allowed to assign it a value above 10000. Adjust your bounds and it should work.</p>
| 0 | 2016-09-11T16:05:36Z | [
"python",
"scipy",
"curve-fitting"
] |
IndexError after running program multiple times | 39,437,142 | <p>After running my program that generates passwords multiple times I get an IndexError: list Index out of range. I am not sure what is causing the problem</p>
<pre><code>import string
import random
def random_pass(length):
alphabet = list(string.ascii_letters + string.digits + string.punctuation)
password = ... | -1 | 2016-09-11T14:34:25Z | 39,437,167 | <p><code>random.randint</code> can generate the <em>end</em> value as well; you'd need to use <code>random.randrange</code> to generate random numbers in the range that includes the start value and <em>excludes</em> the end.</p>
| 2 | 2016-09-11T14:37:39Z | [
"python"
] |
IndexError after running program multiple times | 39,437,142 | <p>After running my program that generates passwords multiple times I get an IndexError: list Index out of range. I am not sure what is causing the problem</p>
<pre><code>import string
import random
def random_pass(length):
alphabet = list(string.ascii_letters + string.digits + string.punctuation)
password = ... | -1 | 2016-09-11T14:34:25Z | 39,439,715 | <p>Antti Haapala's answers your question but I see a few things that could be improved in your code. The idea is to make your code clearer.</p>
<p>First of all here's my version of your code:</p>
<pre><code>import string
import random
alphabet = string.ascii_letters + string.digits + string.punctuation
def random_p... | 0 | 2016-09-11T19:12:05Z | [
"python"
] |
pandas new dataframe based on number of occurences | 39,437,171 | <p>I want to create a new dataframe that only contains the rows that occurred the most:</p>
<p>My code is below:</p>
<pre><code>import pandas as pd
f1=pd.read_csv('FILE1.csv')
f2=pd.read_csv('FILE2.csv')
df_all = f2.merge(f1, how='left', on='Symbol')
df_sort = df_all.sort_values(by=['Symbol','Date'], ascending=[True... | 1 | 2016-09-11T14:37:47Z | 39,437,306 | <p>You can find out the <code>Symbol</code> with maximum group size from <code>df_cnt</code> and filter rows from <code>df_sort</code>:</p>
<pre><code>df_sort[df_sort.Symbol.isin(df_cnt.index[df_cnt == df_cnt.max()])]
# Date Symbol ClosingPrice Weight
# 8 3/1/2010 AAPL 85.07 0.4
# 9 3/2/2010... | 2 | 2016-09-11T14:50:45Z | [
"python",
"pandas",
"dataframe",
"slice"
] |
pandas new dataframe based on number of occurences | 39,437,171 | <p>I want to create a new dataframe that only contains the rows that occurred the most:</p>
<p>My code is below:</p>
<pre><code>import pandas as pd
f1=pd.read_csv('FILE1.csv')
f2=pd.read_csv('FILE2.csv')
df_all = f2.merge(f1, how='left', on='Symbol')
df_sort = df_all.sort_values(by=['Symbol','Date'], ascending=[True... | 1 | 2016-09-11T14:37:47Z | 39,437,401 | <p>You could try</p>
<pre><code> df_sort[df_sort.Symbol.isin(df_cnt[df_cnt >= df_cnt.max()].index)]
</code></pre>
<ul>
<li><p><code>df_cnt.max()</code> is the maximum value of <code>df_cnt</code>.</p></li>
<li><p><code>df_cnt[df_cnt >= df_cnt.max()].index</code> is the index of all the items whose count was at ... | 1 | 2016-09-11T15:00:30Z | [
"python",
"pandas",
"dataframe",
"slice"
] |
pandas new dataframe based on number of occurences | 39,437,171 | <p>I want to create a new dataframe that only contains the rows that occurred the most:</p>
<p>My code is below:</p>
<pre><code>import pandas as pd
f1=pd.read_csv('FILE1.csv')
f2=pd.read_csv('FILE2.csv')
df_all = f2.merge(f1, how='left', on='Symbol')
df_sort = df_all.sort_values(by=['Symbol','Date'], ascending=[True... | 1 | 2016-09-11T14:37:47Z | 39,437,464 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> for this purpose.</p>
<pre><code>df_sort[df_sort['Symbol'].map(df_cnt==df_cnt.max())]
Date Symbol ClosingPrice Weight
8 3/1/2010 AAPL 85.07 0.4
9 3/2/... | 1 | 2016-09-11T15:06:32Z | [
"python",
"pandas",
"dataframe",
"slice"
] |
How to display parent model with its child model in a template | 39,437,207 | <p>Here is my structure:</p>
<p><strong>model.py</strong></p>
<pre><code>class Doctor(models.Model):
name = models.CharField(max_length=50)
room_no = models.IntegerField()
floor_no = models.IntegerField()
contact_no = models.CharField(max_length=50, blank=True, null=True)
notes = models.CharField(... | 0 | 2016-09-11T14:41:02Z | 39,437,499 | <p>You have to render your structure with</p>
<pre><code>doctors = {}
for spec in Specialization.objects.all():
doctors[spec.title] = [doc_spec.doc.name for doc_spec in DoctorSpecialization.objects.filter(spec=spec)]
</code></pre>
<p>then pass this dict to template:</p>
<pre><code>from django.template import Con... | 0 | 2016-09-11T15:09:40Z | [
"python",
"django",
"django-models"
] |
What purpose does [0] serve in numpy.where(y_euler<0.0)[0] | 39,437,226 | <p>Also what is the difference between this:</p>
<pre><code>idx_negative_euler = numpy.where(y_euler<0.0)[0]
</code></pre>
<p>and this:</p>
<pre><code>idx_negative_euler = numpy.where(y_euler<0.0)[0][0]
</code></pre>
<p>I realize that this returns an array of indices where the array <code>y_euler</code> is ne... | -3 | 2016-09-11T14:42:41Z | 39,437,744 | <p><code>[0]</code> means "get the first item of the sequence." For example if you had this list:</p>
<pre><code>x = [5, 7, 9]
</code></pre>
<p>Then <code>x[0]</code> would be the first item of that sequence: 5.</p>
<p><code>numpy.where()</code> returns a sequence. Putting <code>[0]</code> on the end of that expre... | 0 | 2016-09-11T15:34:08Z | [
"python",
"arrays",
"numpy"
] |
What purpose does [0] serve in numpy.where(y_euler<0.0)[0] | 39,437,226 | <p>Also what is the difference between this:</p>
<pre><code>idx_negative_euler = numpy.where(y_euler<0.0)[0]
</code></pre>
<p>and this:</p>
<pre><code>idx_negative_euler = numpy.where(y_euler<0.0)[0][0]
</code></pre>
<p>I realize that this returns an array of indices where the array <code>y_euler</code> is ne... | -3 | 2016-09-11T14:42:41Z | 39,438,221 | <p>Make a simple 1d array:</p>
<pre><code>In [60]: x=np.array([0,1,-1,2,-1,0])
</code></pre>
<p>Where returns a tuple <code>(...,)</code> of arrays, one for each dimension:</p>
<pre><code>In [61]: np.where(x<0)
Out[61]: (array([2, 4], dtype=int32),)
</code></pre>
<p>pull the first (here only) element from the tu... | 0 | 2016-09-11T16:26:44Z | [
"python",
"arrays",
"numpy"
] |
How do you extract the floats from the elements in a python list? | 39,437,366 | <p>I am using BeautifulSoup4 to build a script that does financial calculations. I have successfully extracted data to a list, but only need the float numbers from the elements.</p>
<p>For Example:</p>
<pre><code>Volume = soup.find_all('td', {'class':'text-success'})
print (Volume)
</code></pre>
<p>This gives me th... | 2 | 2016-09-11T14:56:32Z | 39,437,400 | <p>You can do</p>
<pre><code>>>> import re
>>> re.findall("\d+\.\d+", yourString)
['1.3', '5.49', '1.3']
>>>
</code></pre>
<p>Then to convert to floats</p>
<pre><code>>>> [float(x) for x in re.findall("\d+\.\d+", yourString)]
[1.3, 5.49, 1.3]
>>>
</code></pre>
| 1 | 2016-09-11T15:00:30Z | [
"python",
"regex",
"beautifulsoup"
] |
How do you extract the floats from the elements in a python list? | 39,437,366 | <p>I am using BeautifulSoup4 to build a script that does financial calculations. I have successfully extracted data to a list, but only need the float numbers from the elements.</p>
<p>For Example:</p>
<pre><code>Volume = soup.find_all('td', {'class':'text-success'})
print (Volume)
</code></pre>
<p>This gives me th... | 2 | 2016-09-11T14:56:32Z | 39,437,404 | <p>You can find the first text node inside every <code>td</code>, split it by space, get the first item and convert it to <code>float</code> via <code>float()</code> - the <code>+</code> would be handled automatically:</p>
<pre><code>from bs4 import BeautifulSoup
data = """
<table>
<tr>
<td... | 2 | 2016-09-11T15:00:54Z | [
"python",
"regex",
"beautifulsoup"
] |
Pandas Dataframe Transpose | 39,437,387 | <p>I have tried to find something that could help me but I couldn't. I'd appreciate if someone could link me to it, if my question is already answered.</p>
<p>I have a pandas dataframe that has row-wise features. For example:</p>
<pre><code> Patient_ID Feature_Id Feature_Value
0 3 10 ... | 1 | 2016-09-11T14:59:00Z | 39,437,442 | <p>You could try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pd.pivot_table</code></a></p>
<pre><code>In [16]: pd.pivot_table(df, index='Patient_ID', values='Feature_Value', columns='Feature_ID')
Out[16]:
Feature_ID 10 50 60
Patient_ID ... | 1 | 2016-09-11T15:04:37Z | [
"python",
"pandas"
] |
IndexError: string index out of range? | 39,437,396 | <p>I keep getting an <code>IndexError: string index out of range</code> exception on the following code and I cannot figure out why.</p>
<p>I am supposed to solve the following problem recursively.</p>
<blockquote>
<p>Finally, write <code>transcribe( S )</code>. Here is its description:</p>
<p>In an incredible... | 1 | 2016-09-11T14:59:46Z | 39,437,408 | <p>Trying to index with <code>[0]</code> into an <em>empty string</em> raises an <code>IndexError</code>.</p>
<p>You need to test if the string is empty <em>first</em>, as eventually <code>S[1:]</code> will pass an empty sting into <code>transcribe()</code>:</p>
<pre><code>if not S:
return ''
</code></pre>
<p>Yo... | 3 | 2016-09-11T15:01:21Z | [
"python",
"python-2.7"
] |
IndexError: string index out of range? | 39,437,396 | <p>I keep getting an <code>IndexError: string index out of range</code> exception on the following code and I cannot figure out why.</p>
<p>I am supposed to solve the following problem recursively.</p>
<blockquote>
<p>Finally, write <code>transcribe( S )</code>. Here is its description:</p>
<p>In an incredible... | 1 | 2016-09-11T14:59:46Z | 39,438,384 | <p>Here's something a bit closer to your original:</p>
<pre><code>def transcribe( S ):
if S == '':
return ''
elif S[0] == 'A':
return 'U' + transcribe( S[1:] )
elif S[0] == 'C':
return 'G' + transcribe( S[1:] )
elif S[0] == 'G':
return 'C' + transcribe( S[1:] )
elif ... | 0 | 2016-09-11T16:47:05Z | [
"python",
"python-2.7"
] |
Parameter dependencies in Python - can't make it work | 39,437,461 | <p>I am trying to add a parameter dependency to my script. The idea is that <em>--clone</em> argument will require non-empty <em>--gituser</em>.</p>
<p>After perusing <a href="http://stackoverflow.com/questions/21879657/argparse-argument-dependency">this example</a>, I tried the following</p>
<pre><code>In [93]: clas... | 1 | 2016-09-11T15:06:16Z | 39,438,351 | <p>This kind of inter argument dependency is easier to implement <strong>after</strong> parsing.</p>
<pre><code>args = parser.parse_args()
if not namespace.git_user and namespace.clone:
parser.error('"--clone" requires legal git user')
</code></pre>
<p>At that point, both <code>git_user</code> and <code>clone</co... | 3 | 2016-09-11T16:42:09Z | [
"python",
"argparse"
] |
Get rows from DataFrame based on array of indices | 39,437,485 | <p>I have an array with numbers which corresponds to the row numbers that need to be selected from a DataFrame.
For example, <code>arr = np.array([0,0,1,1])</code> and the DataFrame is seen below. <code>arr</code> is the row number and not the index. </p>
<pre><code>Index A B C D
3 10 0 0 0
4 ... | 0 | 2016-09-11T15:08:38Z | 39,437,540 | <p>You can use <code>iloc</code> with integer indexing:</p>
<pre><code>df.iloc[[0,0,1,1], :] # or df.iloc[arr, :]
# A B C D
#Index
#3 10 0 0 0
#3 10 0 0 0
#4 5 2 0 0
#4 5 2 0 0
</code></pre>
| 2 | 2016-09-11T15:13:10Z | [
"python",
"arrays",
"pandas",
"dataframe"
] |
How to count rows efficiently with one pass over the dataframe | 39,437,504 | <p>I have a dataframe made of strings like this:</p>
<pre><code>ID_0 ID_1
g k
a h
c i
j e
d i
i h
b b
d d
i a
d h
</code></pre>
<p>For each pair of strings I can count how many rows have either string in them as follows.</p>
<pre><code>import pandas as pd
import itertools
df... | 2 | 2016-09-11T15:10:02Z | 39,452,228 | <p>Consider a <code>DataFrame.apply()</code> method:</p>
<pre><code>from io import StringIO
import pandas as pd
data = '''ID_0,ID_1
g,k
a,h
c,i
j,e
d,i
i,h
b,b
d,d
i,a
d,h
'''
df = pd.read_csv(StringIO(data))
def f(row):
ser = len(df[(df['ID_0'] == row['ID_0']) | (df['ID_1'] == row['ID_0'])|
... | 1 | 2016-09-12T14:04:04Z | [
"python",
"pandas"
] |
How to count rows efficiently with one pass over the dataframe | 39,437,504 | <p>I have a dataframe made of strings like this:</p>
<pre><code>ID_0 ID_1
g k
a h
c i
j e
d i
i h
b b
d d
i a
d h
</code></pre>
<p>For each pair of strings I can count how many rows have either string in them as follows.</p>
<pre><code>import pandas as pd
import itertools
df... | 2 | 2016-09-11T15:10:02Z | 39,477,292 | <p>You can get past the row level subiteration by using some clever combinatorics/set theory to do the counting:</p>
<pre><code># Count of individual characters and pairs.
char_count = df['ID_0'].append(df.loc[df['ID_0'] != df['ID_1'], 'ID_1']).value_counts().to_dict()
pair_count = df.groupby(['ID_0', 'ID_1']).size().... | 1 | 2016-09-13T19:07:06Z | [
"python",
"pandas"
] |
sklearn DictVectorizer(sparse=False) with a different default value, Impute a constant | 39,437,687 | <p>I'm building a pipeline that starts with a <code>DictVectorizer</code> that produces a sparse matrix. Specifying <code>sparse=True</code> changes the output from a scipy sparse matrix to a numpy dense matrix which is good, but the next stages in the pipeline complain about <code>NaN</code> values, which our obvious ... | 1 | 2016-09-11T15:28:10Z | 39,438,952 | <p>You could fill the <code>NaNs</code> with 0's after converting your <code>list</code> of <code>dictionaries</code> to a pandas <code>dataframe</code> using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>DF.fillna</code></a> as shown:</p>
<pre><code>... | 1 | 2016-09-11T17:47:17Z | [
"python",
"pandas",
"dataframe",
"machine-learning",
"scikit-learn"
] |
Why does Python 3.5 Return a TypeError and not in Python 2.7 | 39,437,722 | <p>I have a working piece of code in Python 2.7:</p>
<pre><code>def reversetomd5(knownhash):
clean=""
for i in [1,2,3,4,5,7,8,9,10,11,13,14,15,16,18,19,20,21,22,24,25,26,27,28]:
clean+=knownhash[i]
b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
block=[]
for i in xrange(2,24,3):
... | 0 | 2016-09-11T15:31:48Z | 39,438,455 | <p>Got it working correctly. <code>chr()</code> was replaced to return the <code>byte</code> equivalent of the character. Had to change the <code>md5hash</code> initialization to an empty <code>byte</code> variable instead of a <code>string</code>. Then just <code>.decode()</code> it at the end to return a nice stri... | 4 | 2016-09-11T16:55:23Z | [
"python",
"python-2.7",
"python-3.x"
] |
Tabs in txt file vs terminal | 39,437,725 | <p>I'm learning Python at the moment and I'm wondering why tabs look a little different in a txt file than when written to the terminal.</p>
<p>In particular, I've run this script</p>
<pre><code>my_file = open('power.txt', 'w')
print( 'N \t\t2**N\t\t3**N' )
print( '---\t\t----\t\t----' )
my_file.write( 'N \t\t2**N\t\... | 1 | 2016-09-11T15:32:25Z | 39,437,808 | <p>Don't rely on tabs, they're application/console dependent. Use <code>str.format</code> instead (<a href="https://docs.python.org/2/library/string.html" rel="nofollow">format specification</a>)</p>
<p>BTW <code>pow(2,N)</code> is a floating number. You want integral powers: <code>2**N</code></p>
<p>Standalone examp... | 1 | 2016-09-11T15:40:16Z | [
"python",
"file"
] |
Find parent in Binary Search Tree? | 39,437,745 | <p>I wish to find the parent to a node with a certain value in a BST. My node class has attributes item (i.e the value/key), left and right. </p>
<p>The idea to find a parent is like this:<br>
1) If the value (key) does not exist, return None, None<br>
2) If the root is equal to the value (key) then return None, roo... | 1 | 2016-09-11T15:34:28Z | 39,438,029 | <p>As your code currently works, it is impossible that you're turning toward a <code>None</code> left or right child. This is because your code starts with</p>
<pre><code>if not self._exists(key):
return None,None
</code></pre>
<p>So <code>key</code> must exist, and if it must exist, it must exist on the search p... | 1 | 2016-09-11T16:04:07Z | [
"python",
"python-3.x"
] |
Django: How to display author of query of posts? | 39,437,751 | <p>I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.</p>
<p>views.py</p>
<pre><code>class UserProfileView(generic.ListView):
template_name = 'howl/user-profile.html'
context_object_name = 'user_howls'
def get_queryset(self):
... | 0 | 2016-09-11T15:34:50Z | 39,437,797 | <p><code>user_howls</code> is a queryset so it won't have an <code>author</code> attribute, you need to get the author of the iterated object</p>
<pre><code>{% for howl in user_howls %}
<h1>User: {{ howl.author}}</h1>
{% endfor %}
</code></pre>
<p>More to the point though, it doesn't make sense to start f... | 3 | 2016-09-11T15:39:34Z | [
"python",
"django"
] |
Django: How to display author of query of posts? | 39,437,751 | <p>I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.</p>
<p>views.py</p>
<pre><code>class UserProfileView(generic.ListView):
template_name = 'howl/user-profile.html'
context_object_name = 'user_howls'
def get_queryset(self):
... | 0 | 2016-09-11T15:34:50Z | 39,437,975 | <p>Since your queryset is based on the posts belonging to the current user, you can shortcut all of this and just show the user directly:</p>
<pre><code>User: {{ user }}
</code></pre>
| 1 | 2016-09-11T15:58:46Z | [
"python",
"django"
] |
Compare elements in large list of data | 39,437,766 | <p>I've got the question on interview by python recently. The question was:</p>
<blockquote>
<p>we have a large list of pictures in python(as I understood we simply read their content, and then got list of their contents), <code>[...]</code>, this list will occupy 1gb of RAM e.g. What is the best way to compare them... | 0 | 2016-09-11T15:36:03Z | 39,437,863 | <p>Assuming the list contains the raw byte strings of the image contents, one quick and dirty way to weed out possible duplicates is to compare the <em>lengths</em> of the byte strings. Two pictures with unequal length byte strings cannot be duplicates.</p>
<p>Then, for each group of pictures with equal length byte s... | 1 | 2016-09-11T15:47:01Z | [
"python",
"bigdata"
] |
numpy extract 3d cubes from 3d array | 39,437,806 | <p>I would like to extract the 3D cubes (3x3x3) from a boolean 3D array of (180x180x197). This is similar to scipy.ndimage.measurements.label but need to fixed size of (3x3x3).
Is there a fast way of doing this than using for loops. </p>
| 0 | 2016-09-11T15:40:06Z | 39,438,310 | <p>In your special case, I suggest to use ndimage.minimum_filter
Let's say your array is called ``a''. The following:</p>
<pre><code>centers = ndimage.minimum_filter(a, 3, mode="constant")
</code></pre>
<p>will only contain ones where your array contained such box of True's
Then you can use scipy.ndimage.measurements... | 1 | 2016-09-11T16:36:44Z | [
"python",
"numpy",
"multidimensional-array",
"scipy"
] |
numpy extract 3d cubes from 3d array | 39,437,806 | <p>I would like to extract the 3D cubes (3x3x3) from a boolean 3D array of (180x180x197). This is similar to scipy.ndimage.measurements.label but need to fixed size of (3x3x3).
Is there a fast way of doing this than using for loops. </p>
| 0 | 2016-09-11T15:40:06Z | 39,473,100 | <p>Final solution with help from dnalow</p>
<pre><code>get_starting_point = numpy.vectorize(lambda sl: sl.start)
s = ndimage.generate_binary_structure(3,3)
result = []
while True:
centers = ndimage.minimum_filter(b, 3, mode="constant")
labels, num = ndimage.measurements.label(centers, s)
if not num:
... | 0 | 2016-09-13T14:56:05Z | [
"python",
"numpy",
"multidimensional-array",
"scipy"
] |
Interpolating in 3D, plotting with matplotlib - something is going wrong | 39,437,895 | <p>Here is some toy data:</p>
<pre><code>import pandas as pd
import numpy as np
testDF = pd.DataFrame(np.linspace(100.,200.,40).reshape(10,4),
columns=list('abcd'))
</code></pre>
<p>It looks like this (the face is just there for illustration, the top line of each parallelogram is what we are in... | 0 | 2016-09-11T15:50:21Z | 39,438,787 | <p>Ok so I figured it out:</p>
<pre><code>class jointInterpolation(object):
"""
Class for performing various forms of interpolation.
"""
def __init__(self,trajDict):
# Concat dictionary into (n_i x D) for all i in speeds.
D = np.vstack(trajDict.values())
# Grid the data: [time,a... | 0 | 2016-09-11T17:30:13Z | [
"python",
"matplotlib"
] |
Redis pipeline - atomic getting a value of another key value | 39,437,922 | <p>I have a string key named "a" and its value is "b", I also have a hash set which is named "b" and it has multiple values for example:</p>
<pre><code>"a" (value equals to "b")
"b": {
"first_name": "John",
"last_name": "Doe"
}
</code></pre>
<p>is it possible to use a pipeline so given the key "a" I w... | 2 | 2016-09-11T15:52:57Z | 39,438,427 | <p>Pipeline is an optimization for sending multiple operations. It doesn't guarantee atomicity and the replies are available only after the pipeline is executed. That being the case, it would appear that it isn't suitable for what you're trying to do.</p>
<p>IIUC, you want to "dereference" the value in the first key a... | 2 | 2016-09-11T16:52:19Z | [
"python",
"redis"
] |
Redis pipeline - atomic getting a value of another key value | 39,437,922 | <p>I have a string key named "a" and its value is "b", I also have a hash set which is named "b" and it has multiple values for example:</p>
<pre><code>"a" (value equals to "b")
"b": {
"first_name": "John",
"last_name": "Doe"
}
</code></pre>
<p>is it possible to use a pipeline so given the key "a" I w... | 2 | 2016-09-11T15:52:57Z | 39,442,703 | <p>Pipeline won't work, since you must wait until the first <code>get</code> command returns the <em>real key</em>, i.e. <em>b</em>.</p>
<p>Instead, you can achieve it with <code>lua scripts</code>.</p>
<pre><code>local real_key = redis.call('get', KEYS[1])
if real_key then return redis.call('hgetall', real_key) end
... | 3 | 2016-09-12T02:40:08Z | [
"python",
"redis"
] |
what anti-ddos security systems python use for socket TCP connections? | 39,438,003 | <p>More in detail, would like to know:</p>
<ul>
<li>what is the default SYN_RECEIVED timer,</li>
<li>how do i get to change it,</li>
<li>are SYN cookies or SYN caches implemented.</li>
</ul>
<p>I'm about to create a simple special-purpose publically accessible server. i must choose whether using built-in TCP sockets ... | 1 | 2016-09-11T16:01:29Z | 39,438,366 | <p>What you describe are internals of the TCP stack of the operating system. Python just uses this stack via the socket interface. I doubt that any of these settings can be changed specific to the application at all, i.e. these are system wide settings which can only be changed with administrator privileges. </p>
| 1 | 2016-09-11T16:44:02Z | [
"python",
"sockets",
"tcp",
"ddos",
"python-sockets"
] |
How to set the default python path for anaconda? | 39,438,049 | <p>i have installed anaconda on a linux machine.
I noticed that after deactivating the anaconda environment with:</p>
<pre><code>source deactivate
</code></pre>
<p>When running:</p>
<pre><code>which python
</code></pre>
<p>I get:</p>
<pre><code>/home/user/anaconda/bin/python
</code></pre>
<p>Instead of</p>
<pre>... | 1 | 2016-09-11T16:05:53Z | 39,470,093 | <p>The comments somewhat cover the answer to the question, but to clarify:</p>
<p>When you installed Anaconda you must have agreed to have it added to your PATH. You'll want to check in your <code>~/.bash*</code> files and look for any <code>export PATH=</code> lines to check this. So Anaconda is <strong>always</str... | 0 | 2016-09-13T12:27:07Z | [
"python",
"anaconda"
] |
How can I set up data validation to restrict input for 3 fields to number only? | 39,438,107 | <p>I was just introducted to <code>python</code> a few days ago</p>
<p>I need user input for three different fields. How can I restrict user input to numbers for all three questions?</p>
<pre><code>while True:
try:
workinghours = int(raw_input("what is your working hours?"))
except ValueError:
... | 1 | 2016-09-11T16:11:59Z | 39,438,392 | <h3>You're asking the poor soul the same information over and over again, no escape is possible :)</h3>
<p>Apart from the fact that the while loop never ends because there is no <code>break</code>statement anywhere, you are misunderstanding the <code>continue</code> statement. As we can read <a href="http://www.tutori... | 0 | 2016-09-11T16:47:59Z | [
"python",
"validation"
] |
python remove obect from array using condition | 39,438,133 | <p>I have a list of dictionaries like below:</p>
<pre><code>tt = [
{
'property1': 'value1',
'property2': 'value2',
'property3': 'value3'
},
{
'property1': 'value4',
'property2': 'value5',
'property3': 'value6'
},
..............................
.............................
]
</code></pre>... | -3 | 2016-09-11T16:15:20Z | 39,438,364 | <p>This should do it. Fairly straight forward so I won't explain it. Good Luck</p>
<pre><code>def search(dict, key=None, val=None):
c_dict = copy.deepcopy(dict)
for i, n in enumerate(dict):
for k, v in n.iteritems():
if key and val and k == key and val == v:
c_dict[i].pop(k)... | 1 | 2016-09-11T16:43:57Z | [
"python",
"python-3.x"
] |
python remove obect from array using condition | 39,438,133 | <p>I have a list of dictionaries like below:</p>
<pre><code>tt = [
{
'property1': 'value1',
'property2': 'value2',
'property3': 'value3'
},
{
'property1': 'value4',
'property2': 'value5',
'property3': 'value6'
},
..............................
.............................
]
</code></pre>... | -3 | 2016-09-11T16:15:20Z | 39,440,787 | <p>Sorry, I didn't notice that the poster only wanted to remove specific properties. Here's the correct solution:</p>
<pre><code>tt=[{k:v for k,v in i.items() if k != 'property3' or v != 'value6'} for i in tt]
</code></pre>
<p>LazyScripter's solution will delete dictionary elements where the key OR the value OR both ... | 0 | 2016-09-11T21:22:39Z | [
"python",
"python-3.x"
] |
Setting a descriptor in python3.5 asynchronously | 39,438,163 | <p>I can write a descriptor returning a future which could be awaited on.</p>
<pre><code>class AsyncDescriptor:
def __get__(self, obj, cls=None):
# generate some async future here
return future
def __set__(self, obj, value):
# generate some async future here
return future
... | 2 | 2016-09-11T16:18:47Z | 39,438,844 | <p>What you are trying to do is not possible (with Python 3.5).</p>
<p>While it may be sensible for <code>__get__</code> to return a Future, making <code>__set__</code> async is simply not supported by Python 3.5. The return value of <code>__set__</code> is ignored by Python since there is no "return value" of assignm... | 2 | 2016-09-11T17:36:15Z | [
"python",
"python-3.5",
"python-asyncio",
"descriptor"
] |
palindromes of sums less than 30, help to optimize my code | 39,438,191 | <p>On my way of studying Python i stacked on the problem:<br><br>
I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example:
<br> <code>i</code> = 93
<br>93 + 39 = 132
<br>132 + 231 = 363
<br><code>cou... | -2 | 2016-09-11T16:22:42Z | 39,438,346 | <p>This solution has a lot of conversions so it may not be the best solution but regardless it is a solution. have a look at this post he has a seemingly much better method of reversing integers without conversion
<a href="http://stackoverflow.com/a/3806212/1642546">http://stackoverflow.com/a/3806212/1642546</a> </p>
... | 0 | 2016-09-11T16:41:39Z | [
"python",
"optimization"
] |
palindromes of sums less than 30, help to optimize my code | 39,438,191 | <p>On my way of studying Python i stacked on the problem:<br><br>
I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example:
<br> <code>i</code> = 93
<br>93 + 39 = 132
<br>132 + 231 = 363
<br><code>cou... | -2 | 2016-09-11T16:22:42Z | 39,438,805 | <p>I had an error in the code, that made the program almost ifinite :)
<br>The correct code (in my opinion is below)</p>
<pre><code>count_of_palindromes = 0
for i in range(12814):
if (i == int(str(i)[::-1])) != True:
trying = 1
sum = i + int(str(i)[::-1])
while trying <= 50:
... | 0 | 2016-09-11T17:31:49Z | [
"python",
"optimization"
] |
palindromes of sums less than 30, help to optimize my code | 39,438,191 | <p>On my way of studying Python i stacked on the problem:<br><br>
I have to count all numbers from <b>0</b> to <b>130000</b> which are palindromes, but they should be palindromes after sum of the number and its reversed version. For example:
<br> <code>i</code> = 93
<br>93 + 39 = 132
<br>132 + 231 = 363
<br><code>cou... | -2 | 2016-09-11T16:22:42Z | 39,439,019 | <p>Let's tidy your code up a bit first for readability. We'll just take some of the syntax heavy string stuff and encapsulate it.</p>
<pre><code>def reverse(n):
return int(str(n)[::-1])
def is_palindrome(n):
return n == reverse(n)
</code></pre>
<p>That's better. I think your problem is the second nested wh... | 0 | 2016-09-11T17:56:15Z | [
"python",
"optimization"
] |
Python: how could I access tarfile.add()'s 'name' parameter in add()'s filter method? | 39,438,335 | <p>I would like to filter subdirectories (skip them) while creating tar(gz) file with <strong>tarfile</strong> (python 3.4).</p>
<p>Files on disk:</p>
<ul>
<li>/home/myuser/temp/test1/</li>
<li>/home/myuser/temp/test1/home/foo.txt</li>
<li>/home/myuser/temp/test1/thing/bar.jpg</li>
<li>/home/myuser/temp/test1/lemon/j... | 0 | 2016-09-11T16:39:02Z | 39,439,567 | <p>You want to create a general/re-useable function to filter out files given their absolute path name. I understand that filtering on the archive name is not enough since sometimes it would be OK to include a file or not depending on where it is originated.</p>
<p>First, add a parameter to your filter function</p>
<... | 0 | 2016-09-11T18:57:59Z | [
"python",
"filter",
"compression",
"tarfile"
] |
Assigning a set properties to each element of a list python | 39,438,446 | <p>I have a list containing unique items (names if you will) that changes every time I run my script. All of these items have some calculated properties that are modified during the script. For example 'S1' will have pos = 55 and ori = 'R'. I'd like an easy way to access these properties based on their name.</p>
<p>Wh... | 0 | 2016-09-11T16:54:16Z | 39,438,586 | <p>You were having problems with the list, you didn't actually replace the old values with the created instance. I also added a name field so you could keep track of each instance.</p>
<pre><code>class Primer: #contains all properties of a primer
def __init__(self, name):
""" Contains all properties of the... | 0 | 2016-09-11T17:08:22Z | [
"python",
"list",
"class"
] |
Dynamically importing a module in a Celery task | 39,438,504 | <p>Is it possible to dynamically import a module in a Celery task?</p>
<p>For example, I have a module called <code>hello.py</code> in my working directory:</p>
<pre><code>$ cat hello.py
def run():
print('hello world')
</code></pre>
<p>I can import it dynamically with <code>importlib</code>:</p>
<pre><code>$ p... | 0 | 2016-09-11T17:00:24Z | 39,466,034 | <p>Is it possible to dynamically import a module in a Celery task?</p>
<p>Yes. Because I have done it.
When the module is single and not belong to any package, you should add the directory of the module to the sys path.</p>
<blockquote>
<p>sys.path.append('path of the module')</p>
</blockquote>
<p>For example:</p>... | 1 | 2016-09-13T08:59:34Z | [
"python",
"celery",
"python-importlib"
] |
TypeError: fun() missing 1 required positional argument: 'link' | 39,438,509 | <p>I am facing a basic problem and unable to resolve it. I am getting this error</p>
<blockquote>
<p>TypeError: fun() missing 1 required positional argument: 'link'</p>
</blockquote>
<p>If i give <code>self</code> as positional argument in call of <code>fun()</code> as <code>fun(self,glit)</code> then I an getting ... | 0 | 2016-09-11T17:00:52Z | 39,438,528 | <p>[Edit]
Use the <code>__init__</code> function to set variables inside of a class, like</p>
<pre><code>def __init__(self):
self.glit = 'www.google.com'
</code></pre>
<p>Now use <code>self.fun(self.glit)</code></p>
| 0 | 2016-09-11T17:03:05Z | [
"python"
] |
TypeError: fun() missing 1 required positional argument: 'link' | 39,438,509 | <p>I am facing a basic problem and unable to resolve it. I am getting this error</p>
<blockquote>
<p>TypeError: fun() missing 1 required positional argument: 'link'</p>
</blockquote>
<p>If i give <code>self</code> as positional argument in call of <code>fun()</code> as <code>fun(self,glit)</code> then I an getting ... | 0 | 2016-09-11T17:00:52Z | 39,438,594 | <p>The problem is that you are trying to call that code from the class. Class should only contain methods, not your logic. You should call it from outside of the class:</p>
<pre><code>class = myClass()
glit = "http://www.google.com/"
class.fun(glit)
</code></pre>
| 0 | 2016-09-11T17:09:35Z | [
"python"
] |
Removing every nth element from a list until two elements remain in python3 | 39,438,533 | <p>modeling a game of Russian roulette where the contestants stand in a circle.
-every 7th contestant loses until 2 are left alive.</p>
<pre><code>contestants = list(range(1, 51))
dead_men = []
dead_man = 6
while len(contestants) > 2:
if dead_man > len(contestants):
dead_man = dead_man - len(contest... | -1 | 2016-09-11T17:03:21Z | 39,438,576 | <p>I assume you meant <code>contestants</code> instead of <code>soldiers</code> everywhere?</p>
<p>If so, then I think you just need:</p>
<pre><code>while dead_man >= len(contestants):
</code></pre>
<p>(<code>while</code> rather than <code>if</code> in case you need to subtract multiple times, and <code>>=</co... | 0 | 2016-09-11T17:06:57Z | [
"python"
] |
How does Python print a variable that is out of scope | 39,438,573 | <p>I have the following function in Pyton that seems to be working:</p>
<pre><code>def test(self):
x = -1
# why don't I need to initialize y = 0 here?
if (x < 0):
y = 23
return y
</code></pre>
<p>But for this to work why don't I need to initialize variable y? I thought Python had block sco... | 2 | 2016-09-11T17:06:29Z | 39,438,593 | <p>This appears to be a simple misunderstanding about <a href="http://stackoverflow.com/q/291978/674039">scope in Python</a>. Conditional statements don't create a scope. The name <code>y</code> is in the local scope inside the function, because of this statement which is present in the syntax tree:</p>
<pre><code>y... | 4 | 2016-09-11T17:09:25Z | [
"python",
"block"
] |
How does Python print a variable that is out of scope | 39,438,573 | <p>I have the following function in Pyton that seems to be working:</p>
<pre><code>def test(self):
x = -1
# why don't I need to initialize y = 0 here?
if (x < 0):
y = 23
return y
</code></pre>
<p>But for this to work why don't I need to initialize variable y? I thought Python had block sco... | 2 | 2016-09-11T17:06:29Z | 39,438,619 | <p>As in <a href="http://stackoverflow.com/questions/2829528/whats-the-scope-of-a-python-variable-declared-in-an-if-statement">What's the scope of a Python variable declared in an if statement?</a>: "Python variables are scoped to the innermost function or module; control blocks like if and while blocks don't count... | 0 | 2016-09-11T17:11:20Z | [
"python",
"block"
] |
How does Python print a variable that is out of scope | 39,438,573 | <p>I have the following function in Pyton that seems to be working:</p>
<pre><code>def test(self):
x = -1
# why don't I need to initialize y = 0 here?
if (x < 0):
y = 23
return y
</code></pre>
<p>But for this to work why don't I need to initialize variable y? I thought Python had block sco... | 2 | 2016-09-11T17:06:29Z | 39,438,628 | <p>There is actually no block scope in python.
Variables may be local (inside of a function) or global (same for the whole scope of the program).</p>
<p>Once you've defined the variable y inside the 'if' block its value is kept for this specific function until you specifically delete it using the 'del' command, or the... | 1 | 2016-09-11T17:11:57Z | [
"python",
"block"
] |
How does Python print a variable that is out of scope | 39,438,573 | <p>I have the following function in Pyton that seems to be working:</p>
<pre><code>def test(self):
x = -1
# why don't I need to initialize y = 0 here?
if (x < 0):
y = 23
return y
</code></pre>
<p>But for this to work why don't I need to initialize variable y? I thought Python had block sco... | 2 | 2016-09-11T17:06:29Z | 39,440,422 | <p>It seems that you misunderstood this part of <a href="https://docs.python.org/3/reference/executionmodel.html" rel="nofollow" title="4. Execution model">Python's documentation</a>:</p>
<blockquote>
<p>A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a... | 2 | 2016-09-11T20:38:31Z | [
"python",
"block"
] |
Drawing a random number from set of numbers excluding those given in certain sets | 39,438,582 | <p>Suppose I have a two arrays:</p>
<pre><code>import numpy as np
a = np.random.randint(0,10,10)
b = np.random.randint(0,10,10)
</code></pre>
<p>I want to generate another length-10 array whose i-th entry is a random integer drawn from the set (<code>{0...9}</code> <strong>minus</strong> the elements <code>a[i]</code... | 2 | 2016-09-11T17:07:09Z | 39,438,723 | <p>Here is one way:</p>
<pre><code>In [87]: col = np.array((a, b)).T # Or as a better way np.column_stack((a,b)); suggested by @Divakar
In [88]: r = np.arange(10)
In [89]: np.ravel([np.random.choice(np.setdiff1d(r, i), 1) for i in col])
Out[89]: array([7, 8, 8, 6, 6, 8, 6, 5, 5, 6])
</code></pre>
<p>Or as a numpyto... | 2 | 2016-09-11T17:22:53Z | [
"python",
"numpy"
] |
Drawing a random number from set of numbers excluding those given in certain sets | 39,438,582 | <p>Suppose I have a two arrays:</p>
<pre><code>import numpy as np
a = np.random.randint(0,10,10)
b = np.random.randint(0,10,10)
</code></pre>
<p>I want to generate another length-10 array whose i-th entry is a random integer drawn from the set (<code>{0...9}</code> <strong>minus</strong> the elements <code>a[i]</code... | 2 | 2016-09-11T17:07:09Z | 39,438,724 | <p>The <code>np.random.choice</code> function seems to not allow to operate on several sets at once. Thus, you will need some form of loop to make the separate calls to <code>np.random.choice</code> for each element of the output. Given that a loop is needed, I don't think one can do much better than your suggestion ... | 0 | 2016-09-11T17:23:26Z | [
"python",
"numpy"
] |
Namespace questions: Mutable variable doesn't need to be declared as global in function? | 39,438,643 | <p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p>
<p><strong>ex1:</strong></p>
<pre><code>def func1():
a = 1
b.add('b')
a = 0
b = set()
func1()
print(a,b)
</code></pre>
<p>the result is 0 {'b'}</p>
<p>Neither a nor b is declared ... | -1 | 2016-09-11T17:13:19Z | 39,438,767 | <p>When you pass a mutable variable to a function you pass if by reference, which means you're creating another variable (which exist only in the scope of the function) which points to the same object.</p>
<p>Moreover, Python works in a way that you can use and see variables that are in you're outer scope (that's why ... | 0 | 2016-09-11T17:28:09Z | [
"python"
] |
Namespace questions: Mutable variable doesn't need to be declared as global in function? | 39,438,643 | <p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p>
<p><strong>ex1:</strong></p>
<pre><code>def func1():
a = 1
b.add('b')
a = 0
b = set()
func1()
print(a,b)
</code></pre>
<p>the result is 0 {'b'}</p>
<p>Neither a nor b is declared ... | -1 | 2016-09-11T17:13:19Z | 39,438,770 | <p>The following is a simplified answer based on the explanation given in the <a href="https://docs.python.org/2/reference/executionmodel.html" rel="nofollow">Python Language Reference "Naming and Binding"</a> document.</p>
<p>Let's look at your first example:</p>
<pre><code>def func1():
a = 1
b.add('b')
</co... | 0 | 2016-09-11T17:28:31Z | [
"python"
] |
Namespace questions: Mutable variable doesn't need to be declared as global in function? | 39,438,643 | <p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p>
<p><strong>ex1:</strong></p>
<pre><code>def func1():
a = 1
b.add('b')
a = 0
b = set()
func1()
print(a,b)
</code></pre>
<p>the result is 0 {'b'}</p>
<p>Neither a nor b is declared ... | -1 | 2016-09-11T17:13:19Z | 39,438,790 | <p>What your asking about is called scope. Scope is a generic name for what's defined where. So when you declare a variable:</p>
<pre><code>b = 0
</code></pre>
<p>anything at the same level of scope, or lower can see its definition.</p>
<pre><code>b = 1
def func():
print(b)
func()
</code></pre>
<p>This works ... | 0 | 2016-09-11T17:30:18Z | [
"python"
] |
Namespace questions: Mutable variable doesn't need to be declared as global in function? | 39,438,643 | <p>I am new to python and I try to figure out how to pass value through functions. I have observed the following behaviors</p>
<p><strong>ex1:</strong></p>
<pre><code>def func1():
a = 1
b.add('b')
a = 0
b = set()
func1()
print(a,b)
</code></pre>
<p>the result is 0 {'b'}</p>
<p>Neither a nor b is declared ... | -1 | 2016-09-11T17:13:19Z | 39,438,791 | <p>This blog post(<a href="http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/" rel="nofollow">1</a>) explains the parameter passing of Python.</p>
<p>When you declare b in example 1 you declared it globally.</p>
<p>In example two you overwrite the name b so it is only k... | 0 | 2016-09-11T17:30:20Z | [
"python"
] |
How to use ExtraTreeClassifier to predict multiclass classifications | 39,438,671 | <p>I'm quite new to machine learning techniques, and I'm having trouble following some of the scikit-learn documentation and other stackoverflow posts.. I'm trying to create a simple model from a bunch of medical data that will help me predict which of three classes a patient could fall into. </p>
<p>I load the data v... | 0 | 2016-09-11T17:16:47Z | 39,439,423 | <p>That's normal behaviour in scikit-learn.</p>
<p>There are two approaches possible:</p>
<h3>A:You use "label binarize"</h3>
<ul>
<li>Binarizing transforms <code>y=[n_samples, ] -> y[n_samples, n_classes]</code> (1 dimension added; integers in range(0, X) get transformed to binary values)</li>
<li>Because of thi... | 1 | 2016-09-11T18:41:16Z | [
"python",
"python-2.7",
"scikit-learn",
"decision-tree"
] |
Get attributes from a returned function in Python | 39,438,732 | <pre><code>def outerFunc(number):
if number < 0:
def innerFunc(factor):
return number * factor
else:
def innerFunc(summand):
return number + summand
return innerFunc
x = outerFunc(-8)
print(x(4))
</code></pre>
<p>The result of the print statement is <code>-32</co... | 1 | 2016-09-11T17:24:06Z | 39,438,813 | <blockquote>
<p>Is it possible to access the inner function's <code>number</code> property</p>
</blockquote>
<p>It's not a property. You can technically access it, but not in a particularly nice way:</p>
<pre><code>number = x.__closure__[0].cell_contents
</code></pre>
<blockquote>
<p>Is it good programming style... | 2 | 2016-09-11T17:32:51Z | [
"python",
"closures"
] |
Get attributes from a returned function in Python | 39,438,732 | <pre><code>def outerFunc(number):
if number < 0:
def innerFunc(factor):
return number * factor
else:
def innerFunc(summand):
return number + summand
return innerFunc
x = outerFunc(-8)
print(x(4))
</code></pre>
<p>The result of the print statement is <code>-32</co... | 1 | 2016-09-11T17:24:06Z | 39,438,830 | <ol>
<li>No.</li>
<li>Rarely, but there are cases where it could make sense. If you have to ask the question, you should probably consider the answer to be 'no,' at least for now.</li>
</ol>
| -1 | 2016-09-11T17:34:51Z | [
"python",
"closures"
] |
What is the difference between Cerberus Custom Rules and Custom Validators? | 39,438,774 | <p>From the <a href="http://docs.python-cerberus.org/en/latest/customize.html#custom-rules" rel="nofollow">documentation</a>, it is not clear to me what the difference in use case for the Custom Rule and the Custom Validators are. In the examples given in the documentation, the only difference is an extra <code>if</cod... | 2 | 2016-09-11T17:28:59Z | 39,452,599 | <p>You use the <code>validator</code> rule when you want to delegate validation of a certain field to a custom function, like so:</p>
<pre><code>>>> def oddity(field, value, error):
... if not value & 1:
... error(field, "Must be an odd number")
>>> schema = {'amount': {'validator': oddity... | 1 | 2016-09-12T14:23:02Z | [
"python",
"cerberus"
] |
Biggest number in a text file | 39,438,927 | <p>I have a text file with numbers and names in the following format:</p>
<pre><code>129308123, Some Name
12390123, Some Other Name
</code></pre>
<p>I am trying to grab the biggest number in this textfile and also read on what line it is located. I tried multiple methods but none seem to be working for me. What am I ... | -1 | 2016-09-11T17:45:29Z | 39,439,150 | <p>To find the largest number in the file, split the line with <code>split</code></p>
<pre><code>file_in = open('kaartnummers.txt', 'r')
smallestInt = 0
intList = [int(x.split(",")[0]) for x in file_in.readlines()]
print(intList)
regels = len(intList)
number = max(intList)
laatsteregel = ''
string_format = 'Deze fi... | 0 | 2016-09-11T18:09:56Z | [
"python",
"python-3.x"
] |
python SQL query insert shows empty rows | 39,438,941 | <p>I am trying to do a insert query in the SQL. It indicates that it succeed but shows no record in the database. Here's my code </p>
<pre><code>conn = MySQLdb.connect("localhost",self.user,"",self.db)
cursor = conn.cursor()
id_val = 123456;
path_val = "/homes/error.path"
host_val = "123.23.45.64"
time_val = 7
cursor.... | 0 | 2016-09-11T17:46:21Z | 39,439,178 | <p>After you are sending your INSERT record, you should commit your changes in the database:</p>
<pre><code>cursor.execute("INSERT INTO success (id,path,hostname,time_elapsed) VALUES (%s,%s,%s,%s)", (id_val, path_val,host_val,time_val))
conn.commit()
</code></pre>
<p>When you want to read the data, you should first s... | 0 | 2016-09-11T18:13:18Z | [
"python",
"mysql",
"python-2.7",
"mysql-python"
] |
What is the cleanest way of setting default values for attributes unless provided by the class call? | 39,439,011 | <p>Currently this is what I'm doing:</p>
<pre><code>class NewShip:
def __init__(self, position = (0,0), x_velocity = 25, y_velocity = 15, anim_frame = 1, frame1 = "space_ship_1.png", frame2 = "space_ship_2.png", angle = 0, border_size = 900):
self.position = position
self.angle = angle
self... | 2 | 2016-09-11T17:55:24Z | 39,439,219 | <p>To reduce the clutter, you could alternatively define a defaults dictionary attribute <code>_init_attrs</code> for example, define your function with <code>**kwargs</code> and then <code>setattr</code> on <code>self</code> with a loop, using <code>_init_attrs[k]</code> as a <code>default</code> value for <code>kwarg... | 3 | 2016-09-11T18:17:19Z | [
"python",
"python-3.x"
] |
file is not defined, python 3.5 | 39,439,018 | <p>I try to create an xml file. THis is the program
I am using python 3.5 and as IDE pycharm. Do I miss a library? Or something?
Or is it the IDE what not correct is?</p>
<p>but I get this error:</p>
<pre><code>NameError: name 'file' is not defined
</code></pre>
<p>I have this:</p>
<pre><code>import datetime
impo... | 0 | 2016-09-11T17:56:03Z | 39,439,390 | <p>tab problem !</p>
<p>file variable is not into def main section </p>
<p>def main and file have not indentation </p>
<p>also your main is not called in your tool's</p>
| 1 | 2016-09-11T18:36:43Z | [
"python",
"python-3.x"
] |
file is not defined, python 3.5 | 39,439,018 | <p>I try to create an xml file. THis is the program
I am using python 3.5 and as IDE pycharm. Do I miss a library? Or something?
Or is it the IDE what not correct is?</p>
<p>but I get this error:</p>
<pre><code>NameError: name 'file' is not defined
</code></pre>
<p>I have this:</p>
<pre><code>import datetime
impo... | 0 | 2016-09-11T17:56:03Z | 39,439,398 | <p>Python is all about indentation. Blocks are defined by indentation. You define a function <code>main()</code> and start its indented block...</p>
<pre><code>def main():
# Write an XML file with the results
file = open("ListAccessTiming.xml","w")
file.write('<?xml version="1.0" encoding="UTF-8" standal... | 1 | 2016-09-11T18:37:35Z | [
"python",
"python-3.x"
] |
Python Error message when opening .txt file / change in working directory | 39,439,020 | <p>Iâm a new python user and have written a python script that prompts for the name of a text file (.txt) to be opened and read by the program. </p>
<pre><code>name = raw_input("Enter file:")
if len(name) < 1:
name = "test.txt"
handle = open(name)
</code></pre>
<p>This was working perfectly fine for me, but... | 1 | 2016-09-11T17:56:17Z | 39,439,101 | <p>It's very simple, your input is wrong:</p>
<p>Incorrect:</p>
<pre><code>$ python /test123.py
Enter file:'test.txt'
</code></pre>
<p>Correct:</p>
<pre><code>$ python /test123.py
Enter file:test.txt
</code></pre>
<p>do not include the <code>'</code> characters. It is not code, it's just standard input</p>
| 3 | 2016-09-11T18:04:25Z | [
"python",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.