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 |
|---|---|---|---|---|---|---|---|---|---|
Numpy: advanced slices | 39,064,607 | <p>I need a fast way to find the smallest element among three neighbor elements in a string, and add it to element under the central element. For border elements only two upper elements are checking.</p>
<p>For example I have a numpy array:</p>
<pre><code> [1, 2, 3, 4, 5],
[0, 0, 0, 0, 0]
</code></pre>
<p>I ... | 1 | 2016-08-21T13:15:11Z | 39,067,003 | <p>Here's a slight variation on <code>Daniel's</code> solution:</p>
<p>Start with the row or list of values:</p>
<pre><code>In [439]: z=[10,40,90,13,21,58,64,56,34,69]
</code></pre>
<p>Replicate the 1st and last values; I could do that with concatenate, indexing, or the simple <code>pad</code> (internally <code>pad<... | 1 | 2016-08-21T17:35:16Z | [
"python",
"arrays",
"performance",
"numpy",
"slice"
] |
Mean Squared error in Python | 39,064,684 | <p>I'm trying to made function that will calculate mean squared error from y (true values) and y_pred (predicted ones) not using sklearn or other implementations.</p>
<p>I'll try next:</p>
<pre><code>def mserror(y, y_pred):
i=0
for i in range (len(y)):
i+=1
mse = ((y - y_pred) ** 2).mean(y) ... | 0 | 2016-08-21T13:23:56Z | 39,065,217 | <p>You are modifying the index for no reason. A for loop increments it anyways. Also you are not using the index for example you are not using any y[i]-y_pred[i] hence you don't need the loop at all. </p>
<p>Use the arrays </p>
<pre><code>mse = np.mean((y-y_pred)**2)
</code></pre>
| 0 | 2016-08-21T14:20:08Z | [
"python",
"numpy",
"scikit-learn"
] |
Regular expression for anything except ']]' characters | 39,064,725 | <p>I had posted a question earlier but it wasn't very clear to understand so it here goes again:</p>
<p>I have a string which looks like this :</p>
<pre><code>{
"1000":[ [some whitespace and nonwhitespace characters],
[some whitespace and nonwhitespace characters],
....
[some whitespace and... | -1 | 2016-08-21T13:28:52Z | 39,064,800 | <p>A regex solution can be achieved using something like:</p>
<pre><code>\d{4}":(.*?)]]
</code></pre>
<p>But you really <em>don't</em> want to use regex here if your string is a valid JSON. It's very natural for Python to work with JSONs. Assuming your data is:</p>
<pre><code>data = {key1: [[str1], [str2], ...], ...... | 0 | 2016-08-21T13:36:23Z | [
"python",
"regex",
"regex-negation"
] |
Giving input to terminal in python | 39,064,796 | <p>I'm writing a code to read serial input. Once the serial input has been read, I have to add a time stamp below it and then the output from a certain software. To get the output from the software, I want python to write a certain command to the terminal, and then read the output that comes on the terminal. Could you ... | 0 | 2016-08-21T13:36:05Z | 39,064,972 | <p>You would need to have python implemented into the software. </p>
<p>Also, I believe this is a task for GCSE Computing this year as I was privileged enough to choose what test we are doing and there was a question about serial numbers.</p>
| 0 | 2016-08-21T13:54:02Z | [
"python",
"python-2.7",
"terminal"
] |
Giving input to terminal in python | 39,064,796 | <p>I'm writing a code to read serial input. Once the serial input has been read, I have to add a time stamp below it and then the output from a certain software. To get the output from the software, I want python to write a certain command to the terminal, and then read the output that comes on the terminal. Could you ... | 0 | 2016-08-21T13:36:05Z | 39,067,408 | <p>To run a command and get the returned output you can use the subprocess module's check_output function.</p>
<pre><code>import subprocess
output = subprocess.check_output("ls -a", shell=True)
</code></pre>
<p>That will return the current directory contents in MacOS/Linux and store the output for you to read from l... | 0 | 2016-08-21T18:14:54Z | [
"python",
"python-2.7",
"terminal"
] |
Numpy arrays means | 39,064,851 | <p>I have an array in numpy with values like these:</p>
<pre><code>array([ 22.1, 10.4, 9.3, 18.5, 12.9, 7.2, 11.8, 13.2, 4.8,
10.6, 8.6, 17.4, 9.2, 9.7, 19. , 22.4, 12.5, 24.4,
11.3, 14.6, 18. , 12.5, 5.6, 15.5, 9.7, 12. , 15. ])
</code></pre>
<p>How can I replace all o... | 0 | 2016-08-21T13:41:28Z | 39,064,997 | <p>If I understand your question correctly, you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.place.html" rel="nofollow">np.place()</a></p>
<pre><code>arr = np.array([ 22.1, 10.4, 9.3, 18.5, 12.9, 7.2, 11.8, 13.2, 4.8,
10.6, 8.6, 17.4, 9.2, 9.7, 19. , 22.... | -1 | 2016-08-21T13:56:42Z | [
"python",
"arrays",
"numpy"
] |
Numpy arrays means | 39,064,851 | <p>I have an array in numpy with values like these:</p>
<pre><code>array([ 22.1, 10.4, 9.3, 18.5, 12.9, 7.2, 11.8, 13.2, 4.8,
10.6, 8.6, 17.4, 9.2, 9.7, 19. , 22.4, 12.5, 24.4,
11.3, 14.6, 18. , 12.5, 5.6, 15.5, 9.7, 12. , 15. ])
</code></pre>
<p>How can I replace all o... | 0 | 2016-08-21T13:41:28Z | 39,065,001 | <p>Do you need something like this?:</p>
<pre><code>import numpy as np
a = np.array([ 22.1, 10.4, 9.3, 18.5, 12.9, 7.2, 11.8, 13.2, 4.8,
10.6, 8.6, 17.4, 9.2, 9.7, 19. , 22.4, 12.5, 24.4,
11.3, 14.6, 18. , 12.5, 5.6, 15.5, 9.7, 12. , 15. ])
a[:] = np.mean... | 1 | 2016-08-21T13:57:03Z | [
"python",
"arrays",
"numpy"
] |
Custom argumental TypeError messages | 39,064,894 | <p>I would like to return a custom set of messages based on the specific cause of the <code>TypeError</code>.</p>
<pre><code>def f(x, y):
value = x + y
return "Success! ({})".format(value)
def safe(function, *args):
try:
result = function(*args)
except TypeError:
if "not_enough_args": ... | 1 | 2016-08-21T13:46:21Z | 39,065,046 | <p>Here's a possible solution to your question:</p>
<pre><code>def f(x, y):
value = x + y
return "Success! ({})".format(value)
def safe(function, *args):
try:
result = function(*args)
except TypeError as e:
return str(e)
else:
return result
def safe2(function, *args):
... | 0 | 2016-08-21T14:01:04Z | [
"python",
"python-3.x",
"exception",
"response"
] |
Custom argumental TypeError messages | 39,064,894 | <p>I would like to return a custom set of messages based on the specific cause of the <code>TypeError</code>.</p>
<pre><code>def f(x, y):
value = x + y
return "Success! ({})".format(value)
def safe(function, *args):
try:
result = function(*args)
except TypeError:
if "not_enough_args": ... | 1 | 2016-08-21T13:46:21Z | 39,065,053 | <p>I wouldn't mess around with changing the nature of the exception object, and having a long list of conditional statements to print out your own custom message. Instead just return back the exception object. You can do this in your <code>except</code> line as: </p>
<pre><code>except TypeError as e
</code></pre>
<p>... | 0 | 2016-08-21T14:01:25Z | [
"python",
"python-3.x",
"exception",
"response"
] |
Using save method to extend M2M relationship | 39,064,980 | <p>I have a model like this </p>
<pre><code>class Authority(models.Model):
name=models.CharField(max_length=100)
country=models.ForeignKey(Country)
category=models.ForeignKey(Category)
competitors=models.ManyToManyField("self",related_name="competitors")
</code></pre>
<p>I want authorities having the ... | 0 | 2016-08-21T13:55:12Z | 39,067,346 | <p>The reason this isn't working the way you expect is because of how Django handles creating m2m relationships in the database. Long story very short, when you save something like a new <code>Authority</code> to the database, Django first writes the new object then goes back in and writes the m2m relationships for tha... | 0 | 2016-08-21T18:09:13Z | [
"python",
"django",
"python-2.7",
"django-models"
] |
aggregating hourly time series by Day via pd.TimeGrouper('D'); issue @ timestamp 00:00:00 (hour 24) | 39,065,034 | <p><strong>df:</strong></p>
<pre><code> hour rev
datetime
2016-05-01 01:00:00 1 -0.02
2016-05-01 02:00:00 2 -0.01
2016-05-01 03:00:00 3 -0.02
2016-05-01 04:00:00 4 -0.02
2016-05-01 05:00:00 5 -0.01
2016-05-01 06:00:00 6 -0.03
2016-05-01 07:00:00 7 -0.10
2016-05-01 08:00:00 8... | 1 | 2016-08-21T13:59:44Z | 39,065,432 | <p>A little bit hack solution, if your starting point for each day is larger than one second, you can subtract one second from the date time column and then groupby date, which seems to work for your case:</p>
<pre><code>from datetime import timedelta
import pandas as pd
df.groupby((df.datetime - timedelta(seconds = 1... | 1 | 2016-08-21T14:43:44Z | [
"python",
"pandas",
"group-by",
"aggregation"
] |
aggregating hourly time series by Day via pd.TimeGrouper('D'); issue @ timestamp 00:00:00 (hour 24) | 39,065,034 | <p><strong>df:</strong></p>
<pre><code> hour rev
datetime
2016-05-01 01:00:00 1 -0.02
2016-05-01 02:00:00 2 -0.01
2016-05-01 03:00:00 3 -0.02
2016-05-01 04:00:00 4 -0.02
2016-05-01 05:00:00 5 -0.01
2016-05-01 06:00:00 6 -0.03
2016-05-01 07:00:00 7 -0.10
2016-05-01 08:00:00 8... | 1 | 2016-08-21T13:59:44Z | 39,069,525 | <p>Simply <code>.shift(-1)</code> or .<code>roll(-1)</code>, the <code>rev</code> column, backward one. So timestamp would be period start vs period end. You would need to add one timestamp. </p>
| 0 | 2016-08-21T22:51:04Z | [
"python",
"pandas",
"group-by",
"aggregation"
] |
aggregating hourly time series by Day via pd.TimeGrouper('D'); issue @ timestamp 00:00:00 (hour 24) | 39,065,034 | <p><strong>df:</strong></p>
<pre><code> hour rev
datetime
2016-05-01 01:00:00 1 -0.02
2016-05-01 02:00:00 2 -0.01
2016-05-01 03:00:00 3 -0.02
2016-05-01 04:00:00 4 -0.02
2016-05-01 05:00:00 5 -0.01
2016-05-01 06:00:00 6 -0.03
2016-05-01 07:00:00 7 -0.10
2016-05-01 08:00:00 8... | 1 | 2016-08-21T13:59:44Z | 39,109,185 | <p>it looks like another hack, but it should do the job:</p>
<pre><code>In [79]: df.assign(t=df.datetime - pd.Timedelta(hours=1)).drop('datetime',1).groupby(pd.TimeGrouper('D', key='t')).sum()
Out[79]:
hour rev
t
2016-05-01 300 -2.49
</code></pre>
| 1 | 2016-08-23T19:23:01Z | [
"python",
"pandas",
"group-by",
"aggregation"
] |
Obtaining values from ipywidgets.widgets.SelectMultiple | 39,065,074 | <p>I am not able to get the values from a MultipleSelect widget after changing the initial selection. The selection looks fine, but the values do not show. The code to create the SelectMultiple widget:</p>
<pre><code>from ipywidgets import widgets
from IPython.display import display
w = widgets.SelectMultiple(descript... | 0 | 2016-08-21T14:04:01Z | 39,066,628 | <p>I believe it to be a browser issue. I usually use Chrome, where it works just fine. Today, I used IE11, and whereas all other <code>ipywidgets.widgets</code> worked as expected, the <code>widgets.SelectMultiple</code> does not. </p>
| 0 | 2016-08-21T16:55:40Z | [
"python",
"jupyter-notebook",
"ipywidgets"
] |
Making script content 'safe' for HTTPS display (Bokeh) | 39,065,089 | <p>I was searching for a solution and came across a removed question from <a href="http://stackoverflow.com/users/5082720/maria-saz">maria saz</a>. Fortunately, I was able to see it <a href="http://webcache.googleusercontent.com/search?q=cache:Cwo3LBTyviIJ:stackoverflow.com/questions/39005081/making-script-content-safe... | 0 | 2016-08-21T14:05:36Z | 39,070,704 | <p>If you are proxying a Bokeh server behind a proxy that is terminating SSL, then you need to configure the proxy to pass the originating protocol on to the Bokeh server, and also use the <code>--use-xheaders</code> command line option to invoke the Bokeh server:</p>
<pre><code>bokeh serve app_script.py --use-xheader... | 0 | 2016-08-22T02:43:34Z | [
"python",
"django",
"google-app-engine",
"https",
"bokeh"
] |
Making script content 'safe' for HTTPS display (Bokeh) | 39,065,089 | <p>I was searching for a solution and came across a removed question from <a href="http://stackoverflow.com/users/5082720/maria-saz">maria saz</a>. Fortunately, I was able to see it <a href="http://webcache.googleusercontent.com/search?q=cache:Cwo3LBTyviIJ:stackoverflow.com/questions/39005081/making-script-content-safe... | 0 | 2016-08-21T14:05:36Z | 40,094,283 | <p>This issue was addressed simply by referring to the CDN address with "https://"</p>
<p>See the <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/embed.html" rel="nofollow">bokeh embed notes</a></p>
| 0 | 2016-10-17T19:35:01Z | [
"python",
"django",
"google-app-engine",
"https",
"bokeh"
] |
I am new to boto.Help me i am getting this error | 39,065,124 | <pre><code>import boto3
>>> client = boto3.client('ec2')
>>> response = client.create_tags(DryRun = True | False, Resources = ['ABC', ], Tags = [{
'Key' : 'vennkata',
'Value' : 'ratnam'
}, ])
Traceback(most recent call last) :
File "<stdin&g... | -2 | 2016-08-21T14:09:26Z | 39,065,236 | <p>Could not connect to the endpoint URL : <a href="https://ec2" rel="nofollow">https://ec2</a>.<strong>us-west</strong>.amazonaws.com</p>
<p><code>us-west</code> is not a valid region. Currently supported regions are <code>us-west-1</code> and <code>us-west-2</code>. See <a href="http://docs.aws.amazon.com/general/la... | 4 | 2016-08-21T14:21:59Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto3"
] |
How can I do context depended substitution (updating of fields) in the vcf (variant call format) files? | 39,065,129 | <p>I have a vcf file that looks like this:</p>
<p><strong>CHROM POS ID REF ALT QUAL FILTER INFO FORMAT 2ms01e 2ms02g 2ms03g 2ms04h</strong></p>
<p>2 15882505 . T A 12134.90 PASS AC=2;AF=0.250;AN=8;BaseQRankSum=-0.021;ClippingRankSum=0.000;DP=695;ExcessHet=3.6798;FS=0.523;MLEAC=2;MLEAF=0.2... | 0 | 2016-08-21T14:09:57Z | 39,065,328 | <p>The below answer won't contain any details about any logic, but it will give you one possible starting point so you can play around by yourself:</p>
<pre><code>class VCFProcessor():
def __init__(self):
pass
def load(self, filename):
with open(filename, "rb") as f:
self.load_str... | 0 | 2016-08-21T14:31:09Z | [
"python",
"awk",
"sed",
"string-substitution"
] |
How can I do context depended substitution (updating of fields) in the vcf (variant call format) files? | 39,065,129 | <p>I have a vcf file that looks like this:</p>
<p><strong>CHROM POS ID REF ALT QUAL FILTER INFO FORMAT 2ms01e 2ms02g 2ms03g 2ms04h</strong></p>
<p>2 15882505 . T A 12134.90 PASS AC=2;AF=0.250;AN=8;BaseQRankSum=-0.021;ClippingRankSum=0.000;DP=695;ExcessHet=3.6798;FS=0.523;MLEAC=2;MLEAF=0.2... | 0 | 2016-08-21T14:09:57Z | 39,068,360 | <pre><code>$ cat > another_mess.awk
$0!="" {
n=split($10,a,":") # split $10 at ":" to a array
if(substr(a[6],2,1)=="|") { # if "|" in PG
a[1]=a[6] # copy PG to GT
$10="" # empty $10
for(i=1;i<=n;i++) # rebuild... | 1 | 2016-08-21T20:00:02Z | [
"python",
"awk",
"sed",
"string-substitution"
] |
What Should the Structure of virtualenv Environment Look Like | 39,065,136 | <p>This is one of my first times really using <code>virtualenv</code> and when I first activated it I was (and am) a bit confused about where my actual project (like the code) should go. Currently (after making and activating the <code>virtualenv</code>) this is what my project looks like in <code>PyCharm</code>:</p>
... | 0 | 2016-08-21T14:10:44Z | 39,065,222 | <p>I don't recommend to put your project to virtualenv folder. I think you should do it in this way:</p>
<p>Do it in terminal if you're using Linux:</p>
<ol>
<li><code>mkdir project-name</code>.</li>
<li><code>cd project-name</code>.</li>
<li><code>virtualenvwrapper env</code>.</li>
<li><code>source env/bin/activate<... | 1 | 2016-08-21T14:20:54Z | [
"python",
"python-3.x",
"pycharm",
"virtualenv",
"development-environment"
] |
What Should the Structure of virtualenv Environment Look Like | 39,065,136 | <p>This is one of my first times really using <code>virtualenv</code> and when I first activated it I was (and am) a bit confused about where my actual project (like the code) should go. Currently (after making and activating the <code>virtualenv</code>) this is what my project looks like in <code>PyCharm</code>:</p>
... | 0 | 2016-08-21T14:10:44Z | 39,065,253 | <p>When you activate a virtual env using <code>virutalenv env</code>, env (where all of your dependencies will be installed), sits at the top of your root directory. Let's say you use <a href="https://www.djangoproject.com/" rel="nofollow">Django</a> to create a project, you would then follow these steps:</p>
<ol>
<li... | 1 | 2016-08-21T14:23:19Z | [
"python",
"python-3.x",
"pycharm",
"virtualenv",
"development-environment"
] |
Internal server error code 500 when uploading a file to a directory with Flask | 39,065,221 | <p>Here is the backend Flask code for a basic file uploading form</p>
<pre><code>@app.route('/gallery',methods=['GET','POST'])
def gallery():
error = None
if request.method == "POST":
if 'file' not in request.files:
flash("No file part")
return redirect(request.url)
file = request.files['file... | 0 | 2016-08-21T14:20:46Z | 39,065,394 | <p>What your error says is that the folder does not exist. Create the folder <code>/uploads/</code> and make it readable for the program.
If the folder should be relative to your Flask directory use
<code>uploads/</code> instead. </p>
| 1 | 2016-08-21T14:39:14Z | [
"python",
"html",
"file-upload",
"flask",
"server"
] |
Internal server error code 500 when uploading a file to a directory with Flask | 39,065,221 | <p>Here is the backend Flask code for a basic file uploading form</p>
<pre><code>@app.route('/gallery',methods=['GET','POST'])
def gallery():
error = None
if request.method == "POST":
if 'file' not in request.files:
flash("No file part")
return redirect(request.url)
file = request.files['file... | 0 | 2016-08-21T14:20:46Z | 39,065,508 | <p>I fixed the issue. It was happening because my UPLOAD_FOLDER variable was set to /uploads when it should have been been set relative to the Flask directory (uploads/)</p>
| 0 | 2016-08-21T14:52:55Z | [
"python",
"html",
"file-upload",
"flask",
"server"
] |
Python script taking too much time and memory to execute | 39,065,405 | <p>I have a python script which uses quite a few libraries.</p>
<pre><code>import time
import cgitb
cgitb.enable()
import numpy as np
import MySQLdb as mysql
import cv2
import sys
import rpy2.robjects as robj
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
from rpy2.robjects.packages import importr
R =... | -1 | 2016-08-21T14:40:29Z | 39,065,540 | <p>You showed only imports, not app or particulat function, so my help is lot limited.</p>
<ol>
<li>As I undrstand, you are embedding R language to python (the rpy2 lib). You are probably working with videos (cv2 lib). There culd be lot of another libs python needs to load to memory because of that. You are simply usi... | 1 | 2016-08-21T14:56:18Z | [
"python",
"memory"
] |
Best way to set Entry Background Color in Python GTK3 and set back to default | 39,065,408 | <p>What is the best way to set background color for one entry and set it back to the default color?</p>
<p>My script is now working but I am very sure this is not the best way.<br>
Also I still have two problems:</p>
<ol>
<li>If I insert a text, not containing string "red" or "green" and select this text I cant see m... | 2 | 2016-08-21T14:41:18Z | 39,066,419 | <p>I will first address the issues you mention, as they give insight into what is going on in GTK and OP's code. <strong>The answer to the main question (and proper code for doing this) is all the way at the bottom of the answer.</strong></p>
<hr>
<blockquote>
<ol>
<li>If I insert a text, not containing string "r... | 1 | 2016-08-21T16:30:38Z | [
"python",
"css",
"gtk3"
] |
dryscrape click "load more button" | 39,065,492 | <p>I've been trying to scrape www.ratemyprofessors.com and I need to click the "load more" button to scrape the all the data that i need. However, the code that im using right now isn't working</p>
<pre><code>loadButton = session.at_xpath(path)
loadButton.click()
</code></pre>
<p>The path is definitely correct si... | 1 | 2016-08-21T14:51:16Z | 39,067,140 | <p>You can do it all using <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> and <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">bs4</a>, when you click the load more button a request is made:</p>
<p><a href="http://i.stack.imgur.com/OfSuV.png" rel="nofoll... | 0 | 2016-08-21T17:48:24Z | [
"javascript",
"python",
"web-scraping"
] |
Why is apply not being applied | 39,065,524 | <p>I have this initial dataframe:</p>
<pre><code>df = pd.DataFrame(data = {'colX': ['TQ95','SM90','SJ07','SH97','TF28']})
</code></pre>
<p>So df is as follows:</p>
<pre><code> colX
0 TQ95
1 SM90
2 SJ07
3 SH97
4 TF28
</code></pre>
<p>No I create a very very simple function and apply it to df:</p>
<pre>... | 1 | 2016-08-21T14:54:21Z | 39,065,598 | <p><code>df.apply(foo)</code> is executed on every column of the DataFrame (for your case, only on <code>colX</code>). It is the same as <code>df['colX'] + 'bar'</code>. You are appending 'bar' to every string in that Series (<code>x</code> in that function is a Series so <code>x + 'bar'</code> is also a Series).</p>
... | 2 | 2016-08-21T15:01:29Z | [
"python",
"pandas"
] |
Why is apply not being applied | 39,065,524 | <p>I have this initial dataframe:</p>
<pre><code>df = pd.DataFrame(data = {'colX': ['TQ95','SM90','SJ07','SH97','TF28']})
</code></pre>
<p>So df is as follows:</p>
<pre><code> colX
0 TQ95
1 SM90
2 SJ07
3 SH97
4 TF28
</code></pre>
<p>No I create a very very simple function and apply it to df:</p>
<pre>... | 1 | 2016-08-21T14:54:21Z | 39,065,614 | <p>Did you mean:</p>
<pre><code>df['colX'].apply(bar)
</code></pre>
<p>Thus, only the length of the <strong>column value</strong> is checked.<br>
The complete code:</p>
<pre><code>import pandas as pd
def bar(x):
if len(x) == 4:
return 'x'
elif len(x) == 6:
return 'y'
else:
return ... | 3 | 2016-08-21T15:03:00Z | [
"python",
"pandas"
] |
Django Save creating two records instead of one | 39,065,568 | <p>Django is creating two records in MySQL instead of one.</p>
<p>I call a function via a link </p>
<pre><code><a href="{% url 'markpresent' id=c.id %}"><button class="btn btn-primary">Thats Me!</button></a>
</code></pre>
<p>The function itself is very straight forward. I take the variable v... | 0 | 2016-08-21T14:58:46Z | 39,065,663 | <p>You should avoid modifying your database on a GET request. Various things could cause a duplicate request - for instance, a request for an asset or favicon being caught by the same URL pattern and routed to the same view - so you should always require a POST before adding an entry in your database.</p>
| 1 | 2016-08-21T15:07:31Z | [
"python",
"mysql",
"django"
] |
Django Save creating two records instead of one | 39,065,568 | <p>Django is creating two records in MySQL instead of one.</p>
<p>I call a function via a link </p>
<pre><code><a href="{% url 'markpresent' id=c.id %}"><button class="btn btn-primary">Thats Me!</button></a>
</code></pre>
<p>The function itself is very straight forward. I take the variable v... | 0 | 2016-08-21T14:58:46Z | 39,065,701 | <p>Are you using Google Chrome? If yes, then Google Chrome has something like lazy loading. So if you will type your URL in Google Chrome, it will try to load site behind the scenes and if you will tap enter, then you will get this URL again. The same is when you're trying to go over anchor with a link. It's an edge ca... | 1 | 2016-08-21T15:11:13Z | [
"python",
"mysql",
"django"
] |
Invalid Literal Issue when trying to convert RGB to HEX | 39,065,585 | <p>While writing a few unit tests, I had to convert RGB colors to HEX. My function for the conversion is </p>
<pre><code> def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
</code></pre>
<p>The output that I am getting using the unit test function (Selenium using Python ) is in the format <code>rgba(255,... | 0 | 2016-08-21T15:00:16Z | 39,087,273 | <p>There may be many reasons :
1. rgb should be tuple in this case having 3 values. So (255, 255, 255) in form of tuple needs to be passed here instead of (255, 255, 255, 1)
2. rgb has to be a tuple, if it is string this will not work.</p>
<p>Try using following commands in python interpreter</p>
<pre><code>"#%02x%02... | 0 | 2016-08-22T19:25:31Z | [
"python",
"selenium",
"type-conversion"
] |
python - best approach when analysing scraped data | 39,065,615 | <p>Newbie here. I have managed to put together a script which scrapes some information from a website. This happens daily, and the data is saved on a csv file. content of each file is similar to this:</p>
<pre><code>date, ticker, company name, momentum indicator, other ratios....
2016-08-19, GSK, GlaxoSmithKline, 42, ... | 0 | 2016-08-21T15:03:05Z | 39,078,390 | <p>In order to process the data you've collected, you could use one of the python modules, <code>csv</code> or <code>pandas</code>. The <code>csv</code> module is used to read/write data from/to csv files and then you can convert the data into python lists and dictionaries and use accordingly. For detailed docs go <a h... | 1 | 2016-08-22T11:29:46Z | [
"python"
] |
Pygame can't open song on Raspberry Pi | 39,065,639 | <p>I have a program that plays a random wav file when it is run. However, when I run the program I get this error:</p>
<pre><code>Traceback (most recent call last):
File "pi/home/python_music/music.py", line 19, in <module>
pygame.mixer.music.load(song)
error: Couldn't open 'Song1.wav
'
</code></pre>
<p... | 0 | 2016-08-21T15:05:37Z | 39,065,780 | <ol>
<li>Make sure your .wavs are in the same folder as your .py</li>
<li>Make sure they are called 'Song1.wav'</li>
<li>Try <code>if not x == '':</code></li>
<li>Put <code>break</code> under <code>songs.append</code></li>
</ol>
| 0 | 2016-08-21T15:19:05Z | [
"python",
"raspberry-pi",
"pygame",
"music"
] |
Pygame can't open song on Raspberry Pi | 39,065,639 | <p>I have a program that plays a random wav file when it is run. However, when I run the program I get this error:</p>
<pre><code>Traceback (most recent call last):
File "pi/home/python_music/music.py", line 19, in <module>
pygame.mixer.music.load(song)
error: Couldn't open 'Song1.wav
'
</code></pre>
<p... | 0 | 2016-08-21T15:05:37Z | 39,065,799 | <p>In your code, you're reading the entire line of the file including the newline character. You can avoid this by instead of having </p>
<pre><code>f = open('List.txt', 'r+')
songs = []
while True:
x = f.readline()
if x == '':
break
songs.append(x)
f.close()
y = randint(0, len(songs))
</c... | 1 | 2016-08-21T15:20:52Z | [
"python",
"raspberry-pi",
"pygame",
"music"
] |
python- pandas- concatenate columns with a loop | 39,065,656 | <p>I have a list of columns that I need to concatenate. An example table would be:</p>
<pre><code>import numpy as np
cats1=['T_JW', 'T_BE', 'T_FI', 'T_DE', 'T_AP', 'T_KI', 'T_HE']
data=np.array([random.sample(range(0,2)*7,7)]*3)
df_=pd.DataFrame(data, columns=cats1)
</code></pre>
<p>So I need to get the concatenatio... | 1 | 2016-08-21T15:07:03Z | 39,065,941 | <p>I don't think you can have a list of space delimited integers in Python without them being in a string (I might be wrong). Having said that, the answer I have is:</p>
<pre><code>output = []
for i in range(0,df_.shape[0]):
output.append(' '.join(str(x) for x in list(df_.loc[i])))
print(output)
</code></pre>
<p>... | 0 | 2016-08-21T15:38:55Z | [
"python",
"pandas",
"dataframe",
"zip",
"concatenation"
] |
Pandas Cumulative Time Series Range in Data Frame | 39,065,904 | <p>I'm looking to have an "expanding" date range based on the values in a starttime and endcolumn.</p>
<p>If any part of a record occurs in a prior record, I want to return a starttime that is the minimum of the two starttime records and an endtime that is the maximum of the two endtime records.</p>
<p>These will be ... | 0 | 2016-08-21T15:32:45Z | 39,066,017 | <p>It looks like you are trying to return a value based on a value that isn't set yet, </p>
<p><code>df['start'] =...conditions... df['start'].shift()</code></p>
<p>looks to me like you are trying to set a condition on a column that Pandas doesn't know anything about.</p>
<p>If you are just trying to set the "start"... | 1 | 2016-08-21T15:46:59Z | [
"python",
"datetime",
"pandas",
"time-series"
] |
Pandas Cumulative Time Series Range in Data Frame | 39,065,904 | <p>I'm looking to have an "expanding" date range based on the values in a starttime and endcolumn.</p>
<p>If any part of a record occurs in a prior record, I want to return a starttime that is the minimum of the two starttime records and an endtime that is the maximum of the two endtime records.</p>
<p>These will be ... | 0 | 2016-08-21T15:32:45Z | 39,068,728 | <p>Try this: </p>
<p>Version 1</p>
<pre><code>NaT = pd.NaT
df['Rolling2'] = np.where(df['starttime'].shift(-1) > df['endtime'], NaT,'drop')
df['Rolling2'] = df['Rolling2'].shift(1)
df['RollingStart'] = np.where(df['Rolling2'] =='drop',None,df['starttime'])
df['RollingStart'] = pd.to_datetime(df['RollingSt... | 0 | 2016-08-21T20:48:37Z | [
"python",
"datetime",
"pandas",
"time-series"
] |
Running lines of code inside code for new thread instead of specifying a target function to run | 39,066,005 | <p>I've tried a lot of searching but didn't really know how to word my problem, so it may be that there's a solution that I couldn't find because I didn't know how to search for it.</p>
<p>I have a single line of code that I'd like to run in a separate thread. So far I have the impression that to create a new thread y... | 0 | 2016-08-21T15:45:53Z | 39,066,032 | <p>Using python you can make inline functions using <code>lambda</code></p>
<pre><code>threading.Thread(target = lambda: print('hi')).start()
</code></pre>
<p><em>In this case, note that 'hi' won't show in the terminal as it's in another thread</em></p>
| 0 | 2016-08-21T15:49:35Z | [
"python"
] |
What are the difference between django-compressor and django-sass processor? | 39,066,027 | <p>I'm using django compressor, to compress JS and CSS. As the introduction about django compressor says:"Django Compressor processes, combines and minifies linked and inline Javascript or CSS in a Django template into cacheable static files."</p>
<p>Looks like the same goal of django-sass-processor. The problem when ... | 0 | 2016-08-21T15:48:41Z | 39,066,080 | <p>I haven't used django befor however the SASS Processor will process SASS code which is kinda like advanced/modified CSS</p>
| 0 | 2016-08-21T15:55:13Z | [
"python",
"django",
"sass",
"django-compressor"
] |
Why are these tuple values seemingly losing their precision | 39,066,064 | <p>I have the following:</p>
<pre><code>import pandas as pd
def TupFirst(x):
return x[0]
def TupSecond(x):
return x[1]
df = pd.DataFrame(data = {'colX': [(51.2990505474, 0.802680507953),(51.7491674401, -4.96357522689)]})
df['colY'] = df['colX'].apply(TupFirst)
df['colZ'] = df['colX'].apply(TupSecond)
df
</cod... | 2 | 2016-08-21T15:53:22Z | 39,066,157 | <p>What you're seeing is the result of a display configuration in pandas. The full precision is still there. Check it with:</p>
<p><code>print(df.loc[1, 'colz'])</code></p>
| 2 | 2016-08-21T16:02:33Z | [
"python",
"pandas"
] |
Django - default field value depends on other field value | 39,066,086 | <p><br>I have a problem to set a default field value. What I want to do?<br>I want that price in class Packages be a default value of priceNoTax in class Bill. As you can see, all three classes are
logically connected.<br>Example: Account 1 has a package with id 1. Price of this package is 100. Default value of priceN... | 2 | 2016-08-21T15:55:31Z | 39,086,622 | <p>perhaps add this to your Bill class?</p>
<pre><code>def save(self, *args, **kwargs):
if self.priceNoTax is None:
self.priceNoTax = self.idAccount.idPackage.price
super(Bill, self).save(*args, **kwargs)
</code></pre>
| 0 | 2016-08-22T18:44:32Z | [
"python",
"django",
"default-value"
] |
Command similar to pygame's get_rel() in tkinter? | 39,066,114 | <p>I was wondering if when I bind the <code><Motion></code> event to a function, if in that function I could define an <code>x</code> and <code>y</code> variable using a version of pygame's <code>mouse.get_rel()</code>, but in tkinter.</p>
| 1 | 2016-08-21T15:58:51Z | 39,067,890 | <p>Event processing is different in <code>tkinter</code> than in <code>pygame</code>, so instead of direct <code>mouse.get_rel()</code> equivalent, it seemed more appropriate to create something that would call a callback function every time the mouse moved (which is what binding to the <code>'<Motion>'</code> ev... | 0 | 2016-08-21T19:07:42Z | [
"python",
"tkinter",
"pygame",
"python-3.5"
] |
Display response(xml) by making a HTTP GET request using javascript? | 39,066,181 | <p>I have very new to JS and I have done my research but I guess I'm kind of using the wrong technique or something.
Like in python to make GET request we do:</p>
<pre><code>request_text = requests.get(url).text
</code></pre>
<p>I want to do the same thing but using JS i.e. display the content from <code>"http://synd... | 0 | 2016-08-21T16:05:10Z | 39,066,520 | <p>When I use</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function test(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
... | 1 | 2016-08-21T16:43:01Z | [
"javascript",
"python",
"xml"
] |
How can I use a SplitArrayField in a ModelForm | 39,066,199 | <p>I am trying to show a postgresql ArrayField as multiple input fields in a form that users can submit data.</p>
<p>Lets say I had a model:</p>
<pre><code>class Venue(models.Model):
additional_links = ArrayField(models.URLField(validators=[URLValidator]), null=True)
</code></pre>
<p>That a form was using:</p>
... | 0 | 2016-08-21T16:07:36Z | 39,556,532 | <p>The SplitArrayField and SplitArrayWidget it is very different things.
Usage SplitArrayField in forms.ModelForm is adding a new field to a form.</p>
<p>The SplitArrayWidget is default widget for SplitArrayField, so you don`t need change it.</p>
<p>A problem is if you need set this widget to the field "additional_li... | 0 | 2016-09-18T10:16:31Z | [
"python",
"django",
"postgresql",
"python-3.x"
] |
How to decrypt a RC2 ciphertext? | 39,066,220 | <p>Python 3.5, pycrypto 2.7a1, Windows, RC2 ciphering</p>
<p>Example:</p>
<pre><code>print('ÐведиÑе ÑекÑ, коÑоÑÑй Ñ
оÑиÑе заÑиÑÑоваÑÑ:')
text = input()
with open('plaintext.txt', 'w') as f:
f.write(text)
key = os.urandom(32)
with open('rc2key.bin', 'wb') as keyfile:
keyfil... | -1 | 2016-08-21T16:09:47Z | 39,066,539 | <p>The IV is a non-secret value and is commonly written in front of the ciphertext. Since, you've done that already, you don't need to write an additional IV file. RC2 has a block size of 64 bit, so the IV will always be 8 byte long.</p>
<pre><code>with open('ciphertext.bin', 'rb') as f:
ciphertext = f.read()
wit... | 0 | 2016-08-21T16:44:55Z | [
"python",
"python-3.x",
"encryption",
"pycrypto",
"rc2-cipher"
] |
Get (first and) second highest values in pandas columns | 39,066,260 | <p>I am using pandas to analyse some election results. I have a DF, Results, which has a row for each constituency and columns representing the votes for the various parties (over 100 of them):</p>
<pre><code>In[60]: Results.columns
Out[60]:
Index(['Constituency', 'Region', 'Country', 'ID', 'Type', 'Electorate',
... | 1 | 2016-08-21T16:14:55Z | 39,066,373 | <p>You could just sort your results, such that the first rows will contain the max. Then you can simply use indexing to get the first n places.</p>
<pre><code>RawResults = Results.ix[:, 'Unnamed: 9': 'Zeb'].sort_values(by='votes', ascending=False)
RawResults.iloc[0, :] # First place
RawResults.iloc[1, :] # Second plac... | 1 | 2016-08-21T16:25:41Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Get (first and) second highest values in pandas columns | 39,066,260 | <p>I am using pandas to analyse some election results. I have a DF, Results, which has a row for each constituency and columns representing the votes for the various parties (over 100 of them):</p>
<pre><code>In[60]: Results.columns
Out[60]:
Index(['Constituency', 'Region', 'Country', 'ID', 'Type', 'Electorate',
... | 1 | 2016-08-21T16:14:55Z | 39,067,057 | <p>Here is a NumPy solution:</p>
<pre><code>In [120]: df
Out[120]:
a b c d e f g h
0 1.334444 0.322029 0.302296 -0.841236 -0.360488 -0.860188 -0.157942 1.522082
1 2.056572 0.991643 0.160067 -0.066473 0.235132 0.533202 1.282371 -2.050731
2 0.9... | 2 | 2016-08-21T17:40:51Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
How to merge two tables as mentioned in the following post? | 39,066,282 | <p>I have two data sets:
1)
Date::</p>
<pre><code>01/03/16 00:00:01
01/03/16 00:00:11
01/03/16 00:00:21
01/03/16 00:00:31
01/03/16 00:00:41
01/03/16 00:00:51
01/03/16 00:01:01
01/03/16 00:01:11
01/03/16 00:01:21
.....
</code></pre>
<p>until 31/03/16 23:59:58 with each date row have a difference of 10 sec.</p>
<p>a... | -2 | 2016-08-21T16:16:47Z | 39,067,793 | <p>you could try this:</p>
<pre><code>Option Explicit
Sub main()
Dim startDateRng As Range, endDateRng As Range, dateRng As Range, locationRng As Range
Dim iniCell As Long, endCell As Long, iCell As Long
SetRanges startDateRng, endDateRng, dateRng, locationRng
For iCell = 1 To startDateRng.Count '&l... | 0 | 2016-08-21T18:56:55Z | [
"python",
"excel",
"vba"
] |
Theano function not working on a simple, 4-value array | 39,066,284 | <p>I was working through the theano documentation/tutorial, and the very first example was this: </p>
<pre><code>>>> import numpy
>>> import theano.tensor as T
>>> from theano import function
>>> x = T.dscalar('x')
>>> y = T.dscalar('y')
>>> z = x + y
>>> ... | 0 | 2016-08-21T16:17:38Z | 39,075,731 | <p><code>function f</code> take two scalars as input and return their sum, each element of <code>r</code> i.e (x, y) is a <a href="https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">tuple</a> not a scalar. This should work:</p>
<pre><code>import numpy as np
import theano.tensor... | 1 | 2016-08-22T09:22:44Z | [
"python",
"arrays",
"theano",
"brackets",
"square-bracket"
] |
bitwise left shift in python | 39,066,369 | <p>I have submitted a code-snippet shown below:</p>
<pre><code>def shift():
m=8
low='10100111'
lw=int(low,2)
lw=lw<<1
l_bin=bin(lw)[2:].zfill(m)
</code></pre>
<p>Output ==> 101001110(9-bits)</p>
<p>while desired output ==> 01001110(8-bits)</p>
<p>I could understand that right shifting the ... | -1 | 2016-08-21T16:25:12Z | 39,066,466 | <p>You have to mask the upper bits if you want to emulate a byte (like it would behave in C)</p>
<pre><code>lw=(lw<<1) & 0xFF
</code></pre>
<p>of course, that is, if you keep <code>m</code> set to 8 or it won't work.</p>
<p>If <code>m</code> varies, you can compute (or pre-compute) the mask value like this... | 2 | 2016-08-21T16:36:00Z | [
"python",
"python-2.7",
"bit-manipulation",
"bit-shift"
] |
Normalising an array of dicts which contain both values directly and other dicts, across whole array | 39,066,371 | <p>I have a huge array which looks like (example rows):</p>
<pre><code>[
{
'value':21,
'openValues':{
'a':24,
'b':56,
'c':78
}
},
{
'value':12,
'openValues':{
'a':98,
... | -3 | 2016-08-21T16:25:34Z | 39,067,821 | <p>Not sure I've understood your question very well, but assuming you want to normalize between [0-1] considering the min & max values from all posible items in your arrays, here's a possible solution:</p>
<pre><code>array = [
{
'value': 21,
'openValues': {
'a': 24,
'b':... | 1 | 2016-08-21T19:01:01Z | [
"python",
"arrays",
"dictionary",
"normalization"
] |
Why am I getting error 404 "Video not found" from the YouTube API? | 39,066,378 | <p>I'm currently writing a slack/youtube plugin to add posted youtube links to a playlist. I think the code is ok but I am just starting out and don't know if it's oauth or me.</p>
<p>Here is the error:</p>
<pre><code> Traceback (most recent call last):
File "slackapi.py", line 124, in <module>
add_video_... | 0 | 2016-08-21T16:26:15Z | 39,066,464 | <p>A 404 error means that the site or API cannot be found. You will come across this a lot with APIs. Unfortunately I can't help you further as I haven't used Python with APIs but just check what your requesting and sending</p>
| 0 | 2016-08-21T16:35:26Z | [
"python",
"youtube-api",
"python-3.5"
] |
Why am I getting error 404 "Video not found" from the YouTube API? | 39,066,378 | <p>I'm currently writing a slack/youtube plugin to add posted youtube links to a playlist. I think the code is ok but I am just starting out and don't know if it's oauth or me.</p>
<p>Here is the error:</p>
<pre><code> Traceback (most recent call last):
File "slackapi.py", line 124, in <module>
add_video_... | 0 | 2016-08-21T16:26:15Z | 39,070,428 | <p>Found it. It was the code. I was parsing all the output into .lower() so the video IDs were not correct. Thanks for your help guys. </p>
<p>Also the <code>credentials = run(flow, storage)</code> is deprecated. It should be <code>credentials = run_flow(flow, storage)</code>.</p>
| 0 | 2016-08-22T01:53:05Z | [
"python",
"youtube-api",
"python-3.5"
] |
Reduce number of levels for large categorical variables | 39,066,382 | <p>Are there some ready to use libraries or packages for python or R to reduce the number of levels for large categorical factors?</p>
<p>I want to achieve something similar to <a href="http://stackoverflow.com/questions/28968983/r-binning-categorical-variables">R: "Binning" categorical variables</a> but enc... | 0 | 2016-08-21T16:26:41Z | 39,066,699 | <p>Here is an example in <code>R</code> using <code>data.table</code> a bit, but it should be easy without <code>data.table</code> also.</p>
<pre><code># Load data.table
require(data.table)
# Some data
set.seed(1)
dt <- data.table(type = factor(sample(c("A", "B", "C"), 10e3, replace = T)),
weight ... | 1 | 2016-08-21T17:03:42Z | [
"python",
"encoding",
"categorical-data",
"binning"
] |
Reduce number of levels for large categorical variables | 39,066,382 | <p>Are there some ready to use libraries or packages for python or R to reduce the number of levels for large categorical factors?</p>
<p>I want to achieve something similar to <a href="http://stackoverflow.com/questions/28968983/r-binning-categorical-variables">R: "Binning" categorical variables</a> but enc... | 0 | 2016-08-21T16:26:41Z | 39,066,722 | <p>Here's an approach using <code>base</code> R:</p>
<pre><code>set.seed(123)
d <- data.frame(x = sample(LETTERS[1:5], 1e5, prob = c(.4, .3, .2, .05, .05), replace = TRUE))
recat <- function(x, new_cat, threshold) {
x <- as.character(x)
xt <- prop.table(table(x))
factor(ifelse(x %in% names(xt)... | 0 | 2016-08-21T17:06:07Z | [
"python",
"encoding",
"categorical-data",
"binning"
] |
Reduce number of levels for large categorical variables | 39,066,382 | <p>Are there some ready to use libraries or packages for python or R to reduce the number of levels for large categorical factors?</p>
<p>I want to achieve something similar to <a href="http://stackoverflow.com/questions/28968983/r-binning-categorical-variables">R: "Binning" categorical variables</a> but enc... | 0 | 2016-08-21T16:26:41Z | 39,947,700 | <p>The R package <code>forcats</code> has <code>fct_lump</code> for this purpose.</p>
<pre><code>fct_lump(f, n)
</code></pre>
<p>Where <code>f</code> is the factor and <code>n</code> is the number of most common levels to be preserved. Others are recoded to <code>Other</code>.</p>
| 1 | 2016-10-09T19:32:28Z | [
"python",
"encoding",
"categorical-data",
"binning"
] |
Selenium webdriver with Python on chrome - Scroll to the exact middle of an element | 39,066,399 | <p>I'm trying to click on an element solely by getting it with XPATH. I get an exception that the element is un-clickable in the given location.</p>
<p>I know for sure that the center of the element is clickable, so how do i get the exact middle (x,y) of the element and click it with Selenium using Python?</p>
<p>EDI... | 0 | 2016-08-21T16:28:36Z | 39,067,206 | <p>Actually selenium itself try to click on element at center position of element, so this exception normally occurs when target element overlayed by other element due to size of the window or any other reason, like it would be hidden inside scroll bar etc.</p>
<p>So basically if you want to get exact element into vie... | 0 | 2016-08-21T17:54:33Z | [
"python",
"selenium-webdriver",
"selenium-chromedriver"
] |
virtualenvwrapper: Command "python setup.py egg_info" failed with error code 1 | 39,066,431 | <p>When trying to install <strong>virtualenvwrapper</strong> on my mac os v10.11 using:</p>
<blockquote>
<p>sudo pip install virtualenvwrapper</p>
</blockquote>
<p>I got the following error message:</p>
<blockquote>
<p>Command "python setup.py egg_info" failed with error code 1 in
/private/tmp/pip-build-ktzs4x... | 1 | 2016-08-21T16:31:59Z | 39,066,467 | <p>You can try the solution explained <a href="https://coderwall.com/p/-k_93g/mac-os-x-valueerror-unknown-locale-utf-8-in-python" rel="nofollow">here</a></p>
<blockquote>
<p>add these lines to your ~/.bash_profile:
<code>
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8</code></p>
</blockquote>
| 3 | 2016-08-21T16:36:08Z | [
"python",
"django",
"web",
"virtualenv",
"virtualenvwrapper"
] |
Scrapy crawls only one page | 39,066,445 | <p>I have made a scrapy spider that I would like to crawl all the pages but it only crawls to the second page and then stops.
It seems that within the <code>if next_page:</code> loop the url only changes to the second page and then sticks there. I think I am misunderstanding how http responses work because it seems to... | 0 | 2016-08-21T16:33:36Z | 39,069,916 | <p>On the 2nd page the 1st link (the one you choose) is the one pointing to the previous page. Just send any links in order and let the de-duplicator cancel out any duplicates:</p>
<pre><code> if next_page:
for i in next_page
url = response.urljoin(i.extract())
print("THIS IS THE URL... | 1 | 2016-08-22T00:07:07Z | [
"python",
"web-scraping",
"scrapy"
] |
Create a dicom print server using python | 39,066,485 | <p>I am trying to create a dicom print server using python. As client,I am using QuantorMeddemo software which can act as an x-ray machine scanning software. So far I managed to create a PACS server using pynetdicom and have received dcm data from QUantor Med.But that doesnt register as a print server(I guess) and only... | 1 | 2016-08-21T16:37:54Z | 39,076,245 | <p>You can try dcmtk whick have a print SCP:</p>
<p><a href="http://dicom.offis.de/dcmtk.php.en" rel="nofollow">dcmtk</a></p>
| 0 | 2016-08-22T09:45:48Z | [
"python",
"dicom"
] |
Django: updated_at/created_at fields have TZ info are "too" precise | 39,066,524 | <p>My env: Django 1.9.7, Python 3.5.2</p>
<p>I use the following model code to enforce values into <code>updated_at</code> and <code>created_at</code> fields in my model class.</p>
<pre><code>class MyObject(models.Model):
...
...
...
created_at = models.DateTimeField(db_index=True, auto_now_add=True)
u... | 0 | 2016-08-21T16:43:23Z | 39,066,993 | <p>You can define your own default value (script below), but with <code>auto_now</code> you cannot do anything, because implementation doesn't offer more.</p>
<pre><code>import datetime
def default_datetime():
now = datetime.datetime.now()
now.replace(microsecond=0)
return now
class MyObje... | 0 | 2016-08-21T17:34:26Z | [
"python",
"django-models"
] |
OpenCV, Python and Raspberry Pi | 39,066,538 | <p>I have a problem considering Python and OpenCV programming on Raspberry Pi.
I want to track an object in video and get the position of that object.</p>
<p>I wrote this code, I tried using HoughCircle but I get only one tracked picture. I want to keep the tracking constant. I want to track a red triangle.</p>
<pre>... | -1 | 2016-08-21T16:44:48Z | 39,376,317 | <p>I succeeded to track the center of a triangle but now i have diff problem, my servo doesn't want to respond to the duty cycle I'm sending to him, can please someone help me</p>
<pre><code>from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np
from matplotlib im... | 0 | 2016-09-07T17:49:04Z | [
"python",
"opencv",
"numpy",
"raspberry-pi2"
] |
Python: How remove duplicates words in string that are not next each other? | 39,066,559 | <p>In the example below, I need to remove only the third "animale" which is alone in the string. How can I do that?</p>
<pre><code>a = 'animale animale eau toilette animale'
</code></pre>
<p>Second "animale": dont remove</p>
<p>Third "animale": remove</p>
| 1 | 2016-08-21T16:47:40Z | 39,066,704 | <pre><code>a = "animale animale eau toilette animale"
words = a.split()
cleaned_words = []
skip = False
for i in range(len(words)):
word = words[i]
print(word)
if skip:
cleaned_words.append(word)
skip = False
try:
next_word = words[i+1]
print(next_word)
except Index... | 0 | 2016-08-21T17:04:03Z | [
"python",
"string"
] |
Python: How remove duplicates words in string that are not next each other? | 39,066,559 | <p>In the example below, I need to remove only the third "animale" which is alone in the string. How can I do that?</p>
<pre><code>a = 'animale animale eau toilette animale'
</code></pre>
<p>Second "animale": dont remove</p>
<p>Third "animale": remove</p>
| 1 | 2016-08-21T16:47:40Z | 39,066,817 | <p>If i understand your question correctly, you want to remove any occurrences of words that are duplicates but not adjacent. I think this solution works for that:</p>
<pre><code>from collections import defaultdict
def remove_duplicates(s):
result = []
word_counts = defaultdict(int)
words = s.split()
... | 0 | 2016-08-21T17:15:33Z | [
"python",
"string"
] |
Python: How remove duplicates words in string that are not next each other? | 39,066,559 | <p>In the example below, I need to remove only the third "animale" which is alone in the string. How can I do that?</p>
<pre><code>a = 'animale animale eau toilette animale'
</code></pre>
<p>Second "animale": dont remove</p>
<p>Third "animale": remove</p>
| 1 | 2016-08-21T16:47:40Z | 39,067,545 | <p>how about this</p>
<pre><code>from collections import defaultdict
def remove_no_adjacent_duplicates(string):
position = defaultdict(list)
words = string.split()
for i,w in enumerate(words):
position[w].append(i)
for w,pos_list in position.items():
adjacent = set()
for i in r... | 1 | 2016-08-21T18:29:22Z | [
"python",
"string"
] |
Python: How remove duplicates words in string that are not next each other? | 39,066,559 | <p>In the example below, I need to remove only the third "animale" which is alone in the string. How can I do that?</p>
<pre><code>a = 'animale animale eau toilette animale'
</code></pre>
<p>Second "animale": dont remove</p>
<p>Third "animale": remove</p>
| 1 | 2016-08-21T16:47:40Z | 39,068,100 | <p>This one works for both:</p>
<p><code>'animale animale eau toilette animale'</code></p>
<p>and</p>
<p><code>'animale animale eau toilette animale eau eau'</code></p>
<p>Here's the code:</p>
<pre><code>from collections import Counter
def cleanup(words):
splitted = words.split()
counter = Counter(splitt... | 0 | 2016-08-21T19:30:24Z | [
"python",
"string"
] |
Scikit-Learn: Std.Error, p-Value from LinearRegression | 39,066,567 | <p>I've been trying to get the standard error & p-Values by using LR from scikit-learn. But no success. </p>
<p>I've end up finding up this <a href="https://regressors.readthedocs.io/en/latest/usage.html" rel="nofollow">article</a>: but the std error & p-value does not match that from the statsmodel.api OLS m... | 1 | 2016-08-21T16:48:43Z | 39,136,835 | <p>Clipped from <a href="http://stats.stackexchange.com/questions/203740/logistic-regression-scikit-learn-vs-statsmodels">CrossValidate post</a></p>
<pre><code># sklearn output
model = LogisticRegression(fit_intercept = False, C = 1e9)
mdl = model.fit(X, y)
model.coef_
# sm
logit = sm.Logit(y, X)
logit.fit().params
<... | 0 | 2016-08-25T04:45:20Z | [
"python",
"machine-learning",
"scikit-learn",
"linear-regression"
] |
How to avoid dependency injection in Django? | 39,066,590 | <p>I'm trying to figure out how to avoid dependency injection in my project. There is a file <code>notifications.py</code> in app directory. </p>
<p>File <code>notifications.py</code> contains methods for sending emails to admin and users. To get admins email, I need to check object of <code>SystemData</code> model. B... | 1 | 2016-08-21T16:51:35Z | 39,066,713 | <p>You can solve circular dependencies in functions by using inline imports:</p>
<pre><code>class SomeModel(models.Model):
....
def save(...):
from .notifications import send_message_to_admin
send_message_to_admin('message')
</code></pre>
<p>This will delay the import statement until the funct... | 2 | 2016-08-21T17:04:44Z | [
"python",
"django",
"python-import"
] |
How to avoid dependency injection in Django? | 39,066,590 | <p>I'm trying to figure out how to avoid dependency injection in my project. There is a file <code>notifications.py</code> in app directory. </p>
<p>File <code>notifications.py</code> contains methods for sending emails to admin and users. To get admins email, I need to check object of <code>SystemData</code> model. B... | 1 | 2016-08-21T16:51:35Z | 39,066,733 | <p>Apart from using circular imports you can either do it like that:</p>
<pre><code>from django.core.mail import EmailMessage
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import SystemData, SomeModel
@receiver(post_save, sender=SomeModel)
def send_message_to_admin... | 2 | 2016-08-21T17:06:59Z | [
"python",
"django",
"python-import"
] |
Python Guessing game - incomplete code | 39,066,610 | <p>Can someone please help me re-design this code so that the program prompts the user to choose Easy, Medium or Hard.</p>
<pre><code>Easy: maxNumber = 10
Medium: maxNumber = 50
Hard: maxNumber = 100
</code></pre>
<p>It should choose a random number between 0 and the maxNumber.
The program will loop calling a funct... | -2 | 2016-08-21T16:53:38Z | 39,066,764 | <p>You could do something like this:</p>
<pre><code>from random import randint
myName = input("what's your name? ")
def pre_game():
difficulty = input("Choose difficulty: type easy medium or hard: ")
main_loop(difficulty)
def main_loop(difficulty):
if difficulty == "easy":
answer = randint(0, 10)
... | -1 | 2016-08-21T17:09:45Z | [
"python"
] |
"Segmentation Fault" in matplotlib running example Librosa script | 39,066,625 | <p>After many issues I've installed Librosa (<a href="https://github.com/librosa/librosa" rel="nofollow">https://github.com/librosa/librosa</a>) on Linux Mint 18 Mate x64. When I want to run example script, e.g.: <a href="http://librosa.github.io/librosa/generated/librosa.feature.tempogram.html#librosa.feature.tempogra... | 0 | 2016-08-21T16:55:26Z | 39,259,837 | <p>Finally, I've solved this issue by installing these packages: <code>sudo apt-get install tk-dev libpng-dev libffi-dev dvipng texlive-latex-base</code> and reinstalling <em>matplotlib</em> using <em>pip</em>. I have also changed background in <em>matplotlib</em> on <em>TkAgg</em>. There is a beginning of a code with ... | 0 | 2016-08-31T22:17:12Z | [
"python",
"python-2.7",
"qt",
"matplotlib",
"librosa"
] |
All-to-All comparison of two lists in Python | 39,066,655 | <p>I'm struggling with some performance complications.
The task in hand is to extract the similarity value between two strings. For this I am using <code>fuzzywuzzy</code>:</p>
<pre><code>from fuzzywuzzy import fuzz
print fuzz.ratio("string one", "string two")
print fuzz.ratio("string one", "string two which is signi... | 0 | 2016-08-21T16:59:05Z | 39,067,127 | <p>If you need to count the number of times each of the statements appear then no, there is no way I know of to get a huge speedup over the n^2 operations needed to compare the elements in each list. You might be able to avoid some string matching by using the length to rule out the possibility that a match could occur... | 1 | 2016-08-21T17:47:26Z | [
"python",
"performance",
"fuzzywuzzy"
] |
All-to-All comparison of two lists in Python | 39,066,655 | <p>I'm struggling with some performance complications.
The task in hand is to extract the similarity value between two strings. For this I am using <code>fuzzywuzzy</code>:</p>
<pre><code>from fuzzywuzzy import fuzz
print fuzz.ratio("string one", "string two")
print fuzz.ratio("string one", "string two which is signi... | 0 | 2016-08-21T16:59:05Z | 39,067,506 | <p>I've made something on my own for you (python 2.7):</p>
<pre><code>from __future__ import division
import time
from itertools import izip
from fuzzywuzzy import fuzz
one = "different simliar"
two = "similar"
def compare(first, second):
smaller, bigger = sorted([first, second], key=len)
s_smaller= sma... | 1 | 2016-08-21T18:25:03Z | [
"python",
"performance",
"fuzzywuzzy"
] |
All-to-All comparison of two lists in Python | 39,066,655 | <p>I'm struggling with some performance complications.
The task in hand is to extract the similarity value between two strings. For this I am using <code>fuzzywuzzy</code>:</p>
<pre><code>from fuzzywuzzy import fuzz
print fuzz.ratio("string one", "string two")
print fuzz.ratio("string one", "string two which is signi... | 0 | 2016-08-21T16:59:05Z | 39,082,168 | <p>The best solution I can think of is to use the <a href="http://www.ibm.com/analytics/us/en/technology/stream-computing/" rel="nofollow">IBM Streams framework</a> to parallelize your essentially unavoidable O(n^2) solution.</p>
<p>Using the framework, you would be able to write a single-threaded kernel similar to th... | 0 | 2016-08-22T14:29:42Z | [
"python",
"performance",
"fuzzywuzzy"
] |
how to get rid of unicode characters in python output? | 39,066,761 | <p>i am trying to load a json file and then trying to parse it later.
however, in the output i keep getting the 'u' characters.
I tried to open the file with encoding='utf-8' which dint solve the problem.
i am using python 2.7. is there a straight forward approach or workaround to ignore and get ride of the 'u' charact... | 0 | 2016-08-21T17:09:35Z | 39,066,833 | <p>Use json.dumps and decode it to convert it to string</p>
<pre><code>data = json.dumps(d, ensure_ascii=False).decode('utf8')
print data
</code></pre>
| 2 | 2016-08-21T17:17:06Z | [
"python",
"json",
"unicode"
] |
how to get rid of unicode characters in python output? | 39,066,761 | <p>i am trying to load a json file and then trying to parse it later.
however, in the output i keep getting the 'u' characters.
I tried to open the file with encoding='utf-8' which dint solve the problem.
i am using python 2.7. is there a straight forward approach or workaround to ignore and get ride of the 'u' charact... | 0 | 2016-08-21T17:09:35Z | 39,067,349 | <p><code>u</code> just indicates a Unicode string. If you print the string, it won't be displayed:</p>
<pre><code>d = {u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544}}
print 'Status:',d[u'install'][u'Status']
</code></pre>
<p>Output:</p>
<pre><code>Status: In Progress...
</code></pre>
| 0 | 2016-08-21T18:09:27Z | [
"python",
"json",
"unicode"
] |
Python 3.4 ctypes message box doesn't open with other code included | 39,066,820 | <p>Normally this code works fine when called.</p>
<pre><code>import ctypes
def message_box(title, text):
ctypes.windll.user32.MessageBoxW(0, text, title, 1)
</code></pre>
<p>But when it's used with other code it hangs at the line where message_box is called.</p>
<pre><code>import ctypes
def message_box(title, ... | 0 | 2016-08-21T17:15:39Z | 39,068,289 | <p>I found how to do it.</p>
<p>In the fourth argument for the message box, you need to put in values separated by pipes ('|'). From my limited testing, the MB arguments define the buttons that the user can click, apart from MB_SYSTEMMODAL which brings the window to the front. The ICON arguments define what noise the ... | 0 | 2016-08-21T19:51:00Z | [
"python",
"ctypes"
] |
How to crawl multiple websites and create a text file with the plain text | 39,066,865 | <p>I started a new project and I'm new using python scrapy.
I'm trying to craw through multiple websites and get the plain text from them. After that I would like to create a text-file with the raw text.</p>
<p>This is the code that I have. Maybe you can help me and give me some tips on how e.g. I can read other links... | 0 | 2016-08-21T17:20:49Z | 39,067,006 | <p>I used <strong>BeautifulSoup</strong> to get the parsedHtml and this is how i retrieved html links from the current html page.</p>
<pre><code>parsedHtml = BeautifulSoup(htmlSource, "lxml")
for href in parsedHtml.find_all('a'):
linkedUrl = href.get('href')
</code></pre>
| 0 | 2016-08-21T17:35:45Z | [
"python",
"scrapy",
"web-crawler"
] |
How to crawl multiple websites and create a text file with the plain text | 39,066,865 | <p>I started a new project and I'm new using python scrapy.
I'm trying to craw through multiple websites and get the plain text from them. After that I would like to create a text-file with the raw text.</p>
<p>This is the code that I have. Maybe you can help me and give me some tips on how e.g. I can read other links... | 0 | 2016-08-21T17:20:49Z | 39,069,989 | <p>Just consider extending one later examples from the <a href="http://doc.scrapy.org/en/latest/intro/tutorial.html#following-links" rel="nofollow">same page</a>. For example:</p>
<pre><code>import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [ "http://... | 0 | 2016-08-22T00:22:42Z | [
"python",
"scrapy",
"web-crawler"
] |
Duplicate keys in dictionary from database | 39,066,889 | <p>when i make a query to my database, i return the values as such:</p>
<pre><code>tuplematches = cursor.fetchall()
for items in tuplematches:
print(items)
</code></pre>
<p>prints as:</p>
<pre><code> NAME/ PRICE/ HOURS/
1. ('honda accord 2nd light', 20.00, 10.0)
2. ('honda accord 2nd ligh... | 0 | 2016-08-21T17:23:11Z | 39,066,991 | <p>Since you are dealing with database already, why not do the aggregation within the query?</p>
<pre><code>select NAME, SUM(PRICE) AS PRICE, SUM(HOURS) AS HOURS, COUNT(*) AS OCCURENCE
from ...
group by NAME
</code></pre>
| 0 | 2016-08-21T17:34:22Z | [
"python",
"sqlite3"
] |
Copy the result of a selection grouped by into a table | 39,066,947 | <p>Ok, first of all: I am quite new to PostgreSQL and programming in general.
So I have two tables. One table (cars) is:</p>
<pre><code> id | brand | model | price
----+---------+-------+-------
1 | Opel | Astra | 12000
2 | Citroen | C1 | 12000
3 | Citroen | C2 | 15000
4 | Citroen | C3 | 18000
... | 1 | 2016-08-21T17:29:55Z | 39,069,034 | <p>When using <code>cur.execute</code>, you should never use the <code>%</code> operator. It opens up your queries to SQL injection attacks. </p>
<p>Instead, use the built-in query parameterization like so:</p>
<p><code>cur.execute ("""INSERT INTO temp (max_price_int) VALUES (%s)""",(results,))
</code></p>
<p>See d... | 1 | 2016-08-21T21:29:28Z | [
"python",
"postgresql"
] |
iterating through list - splitting strings | 39,066,980 | <p>I have a list of <code>drawingnumbers</code>, I am attempting to split these strings and then append to a number of lists. </p>
<p>I am hoping to end up with a number of lists, which contains each relevant piece of the original string. </p>
<p>At the minute my definition is iterating through the list, but overwrit... | 2 | 2016-08-21T17:33:18Z | 39,067,031 | <p>You can use <code>zip</code> after splitting each element in the list to transpose your lists as:</p>
<pre><code>zip(*[i.split("-") for i in drawingnumber])
</code></pre>
<p>And assign them to lists names:</p>
<pre><code>building, originator, discipline, level, scope, \
drawingtype, drawingsubtype, numbera, numbe... | 2 | 2016-08-21T17:38:13Z | [
"python",
"list",
"split"
] |
iterating through list - splitting strings | 39,066,980 | <p>I have a list of <code>drawingnumbers</code>, I am attempting to split these strings and then append to a number of lists. </p>
<p>I am hoping to end up with a number of lists, which contains each relevant piece of the original string. </p>
<p>At the minute my definition is iterating through the list, but overwrit... | 2 | 2016-08-21T17:33:18Z | 39,067,059 | <p>Just change</p>
<pre><code> for i in drawingnumber:
building, originator, discipline, level, scope, drawingtype,drawingsubtype, numbera, numberb = i.split("-")
</code></pre>
<p>to:</p>
<pre><code> for i in drawingnumber:
building_, originator_, discipline_, level_, scope_, drawingtype_,drawingsubtyp... | 0 | 2016-08-21T17:41:10Z | [
"python",
"list",
"split"
] |
iterating through list - splitting strings | 39,066,980 | <p>I have a list of <code>drawingnumbers</code>, I am attempting to split these strings and then append to a number of lists. </p>
<p>I am hoping to end up with a number of lists, which contains each relevant piece of the original string. </p>
<p>At the minute my definition is iterating through the list, but overwrit... | 2 | 2016-08-21T17:33:18Z | 39,067,136 | <pre><code>drawingnumber = ["AAA601-XX1-A-L00-1028-DR-GA-200-001",
"AAA602-XX2-A-L10-1028-DR-GA-200-001",
"AAA603-XX3-A-L00-1029-DR-GA-200-001",
"AAA604-XX4-A-L00-1029-DR-GA-200-XXX"]
building = []
buildinglist = []
originator = []
discipline = []
level = []
scope = []
drawingtype = []
drawingsubtype ... | 0 | 2016-08-21T17:48:12Z | [
"python",
"list",
"split"
] |
Python program to multiply two polynomial where each term of the polynomial is represented as a pair of integers (coefficient, exponent)? | 39,066,982 | <p>fuction takes two list(having tuples as values) as input
i got in my mind following algorithm to write code for this, but to write it properly.</p>
<p>-->firstly make required no. of dictionary to store coefficient of each power is multiplied with all coefficient of polynomial p2.</p>
<p>then all dictionary coeffi... | -2 | 2016-08-21T17:33:39Z | 39,067,151 | <p>If I understand correctly, you want a function to multiply two polynomials and return the result. In the future, try and post a specific question. Here is code that will work for you:</p>
<pre><code>def multiply_terms(term_1, term_2):
new_c = term_1[0] * term_2[0]
new_e = term_1[1] + term_2[1]
return (n... | 1 | 2016-08-21T17:49:20Z | [
"python",
"python-2.7",
"python-3.x"
] |
bot.polling funciton in a try-except block, do not run the rest of the code | 39,067,029 | <p>In my python code, the polling function is in a try-except block </p>
<pre><code>bot = telebot.TeleBot(TOKEN)
while True:
try:
status = "Conected"
bot.polling(none_stop=False, interval=1)
except:
status = "failure"
print status
#do something..
time.sleep(1)
</code>... | 0 | 2016-08-21T17:38:05Z | 39,067,049 | <p>Apologies, my last answer wasn't as clear as it could have been.</p>
<p>So when working with try/except you'll want to make sure that you've got the indentation under the While look and the Try: and Except: (and Else, Finally if you're using them too).</p>
<p>Next, you want the action that you're looking for to ta... | 0 | 2016-08-21T17:40:18Z | [
"python",
"bots",
"polling",
"telegram",
"try-except"
] |
Squaring values of dictionary | 39,067,114 | <p>I am using Python 2.7, still learning about dictionaries. I am focusing on performing numerical computations for dictionaries and need some help.</p>
<p>I have a dictionary and I would like to square the values in it:</p>
<pre><code> dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'... | 3 | 2016-08-21T17:46:29Z | 39,067,165 | <p>It's because you have nested dictionaries, look:</p>
<pre><code>results = {}
for key, data_dict in dict1.iteritems():
results[key] = {key: pow(value,2.) for key, value in data_dict.iteritems()}
</code></pre>
| 4 | 2016-08-21T17:50:35Z | [
"python",
"dictionary"
] |
Squaring values of dictionary | 39,067,114 | <p>I am using Python 2.7, still learning about dictionaries. I am focusing on performing numerical computations for dictionaries and need some help.</p>
<p>I have a dictionary and I would like to square the values in it:</p>
<pre><code> dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'... | 3 | 2016-08-21T17:46:29Z | 39,067,171 | <p>You were very close with the dictionary comprehension. The issue is that <em>value</em> in your solution is a dictionary itself, so you have to iterate over it too.</p>
<pre><code>dict1_squared = {key: {k: pow(v,2) for k,v in value.items()} for key, value in dict1.items()}
</code></pre>
| 3 | 2016-08-21T17:51:27Z | [
"python",
"dictionary"
] |
Squaring values of dictionary | 39,067,114 | <p>I am using Python 2.7, still learning about dictionaries. I am focusing on performing numerical computations for dictionaries and need some help.</p>
<p>I have a dictionary and I would like to square the values in it:</p>
<pre><code> dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'... | 3 | 2016-08-21T17:46:29Z | 39,067,216 | <p>One of those cases where I might prefer loops:</p>
<pre><code>for d in dict1.values():
for k in d:
d[k] **= 2
</code></pre>
| 5 | 2016-08-21T17:55:38Z | [
"python",
"dictionary"
] |
Squaring values of dictionary | 39,067,114 | <p>I am using Python 2.7, still learning about dictionaries. I am focusing on performing numerical computations for dictionaries and need some help.</p>
<p>I have a dictionary and I would like to square the values in it:</p>
<pre><code> dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'... | 3 | 2016-08-21T17:46:29Z | 39,067,237 | <p>Based on your question I think it would be a good idea to work through a tutorial. <a href="http://www.tutorialspoint.com/python/index.htm" rel="nofollow">Here is one from tutorialspoint</a>. You said you are trying to square the dictionary, but that is not what you are trying to do. You are trying to square the val... | 1 | 2016-08-21T17:58:10Z | [
"python",
"dictionary"
] |
Squaring values of dictionary | 39,067,114 | <p>I am using Python 2.7, still learning about dictionaries. I am focusing on performing numerical computations for dictionaries and need some help.</p>
<p>I have a dictionary and I would like to square the values in it:</p>
<pre><code> dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'... | 3 | 2016-08-21T17:46:29Z | 39,067,247 | <p>If your structure is alway the same you can do this way:</p>
<pre><code>for k,w in dict1.items():
for k1,w1 in w.items():
print w1, pow(w1,2)
20 400
1 1
2 4
35 1225
5 25
15 225
20 400
3 9
3 9
16 256
2 4
16 256
</code></pre>
| 0 | 2016-08-21T17:59:13Z | [
"python",
"dictionary"
] |
variables defined in a %time statement inside a method are not accessible after the statement | 39,067,203 | <p>This seems to work fine - </p>
<pre><code>%time a = "abc"
print(a)
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 19.1 µs
abc
</code></pre>
<p>This doesn't - </p>
<pre><code>def func():
%time b = "abc"
print(b)
func()
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 31 µs
------------... | 1 | 2016-08-21T17:54:27Z | 39,067,622 | <p>I am almost certain this is an IPython bug. <a href="https://github.com/ipython/ipython/issues/9892" rel="nofollow">Reported here</a>.</p>
<pre><code>In [31]: def func():
...: a = 2
...: %time b = 1
...: print(locals())
...: print a
...: print b
In [32]: func()
CPU times: us... | 1 | 2016-08-21T18:36:58Z | [
"python",
"python-2.7",
"ipython"
] |
Pygame for Python3.5 on CentOS 7 | 39,067,306 | <p>Thanks in advance for the help.</p>
<p>I am trying to install Pygame for Python 3.5. </p>
<p>I have spent many hours doing research and found that it was possible for Windows, yet nothing about CentOS. </p>
<p><strong>Is it possible to install Pygame for Python 3.5 on CentOS 7?</strong></p>
<p><strong>If so, how... | 0 | 2016-08-21T18:05:58Z | 39,067,446 | <p>You can compile pygame from source code. </p>
<p>1) Get dependances: </p>
<pre><code>yum install python3 python3-tools python3-devel SDL SDL-devel portmidi portmidi-devel ffmpeg ffmpeg-devel SDL_image-devel SDL_mixer-devel SDL_ttf-devel libjpeg-turbo-devel
cd /usr/lib
ln -s libportmidi.so libporttime.so
</c... | 1 | 2016-08-21T18:18:56Z | [
"python",
"python-3.x",
"pygame",
"install",
"centos7"
] |
how to draw rectangles using list in python | 39,067,400 | <pre><code>for line, images_files in zip(lines, image_list):
info = line.split(',')
image_index = [int(info[0])]
box_coordiante1 = [info[2]]
box_coordiante2 = [info[3]]
box_coordiante3 = [info[4]]
bo... | 2 | 2016-08-21T18:14:13Z | 39,069,104 | <p>I'm not very familiar with Python, but it seems like you want a plain number in the variables <code>image_index</code> and <code>box_coordinateN</code>. It looks like you're assigning single-element arrays to them. Try changing:</p>
<pre><code>image_index = [int(info[0])] // list containing one element: int(info[0]... | 0 | 2016-08-21T21:41:14Z | [
"python",
"image",
"python-2.7",
"draw",
"drawrectangle"
] |
Python + BeautifulSoup: Encoding Error | 39,067,445 | <p>If I run this code:</p>
<pre><code>for link in soup.findAll('a'):
href = link.get('href')
href = str(href)
</code></pre>
<p>I'm getting the following error in the last line</p>
<pre><code>href = str(href)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' in position 68: ordinal not in ran... | 0 | 2016-08-21T18:18:46Z | 39,067,608 | <p>In my native language we have a lot of "áçéà ó" characters, so I frequently found myself in a similar situation, and most of the decoding/encoding tips didn't worked all the way.</p>
<p>Found my way out reseting the sys default language at the begining of my code using:</p>
<pre><code>import sys
reload(sys)
s... | 0 | 2016-08-21T18:35:50Z | [
"python",
"python-2.7",
"encoding",
"beautifulsoup"
] |
Python + BeautifulSoup: Encoding Error | 39,067,445 | <p>If I run this code:</p>
<pre><code>for link in soup.findAll('a'):
href = link.get('href')
href = str(href)
</code></pre>
<p>I'm getting the following error in the last line</p>
<pre><code>href = str(href)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2018' in position 68: ordinal not in ran... | 0 | 2016-08-21T18:18:46Z | 39,091,779 | <p>If anyone ever faces this issue, here's how I resolved it:</p>
<p>Ideally, for the encoding issue, this should've worked:</p>
<pre><code>href = href.encode('utf-8')
href = str(href)
</code></pre>
<p>But in the set of webpages I was scrubbing, there were a few pages which didn't store any value in <code>href</code... | 0 | 2016-08-23T03:17:51Z | [
"python",
"python-2.7",
"encoding",
"beautifulsoup"
] |
"SyntaxError: non-keyword arg after keyword arg" when trying to print values of variables in a Label | 39,067,466 | <p>I was just trying to print the values of variables in a <code>Label</code> declaration as given below</p>
<pre><code>c = Label(root, text="Enter The Number Of Fruits In Basket%d Of Type%d\n"%j,i)
</code></pre>
<p>but I am getting the below error</p>
<blockquote>
<p>SyntaxError: non-keyword arg after keyword arg... | 0 | 2016-08-21T18:21:06Z | 39,067,504 | <p>Because you haven't used brackets around <code>j, i</code> for the format string, Python thinks that <code>i</code> is a variable being passed to the <code>Label()</code> function as the 3 argument, instead of the format string. And since you've put <code>text=</code> (as a named argument) already, then all subseque... | 1 | 2016-08-21T18:24:48Z | [
"python",
"python-2.7",
"tkinter"
] |
"rethinkdb.errors.ReqlServerCompileError: Expected 2 arguments but found 1 in:" when trying to .update() with Python rethink | 39,067,492 | <p>I'm working with RethinkDB using the Python module and right now I'm trying to update a model with this statement:</p>
<pre><code>results = rethink.table(model + "s").filter(id=results["id"]).update(data).run(g.rdb_conn)
</code></pre>
<p><code>model</code> is something being defined earlier in the function, in thi... | 2 | 2016-08-21T18:24:00Z | 39,067,872 | <p>This was caused by me trying to do <code>.filter()</code> with a single argument. <code>.filter()</code> is expecting a dictionary and I was simply providing <code>id = 92c5160a-db57-4c3b-b2b2-2704cdcfc2b7'</code>.</p>
<p>I changed the query around to </p>
<p><code>rethink.table(model + "s").get(results["id"]).upd... | 2 | 2016-08-21T19:05:38Z | [
"python",
"rethinkdb",
"rethinkdb-python"
] |
Pyspark: display a spark data frame in a table format | 39,067,505 | <p>I am using pyspark to read a parquet file like below:</p>
<pre><code>my_df = sqlContext.read.parquet('hdfs://myPath/myDB.db/myTable/**')
</code></pre>
<p>Then when I do <code>my_df.take(5)</code>, it will show <code>[Row(...)]</code>, instead of a table format like when we use the pandas data frame.</p>
<p>Is it... | 1 | 2016-08-21T18:24:58Z | 39,071,773 | <p>Yes: call the <code>toPandas</code> method on your dataframe and you'll get an <strong>actual</strong> pandas dataframe !</p>
| 0 | 2016-08-22T05:12:05Z | [
"python",
"pandas",
"pyspark",
"spark-dataframe"
] |
Files not being received correctly when sent through sockets over LAN | 39,067,537 | <p>I am trying to build an application that will send files over wireless LAN through the Python 3.4 socket module. It appears to be able to send files within one workstation, but when attempting to send files between two computers on the same network, the computer only appears to receive the first few thousand bytes, ... | 0 | 2016-08-21T18:28:46Z | 39,067,867 | <p>You are receiving only the first few packages of the transmission. This is because the <code>s.recv()</code> will receive the bytes that have reached the client already, but at most the number given as argument. On a local machine the transmission is fast, you will receive more.</p>
<p>To get all parts of the trans... | 0 | 2016-08-21T19:05:11Z | [
"python",
"sockets",
"lan"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.