title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
How do you iteratre over a list performing some operation that turns a single element into multiple?
| 39,599,807 |
<p>I have a csv file of data from a LiDAR sensor that looks like this, but with a bagillion more lines:</p>
<pre><code>scan_0,scan_1,scan_2
timestamp_0,timestamp_1,timestamp_2
7900200,7900225,7900250
logTime_0,logTime_1,logTime_2
27:46.8,27:46.8,27:46.8
distance_0,distance_0,distance_0
132,141,139
136,141,155
139,141,155
138,143,155
138,143,142
139,143,136
138,143,136
</code></pre>
<p>This is data from a planar sensor. So Scan_0 is a list or "radial" coordinates for the specific scan at a time stamp. </p>
<p>My plan is to:</p>
<ol>
<li>Read the CSV file into a list</li>
<li>Transpose the list</li>
<li><p>Turn each element of row into a xyz format like the example below.</p>
<pre><code>scan_0 -----> scan_0
timestamp_0-> timestamp_0
7900200-----> 7900200
logTime_0---> logTime_0
27:46.8-----> 27:46.8
distance_0--> distance_0
132---------> [132*cos(1),132*sin(1),7900200]
136---------> [136*cos(2),136*sin(2),7900200]
139---------> [139*cos(3),139*sin(3),7900200]
138---------> . .
138---------> . .
139---------> . .
138---------> [138*cos(7),139*sin(7),7900200]
</code></pre></li>
<li><p>Write the array of xyz coordinates to a new csv file with one coordinate per line'</p></li>
<li><p>eventually use a trajectory instead of timestamp for the z coordinate from another csv file.</p></li>
</ol>
<p>I tell you all of this, so you have some context for my motivation. </p>
<p>here is what I have so far:</p>
<pre><code>import csv
import numpy
from numpy import genfromtxt
from numpy import vsplit
import math
with open('2016_09_16_14_29_09_953.csv',"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
print row_count
with open("out.csv", "a") as f1:
my_r = genfromtxt('2016_09_16_14_29_09_953.csv', delimiter=',', skip_header=6, autostrip=True) #import data
my_r = my_r.T #transpose
for x in my_r:
i=0
while i < row_count/360:
x = [x*math.cos(i), x*math.sin(i), i]
i = i + row_count/360
thedatawriter = csv.writer(f1) #setup writer
for row in my_r: #write the data
thedatawriter.writerow(row)
</code></pre>
<p>All this really does it ouput the transpose of the source file. It appears that I am having trouble turning the single entry in the list into a list itself. What am I doing wrong here? Any help, advice, and guidance is greatly appreciated. </p>
| 2 |
2016-09-20T16:56:00Z
| 39,600,163 |
<p>The problem that you have is that you are trying to assign new value to variable that does not reference to array.</p>
<p>So you have </p>
<pre><code>for x in my_r:
i=0
while i < row_count/360:
x = [x*math.cos(i), x*math.sin(i), i]
i = i + row_count/360
</code></pre>
<p>You cannot do that, because x is not actual element of <code>my_r</code> list(changing <code>x</code> would not lead to changing element on <code>my_r</code>).</p>
<p>The simplest way is to create new array to store desired values.</p>
<pre><code>my_r = genfromtxt('2016_09_16_14_29_09_953.csv', delimiter=',', skip_header=6, autostrip=True) #import data
my_r = my_r.T #transpose
new_r = []
for x in my_r:
i=0
while i < row_count/360:
new_r.append([x*math.cos(i), x*math.sin(i), i])
i = i + row_count/360
thedatawriter = csv.writer(f1) #setup writer
for row in new_r: #write the data
thedatawriter.writerow(row)
</code></pre>
| 1 |
2016-09-20T17:17:51Z
|
[
"python"
] |
Django password field input showing up as plaintext despite forms.PasswordInput declaration
| 39,599,839 |
<p>Django password field input showing up as plaintext despite <code>widget=forms.PasswordInput</code> declaration:</p>
<h1>forms.py</h1>
<pre><code>from django.contrib.auth.models import User
class LoginForm(forms.ModelForm):
# specify password type so that passwords show up as *******, not plaintext
# but this doesn't work if placeholder = ''
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ["username", "password"]
def __init__(self, *args, **kwargs):
# first call the 'real' __init__()
super(LoginForm, self).__init__(*args, **kwargs)
# then do extra stuff:
self.fields['username'].help_text = ''
self.fields['password'].widget = forms.TextInput(attrs={'placeholder': ''})
self.fields['password'].widget.attrs['class'] = 'form-control'
</code></pre>
<p>So interestingly, when I surface this form in a template, the <code>password</code> value shows up as plaintext instead of '******' text. But only if I add the <code>'placeholder': ''</code> line. I inspected the form element and figured out that when I added the <code>'placeholder': ''</code> line, <code>type='password'</code> was being changed to <code>type='text'</code> in the <code><input type='FOO'></input></code>element in the rendered HTML.</p>
<p>--> How do I keep this from happening, so passwords continue to show up as plaintext, without removing my <code>'placeholder': ''</code> line?</p>
| 0 |
2016-09-20T16:58:04Z
| 39,599,912 |
<p>You should not be using <code>forms.TextInput</code> for your password field. <a href="https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#passwordinput" rel="nofollow">Django provides a PasswordInput widget</a> that is more appropriate. Try this:</p>
<pre><code>class Meta:
model = User
fields = ["username", "password"]
def __init__(self, *args, **kwargs):
# first call the 'real' __init__()
super(LoginForm, self).__init__(*args, **kwargs)
# then do extra stuff:
self.fields['username'].help_text = ''
self.fields['password'].widget = forms.PasswordInput(attrs={'placeholder': ''})
self.fields['password'].widget.attrs['class'] = 'form-control'
</code></pre>
<p>While you can edit the type of the field manually, it's better convention to use the widget.</p>
| 3 |
2016-09-20T17:02:35Z
|
[
"python",
"django",
"forms"
] |
Raspberry send data via serial USB to Arduino Python
| 39,599,857 |
<p>Hi I have connected my raspberry to arduino via serial USB and on arduino there is a led that I want turn on if in the script in python I send a letter o a number</p>
<p>I have write this code in raspberry Python:</p>
<pre><code>import serial
ser=serial.Serial('/dev/ttyUSB0', 9600)
ser.write('3')
</code></pre>
<p>In my arduino I have load this skatch:</p>
<pre><code>const int ledPin = 12;
int val;
void setup(){
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
if (Serial.available()) {
val=Serial.read();
if(vale==3)
digitalWrite(ledpin, HIGH);
}
delay(500);
}
}
</code></pre>
<p>When I lunch the script py from rasp, I see that led not turn on, but turn on a onboard led of arduino.</p>
<p>I think that the problem is the type of data like ASCII or integer but I don't understand how to fix.
Serial device is ok and is USB0 and the pin of led on arduino is right
Please help me</p>
| 0 |
2016-09-20T16:59:18Z
| 39,600,005 |
<p>There is a typo in the if statement, you have put vale instead of val.</p>
<pre><code>ser.write('3')
</code></pre>
<p>takes 3 as a string.So try this in the if statement,</p>
<pre><code>if(val=='3')
</code></pre>
| 0 |
2016-09-20T17:07:54Z
|
[
"python",
"serialization",
"arduino"
] |
building simple terminal pyqt4 and pyserial how to update textbrowser
| 39,600,006 |
<p>I have followed a simple tutorial on creating a basic gui using qt designer and have incorporated that into python. I then made a simple python script that just continuously reads newlines from the serial port and prints them to the terminal. I want to combine them but I'm afraid my understanding of how pyqt4 works or perhaps classes themselves is just too lacking to accomplish such a simple task. For starters all I want to accomplish is to continuously print the incoming serial data. I've tried to move the serial print loop into different areas of the python script but it causes the window to hang. What is the proper way to do this?
pyqt code:</p>
<pre><code>from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralWidget)
self.verticalLayout.setMargin(11)
self.verticalLayout.setSpacing(6)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
self.verticalLayout.addWidget(self.textBrowser)
self.pushButton = QtGui.QPushButton(self.centralWidget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 21))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.textBrowser.append("blabla")
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.close)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Close", None))
self.textBrowser.append("blabla")
if __name__ == "__main__":
import sys
import serial
ser = serial.Serial()
ser.baudrate = 115200
ser.port = 'COM6'
ser.open()
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
ui.textBrowser.append(str(ser.readline()))
sys.exit(app.exec_())
</code></pre>
<p>serial code:</p>
<pre><code>import serial
ser = serial.Serial()
ser.baudrate = 115200
ser.port = 'COM6'
ser.open()
while True:
print(ser.readline()) # read a '\n' terminated line
</code></pre>
| 0 |
2016-09-20T17:07:57Z
| 39,601,336 |
<p>For anyone that has a similar issue. I found a solution by implementing a timer and creating a new function in the class:</p>
<pre><code>self.my_timer = QtCore.QTimer()
self.my_timer.timeout.connect(self.print_serial)
self.my_timer.start(10) # milliseconds
def print_serial(self):
if ser.in_waiting:
self.textBrowser.append(str(ser.readline()))
</code></pre>
<p>this worked for my application.</p>
| 0 |
2016-09-20T18:31:07Z
|
[
"python",
"pyqt",
"pyserial"
] |
Using a decorator to bring variables into decorated function namespace
| 39,600,106 |
<p>Say I have a function that looks like this:</p>
<pre><code>def func(arg1, arg2):
return arg1 + arg2 + arg3
</code></pre>
<p>And I want to bring in <code>arg3</code> using an argument passed to a decorator. Is this possible and if so how would this be done?</p>
<p>I've tried this which was suggested <a href="http://www.saltycrane.com/blog/2010/03/simple-python-decorator-examples/" rel="nofollow">here</a> to be able to pass arguments to decorators:</p>
<pre><code>from functools import wraps
def addarg(arg):
def decorate(func):
arg3 = arg
@wraps(func)
def wrapped(*args):
return func(*args)
return wrapped
return decorate
@addarg(3)
def func(arg1, arg2):
return arg1 + arg2 + arg3
if __name__ == "__main__":
print(func(1, 2))
</code></pre>
<p>But I get this error (understandably):</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 19, in <module>
print(func(1, 2))
File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 9, in wrapped
return func(*args)
File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 16, in func
return arg1 + arg2 + arg3
NameError: name 'arg3' is not defined
</code></pre>
<p>For my application it would be much nicer to be able to define the function in this way. There are other ways but then more code will have to be added to the body of each function.</p>
| -1 |
2016-09-20T17:13:41Z
| 39,600,533 |
<p>You can do it like that</p>
<pre><code>from functools import wraps
def addarg(arg):
def decorate(func):
@wraps(func)
def wrapped(*args):
return func(*args, arg)
return wrapped
return decorate
@addarg(3)
def func(arg1, arg2, *args):
return arg1 + arg2 + sum(args)
if __name__ == "__main__":
print(func(1, 2))
</code></pre>
<p>So that you are not attached to any name and you can apply as many decorators as you want. So if you want to add more decorators it would work. For example</p>
<pre><code>@addarg(3)
@addarg(3)
@addarg(3)
def func(arg1, arg2, *args):
return arg1 + arg2 + sum(args)
if __name__ == "__main__":
print(func(1, 2))
# Output would be 12(1 + 2 + 3 + 3 + 3)
</code></pre>
| 0 |
2016-09-20T17:43:24Z
|
[
"python",
"function",
"namespaces",
"python-decorators"
] |
Using a decorator to bring variables into decorated function namespace
| 39,600,106 |
<p>Say I have a function that looks like this:</p>
<pre><code>def func(arg1, arg2):
return arg1 + arg2 + arg3
</code></pre>
<p>And I want to bring in <code>arg3</code> using an argument passed to a decorator. Is this possible and if so how would this be done?</p>
<p>I've tried this which was suggested <a href="http://www.saltycrane.com/blog/2010/03/simple-python-decorator-examples/" rel="nofollow">here</a> to be able to pass arguments to decorators:</p>
<pre><code>from functools import wraps
def addarg(arg):
def decorate(func):
arg3 = arg
@wraps(func)
def wrapped(*args):
return func(*args)
return wrapped
return decorate
@addarg(3)
def func(arg1, arg2):
return arg1 + arg2 + arg3
if __name__ == "__main__":
print(func(1, 2))
</code></pre>
<p>But I get this error (understandably):</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 19, in <module>
print(func(1, 2))
File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 9, in wrapped
return func(*args)
File "C:/Users/pbreach/Dropbox/FIDS/PhD/Code/anemi3/utils.py", line 16, in func
return arg1 + arg2 + arg3
NameError: name 'arg3' is not defined
</code></pre>
<p>For my application it would be much nicer to be able to define the function in this way. There are other ways but then more code will have to be added to the body of each function.</p>
| -1 |
2016-09-20T17:13:41Z
| 39,601,696 |
<p>It's a little on the hacky side, but this implmentation of the decorator seems to do what you want. The <code>arg3</code> variable had to be made to appear as a global because it's referenced as one in the byte-code generated from the definition of <code>func()</code>, so it's not really considered a function argumentâbut that doesn't appear to matter in this case.</p>
<pre><code>from functools import wraps
def addarg(arg):
def decorate(func):
@wraps(func)
def wrapped(*args):
global_vars, local_vars = {'func': func, 'args': args}, {}
func.__globals__.update(arg3=arg)
exec('_result = func(*args)', global_vars, local_vars)
return local_vars['_result']
return wrapped
return decorate
@addarg(3)
def func(arg1, arg2):
return arg1 + arg2 + arg3
if __name__ == "__main__":
print(func(1, 2)) # -> 6
</code></pre>
| 1 |
2016-09-20T18:50:58Z
|
[
"python",
"function",
"namespaces",
"python-decorators"
] |
Can't import tkinter (or Tkinter)
| 39,600,159 |
<p>I am trying to import Tkinter to my project using Python 2.7 and instead I get the error:</p>
<pre><code>ImportError: No module named tkinter
</code></pre>
<p>Before anyone says it, I have tried both "Tkinter" and "tkinter" but have gotten the exact same message.</p>
| -1 |
2016-09-20T17:17:33Z
| 39,822,599 |
<p>First try using this code for your imports.</p>
<pre><code>try:
import Tkinter as tk # this is for python2
except:
import tkinter as tk # this is for python3
</code></pre>
<p>If this doesn't work, try reinstalling tkinter. If you don't know how to reinstall tkinter look at the tkinter installation page,<a href="http://www.tkdocs.com/tutorial/install.html" rel="nofollow"> here.</a> </p>
| 1 |
2016-10-02T22:59:10Z
|
[
"python",
"import",
"tkinter"
] |
Regular expression matching all but a string
| 39,600,161 |
<p>I need to find all the strings matching a pattern with the exception of two given strings. </p>
<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>
<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>
<p>Should return:</p>
<pre><code>('a', 'bc', 'def', 'ghij')
</code></pre>
<p>I tried with <a href="http://pythex.org/?regex=-(%5Cw.*%3F)(%3F%3D-)&test_string=-a-bc-def-ghij-&ignorecase=0&multiline=0&dotall=0&verbose=0" rel="nofollow">this regular</a> expression that captures 4 strings. I thought I was getting close, but (1) it doesn't work in Python and (2) I can't figure out how to exclude a few strings from the search. (Yes, I could remove them later, but my real regular expression does everything in one shot and I would like to include this last step in it.)</p>
<p>I said it doesn't work in Python because I tried this, expecting the exact same result, but instead I get only the first group:</p>
<pre><code>>>> import re
>>> re.search('-(\w.*?)(?=-)', '-a-bc-def-ghij-').groups()
('a',)
</code></pre>
<p>I tried with negative look ahead, but I couldn't find a working solution for this case.</p>
| 4 |
2016-09-20T17:17:43Z
| 39,600,219 |
<p>You need to use a negative lookahead to restrict a more generic pattern, and a <code>re.findall</code> to find all matches.</p>
<p>Use</p>
<pre><code>res = re.findall(r'-(?!(?:aa|bb)-)(\w+)(?=-)', s)
</code></pre>
<p>or - if your values in between hyphens can be any but a hyphen, use a negated character class <code>[^-]</code>:</p>
<pre><code>res = re.findall(r'-(?!(?:aa|bb)-)([^-]+)(?=-)', s)
</code></pre>
<p>Here is the <a href="https://regex101.com/r/eJ4uG7/2" rel="nofollow">regex demo</a>.</p>
<p><strong>Details</strong>:</p>
<ul>
<li><code>-</code> - a hyphen</li>
<li><code>(?!(?:aa|bb)-)</code> - if there is a<code>aa-</code> or <code>bb-</code> after the first hyphen, no match should be returned</li>
<li><code>(\w+)</code> - Group 1 (this value will be returned by the <code>re.findall</code> call) capturing 1 or more word chars <strong>OR</strong> <code>[^-]+</code> - 1 or more characters other than <code>-</code></li>
<li><code>(?=-)</code> - there must be a <code>-</code> after the word chars. The lookahead is required here to ensure overlapping matches (as this hyphen will be a starting point for the next match).</li>
</ul>
<p><a href="http://ideone.com/qPZOny" rel="nofollow">Python demo</a>:</p>
<pre><code>import re
p = re.compile(r'-(?!(?:aa|bb)-)([^-]+)(?=-)')
s = "-a-bc-aa-def-bb-ghij-"
print(p.findall(s)) # => ['a', 'bc', 'def', 'ghij']
</code></pre>
| 2 |
2016-09-20T17:21:32Z
|
[
"python",
"regex"
] |
Regular expression matching all but a string
| 39,600,161 |
<p>I need to find all the strings matching a pattern with the exception of two given strings. </p>
<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>
<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>
<p>Should return:</p>
<pre><code>('a', 'bc', 'def', 'ghij')
</code></pre>
<p>I tried with <a href="http://pythex.org/?regex=-(%5Cw.*%3F)(%3F%3D-)&test_string=-a-bc-def-ghij-&ignorecase=0&multiline=0&dotall=0&verbose=0" rel="nofollow">this regular</a> expression that captures 4 strings. I thought I was getting close, but (1) it doesn't work in Python and (2) I can't figure out how to exclude a few strings from the search. (Yes, I could remove them later, but my real regular expression does everything in one shot and I would like to include this last step in it.)</p>
<p>I said it doesn't work in Python because I tried this, expecting the exact same result, but instead I get only the first group:</p>
<pre><code>>>> import re
>>> re.search('-(\w.*?)(?=-)', '-a-bc-def-ghij-').groups()
('a',)
</code></pre>
<p>I tried with negative look ahead, but I couldn't find a working solution for this case.</p>
| 4 |
2016-09-20T17:17:43Z
| 39,600,224 |
<p>You can make use of negative look aheads.</p>
<p>For example,</p>
<pre><code>>>> re.findall(r'-(?!aa|bb)([^-]+)', string)
['a', 'bc', 'def', 'ghij']
</code></pre>
<hr>
<ul>
<li><p><code>-</code> Matches <code>-</code></p></li>
<li><p><code>(?!aa|bb)</code> Negative lookahead, checks if <code>-</code> is not followed by <code>aa</code> or <code>bb</code></p></li>
<li><p><code>([^-]+)</code> Matches ony or more character other than <code>-</code></p></li>
</ul>
<hr>
<p><strong>Edit</strong></p>
<p>The above regex will not match those which start with <code>aa</code> or <code>bb</code>, for example like <code>-aabc-</code>. To take care of that we can add <code>-</code> to the lookaheads like, </p>
<pre><code>>>> re.findall(r'-(?!aa-|bb-)([^-]+)', string)
</code></pre>
| 6 |
2016-09-20T17:21:46Z
|
[
"python",
"regex"
] |
Regular expression matching all but a string
| 39,600,161 |
<p>I need to find all the strings matching a pattern with the exception of two given strings. </p>
<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>
<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>
<p>Should return:</p>
<pre><code>('a', 'bc', 'def', 'ghij')
</code></pre>
<p>I tried with <a href="http://pythex.org/?regex=-(%5Cw.*%3F)(%3F%3D-)&test_string=-a-bc-def-ghij-&ignorecase=0&multiline=0&dotall=0&verbose=0" rel="nofollow">this regular</a> expression that captures 4 strings. I thought I was getting close, but (1) it doesn't work in Python and (2) I can't figure out how to exclude a few strings from the search. (Yes, I could remove them later, but my real regular expression does everything in one shot and I would like to include this last step in it.)</p>
<p>I said it doesn't work in Python because I tried this, expecting the exact same result, but instead I get only the first group:</p>
<pre><code>>>> import re
>>> re.search('-(\w.*?)(?=-)', '-a-bc-def-ghij-').groups()
('a',)
</code></pre>
<p>I tried with negative look ahead, but I couldn't find a working solution for this case.</p>
| 4 |
2016-09-20T17:17:43Z
| 39,600,980 |
<p>Although a regex solution was asked for, I would argue that this problem can be solved easier with simpler python functions, namely string splitting and filtering:</p>
<pre><code>input_list = "-a-bc-aa-def-bb-ghij-"
exclude = set(["aa", "bb"])
result = [s for s in input_list.split('-')[1:-1] if s not in exclude]
</code></pre>
<p>This solution has the additional advantage that <code>result</code> could also be turned into a generator and the result list does not need to be constructed explicitly. </p>
| 0 |
2016-09-20T18:10:58Z
|
[
"python",
"regex"
] |
What is the fastest way to put the first axis behind the last one? [numpy]
| 39,600,233 |
<p>Let us look at this stupid example with a N0 x N1 x ... x Nm dimensional array, such as </p>
<pre><code>import numpy as np
x = np.random.random([N0,N1,...,Nm])
</code></pre>
<p>Now I want the N0 dimension to be behind the last one, i.e.</p>
<pre><code>np.swapaxis np.swapaxis(np.swapaxis(x, 0,1),1,2) ... # swapping m times
</code></pre>
<p>I tried with np.rollaxis, but this seems to be the wrong function. In the end, I want to have an array with shape (N1,N2,N3,...,Nm,N0).</p>
<p>Any nice ideas?</p>
| 1 |
2016-09-20T17:22:28Z
| 39,600,367 |
<blockquote>
<p>I tried with np.rollaxis, but this seems to be the wrong function.</p>
</blockquote>
<p>No, it's the right function.</p>
<pre><code>x = numpy.rollaxis(x, 0, x.ndim)
</code></pre>
| 1 |
2016-09-20T17:31:16Z
|
[
"python",
"numpy"
] |
How to capture website screenshot in high resolution?
| 39,600,245 |
<p>I want to capture screenshot of a website in high resolution to recognize text or simply to save high quality images. I tried this code in Python 2.7. The website <a href="http://www.flaticon.com/" rel="nofollow">http://www.flaticon.com/</a> has been taken merely as example.</p>
<pre><code>from selenium import webdriver
import time
driver = webdriver.PhantomJS()
#Setting large window size doesn`t resolve the problem
driver.set_window_size(16000, 12000)
driver.get('http://www.flaticon.com/')
time.sleep(3)
#set resolution 640 dots per inch for this image
#???
driver.save_screenshot('./downloaded/img/welcome_icons.png') # save a screenshot to disk
driver.close()
</code></pre>
<p>It captures screenshot, but the resolution is not enough for me. Enlarging window size doesn`t resolve the problem. The picture from webside reside only on the part of the image. It seems that image resolution is not affected.
Is there some way to explicitly set image resolution before saving it?</p>
| 1 |
2016-09-20T17:23:23Z
| 39,600,457 |
<p>If it is about changing window size, you can set it by</p>
<pre><code>driver.set_window_size(480, 320)
</code></pre>
<p>Here is an example of doing this from <a href="https://gist.github.com/jsok/9502024" rel="nofollow">Github</a> of one of the developers. As you can see, you can adjust both Window size and quality of the screenshot.</p>
<pre><code>import StringIO
from selenium import webdriver
from PIL import Image
# Install instructions
#
# npm install phantomjs
# sudo apt-get install libjpeg-dev
# pip install selenium pillow
driver = webdriver.PhantomJS(executable_path="node_modules/phantomjs/bin/phantomjs")
driver.set_window_size(1366, 728) # optional
driver.get('http://google.com')
driver.save_screenshot('screen_hires.png')
screen = driver.get_screenshot_as_png()
# Crop it back to the window size (it may be taller)
box = (0, 0, 1366, 728)
im = Image.open(StringIO.StringIO(screen))
region = im.crop(box)
region.save('screen_lores.jpg', 'JPEG', optimize=True, quality=95)
</code></pre>
<p>The quality of 100 is max, 0 - min.</p>
<p><strong>EDIT:</strong></p>
<p>You can also use <code>selenium.windowMaxmize()</code>.</p>
<p>And if you want to magnify the screen to see some specific texts as you said, you can try this in Mozilla:</p>
<pre><code>from selenium.webdriver.common.keys import Keys
br = webdriver.Firefox()
zoom = ActionChains(br)
body = br.find_element_by_tag_name('body')
for i in range(2):
zoom.send_keys_to_element(body,Keys.CONTROL,"+").perform()
</code></pre>
| 1 |
2016-09-20T17:36:45Z
|
[
"python",
"selenium-webdriver"
] |
Django settings.py not updating
| 39,600,309 |
<p>I have enabled the setting:</p>
<p><code>USE_X_FORWARDED_HOST = True</code></p>
<p>in my settings.py. I am currently deploying the server, but when I try to render my index page it gives me a 404. The email says that it is a:</p>
<p><code>Invalid HTTP_HOST header: u'127.0.0.1:9001</code></p>
<p>And BEFORE ANYONE SAYS THAT I NEED TO ADD IT TO MY ALLOWED_HOSTS, I already have, so please spare me with from that advice. I also received an email with the debug error. When I looked through the debug info, it had a list of my settings and it stated that:</p>
<pre><code>USE_X_FORWARDED_HOST = False
</code></pre>
<p>Another field that is not being updated is my ALLOWED_HOSTS. I tried restarting apache2, touching wsgi.py, and deleting *.pyc in the main app directory that contains settings.pyc. However, none of this has worked.</p>
<p>Some background on my deployment. I have my django behind a proxy because I am using django channels with an apache2 webserver serving as the proxy. I also have daphne running behind it which receives the requests and services them.</p>
| 0 |
2016-09-20T17:27:55Z
| 39,617,323 |
<p>Solved the problem. The redis server had to be restarted everytime the settings.py was updated for some reason.</p>
| 0 |
2016-09-21T13:01:43Z
|
[
"python",
"django",
"django-settings",
"django-deployment",
"django-channels"
] |
Dictionary Combinations - Unequal Number of Keys & Values
| 39,600,405 |
<p>I want to print all unique combinations of keys and values for this dictionary:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
</code></pre>
<p>Using the code,</p>
<pre><code>for key, value in items.items():
print(key,value)
</code></pre>
<p>I receive the following output:</p>
<pre><code>b [11, 110]
c [12, 120]
a [10, 100, 1000]
</code></pre>
<p>I would like to produce the following result given the dictionary:</p>
<pre><code>b 11
b 110
c 12
c 120
a 10
a 100
a 1000
</code></pre>
<p>Order of the key-value combinations is not important, but the result should preserve the relationship. As always, any recommended resources and/or search terms associated with this problem will be appreciated.</p>
| 1 |
2016-09-20T17:33:21Z
| 39,600,446 |
<p>You were really close:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
# iterate on key/items couple
for k,vl in items.items():
# iterate on all values of the list
for v in vl:
# print with a simple format
print("{} {}".format(k,v))
</code></pre>
<p>output:</p>
<pre><code>a 10
a 100
a 1000
c 12
c 120
b 11
b 110
</code></pre>
<p>Note that you can use <code>for k,vl in sorted(items.items()):</code> to print the keys in the sorted order <code>(a,b,c)</code>, same goes for the inside list:</p>
<pre><code># iterate on key/items couple
for k,vl in sorted(items.items()):
# iterate on all values of the list
for v in sorted(vl):
# print with a simple format
print("{} {}".format(k,v))
</code></pre>
<p>output:</p>
<pre><code>a 10
a 100
a 1000
b 11
b 110
c 12
c 120
</code></pre>
| 1 |
2016-09-20T17:35:57Z
|
[
"python",
"loops",
"dictionary"
] |
Dictionary Combinations - Unequal Number of Keys & Values
| 39,600,405 |
<p>I want to print all unique combinations of keys and values for this dictionary:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
</code></pre>
<p>Using the code,</p>
<pre><code>for key, value in items.items():
print(key,value)
</code></pre>
<p>I receive the following output:</p>
<pre><code>b [11, 110]
c [12, 120]
a [10, 100, 1000]
</code></pre>
<p>I would like to produce the following result given the dictionary:</p>
<pre><code>b 11
b 110
c 12
c 120
a 10
a 100
a 1000
</code></pre>
<p>Order of the key-value combinations is not important, but the result should preserve the relationship. As always, any recommended resources and/or search terms associated with this problem will be appreciated.</p>
| 1 |
2016-09-20T17:33:21Z
| 39,600,491 |
<p>Using <a href="https://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain.from_iterables</code></a> and <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>, you can "flatten" this to a list of tuples:</p>
<pre><code>In [27]: import itertools
In [28]: list(itertools.chain.from_iterable([[(item_[0], v) for v in item_[1]] for item_ in items.items()]))
Out[28]:
[('a', 10),
('a', 100),
('a', 1000),
('c', 12),
('c', 120),
('b', 11),
('b', 110)]
</code></pre>
<p>From this, it's easy to do anything you want like printing it:</p>
<pre><code>In [29]: for k, v in itertools.chain.from_iterable([[(item_[0], v) for v in item_[1]] for item_ in items.items()]):
....: print k, v
....:
a 10
a 100
a 1000
c 12
c 120
b 11
b 110
</code></pre>
| 1 |
2016-09-20T17:39:34Z
|
[
"python",
"loops",
"dictionary"
] |
Dictionary Combinations - Unequal Number of Keys & Values
| 39,600,405 |
<p>I want to print all unique combinations of keys and values for this dictionary:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
</code></pre>
<p>Using the code,</p>
<pre><code>for key, value in items.items():
print(key,value)
</code></pre>
<p>I receive the following output:</p>
<pre><code>b [11, 110]
c [12, 120]
a [10, 100, 1000]
</code></pre>
<p>I would like to produce the following result given the dictionary:</p>
<pre><code>b 11
b 110
c 12
c 120
a 10
a 100
a 1000
</code></pre>
<p>Order of the key-value combinations is not important, but the result should preserve the relationship. As always, any recommended resources and/or search terms associated with this problem will be appreciated.</p>
| 1 |
2016-09-20T17:33:21Z
| 39,600,568 |
<p>Or simply :</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
for key, value in items.items():
for v in value :
print(key,v)
</code></pre>
| 2 |
2016-09-20T17:45:42Z
|
[
"python",
"loops",
"dictionary"
] |
Unicode issues when writing to CSV file
| 39,600,483 |
<p>I need some guidance, please. I'm using the following code: </p>
<pre><code>import requests
import bs4
import csv
results = requests.get('http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/top-engineering-schools/eng-rankings?int=a74509')
reqSoup = bs4.BeautifulSoup(results.text, "html.parser")
i = 0
schools = []
for school in reqSoup:
x = reqSoup.find_all("a", {"class" : "school-name"})
while i < len(x):
for name in x:
y = x[i].get_text()
i += 1
schools.append(y)
with open('usnwr_schools.csv', 'wb') as f:
writer = csv.writer(f)
for y in schools:
writer.writerow([y])
</code></pre>
<p>My problem is that the em-dashes are showing up as utf-8 in the resulting CSV file. I've tried several different things to fix it, but nothing seems to work (including <a href="http://stackoverflow.com/questions/33930767/trying-to-remove-character-em-dash-%C3%A2%E2%82%AC-in-python-using-regex">attempting to use regex</a> to get rid of it, as well as trying the <a href="http://stackoverflow.com/questions/27996448/python-encoding-decoding-problems">.translate method that I found in a StackOverflow</a> question from a few years ago). </p>
<p>What am I missing? I'd like the csv results to just include the text, minus the dashes.</p>
<p>I'm using Python 3.5, and am fairly new to Python.</p>
| 1 |
2016-09-20T17:38:58Z
| 39,600,588 |
<p>For removing the dashes try <code>y.replace("â","-").replace("â","-")</code> (first one is em-dash to minus, second one is en-dash to minus)</p>
<p>If you only want ASCII-codepoints you can remove everything else with</p>
<pre><code>import string
whitelist=string.printable+string.whitespace
def clean(s):
return "".join(c for c in s if c in whitelist)
</code></pre>
<p>(this yields mostly-reasonable results for pure-english text only)</p>
<p>Btw try using</p>
<pre><code>open('usnwr_schools.csv', 'w', newline='', encoding='utf-8') # or whatever encoding you like
</code></pre>
<p>because in Python 3 <code>csv.writer</code> takes text files not binary like it did in Python 2 (you opened it in binary mode (<code>"wb"</code>))</p>
| 1 |
2016-09-20T17:46:51Z
|
[
"python",
"python-3.x",
"unicode"
] |
Unicode issues when writing to CSV file
| 39,600,483 |
<p>I need some guidance, please. I'm using the following code: </p>
<pre><code>import requests
import bs4
import csv
results = requests.get('http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/top-engineering-schools/eng-rankings?int=a74509')
reqSoup = bs4.BeautifulSoup(results.text, "html.parser")
i = 0
schools = []
for school in reqSoup:
x = reqSoup.find_all("a", {"class" : "school-name"})
while i < len(x):
for name in x:
y = x[i].get_text()
i += 1
schools.append(y)
with open('usnwr_schools.csv', 'wb') as f:
writer = csv.writer(f)
for y in schools:
writer.writerow([y])
</code></pre>
<p>My problem is that the em-dashes are showing up as utf-8 in the resulting CSV file. I've tried several different things to fix it, but nothing seems to work (including <a href="http://stackoverflow.com/questions/33930767/trying-to-remove-character-em-dash-%C3%A2%E2%82%AC-in-python-using-regex">attempting to use regex</a> to get rid of it, as well as trying the <a href="http://stackoverflow.com/questions/27996448/python-encoding-decoding-problems">.translate method that I found in a StackOverflow</a> question from a few years ago). </p>
<p>What am I missing? I'd like the csv results to just include the text, minus the dashes.</p>
<p>I'm using Python 3.5, and am fairly new to Python.</p>
| 1 |
2016-09-20T17:38:58Z
| 39,611,047 |
<p>Learn to embrace Unicode...the world isn't ASCII anymore.</p>
<p>Assuming you are on Windows and viewing the .CSV with Excel or Notepad, use the following line on Python 3. With only this change (and fixing indentation of your post), You will even be able to view the non-ASCII characters correctly. Notepad and Excel like a UTF-8 BOM signature at the start of the file, which <code>utf-8-sig</code> provides.</p>
<pre><code>with open('usnwr_schools.csv', 'w', newline='', encoding='utf-8-sig') as f:
</code></pre>
<p>If reading the file in another Python script, make sure to read the file with the following. Your example of what you read <code>b'University of Michigan\xe2\x80\x94\xe2\x80\x8bAnn Arbor'</code> was read in binary mode <code>'rb'</code>.</p>
<pre><code>with open('usnwr_schools.csv', encoding='utf-8-sig') as f:
</code></pre>
<p>If on Linux, you can use <code>utf8</code> instead of <code>utf-8-sig</code>.</p>
<p>As an aside, you can replace your loops with:</p>
<pre><code>with open('usnwr_schools.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
for school in reqSoup:
x = reqSoup.find_all("a", {"class" : "school-name"})
for item in x:
y = item.get_text()
writer.writerow([y])
</code></pre>
<p>Reading it back:</p>
<pre><code>with open('usnwr_schools.csv',encoding='utf-8-sig') as f:
print(f.read())
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Massachusetts Institute of Technology
Stanford University
University of CaliforniaââBerkeley
California Institute of Technology
Carnegie Mellon University
University of MichiganââAnn Arbor
Georgia Institute of Technology
University of IllinoisââUrbana-âChampaign
Purdue UniversityââWest Lafayette
University of TexasââAustin (Cockrell)
Texas A&M; UniversityââCollege Station (Look)
Cornell University
University of Southern California (Viterbi)
Columbia University (Fu Foundation)
University of CaliforniaââLos Angeles (Samueli)
University of CaliforniaââSan Diego (Jacobs)
Princeton University
Northwestern University (McCormick)
University of Pennsylvania
Johns Hopkins University (Whiting)
Virginia Tech
University of CaliforniaââSanta Barbara
Harvard University
University of MarylandââCollege Park (Clark)
University of Washington
Massachusetts Institute of Technology
Stanford University
University of CaliforniaââBerkeley
California Institute of Technology
Carnegie Mellon University
University of MichiganââAnn Arbor
Georgia Institute of Technology
University of IllinoisââUrbana-âChampaign
Purdue UniversityââWest Lafayette
University of TexasââAustin (Cockrell)
Texas A&M; UniversityââCollege Station (Look)
Cornell University
University of Southern California (Viterbi)
Columbia University (Fu Foundation)
University of CaliforniaââLos Angeles (Samueli)
University of CaliforniaââSan Diego (Jacobs)
Princeton University
Northwestern University (McCormick)
University of Pennsylvania
Johns Hopkins University (Whiting)
Virginia Tech
University of CaliforniaââSanta Barbara
Harvard University
University of MarylandââCollege Park (Clark)
University of Washington
Massachusetts Institute of Technology
Stanford University
University of CaliforniaââBerkeley
California Institute of Technology
Carnegie Mellon University
University of MichiganââAnn Arbor
Georgia Institute of Technology
University of IllinoisââUrbana-âChampaign
Purdue UniversityââWest Lafayette
University of TexasââAustin (Cockrell)
Texas A&M; UniversityââCollege Station (Look)
Cornell University
University of Southern California (Viterbi)
Columbia University (Fu Foundation)
University of CaliforniaââLos Angeles (Samueli)
University of CaliforniaââSan Diego (Jacobs)
Princeton University
Northwestern University (McCormick)
University of Pennsylvania
Johns Hopkins University (Whiting)
Virginia Tech
University of CaliforniaââSanta Barbara
Harvard University
University of MarylandââCollege Park (Clark)
University of Washington
Massachusetts Institute of Technology
Stanford University
University of CaliforniaââBerkeley
California Institute of Technology
Carnegie Mellon University
University of MichiganââAnn Arbor
Georgia Institute of Technology
University of IllinoisââUrbana-âChampaign
Purdue UniversityââWest Lafayette
University of TexasââAustin (Cockrell)
Texas A&M; UniversityââCollege Station (Look)
Cornell University
University of Southern California (Viterbi)
Columbia University (Fu Foundation)
University of CaliforniaââLos Angeles (Samueli)
University of CaliforniaââSan Diego (Jacobs)
Princeton University
Northwestern University (McCormick)
University of Pennsylvania
Johns Hopkins University (Whiting)
Virginia Tech
University of CaliforniaââSanta Barbara
Harvard University
University of MarylandââCollege Park (Clark)
University of Washington
Massachusetts Institute of Technology
Stanford University
University of CaliforniaââBerkeley
California Institute of Technology
Carnegie Mellon University
University of MichiganââAnn Arbor
Georgia Institute of Technology
University of IllinoisââUrbana-âChampaign
Purdue UniversityââWest Lafayette
University of TexasââAustin (Cockrell)
Texas A&M; UniversityââCollege Station (Look)
Cornell University
University of Southern California (Viterbi)
Columbia University (Fu Foundation)
University of CaliforniaââLos Angeles (Samueli)
University of CaliforniaââSan Diego (Jacobs)
Princeton University
Northwestern University (McCormick)
University of Pennsylvania
Johns Hopkins University (Whiting)
Virginia Tech
University of CaliforniaââSanta Barbara
Harvard University
University of MarylandââCollege Park (Clark)
University of Washington
</code></pre>
<p>If you still want to be ASCII only, this will do it:</p>
<pre><code>import requests
import bs4
import csv
results = requests.get('http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/top-engineering-schools/eng-rankings?int=a74509')
replacements = {ord('\N{EN DASH}'):'-',
ord('\N{EM DASH}'):'-',
ord('\N{ZERO WIDTH SPACE}'):None}
reqSoup = bs4.BeautifulSoup(results.text, "html.parser")
with open('usnwr_schools.csv', 'w', newline='', encoding='ascii') as f:
writer = csv.writer(f)
for school in reqSoup:
x = reqSoup.find_all("a", {"class" : "school-name"})
for item in x:
y = item.get_text()
writer.writerow([y.translate(replacements)])
with open('usnwr_schools.csv',encoding='ascii') as f:
print(f.read())
</code></pre>
| 0 |
2016-09-21T08:16:25Z
|
[
"python",
"python-3.x",
"unicode"
] |
Appending lists according to a pair of lists (IndexError: list index out of range)
| 39,600,504 |
<p>I have these lists:</p>
<pre><code>n_crit = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 4, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 6, 0, 0], [0, 0, 0, 0, 0, 5]]
crit = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3, 8], [94, 96, 7, 3.6, 5, 6]]
</code></pre>
<p>and i have these code:</p>
<pre><code>DivMatrix = []
for x in range(len(crit)):
subList1 = []
for y in range(len(crit[x])):
subList2 = []
if (n_crit[2][x]>0):
for z in range(len(crit[x])):
subList2.append(crit[y][x] - crit[z][x])
elif (n_crit[2][x]<0):
for z in range(len(crit[x])):
subList2.append(-(crit[y][x] - crit[z][x]))
subList1.append(subList2)
DivMatrix.append(subList1)
</code></pre>
<p>Now I want to use the same code for another pair of lists that are:</p>
<pre><code>n_crit = [[1, 2, 3, 4, 5], [0.23, 0.15, 0.15, 0.215, 0.255], [-1, -1, 1, 1, 1], [2, 6, 5, 4, 1], [4000, 0, 20, 0, 0], [0, 0, 40, 2, 0], [0, 1.5, 0, 0, 0]]
crit = [[15000, 7, 60, 3, 3], [27000, 9, 120, 7, 7], [19000, 8.5, 90, 4, 5], [36000, 10, 140, 8, 7]]
</code></pre>
<p>But instead I get this error message:</p>
<pre><code> subList2.append(-(crit[y][x] - crit[z][x]))
IndexError: list index out of range
</code></pre>
<p>I really don't know what is wrong but I want to use this code for any pair of lists I want.</p>
| -3 |
2016-09-20T17:40:48Z
| 39,600,672 |
<p>At the time the exception is raised your Z value 4 but the n_crit is a list of 4 so index 4 (5th in the list) doesn't exist </p>
| 0 |
2016-09-20T17:51:45Z
|
[
"python",
"list",
"for-loop",
"append"
] |
Appending lists according to a pair of lists (IndexError: list index out of range)
| 39,600,504 |
<p>I have these lists:</p>
<pre><code>n_crit = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 4, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 6, 0, 0], [0, 0, 0, 0, 0, 5]]
crit = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3, 8], [94, 96, 7, 3.6, 5, 6]]
</code></pre>
<p>and i have these code:</p>
<pre><code>DivMatrix = []
for x in range(len(crit)):
subList1 = []
for y in range(len(crit[x])):
subList2 = []
if (n_crit[2][x]>0):
for z in range(len(crit[x])):
subList2.append(crit[y][x] - crit[z][x])
elif (n_crit[2][x]<0):
for z in range(len(crit[x])):
subList2.append(-(crit[y][x] - crit[z][x]))
subList1.append(subList2)
DivMatrix.append(subList1)
</code></pre>
<p>Now I want to use the same code for another pair of lists that are:</p>
<pre><code>n_crit = [[1, 2, 3, 4, 5], [0.23, 0.15, 0.15, 0.215, 0.255], [-1, -1, 1, 1, 1], [2, 6, 5, 4, 1], [4000, 0, 20, 0, 0], [0, 0, 40, 2, 0], [0, 1.5, 0, 0, 0]]
crit = [[15000, 7, 60, 3, 3], [27000, 9, 120, 7, 7], [19000, 8.5, 90, 4, 5], [36000, 10, 140, 8, 7]]
</code></pre>
<p>But instead I get this error message:</p>
<pre><code> subList2.append(-(crit[y][x] - crit[z][x]))
IndexError: list index out of range
</code></pre>
<p>I really don't know what is wrong but I want to use this code for any pair of lists I want.</p>
| -3 |
2016-09-20T17:40:48Z
| 39,601,183 |
<p>Apparently it was caused by out-of-range when referring list element. </p>
<p>For the first example, consider the dimensions of the list (try to think the list as two dimensions of matrix, each element in list is a row in matrix)</p>
<pre><code>n_crit = 7x6 (6x5, if starts with 0)
crit = 6x6 (5x5, if starts with 0)
</code></pre>
<p>And in your programming code:</p>
<pre><code>x should in [0, rows of crit-1], that is [0, 5]
y should in [0, cols of crit-1], that is [0, 5]
z should in [0, cols of crit-1], that is [0, 5]
</code></pre>
<p>So every</p>
<pre><code>crit[y][x], crit[z][x] are in 5x5 matrix, crit itself is 5x5,
</code></pre>
<p>which means they are valid.</p>
<p>For your second example</p>
<pre><code>n_crit = 7x5 (6x4, if starts with 0)
crit = 4x5 (3x4, if starts with 0)
x should in [0,3]
y should in [0,4]
z should in [0,4]
crit[y][x], crit[z][x] are in 4x3 matrix, while crit itself is 3x4
</code></pre>
<p>apparently will raise out-of-range exception.</p>
<p>I believe there must something wrong with your input, did you mistake the rows and columns of your second list.</p>
<p>In theory, when you do operation on two matrix, A and B, often it requires
that cols(A)=rows(B), e.g., matrix multiplication. So check your input.</p>
| 1 |
2016-09-20T18:22:18Z
|
[
"python",
"list",
"for-loop",
"append"
] |
Flaw in hangman program
| 39,600,549 |
<p>I need to write a simple hangman function that takes in one string (the word that's being guessed) and a list of letters (the letters that are guessed).
Here is my code so far:</p>
<pre><code>def WordGuessed(Word, letters):
if letters == []:
return False
else:
for i in letters:
if i not in Word:
return False
else:
if i == letters[-1]:
return True
</code></pre>
<p>The code usually works, but I am finding that occasionally prints the wrong answer. For example, if </p>
<pre><code>WordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u'])
</code></pre>
<p>It prints False when it should be printing True. Can anyone see where my code is wrong?</p>
| 0 |
2016-09-20T17:44:16Z
| 39,600,776 |
<p>You are returning False as soon as you find a guessed letter that is not in the word. In your example, the very first letter is not in the word.</p>
<p>It would work if instead you loop through <code>Word</code> and check each letter if it is in the array <code>letters</code>:</p>
<pre><code>def WordGuessed(Word, letters):
if letters == []:
return False
else:
for i in Word:
if i not in letters:
return False
else:
if i == Word[-1]:
return True
# prints True
print(WordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't', 'u']))
# prints False, missing 'u'
print(WordGuessed('durian', ['h', 'a', 'c', 'd', 'i', 'm', 'n', 'r', 't']))
</code></pre>
| 0 |
2016-09-20T17:57:49Z
|
[
"python"
] |
Python 3.5.2 web-scraping - list index out of range
| 39,600,662 |
<p>I am new web scraping and trying to scrap all the contents of Restaurant's Details Form so that I can proceed my further scraping.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib
url = "https://www.foodpanda.in/restaurants"
r=requests.get(url)
soup=BeautifulSoup(r.content,"html.parser")
print(soup.find_all("Section",class_="js-infscroll-load-more-here")[0])
</code></pre>
| 0 |
2016-09-20T17:51:06Z
| 39,601,782 |
<p>The problem is with accessing element at index <code>0</code> for <code>soup.find_all("Section",class_="js-infscroll-load-more-here"ââ)</code>, because the result is an empty list.</p>
| 0 |
2016-09-20T18:55:23Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
Python 3.5.2 web-scraping - list index out of range
| 39,600,662 |
<p>I am new web scraping and trying to scrap all the contents of Restaurant's Details Form so that I can proceed my further scraping.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib
url = "https://www.foodpanda.in/restaurants"
r=requests.get(url)
soup=BeautifulSoup(r.content,"html.parser")
print(soup.find_all("Section",class_="js-infscroll-load-more-here")[0])
</code></pre>
| 0 |
2016-09-20T17:51:06Z
| 39,605,554 |
<p>html has no notion of uppercase tag and regardless even in the source itself it is <em>section</em> not <em>Section</em> with a lowercase s:</p>
<pre><code>section = soup.find_all("section",class_="js-infscroll-load-more-here")[0]
</code></pre>
<p>Since there is only one you can also use find:</p>
<pre><code> section = soup.find("section",class_="js-infscroll-load-more-here")
</code></pre>
<p>Both of which will find what you are looking for.</p>
| 0 |
2016-09-21T00:05:37Z
|
[
"python",
"web-scraping",
"beautifulsoup"
] |
Tkinter call function in another class
| 39,600,676 |
<p>Hi i got some code from an answer on <a href="http://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter">Switch between two frames in tkinter</a> which im trying to modify so a button in the StartPage class can call a function called msg in PageOne class. </p>
<p>But im getting this error:</p>
<blockquote>
<p>AttributeError: 'Frame' object has no attribute 'msg'</p>
</blockquote>
<p>Here is the code so far i marked out the modifications i made to the code.</p>
<pre><code>import tkinter as tk # python3
#import Tkinter as tk # python
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.parent = parent #<-- my mod
label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
self.button3 = tk.Button(text='Calling msg in another class', command=self.parent.msg)#<-- my mod
button1.pack()
button2.pack()
button3.pack()#<-- my mod
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.parent = parent #<-- my mod
label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
def msg(self): #<-- my mod
print("IT WORKS!!")
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
</code></pre>
<p>Could anyone help me out?</p>
| -1 |
2016-09-20T17:52:09Z
| 39,621,662 |
<p>Since you're instantiating all your classes in a loop, the easiest way to add references between them is probably to do it after that loop. Remove those references from inside the class, as they won't be valid until after instantiation. Note how <code>button3</code> is no longer created or packed in <code>StartPage</code>, but rather in <code>SampleApp</code>.</p>
<pre><code>for F in (StartPage, PageOne, PageTwo):
...
self.frames['StartPage'].pageone = self.frames['PageOne']
self.frames['StartPage'].button3 = tk.Button(
text='Calling msg in another class',
command=self.frames['StartPage'].pageone.msg) #<-- my mod
self.frames['StartPage'].button3.pack() #<-- my mod
</code></pre>
| 0 |
2016-09-21T16:15:16Z
|
[
"python",
"tkinter"
] |
How to paint on top of QListWidget in eventfilter in PyQt4/PySide?
| 39,600,696 |
<p>I tried this on QLable and it works, I do not want to subclass the widget, because they are defined in .ui files, and I just need to do simple modification so I want to avoid delegate. If I put my code in paintEvent it works, but why I can not put it in eventfilter? </p>
<p>It seems it painted the square but it's below the listWidgetItem area.</p>
<pre><code># -*- coding: utf-8 -*-
from PySide.QtCore import *
from PySide.QtGui import *
class xxxx(QListWidget):
def __init__(self, parent=None):
super(xxxx, self).__init__(parent)
self.installEventFilter(self)
# def paintEvent(self, event):
# p = QPainter()
# p.begin(self.viewport())
# p.setPen(QPen(Qt.black))
# p.fillRect(QRect(0, 1, 20, 20), Qt.red)
# p.end()
def eventFilter(self, widget, event):
if event.type() == QEvent.Paint:
p = QPainter()
# p.begin(self.viewport())
p.begin(widget)
p.setPen(QPen(Qt.red))
p.fillRect(QRect(0, 1, 20, 20), Qt.red)
p.end()
return True
return QListWidget.eventFilter(self, widget, event)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
view = xxxx()
view.show()
sys.exit(app.exec_())
</code></pre>
| 1 |
2016-09-20T17:53:23Z
| 39,601,599 |
<p>You need to install the event-filter on the viewport:</p>
<pre><code>class xxxx(QListWidget):
def __init__(self, parent=None):
super(xxxx, self).__init__(parent)
self.viewport().installEventFilter(self)
def eventFilter(self, widget, event):
if event.type() == QEvent.Paint:
p = QPainter()
p.begin(widget)
p.setPen(QPen(Qt.red))
p.fillRect(QRect(0, 1, 20, 20), Qt.red)
p.end()
return True
return super(xxxx, self).eventFilter(widget, event)
</code></pre>
| 0 |
2016-09-20T18:46:14Z
|
[
"python",
"pyqt",
"pyside",
"qpainter",
"qlistwidget"
] |
How to print query result in python/django
| 39,600,741 |
<p>I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:</p>
<ul>
<li>A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.</li>
<li>A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.</li>
</ul>
<p>I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
<strong><em>app_name/views.py:</em></strong></p>
<pre><code>def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
return render(request, 'socs/detail.html', {'soc': soc})
</code></pre>
<p>How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.</p>
<p>I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)</p>
<pre><code>import pprint
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
pprint.pprint(soc)
return render(request, 'socs/detail.html', {'soc': soc})
</code></pre>
<p>I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.</p>
| 0 |
2016-09-20T17:55:24Z
| 39,602,003 |
<p>The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.</p>
<p>If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send <code>{'soc': soc}</code> to your template as context. Because of this, you should be able to use it in your template. So, in your template (<code>socs/detail.html</code>), just add <code>{{ soc }}</code> somewhere and it should print out the value. The template has full access to the object, so if you wanted something specific, you can also print that instead (like <code>{{ soc.id }}</code>).</p>
<p>If you want to see everything that's in the object without specifying all of the different fields yourself, send <code>OBJECT.__dir__</code>. For example, for this you'd send <code>{'soc': soc.__dir__}</code> as your context. Keep in mind that this likely should not be used for anything but inspection on your part.</p>
<p>If you'd like to learn more about Django's templating, check out <a href="https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language" rel="nofollow">the syntax and more</a>.</p>
| 0 |
2016-09-20T19:07:49Z
|
[
"php",
"python",
"django",
"cakephp",
"pprint"
] |
How to print query result in python/django
| 39,600,741 |
<p>I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:</p>
<ul>
<li>A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.</li>
<li>A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.</li>
</ul>
<p>I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
<strong><em>app_name/views.py:</em></strong></p>
<pre><code>def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
return render(request, 'socs/detail.html', {'soc': soc})
</code></pre>
<p>How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.</p>
<p>I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)</p>
<pre><code>import pprint
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
pprint.pprint(soc)
return render(request, 'socs/detail.html', {'soc': soc})
</code></pre>
<p>I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.</p>
| 0 |
2016-09-20T17:55:24Z
| 39,602,469 |
<p>I meant something like this in CakePHP</p>
<pre><code>/* First, create our posts table: */
CREATE TABLE posts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
/* Then insert some posts for testing: */
INSERT INTO posts (title, body, created)
VALUES ('The title', 'This is the post body.', NOW());
INSERT INTO posts (title, body, created)
VALUES ('A title once again', 'And the post body follows.', NOW());
INSERT INTO posts (title, body, created)
VALUES ('Title strikes back', 'This is really exciting! Not.', NOW());
</code></pre>
<p>And in the PostController.php</p>
<pre><code>class PostsController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
$this->set('posts', $this->Post->find('all'));
}
}
</code></pre>
<p>And with the variable $posts in $this->set('posts'...) I can do this</p>
<pre><code>// print_r($posts) output:
Array
(
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => The title
[body] => This is the post body.
[created] => 2008-02-13 18:34:55
[modified] =>
)
)
[1] => Array
(
[Post] => Array
(
[id] => 2
[title] => A title once again
[body] => And the post body follows.
[created] => 2008-02-13 18:34:56
[modified] =>
)
)
[2] => Array
(
[Post] => Array
(
[id] => 3
[title] => Title strikes back
[body] => This is really exciting! Not.
[created] => 2008-02-13 18:34:57
[modified] =>
)
)
)
</code></pre>
<p>The output will be displayed directly on the Index page of Posts. Really easy for me to travel through the $posts variable to actually write the view.</p>
<p>I'm looking for something similar in Django. I really hope I explain my question clear enough, since I don't have enough experience with Django yet.</p>
| 0 |
2016-09-20T19:37:13Z
|
[
"php",
"python",
"django",
"cakephp",
"pprint"
] |
Webassets + Typescript, cannot resolve symbols/modules
| 39,600,748 |
<p>I have a flask project with the following structure:</p>
<pre><code>ââ app.py
ââ project
| ââ __init__.py
| ââ static
| ââ typescript
| ââ app.ts
ââ typings
ââ globals
| ââ ... # multiple imported ts libraries
ââ index.d.ts
</code></pre>
<p>I'm using a webpacker integration called <a href="https://flask-assets.readthedocs.io/en/latest/" rel="nofollow">Flask Assets</a>. I've set up the compilation like so (in <code>__init__.py</code>)</p>
<pre><code>ts = get_filter('typescript')
ts.load_paths = [
#os.path.join(config.APP_ROOT, '..', 'typings'), # doesn't do anything :/
os.path.join(app.static_folder, 'typescript')
]
assets.register('javascript', Bundle(
'typescript/app.ts',
filters = (ts, 'jsmin'),
output = 'js/app-%(version)s.js'
))
</code></pre>
<p>My app.ts is, more or less, </p>
<pre><code>class SomeClass {
... various class methods, using things like jQuery and CryptoJS
}
</code></pre>
<p>no imports - I'm not really sure whether or not I need them.</p>
<p>The specific error I'm getting is </p>
<pre><code>Cannot find name 'JQuery'.
../../../../../var/folders/5t/4x0gmsdx0dbbgv_fr3cv3x6m0000gn/T/tmphFTSQo.ts(7,17): error TS2503: Cannot find namespace 'CryptoJS'.
../../../../../var/folders/5t/4x0gmsdx0dbbgv_fr3cv3x6m0000gn/T/tmphFTSQo.ts(10,27): error TS2304: Cannot find name '$'.
... a bunch more about other symbols
</code></pre>
| 0 |
2016-09-20T17:55:57Z
| 39,604,440 |
<p>I <em>kind of</em> solved it...</p>
<pre><code>glob_string = os.path.join(config.APP_ROOT, '..', 'typings', '*', '*', '*.d.ts')
assets.register('javascript', Bundle(
glob.glob(glob_string),
'typescript/app.ts',
filters = ('typescript', 'jsmin'),
output = 'js/app-%(version)s.js'
))
</code></pre>
<p>basically I just "manually" add all the definition files to the bundle (using glob). It's not sufficient to just add the <code>index.d.ts</code> in the root of the typings dir as the typescript filter copies the <code>.ts</code> to a temp file (in <code>/tmp</code>) before compiling and the paths in <code>index.d.ts</code> are relative.</p>
<p>it should also be noted that <code>ts.load_paths</code> does nothing...</p>
| 0 |
2016-09-20T22:04:37Z
|
[
"python",
"typescript",
"flask",
"webpack",
"webassets"
] |
Hacking tail-optimization
| 39,600,764 |
<p>I've recently discovered the <code>inspect</code> and thought if it's possible to manually remove "outer" frames of the current frame and thus implementing tail-recursion optimization. </p>
<p><strong>Is it possible? How?</strong></p>
| 0 |
2016-09-20T17:57:06Z
| 39,600,829 |
<p>It's not possible. <code>inspect</code> doesn't let you rewrite the stack that way, and in any case, it only gives Python stack frames. Even if you could change how the Python stack frames hook up to each other, the C call stack would be unaffected.</p>
| 1 |
2016-09-20T18:01:06Z
|
[
"python",
"optimization",
"tail-recursion"
] |
Django 1.9 check if email already exists
| 39,600,784 |
<p>My site is set up so there is no username (or rather user.username = user.email). Django has an error message if a user tries to input a username that is already in the database, however since I'm not using a username for registration I can't figure out how to do this. </p>
<p>Just like the default settings already is, I don't want to reload the page to find out if there is an email address already associated with a user. My guess is to use Ajax, but I can't figure out how to do it. Ive looked at other posts, but there doesn't seem to be anything recent. </p>
<p>How can I check to see if an email address already exists, and if so, give an error message for the user to input a new email address?</p>
<p>models.py:</p>
<pre><code>class MyUsers(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=100, blank=True)
last_name = models.CharField(max_length=100, blank=True)
email = models.EmailField(max_length=100, blank=True, unique=True)
company = models.CharField(max_length=100, blank=True, null=True)
website = models.URLField(max_length=100, blank=True, null=True)
phone_number = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.user.username
</code></pre>
<p>forms.py:</p>
<pre><code>class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
</code></pre>
<p>views.py:</p>
<pre><code>def index(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.password = ""
user.username = user.email
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.email = user.email
profile.save()
user.first_name = profile.first_name
user.last_name = profile.last_name
user.save()
registered = True
return HttpResponseRedirect(reverse('registration'))
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm1()
context = {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}
return render(request, 'mysite/register.html', context)
</code></pre>
<p>register.html:</p>
<pre><code>{% extends 'mysite/base.html' %}
{% load staticfiles %}
{% block title_block %}
Register
{% endblock %}
{% block head_block %}
{% endblock %}
{% block body_block %}
<form id="user_form" method="post" action="/mysite/" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="submit" value="Register" />
</form>
{% endblock %}
</code></pre>
| 1 |
2016-09-20T17:58:08Z
| 39,602,446 |
<p>You can override the <code>clean_<INSERT_FIELD_HERE>()</code> method on the <code>UserForm</code> to check against this particular case. It'd look something like this:</p>
<p><em>forms.py:</em></p>
<pre><code>class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
# Check to see if any users already exist with this email as a username.
try:
match = User.objects.get(username=email)
except User.DoesNotExist:
# Unable to find a user, this is fine
return email
# A user was found with this as a username, raise an error.
raise forms.ValidationError('This email address is already in use.')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'company', 'website', 'phone_number')
</code></pre>
<p>You can read more about cleaning specific fields in a form in the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-a-specific-field-attribute" rel="nofollow">Django documentation</a> about forms.</p>
<p>That said, I think you should look into creating a <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#specifying-a-custom-user-model" rel="nofollow">custom user model</a> instead of treating your <code>User Profile</code> class as a wrapper for <code>User</code>.</p>
| 1 |
2016-09-20T19:35:38Z
|
[
"python",
"ajax",
"django",
"django-forms",
"django-templates"
] |
Why can you close() a file object more than once?
| 39,600,786 |
<p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error when people explicitly close the file anyway through misunderstanding... and then I found that you can call <code>close()</code> on a file multiple times with no error even without using <code>with</code>.</p>
<p>The only thing we can find relating to this is <a href="https://docs.python.org/2.4/lib/bltin-file-objects.html" rel="nofollow">here</a> and it just blandly says (emphasis mine):</p>
<blockquote>
<p>close( ) <br>
Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. <strong>Calling close() more than once is allowed</strong>.</p>
</blockquote>
<p>It would appear that this is intentional by design but, if you can't perform any operations on the closed file without an exception, we can't work out why closing the file multiple times is permitted. Is there a use case?</p>
| 1 |
2016-09-20T17:58:19Z
| 39,600,863 |
<p>Resource management is a big deal. It's part of the reason why we have context managers in the first place.</p>
<p>I'm <em>guessing</em> that the core development team thought that it is better to make it "safe" to call close more than once to encourage people to close their files. Otherwise, you could get yourself into a situation where you're asking "Was this closed before?". If <code>.close()</code> couldn't be called multiple times, the only option would be to put your <code>file.close()</code> call in a <code>try</code>/<code>except</code> clause. That makes the code uglier and (frankly), lots of people probably would just delete the call to <code>file.close()</code> rather than handle it properly. In this case, it's just convenient to be able to call <code>file.close()</code> without worrying about any consequences since it's almost certain to succeed and leave you with a file that you know is closed afterward.</p>
| 3 |
2016-09-20T18:03:18Z
|
[
"python"
] |
Why can you close() a file object more than once?
| 39,600,786 |
<p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error when people explicitly close the file anyway through misunderstanding... and then I found that you can call <code>close()</code> on a file multiple times with no error even without using <code>with</code>.</p>
<p>The only thing we can find relating to this is <a href="https://docs.python.org/2.4/lib/bltin-file-objects.html" rel="nofollow">here</a> and it just blandly says (emphasis mine):</p>
<blockquote>
<p>close( ) <br>
Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. <strong>Calling close() more than once is allowed</strong>.</p>
</blockquote>
<p>It would appear that this is intentional by design but, if you can't perform any operations on the closed file without an exception, we can't work out why closing the file multiple times is permitted. Is there a use case?</p>
| 1 |
2016-09-20T17:58:19Z
| 39,600,900 |
<ol>
<li><p>Thinking about <code>with</code> is just wrong. This behaviour has been in Python <em>forever</em> and thus it's worth keeping it for backward compatibility.</p></li>
<li><p>Because it would serve no purpose to raise an exception. If you have an actual bug in your code where you might close the file before finishing using it, you'll get an exception when using the <code>read</code> or <code>write</code> operations anyway, and thus you'll never reach the second call to <code>close</code>.</p></li>
<li><p>Allowing this will <em>rarely</em> make the code easier to write avoiding adding lots of <code>if not the_file.isclosed(): the_file.close()</code>.</p></li>
<li><p>The BDFL designed the file objects in that way and we are stuck with that behaviour since there's no strong reason to change it.</p></li>
</ol>
| 2 |
2016-09-20T18:06:11Z
|
[
"python"
] |
Why can you close() a file object more than once?
| 39,600,786 |
<p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error when people explicitly close the file anyway through misunderstanding... and then I found that you can call <code>close()</code> on a file multiple times with no error even without using <code>with</code>.</p>
<p>The only thing we can find relating to this is <a href="https://docs.python.org/2.4/lib/bltin-file-objects.html" rel="nofollow">here</a> and it just blandly says (emphasis mine):</p>
<blockquote>
<p>close( ) <br>
Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. <strong>Calling close() more than once is allowed</strong>.</p>
</blockquote>
<p>It would appear that this is intentional by design but, if you can't perform any operations on the closed file without an exception, we can't work out why closing the file multiple times is permitted. Is there a use case?</p>
| 1 |
2016-09-20T17:58:19Z
| 39,600,961 |
<p>Function call fulfilled its promise - after calling it file <strong>is closed</strong>. It's not like something <em>failed</em>, it's just you did not have to do anything at all to ensure condition you we're asking for.</p>
| 0 |
2016-09-20T18:10:08Z
|
[
"python"
] |
Scraping values from a webpage table
| 39,600,800 |
<p>I want to create a python dictionary of color names to background color from this <a href="http://people.csail.mit.edu/jaffer/Color/M.htm" rel="nofollow">color dictionary</a>.</p>
<p>What is the best way to access the color name strings and the background color hex values? I want to create a mapping for color name --> hex values, where 1 color name maps to 1 or more hex values.</p>
<p>The following is my code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
page = requests.get('http://people.csail.mit.edu/jaffer/Color/M.htm')
soup = BeautifulSoup(page.text)
</code></pre>
<p>I'm not sure how to specify what to scrape from the table. I've tried the following to get a format that's useful:</p>
<pre><code>soup.td
<td nowrap="" width="175*">abbey</td>
soup.get_text()
"(M)\n td { padding: 0 10px; } \n\n(M) Dictionary of Color Maerz and Paul, Dictionary of Color, 1st ed. \n\nabbey207\nabsinthe [green] 120\nabsinthe yellow105\nacacia101102\nacademy blue173\nacajou43\nacanthe95\nacier109\nackermann's green137\naconite violet223....
.............\nyolk yellow84\nyosemite76\nyucatan5474\nyucca150\nyu chi146\nyvette violet228\n\nzaffre blue 179182\nzanzibar47\nzedoary wash71\nzenith [blue] 199203\nzephyr78\nzinc233265\nzinc green136\nzinc orange5053\nzinc yellow84\nzinnia15\nzulu47\nzuni brown58\n\n"
soup.select('tr td')
[...
<td nowrap="" width="175*">burnt russet</td>,
<td style="background-color:#722F37; color:#FFF" title="16">16</td>,
<td style="background-color:#79443B; color:#FFF" title="43">43
</td>,
<td nowrap="" width="175*">burnt sienna</td>,
<td style="background-color:#9E4732; color:#FFF" title="38">38
</td>,
...]
</code></pre>
<p>EDIT:
I want to scrape the strings in the td elements e.g "burnt russet" as the color and the string (hex component) in the following td elements where the "style" attribute is specified as the background color.</p>
<p>I want the dictionary to look as follows:</p>
<pre><code>color_map = {'burnt russet': [#722F37, #79443B], 'burnt sienna': [#9E4732]}
</code></pre>
| 1 |
2016-09-20T17:58:56Z
| 39,603,058 |
<p>The webpage that you are trying to scrape is horribly-formed HTML. After <code>View Page Source</code>, it is apparent that most rows start with a <code><tr></code> and then have one or more <code><td></code> elements, all without their closing tags. With <code>BeautifulSoup</code> one should specify an HTML parser, and for the case at hand, we had better hope the parser can understand the table structure.</p>
<p>I present a solution that relies on the structured format of the webpage itself. Instead of parsing the webpage as HTML, I use the fact that each color has its own line and each line has a common format.</p>
<pre><code>import re
import requests
page = requests.get('http://people.csail.mit.edu/jaffer/Color/M.htm')
lines = page.text.splitlines()
opening = '<tr><td width="175*" nowrap>'
ending = '<td title="'
bg_re = r'style="background-color:(#.{6})'
color_map = dict()
for line in lines:
if line.startswith(opening):
color_name = line[len(opening):line.find(ending)].strip()
color_hex = [match.group(1) for match in re.finditer(bg_re, line)]
if color_name in color_map:
color_map[color_name].extend(color_hex) # Note: some colors are repeated
else:
color_map[color_name] = color_hex
color_map['burnt russet']
## ['#722F37', '#79443B']
</code></pre>
<p>Quick and dirty, but it works.</p>
| 0 |
2016-09-20T20:16:57Z
|
[
"python",
"html",
"beautifulsoup"
] |
Scraping values from a webpage table
| 39,600,800 |
<p>I want to create a python dictionary of color names to background color from this <a href="http://people.csail.mit.edu/jaffer/Color/M.htm" rel="nofollow">color dictionary</a>.</p>
<p>What is the best way to access the color name strings and the background color hex values? I want to create a mapping for color name --> hex values, where 1 color name maps to 1 or more hex values.</p>
<p>The following is my code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
page = requests.get('http://people.csail.mit.edu/jaffer/Color/M.htm')
soup = BeautifulSoup(page.text)
</code></pre>
<p>I'm not sure how to specify what to scrape from the table. I've tried the following to get a format that's useful:</p>
<pre><code>soup.td
<td nowrap="" width="175*">abbey</td>
soup.get_text()
"(M)\n td { padding: 0 10px; } \n\n(M) Dictionary of Color Maerz and Paul, Dictionary of Color, 1st ed. \n\nabbey207\nabsinthe [green] 120\nabsinthe yellow105\nacacia101102\nacademy blue173\nacajou43\nacanthe95\nacier109\nackermann's green137\naconite violet223....
.............\nyolk yellow84\nyosemite76\nyucatan5474\nyucca150\nyu chi146\nyvette violet228\n\nzaffre blue 179182\nzanzibar47\nzedoary wash71\nzenith [blue] 199203\nzephyr78\nzinc233265\nzinc green136\nzinc orange5053\nzinc yellow84\nzinnia15\nzulu47\nzuni brown58\n\n"
soup.select('tr td')
[...
<td nowrap="" width="175*">burnt russet</td>,
<td style="background-color:#722F37; color:#FFF" title="16">16</td>,
<td style="background-color:#79443B; color:#FFF" title="43">43
</td>,
<td nowrap="" width="175*">burnt sienna</td>,
<td style="background-color:#9E4732; color:#FFF" title="38">38
</td>,
...]
</code></pre>
<p>EDIT:
I want to scrape the strings in the td elements e.g "burnt russet" as the color and the string (hex component) in the following td elements where the "style" attribute is specified as the background color.</p>
<p>I want the dictionary to look as follows:</p>
<pre><code>color_map = {'burnt russet': [#722F37, #79443B], 'burnt sienna': [#9E4732]}
</code></pre>
| 1 |
2016-09-20T17:58:56Z
| 39,603,387 |
<p>Just look for the tds with nowrap, extract the text and get the following siblings td's <em>style</em> attribute:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
page = requests.get('http://people.csail.mit.edu/jaffer/Color/M.htm')
soup = BeautifulSoup(page.content)
for td in soup.select("td[nowrap]"):
print(td.text, [sib["style"] for sib in td.find_next_siblings("td")])
</code></pre>
<p>A snippet of the output:</p>
<pre><code> (u'abbey', ['background-color:#604E97; color:#FFF'])
(u'absinthe [green] ', ['background-color:#8A9A5B'])
(u'absinthe yellow', ['background-color:#B9B57D'])
(u'acacia', ['background-color:#EAE679', 'background-color:#B9B459'])
(u'academy blue', ['background-color:#367588'])
(u'acajou', ['background-color:#79443B; color:#FFF'])
(u'acanthe', ['background-color:#6C541E; color:#FFF'])
(u'acier', ['background-color:#8C8767'])
(u"ackermann's green", ['background-color:#355E3B; color:#FFF'])
(u'aconite violet', ['background-color:#86608E'])
(u'acorn', ['background-color:#7E6D5A; color:#FFF'])
(u'adamia', ['background-color:#563C5C; color:#FFF'])
(u'adelaide', ['background-color:#32174D; color:#FFF'])
</code></pre>
<p>If you just want the hex values you can split the style text on <code>"; "</code> then split the sub strings on <code>:</code>:</p>
<pre><code>page = requests.get('http://people.csail.mit.edu/jaffer/Color/M.htm')
soup = BeautifulSoup(page.content)
d = {}
for td in soup.select("td[nowrap]"):
cols = td.find_next_siblings("td")
d[td.text] = [st.split(":", 1)[-1] for sib in cols for st in sib["style"].split("; ")]
print(d)
</code></pre>
<p>That will give you a dioct like:</p>
<pre><code>{u'moonlight ': ['#FAD6A5', '#BFB8A5'], u'honey bird': ['#239EBA'], u'monte carlo ': ['#007A74', '#317873'],...............
</code></pre>
<p>You will need to use either <code>lxml</code> or <code>html5lib</code> as the parser to handle the broken html. I presume you are using one of them as if not you would not get the output you do.</p>
| 2 |
2016-09-20T20:42:20Z
|
[
"python",
"html",
"beautifulsoup"
] |
Setting pandas.DataFrame string dtype (not file based)
| 39,600,816 |
<p>I'm having trouble with using <code>pandas.DataFrame</code>'s constructor and using the <code>dtype</code> argument. I'd like to preserve string values, but the following snippets always convert to a numeric type and then yield <code>NaN</code>s.</p>
<pre><code>from __future__ import unicode_literals
from __future__ import print_function
import numpy as np
import pandas as pd
def main():
columns = ['great', 'good', 'average', 'bad', 'horrible']
# minimal example, dates are coming (as strings) from some
# non-file source.
example_data = {
'alice': ['', '', '', '2016-05-24', ''],
'bob': ['', '2015-01-02', '', '', '2012-09-15'],
'eve': ['2011-12-31', '', '1998-08-13', '', ''],
}
# first pass, yields dataframe full of NaNs
df = pd.DataFrame(data=example_data, index=example_data.keys(),
columns=columns, dtype=str) #or string, 'str', 'string', 'object'
print(df.dtypes)
print(df)
print()
# based on https://github.com/pydata/pandas/blob/master/pandas/core/frame.py
# and https://github.com/pydata/pandas/blob/37f95cef85834207db0930e863341efb285e38a2/pandas/types/common.py
# we're ultimately feeding dtype to numpy's dtype, so let's just use that:
# (using np.dtype('S10') and converting to str doesn't work either)
df = pd.DataFrame(data=example_data, index=example_data.keys(),
columns=columns, dtype=np.dtype('U'))
print(df.dtypes)
print(df) # still full of NaNs... =(
if __name__ == '__main__':
main()
</code></pre>
<p>What value(s) of <code>dtypes</code> will preserve strings in the data frame?</p>
<p>for reference:</p>
<blockquote>
<p>$ python --version</p>
<p>2.7.12</p>
<p>$ pip2 list | grep pandas</p>
<p>pandas (0.18.1)</p>
<p>$ pip2 list | grep numpy</p>
<p>numpy (1.11.1)</p>
</blockquote>
| 1 |
2016-09-20T18:00:36Z
| 39,601,970 |
<p>This is not a proper answer, but while you get one by someone else, I've noticed that using the <code>read_csv</code> function everything works.</p>
<p>So if you place your data in a <code>.csv</code> file called <code>myData.csv</code>, like this:</p>
<pre><code>great,good,average,bad,horrible
alice,,,,2016-05-24,
bob,,2015-01-02,,,2012-09-15
eve,2011-12-31,,1998-08-13,,
</code></pre>
<p>and do</p>
<pre><code>df = pd.read_csv('blablah/myData.csv')
</code></pre>
<p>it will keep the strings as they are!</p>
<pre><code> great good average bad horrible
alice NaN NaN NaN 2016-05-24 NaN
bob NaN 2015-01-02 NaN NaN 2012-09-15
eve 2011-12-31 NaN 1998-08-13 NaN NaN
</code></pre>
<p>if you want, the empty values can be put as an space in the csv file or any other character/marker.</p>
| 0 |
2016-09-20T19:06:03Z
|
[
"python",
"pandas",
"numpy"
] |
Setting pandas.DataFrame string dtype (not file based)
| 39,600,816 |
<p>I'm having trouble with using <code>pandas.DataFrame</code>'s constructor and using the <code>dtype</code> argument. I'd like to preserve string values, but the following snippets always convert to a numeric type and then yield <code>NaN</code>s.</p>
<pre><code>from __future__ import unicode_literals
from __future__ import print_function
import numpy as np
import pandas as pd
def main():
columns = ['great', 'good', 'average', 'bad', 'horrible']
# minimal example, dates are coming (as strings) from some
# non-file source.
example_data = {
'alice': ['', '', '', '2016-05-24', ''],
'bob': ['', '2015-01-02', '', '', '2012-09-15'],
'eve': ['2011-12-31', '', '1998-08-13', '', ''],
}
# first pass, yields dataframe full of NaNs
df = pd.DataFrame(data=example_data, index=example_data.keys(),
columns=columns, dtype=str) #or string, 'str', 'string', 'object'
print(df.dtypes)
print(df)
print()
# based on https://github.com/pydata/pandas/blob/master/pandas/core/frame.py
# and https://github.com/pydata/pandas/blob/37f95cef85834207db0930e863341efb285e38a2/pandas/types/common.py
# we're ultimately feeding dtype to numpy's dtype, so let's just use that:
# (using np.dtype('S10') and converting to str doesn't work either)
df = pd.DataFrame(data=example_data, index=example_data.keys(),
columns=columns, dtype=np.dtype('U'))
print(df.dtypes)
print(df) # still full of NaNs... =(
if __name__ == '__main__':
main()
</code></pre>
<p>What value(s) of <code>dtypes</code> will preserve strings in the data frame?</p>
<p>for reference:</p>
<blockquote>
<p>$ python --version</p>
<p>2.7.12</p>
<p>$ pip2 list | grep pandas</p>
<p>pandas (0.18.1)</p>
<p>$ pip2 list | grep numpy</p>
<p>numpy (1.11.1)</p>
</blockquote>
| 1 |
2016-09-20T18:00:36Z
| 39,602,426 |
<p>For the particular case in the OP, you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html" rel="nofollow"><code>DataFrame.from_dict()</code> constructor</a> (see also the <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#alternate-constructors" rel="nofollow">Alternate Constructors</a> section of the DataFrame documentation) .</p>
<pre><code>from __future__ import unicode_literals
from __future__ import print_function
import pandas as pd
columns = ['great', 'good', 'average', 'bad', 'horrible']
example_data = {
'alice': ['', '', '', '2016-05-24', ''],
'bob': ['', '2015-01-02', '', '', '2012-09-15'],
'eve': ['2011-12-31', '', '1998-08-13', '', ''],
}
df = pd.DataFrame.from_dict(example_data, orient='index')
df.columns = columns
print(df.dtypes)
# great object
# good object
# average object
# bad object
# horrible object
# dtype: object
print(df)
# great good average bad horrible
# bob 2015-01-02 2012-09-15
# eve 2011-12-31 1998-08-13
# alice 2016-05-24
</code></pre>
<p>You can even specify <code>dtype=str</code> in <code>DataFrame.from_dict()</code> — though it is not necessary in this example.</p>
<p>EDIT: The DataFrame constructor interprets a dictionary as a collection of columns:</p>
<pre><code>print(pd.DataFrame(example_data))
# alice bob eve
# 0 2011-12-31
# 1 2015-01-02
# 2 1998-08-13
# 3 2016-05-24
# 4 2012-09-15
</code></pre>
<p>(I'm dropping the <code>data=</code>, since <code>data</code> is the first argument in the function's signature anyway). Your code confuses rows and columns:</p>
<pre><code>print(pd.DataFrame(example_data, index=example_data.keys(), columns=columns))
# great good average bad horrible
# alice NaN NaN NaN NaN NaN
# bob NaN NaN NaN NaN NaN
# eve NaN NaN NaN NaN NaN
</code></pre>
<p>(though I'm not exactly sure how it ends up giving you a DataFrame of <code>NaN</code>s). It would be correct to do</p>
<pre><code>print(pd.DataFrame(example_data, columns=example_data.keys(), index=columns))
# alice bob eve
# great 2011-12-31
# good 2015-01-02
# average 1998-08-13
# bad 2016-05-24
# horrible 2012-09-15
</code></pre>
<p>Specifying the column names is actually unnecessary — they are already parsed from the dictionary:</p>
<pre><code>print(pd.DataFrame(example_data, index=columns))
# alice bob eve
# great 2011-12-31
# good 2015-01-02
# average 1998-08-13
# bad 2016-05-24
# horrible 2012-09-15
</code></pre>
<p>What you want is actually the <em>transpose</em> of this — so you can also take said transpose!</p>
<pre><code>print(pd.DataFrame(data=example_data, index=columns).T)
# great good average bad horrible
# alice 2016-05-24
# bob 2015-01-02 2012-09-15
# eve 2011-12-31 1998-08-13
</code></pre>
| 1 |
2016-09-20T19:34:08Z
|
[
"python",
"pandas",
"numpy"
] |
Python 3.X Rock Paper Scissors Lizard Spock issue
| 39,600,824 |
<p>Hello i am new to coding but i have been stuck on a code for very long and can't seem to find the answer here on stackoverflow. </p>
<p>Whatever i do the answer ends up with the first print of Player 1 wins: Player One wins, Rock beats Scissors.</p>
<pre><code>player1 = input("Player One do you want Rock, Paper, Scissors, Lizard or Spock?")
player2 = input("Player Two do you want Rock, Paper, Scissors, Lizard or Spock?")
print(player1)
print(player2)
rock = 1
paper = 2
scissors = 3
lizard = 4
spock = 5
#Tie
if (player1 == player2):
print("It's a tie.")
#Player 1 wins
elif (player1 == 1, player2 == 3):
print("Player One wins, Rock beats Scissors.")
elif (player1 == 1, player2 == 4):
print("Player One wins, Rock beats Lizard.")
elif (player1 == 2, player2 == 1):
print("Player One wins, Paper beats Rock.")
elif (player1 == 2, player2 == 5):
print("Player One wins, Paper beats Spock.")
elif (player1 == 3, player2 == 2):
print("Player One wins, Scissors beats Paper.")
elif (player1 == 3, player2 == 4):
print("Player One wins, Scissors beats Lizard.")
elif (player1 == 4, player2 == 2):
print("Player One wins, Lizard beats Paper.")
elif (player1 == 4, player2 == 5):
print("Player One wins, Lizard beats Spock.")
elif (player1 == 5, player2 == 3):
print("Player One wins, Spock beats Scissors.")
elif (player1 == 5 , player2 == 1):
print("Player One wins, Spock beats Rock.")
#Player 2 wins
elif (player2 == 1, player1 == 3):
print("Player Two wins, Rock beats Scissors.")
elif (player2 == 1, player1 == 4):
print("Player Two wins, Rock beats Lizard.")
elif (player2 == 2, player1 == 1):
print("Player Two wins, Paper beats Rock.")
elif (player2 == 2, player1 == 5):
print("Player Two wins, Paper beats Spock.")
elif (player2 == 3, player1 == 2):
print("Player Two wins, Scissors beats Paper.")
elif (player2 == 3, player1 == 4):
print("Player Two wins, Scissors beats Lizard.")
elif (player2 == 4, player1 == 2):
print("Player Two wins, Lizard beats Paper.")
elif (player2 == 4, player1 == 5):
print("Player Two wins, Lizard beats Spock.")
elif (player2 == 5, player1 == 3):
print("Player Two wins, Spock beats Scissors.")
elif (player2 == 5 , player1 == 1):
print("Player Two wins, Spock beats Rock.")
</code></pre>
| 0 |
2016-09-20T18:00:49Z
| 39,600,861 |
<p>You are not properly constructing your conditions.</p>
<pre><code>elif (player1 == 1, player2 == 3)
</code></pre>
<p>This creates a <code>tuple</code> and then checks it for truthiness, which always succeeds, because that <code>tuple</code> is not empty. You need to use the logical operator <code>and</code>:</p>
<pre><code>elif player1 == 1 and player2 == 3
</code></pre>
<p>This will check whether both of those conditions are true. Do this for all similar instances in your code.</p>
<p>Additionally, it's unclear what you are expecting from the user here:</p>
<pre><code>player1 = input("Player One do you want Rock, Paper, Scissors, Lizard or Spock?")
player2 = input("Player Two do you want Rock, Paper, Scissors, Lizard or Spock?")
print(player1)
print(player2)
rock = 1
paper = 2
scissors = 3
lizard = 4
spock = 5
</code></pre>
<p>It looks like the user is supposed to enter something like <code>Rock</code>, and then you expect the <code>rock = 1</code> line to convert <code>'Rock'</code> to <code>1</code>. It does not work that way. The most basic way to do this is with another <code>if..elif</code> block, but a dictionary would be better:</p>
<pre><code>player1 = input("Player One do you want Rock, Paper, Scissors, Lizard or Spock?")
player2 = input("Player Two do you want Rock, Paper, Scissors, Lizard or Spock?")
print(player1)
print(player2)
d = {'Rock':1, 'Paper':2, 'Scissors':3, 'Lizard':4, 'Spock':5}
player1 = d.get(player1)
player2 = d.get(player2)
</code></pre>
| 6 |
2016-09-20T18:03:07Z
|
[
"python"
] |
Python 3.X Rock Paper Scissors Lizard Spock issue
| 39,600,824 |
<p>Hello i am new to coding but i have been stuck on a code for very long and can't seem to find the answer here on stackoverflow. </p>
<p>Whatever i do the answer ends up with the first print of Player 1 wins: Player One wins, Rock beats Scissors.</p>
<pre><code>player1 = input("Player One do you want Rock, Paper, Scissors, Lizard or Spock?")
player2 = input("Player Two do you want Rock, Paper, Scissors, Lizard or Spock?")
print(player1)
print(player2)
rock = 1
paper = 2
scissors = 3
lizard = 4
spock = 5
#Tie
if (player1 == player2):
print("It's a tie.")
#Player 1 wins
elif (player1 == 1, player2 == 3):
print("Player One wins, Rock beats Scissors.")
elif (player1 == 1, player2 == 4):
print("Player One wins, Rock beats Lizard.")
elif (player1 == 2, player2 == 1):
print("Player One wins, Paper beats Rock.")
elif (player1 == 2, player2 == 5):
print("Player One wins, Paper beats Spock.")
elif (player1 == 3, player2 == 2):
print("Player One wins, Scissors beats Paper.")
elif (player1 == 3, player2 == 4):
print("Player One wins, Scissors beats Lizard.")
elif (player1 == 4, player2 == 2):
print("Player One wins, Lizard beats Paper.")
elif (player1 == 4, player2 == 5):
print("Player One wins, Lizard beats Spock.")
elif (player1 == 5, player2 == 3):
print("Player One wins, Spock beats Scissors.")
elif (player1 == 5 , player2 == 1):
print("Player One wins, Spock beats Rock.")
#Player 2 wins
elif (player2 == 1, player1 == 3):
print("Player Two wins, Rock beats Scissors.")
elif (player2 == 1, player1 == 4):
print("Player Two wins, Rock beats Lizard.")
elif (player2 == 2, player1 == 1):
print("Player Two wins, Paper beats Rock.")
elif (player2 == 2, player1 == 5):
print("Player Two wins, Paper beats Spock.")
elif (player2 == 3, player1 == 2):
print("Player Two wins, Scissors beats Paper.")
elif (player2 == 3, player1 == 4):
print("Player Two wins, Scissors beats Lizard.")
elif (player2 == 4, player1 == 2):
print("Player Two wins, Lizard beats Paper.")
elif (player2 == 4, player1 == 5):
print("Player Two wins, Lizard beats Spock.")
elif (player2 == 5, player1 == 3):
print("Player Two wins, Spock beats Scissors.")
elif (player2 == 5 , player1 == 1):
print("Player Two wins, Spock beats Rock.")
</code></pre>
| 0 |
2016-09-20T18:00:49Z
| 39,600,945 |
<p>While TigerHawk covered your condiction, you also have to cast your inputs to ints.</p>
<pre><code>player1 = int(player1)
player2 = int(player2)
</code></pre>
<p>Right now you are comparing a str (your input) to an int (<code>player == 1</code>). Which won't yield what you want.</p>
<pre><code>player1 == 1 #fails right now since it's like asking "1" == 1 which fails.
int(player1) == 1 # passes since it's asking 1 == 1.
</code></pre>
<p>Also your <code>print("It's a tie.")</code> is indented wrong.</p>
| 0 |
2016-09-20T18:09:08Z
|
[
"python"
] |
Understanding python slicings syntax as described in the python language reference
| 39,600,833 |
<p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
</code></pre>
<p>Per my understanding, this syntax equates to <code>SomeMappingObj[slice_item,slice_item etc...]</code> which again equates to something like <code>a[0:2:1,4:7:1]</code> and <code>a =[i for i in range(20)]</code>. </p>
<p>But, I can't test this in IPython and I did not find any questions about multiple slicings. Is my interpretation about multiple slicing in python correct? What am I doing incorrectly?</p>
<pre><code>In [442]: a=[i for i in range(20)]
In [443]: a[0:12:2]
Out[443]: [0, 2, 4, 6, 8, 10]
In [444]: a[0:12:2,14:17:1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-444-117395d33bfd> in <module>()
----> 1 a[0:12:2,14:17:1]
TypeError: list indices must be integers or slices, not tuple
</code></pre>
| 5 |
2016-09-20T18:01:14Z
| 39,600,891 |
<p>That's valid syntax, so you didn't get a SyntaxError. It's just not a meaningful or supported operation on Python lists. Similarly, <code>"5" + fish</code> isn't a SyntaxError, <code>1/0</code> isn't a SyntaxError, and <code>I.am.a.monkey</code> isn't a SyntaxError.</p>
<p>You can't just expect all syntactically valid expressions to be meaningful.</p>
| 2 |
2016-09-20T18:05:22Z
|
[
"python",
"python-3.x",
"slice"
] |
Understanding python slicings syntax as described in the python language reference
| 39,600,833 |
<p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
</code></pre>
<p>Per my understanding, this syntax equates to <code>SomeMappingObj[slice_item,slice_item etc...]</code> which again equates to something like <code>a[0:2:1,4:7:1]</code> and <code>a =[i for i in range(20)]</code>. </p>
<p>But, I can't test this in IPython and I did not find any questions about multiple slicings. Is my interpretation about multiple slicing in python correct? What am I doing incorrectly?</p>
<pre><code>In [442]: a=[i for i in range(20)]
In [443]: a[0:12:2]
Out[443]: [0, 2, 4, 6, 8, 10]
In [444]: a[0:12:2,14:17:1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-444-117395d33bfd> in <module>()
----> 1 a[0:12:2,14:17:1]
TypeError: list indices must be integers or slices, not tuple
</code></pre>
| 5 |
2016-09-20T18:01:14Z
| 39,600,904 |
<p>A <code>slice_list</code> should contain as many "dimensions" as the object being indexed. The multi-dimensional capability is not used by any Python library object that I am aware of, but you can test it easily with <code>numpy</code>:</p>
<pre><code>import numpy as np
a = np.array([[1, 2], [3, 4]])
a[0:1, 0]
</code></pre>
<p>There are a number of such features in the Python language that are not used directly in the main library. The <code>__matmul__</code> magic method (<code>@</code> operator) is another example.</p>
| 2 |
2016-09-20T18:06:38Z
|
[
"python",
"python-3.x",
"slice"
] |
Understanding python slicings syntax as described in the python language reference
| 39,600,833 |
<p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
</code></pre>
<p>Per my understanding, this syntax equates to <code>SomeMappingObj[slice_item,slice_item etc...]</code> which again equates to something like <code>a[0:2:1,4:7:1]</code> and <code>a =[i for i in range(20)]</code>. </p>
<p>But, I can't test this in IPython and I did not find any questions about multiple slicings. Is my interpretation about multiple slicing in python correct? What am I doing incorrectly?</p>
<pre><code>In [442]: a=[i for i in range(20)]
In [443]: a[0:12:2]
Out[443]: [0, 2, 4, 6, 8, 10]
In [444]: a[0:12:2,14:17:1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-444-117395d33bfd> in <module>()
----> 1 a[0:12:2,14:17:1]
TypeError: list indices must be integers or slices, not tuple
</code></pre>
| 5 |
2016-09-20T18:01:14Z
| 39,601,204 |
<p>This isn't a syntax issue hence no <code>SyntaxError</code>, <em>this syntax is totally supported</em>. <code>list</code>'s just don't know what to do with your slices. Take for example a dummy class that does <em>nothing</em> but define <code>__getitem__</code> that receives the contents of subscriptions <code>[]</code>:</p>
<pre><code>class DummySub:
def __getitem__(self, arg):
print(arg)
f = DummySub()
</code></pre>
<p>It just prints its <code>arg</code>. We can supply slices, as permitted by the grammar, but, <em>it's up to the implementing object to decide if these are an operation</em> that's supported and act on them (like <code>nparray</code>s do) or not (and raise a <code>TypeError</code>):</p>
<pre><code>f[1:2:3, 4:4:4]
(slice(1, 2, 3), slice(4, 4, 4))
</code></pre>
<p>Heck:</p>
<pre><code>f[1:2:3, 4:5:6, 7:8:9, ...] # totally valid
(slice(1, 2, 3), slice(4, 5, 6), slice(7, 8, 9), Ellipsis)
</code></pre>
<p>By reading further on in the <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow"><em>reference for slicings</em></a> you should see that:</p>
<blockquote>
<p>The semantics for a slicing are as follows. The primary is indexed (using the same <code>__getitem__()</code> method as normal subscription) with a key that is constructed from the slice list, as follows. <em>If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items</em>; otherwise, the conversion of the lone slice item is the key. </p>
</blockquote>
<p><sup><em>(emphasis mine)</em></sup></p>
| 1 |
2016-09-20T18:23:43Z
|
[
"python",
"python-3.x",
"slice"
] |
Understanding python slicings syntax as described in the python language reference
| 39,600,833 |
<p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
</code></pre>
<p>Per my understanding, this syntax equates to <code>SomeMappingObj[slice_item,slice_item etc...]</code> which again equates to something like <code>a[0:2:1,4:7:1]</code> and <code>a =[i for i in range(20)]</code>. </p>
<p>But, I can't test this in IPython and I did not find any questions about multiple slicings. Is my interpretation about multiple slicing in python correct? What am I doing incorrectly?</p>
<pre><code>In [442]: a=[i for i in range(20)]
In [443]: a[0:12:2]
Out[443]: [0, 2, 4, 6, 8, 10]
In [444]: a[0:12:2,14:17:1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-444-117395d33bfd> in <module>()
----> 1 a[0:12:2,14:17:1]
TypeError: list indices must be integers or slices, not tuple
</code></pre>
| 5 |
2016-09-20T18:01:14Z
| 39,601,454 |
<p>Note that the grammar is structured this way to allow two things:</p>
<ol>
<li><p>A family of <code>slice</code> literals:</p>
<ol>
<li><code>x:y:z == slice(x, y, z)</code></li>
<li><code>x:y == slice(x, y, None)</code></li>
<li><code>x: == slice(x, None, None)</code></li>
<li><code>x::z == slice(x, None, z)</code></li>
<li><code>::z == slice(None, None, z)</code></li>
<li><code>:y:z == slice(None, y, z)</code></li>
<li><code>:: == slice(None, None, None)</code></li>
<li><code>:y: == slice(None, y, None)</code></li>
</ol>
<p>There are a few other patterns possible (<code>x:y:</code>, <code>:y</code>, etc), but each
is a variation on one of the above.</p></li>
<li><p>Slice literals may <em>only</em> be used inside <code>[...]</code>, not in any arbitrary expression.</p></li>
</ol>
<p>Otherwise, the comma-separate list is treated like any other tuple. When you write an expression like <code>f[1, 2:3, 5::7]</code>, then <code>f.__getitem__</code> receives a tuple <code>(1, slice(2, 3, None), slice(5, None, 7)</code> as its argument. What <code>f.__getitem__</code> <em>does</em> with that argument is entirely up to <code>type(f)</code>'s implementation of <code>__getitem__</code>. For instance, lists and strings only accept <code>int</code> and <code>slice</code> values as arguments, and dicts only accept hashable values.</p>
| 2 |
2016-09-20T18:38:42Z
|
[
"python",
"python-3.x",
"slice"
] |
XML generation Python reading from DB
| 39,601,053 |
<p>I have generate an xml, that take a param value from the model. </p>
<p>The result xml should be like this <code><read><test><value string/></test></read></code></p>
<pre><code>root = etree.Element('read')
node = etree.Element('test')
value = etree.SubElement(node, "value" )
for dict in Listing.objects.values('string'):
value.text = dict['string']
</code></pre>
<p>I get like this :<code><read><test><value>string</value></test></read></code></p>
<p>How should I add the string to the value tag rather than as a TEXT?</p>
| 0 |
2016-09-20T18:15:10Z
| 39,608,219 |
<p>Firstly, as @parfait mentioned, the XML result you want (<code><read><test><value string/></test></read></code>) is not valid XML.</p>
<p>Using the code you provided, the node <code>test</code> doesn't get added to the root node <code>read</code>.</p>
<h1>1. Code to get your current result:</h1>
<p>If you want something like this as the result: <code><read><test><value>string</value></test></read></code> (which you said you don't), then the code for it would be:</p>
<pre><code>>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test') # `node` should be a `SubElement` of root
>>> # or create as `Element` and use `root.append(node)` to make it a `SubElement` later
... value = etree.SubElement(node, 'value')
>>> value.text = 'string' # or populate based on your `Listing.objects`
>>> etree.dump(root)
<read><test><value>string</value></test></read>
</code></pre>
<h1>2. "string" as a value (<em>text</em>) of "test":</h1>
<p>If you want 'string' to be the value of <code>test</code> and not as a <em>node</em> 'value' under 'test', then you should set 'string' as the <code>.text</code> attribute of 'test':</p>
<pre><code>>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test')
>>> node.text = 'string'
>>> etree.dump(root)
<read><test>string</test></read>
</code></pre>
<h1>3. "value" as an <em>attribute</em> of "test" with the <em>value</em> "string":</h1>
<p>The one I <em>think</em> you're trying to get:</p>
<pre><code>>>> root = etree.Element('read')
>>> node = etree.SubElement(root, 'test')
>>> node.attrib # the current attributes of the node, nothing, empty dict
{}
>>> node.attrib['value'] = 'string' # this is how you set an attribute
>>> etree.dump(root)
<read><test value="string" /></read>
</code></pre>
<p>Btw, in XML <em>good-ness</em>, the 2nd option is nicer than the 3rd; but botha/all are valid XML.</p>
| 0 |
2016-09-21T05:30:57Z
|
[
"python",
"xml"
] |
Python file.close() and with() behavior in high frequency loops
| 39,601,070 |
<p>I am working with a Raspberry PI and outputting a value from a sound sensor using a python script. In order to display this, I use an HTML page on my PI that calls a javascript include which is simply a single line that defines a value that will be used to change what the Google gauge displays. All of this is pretty simple and straightforward, and works just fine for my needs. (Added bonus that I actually understand how it works.)</p>
<p>The .js file is written out by my python script which does a bunch of other stuff too. This all actually works exactly as I want it to, and the values that get written to the file are accurate and do appear correctly on the gauge if I run it as a single loop and not in a continuous "monitoring service" mode where it runs until interrupted.</p>
<p>Here's where the issue starts I think: the loop that measures sound levels runs ~ 30k times in 5 seconds. In my python code I use:</p>
<pre><code>with open(web_file, 'w') as f_output:
f_output.write("var int_level = " + str(per_detected))
f_output.close()
</code></pre>
<p>I am doing this because I <em>THINK</em> I need to do the close each time because of the loop (I know the "with" is an implicit close, but because I reopen the file every time it seemed better to close it by force to be sure), <em>BUT</em> I think it also may be the issue. (also I am using mode 'w' on purpose so I can reset the file each time as it is only a single line - seemed faster and less computationally expensive than replacing a value)</p>
<p>The symptom is that the Google gauge HTML page refreshes once every 5 seconds to load the new value, BUT the gauge itself only renders maybe once every 10 refreshes, but this is totally random, obviously indicating that there is no value in the .js file to be returned. I take this to mean it is probably getting lucky once in a few tries and hitting the file before the close, OR is it just too fast and this is a stupid way to do it? </p>
<p>As an additional note, when I cat level.js (<- the include file) from the command line on the PI, after "killing" my python code, it is empty. </p>
<p>I have all the code (including the HTML page) at: </p>
<p><a href="https://www.GitHub.com/ChrisHarrold/Pi-Projects" rel="nofollow">https://www.GitHub.com/ChrisHarrold/Pi-Projects</a> </p>
<p>if you wish to review for greater detail. It is commented 6-ways till Sunday so it should be trivial to figure out what I did and why.</p>
| 2 |
2016-09-20T18:15:56Z
| 39,601,261 |
<p>The <code>.close()</code> is definitely not needed. At issue is your browser reading the file <em>while it is still open anyway</em> and finding it in a truncated (so empty) state from time to time. And you can never close the file fast enough to prevent this.</p>
<p>What you should do instead is write the file to a <em>different</em> filename, then <em>rename</em> the file to replace the old file. This is an atomic operation (meaning the Operating System guarantees that any other access to the file will either get the old, or the new file, but never just a part of both).</p>
<p>This is as simple as:</p>
<pre><code>with open(web_file + '.new', 'w') as f_output:
f_output.write("var int_level = " + str(per_detected))
os.rename(web_file + '.new', web_file)
</code></pre>
<p>The above code writes out to a different filename, one ending in <code>.new</code>, and only when writing has completed (and the file is closed), is it moved into place to replace the old version of the file.</p>
| 5 |
2016-09-20T18:26:33Z
|
[
"javascript",
"python"
] |
Python Tkinter Window not closing
| 39,601,107 |
<p>So I was writing a short code to test something when I noticed this interesting behaviour. </p>
<pre><code>import tkinter
from tkinter import *
master=tkinter.Tk()
master.geometry("800x850+0+0")
master.configure(background="lightblue")
def d():
master.destroy()
button=Button(master, text="asdf", command=d).pack()
master.mainloop()
</code></pre>
<p>The button closes the window as expected, but when I click on the red button on the top left button (from the actual window, not tkinter), the program gets stuck and doesn't respond.
However, when I change the code to remove the text in the button as follows:</p>
<pre><code>import tkinter
from tkinter import *
master=tkinter.Tk()
master.geometry("800x850+0+0")
master.configure(background="lightblue")
def d():
master.destroy()
button=Button(master, command=d).pack()
master.mainloop()
</code></pre>
<p>It now works perfectly fine. Both the tkinter button in the window and the red button from the actual window close the window as expected.
Why does this happen?
I am using python 3.5 on Mac, in case this matters.</p>
| 0 |
2016-09-20T18:18:02Z
| 39,678,316 |
<p>I tried it out on some of my friends computers and they didn't have this issue, so it appears that it was just a hardware specific problem.</p>
| 0 |
2016-09-24T16:05:43Z
|
[
"python",
"tkinter",
"window"
] |
How to access prior rows within a multiindex Panda dataframe
| 39,601,110 |
<p>How to reach within a Datetime indexed multilevel Dataframe such as the following: This is downloaded Fin data.
The tough part is getting inside the frame and accessing non adjacent rows of a particular inner level, without specifying explicitly the outer level date, since I have thousands of such rows..</p>
<pre><code> ABC DEF GHI \
Date STATS
2012-07-19 00:00:00 NaN NaN NaN
investment 4 9 13
price 5 8 1
quantity 12 9 8
</code></pre>
<p>So the 2 formulas i am searching could be summarized as </p>
<pre><code>X(today row) = quantity(prior row)*price(prior row)
or
X(today row) = quantity(prior row)*price(today)
</code></pre>
<p>The difficulty is how to formulate the access to those rows using numpy or panda for a multilevel index, and the rows are not adjacent.</p>
<p>In the end i would end up with this:</p>
<pre><code> ABC DEF GHI XN
Date STATS
2012-07-19 00:00:00 NaN NaN NaN
investment 4 9 13 X1
price 5 8 1
quantity 12 9 8
2012-07-18 00:00:00 NaN NaN NaN
investment 1 2 3 X2
price 2 3 4
quantity 18 6 7
X1= (18*2)+(6*3)+(7*4) (quantity_day_2 *price_day_2 data)
or for the other formula
X1= (18*5)+(6*8)+(7*1) (quantity_day_2 *price_day_1 data)
</code></pre>
<p>Could I use a groupby?</p>
| 1 |
2016-09-20T18:18:09Z
| 39,602,842 |
<p>You can use:</p>
<pre><code>#add new datetime with data for better testing
print (df)
ABC DEF GHI
Date STATS
2012-07-19 NaN NaN NaN
investment 4.0 9.0 13.0
price 5.0 8.0 1.0
quantity 12.0 9.0 8.0
2012-07-18 NaN NaN NaN
investment 1.0 2.0 3.0
price 2.0 3.0 4.0
quantity 18.0 6.0 7.0
2012-07-17 NaN NaN NaN
investment 1.0 2.0 3.0
price 0.0 1.0 4.0
quantity 5.0 1.0 0.0
</code></pre>
<pre><code>#lexsorted Multiindex
df.sort_index(inplace=True)
#select data and remove last level, because:
#1. need shift
#2. easier working
idx = pd.IndexSlice
p = df.loc[idx[:,'price'],:]
p.index = p.index.droplevel(-1)
q = df.loc[idx[:,'quantity'],:]
q.index = q.index.droplevel(-1)
print (p)
ABC DEF GHI
Date
2012-07-17 0.0 1.0 4.0
2012-07-18 2.0 3.0 4.0
2012-07-19 5.0 8.0 1.0
print (q)
ABC DEF GHI
Date
2012-07-17 5.0 1.0 0.0
2012-07-18 18.0 6.0 7.0
2012-07-19 12.0 9.0 8.0
</code></pre>
<pre><code>print (p * q)
ABC DEF GHI
Date
2012-07-17 0.0 1.0 0.0
2012-07-18 36.0 18.0 28.0
2012-07-19 60.0 72.0 8.0
print ((p * q).sum(axis=1).to_frame().rename(columns={0:'col1'}))
col1
Date
2012-07-17 1.0
2012-07-18 82.0
2012-07-19 140.0
</code></pre>
<pre><code>#shift row with -1, because lexsorted df
print (p.shift(-1, freq='D') * q)
ABC DEF GHI
Date
2012-07-16 NaN NaN NaN
2012-07-17 10.0 3.0 0.0
2012-07-18 90.0 48.0 7.0
2012-07-19 NaN NaN NaN
print ((p.shift(-1, freq='D') * q).sum(axis=1).to_frame().rename(columns={0:'col2'}))
col2
Date
2012-07-16 0.0
2012-07-17 13.0
2012-07-18 145.0
2012-07-19 0.0
</code></pre>
| 1 |
2016-09-20T20:01:53Z
|
[
"python",
"pandas",
"indexing",
"dataframe",
"multi-index"
] |
How to access prior rows within a multiindex Panda dataframe
| 39,601,110 |
<p>How to reach within a Datetime indexed multilevel Dataframe such as the following: This is downloaded Fin data.
The tough part is getting inside the frame and accessing non adjacent rows of a particular inner level, without specifying explicitly the outer level date, since I have thousands of such rows..</p>
<pre><code> ABC DEF GHI \
Date STATS
2012-07-19 00:00:00 NaN NaN NaN
investment 4 9 13
price 5 8 1
quantity 12 9 8
</code></pre>
<p>So the 2 formulas i am searching could be summarized as </p>
<pre><code>X(today row) = quantity(prior row)*price(prior row)
or
X(today row) = quantity(prior row)*price(today)
</code></pre>
<p>The difficulty is how to formulate the access to those rows using numpy or panda for a multilevel index, and the rows are not adjacent.</p>
<p>In the end i would end up with this:</p>
<pre><code> ABC DEF GHI XN
Date STATS
2012-07-19 00:00:00 NaN NaN NaN
investment 4 9 13 X1
price 5 8 1
quantity 12 9 8
2012-07-18 00:00:00 NaN NaN NaN
investment 1 2 3 X2
price 2 3 4
quantity 18 6 7
X1= (18*2)+(6*3)+(7*4) (quantity_day_2 *price_day_2 data)
or for the other formula
X1= (18*5)+(6*8)+(7*1) (quantity_day_2 *price_day_1 data)
</code></pre>
<p>Could I use a groupby?</p>
| 1 |
2016-09-20T18:18:09Z
| 39,603,487 |
<p>If need add output to original <code>DataFrame</code>, then it is more complicated:</p>
<pre><code>print (df)
ABC DEF GHI
Date STATS
2012-07-19 NaN NaN NaN
investment 4.0 9.0 13.0
price 5.0 8.0 1.0
quantity 12.0 9.0 8.0
2012-07-18 NaN NaN NaN
investment 1.0 2.0 3.0
price 2.0 3.0 4.0
quantity 18.0 6.0 7.0
2012-07-17 NaN NaN NaN
investment 1.0 2.0 3.0
price 0.0 1.0 4.0
quantity 5.0 1.0 0.0
</code></pre>
<pre><code>df.sort_index(inplace=True)
#rename value in level to investment - align data in final concat
idx = pd.IndexSlice
p = df.loc[idx[:,'price'],:].rename(index={'price':'investment'})
q = df.loc[idx[:,'quantity'],:].rename(index={'quantity':'investment'})
print (p)
ABC DEF GHI
Date STATS
2012-07-17 investment 0.0 1.0 4.0
2012-07-18 investment 2.0 3.0 4.0
2012-07-19 investment 5.0 8.0 1.0
print (q)
ABC DEF GHI
Date STATS
2012-07-17 investment 5.0 1.0 0.0
2012-07-18 investment 18.0 6.0 7.0
2012-07-19 investment 12.0 9.0 8.0
#multiple and concat to original df
print (p * q)
ABC DEF GHI
Date STATS
2012-07-17 investment 0.0 1.0 0.0
2012-07-18 investment 36.0 18.0 28.0
2012-07-19 investment 60.0 72.0 8.0
</code></pre>
<pre><code>a = (p * q).sum(axis=1).rename('col1')
print (pd.concat([df, a], axis=1))
ABC DEF GHI col1
Date STATS
2012-07-17 NaN NaN NaN NaN
investment 1.0 2.0 3.0 1.0
price 0.0 1.0 4.0 NaN
quantity 5.0 1.0 0.0 NaN
2012-07-18 NaN NaN NaN NaN
investment 1.0 2.0 3.0 82.0
price 2.0 3.0 4.0 NaN
quantity 18.0 6.0 7.0 NaN
2012-07-19 NaN NaN NaN NaN
investment 4.0 9.0 13.0 140.0
price 5.0 8.0 1.0 NaN
quantity 12.0 9.0 8.0 NaN
</code></pre>
<pre><code>#shift with Multiindex - not supported yet - first create Datatimeindex with unstack
#, then shift and last reshape to original by stack
#multiple and concat to original df
print (p.unstack().shift(-1, freq='D').stack() * q)
ABC DEF GHI
Date STATS
2012-07-16 investment NaN NaN NaN
2012-07-17 investment 10.0 3.0 0.0
2012-07-18 investment 90.0 48.0 7.0
2012-07-19 investment NaN NaN NaN
b = (p.unstack().shift(-1, freq='D').stack() * q).sum(axis=1).rename('col2')
print (pd.concat([df, b], axis=1))
ABC DEF GHI col2
Date STATS
2012-07-16 investment NaN NaN NaN 0.0
2012-07-17 NaN NaN NaN NaN
investment 1.0 2.0 3.0 13.0
price 0.0 1.0 4.0 NaN
quantity 5.0 1.0 0.0 NaN
2012-07-18 NaN NaN NaN NaN
investment 1.0 2.0 3.0 145.0
price 2.0 3.0 4.0 NaN
quantity 18.0 6.0 7.0 NaN
2012-07-19 NaN NaN NaN NaN
investment 4.0 9.0 13.0 0.0
price 5.0 8.0 1.0 NaN
quantity 12.0 9.0 8.0 NaN
</code></pre>
| 1 |
2016-09-20T20:49:42Z
|
[
"python",
"pandas",
"indexing",
"dataframe",
"multi-index"
] |
Extracting Fasta Moonlight Protein Sequences with Python
| 39,601,114 |
<p>I want to extract the FASTA files that have the aminoacid sequence from the Moonlighting Protein Database ( www.moonlightingproteins.org/results.php?search_text= ) via Python, since it's an iterative process, which I'd rather learn how to program than manually do it, b/c come on, we're in 2016. The problem is I don´t know how to write the code, because I'm a rookie programmer :( . The basic pseudocode would be: </p>
<pre><code> for protein_name in site: www.moonlightingproteins.org/results.php?search_text=:
go to the uniprot option
download the fasta file
store it in a .txt file inside a given folder
</code></pre>
<p>Thanks in advance! </p>
| 0 |
2016-09-20T18:18:27Z
| 39,603,854 |
<p>I would strongly suggest to ask the authors for the database. From the <a href="http://www.moonlightingproteins.org/faqs.php" rel="nofollow">FAQ</a>:</p>
<blockquote>
<p>I would like to use the MoonProt database in a project to analyze the
amino acid sequences or structures using bioinformatics. </p>
<p>Please contact us at bioinformatics@moonlightingproteins.org if you are
interested in using MoonProt database for analysis of sequences and/or
structures of moonlighting proteins.</p>
</blockquote>
<p>Assuming you find something interesting, how are you going to cite it in your paper or your thesis?
"The sequences were scraped from a public webpage without the consent of the authors". Much better to give credit to the original researchers.</p>
<p>That's a good introduction to <a href="http://docs.python-guide.org/en/latest/scenarios/scrape/" rel="nofollow">scraping</a></p>
<p>But back to your your original question.</p>
<pre><code>import requests
from lxml import html
#let's download one protein at a time, change 3 to any other number
page = requests.get('http://www.moonlightingproteins.org/detail.php?id=3')
#convert the html document to something we can parse in Python
tree = html.fromstring(page.content)
#get all table cells
cells = tree.xpath('//td')
for i, cell in enumerate(cells):
if cell.text:
#if we get something which looks like a FASTA sequence, print it
if cell.text.startswith('>'):
print(cell.text)
#if we find a table cell which has UniProt in it
#let's print the link from the next cell
if 'UniProt' in cell.text_content():
if cells[i + 1].find('a') is not None and 'href' in cells[i + 1].find('a').attrib:
print(cells[i + 1].find('a').attrib['href'])
</code></pre>
| 0 |
2016-09-20T21:17:04Z
|
[
"python",
"database",
"data-mining",
"bioinformatics",
"protein-database"
] |
Tornado's reverse_url to a fully qualified URL
| 39,601,123 |
<p>Tornado's <code>reverse_url</code> is not a fully qualified URL. Is there a mechanism in Tornado to get back a fully qualified URL? For instance:</p>
<pre><code>>>> some_method('foo', 1234)
http://localhost:8080/foo/1234
</code></pre>
| 1 |
2016-09-20T18:19:17Z
| 39,612,115 |
<p>This is a small helper method which I add to all my handlers:</p>
<pre><code>from urllib.parse import urljoin # urlparse in Python 2
class BaseHandler(tornado.web.RequestHandler):
def reverse_full_url(self, name, *args, **kwargs):
host_url = "{protocol}://{host}".format(**vars(self.request))
return urljoin(host_url, self.reverse_url(name, *args, *kwargs))
</code></pre>
| 1 |
2016-09-21T09:07:14Z
|
[
"python",
"tornado"
] |
Transposing a subset of columns in a Pandas DataFrame while using others as grouping variable?
| 39,601,126 |
<p>Let's say I have a Pandas dataframe (that is already in the dataframe format):</p>
<pre><code>x = [[1,2,8,7,9],[1,3,5.6,4.5,4],[2,3,4.5,5,5]]
df = pd.DataFrame(x, columns=['id1','id2','val1','val2','val3'])
id1 id2 val1 val2 val3
1 2 8.0 7.0 9
1 3 5.6 4.5 4
2 3 4.5 5.0 5
</code></pre>
<p>I want <code>val1</code>, <code>val2</code>, and <code>val2</code> in one column, with <code>id1</code> and <code>id2</code> as grouping variables. I can use this <strong>extremely</strong> convoluted code:</p>
<pre><code>dfT = df.iloc[:,2::].T.reset_index(drop=True)
n_points = dfT.shape[0]
final = pd.DataFrame()
for i in range(0, df.shape[0]):
data = np.asarray([[df.ix[i,'id1']]*n_points,
[df.ix[i,'id2']]*n_points,
dfT.ix[:,i].values]).T
temp = pd.DataFrame(data, columns=['id1','id2','val'])
final = pd.concat([final, temp], axis=0)
</code></pre>
<p>to get my dataframe into the correct format:</p>
<pre><code> id1 id2 val
0 1.0 2.0 8.0
1 1.0 2.0 7.0
2 1.0 2.0 9.0
0 1.0 3.0 5.6
1 1.0 3.0 4.5
2 1.0 3.0 4.0
0 2.0 3.0 4.5
1 2.0 3.0 5.0
2 2.0 3.0 5.0
</code></pre>
<p>but there must be a more efficient way of doing this, since on a large dataframe this takes way too long.</p>
<p>Suggestions?</p>
| 2 |
2016-09-20T18:19:24Z
| 39,601,213 |
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> column <code>variable</code>:</p>
<pre><code>print (pd.melt(df, id_vars=['id1','id2'], value_name='val')
.drop('variable', axis=1))
id1 id2 val
0 1 2 8.0
1 1 3 5.6
2 2 3 4.5
3 1 2 7.0
4 1 3 4.5
5 2 3 5.0
6 1 2 9.0
7 1 3 4.0
8 2 3 5.0
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p>
<pre><code>print (df.set_index(['id1','id2'])
.stack()
.reset_index(level=2, drop=True)
.reset_index(name='val'))
id1 id2 val
0 1 2 8.0
1 1 2 7.0
2 1 2 9.0
3 1 3 5.6
4 1 3 4.5
5 1 3 4.0
6 2 3 4.5
7 2 3 5.0
8 2 3 5.0
</code></pre>
| 2 |
2016-09-20T18:24:02Z
|
[
"python",
"performance",
"pandas",
"optimization",
"dataframe"
] |
Transposing a subset of columns in a Pandas DataFrame while using others as grouping variable?
| 39,601,126 |
<p>Let's say I have a Pandas dataframe (that is already in the dataframe format):</p>
<pre><code>x = [[1,2,8,7,9],[1,3,5.6,4.5,4],[2,3,4.5,5,5]]
df = pd.DataFrame(x, columns=['id1','id2','val1','val2','val3'])
id1 id2 val1 val2 val3
1 2 8.0 7.0 9
1 3 5.6 4.5 4
2 3 4.5 5.0 5
</code></pre>
<p>I want <code>val1</code>, <code>val2</code>, and <code>val2</code> in one column, with <code>id1</code> and <code>id2</code> as grouping variables. I can use this <strong>extremely</strong> convoluted code:</p>
<pre><code>dfT = df.iloc[:,2::].T.reset_index(drop=True)
n_points = dfT.shape[0]
final = pd.DataFrame()
for i in range(0, df.shape[0]):
data = np.asarray([[df.ix[i,'id1']]*n_points,
[df.ix[i,'id2']]*n_points,
dfT.ix[:,i].values]).T
temp = pd.DataFrame(data, columns=['id1','id2','val'])
final = pd.concat([final, temp], axis=0)
</code></pre>
<p>to get my dataframe into the correct format:</p>
<pre><code> id1 id2 val
0 1.0 2.0 8.0
1 1.0 2.0 7.0
2 1.0 2.0 9.0
0 1.0 3.0 5.6
1 1.0 3.0 4.5
2 1.0 3.0 4.0
0 2.0 3.0 4.5
1 2.0 3.0 5.0
2 2.0 3.0 5.0
</code></pre>
<p>but there must be a more efficient way of doing this, since on a large dataframe this takes way too long.</p>
<p>Suggestions?</p>
| 2 |
2016-09-20T18:19:24Z
| 39,601,545 |
<p>There's even a simpler one which can be done using <a href="https://github.com/pydata/pandas/blob/master/pandas/core/reshape.py#L804" rel="nofollow"><code>lreshape</code></a>(Not yet documented though):</p>
<pre><code>pd.lreshape(df, {'val': ['val1', 'val2', 'val3']}).sort_values(['id1', 'id2'])
</code></pre>
<p><a href="http://i.stack.imgur.com/UAHVp.png" rel="nofollow"><img src="http://i.stack.imgur.com/UAHVp.png" alt="Image"></a></p>
| 3 |
2016-09-20T18:43:11Z
|
[
"python",
"performance",
"pandas",
"optimization",
"dataframe"
] |
Why does PyCharm want to install itself in AppData\Roaming on Windows 7? Can I just put it in Program Files?
| 39,601,151 |
<p>Does anybody have any idea why PyCharm wants to install in the following directory:</p>
<pre><code>C:\Users\Lenovo\AppData\Roaming\JetBrains\PyCharm 2016.2.3
</code></pre>
<p><a href="http://i.stack.imgur.com/jy0sy.png" rel="nofollow"><img src="http://i.stack.imgur.com/jy0sy.png" alt="enter image description here"></a></p>
<p>I'm used to installers picking Program Files or Program Files (x86) or in the case of Anaconda just making its own directory on the C: drive. Is it cool if I go ahead and install it in Program Files or Program Files (x86)? There doesn't seem to be anything on the website about any of this. Normally I'd just figure this one out trial and error but I know IDEs are super finicky about things so I'm asking the pros.</p>
<p>I'm running Windows 7 Professional in case that makes any difference. </p>
| 0 |
2016-09-20T18:20:43Z
| 39,601,368 |
<p>I just restarted the installer and it automatically decided to install into the Program Files (x86) directory. Weird.</p>
| 0 |
2016-09-20T18:33:25Z
|
[
"python",
"windows",
"pycharm",
"windows-7-x64"
] |
Python get a value from numpy.ndarray by [index]
| 39,601,165 |
<pre><code>import numpy as np
ze=np.zeros(3)
print(ze[0]) # -> 0
</code></pre>
<p>I am pretty new to Python (3.5.2)</p>
<p>I learned 'list' in python and to show the i th element in list1</p>
<pre><code>print (list1[i])
</code></pre>
<p>but, even 'np.zeros(3)' is ndarray, a class in NumPy,
it can be used as the 'list' like above.</p>
<p>What is happening on that?</p>
<p>I am pretty new but I have worked on Java..so I hope the issues can be understood...</p>
<p>I guess this question is too early for one who just learned range() and not known how to define functions(methods?)..</p>
<p>But please let me know how to achieve the access by operator [].</p>
<p>Maybe it will be usefull, when I really start to Python.</p>
| 0 |
2016-09-20T18:21:31Z
| 39,601,403 |
<p>If you want to implement a class that can return a value using the [] operator. Then implement the <code>__getitem__(self, key)</code> function in the class, see <a href="https://docs.python.org/2/reference/datamodel.html#emulating-container-types" rel="nofollow">https://docs.python.org/2/reference/datamodel.html#emulating-container-types</a>.</p>
| 1 |
2016-09-20T18:35:59Z
|
[
"python",
"numpy"
] |
Why do I get ValueError in one piece of code but not the other although they are identical?
| 39,601,169 |
<p>I've been solving Project Euler problems and here is my code for <a href="https://projecteuler.net/problem=35" rel="nofollow">problem 35</a>:</p>
<pre><code>def sieve_of_Erathosthenes():
sieve = [True] * 10**6
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = False
for x in xrange(2, int(len(sieve) ** 0.5) + 1):
if sieve[x]:
mark(sieve, x)
return list(str(i) for i in range(2, len(sieve)) if sieve[i])
def is_prime(n):
from math import sqrt
if all(n % i != 0 for i in xrange(2,int(sqrt(n))+1)):
return True
def is_circular_prime(p):
if all(is_prime(int(p[i:] + p[:i])) for i in xrange(len(p))):
return True
primes = sieve_of_Erathosthenes()
number_of_circular_primes = 0
for i in primes:
if is_circular_prime(i):
number_of_circular_primes += 1
print number_of_circular_primes
</code></pre>
<p>It works just as I intended and outputs the correct solution. I used a similar approach to solve <a href="https://projecteuler.net/problem=37" rel="nofollow">problem 37</a> but I get: " ValueError: invalid literal for int() with base 10: ''. " I tried everything and it still didin't work. Here is my code:</p>
<pre><code>def sieve_of_Erathosthenes():
sieve = [True] * 10**5
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = False
for x in xrange(2, int(len(sieve) ** 0.5) + 1):
if sieve[x]:
mark(sieve, x)
return [str(i) for i in range(2, len(sieve)) if sieve[i] and i > 10]
def is_prime(n):
from math import sqrt
if all(n % i != 0 for i in xrange(2,int(sqrt(n))+1)):
return True
def is_trunctable_from_the_right(n):
if all(is_prime(int(n[:i])) for i in range(len(n)-1)):
return True
def is_trunctable_from_the_left(n):
if all(is_prime(int(n[i:])) for i in range(1,len(n))):
return True
primes = sieve_of_Erathosthenes()
trunctable_from_both_sides = 0
for i in primes:
if is_trunctable_from_the_left(str(i)) and is_trunctable_from_the_right(str(i)):
trunctable_from_both_sides += int(i)
print trunctable_from_both_sides
</code></pre>
<p>As you can see most of the code here is just copied and pasted from the previous problem. Why doesn't it work this time? How do I fix this?</p>
| -1 |
2016-09-20T18:21:41Z
| 39,601,717 |
<p>You don't mention the line on which you get the error. That would have helped. Also you know much of the code works. So just focus on the bit which is different: the truncations. </p>
<p>I suspect the error is in this <code>int(n[:i])</code></p>
<p>The range starts from 0, so the first term is a zero length string</p>
<pre><code>ValueError: invalid literal for int() with base 10: ''
</code></pre>
<p>The invalid literal string is the empty string, It can't convert that to a number. So fix the range statement:</p>
<pre><code>(isprime(int(n[:i])) for i in range(1,len(n)))
</code></pre>
| 1 |
2016-09-20T18:52:12Z
|
[
"python"
] |
Why do I get ValueError in one piece of code but not the other although they are identical?
| 39,601,169 |
<p>I've been solving Project Euler problems and here is my code for <a href="https://projecteuler.net/problem=35" rel="nofollow">problem 35</a>:</p>
<pre><code>def sieve_of_Erathosthenes():
sieve = [True] * 10**6
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = False
for x in xrange(2, int(len(sieve) ** 0.5) + 1):
if sieve[x]:
mark(sieve, x)
return list(str(i) for i in range(2, len(sieve)) if sieve[i])
def is_prime(n):
from math import sqrt
if all(n % i != 0 for i in xrange(2,int(sqrt(n))+1)):
return True
def is_circular_prime(p):
if all(is_prime(int(p[i:] + p[:i])) for i in xrange(len(p))):
return True
primes = sieve_of_Erathosthenes()
number_of_circular_primes = 0
for i in primes:
if is_circular_prime(i):
number_of_circular_primes += 1
print number_of_circular_primes
</code></pre>
<p>It works just as I intended and outputs the correct solution. I used a similar approach to solve <a href="https://projecteuler.net/problem=37" rel="nofollow">problem 37</a> but I get: " ValueError: invalid literal for int() with base 10: ''. " I tried everything and it still didin't work. Here is my code:</p>
<pre><code>def sieve_of_Erathosthenes():
sieve = [True] * 10**5
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = False
for x in xrange(2, int(len(sieve) ** 0.5) + 1):
if sieve[x]:
mark(sieve, x)
return [str(i) for i in range(2, len(sieve)) if sieve[i] and i > 10]
def is_prime(n):
from math import sqrt
if all(n % i != 0 for i in xrange(2,int(sqrt(n))+1)):
return True
def is_trunctable_from_the_right(n):
if all(is_prime(int(n[:i])) for i in range(len(n)-1)):
return True
def is_trunctable_from_the_left(n):
if all(is_prime(int(n[i:])) for i in range(1,len(n))):
return True
primes = sieve_of_Erathosthenes()
trunctable_from_both_sides = 0
for i in primes:
if is_trunctable_from_the_left(str(i)) and is_trunctable_from_the_right(str(i)):
trunctable_from_both_sides += int(i)
print trunctable_from_both_sides
</code></pre>
<p>As you can see most of the code here is just copied and pasted from the previous problem. Why doesn't it work this time? How do I fix this?</p>
| -1 |
2016-09-20T18:21:41Z
| 39,601,722 |
<p>If I run your code, you'll notice the error happens when <code>i</code> is 11:</p>
<pre><code>>>> primes = sieve_of_Erathosthenes()
>>>
>>> trunctable_from_both_sides = 0
>>> for i in primes:
... if is_trunctable_from_the_left(str(i)) and is_trunctable_from_the_right(str(i)):
... trunctable_from_both_sides += int(i)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in is_trunctable_from_the_right
File "<stdin>", line 2, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> i
'11'
>>>
</code></pre>
<p>So, digging into the Traceback, we see you end up with a situation like this in <code>is_trunctable_from_the_right</code>:</p>
<pre><code>>>> for x in range(len(n)-1):
... print n[:i]
...
>>> n
'11'
>>> range(len(n)-1)
[0]
</code></pre>
<p>So you are returning an empty string when you truncate your string, passing that empty string to <code>int</code>, which is throwing the error.</p>
| 1 |
2016-09-20T18:52:33Z
|
[
"python"
] |
string index out of range error in for loop
| 39,601,218 |
<p>I am trying to make a program that searches a string for 'bob' and prints the amount of times it appears.
Here is the code:</p>
<pre><code>s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s) ) :
u = s[i]
if u == 'o':
g = i
if g != 0 and g != len(s) :
if (s[g+1]) == 'b' and (s[g-1]) == 'b': #this line is the problam
numbob += 1
print("Number of times bob occurs is: " +str(numbob) )
</code></pre>
<p>I am getting the string index out of range error and i cant seem to fix it. any suggestions</p>
| -1 |
2016-09-20T18:24:20Z
| 39,601,335 |
<p>Use </p>
<pre><code>for i in range(len(s)-1)
</code></pre>
<p>or</p>
<pre><code>g!=len(s)-1
</code></pre>
<p><code>len()</code> gives you the total number of characters, which will be the index of the character after the last one since indexing starts at 0.</p>
<p>You can get rid of the <code>if g!=0 and g!=len(s)</code> part all together if you use </p>
<pre><code>for i in range(1,len(s)-1)
</code></pre>
| 1 |
2016-09-20T18:31:06Z
|
[
"python",
"python-3.x"
] |
string index out of range error in for loop
| 39,601,218 |
<p>I am trying to make a program that searches a string for 'bob' and prints the amount of times it appears.
Here is the code:</p>
<pre><code>s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s) ) :
u = s[i]
if u == 'o':
g = i
if g != 0 and g != len(s) :
if (s[g+1]) == 'b' and (s[g-1]) == 'b': #this line is the problam
numbob += 1
print("Number of times bob occurs is: " +str(numbob) )
</code></pre>
<p>I am getting the string index out of range error and i cant seem to fix it. any suggestions</p>
| -1 |
2016-09-20T18:24:20Z
| 39,601,339 |
<p>When you make your condition :</p>
<pre><code>if (s[g+1]) == 'b' and (s[g-1]) == 'b':
</code></pre>
<p>At the last element of your string, it is impossible to do <code>s[g+1]</code> because it is out of the string.</p>
<p>So you have to finish your loop just before the end. Like this for exemple :</p>
<pre><code>for i in range(len(s)-1) :
</code></pre>
| 0 |
2016-09-20T18:31:24Z
|
[
"python",
"python-3.x"
] |
Python error when calling column data from Pandas DataFrame
| 39,601,251 |
<p>I was practicing to import stock market data from Google Finance into a Pandas DataFrame:</p>
<pre><code>import pandas as pd
from pandas import Series
path = 'http://www.google.com/finance/historical?cid=542029859096076&startdate=Sep+22%2C+2001&enddate=Sep+20%2C+2016&num=30&ei=3HvhV4n3D8XGmAGp4q74Ag&output=csv'
df = pd.read_csv(path)
</code></pre>
<p>So far so good, and df also shows the complete data set I need.</p>
<p>However, when calling particular columns, like</p>
<pre><code>df['Date']
</code></pre>
<p>Python shows the error codes below:</p>
<pre><code>Traceback (most recent call last):
File "<ipython-input-31-cb486dd31fbc>", line 1, in <module>
df['Date']
File "/Users/Username/anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line 1997, in __getitem__
return self._getitem_column(key)
File "/Users/Username/anaconda/lib/python3.5/site-packages/pandas/core/frame.py", line 2004, in _getitem_column
return self._get_item_cache(key)
File "/Users/Username/anaconda/lib/python3.5/site-packages/pandas/core/generic.py", line 1350, in _get_item_cache
values = self._data.get(item)
File "/Users/Username/anaconda/lib/python3.5/site-packages/pandas/core/internals.py", line 3290, in get
loc = self.items.get_loc(item)
File "/Users/Username/anaconda/lib/python3.5/site-packages/pandas/indexes/base.py", line 1947, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)
File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)
File "pandas/hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12368)
File "pandas/hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12322)
KeyError: 'Date'
</code></pre>
<p>On the other hand, other columns such as df['High'] turns out to be okay. Is there anyway I can fix this issue?</p>
| 2 |
2016-09-20T18:26:14Z
| 39,601,325 |
<p>this CSV file contains <a href="http://stackoverflow.com/questions/17912307/u-ufeff-in-python-string">BOM (Byte Order Mark) signature</a>, so try it this way:</p>
<pre><code>df = pd.read_csv(path, encoding='utf-8-sig')
</code></pre>
<p>How one can easily identify this problem (thanks to <a href="http://stackoverflow.com/questions/39601251/python-error-when-calling-column-data-from-pandas-dataframe?noredirect=1#comment66511340_39601325">@jezrael's hint</a>):</p>
<pre><code>In [11]: print(df.columns.tolist())
['\ufeffDate', 'Open', 'High', 'Low', 'Close', 'Volume']
</code></pre>
<p>and pay attention at the first column</p>
<p><strong>NOTE:</strong> as <a href="http://stackoverflow.com/questions/39601251/python-error-when-calling-column-data-from-pandas-dataframe/39601325#comment66511256_39601251">@ayhan</a> has noticed, starting with version 0.19.0 <a href="https://pandas-docs.github.io/pandas-docs-travis/whatsnew.html" rel="nofollow">Pandas will take care of it automatically</a>:</p>
<p>Bug in pd.read_csv() which caused BOM files to be incorrectly parsed by not ignoring the BOM <a href="https://github.com/pydata/pandas/issues/4793" rel="nofollow">GH4793</a></p>
| 4 |
2016-09-20T18:30:20Z
|
[
"python",
"pandas",
"dataframe"
] |
Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
| 39,601,272 |
<p>I'm getting an error when trying to access edit link in django, i have looked here on stack overflow but i haven't found the solution that works in my case.</p>
<p>ERROR :
Exception Type : NoReverseMatch
Exception Value : Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] arguments '{}' not found. 0 pattern(s) tried: []</p>
<p>this is my urls.py</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
from posts import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^create/$', views.create, name='create'),
url(r'^(?P<id>\d+)/$', views.show_post, name = 'show_post'),
url(r'^(?P<id>\d+)/edit/$', views.update_post, name = 'update_post'),
url(r'^(?P<id>\d+)/delete/$', views.delete_post),
]
</code></pre>
<p>views.py</p>
<pre class="lang-py prettyprint-override"><code>from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .forms import PostForm
from .models import Post
# Create your views here.
def index(request):
post_list = Post.objects.order_by('-created_date')[:10]
context = {'post_list': post_list}
return render(request, 'index.html', context)
def create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
#flass messages
messages.success(request, "Successfully created")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form":form,
}
return render(request, 'post_form.html', context)
def show_post(request, id=None):
instance = get_object_or_404(Post, id=id)
context = {'instance': instance}
return render(request, 'show_post.html', context)
def update_post(request, id=None):
instance = get_object_or_404(Post, id=id)
form = PostForm(request.POST or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request, "Post updated")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form":form,
"instance":instance
}
return render(request, 'post_form.html', context)
def delete_post(request, id=None):
instance = get_object_or_404(Post, id=id)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("posts:index")
</code></pre>
<p>show_post.html</p>
<pre><code>{% extends "base.html" %}
<div class="container">
{% block content %}
<h1> {{instance.title}} </h1>
<h3>{{instance.content| linebreaks}} </h3>
<a href="{% url 'posts:index' %}"> Home</a> | <a href="{{instance.url}}" target="_blank" > visit url</a> |
<a href="{% url 'posts:update_post' %}"> Edit</a>
{% endblock %}
</div>
</code></pre>
| 0 |
2016-09-20T18:27:05Z
| 39,601,591 |
<p>You need to use the namespace. Rather than <code>'edit'</code>, you should use <code>'posts:edit'</code>.</p>
<p>Or <code>'posts:update_post'</code> depending which name you're using in urls.py.</p>
| 1 |
2016-09-20T18:45:51Z
|
[
"python",
"django",
"django-models",
"django-templates",
"django-views"
] |
How to find largest number in file and see on which line it is
| 39,601,278 |
<p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 |
2016-09-20T18:27:31Z
| 39,601,428 |
<p>So you are just looking to find the biggest number in the first column of the file? This should help</p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
max = 0
for line in b.readlines():
num = int(line.split(",")[0])
if (max < num):
max = num
print(max)
# Close file
b.close()
</code></pre>
| 0 |
2016-09-20T18:37:20Z
|
[
"python"
] |
How to find largest number in file and see on which line it is
| 39,601,278 |
<p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 |
2016-09-20T18:27:31Z
| 39,601,515 |
<ul>
<li>Read line </li>
<li>Split it on basis of comma</li>
<li>Append first element to temp list.</li>
</ul>
<p>Once complete reading of file is done,</p>
<ul>
<li>To get maximum number, just use <code>max</code> function on temp list.</li>
<li>Since file is read line by line sequentially and appending number from line to temp list, to get line number on which maximum number is present, just find the index of max number in temp list and increment it by one since list index starts with zero.</li>
</ul>
<p><strong>P.S :</strong> Check last three print statements</p>
<p><strong>Code:</strong></p>
<pre><code>num_list = []
with open('master.csv','r')as fh:
for line in fh.readlines():
num_list.append(int((line.split(','))[0]))
print num_list
print "Max number is -" ,max(num_list)
print "Line number is - ", (num_list.index(max(num_list)))+1
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
[1, 2, 3]
Max number is - 3
Line number is - 3
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 0 |
2016-09-20T18:42:02Z
|
[
"python"
] |
How to find largest number in file and see on which line it is
| 39,601,278 |
<p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 |
2016-09-20T18:27:31Z
| 39,601,540 |
<p>Iterate through the file and keep track of the highest number you've seen and the line you found it on. Just replace this with the new number and new line number when you see a bigger one.</p>
<pre><code>b = open('file.txt', 'r')
max = -1
lineNum = -1
line = b.readline()
index = 0
while(line):
index+=1
newNum = line[0]
if(newNum>max):
max = newNum
lineNum = index
line = b.readline()
print lineNum,max,index
</code></pre>
<p>max is your highest number, lineNum is where it was, and index is the number of lines in the file</p>
| -1 |
2016-09-20T18:42:54Z
|
[
"python"
] |
How to find largest number in file and see on which line it is
| 39,601,278 |
<p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 |
2016-09-20T18:27:31Z
| 39,601,556 |
<p>This is how I'd go about doing it.</p>
<pre><code>max_num = 0
with open('file.txt', 'r') as data: # use the with context so that the file closes gracefully
for line in data.readlines(): # read the lines as a generator to be nice to my memory
try:
val = int(line.split(",")[0])
except ValueError: # just incase the text file is not formatted like your example
val = 0
if val > max_num: # logic
max_num = val
print max_num #result
</code></pre>
| 0 |
2016-09-20T18:43:55Z
|
[
"python"
] |
How to find largest number in file and see on which line it is
| 39,601,278 |
<p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 |
2016-09-20T18:27:31Z
| 39,601,613 |
<p>You need loop over each line in file, parse each line and find the largest number.</p>
<p>I do not quite understand how the numbers are stored in your file. Just assuming that in each line, the first field are numeric and separate with others (non-numeric) by <code>','</code>. And I assume all numbers are integer.</p>
<pre><code>ln = 0
maxln = 0
maxn = 0
with open(filename, 'r') as f:
line = f.next()
if line:
ln = 1
maxln = 1
maxn = int(line.split(",")[0].strip())
else:
raise Exception('Empty content')
for line in f:
ln += 1
cur = int(line.split(",")[0].strip())
if cur > maxn:
maxn = cur
maxln = ln
</code></pre>
<p>ln is used to record current line number, maxn is used to record current maximum number, and maxln is used to record current maximum number location.</p>
<p>One thing you need to do is fetch the first line to initialize these variables.</p>
| 0 |
2016-09-20T18:47:05Z
|
[
"python"
] |
How to find largest number in file and see on which line it is
| 39,601,278 |
<p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 |
2016-09-20T18:27:31Z
| 39,601,708 |
<p>None of the answers give you the line of the max number so I'll post some quick code and refine later</p>
<pre><code>max_num = 0
line_count = 0
with open('file.txt', 'r') as infile:
for line in infile:
number = int(line.split(',')[0])
if number > max_num:
max_num = number
line_num = line_count
line_count += 1
print (max_num)
print (line_num)
</code></pre>
| 0 |
2016-09-20T18:51:41Z
|
[
"python"
] |
Scrapy. First response requires Selenium
| 39,601,298 |
<p>I'm scraping a website that strongly depends on Javascript. The main page from which I need to extract the urls that will be parsed depends on Javascript, so I have to modify start_requests.
I'm looking for a way to connect start_requests, with the linkextractor and with process_match</p>
<pre><code>class MatchSpider(CrawlSpider):
name = "match"
allowed_domains = ["whoscored"]
rules = (
Rule(LinkExtractor(restrict_xpaths='//*[contains(@class, "match-report")]//@href'), callback='parse_item'),
)
def start_requests(self):
url = 'https://www.whoscored.com/Regions/252/Tournaments/2/Seasons/6335/Stages/13796/Fixtures/England-Premier-League-2016-2017'
browser = Browser(browser='Chrome')
browser.get(url)
# should return a request with the html body from Selenium driver so that LinkExtractor rule can be applied
def process_match(self, response):
match_item = MatchItem()
regex = re.compile("matchCentreData = \{.*?\};", re.S)
match = re.search(regex, response.text).group()
match = match.replace('matchCentreData =', '').replace(';', '')
match_item['match'] = json.loads(match)
match_item['url'] = response.url
match_item['project'] = self.settings.get('BOT_NAME')
match_item['spider'] = self.name
match_item['server'] = socket.gethostname()
match_item['date'] = datetime.datetime.now()
yield match_item
</code></pre>
<p>A wrapper I'm using around Selenium:</p>
<pre><code>class Browser:
"""
selenium on steroids. allows you to create different types of browsers plus
adds methods for safer calls
"""
def __init__(self, browser='Firefox'):
"""
type: silent or not
browser: chrome of firefox
"""
self.browser = browser
self._start()
def _start(self):
'''
starts browser
'''
if self.browser == 'Chrome':
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_extension('./libcommon/adblockpluschrome-1.10.0.1526.crx')
chrome_options.add_experimental_option("prefs", prefs)
chrome_options.add_argument("user-agent={0}".format(random.choice(USER_AGENTS)))
self.driver_ = webdriver.Chrome(executable_path='./libcommon/chromedriver', chrome_options=chrome_options)
elif self.browser == 'Firefox':
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", random.choice(USER_AGENTS))
profile.add_extension('./libcommon/adblock_plus-2.7.1-sm+tb+an+fx.xpi')
profile.set_preference('permissions.default.image', 2)
profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
profile.set_preference("webdriver.load.strategy", "unstable")
self.driver_ = webdriver.Firefox(profile)
elif self.browser == 'PhantomJS':
self.driver_ = webdriver.PhantomJS()
self.driver_.set_window_size(1120, 550)
def close(self):
self.driver_.close()
def return_when(self, condition, locator):
"""
returns browser execution when condition is met
"""
for _ in range(5):
with suppress(Exception):
wait = WebDriverWait(self.driver_, timeout=100, poll_frequency=0.1)
wait.until(condition(locator))
self.driver_.execute_script("return window.stop")
return True
return False
def __getattr__(self, name):
"""
ruby-like method missing: derive methods not implemented to attribute that
holds selenium browser
"""
def _missing(*args, **kwargs):
return getattr(self.driver_, name)(*args, **kwargs)
return _missing
</code></pre>
| 0 |
2016-09-20T18:28:36Z
| 39,602,405 |
<p>There's two problems I see after looking into this. Forgive any ignorance on my part, because it's been a while since I was last in the Python/Scrapy world.</p>
<hr>
<p><strong>First:</strong> <strong><em>How do we get the HTML from Selenium?</em></strong></p>
<p>According to the <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.page_source" rel="nofollow">Selenium docs</a>, the driver should have a <code>page_source</code> attribute containing the contents of the page.</p>
<pre><code>browser = Browser(browser='Chrome')
browser.get(url)
html = browser.driver_.page_source
browser.close()
</code></pre>
<p>You may want to make this a function in your browser class to avoid accessing <code>browser.driver_</code> from <code>MatchSpider</code>.</p>
<pre><code># class Browser
def page_source(self):
return self.driver_.page_source
# end class
browser.get(url)
html = browser.page_source()
</code></pre>
<hr>
<p><strong>Second:</strong> <strong><em>How do we override Scrapy's internal web requests?</em></strong></p>
<p>It looks like Scrapy tries to decouple the behind-the-scenes web requests from the what-am-I-trying-to-parse functionality of each spider you write. <code>start_requests()</code> should <em>"return an iterable with the first Requests to crawl"</em> and <code>make_requests_from_url(url)</code> (which is called if you don't override <code>start_requests()</code>) takes <em>"a URL and returns a <code>Request</code> object"</em>. When internally processing a <code>Spider</code>, Scrapy starts creating a plethora of <code>Request</code> objects that will be asynchronously executed and the subsequent <code>Response</code> will be sent to <code>parse(response)</code>...the <code>Spider</code> never actually does the processing from <code>Request</code> to `Response.</p>
<p>Long story short, this means you would need to <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#downloader-middleware" rel="nofollow">create middleware for the Scrapy Downloader</a> to use Selenium. Then, you can remove your overridden <code>start_requests()</code> method and add a <code>start_urls</code> attribute. Specifically, your SeleniumDownloaderMiddleware should overwrite the <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#scrapy.downloadermiddlewares.DownloaderMiddleware.process_request" rel="nofollow"><code>process_request(request, spider)</code></a> method to use the above Selenium code.</p>
| 1 |
2016-09-20T19:32:33Z
|
[
"python",
"selenium",
"scrapy"
] |
Scrapy SgmlLinkExtractor how to define XPath
| 39,601,361 |
<p>I want to retreive the cityname and citycode and store it in one string variable. The image shows the precise location:</p>
<p><a href="http://i.stack.imgur.com/PmMcq.png" rel="nofollow"><img src="http://i.stack.imgur.com/PmMcq.png" alt="enter image description here"></a></p>
<p>Google Chrome gave me the following XPath:</p>
<pre><code>//*[@id="page"]/main/div[4]/div[2]/div[1]/div/div/div[1]/div[2]/div/div[1]/div/a[1]/span
</code></pre>
<p>So I defined the following statement in scrapy to get the desired information: </p>
<pre><code>plz = response.xpath('//*[@id="page"]/main/div[4]/div[2]/div[1]/div/div/div[1]/div[2]/div/div[1]/div/a[1]/span/text()').extract()
</code></pre>
<p>However I was not successful, the string remains empty. What XPath definition should I use instead?</p>
| 0 |
2016-09-20T18:32:51Z
| 39,601,633 |
<p>Most of the time this occurs, this is because browsers correct invalid HTML. How do you fix this? Inspect the (raw) HTML source and write your own XPath that navigate the DOM with the shortest/simplest query.</p>
<p>I scrape a lot of data off of the web and I've never used an XPath as specific as the one you got from the browser. This is for a few reasons:</p>
<ol>
<li>It will fail quickly on invalid HTML or the most basic of hierarchy changes.</li>
<li>It contains no identifying data for debugging an issue when the website changes.</li>
<li>It's way longer than it should be.</li>
</ol>
<p>Here's an <strong><em>example</em></strong> (there are a lot of different XPath queries you could write to find this data, I'd suggest you learning and re-writing this query so there are common themes for XPath queries throughout your project) query for grabbing that element:</p>
<pre><code>//div[contains(@class, "detail-address")]//h2/following-sibling::span
</code></pre>
<hr>
<p>The other main source of this problem is sites that extensively rely on JS to modify what is shown on the screen. Conveniently, though, this would be debugged the same was as above. As soon as you glance at the HTML returned on page load, you would notice that the data you are querying doesn't exist until JS executes. At that point, you would need to do some sort of <a href="https://en.wikipedia.org/wiki/Headless_browser" rel="nofollow">headless browsing</a>.</p>
<hr>
<p>Since my answer was essentially "write your own XPath" (rather than relying on the browser), I'll leave some sources:</p>
<ul>
<li><a href="http://archive.oreilly.com/pub/a/perl/excerpts/system-admin-with-perl/ten-minute-xpath-utorial.html" rel="nofollow">basic XPath introduction</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/XPath/Functions" rel="nofollow">list of XPath functions</a></li>
<li><a href="https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl?hl=en" rel="nofollow">XPath Chrome extension</a></li>
</ul>
| 1 |
2016-09-20T18:47:47Z
|
[
"python",
"regex",
"xpath",
"scrapy"
] |
Scrapy SgmlLinkExtractor how to define XPath
| 39,601,361 |
<p>I want to retreive the cityname and citycode and store it in one string variable. The image shows the precise location:</p>
<p><a href="http://i.stack.imgur.com/PmMcq.png" rel="nofollow"><img src="http://i.stack.imgur.com/PmMcq.png" alt="enter image description here"></a></p>
<p>Google Chrome gave me the following XPath:</p>
<pre><code>//*[@id="page"]/main/div[4]/div[2]/div[1]/div/div/div[1]/div[2]/div/div[1]/div/a[1]/span
</code></pre>
<p>So I defined the following statement in scrapy to get the desired information: </p>
<pre><code>plz = response.xpath('//*[@id="page"]/main/div[4]/div[2]/div[1]/div/div/div[1]/div[2]/div/div[1]/div/a[1]/span/text()').extract()
</code></pre>
<p>However I was not successful, the string remains empty. What XPath definition should I use instead?</p>
| 0 |
2016-09-20T18:32:51Z
| 39,602,061 |
<p>The DOM is manipulated by javascript, so what chrome shows is the xpath after
the all the stuff has happened.</p>
<p>If all you want is to get the cities, you can get it this way (using scrapy):</p>
<pre><code>city_text = response.css('.detail-address span::text').extract_first()
city_code, city_name = city_text.split(maxsplit=1)
</code></pre>
<p>Or you can manipulate the JSON in CDATA to get all the data you need:</p>
<pre><code>cdata_text = response.xpath('//*[@id="tdakv"]/text()').extract_first()
json_str = cdata_text.splitlines()[2]
json_str = json_str[json_str.find('{'):]
data = json.loads(json_str) # import json
city_code = data['kvzip']
city_name = data['kvplace']
</code></pre>
| 1 |
2016-09-20T19:11:49Z
|
[
"python",
"regex",
"xpath",
"scrapy"
] |
Python openCV find image in folder of images(road sign recognition)
| 39,601,465 |
<p>I'm doing road sign recognition program. I've successfuly done with image preprocesing. I have extracted image of road sign. </p>
<p>Now I don't know what algorithem or template matching should I use to find matching image of my extracted image.</p>
<p>Solution must be simple and effective, because I'm still learning Python.</p>
<p>1.image: extracted image 2. image: matched image</p>
<p><a href="http://i.stack.imgur.com/yTi1N.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/yTi1N.jpg" alt="Extracted image"></a><a href="http://i.stack.imgur.com/lkOqT.png" rel="nofollow"><img src="http://i.stack.imgur.com/lkOqT.png" alt="That image sould find algorithm in folder of images"></a></p>
| 0 |
2016-09-20T18:39:29Z
| 39,602,564 |
<p>Template matching doesn't work in your case. Template matching works only with nearly the same template in your source.
I propose to use <code>dlib</code>
<a href="http://dlib.net/ml.html" rel="nofollow">http://dlib.net/ml.html</a> for deep learning.
It's easy to learn and you don't need write a lot of code. If you still want to use template matching you could try following:</p>
<pre><code>import cv2
source = cv2.imread("/source/of/your_stop_sign")
template = cv2.imread("our/template")
(tempH, tempW) = template.shape[:2]
</code></pre>
<p>try to find the template:</p>
<pre><code>result = cv2.matchTemplate(source, template, cv2.TM_CCOEFF)
(minVal, maxVal, minLoc, (x, y)) = cv2.minMaxLoc(result)
</code></pre>
<p>draw the bounding box</p>
<pre><code>cv2.rectangle(source, (x, y), (x + tempW, y + tempH), (0, 255, 0), 2)
</code></pre>
<p>show the result</p>
<pre><code>cv2.imshow("source", source)
cv2.imshow("template", template)
cv2.waitKey(0)
</code></pre>
<p><img src="http://i.stack.imgur.com/uU4dI.jpg" alt="Template">
<img src="http://i.stack.imgur.com/AWeF4.jpg" alt="Source">
<img src="http://i.stack.imgur.com/BfFPJ.png" alt="Result"></p>
| 0 |
2016-09-20T19:44:13Z
|
[
"python",
"algorithm",
"opencv",
"template-matching"
] |
Error in scipy odeint use for system of ODE's
| 39,601,483 |
<p>I am trying to reproduce the two graphs shown below, which are temperature and concentration profiles as a function of time. I have checked my method and code a million times but cannot seem to find an error in it but I cannot reproduce those graphs. All values are constants except CA and T. Could it be an issue with the accuracy of odeint from scipy? Any help would be much appreciated! </p>
<p>The two equations are as follows:</p>
<p>dCA/dt = q*(CAi - CA)/V - k*CA</p>
<p>dT/dt = w*(Ti - T)/(V<em>p) + d_HR</em>k<em>CA/(p</em>C) + UA*(Tc - T)/(V<em>p</em>C)</p>
<p>The code is: </p>
<pre><code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def ODESolve(y, t, q, CAi, V, k0, w, Ti, p, dH_R, C, UA, Tc):
CA, T = y
k = k0*np.exp(8750*1/T)
dydt = [q*(CAi - CA)/V - k*CA, w*(Ti - T)/(V*p) + \
dH_R*k*CA/(p*C) + UA*(Tc - T)/(V*p*C)]
return dydt
q = 100
CAi = 1.0
V = 100
p = 1000
C = .239
dH_R = 5*(10**4)
k0 = 7.2*(10**10)
UA = 5*10**4
CA0 = .5
T0 = 350
Ti = T0
w = p*q
y0 = [CA0, T0]
t = np.linspace(0, 20, 100)
Tc = 305
sol1 = odeint(ODESolve, y0, t, args = (q, CAi, V, k0, w, Ti, p, dH_R, C, UA, Tc))
Tc = 300
sol2 = odeint(ODESolve, y0, t, args = (q, CAi, V, k0, w, Ti, p, dH_R, C, UA, Tc))
Tc = 290
sol3 = odeint(ODESolve, y0, t, args = (q, CAi, V, k0, w, Ti, p, dH_R, C, UA, Tc))
plt.figure(1)
plt.plot(t, sol1[:,0], label = 'Tc = 305')
plt.plot(t, sol2[:,0], label = 'Tc = 300')
plt.plot(t, sol3[:,0], label = 'Tc = 290')
plt.ylim(ymax = 1, ymin = 0)
plt.title ('CA(t)')
plt.legend(loc = 'best')
plt.figure(2)
plt.plot(t, sol1[:,1], label = 'Tc = 305')
plt.plot(t, sol2[:,1], label = 'Tc = 300')
plt.plot(t, sol3[:,1], label = 'Tc = 290')
plt.ylim(ymax = 450, ymin = 300)
plt.legend(loc = 'best')
plt.title ('T(t)')
plt.show()
</code></pre>
<p>Here is what the graphs are supposed to produce: </p>
<p><a href="http://i.stack.imgur.com/XDrLp.png" rel="nofollow"><img src="http://i.stack.imgur.com/XDrLp.png" alt="enter image description here"></a></p>
<p>And here is the output of my code above:</p>
<p><a href="http://i.stack.imgur.com/nq6uS.png" rel="nofollow"><img src="http://i.stack.imgur.com/nq6uS.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/924MS.png" rel="nofollow"><img src="http://i.stack.imgur.com/924MS.png" alt="enter image description here"></a></p>
| 0 |
2016-09-20T18:40:39Z
| 39,602,463 |
<p>Apparently there is a sign error in the formula <code>k = k0*np.exp(8750*1/T)</code>. If you change that to <code>k = k0*np.exp(-8750*1/T)</code>, you'll get plots like those you expect.</p>
| 1 |
2016-09-20T19:36:27Z
|
[
"python",
"scipy",
"ode",
"odeint"
] |
Twitter Search API query results don't match keyword
| 39,601,524 |
<p>I'm using Tweepy Cursor to find some tweets.</p>
<pre><code>for tweet in tweepy.Cursor(api.search, q='pg&e', count=100, lang='en', since=sinceDate, until=untilDate).items():
print str(tweet.created_at) + '\t' + str(tweet.text)
</code></pre>
<p>I have noticed that the tweet.text for many of the tweets returned mention "pg", as in the movie ranking, but don't contain my query, "pg&e" at all. </p>
<p>Why is this? Is there a way to get an exact match? Also, is there a way to give tweepy.Cursor a list of keywords to search for?</p>
<p>Thanks!</p>
| 0 |
2016-09-20T18:42:26Z
| 39,603,057 |
<p><code>q="\"pg&e\""</code> will give you what you want. I guess the <code>&</code> is interpreted as an AND by the API, so you have to specify that you want to search for pure text by putting extra quotation marks.</p>
<p>If you want to search for more keywords, using OR in your query should work, provided the query does not get rejected for being too complex. Something like <code>q="\"pg&e\" OR other_keyword OR \"exact expression to search\""</code> should do the trick.</p>
| 1 |
2016-09-20T20:16:45Z
|
[
"python",
"api",
"search",
"twitter",
"tweepy"
] |
Retrieving tail text from html
| 39,601,578 |
<p>Python 2.7 using lxml</p>
<p>I have some annoyingly formed html that looks like this:</p>
<pre><code><td>
<b>"John"
</b>
<br>
"123 Main st.
"
<br>
"New York
"
<b>
"Sally"
</b>
<br>
"101 California St.
"
<br>
"San Francisco
"
</td>
</code></pre>
<p>So basically it's a single td with a ton of stuff in it. I'm trying to compile a list or dict of the names and their addresses.</p>
<p>So far what I've done is gotten a list of nodes with names using <code>tree.xpath('//td/b')</code>. So let's assume I'm currently on the <code>b</code> node for John. </p>
<p>I'm trying to get <code>whatever.xpath('string()')</code> for everything following the current node but preceding the next <code>b</code> node (Sally). I've tried a bunch of different xpath queries but can't seem to get this right. In particular, any time I use an <code>and</code> operator in an expression that has no <code>[]</code> brackets, it returns a bool rather than a list of all nodes meeting the conditions. Can anyone help out?</p>
| 0 |
2016-09-20T18:45:01Z
| 39,602,352 |
<p>What not use getchildren function from view of each td. For example:</p>
<pre><code>from lxml import html
s = """
<td>
<b>"John"
</b>
<br>
"123 Main st.
"
<br>
"New York
"
<b>
"Sally"
</b>
<br>
"101 California St.
"
<br>
"San Francisco
"
</td>
"""
records = []
cur_record = -1
cur_field = 1
FIELD_NAME = 0
FIELD_STREET = 1
FIELD_CITY = 2
doc = html.fromstring(s)
td = doc.xpath('//td')[0]
for child in td.getchildren():
if child.tag == 'b':
cur_record += 1
record = dict()
record['name'] = child.text.strip()
records.append(record)
cur_field = 1
elif child.tag == 'br':
if cur_field == FIELD_STREET:
records[cur_record]['street'] = child.tail.strip()
cur_field += 1
elif cur_field == FIELD_CITY:
records[cur_record]['city'] = child.tail.strip()
</code></pre>
<p>And the results are:</p>
<pre><code>records = [
{'city': '"New York\n"', 'name': '"John"\n', 'street': '"123 Main st.\n"'},
{'city': '"San Francisco\n"', 'name': '\n"Sally"\n', 'street': '"101 California St.\n"'}
]
</code></pre>
<p>Note you should use <code>tag.tail</code> if you want to get text of some non-close html tag, e.g., <code><br></code>.</p>
<p>Hope this would be helpful.</p>
| 0 |
2016-09-20T19:29:35Z
|
[
"python",
"xpath",
"lxml"
] |
Retrieving tail text from html
| 39,601,578 |
<p>Python 2.7 using lxml</p>
<p>I have some annoyingly formed html that looks like this:</p>
<pre><code><td>
<b>"John"
</b>
<br>
"123 Main st.
"
<br>
"New York
"
<b>
"Sally"
</b>
<br>
"101 California St.
"
<br>
"San Francisco
"
</td>
</code></pre>
<p>So basically it's a single td with a ton of stuff in it. I'm trying to compile a list or dict of the names and their addresses.</p>
<p>So far what I've done is gotten a list of nodes with names using <code>tree.xpath('//td/b')</code>. So let's assume I'm currently on the <code>b</code> node for John. </p>
<p>I'm trying to get <code>whatever.xpath('string()')</code> for everything following the current node but preceding the next <code>b</code> node (Sally). I've tried a bunch of different xpath queries but can't seem to get this right. In particular, any time I use an <code>and</code> operator in an expression that has no <code>[]</code> brackets, it returns a bool rather than a list of all nodes meeting the conditions. Can anyone help out?</p>
| 0 |
2016-09-20T18:45:01Z
| 39,602,410 |
<p>This should work:</p>
<pre><code>from lxml import etree
p = etree.HTMLParser()
html = open(r'./test.html','r')
data = html.read()
tree = etree.fromstring(data, p)
my_dict = {}
for b in tree.iter('b'):
br = b.getnext().tail.replace('\n', '')
my_dict[b.text.replace('\n', '')] = br
print my_dict
</code></pre>
<p>This code prints:</p>
<pre><code>{'"John"': '"123 Main st."', '"Sally"': '"101 California St."'}
</code></pre>
<p>(You may want to strip the quotation marks out!)</p>
<p>Rather than using xpath, you could use one of lxml's parsers in order to easily navigate the HTML. The parser will turn the HTML document into an "etree", which you can navigate with provided methods. The lxml module provides a method called <code>iter()</code> which allows you to pass in a tag name and receive all elements in the tree with that name. In your case, if you use this to obtain all of the <code><b></code> elements, you can then manually navigate to the <code><br></code> element and retrieve its tail text, which contains the information you need. You can find information about this in the "Elements contain text" header of the <a href="http://lxml.de/tutorial.html" rel="nofollow">lxml.etree tutorial.</a></p>
| 1 |
2016-09-20T19:32:52Z
|
[
"python",
"xpath",
"lxml"
] |
Numpy - generating a sequence with a higher resolution within certain bounds
| 39,601,601 |
<p>Generating a sequence of a range with evenly spaced points using Numpy is accomplished easily using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow"><code>np.linspace(a, c, n)</code></a> where <code>a</code> is the start of the range, <code>c</code> is the endpoint of the range and <code>n</code> are the number of evenly spaced intervals.</p>
<p>I am interested to know if there is any similar function which allows a finer resolution for a subset of the range e.g. <code>[a,b]</code> where <code>a<b<c</code>. At the moment i am using:</p>
<p><code>np.append(np.linspace(a, b, n), np.linspace(b, c, n))</code></p>
<p>which does the trick but is there a Numpy implementation already specifically for this or perhaps a smarter way to do this?</p>
| 2 |
2016-09-20T18:46:17Z
| 39,604,183 |
<p>You could construct such a sequence by first making an array containing the spacings between each pair of points, then taking a cumsum over this.</p>
<p>For example, let's suppose I want to go from 0 to 50 everywhere in steps of 1, except between 20 and 30 where I want steps of 0.25:</p>
<pre><code>import numpy as np
deltas = np.repeat([0, 1, 0.25, 1], [1, 20, 40, 20])
pts = np.cumsum(deltas)
</code></pre>
<p>Plotting:</p>
<pre><code>from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.eventplot(pts)
ax.margins(x=0.05)
</code></pre>
<p><a href="http://i.stack.imgur.com/IBINi.png" rel="nofollow"><img src="http://i.stack.imgur.com/IBINi.png" alt="enter image description here"></a></p>
<hr>
<h3>Edit</h3>
<p>I'd totally forgotten about <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html" rel="nofollow"><code>np.r_</code></a>, which offers a very nice compact way to achieve the same thing:</p>
<pre><code>pts2 = np.r_[0:20:1, 20:30:0.25, 30:51:1]
</code></pre>
<p>As well as specifying a step size manually, you can also use an imaginary number as the step size, which is equivalent to using <code>np.linspace</code> to specifying the number of steps to take, e.g. <code>np.r_[0:10:20j]</code> is the same as <code>np.linspace(0, 10, 20)</code>.</p>
| 3 |
2016-09-20T21:41:43Z
|
[
"python",
"numpy"
] |
Print variable in Shell command
| 39,601,614 |
<p>I want to extract the text field from a json objcet of a tweet and run it through syntaxnet. I am doing it all in Python.</p>
<p>My code is:</p>
<pre><code>import os, sys
import subprocess
import json
def parse(text):
os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/data_analysis/syntaxnet/models/syntaxnet")
#synnet_output = subprocess.check_output()
subprocess.call(["echo 'hello world' | syntaxet/demo.sh"], shell = True)
#print synnet_output
for line in sys.stdin:
line1 = json.loads(line)
text = line1['avl_lexicon_text']
print text
synnet_output = parse(text)
</code></pre>
<p>Now, instead of <code>echo 'hello world'</code> in <code>parse</code> function, I want to echo <code>text</code> there. That is I want to feed the <code>text</code> variable to <code>syntaxnet/demo.sh</code> file. I tried doing <code>subprocess.call(["echo text | syntaxet/demo.sh"], shell = True)</code> but that did not work. How can I do that?</p>
| 1 |
2016-09-20T18:47:07Z
| 39,601,755 |
<p>You can just use string formatter <code>%s</code> and substitute the text </p>
<pre><code>def parse(text):
os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/data_analysis/syntaxnet/models/syntaxnet")
#synnet_output = subprocess.check_output()
subprocess.call(["echo '%s' | syntaxet/demo.sh"%text], shell = True)
#print synnet_output
</code></pre>
<p>If you suspect that your text may have single quotes, then you can escape it:</p>
<pre><code>text = text.replace("'", "\\'")
</code></pre>
| 0 |
2016-09-20T18:54:16Z
|
[
"python",
"shell",
"arguments",
"subprocess"
] |
math.acos math domain error within the range of acos
| 39,601,642 |
<p>I've got a script that runs through a set of coordinates for triangles and determines whether or not they're a right triangle. Part of this uses the cosine rule, and I've come across a problem when checking a certain set of points that happen to fall in a line. Here's the part that is causing problems:</p>
<pre><code>s1 = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
s2 = math.sqrt(((x3-x2)**2)+((y3-y2)**2))
s3 = math.sqrt(((x3-x1)**2)+((y3-y1)**2))
num1 = (s1**2)+(s2**2)-(s3**2)
den1 = (2)*(s1)*(s2)
theta1 = math.acos(num1/den1)
num2 = (s1**2)+(s3**2)-(s2**2)
den2 = (2)*(s1)*(s3)
theta2 = math.acos(num2/den2)
num3 = (s3**2)+(s2**2)-(s1**2)
den3 = (2)*(s3)*(s2)
theta3 = math.acos(num3/den3)
</code></pre>
<p>When I run this through with the three points ([0,0],[4,4],[1,1]), I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "./i091.py", line 79, in <module>
detect_right_triangle(xy1, xy2, xy3)
File "./i091.py", line 50, in detect_right_triangle
theta2 = math.acos(num2/den2)
ValueError: math domain error
</code></pre>
<p>Just to be sure that I wasn't going outside of the bounds of the cosine function, I had it print the numerator and denominator of theta2 for all of the assessed points, and got this leading up to the point in question:</p>
<pre><code>***** [[0, 0], [4, 2], [1, 1]]
>>> num2 = 12.0
>>> den2 = 12.6491106407
***** [[0, 0], [4, 3], [1, 1]]
>>> num2 = 14.0
>>> den2 = 14.1421356237
***** [[0, 0], [4, 4], [1, 1]]
>>> num2 = 16.0
>>> den2 = 16.0
</code></pre>
<p>I would've thought that there was a problem with dividing two numbers that were the same for whatever reason (16.0), but it worked fine on [2,2] and [3,3] for the second point:</p>
<pre><code>***** [[0, 0], [2, 2], [1, 1]]
>>> num2 = 8.0
>>> den2 = 8.0
</code></pre>
<p>...</p>
<pre><code>***** [[0, 0], [3, 3], [1, 1]]
>>> num2 = 12.0
>>> den2 = 12.0
</code></pre>
<p>Any thoughts on what might be going wrong here?</p>
| 0 |
2016-09-20T18:48:24Z
| 39,601,925 |
<p>When I run your code:</p>
<pre><code>import math
def foo(x, y):
x1, x2, x3 = x
y1, y2, y3 = y
s1 = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
s2 = math.sqrt(((x3-x2)**2)+((y3-y2)**2))
s3 = math.sqrt(((x3-x1)**2)+((y3-y1)**2))
num1 = (s1**2)+(s2**2)-(s3**2)
den1 = (2)*(s1)*(s2)
theta1 = math.acos(num1/den1)
num2 = (s1**2)+(s3**2)-(s2**2)
den2 = (2)*(s1)*(s3)
print repr(num2), repr(den2)
print repr(num2 / den2)
theta2 = math.acos(num2/den2)
num3 = (s3**2)+(s2**2)-(s1**2)
den3 = (2)*(s3)*(s2)
theta3 = math.acos(num3/den3)
foo([0, 4, 1], [0, 4, 1])
</code></pre>
<p>I get that <code>num2/den2 == 1.0000000000000004</code>. Unless you print out the full precision, you might not notice that <code>num2</code> is <em>slightly</em> bigger than <code>den2</code> which results in a value slightly bigger than one. Obviously, since the maximum of cosine is 1, then you can't take the arcos of a number <em>larger</em> than 1.</p>
| 1 |
2016-09-20T19:02:51Z
|
[
"python",
"math",
"cosine"
] |
Extract values between square brackets ignoring single quotes
| 39,601,759 |
<p>I am trying the following:</p>
<pre><code>s = "Text text text [123] ['text']"
</code></pre>
<p>This is my function:</p>
<pre><code>def getFromSquareBrackets(s):
m = re.findall(r"\[([A-Za-z0-9_']+)\]", s)
return m
</code></pre>
<p>But I am obtaining:</p>
<pre><code>['123', "'text'"]
</code></pre>
<p>I want to obtain:</p>
<pre><code>['123', 'text']
</code></pre>
<p>How can I ignore the single quotes?</p>
| 1 |
2016-09-20T18:54:26Z
| 39,601,804 |
<p>Make <code>'</code> optional and outside the capturing group</p>
<pre><code>m = re.findall(r"\['?([A-Za-z0-9_]+)'?\]", s)
</code></pre>
| 2 |
2016-09-20T18:56:45Z
|
[
"python",
"regex"
] |
Extract values between square brackets ignoring single quotes
| 39,601,759 |
<p>I am trying the following:</p>
<pre><code>s = "Text text text [123] ['text']"
</code></pre>
<p>This is my function:</p>
<pre><code>def getFromSquareBrackets(s):
m = re.findall(r"\[([A-Za-z0-9_']+)\]", s)
return m
</code></pre>
<p>But I am obtaining:</p>
<pre><code>['123', "'text'"]
</code></pre>
<p>I want to obtain:</p>
<pre><code>['123', 'text']
</code></pre>
<p>How can I ignore the single quotes?</p>
| 1 |
2016-09-20T18:54:26Z
| 39,601,821 |
<p>You can make <code>'</code> optional using <code>?</code> as</p>
<pre><code>>>> re.findall(r"\['?([^'\]]+)'?\]", s)
['123', 'text']
</code></pre>
<hr>
<ul>
<li><p><code>\['?</code> Matches <code>[</code> or <code>['</code>.</p></li>
<li><p><code>([^'\]]+)</code> Matches anything other than <code>'</code> or <code>]</code> and captures them.</p></li>
<li><p><code>'?\]</code> Matches <code>]</code> or <code>']</code></p></li>
</ul>
| 2 |
2016-09-20T18:57:25Z
|
[
"python",
"regex"
] |
How can I optimize the intersections between lists with two elements and generate a list of lists without duplicates in python?
| 39,601,823 |
<p>I need help with my loop. In my script I have two huge lists (~87.000 integers each) taken from an input file. </p>
<p>Check this example with a few numbers:</p>
<p>We have two lists:</p>
<p><code>nga = [1, 3, 5, 34, 12]</code></p>
<p><code>ngb = [3, 4, 6, 6, 5]</code></p>
<p>The order of these two lists matters because each position is related with the same position in the other list, so <code>1</code> in <code>nga</code> is related with <code>3</code> in <code>ngb</code>, <code>3</code> with <code>4</code>, etc...</p>
<p>So what I want is this output:</p>
<p><code>listoflists = [[1, 3, 4], [5, 6, 12, 34]]</code></p>
<p>What I have so far is this loop:</p>
<pre><code>listoflists = []
for p in range(0, len(nga)):
z = [nga[p], ngb[p]]
for a, b in zip(nga, ngb):
if a in z:
z.append(b)
else:
pass
if b in z:
z.append(a)
else:
pass
listoflists.append(z)
</code></pre>
<p>The problem appears when I used the whole lists, because it crashed and give me a Segmentation fault error. So, what can I do? </p>
<p>Thanks in advance.</p>
| 0 |
2016-09-20T18:57:36Z
| 40,137,246 |
<p>I solved my problem with this beautiful function:</p>
<pre><code>net = []
for a, b in zip(nga, ngb):
net.append([a, b])
def nets_super_gen(net):
not_con = list(net)
netn = list(not_con[0])
not_con.remove(not_con[0])
new_net = []
while len(netn) != len(new_net):
new_net = list(netn)
for z in net:
if z[0] in netn and z[1] not in netn:
netn.append(z[1])
not_con.remove(z)
elif z[0] not in netn and z[1] in netn:
netn.append(z[0])
not_con.remove(z)
try:
if z[0] in netn and z[1] in netn:
not_con.remove(z)
except ValueError:
pass
return(netn, not_con)
list_of_lists, not_con = nets_super_gen(net)
</code></pre>
| 0 |
2016-10-19T16:47:48Z
|
[
"python",
"list",
"optimization",
"intersection"
] |
pandas: slice dataframe based on NaN
| 39,601,854 |
<p>I have following dataframe <code>df</code></p>
<pre><code>prod_id prod_ref
10 ef3920
12 bovjhd
NaN lkbljb
NaN jknnkn
30 kbknkn
</code></pre>
<p>I am trying the following:</p>
<pre><code>df[df['prod_id'] != np.nan]
</code></pre>
<p>but I get exactly the same dataframe.</p>
<p>I would like to display</p>
<pre><code>prod_id prod_ref
10 ef3920
12 bovjhd
30 kbknkn
</code></pre>
<p>What am I doing wrong?</p>
| 1 |
2016-09-20T18:58:58Z
| 39,601,872 |
<p>Use function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a> or inverting <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a>:</p>
<pre><code>print (df[df.prod_id.notnull()])
prod_id prod_ref
0 10.0 ef3920
1 12.0 bovjhd
4 30.0 kbknkn
print (df[~df.prod_id.isnull()])
prod_id prod_ref
0 10.0 ef3920
1 12.0 bovjhd
4 30.0 kbknkn
</code></pre>
<p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a>, but need specify column for check <code>NaN</code>:</p>
<pre><code>print (df.dropna(subset=['prod_id']))
prod_id prod_ref
0 10.0 ef3920
1 12.0 bovjhd
4 30.0 kbknkn
</code></pre>
<p>If in another columns are not <code>NaN</code> values, use <a href="http://stackoverflow.com/a/39601897/2901002">Alberto Garcia-Raboso's solution</a>.</p>
| 3 |
2016-09-20T18:59:59Z
|
[
"python",
"python-2.7",
"pandas"
] |
pandas: slice dataframe based on NaN
| 39,601,854 |
<p>I have following dataframe <code>df</code></p>
<pre><code>prod_id prod_ref
10 ef3920
12 bovjhd
NaN lkbljb
NaN jknnkn
30 kbknkn
</code></pre>
<p>I am trying the following:</p>
<pre><code>df[df['prod_id'] != np.nan]
</code></pre>
<p>but I get exactly the same dataframe.</p>
<p>I would like to display</p>
<pre><code>prod_id prod_ref
10 ef3920
12 bovjhd
30 kbknkn
</code></pre>
<p>What am I doing wrong?</p>
| 1 |
2016-09-20T18:58:58Z
| 39,601,897 |
<p>The problem is that <code>np.nan != np.nan</code> is <code>True</code> (alternatively, <code>np.nan == np.nan</code> is <code>False</code>). Pandas provides the <code>.dropna()</code> method to do what you want:</p>
<pre><code>df.dropna()
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code> prod_id prod_ref
0 10.0 ef3920
1 12.0 bovjhd
4 30.0 kbknkn
</code></pre>
<p>By default, <code>.dropna()</code> will drop any row that has a <code>NaN</code> in any column. You can tweak this behavior in two ways:</p>
<ul>
<li>check only some columns using the <code>subset</code> argument, and</li>
<li>require that the row contains <code>NaN</code> in <em>all</em> columns (in the <code>subset</code>, if you are using it) using <code>how='all'</code> — the default is <code>how='any'</code>.</li>
</ul>
<p>You can check the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow">documentation</a>.</p>
| 3 |
2016-09-20T19:01:37Z
|
[
"python",
"python-2.7",
"pandas"
] |
How to use a for loop to iterate through an array
| 39,601,863 |
<p>So basically I am getting a list of ids and storing them in an array ids. I want to use these ids to do api calls. Here is my code:</p>
<pre><code>url = "https://swag.com"
headers = {'x-api-token': "cool"}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
ids = [element['id'] for element in data['result']['elements']]
for i in ids:
url_2 = "https://swag.com/"
survey_url = url_2 + str(ids)
response_2 = requests.get(survey_url, headers=headers)
data_2 = json.loads(response_2.text)
print(response_2.text)
</code></pre>
<p>so basically I don't know how to separate the ids to run individual calls. How would I go about doing this. With my code it just tries to run all ids as 1 api call.</p>
| -1 |
2016-09-20T18:59:30Z
| 39,601,966 |
<p>Your for loop is constructing a survey url based on <code>ids</code> instead of <code>id</code>.</p>
<p>Change it to</p>
<pre><code>for i in ids:
url2 = "https://swag.com/"
# your mistake was using str(ids) here.
survey_url = url_2 + str(i)
# proceed further with making the request for this survey url
# Also, I feel the response_2, data_2 and print(response_2.text)
# should be inside this for loop
</code></pre>
<p>An easy way to catch this error would be to put a print statement and print your survey_url.</p>
| 3 |
2016-09-20T19:05:44Z
|
[
"python",
"arrays",
"api"
] |
Writing from a dictionary to a text file in a sorted way (python)
| 39,601,875 |
<p>I have a code where i need to write a dictionary to a .txt file in order.</p>
<pre><code>with open("Items.txt", "w+") as file:
for item in sorted(orders):
file.write(item + "," + ",".join(map(str,orders[item])) + "\n")
file.close
print("New stock level to file complete.")
</code></pre>
<p>Here orders is my dictionary which i want to write into Items.txt</p>
<p>Every time i run this i get a type error like this:</p>
<pre><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>My contents of my dictionary are:</p>
<pre><code>orders[int(code)] = [str(name),int(current_stock),int(re_order),int(target_stock),float(price)]
</code></pre>
<p>Can some one please help me with this issue. I suspect that all the contents are not string but i don't know how to change the contents in the dictionary to a string.</p>
<p>PS: I cant change the contents in my dictionary to string as i need to use integer for later.</p>
| 0 |
2016-09-20T19:00:15Z
| 39,601,953 |
<p>Because <code>item</code> will be an <code>int</code>, you cannot use the <code>+</code> operator with it on a string (<code>,</code>). Python is a strongly typed language. Use:</p>
<pre><code>file.write(str(item) + "," + ",".join(map(str,orders[item])) + "\n")
</code></pre>
<p>instead.</p>
| 1 |
2016-09-20T19:04:37Z
|
[
"python"
] |
Can I use pandas.dataframe.isin() with a numeric tolerance parameter?
| 39,602,004 |
<p>I reviewed the following posts beforehand. Is there a way to use DataFrame.isin() with an approximation factor or a tolerance value? Or is there another method that could?</p>
<p><a href="http://stackoverflow.com/questions/12065885/how-to-filter-the-dataframe-rows-of-pandas-by-within-in">How to filter the DataFrame rows of pandas by "within"/"in"?</a></p>
<p><a href="http://stackoverflow.com/questions/12096252/use-a-list-of-values-to-select-rows-from-a-pandas-dataframe">use a list of values to select rows from a pandas dataframe</a></p>
<p>EX)</p>
<pre><code>df = DataFrame({'A' : [5,6,3.3,4], 'B' : [1,2,3.2, 5]})
In : df
Out:
A B
0 5 1
1 6 2
2 3.3 3.2
3 4 5
df[df['A'].isin([3, 6], tol=.5)]
In : df
Out:
A B
1 6 2
2 3.3 3.2
</code></pre>
| 6 |
2016-09-20T19:07:50Z
| 39,602,108 |
<p>You can do a similar thing with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow">numpy's isclose</a>:</p>
<pre><code>df[np.isclose(df['A'].values[:, None], [3, 6], atol=.5).any(axis=1)]
Out:
A B
1 6.0 2.0
2 3.3 3.2
</code></pre>
<hr>
<p>np.isclose returns this:</p>
<pre><code>np.isclose(df['A'].values[:, None], [3, 6], atol=.5)
Out:
array([[False, False],
[False, True],
[ True, False],
[False, False]], dtype=bool)
</code></pre>
<p>It is a pairwise comparison of <code>df['A']</code>'s elements and <code>[3, 6]</code> (that's why we needed <code>df['A'].values[: None]</code> - for broadcasting). Since you are looking for whether it is close to any one of them in the list, we call <code>.any(axis=1)</code> at the end.</p>
<hr>
<p>For multiple columns, change the slice a little bit:</p>
<pre><code>mask = np.isclose(df[['A', 'B']].values[:, :, None], [3, 6], atol=0.5).any(axis=(1, 2))
mask
Out: array([False, True, True, False], dtype=bool)
</code></pre>
<p>You can use this mask to slice the DataFrame (i.e. <code>df[mask]</code>)</p>
<hr>
<p>If you want to compare <code>df['A']</code> and <code>df['B']</code> (and possible other columns) with different vectors, you can create two different masks:</p>
<pre><code>mask1 = np.isclose(df['A'].values[:, None], [1, 2, 3], atol=.5).any(axis=1)
mask2 = np.isclose(df['B'].values[:, None], [4, 5], atol=.5).any(axis=1)
mask3 = ...
</code></pre>
<p>Then slice:</p>
<pre><code>df[mask1 & mask2] # or df[mask1 & mask2 & mask3 & ...]
</code></pre>
| 9 |
2016-09-20T19:14:33Z
|
[
"python",
"pandas",
"comparison",
"floating-accuracy",
"comparison-operators"
] |
Return Events from DispatchWithEvents using third party COM
| 39,602,065 |
<p>My code prints out what I need from the print statement in Events. But, I have no idea how to return the data because of the way the class is instantiated. Further, the print statement only works if pythoncom.PumpWaitingMessages() is included, but it doesn't return the data that's printed, or anything.</p>
<p>I'd like to be able to use what's printed as a return value to be accessed by other functions. </p>
<p>(If worse comes to worse, I could capture stdout (which is a last resort).)</p>
<p>Code:</p>
<pre><code># Standard Lib
import time
# Third Party
from win32com.client import DispatchWithEvents
import pythoncom
# Local Lib
import scan_var
class Events(object):
def OnBarcodeEvent(self, eventType=pythoncom.Empty, pscanData=pythoncom.Empty):
print pscanData
return pscanData
zebra = DispatchWithEvents("CoreScanner.CoreScanner", Events)
# open api
open_status = zebra.Open(0, [1], 1)
print "Open status: {}".format(open_status)
# get scanners
get_scanners = zebra.GetScanners(0, [1])
print "get_scanners: {}".format(get_scanners)
# Register for events
register = zebra.ExecCommand(1001,scan_var.register_for_events)
print "register: {}".format(register)
# PEWPEWPEW (pull trigger)
fire_result = zebra.ExecCommand(2011, scan_var.pull_trigger)
print "PEWPEWPEW {}".format(fire_result)
time.sleep(5)
while True:
time.sleep(1)
pythoncom.PumpWaitingMessages()
</code></pre>
<p>Output:</p>
<pre><code>Open status: 0
get_scanners: (1, (1,),504</VID> <PID>6400</PID> ...
register: (u'', 0)
PEWPEWPEW (u'', 0)
<?xml version="1.0" encoding="UTF-8"?>
<outArgs>
<scannerID>1</scannerID>
<arg-xml>
<scandata>
<modelnumber>new_hotness </modelnumber>
<serialnumber>1522501a0501156 </serialnumber>
<GUID>2A4BE99CFCEFD047837ADF0082aD51AD5</GUID>
<datatype>27</datatype>
<datalabel>0x39 0x32 0x304 ...</datalabel>
<rawdata>0x22 0x03 0x00 ... </rawdata>
</scandata>
</arg-xml>
</outArgs>
</code></pre>
| 0 |
2016-09-20T19:12:03Z
| 39,664,585 |
<p>My solution is as follows. This may be ugly and wrong but it got me what I need. If anyone has a better way I'm happy to edit.</p>
<pre><code>class Events(object):
def get_barcode(self):
return self.pscanData
def OnBarcodeEvent(self, eventType=1, pscanData=pythoncom.Empty):
self.pscanData = pscanData
print self.pscanData
def save_serial_to_cache():
zebra = DispatchWithEvents("CoreScanner.CoreScanner", Events)
# open api
open_status = zebra.Open(0, [1], 1)
print "Open status: {}".format(open_status)
#get scanners
get_scanners = zebra.GetScanners(0, [1])
print "get_scanners: {}".format(get_scanners)
# Register for events
register = zebra.ExecCommand(1001,scan_var.register_for_events)
print "register: {}".format(register)
# PEWPEWPEW (pull trigger)
fire_result = zebra.ExecCommand(2011, scan_var.pull_trigger)
print "PEWPEWPEW {}".format(fire_result)
for counter in xrange(0, 5):
time.sleep(1)
pythoncom.PumpWaitingMessages()
return zebra._obj_.get_barcode.__self__.pscanData
</code></pre>
| 0 |
2016-09-23T15:33:43Z
|
[
"python",
"python-2.7",
"com",
"win32com",
"pythoncom"
] |
Map if it can be converted
| 39,602,093 |
<p>I have the following list:</p>
<pre><code>a = ['1', '2', 'hello']
</code></pre>
<p>And I want to obtain</p>
<pre><code>a = [1, 2, 'hello']
</code></pre>
<p>I mean, convert all integers I can.</p>
<p>This is my function:</p>
<pre><code>def listToInt(l):
casted = []
for e in l:
try:
casted.append(int(e))
except:
casted.append(e)
return casted
</code></pre>
<p>But, can I use the <code>map()</code> function or something similar?</p>
| 0 |
2016-09-20T19:13:36Z
| 39,602,178 |
<p>Sure you can do this with <code>map</code></p>
<pre><code>def func(i):
try:
i = int(i)
except:
pass
return i
a = ['1', '2', 'hello']
print(list(map(func, a)))
</code></pre>
| 3 |
2016-09-20T19:19:04Z
|
[
"python",
"algorithm",
"list",
"casting"
] |
Map if it can be converted
| 39,602,093 |
<p>I have the following list:</p>
<pre><code>a = ['1', '2', 'hello']
</code></pre>
<p>And I want to obtain</p>
<pre><code>a = [1, 2, 'hello']
</code></pre>
<p>I mean, convert all integers I can.</p>
<p>This is my function:</p>
<pre><code>def listToInt(l):
casted = []
for e in l:
try:
casted.append(int(e))
except:
casted.append(e)
return casted
</code></pre>
<p>But, can I use the <code>map()</code> function or something similar?</p>
| 0 |
2016-09-20T19:13:36Z
| 39,602,239 |
<pre><code>a = ['1', '2', 'hello']
y = [int(x) if x.isdigit() else x for x in a]
>> [1, 2, 'hello']
>> #tested in Python 3.5
</code></pre>
<p>Maybe something like this? </p>
| 2 |
2016-09-20T19:22:43Z
|
[
"python",
"algorithm",
"list",
"casting"
] |
Is there a way to read all files excluding a defined list of files in python apache beam?
| 39,602,163 |
<p>My use case is that I am batch processing files in a bucket that is constantly being updated with new files. I don't want to process csv files that have already been processed. </p>
<p>Is there a way to do that? </p>
<p>One potential solution I thought of, is to have a text file that maintains a list of processed files and then reads all csv files excluding the files in the processed list. Is that possible? </p>
<p>Or is it possible to read a list of specific files? </p>
| 1 |
2016-09-20T19:18:00Z
| 39,604,762 |
<p>There's not a good built-in way to do this, but you can have one stage of your pipeline that computes the list of files to read as you suggested, the using a DoFn that maps a filename to the contents of the file. See <a href="http://stackoverflow.com/questions/39578932/reading-multiple-gz-file-and-identifying-which-row-belongs-to-which-file">Reading multiple .gz file and identifying which row belongs to which file</a> for information about how to write this DoFn</p>
| 1 |
2016-09-20T22:34:17Z
|
[
"python",
"google-cloud-dataflow",
"dataflow",
"apache-beam"
] |
compare datetime.now() with utc timestamp with python 2.7
| 39,602,188 |
<p>I have a timestamp such <code>1474398821633L</code> that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.</p>
<p>I am using python 2.7</p>
<pre><code>from datetime import datetime
timestamp = 1474398821633L
now = datetime.now()
if datetime.utcfromtimestamp(timestamp) < now:
print "timestamp expired"
</code></pre>
<p>However I got this error when trying to create a datetime object from the timestamp: <code>ValueError: timestamp out of range for platform localtime()/gmtime() function</code></p>
<p>What can I do?</p>
| 0 |
2016-09-20T19:19:30Z
| 39,602,250 |
<p>It <em>looks</em> like your timestamp is in milliseconds. Python uses timestamps in seconds:</p>
<pre><code>>>> datetime.datetime.utcfromtimestamp(1474398821.633)
datetime.datetime(2016, 9, 20, 19, 13, 41, 633000)
</code></pre>
<p>In other words, you might need to divide your timestamp by <code>1000.</code> in order to get it in the proper range.</p>
<p>Also, you'll probably want to compare <code>datetime.utcnow()</code> instead of <code>datetime.now()</code> to make sure that you're handling timezones correctly :-).</p>
| 3 |
2016-09-20T19:23:20Z
|
[
"python",
"python-2.7"
] |
compare datetime.now() with utc timestamp with python 2.7
| 39,602,188 |
<p>I have a timestamp such <code>1474398821633L</code> that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.</p>
<p>I am using python 2.7</p>
<pre><code>from datetime import datetime
timestamp = 1474398821633L
now = datetime.now()
if datetime.utcfromtimestamp(timestamp) < now:
print "timestamp expired"
</code></pre>
<p>However I got this error when trying to create a datetime object from the timestamp: <code>ValueError: timestamp out of range for platform localtime()/gmtime() function</code></p>
<p>What can I do?</p>
| 0 |
2016-09-20T19:19:30Z
| 39,602,530 |
<p>As <a href="http://stackoverflow.com/a/39602250/4279">@mgilson pointed out</a> your input is likely "milliseconds", not "seconds since epoch".</p>
<p>Use <code>time.time()</code> instead of <code>datetime.now()</code>:</p>
<pre><code>import time
if time.time() > (timestamp_in_millis * 1e-3):
print("expired")
</code></pre>
<p>If you need <code>datetime</code> then use <code>datetime.utcnow()</code> instead of <code>datetime.now()</code>. Do not compare <code>.now()</code> that returns local time as a naive datetime object with <code>utcfromtimestamp()</code> that returns UTC time also as a naive datetime object (it is like comparing celsius and fahrenheit directly: you should convert to the same unit first).</p>
<pre><code>from datetime import datetime
now = datetime.utcnow()
then = datetime.utcfromtimestamp(timestamp_in_millis * 1e-3)
if now > then:
print("expired")
</code></pre>
<p>See more details in <a href="http://stackoverflow.com/q/26313520/4279">Find if 24 hrs have passed between datetimes - Python</a>.</p>
| 1 |
2016-09-20T19:42:03Z
|
[
"python",
"python-2.7"
] |
Image to Array: Plain English
| 39,602,190 |
<p>I'm starting to use numpy and PILlow to work with image files. And, generally loosing myself when it comes to converting images to arrays, and then working with arrays.
can someone explain what is happening when I convert an image to array. Such as this:</p>
<pre><code>ab = numpy.asarray(img.convert('L'))
</code></pre>
<p>And, also, why convert to an array? what functionality does this provide, what can I do with the array?</p>
<p>Thanks</p>
| 0 |
2016-09-20T19:19:37Z
| 39,669,750 |
<p><strong>What is a digital image?</strong></p>
<p>A digital image is a set of pixel values. Consider this image: <a href="http://i.imgur.com/wlDQhpL.png" rel="nofollow"><img src="http://i.imgur.com/wlDQhpL.png" alt="small smiley face"></a>. It consists of 16x16 pixels. Because most displays have 8 bits (2^8 (256) possible values) and 3 channels (for red, green, and blue), it consists of a 16x16x3 array of numbers between 0 and 255.</p>
<p>The digital image of the smile was <em>already</em> made of numbers. When you loaded it using <code>PIL.Image</code> and then converted to a numpy array, all you did was expose the numbers to numpy. The <code>convert('L')</code> call asks PIL to convert a color image (3 channels) into a <strong>L</strong>uminance or grayscale (1 channel) image. So instead of being exposed to numpy as a 16x16x3 matrix, it's exposed as a 16x16x1 array.</p>
<p>There's nothing special about the numbers in a digital image. In fact here are the numbers that comprise the digital image above:</p>
<pre><code>255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 6 6 6 6 6 6 6 255 255 255 255
255 255 255 6 6 6 6 6 6 6 6 6 6 255 255 255
255 255 6 6 6 130 255 255 255 255 255 6 6 6 255 255
255 255 6 6 255 255 255 255 255 255 255 255 6 6 6 255
255 6 6 68 255 255 255 255 255 255 255 255 255 6 6 255
255 6 6 255 255 6 161 255 255 255 6 6 255 84 6 6
255 6 6 255 68 6 6 255 255 255 6 6 255 255 6 6
255 6 6 255 255 6 255 255 255 255 6 115 255 255 6 6
255 6 6 255 255 255 255 255 255 255 255 255 255 224 6 6
255 6 6 255 255 6 6 6 6 6 6 255 255 6 6 176
255 130 6 6 255 255 6 6 6 6 84 255 239 6 6 255
255 255 6 6 6 255 255 255 255 255 255 208 6 6 176 255
255 255 255 6 6 6 6 239 255 115 6 6 6 6 255 255
255 255 255 255 6 6 6 6 6 6 6 6 224 255 255 255
255 255 255 255 255 255 115 6 6 6 255 255 255 255 255 255
</code></pre>
<p><strong>Why would you want to convert a digital image to a numpy array?</strong></p>
<p>I don't know what Pillow's capabilities are, but I would guess that numpy's numerical/statistical/quantitative capabilities are much more powerful than Pillow's. Once you've exposed the numbers in the image to numpy, you can do all sorts of cool things, like find it's average luminance or variance (<code>ab_mean = numpy.mean(ab)</code> or <code>ab_var = numpy.var(ab)</code>), FFT it (<code>ab_fft = numpy.fft.fft2(ab)</code>), or transpose it (<code>ab_transposed = ab.T</code>):<a href="http://i.imgur.com/jV2Zy60.png" rel="nofollow"><img src="http://i.imgur.com/jV2Zy60.png" alt="small transposed smiley face"></a></p>
| 2 |
2016-09-23T21:23:16Z
|
[
"python",
"arrays",
"python-2.7",
"numpy",
"pillow"
] |
BeautifulSoup webscraper issue: can't find certain divs/tables
| 39,602,223 |
<p>I'm having issues with scraping pro-football-reference.com. I'm trying to access the "Team Offense" table but can't seem to target the div/table.
The best I can do is:</p>
<pre><code>soup.find('div', {'id':'all_team_stats})
</code></pre>
<p>which doesn't return the table nor it's immediate div wrapper. The following attempts return "None":</p>
<pre><code>soup.find('div', {'id':'div_team_stats'})
soup.find('table', {'id':'team_stats'})
</code></pre>
<p>I've already scraped different pages simply by:</p>
<pre><code>soup.find('table', {'id':'table_id})
</code></pre>
<p>but I can't figure out why it's not working on this page. Below is the code I've been working with. Any help is much appreciated!</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
def make_soup(url):
page = urllib2.urlopen(url)
soupdata = BeautifulSoup(page, 'lxml')
return soupdata
def get_player_totals():
soup = make_soup("http://www.pro-football-reference.com/years/2015/")
tableStats = soup.find('table', {'id':'team_stats'})
return tableStats
print get_player_totals()
</code></pre>
<p>EDIT:</p>
<p>Thanks for all the help everyone. Both of the provided solutions below have been successful. Much appreciated!</p>
| 2 |
2016-09-20T19:21:56Z
| 39,602,574 |
<p>A couple of thoughts here: first, as mentioned in the comments, the acutal table is commented out and is not <em>per se</em> part of the <code>DOM</code> (not accessible via a parser adhoc).<br>
In this situation, you can loop over the comments found and try to get the information via regular expressions (though this heavily discussed and mostly disliked on Stackoverflow, <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags"><strong>see here for more information</strong></a>). Last, but not least, I would recommend <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><strong><code>requests</code></strong></a> rather than <code>urllib2</code>. </p>
<p>That being said, here is a working code example:</p>
<pre><code>from bs4 import BeautifulSoup, Comment
import requests, re
def make_soup(url):
r = requests.get(url)
soupdata = BeautifulSoup(r.text, 'lxml')
return soupdata
soup = make_soup("http://www.pro-football-reference.com/years/2015/")
# get the comments
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
# look for table with the id "team_stats"
rx = re.compile(r'<table.+?id="team_stats".+?>[\s\S]+?</table>')
for comment in comments:
try:
table = rx.search(comment.string).group(0)
print(table)
# break the loop if found
break
except:
pass
</code></pre>
<p><strong>Always</strong> favour a parser solution over this one, especially the regex part is very error-prone.</p>
| 1 |
2016-09-20T19:44:35Z
|
[
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
BeautifulSoup webscraper issue: can't find certain divs/tables
| 39,602,223 |
<p>I'm having issues with scraping pro-football-reference.com. I'm trying to access the "Team Offense" table but can't seem to target the div/table.
The best I can do is:</p>
<pre><code>soup.find('div', {'id':'all_team_stats})
</code></pre>
<p>which doesn't return the table nor it's immediate div wrapper. The following attempts return "None":</p>
<pre><code>soup.find('div', {'id':'div_team_stats'})
soup.find('table', {'id':'team_stats'})
</code></pre>
<p>I've already scraped different pages simply by:</p>
<pre><code>soup.find('table', {'id':'table_id})
</code></pre>
<p>but I can't figure out why it's not working on this page. Below is the code I've been working with. Any help is much appreciated!</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
def make_soup(url):
page = urllib2.urlopen(url)
soupdata = BeautifulSoup(page, 'lxml')
return soupdata
def get_player_totals():
soup = make_soup("http://www.pro-football-reference.com/years/2015/")
tableStats = soup.find('table', {'id':'team_stats'})
return tableStats
print get_player_totals()
</code></pre>
<p>EDIT:</p>
<p>Thanks for all the help everyone. Both of the provided solutions below have been successful. Much appreciated!</p>
| 2 |
2016-09-20T19:21:56Z
| 39,603,191 |
<p>Just remove the comments with <em>re.sub</em> before you pass to bs4:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
import re
comm = re.compile("<!--|-->")
def make_soup(url):
page = urllib2.urlopen(url)
soupdata = BeautifulSoup(comm.sub("", page.read()), 'lxml')
return soupdata
def get_player_totals():
soup = make_soup("http://www.pro-football-reference.com/years/2015/")
tableStats = soup.find('table', {'id':'team_stats'})
return tableStats
print get_player_totals()
</code></pre>
<p>You will see the table when you run the code.</p>
| 1 |
2016-09-20T20:28:55Z
|
[
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
Invalid syntax while using socket
| 39,602,305 |
<p>i've struggled with this code and I can't see why its saying there is a syntax error on line 15. Im trying to create a TCP connection with google for a diagnostic tool for my college coursework.</p>
<pre class="lang-python prettyprint-override"><code>import socket
import sys
#defining the port and host we wll be using to check the internet connection on.
remote_connection = "www.google.com" #google will automatically load balance the request to the uk servers.
port = 80
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print("The script has exited with error %s" %(err))
try:
sockettest = socket.gethostbyname(remote_connection)
if socket.gaierror:
# this means that the connection is possibly blocked by a firewall and we will tell the end user.
print("there was an error resolving the host, possibly a firewall issue")
sys.exit()
elif socket.timeout:
#the connection has timedout which probably means the internet is offline
print("Your internet connection is offline, please connect all cables, reboot any network equiptment and try again")
sys.exit()
# connecting to the server
s.connect((remote_connection,port))
print("Your internet connection is active and working correctly! \n\
I was able to connect to:", (remote_connection), "sucessfully")
</code></pre>
| 0 |
2016-09-20T19:27:01Z
| 39,602,332 |
<p>There is no <code>except</code> statement for </p>
<pre><code>try:
sockettest = socket.gethostbyname(remote_connection)
</code></pre>
| 5 |
2016-09-20T19:28:25Z
|
[
"python",
"sockets"
] |
Building JSON object that can hold contents of file
| 39,602,353 |
<p>I have to save contents of a python file to my database. I am writing fixtures so that I can load that to my database from Django project.</p>
<p>I have no idea where to begin with. The size is an issue that I need to address for my JSON object.</p>
<p>Edit: My app features an upload option where user can upload their python file which does some action, and gives some result. If the user is pleased with my app's performance he can store his script (python file) and can run it anytime.</p>
<p>So far, I am using a static file location to store the python file. I feel like not updating my SCM whenever a file is uploaded to the system, instead have it store in my database in assumption that I will be having a infinite storage space.</p>
| 0 |
2016-09-20T19:29:36Z
| 39,602,784 |
<p>You should not be creating your fixtures manually. You should populate a test database with data then use <a href="https://docs.djangoproject.com/en/1.8/ref/django-admin/#django-admin-dumpdata" rel="nofollow"><code>manage.py dumpdata</code></a> to export it. </p>
<p>Django <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.FileField" rel="nofollow"><code>FileField</code></a> and <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ImageField" rel="nofollow"><code>ImageField</code></a> both store a path to the <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow"><code>staticfiles</code></a> location, they do not store the contents of the files directly.</p>
<p>If you're trying to store the contents of a text file, that can be held in a <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.TextField" rel="nofollow"><code>TextField</code></a>. To represent this in JSON, it will most likely need to be encoded to UTF8 to handle special characters (pretty quotes, accents, etc.) and escaped so that line endings are turned into <code>\n</code>, etc.</p>
| 1 |
2016-09-20T19:58:01Z
|
[
"python",
"json",
"django",
"database"
] |
python convert string time to sql datetime format
| 39,602,376 |
<p>I am importing a large csv file to ETL into a database, and the date format that was originally set in the csv file looks like <code>4/22/2016 1:00:00 PM</code>. Each date is part of a larger list that might have non-date type items in it. for example:</p>
<pre><code>v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
</code></pre>
<p>I would like to reformat every date (if present in the list) with the correct MySQL format of </p>
<p><code>%m-%d-%Y %I:%M:%S</code></p>
<p>How would i do this with a <strong>list comprehension</strong>? my code is not working for obvious reasons but i'm not sure where to go from here. I need to retain the index that the date is found in <code>v</code>. </p>
<pre><code>from datetime import datetime, date, time
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
tstamp = datetime.strptime(_params, "%m/%d/%Y %I:%M:%S %p")
newtstamp = date.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
replace = { _params: newtstamp }
l = [replace.get(x, x) for x in _params]
print l
fixdate(v)
</code></pre>
| 0 |
2016-09-20T19:30:46Z
| 39,602,723 |
<p>Please check this. <strong>Comments inline with code.</strong></p>
<pre><code>from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
#First date in list
tstamp = datetime.strptime(_params[0], "%m/%d/%Y %I:%M:%S %p")
#Add %p after %S if AM or PM is required
newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
#Update the element in list
_params[0] = newtstamp
#Second date in list
tstamp = datetime.strptime(_params[1], "%m/%d/%Y %I:%M:%S %p")
newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
#Update the element in list
_params[1] = newtstamp
print "After changing format..."
print _params
fixdate(v)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
<p><strong>Code with list comprehension:</strong></p>
<pre><code>from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
_params = [i if ':' not in str(i) and '/' not in str(i) else datetime.strftime(datetime.strptime(i, "%m/%d/%Y %I:%M:%S %p"), "%m-%d-%Y %I:%M:%S") for i in _params]
print "After changing format..."
print _params
fixdate(v)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 2 |
2016-09-20T19:53:52Z
|
[
"python",
"mysql",
"datetime"
] |
Numpy matrix exponentiation gives negative value
| 39,602,404 |
<p>I wanted to use <code>NumPy</code> in a Fibonacci question because of its efficiency in matrix multiplication. You know that there is a method for finding Fibonacci numbers with the matrix <code>[[1, 1], [1, 0]]</code>.</p>
<p><a href="http://i.stack.imgur.com/JuBny.gif" rel="nofollow"><img src="http://i.stack.imgur.com/JuBny.gif" alt="Fibo"></a></p>
<p>I wrote some very simple code but after increasing <code>n</code>, the matrix is starting to give negative numbers.</p>
<pre><code>import numpy
def fib(n):
return (numpy.matrix("1 1; 1 0")**n).item(1)
print fib(90)
# Gives -1581614984
</code></pre>
<p>What could be the reason for this?</p>
<p><strong>Note:</strong> <code>linalg.matrix_power</code> also gives negative values.</p>
<p><strong>Note2:</strong> I tried numbers from 0 to 100. It starts to give negative values after 47. Is it a large integer issue because NumPy is coded in C ? If so, how could I solve this ?</p>
<p><strong>Edit:</strong> Using regular python <code>list</code> matrix with <code>linalg.matrix_power</code> also gave negative results. Also let me add that not all results are negative after 47, it occurs randomly.</p>
<p><strong>Edit2:</strong> I tried using the method @AlbertoGarcia-Raboso suggested. It resolved the negative number problem, however another issues occured. It gives the answer as <code>-5.168070885485832e+19</code> where I need <code>-51680708854858323072L</code>. So I tried using <code>int()</code>, it converted it to <code>L</code>, but now it seems the answer is incorrect because of a loss in precision.</p>
| 2 |
2016-09-20T19:32:29Z
| 39,602,984 |
<p>The reason you see negative values appearing is because NumPy has defaulted to using the <code>np.int32</code> dtype for your matrix.</p>
<p>The maximum positive integer this dtype can represent is 2<sup>31</sup>-1 which is 2147483647. Unfortunately, this is less the 47th Fibonacci number, 2971215073. The resulting overflow is causing the negative number to appear:</p>
<pre><code>>>> np.int32(2971215073)
-1323752223
</code></pre>
<p>Using a bigger integer type (like <code>np.int64</code>) would fix this, but only temporarily: you'd still run into problems if you kept on asking for larger and larger Fibonacci numbers.</p>
<p>The only sure fix is to use an unlimited-size integer type, such as Python's <code>int</code> type. To do this, modify your matrix to be of <code>np.object</code> type:</p>
<pre><code>def fib_2(n):
return (np.matrix("1 1; 1 0", dtype=np.object)**n).item(1)
</code></pre>
<p>The <code>np.object</code> type allows a matrix or array to hold any mix of native Python types. Essentially, instead of holding machine types, the matrix is now behaving like a Python list and simply consists of pointers to integer objects in memory. Python integers will be used in the calculation of the Fibonacci numbers now and overflow is not an issue.</p>
<pre><code>>>> fib_2(300)
222232244629420445529739893461909967206666939096499764990979600
</code></pre>
<p>This flexibility comes at the cost of decreased performance: NumPy's speed originates from direct storage of integer/float types which can be manipulated by your hardware.</p>
| 6 |
2016-09-20T20:11:54Z
|
[
"python",
"numpy",
"matrix"
] |
Calling out a function, not defined error
| 39,602,440 |
<p>I'm new to making classes and I'm trying to complete exercise 9-1 in my 'Python Crash Course' book where the last part of the question asks me to call back my method but I end up getting</p>
<blockquote>
<p>'not defined error' for <code>describe_restaurant()</code>.</p>
</blockquote>
<p><strong>Here is my code:</strong></p>
<pre><code>class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant():
print(self.r_name.title())
print(self.c_type.title())
def open_restaurant():
print(self.r_name + " is now open!")
Restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(Restaurant.r_name)
print(Restaurant.c_type)
describe_restaurant()
open_restaurant()
</code></pre>
<p>I thought that <code>describe_restaurant</code> shouldn't need to be defined though because I'm calling it out as a function to use?</p>
| 0 |
2016-09-20T19:35:28Z
| 39,602,472 |
<p>Try:</p>
<pre><code>class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant(self):
print(self.r_name)
print(self.c_type)
def open_restaurant(self):
return "{} is now open!".format(self.r_name)
restaurant = Restaurant('Joe\'s Sushi', 'sushi')
print(restaurant.r_name)
print(restaurant.c_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
</code></pre>
<p>You need to create a class instance and call it's functions. In addition, as mentioned in the comments, you need to pass <code>self</code> to the instance methods. A short explanation of this can be found <a href="https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/" rel="nofollow">here</a>.</p>
| 2 |
2016-09-20T19:37:18Z
|
[
"python",
"class"
] |
Replace Values in Dictionary
| 39,602,476 |
<p>I am trying to replace the <code>values</code> in the <code>lines dictionary</code> by the <code>values of the corresponding key</code> in the <code>points dictionary</code></p>
<pre><code>lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points)
points = {'10': ('2.416067758476', '2.075872272548'), '17': ('2.454725131264', '5.000000000000'), '18': ('1.828299357105', '5.000000000000'), '2': ('3.541310767185', '2.774647545044')} #Point ID => (X,Y)
i = 1
while i in range(len(lines)):
for k, v in lines.iteritems():
for k1, v1 in points.iteritems():
for n, new in enumerate(v):
if k1 == new:
lines[k] = v1
i += 1
</code></pre>
<p>The expected output is:</p>
<pre><code>lines = {'24': ('2.416067758476', '2.075872272548', '3.541310767185', '2.774647545044'), '25': ('2.454725131264', '5.000000000000', '1.828299357105', '5.000000000000')}
</code></pre>
<p>The output from the above code</p>
<pre><code>lines = {'24': ('3.541310767185', '2.774647545044'), '25': ('1.828299357105', '5.000000000000')}
</code></pre>
<p>If i create a list, then append that into the <code>lines[k]</code> i end up getting the all the values in the points list as that of each key element of lines. I think it is not looping out of the for loop properly. </p>
| 2 |
2016-09-20T19:37:41Z
| 39,602,535 |
<p>You are getting the wrong output because of
<code>lines[k] = v</code> . That is overwriting your previous assignment.</p>
<p>For your desired output - </p>
<pre><code>lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points)
points = {'10': ('2.416067758476', '2.075872272548'), '17': ('2.454725131264', '5.000000000000'), '18': ('1.828299357105', '5.000000000000'), '2': ('3.541310767185', '2.774647545044')} #Point ID => (X,Y)
new_lines = {}
for k, v in lines.iteritems():
x, y = v
new_v = []
new_v.extend(points[x])
new_v.extend(points[y])
new_lines[k] = tuple(new_v)
print new_lines
</code></pre>
| 2 |
2016-09-20T19:42:27Z
|
[
"python",
"python-2.7",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.