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 |
|---|---|---|---|---|---|---|---|---|---|
Get Javascript code as string from url with Python | 38,167,758 | <p>I am trying to get a script written in Javascript from a URL with Python 2.7. I have tried using urllib, urllib2, and requests. They all return an empty string. The url contains no HTML elements it is just the javascript code.</p>
<p>Here's the link: <a href="http://go.pub2srv.com/apu.php?zoneid=676495" rel="nofoll... | 0 | 2016-07-03T07:40:54Z | 38,167,821 | <p>try this:</p>
<pre><code>import urllib2
data = urllib2.openurl("http://onclickads.net/apu.php?zoneid=676495")
js = ""
for lines in data.readlines():
js = js +lines
print js
</code></pre>
| 0 | 2016-07-03T07:48:13Z | [
"javascript",
"python",
"string",
"url"
] |
Tkinter Python Scale retrieving integer value | 38,167,774 | <p>Could anyone advise how to retrieve and update a label with a scale in Python. Currently it shows a very large real number. I have tried to type cast the value but this only works when I print to idle. I tried slider.get() but the label is blank. Also tried int(slider.get()) which works when I print to idle.</p>
<p... | 2 | 2016-07-03T07:42:54Z | 38,168,038 | <p>An other less complicated option and easy to use alternative is to use an instance of <code>tkinter.Scale()</code> class with which you can inject the <code>resolution</code> option to whatever value you want. The default one is the one you are looking for because its value is 1</p>
| 2 | 2016-07-03T08:17:48Z | [
"python",
"tkinter",
"scale"
] |
Tkinter Python Scale retrieving integer value | 38,167,774 | <p>Could anyone advise how to retrieve and update a label with a scale in Python. Currently it shows a very large real number. I have tried to type cast the value but this only works when I print to idle. I tried slider.get() but the label is blank. Also tried int(slider.get()) which works when I print to idle.</p>
<p... | 2 | 2016-07-03T07:42:54Z | 38,168,041 | <p>I don't see a way to control the resolution of the Scale widget, but it's fairly easy to modify the string it produces. According to <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Scale.html" rel="nofollow">these ttk docs</a> the Scale widget returns a float, but in my experiments it returns a string... | 3 | 2016-07-03T08:18:13Z | [
"python",
"tkinter",
"scale"
] |
What is the logical error in the for loop? | 38,167,805 | <p>This is the question:</p>
<blockquote>
<p>Use the debugging tool, IDLE Debugger to correct a logical error in a
Python program. The program should generate a pattern of rows of
asterisks in even columns and dollars in odd columns, where the number
of row and column is input by the user. The expected output ... | 0 | 2016-07-03T07:46:53Z | 38,167,856 | <p>You use col and row both for the input and for the variables of the loop step.</p>
<p>As <code>range</code> (and your algorithm) is zero based, after the first run of the inner <code>for</code>, the value of <code>col</code> will be smaller by one from the original desired input. And so on.</p>
<p>This will work:<... | 1 | 2016-07-03T07:52:28Z | [
"python"
] |
What is the logical error in the for loop? | 38,167,805 | <p>This is the question:</p>
<blockquote>
<p>Use the debugging tool, IDLE Debugger to correct a logical error in a
Python program. The program should generate a pattern of rows of
asterisks in even columns and dollars in odd columns, where the number
of row and column is input by the user. The expected output ... | 0 | 2016-07-03T07:46:53Z | 38,167,933 | <p>You should store the number the user inputs in a different variable than the ones you use to iterate.
This worked:</p>
<pre><code>num = int(input("Enter number of row and column: "))
for row in range(num):
for col in range(num):
if row % 2 == 0 and col % 2 == 1:
print('*', end='')
el... | 1 | 2016-07-03T08:03:47Z | [
"python"
] |
What is the logical error in the for loop? | 38,167,805 | <p>This is the question:</p>
<blockquote>
<p>Use the debugging tool, IDLE Debugger to correct a logical error in a
Python program. The program should generate a pattern of rows of
asterisks in even columns and dollars in odd columns, where the number
of row and column is input by the user. The expected output ... | 0 | 2016-07-03T07:46:53Z | 38,168,344 | <p>As a general rules: Too many logical conditions makes for difficult debugging and too many divisions makes for slow code (your doing a division operation up to 4 times per loop!) and your <code>for</code> loops are nested so you've squared the number of iterations required.</p>
<p>Set out as much of your logic as p... | 0 | 2016-07-03T08:57:46Z | [
"python"
] |
How to know when to use numpy.linalg instead of scipy.linalg? | 38,168,016 | <p>Received wisdom is to prefer <code>scipy.linalg</code> over <code>numpy.linalg</code> functions. For doing linear algebra, ideally (and conveniently) I would like to combine the functionalities of <code>numpy.array</code> and <code>scipy.linalg</code> without ever looking towards <code>numpy.linalg</code>. This is n... | 6 | 2016-07-03T08:15:01Z | 38,168,215 | <p>So, the normal rule is to just use <code>scipy.linalg</code> as it generally supports all of the <code>numpy.linalg</code> functionality and more. The <a href="https://docs.scipy.org/doc/scipy/reference/linalg.html">documentation</a> says this:</p>
<blockquote>
<p><strong>See also</strong></p>
<p><code>numpy... | 8 | 2016-07-03T08:41:20Z | [
"python",
"arrays",
"numpy",
"scipy"
] |
ctypes - get output from c++ function into python object | 38,168,197 | <p>I've followed the sample code in the second answer given here - <a href="http://stackoverflow.com/questions/145270/calling-c-c-from-python">Calling C/C++ from python?</a></p>
<p>and managed to get it to take a string argument.</p>
<p>Here is my modified cpp file:</p>
<pre><code>#include <iostream>
using na... | 2 | 2016-07-03T08:38:43Z | 38,176,099 | <p>@Paul Mu Guire's suggestion above might have helped, but what I needed was something really simple that took a string and output a string. So, the whole object oriented paradigm was overkill. I changed to a simple C structure - </p>
<pre><code>extern "C" {
char* linked(char * in){
return in;
}
}
</code></pre... | 1 | 2016-07-04T02:15:53Z | [
"python",
"c++",
"c",
"ctypes"
] |
Compare two identical folders on two different machines, SSH issue | 38,168,263 | <p>So i got two (supposed) to be equal very big folders on two machines.
I want to compare their file sizes for each file in the folder.
Every once in a while files that should be equal are not, and one of the files is smaller then it should be.</p>
<p>The compare is easy and widely explained on the net, but how is th... | 2 | 2016-07-03T08:47:33Z | 38,171,469 | <p>This is not a real compare but anyway:</p>
<pre><code>import subprocess
f_pass ='pswd'
f_ip = '10.10.10.10'
f_user = 'root'
f_folder = '/tmp/'
s_pass ='pswd'
s_ip = '10.10.10.11'
s_user = 'root'
s_folder = '/tmp/'
f_cmd = "sshpass -p '{}' ssh {}@{} find {} -ls".format(f_pass, f_user, f_ip, f_cmp_folder)
s_cmd = "... | 1 | 2016-07-03T15:29:51Z | [
"python",
"compare"
] |
Render Latex text with python | 38,168,292 | <p>I'm trying to render Latex text with python. This is what I tried to do:</p>
<pre><code>import matplotlib.pyplot as plt
txte = r"""
The \emph{characteristic polynomial} $\chi(\lambda)$ of the
$3 \times 3$~matrix
\[ \left( \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array} \r... | 1 | 2016-07-03T08:51:41Z | 38,168,475 | <p>Maybe you schould trty to automaticaly compile it to a png with calling a console command line from python
like this : <a href="http://tex.stackexchange.com/questions/11866/compile-a-latex-document-into-a-png-image-thats-as-short-as-possible">http://tex.stackexchange.com/questions/11866/compile-a-latex-document-int... | 1 | 2016-07-03T09:14:34Z | [
"python",
"matplotlib",
"tex"
] |
Render Latex text with python | 38,168,292 | <p>I'm trying to render Latex text with python. This is what I tried to do:</p>
<pre><code>import matplotlib.pyplot as plt
txte = r"""
The \emph{characteristic polynomial} $\chi(\lambda)$ of the
$3 \times 3$~matrix
\[ \left( \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array} \r... | 1 | 2016-07-03T08:51:41Z | 38,168,602 | <p>You have to add to your code these lines to render latex text by your own installed software (by default matplotlib use MathText: <a href="http://matplotlib.org/api/mathtext_api.html" rel="nofollow">http://matplotlib.org/api/mathtext_api.html</a>):</p>
<pre><code>from matplotlib import rcParams
rcParams['text.usete... | 1 | 2016-07-03T09:32:57Z | [
"python",
"matplotlib",
"tex"
] |
Python throws ascii codec can't encode when parsing xml | 38,168,346 | <p>I was running the following code in Python:</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.parse('dplp_11.xml')
root = tree.getroot()
f = open('workfile', 'w')
for country in root.findall('article'):
rank = country.find('year').text
name = country.find('title').text
if(int(rank)>2009):
... | 0 | 2016-07-03T08:58:07Z | 38,168,365 | <p><code>a.text</code> is a Unicode object, but you are trying to write it to a plain Python 2 file object:</p>
<pre><code>f.write(a.text)
</code></pre>
<p>The <code>f.write()</code> method only takes a <em>byte</em> string (type <code>str</code>), triggering an implicit encode to the ASCII codec, triggering your exc... | 1 | 2016-07-03T09:00:03Z | [
"python",
"xml",
"unicode"
] |
radio buttons are active on running the program | 38,168,389 | <p>I have tried this code and facing with problem that all options of radiobuttons are coming to be selected intially i.e. all options are selected on running the program.</p>
<pre><code>import tkinter as tk
from tkinter import *
from tkinter import Tk
root=Tk()
a=Label(root,text='Name')
a.grid(row=0,column=0)
b=Entr... | 0 | 2016-07-03T09:03:05Z | 38,168,712 | <p>Use <code>var.set()</code> and pass it an argument of the value for the radiobutton you'd like to choose as default. For example:</p>
<pre><code>var.set('English')
</code></pre>
<p>will set the "English" radiobutton as active.</p>
| 0 | 2016-07-03T09:48:40Z | [
"python"
] |
Multiple values per key (array or dictionary)? | 38,168,502 | <p>I'm designing a very simple database for products I have in a mock warehouse. </p>
<p>There is a code (the key), a description (value), number of units available per pack (value), individual prices (value) and the total cost of the pack (value):</p>
<pre><code>Product Number | Description | Pack | Individual Cost ... | -2 | 2016-07-03T09:18:28Z | 38,168,740 | <blockquote>
<p>I want it something like:</p>
<pre><code>{01234567:("Black Ballpoint Pen", 4, 0.50, 2.00), 12345670:(Football,2, 4.50, 9.00)}
</code></pre>
</blockquote>
<p>Did you try it? All you have to do is change <code>Football</code> to <code>"Football"</code>, and it works as expected:</p>
<pre><code>>&g... | 0 | 2016-07-03T09:52:36Z | [
"python",
"arrays",
"sorting",
"dictionary"
] |
Best way to perform string validation with user input in Python 3.4? | 38,168,544 | <p>I have got a string as is:</p>
<pre><code>line = 'City' /* City can be in 2 or 3 parts */
</code></pre>
<p>----> 2 parts: first char of each part is a capital letter.</p>
<p>----> 3 parts: first char of 1st and 2nd part is a capital letter.</p>
<p>The line I get is always valid because I check it with a regex al... | 0 | 2016-07-03T09:24:25Z | 38,169,496 | <blockquote>
<p><em>"(...) if the input is the same as the City's first character (no matter what part of the city)"</em></p>
</blockquote>
<p>You can split the city name by space using the string method <code>split()</code> to get a <code>list</code> of its parts:</p>
<pre><code>>>> "Mont de Marsan".split... | 3 | 2016-07-03T11:30:06Z | [
"python",
"python-3.x"
] |
Best way to perform string validation with user input in Python 3.4? | 38,168,544 | <p>I have got a string as is:</p>
<pre><code>line = 'City' /* City can be in 2 or 3 parts */
</code></pre>
<p>----> 2 parts: first char of each part is a capital letter.</p>
<p>----> 3 parts: first char of 1st and 2nd part is a capital letter.</p>
<p>The line I get is always valid because I check it with a regex al... | 0 | 2016-07-03T09:24:25Z | 38,169,791 | <p>My strategy is to create a dictionary of sets of city names, with the initial letter of each word in a city name as the key. It doesn't take long to create this dictionary, but it makes finding the matching cities very fast.</p>
<p>My input loop ignores empty strings and leading or trailing blank spaces, and it pri... | 2 | 2016-07-03T12:07:58Z | [
"python",
"python-3.x"
] |
Dependencies not being installed in Openshift [Flask] | 38,168,679 | <p>I am deploying my flask project into Openshift, however it seems that Openshift is not installing the dependencies provided in the setup.py file.</p>
<p>This is my code:</p>
<pre><code>setup(
...
install_requires=['Flask==0.10.1','SQLAlchemy==0.9.8','flask-
login==0.2.7','flask-pymongo-0.4.1','httplib2-0.9.2... | -1 | 2016-07-03T09:43:47Z | 38,169,217 | <p>It looks like you switched from <code>library==version</code> to <code>library-version</code> part way through your requirements list.</p>
<p>Try:</p>
<pre><code>setup(
...
install_requires=[
'Flask==0.10.1','SQLAlchemy==0.9.8','flask-login==0.2.7',
'flask-pymongo==0.4.1','httplib2==-0.9.2', 'oauth2cli... | 0 | 2016-07-03T10:53:21Z | [
"python",
"flask",
"dependencies",
"openshift",
"google-api-python-client"
] |
Motion detection + Contours (Python) | 38,168,760 | <p>What's wrong with my python code. It says syntax error at line 5 "Mat frame", line 13 "std". This code was originally from C++, I converted it to Python.</p>
<pre><code>import numpy as np
import cv2
def run_main():
cv2.Mat frame
cv2.Mat back
cv2.Mat fore
cv2.VideoCapture cap(0)
cv2.BackgroundSu... | -1 | 2016-07-03T09:55:13Z | 38,169,611 | <p>Your code is no valid Python, it's a syntactic mix between C++ and Python.
Some hints on what needs to be changed:</p>
<pre><code>cv2.Mat frame
cv2.Mat back
cv2.Mat fore
cv2.VideoCapture cap(0)
cv2.BackgroundSubtractorMOG2 bg
</code></pre>
<p>There is no <strong>Mat</strong> type in OpenCV Python. It uses <a href=... | 0 | 2016-07-03T11:44:17Z | [
"python",
"python-2.7",
"opencv"
] |
How am I getting two different results from same Python print command? | 38,168,780 | <p>For the first <code>print tag</code> I am getting a large list of hundreds of <code><a</code> tags. For the second <code>print tag</code> I am getting a list with four <code><a</code> tags, not including the ones that I want.</p>
<p>One of the tags that tags that I want is at the end of <code>tags</code>. A... | 0 | 2016-07-03T09:57:23Z | 38,169,317 | <p>You have a blanket <code>except:</code>:</p>
<pre><code>try:
# ...
except:
continue
</code></pre>
<p>so <em>any error</em> in the block will be masked and your loop will be skipped. Don't use blanket except handlers without raising again, ever, see <a href="https://stackoverflow.com/questions/21553327/why-... | 3 | 2016-07-03T11:07:12Z | [
"python"
] |
Sci-Kit Learn: getting value from matrix generated by CountVectorizer.fit_transofrm() (PYTHON) | 38,168,831 | <p>My code is this one:</p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
new_text = ["with with hello hello hello house"]
X_new_counts = count_vect.fit_transform(new_text)
i = count_vect.vocabulary_.get('hello')
print(X_new_counts.shape)
c = X_new_counts.getc... | 0 | 2016-07-03T10:04:37Z | 38,176,849 | <p>X_new_counts is a (sparse) matrix so you can get the values in i, j using:</p>
<pre><code>X_new_counts[i, j]
</code></pre>
| 0 | 2016-07-04T04:11:49Z | [
"python",
"matrix",
"count",
"scikit-learn"
] |
How can i get values of JSONfield in my template | 38,168,856 | <p>i tried to find the answer but couldn't. In my template when i iterate over JSONfield </p>
<pre><code>{% extends "electronic/electronic_base.html" %}
{% load staticfiles %}
{% block content %}
{% for item in micro_all %}
<h1>{{item.title}}</h1>
<table class="table table-condensed">
<tbody>
... | 0 | 2016-07-03T10:09:36Z | 38,168,986 | <p>You should be able to iterate it as a normal dictionary:</p>
<pre><code><table>
{% for key,value in item.attributes.items %}
<tr>
<td>{{key}}</td><td>{{value}}</td>
</tr>
{% endfor %}
</table>
</code></pre>
| 1 | 2016-07-03T10:25:15Z | [
"python",
"django",
"postgresql"
] |
Python: List algebraic simplification | 38,168,922 | <p>Hi I am trying to get the common terms of a list to simplify it for example if the list I have is:</p>
<pre><code>List=[['1','A1','B1','Kc','Ka'],['1','A1','B1','D2','Kc','Ka'],['-1','A1','B1','D1','Kc','Ka'],['1','A1','B1','D1','KD','Ka'],['-1','B1','D1','C1','Kc','Ka','KF'],['1','B1','D1','F1','Kc','Kz','Kl']] ... | 6 | 2016-07-03T10:17:26Z | 38,180,655 | <p>First of all, transform your list to a SymPy expression:</p>
<pre><code>In [1]: List=[['1','A1','B1','Kc','Ka'],['1','A1','B1','D2','Kc','Ka'],['-1','A1','B1','D1','Kc','Ka'],['1','A1','B1','D1','KD','Ka'],['-1','B1','D1','C1','Kc','Ka','KF'],['1','B1','D1','F1','Kc','Kz','Kl']]
In [2]: list_add_mul = sympify(List... | 0 | 2016-07-04T09:01:24Z | [
"python",
"list",
"sympy",
"simplify"
] |
Python: List algebraic simplification | 38,168,922 | <p>Hi I am trying to get the common terms of a list to simplify it for example if the list I have is:</p>
<pre><code>List=[['1','A1','B1','Kc','Ka'],['1','A1','B1','D2','Kc','Ka'],['-1','A1','B1','D1','Kc','Ka'],['1','A1','B1','D1','KD','Ka'],['-1','B1','D1','C1','Kc','Ka','KF'],['1','B1','D1','F1','Kc','Kz','Kl']] ... | 6 | 2016-07-03T10:17:26Z | 38,711,973 | <p>I think you know what algebraic manipulations you want to do, but you are hung up on getting the "K" symbols out of sympy? Sympy is pretty good about guessing variable names. You can just construct the expression:</p>
<pre><code>In [1]: import sympy
In [2]: List=[['1','A1','B1','Kc','Ka'],['1','A1','B1','D2','Kc',... | 0 | 2016-08-02T04:48:51Z | [
"python",
"list",
"sympy",
"simplify"
] |
How to decouple hatch and edge color in matplotlib? | 38,168,948 | <p>I would like to draw a bar in matplotlib with white as fill color, red as hatch color and black as edgecolor. However, it looks like the edgecolor changes also the color of hatch. So, I am not able to decouple the color of edges and hatch. Do you have any suggestion?
Thanks.</p>
| 2 | 2016-07-03T10:20:27Z | 38,169,221 | <p>Plot bar plot twice:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
fig = plt.figure()
ax1 = fig.add_subplot(111)
# draw hatch
ax1.bar(range(1, 5), range(1, 5), color='none', edgecolor='red', hatch="/", lw=1., zorder = 0)
# draw edge
ax1.bar(range(1, 5), range(1, 5),... | 3 | 2016-07-03T10:54:15Z | [
"python",
"matplotlib"
] |
Python: find the exponent of two numbers using only incrementation/addition by 1(+=1), can not use multiplication or division operators. | 38,168,949 | <p>I am trying to find the exponent of two numbers (<strong>n</strong>,<strong>m</strong>) using the only arithmetic operation of incrementation "+=1" by 1. I can not use any other addition/multiplication or division operators. The program can be a function or a loop such that the user enters <strong>n</strong>, and t... | -2 | 2016-07-03T10:20:48Z | 38,169,080 | <p>To do this, we need to understand first: What is multiplication?</p>
<p><code>a x b</code> is equivalent to <code>a + a + a +...</code> b times. Then, what is exponent? <code>a^b</code> is equivalent to <code>a x a x a x..</code> b times. So, you would need two while loops and two counters.</p>
<pre><code>n = int(... | 1 | 2016-07-03T10:35:28Z | [
"python",
"function",
"while-loop",
"increment",
"square"
] |
Python: find the exponent of two numbers using only incrementation/addition by 1(+=1), can not use multiplication or division operators. | 38,168,949 | <p>I am trying to find the exponent of two numbers (<strong>n</strong>,<strong>m</strong>) using the only arithmetic operation of incrementation "+=1" by 1. I can not use any other addition/multiplication or division operators. The program can be a function or a loop such that the user enters <strong>n</strong>, and t... | -2 | 2016-07-03T10:20:48Z | 38,169,133 | <p>With only <code>+= 1</code> as arithmetical operation, your solution could look like this:</p>
<pre><code>def mul(n, m):
result = 0
mi = 0
while mi < m:
ni = 0
while ni < n:
result += 1
ni += 1
mi += 1
return result
def pow(n, e):
resul... | 1 | 2016-07-03T10:42:53Z | [
"python",
"function",
"while-loop",
"increment",
"square"
] |
Python: find the exponent of two numbers using only incrementation/addition by 1(+=1), can not use multiplication or division operators. | 38,168,949 | <p>I am trying to find the exponent of two numbers (<strong>n</strong>,<strong>m</strong>) using the only arithmetic operation of incrementation "+=1" by 1. I can not use any other addition/multiplication or division operators. The program can be a function or a loop such that the user enters <strong>n</strong>, and t... | -2 | 2016-07-03T10:20:48Z | 38,169,381 | <p>Functional programming works nicely here. Addition is repeated incrementing. Multiplication is repeated addition. Power is repeated multiplication.</p>
<p>By defining a function (<code>repeat</code>) that repeatedly applies a function to an argument a given number of times, one can build up the <code>power</code> f... | 2 | 2016-07-03T11:13:50Z | [
"python",
"function",
"while-loop",
"increment",
"square"
] |
Django 1.9 : Pass variables from python script to bash script - OSError : [Errno 2] No such file or directory | 38,168,976 | <pre><code>subprocess.call(["echo",instance.Username]) # => works .
subprocess.call(["username=",instance.Username]) # => error
subprocess.Call(["username","=",instance.Username]) # => error
subprocess.call(["username=",instance.Username],shell=True)
# => no Error but when i do echo $username there is... | 0 | 2016-07-03T10:24:28Z | 38,169,265 | <p>You'll want to pass it as an environment variable to <code>subprocess.call()</code> like so:</p>
<pre><code>env = {
'username': instance.Username,
}
subprocess.call(['./your_script.sh'], env=env)
</code></pre>
<p>This will make the environment variable <code>$username</code> available to your bash script.</p>... | 2 | 2016-07-03T10:59:49Z | [
"python",
"django"
] |
Virtualenv error - build_ext | 38,169,053 | <p>I have a requirements.txt file that consists of the following modules:</p>
<pre><code>Flask==0.10.1
Flask-Login==0.3.1
Flask-SQLAlchemy==2.0
Jinja2==2.7.3
MarkupSafe==0.23
SQLAlchemy==0.9.8
Werkzeug==0.9.6
argparse==1.2.1
itsdangerous==0.24
rauth==0.7.0
requests==2.4.3
</code></pre>
<p>When I activate my virtualen... | 0 | 2016-07-03T10:33:40Z | 38,325,892 | <p>I found the answer to my issue.</p>
<p>The environment variable for python had been incorrectly configured (it had been made it's own system variable, rather than simply being added to the 'path' system variable).</p>
<p>Once this was changed, the issues disappeared.</p>
| 0 | 2016-07-12T10:12:03Z | [
"python",
"virtualenv"
] |
Ignoring statement names inside parameters | 38,169,267 | <p>When creating a function in PyCharm an error occurred as I tried to use a statement (in my case the <em>try</em> statement) as a parameter. </p>
<p>I also do get an error at second line due to Python tries to resolve the <em>try</em> as well.</p>
<pre><code>def currency_converter_to_dkk(try):
amount = float(tr... | 0 | 2016-07-03T11:00:02Z | 38,169,298 | <p><code>try</code> is a keyword in Python used in <a href="https://docs.python.org/3/reference/compound_stmts.html#the-try-statement" rel="nofollow">the <code>try</code> statement</a>. You cannot use keywords as a name.</p>
<p>You need to use another name. Appending an underscore is a very common practice.</p>
<pre>... | 0 | 2016-07-03T11:04:12Z | [
"python",
"pycharm"
] |
Python/Pandas dataframe - return column name | 38,169,342 | <p>Is there a way to return the name/header of a column into a string in a pandas dataframe? I want to work with a row of data which has the same prefix. The dataframe header looks like this:</p>
<pre><code>col_00 | col_01 | ... | col_51 | bc_00 | cd_00 | cd_01 | ... | cd_90
</code></pre>
<p>I'd like to apply a funct... | 1 | 2016-07-03T11:10:01Z | 38,169,403 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html" rel="nofollow"><code>str.startswith</code></a>:</p>
<pre><code>cols... | 0 | 2016-07-03T11:16:22Z | [
"python",
"pandas",
"dataframe"
] |
Convert blob to Django ImageField in python? | 38,169,357 | <p>I read user image in BLOB file, but i want save it to image format in django model.
How can i convert this file to image file(.jpeg) and save it in django models.ImageField?
I use python 2.7 and django 1.9.
my model is:</p>
<pre><code>class Staff(models.Model):
user = models.ForeignKey(User)
cn = models.Ch... | 0 | 2016-07-03T11:11:20Z | 38,169,590 | <p>You need to try something like this.</p>
<pre><code>import io
from django.core.files.base import File
# Set values of your model filed.
staff_instance = Staff()
staff_instance.user = user_instance
...
...
with io.BytesIO(blob_file) as stream:
django_file = File(stream)
staff_instance.avatar.save(some_file... | 0 | 2016-07-03T11:41:57Z | [
"python",
"django",
"django-models",
"blob"
] |
Python inheritance display nodes from some edge | 38,169,406 | <p>I tried build these classes and I need to display every node of an edge.
(state of a node is just a number 1 or 0 (visited/not visited)).</p>
<p>I have to build a graph (undirected) and manage all edges (display edge, change state of a node of an edge etc.)</p>
<p>The problem is in class Edge on method getNode1()<... | -1 | 2016-07-03T11:16:37Z | 38,169,805 | <p>I believe you don't understand what inheritance is.</p>
<p>Your code do not have node1 and node2 instance variables.
Which is the main problem.
If the following code covers your needs you don't need any inheritance.</p>
<pre><code>class Node(object):
def __init__(self, node, state):
self.node = node
... | 0 | 2016-07-03T12:09:30Z | [
"python",
"oop"
] |
Regex parsing text and get relevant words / characters | 38,169,446 | <p>I want to parse a file, that contains some programming language. I want to get a list of all symbols etc.</p>
<p>I tried a few patterns and decided that this is the most successful yet:</p>
<pre><code>pattern = "\b(\w+|\W+)\b"
</code></pre>
<p>Using this on my text, that is something like:</p>
<pre><code>string ... | -1 | 2016-07-03T11:22:37Z | 38,169,770 | <p>Why use <code>\W+</code> for one or more, if you want single non-word characters in output? Additionally exclude whitespace by use of a <a href="http://www.regular-expressions.info/charclass.html#negated" rel="nofollow">negated class</a>. Also it seems like you could drop the word boundaries.</p>
<pre><code>re.find... | 1 | 2016-07-03T12:05:22Z | [
"python",
"regex",
"parsing"
] |
Why is my object moving faultily in Pygame? | 38,169,561 | <p>In my program, I am trying to move my cuboid using my arrow keys. However, it moves but sort of leaves behind replicas of itself. I am trying to move the health bar above it too. This is my code:</p>
<pre><code>import pygame
from pygame.locals import *
pygame.init()
black = (0,0,0)
white = (255,255,255)
red = (25... | 0 | 2016-07-03T11:38:46Z | 38,169,613 | <p>You need to erase the old position of the cuboid by drawing the background over it, otherwise you'll end up seeing two copies. Pygame does not automatically erase everything you've drawn with every update, you have to do that yourself. <a href="http://www.pygame.org/docs/tut/MoveIt.html" rel="nofollow">Here</a> is a... | 1 | 2016-07-03T11:44:28Z | [
"python",
"pygame"
] |
Loss function not showing | 38,169,582 | <p>I want to start trying my hand at neural networks and found keras to be very simple syntactically. My set up is X_train is an array of shape (3516, 6)
and y_train is of shape (3516,)</p>
<p>X_train looks like this:</p>
<pre><code>[[ 888. 900.5 855. 879.311 877.00266667
893.5008 ... | 0 | 2016-07-03T11:41:18Z | 38,265,390 | <p>accuracy really low because it doesnt make sense to show accuracy, for a regression problem, it is more for classification </p>
<p>data was being passed through it was just so low it was a Nan question answered</p>
| 0 | 2016-07-08T11:20:38Z | [
"python",
"neural-network",
"keras",
"recurrent-neural-network"
] |
How to ensure parent pipe is closed on parent crash in python multiprocessing? | 38,169,786 | <p>If I <code>close()</code> the parent end of a pipe, <code>poll()</code> will raise <code>IOError</code>/<code>EOFError</code>, which is the expected behaviour.</p>
<p>How to ensure the pipe gets closed when the parent terminates or, even worse, <strong>crashes</strong> so that the child can notice there is no one o... | 0 | 2016-07-03T12:07:43Z | 38,314,319 | <p>The <code>multiprocessing.Pipe</code> object is a message oriented interface over a simple <code>os.pipe</code>.</p>
<p>The <code>multiprocessing.Connection.poll</code> method has several limitations. Not only it cannot detect closed pipes but it can also lead to deadlocks if the message sent from the other side of... | 1 | 2016-07-11T19:03:42Z | [
"python",
"pipe",
"multiprocessing"
] |
Extracting a value from a HTML string (PYTHON) | 38,169,790 | <p>I'm having some trouble extracting some data from this string:</p>
<pre><code><input class="mail-address-address" id="mailAddress" readonly="readonly" type="text" value="THE_EMAIL_ADDRESS_HERE"/>).
</code></pre>
<p>How could I store the <code>value=</code> into my own variable? I've thought about splitting b... | 0 | 2016-07-03T12:07:56Z | 38,169,896 | <p>As @Daniel Roseman says, it would be nice to have some more context. Normally when parsing HTML you can use libraries like <code>BeautifulSoup</code>. A good example for your case is <a href="http://stackoverflow.com/questions/11691271/python-beautifulsoup-getting-input-value">Python beautifulsoup - getting input va... | 1 | 2016-07-03T12:21:03Z | [
"python",
"html",
"email",
"variables",
"split"
] |
Extracting a value from a HTML string (PYTHON) | 38,169,790 | <p>I'm having some trouble extracting some data from this string:</p>
<pre><code><input class="mail-address-address" id="mailAddress" readonly="readonly" type="text" value="THE_EMAIL_ADDRESS_HERE"/>).
</code></pre>
<p>How could I store the <code>value=</code> into my own variable? I've thought about splitting b... | 0 | 2016-07-03T12:07:56Z | 38,169,924 | <p>This would be pretty messy to handle using <code>.split()</code>, so I would suggest using regular expressions (if you choose not to use HTML parsing libraries). To use regex, you need to import the <code>re</code> module, and use the following regular expression, <code>" +value=\"(.*?)\""</code>, like so:</p>
<pre... | 1 | 2016-07-03T12:25:23Z | [
"python",
"html",
"email",
"variables",
"split"
] |
Extracting a value from a HTML string (PYTHON) | 38,169,790 | <p>I'm having some trouble extracting some data from this string:</p>
<pre><code><input class="mail-address-address" id="mailAddress" readonly="readonly" type="text" value="THE_EMAIL_ADDRESS_HERE"/>).
</code></pre>
<p>How could I store the <code>value=</code> into my own variable? I've thought about splitting b... | 0 | 2016-07-03T12:07:56Z | 38,170,138 | <p>You should really use an html parser to parse html (not a regex or string manipulation). For example, you can use <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>. </p>
<p>first, install the package:</p>
<p><code>pip install beautifulsoup4</code></p>
<p>then use it to to ... | 1 | 2016-07-03T12:54:08Z | [
"python",
"html",
"email",
"variables",
"split"
] |
Python Array Creation Using 2 other arrays | 38,169,851 | <p>I have two arrays whose values i would like to use together in the creation of a third array. Below i have given the size and shapes of the arrays incase they can be of any help.</p>
<pre><code>CV Shape = (126,)
RV Shape = (94,)
CV Size =126
RV Size =94
</code></pre>
<p>The array into which i want their values ... | 0 | 2016-07-03T12:15:28Z | 38,194,870 | <p>The comments address the syntax change you'd need to make your loops work. A way to accomplish that final assignment with no looping uses <code>np.meshgrid</code>:</p>
<pre><code>RR, CC = np.meshgrid(RV, CV, indexing='ij')
temp = mag[RR, CC]
</code></pre>
| 0 | 2016-07-05T03:40:21Z | [
"python",
"arrays",
"numpy",
"for-loop",
"iterator"
] |
Python 3 best practice argument order | 38,169,978 | <p>In this <a href="http://stackoverflow.com/questions/9872824/calling-a-python-function-with-args-kwargs-and-optional-default-arguments">question</a> it is described that since Python3 you can use this notation:</p>
<pre><code>def func(a, b, *args, kw1=None, **kwargs)
</code></pre>
<p>to define a function, instead o... | 2 | 2016-07-03T12:32:09Z | 38,170,127 | <p>There cannot be any "best" practice here, since those two definitions mean different (in a way, the opposite) things:</p>
<pre><code>def func(a, b, kw1=None, *args, **kwargs):
...
</code></pre>
<p>means that the function will have an optional named argument <code>kw1</code>, which can be passed either as a key... | 4 | 2016-07-03T12:52:32Z | [
"python"
] |
ImportError: No module named _sqlite3 python 2.7 | 38,169,979 | <p>I'm currently developing python server using flask and AppEngine technologies. And when I realized I need DB, I tried to use <strong>sqlite3</strong>, but there are some troubles:</p>
<pre><code>INFO 2016-07-03 12:25:35,324 sdk_update_checker.py:229] Checking for updates to the SDK.
INFO 2016-07-03 12:25:35... | 0 | 2016-07-03T12:32:14Z | 38,176,964 | <p>The development environment tries very hard to simulate the deployment environment. Part of that trying means preventing the import of things (like <code>sqlite3</code>) that that aren't available in the deployment environment.</p>
<p>You can develop against a local <code>MySQL</code> instance. See <a href="https:/... | 1 | 2016-07-04T04:27:32Z | [
"python",
"python-2.7",
"google-app-engine"
] |
Show select as a tree | 38,169,985 | <p>How to show categories as a tree in Django admin using MPTT?</p>
<p>I made it show list of categories as a tree:</p>
<p><a href="http://i.stack.imgur.com/ewc99.png" rel="nofollow"><img src="http://i.stack.imgur.com/ewc99.png" alt="enter image description here"></a></p>
<p>But it does not work when I try to create... | 0 | 2016-07-03T12:33:22Z | 38,171,668 | <p>You should use <code>TreeForeignKey</code> in your child model:</p>
<pre><code>class Article(models.Model):
category = TreeForeignKey(Category, on_delete=models.CASCADE, blank=False,
null=False, verbose_name=u'Раздел')
...
</code></pre>
| 1 | 2016-07-03T15:53:18Z | [
"python",
"django",
"django-mptt",
"mptt"
] |
csv to json convertion with python | 38,170,071 | <p>i'm very new to programming, have been learning python from past 3/4 weeks and
this is one of the assignment given.</p>
<p>Input</p>
<pre><code>A, B, C, D
1, 2, 3, 4
5, 6, 7, 8
</code></pre>
<p>Output</p>
<pre><code>{{A:â1â, B:â2â, C:â3â, D:â4â}, {A:â5â, B:â6â, C:â7â, D:â8â}}
</c... | 1 | 2016-07-03T12:44:54Z | 38,170,095 | <p>Read the csv then write it step by step. </p>
<pre><code>#Read CSV File
def read_csv(file, json_file, format):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i... | 1 | 2016-07-03T12:48:11Z | [
"python",
"json",
"csv"
] |
csv to json convertion with python | 38,170,071 | <p>i'm very new to programming, have been learning python from past 3/4 weeks and
this is one of the assignment given.</p>
<p>Input</p>
<pre><code>A, B, C, D
1, 2, 3, 4
5, 6, 7, 8
</code></pre>
<p>Output</p>
<pre><code>{{A:â1â, B:â2â, C:â3â, D:â4â}, {A:â5â, B:â6â, C:â7â, D:â8â}}
</c... | 1 | 2016-07-03T12:44:54Z | 38,170,102 | <p>Dump after processing whole rows.</p>
<hr>
<pre><code>import csv
import json
with open('test.csv') as f:
reader = csv.DictReader(f)
rows = list(reader)
with open('test.json', 'w') as f:
json.dump(rows, f)
</code></pre>
| 0 | 2016-07-03T12:49:15Z | [
"python",
"json",
"csv"
] |
csv to json convertion with python | 38,170,071 | <p>i'm very new to programming, have been learning python from past 3/4 weeks and
this is one of the assignment given.</p>
<p>Input</p>
<pre><code>A, B, C, D
1, 2, 3, 4
5, 6, 7, 8
</code></pre>
<p>Output</p>
<pre><code>{{A:â1â, B:â2â, C:â3â, D:â4â}, {A:â5â, B:â6â, C:â7â, D:â8â}}
</c... | 1 | 2016-07-03T12:44:54Z | 38,170,302 | <pre><code>import csv
import json
# Constants to make everything easier
CSV_PATH = './csv.csv'
JSON_PATH = './json'
# Reads the file the same way that you did
csv_file = csv.DictReader(open(CSV_PATH, 'r'))
# Created a list and adds the rows to the list
json_list = []
for row in csv_file:
json_list.append(row)
#... | 1 | 2016-07-03T13:15:30Z | [
"python",
"json",
"csv"
] |
Changing variable in a function | 38,170,080 | <pre><code>from random import randint
count = 0
Validation = False
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
Number = generateNumber()
if int(Guess) == Number and count < 1:
return "First time right! Genius?"
Validation = True
elif int... | 0 | 2016-07-03T12:46:26Z | 38,170,126 | <p>Global variables in Python are a bit tricky, it is not enough to declare a variable at the top of the file. </p>
<p>Also, keep you return the value before you set the Validation value, causing the function to terminate before setting this variable</p>
<p>Last issue is the while logic, see correction for using raw... | 0 | 2016-07-03T12:52:28Z | [
"python",
"variables"
] |
Changing variable in a function | 38,170,080 | <pre><code>from random import randint
count = 0
Validation = False
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
Number = generateNumber()
if int(Guess) == Number and count < 1:
return "First time right! Genius?"
Validation = True
elif int... | 0 | 2016-07-03T12:46:26Z | 38,170,160 | <p>You need to set <em>Validation</em> to <em>True</em> before you return from the method, like this:</p>
<pre><code>if int(Guess) == Number and count < 1:
Validation = True
return "First time right! Genius?"
</code></pre>
<p>Do this for all if-statements.</p>
| 0 | 2016-07-03T12:57:47Z | [
"python",
"variables"
] |
Changing variable in a function | 38,170,080 | <pre><code>from random import randint
count = 0
Validation = False
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
Number = generateNumber()
if int(Guess) == Number and count < 1:
return "First time right! Genius?"
Validation = True
elif int... | 0 | 2016-07-03T12:46:26Z | 38,170,164 | <p>I spot two (and a half) problems in your code:</p>
<ol>
<li>As pointed out by Ishay Peled, you need to make Validation global</li>
<li>Your "return" statements are located <strong>before</strong> you change the value of "Validation"</li>
<li>"while" has no "else"</li>
</ol>
<p>Here's the updated code:</p>
<pre><c... | 0 | 2016-07-03T12:58:02Z | [
"python",
"variables"
] |
Changing variable in a function | 38,170,080 | <pre><code>from random import randint
count = 0
Validation = False
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
Number = generateNumber()
if int(Guess) == Number and count < 1:
return "First time right! Genius?"
Validation = True
elif int... | 0 | 2016-07-03T12:46:26Z | 38,170,196 | <p>Besides the global variable issue, you need to make another set of fixes. All your assignments to Validation = True appear after the "return" statements. The Validation = True will never execute! It will exit the function before executing those. Set 'Validation = True' before you 'return'. You still need to have the... | 0 | 2016-07-03T13:03:18Z | [
"python",
"variables"
] |
Letsencrypt ImportError: No module named interface on amazon linux while renewing | 38,170,100 | <p><strong>Today when i tried to renew my certificates using this command I'm facing error</strong></p>
<pre><code>/opt/letsencrypt/letsencrypt-auto renew --config /etc/letsencrypt/config.ini --agree-tos && apachectl graceful
</code></pre>
<p><strong>also tried this command</strong></p>
<pre><code>/opt/letse... | 4 | 2016-07-03T12:48:50Z | 38,176,291 | <p><strong>After doing lots of research I found it.</strong></p>
<p>You have to unset Python install layout</p>
<pre><code> unset PYTHON_INSTALL_LAYOUT
</code></pre>
<p>then update letsencrypt</p>
<pre><code> /opt/letsencrypt/letsencrypt-auto -v
</code></pre>
<p>for more refer this blog <a href="https://o-mkar.com... | 5 | 2016-07-04T02:48:26Z | [
"python",
"linux",
"lets-encrypt"
] |
Generate subsets of two elements of parameters | 38,170,173 | <p>I am a brand new to python and currently I am working on generating subsets in the list with function. Here is the sample I need to get back. </p>
<p>Eg.</p>
<ul>
<li>String: <code>AECG</code></li>
<li>Subsets: <code>['AE', 'AC', 'AG', 'EC', 'EG', 'CG']</code></li>
</ul>
<p>I was thinking to put the string into a... | -1 | 2016-07-03T12:59:48Z | 38,170,201 | <p>Use <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a>:</p>
<pre><code>>>> import itertools
>>> list(itertools.combinations('AECG', 2))
[('A', 'E'), ('A', 'C'), ('A', 'G'), ('E', 'C'), ('E', 'G'), ('C', 'G')]
>... | 4 | 2016-07-03T13:04:07Z | [
"python",
"list"
] |
Generate subsets of two elements of parameters | 38,170,173 | <p>I am a brand new to python and currently I am working on generating subsets in the list with function. Here is the sample I need to get back. </p>
<p>Eg.</p>
<ul>
<li>String: <code>AECG</code></li>
<li>Subsets: <code>['AE', 'AC', 'AG', 'EC', 'EG', 'CG']</code></li>
</ul>
<p>I was thinking to put the string into a... | -1 | 2016-07-03T12:59:48Z | 38,170,240 | <p>For the sake of completeness here is the solution without itertools</p>
<pre><code>subsets=[]
s="AECG"
for i in range (len(s)):
for j in range (i+1, len(s)):
subsets.append(s[i]+s[j]) # append modifies the list
print(subsets)
</code></pre>
| 2 | 2016-07-03T13:08:34Z | [
"python",
"list"
] |
Generate a n-dimensional array of coordinates in numpy | 38,170,188 | <p>Let's say I have a function f which can take coordinates as parameter and returns an integer (f(x) in this case). The coordinates can be multidimensional and are in the form of a list. My goal is to fill a numpy array with all values between two coordinates. I've tried to make a list of all possible indices and use ... | 8 | 2016-07-03T13:01:50Z | 38,170,406 | <p>Indeed <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> would be one way to do it with some <code>stacking</code>, as shown below -</p>
<pre><code>def ndim_grid(start,stop):
# Set number of dimensions
ndims = len(start)
# List... | 4 | 2016-07-03T13:28:02Z | [
"python",
"numpy",
"multidimensional-array",
"iterator",
"coordinates"
] |
Generate a n-dimensional array of coordinates in numpy | 38,170,188 | <p>Let's say I have a function f which can take coordinates as parameter and returns an integer (f(x) in this case). The coordinates can be multidimensional and are in the form of a list. My goal is to fill a numpy array with all values between two coordinates. I've tried to make a list of all possible indices and use ... | 8 | 2016-07-03T13:01:50Z | 38,170,519 | <p>Another option is to use the <code>product</code> from <code>itertools</code>, this also works if the corners are higher than <code>2D</code>:</p>
<pre><code>import itertools as it
lower_corner = [2, -2]
upper_corner = [5, 3]
[coord for coord in it.product(*[range(r[0], r[1]) for r in zip(lower_corner, upper_corner... | 2 | 2016-07-03T13:39:22Z | [
"python",
"numpy",
"multidimensional-array",
"iterator",
"coordinates"
] |
Parsing Snort Alert File with Regex | 38,170,253 | <p>I'm trying to use regex in Python to parse out the source, destination (IPs and ports) and the time stamp from a snort alert file. Example as below:</p>
<pre><code>03/09-14:10:43.323717 [**] [1:2008015:9] ET MALWARE User-Agent (Win95) [**] [Classification: A Network Trojan was detected] [Priority: 1] {TCP} 172.16.... | 1 | 2016-07-03T13:10:12Z | 38,170,318 | <p>You can separate them into different capture groups this way:</p>
<pre><code>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})
</code></pre>
<p>Losing both <code>^</code> and <code>$</code> will give you the ability to match in the middle of the line not just as a whole line.</p>
| 1 | 2016-07-03T13:16:49Z | [
"python",
"regex",
"text-processing",
"snort"
] |
Parsing Snort Alert File with Regex | 38,170,253 | <p>I'm trying to use regex in Python to parse out the source, destination (IPs and ports) and the time stamp from a snort alert file. Example as below:</p>
<pre><code>03/09-14:10:43.323717 [**] [1:2008015:9] ET MALWARE User-Agent (Win95) [**] [Classification: A Network Trojan was detected] [Priority: 1] {TCP} 172.16.... | 1 | 2016-07-03T13:10:12Z | 38,170,322 | <p>If I understand you correctly, you want to capture the IPs and the ports separately, right?</p>
<p>In that case, using "groups" in the regular expression would solve your problem:</p>
<pre><code>result = re.search(r'((\d{1,3}\.){3}\d{1,3}):(\d{1,5})', input)
</code></pre>
<p>Now, <code>result.group(1)</code> cont... | 1 | 2016-07-03T13:17:13Z | [
"python",
"regex",
"text-processing",
"snort"
] |
Parsing Snort Alert File with Regex | 38,170,253 | <p>I'm trying to use regex in Python to parse out the source, destination (IPs and ports) and the time stamp from a snort alert file. Example as below:</p>
<pre><code>03/09-14:10:43.323717 [**] [1:2008015:9] ET MALWARE User-Agent (Win95) [**] [Classification: A Network Trojan was detected] [Priority: 1] {TCP} 172.16.... | 1 | 2016-07-03T13:10:12Z | 38,170,363 | <p>This should extract the necessary parts from the full line:</p>
<pre><code>r'([0-9:./-]+)\s+.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})\s+->\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})'
</code></pre>
<p>See this example:</p>
<pre><code>In [22]: line = '03/09-14:10:43.323717 [**] [1:2008015:9] ET MA... | 2 | 2016-07-03T13:23:06Z | [
"python",
"regex",
"text-processing",
"snort"
] |
Parsing Snort Alert File with Regex | 38,170,253 | <p>I'm trying to use regex in Python to parse out the source, destination (IPs and ports) and the time stamp from a snort alert file. Example as below:</p>
<pre><code>03/09-14:10:43.323717 [**] [1:2008015:9] ET MALWARE User-Agent (Win95) [**] [Classification: A Network Trojan was detected] [Priority: 1] {TCP} 172.16.... | 1 | 2016-07-03T13:10:12Z | 38,170,815 | <h1>Description</h1>
<pre class="lang-regex prettyprint-override"><code>^((?:[0-9]{2}[-\/:.]){5}[0-9]{6}).*[{]TCP[}]\s*(((?:[0-9]{1,3}[.]){1,3}[0-9]{1,3}):([0-9]{1,6}))\s*->\s*(((?:[0-9]{1,3}[.]){1,3}[0-9]{1,3}):([0-9]{1,6}))
</code></pre>
<p><img src="https://www.debuggex.com/i/P-JCEpdOaVWRNqjj.png" alt="Regular ... | 0 | 2016-07-03T14:15:13Z | [
"python",
"regex",
"text-processing",
"snort"
] |
How to run multiple blocking IO coroutines in parallel | 38,170,373 | <p>I have a long running pipeline implemented with coroutines. This is typically fetching log streams, performing some enrichment(threaded) and writing them to a data-store.</p>
<p>Here is a small example to simulate the pipeline:</p>
<pre><code>import time
import random
from concurrent import futures
def coroutine(... | 1 | 2016-07-03T13:24:28Z | 38,170,922 | <p>Because the <code>source</code> function is never-ending, the <code>tasks = [source('task one ', foo()), source('task two ', foo())]</code> list is not created. That's why the first task runs and the pipelne blocks.<br>
The solution is to pass <code>source</code> and its arguments to <code>pool.submit</code>. </p>
... | 2 | 2016-07-03T14:28:46Z | [
"python",
"multithreading",
"concurrency",
"threadpoolexecutor"
] |
basic image processing with numpy and matplotlib | 38,170,464 | <p>I'm just testing very basic stuff about image manipulation with numpy ndarray data structure and matplotlib for show the image. I created a 2-dimensional array with np.zeros((n,m)) function where store my pixel, to keep things easy I'm just working in grayscale so I only need one value to represent my pixel. this is... | 1 | 2016-07-03T13:34:26Z | 38,170,586 | <p>By default, the colors of the color map are mapped to the minimum and maximum values of the data to be plotted. To override this, use the arguments <code>vmin</code> and <code>vmax</code>:</p>
<pre><code>plt.matshow(matrix, cmap=plt.cm.gray, vmin=0, vmax=255)
</code></pre>
| 2 | 2016-07-03T13:47:42Z | [
"python",
"arrays",
"numpy",
"image-processing",
"matplotlib"
] |
Set partitions into k groups (including the NULL set) in Python | 38,170,535 | <p>there a few posts like this one
<a href="http://stackoverflow.com/questions/15317360/i-have-a-list-of-numbers-how-to-generate-all-unique-k-partitions">I have a list of numbers, how to generate all unique k-partitions?</a></p>
<p>but i'd like to know if there are some new efficient libraries to solve this problem (<... | 2 | 2016-07-03T13:41:51Z | 38,186,292 | <p>Here is a solution in Sagemath, using NumPy arrays and itertools. The idea is same as in your code: create OrderedSetPartitions and beef them up with empty sets. To do this without too many loops, NumPy arrays are used: the key part is <code>partitions[:, s] = P</code> where certain columns of a 2D array <code>parti... | 2 | 2016-07-04T13:46:34Z | [
"python",
"algorithm",
"combinatorics",
"itertools",
"sage"
] |
Python TypeError: set() missing 1 required positional argument: 'value' | 38,170,566 | <p>It tells me "TypeError: set() missing 1 required positional argument: 'value'" and I am really new so I can't figure out what I did wrong. When using pyCharm and hovering over the argument in set() it says "Expected type 'Variable', got 'int' instead". I don't know what that means. Here's the code:</p>
<pre><code>f... | -1 | 2016-07-03T13:45:22Z | 38,170,575 | <p>following line is missing <code>()</code></p>
<pre><code>var = StringVar()
^^
</code></pre>
<p>And creation of <code>StringVar</code> should be done after creating root windows:</p>
<pre><code>master = Tk()
var = StringVar()
</code></pre>
| 1 | 2016-07-03T13:46:18Z | [
"python",
"tkinter"
] |
Python TypeError: set() missing 1 required positional argument: 'value' | 38,170,566 | <p>It tells me "TypeError: set() missing 1 required positional argument: 'value'" and I am really new so I can't figure out what I did wrong. When using pyCharm and hovering over the argument in set() it says "Expected type 'Variable', got 'int' instead". I don't know what that means. Here's the code:</p>
<pre><code>f... | -1 | 2016-07-03T13:45:22Z | 38,183,189 | <p>You are missing parentheses after <code>StringVar</code>. it should be <code>StringVar()</code>, because the <code>set()</code> method only work on <code>StringVar()</code> object. </p>
<p>Your code should be like this:</p>
<pre><code>from tkinter import *
var = StringVar() #With parentheses
var.set("Whatever S... | 0 | 2016-07-04T11:05:09Z | [
"python",
"tkinter"
] |
How to create a 2-dimensional CellRendererToggle | 38,170,573 | <p>I want to create a table like this:</p>
<pre><code>| | username | (x) task01 | (x) task02 |
|-|------------|------------|------------|
|x| user0001 | 1.00 | 1.00 |
| | user0002 | | |
etc...
</code></pre>
<p>A cell will be shown its value if its column and its row are being t... | -4 | 2016-07-03T13:46:15Z | 38,170,711 | <p>Your proposed solution isn't possible, but there's an easier way to do what you want: when you create the table column's attribute binding, simply bind the <code>visible</code> property of the other cell renderers to the same column in your model that the <code>active</code> property of the GtkCellRendererToggle is ... | 0 | 2016-07-03T14:02:50Z | [
"python",
"linux",
"python-2.7",
"gtk",
"gtk3"
] |
editing a specific line in python 3.5.1 | 38,170,950 | <p>Having trouble with overwriting a specific line in python 3.5.1 I know there are solutions out there but they use external modules or are lengthy and specific to that persons problem.</p>
<p>is there a line of code that could do that?
here is what im looking for: File.write("insert text here","line to overwrite")<... | -1 | 2016-07-03T14:32:36Z | 38,171,056 | <p>You want to replace a single line in the textfile with a different line?</p>
<pre><code> for line in open(filename):
if line.rstrip('\n') == search_pattern:
sys.stdout.write('%s\n' % replacement)
else:
sys.stdout.write('%s' % line)
</code></pre>
<p>Instead of the <code>sy... | 0 | 2016-07-03T14:44:43Z | [
"python"
] |
different validation in drf serializer per request method | 38,170,972 | <p>Lets say i have a model like so:</p>
<pre><code>class MyModel(models.Model):
first_field = models.CharField()
second_field = models.CharField()
</code></pre>
<p>and an API view like so:</p>
<pre><code>class MyModelDetailAPI(GenericAPIView):
serializer_class = MyModelSerializer
def patch(self, requ... | 4 | 2016-07-03T14:35:46Z | 38,171,416 | <p>I need more space than comments provide to make my meaning clear. So here is what I suggest:</p>
<ol>
<li><p>Different formatting means different serializers.</p>
<p>So here you have, for instance a <code>MyModelSerializer</code> and a <code>MyModelCreationSerializer</code>. Either create them independently, or ha... | 3 | 2016-07-03T15:24:17Z | [
"python",
"django",
"validation",
"serialization",
"django-rest-framework"
] |
Python - breaking while loop with function (Raspberry Pi) | 38,171,017 | <p>I have a project that involves a raspberry pi, the dothat 16x2 lcd display and some python code. I am essentially trying to make a dynamic while loop that displays information on the lcd. I am also trying to add a function that cancels the while loop by pressing one of the touch buttons (reference: <a href="https://... | -4 | 2016-07-03T14:40:57Z | 38,171,918 | <p>I don't have a dothat LCD display, so I can't test your code. But I think @Pigface333 was right, the <code>i</code> inside <code>cancel</code> is a local variable, thus the <code>i</code> in your <code>if</code> statement is not set to 1 after pressing Cancel. The following code demonstrates that:</p>
<pre><code>fr... | -1 | 2016-07-03T16:22:51Z | [
"python",
"raspberry-pi"
] |
Python - breaking while loop with function (Raspberry Pi) | 38,171,017 | <p>I have a project that involves a raspberry pi, the dothat 16x2 lcd display and some python code. I am essentially trying to make a dynamic while loop that displays information on the lcd. I am also trying to add a function that cancels the while loop by pressing one of the touch buttons (reference: <a href="https://... | -4 | 2016-07-03T14:40:57Z | 38,175,123 | <p>I fixed it, though I'm getting errors about the 'module' object not being callable regarding os(cmd).</p>
<p>The code:</p>
<pre><code>def main():
global i
i=0
k=0
while True:
l.clear()
b.hue(1.5)
l.set_cursor_position(0, 1)
l.write("%s" % k)
@t.... | 0 | 2016-07-03T23:08:51Z | [
"python",
"raspberry-pi"
] |
Make two Frames occupy 50% of the available width each? | 38,171,036 | <p>How can I make two <code>Frame</code>s occupy 50% each of the available width of the window? </p>
<p>Right now I'm just letting the contents dictate the widths and using <code>pack(side=Tkinter.LEFT)</code>, and obviously that doesn't make them both equal width.</p>
<p>I tried using <code>grid()</code> instead, bu... | 1 | 2016-07-03T14:42:45Z | 38,171,299 | <p>I finally came up with a hack that works correctly.</p>
<p>In the start, I create 2 frames, one of them has a label with (intentionally) a long text, and the other one a simple button. You can add as many widgets to both frames as you want.</p>
<p>The idea is to bind a callback method which takes in consideration ... | 0 | 2016-07-03T15:10:54Z | [
"python",
"python-2.7",
"tkinter"
] |
Make two Frames occupy 50% of the available width each? | 38,171,036 | <p>How can I make two <code>Frame</code>s occupy 50% each of the available width of the window? </p>
<p>Right now I'm just letting the contents dictate the widths and using <code>pack(side=Tkinter.LEFT)</code>, and obviously that doesn't make them both equal width.</p>
<p>I tried using <code>grid()</code> instead, bu... | 1 | 2016-07-03T14:42:45Z | 38,171,987 | <p>You should use expand and fill if using the pack method</p>
<p>Example</p>
<pre><code>import Tkinter as tk
root = tk.Tk()
left_frame = tk.Frame(root, bg = 'yellow')
left_frame.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
right_frame = tk.Frame(root, bg = 'lime')
right_frame.pack(side = tk.LEFT, expand = ... | 1 | 2016-07-03T16:30:25Z | [
"python",
"python-2.7",
"tkinter"
] |
Make two Frames occupy 50% of the available width each? | 38,171,036 | <p>How can I make two <code>Frame</code>s occupy 50% each of the available width of the window? </p>
<p>Right now I'm just letting the contents dictate the widths and using <code>pack(side=Tkinter.LEFT)</code>, and obviously that doesn't make them both equal width.</p>
<p>I tried using <code>grid()</code> instead, bu... | 1 | 2016-07-03T14:42:45Z | 38,174,944 | <p>You can use grid, using the <code>uniform</code> option. Put both halves in a "uniform group" (same value for <code>uniform</code> option) and they will be the same size.</p>
<pre><code>frame1 = tk.Frame(parent, ...)
frame2 = tk.Frame(parent, ...)
frame1.grid(row=0, column=0, sticky="nsew")
frame2.grid(row=0, colu... | 1 | 2016-07-03T22:41:18Z | [
"python",
"python-2.7",
"tkinter"
] |
How do I convert csv string to list in pandas? | 38,171,072 | <p>I'm working with a csv file that has the following format:</p>
<pre><code>"Id","Sequence"
3,"1,3,13,87,1053,28576,2141733,508147108,402135275365,1073376057490373,9700385489355970183,298434346895322960005291,31479360095907908092817694945,11474377948948020660089085281068730"
7,"1,2,1,5,5,1,11,16,7,1,23,44,30,9,1,47,1... | 0 | 2016-07-03T14:46:34Z | 38,171,123 | <p>You can specify a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>converter</code></a> for the <code>Sequence</code> column:</p>
<blockquote>
<p><code>converters</code>: <code>dict</code>, default <code>None</code></p>
<p>Dict of functions for convert... | 3 | 2016-07-03T14:51:34Z | [
"python",
"python-3.x",
"csv",
"numpy",
"pandas"
] |
How do I convert csv string to list in pandas? | 38,171,072 | <p>I'm working with a csv file that has the following format:</p>
<pre><code>"Id","Sequence"
3,"1,3,13,87,1053,28576,2141733,508147108,402135275365,1073376057490373,9700385489355970183,298434346895322960005291,31479360095907908092817694945,11474377948948020660089085281068730"
7,"1,2,1,5,5,1,11,16,7,1,23,44,30,9,1,47,1... | 0 | 2016-07-03T14:46:34Z | 38,171,189 | <p>This also works, except that the <code>Sequence</code> is list of string instead of list of int:</p>
<pre><code>df = pd.read_csv(training_data_file)
df['Sequence'] = df['Sequence'].str.split(',')
</code></pre>
<p>To convert each element to int:</p>
<pre><code>df = pd.read_csv(training_data_file)
df['Sequence'] = ... | 0 | 2016-07-03T14:57:59Z | [
"python",
"python-3.x",
"csv",
"numpy",
"pandas"
] |
Trying to pull data from a poorly formatted HTML website | 38,171,154 | <p>I've been recently trying to pull information from a website, and while I have been mostly successful it's been a bit of a struggle.</p>
<p>I've been currently using Regex to find some information (in here the names that I want to look at)</p>
<pre><code>webAddress = 'http://meridian.puzzlepirates.com/yoweb/crew/i... | 0 | 2016-07-03T14:54:09Z | 38,171,250 | <p>The markup is definitely not easy to deal with, but you definitely <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">should not be approaching it with regular expressions</a>. <em>Don't use a tool just because it is familiar to you or you are ... | 2 | 2016-07-03T15:04:55Z | [
"python",
"html",
"regex",
"html-parsing",
"pull"
] |
How to play mp3 from URL | 38,171,169 | <p>I'm trying to write a python script that will play mp3 from Soundcloud URL</p>
<p>This is what I've already done:</p>
<pre><code>from urllib.request import urlopen
url = "soundcloud.com/artist/song.mp3"
u = urlopen(url)
data = u.read(1024)
while data:
player.play(data)
data = u.read(1024)
</code></pre>
<... | 3 | 2016-07-03T14:55:52Z | 38,227,984 | <p>Check if you can download file manually using that <code>URL</code>. If its protected site with username/passwd, you may need to take care of that first.</p>
<p>If not, here is a working code that downloads file from <code>url</code> using <code>urllib2</code> and then plays it using <a href="https://github.com/jia... | 1 | 2016-07-06T15:35:53Z | [
"python",
"ubuntu",
"audio"
] |
How to play mp3 from URL | 38,171,169 | <p>I'm trying to write a python script that will play mp3 from Soundcloud URL</p>
<p>This is what I've already done:</p>
<pre><code>from urllib.request import urlopen
url = "soundcloud.com/artist/song.mp3"
u = urlopen(url)
data = u.read(1024)
while data:
player.play(data)
data = u.read(1024)
</code></pre>
<... | 3 | 2016-07-03T14:55:52Z | 38,246,702 | <p>Sorry but I do not have Python3 to test here, to stream <code>mp3</code> using <code>pyaudio</code> you will need decode it in PCM data, I know that <a href="http://pymedia.org/" rel="nofollow">pymedia</a> can do it, but it is too old and just support <code>python27</code>.</p>
<p>To do this the right way you will ... | 1 | 2016-07-07T13:25:16Z | [
"python",
"ubuntu",
"audio"
] |
How to play mp3 from URL | 38,171,169 | <p>I'm trying to write a python script that will play mp3 from Soundcloud URL</p>
<p>This is what I've already done:</p>
<pre><code>from urllib.request import urlopen
url = "soundcloud.com/artist/song.mp3"
u = urlopen(url)
data = u.read(1024)
while data:
player.play(data)
data = u.read(1024)
</code></pre>
<... | 3 | 2016-07-03T14:55:52Z | 38,247,503 | <p>If you happen to have VLC installed (or are willing to install it), then this should work:</p>
<pre><code>import vlc
p = vlc.MediaPlayer("http://your_mp3_url")
p.play()
</code></pre>
<p>This has the advantage that it works with everything VLC works with, not just MP3. It can also be paused if you want to.</p>
| 1 | 2016-07-07T14:01:29Z | [
"python",
"ubuntu",
"audio"
] |
Python GTK3: how to create a Gtk.FileChooseDialog? | 38,171,196 | <p>How to create a Gtk.FileChooseDialog properly?</p>
<p><a href="http://python-gtk-3-tutorial.readthedocs.io/en/latest/dialogs.html#id2" rel="nofollow">This popular tutorial</a> says to use code like the following:</p>
<pre><code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
dialog = Gtk.... | 2 | 2016-07-03T14:58:43Z | 38,171,402 | <p>Simply follow out the instructions and use keyword arguments. I also changed the buttons to using <code>.add_buttons()</code> since that also threw a DeprecationWarning:</p>
<pre><code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
dialog = Gtk.FileChooserDialog(
title="Please choose... | 2 | 2016-07-03T15:23:06Z | [
"python",
"gtk3"
] |
Python - does class exist? Test | 38,171,243 | <p>Is there a way to check if a class has been defined/exists?
I have different options on a menu, and some of them require inherited variables, so if you try to select that function before you have set the variables, it crashes.
My class is called Gen0, and I started it by simply putting</p>
<pre><code>class Gen0():
... | 0 | 2016-07-03T15:03:43Z | 38,171,423 | <p>Instead of checking whether the variable exists, you might want to go for a <a href="http://stackoverflow.com/a/11360880/6537490">EAFP</a> solution. For example:</p>
<pre><code>try:
print(var)
except NameError:
var = 2
print(var)
</code></pre>
<p>If <code>var</code> is not defined before this piece of cod... | 0 | 2016-07-03T15:24:52Z | [
"python",
"class",
"if-statement",
"while-loop"
] |
Python - does class exist? Test | 38,171,243 | <p>Is there a way to check if a class has been defined/exists?
I have different options on a menu, and some of them require inherited variables, so if you try to select that function before you have set the variables, it crashes.
My class is called Gen0, and I started it by simply putting</p>
<pre><code>class Gen0():
... | 0 | 2016-07-03T15:03:43Z | 38,171,462 | <p>I'm guessing <code>gen0</code> is defined something like this:</p>
<pre><code>class gen0:
pass
</code></pre>
<p>as opposed to initialising the attributes in your class on object creation</p>
<pre><code>class gen0:
def __init__(self):
# this function will be run when you call "g = gen0()"
#... | 0 | 2016-07-03T15:29:24Z | [
"python",
"class",
"if-statement",
"while-loop"
] |
Python - does class exist? Test | 38,171,243 | <p>Is there a way to check if a class has been defined/exists?
I have different options on a menu, and some of them require inherited variables, so if you try to select that function before you have set the variables, it crashes.
My class is called Gen0, and I started it by simply putting</p>
<pre><code>class Gen0():
... | 0 | 2016-07-03T15:03:43Z | 38,209,724 | <p>Your situation is not entirely clear, so I'm just going to answer the question "Is there a way to check if a class has been defined/exists?"</p>
<p>Yes, there are ways to check if a class has been defined in the current scope. I'll go through a few.</p>
<h2>1. It's Better to Ask Forgiveness Than Permission</h2>
<... | 0 | 2016-07-05T17:56:14Z | [
"python",
"class",
"if-statement",
"while-loop"
] |
How to hash PySpark DataFrame to get a float returned? | 38,171,265 | <p>Let's say I have spark dataframe</p>
<pre><code>+--------+-----+
| letter|count|
+--------+-----+
| a| 2|
| b| 2|
| c| 1|
+--------+-----+
</code></pre>
<p>Then I wanted to find mean. So, I did</p>
<pre><code>df = df.groupBy().mean('letter')
</code></pre>
<p>which give a dataframe</p>... | 0 | 2016-07-03T15:06:21Z | 38,171,494 | <p>Take first:</p>
<pre><code>>>> df.groupBy().mean('letter').first()[0]
</code></pre>
| 1 | 2016-07-03T15:32:37Z | [
"python",
"pyspark",
"spark-dataframe"
] |
Python Function Decorator Puzzle | 38,171,311 | <p>I recently leant the subject of python decorators, and found something strange for the below two different programs:</p>
<p>Example1:</p>
<pre><code>def deco(func):
def inner():
print("Running inner")
return func
@deco
def target():
print("Running target")
def main():
print("Running main(... | 1 | 2016-07-03T15:12:02Z | 38,171,386 | <p>Running Example 2 will give that result because <code>deco</code> is executed at definition time, and in that example it prints <code>inner</code> immediately.</p>
<p>Example 1 won't print inner because you never do anything with the <code>inner</code> func. Your decorator there should be returning <code>inner</cod... | 4 | 2016-07-03T15:20:43Z | [
"python",
"decorator"
] |
Python scraping XHR returns ValueError: Too many values to unpack | 38,171,380 | <p>So for educational purposes I've got this piece of code written to scrape the 'detailed' tab of this webpage : <a href="https://www.whoscored.com/Regions/252/Tournaments/2/Seasons/5826/Stages/12496/TeamStatistics/England-Premier-League-2015-2016" rel="nofollow">https://www.whoscored.com/Regions/252/Tournaments/2/Sea... | 1 | 2016-07-03T15:20:09Z | 38,171,413 | <p>You are incorrectly defining the <code>params</code> - currently it is actually a set of strings. Break down the strings to produce key-value pairs and create a dictionary instead:</p>
<pre><code>params = {
'category': 'shots',
'subcategory': 'zones',
'statsAccumulationType': '0',
'timeOfTheGameStar... | 1 | 2016-07-03T15:24:10Z | [
"python",
"python-2.7",
"web-scraping",
"python-requests"
] |
Some problems with input functions and or logic | 38,171,575 | <p>I am having a simple problem with some input and if statements. I am using a function from this page and my modifications aren't working. This is my code:</p>
<pre><code>def correct(prompt):
while True:
try:
value = int(raw_input(prompt))
except ValueError:
print("Enter a... | -3 | 2016-07-03T15:41:29Z | 38,171,591 | <p>The problem is with this test: </p>
<pre><code>if (value != 1) or (value != 2):
...
</code></pre>
<p>Apparently, it's <code>True</code> for any <code>value</code>, includung <code>1</code> and <code>2</code>. You could use <code>in</code>: </p>
<pre><code>if value not in [1, 2]:
...
</code></pre>
<p>Als... | 1 | 2016-07-03T15:43:23Z | [
"python",
"if-statement",
"input"
] |
Some problems with input functions and or logic | 38,171,575 | <p>I am having a simple problem with some input and if statements. I am using a function from this page and my modifications aren't working. This is my code:</p>
<pre><code>def correct(prompt):
while True:
try:
value = int(raw_input(prompt))
except ValueError:
print("Enter a... | -3 | 2016-07-03T15:41:29Z | 38,171,593 | <p>You are in a common pitfall. You want to use <code>and</code> not <code>or</code> in your <code>if</code> statement. All numbers are not <code>1</code> or <code>2</code>. So you would want to change your code from <code>if (value != 1) or (value != 2):</code> to <code>if (value != 1) and (value != 2):</code></p>
| 1 | 2016-07-03T15:43:33Z | [
"python",
"if-statement",
"input"
] |
Some problems with input functions and or logic | 38,171,575 | <p>I am having a simple problem with some input and if statements. I am using a function from this page and my modifications aren't working. This is my code:</p>
<pre><code>def correct(prompt):
while True:
try:
value = int(raw_input(prompt))
except ValueError:
print("Enter a... | -3 | 2016-07-03T15:41:29Z | 38,171,697 | <p>You could use:</p>
<pre><code>if value not in [1,2]:
...
</code></pre>
| 1 | 2016-07-03T15:57:21Z | [
"python",
"if-statement",
"input"
] |
Modify namespace of importing script in Python | 38,171,723 | <p>I'd like a function in my module to be able to access and change the local namespace of the script that's importing it. This would enable functions like this:</p>
<pre><code>>>> import foo
>>> foo.set_a_to_three()
>>> a
3
>>>
</code></pre>
<p>Is this possible in Python?</p>
| 5 | 2016-07-03T16:00:13Z | 38,171,799 | <p>To let the module access your script's namespace, you will have to pass the namespace to the function. For example:</p>
<pre><code>>>> import foo
>>> foo.set_a_to_three(globals(), locals())
>>> a
3
</code></pre>
<p>The inside of the code would look like this:</p>
<pre><code>def set_a_to... | 3 | 2016-07-03T16:09:38Z | [
"python",
"namespaces",
"python-import",
"python-module"
] |
Modify namespace of importing script in Python | 38,171,723 | <p>I'd like a function in my module to be able to access and change the local namespace of the script that's importing it. This would enable functions like this:</p>
<pre><code>>>> import foo
>>> foo.set_a_to_three()
>>> a
3
>>>
</code></pre>
<p>Is this possible in Python?</p>
| 5 | 2016-07-03T16:00:13Z | 38,171,800 | <p>An answer was generously provided by <a href="http://stackoverflow.com/users/573626/omz">@omz</a> in a Slack team:</p>
<pre><code>import inspect
def set_a_to_three():
f = inspect.currentframe().f_back
f.f_globals['a'] = 3
</code></pre>
<p>This provides the advantage over the <code>__main__</code> solution ... | 3 | 2016-07-03T16:09:40Z | [
"python",
"namespaces",
"python-import",
"python-module"
] |
Modify namespace of importing script in Python | 38,171,723 | <p>I'd like a function in my module to be able to access and change the local namespace of the script that's importing it. This would enable functions like this:</p>
<pre><code>>>> import foo
>>> foo.set_a_to_three()
>>> a
3
>>>
</code></pre>
<p>Is this possible in Python?</p>
| 5 | 2016-07-03T16:00:13Z | 38,171,949 | <p>Disclaimer: This solution can only modify global variables, so it's not perfect. See <a href="http://stackoverflow.com/questions/24023601/is-it-good-practice-to-use-import-main">Is it good practice to use <code>import __main__</code>?</a> for pros and cons.</p>
<p>In foo.py:</p>
<pre><code>import __main__
def set... | 3 | 2016-07-03T16:26:01Z | [
"python",
"namespaces",
"python-import",
"python-module"
] |
Modify namespace of importing script in Python | 38,171,723 | <p>I'd like a function in my module to be able to access and change the local namespace of the script that's importing it. This would enable functions like this:</p>
<pre><code>>>> import foo
>>> foo.set_a_to_three()
>>> a
3
>>>
</code></pre>
<p>Is this possible in Python?</p>
| 5 | 2016-07-03T16:00:13Z | 38,172,186 | <p>It's easy to set in the <code>__main__</code>, because we know it's name. </p>
<pre><code>#foo.py
import sys
def set_a_to_three():
sys.modules['__main__'].a = 3
</code></pre>
| 2 | 2016-07-03T16:52:25Z | [
"python",
"namespaces",
"python-import",
"python-module"
] |
Python: Change an element in a list of lists | 38,171,833 | <p>I have 2 lists:</p>
<pre><code>one = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]
]
two = [
[one[0][0], one[0][1], one[1][0], one[1][1]],
[one[0][2], one[0][3], one[1][2], one[1][3]],
[one[2][0], one[2][1], one[3][0], one[3][1]],
[one[2][2], one[2][3], one[3][2], one... | 3 | 2016-07-03T16:13:21Z | 38,171,894 | <p>You're actually copying the values.</p>
<p>Copy the reference to the lists in one:</p>
<pre><code>two=[one[0], one[1], one[2], one[3]]
</code></pre>
<p>Then you get for <code>two[0][0]=9</code>:</p>
<pre><code>one == [[9, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]]
two == [[9, 2, 3, 4], [2, 3, 4, 5], [3,... | 0 | 2016-07-03T16:20:31Z | [
"python",
"python-2.7"
] |
Python: Change an element in a list of lists | 38,171,833 | <p>I have 2 lists:</p>
<pre><code>one = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]
]
two = [
[one[0][0], one[0][1], one[1][0], one[1][1]],
[one[0][2], one[0][3], one[1][2], one[1][3]],
[one[2][0], one[2][1], one[3][0], one[3][1]],
[one[2][2], one[2][3], one[3][2], one... | 3 | 2016-07-03T16:13:21Z | 38,171,995 | <p>Integers are immutable in python. One approach you can take is to enclose the integers in a container type (list) and modify the container values. </p>
<p>See these additional pointers for related details:</p>
<p><a href="http://stackoverflow.com/questions/15148496/python-passing-an-integer-by-reference">Python ... | 1 | 2016-07-03T16:31:38Z | [
"python",
"python-2.7"
] |
Python: Change an element in a list of lists | 38,171,833 | <p>I have 2 lists:</p>
<pre><code>one = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]
]
two = [
[one[0][0], one[0][1], one[1][0], one[1][1]],
[one[0][2], one[0][3], one[1][2], one[1][3]],
[one[2][0], one[2][1], one[3][0], one[3][1]],
[one[2][2], one[2][3], one[3][2], one... | 3 | 2016-07-03T16:13:21Z | 38,172,160 | <p>Is this what you're trying to accomplish? </p>
<pre><code>def listfix(one, two):
if one != two:
one = two
return one, two
two[0][0]=9
one, two = listfix(one, two)
</code></pre>
| 0 | 2016-07-03T16:49:24Z | [
"python",
"python-2.7"
] |
Python: Change an element in a list of lists | 38,171,833 | <p>I have 2 lists:</p>
<pre><code>one = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7]
]
two = [
[one[0][0], one[0][1], one[1][0], one[1][1]],
[one[0][2], one[0][3], one[1][2], one[1][3]],
[one[2][0], one[2][1], one[3][0], one[3][1]],
[one[2][2], one[2][3], one[3][2], one... | 3 | 2016-07-03T16:13:21Z | 38,187,428 | <p>the issue here as other explained is that int objects are immutable
So doing </p>
<pre><code>two[0][0] = 9
</code></pre>
<p>wont change the old two[0][0] object instead it will create new object and make two[0][0] reference this new object (the old object is garbage collected if not other reference it in this case... | 1 | 2016-07-04T14:48:04Z | [
"python",
"python-2.7"
] |
How to exit loop and continue script with return key without getting ValueError: invalid literal for int() with base 10: '' | 38,171,855 | <p>I'm new to python and need some assistance with an assignment.</p>
<p>My script is this:</p>
<pre><code>print "Enter age of individuals (male only!) in order of entered names..."
age = " "
ages = []
while age <> "":
age = raw_input("Enter a age or press enter: ")
if int(age) <... | -1 | 2016-07-03T16:16:17Z | 38,171,891 | <p>Your method can throw a <code>ValueError</code> and you have no <code>except</code> for it so you want to rescue the <code>ValueError</code></p>
<pre><code>print "Enter age of individuals (male only!) in order of entered names..."
age = " "
ages = []
while age != "":
age = raw_input("Enter a age or press enter:... | 0 | 2016-07-03T16:20:28Z | [
"python"
] |
How to exit loop and continue script with return key without getting ValueError: invalid literal for int() with base 10: '' | 38,171,855 | <p>I'm new to python and need some assistance with an assignment.</p>
<p>My script is this:</p>
<pre><code>print "Enter age of individuals (male only!) in order of entered names..."
age = " "
ages = []
while age <> "":
age = raw_input("Enter a age or press enter: ")
if int(age) <... | -1 | 2016-07-03T16:16:17Z | 38,171,910 | <p>Move this line </p>
<pre><code>age = raw_input("Enter a age or press enter: ")
</code></pre>
<p>Outside the while loop above it</p>
<p>And then reads the same line at the end of while loop</p>
| 0 | 2016-07-03T16:22:08Z | [
"python"
] |
How to exit loop and continue script with return key without getting ValueError: invalid literal for int() with base 10: '' | 38,171,855 | <p>I'm new to python and need some assistance with an assignment.</p>
<p>My script is this:</p>
<pre><code>print "Enter age of individuals (male only!) in order of entered names..."
age = " "
ages = []
while age <> "":
age = raw_input("Enter a age or press enter: ")
if int(age) <... | -1 | 2016-07-03T16:16:17Z | 38,172,125 | <p>The problem is that right after the input you test for age. If the user inputted nothing (pressing enter), it complains that what the user inputted isn't a number. So, before you check the age you need to add a part which detects if enter was pressed.</p>
<pre><code>print "Enter age of individuals (male only!) in o... | 0 | 2016-07-03T16:44:46Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.