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 |
|---|---|---|---|---|---|---|---|---|---|
Python Selenium Detection Error? | 39,060,524 | <p>Hi i've been trying to learn selenium.</p>
<p>The problem i am having is that an element isn't being detected. The html code i am working with is highlighted right here <a href="https://gyazo.com/a76608d4c4e9fc3bd29412436604c173" rel="nofollow">https://gyazo.com/a76608d4c4e9fc3bd29412436604c173</a>. That line of code stopped my program and gave me the error <a href="https://gyazo.com/72fc72e6488578c9c2a50b71311602c5" rel="nofollow">https://gyazo.com/72fc72e6488578c9c2a50b71311602c5</a>.</p>
<p>The code i am using to detect for the textarea class is</p>
<pre><code>comment=driver.find_element_by_xpath("//form[@class='comment-form no-border-top']/div/*[1]") or driver.find_element_by_xpath("//form[@class='comment-form']/div/*[1]")
</code></pre>
<p>because sometimes it switches between comment-form no border and comment form.</p>
<p>My idea is to use a conditional assignment operator check for example if(comment!=none): do something, but to my understanding python doesn't allow this.</p>
<p>any suggestions on what to do and whether my xpath is a reliable method?</p>
| 0 | 2016-08-21T03:11:31Z | 39,060,579 | <p>If the problem you're trying to solve is actually conditional assignment, there are two different things you might want to know.</p>
<p>The first is that you <em>can</em> do:</p>
<blockquote>
<p>if(comment!=none)</p>
</blockquote>
<p>you just have to do it like this:</p>
<pre><code>comment = Foo()
if comment is None:
comment = Bar()
</code></pre>
<p>Second, maybe you want to <em>try</em> assigning <code>comment</code> if the first call throws an error rather than just being <code>None</code>. If so, try using <code>try</code>!</p>
<pre><code>from selenium.common.exceptions import NoSuchElementException
try:
comment = driver.find_element_by_xpath("//form[@class='comment-form no-border-top']/div/*[1]")
except NoSuchElementException:
comment = driver.find_element_by_xpath("//form[@class='comment-form']/div/*[1]")
</code></pre>
| 0 | 2016-08-21T03:23:10Z | [
"python",
"selenium"
] |
PySide Application with asynchronous function execution | 39,060,584 | <p>I have a sample pyside demo which I created to see the webkit browser communication with python...
I have two buttons in webkit</p>
<ul>
<li><p>button 1 - when clicked it sleeps for 10 seconds and then prints a message</p></li>
<li><p>button2 - when clicked it prints a message immediately.</p></li>
</ul>
<p>When I clicked on button 1, the whole apps freezes and waits for python to finish sleeping, this means I cannot click on button 2 to do some other stuff. How can I implement an asynchronous method between function calls? </p>
<p>My python codes are below</p>
<pre><code>import sys,json
from time import sleep
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import QWebView, QWebSettings
from PySide.QtNetwork import QNetworkRequest
from PySide.QtCore import QObject, Slot, Signal
html_str="""<!doctype>
<html>
<body>hello world
<button id="button" >button1</button>
<button id="button2" >button2</button>
</body>
</html>
<script type="text/javascript">
document.getElementById("button").onclick=function(){
object.reply(" hello ");
}
document.getElementById("button2").onclick=function(){
object.reply2(" hello ");
}
function data_from_js(msg){
var tag=document.createElement('div');
tag.innerHTML="message from python";
document.body.appendChild(tag);
alert(msg['name']);
}
</script>
<style>
body{
border:solid black 1px;
}
</style>
</doctype>"""
class Qbutton(QObject):
from time import sleep
def __init__(self):
super(Qbutton,self).__init__()
@Slot(str)
def reply(self,recd):
#r=QMessageBox.information(self,"Info",msg)
msgBox = QMessageBox()
sleep(10)
msgBox.setText("python just said"+recd)
msgBox.exec_()
return "I am recieving pythonic data"
#r=QMessageBox.question(self,title,recd,QMessageBox.Yes | QMessageBox.No)
@Slot(str)
def reply2(self,recd):
msgBox = QMessageBox()
msgBox.setText("python just said"+recd+ " another time")
msgBox.exec_()
return "I am recieving pythonic data"
@Slot(str)
def send_tojs(self):
pass
class adstar_gui(QWidget):
def __init__(self):
super(adstar_gui,self).__init__()
self.setWindowTitle("Adstar Wordlist Generator")
self.setMaximumWidth(5000)
self.setMaximumHeight(5000)
self.setMinimumWidth(500)
self.setMinimumHeight(500)
self.show()
print "Sample window"
def closeEvent(self,event):
self.closeEvent()
if __name__=="__main__":
Qapp=QApplication(sys.argv)
t=QWebView()
t.setHtml(html_str)
button=Qbutton()
t.page().mainFrame().addToJavaScriptWindowObject("object",button)
t.show()
#t.page().mainFrame().evaluateJavaScript("data_from_js(%s);" % (json.dumps({'name':"My name is Junior"}) ))
QCoreApplication.processEvents()
#sys.exit(Qapp.exec_())
Qapp.exec_()
</code></pre>
<p>QUESTION</p>
<p>How can I click on <code>button 1</code> in webkit and let python do something in the background when button 1 is clicked? (so that <code>button 2</code> function does not need to wait for button 1 function to finish)</p>
<p>Kindly use this demo and improve on it...much appreciated</p>
| 6 | 2016-08-21T03:24:10Z | 39,100,133 | <p>Use a <code>QTimer</code> to execute a signal after a certain time period. Like this:</p>
<pre><code>import sys,json
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import QWebView, QWebSettings
from PySide.QtNetwork import QNetworkRequest
from PySide.QtCore import QObject, Slot, Signal, QTimer
html_str="""<!doctype>
<html>
<body>hello world
<button id="button" >button1</button>
<button id="button2" >button2</button>
</body>
</html>
<script type="text/javascript">
document.getElementById("button").onclick=function(){
object.replyAfter10Seconds(" hello ");
}
document.getElementById("button2").onclick=function(){
object.reply2(" hello ");
}
function data_from_js(msg){
var tag=document.createElement('div');
tag.innerHTML="message from python";
document.body.appendChild(tag);
alert(msg['name']);
}
</script>
<style>
body{
border:solid black 1px;
}
</style>
</doctype>"""
class Qbutton(QObject):
def __init__(self):
super(Qbutton,self).__init__()
self.timer = QTimer()
self.timer.setSingleShot(True)
self.timer.setInterval(10 * 1000)
self.timer.timeout.connect(self.reply)
@Slot(str)
def replyAfter10Seconds(self,recd):
self._replyText = recd
print "Started timer"
self.timer.start()
@Slot()
def reply(self):
#r=QMessageBox.information(self,"Info",msg)
msgBox = QMessageBox()
msgBox.setText("python just said"+self._replyText)
msgBox.exec_()
return "I am recieving pythonic data"
#r=QMessageBox.question(self,title,recd,QMessageBox.Yes | QMessageBox.No)
@Slot(str)
def reply2(self,recd):
msgBox = QMessageBox()
msgBox.setText("python just said"+recd+ " another time")
msgBox.exec_()
return "I am recieving pythonic data"
@Slot(str)
def send_tojs(self):
pass
class adstar_gui(QWidget):
def __init__(self):
super(adstar_gui,self).__init__()
self.setWindowTitle("Adstar Wordlist Generator")
self.setMaximumWidth(5000)
self.setMaximumHeight(5000)
self.setMinimumWidth(500)
self.setMinimumHeight(500)
self.show()
print "Sample window"
def closeEvent(self,event):
self.closeEvent()
if __name__=="__main__":
Qapp=QApplication(sys.argv)
t=QWebView()
t.setHtml(html_str)
button=Qbutton()
t.page().mainFrame().addToJavaScriptWindowObject("object",button)
t.show()
t.raise_()
#t.page().mainFrame().evaluateJavaScript("data_from_js(%s);" % (json.dumps({'name':"My name is Junior"}) ))
QCoreApplication.processEvents() # does nothing as long as App.exec_() hasn't statred.
#sys.exit(Qapp.exec_())
Qapp.exec_()
</code></pre>
| 1 | 2016-08-23T11:38:06Z | [
"python",
"pyside"
] |
PySide Application with asynchronous function execution | 39,060,584 | <p>I have a sample pyside demo which I created to see the webkit browser communication with python...
I have two buttons in webkit</p>
<ul>
<li><p>button 1 - when clicked it sleeps for 10 seconds and then prints a message</p></li>
<li><p>button2 - when clicked it prints a message immediately.</p></li>
</ul>
<p>When I clicked on button 1, the whole apps freezes and waits for python to finish sleeping, this means I cannot click on button 2 to do some other stuff. How can I implement an asynchronous method between function calls? </p>
<p>My python codes are below</p>
<pre><code>import sys,json
from time import sleep
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import QWebView, QWebSettings
from PySide.QtNetwork import QNetworkRequest
from PySide.QtCore import QObject, Slot, Signal
html_str="""<!doctype>
<html>
<body>hello world
<button id="button" >button1</button>
<button id="button2" >button2</button>
</body>
</html>
<script type="text/javascript">
document.getElementById("button").onclick=function(){
object.reply(" hello ");
}
document.getElementById("button2").onclick=function(){
object.reply2(" hello ");
}
function data_from_js(msg){
var tag=document.createElement('div');
tag.innerHTML="message from python";
document.body.appendChild(tag);
alert(msg['name']);
}
</script>
<style>
body{
border:solid black 1px;
}
</style>
</doctype>"""
class Qbutton(QObject):
from time import sleep
def __init__(self):
super(Qbutton,self).__init__()
@Slot(str)
def reply(self,recd):
#r=QMessageBox.information(self,"Info",msg)
msgBox = QMessageBox()
sleep(10)
msgBox.setText("python just said"+recd)
msgBox.exec_()
return "I am recieving pythonic data"
#r=QMessageBox.question(self,title,recd,QMessageBox.Yes | QMessageBox.No)
@Slot(str)
def reply2(self,recd):
msgBox = QMessageBox()
msgBox.setText("python just said"+recd+ " another time")
msgBox.exec_()
return "I am recieving pythonic data"
@Slot(str)
def send_tojs(self):
pass
class adstar_gui(QWidget):
def __init__(self):
super(adstar_gui,self).__init__()
self.setWindowTitle("Adstar Wordlist Generator")
self.setMaximumWidth(5000)
self.setMaximumHeight(5000)
self.setMinimumWidth(500)
self.setMinimumHeight(500)
self.show()
print "Sample window"
def closeEvent(self,event):
self.closeEvent()
if __name__=="__main__":
Qapp=QApplication(sys.argv)
t=QWebView()
t.setHtml(html_str)
button=Qbutton()
t.page().mainFrame().addToJavaScriptWindowObject("object",button)
t.show()
#t.page().mainFrame().evaluateJavaScript("data_from_js(%s);" % (json.dumps({'name':"My name is Junior"}) ))
QCoreApplication.processEvents()
#sys.exit(Qapp.exec_())
Qapp.exec_()
</code></pre>
<p>QUESTION</p>
<p>How can I click on <code>button 1</code> in webkit and let python do something in the background when button 1 is clicked? (so that <code>button 2</code> function does not need to wait for button 1 function to finish)</p>
<p>Kindly use this demo and improve on it...much appreciated</p>
| 6 | 2016-08-21T03:24:10Z | 39,217,337 | <p>There are a couple of issues here. First, it's worth pointing out why the app freezes when you click on button1: the click causes Qt to call the event handler, <code>reply</code>, and Qt can't handle another event until this handler returns (in my experience, all windowing systems work this way). So if you put any long running routine inside an event handler, your application will freeze until the routine finishes. Any time an event handler takes longer than about 0.05s, the user will notice.</p>
<p>As titusjan points out in his answer, it's pretty easy to get Qt to execute a function after a time interval. But I think your question isn't about how to handle a simple time delay, but rather how to handle a long-running process. In my example code, I replaced your ten second delay with a loop that counts ten one-second delays, which I think is a better model for what you are trying to achieve.</p>
<p>The solution is to do the long process in another thread. You have two options: QThreads, which are a part of the Qt environment, and Python threads. Both of them work, but I always use Python threads wherever possible. They're better documented and a little bit more lightweight. The ability to designate threads as daemons sometimes makes application shutdown a little simpler. Also, it's easier to convert a multithreaded program to one that uses multiprocesses. I used a Python thread in the example code below.</p>
<p>The problem then arises, how does the application know when the secondary thread is finished? For that purpose, you must create a custom Qt Signal. Your secondary thread emits this signal when it's done working, and the main app connects up a Slot to do something when that happens. If you're going to make a custom Qt Signal you must declare it in a subclass of QObject, as I did in the example.</p>
<p>Needless to say, all the standard multithreading issues have to be dealt with.</p>
<pre><code>import sys
import json
import threading
from time import sleep
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import QWebView, QWebSettings
from PySide.QtNetwork import QNetworkRequest
from PySide.QtCore import QObject, Slot, Signal
html_str="""<!doctype>
<html>
<body>hello world
<button id="button" >button1</button>
<button id="button2" >button2</button>
</body>
</html>
<script type="text/javascript">
document.getElementById("button").onclick=function(){
object.reply(" hello ");
}
document.getElementById("button2").onclick=function(){
object.reply2(" hello ");
}
function data_from_js(msg){
var tag=document.createElement('div');
tag.innerHTML="message from python";
document.body.appendChild(tag);
alert(msg['name']);
}
</script>
<style>
body{
border:solid black 1px;
}
</style>
</doctype>"""
class Qbutton(QObject):
def __init__(self):
super(Qbutton,self).__init__()
self.long_thread = LongPythonThread()
self.long_thread.thread_finished.connect(self.reply2_finished)
@Slot(str)
def reply(self,recd):
print("reply")
t = threading.Thread(target=self.long_thread.long_thread, args=(recd,))
t.daemon = True
t.start()
@Slot(str)
def reply2(self,recd):
print("reply2")
msgBox = QMessageBox()
msgBox.setText("python just said"+recd)
msgBox.exec_()
return "I am receiving pythonic data"
@Slot(str)
def reply2_finished(self, recd):
print("reply2 finished")
msgBox = QMessageBox()
msgBox.setText("python just said"+recd+ " another time")
msgBox.exec_()
@Slot(str)
def send_tojs(self):
pass
class LongPythonThread(QObject):
thread_finished = Signal(str)
def __init__(self):
super(LongPythonThread,self).__init__()
def long_thread(self, recd):
for n in range(10):
sleep(1.0)
print("Delayed for {:d}s".format(n+1))
self.thread_finished.emit(recd)
if __name__=="__main__":
Qapp=QApplication(sys.argv)
t=QWebView()
t.setHtml(html_str)
button=Qbutton()
t.page().mainFrame().addToJavaScriptWindowObject("object",button)
t.show()
#t.page().mainFrame().evaluateJavaScript("data_from_js(%s);" % (json.dumps({'name':"My name is Junior"}) ))
QCoreApplication.processEvents()
#sys.exit(Qapp.exec_())
Qapp.exec_()
</code></pre>
| 2 | 2016-08-30T01:02:52Z | [
"python",
"pyside"
] |
why does a script run faster as a module? | 39,060,596 | <p>I have a scrip 'xyz.py' that I'm importing as a module for another script (Main.py). Everything in xyz.py is inside of a class that I call in Main.py. Both, xyz.py and Main.py share the same import statements: "xml.etree.ElementTree"; "Tkinter"; "cv2"; "tkFileDialog"; "tkfd"; "from PIL import Image"; "ImageTk"; "os"</p>
<p>I noticed that when I run in Main.py the class having all the methods and statements of xyz.py, they run faster as a module than as the main script.
Is there a general fact behind this observation that I could use to speed up other stuff? Thank you.</p>
<p>PS: I didn't provide the code because it sums up to >400 lines, and I don't know exactly what I'm supposed to be looking at, so I'm not able to take a small and relevant sample.</p>
| 0 | 2016-08-21T03:26:56Z | 39,060,635 | <p>When a python program runs, the main script is always passed through the interpreter. When a module is imported, however, python checks its cache ( subdirectory named <code>__pycache__</code>) where it stores modules that have previously been compiled to bytecode. If the date of the cached copy matches the date of the source code date, it uses the cached version. That probably accounts for what you are seeing.</p>
| 0 | 2016-08-21T03:36:45Z | [
"python",
"performance",
"import",
"module"
] |
Cannot find reference to Python package (plt.cm.py) | 39,060,599 | <p>I have a small issue with running code from a tutorial that isn't working as it should. It's not a syntax problem for sure. I'm working with scikit-learn and matplotlib, and I'm getting a warning message in my IDE "Cannot find reference 'gray_r' in 'cm.py'..." All my packages are installed properly (via pip) and have worked for sample programs except this.</p>
<p>Any advice?</p>
<pre><code>import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
digits = datasets.load_digits()
print(digits.data)
print(digits.target)
print(digits.images[0])
clf = svm.SVC(gamma=0.001, C=100)
print(len(digits.data))
x, y = digits.data[:-1], digits.target[:-1]
clf.fit(x,y)
print('Prediction:', clf.predict(digits.data[-1])
plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
</code></pre>
| 0 | 2016-08-21T03:27:29Z | 39,060,672 | <p>Well for starters your missing a closing parenthesis on your last print statement: <code>print('Prediction:', clf.predict(digits.data[-1]))</code> Other than that, this code runs on my computer with only a deprecation warning. What does the traceback say?</p>
| 0 | 2016-08-21T03:44:45Z | [
"python",
"matplotlib",
"scipy",
"scikit-learn",
"pycharm"
] |
PyQt4 - Running functions that use python 2.7.11's builtin modules in separate threads | 39,060,634 | <p>i'm making an application for my grad paper at the university and i'm stuck with threading.
i'm trying to make an audio player that loads files into a table and plays them while taking specified intervals into account (basically sleeps after each sound played). i can get the list to play in order but it's in the same thread so GUI gets stcuk while that's happening. i used PyQt4 for the GUI because it was the fastest way to make a GUI and i'm visually impaired so i don't want to waste time coding all the UI stuff.
i've seen some QThread examples but i can't seem to get my threading to work.
i'm using winsound to play the sounds and they are loaded from an internal list which correpsonds to the table that displays on GUI
the file_list is an Ui_MainWindow instance variable (basically the main application class's variable) and all the functions are also defined in that class
Here's the relevant code:</p>
<pre><code>import sys
from PyQt4 import QtGui, QtCore
from winsound import PlaySound, SND_FILENAME
</code></pre>
<p>#some more code for the Ui_MainWindow class</p>
<pre><code> def play_stop(self):
t=Create_thread(self.snd_play) t.started.connect(func)
t.start()
def snd_play(self):
if not self.is_playing:
self.is_playing=True
for e in self.file_list:
PlaySound(e, SND_FILENAME)
self.is_playing=False
class Create_thread(QtCore.QThread):
def __init__(self,function):
QtCore.QThread.__init__(self)
self.function=function
def run(self):
self.function()
def main():
app=QtGui.QApplication([])
window=Ui_MainWindow()
window.setupUi(window)
window.show()
sys.exit(app.exec_())
</code></pre>
<p>I made a Create_thread class because i wanted a quick way to run functions in separate threads which is why the run function executes the function given as the argument</p>
<p>this worked when i was testing without GUI and with the threading module but when i introduced the GUI it stopped working and crashed my program
like i said the play_stop and snd_play are functions of the Ui_Mainwindow class
Any help would be greatly appreciated because without threading my application won't work properly.</p>
| 0 | 2016-08-21T03:36:02Z | 39,064,373 | <p>i found the issue with the threading module (it was my fault, of course)
For anyone having similar issues here's the correct class code:</p>
<pre><code> class Create_thread(threading.Thread):
def __init__(self,function):
threading.Thread.__init__(self)
self.function=function
def run(self):
self.function()
</code></pre>
<p>so i just needed to call the <strong>init</strong> function of the Thread class.
also here's the play_stop function code:</p>
<pre><code> def play_stop(self):
t=Create_thread(self.snd_play) #calls the actual function to play
t.start()
</code></pre>
<p>@101 thanks for your response</p>
| 1 | 2016-08-21T12:48:19Z | [
"python",
"multithreading",
"user-interface",
"pyqt4",
"qthread"
] |
Subprocess not working with complex Unix command | 39,060,644 | <p>I am trying to run a <code>join</code> command within Python, and I'm being foiled by <code>subprocess</code>. I'm combining thousands of large files iteratively, so a dictionary would require a lot of memory. My rationale is that <code>join</code> only has to deal with two files at a time, so my memory overhead will be lower. </p>
<p>I have tried many different versions of this trying to get <code>subprocess</code> to run. Can anyone explain why this is not working? When I print the <code>cmd</code> and execute it myself on the shell, it runs perfectly.</p>
<pre><code>cmd = "join <(sort %s) <(sort %s)" % (outfile, filename)
with open(out_temp, 'w') as out:
return_code = subprocess.call(cmd, stdout=out, shell=True)
if return_code != 0:
print "not working!"
break
</code></pre>
<p>The error produced looks like this. However, when I have python print <code>cmd</code> and execute it myself on the shell, it runs perfectly.</p>
<pre><code>/bin/sh: -c: line 0: syntax error near unexpected token `('
</code></pre>
<p>I have also tried turning the command into a list, but I'm not sure what the rationale is for how to break up the commands. Can anyone explain? <code>outfile</code> and <code>filename</code> are variables</p>
<pre><code>["join" , "<(sort" , outfile , ") <(sort" , filename , ")"]
</code></pre>
<p>Any help would be appreciated! I'm doing this in Python because I'm heavily parsing filenames upstream to figure out which files to combine.</p>
| 1 | 2016-08-21T03:38:48Z | 39,060,682 | <p><code><(</code> is a <code>bash</code> extension to standard shell syntax. Notice in the error message that it's running <code>/bin/sh</code>, not <code>/bin/bash</code>; even if <code>/bin/sh</code> is a link to <code>/bin/bash</code>, <code>bash</code> drops many of its extensions when it's run using that link.</p>
<p>You can use <code>bash</code> explicitly with:</p>
<pre><code>cmd = "bash -c 'join <(sort %s) <(sort %s)'" % (outfile, filename)
</code></pre>
| 2 | 2016-08-21T03:47:17Z | [
"python",
"unix",
"subprocess"
] |
Python matplotlib install issue on Windows 7 for freetype, png packages | 39,060,669 | <p>Using Python 2.7 on Windows 7. Here is the command I am using to install and error message. Wondering if anyone have met with similar issues before? Thanks.</p>
<pre><code>C:\Python27\Scripts>pip install matplotlib
Collecting matplotlib
Downloading matplotlib-1.5.2.tar.gz (51.6MB)
100% |################################| 51.6MB 19kB/s
Complete output from command python setup.py egg_info:
============================================================================
Edit setup.cfg to change the build options
BUILDING MATPLOTLIB
matplotlib: yes [1.5.2]
python: yes [2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015,
20:40:30) [MSC v.1500 64 bit (AMD64)]]
platform: yes [win32]
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [version 1.11.1]
dateutil: yes [dateutil was not found. It is required for date
axis support. pip/easy_install may attempt to
install it after matplotlib.]
pytz: yes [pytz was not found. pip will attempt to install
it after matplotlib.]
cycler: yes [cycler was not found. pip will attempt to
install it after matplotlib.]
tornado: yes [tornado was not found. It is required for the
WebAgg backend. pip/easy_install may attempt to
install it after matplotlib.]
pyparsing: yes [pyparsing was not found. It is required for
mathtext support. pip/easy_install may attempt to
install it after matplotlib.]
libagg: yes [pkg-config information for 'libagg' could not
be found. Using local copy.]
freetype: no [The C/C++ header for freetype (ft2build.h)
could not be found. You may need to install the
development package.]
png: no [The C/C++ header for png (png.h) could not be
found. You may need to install the development
package.]
qhull: yes [pkg-config information for 'qhull' could not be
found. Using local copy.]
OPTIONAL SUBPACKAGES
sample_data: yes [installing]
toolkits: yes [installing]
tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / mock is
required to run the matplotlib test suite. Please
install it with pip or your preferred tool to run
the test suite]
toolkits_tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / mock is
required to run the matplotlib test suite. Please
install it with pip or your preferred tool to run
the test suite]
OPTIONAL BACKEND EXTENSIONS
macosx: no [Mac OS-X only]
qt5agg: no [PyQt5 not found]
qt4agg: no [PySide not found; PyQt4 not found]
gtk3agg: no [Requires pygobject to be installed.]
gtk3cairo: no [Requires cairocffi or pycairo to be installed.]
gtkagg: no [Requires pygtk]
tkagg: yes [installing; run-time loading from Python Tcl /
Tk]
wxagg: no [requires wxPython]
gtk: no [Requires pygtk]
agg: yes [installing]
cairo: no [cairocffi or pycairo not found]
windowing: yes [installing]
OPTIONAL LATEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
OPTIONAL PACKAGE DATA
dlls: no [skipping due to configuration]
============================================================================
* The following required packages can not be built:
* freetype, png
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\foo\a
ppdata\local\temp\pip-build-zxfsow\matplotlib\
</code></pre>
| 1 | 2016-08-21T03:44:16Z | 39,060,865 | <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<p>Get matplotlib from above location. Choose correct package based on python(2.x/3.x) and bit(32/64) version.</p>
<pre><code>32-bit 2.7: matplotlib-1.5.2-cp27-cp27m-win32.whl
64-bit 2.7: matplotlib-1.5.2-cp27-cp27m-win_amd64.whl
</code></pre>
<p>If you face any issues in the middle, please refer to below link:
<a href="http://stackoverflow.com/a/38618044/5334188">http://stackoverflow.com/a/38618044/5334188</a> </p>
| 2 | 2016-08-21T04:34:50Z | [
"python",
"windows",
"python-2.7",
"matplotlib",
"windows-7"
] |
Python matplotlib install issue on Windows 7 for freetype, png packages | 39,060,669 | <p>Using Python 2.7 on Windows 7. Here is the command I am using to install and error message. Wondering if anyone have met with similar issues before? Thanks.</p>
<pre><code>C:\Python27\Scripts>pip install matplotlib
Collecting matplotlib
Downloading matplotlib-1.5.2.tar.gz (51.6MB)
100% |################################| 51.6MB 19kB/s
Complete output from command python setup.py egg_info:
============================================================================
Edit setup.cfg to change the build options
BUILDING MATPLOTLIB
matplotlib: yes [1.5.2]
python: yes [2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015,
20:40:30) [MSC v.1500 64 bit (AMD64)]]
platform: yes [win32]
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [version 1.11.1]
dateutil: yes [dateutil was not found. It is required for date
axis support. pip/easy_install may attempt to
install it after matplotlib.]
pytz: yes [pytz was not found. pip will attempt to install
it after matplotlib.]
cycler: yes [cycler was not found. pip will attempt to
install it after matplotlib.]
tornado: yes [tornado was not found. It is required for the
WebAgg backend. pip/easy_install may attempt to
install it after matplotlib.]
pyparsing: yes [pyparsing was not found. It is required for
mathtext support. pip/easy_install may attempt to
install it after matplotlib.]
libagg: yes [pkg-config information for 'libagg' could not
be found. Using local copy.]
freetype: no [The C/C++ header for freetype (ft2build.h)
could not be found. You may need to install the
development package.]
png: no [The C/C++ header for png (png.h) could not be
found. You may need to install the development
package.]
qhull: yes [pkg-config information for 'qhull' could not be
found. Using local copy.]
OPTIONAL SUBPACKAGES
sample_data: yes [installing]
toolkits: yes [installing]
tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / mock is
required to run the matplotlib test suite. Please
install it with pip or your preferred tool to run
the test suite]
toolkits_tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / mock is
required to run the matplotlib test suite. Please
install it with pip or your preferred tool to run
the test suite]
OPTIONAL BACKEND EXTENSIONS
macosx: no [Mac OS-X only]
qt5agg: no [PyQt5 not found]
qt4agg: no [PySide not found; PyQt4 not found]
gtk3agg: no [Requires pygobject to be installed.]
gtk3cairo: no [Requires cairocffi or pycairo to be installed.]
gtkagg: no [Requires pygtk]
tkagg: yes [installing; run-time loading from Python Tcl /
Tk]
wxagg: no [requires wxPython]
gtk: no [Requires pygtk]
agg: yes [installing]
cairo: no [cairocffi or pycairo not found]
windowing: yes [installing]
OPTIONAL LATEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
OPTIONAL PACKAGE DATA
dlls: no [skipping due to configuration]
============================================================================
* The following required packages can not be built:
* freetype, png
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\foo\a
ppdata\local\temp\pip-build-zxfsow\matplotlib\
</code></pre>
| 1 | 2016-08-21T03:44:16Z | 39,060,880 | <p>As you can see it <code>png</code> and <code>freetype</code> modules are missing. You need to install them separately.</p>
<p>Try doing the following :</p>
<pre><code>> pip install freetype-py
> pip install pypng
> pip install matplotlib
</code></pre>
| 2 | 2016-08-21T04:37:21Z | [
"python",
"windows",
"python-2.7",
"matplotlib",
"windows-7"
] |
Python matplotlib install issue on Windows 7 for freetype, png packages | 39,060,669 | <p>Using Python 2.7 on Windows 7. Here is the command I am using to install and error message. Wondering if anyone have met with similar issues before? Thanks.</p>
<pre><code>C:\Python27\Scripts>pip install matplotlib
Collecting matplotlib
Downloading matplotlib-1.5.2.tar.gz (51.6MB)
100% |################################| 51.6MB 19kB/s
Complete output from command python setup.py egg_info:
============================================================================
Edit setup.cfg to change the build options
BUILDING MATPLOTLIB
matplotlib: yes [1.5.2]
python: yes [2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015,
20:40:30) [MSC v.1500 64 bit (AMD64)]]
platform: yes [win32]
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [version 1.11.1]
dateutil: yes [dateutil was not found. It is required for date
axis support. pip/easy_install may attempt to
install it after matplotlib.]
pytz: yes [pytz was not found. pip will attempt to install
it after matplotlib.]
cycler: yes [cycler was not found. pip will attempt to
install it after matplotlib.]
tornado: yes [tornado was not found. It is required for the
WebAgg backend. pip/easy_install may attempt to
install it after matplotlib.]
pyparsing: yes [pyparsing was not found. It is required for
mathtext support. pip/easy_install may attempt to
install it after matplotlib.]
libagg: yes [pkg-config information for 'libagg' could not
be found. Using local copy.]
freetype: no [The C/C++ header for freetype (ft2build.h)
could not be found. You may need to install the
development package.]
png: no [The C/C++ header for png (png.h) could not be
found. You may need to install the development
package.]
qhull: yes [pkg-config information for 'qhull' could not be
found. Using local copy.]
OPTIONAL SUBPACKAGES
sample_data: yes [installing]
toolkits: yes [installing]
tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / mock is
required to run the matplotlib test suite. Please
install it with pip or your preferred tool to run
the test suite]
toolkits_tests: yes [nose 0.11.1 or later is required to run the
matplotlib test suite. Please install it with pip or
your preferred tool to run the test suite / mock is
required to run the matplotlib test suite. Please
install it with pip or your preferred tool to run
the test suite]
OPTIONAL BACKEND EXTENSIONS
macosx: no [Mac OS-X only]
qt5agg: no [PyQt5 not found]
qt4agg: no [PySide not found; PyQt4 not found]
gtk3agg: no [Requires pygobject to be installed.]
gtk3cairo: no [Requires cairocffi or pycairo to be installed.]
gtkagg: no [Requires pygtk]
tkagg: yes [installing; run-time loading from Python Tcl /
Tk]
wxagg: no [requires wxPython]
gtk: no [Requires pygtk]
agg: yes [installing]
cairo: no [cairocffi or pycairo not found]
windowing: yes [installing]
OPTIONAL LATEX DEPENDENCIES
dvipng: no
ghostscript: no
latex: no
pdftops: no
OPTIONAL PACKAGE DATA
dlls: no [skipping due to configuration]
============================================================================
* The following required packages can not be built:
* freetype, png
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\foo\a
ppdata\local\temp\pip-build-zxfsow\matplotlib\
</code></pre>
| 1 | 2016-08-21T03:44:16Z | 39,105,374 | <p>I solved it by taking version 1.5.1</p>
<pre><code>pip install matplotlib==1.5.1
</code></pre>
<p>it seems that version 1.5.2 installer is broken.</p>
| 3 | 2016-08-23T15:35:31Z | [
"python",
"windows",
"python-2.7",
"matplotlib",
"windows-7"
] |
Python 3: Regex doesn't work when read text from file | 39,060,721 | <p>The following is my information:</p>
<p>The input:</p>
<pre><code> \"button\" \"button\" href=\"#\" data-id=\"11111111111\" \"button\" \"button\" href=\"#\" data-id=\"222222222222\"
\"button\" \"button\" href=\"#\"
</code></pre>
<p>The output I'd like:</p>
<pre><code>11111111111
222222222222
</code></pre>
<p>My 1st code which worked well: </p>
<pre><code>text = 'data-id=\"11111111111 \" data-id=\"222222222222\" '
c = re.findall('data-id=\\"(.*?)\\"', text)
</code></pre>
<p>My 2nd code which doesn't work. It show nothing</p>
<pre><code>with open("E:/test.txt","r") as f:
text = f.readline()
c = re.findall('data-id=\\"(.*?)\\"', text)
</code></pre>
<p>Why my secondary code doesn't work. Please help me fix it. I highly appreciate you. Thank you :)</p>
| -1 | 2016-08-21T03:57:49Z | 39,060,748 | <p>You can do:</p>
<pre><code>re.findall(r'"([^\\]+)\\"', s)
</code></pre>
<ul>
<li><code>"([^\\]+)</code> matches a <code>"</code>, then the captured grouo contains the desired portion i.e. substring upto next <code>\</code>, <code>\\"</code> makes sure that the portion is followed by <code>\\"</code></li>
</ul>
<p><strong>Example:</strong></p>
<pre><code>In [34]: s
Out[34]: 'randomtext data-id=\\"11111111111\\" randomtext data-id=\\"222222222222\\"'
In [35]: re.findall(r'"([^\\]+)\\"', s)
Out[35]: ['11111111111', '222222222222']
</code></pre>
<hr>
<p><strong>Answer to edited question:</strong></p>
<p>Use <code>\d+</code> to match digits:</p>
<pre><code>re.findall(r'"(\d+)\\"', s)
</code></pre>
<p>to match based on ID instead:</p>
<pre><code>re.findall(r'data-id=\\"([^\\]+)\\"', s)
</code></pre>
<p><strong>Example:</strong></p>
<pre><code>In [45]: s
Out[45]: '\\"button\\" \\"button\\" href=\\"#\\" data-id=\\"11111111111\\" \\"button\\" \\"button\\" href=\\"#\\" data-id=\\"222222222222\\" \\"button\\" \\"button\\" href=\\"#\\"'
In [50]: re.findall(r'"(\d+)\\"', s)
Out[50]: ['11111111111', '222222222222']
In [46]: re.findall(r'data-id=\\"([^\\]+)\\"', s)
Out[46]: ['11111111111', '222222222222']
</code></pre>
| 1 | 2016-08-21T04:04:20Z | [
"python",
"regex",
"file",
"find"
] |
Python 3: Regex doesn't work when read text from file | 39,060,721 | <p>The following is my information:</p>
<p>The input:</p>
<pre><code> \"button\" \"button\" href=\"#\" data-id=\"11111111111\" \"button\" \"button\" href=\"#\" data-id=\"222222222222\"
\"button\" \"button\" href=\"#\"
</code></pre>
<p>The output I'd like:</p>
<pre><code>11111111111
222222222222
</code></pre>
<p>My 1st code which worked well: </p>
<pre><code>text = 'data-id=\"11111111111 \" data-id=\"222222222222\" '
c = re.findall('data-id=\\"(.*?)\\"', text)
</code></pre>
<p>My 2nd code which doesn't work. It show nothing</p>
<pre><code>with open("E:/test.txt","r") as f:
text = f.readline()
c = re.findall('data-id=\\"(.*?)\\"', text)
</code></pre>
<p>Why my secondary code doesn't work. Please help me fix it. I highly appreciate you. Thank you :)</p>
| -1 | 2016-08-21T03:57:49Z | 39,060,952 | <p>Please check this answer. (Added two lines in str_txt.txt file).</p>
<p>Only change I did in your second code is , I have <strong>'r' as prefix in regex</strong>.
For more info on <strong>'r' prefix in regex</strong>, please <a href="http://stackoverflow.com/questions/2241600/python-regex-r-prefix">check here</a> !!!</p>
<pre><code>import re
with open("str_txt.txt","r") as f:
text = f.readlines()
for line in text:
c=[]
c = re.findall(r'data-id=\\"(.*?)\\"', line)
print c
</code></pre>
<p>Output:</p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python demo.Py
['11111111111', '222222222222']
['1111113434111', '222222222222']
</code></pre>
| 1 | 2016-08-21T04:56:12Z | [
"python",
"regex",
"file",
"find"
] |
How to hide ttk Treeitem indicators in a Python GUI | 39,060,756 | <p>I'm building a Python GUI application using ttk treeviews. On Linux, when a Treeitem has child items, it displays an arrow to show that the row can be expanded. I want to hide this indicator arrow (I am using other ways to hint that the row can be expanded). How can I do this?</p>
<p>If I run <code>Style().element_names()</code> I see that there's a Treeview element and a Treeitem.indicator element. If I run <code>Style().configure("Treeview", padding=50)</code>, I see the padding style get applied when I create the treeview, so I feel confident that any style I correctly apply to Treeitem.indicator should be visible also. </p>
<p>Running <code>Style().element_options("Treeitem.indicator")</code>, I see <code>('-foreground', '-indicatorsize', '-indicatormargins')</code>. Running <code>Style().lookup("Treeitem.indicator", "foreground")</code> gives me <code>"#000000"</code>, so it appears that value is initialized. If I try <code>Style().configure("Treeview", foreground="#123456")</code> I don't see the indicator arrow change color, though running <code>Style.lookup("Treeitem.indicator", "foreground")</code> shows me <code>"#123456"</code> as expected. My plan was to set the indicatorsize to 0 to make the arrow go away entirely, but I cannot even successfully edit the color. What am I doing wrong here and is there a better way to hide the indicator? In case it matters, I'm running Python 3.5.0.</p>
| 6 | 2016-08-21T04:06:15Z | 39,259,113 | <p>Not sure if you ever figured it out.</p>
<p>When you create the new style and configure it, you have to change the name of the template to <code>"."</code>. This changes the root style for the treeview. You also need to specify a theme, even if it is <code>default</code>. So it would look something like:</p>
<pre><code>s = ttk.Style()
s.configure(".", indicatorsize = '0')
s.theme_use('default')
</code></pre>
<p>Then when you create the treeview, you shouldn't have to specify a style at all.</p>
<p>Let me know if this works for you.</p>
<p>Edit: Since this is being downvoted for some reason, I'll clarify:</p>
<p>Code with the style part commented out:</p>
<pre><code> #s = ttk.Style()
#s.configure(".", indicatorsize = '0')
#s.theme_use('clam')
j = ttk.Treeview(self.parent)
j.place(relx = 0.5, rely = 0.5, anchor = "center")
j.insert("",1,"jacob",text = "Jacob")
j.insert("jacob",1,"marcus",text = "Marcus")
j.insert("jacob",2,"tony",text = "Tony")
j.insert("jacob",3,"ricardo",text = "Ricardo")
</code></pre>
<p>gives us</p>
<p><a href="http://i.stack.imgur.com/GPxNj.png" rel="nofollow"><img src="http://i.stack.imgur.com/GPxNj.png" alt="enter image description here"></a><a href="http://i.stack.imgur.com/49UBo.png" rel="nofollow"><img src="http://i.stack.imgur.com/49UBo.png" alt="enter image description here"></a></p>
<p>Code with the style part present</p>
<pre><code>s = ttk.Style()
s.configure(".", indicatorsize = '0')
s.theme_use('clam')
j = ttk.Treeview(self.parent)
j.place(relx = 0.5, rely = 0.5, anchor = "center")
j.insert("",1,"jacob",text = "Jacob")
j.insert("jacob",1,"marcus",text = "Marcus")
j.insert("jacob",2,"tony",text = "Tony")
j.insert("jacob",3,"ricardo",text = "Ricardo")
</code></pre>
<p><a href="http://i.stack.imgur.com/Srxhi.png" rel="nofollow"><img src="http://i.stack.imgur.com/Srxhi.png" alt="enter image description here"></a><a href="http://i.stack.imgur.com/ERmMo.png" rel="nofollow"><img src="http://i.stack.imgur.com/ERmMo.png" alt="enter image description here"></a></p>
<p>Hope this helps.</p>
<p>EDIT 2:
Added the <code>s.theme_use('clam')</code> line because you need to specify which theme you're using. It also works with <code>classic</code> and <code>default</code>, but for some reason doesn't work with the <code>vista</code> theme.</p>
| 3 | 2016-08-31T21:14:43Z | [
"python",
"treeview",
"ttk"
] |
Can a Python script in a (sub)module import from upstream in its directory hierarchy? | 39,060,757 | <p>I realize there are a slew of posts on SO related to Python and imports, but it seems like a fair number of these posts are asking about import rules/procedures with respect to creating an actual Python package (vs just a project with multiple directories and python files). I am very new to Python and just need some more basic clarification on what is and is not possible with regard to access/importing within the context of multiple py files in a project directory. </p>
<p>Let's say you have the following project directory (to be clear, this is not a package that is somewhere on sys.path, but say, on your Desktop):</p>
<pre><code>myProject/
âââ __init__.py
âââ scriptA.py
âââ subfolder
âââ __init__.py
âââ scriptB.py
âââ subsubfolder
âââ __init__.py
âââ scriptC.py
âââ foo.py
</code></pre>
<p>Am I correct in understanding that the only way <code>scriptC.py</code> could import and use methods or classes within <code>scriptB.py</code> if <code>scriptC.py</code> is run directly via <code>$ python scriptC.py</code> and from within the <code>subsubfolder</code> directory is if I add the parent directory and path to <code>scriptB.py</code> to the Python path at runtime via <code>sys.path</code> ? </p>
<p>It is possible, however, for <code>scriptC.py</code> to import <code>foo.py</code> or for <code>scriptB.py</code> to import <code>scriptC.py</code> or <code>foo.py</code> without dealing with <code>sys.path</code>, correct? Adjacent py files and py files in subdirectories are accessible just by using relative import paths, you just can't import python scripts that live in parent or sibling directories (without using sys.path) ? </p>
| 1 | 2016-08-21T04:06:31Z | 39,060,829 | <h3>What's Possible</h3>
<p>Anything.</p>
<p>No, really. See <A HREF="https://docs.python.org/2/library/imp.html" rel="nofollow">the <code>imp</code> module</A>, the <A HREF="https://docs.python.org/2/library/imputil.html" rel="nofollow">the <code>imputil</code> module</A> -- take a look at how <A HREF="https://docs.python.org/2/library/zipimport.html" rel="nofollow">the <code>zipimport</code> module</A> is written if you want some inspiration.</p>
<p>If you can get a string with your module's code in a variable, you can get a module into <code>sys.modules</code> using the above, and perhaps hack around with its contents using <A HREF="https://docs.python.org/2/library/ast.html" rel="nofollow">the <code>ast</code> module</A> on the way.</p>
<p>A custom import hook that looks in parent directories? Well within the range of possibilities.</p>
<hr>
<h3>What's Best Practice</h3>
<p>What you're proposing isn't actually good practice. The best-practice approach looks more like the following:</p>
<pre><code>myProject/
âââ setup.py
âââ src/
âââ moduleA.py
âââ submodule/
âââ __init__.py
âââ moduleB.py
âââ subsubmodule/
âââ __init__.py
âââ moduleC.py
</code></pre>
<p>Here, the top of your project is always in <code>myProject/src</code>. If you use <code>setup.py</code> to configure <code>moduleA:main</code>, <code>submodule.moduleB:main</code> and <code>submodule.subsubmodule.moduleC:main</code> as entry points (perhaps named <code>scriptA</code>, <code>scriptB</code> and <code>scriptC</code>), then the functions named <code>main</code> in each of those modules would be invoked when the user ran the (automatically generated by setuptools) scripts so named.</p>
<p>With this layout (and appropriate setuptools use), your <code>moduleC.py</code> can absolutely <code>import moduleA</code>, or <code>import submodule.moduleB</code>.</p>
<hr>
<p>Another approach, which doesn't involve entrypoints, to invoke the code in your <code>moduleC.py</code> (while keeping the module's intended hierarchy intact, and assuming you're in a virtualenv where <code>python setup.py develop</code> has been run) like so:</p>
<pre><code>python -m submodule.subsubmodule.moduleC
</code></pre>
| 1 | 2016-08-21T04:26:10Z | [
"python",
"python-2.7",
"import",
"sys.path"
] |
str.replace not appearing to function properly when target string is contained in a list | 39,060,773 | <p>In my program I have a section of code that looks in one of my computer's directories for pickle files and puts their names in a list using a list comprehension. After this I am attempting to remove the ".pickle" file extension from each of the file names in the list, for reasons unnecessary to explain here. However, after iterating through the list and redefining each element as what it would be when passed into the str.replace built-in function and replacing the ".pickle" string with "", the names in the list do not appear to have changed. Here is my code:</p>
<pre><code>import os
file_names = [file for file in os.listdir("C:/~~/dir") if file.endswith(".pickle")]
for each in file_names:
each = each.replace(".pickle","")
</code></pre>
<p>The one pickle file that I'm using in the early stage of my program's development is the only in the directory.<br>
The program has thrown no errors.<br><br>
The name of the file itself is called "debugger.pickle" and when printing the "file_names" list it prints</p>
<pre><code>['debugger.pickle']
</code></pre>
<p>instead of just</p>
<pre><code>['debugger']
</code></pre>
<p>which is my desired result.</p>
| 1 | 2016-08-21T04:10:43Z | 39,060,799 | <p><code>each = each.replace(".pickle","")</code> creates a new string and binds it to the name <code>each</code>. This has no effect on the original string object in <code>file_names</code>. </p>
<p>If the <code>.replace</code> method mutated its string in-place then </p>
<pre><code>for each in file_names:
each.replace(".pickle","")
</code></pre>
<p>would work, but that code won't actually do what you want because Python strings are immutable. </p>
<p>So you need to save the pruned strings, the simple way to do that is with a list comprehension:</p>
<pre><code>file_names = [each.replace(".pickle","") for each in file_names]
</code></pre>
<p>Note that this replaces the original <code>file_names</code> list object with a new object. If you'd like to instead modify the original <code>file_names</code> object you can do</p>
<pre><code>file_names[:] = [each.replace(".pickle","") for each in file_names]
</code></pre>
<p>That's slightly less efficient (and slower), but it can be useful if you have other objects referring to the original <code>file_names</code> object.</p>
| 3 | 2016-08-21T04:18:18Z | [
"python",
"python-3.x"
] |
str.replace not appearing to function properly when target string is contained in a list | 39,060,773 | <p>In my program I have a section of code that looks in one of my computer's directories for pickle files and puts their names in a list using a list comprehension. After this I am attempting to remove the ".pickle" file extension from each of the file names in the list, for reasons unnecessary to explain here. However, after iterating through the list and redefining each element as what it would be when passed into the str.replace built-in function and replacing the ".pickle" string with "", the names in the list do not appear to have changed. Here is my code:</p>
<pre><code>import os
file_names = [file for file in os.listdir("C:/~~/dir") if file.endswith(".pickle")]
for each in file_names:
each = each.replace(".pickle","")
</code></pre>
<p>The one pickle file that I'm using in the early stage of my program's development is the only in the directory.<br>
The program has thrown no errors.<br><br>
The name of the file itself is called "debugger.pickle" and when printing the "file_names" list it prints</p>
<pre><code>['debugger.pickle']
</code></pre>
<p>instead of just</p>
<pre><code>['debugger']
</code></pre>
<p>which is my desired result.</p>
| 1 | 2016-08-21T04:10:43Z | 39,061,369 | <p>You can't replace items inline; try using map or a list comprehension to recreate the list:</p>
<pre><code>import glob
import os
original_files = glob.glob(r'C:/foo/blah/*.pickle')
files = [os.path.basename(os.path.splitext(i)[0]) for i in original_files]
</code></pre>
<p>You can also combine it:</p>
<pre><code>files = [os.path.basename(os.path.splitext(i)[0]) for i in glob.iglob(r'C:/foo/*.pickle')]
</code></pre>
| 0 | 2016-08-21T06:16:04Z | [
"python",
"python-3.x"
] |
pygame.event.get() is not returning any event | 39,060,855 | <pre><code>import pygame
from pygame.locals import *
...
...
while True:
#comment
for event in pygame.event.get():
if event.type == KEYDOWN:
key_pressed = pygame.key.get_pressed()
#do something
</code></pre>
<p>I replaced <code>#comment</code> with a print statement and found that the <code>for loop</code> is not at all executed i.e, print statement is running infinitely.</p>
<p>What I'm expecting is that, <code>get_pressed()</code> returns the key pressed as soon as the key is pressed, but it's not happening.</p>
<p>What's wrong in the above code and how do I correct it?</p>
<p>EDIT: Adding link to python script file
<a href="https://drive.google.com/open?id=0ByP5h3h0_JHNLTA5OXNOS19sQXM" rel="nofollow">python script</a></p>
| 0 | 2016-08-21T04:32:26Z | 39,067,100 | <p><code>pygame.event.get()</code> grabs all of the events that have registered in the event queue and keeps them in the order they happened. <code>pygame.key.get_pressed()</code> only has the keys that are pressed in that moment. That means that they have to be pressed when your game tries to access them.</p>
<p>You don't need to use both of these methods together. Instead just loop through the events and do something when a key matches one that you want. A common thing is to react to the cursor keys which is shown below:</p>
<pre><code>import pygame
from pygame.locals import *
pygame.init()
...
...
while True:
#comment
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_DOWN:
print('Down was pressed')
if event.key == pygame.K_UP:
print('Up was pressed')
if event.key == pygame.K_RIGHT:
print('Right was pressed')
if event.key == pygame.K_LEFT:
print('Left was pressed')
</code></pre>
| 2 | 2016-08-21T17:45:19Z | [
"python",
"pygame"
] |
How to get the corresponding json data in different { } and [ ] (using Python)? | 39,060,894 | <p>I am trying to use Python Flask to process JSON data.<br>
Here is what my data looks like:</p>
<pre><code>[
{ 'className': 'BoardGame',
'fields': {
'objectId': {'type': 'String'},
'playerName': {'type': 'String'},
'cheatMode': {'type': 'Boolean'},
'score': {'type': 'Number'},
'updatedAt': {'type': 'Date'},
'createdAt': {'type': 'Date'}
},
'classLevelPermissions': {
'addField': {'*': True},
'create': {'*': True}, 'get': {'*': True},
'update': {'*': True}, 'find': {'*': True},
'delete': {'*': True}
}
},
{ 'className': 'RPGGAme',
'fields': {
'objectId': {'type': 'String'},
'GameId': {'type': 'String'},
'robotName': {'type': 'String'},
'updatedAt': {'type': 'Date'},
'createdAt': {'type': 'Date'}
},
'classLevelPermissions': {
'addField': {'*': True},
'create': {'*': True}, 'get': {'*': True},
'fields': {'*': True}, 'find': {'*': True},
'delete': {'*': True}
}
}
]
</code></pre>
<p>The problem is that I cannot get the corresponding data due to the complex format of <code>[]</code> and <code>{}</code></p>
<p><strong>Here is what I want:</strong></p>
<pre><code>[0]["className"]: "BoardGame" <---String
[0]["fields"]: ["objectId","playerName","cheatMode"....] <-- List Of String
[1]["className"]: "RPGGame" <---String
[1]["fields"]: ["objectId","GameId",....] <-- List Of String
</code></pre>
<p>Thus I tried the code here:</p>
<pre><code>def findkeys(node, kv):
if isinstance(node, list):
for i in node:
for x in findkeys(i, kv):
yield x
elif isinstance(node, dict):
if kv in node:
yield node[kv]
for j in node.values():
for x in findkeys(j, kv):
yield x
</code></pre>
<p>However, it can only find the special key's value, but cannot set the range (what I mean by range is that the first "<code>{}</code>" as array 0 + the second "<code>{}</code>" as array 1+ the "fields" in classLevelPermissions won't be involved in the result, in some sense I guess is the depth level ). I still cannot resolve the problem and get what I want. </p>
<p>How can I set the depth and put to corresponding array e.g. [0],[1]?</p>
| -1 | 2016-08-21T04:40:47Z | 39,060,993 | <pre><code>data = [
{ 'className': 'BoardGame',
'fields': {
'objectId': {'type': 'String'},
'playerName': {'type': 'String'},
'cheatMode': {'type': 'Boolean'},
'score': {'type': 'Number'},
'updatedAt': {'type': 'Date'},
'createdAt': {'type': 'Date'}
},
'classLevelPermissions': {
'addField': {'*': True},
'create': {'*': True}, 'get': {'*': True},
'update': {'*': True}, 'find': {'*': True},
'delete': {'*': True}
}
},
{ 'className': 'RPGGAme',
'fields': {
'objectId': {'type': 'String'},
'GameId': {'type': 'String'},
'robotName': {'type': 'String'},
'updatedAt': {'type': 'Date'},
'createdAt': {'type': 'Date'}
},
'classLevelPermissions': {
'addField': {'*': True},
'create': {'*': True}, 'get': {'*': True},
'fields': {'*': True}, 'find': {'*': True},
'delete': {'*': True}
}
}
]
</code></pre>
<p>Try this:</p>
<pre><code>oput = {}
for idx, dict in enumerate(data):
oput[idx] = {}
oput[idx]["className"] = dict["className"]
oput[idx]["fields"] = dict["fields"].keys()
</code></pre>
<p>then:</p>
<pre><code>oput[0]["className"]
>> 'BoardGame'
oput[0]["fields"]
>> ['objectId', 'playerName', 'cheatMode', 'score', 'updatedAt', 'createdAt']
oput[1]["className"]
>> 'RPGGAme'
oput[1]["fields"]
>> ['robotName', 'GameId', 'createdAt', 'objectId', 'updatedAt']
</code></pre>
| 1 | 2016-08-21T05:07:21Z | [
"python",
"json"
] |
Variable issues in if statements | 39,060,948 | <p>I've just started python and I've decided to start with a simple program to parse a single line, two argument mathematical expression directly into an answer. Examples: 4 + 2, 3/4, 5435 * 3423, ect. To start with I'm trying to interpret the two variables in the equation before I work on having the program mathify them. My problem is the lines 39, 40, 42, and 43 are not modifying their respective variables at 1, 3, 2, and 5. In PyCharm, they are greyed out with an error about shadowing names out of scope. </p>
<p>It is currently almost 1AM and I'm not much of a night owl (I'll never make it as a coder lol) so it's probably a stupid mistake on my part but just in case...</p>
<pre><code>primeNumber = None
secNumber = None
num11 = 0
buildList = []
finished = False
def interpret(statement):
i = 0
iMax = len(statement)
while True:
if i >= iMax:
break
parse(statement[i])
i = i + 1
def parse(char, buildList=buildList):
interrupt = [" ", "+", "-", "/", "*"]
if char in interrupt:
buildNumber(buildList)
buildList.clear()
elif num11 == 1:
buildNumber(buildList)
buildList.clear()
else:
buildList.append(char)
def isNumber(att):
try:
int(att)
return True
except ValueError:
return False
def buildNumber(finishedList, num11 = num11):
finishedNumber = ''.join(finishedList)
print(finishedNumber)
if num11 == 0:
primeNumber = finishedNumber # <<< line 39
num11 = 1
elif num11 == 1:
secNumber = finishedNumber
finished = True
</code></pre>
| 0 | 2016-08-21T04:55:36Z | 39,061,995 | <p>In Python variables that are referenced inside a function are assumed to be local if their value is set within the function. To override this default behavior, and set globals from inside a function, you need to declare them with the <code>global</code> statement (only if you want to <em>write</em> them, you don't need to predeclare them to <em>read</em> them.)</p>
<p>Other issues with your code: you randomly mix accessing globals with passing around globals and defaulting to globals -- you should minimize your globals and treat them consistently; pick more descriptive variable names (why expect folks on SO to guess what <code>num11</code> means?); don't reinvent booleans (<code>num11</code> again); you initiate the construction of the second number prematurely.</p>
<p>I've reworked your code with the above issues in mind and added just enough wrapper and glue code to make it run:</p>
<pre><code>firstNumber = None
secondNumber = None
finishedFirst = False
finishedSecond = False
operation = None
operations = {
" ": None,
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"/": lambda a, b: a / b,
"*": lambda a, b: a * b,
}
def interpret(statement):
buildList = []
for character in statement:
parse(character, buildList)
if not finishedSecond:
buildNumber(buildList)
def parse(character, buildList):
global operation
if character in operations:
if buildList:
buildNumber(buildList)
buildList.clear()
if operations[character] is not None:
operation = operations[character]
else:
buildList.append(character)
def buildNumber(finishedList):
global firstNumber, secondNumber, finishedFirst, finishedSecond
finishedNumber = ''.join(finishedList)
if not finishedFirst:
firstNumber = int(finishedNumber)
finishedFirst = True
else:
secondNumber = int(finishedNumber)
finishedSecond = True
statement = input("> ")
interpret(statement)
print(operation(firstNumber, secondNumber))
</code></pre>
<p><strong>EXAMPLE</strong></p>
<pre><code>python3 test.py
> 34 + 56
90
</code></pre>
| 0 | 2016-08-21T07:45:46Z | [
"python",
"variables",
"if-statement"
] |
Determine if line is date, string or int in python | 39,060,991 | <p>My code reads all lines in a textfile and determines if it is a string, int or date.. The problem is reading if it is a datetime.. If I tried to convert it into a datetime object from a string it raises the error:</p>
<pre><code>ValueError: unconverted data remains:
</code></pre>
<p>Here is my code:</p>
<pre><code>with open('file.txt') as input_file:
for i, line in enumerate(input_file):
from datetime import datetime
try:
int(line)
print "This is an integer"
except:
try:
date_object = datetime.strptime(line, '%m-%d-%Y')
print date_object
del date_object
print "This is a date"
except:
print "This is a string"
</code></pre>
<p>My textfile contains:</p>
<pre><code>1
John Doe
08-15-2016
</code></pre>
| 1 | 2016-08-21T05:07:06Z | 39,061,054 | <p>Looks like You forgot to remove '\n'. You can modify a line as below :- </p>
<pre><code>date_object = datetime.strptime(line.strip(), '%m-%d-%Y')
</code></pre>
<p>I hope it will solve the problem</p>
| 4 | 2016-08-21T05:20:55Z | [
"python"
] |
Could not figure out the use of prefetch_related in django | 39,061,107 | <p>There is a scenario where i want to show total purchase of the user. I did using @property inside models of userprofiles. Fortunately, it is working as i expected. But i want to use prefetch_related for optimizing django queries as total purchase of user is calculated from order_history which has ManyToMany Relation with the OrderMenu.</p>
<p><strong>How i did ?</strong></p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
slug = models.SlugField(unique=True,blank=True,null=True)
restaurant = models.ManyToManyField(Restaurant, blank=True)
order_history = models.ManyToManyField(OrderMenu, blank=True)
# favorites = models.ManyToManyField(Restaurant)
is_owner = models.BooleanField(default=False)
@property
def total_purchase(self):
total_purchase = 0
# user_order = UserProfile.objects.prefetch_related('order_history').get(slug=self.slug)
userprofile = UserProfile.objects.get(slug=self.slug)
user_order = userprofile.order_history.all()
for usr in user_order:
total_purchase += usr.get_cost()
return total_purchase
</code></pre>
<blockquote>
<p>In this solution, isn't</p>
<p>userprofile = UserProfile.objects.get(slug=self.slug) user_order =
userprofile.order_history.all()</p>
<p>is equivalent to </p>
<p>user_order=UserProfile.objects.prefetch_related('order_history').get(slug=self.slug)</p>
</blockquote>
<p>I am so much confused with prefetch_related. Could anyone please enlighten me with simple language? Sorry i am non-native English speaker.</p>
| 1 | 2016-08-21T05:28:58Z | 39,061,764 | <p>The difference between the two is</p>
<p>In case of </p>
<p><code>userprofile = UserProfile.objects.get(slug=self.slug)</code> #hits database</p>
<p>This query gets the object of userprofile based on condition from database</p>
<p><code>user_order = userprofile.order_history.all()</code> #hits database again</p>
<p>This query gets user_order queryset using userprofile object hitting database again.</p>
<p>i.e. userprofile hits database as well as user_order</p>
<p>In this case however</p>
<p><code>user_order=UserProfile.objects.prefetch_related('order_history').get(slug=self.slug)</code></p>
<p>user_order queryset set returns not only user profile object but also 'order_history' queryset that is related to UserProfile object in one hit to database. Now when you access 'order_history' querset with user_order object it will not hit database, but gets the queryset of 'order_history' from prefetched QuerySet cache of 'user_order'. more about it <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets" rel="nofollow">here</a>.</p>
| 1 | 2016-08-21T07:13:41Z | [
"python",
"django",
"django-models",
"query-optimization",
"django-orm"
] |
logistic regression feature value normalization in scikit-learn | 39,061,109 | <p>Using Python 2.7. The question is about fit method. Question is for features (provided by parameter <code>X</code>), if there are non-numeric features (e.g. string type features, like <code>Male</code>, <code>Female</code>), do I need, or it is recommended to convert into numeric features (for performance and other reasons)? And also if I have multi-value string type features (e.g. feature geo could be any value of <code>San Francisco</code>, <code>San Jose</code>, <code>Mountain View</code>, etc.)</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.fit" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.fit</a></p>
<p>regards,
Lin</p>
| 0 | 2016-08-21T05:29:27Z | 39,061,168 | <p>You must encode categorical features and convert them to numerical values, if you want to use <code>sklearn</code>. This apples to all <code>sklearn</code> estimators (including <code>LogisticRegression</code>) and it does not matter which version of python you are using. </p>
<p>look at <strong>4.3.4. Encoding categorical features</strong> of <a href="http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features" rel="nofollow">http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features</a> for more information. </p>
| 1 | 2016-08-21T05:39:54Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
logistic regression feature value normalization in scikit-learn | 39,061,109 | <p>Using Python 2.7. The question is about fit method. Question is for features (provided by parameter <code>X</code>), if there are non-numeric features (e.g. string type features, like <code>Male</code>, <code>Female</code>), do I need, or it is recommended to convert into numeric features (for performance and other reasons)? And also if I have multi-value string type features (e.g. feature geo could be any value of <code>San Francisco</code>, <code>San Jose</code>, <code>Mountain View</code>, etc.)</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.fit" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.fit</a></p>
<p>regards,
Lin</p>
| 0 | 2016-08-21T05:29:27Z | 39,061,289 | <p>Just to add a bit to MhFarahani's answer:
Yes, you need to convert those labels to numerical values (generally 0 or 1). For things like gender, you would want to have a row that has 0 for male and 1 for female, or vice versa. For something like geographical location, it'd be a bit more complicated. If there's a reasonable number of possible answers, you could use the get_dummies function in pandas (check the doc <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow">here</a>) to automatically populate your dataframe with rows to represent each possible location; you could then drop one of those rows to make that location the 'default'.</p>
| 1 | 2016-08-21T06:01:18Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
Use request.user in class Index(TemplateView) | 39,061,190 | <p>i'm trying to implement this:</p>
<pre><code>class Index(TemplateView):
if request.user.role == 'admin':
template_name = 'index/admin/index.html'
elif request.user.role == 'ff':
template_name = 'index/firefighter/index.html'
else:
template_name = 'index/dev/index.html'
@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(Index, self).dispatch(*args, **kwargs)
</code></pre>
<p>And i don't have idea that how implement it... Any help? This Code not work have the error: "Undefined name 'request' "</p>
| 0 | 2016-08-21T05:43:21Z | 39,061,467 | <p>Set your template in the <code>get_template_names()</code> method:</p>
<pre><code>from django.utils.decorator import method_decorator
class Index(TemplateView):
def get_template_names(self, *args, **kwargs):
roles_urls = {'admin': 'index/admin/index.html',
'ff': 'index/firefighter/index.html'}
default = 'index/dev/index.html'
return [roles_urls.get(self.request.user.role, default)]
@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(Index, self).dispatch(*args, **kwargs)
</code></pre>
| 2 | 2016-08-21T06:33:08Z | [
"python",
"django",
"django-templates",
"django-views",
"django-rest-framework"
] |
Variable not being assigned value when returned from subprogram? Python 3? | 39,061,280 | <p>I am trying to return a value from my subprogram, but when trying to use the variable in the main program, it comes up with an error saying it has not been assigned a value.</p>
<pre><code>correct = 0
def subprogram():
correct2 = 0
loop = 0
while loop == 0:
loop2 = 0
memberID = input("Please enter your member ID: ")
if memberID == "1495":
print("Login successful!")
loop = 1
correct2 = 1
else:
print("Login unsuccessful.")
while loop2 == 0:
decision = input("<T>ry Again or <E>xit to Menu? ")
if decision == "t" or decision == "T":
print("Ok, restarting.")
print("")
loop2 = 1
elif decision == "e" or decision == "E":
print("Ok, exiting to main menu.")
print("")
loop2 = 1
loop = 1
correct2 = 0
else:
print("-----------------------------------------------------")
print("Sorry, this is not a valid answer. Please try again.")
print("-----------------------------------------------------")
continue
return correct2
#main
while correct == 0:
print ("Are you a member?")
member = input("<Y>es or <N>o? ")
if member == "y":
correct = subprogram()
if correct2 == 0:
correct = 0
elif correct2 == 1:
correct = 1
elif member == "Y":
correct = subprogram()
if correct2 == 0:
correct = 0
elif correct2 == 1:
correct = 1
elif member == "n" or member == "N":
print("Ok, not a problem! Welcome!")
correct = 1
else:
print("-----------------------------------------------------")
print("Sorry, this is not a valid answer. Please try again.")
print("-----------------------------------------------------")
correctVIP = 0
print("END")
</code></pre>
<p>How would I fix this error? Thankyou.</p>
| 0 | 2016-08-21T05:59:18Z | 39,061,375 | <p>In your main <code>while</code> loop you don't define the <code>correct2</code> variable so it throws an error when you try to do:</p>
<pre><code>if correct2 == 0:
</code></pre>
<p>You assign the result of subprogram to <code>correct</code>:</p>
<pre><code>correct = subprogram()
</code></pre>
<p>where you probably mean to do:</p>
<pre><code>correct2 = subprogram()
</code></pre>
| 0 | 2016-08-21T06:17:00Z | [
"python"
] |
Scraping YouTube playlist video links | 39,061,354 | <p>I wanted to download all videos of <a href="https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5" rel="nofollow">this</a> Youtube channel. So I tried to write a script with <code>BeautifulSoup</code> to scrape all the links of the videos. </p>
<p>I did some inspection and found out that the "<code>tr class="pl-video yt-uix-tile</code>" can be used to get the links. This is the Python code:</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
url='https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5'
html=urllib2.urlopen(url)
response=html.read()
soup=BeautifulSoup(response)
res=soup.find_all('tr',class_="pl-video yt-uix-tile ")
print res
</code></pre>
<p>But I am not able to get all the links. The output is empty. What can be done to resolve this?</p>
| 0 | 2016-08-21T06:13:33Z | 39,061,569 | <p>Try this one:</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
htmlParser = "lxml"
url='https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5'
html=urllib2.urlopen(url)
response=html.read()
soup=BeautifulSoup(response, htmlParser)
links = soup.find_all('a', attrs={'class':'pl-video-title-link'})
for a in links:
print(a.get("href"))
</code></pre>
<p>Output:</p>
<blockquote>
<p>/watch?v=SUOWNXGRc6g&list=PL3D7BFF1DDBDAAFE5&index=1<br>
/watch?v=857zrsYZKGo&list=PL3D7BFF1DDBDAAFE5&index=2<br>
/watch?v=Da1jlmwuW_w&list=PL3D7BFF1DDBDAAFE5&index=3<br>
/watch?v=MIKl8PX838E&list=PL3D7BFF1DDBDAAFE5&index=4<br>
/watch?v=sPFUTJgvVpQ&list=PL3D7BFF1DDBDAAFE5&index=5<br>
/watch?v=maYFI5O6P-8&list=PL3D7BFF1DDBDAAFE5&index=6<br>
/watch?v=6moe-rLZKCk&list=PL3D7BFF1DDBDAAFE5&index=7<br>
/watch?v=eKXnQ83RU3I&list=PL3D7BFF1DDBDAAFE5&index=8<br>
/watch?v=WjE-pWYElsE&list=PL3D7BFF1DDBDAAFE5&index=9<br>
/watch?v=hUA_isgpTHI&list=PL3D7BFF1DDBDAAFE5&index=10<br>
/watch?v=IHg_0HJ5iQo&list=PL3D7BFF1DDBDAAFE5&index=11<br>
/watch?v=H92G3CpSQf4&list=PL3D7BFF1DDBDAAFE5&index=12<br>
...</p>
</blockquote>
| 0 | 2016-08-21T06:48:53Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Scraping YouTube playlist video links | 39,061,354 | <p>I wanted to download all videos of <a href="https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5" rel="nofollow">this</a> Youtube channel. So I tried to write a script with <code>BeautifulSoup</code> to scrape all the links of the videos. </p>
<p>I did some inspection and found out that the "<code>tr class="pl-video yt-uix-tile</code>" can be used to get the links. This is the Python code:</p>
<pre><code>import urllib2
from bs4 import BeautifulSoup
url='https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5'
html=urllib2.urlopen(url)
response=html.read()
soup=BeautifulSoup(response)
res=soup.find_all('tr',class_="pl-video yt-uix-tile ")
print res
</code></pre>
<p>But I am not able to get all the links. The output is empty. What can be done to resolve this?</p>
| 0 | 2016-08-21T06:13:33Z | 39,064,649 | <pre><code>from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://www.youtube.com/playlist?list=PL3D7BFF1DDBDAAFE5')
page = r.text
soup=bs(page,'html.parser')
res=soup.find_all('a',{'class':'pl-video-title-link'})
for l in res:
print l.get("href")
</code></pre>
<p>It is giving me output as below in pycharm:</p>
<pre><code>/watch?v=SUOWNXGRc6g&index=1&list=PL3D7BFF1DDBDAAFE5
/watch?v=857zrsYZKGo&index=2&list=PL3D7BFF1DDBDAAFE5
/watch?v=Da1jlmwuW_w&index=3&list=PL3D7BFF1DDBDAAFE5
/watch?v=MIKl8PX838E&index=4&list=PL3D7BFF1DDBDAAFE5
/watch?v=sPFUTJgvVpQ&index=5&list=PL3D7BFF1DDBDAAFE5
/watch?v=maYFI5O6P-8&index=6&list=PL3D7BFF1DDBDAAFE5
/watch?v=6moe-rLZKCk&index=7&list=PL3D7BFF1DDBDAAFE5
/watch?v=eKXnQ83RU3I&index=8&list=PL3D7BFF1DDBDAAFE5
/watch?v=WjE-pWYElsE&index=9&list=PL3D7BFF1DDBDAAFE5
/watch?v=hUA_isgpTHI&index=10&list=PL3D7BFF1DDBDAAFE5
/watch?v=IHg_0HJ5iQo&index=11&list=PL3D7BFF1DDBDAAFE5
/watch?v=H92G3CpSQf4&index=12&list=PL3D7BFF1DDBDAAFE5
/watch?v=B5uJeno3xg8&index=13&list=PL3D7BFF1DDBDAAFE5
/watch?v=hy0mRoT1ZlM&index=14&list=PL3D7BFF1DDBDAAFE5
/watch?v=Xpkbu2GrJpE&index=15&list=PL3D7BFF1DDBDAAFE5
/watch?v=-G91Hp3t6sg&index=16&list=PL3D7BFF1DDBDAAFE5
/watch?v=-zGS_zrL0rY&index=17&list=PL3D7BFF1DDBDAAFE5
/watch?v=4LHIESO0NGk&index=18&list=PL3D7BFF1DDBDAAFE5
/watch?v=8kybpxIixRk&index=19&list=PL3D7BFF1DDBDAAFE5
/watch?v=eHh2Yib7u-A&index=20&list=PL3D7BFF1DDBDAAFE5
/watch?v=zjHYyAJQ7Vw&index=21&list=PL3D7BFF1DDBDAAFE5
/watch?v=ma8aUC-Mf5M&index=22&list=PL3D7BFF1DDBDAAFE5
/watch?v=4MnuiIKCqsQ&index=23&list=PL3D7BFF1DDBDAAFE5
/watch?v=gz6P2E9lkfo&index=24&list=PL3D7BFF1DDBDAAFE5
/watch?v=roulejuE6B8&index=25&list=PL3D7BFF1DDBDAAFE5
/watch?v=NyusGsXc6SQ&index=26&list=PL3D7BFF1DDBDAAFE5
/watch?v=_joTj5XTwuQ&index=27&list=PL3D7BFF1DDBDAAFE5
/watch?v=55G47PgDwkY&index=28&list=PL3D7BFF1DDBDAAFE5
/watch?v=0MkeTcH0SPc&index=29&list=PL3D7BFF1DDBDAAFE5
/watch?v=QjQg8NkHGbw&index=30&list=PL3D7BFF1DDBDAAFE5
/watch?v=2CuTy8SA5kU&index=31&list=PL3D7BFF1DDBDAAFE5
/watch?v=MC2WFgZIZjo&index=32&list=PL3D7BFF1DDBDAAFE5
/watch?v=G_MkSpfKIPA&index=33&list=PL3D7BFF1DDBDAAFE5
/watch?v=Krt3g9HhhZ4&index=34&list=PL3D7BFF1DDBDAAFE5
/watch?v=lIwTbp5N7Hw&index=35&list=PL3D7BFF1DDBDAAFE5
/watch?v=geB8FqcUjo8&index=36&list=PL3D7BFF1DDBDAAFE5
/watch?v=Sqk154QSe8Y&index=37&list=PL3D7BFF1DDBDAAFE5
/watch?v=nq3yUjZGj5c&index=38&list=PL3D7BFF1DDBDAAFE5
/watch?v=8yA0vkjREyI&index=39&list=PL3D7BFF1DDBDAAFE5
/watch?v=AlC_Z5w8nDE&index=40&list=PL3D7BFF1DDBDAAFE5
/watch?v=2jduTfdt8RY&index=41&list=PL3D7BFF1DDBDAAFE5
/watch?v=6AoBM110DAY&index=42&list=PL3D7BFF1DDBDAAFE5
/watch?v=n6xhAVcopYU&index=43&list=PL3D7BFF1DDBDAAFE5
/watch?v=P2tNi1tS0xU&index=44&list=PL3D7BFF1DDBDAAFE5
/watch?v=AEA1qJFpheY&index=45&list=PL3D7BFF1DDBDAAFE5
/watch?v=iA2Efmo2PCA&index=46&list=PL3D7BFF1DDBDAAFE5
/watch?v=0-NTc0ezXes&index=47&list=PL3D7BFF1DDBDAAFE5
/watch?v=jbUQyJdf2P8&index=48&list=PL3D7BFF1DDBDAAFE5
/watch?v=zJ9qzvOOjAM&index=49&list=PL3D7BFF1DDBDAAFE5
/watch?v=wRa5Q2Eloa4&index=50&list=PL3D7BFF1DDBDAAFE5
/watch?v=Df129IGl31I&index=51&list=PL3D7BFF1DDBDAAFE5
/watch?v=SGx03Uqn9JA&index=52&list=PL3D7BFF1DDBDAAFE5
/watch?v=oaNus5QigYA&index=53&list=PL3D7BFF1DDBDAAFE5
/watch?v=fV3cpnNPWo0&index=54&list=PL3D7BFF1DDBDAAFE5
/watch?v=zXXCFmfJMNw&index=55&list=PL3D7BFF1DDBDAAFE5
/watch?v=iFoaqeEtTNU&index=56&list=PL3D7BFF1DDBDAAFE5
/watch?v=UlOM-CUlsBc&index=57&list=PL3D7BFF1DDBDAAFE5
/watch?v=XzTSdfLJt04&index=58&list=PL3D7BFF1DDBDAAFE5
/watch?v=iMe4fW31jMs&index=59&list=PL3D7BFF1DDBDAAFE5
/watch?v=BlKDYBqlfgs&index=60&list=PL3D7BFF1DDBDAAFE5
/watch?v=kOJGmVXuuFA&index=61&list=PL3D7BFF1DDBDAAFE5
/watch?v=wUmId0rwsBQ&index=62&list=PL3D7BFF1DDBDAAFE5
/watch?v=0wy907WZFiA&index=63&list=PL3D7BFF1DDBDAAFE5
/watch?v=ZMcYbf9Hhe4&index=64&list=PL3D7BFF1DDBDAAFE5
/watch?v=yowNavIDzzE&index=65&list=PL3D7BFF1DDBDAAFE5
/watch?v=cJUsL7sc1E8&index=66&list=PL3D7BFF1DDBDAAFE5
/watch?v=Od3xkrxcsE8&index=67&list=PL3D7BFF1DDBDAAFE5
/watch?v=iZMNaPgP4Ak&index=68&list=PL3D7BFF1DDBDAAFE5
/watch?v=PmOtvJqDfqY&index=69&list=PL3D7BFF1DDBDAAFE5
/watch?v=ulFq_0x29sI&index=70&list=PL3D7BFF1DDBDAAFE5
/watch?v=Dmq_WGhJbgI&index=71&list=PL3D7BFF1DDBDAAFE5
/watch?v=S36C23lW5qI&index=72&list=PL3D7BFF1DDBDAAFE5
/watch?v=3r9NGjBvv2w&index=73&list=PL3D7BFF1DDBDAAFE5
/watch?v=ioGWpu8Ud7A&index=74&list=PL3D7BFF1DDBDAAFE5
/watch?v=K7YuusyEvOg&index=75&list=PL3D7BFF1DDBDAAFE5
/watch?v=3OhGkg_XT3o&index=76&list=PL3D7BFF1DDBDAAFE5
/watch?v=G8QK452ynr4&index=77&list=PL3D7BFF1DDBDAAFE5
/watch?v=XVPCXNoiYIg&index=78&list=PL3D7BFF1DDBDAAFE5
/watch?v=m1AeMJux0Zo&index=79&list=PL3D7BFF1DDBDAAFE5
/watch?v=o5LrdSQrWEI&index=80&list=PL3D7BFF1DDBDAAFE5
/watch?v=NcKSFlYEqYY&index=81&list=PL3D7BFF1DDBDAAFE5
/watch?v=N2Tx8S2V8ek&index=82&list=PL3D7BFF1DDBDAAFE5
/watch?v=Iy3wCppq2Yc&index=83&list=PL3D7BFF1DDBDAAFE5
/watch?v=lkadcYQ6SuY&index=84&list=PL3D7BFF1DDBDAAFE5
/watch?v=PQ94MmEg0Qw&index=85&list=PL3D7BFF1DDBDAAFE5
/watch?v=DqNzTaf9g5w&index=86&list=PL3D7BFF1DDBDAAFE5
/watch?v=BWGW8UsO4Hc&index=87&list=PL3D7BFF1DDBDAAFE5
/watch?v=b4MYh6N4z6s&index=88&list=PL3D7BFF1DDBDAAFE5
/watch?v=9xGIlaezMAU&index=89&list=PL3D7BFF1DDBDAAFE5
/watch?v=UC2wAuxECw0&index=90&list=PL3D7BFF1DDBDAAFE5
/watch?v=zRqcoUSbMI0&index=91&list=PL3D7BFF1DDBDAAFE5
/watch?v=D2iMtK8ETGs&index=92&list=PL3D7BFF1DDBDAAFE5
/watch?v=PJL8UChOsSk&index=93&list=PL3D7BFF1DDBDAAFE5
/watch?v=QbD6qwxiEUU&index=94&list=PL3D7BFF1DDBDAAFE5
/watch?v=-ZbdfYleuJU&index=95&list=PL3D7BFF1DDBDAAFE5
/watch?v=JVaGZwuYmck&index=96&list=PL3D7BFF1DDBDAAFE5
/watch?v=5pr7jwYF0JU&index=97&list=PL3D7BFF1DDBDAAFE5
/watch?v=MNCAmgFHcOI&index=98&list=PL3D7BFF1DDBDAAFE5
/watch?v=tXR0AlhNYxQ&index=99&list=PL3D7BFF1DDBDAAFE5
/watch?v=GtWXOzsD5Fw&index=100&list=PL3D7BFF1DDBDAAFE5
</code></pre>
<p>And below output on cmd:</p>
<pre><code>/watch?v=SUOWNXGRc6g&list=PL3D7BFF1DDBDAAFE5&index=1
/watch?v=857zrsYZKGo&list=PL3D7BFF1DDBDAAFE5&index=2
/watch?v=Da1jlmwuW_w&list=PL3D7BFF1DDBDAAFE5&index=3
/watch?v=MIKl8PX838E&list=PL3D7BFF1DDBDAAFE5&index=4
/watch?v=sPFUTJgvVpQ&list=PL3D7BFF1DDBDAAFE5&index=5
/watch?v=maYFI5O6P-8&list=PL3D7BFF1DDBDAAFE5&index=6
/watch?v=6moe-rLZKCk&list=PL3D7BFF1DDBDAAFE5&index=7
/watch?v=eKXnQ83RU3I&list=PL3D7BFF1DDBDAAFE5&index=8
/watch?v=WjE-pWYElsE&list=PL3D7BFF1DDBDAAFE5&index=9
/watch?v=hUA_isgpTHI&list=PL3D7BFF1DDBDAAFE5&index=10
/watch?v=IHg_0HJ5iQo&list=PL3D7BFF1DDBDAAFE5&index=11
/watch?v=H92G3CpSQf4&list=PL3D7BFF1DDBDAAFE5&index=12
/watch?v=B5uJeno3xg8&list=PL3D7BFF1DDBDAAFE5&index=13
/watch?v=hy0mRoT1ZlM&list=PL3D7BFF1DDBDAAFE5&index=14
/watch?v=Xpkbu2GrJpE&list=PL3D7BFF1DDBDAAFE5&index=15
/watch?v=-G91Hp3t6sg&list=PL3D7BFF1DDBDAAFE5&index=16
/watch?v=-zGS_zrL0rY&list=PL3D7BFF1DDBDAAFE5&index=17
/watch?v=4LHIESO0NGk&list=PL3D7BFF1DDBDAAFE5&index=18
/watch?v=8kybpxIixRk&list=PL3D7BFF1DDBDAAFE5&index=19
/watch?v=eHh2Yib7u-A&list=PL3D7BFF1DDBDAAFE5&index=20
/watch?v=zjHYyAJQ7Vw&list=PL3D7BFF1DDBDAAFE5&index=21
/watch?v=ma8aUC-Mf5M&list=PL3D7BFF1DDBDAAFE5&index=22
/watch?v=4MnuiIKCqsQ&list=PL3D7BFF1DDBDAAFE5&index=23
/watch?v=gz6P2E9lkfo&list=PL3D7BFF1DDBDAAFE5&index=24
/watch?v=roulejuE6B8&list=PL3D7BFF1DDBDAAFE5&index=25
/watch?v=NyusGsXc6SQ&list=PL3D7BFF1DDBDAAFE5&index=26
/watch?v=_joTj5XTwuQ&list=PL3D7BFF1DDBDAAFE5&index=27
/watch?v=55G47PgDwkY&list=PL3D7BFF1DDBDAAFE5&index=28
/watch?v=0MkeTcH0SPc&list=PL3D7BFF1DDBDAAFE5&index=29
/watch?v=QjQg8NkHGbw&list=PL3D7BFF1DDBDAAFE5&index=30
/watch?v=2CuTy8SA5kU&list=PL3D7BFF1DDBDAAFE5&index=31
/watch?v=MC2WFgZIZjo&list=PL3D7BFF1DDBDAAFE5&index=32
/watch?v=G_MkSpfKIPA&list=PL3D7BFF1DDBDAAFE5&index=33
/watch?v=Krt3g9HhhZ4&list=PL3D7BFF1DDBDAAFE5&index=34
/watch?v=lIwTbp5N7Hw&list=PL3D7BFF1DDBDAAFE5&index=35
/watch?v=geB8FqcUjo8&list=PL3D7BFF1DDBDAAFE5&index=36
/watch?v=Sqk154QSe8Y&list=PL3D7BFF1DDBDAAFE5&index=37
/watch?v=nq3yUjZGj5c&list=PL3D7BFF1DDBDAAFE5&index=38
/watch?v=8yA0vkjREyI&list=PL3D7BFF1DDBDAAFE5&index=39
/watch?v=AlC_Z5w8nDE&list=PL3D7BFF1DDBDAAFE5&index=40
/watch?v=2jduTfdt8RY&list=PL3D7BFF1DDBDAAFE5&index=41
/watch?v=6AoBM110DAY&list=PL3D7BFF1DDBDAAFE5&index=42
/watch?v=n6xhAVcopYU&list=PL3D7BFF1DDBDAAFE5&index=43
/watch?v=P2tNi1tS0xU&list=PL3D7BFF1DDBDAAFE5&index=44
/watch?v=AEA1qJFpheY&list=PL3D7BFF1DDBDAAFE5&index=45
/watch?v=iA2Efmo2PCA&list=PL3D7BFF1DDBDAAFE5&index=46
/watch?v=0-NTc0ezXes&list=PL3D7BFF1DDBDAAFE5&index=47
/watch?v=jbUQyJdf2P8&list=PL3D7BFF1DDBDAAFE5&index=48
/watch?v=zJ9qzvOOjAM&list=PL3D7BFF1DDBDAAFE5&index=49
/watch?v=wRa5Q2Eloa4&list=PL3D7BFF1DDBDAAFE5&index=50
/watch?v=Df129IGl31I&list=PL3D7BFF1DDBDAAFE5&index=51
/watch?v=SGx03Uqn9JA&list=PL3D7BFF1DDBDAAFE5&index=52
/watch?v=oaNus5QigYA&list=PL3D7BFF1DDBDAAFE5&index=53
/watch?v=fV3cpnNPWo0&list=PL3D7BFF1DDBDAAFE5&index=54
/watch?v=zXXCFmfJMNw&list=PL3D7BFF1DDBDAAFE5&index=55
/watch?v=iFoaqeEtTNU&list=PL3D7BFF1DDBDAAFE5&index=56
/watch?v=UlOM-CUlsBc&list=PL3D7BFF1DDBDAAFE5&index=57
/watch?v=XzTSdfLJt04&list=PL3D7BFF1DDBDAAFE5&index=58
/watch?v=iMe4fW31jMs&list=PL3D7BFF1DDBDAAFE5&index=59
/watch?v=BlKDYBqlfgs&list=PL3D7BFF1DDBDAAFE5&index=60
/watch?v=kOJGmVXuuFA&list=PL3D7BFF1DDBDAAFE5&index=61
/watch?v=wUmId0rwsBQ&list=PL3D7BFF1DDBDAAFE5&index=62
/watch?v=0wy907WZFiA&list=PL3D7BFF1DDBDAAFE5&index=63
/watch?v=ZMcYbf9Hhe4&list=PL3D7BFF1DDBDAAFE5&index=64
/watch?v=yowNavIDzzE&list=PL3D7BFF1DDBDAAFE5&index=65
/watch?v=cJUsL7sc1E8&list=PL3D7BFF1DDBDAAFE5&index=66
/watch?v=Od3xkrxcsE8&list=PL3D7BFF1DDBDAAFE5&index=67
/watch?v=iZMNaPgP4Ak&list=PL3D7BFF1DDBDAAFE5&index=68
/watch?v=PmOtvJqDfqY&list=PL3D7BFF1DDBDAAFE5&index=69
/watch?v=ulFq_0x29sI&list=PL3D7BFF1DDBDAAFE5&index=70
/watch?v=Dmq_WGhJbgI&list=PL3D7BFF1DDBDAAFE5&index=71
/watch?v=S36C23lW5qI&list=PL3D7BFF1DDBDAAFE5&index=72
/watch?v=3r9NGjBvv2w&list=PL3D7BFF1DDBDAAFE5&index=73
/watch?v=ioGWpu8Ud7A&list=PL3D7BFF1DDBDAAFE5&index=74
/watch?v=K7YuusyEvOg&list=PL3D7BFF1DDBDAAFE5&index=75
/watch?v=3OhGkg_XT3o&list=PL3D7BFF1DDBDAAFE5&index=76
/watch?v=G8QK452ynr4&list=PL3D7BFF1DDBDAAFE5&index=77
/watch?v=XVPCXNoiYIg&list=PL3D7BFF1DDBDAAFE5&index=78
/watch?v=m1AeMJux0Zo&list=PL3D7BFF1DDBDAAFE5&index=79
/watch?v=o5LrdSQrWEI&list=PL3D7BFF1DDBDAAFE5&index=80
/watch?v=NcKSFlYEqYY&list=PL3D7BFF1DDBDAAFE5&index=81
/watch?v=N2Tx8S2V8ek&list=PL3D7BFF1DDBDAAFE5&index=82
/watch?v=Iy3wCppq2Yc&list=PL3D7BFF1DDBDAAFE5&index=83
/watch?v=lkadcYQ6SuY&list=PL3D7BFF1DDBDAAFE5&index=84
/watch?v=PQ94MmEg0Qw&list=PL3D7BFF1DDBDAAFE5&index=85
/watch?v=DqNzTaf9g5w&list=PL3D7BFF1DDBDAAFE5&index=86
/watch?v=BWGW8UsO4Hc&list=PL3D7BFF1DDBDAAFE5&index=87
/watch?v=b4MYh6N4z6s&list=PL3D7BFF1DDBDAAFE5&index=88
/watch?v=9xGIlaezMAU&list=PL3D7BFF1DDBDAAFE5&index=89
/watch?v=UC2wAuxECw0&list=PL3D7BFF1DDBDAAFE5&index=90
/watch?v=zRqcoUSbMI0&list=PL3D7BFF1DDBDAAFE5&index=91
/watch?v=D2iMtK8ETGs&list=PL3D7BFF1DDBDAAFE5&index=92
/watch?v=PJL8UChOsSk&list=PL3D7BFF1DDBDAAFE5&index=93
/watch?v=QbD6qwxiEUU&list=PL3D7BFF1DDBDAAFE5&index=94
/watch?v=-ZbdfYleuJU&list=PL3D7BFF1DDBDAAFE5&index=95
/watch?v=JVaGZwuYmck&list=PL3D7BFF1DDBDAAFE5&index=96
/watch?v=5pr7jwYF0JU&list=PL3D7BFF1DDBDAAFE5&index=97
/watch?v=MNCAmgFHcOI&list=PL3D7BFF1DDBDAAFE5&index=98
/watch?v=tXR0AlhNYxQ&list=PL3D7BFF1DDBDAAFE5&index=99
/watch?v=GtWXOzsD5Fw&list=PL3D7BFF1DDBDAAFE5&index=100
</code></pre>
<p>I am using Python 2.7.12 and beautifulsoup4</p>
| -3 | 2016-08-21T13:20:10Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Create daily rolling current highest Value series | 39,061,643 | <p>I have the following data which has a <code>Value</code>, <code>Time</code> and <code>Date</code> column:</p>
<p><a href="http://i.stack.imgur.com/MFs4F.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/MFs4F.jpg" alt="raw_date_img"></a></p>
<p><strong>Desired output</strong></p>
<p>I would like to create a new Series capturing the rows for current highest <code>Value</code> as follows in this example:</p>
<p><a href="http://i.stack.imgur.com/49Bbs.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/49Bbs.jpg" alt="img2"></a></p>
<p>This looks at the <code>Value</code> column each day and captures the recent highest <code>Value</code>. </p>
<ul>
<li>At 9:00 on 1/1/00 the <code>Value</code> was 2 so this was the highest.</li>
<li>At 17:00 on 1/1/00 the <code>Value</code> was 3 so we capture this.</li>
</ul>
<p>Please see df.to_dict() below to reproduce this:</p>
<pre><code> df.to_dict()
{'Date': {0: Timestamp('2000-01-01 00:00:00'),
1: Timestamp('2000-01-01 00:00:00'),
2: Timestamp('2000-01-01 00:00:00'),
3: Timestamp('2000-01-02 00:00:00'),
4: Timestamp('2000-01-02 00:00:00'),
5: Timestamp('2000-01-02 00:00:00'),
6: Timestamp('2000-01-03 00:00:00'),
7: Timestamp('2000-01-03 00:00:00'),
8: Timestamp('2000-01-03 00:00:00'),
9: Timestamp('2000-01-04 00:00:00'),
10: Timestamp('2000-01-04 00:00:00'),
11: Timestamp('2000-01-04 00:00:00')},
'Time': {0: datetime.time(9, 0),
1: datetime.time(13, 0),
2: datetime.time(17, 0),
3: datetime.time(9, 0),
4: datetime.time(13, 0),
5: datetime.time(17, 0),
6: datetime.time(9, 0),
7: datetime.time(13, 0),
8: datetime.time(17, 0),
9: datetime.time(9, 0),
10: datetime.time(13, 0),
11: datetime.time(17, 0)},
'Value': {0: 2,
1: 2,
2: 3,
3: 2,
4: 3,
5: 3,
6: 1,
7: 1,
8: 1,
9: 3,
10: 1,
11: 2}}
</code></pre>
| 1 | 2016-08-21T06:59:17Z | 39,062,775 | <p>IIUC, you need to use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.cummax.html" rel="nofollow"><code>cummax</code></a> to get the cumulative maximum for the <code>Value</code> column followed by dropping off duplicated entries after grouping them w.r.t <code>Date</code> column.</p>
<pre><code>grouped = df.groupby('Date').apply(lambda x: x['Value'].cummax() \
.drop_duplicates()) \
.reset_index()
print(df[df.index.isin(grouped['level_1'])])
Date Time Value
0 2000-01-01 09:00:00 2
2 2000-01-01 17:00:00 3
3 2000-01-02 09:00:00 2
4 2000-01-02 13:00:00 3
6 2000-01-03 09:00:00 1
9 2000-01-04 09:00:00 3
</code></pre>
| 1 | 2016-08-21T09:29:08Z | [
"python",
"pandas"
] |
Show if restaurant is open or closed based on weekday, opening and closing time | 39,061,718 | <p>I have a model of restaurant and operating time which has foreign key relation.
for example a restaurant ocean view cafe whose operating time in each week day is </p>
<p>Friday - 10am - 6:30pm</p>
<p>Thursday - 10 am - 9:45 pm</p>
<p>Wednesday - 10 am - 9:45 pm</p>
<p>Tuesday - 10 am - 9:45 pm</p>
<p>Monday - 10 am - 9:45 pm</p>
<p>Sunday - 10 am - 8 pm</p>
<p>I could only check based on opening and closing time like this</p>
<p>models.py</p>
<pre><code>class OperatingTime(models.Model):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
DAY_IN_A_WEEK = (
(MONDAY, 'Monday'),
(TUESDAY, 'Tuesday'),
(WEDNESDAY, 'Wednesday'),
(THURSDAY, 'Thursday'),
(FRIDAY, 'Friday'),
(SATURDAY, 'Saturday'),
(SUNDAY, 'Sunday'),
)
# HOURS = [(i, i) for i in range(1, 25)]
restaurant = models.ForeignKey(Restaurant,related_name="operating_time")
opening_time = models.TimeField()
closing_time = models.TimeField()
day_of_week = models.IntegerField(choices=DAY_IN_A_WEEK)
@property
def open_or_closed(self):
operating_time = OperatingTime.objects.all()
opening_time = operating_time.opening_time
closing_time = operating_time.closing_time
current_time = datetime.now().time()
weekday = operating_time.day_of_week
if opening_time < current_time < closing_time:
open_or_closed = True
else:
open_or_closed = False
return open_or_closed
@property
def open_or_closed(self):
operating_time = OperatingTime.objects.all()
opening_time = operating_time.opening_time
closing_time = operating_time.closing_time
current_time = datetime.now().time()
weekday = operating_time.day_of_week
if opening_time < current_time < closing_time:
open_or_closed = True
else:
open_or_closed = False
return self.open_or_closed
</code></pre>
<p>How can i find if restaurant is open or closed on each day for all the restaurant?</p>
| 0 | 2016-08-21T07:09:34Z | 39,074,515 | <p>Not tested but it should work.</p>
<pre><code>class OperatingTimeManager(models.Manager):
# Use a model manager when accesing table data, use model methods only for row operations
def get_open_restaurants(self, date=datetime.datetime.now()):
# get the id's of open restaurants
open_restaurants_ids = self.get_queryset().filter(opening_time__lte=date, closing_time__gt=date).values_list('restaurant__id', flat=True)
# get the actual restaurants instances
return Restaurant.objects.filter(id__in=open_restaurants_ids)
class OperatingTime(models.Model):
closing_time = fields.DateTimeField()
opening_time = fields.DateTimeField()
restaurant = fields.ForeignKey(Restaurant)
objects = OperatingTimeManager()
</code></pre>
| 0 | 2016-08-22T08:22:12Z | [
"python",
"django",
"python-3.x",
"django-models"
] |
python, import package from parent dir | 39,061,805 | <p>My project tree is like this:</p>
<pre><code>maindir\
dir1\
MAINSCRIPT.py
dir2\
scriptA.py
</code></pre>
<p>The <code>MAINSCRIPT.py</code> is my main script!</p>
<p>How can I import <code>scriptA.py</code> from <code>MAINSCRIPT.py</code></p>
| 1 | 2016-08-21T07:19:36Z | 39,061,904 | <p>Well this isn't technical a python package in the first place or it would have an <code>__init__.py</code> in each folder. And also I'm confused why you would have your main program in one of your folders. But something that I've used often to import a file that isn't in Python's regularly checked paths is </p>
<pre><code>import sys; sys.path.insert(0, '../dir2'); import scriptA
</code></pre>
<p>Hope that helps!
For more info: <a href="http://askubuntu.com/questions/470982/how-to-add-a-python-module-to-syspath" title="more on path insertion">more on path insertion</a></p>
| 2 | 2016-08-21T07:33:17Z | [
"python",
"import",
"package"
] |
python, import package from parent dir | 39,061,805 | <p>My project tree is like this:</p>
<pre><code>maindir\
dir1\
MAINSCRIPT.py
dir2\
scriptA.py
</code></pre>
<p>The <code>MAINSCRIPT.py</code> is my main script!</p>
<p>How can I import <code>scriptA.py</code> from <code>MAINSCRIPT.py</code></p>
| 1 | 2016-08-21T07:19:36Z | 39,062,079 | <p>The following nice solution is from <a href="http://www.napuzba.com/story/import-error-relative-no-parent/" rel="nofollow">ImportError: attempted relative import with no known parent package</a></p>
<p>You can use relative imports. First change your directory structure as follows:</p>
<pre><code>maindir\
main.py
lib\
__init__.py
dir1\
__init__.py
MAINSCRIPT.py
dir2\
__init__.py
scriptA.py
</code></pre>
<p><strong>maindir\lib\dir1\MAINSCRIPT.py</strong></p>
<pre><code>from ..dir2 import scriptA
...
</code></pre>
<p><strong>maindir\main.py</strong></p>
<pre><code>import lib.dir1.MAINSCRIPT
</code></pre>
<p>Now, we can invoke the script from <code>maindir\</code>:</p>
<pre><code>python main.py
</code></pre>
| 1 | 2016-08-21T07:57:59Z | [
"python",
"import",
"package"
] |
Function call on individual field save in django | 39,061,819 | <p>Say I have a model:</p>
<pre><code>class Workplace(models.Model):
name = models.CharField(max_length=255)
...
office_mail_id = models.EmailField(null=True, blank=True)
</code></pre>
<p>What I want is whenever the value of email is changed and the object is saved, a function should be run which would save the value of that field to other models (say Emails)</p>
<p>Now, this can be done in many ways like creating a custom save function which would call the email saving function or otherwise making a custom function and save emails through it:</p>
<pre><code>def set_email(self, email):
self.office_mail_id = email
self.save()
# do whatever i want
return
</code></pre>
<p>What i want to know is that is there a simpler way to do this so that whenever i run </p>
<pre><code>company.office_mail_id = request.POST.get('email')
company.save()
</code></pre>
<p>in a view, the function may be run saving it to other models as i want</p>
<p>The problem here is that I am not saving all fields individually but making a dictionary and saving all fields based on key and values like this as there are so many fields:</p>
<pre><code>for key in dictionary:
setattr(workplace, key, dictionary[key])
workplace.save()
</code></pre>
<p>What can be the best way to do it?</p>
| 0 | 2016-08-21T07:21:51Z | 39,061,864 | <p>Just override <code>save</code> in <code>Workplace</code>:</p>
<pre><code>def save(self, *args, **kwargs):
# do whatever you need, save other models etc..
super().save(*args, **kwargs)) # or super(Workplace, self).save(*args, **kwargs)
# if Python 2
</code></pre>
| 1 | 2016-08-21T07:27:52Z | [
"python",
"django",
"django-models"
] |
How can I 'cycle' through list items when using classes in python pygame to change object colors? | 39,061,843 | <p>I have drawn a caterpillar using <code>pygame.draw</code> and it's color is set as <code>self.color_scheme[0]</code> For example.</p>
<pre><code>self.color_scheme = [red,yellow,purple]
...
...
pygame.draw.ellipse(screen, self.color_scheme[0], [x, y, 40, 45])
</code></pre>
<p>What I'm trying to enable is that when the user presses a key, lets say <code>s</code> then the color will change to <code>self.color_scheme[1]</code> or <code>self.color_scheme[2]</code></p>
<p>Something along the lines of</p>
<pre><code> if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
#scroll through self.color_scheme or randomly select a color
</code></pre>
| 0 | 2016-08-21T07:25:16Z | 39,062,348 | <p>To cycle:</p>
<pre><code>self.color_scheme_idx = -1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
self.color_scheme_idx += 1
pygame.draw.ellipse(screen, self.color_scheme[self.color_scheme_idx], [x, y, 40, 45])
</code></pre>
<p>To randomize:</p>
<pre><code>import random
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
pygame.draw.ellipse(screen, random.choice(self.color_scheme), [x, y, 40, 45])
</code></pre>
| 1 | 2016-08-21T08:31:52Z | [
"python",
"pygame"
] |
Python-Firebase (401) Unauthorised error | 39,061,866 | <p>Been trying to retrieve data from my firebase however I keep getting <code>HTTPError: 401 Client Error: Unauthorized.</code> Been using <a href="https://pypi.python.org/pypi/python-firebase/1.2" rel="nofollow">https://pypi.python.org/pypi/python-firebase/1.2</a> as a guide. Tried adjusting the authentication code but got nowhere. How would I retrieve data from my firebase</p>
<pre><code>from firebase import firebase
firebase = firebase.FirebaseApplication('(my firebase url)',None)
result = firebase.get('/User',None)
print (result)
</code></pre>
| 0 | 2016-08-21T07:28:05Z | 39,713,101 | <p>Go to in Firebase Console > Database >Rules and change </p>
<pre><code> ".read": "auth != null",
".write": "auth != null"
</code></pre>
<p>to:</p>
<pre><code>".read": "auth == null",
".write": "auth == null"
</code></pre>
| 0 | 2016-09-26T22:01:47Z | [
"python",
"authentication",
"firebase",
"firebase-database"
] |
Why does my variable resets it's value? | 39,061,875 | <p>I am making a small Python console RPG. I have a very basic fighting system in place, but the health values of my <code>player</code> and <code>enemy</code> keep resetting after they've taken damage. Any ideas as to why this is happening? I think it might have something to do with my variables not being <code>global</code> or not being declared properly, but I can't find the mistake (I don't really understand how global variables works in Python). I did some testing ( as you can see by the <code># Testing</code> comments), and the <code>attack()</code> function does take the health away but when it returns to the <code>fight()</code> function the health is back to 100% for both variables.</p>
<pre><code>import sys
import os
import random
def clear(): return os.system('clear')
# Program
class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
self.health_stat = "{}/{}".format(self.health, self.max_health)
class Goblin:
def __init__(self, name):
self.name = name
self.max_health = 50
self.health = self.max_health
self.attack = 2
self.health_stat = "{}/{}".format(self.health, self.max_health)
goblin = Goblin("Goblin")
# all other enemies are the same as the Goblin
enemies = [wolf, goblin, rat, bandit]
# New game
def start0():
global player
player = Player('Mark')
start1()
def start1():
clear()
print("Name: {}\n"
"Health: {}\n"
"".format(player.name, player.health_stat,))
print(".1) Fight\n"
".4) Exit\n")
selection = input("-> ")
if selection == "1":
select_enemy_to_fight()
fight()
elif selection == "4":
sys.exit()
def select_enemy_to_fight():
global enemy
enemy = random.choice(enemies)
# Actions
def attack():
clear()
playerAttack = random.randint(0, player.attack)
enemyAttack = random.randint(0, enemy.attack)
#player attack
if playerAttack == 0:
print("You miss!")
else:
enemy.health -= playerAttack
print("You dealt {} damage!".format(playerAttack))
# Testing
print("PH = ", player.health)
print("EH = ", enemy.health)
input(" ")
if enemy.health <= 0:
win()
clear()
# Enemy attack
if enemyAttack == 0:
print("The enemy missed!")
else:
player.health -= enemyAttack
print("The enemy dealt {} damage!".format(enemyAttack))
# Testing
print("PH = ", player.health)
print("EH = ", enemy.health)
input(" ")
# clear()
dead() if player.health <= 0 else fight()
def fight():
global enemy
global player
clear()
print("{} vs {}".format(player.name, enemy.name))
print("{}'s Health: {} {}'s Health: {}".format(player.name, player.health_stat, enemy.name, enemy.health_stat))
print(".1) Attack\n"
".3) Run Away\n")
selection = input("-> ")
if selection == "1":
attack()
elif selection == "3":
run()
main()
</code></pre>
| 0 | 2016-08-21T07:29:49Z | 39,062,092 | <p>Could you try mark the variables global in <code>attack</code> function, as you d in <code>fight</code> and see?</p>
| 0 | 2016-08-21T07:59:55Z | [
"python",
"python-3.x",
"global-variables"
] |
Why does my variable resets it's value? | 39,061,875 | <p>I am making a small Python console RPG. I have a very basic fighting system in place, but the health values of my <code>player</code> and <code>enemy</code> keep resetting after they've taken damage. Any ideas as to why this is happening? I think it might have something to do with my variables not being <code>global</code> or not being declared properly, but I can't find the mistake (I don't really understand how global variables works in Python). I did some testing ( as you can see by the <code># Testing</code> comments), and the <code>attack()</code> function does take the health away but when it returns to the <code>fight()</code> function the health is back to 100% for both variables.</p>
<pre><code>import sys
import os
import random
def clear(): return os.system('clear')
# Program
class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
self.health_stat = "{}/{}".format(self.health, self.max_health)
class Goblin:
def __init__(self, name):
self.name = name
self.max_health = 50
self.health = self.max_health
self.attack = 2
self.health_stat = "{}/{}".format(self.health, self.max_health)
goblin = Goblin("Goblin")
# all other enemies are the same as the Goblin
enemies = [wolf, goblin, rat, bandit]
# New game
def start0():
global player
player = Player('Mark')
start1()
def start1():
clear()
print("Name: {}\n"
"Health: {}\n"
"".format(player.name, player.health_stat,))
print(".1) Fight\n"
".4) Exit\n")
selection = input("-> ")
if selection == "1":
select_enemy_to_fight()
fight()
elif selection == "4":
sys.exit()
def select_enemy_to_fight():
global enemy
enemy = random.choice(enemies)
# Actions
def attack():
clear()
playerAttack = random.randint(0, player.attack)
enemyAttack = random.randint(0, enemy.attack)
#player attack
if playerAttack == 0:
print("You miss!")
else:
enemy.health -= playerAttack
print("You dealt {} damage!".format(playerAttack))
# Testing
print("PH = ", player.health)
print("EH = ", enemy.health)
input(" ")
if enemy.health <= 0:
win()
clear()
# Enemy attack
if enemyAttack == 0:
print("The enemy missed!")
else:
player.health -= enemyAttack
print("The enemy dealt {} damage!".format(enemyAttack))
# Testing
print("PH = ", player.health)
print("EH = ", enemy.health)
input(" ")
# clear()
dead() if player.health <= 0 else fight()
def fight():
global enemy
global player
clear()
print("{} vs {}".format(player.name, enemy.name))
print("{}'s Health: {} {}'s Health: {}".format(player.name, player.health_stat, enemy.name, enemy.health_stat))
print(".1) Attack\n"
".3) Run Away\n")
selection = input("-> ")
if selection == "1":
attack()
elif selection == "3":
run()
main()
</code></pre>
| 0 | 2016-08-21T07:29:49Z | 39,062,226 | <p>Just found the problem:</p>
<pre><code>class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
self.health_stat = "{}/{}".format(self.health, self.max_health)
</code></pre>
<p><code>self.health_stat</code> is using the original <code>self.health</code>, so after <code>self.health</code> changes <code>self.health_stat</code> remains the same.</p>
<p>I made this solution:</p>
<pre><code>class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
def health_stat(self):
return "{}/{}".format(self.health, self.max_health)
</code></pre>
| 0 | 2016-08-21T08:16:32Z | [
"python",
"python-3.x",
"global-variables"
] |
Why matplotlib plot a graph have ticks line off-axis ï¼ | 39,061,930 | <p>I use matplotlib plot graph on OS X system,the top left corner ticks line have off-axis distributionï¼but,on windows,there is no this problem.how to deal with this problemï¼</p>
<p><a href="http://i.stack.imgur.com/XhpyZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/XhpyZ.png" alt="enter image description here"></a></p>
| 1 | 2016-08-21T07:37:06Z | 39,073,530 | <p>I Have work out this problem,</p>
<p>1.savefig() do not support the jpg,tif ,so if save the graph use this format, the graph tick line will off-axis.if save the graph use png,eps,svg,the graph will have no this problem</p>
<p>2.show graph program have a bug on OS X system, no matter which format of graph you save,it will always show tick line off-axis.</p>
| 0 | 2016-08-22T07:25:21Z | [
"python",
"osx",
"matplotlib"
] |
Looping dict[key] into gui interface, removing, and replacing | 39,061,986 | <p>So I have this code for Python 2.7 which calculates word frequencies (any optimizations are welcome). </p>
<pre><code>import Tkinter as tk
def let_freq():
user_input = e.get()
alphabet = {
'a': 0,'b': 1,'c': 2,'d': 3,
'e': 4,'f': 5,'g': 6,'h': 7,
'i': 8,'j': 9,'k': 10,'l': 11,
'm': 12,'n': 13,'o': 14,'p': 15,
'q': 16,'r': 17,'s': 18,'t': 19,
'u': 20,'v': 21,'w': 22,'x': 23,'y': 2,'z': 25}
value_alphabet = {
'a': 0,'b': 0,'c': 0,'d': 0,
'e': 0,'f': 0,'g': 0,'h': 0,
'i': 0,'j': 0,'k': 0,'l': 0,
'm': 0,'n': 0,'o': 0,'p': 0,
'q': 0,'r': 0,'s': 0,'t': 0,
'u': 0,'v': 0,'w': 0,'x': 0,'y': 0,'z': 0}
letters = []
count = 0
for character in user_input:
letters.append(character)
for item in letters:
for key, val in alphabet.items():
if key is item:
value_alphabet[key] += 1
for key in value_alphabet:
if value_alphabet[key] > 0:
count += value_alphabet[key]
for key in sorted(value_alphabet):
if value_alphabet[key] > 0:
print value_alphabet[key], ',', key, '-', float(value_alphabet[key])/count*100, '%'
root = tk.Tk()
e = tk.Entry(root)
assert type(e)
e.grid(ipadx=5,ipady=5)
button = tk.Button(root, text='Letterfrequency',command=let_freq).grid(ipadx=5, ipady=5)
root.mainloop()
</code></pre>
<p>Now, the problem is displaying the</p>
<pre><code>print value_alphabet[key], ',', key, '-', float(value_alphabet[key])/count*100, '%'
</code></pre>
<p>in a Tkinter Label or any other appropriate Tkinter widget and I'd like to know how to actively edit a Label within the loop, remove them if the <code>user_input</code> variable changes, and (this should come naturally) display the information of the new entry in <code>user_input</code> (<code>e</code> prior to the '<code>e.get()</code>' section).</p>
<p>(i.e. if you input 'banana', you should get a-50%, n-33.333333333%, b-16.666666666%...it is word frequency)</p>
| 0 | 2016-08-21T07:44:45Z | 39,062,165 | <p>When setting up a Label, you can give it a <code>tkinter.StringVar</code> as it's text variable. Then, whenever you update the variable, the Label will update automatically:</p>
<pre><code>from tkinter import *
from time import sleep
root = Tk()
labeltext = StringVar()
labeltext.set('hello')
label = Label(root, textvariable = labeltext)
label.pack()
for i in range(10):
labeltext.set(str(i))
root.update_idletasks()
sleep(1) #slow it down so that the changes are visible
</code></pre>
<p>This code will update the label inside the for loop. Now, you just need to <code>labeltext.set(str(user_input))</code> and you will get the user input on the label.</p>
| 1 | 2016-08-21T08:08:08Z | [
"python",
"python-2.7",
"tkinter"
] |
Looping dict[key] into gui interface, removing, and replacing | 39,061,986 | <p>So I have this code for Python 2.7 which calculates word frequencies (any optimizations are welcome). </p>
<pre><code>import Tkinter as tk
def let_freq():
user_input = e.get()
alphabet = {
'a': 0,'b': 1,'c': 2,'d': 3,
'e': 4,'f': 5,'g': 6,'h': 7,
'i': 8,'j': 9,'k': 10,'l': 11,
'm': 12,'n': 13,'o': 14,'p': 15,
'q': 16,'r': 17,'s': 18,'t': 19,
'u': 20,'v': 21,'w': 22,'x': 23,'y': 2,'z': 25}
value_alphabet = {
'a': 0,'b': 0,'c': 0,'d': 0,
'e': 0,'f': 0,'g': 0,'h': 0,
'i': 0,'j': 0,'k': 0,'l': 0,
'm': 0,'n': 0,'o': 0,'p': 0,
'q': 0,'r': 0,'s': 0,'t': 0,
'u': 0,'v': 0,'w': 0,'x': 0,'y': 0,'z': 0}
letters = []
count = 0
for character in user_input:
letters.append(character)
for item in letters:
for key, val in alphabet.items():
if key is item:
value_alphabet[key] += 1
for key in value_alphabet:
if value_alphabet[key] > 0:
count += value_alphabet[key]
for key in sorted(value_alphabet):
if value_alphabet[key] > 0:
print value_alphabet[key], ',', key, '-', float(value_alphabet[key])/count*100, '%'
root = tk.Tk()
e = tk.Entry(root)
assert type(e)
e.grid(ipadx=5,ipady=5)
button = tk.Button(root, text='Letterfrequency',command=let_freq).grid(ipadx=5, ipady=5)
root.mainloop()
</code></pre>
<p>Now, the problem is displaying the</p>
<pre><code>print value_alphabet[key], ',', key, '-', float(value_alphabet[key])/count*100, '%'
</code></pre>
<p>in a Tkinter Label or any other appropriate Tkinter widget and I'd like to know how to actively edit a Label within the loop, remove them if the <code>user_input</code> variable changes, and (this should come naturally) display the information of the new entry in <code>user_input</code> (<code>e</code> prior to the '<code>e.get()</code>' section).</p>
<p>(i.e. if you input 'banana', you should get a-50%, n-33.333333333%, b-16.666666666%...it is word frequency)</p>
| 0 | 2016-08-21T07:44:45Z | 39,062,237 | <p>A few tweaks on your function before getting to the question at hand. You're doing a bunch of stuff you don't really need to, and can pare this down quite a bit.</p>
<p>First of all, your <code>value_alphabet</code> is just a reimplemented <code>collections.Counter</code>. Use that instead.</p>
<pre><code>from collections import Counter
...
value_alphabet = Counter()
</code></pre>
<p>You're also doing some funky low-level stuff that A) isn't necessary in Python and B) isn't the best way to do that in Python even if it were necessary. I'm talking about</p>
<pre><code>letters = []
for character in user_input:
letters.append(character)
</code></pre>
<p>This is just</p>
<pre><code>letters = list(user_input)
</code></pre>
<p>But since you can iterate directly over a string, you don't need <code>letters</code> AT ALL. Remove it. Similarly <code>count</code> is just <code>len(user_input)</code>. All you do is loop over each letter and count them up. Toss it. Now your function looks like:</p>
<pre><code>def let_freq():
user_input = e.get()
alphabet = {
'a': 0,'b': 1,'c': 2,'d': 3,
'e': 4,'f': 5,'g': 6,'h': 7,
'i': 8,'j': 9,'k': 10,'l': 11,
'm': 12,'n': 13,'o': 14,'p': 15,
'q': 16,'r': 17,'s': 18,'t': 19,
'u': 20,'v': 21,'w': 22,'x': 23,'y': 2,'z': 25}
value_alphabet = Counter()
for item in user_input:
for key,val in alphabet.items():
if key is item:
value_alphabet[key] += 1
</code></pre>
<p>That loop there is pretty ugly. You're neglecting the best part of dictionaries: O(1) lookups! You don't need to do the double loop. <code>if key is item</code> is bad for other reasons, but I won't go into that here since identity vs equality isn't really in the same kettle of fish as this (and it doesn't affect functionality here. Just know that 'somestring is somestring' isn't always <code>True</code>.)</p>
<pre><code> for ch in user_input: # changed the loopvar here to sound better
value_alphabet[ch] += alphabet[ch]
# look it up directly.
</code></pre>
<p>If you're worried about the user_input including invalid characters, use <code>dict.get</code> instead to default to zero.</p>
<pre><code> for ch in user_input:
value_alphabet += alphabet.get(ch, 0)
# if ch isn't in alphabet, do value_alphabet += 0
</code></pre>
<p>Sweet! We're almost sorted now. Let's move on. Since we've done away with your <code>count</code> variable, we can skip the next <code>for key in value_alphabet</code> loop since it only populates <code>count</code>. For your last bit, you can shorten your code by doing:</p>
<pre><code>for key,val in sorted(value_alphabet.items()):
if val > 0:
print val, ',', key, '-', float(val * 100 / len(user_input)), '%'
</code></pre>
<hr>
<p>Now for your question about changing a label? You're looking for callbacks. You should probably roll this into its own class rather than just have it hanging out in the middle of nowhere, but let's talk about binding a callback to the user entry changing. The easiest way to do this is using <code>tk.StringVar</code> and its <code>trace</code> method.</p>
<pre><code>root = tk.Tk()
e_stringvar = tk.StringVar()
e = tk.Entry(root, textvariable=e_stringvar)
e_stringvar.trace('w', some_func)
</code></pre>
<p>This binds <code>e_stringvar</code> together with your <code>tk.Entry</code> widget, storing the contents of <code>e</code> in <code>e_stringvar</code>. Furthermore it binds some unknown function <code>some_func</code> to <code>e_stringvar</code> so that every time <code>e_stringvar</code> has something written to it (e.g. <code>e</code> has changed due to user entry), it calls <code>some_func</code>. We could define <code>some_func</code> as something like:</p>
<pre><code>f = tk.Label(root)
f.pack()
e.pack() # whatever, pack everything
def some_func(*args, **kwargs):
text = e_stringvar.get()
f.configure(text=text)
# change the f label so it's displaying the same text as the entry
</code></pre>
<p>I've defined <code>some_func</code> to take arguments, because I honestly forget if the <code>tk.StringVar.trace</code> callback functions get passed the event that triggered them. We're not using them, but if you don't allow it to be passed you'll get ArgumentErrors.</p>
<hr>
<p>I've written a bit of (Py3) code somewhat recently that uses this concept to track a <code>tk.Entry</code> field and use it to filter a text list. The relevant code is on bitbucket <a href="https://bitbucket.org/darimart/find-paperwork/src/3e03b8982152c557b3ae6c92368e60b3bd935092/views/frames.py?at=master&fileviewer=file-view-default" rel="nofollow">findppw.views.frames</a> (the FilterFrame class) and <a href="https://bitbucket.org/darimart/find-paperwork/src/3e03b8982152c557b3ae6c92368e60b3bd935092/app.pyw?at=master&fileviewer=file-view-default" rel="nofollow">findppw.app</a> (line 38 instantiates FilterFrame and names its callback func)</p>
| 1 | 2016-08-21T08:18:29Z | [
"python",
"python-2.7",
"tkinter"
] |
How can I enter multiple commands at once in the python console | 39,061,989 | <p>I'm trying to enter several commands in the python console all at once for the purpose of testing. <br>For example:</p>
<pre><code>userInput = None
while userInput != 'end':
userInput = input('$ ')
userInput = userInput.strip()
if userInput == 'one':
print('all')
elif userInput == 'two':
print('at')
elif userInput == 'three':
print('once')
</code></pre>
<p>Is it possible to enter "one" then without touching the keyboard again "two" then "three".<br>Something along the lines of:<br><br>one\rtwo\rthree\r<br><br>Thanks for the help in advance!!!</p>
| 3 | 2016-08-21T07:45:02Z | 39,062,121 | <p>just create a text file named <code>input.txt</code> like this:</p>
<pre><code>one
two
three
end
</code></pre>
<p>and call your script like this:</p>
<pre><code>python myscript.py < file.txt
</code></pre>
| 1 | 2016-08-21T08:04:09Z | [
"python",
"console",
"arguments",
"automated-tests"
] |
How can I enter multiple commands at once in the python console | 39,061,989 | <p>I'm trying to enter several commands in the python console all at once for the purpose of testing. <br>For example:</p>
<pre><code>userInput = None
while userInput != 'end':
userInput = input('$ ')
userInput = userInput.strip()
if userInput == 'one':
print('all')
elif userInput == 'two':
print('at')
elif userInput == 'three':
print('once')
</code></pre>
<p>Is it possible to enter "one" then without touching the keyboard again "two" then "three".<br>Something along the lines of:<br><br>one\rtwo\rthree\r<br><br>Thanks for the help in advance!!!</p>
| 3 | 2016-08-21T07:45:02Z | 39,062,239 | <p>I recommend inputs from @Jean-Francois Fabre and @Abhirath Mahipal. </p>
<p>But this is just another option, if your inputs are limited.</p>
<pre><code>userInput = raw_input('$ ')
userInput = userInput.strip()
for each in userInput.split('\\r'):
if each == 'one':
print('all')
elif each == 'two':
print('at')
elif each == 'three':
print('once')
elif each == 'exit':
break
</code></pre>
<p>Here is the execution:</p>
<pre><code>python test.py
$ one\rtwo\rthree\rexit
all
at
once
</code></pre>
<p>Note: python 3 users should replace <code>raw_input</code> by <code>input</code></p>
| 1 | 2016-08-21T08:18:44Z | [
"python",
"console",
"arguments",
"automated-tests"
] |
How can I enter multiple commands at once in the python console | 39,061,989 | <p>I'm trying to enter several commands in the python console all at once for the purpose of testing. <br>For example:</p>
<pre><code>userInput = None
while userInput != 'end':
userInput = input('$ ')
userInput = userInput.strip()
if userInput == 'one':
print('all')
elif userInput == 'two':
print('at')
elif userInput == 'three':
print('once')
</code></pre>
<p>Is it possible to enter "one" then without touching the keyboard again "two" then "three".<br>Something along the lines of:<br><br>one\rtwo\rthree\r<br><br>Thanks for the help in advance!!!</p>
| 3 | 2016-08-21T07:45:02Z | 39,062,396 | <p>Occasionally I like hacking <code>input</code> so I can just test by hitting F5 in IDLE. In your case you could for example add this before your code:</p>
<pre><code>def input(prompt, inputs=iter('one two three end'.split())):
x = next(inputs)
print(prompt + x)
return x
</code></pre>
<p>Then you don't need to type any input. The output is:</p>
<pre><code>$ one
all
$ two
at
$ three
once
$ end
</code></pre>
| 2 | 2016-08-21T08:38:16Z | [
"python",
"console",
"arguments",
"automated-tests"
] |
Sending email using python through postfix | 39,062,015 | <p>When I send emails through postfix, headers always contain one extra hop that I would like to get rid of. Here are the headers:</p>
<pre><code>From admin@mta.emailcab.com Sat Aug 20 18:40:58 2016
Return-Path: <admin@mta.emailcab.com>
X-Original-To: oneprovider@prosolutionmail.com
Delivered-To: oneprovider@prosolutionmail.com
Received: from mta.emailcab.com (mta.emailcab.com [52.58.223.55])
by prosolutionmail.com (Postfix) with ESMTP id 75F5B23C0AC7
for <oneprovider@prosolutionmail.com>; Sat, 20 Aug 2016 18:40:58 +0200 (CEST)
Authentication-Results: prosolutionmail.com; dkim=pass
reason="2048-bit key; unprotected key"
header.d=mta.emailcab.com header.i=@mta.emailcab.com
header.b=mXAsVoW+; dkim-adsp=pass; dkim-atps=neutral
Received: from [127.0.0.1] (localhost [127.0.0.1])
by mta.emailcab.com (Postfix) with ESMTP id 0585383189
for <oneprovider@prosolutionmail.com>; Sat, 20 Aug 2016 16:40:58 +0000 (UTC)
DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple; d=mta.emailcab.com;
s=key1; t=1471711258;
bh=BUn1x+fCFHl9Q+e98U5epKcL5xZNNNU3Lq/zNz0IMnI=;
h=Subject:From:To:Date:From;
b=mXAsVoW+IYePOdDe1d7OyQdYpRzNoKdYclLEv/wXm3dDjJulDMfr5HM274U1ypNNs
OCqK5TNRo4UMrFqIcU38BVjOIwN3gPOStxs3jSEmoWLXynIAuclbNew692P2KY7jkn
oU7lhPZ1CwBln+qEKKXbyuiXtRmbA2Qp1pvLu+R9T/WfPzWiVhe+2CPq9ob3j3mwBW
oBjLNvmbm74eenMKxv8G47FBi7HS4+9eSuUI9TVV0fb/qZwNHwumpFeTA5DPRzkQPM
u5imAbdz5GqXxs4wo4UXTpWEb7dSkzJu7/2ebLshCnnuSoN8HV5j79GEoidyzmqEpC
saF1XA+rJvKwg==
Content-Type: multipart/alternative; boundary="===============5118095836845773678=="
MIME-Version: 1.0
Subject: =?utf-8?b?0JrQsNC6INC00L7QsdGA0LDRgtGM0YHRjyDQtNC+INCb0YzQstC+0LLQsD8=?=
From: admin@mta.emailcab.com
To: oneprovider@prosolutionmail.com
Message-Id: <20160820164058.0585383189@mta.emailcab.com>
Date: Sat, 20 Aug 2016 16:40:58 +0000 (UTC)
</code></pre>
<p>As you can see, there are two "Received" headers, one of outgoing IP and a local one. How can I send the email so that only public ip will be visible?</p>
<p>The python code is something like that:</p>
<pre><code>import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
smtp = smtplib.SMTP()
smtp.connect('localhost')
msgRoot = MIMEMultipart("alternative")
msgRoot['Subject'] = Header("Subject subject", "utf-8")
msgRoot['From'] = "admin@example.com"
msgRoot['To'] = "foo@bar.com"
text = MIMEText(open('template.txt', 'r').read(), "plain", "utf-8")
msgRoot.attach(text)
html = MIMEText(open('template.html', 'r').read(), "html", "utf-8")
msgRoot.attach(html)
smtp.sendmail("admin@example.com", "foo@bar.com", msgRoot.as_string())
</code></pre>
| 0 | 2016-08-21T07:48:33Z | 39,062,990 | <p>It shouldn't be fixed in python, I don't believe it can be anyway. SMTP uses the "addressed envelope"(To:,From:). The <code>Received From</code> value you are referencing isn't a python issue its a Postfix configuration issue., Think of it like TCP, you don't see the encapsulation/de-encapsulation which would be the difference, but it still occurs. When you view the raw message you are seeing the SMTP communication between your server and theirs. </p>
<p>You need to take a look at your Postfix config. </p>
<p>There is a value in your <code>/etc/postfix/main.cf</code> that you can change that will.. should... change that value you are seeing. </p>
<p>find:</p>
<pre><code>myhostname = ???
</code></pre>
<p>I am assuming yours is set to localhost.
Are you using MySQL or PostgreSQL? If you are there should be a <code>users</code> and a <code>virtual_alias</code> table setup, the value of <code>myhostname</code> should correspond to one of those objects in the table.</p>
<p>Could you post your main.cf file? </p>
<p>Are the users on the same server as you?</p>
| 0 | 2016-08-21T10:00:48Z | [
"python",
"email",
"postfix"
] |
Django Model Form - Not Valid without any errors | 39,062,172 | <p>I am writing a test for a Django Form. I am populating it with initial data. But when i save the form i get the error that it does not have cleaned_data attribute.</p>
<p>This may happen because the form does not validate but it does not show any errors either.</p>
<p>here is the code.</p>
<pre><code>def test_keyw(self):
class BlogPostKeywordCheck(forms.ModelForm):
class Meta:
model = BlogPost
exclude = ()
data = {'keywords': 'awwww,aaa,lol'}
initial_data = {
"title":"Test Keywords",
"content":"<p>Testing Keywords</p>",
"status":CONTENT_STATUS_PUBLISHED,
"keywords":"call,me,abc",
"user":self._user,
"allow_comments":"on",
"gen_description":"on",
"in_sitemap":"on",
"_save":"Save"
}
print (self._user)
submitted_form = BlogPostKeywordCheck(initial=initial_data)
print (submitted_form.fields)
submitted_form.instance.user = self._user
print("Instance Title",submitted_form.instance.title)
print("Valid: ",submitted_form.is_valid())
print ("Errors: ",submitted_form.errors)
submitted_form.save()
print (Keyword.objects.all())
self.assertTrue(submitted_form.is_valid())
print (submitted_form.errors)
</code></pre>
<p>Currently the O/P is</p>
<pre><code>Creating test database for alias 'default'...
test
OrderedDict([('title', <django.forms.fields.CharField object at 0x05185CF0>), ('slug', <django.forms.fields.CharField object at 0x05185BD0>), ('_meta_title', <django.forms.fields.CharField object at 0x05185ED0>), ('description', <django.forms.fields.CharField object at 0x05185E10>), ('gen_description', <django.forms.fields.BooleanField object at 0x05185C10>), ('keywords', <django.forms.fields.CharField object at 0x05185CD0>), ('status', <django.forms.fields.TypedChoiceField object at 0x05185C50>), ('publish_date', <django.forms.fields.DateTimeField object at 0x05185B10>), ('expiry_date', <django.forms.fields.DateTimeField object at 0x05185D90>), ('short_url', <django.forms.fields.URLField object at 0x05185AD0>), ('in_sitemap', <django.forms.fields.BooleanField object at 0x05185FD0>), ('content', <django.forms.fields.CharField object at 0x05182E50>), ('user', <django.forms.models.ModelChoiceField object at 0x05182350>), ('categories', <django.forms.models.ModelMultipleChoiceField object at 0x051820D0>), ('allow_comments', <django.forms.fields.BooleanField object at 0x051821F0>), ('featured_image', <filebrowser_safe.fields.FileBrowseFormField object at 0x05182310>), ('related_posts', <django.forms.models.ModelMultipleChoiceField object at 0x051822B0>)])
(u'Instance Title', u'')
(u'Valid: ', False)
(u'Errors: ', {})
Destroying test database for alias 'default'...
Process finished with exit code 1
Error
Traceback (most recent call last):
File "F:\Projects\GIT\mezzanine\build\build1\mezzanine\generic\tests.py", line 226, in test_keyw
submitted_form.save()
File "C:\Python27\lib\site-packages\django\forms\models.py", line 449, in save
self._save_m2m()
File "C:\Python27\lib\site-packages\django\forms\models.py", line 416, in _save_m2m
cleaned_data = self.cleaned_data
AttributeError: 'BlogPostKeywordCheck' object has no attribute 'cleaned_data'
</code></pre>
<p>And also if I don't add the user_id explicitly in the instance, it tells me that the User_id cannot be null. Doesn't work if i put it in the initial data.</p>
| 1 | 2016-08-21T08:09:32Z | 39,062,256 | <p>You haven't passed any data to the form, only initial values. Therefore the form is not bound and cannot be valid.</p>
| 2 | 2016-08-21T08:20:34Z | [
"python",
"django"
] |
Python-Kivy: on_touch_down() defined to specific children affects on all childrens | 39,062,299 | <p>I want to make an android-lock like thing, so I have 2 Images of the button (the button normal, the the button pressed).</p>
<p>I defined a function on_touch_down on every image, so when I press it, it changes the source to the pressed button, and on_touch_up it changes it back to normal. But every time I press on any part of the screen, it changes all the buttons at once.</p>
<p>How can I make it change just each button when I press it, and not change everything when I press anywhere?</p>
<p>here is my kv file:</p>
<pre><code>Manager:
Principal:
<Principal>:
GridLayout:
cols: 3
Image:
id: '1'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '2'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '3'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '4'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '5'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '6'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '7'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '8'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
Image:
id: '9'
size: 30,30
source: 'button.png'
on_touch_down: self.source = 'button_press.png'
on_touch_up: self.source = 'button.png'
allow_strech: True
</code></pre>
| 0 | 2016-08-21T08:27:18Z | 39,062,465 | <p>Instead of defining <code>on_touch_*</code> event handlers, define a clickable image class with help of the <code>ButtonBehavior</code>:</p>
<pre><code>from kivy.uix.behaviors.button import ButtonBehavior
class ClickableImage(ButtonBehavior, Image):
def on_press(self):
pass
def on_release(self):
pass
</code></pre>
<p>Now, you can use it in your kv file. There are other behaviors, you can check them <a href="https://kivy.org/docs/api-kivy.uix.behaviors.html#module-kivy.uix.behaviors" rel="nofollow">here</a>.</p>
| 0 | 2016-08-21T08:48:46Z | [
"python",
"kivy",
"kivy-language"
] |
Google Cloud Datastore API in Python Code | 39,062,334 | <p>I am trying to Implement Google Cloud DataStore in my Python Django Project not running on Google App Engine.</p>
<p>Can it be possible to use Google Datastore without having the project run on Google App Engine ? If yes, Can you please tell how to retrieve the complete entity object or execute the query successfully ?</p>
<p>The below code snippet prints the query object but throws an error after that. </p>
<p>Code Snippet: </p>
<pre><code>from gcloud import datastore
entity_kind = 'EntityKind'
numeric_id = 1234
client = datastore.Client()
key = client.key(entity_kind, numeric_id)
query = client.query(kind=entity_kind)
print(query)
results = list(query.fetch())
print(results)
</code></pre>
<p>Error: </p>
<pre><code>NotFound: 404 The project gproj does not exist or it does not contain an active App Engine application. Please visit http://console.developers.google.com to create a project or https://console.developers.google.com/appengine?project=gproj to add an App Engine application. Note that the app must not be disabled.
</code></pre>
| 1 | 2016-08-21T08:30:06Z | 39,158,527 | <p>This <a href="https://cloud.google.com/python/getting-started/using-cloud-datastore" rel="nofollow">guide</a> will probably be helpful. You can see an example of it in action <a href="https://github.com/GoogleCloudPlatform/getting-started-python/blob/master/2-structured-data/bookshelf/model_datastore.py" rel="nofollow">here</a>.</p>
<p>You just need to pass a project id to the <code>.Client()</code> method:</p>
<pre><code>datastore.Client("YOUR_PROJECT_ID")
</code></pre>
<p>You can also skip this part by running this command before running your app:</p>
<pre><code>$ gcloud beta auth application-default login
</code></pre>
<p>If you run that, it will authenticate all of your requests locally without injecting the project id :)</p>
<p>Hope this helps!</p>
| 1 | 2016-08-26T04:57:19Z | [
"python",
"google-app-engine",
"google-cloud-storage",
"google-cloud-platform",
"google-app-engine-python"
] |
Does read(size) have a built in pointer? | 39,062,336 | <p>I found this code here which monitors the progress of downloads. -</p>
<pre><code>import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
</code></pre>
<p>I do not see the block size being modified at any point in the <code>while</code> loop, so, to me, <code>buffer = u.read(block_sz)</code> should keep reading the same thing over and over again.</p>
<p>We know this doesn't happen, is it because <code>read()</code> in <code>while</code> loop has a built in pointer that starts reading from where you left off last time?</p>
<p>What about <code>write()</code>? Does it keep appending after where it last left off, even though the file is not opened in append mode? </p>
| -1 | 2016-08-21T08:30:14Z | 39,062,413 | <p>File objects and network sockets and other forms of I/O communication are <em>data streams</em>. Reading from them always produces the <em>next</em> section of data, calling <code>.read()</code> with a buffer size does not re-start the stream from the beginning.</p>
<p>So yes, there is a virtual 'position' in streams where you are reading from.</p>
<p>For files, that position is called the file pointer, and this pointer advances both for reading and writing. You can alter the position by using <a href="https://docs.python.org/2/library/stdtypes.html#file.seek" rel="nofollow"><em>seeking</em></a>, or by simply re-opening the file. You can ask a file object to <a href="https://docs.python.org/2/library/stdtypes.html#file.tell" rel="nofollow"><em>tell</em></a> you the current position, too.</p>
<p>For network sockets however, you can only go forward; the data is received from outside your computer and reading consumes that data.</p>
| 1 | 2016-08-21T08:41:22Z | [
"python",
"io"
] |
Pandas sql equivalent | 39,062,388 | <p>I've got a <code>pd.dataframe</code> with following fields: <code>id, value</code> (multiple values per id).</p>
<p>What is the <code>pandas</code> equivalent of <code>sql query</code>:</p>
<pre><code>SELECT id, Max(value)-Min(value) AS val1
FROM t1
GROUP BY t1.id
</code></pre>
| 1 | 2016-08-21T08:37:11Z | 39,062,416 | <p>you can do it this way:</p>
<pre><code>In [31]: df = pd.DataFrame(np.random.randint(0, 5, (10, 2)), columns=['id','value'])
In [32]: df
Out[32]:
id value
0 2 4
1 4 0
2 3 1
3 4 2
4 4 1
5 2 3
6 1 0
7 3 2
8 2 2
9 1 1
In [33]: df.groupby('id')['value'].apply(lambda x: x.max() - x.min()).reset_index()
Out[33]:
id value
0 1 1
1 2 2
2 3 1
3 4 2
</code></pre>
<p>Here is <a href="http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html" rel="nofollow">Pandas comparison with SQL</a> with lots of examples - this might be useful</p>
| 1 | 2016-08-21T08:41:35Z | [
"python",
"pandas"
] |
Opencv has found image that doesn't exist on screen | 39,062,403 | <p>I try to use opencv for search button location on screen. If button exist on screen opencv work perfect but it return some !=0 x,y even if image doesn't exist. How to fix it?</p>
<pre><code>import cv2
def buttonlocation(image):
im = ImageGrab.grab()
im.save('screenshot.png')
img = cv2.imread(image,0)
img2 = img.copy()
template = cv2.imread('screenshot.png',0)
w,h = template.shape[::-1]
meth = 'cv2.TM_SQDIFF'
img = img2.copy()
method = eval(meth)
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = min_loc
x,y = top_left
return x,y
</code></pre>
| -1 | 2016-08-21T08:39:18Z | 39,066,916 | <p>The <a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html" rel="nofollow">documentation of opencv</a> details to two steps of the template matching procedure.</p>
<ol>
<li><code>R=cv2.matchTemplate(I,T,method)</code> computes an image <code>R</code>. Each pixel <code>x,y</code> of this image represents a mark depending on the similarity between the template <code>T</code> and the sub-image of <code>I</code> starting at <code>x,y</code>. For instance, if the method <code>cv.TM_SQDIFF</code> is applied, the mark is computed as:</li>
</ol>
<p><img src="https://latex.codecogs.com/gif.latex?R%28x%2Cy%29%3D%5Csum_%7Bx%27%2Cy%27%7D%28T%28x%27%2Cy%27%29-I%28x+x%27%2Cy+y%27%29%29%5E2" alt="enter image description here"></p>
<p>If <code>R[x,y]</code> is null, then the sub-image <code>I[x:x+sxT,y:y+syT]</code> is exactly identical to the template <code>T</code>. The smaller <code>R[x,y]</code> is, the closer to the template the sub-image is. </p>
<ol start="2">
<li><code>cv2.minMaxLoc(R)</code> is applied to find the minimum of <code>R</code>. The corresponding subimage of <code>I</code> is expected to closer to the template than any other sub-image of <code>I</code>.</li>
</ol>
<p>If the image <code>I</code> does not contain the template, the sub-image of <code>I</code> corresponding to the minimum of <code>R</code> can be very different from <code>T</code>. But the value of the minimum reflects this ! <strong>Indeed, a threshold on <code>R</code> can be applied as a way to decide whether the template is in the image or not.</strong> </p>
<p>Choosing the value for the threshold is a tricky task. It could be a fraction of the maximum value of <code>R</code> or a fraction of the mean value of R. The influence of the size of the template can be discarted by dividing <code>R</code> by the <code>sxT*syT</code>. For instance, the maximum value of <code>R</code> depends on the template size and the type of the image. For instance, for CV_8UC3 (unsigned char, 3 channels) the maximum value of <code>R</code> is <code>255*3*sxT*syT</code>.</p>
<p>Here is an example:</p>
<pre><code>import cv2
img = cv2.imread('image.jpg',eval('cv2.CV_LOAD_IMAGE_COLOR'))
template = cv2.imread('template.jpg',eval('cv2.CV_LOAD_IMAGE_COLOR'))
cv2.imshow('image',img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
meth = 'cv2.TM_SQDIFF'
method = eval(meth)
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = min_loc
x,y = top_left
h,w,c=template.shape
print 'R='+str( min_val)
if min_val< h*w*3*(20*20):
cv2.rectangle(img,min_loc,(min_loc[0] + w,min_loc[1] + h),(0,255,0),3)
else:
print 'first template not found'
template = cv2.imread('template2.jpg',eval('cv2.CV_LOAD_IMAGE_COLOR'))
res = cv2.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = min_loc
x,y = top_left
h,w,c=template.shape
print 'R='+str( min_val)
if min_val< h*w*3*(20*20):
cv2.rectangle(img,min_loc,(min_loc[0] + w,min_loc[1] + h),(0,0,255),3)
else:
print 'second template not found'
cv2.imwrite( "result.jpg", img);
cv2.namedWindow('res',0)
cv2.imshow('res',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>The image:
<a href="http://i.stack.imgur.com/WzziU.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/WzziU.jpg" alt="enter image description here"></a></p>
<p>The first template is to be found:
<a href="http://i.stack.imgur.com/wgSiG.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/wgSiG.jpg" alt="enter image description here"></a></p>
<p>The second template is not to be found:
<a href="http://i.stack.imgur.com/iT64l.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/iT64l.jpg" alt="enter image description here"></a></p>
<p>The result:
<a href="http://i.stack.imgur.com/zPgFe.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/zPgFe.jpg" alt="enter image description here"></a></p>
| 0 | 2016-08-21T17:26:19Z | [
"python",
"python-2.7",
"python-3.x"
] |
Django: how to send argument in HtpResponseRedirect | 39,062,448 | <p><strong>Views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from .models import studentDetails
from .forms import loginForm
# Create your views here.
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def auth_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
q = studentDetails.objects.get(name=username)
if q.password==password:
return HttpResponseRedirect("/student/accounts/loggedin")
return HttpResponseRedirect("/studemt/accounts/invalid")
def loggedin(request):
username = request.GET.get("username")
return render(request, "loggedin.html", {"full_name": username})
def invalid(request):
return render(request, "invalid_login.html")
def logout(request):
return render(request, "logout.html")
</code></pre>
<p><strong>Urls.py</strong></p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from .views import (
login,
auth_view,
loggedin,
logout
)
urlpatterns = [
url(r"^accounts/login/$", login , name="login"),
url(r"^accounts/auth/$", auth_view ,name="auth_view"),
url(r"^accounts/loggedin/$", loggedin , name="loggedin"),
url(r"^accounts/logout/$", logout, name="logout"),
]
</code></pre>
<p>i want to send username from auth_view to loggedin view but i don'y know how to do that.
i have used <code>username = request.GET.get("username")</code> but it is not working.
i want to show username in url also such that it looks like <code>/student/username/</code>
where username will change as different user login.</p>
| 0 | 2016-08-21T08:46:59Z | 39,062,559 | <p>You should pass parameter in url first: </p>
<pre><code>url(r'^student/(?P<username>\w+)/$', views.userpage, name='userpage)
</code></pre>
<p>But better use <code>pk</code> field or something with <code>name</code> + <code>pk</code>, as url parametr, because username can be duplicate.<br>
Now you can pass this parameter in view and don't hardcore url, use <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/" rel="nofollow">reverse</a> with url name instead. </p>
<pre><code>def auth_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
q = studentDetails.objects.get(name=username)
if q.password==password:
return HttpResponseRedirect(reverse('userpage', args=[q.username]))
return HttpResponseRedirect(reverse('invalid'))
</code></pre>
| 0 | 2016-08-21T09:01:53Z | [
"python",
"django",
"django-templates",
"django-views",
"django-urls"
] |
Python syslog - view syslog messages | 39,062,464 | <p>I'm running the following code:
# create logger
logger = logging.getLogger("myApp")
logger.setLevel(logging.DEBUG)</p>
<pre><code># create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# add ch to logger
logger.addHandler(ch)
logger.debug('debug sample message')
</code></pre>
<p>Now, on a different python script, I'd like to read those messages (that belongs to "myApp", from syslog) - how can I do so???</p>
<p>Thanks a lot,
Efrat</p>
| 0 | 2016-08-21T08:48:46Z | 39,062,561 | <p>you can read as file :</p>
<pre><code>important = []
keep_phrases = ["test",
"important",
"warning"]
with open("log.log" 'r') as f:
for line in f:
for phrase in keep_phrases:
if phrase in line:
important.append(line)
print line
break
print(important)
</code></pre>
| 0 | 2016-08-21T09:01:58Z | [
"python"
] |
Python TIC TAC TOE skipping turns | 39,062,521 | <p>I am working on a tic-tac-toe program in python. Now, the Human's turn work's fine. However, the AI, after playing the first turn, does not play any further turns. I have scanned through the code and cannot seem to find any errors that can cause this. </p>
<p>Please ignore the comments and the part that deals with ties. I am still working on that. </p>
<pre><code>import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
print("--------")
print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
print("--------")
print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])
def choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
#printboard(the_board)
if board_full(the_board) == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
#if loop_break == 6:
#continue
if turn == "hum":
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
#printboard(the_board)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
loop_break = 7
break
else:
turn = "comp"
printboard(the_board)
continue
else:
copied_board = copy_board(the_board)
for i in range(1,10):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,i,comp)
printboard(the_board)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break == 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
printboard(the_board)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
printboard(the_board)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
printboard(the_board)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
printboard(the_board)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
</code></pre>
| 1 | 2016-08-21T08:56:32Z | 39,062,840 | <p>In a word, the problem of your AI is that <em>it chose the same position all the times</em>, which seems like "not playing any further turns".</p>
<p>To prove that, simply add a <code>print</code> in the for-loop of your AI:</p>
<pre><code>for i in range(1,10):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,i,comp)
print("The AI chose #%d"%i) # <-- here it is
printboard(the_board)
# ......
</code></pre>
<p>And here's the result.</p>
<pre><code>welcome to TIC TAC TOE
What do you want to be; X or O?X
You chose X
Tossing to see who goes first.....
Human goes first
Enter the number1
| |
--------
| |
--------
X | |
The AI chose #3
| |
--------
| |
--------
X | |O
Enter the number2
| |
--------
| |
--------
X |X |O
The AI chose #3
| |
--------
| |
--------
X |X |O
Enter the number
</code></pre>
<p>I can't give a specific advice to solve this bug, as I totally didn't get the point of this AI <em>#=_=</em> (maybe you should use <a href="http://neverstopbuilding.com/minimax" rel="nofollow">MiniMax</a>). But anyway, your AI shouldn't place pieces at the same position.</p>
<p>ps. you might need to change <code>system.exit()</code> into <code>sys.exit()</code>.</p>
<p>pps. the <a href="http://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops">for-else grammar</a> in Python is great for you.</p>
<p>ppps. "remove redundant parentheses", says PyCharm.</p>
| 2 | 2016-08-21T09:39:16Z | [
"python",
"python-3.x",
"tic-tac-toe"
] |
Django select_related join model attributes with a single query | 39,062,538 | <p>I'm trying to find a optimal solution with a single query to retrieve attributes on a join model.</p>
<p>I have the following models relationships:</p>
<pre><code>class Player(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
season_team = models.ForeignKey(SeasonTeam, related_name='players', blank=True, null=True)
leagues = models.ManyToManyField(League, related_name='players', through='PlayerLeague')
class League(models.Model):
name = models.CharField()
class PlayerLeague(models.Model):
player = models.ForeignKey(Player)
league = models.ForeignKey(League)
stamina = models.PositiveSmallIntegerField(_('Stamina'), default=100)
class Team(models.Model):
name = models.CharField(max_length=30, validators=[
RegexValidator(regex='^[a-zA-Z0-9\s]+$', message=_('name must contain only chars and numbers'), ), ])
players = models.ManyToManyField(Player, blank=True, related_name='teams')
league = models.ForeignKey(League, related_name='teams')
</code></pre>
<p>This is the view where I want all players loaded in get_context_data to preload stamina attribute</p>
<pre><code>class FormationUpdateView(AjaxResponseMixin, FormationRequirementsMixin, UpdateView):
model = Formation
template_desktop = 'hockey/formation/form.html'
template_mobile = 'hockey/formation/mobile/form.html'
form_class = FormationForm
def get_initial(self):
self.initial = {'active': True}
return self.initial.copy()
def get_context_data(self, **kwargs):
context = super(FormationUpdateView, self).get_context_data(**kwargs)
team = Team.objects.select_related('league').get(formations=self.kwargs['pk'])
context['players'] = Player.objects.filter(teams=team).all()
context['league'] = team.league
return context
def get_queryset(self):
return Formation.objects.select_related()
def get_template_names(self):
if 'Mobile' in self.request.META['HTTP_USER_AGENT']:
return self.template_mobile
return self.template_desktop
</code></pre>
<p>My first solution was by adding a stamina method to Player class:</p>
<pre><code>def stamina(self, league):
p_l = self.leagues.through.objects.filter(league=league)[0]
return p_l.stamina
</code></pre>
<p>I don't like this solution because is going to query for each player its stamina value.</p>
<p>Thank you for any help</p>
| 1 | 2016-08-21T08:58:00Z | 39,069,148 | <p>Your models are a little mind-twisting, but something like that should minimize the number of requests</p>
<pre><code>from django.db.models import Q, F, Prefetch
...
def get_context_data(self, **kwargs)
context = super(FormationUpdateView, self).get_context_data(**kwargs)
team = (Team.objects
.select_related('league')
.prefetch_related(
Prefetch(
'players',
queryset=(Player.objects.filter(leagues=F('leagues'))
.prefetch_related('playerleagues'))
)
).get(formations=self.kwargs['pk']))
context['players'] = team.players.all()
context['league'] = team.league
return context
</code></pre>
<p>To get the stamina of a player without hitting the database again.</p>
<pre><code>players[0].playerleagues.all()[0].stamina
</code></pre>
| 1 | 2016-08-21T21:47:45Z | [
"python",
"django",
"orm",
"django-select-related"
] |
Parsing a binary file written in MATLAB from Python and vice versa | 39,062,570 | <p>I am having major troubles with <code>struct.unpack</code> in python. I have a binary file with a pre-determined format, that can either be written in MATLAB or in Python.</p>
<p>I can write binary data to a file in Python and read the data back with no issues. I can also write the same data to a binary file from MATLAB and read it back in MATLAB with no problem. </p>
<p>My problem comes when I either write the data from MATLAB and try to read it back in Python, or when I write the data in Python and try to read it back in MATLAB.</p>
<p>For simplicity, let's say I'm writing two integers to a binary file (big-endian). Each integer is 4 bytes. The first integer is a valid integer not greater than 4 bytes, and the second integer must be equal to either 1, 2, or 3.</p>
<p>First, here is how I write my data in MATLAB:</p>
<pre><code>fid=fopen('hello_matlab.test','wb');
first_data=4+4;
second_data=1;
fwrite(fid,first_data,'int');
fwrite(fid,second_data,'int');
fclose(fid);
</code></pre>
<p>And here is how I read that back in MATLAB:</p>
<pre><code>fid=fopen('hello_matlab.test','rb');
first_data=fread(fid,1,'int');
second_data=fread(fid,1,'int');
fprintf('first data: %d\n', first_data);
fprintf('second data: %d\n', second_data);
fclose(fid);
>> first data: 8
>> second data: 1
</code></pre>
<p>Now, here is how I write the data in Python:</p>
<pre><code>fid=open('hello_python.test','wb')
first_data=4+4
second_data=1
fid.write(struct.pack('>i',first_data))
fid.write(struct.pack('>i',second_data))
fid.close()
</code></pre>
<p>And here is how I read that data back in python. Also note, the commented out portion worked (when reading from files written in Python). I originally thought something weird was happening with the way <code>struct.calcsize('>i')</code> was being calculated, so I removed it and instead put a hard-coded constant, <code>INTEGER_SIZE</code>, to represent the amount of bytes I knew MATLAB had used when encoding it:</p>
<pre><code>INTEGER_SIZE=4
fid=open('hello_python.test','rb')
### FIRST WAY I ORIGINALLY READ THE DATA ###
# This works, but I figured I would try hard coding the size
# so the uncommented version is what I am currently using.
#
# first_data=struct.unpack('>i',fid.read(struct.calcsize('>i')))[0]
# second_data=struct.unpack('>i',fid.read(struct.calcsize('>i')))[0]
### HOW I READ DATA CURRENTLY ###
first_data=struct.unpack('>i',fid.read(INTEGER_SIZE))[0]
second_data=struct.unpack('>i',fid.read(INTEGER_SIZE))[0]
print "first data: '%d'" % first_data
print "second data: '%d'" % second_data
fid.close()
>> first data: 8
>> second data: 1
</code></pre>
<p>Now, lets say I want to read <code>hello_python.test</code> in MATLAB. With my current MATLAB code, here is the new output:</p>
<pre><code>>> first data: 419430400
>> second data: 16777216
</code></pre>
<p>That is strange, so I did the reverse. I looked at what happens when I read <code>hello_matlab.test</code>. With my current Python code, here is the new output:</p>
<pre><code>>> first data: 419430400
>> second data: 16777216
</code></pre>
<p>So, something weird is happening but I don't know what it is. Also note, although this is part of a larger project, I did just extract these parts of my code into a new project, and tested the example above with those results. I'm really confused on how to make this file portable :( Any help would be appreciated.</p>
| 0 | 2016-08-21T09:03:06Z | 39,062,772 | <p>You may be intrested in pandas hdf5 store:</p>
<p>In Python:</p>
<blockquote>
<pre><code>In [418]: df_for_r = pd.DataFrame({"first": np.random.rand(100),
.....: "second": np.random.rand(100),
.....: "class": np.random.randint(0, 2, (100,))},
.....: index=range(100))
.....:
In [419]: df_for_r.head()
Out[419]:
class first second
0 0 0.417022 0.326645
1 0 0.720324 0.527058
2 1 0.000114 0.885942
3 1 0.302333 0.357270
4 1 0.146756 0.908535
In [420]: store_export = HDFStore('export.h5')
In [421]: store_export.append('df_for_r', df_for_r)
In [422]: store_export
Out[422]:
<class 'pandas.io.pytables.HDFStore'>
File path: export.h5
/df_for_r frame_table (typ->appendable,nrows->100,ncols->3,indexers->[index])
</code></pre>
</blockquote>
<p>In matlab:</p>
<pre><code>data = h5read('export.h5','/df_for_r');
</code></pre>
<p>But Im not sure if it works, wrote completely in browser...</p>
| 1 | 2016-08-21T09:28:52Z | [
"python",
"matlab",
"file",
"struct",
"binary"
] |
Parsing a binary file written in MATLAB from Python and vice versa | 39,062,570 | <p>I am having major troubles with <code>struct.unpack</code> in python. I have a binary file with a pre-determined format, that can either be written in MATLAB or in Python.</p>
<p>I can write binary data to a file in Python and read the data back with no issues. I can also write the same data to a binary file from MATLAB and read it back in MATLAB with no problem. </p>
<p>My problem comes when I either write the data from MATLAB and try to read it back in Python, or when I write the data in Python and try to read it back in MATLAB.</p>
<p>For simplicity, let's say I'm writing two integers to a binary file (big-endian). Each integer is 4 bytes. The first integer is a valid integer not greater than 4 bytes, and the second integer must be equal to either 1, 2, or 3.</p>
<p>First, here is how I write my data in MATLAB:</p>
<pre><code>fid=fopen('hello_matlab.test','wb');
first_data=4+4;
second_data=1;
fwrite(fid,first_data,'int');
fwrite(fid,second_data,'int');
fclose(fid);
</code></pre>
<p>And here is how I read that back in MATLAB:</p>
<pre><code>fid=fopen('hello_matlab.test','rb');
first_data=fread(fid,1,'int');
second_data=fread(fid,1,'int');
fprintf('first data: %d\n', first_data);
fprintf('second data: %d\n', second_data);
fclose(fid);
>> first data: 8
>> second data: 1
</code></pre>
<p>Now, here is how I write the data in Python:</p>
<pre><code>fid=open('hello_python.test','wb')
first_data=4+4
second_data=1
fid.write(struct.pack('>i',first_data))
fid.write(struct.pack('>i',second_data))
fid.close()
</code></pre>
<p>And here is how I read that data back in python. Also note, the commented out portion worked (when reading from files written in Python). I originally thought something weird was happening with the way <code>struct.calcsize('>i')</code> was being calculated, so I removed it and instead put a hard-coded constant, <code>INTEGER_SIZE</code>, to represent the amount of bytes I knew MATLAB had used when encoding it:</p>
<pre><code>INTEGER_SIZE=4
fid=open('hello_python.test','rb')
### FIRST WAY I ORIGINALLY READ THE DATA ###
# This works, but I figured I would try hard coding the size
# so the uncommented version is what I am currently using.
#
# first_data=struct.unpack('>i',fid.read(struct.calcsize('>i')))[0]
# second_data=struct.unpack('>i',fid.read(struct.calcsize('>i')))[0]
### HOW I READ DATA CURRENTLY ###
first_data=struct.unpack('>i',fid.read(INTEGER_SIZE))[0]
second_data=struct.unpack('>i',fid.read(INTEGER_SIZE))[0]
print "first data: '%d'" % first_data
print "second data: '%d'" % second_data
fid.close()
>> first data: 8
>> second data: 1
</code></pre>
<p>Now, lets say I want to read <code>hello_python.test</code> in MATLAB. With my current MATLAB code, here is the new output:</p>
<pre><code>>> first data: 419430400
>> second data: 16777216
</code></pre>
<p>That is strange, so I did the reverse. I looked at what happens when I read <code>hello_matlab.test</code>. With my current Python code, here is the new output:</p>
<pre><code>>> first data: 419430400
>> second data: 16777216
</code></pre>
<p>So, something weird is happening but I don't know what it is. Also note, although this is part of a larger project, I did just extract these parts of my code into a new project, and tested the example above with those results. I'm really confused on how to make this file portable :( Any help would be appreciated.</p>
| 0 | 2016-08-21T09:03:06Z | 39,065,661 | <p>The issue is with <a href="https://en.wikipedia.org/wiki/Endianness" rel="nofollow">endianness</a>, the order of bits in a number. You must be on an x86 or x86-64 computer (since those are the only ones MATLAB supports), and those are <a href="https://en.wikipedia.org/wiki/Endianness#Current_architectures" rel="nofollow">little-endian</a>. However, the python <code>>i</code> is telling it to use big-endian byte order. So you are using opposite byte orders, which is making the two languages read completely different numbers out. </p>
<p>If you only ever plan on using the Python code on an x86 or x86-64 computer, or you only care about sending data between MATLAB and Python on the same computer, then you can just leave off the byte order mark completely and use the native byte order (so <code>i</code> instead of <code>>i</code>). If you may be running on python on a powerpc system you might want to manually-specify little-endianess (<code><i</code>).</p>
<p>For this example, that appears to be the only issue. I would like to point out that if you are trying to read and write arrays/matrices of data a time, then <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html" rel="nofollow"><code>numpy.fromfile</code></a> will be much faster and easier.</p>
| 1 | 2016-08-21T15:07:17Z | [
"python",
"matlab",
"file",
"struct",
"binary"
] |
Python - compare files with header field by field | 39,062,671 | <p>I have been trying for a couple of days now and I am still stuck and puzzled at why the following code isn't working.<br>
The issue seems to be related in the if condition while calling the lineNumber function. The function compares the length of two files and it works fine(tried), but when called within the if statement, the nestled code will no longer work (fyi - for each line, the inner code compares the correspondent field values in the two files and print out differences ). If I call the function without passing file1 and file2 (equivalent of not calling it at all), or remove the if condition, the code works. Can anybody help me with this please? Thank you in advance</p>
<pre><code>import csv
def lineNumber(file1, file2):
if len(list(file1)) == len(list(file2)):
return True
else:
return False
with open('filea.csv', 'rU') as filea, open('fileb.csv', 'rU') as fileb:
readera = csv.DictReader(filea)
readerb = csv.DictReader(fileb)
count = 0
for rowa,rowb in zip(readera, readerb):
if lineNumber(filea, fileb):
diff = [key for key in rowa if rowa[key] != rowb[key]]
count = count+1
for key in diff:
print "Line:", count,"Column:", key, ':', "Expected:",rowa[key], '->', "Actual:", rowb[key]
else:
print "The two files have different line number. Check sources"
filea.close()
fileb.close()
</code></pre>
<p><a href="http://i.stack.imgur.com/5jhcK.jpg" rel="nofollow">WITH PARAMS - I get NO Results</a></p>
<p><a href="http://i.stack.imgur.com/kWDWX.jpg" rel="nofollow">NO PARAMS - I GET Results </a></p>
| -5 | 2016-08-21T09:16:52Z | 39,062,708 | <p>You may have a typo. Try changing</p>
<pre><code>if lineNumber(file, fileb):
</code></pre>
<p>to</p>
<pre><code>if lineNumber(filea, fileb):
</code></pre>
| 1 | 2016-08-21T09:21:37Z | [
"python",
"dictionary",
"compare"
] |
Python - compare files with header field by field | 39,062,671 | <p>I have been trying for a couple of days now and I am still stuck and puzzled at why the following code isn't working.<br>
The issue seems to be related in the if condition while calling the lineNumber function. The function compares the length of two files and it works fine(tried), but when called within the if statement, the nestled code will no longer work (fyi - for each line, the inner code compares the correspondent field values in the two files and print out differences ). If I call the function without passing file1 and file2 (equivalent of not calling it at all), or remove the if condition, the code works. Can anybody help me with this please? Thank you in advance</p>
<pre><code>import csv
def lineNumber(file1, file2):
if len(list(file1)) == len(list(file2)):
return True
else:
return False
with open('filea.csv', 'rU') as filea, open('fileb.csv', 'rU') as fileb:
readera = csv.DictReader(filea)
readerb = csv.DictReader(fileb)
count = 0
for rowa,rowb in zip(readera, readerb):
if lineNumber(filea, fileb):
diff = [key for key in rowa if rowa[key] != rowb[key]]
count = count+1
for key in diff:
print "Line:", count,"Column:", key, ':', "Expected:",rowa[key], '->', "Actual:", rowb[key]
else:
print "The two files have different line number. Check sources"
filea.close()
fileb.close()
</code></pre>
<p><a href="http://i.stack.imgur.com/5jhcK.jpg" rel="nofollow">WITH PARAMS - I get NO Results</a></p>
<p><a href="http://i.stack.imgur.com/kWDWX.jpg" rel="nofollow">NO PARAMS - I GET Results </a></p>
| -5 | 2016-08-21T09:16:52Z | 39,069,622 | <p>I found the issue. I have updated the code above. Thanks everyone</p>
| 0 | 2016-08-21T23:10:18Z | [
"python",
"dictionary",
"compare"
] |
How to run a python app repeatedly using Bluemix? | 39,062,891 | <p>The Bluemix python build pack works just fine - very easy to <code>cf push myapp --no-route</code>. So far, so good.</p>
<h3>A question, though:</h3>
<p>I want to run it periodically on Bluemix as I would using <code>cron</code> on my local system.</p>
<h3>Background</h3>
<p>The app is not written as a long-running task. I just run it periodically to collect data from several websites that I have written for my clients and to email me results when appropriate. </p>
<p>When I run it on IBM Bluemix though, the Bluemix runtime currently thinks the app is failing when it exits and needs to be restarted immediately. This is not what I want, of course.</p>
| 2 | 2016-08-21T09:45:22Z | 39,064,511 | <p>There are a couple options:</p>
<p>1) If you want to do it completely in Python, you could try something like I did in <a href="http://blog.4loeser.net/2015/07/bluemix-simple-cron-like-service-for-my.html" rel="nofollow">this example</a>. The basic structure is like this:</p>
<pre><code>import schedule
import time
def job():
#put the task to execute here
def anotherJob():
#another task can be defined here
schedule.every(10).minutes.do(job)
schedule.every().day.at("10:30").do(anotherJob)
while True:
schedule.run_pending()
time.sleep(1)
</code></pre>
<p>2) Bluemix has changed and today a better approach would be to use <a href="https://developer.ibm.com/openwhisk/" rel="nofollow">OpenWhisk</a>. It is IBM's version of "serverless" computing and it allows to schedule execution of tasks or do it event-driven. You could move your app into a Docker container and invoke it based on a schedule or driven by external events.</p>
| 2 | 2016-08-21T13:05:22Z | [
"python",
"ibm-bluemix",
"openwhisk"
] |
How to run a python app repeatedly using Bluemix? | 39,062,891 | <p>The Bluemix python build pack works just fine - very easy to <code>cf push myapp --no-route</code>. So far, so good.</p>
<h3>A question, though:</h3>
<p>I want to run it periodically on Bluemix as I would using <code>cron</code> on my local system.</p>
<h3>Background</h3>
<p>The app is not written as a long-running task. I just run it periodically to collect data from several websites that I have written for my clients and to email me results when appropriate. </p>
<p>When I run it on IBM Bluemix though, the Bluemix runtime currently thinks the app is failing when it exits and needs to be restarted immediately. This is not what I want, of course.</p>
| 2 | 2016-08-21T09:45:22Z | 39,250,213 | <p>This turned out to be incredibly easy after having got my head around <em>Openwhisk</em>'s simple <strong>trigger</strong>; <strong>action</strong>; <strong>rule</strong> model. </p>
<p>So I migrated my Python app to <em>Openwhisk</em> entirely rather than use the Bluemix Python buildpack or Bluemix Docker containers neither of which were appropriate to this task's simple needs.</p>
<p>I include a summary below. I wrote a more verbose version <a href="https://iainhouston.com/blog/openwhisk-workflow.html" rel="nofollow">here</a>. </p>
<p>As an added bonus I was able to remove a good deal of my own code and instead use <a href="https://slack.com" rel="nofollow">Slack</a> for notifications. As it was so simple to do, I include it in this answer. </p>
<h2>The program</h2>
<p>Openwhisk Python actions are python 2.7.<br>
File <code>sitemonitor.py</code>:</p>
<pre><code>def main(inDict):
inTimeout = inDict.get('timeout', '4')
// A few function calls omitted for brevity
if state.errorCount == 0:
return {'text': "All sites OK"}
else:
return { 'text' : state.slackMessage }
</code></pre>
<p><code>main</code> takes a dictionary and returns a dictionary</p>
<h2>Setting up the job</h2>
<h3>Create the <code>sitemonitor</code> action</h3>
<p><code>timeout</code> is a parameter specific to my app only.</p>
<pre><code>$ wsk action create sitemonitor sitemonitor.py # default timeout of 4 seconds
</code></pre>
<p>or give the action a different timeout in a default parameter</p>
<pre><code>$ wsk action update sitemonitor sitemonitor.py --param timeout 2 # seconds
</code></pre>
<h3>Create the Slack package action <code>monitorSlack</code></h3>
<pre><code>wsk package bind /whisk.system/slack monitorSlack \
--param url 'https://hooks.slack.com/services/...' \
--param username 'monitor-bot' \
--param channel '#general'
</code></pre>
<p>Find the <a href="https://slack.com" rel="nofollow">Incoming Webhook URL from your Slack Team account</a></p>
<h3>Create the composed <code>monitor2slack</code> action</h3>
<pre><code>$ wsk action create monitor2slack --sequence sitemonitor,monitorSlack/post
</code></pre>
<h3>Create the trigger</h3>
<p>It will fire automatically every other hour</p>
<pre><code>$ wsk trigger create monitor2hrs \
--feed /whisk.system/alarms/alarm \
--param cron '0 0 */2 * * *'
$ wsk trigger fire monitor2hrs # fire manually to test
</code></pre>
<h3>Create the rule</h3>
<pre><code>$ wsk rule create monitorsites monitor2hrs monitor2slack
</code></pre>
<p>... and <em>Openwhisk</em> will do the rest.</p>
<h2>References</h2>
<p><a href="https://new-console.eu-gb.bluemix.net/docs/" rel="nofollow">Openwhisk documentation</a> : very good </p>
<p>People at the <code>#openwhisk</code> channel in the the Slack <a href="https://slack.com" rel="nofollow"><code>dW Open</code>Team</a> were very helpful.</p>
| 2 | 2016-08-31T12:52:55Z | [
"python",
"ibm-bluemix",
"openwhisk"
] |
How to create dictionary from another dictionary if some condition met | 39,062,987 | <p>From dictionary : </p>
<pre><code>{0: (u'Donald', u'PERSON'), 1: (u'John', u'PERSON'), 2: (u'Trump', u'PERSON'), 14: (u'Barack', u'PERSON'), 15: (u'Obama', u'PERSON'), 17: (u'Michelle', u'PERSON'), 18: (u'Obama', u'PERSON'), 30: (u'Donald', u'PERSON'), 31: (u'Jonh', u'PERSON'), 32: (u'Trump', u'PERSON')}
</code></pre>
<p>I'd like to create another dictionary as follows:</p>
<pre><code>{u'Donald John Trump': 2, u'Barack Obama':1, u'Michele Obama':1}
</code></pre>
<p>Here 0,1,2 and 30,31,32 keys are increasing by 1 and occurred twice. And 14,15 17,18 occurred once each. Is there any way to create such dict?</p>
| 1 | 2016-08-21T10:00:43Z | 39,063,130 | <p>I think the main problem you need to solve is to identify persons by grouping keys denoting an increasing int sequence, as you described it.</p>
<p>Fortunately, Python has <a href="https://docs.python.org/2.6/library/itertools.html#examples" rel="nofollow">a recipe</a> for this.</p>
<pre><code>from itertools import groupby
from operator import itemgetter
from collections import defaultdict
dct = {
0: ('Donald', 'PERSON'),
1: ('John', 'PERSON'),
2: ('Trump', 'PERSON'),
14: ('Barack', 'PERSON'),
15: ('Obama', 'PERSON'),
17: ('Michelle', 'PERSON'),
18: ('Obama', 'PERSON'),
30: ('Donald', 'PERSON'),
31: ('John', 'PERSON'),
32: ('Trump', 'PERSON')
}
persons = defaultdict(int) # Used for conveniance
keys = sorted(dct.keys()) # So groupby() can recognize sequences
for k, g in groupby(enumerate(keys), lambda d: d[0] - d[1]):
ids = map(itemgetter(1), g) # [0, 1, 2], [14, 15], etc.
person = ' '.join(dct[i][0] for i in ids) # "Donald John Trump", "Barack Obama", etc
persons[person] += 1
print(persons)
# defaultdict(<class 'int'>,
# {'Barack Obama': 1,
# 'Donald John Trump': 2,
# 'Michelle Obama': 1})
</code></pre>
| 3 | 2016-08-21T10:20:39Z | [
"python",
"dictionary",
"count"
] |
How to create dictionary from another dictionary if some condition met | 39,062,987 | <p>From dictionary : </p>
<pre><code>{0: (u'Donald', u'PERSON'), 1: (u'John', u'PERSON'), 2: (u'Trump', u'PERSON'), 14: (u'Barack', u'PERSON'), 15: (u'Obama', u'PERSON'), 17: (u'Michelle', u'PERSON'), 18: (u'Obama', u'PERSON'), 30: (u'Donald', u'PERSON'), 31: (u'Jonh', u'PERSON'), 32: (u'Trump', u'PERSON')}
</code></pre>
<p>I'd like to create another dictionary as follows:</p>
<pre><code>{u'Donald John Trump': 2, u'Barack Obama':1, u'Michele Obama':1}
</code></pre>
<p>Here 0,1,2 and 30,31,32 keys are increasing by 1 and occurred twice. And 14,15 17,18 occurred once each. Is there any way to create such dict?</p>
| 1 | 2016-08-21T10:00:43Z | 39,063,228 | <pre><code>def add_name(d, consecutive_keys, result):
result_key = ' '.join(d[k][0] for k in consecutive_keys)
if result_key in result:
result[result_key] += 1
else:
result[result_key] = 1
d = {0: (u'Donald', u'PERSON'), 1: (u'John', u'PERSON'), 2: (u'Trump', u'PERSON'),
14: (u'Barack', u'PERSON'), 15: (u'Obama', u'PERSON'),
17: (u'Michelle', u'PERSON'), 18: (u'Obama', u'PERSON'),
30: (u'Donald', u'PERSON'), 31: (u'John', u'PERSON'), 32: (u'Trump', u'PERSON')}
sorted_keys = sorted(d.keys())
last_key = sorted_keys[0]
consecutive_keys = [last_key]
result = {}
for i in sorted_keys[1:]:
if i == last_key + 1:
consecutive_keys.append(i)
else:
add_name(d, consecutive_keys, result)
consecutive_keys = [i]
last_key = i
add_name(d, consecutive_keys, result)
print(result)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>{'Donald John Trump': 2, 'Barack Obama': 1, 'Michelle Obama': 1}
</code></pre>
| 2 | 2016-08-21T10:32:53Z | [
"python",
"dictionary",
"count"
] |
How to copy queryset Django | 39,063,017 | <p>I am trying to access queryset of ManyToManyField before and after saving in def save_related(self, request, form, *args, **kwargs) method.
I want to compare them and get new objects, that were added to ManyToManyField.</p>
<p>So, I am getting old queryset with:</p>
<pre><code>def save_related(self, request, form, * args, * * kwargs):
obj = form.instance
queryset_before = obj.translations.all()
print(queryset_before)
super(WordAdmin, self).save_related(request, form, * args, * * kwargs)
print(queryset_before)
</code></pre>
<p>But print(queryset_before) outputs the new, updated queryset after calling super().save_related.</p>
<p>So:</p>
<ol>
<li>How to copy queryset, so that saving will not affect it?</li>
<li>Or is there a way to compare old and new values of ManyToManyField more properly?</li>
</ol>
| 0 | 2016-08-21T10:04:42Z | 39,063,122 | <p>You can get lists of IDs before and after save, then compare these lists:</p>
<pre><code>def save_related(self, request, form, *args, **kwargs):
obj = form.instance
list_before = list(obj.translations.all().values_list('pk', flat=True))
super(WordAdmin, self).save_related(request, form, *args, ** kwargs)
list_after = list(obj.translations.all().values_list('pk', flat=True))
added_ids = [x for x in list_after if x not in list_before]
removed_ids = [y for y in list_before if y not in list_after]
</code></pre>
| 0 | 2016-08-21T10:19:44Z | [
"python",
"django",
"many-to-many",
"django-queryset",
"manytomanyfield"
] |
How to copy queryset Django | 39,063,017 | <p>I am trying to access queryset of ManyToManyField before and after saving in def save_related(self, request, form, *args, **kwargs) method.
I want to compare them and get new objects, that were added to ManyToManyField.</p>
<p>So, I am getting old queryset with:</p>
<pre><code>def save_related(self, request, form, * args, * * kwargs):
obj = form.instance
queryset_before = obj.translations.all()
print(queryset_before)
super(WordAdmin, self).save_related(request, form, * args, * * kwargs)
print(queryset_before)
</code></pre>
<p>But print(queryset_before) outputs the new, updated queryset after calling super().save_related.</p>
<p>So:</p>
<ol>
<li>How to copy queryset, so that saving will not affect it?</li>
<li>Or is there a way to compare old and new values of ManyToManyField more properly?</li>
</ol>
| 0 | 2016-08-21T10:04:42Z | 39,064,659 | <p>The problem is that printing a queryset will evaluate only a slice of the queryset, and as a result, it won't fill the queryset's internal cache.</p>
<p>You need to completely evaluate the queryset before you make the changes, so that the internal cache is filled. The easiest way to do this is with the <code>bool()</code> function:</p>
<pre><code>def save_related(self, request, form, *args, **kwargs):
obj = form.instance
queryset_before = obj.translations.all()
bool(queryset_before)
print(queryset_before)
super(WordAdmin, self).save_related(request, form, *args, **kwargs)
print(queryset_before)
</code></pre>
<p>Now both print statements should give you the same results.</p>
| 0 | 2016-08-21T13:21:13Z | [
"python",
"django",
"many-to-many",
"django-queryset",
"manytomanyfield"
] |
How to filter model_set in django | 39,063,092 | <p>Here is my part of template:</p>
<pre><code>{% for sitting in c.sittings %}
{% if sittings.sit_date == sittings.shiftdate_set.all %}
<p>Firstly it was scheduled on {{sitting.sit_date}}</p>
{% endif %}
{% endfor %}
</code></pre>
<p>But this code return all the sitting dates not particularly equal to sit_date of Shiftdate model. I can't filter sit_date from shiftdate_set. I also tried to using following method in Sitting model:</p>
<pre><code>def get_shiftdate(self):
return self.shiftdate_set.filter(shift_date=self.sit_date)
</code></pre>
<p>and Using it in the above template as: </p>
<pre><code>{% for sitting in c.sittings %}
{% if sittings.sit_date == sittings.get_shiftdate %}
<p>Firstly it was scheduled on {{sitting.sit_date}}</p>
{% endif %}
{% endfor %}
</code></pre>
<p>But still I am getting all the sitting dates not only related sitting dates. Could anybody help to figure out what I am doing wrong.</p>
<p>Edit:
<a href="http://i.stack.imgur.com/XJxLQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/XJxLQ.png" alt="enter image description here"></a></p>
<p>Here you see it shows on the same date. It should be other dates. for my example it should be on 14 and 15 September.</p>
<p>Update: </p>
<p><strong>Edit:</strong></p>
<p>Here is my Sitting model:</p>
<pre><code>class Sitting(models.Model):
sit_date = models.DateField(blank=False,unique=True)
cut_off_date = models.DateField(null=True, blank=True)
ballot_date = models.DateField(null=True, blank=True)
sess_no = models.ForeignKey(Session,
on_delete=models.CASCADE)
genre = TreeForeignKey('Genre', null=True, blank=True, db_index=True)
</code></pre>
<p>Here is Shiftdate model:</p>
<pre><code>class Shiftdate(models.Model):
shift_date = models.DateField(blank=False,unique=True)
sit_date = models.ForeignKey(Sitting,
on_delete=models.CASCADE)
shift_cut_off_date = models.DateField(null=True, blank=True)
shift_ballot_date = models.DateField(null=True, blank=True)
sess_no = models.ForeignKey(Session,
on_delete=models.CASCADE)
genre = TreeForeignKey('Genre', null=True, blank=True, db_index=True)
</code></pre>
<p>I updated new sitting dates in the sit_date of Sitting model from Shiftdate model. Here I need to show messages only the date which is related to the shift_date of Shiftdate model not the sit_date of Sitting model.</p>
<p>I hope this clear the question. </p>
| 0 | 2016-08-21T10:14:46Z | 39,063,360 | <p>I don't think you can just compare sitting.sit_date to whatever model the shift date is. You probably need to point it to the field that contains the new sit_date and then do this:</p>
<pre><code>{% for sitting in c.sittings %}
{% for shiftdate in sittings.shiftdate_set.all %}
{% if sittings.sit_date == shiftdate.sit_date %}
<p>Firstly it was scheduled on {{sitting.sit_date}}</p>
{% endif %}
{% endfor %}
{% endfor %}
</code></pre>
| 0 | 2016-08-21T10:49:15Z | [
"python",
"django"
] |
Passing a Python list to C function using the Python/C API | 39,063,112 | <p>I've recently started using the Python/C API to build modules for Python using C code. I've been trying to pass a Python list of numbers to a C function without success:</p>
<p><strong>asdf_module.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <Python.h>
int _asdf(int low, int high, double *pr)
// ...
for (i = 0; i < range; i++)
{
printf("pr[%d] = %f\n", i, pr[i]);
}
// ...
return 0;
}
static PyObject*
asdf(PyObject* self, PyObject* args)
{
int low, high;
double *pr;
// maybe something about PyObject *pr ?
if (!PyArg_ParseTuple(args, "iiO", &low, &high, &pr))
return NULL;
// how to pass list pr to _asdf?
return Py_BuildValue("i", _asdf(low, high, pr));
}
static PyMethodDef AsdfMethods[] =
{
{"asdf", asdf, METH_VARARGS, "..."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initasdf(void)
{
(void) Py_InitModule("asdf", AsdfMethods);
}
</code></pre>
<p>Building the module with <strong>setup.py</strong> :</p>
<pre class="lang-python prettyprint-override"><code>from distutils.core import setup, Extension
module1 = Extension('asdf', sources = ['asdf_module.c'])
setup (name = 'asdf',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
</code></pre>
<p>Using the module in <strong>test_module.py</strong> :</p>
<pre class="lang-python prettyprint-override"><code>import asdf
print asdf.asdf(-2, 3, [0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
</code></pre>
<p>However, what I got as an output is :</p>
<blockquote>
<p>pr[0] = 0.000000</p>
<p>pr[1] = 0.000000</p>
<p>pr[2] = 0.000000</p>
<p>pr[3] = 0.000000</p>
<p>pr[4] = 0.000000</p>
<p>pr[5] = -nan</p>
</blockquote>
<p>Also, instead of <em>_asdf</em> returning 0, how can it return an array of <code>n</code> values (where <code>n</code> is a fixed number)?</p>
| 1 | 2016-08-21T10:17:54Z | 39,133,508 | <p>This example will show you how to</p>
<ol>
<li>Get the length of the list</li>
<li>Allocate storage for an array of <code>double</code></li>
<li>Get each element of the list</li>
<li>Convert each element to a <code>double</code></li>
<li>Store each converted element in the array</li>
</ol>
<p>Here is the code:</p>
<pre><code>#include "Python.h"
int _asdf(double pr[], int length) {
for (int index = 0; index < length; index++)
printf("pr[%d] = %f\n", index, pr[index]);
return 0;
}
static PyObject *asdf(PyObject *self, PyObject *args)
{
PyObject *float_list;
int pr_length;
double *pr;
if (!PyArg_ParseTuple(args, "O", &float_list))
return NULL;
pr_length = PyObject_Length(float_list);
if (pr_length < 0)
return NULL;
pr = (double *) malloc(sizeof(double *) * pr_length);
if (pr == NULL)
return NULL;
for (int index = 0; index < pr_length; index++) {
PyObject *item;
item = PyList_GetItem(float_list, index);
if (!PyFloat_Check(item))
pr[index] = 0.0;
pr[index] = PyFloat_AsDouble(item);
}
return Py_BuildValue("i", _asdf(pr, pr_length));
}
</code></pre>
<p>NOTE: White space and braces removed to keep code from scrolling.</p>
<p><strong>Test program</strong></p>
<pre><code>import asdf
print asdf.asdf([0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
</code></pre>
<p><strong>Output</strong></p>
<pre><code>pr[0] = 0.700000
pr[1] = 0.000000
pr[2] = 0.100000
pr[3] = 0.000000
pr[4] = 0.000000
pr[5] = 0.200000
0
</code></pre>
| 0 | 2016-08-24T21:45:23Z | [
"python",
"c"
] |
IndexError: fail to coerce slice entry of type tensorvariable to integer | 39,063,169 | <p>I run "ipython debugf.py" and it gave me error message as below</p>
<pre><code>IndexError Traceback (most recent call last)
/home/ml/debugf.py in <module>()
8 fff = theano.function(inputs=[index],
9 outputs=cost,
---> 10 givens={x: train_set_x[index: index+1]})
IndexError: failed to coerce slice entry of type TensorVariable to integer"
</code></pre>
<p>I search the forum and no luck, is there someone can help ?
thanks!<br>
debugf.py : </p>
<pre><code>import theano.tensor as T
import theano
import numpy
index =T.lscalar()
x=T.dmatrix()
cost=x +index
train_set_x=numpy.arange(100).reshape([20,5])
fff=theano.function(inputs=[index],
outputs=cost,
givens={x:train_set_x[index: index+1]}) #<--- Error here
</code></pre>
| 3 | 2016-08-21T10:24:59Z | 39,064,543 | <p>Change train_set_x variable to theano.shared variable, and the code is OK.
I dont know the reason, but it works! Hope this post can help others.
The correct code is as below </p>
<pre><code>import theano.tensor as T
import theano
import numpy
index =T.lscalar()
x=T.dmatrix()
cost=x +index
train_set_x=numpy.arange(100.).reshape([20,5]) #<--- change to float,
#because shared must be floatX type
#change to shared variable
shared_x = theano.shared(train_set_x)
fff=theano.function(inputs=[index],
outputs=cost,
givens={x:shared_x[index: index+1]}) #<----change to shared_x
</code></pre>
| 0 | 2016-08-21T13:08:09Z | [
"python",
"theano"
] |
IndexError: fail to coerce slice entry of type tensorvariable to integer | 39,063,169 | <p>I run "ipython debugf.py" and it gave me error message as below</p>
<pre><code>IndexError Traceback (most recent call last)
/home/ml/debugf.py in <module>()
8 fff = theano.function(inputs=[index],
9 outputs=cost,
---> 10 givens={x: train_set_x[index: index+1]})
IndexError: failed to coerce slice entry of type TensorVariable to integer"
</code></pre>
<p>I search the forum and no luck, is there someone can help ?
thanks!<br>
debugf.py : </p>
<pre><code>import theano.tensor as T
import theano
import numpy
index =T.lscalar()
x=T.dmatrix()
cost=x +index
train_set_x=numpy.arange(100).reshape([20,5])
fff=theano.function(inputs=[index],
outputs=cost,
givens={x:train_set_x[index: index+1]}) #<--- Error here
</code></pre>
| 3 | 2016-08-21T10:24:59Z | 39,368,179 | <p>The reason this occurs is because index is a tensor symbolic variable (a long scalar, as you can see on line 4). So when python tries to build the dictionary that theano needs for its 'given' input, it tries to slice the numpy array using the symbolic variable â which it obviously can't do because it doesn't have a value yet (it is only set when you input something to the function).</p>
<p>As you've realised passing the data through theano.shared is the best approach. This means all the training data can be offloaded to the GPU, and then sliced/indexed on the fly to run each example. </p>
<p>However you might find that you have too much training data to fit in your GPU's memory, or for some other reason don't want to use a shared variable. Then you could just change your function definition</p>
<pre><code>data = T.matrix()
fff=theano.function(inputs=[data],
outputs=cost,
givens={x: data}
)
</code></pre>
<p>Then instead of writing</p>
<pre><code>fff(index)
</code></pre>
<p>You write</p>
<pre><code>fff(train_set_x[index: index+1])
</code></pre>
<p>Be warned the process of moving data onto the GPU is slow, so it's much better to minimise the number of transfers if possible.</p>
| 0 | 2016-09-07T11:03:58Z | [
"python",
"theano"
] |
Python - Regex findall repeated pattern followed by variable length of chars | 39,063,200 | <p>I have the following pattern:<br>
<code>1MHG161 xxxxxxxxxxxxx 1MHG161 xxx</code> <br>
where <code>xxxx</code> is variable length of chars & spaces.</p>
<p>I am trying to capture each one and have the following expected output: <br>
<code>[ '1MHG161 xxxxxxxxxxxxx ' , '1MHG161 xxx' ]</code></p>
<p>I have tried a lot of combination this is the last one</p>
<pre><code>messages_strings = re.findall("(1MHG161.+?)(?=1MHG161)",content)
</code></pre>
<p>This finds all except the last one.</p>
<hr>
<h3>Edit 1:</h3>
<p>I have taken @anubhava answer, a little bit further to solve the same problem but with dynamic delimiters by using <code>\d[A-Z]{3}\d{3}</code> instead of <code>1MHG161</code></p>
<p>This may help people working with EDI parsers.</p>
| 1 | 2016-08-21T10:30:01Z | 39,063,243 | <p>You can use:</p>
<pre><code>>>> re.findall(r"(1MHG161.+?)(?=1MHG161|$)", content)
['1MHG161 xxxxxxxxxxxxx ', '1MHG161 xxx']
</code></pre>
<p>Lookahead <code>(?=1MHG161|$)</code> will match <code>1MHG161</code> or end of line anchor <code>$</code> after your match.</p>
| 3 | 2016-08-21T10:34:50Z | [
"python",
"regex"
] |
Python path in command prompt | 39,063,247 | <p>I had Python3 installed on my computer after Python2. Then I executed "python" in command prompt, Python3 showed up.
How does the command prompt find Python without specifying the path?
Can I switch it back to Python2 without reinstalling?</p>
| 0 | 2016-08-21T10:35:13Z | 39,063,264 | <p>If you are on windows you need the python27 to be first in your PATH enviroment variable</p>
<pre><code>PATH=c:\python27;otherstuff...;c:\python35;...;
</code></pre>
<p>or just write </p>
<pre><code>py -2
</code></pre>
<p>To start python2</p>
| 2 | 2016-08-21T10:38:07Z | [
"python",
"command-prompt"
] |
Cost function for Convolution neural network | 39,063,302 | <p>I am doing Text Classification by Convolution Neural Network. In the example <a href="https://www.tensorflow.org/versions/r0.10/tutorials/mnist/beginners/index.html" rel="nofollow">MNIST</a> they have 60.000 images examples of hand-written digits, each image has size 28 x 28 and there are 10 labels (from 0 to 9). So the size of Weight will be 784 * 10 (28 * 28 = 784)</p>
<p><a href="http://i.stack.imgur.com/qKVBF.png" rel="nofollow"><img src="http://i.stack.imgur.com/qKVBF.png" alt="enter image description here"></a></p>
<p>Here is their code: </p>
<pre><code>x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
</code></pre>
<p>In my case, I applied <a href="https://www.tensorflow.org/versions/r0.10/tutorials/word2vec/index.html" rel="nofollow">word2vec</a> to encode my documents. The result "dictionary size" of word embedding is 2000 and the embedding size is 128. There are 45 labels. I tried to do the same as the example but It did not work. Here what I did: I treated each document same as image. For instance, The document could be represent as the matrix of 2000 x 128 (for words appear in document I appended the word Vector value for that column and left other equal zero. I have a trouble with creating W and x since my input data is a numpy array of 2000 x 128 while <code>x = tf.placeholder("float", [None, 256000])</code>. The size did not match. </p>
<p>Could nay one suggest any advises ?</p>
<p>Thanks</p>
| 0 | 2016-08-21T10:42:43Z | 39,063,705 | <p>Placeholder <code>x</code> is an array of flattened images, where first dimension <code>None</code> corresponds to batch size, i.e. number of images, and <code>256000 = 2000 * 128</code>. So, in order to feed <code>x</code> properly you need to flatten your input. Since you mention that your input is numpy arrays, take a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow" title="numpy.reshape">numpy.reshape</a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html" rel="nofollow">flatten</a>.</p>
| 1 | 2016-08-21T11:31:46Z | [
"python",
"tensorflow",
"word2vec"
] |
django custom property to return filtered field | 39,063,340 | <p>In a django app, with an existing database, I've used <code>inspectdb</code> to build a model:</p>
<pre><code> class Sensorparser(models.Model):
""" a read-only implemenation to access the MeshliumDB """
id_wasp = models.TextField(blank=True, null=True)
id_secret = models.TextField(blank=True, null=True)
frame_type = models.IntegerField(blank=True, null=True)
frame_number = models.IntegerField(blank=True, null=True)
sensor = models.TextField(blank=True, null=True)
value = models.TextField(blank=True, null=True)
timestamp = models.DateTimeField()
raw = models.TextField(blank=True, null=True)
parser_type = models.IntegerField()
def save(self, *args, **kwargs):
return
def delete(self, *args, **kwargs):
return
class Meta:
managed = False
db_table = 'sensorParser'
</code></pre>
<p>I added the <code>save</code> and <code>delete</code> methods because this should be a read-only model.</p>
<p>One of the fields is <code>sensor</code> which defines strings for different, well, "sensors" (e.g. BAT, ANE, etc.). I would like to have a property like this:</p>
<pre><code>@property
def battery()
return self.sensor.objects.filter(sensor='BAT')
</code></pre>
<p>How can I accomplish this?</p>
| 2 | 2016-08-21T10:46:54Z | 39,063,398 | <p>You can create <a href="https://docs.djangoproject.com/en/1.10/topics/db/managers/#custom-managers" rel="nofollow">custom manager</a>:</p>
<pre><code>class BatteryManager(models.Manager):
def get_queryset(self):
return super(BatteryManager, self).get_queryset().filter(sensor='BAT')
class Sensorparser(models.Model):
batteries = BatteryManager()
# etc
</code></pre>
<p>And use it like this:</p>
<pre><code>batteries = Sensorparser.batteries.all()
</code></pre>
| 3 | 2016-08-21T10:53:59Z | [
"python",
"django",
"django-models"
] |
django custom property to return filtered field | 39,063,340 | <p>In a django app, with an existing database, I've used <code>inspectdb</code> to build a model:</p>
<pre><code> class Sensorparser(models.Model):
""" a read-only implemenation to access the MeshliumDB """
id_wasp = models.TextField(blank=True, null=True)
id_secret = models.TextField(blank=True, null=True)
frame_type = models.IntegerField(blank=True, null=True)
frame_number = models.IntegerField(blank=True, null=True)
sensor = models.TextField(blank=True, null=True)
value = models.TextField(blank=True, null=True)
timestamp = models.DateTimeField()
raw = models.TextField(blank=True, null=True)
parser_type = models.IntegerField()
def save(self, *args, **kwargs):
return
def delete(self, *args, **kwargs):
return
class Meta:
managed = False
db_table = 'sensorParser'
</code></pre>
<p>I added the <code>save</code> and <code>delete</code> methods because this should be a read-only model.</p>
<p>One of the fields is <code>sensor</code> which defines strings for different, well, "sensors" (e.g. BAT, ANE, etc.). I would like to have a property like this:</p>
<pre><code>@property
def battery()
return self.sensor.objects.filter(sensor='BAT')
</code></pre>
<p>How can I accomplish this?</p>
| 2 | 2016-08-21T10:46:54Z | 39,063,414 | <p>Something like this maybe:</p>
<pre><code>def _get_battery(self):
return self.sensor.objects.filter(sensor='BAT')
battery = property(_get_battery)
</code></pre>
| 0 | 2016-08-21T10:55:55Z | [
"python",
"django",
"django-models"
] |
Parsing an optional list of ranges | 39,063,371 | <p>My script needs to take an option followed by a list of pages, specified as comma-separated list of ranges, and to process the expanded list of pages. So, for instance,</p>
<pre><code>script.py -a 2,4-6,9,10-13
</code></pre>
<p>should get the list</p>
<pre><code>[2, 4, 5, 6, 9, 10, 11, 12, 13]
</code></pre>
<p>to work with. Currently I am doing this:</p>
<pre><code>import argparse
def getList(argument):
ranges = list(argument.split(","))
newRange = []
for theRange in ranges:
subRange = list(map(int, theRange.split("-")))
if (len(subRange) > 1):
newRange.extend(range(subRange[0], subRange[1] + 1))
else:
newRange.extend(subRange)
newRange.sort()
return newRange
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--pages", type=getList, dest="pages", default=[], help="pages to process")
args = parser.parse_args()
</code></pre>
<p>and it works but I'm relatively new to this Python thing and was wondering if there is a better way to do it?</p>
<p>Edit: I fail to see why it was marked as a duplicate question. <em>None</em> of the answers to the questions it was marked as a duplicate of does exactly what I have described above. The idea is <em>not</em> to process a simple list of space- or comma-delimited arguments but something more complex - a list of ranges that have to be expanded.</p>
| 1 | 2016-08-21T10:50:56Z | 39,066,191 | <p>Here's one solution. It's not necessarily the best. In particular, there is probably a more performant version involving chained iterators rather than nested iterators.</p>
<p>Given:</p>
<pre><code>>>> range='2,4-6,9,10-13'
</code></pre>
<p>You could do something like:</p>
<pre><code>>>> result = [range(int(y[0]), int(y[1])+1)
... for y in [(x.split('-') + [x])[:2]
... for x in r.split(',')]]
</code></pre>
<p>Which gets you:</p>
<pre><code>>>> result
[[2], [4, 5, 6], [9], [10, 11, 12, 13]]
</code></pre>
<p>If we unpack those comprehensions, the innermost one iterates over:</p>
<pre><code>>>> range.split(',')
['2', '4-6', '9', '10-13']
</code></pre>
<p>The second is:</p>
<pre><code>>>> result = range.split(',')
>>> [(x.split('-') + [x])[:2] for x in result]
[['2', '2'], ['4', '6'], ['9', '9'], ['10', '13']]
</code></pre>
<p>The expression <code>(x.split('-') + [x])[:2]</code> is ensuring that we have a two-item list, even for single numbers, so that we can pass that to the <code>range</code> function.</p>
<p>Finally, we iterate over that result:</p>
<pre><code>>>> [range(int(y[0]), int(y[1])+1) for y in <the result from the rpevious operation]
</code></pre>
<p>Which is hopefuly obvious. Given the list <code>[2, 2]</code>, we call <code>range(2, 3)</code> which gives us <code>[2]</code>. Applied across all the results from the previous operation, this gets us the result we saw earlier:</p>
<pre><code>[[2], [4, 5, 6], [9], [10, 11, 12, 13]]
</code></pre>
<p>And now your problem is "how do I flatten a list", to which one solution (from <a href="https://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">here</a>) is:</p>
<pre><code>>>> import itertools
>>> list(itertools.chain.from_iterable(result))
[2, 4, 5, 6, 9, 10, 11, 12, 13]
</code></pre>
| 1 | 2016-08-21T16:07:00Z | [
"python",
"argparse"
] |
How to do a "tree walk" recursively on an Abstract Syntax Tree? | 39,063,413 | <p>Simple example of assignment in my language:</p>
<pre><code>x = 3 ->
</code></pre>
<p>Here's the generated AST after parsing (In Python):</p>
<pre><code>[('statement', ('assignment', 'x', ('assignment_operator', '='), ('expr', ('term', ('factor', '3')))), '->')]
</code></pre>
<p>How can I recursively access any possible depth in order to, in the most trivial case, print all of them? (Or convert the text into something else?). Is there a specific algorithm for doing this? If there is, do you recommend any specific material?</p>
| 6 | 2016-08-21T10:55:55Z | 39,063,464 | <p>To walk a tree, just use a stack or a queue (depending on wether you want to go depth first or breath first).</p>
<p>For each node encountered, push the children onto the stack or into the queue, then take the next item out of the data structure to process and repeat.</p>
<p>For example, breath first could look like this:</p>
<pre><code>from collections import deque
def walk(node):
queue = deque([node])
while queue:
node = queue.popleft()
if isinstance(node, tuple):
queue.extend(node[1:]) # add the children to the queue
yield node
</code></pre>
<p>which produces the following walking order for your tree:</p>
<pre><code>>>> for node in walk(tree[0]):
... print(node[0] if isinstance(node, tuple) else node)
...
statement
assignment
->
x
assignment_operator
expr
=
term
factor
3
</code></pre>
<p>Your data structure is a little messy, mixing tuples of different length. You may want to look to using a <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow"><code>nametuple</code> class</a> to formalise the contents a little.</p>
| 6 | 2016-08-21T11:02:05Z | [
"python",
"recursion"
] |
golang appengine - filename too long | 39,063,494 | <p>I developed an appengine application in GO and now I tried to use the androidpublisher api. For this I need many dependencies like:</p>
<ul>
<li>github.com/google/google-api-go-client</li>
<li>github.com/golang/oauth2</li>
<li>google.golang.org/appengine</li>
<li>google.golang.org/appengine/urlfetch</li>
</ul>
<p>I tried to setup oauth2 authentication for google-api-go-client according to the example in <a href="https://github.com/golang/oauth2" rel="nofollow">https://github.com/golang/oauth2</a></p>
<p>Everything looks fine but I can't run the app-server anymore on my windows development machine. It complains about too long filenames:</p>
<pre><code>INFO 2016-08-20 22:48:03,786 devappserver2.py:769] Skipping SDK update check.
INFO 2016-08-20 22:48:03,960 api_server.py:205] Starting API server at: http://localhost:64053
INFO 2016-08-20 22:48:03,969 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO 2016-08-20 22:48:03,974 admin_server.py:116] Starting admin server at:http://localhost:8000
Exception in thread Instance Adjustment: Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\work\go_appengine\google\appengine\tools\devappserver2\module.py",line 1485, in _loop_adjusting_instances
self._adjust_instances()
File "C:\work\go_appengine\google\appengine\tools\devappserver2\module.py",line 1460, in _adjust_instances
self._add_instance(permit_warmup=True)
File "C:\work\go_appengine\google\appengine\tools\devappserver2\module.py",line 1338, in _add_instance
expect_ready_request=perform_warmup)
File "C:\work\go_appengine\google\appengine\tools\devappserver2\go_runtime.py",line 174, in new_instance
if self._go_application.maybe_build(self._modified_since_last_build):
File "C:\work\go_appengine\google\appengine\tools\devappserver2\go_application.py",line 304, in maybe_build
self._extras_hash, old_extras_hash = (self._get_extras_hash(),
File "C:\work\go_appengine\google\appengine\tools\devappserver2\go_application.py",line 247, in _get_extras_hash gab_stdout,
_ = self._run_gab(gab_args, env={})
File "C:\work\go_appengine\google\appengine\tools\devappserver2\go_application.py",line 175, in _run_gab
gab_extra_args, env)
File "C:\work\go_appengine\google\appengine\tools\devappserver2\go_application.py",line 111, in _run_gab
env=env)
File "C:\work\go_appengine\google\appengine\tools\devappserver2\safe_subprocess.py",line 74, in start_process
stdin=subprocess.PIPE, startupinfo=startupinfo)
File "C:\Python27\lib\subprocess.py", line710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 206] The filename or extension is too long
</code></pre>
<p>I think my <code>GOPATH</code> is set up wrong so he gives all gofiles as argument to <code>go-app-builder.exe</code>.</p>
<p>My project is under <code>C:\Users\me\project\</code> that's where the gopath points to and were I'm standing when I type: </p>
<pre><code>goapp.bat serve .
</code></pre>
<p>Can someone help to fix this problem? Thank you.</p>
<p><strong>EDIT</strong></p>
<p>My project structure is like this:
How should i set my GOPATH? </p>
<pre><code>GOPATH
$GOPATH
app.yaml
cron.yaml
pkg
src
testapp
app.go
golang.org
x
oauth2
</code></pre>
<p><strong>Edit 2</strong></p>
<p>I tried to move my GOPATH to project-root-dir/gopath but now i get this error message:</p>
<pre><code>Exception in thread Instance Adjustment: Traceback (most recent call last): File "C:\Python27\lib\threading.py", line 810, in
__bootstrap_inner
self.run() File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs) File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\module.py", line 1486, in _loop_adjusting_instances
self._adjust_instances() File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\module.py", line 1461, in _adjust_instances
self._add_instance(permit_warmup=True) File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\module.py", line 1339, in _add_instance
expect_ready_request=perform_warmup) File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\go_runtime.py", line 176, in new_instance
if self._go_application.maybe_build(self._modified_since_last_build): File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\go_application.py", line 304, in maybe_build
self._extras_hash, old_extras_hash = (self._get_extras_hash(), File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\go_application.py", line 247, in _get_extras_hash
gab_stdout, _ = self._run_gab(gab_args, env={}) File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\go_application.py", line 175, in _run_gab
gab_extra_args, env) File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\go_application.py", line 111, in _run_gab
env=env) File "C:\Users\Indra\development\tools\go_appengine\google\appengine\tools\devappserver2\safe_subprocess.py", line 74, in start_process
stdin=subprocess.PIPE, startupinfo=startupinfo) File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite) File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo) WindowsError: [Error 87] Falscher Parameter
</code></pre>
<p>for all non german users it complains about a wrong parameter</p>
| 2 | 2016-08-21T11:05:42Z | 39,132,556 | <p>I solved the problem by setting my GOPATH.</p>
<p>It's set now like this:</p>
<pre><code>GOPATH=C:\Users\me\development\appengine\gopath;C:\Users\me\project
</code></pre>
<p>Now everything works find and the uploaded file is much smaller now. 2MB vs. 11MB.</p>
<p>Thanks for the tip.</p>
| 0 | 2016-08-24T20:31:46Z | [
"python",
"google-app-engine",
"go"
] |
Update Cassandra Via python | 39,063,661 | <p>I'm quite new to python and I am trying to Update cassandra table via python. When i run the code following error appears.</p>
<pre><code>type error not all arguments converted during string formatting
</code></pre>
<p>error was in following line, is there anything wrong with the formatting with following code,</p>
<pre><code>session.execute('UPDATE CourseAssignment SET value = \'%s\' WHERE key = \'SYSTEM\'', (jsonObject))
</code></pre>
<p>"value" is a json object which is stored in a text column of cassandra.</p>
<pre><code>jsonObjectNew = json.dumps(jsonObject, indent=4, sort_keys=True)
</code></pre>
| 1 | 2016-08-21T11:26:59Z | 39,066,915 | <p>The error is because your string is malformed. In this case, it would be better to split the command in many lines for readability:</p>
<pre><code>command = """
UPDATE "CourseAssignment"
SET "value" = '%s'
WHERE "key" = "SYSTEM"
"""
</code></pre>
<p>Using the triple quotes, don't need escaping the inner quotes.</p>
<p>Now, to incorporate your JSON object, you can do:</p>
<pre><code>import json
jsonObject = {"one": 1, "two": [1, 10], "three": "string", "four": {"other":"etc."}}
jsonObjectNew = json.dumps(jsonObject, indent=4, sort_keys=True)
print(command % jsonObjectNew)
''' prints:
UPDATE "CourseAssignment"
SET "value" = '{
"four": {
"other": "etc."
},
"one": 1,
"three": "string",
"two": [
1,
10
]
}'
WHERE "key" = "SYSTEM"
'''
</code></pre>
<p>To use this command in your <code>session.execute()</code> command, don't use the <code>%</code> as you do with the print command, to prevent SQL injection and to assure proper escaping. Use the syntax recommended by your <a href="http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Session.execute" rel="nofollow">cassandra python driver</a>:</p>
<p>execute(statement[, parameters][, timeout][, trace][, custom_payload])</p>
<pre><code>session.execute(command, jsonObjectNew)
</code></pre>
| 0 | 2016-08-21T17:26:16Z | [
"python",
"python-3.x",
"cassandra"
] |
Saving Django model with DateTime fields | 39,063,671 | <p>Model:</p>
<pre><code>class Meal(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
collection_from = models.DateTimeField(blank=False, null=False)
discount_price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4)
normal_price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=4)
available_count = models.IntegerField(blank=False, null=False)
name = models.CharField(blank=False, null=False, max_length=255)
active = models.BooleanField(blank=False, null=False, default=True)
</code></pre>
<p>Now, when I'm saving it's instances the <code>created_at</code> and <code>updated_at</code> values are set properly, eg: <code>2016-08-21 13:13:57.585472+02</code>. <code>collection_from</code> value should be nearly the same as those two previous ones, but it's getting set to point to the next day, eg: <code>2016-08-22 01:00:00+02</code> which I don't get at all :). The <code>collection_from</code> value looks like that when sent by the browser: <code>2016-08-21 23:00</code>. I believe I have proper settings set up int the <code>settings.py</code> file:</p>
<pre><code>TIME_ZONE = 'UTC'
USE_TZ = True
</code></pre>
<p>So what's the problem here? How do I make Django save <code>collection_from</code> value the same way as <code>created_at</code> or <code>updated_at</code>?</p>
<p><strong>EDIT:</strong></p>
<p>I noticed that when the values for this model are retrieved, I get the correct ones - so if I the value of <code>collection_from</code> field is equal to <code>2016-08-22 01:00:00+02</code> in the database, on the output it's being converted to what the initial value was, so <code>2016-08-21 23:00</code>. So now the question changes - why the difference between <code>created_at</code> and <code>updated_at</code> fields and this one?</p>
<p><strong>EDIT2:</strong> </p>
<p>I didn't think it will be necessary (as I described well enough how I supply the <code>collection_from</code> value), but here's the POST request body:</p>
<pre><code>[{"collection_from":"2016-08-21 23:00","discount_price"
:"10","normal_price":"20","available_count":"4","name":"pizza"}]
</code></pre>
<p>And the DRF view saving it:</p>
<pre><code>class MealsCrudView(CreateAPIView):
serializer_class = MealSerializer
</code></pre>
<p>And the serializer:</p>
<pre><code>class MealSerializer(serializers.ModelSerializer):
class Meta:
model = Meal
</code></pre>
| 1 | 2016-08-21T11:28:21Z | 39,064,936 | <p>Did you try:</p>
<pre><code>from django.utils import timezone
class Meal(models.Model):
...
collection_from = models.DateTimeField(default=timezone.now)
...
</code></pre>
<p>instead of sending current time?</p>
| -1 | 2016-08-21T13:50:50Z | [
"python",
"django",
"datetime",
"django-rest-framework"
] |
How to boost a Keras based neural network using AdaBoost? | 39,063,676 | <p>Assuming I fit the following neural network for a binary classification problem:</p>
<pre><code>model = Sequential()
model.add(Dense(21, input_dim=19, init='uniform', activation='relu'))
model.add(Dense(80, init='uniform', activation='relu'))
model.add(Dense(80, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(x2, training_target, nb_epoch=10, batch_size=32, verbose=0,validation_split=0.1, shuffle=True,callbacks=[hist])
</code></pre>
<p>How would I boost the neural network using AdaBoost? Does keras have any commands for this?</p>
| 1 | 2016-08-21T11:28:46Z | 39,084,657 | <p>Keras itself does not implement adaboost. However, Keras models are compatible with scikit-learn, so you probably can use <code>AdaBoostClassifier</code> from there: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html" rel="nofollow">link</a>. Use your <code>model</code> as the <code>base_estimator</code> after you compile it, and <code>fit</code> the <code>AdaBoostClassifier</code> instance instead of <code>model</code>.</p>
<p>This way, however, you will not be able to use the arguments you pass to <code>fit</code>, such as number of epochs or batch_size, so the defaults will be used. If the defaults are not good enough, you might need to build your own class that implements the scikit-learn interface on top of your model and passes proper arguments to <code>fit</code>.</p>
| 2 | 2016-08-22T16:40:49Z | [
"python",
"neural-network",
"keras",
"adaboost",
"boosting"
] |
Ruby's ERB like feature in python | 39,063,728 | <p>I've configuration files some formatted as <code>json</code> some formatted as <code>yaml</code>. I want to be able to read those configuration files with values which comes as environment variables. for example:</p>
<pre><code>{"username":"Dan", "password":"<%= ENV['DB_PASSWORD']%>"}
</code></pre>
<p>Which means that password is retrieved when loading the json file from environment variable and replace the <code><%= ENV['DB_PASSWORD']%></code> with concrete value.</p>
<p><strong>Note:1. The syntax mentioned above is like it is being used using ruby's erb only for illustration
2. I prefer a solution of native python without installing new python packages, but if there no such ,I'll accept this also.</strong></p>
| 2 | 2016-08-21T11:33:49Z | 39,064,824 | <p>What you are looking for is commonly called <em>templating</em>, and you have basically defined a <em>template language</em>.</p>
<p>Depending on what <em>exactly</em> you want to do, you can use the <a href="https://docs.python.org/3/library/string.html#template-strings" rel="nofollow"><code>string.Template</code></a> library from the stdlib. It only does simple variable substitutions, though, as opposed to ERb, which allows <em>arbitrary</em> code (including code that deletes all your data, formats your harddisk, starts a backdoor, â¦).</p>
<p>So, <code>string.Template</code> is both <em>much</em> less powerful than ERb, but also <em>much</em> safer. Your example already demonstrates this, as you cannot even access environment variables from within a template, you would have to pass them in explicitly.</p>
<p>This is the basic usage:</p>
<pre><code>from string import Template
s = Template('{"username": "Dan", "password": "$db_password"}')
s.safe_substitute(db_password = 's00persekrit')
# >>> {"username": "Dan", "password": "s00persekrit"}
</code></pre>
<p>As accessing environment variables isn't possible inside the template, you will have to pass them in to the template explicitly:</p>
<pre><code>from string import Template
from os import environ as env
s = Template('{"username": "Dan", "password": "$db_password"}')
s.safe_substitute(db_password = env['DB_PASSWORD'])
# >>> {"username": "Dan", "password": "s00persekrit"}
</code></pre>
<p>Actually, if you want to give the template access to all environment variables, you should be able to pass the <code>os.environ</code> dict directly (you can pass any <code>dict</code>-like object for the mapping).</p>
<pre><code>from string import Template
from os import environ as env
s = Template('{"username": "Dan", "password": "$DB_PASSWORD"}')
s.safe_substitute(env)
# >>> {"username": "Dan", "password": "s00persekrit"}
</code></pre>
<p>If you want some more powerful substitutions, then you should look at some other so-called "logic-less" template languages (i.e. languages which only perform simple substitutions but don't allow executing code, and don't allow conditionals or loops). One of those languages is <a href="http://mustache.github.io/" rel="nofollow">Mustache</a> (the templating language used by GitHub), there are implementations in many languages, including <a href="https://github.com/defunkt/pystache/" rel="nofollow">Pystache for Python</a>.</p>
<p>If you want / need more advanced features such as loops, conditionals, etc., you might need to look for more full-featured <a href="https://wiki.python.org/moin/Templating" rel="nofollow">template languages</a> such as <a href="http://jinja.pocoo.org/" rel="nofollow">Jinja</a>.</p>
| 1 | 2016-08-21T13:39:16Z | [
"python",
"ruby",
"python-2.7"
] |
Python 2.7 [Errno 113] No route to host | 39,063,817 | <p>I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V command).</p>
<p>I copied simple python code from a computer networking book. </p>
<p>client.py</p>
<pre><code>from socket import *
serverName = '192.168.178.30'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence: ')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From Server:', modifiedSentence
clientSocket.close()
</code></pre>
<p>server.py</p>
<pre><code>from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('192.168.178.30',serverPort))
serverSocket.listen(5)
print 'The server is ready to receive'
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
</code></pre>
<p>The code works when it is ran on the same PC (where the server is listening on localhost).
When I run the client code on one PC and the server code on the other PC I get this error on the client side.</p>
<pre><code>Traceback (most recent call last):
File "client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
</code></pre>
<p>Can someone help?</p>
| 1 | 2016-08-21T11:44:49Z | 39,063,838 | <p>You should <code>bind</code> the server socket to <code>'0.0.0.0'</code>, not <code>'192.168.178.30'</code>.</p>
| 1 | 2016-08-21T11:47:24Z | [
"python",
"python-2.7",
"sockets"
] |
Python 2.7 [Errno 113] No route to host | 39,063,817 | <p>I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V command).</p>
<p>I copied simple python code from a computer networking book. </p>
<p>client.py</p>
<pre><code>from socket import *
serverName = '192.168.178.30'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence: ')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From Server:', modifiedSentence
clientSocket.close()
</code></pre>
<p>server.py</p>
<pre><code>from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('192.168.178.30',serverPort))
serverSocket.listen(5)
print 'The server is ready to receive'
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
</code></pre>
<p>The code works when it is ran on the same PC (where the server is listening on localhost).
When I run the client code on one PC and the server code on the other PC I get this error on the client side.</p>
<pre><code>Traceback (most recent call last):
File "client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
</code></pre>
<p>Can someone help?</p>
| 1 | 2016-08-21T11:44:49Z | 39,063,883 | <p>Check the firewall (on the server).</p>
| 1 | 2016-08-21T11:52:38Z | [
"python",
"python-2.7",
"sockets"
] |
Python 2.7 [Errno 113] No route to host | 39,063,817 | <p>I have 2 computers on the same LAN. The first PC has an ip address 192.168.178.30, the other PC has an ip address 192.168.178.26.
Ping, traceroute, telnet, ssh, everything works between the two PCs. Both PCs run the same OS - CentOS 7 and both PCs have the same python version 2.7.5 (checked with the python -V command).</p>
<p>I copied simple python code from a computer networking book. </p>
<p>client.py</p>
<pre><code>from socket import *
serverName = '192.168.178.30'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence: ')
clientSocket.send(sentence)
modifiedSentence = clientSocket.recv(1024)
print 'From Server:', modifiedSentence
clientSocket.close()
</code></pre>
<p>server.py</p>
<pre><code>from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('192.168.178.30',serverPort))
serverSocket.listen(5)
print 'The server is ready to receive'
while 1:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
</code></pre>
<p>The code works when it is ran on the same PC (where the server is listening on localhost).
When I run the client code on one PC and the server code on the other PC I get this error on the client side.</p>
<pre><code>Traceback (most recent call last):
File "client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 113] No route to host
</code></pre>
<p>Can someone help?</p>
| 1 | 2016-08-21T11:44:49Z | 39,063,973 | <p>I stopped the firewall like Messa suggested and now it works. </p>
<pre><code>service firewalld stop
</code></pre>
<p>I still don't understand what the problem was. I even tried using different distributions. Do all distributions have strict firewalls or something. For example Ubuntu to Ubuntu, Ubuntu to CentOS, CentOS to Ubuntu I still had the same problem (error).</p>
| 0 | 2016-08-21T12:05:23Z | [
"python",
"python-2.7",
"sockets"
] |
Django - How to restrict foreign key choices in dropdown menu depending on datatime field | 39,063,850 | <p><br>I have form for adding data in database and I want to restrict foreign key choices in my dropdown menu. It have to be restricted on my finishDate field. If finishDate is date before today (eg. today is 21-08-2016 and finishDate is 30-06-2013), then I don't want to show foreign key value of that finishDate. What is the easiest way to do this? I am relative new at this, so I need help.</p>
<p>models.py</p>
<pre><code>class Account(models.Model):
startDate = models.DateField(verbose_name="Start")
finishDate = models.DateField(verbose_name="Finish")
def __str__(self):
return 'A{}'.format(self.id)
class Net(models.Model):
date = models.DateTimeField(default=datetime.now())
MB = models.IntegerField(validators=[MinValueValidator(1)],default=randint(100,2000))
idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account")
def __str__(self):
return 'Record {}'.format(self.datum)
</code></pre>
<p>forms.py</p>
<pre><code>class NetForm(ModelForm):
class Meta:
model = Net
fields = ['idAccount']
</code></pre>
<p>views.py</p>
<pre><code>@login_required(login_url="/accounts/login/")
def net(request):
if request.method == 'POST':
form = NetForm(request.POST)
if form.is_valid():
internet = form.save()
return HttpResponseRedirect('/')
else:
form = NetForm()
return render(request, 'project/Net.html', {'form': form})
</code></pre>
<p>Thanks a lot!</p>
| 0 | 2016-08-21T11:49:11Z | 39,063,978 | <p>You can filter it in the <code>__init__</code></p>
<pre><code>import datetime
def NetForm(forms.ModelForm):
#...fields
def __init__(self, *args, **kwargs):
super(NetForm, self).__init__(*args, **kwargs)
# Now set the queryset...
self.fields['idAccount'].queryset = Account.objects.filter(finishDate__gte=datetime.datetime.now())
</code></pre>
| 0 | 2016-08-21T12:05:42Z | [
"python",
"django",
"date",
"dropdown"
] |
Python pyttsx, how to use external loop | 39,064,089 | <p>In my program I need class(which can be some thread) to check some list like "say_list" and when other classes add some text to it, pyttsx say that text.
I search in pyttsx <a href="http://pyttsx.readthedocs.io/en/latest/engine.html" rel="nofollow">docs</a> and I find some external loops feature but I can not find example which work correctly.
I want something like this:</p>
<pre><code>import pyttsx
import threading
class VoiceAssistant(threading.Thread):
def __init__(self):
super(VoiceAssistant, self).__init__()
self.engine = pyttsx.init()
self.say_list = []
def add_say(self, msg):
self.say_list.append(msg)
def run(self):
while True:
if len(self.say_list) > 0:
self.engine.say(self.say_list[0])
self.say_list.remove(self.say_list[0])
if __name__ == '__main__':
va = VoiceAssistant()
va.start()
</code></pre>
<p>Thanks.</p>
| 0 | 2016-08-21T12:16:58Z | 39,069,269 | <p>I can get the proper results by using python's built in Queue class:</p>
<pre><code>import pyttsx
from Queue import Queue
from threading import Thread
q = Queue()
def say_loop():
engine = pyttsx.init()
while True:
engine.say(q.get())
engine.runAndWait()
q.task_done()
def another_method():
t = Thread(target=say_loop)
t.daemon = True
t.start()
for i in range(0, 3):
q.put('Sally sells seashells by the seashore.')
print "end of another method..."
def third_method():
q.put('Something Something Something')
if __name__=="__main__":
another_method()
third_method()
q.join() # ends the loop when queue is empty
</code></pre>
<p>Above is a simple example I whipped up. It uses the 'queue/consumer' model to allow separate functions/classes to access the same queue, then a worker that will execute anytime the queue has items. Should be pretty easy to adapt to your needs. </p>
<p>Further reading about Queues: <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">https://docs.python.org/2/library/queue.html</a>
There appears to be an interface for this in the docs you linked to, but it seemed like you were already on the separate thread track so this seemed closer to what you wanted.</p>
<p>And here's the modified version of your code:</p>
<pre><code>import pyttsx
from Queue import Queue
import threading
class VoiceAssistant(threading.Thread):
def __init__(self):
super(VoiceAssistant, self).__init__()
self.engine = pyttsx.init()
self.q = Queue()
self.daemon = True
def add_say(self, msg):
self.q.put(msg)
def run(self):
while True:
self.engine.say(self.q.get())
self.engine.runAndWait()
self.q.task_done()
if __name__ == '__main__':
va = VoiceAssistant()
va.start()
for i in range(0, 3):
va.add_say('Sally sells seashells by the seashore.')
print "now we want to exit..."
va.q.join() # ends the loop when queue is empty
</code></pre>
| 1 | 2016-08-21T22:05:23Z | [
"python",
"text-to-speech",
"pyttsx"
] |
Failed to establish a new connection | 39,064,126 | <pre><code>import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '{"query":{"bool":{"must":[{"text":{"record.document":"SOME_JOURNAL"}},{"text":{"record.articleTitle":"farmers"}}],"must_not":[],"should":[]}},"from":0,"size":50,"sort":[],"facets":{}}'
response = requests.get(url, data=data)
</code></pre>
<p>when i run this code i get this error </p>
<pre><code> Traceback (most recent call last):
File "simpleclient.py", line 6, in <module>
response = requests.get(url, data=data)
File "/home/ryan/local/lib/python2.7/site-packages/requests/api.py", line 70, in get
return request('get', url, params=params, **kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/sessions.py", line 471, in request
resp = self.send(prep, **send_kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/sessions.py", line 581, in send
r = adapter.send(request, **kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/adapters.py", line 481, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='es_search_demo.com', port=80): Max retries exceeded with url: /document/record/_search?pretty=true (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f544af9a5d0>: Failed to establish a new connection: [Errno -2] Name or service not known',))
</code></pre>
| -1 | 2016-08-21T12:20:59Z | 39,064,181 | <p>Seems like your DNS server can't find an address associated to the URL you are passing</p>
| 0 | 2016-08-21T12:26:39Z | [
"python",
"python-2.7",
"ubuntu-14.04"
] |
Failed to establish a new connection | 39,064,126 | <pre><code>import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '{"query":{"bool":{"must":[{"text":{"record.document":"SOME_JOURNAL"}},{"text":{"record.articleTitle":"farmers"}}],"must_not":[],"should":[]}},"from":0,"size":50,"sort":[],"facets":{}}'
response = requests.get(url, data=data)
</code></pre>
<p>when i run this code i get this error </p>
<pre><code> Traceback (most recent call last):
File "simpleclient.py", line 6, in <module>
response = requests.get(url, data=data)
File "/home/ryan/local/lib/python2.7/site-packages/requests/api.py", line 70, in get
return request('get', url, params=params, **kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/sessions.py", line 471, in request
resp = self.send(prep, **send_kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/sessions.py", line 581, in send
r = adapter.send(request, **kwargs)
File "/home/ryan/local/lib/python2.7/site-packages/requests/adapters.py", line 481, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='es_search_demo.com', port=80): Max retries exceeded with url: /document/record/_search?pretty=true (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f544af9a5d0>: Failed to establish a new connection: [Errno -2] Name or service not known',))
</code></pre>
| -1 | 2016-08-21T12:20:59Z | 39,064,195 | <blockquote>
<p>NewConnectionError(': Failed to establish a new connection: [Errno -5] No address associated with hostname',))</p>
</blockquote>
<p>In other words, your DNS does not have an IP address for the given host.
Since there is, however, a valid IP address with the domain name <em>given originally</em>, probably there is no connection to the internet:</p>
<pre><code>$ nslookup mmsdemo.cloudapp.net
(...)
Non-authoritative answer:
Name: mmsdemo.cloudapp.net
Address: 40.113.108.105
</code></pre>
<p>In other words, check that the internet connection is set up properly (on the machine that runs your code, and more specifically, that python can make use of it).</p>
<p><strong>Update</strong></p>
<p>The hostname given originally was as in my first answer. The new domain now in the question proofs my assumption was right:</p>
<pre><code>$ nslookup es_search_demo.com
(...)
** server can't find es_search_demo.com: NXDOMAIN
</code></pre>
| 0 | 2016-08-21T12:29:07Z | [
"python",
"python-2.7",
"ubuntu-14.04"
] |
Python PyQt QLineEdit to Search bar | 39,064,247 | <p>am trying to build translator and put a search bar in it .with QLineEdit
and what i want is auto complet the word .
..
i tried this . but this code is not working , i'm talking about SearchBar function . but the rest of the code is working with the rest program just fine . but the SearchBar function not working . and not completing what i type in LineEdit</p>
<pre><code>from PyQt4 import QtGui,QtCore
import sys
from MainWin import Ui_MainWindow
import sqlite3
conn = sqlite3.connect('DictDB.db')
cors = conn.cursor()
class MainApp(QtGui.QMainWindow,Ui_MainWindow):
def __init__(self):
super(MainApp,self).__init__()
self.setupUi(self)
self.showMaximized()
cors.execute("SELECT * FROM DictContents")
for raw in cors.fetchall():
self.TextBrowserAra.append(raw[0])
self.TextBrowserGer.append(raw[1])
self.SearchBar(raw[0].strip(),raw[1].strip())
def SearchBar(self,keys,values):
mydict = {}
AraKey = mydict[0]=[keys]
GerKey = mydict[1]=[values]
Model = QtGui.QStringListModel()
ModAra = Model.setStringList(AraKey)
ModGer = Model.setStringList(GerKey)
completer = QtGui.QCompleter()
CompAra = completer.setModel(ModAra)
ComGer = completer.setModel(ModGer)
self.LineEditAra.setCompleter(CompAra)
self.LineEditGer.setCompleter(ComGer)
</code></pre>
| 0 | 2016-08-21T12:34:41Z | 39,064,919 | <p>The function setModel() and setCompleter() are void, return no value.</p>
<p>Doc: <a href="http://doc.qt.io/qt-4.8/qcompleter.html#setModel" rel="nofollow">setModel</a> <a href="http://doc.qt.io/qt-4.8/qlineedit.html#setCompleter" rel="nofollow">setCompleter</a></p>
<p>You can write like this:</p>
<pre><code> AraKey = ['a','ab','abc']
ModAra = QtGui.QStringListModel()
ModAra.setStringList(AraKey)
ComAra = QtGui.QCompleter()
ComAra.setModel(ModAra)
self.LineEditAra.setCompleter(ComAra)
</code></pre>
<p>I hava tried this, and it really works.</p>
| 0 | 2016-08-21T13:49:13Z | [
"python",
"pyqt4",
"pyqt5"
] |
Python PyQt QLineEdit to Search bar | 39,064,247 | <p>am trying to build translator and put a search bar in it .with QLineEdit
and what i want is auto complet the word .
..
i tried this . but this code is not working , i'm talking about SearchBar function . but the rest of the code is working with the rest program just fine . but the SearchBar function not working . and not completing what i type in LineEdit</p>
<pre><code>from PyQt4 import QtGui,QtCore
import sys
from MainWin import Ui_MainWindow
import sqlite3
conn = sqlite3.connect('DictDB.db')
cors = conn.cursor()
class MainApp(QtGui.QMainWindow,Ui_MainWindow):
def __init__(self):
super(MainApp,self).__init__()
self.setupUi(self)
self.showMaximized()
cors.execute("SELECT * FROM DictContents")
for raw in cors.fetchall():
self.TextBrowserAra.append(raw[0])
self.TextBrowserGer.append(raw[1])
self.SearchBar(raw[0].strip(),raw[1].strip())
def SearchBar(self,keys,values):
mydict = {}
AraKey = mydict[0]=[keys]
GerKey = mydict[1]=[values]
Model = QtGui.QStringListModel()
ModAra = Model.setStringList(AraKey)
ModGer = Model.setStringList(GerKey)
completer = QtGui.QCompleter()
CompAra = completer.setModel(ModAra)
ComGer = completer.setModel(ModGer)
self.LineEditAra.setCompleter(CompAra)
self.LineEditGer.setCompleter(ComGer)
</code></pre>
| 0 | 2016-08-21T12:34:41Z | 39,066,331 | <p>i found it .. it must pass a list to SearchBar function not a dict ..
so this works .. </p>
<pre><code> # first make an empty lists
self.AraList = []
self.GerList = []
for raw in cors.fetchall():
self.AraList.append(raw[0]) # put all data in one list
self.GerList.append(raw[1]) # " "
self.SearchBar(self.AraList,self.GerList) # passing the lists to SearchBar Function
def SearchBar(self,keys,values):
print(keys) #make sure its returns one big list , Lets try the keys first
ModAra = QtGui.QStringListModel()
ModAra.setStringList(keys)
ComAra = QtGui.QCompleter()
ComAra.setModel(ModAra)
self.LineEditAra.setCompleter(ComAra)
# It worked just fine
</code></pre>
| 0 | 2016-08-21T16:21:37Z | [
"python",
"pyqt4",
"pyqt5"
] |
Reconnecting to a websocket using AutoBahn | 39,064,347 | <p>I'm getting data from the <a href="https://poloniex.com/support/api/" rel="nofollow">Poloniex API</a> by consuming their websocket API. I'm using the <a href="https://pypi.python.org/pypi/autobahn" rel="nofollow">AutoBahn Python websocket library</a>. </p>
<p>Currently, I'm using the following code to print ticket data as it becomes available. This works well, but not for extended periods of time. Every 12-36 hours it stops producing output (I think when Poloniex restart their servers). </p>
<p>Is there an elegant way to check if the <code>ApplicationRunner</code> is still connected, and to restart it if it disconnects? The <code>onDisconnect</code> is not triggering. When I run the script, the process does not terminate when the socket stops receiving data, so I don't think that the event loop gets stopped.</p>
<pre><code>from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine
import asyncio
from datetime import datetime
class PoloniexComponent(ApplicationSession):
def onConnect(self):
self.join(self.config.realm)
@coroutine
def onJoin(self, details):
def onTicker(*args):
print("{}: {}".format(datetime.utcnow(), str(args)))
try:
yield from self.subscribe(onTicker, 'ticker')
except Exception as e:
print("Could not subscribe to topic:", e)
def onDisconnect(self):
asyncio.get_event_loop().stop()
def main():
runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
runner.run(PoloniexComponent)
if __name__ == "__main__":
main()
</code></pre>
| 1 | 2016-08-21T12:44:47Z | 39,546,824 | <p><em>Since WebSocket connections are persistent, and no data is sent when there's no need, without actual traffic it's not discovered that the underlying connection has been killed</em> (which is what happens when Poloniex Websocket server restart) - <em>at least not quickly.</em> </p>
<p><em>To enable reacting quickly and deterministically to the disconnect</em>, it is required to enable WebSocket auto pings on server side. [<a href="https://groups.google.com/forum/#!topic/autobahnws/wNRjnM8b67w" rel="nofollow">source</a>]</p>
<p>I don't know but suppose that polo have not activated this option ... </p>
<p>But you could build your "own" active ping version using something like this:</p>
<p>Create another ApplicationRunner instance (named "runner_watcher"), try to subscribe to a new topic with it and when it s done close the instance, then wait N second and restart the procedure, etc..</p>
<p>When the Exception ("Could not subscribe to topic") is raised on your "runner_watcher" instance, you may probably assume that server is down ..., so you force the stop of the primary ApplicationRunner and when server is back (no more Exception raised during execution of "runner_watcher", you may assume server is up again and restart the primary ApplicationRunner</p>
<p>I agree that this approach is dirty (not elegant), but it may probably works </p>
<p>Automatic reconnection was not yet implemented in autobahn <em>in 2015</em>, but currently in the works.</p>
| 0 | 2016-09-17T12:28:56Z | [
"python",
"python-3.x",
"websocket",
"python-asyncio",
"autobahn"
] |
How to assign a variable in my python script? | 39,064,392 | <p>im new to python and i have have script that need to parse different urls
for now i have been able only to make it like this..
i would like to assign a variable into URLList {0 to 10} instead of my solution
thanks you very much</p>
<pre><code>def ReadUrl():
URLList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',]
extracted_data =[]
for i in URLList:
url = "http://www.exemple.com/?&page="+i
print "Processing: "+url
extracted_data.append(SiteParser(url))
sleep(3)
f = open('urls.json','w')
json.dump(extracted_data, f, indent=4)
</code></pre>
| -3 | 2016-08-21T12:51:05Z | 39,064,405 | <p>Use <a href="https://docs.python.org/2/library/functions.html#xrange" rel="nofollow"><code>xrange</code></a> (or <code>range</code> in Python 3):</p>
<pre><code>for i in xrange(1, 11):
url = "http://www.exemple.com/?&page=" + str(i)
.
.
.
</code></pre>
| 1 | 2016-08-21T12:52:50Z | [
"python"
] |
Parsing data from JSON with python | 39,064,490 | <p>I'm just starting out with Python and here is what I'm trying to do. I want to access Bing's API to get the picture of the day's url. I can import the json file fine but then I can't parse the data to extract the picture's url.</p>
<p>Here is my python script:</p>
<pre><code>import urllib, json
url = "http://www.bing.com/HPImageArchive.aspx? format=js&idx=0&n=1&mkt=en-US"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
print data["images"][3]["url"]
</code></pre>
<p>I get this error: </p>
<pre><code>Traceback (most recent call last):
File "/Users/Robin/PycharmProjects/predictit/api.py", line 9, in <module>
print data["images"][3]["url"]
IndexError: list index out of range
</code></pre>
<p>FYI, here is what the JSON file looks like:
<a href="http://jsonviewer.stack.hu/#http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US" rel="nofollow">http://jsonviewer.stack.hu/#http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US</a></p>
| 1 | 2016-08-21T13:03:20Z | 39,064,538 | <pre><code>print data["images"][0]["url"]
</code></pre>
<p>there is only one object in "images" array</p>
| 0 | 2016-08-21T13:07:47Z | [
"python",
"json",
"api",
"parsing",
"bing"
] |
Parsing data from JSON with python | 39,064,490 | <p>I'm just starting out with Python and here is what I'm trying to do. I want to access Bing's API to get the picture of the day's url. I can import the json file fine but then I can't parse the data to extract the picture's url.</p>
<p>Here is my python script:</p>
<pre><code>import urllib, json
url = "http://www.bing.com/HPImageArchive.aspx? format=js&idx=0&n=1&mkt=en-US"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
print data["images"][3]["url"]
</code></pre>
<p>I get this error: </p>
<pre><code>Traceback (most recent call last):
File "/Users/Robin/PycharmProjects/predictit/api.py", line 9, in <module>
print data["images"][3]["url"]
IndexError: list index out of range
</code></pre>
<p>FYI, here is what the JSON file looks like:
<a href="http://jsonviewer.stack.hu/#http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US" rel="nofollow">http://jsonviewer.stack.hu/#http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US</a></p>
| 1 | 2016-08-21T13:03:20Z | 39,064,564 | <p>Since there is only one element in the <code>images</code> list, you should have <code>data['images'][0]['url']</code>.</p>
<p>You can also see that under the "Viewer" tab in the "json viewer" that you linked to.</p>
| 0 | 2016-08-21T13:11:10Z | [
"python",
"json",
"api",
"parsing",
"bing"
] |
Failed to run an ansible-play book, | 39,064,528 | <p>I created an ansible-playbook which does some system configuration, but when I run it on my cluster, it raises errors like: </p>
<pre><code> [WARNING]: Host file not found: /etc/ansible/hosts
[WARNING]: provided hosts list is empty, only localhost is available
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/home/ansible/goblin/roles/prepare-sys/tasks/main.yml': line 50, column 3, but maybe elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
mode=0644}
when: selinux_status !=0
^ here
</code></pre>
<p>Since I only run ansible via simple command line, This is my first time writing a structured playbook. Could any one tell me the mistakes I made here.</p>
<p>The structure of my playbook is: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>âââ group_vars
âââ host_vars
âââ prepare-sys
âââ prepare-sys.yml
âââ roles
â  âââ prepare-sys
â  âââ defaults
â  â  âââ main.yml
â  âââ files
â  â  âââ hosts
â  â  âââ ntp
â  â  â  âââ ntp.conf
â  â  âââ selinux
â  â  âââ umask
â  âââ handlers
â  â  âââ main.yml
â  âââ logs
â  âââ tasks
â  â  âââ main.yml
â  âââ templates
â  âââ disk.j2
â  âââ ntp.conf.slave.j2
âââ site.yml</code></pre>
</div>
</div>
master playbook site.yml:
---
# goblin/site.yml
# master playbook consists all sub playbooks</p>
<pre><code>- include: prepare-sys.yml
</code></pre>
<p>playbook prepare-sys.yml: </p>
<pre><code> ---
# file - playbook prepare-sys
- hosts: prepare-sys
roles:
- prepare-sys
</code></pre>
<p>inventory file: prepare-sys</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>[cluster]
10.254.2.160
10.254.2.92
10.254.2.93
10.254.2.94
[group1]
10.254.2.160
[group2]
10.254.2.93
[ansible_server]
127.0.0.1
[all:vars]
ansible_ssh_user= "root"
ansible_ssh_pass= "qwe123"</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>---
# goblin/roles/task/prepare.yml
# At the very beginning, we shall create a tmp dir on each remote nodes for sake of info collection
- name: Make Directory For latter Use
file: path=/tmp/ansible/mounts_log state=directory mode=0777
- name: copy local modified config files to DIR files
# list:
# - /etc/hosts
# - /etc/selinux/config
# - /etc/ntp.conf
# - /etc/bashrc
# - /etc/csh.cshrc
# - /etc/profile
local_action: copy src={{item.src}} dest={{item.dest}}
with_items:
- { src: "/etc/hosts", dest: "$GOBLIN_HOME/roles/prepare-sys/files/hosts/hosts" }
- { src: "/etc/selinux/config", dest: "$GOBLIN_HOME/roles/prepare-sys/files/selinux/config" }
- { src: "/etc/ntp.conf", dest: "$GOBLIN_HOME/roles/prepare-sys/files/ntp/ntp.conf" }
- { src: "/etc/bashrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc"}
- { src: "/etc/csh.cshrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc"}
- { src: "/etc/profile", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile"}
# OS Distribution and regarding Version need to be verified as present BC products flows better on Redhat/CentOS 6.5
- name: Check OS Distribution
fail: msg="inappropriate Operation System Distribution {{ansible_distribution}}"
when: (ansible_distribution != "CentOS") or (ansible_distribution != "Redhat")
- name: Check OS Version
fail: msg="inappropriate Operation System Version {{ansible_distribution_version}}"
when: ansible_distribution_version != 6.5
# Firewalls (iptables & selinux) must in off mode
- name: Turnoff Iptables
service: {
name: iptables,
state: stopped,
enabled: no
}
- name: Check selinux
shell: "getenforce"
register: selinux_status
- name: Turnoff selinux
selinux: state=disable
when: (selinux_status != 0)
- name: swap selinux file
copy:{
src="$GOBLIN_HOME/roles/prepare-sys/files/selinux/config",
dest=/etc/selinux/config,
owner=root,
group=root,
mode=0644
}
when: selinux_status !=0
# Ensuring data storage disks are at correct mount point, defualt format: /data1 -- /dataN or /chunk1 -- /chunkN
- name: Collect mount and fstype info
template: {
src="$GOBLIN_HOME/roles/prepare-sys/templates/disk.j2",
dest=/tmp/ansible/mounts_log/{{ansible_hostname}}.log
}
with_items: ansible_mounts
- name: fetch remote facts logs
fetch: {
src: "/tmp/ansible/mounts_log/{{ansible_hostname}}.log",
dest: "$GOBLIN_HOME/roles/prepare-sys/logs/",
flate: yes
}
# once the mount log has been fetched to dir logs/ , comparing this {{ansible_hostname}}.log file
# with a template file in files/mount_check_templates/
# there might be couple of templates prepared due to various situations
#- name: compare current operated remote server"s mounts_log with template mount_log
## Ensuring cluster"s clocks are in sync with appropriate ntp server with correct time zone(Asian/Shanghai)
# - name: set time zone
# timezone: name=Asian/Shanghai
# - name: set ntp service
# yum: name=ntp state=stopped
# notify:
# - set ntp configuration file
# tags: ntp
# - name: set ntp_server"s configuration file
# copy: src=file
# when: inventory_hostname in groups["ntp_server"]
###################################
- name: Check umask status
shell: "umask"
register: umask_status
- name: set umask
copy: {
src: "{{item.src}}",
dest: "{{item.dest}}"
}
with_items:
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc" , dest: "/etc/bashrc" }
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc", dest: "/etc/csh.cshrc"}
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile", dest: "/etc/profile"}
when: (umask_status != 0022 ) or (umask_status != 0002)
- name: set ulimit nofile use_max
pam_limits: domain=* limit_item=nofile limit_type=- use_max=yes
- name: set ulimit nproc use_max
pam_limits: {
domain=*,
limit_item=nproc,
limit_type=-,
value=unlimited,
use_max=yes,
dest=/etc/security/limits.d/90-nproc.conf
}
- name: update openssl
yum: name=openssl state=latest
- name: update hosts file
copy: {
src=files/hosts/hosts,
dest=/etc/hosts,
owner=root,
group=root,
mode=0644
}
# - name: update yum repository
# yum_repol:
...</code></pre>
</div>
</div>
</p>
<p>I corrected syntax of my playbook, and run --syntax-check, it throw errors like:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>ERROR! 'file' is not a valid attribute for a Play
The error appears to have been in '/home/ansible/goblin/roles/prepare-sys/tasks/main.yml': line 7, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Make Directory For latter Use
^ here</code></pre>
</div>
</div>
</p>
<p>updated playbook:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>---
# goblin/roles/task/prepare.yml
# At the very beginning, we shall create a tmp dir on each remote nodes for sake of info collection
# - name: read local environment varible
- name: Make Directory For latter Use
file: path=/tmp/ansible/mounts_log
state=directory
mode=0777
- name: copy local modified config files to DIR files
# list:
# - /etc/hosts
# - /etc/selinux/config
# - /etc/ntp.conf
# - /etc/bashrc
# - /etc/csh.cshrc
# - /etc/profile
local_action: copy src={{item.src}} dest={{item.dest}}
with_items:
- { src: "/etc/hosts", dest: "$GOBLIN_HOME/roles/prepare-sys/files/hosts/hosts" }
- { src: "/etc/selinux/config", dest: "$GOBLIN_HOME/roles/prepare-sys/files/selinux/config" }
- { src: "/etc/ntp.conf", dest: "$GOBLIN_HOME/roles/prepare-sys/files/ntp/ntp.conf" }
- { src: "/etc/bashrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc"}
- { src: "/etc/csh.cshrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc"}
- { src: "/etc/profile", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile"}
# OS Distribution and regarding Version need to be verified as present BC products flows better on Redhat/CentOS 6.5
#- name: Check OS Distribution
# fail: msg="inappropriate Operation System Distribution {{ansible_distribution}}"
# when: (ansible_distribution != "CentOS") or (ansible_distribution != "Redhat")
#- name: Check OS Version
# fail: msg="inappropriate Operation System Version {{ansible_distribution_version}}"
# when: ansible_distribution_version != 6.5
# Firewalls (iptables & selinux) must in off mode
- name: Turnoff Iptables
service: name=iptables
state=stopped
enabled=no
- name: Check selinux
shell: "getenforce"
register: selinux_status
- name: Turnoff selinux
selinux: state=disable
when: (selinux_status != 0)
- name: swap selinux file
copy: src="$GOBLIN_HOME/roles/prepare-sys/files/selinux/config"
dest=/etc/selinux/config
owner=root
group=root
mode=0644
when: selinux_status !=0
# Ensuring data storage disks are at correct mount point, defualt format: /data1 -- /dataN or /chunk1 -- /chunkN
- name: Collect mount and fstype info
template:
src="$GOBLIN_HOME/roles/prepare-sys/templates/disk.j2"
dest="/tmp/ansible/mounts_log/{{ansible_hostname}}.log"
with_items: ansible_mounts
- name: fetch remote facts logs
fetch: src="/tmp/ansible/mounts_log/{{ansible_hostname}}.log"
dest="$GOBLIN_HOME/roles/prepare-sys/logs/"
flate=yes
# once the mount log has been fetched to dir logs/ , comparing this {{ansible_hostname}}.log file
# with a template file in files/mount_check_templates/
# there might be couple of templates prepared due to various situations
#- name: compare current operated remote server"s mounts_log with template mount_log
## Ensuring cluster"s clocks are in sync with appropriate ntp server with correct time zone(Asian/Shanghai)
# - name: set time zone
# timezone: name=Asian/Shanghai
# - name: set ntp service
# yum: name=ntp state=stopped
# notify:
# - set ntp configuration file
# tags: ntp
# - name: set ntp_server"s configuration file
# copy: src=file
# when: inventory_hostname in groups["ntp_server"]
###################################
- name: Check umask status
shell: "umask"
register: umask_status
- name: set umask
copy: src="{{item.src}}"
dest="{{item.dest}}"
with_items:
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc" , dest: "/etc/bashrc" }
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc", dest: "/etc/csh.cshrc"}
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile", dest: "/etc/profile"}
when: (umask_status != 0022 ) or (umask_status != 0002)
- name: set ulimit nproc use_max
pam_limits: domain=*
limit_item=nproc
limit_type=-
value=unlimited
use_max=yes
dest=/etc/security/limits.d/90-nproc.conf
- name: update openssl
yum: name=openssl state=latest
- name: update hosts file
copy: src=files/hosts/hosts
dest=/etc/hosts
owner=root
group=root
mode=0644
...</code></pre>
</div>
</div>
</p>
<p>I googled this error, which saying it's caused by incorrect indentation but I tried run on YAMLlint, it shows the script is valid. so I'm wondering if there are some difference between ansible yaml syntax and normal yaml syntax</p>
| -1 | 2016-08-21T13:07:12Z | 39,065,130 | <p>You've got a syntax error in the task which Ansible complains about (although it points to a different line).</p>
<p>In <code>/home/ansible/goblin/roles/prepare-sys/tasks/main.yml</code> change:</p>
<pre><code>copy:{
</code></pre>
<p>To:</p>
<pre><code>copy: {
</code></pre>
| 1 | 2016-08-21T14:10:04Z | [
"python",
"ansible",
"ansible-playbook"
] |
Failed to run an ansible-play book, | 39,064,528 | <p>I created an ansible-playbook which does some system configuration, but when I run it on my cluster, it raises errors like: </p>
<pre><code> [WARNING]: Host file not found: /etc/ansible/hosts
[WARNING]: provided hosts list is empty, only localhost is available
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/home/ansible/goblin/roles/prepare-sys/tasks/main.yml': line 50, column 3, but maybe elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
mode=0644}
when: selinux_status !=0
^ here
</code></pre>
<p>Since I only run ansible via simple command line, This is my first time writing a structured playbook. Could any one tell me the mistakes I made here.</p>
<p>The structure of my playbook is: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>âââ group_vars
âââ host_vars
âââ prepare-sys
âââ prepare-sys.yml
âââ roles
â  âââ prepare-sys
â  âââ defaults
â  â  âââ main.yml
â  âââ files
â  â  âââ hosts
â  â  âââ ntp
â  â  â  âââ ntp.conf
â  â  âââ selinux
â  â  âââ umask
â  âââ handlers
â  â  âââ main.yml
â  âââ logs
â  âââ tasks
â  â  âââ main.yml
â  âââ templates
â  âââ disk.j2
â  âââ ntp.conf.slave.j2
âââ site.yml</code></pre>
</div>
</div>
master playbook site.yml:
---
# goblin/site.yml
# master playbook consists all sub playbooks</p>
<pre><code>- include: prepare-sys.yml
</code></pre>
<p>playbook prepare-sys.yml: </p>
<pre><code> ---
# file - playbook prepare-sys
- hosts: prepare-sys
roles:
- prepare-sys
</code></pre>
<p>inventory file: prepare-sys</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>[cluster]
10.254.2.160
10.254.2.92
10.254.2.93
10.254.2.94
[group1]
10.254.2.160
[group2]
10.254.2.93
[ansible_server]
127.0.0.1
[all:vars]
ansible_ssh_user= "root"
ansible_ssh_pass= "qwe123"</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>---
# goblin/roles/task/prepare.yml
# At the very beginning, we shall create a tmp dir on each remote nodes for sake of info collection
- name: Make Directory For latter Use
file: path=/tmp/ansible/mounts_log state=directory mode=0777
- name: copy local modified config files to DIR files
# list:
# - /etc/hosts
# - /etc/selinux/config
# - /etc/ntp.conf
# - /etc/bashrc
# - /etc/csh.cshrc
# - /etc/profile
local_action: copy src={{item.src}} dest={{item.dest}}
with_items:
- { src: "/etc/hosts", dest: "$GOBLIN_HOME/roles/prepare-sys/files/hosts/hosts" }
- { src: "/etc/selinux/config", dest: "$GOBLIN_HOME/roles/prepare-sys/files/selinux/config" }
- { src: "/etc/ntp.conf", dest: "$GOBLIN_HOME/roles/prepare-sys/files/ntp/ntp.conf" }
- { src: "/etc/bashrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc"}
- { src: "/etc/csh.cshrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc"}
- { src: "/etc/profile", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile"}
# OS Distribution and regarding Version need to be verified as present BC products flows better on Redhat/CentOS 6.5
- name: Check OS Distribution
fail: msg="inappropriate Operation System Distribution {{ansible_distribution}}"
when: (ansible_distribution != "CentOS") or (ansible_distribution != "Redhat")
- name: Check OS Version
fail: msg="inappropriate Operation System Version {{ansible_distribution_version}}"
when: ansible_distribution_version != 6.5
# Firewalls (iptables & selinux) must in off mode
- name: Turnoff Iptables
service: {
name: iptables,
state: stopped,
enabled: no
}
- name: Check selinux
shell: "getenforce"
register: selinux_status
- name: Turnoff selinux
selinux: state=disable
when: (selinux_status != 0)
- name: swap selinux file
copy:{
src="$GOBLIN_HOME/roles/prepare-sys/files/selinux/config",
dest=/etc/selinux/config,
owner=root,
group=root,
mode=0644
}
when: selinux_status !=0
# Ensuring data storage disks are at correct mount point, defualt format: /data1 -- /dataN or /chunk1 -- /chunkN
- name: Collect mount and fstype info
template: {
src="$GOBLIN_HOME/roles/prepare-sys/templates/disk.j2",
dest=/tmp/ansible/mounts_log/{{ansible_hostname}}.log
}
with_items: ansible_mounts
- name: fetch remote facts logs
fetch: {
src: "/tmp/ansible/mounts_log/{{ansible_hostname}}.log",
dest: "$GOBLIN_HOME/roles/prepare-sys/logs/",
flate: yes
}
# once the mount log has been fetched to dir logs/ , comparing this {{ansible_hostname}}.log file
# with a template file in files/mount_check_templates/
# there might be couple of templates prepared due to various situations
#- name: compare current operated remote server"s mounts_log with template mount_log
## Ensuring cluster"s clocks are in sync with appropriate ntp server with correct time zone(Asian/Shanghai)
# - name: set time zone
# timezone: name=Asian/Shanghai
# - name: set ntp service
# yum: name=ntp state=stopped
# notify:
# - set ntp configuration file
# tags: ntp
# - name: set ntp_server"s configuration file
# copy: src=file
# when: inventory_hostname in groups["ntp_server"]
###################################
- name: Check umask status
shell: "umask"
register: umask_status
- name: set umask
copy: {
src: "{{item.src}}",
dest: "{{item.dest}}"
}
with_items:
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc" , dest: "/etc/bashrc" }
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc", dest: "/etc/csh.cshrc"}
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile", dest: "/etc/profile"}
when: (umask_status != 0022 ) or (umask_status != 0002)
- name: set ulimit nofile use_max
pam_limits: domain=* limit_item=nofile limit_type=- use_max=yes
- name: set ulimit nproc use_max
pam_limits: {
domain=*,
limit_item=nproc,
limit_type=-,
value=unlimited,
use_max=yes,
dest=/etc/security/limits.d/90-nproc.conf
}
- name: update openssl
yum: name=openssl state=latest
- name: update hosts file
copy: {
src=files/hosts/hosts,
dest=/etc/hosts,
owner=root,
group=root,
mode=0644
}
# - name: update yum repository
# yum_repol:
...</code></pre>
</div>
</div>
</p>
<p>I corrected syntax of my playbook, and run --syntax-check, it throw errors like:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>ERROR! 'file' is not a valid attribute for a Play
The error appears to have been in '/home/ansible/goblin/roles/prepare-sys/tasks/main.yml': line 7, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Make Directory For latter Use
^ here</code></pre>
</div>
</div>
</p>
<p>updated playbook:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>---
# goblin/roles/task/prepare.yml
# At the very beginning, we shall create a tmp dir on each remote nodes for sake of info collection
# - name: read local environment varible
- name: Make Directory For latter Use
file: path=/tmp/ansible/mounts_log
state=directory
mode=0777
- name: copy local modified config files to DIR files
# list:
# - /etc/hosts
# - /etc/selinux/config
# - /etc/ntp.conf
# - /etc/bashrc
# - /etc/csh.cshrc
# - /etc/profile
local_action: copy src={{item.src}} dest={{item.dest}}
with_items:
- { src: "/etc/hosts", dest: "$GOBLIN_HOME/roles/prepare-sys/files/hosts/hosts" }
- { src: "/etc/selinux/config", dest: "$GOBLIN_HOME/roles/prepare-sys/files/selinux/config" }
- { src: "/etc/ntp.conf", dest: "$GOBLIN_HOME/roles/prepare-sys/files/ntp/ntp.conf" }
- { src: "/etc/bashrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc"}
- { src: "/etc/csh.cshrc", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc"}
- { src: "/etc/profile", dest: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile"}
# OS Distribution and regarding Version need to be verified as present BC products flows better on Redhat/CentOS 6.5
#- name: Check OS Distribution
# fail: msg="inappropriate Operation System Distribution {{ansible_distribution}}"
# when: (ansible_distribution != "CentOS") or (ansible_distribution != "Redhat")
#- name: Check OS Version
# fail: msg="inappropriate Operation System Version {{ansible_distribution_version}}"
# when: ansible_distribution_version != 6.5
# Firewalls (iptables & selinux) must in off mode
- name: Turnoff Iptables
service: name=iptables
state=stopped
enabled=no
- name: Check selinux
shell: "getenforce"
register: selinux_status
- name: Turnoff selinux
selinux: state=disable
when: (selinux_status != 0)
- name: swap selinux file
copy: src="$GOBLIN_HOME/roles/prepare-sys/files/selinux/config"
dest=/etc/selinux/config
owner=root
group=root
mode=0644
when: selinux_status !=0
# Ensuring data storage disks are at correct mount point, defualt format: /data1 -- /dataN or /chunk1 -- /chunkN
- name: Collect mount and fstype info
template:
src="$GOBLIN_HOME/roles/prepare-sys/templates/disk.j2"
dest="/tmp/ansible/mounts_log/{{ansible_hostname}}.log"
with_items: ansible_mounts
- name: fetch remote facts logs
fetch: src="/tmp/ansible/mounts_log/{{ansible_hostname}}.log"
dest="$GOBLIN_HOME/roles/prepare-sys/logs/"
flate=yes
# once the mount log has been fetched to dir logs/ , comparing this {{ansible_hostname}}.log file
# with a template file in files/mount_check_templates/
# there might be couple of templates prepared due to various situations
#- name: compare current operated remote server"s mounts_log with template mount_log
## Ensuring cluster"s clocks are in sync with appropriate ntp server with correct time zone(Asian/Shanghai)
# - name: set time zone
# timezone: name=Asian/Shanghai
# - name: set ntp service
# yum: name=ntp state=stopped
# notify:
# - set ntp configuration file
# tags: ntp
# - name: set ntp_server"s configuration file
# copy: src=file
# when: inventory_hostname in groups["ntp_server"]
###################################
- name: Check umask status
shell: "umask"
register: umask_status
- name: set umask
copy: src="{{item.src}}"
dest="{{item.dest}}"
with_items:
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/bashrc" , dest: "/etc/bashrc" }
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/csh.cshrc", dest: "/etc/csh.cshrc"}
- {src: "$GOBLIN_HOME/roles/prepare-sys/files/umask/profile", dest: "/etc/profile"}
when: (umask_status != 0022 ) or (umask_status != 0002)
- name: set ulimit nproc use_max
pam_limits: domain=*
limit_item=nproc
limit_type=-
value=unlimited
use_max=yes
dest=/etc/security/limits.d/90-nproc.conf
- name: update openssl
yum: name=openssl state=latest
- name: update hosts file
copy: src=files/hosts/hosts
dest=/etc/hosts
owner=root
group=root
mode=0644
...</code></pre>
</div>
</div>
</p>
<p>I googled this error, which saying it's caused by incorrect indentation but I tried run on YAMLlint, it shows the script is valid. so I'm wondering if there are some difference between ansible yaml syntax and normal yaml syntax</p>
| -1 | 2016-08-21T13:07:12Z | 39,075,153 | <p>Your playbook syntax is flawed.<br>
This code is a mix of dict and string parameters passing, which will not work even if you fix the typo (space between <code>:</code> and <code>{</code>).</p>
<pre><code># THIS CODE IS WRONG
- name: swap selinux file
copy:{
src="$GOBLIN_HOME/roles/prepare-sys/files/selinux/config",
dest=/etc/selinux/config,
owner=root,
group=root,
mode=0644
}
when: selinux_status !=0
</code></pre>
<p>You should either pass parameters with <code>param=value</code> single string, like this:</p>
<pre><code>- name: swap selinux file
copy: src="$GOBLIN_HOME/roles/prepare-sys/files/selinux/config"
dest=/etc/selinux/config
owner=root
group=root
mode=0644
when: selinux_status !=0
</code></pre>
<p>The sting with parameters <code>src=... dest=... ...</code> is actually a single line, I just used a YAML trick to split one line to multiples lines.<br>
But if you have complex arguments, you are encouraged to use dict-style parameters passing:</p>
<pre><code>- name: swap selinux file
copy: {
src: "$GOBLIN_HOME/roles/prepare-sys/files/selinux/config",
dest: /etc/selinux/config,
owner: root,
group: root,
mode: 0644
}
when: selinux_status !=0
</code></pre>
<p>And you may write the same dict in a more YAML-way (without braces and commas):</p>
<pre><code>- name: swap selinux file
copy:
src: "$GOBLIN_HOME/roles/prepare-sys/files/selinux/config"
dest: /etc/selinux/config
owner: root
group: root
mode: 0644
when: selinux_status !=0
</code></pre>
<p>So please correct all your playbook with this rule in mind.<br>
Then check syntax with <code>ansible-playbook --syntax-check myplaybook.yml</code> and you are good to go.</p>
| 0 | 2016-08-22T08:56:22Z | [
"python",
"ansible",
"ansible-playbook"
] |
How to use SimpleHTTPServer? | 39,064,577 | <p>I'm trying to start a simple http server with the most recent version of Python 2.7. I'm following a tutorial and it instructs me to do the following:</p>
<p>Open the Terminal then navigate to our client directory and enter the following command:</p>
<pre><code>$ python -m SimpleHTTPServer
</code></pre>
<p>But no matter what I've tried, including other codes, it doesn't work. Can anyone help please? It always puts a syntax error such as:</p>
<p>'$' is not recognized as an internal or external command, operable program or batch file.</p>
<p>If I leave out the $, it returns:</p>
<p>'Python' is not recognized as an internal or external command, operable program or batch file.</p>
<p>I've tried starting python from the Python27 directory, then changing to the directory I want to start the server from and using the same commands, but nothing works! It then says Syntax Error.</p>
| 0 | 2016-08-21T13:12:45Z | 39,064,595 | <p>The dollar sign is not part of the command:</p>
<p><code>python -m SimpleHTTPServer</code></p>
<p>I guess it was simply used as a representation for the command line prompt
in the tutorial you have been following</p>
| 0 | 2016-08-21T13:14:14Z | [
"python",
"terminal",
"server",
"directory",
"simplehttpserver"
] |
How to use SimpleHTTPServer? | 39,064,577 | <p>I'm trying to start a simple http server with the most recent version of Python 2.7. I'm following a tutorial and it instructs me to do the following:</p>
<p>Open the Terminal then navigate to our client directory and enter the following command:</p>
<pre><code>$ python -m SimpleHTTPServer
</code></pre>
<p>But no matter what I've tried, including other codes, it doesn't work. Can anyone help please? It always puts a syntax error such as:</p>
<p>'$' is not recognized as an internal or external command, operable program or batch file.</p>
<p>If I leave out the $, it returns:</p>
<p>'Python' is not recognized as an internal or external command, operable program or batch file.</p>
<p>I've tried starting python from the Python27 directory, then changing to the directory I want to start the server from and using the same commands, but nothing works! It then says Syntax Error.</p>
| 0 | 2016-08-21T13:12:45Z | 39,065,687 | <p>Firstly, if you're just starting to learn Python, I (and the members of the <a href="http://sopython.com" rel="nofollow">Stack Overflow Python community</a>) <strong>strongly</strong> <a href="http://sopython.com/wiki/What_tutorial_should_I_read%3F" rel="nofollow">recommend</a> using <a href="https://www.python.org/downloads/release/python-352/" rel="nofollow">Python 3</a>. Py2 is the past, Py3 is the present and future of the language. Support for Py2 ends in 2020, while Py3 will be supported indefinitely. You will learn some bad habits with Py2 that will make learning Py3 (which you'll have to do eventually) that much harder. Learn Py3 now, and when you're proficient with it you can then go back and see what the differences are with Py2. Also, stay away from the <em>Learn Python the Hard Way</em> tutorial. <a href="http://sopython.com/wiki/LPTHW_Complaints" rel="nofollow">It's bad</a>.</p>
<p>When you go to the download page I linked above, choose the installer for your version of Windows - if you're using 64-bit Windows, choose the 64-bit installer. When you run it, change the default installation directory to <code>C:\Python35</code>, and select the option to add the installation directory to your PATH. Once installation is complete, you can then uninstall Python 2 if you wish.</p>
<p>You can now open up the command line and run</p>
<pre><code>python -m SimpleHTTPServer
</code></pre>
<p>and it should work as expected.</p>
| 0 | 2016-08-21T15:10:13Z | [
"python",
"terminal",
"server",
"directory",
"simplehttpserver"
] |
why must one use __iter__() method in classes? | 39,064,605 | <p>What exactly is the role of <strong>iter</strong>? Consider the following code block:</p>
<pre><code>class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
</code></pre>
<p>omitting <strong>iter</strong>(self) and rewritting:</p>
<pre><code>class Reverse2:
def __init__(self,data):
self.data = data
self.index = len(data)
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
</code></pre>
<p>Then:</p>
<pre><code>x = [1,2,3]
y = Reverse(x)
z = Reverse2(x)
y.next()
>>> 3
y.next()
>>> 2
y.next()
>>> 1
z.next()
>>> 3
z.next()
>>> 2
z.next()
>>> 1
</code></pre>
<p>The classes behave the same way regardless of whether I include <strong>iter</strong>() or not, so why should i include it in the first place? I'm sorry if my question isn't clear--I simply don't know how to state it in a more clear way...</p>
| 0 | 2016-08-21T13:14:47Z | 39,064,642 | <p>The __iter__ return the <a href="https://docs.python.org/3/library/stdtypes.html#iterator-types" rel="nofollow">iterator object</a> which allows to convert the object to a container which can be iterated via <code>for .. in ..</code>.</p>
<p>The iterator object is any object which define __next__ method which returns the next item if exists or raise <code>StopIteration</code> otherwise.</p>
<p>While __iter__ can return any such iterator object, It can return itself if it implement __next__ method.</p>
<p>For example:</p>
<pre><code>class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
</code></pre>
<p>Now you can use in for loops:</p>
<pre><code>for xx in Reverse(x):
print xx
</code></pre>
| 0 | 2016-08-21T13:19:26Z | [
"python"
] |
why must one use __iter__() method in classes? | 39,064,605 | <p>What exactly is the role of <strong>iter</strong>? Consider the following code block:</p>
<pre><code>class Reverse:
def __init__(self,data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
</code></pre>
<p>omitting <strong>iter</strong>(self) and rewritting:</p>
<pre><code>class Reverse2:
def __init__(self,data):
self.data = data
self.index = len(data)
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
</code></pre>
<p>Then:</p>
<pre><code>x = [1,2,3]
y = Reverse(x)
z = Reverse2(x)
y.next()
>>> 3
y.next()
>>> 2
y.next()
>>> 1
z.next()
>>> 3
z.next()
>>> 2
z.next()
>>> 1
</code></pre>
<p>The classes behave the same way regardless of whether I include <strong>iter</strong>() or not, so why should i include it in the first place? I'm sorry if my question isn't clear--I simply don't know how to state it in a more clear way...</p>
| 0 | 2016-08-21T13:14:47Z | 39,064,657 | <p>The <code>__iter__</code> method is always called, when an iterator is needed, e.g. by explicitly calling <code>iter</code> or in <code>for</code>-loops or when creating lists <code>list(xy)</code>.</p>
<p>So you cannot use your second class <code>Reverse2</code> in all these contexts.</p>
<pre><code>>>> list(Reverse("abc"))
['c', 'b', 'a']
>>> list(Reverse2("abc"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: iteration over non-sequence
</code></pre>
<p>To answer the question in the comment: the <code>__iter__</code>-method must return any iterator or instance with a <code>__next__</code>-method. Only if your class is a iterator by itself, it should return <code>self</code>. An example of returning a generator as iterator:</p>
<pre><code>class Reverse3:
def __init__(self,data):
self.data = data
def __iter__(self):
# returns an generator as iterator
for idx in range(len(self.data)-1, -1, -1):
yield self.data[idx]
</code></pre>
| 1 | 2016-08-21T13:21:12Z | [
"python"
] |
Numpy: advanced slices | 39,064,607 | <p>I need a fast way to find the smallest element among three neighbor elements in a string, and add it to element under the central element. For border elements only two upper elements are checking.</p>
<p>For example I have a numpy array:</p>
<pre><code> [1, 2, 3, 4, 5],
[0, 0, 0, 0, 0]
</code></pre>
<p>I should get this:</p>
<pre><code> [1, 2, 3, 4, 5],
[1, 1, 2, 3, 4]
</code></pre>
<p>I have this code:</p>
<pre><code>for h in range(1, matrix.shape[0]):
matrix[h][0] = min(matrix[h - 1][0], matrix[h - 1][1])
matrix[h][1:-1] = ...(DONT KNOW, WHAT SHOULD BE HERE!!)
matrix[h][-1] = min(matrix[h - 1][-2], matrix[h - 1][-1])
</code></pre>
<p>How can I count it without using more <code>for</code> loops because I have too much data and I need to make it fast? <code>Edit:</code> David-z, here is my project) <a href="http://i.stack.imgur.com/NSJHo.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NSJHo.jpg" alt="Seam carving"></a></p>
| 1 | 2016-08-21T13:15:11Z | 39,064,754 | <p>Use <code>numpy.minimum.reduce</code>:</p>
<pre><code>matrix[h][1:-1] = numpy.minimum.reduce([matrix[h-1][0:-2], matrix[h-1][1:-1], matrix[h-1][2:]])
</code></pre>
<p>For example:</p>
<pre><code>>>> matrix = numpy.zeros((2,10))
>>> matrix[0, :] = numpy.random.randint(0,100,10)
>>> h = 1
>>> matrix[h][0] = matrix[h-1][:2].min()
>>> matrix[h][1:-1] = numpy.minimum.reduce([matrix[h-1][0:-2], matrix[h-1][1:-1], matrix[h-1][2:]])
>>> matrix[h][-1] = matrix[h-1][-2:].min()
>>> matrix
array([[ 10., 40., 90., 13., 21., 58., 64., 56., 34., 69.],
[ 10., 10., 13., 13., 13., 21., 56., 34., 34., 34.]])
</code></pre>
| 2 | 2016-08-21T13:32:42Z | [
"python",
"arrays",
"performance",
"numpy",
"slice"
] |
Numpy: advanced slices | 39,064,607 | <p>I need a fast way to find the smallest element among three neighbor elements in a string, and add it to element under the central element. For border elements only two upper elements are checking.</p>
<p>For example I have a numpy array:</p>
<pre><code> [1, 2, 3, 4, 5],
[0, 0, 0, 0, 0]
</code></pre>
<p>I should get this:</p>
<pre><code> [1, 2, 3, 4, 5],
[1, 1, 2, 3, 4]
</code></pre>
<p>I have this code:</p>
<pre><code>for h in range(1, matrix.shape[0]):
matrix[h][0] = min(matrix[h - 1][0], matrix[h - 1][1])
matrix[h][1:-1] = ...(DONT KNOW, WHAT SHOULD BE HERE!!)
matrix[h][-1] = min(matrix[h - 1][-2], matrix[h - 1][-1])
</code></pre>
<p>How can I count it without using more <code>for</code> loops because I have too much data and I need to make it fast? <code>Edit:</code> David-z, here is my project) <a href="http://i.stack.imgur.com/NSJHo.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NSJHo.jpg" alt="Seam carving"></a></p>
| 1 | 2016-08-21T13:15:11Z | 39,064,969 | <p>I would do it explicitly for somewhat more clarity with explicit slicing</p>
<pre><code>n = 10
x = np.random.randint(0,100,n)
y = np.zeros_like(x,dtype=int)
for ind in range(n):
if ind == 0:
lo , hi = None , ind + 2
elif ind >= n-2:
lo , hi = ind - 1 , None
else:
lo , hi = ind - 1 , ind + 2
y[ind] = np.min(x[lo:hi])
</code></pre>
<p>An example output is </p>
<pre><code>[21 74 95 96 6 96 78 74 6 92 5 32 72 64 30 13 72 59 19 26]
[21 21 74 6 6 6 74 6 6 5 5 5 32 30 13 13 13 19 19 19]
</code></pre>
| 1 | 2016-08-21T13:53:30Z | [
"python",
"arrays",
"performance",
"numpy",
"slice"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.