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
listlengths
1
5
Using QApplication::exec() in a function or class
38,800,568
<p>I want the following code to get the request url starting with <code>http://down.51en.com:88</code> during the web loading process , and then do other processing with the response object of the url . In my program, once <code>targetUrl</code> is assigned a value , I want the function <code>targetUrlGetter(url)</code> to return it to the caller, however , the problem is that <code>QApplication::exec()</code> enters the main event loop so cannot execute code at the end of the<code>targetUrlGetter()</code> function after the exec() call , thus the function cannot return , I have tried with <code>qApp.quit()</code> in <code>interceptRequest(self, info)</code> in order to tell the application to exit so that <code>targetUrlGetter(url)</code> can return , but the function still cannot return and the program even crashes on exit(tested on Win7 32bit), so how can I return the <code>targetUrl</code> to the caller program ?</p> <p>The difficulties here are how to exit the Qt event loop without crash and return the request url to the caller.</p> <pre><code>import sys from PyQt5.QtWidgets import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtWebEngineCore import * from PyQt5.QtCore import * class WebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor): def __init__(self, parent=None): super().__init__(parent) self.page = parent def interceptRequest(self, info): if info.requestUrl().toString().startswith('http://down.51en.com:88'): self.targetUrl = info.requestUrl().toString() print('----------------------------------------------', self.targetUrl) qApp.quit() # self.page.load(QUrl('')) def targetUrlGetter(url=None): app = QApplication(sys.argv) page = QWebEnginePage() globalSettings = page.settings().globalSettings() globalSettings.setAttribute( QWebEngineSettings.PluginsEnabled, True) globalSettings.setAttribute( QWebEngineSettings.AutoLoadImages, False) profile = page.profile() webEngineUrlRequestInterceptor = WebEngineUrlRequestInterceptor(page) profile.setRequestInterceptor(webEngineUrlRequestInterceptor) page.load(QUrl(url)) # view = QWebEngineView() # view.setPage(page) # view.show() app.exec_() return webEngineUrlRequestInterceptor.targetUrl url = "http://www.51en.com/news/sci/everything-there-is-20160513.html" # url = "http://www.51en.com/news/sci/obese-dad-s-sperm-may-influence-offsprin.html" # url = "http://www.51en.com/news/sci/mars-surface-glass-could-hold-ancient-fo.html" targetUrl = targetUrlGetter(url) print(targetUrl) </code></pre>
0
2016-08-06T04:33:38Z
38,810,188
<p>You should always initialize <code>QApplication</code> at the beginning of the program, and always call the <code>QApplication::exec</code> function at the end of the program.</p> <p>Another thing is that <code>QWebEngineUrlRequestInterceptor.interceptRequest</code> is a callback function which is called asynchronously. Since <code>info.requestUrl().toString()</code> is called inside the callback function, there is <em>no way</em> to <code>return</code> the result it synchronously.</p> <pre><code>import sys from PyQt5.QtWidgets import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtWebEngineCore import * from PyQt5.QtCore import * class WebEngineUrlRequestInterceptor(QWebEngineUrlRequestInterceptor): def __init__(self, parent=None): super().__init__(parent) self.page = parent def interceptRequest(self, info): if info.requestUrl().toString().startswith('http://down.51en.com:88'): self.targetUrl = info.requestUrl().toString() print('----------------------------------------------', self.targetUrl) # Don't do thatDo you really want to exit the whole program? # qApp.quit() # Do something here, rather than return it. # It must be run asynchronously # self.page.load(QUrl('')) def targetUrlGetter(url=None): page = QWebEnginePage() globalSettings = page.settings().globalSettings() globalSettings.setAttribute( QWebEngineSettings.PluginsEnabled, True) globalSettings.setAttribute( QWebEngineSettings.AutoLoadImages, False) profile = page.profile() webEngineUrlRequestInterceptor = WebEngineUrlRequestInterceptor(page) profile.setRequestInterceptor(webEngineUrlRequestInterceptor) page.load(QUrl(url)) # view = QWebEngineView() # view.setPage(page) # view.show() # Don't return this. It cannot be called synchronously. It must be called asynchronously. # return webEngineUrlRequestInterceptor.targetUrl app = QApplication(sys.argv) # always initialize QApplication at the beginning of the program url = "http://www.51en.com/news/sci/everything-there-is-20160513.html" # url = "http://www.51en.com/news/sci/obese-dad-s-sperm-may-influence-offsprin.html" # url = "http://www.51en.com/news/sci/mars-surface-glass-could-hold-ancient-fo.html" targetUrl = targetUrlGetter(url) print(targetUrl) app.exec_() # always call the QApplication::exec at the end of the program </code></pre>
-1
2016-08-07T01:49:05Z
[ "python", "qt", "pyqt", "qt5", "pyqt5" ]
Pandas read_csv incorrectly reading headers
38,800,587
<p>I am reading a csv file using 'pd.read_csv' and writing it to another csv using 'file.to_csv'. It is incorrectly displaying the headers in the output file. For example,</p> <p><strong>input</strong>: </p> <pre><code>ABC | 20151004 | 1900 | 0000000002 | MUPPETS SP 1-10/4, THE | | | R|RS 0 0 0 0 0 2993 </code></pre> <p><strong>script</strong>:</p> <pre><code>data = pd.read_csv(r'filepath/input.csv') </code></pre> <p>print data</p> <p><strong>Input header</strong>: <code>ABC | 20151004 | 1900 | 0000000002 | MUPPETS SP 1-10/4, THE | | | R|RS</code></p> <p><strong>Output header</strong>: <code>ABC | 20151004 | 1900 | 0000000002 | MUPPETS SP 1-10/4, THE | | | R|RS.1</code></p> <p>Not sure why it is adding <code>'.1'</code> to the end of some of the headers.</p>
-2
2016-08-06T04:37:56Z
38,806,408
<p>Try this:</p> <pre><code>data = pd.read_csv(r'filepath/input.csv',sep='|') </code></pre> <p>The rs.1 is likely indicative of duplicate 'rs' columns</p>
0
2016-08-06T16:30:23Z
[ "python", "pandas" ]
My submit button in html template is not working in django
38,800,710
<p>I prepared an attendance register template in HTML.I have a HTML table and a submit button in the given HTML page.While clicking the submit button,i want to save the data in HTML table.But i can't.</p> <p>Ist std.html</p> <pre><code> {% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Attendance register&lt;/title&gt; &lt;style&gt; table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 5px; text-align: left; } table#t01 { width: 100%; background-color: #f1f1c1; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;&lt;center&gt;&lt;u&gt;ATTENDANCE-REGISTER&lt;/u&gt;&lt;/center&gt;&lt;/h1&gt;&lt;br&gt; &lt;h2&gt;&lt;center&gt;&lt;i&gt;Ist Standard&lt;/i&gt;&lt;/center&gt;&lt;/h2&gt; &lt;h4&gt;Class in-charge: Hema.B &lt;br&gt;&lt;br&gt; Date: June 2016 - March 2017&lt;/h4&gt; &lt;form name="demo_form.asp" method="get"&gt; &lt;button type="submit" value="continue"&gt;Submit&lt;/button&gt; &lt;/form&gt; {% if user.is_authenticated %} &lt;a href="{% url 'post_new' %}" class="top-menu"&gt;&lt;span class="glyphicon glyphicon-plus"&gt;&lt;/span&gt;&lt;/a&gt; {% endif %} &lt;table style="width:100%"&gt; &lt;tr&gt; &lt;th&gt;Slno&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Attendance&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;Abijith&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="aNumber"&gt; &lt;button onclick="aFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="abFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="abNumber"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;Adithya&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="bNumber"&gt; &lt;button onclick="bFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="acFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="acNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;Bavana&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="cNumber"&gt; &lt;button onclick="cFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="adFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="adNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;Bibin&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="dNumber"&gt; &lt;button onclick="dFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="aeFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="aeNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;5&lt;/td&gt; &lt;td&gt;Devan&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="eNumber"&gt; &lt;button onclick="eFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="afFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="afNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;6&lt;/td&gt; &lt;td&gt;Faizal&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="fNumber"&gt; &lt;button onclick="fFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="agFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="agNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;Ganga&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="gNumber"&gt; &lt;button onclick="gFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="ahFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="ahNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;Haris&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="hNumber"&gt; &lt;button onclick="hFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="aiFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="aiNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;9&lt;/td&gt; &lt;td&gt;Jamsina&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="iNumber"&gt; &lt;button onclick="iFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="ajFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="ajNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;10&lt;/td&gt; &lt;td&gt;Tara&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="jNumber"&gt; &lt;button onclick="jFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="akFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="akNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br&gt; &lt;body&gt; &lt;script&gt; function aFunction() { document.getElementById("aNumber").stepUp(); } function abFunction() { document.getElementById("abNumber").stepUp(); } function bFunction() { document.getElementById("bNumber").stepUp(); } function acFunction() { document.getElementById("acNumber").stepUp(); } function cFunction() { document.getElementById("cNumber").stepUp(); } function adFunction() { document.getElementById("adNumber").stepUp(); } function dFunction() { document.getElementById("dNumber").stepUp(); } function aeFunction() { document.getElementById("aeNumber").stepUp(); } function eFunction() { document.getElementById("eNumber").stepUp(); } function afFunction() { document.getElementById("afNumber").stepUp(); } function fFunction() { document.getElementById("fNumber").stepUp(); } function agFunction() { document.getElementById("agNumber").stepUp(); } function gFunction() { document.getElementById("gNumber").stepUp(); } function ahFunction() { document.getElementById("ahNumber").stepUp(); } function hFunction() { document.getElementById("hNumber").stepUp(); } function aiFunction() { document.getElementById("aiNumber").stepUp(); } function iFunction() { document.getElementById("iNumber").stepUp(); } function ajFunction() { document.getElementById("ajNumber").stepUp(); } function jFunction() { document.getElementById("jNumber").stepUp(); } function akFunction() { document.getElementById("akNumber").stepUp(); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Views.py</p> <pre><code>def Ist_std(request): if 'save' in request.POST: form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('blog/IInd_std.html', pk=post.pk) else: form = PostForm() return render(request, 'blog/Ist_std.html') </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^Ist_std/$', views.Ist_std, name='Ist_std'), ] </code></pre>
0
2016-08-06T05:00:30Z
38,800,761
<p>In the template the <code>form</code> is closed before any <code>input</code> elements are defined, therefore the form will not contain any of the data entered as part of the table.</p> <p>You can fix it by moving the <code>&lt;/form&gt;</code> closing tag to somewhere after the end of the table.</p> <p>Furthermore the <code>&lt;input&gt;</code> tags do not have <code>name</code> attributes, so none of the values entered in the input elements can be passed in the HTTP request. For example the first table row could be written as:</p> <pre><code> &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;Abijith&lt;/td&gt; &lt;td&gt; &lt;input type="number" id="aNumber" name="aNumber"&gt; &lt;button onclick="aFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="abFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="abNumber" name="abNumber"&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>note that <code>name</code> attributes have been added to the input tags.</p> <p>There might be other problems, but this is the one that stood out to me.</p> <p><strong>Edit</strong></p> <p>One other problem is that the view expects the data to be sent in a POST request, however, the form is using GET. Change the HTML form to use <code>method="post"</code>.</p>
0
2016-08-06T05:08:31Z
[ "python", "html", "django", "django-forms" ]
My submit button in html template is not working in django
38,800,710
<p>I prepared an attendance register template in HTML.I have a HTML table and a submit button in the given HTML page.While clicking the submit button,i want to save the data in HTML table.But i can't.</p> <p>Ist std.html</p> <pre><code> {% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Attendance register&lt;/title&gt; &lt;style&gt; table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 5px; text-align: left; } table#t01 { width: 100%; background-color: #f1f1c1; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;&lt;center&gt;&lt;u&gt;ATTENDANCE-REGISTER&lt;/u&gt;&lt;/center&gt;&lt;/h1&gt;&lt;br&gt; &lt;h2&gt;&lt;center&gt;&lt;i&gt;Ist Standard&lt;/i&gt;&lt;/center&gt;&lt;/h2&gt; &lt;h4&gt;Class in-charge: Hema.B &lt;br&gt;&lt;br&gt; Date: June 2016 - March 2017&lt;/h4&gt; &lt;form name="demo_form.asp" method="get"&gt; &lt;button type="submit" value="continue"&gt;Submit&lt;/button&gt; &lt;/form&gt; {% if user.is_authenticated %} &lt;a href="{% url 'post_new' %}" class="top-menu"&gt;&lt;span class="glyphicon glyphicon-plus"&gt;&lt;/span&gt;&lt;/a&gt; {% endif %} &lt;table style="width:100%"&gt; &lt;tr&gt; &lt;th&gt;Slno&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Attendance&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;Abijith&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="aNumber"&gt; &lt;button onclick="aFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="abFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="abNumber"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;Adithya&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="bNumber"&gt; &lt;button onclick="bFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="acFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="acNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;Bavana&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="cNumber"&gt; &lt;button onclick="cFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="adFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="adNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;Bibin&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="dNumber"&gt; &lt;button onclick="dFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="aeFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="aeNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;5&lt;/td&gt; &lt;td&gt;Devan&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="eNumber"&gt; &lt;button onclick="eFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="afFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="afNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;6&lt;/td&gt; &lt;td&gt;Faizal&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="fNumber"&gt; &lt;button onclick="fFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="agFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="agNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;Ganga&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="gNumber"&gt; &lt;button onclick="gFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="ahFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="ahNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;8&lt;/td&gt; &lt;td&gt;Haris&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="hNumber"&gt; &lt;button onclick="hFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="aiFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="aiNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;9&lt;/td&gt; &lt;td&gt;Jamsina&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="iNumber"&gt; &lt;button onclick="iFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="ajFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="ajNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;10&lt;/td&gt; &lt;td&gt;Tara&lt;/td&gt; &lt;td&gt;&lt;input type="number" id="jNumber"&gt; &lt;button onclick="jFunction()"&gt;&lt;font color="green"&gt;Present&lt;/button&gt; &lt;button onclick="akFunction()"&gt;&lt;font color="red"&gt;Absent&lt;/button&gt; &lt;input type="number" id="akNumber"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br&gt; &lt;body&gt; &lt;script&gt; function aFunction() { document.getElementById("aNumber").stepUp(); } function abFunction() { document.getElementById("abNumber").stepUp(); } function bFunction() { document.getElementById("bNumber").stepUp(); } function acFunction() { document.getElementById("acNumber").stepUp(); } function cFunction() { document.getElementById("cNumber").stepUp(); } function adFunction() { document.getElementById("adNumber").stepUp(); } function dFunction() { document.getElementById("dNumber").stepUp(); } function aeFunction() { document.getElementById("aeNumber").stepUp(); } function eFunction() { document.getElementById("eNumber").stepUp(); } function afFunction() { document.getElementById("afNumber").stepUp(); } function fFunction() { document.getElementById("fNumber").stepUp(); } function agFunction() { document.getElementById("agNumber").stepUp(); } function gFunction() { document.getElementById("gNumber").stepUp(); } function ahFunction() { document.getElementById("ahNumber").stepUp(); } function hFunction() { document.getElementById("hNumber").stepUp(); } function aiFunction() { document.getElementById("aiNumber").stepUp(); } function iFunction() { document.getElementById("iNumber").stepUp(); } function ajFunction() { document.getElementById("ajNumber").stepUp(); } function jFunction() { document.getElementById("jNumber").stepUp(); } function akFunction() { document.getElementById("akNumber").stepUp(); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Views.py</p> <pre><code>def Ist_std(request): if 'save' in request.POST: form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('blog/IInd_std.html', pk=post.pk) else: form = PostForm() return render(request, 'blog/Ist_std.html') </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^Ist_std/$', views.Ist_std, name='Ist_std'), ] </code></pre>
0
2016-08-06T05:00:30Z
38,800,824
<p>You should not be manually generating your form like that in your html. I can see that you have already had a look at django forms. May I propose the following:</p> <pre><code>&lt;form name="demo_form.asp" method="post"&gt; {% csrf_token %} {{ form.as_p }} &lt;button type="submit" value="continue"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>There are lot's of other <a href="https://docs.djangoproject.com/en/1.9/topics/forms/#form-rendering-options" rel="nofollow">form rendering options</a> as well. This approach will also ensure that the correct messages are displayed automatically when the form validation fails.</p> <p>Also note that I have changed GET to POST. It's always better to use post for forms. I have added {% csrf_token %} remove this if you do not have the csrf middleware installed.</p>
1
2016-08-06T05:20:30Z
[ "python", "html", "django", "django-forms" ]
Install Python mysqlclient on Ubuntu docker container
38,800,723
<p>I want to install <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">Python's mysqlclient</a> package on a Docker container running <a href="https://hub.docker.com/_/ubuntu/" rel="nofollow">Ubuntu</a>. The installation fails because I don't have gcc installed in the container:</p> <pre><code>x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,3,7,'final',1) -D__version__=1.3.7 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -fabi-version=2 -fno-omit-frame-pointer unable to execute 'x86_64-linux-gnu-gcc': No such file or directory error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 </code></pre> <p>However, I do not want to install gcc in the container. Is there a wheel available for mysqlclient? I cannot find any.</p>
0
2016-08-06T05:01:58Z
38,800,828
<p>You can install the build dependencies, make the module, then remove them.</p> <p><a href="https://github.com/docker-library/redis/blob/8929846148513a1e35e4212003965758112f8b55/3.0/Dockerfile#L24" rel="nofollow">Redis is a good example</a> of how to build and cleanup in one step so you don't create a bulky image layer. </p> <pre><code>RUN buildDeps='gcc libc6-dev make' \ &amp;&amp; set -x \ &amp;&amp; apt-get update &amp;&amp; apt-get install -y $buildDeps --no-install-recommends \ &amp;&amp; rm -rf /var/lib/apt/lists/* \ &amp;&amp; mkdir -p /usr/src/redis \ &amp;&amp; curl -sSL "$REDIS_DOWNLOAD_URL" -o redis.tar.gz \ &amp;&amp; echo "$REDIS_DOWNLOAD_SHA1 *redis.tar.gz" | sha1sum -c - \ &amp;&amp; tar -xzf redis.tar.gz -C /usr/src/redis --strip-components=1 \ &amp;&amp; rm redis.tar.gz \ &amp;&amp; make -C /usr/src/redis \ &amp;&amp; make -C /usr/src/redis install \ &amp;&amp; rm -r /usr/src/redis \ &amp;&amp; apt-get purge -y --auto-remove $buildDeps </code></pre>
0
2016-08-06T05:20:43Z
[ "python", "ubuntu", "docker" ]
Install Python mysqlclient on Ubuntu docker container
38,800,723
<p>I want to install <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">Python's mysqlclient</a> package on a Docker container running <a href="https://hub.docker.com/_/ubuntu/" rel="nofollow">Ubuntu</a>. The installation fails because I don't have gcc installed in the container:</p> <pre><code>x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,3,7,'final',1) -D__version__=1.3.7 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -fabi-version=2 -fno-omit-frame-pointer unable to execute 'x86_64-linux-gnu-gcc': No such file or directory error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 </code></pre> <p>However, I do not want to install gcc in the container. Is there a wheel available for mysqlclient? I cannot find any.</p>
0
2016-08-06T05:01:58Z
38,906,785
<p>I created a container and installed everything I needed to build mysqlclient. I downloaded the .tgz and used <code>python setup.py bdist_wheel</code> to generate the Wheel file. I copied over the wheel file to a directory mounted from my host machine, and installed it on the container where I wanted mysqlclient installed. This way I didn't have to remove the packages I downloaded. I saved the instance of the container with gcc as a separate image for future use.</p>
0
2016-08-11T22:01:07Z
[ "python", "ubuntu", "docker" ]
How to split large txt file into small txt files by line using python
38,800,810
<p>I have a large txt file contains 1 million lines, I want to split them into small txt files each contains 10 lines, how to do it using python? I found some related questions and have code like this :</p> <pre><code>def split_file(filepath, lines=30): """Split a file based on a number of lines.""" path, filename = os.path.split(filepath) # filename.split('.') would not work for filenames with more than one . basename, ext = os.path.splitext(filename) # open input file with open(filepath, 'r') as f_in: try: # open the first output file f_out = open(os.path.join(path, '{}_{}{}'.format(basename, 0, ext)), 'w') # loop over all lines in the input file, and number them for i, line in enumerate(f_in): # every time the current line number can be divided by the # wanted number of lines, close the output file and open a # new one if i % lines == 0: f_out.close() f_out = open(os.path.join(path, '{}_{}{}'.format(basename, i, ext)), 'w') # write the line to the output file f_out.write(line) finally: # close the last output file f_out.close() </code></pre> <p>However it only functions in small txt file but does not work in my target file, and does not have error information I don't know why.</p>
-3
2016-08-06T05:17:32Z
38,806,953
<p>This should work. It's a little roundabout, but should circumvent your mystery error while being human readable.</p> <p>First let's define a couple of useful functions. The first reads a file and makes each line a list element, and the second writes lists as files.</p> <p>Note, the second function will create a new file if no file with that name exists or overwrite the file if one does.</p> <pre><code>def line_reader(target_file): with open(target_file, 'r') as file: store = file.readlines() return store def line_writer(file_name, store): with open(file_name, 'w') as file: file.writelines(store) </code></pre> <p>Next, let's define the function that will actually break files into smaller files.</p> <pre><code>def breakdown(target, new_file_name, chunk_length = 10): # First let's store a list representing the data from the original file data = line_reader(target) # part_no is solely for naming purposes part_no = 0 # this list will be used to hold smaller chunks of lines tmp_list = [] condition = True while condition: for i in range(chunk_length): # just a basic check to make sure that there are still lines left to be replaced if len(data) &gt; 0: tmp_list.append(data.pop(0)) else: condition = False tmp_list.append('\n') break part_no += 1 line_writer(str(new_file_name + ' ' + str(part_no)), tmp_list) tmp_list = [] </code></pre> <p>Calling breakdown will split target into smaller files of <code>chunk_length</code> lines (10 by default) followed by a single blank line at the end. The last file will just be whatever's left from the original file.</p>
0
2016-08-06T17:29:40Z
[ "python", "text", "split" ]
python 2.7 regular expression match with \r\n in string
38,800,817
<p>Wondering if any ways to match string contains <code>\r \n</code>? It seems the same regular expression match does not work if input string content contains <code>\r \n</code>. Using Python 2.7.</p> <p><strong>works pretty good</strong>,</p> <pre><code>import re content = '{(1) hello (1)}' reg = '{\(1\)(.*?)\(1\)}' results = re.findall(reg, content) print results[0] prog = re.compile(reg) results = prog.findall(content) print results[0] </code></pre> <p><strong>will not work when add <code>\r \n</code></strong></p> <pre><code>import re content = '{(1) hello \r\n (1)}' reg = '{\(1\)(.*?)\(1\)}' results = re.findall(reg, content) print results[0] prog = re.compile(reg) results = prog.findall(content) print results[0] </code></pre> <p>regards, Lin</p>
0
2016-08-06T05:19:28Z
38,800,849
<p>This works:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; content = '{(1) hello \r\n (1)}' &gt;&gt;&gt; reg = '{\(1\)(.*?)\(1\)}' &gt;&gt;&gt; results = re.findall(reg, content, re.DOTALL) &gt;&gt;&gt; &gt;&gt;&gt; print results[0] hello &gt;&gt;&gt; &gt;&gt;&gt; prog = re.compile(reg, re.DOTALL) &gt;&gt;&gt; results = prog.findall(content) &gt;&gt;&gt; &gt;&gt;&gt; print results[0] hello &gt;&gt;&gt; </code></pre> <p>From <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Python Docs</a>: </p> <blockquote> <p>'.' (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.</p> </blockquote>
2
2016-08-06T05:23:56Z
[ "python", "regex", "python-2.7" ]
NameError: name 'driver' is not defined
38,800,908
<p>I use above code to scrape friend list from facebook UID and am getting an error: </p> <pre><code> File "C:\Users\Tn\PycharmProjects\untitled\test\1.py", line 15, in friend_uid_list soup = from_uid(uid) File "C:\Users\Tn\PycharmProjects\untitled\test\1.py", line 11, in from_uid driver.get('https://www.facebook.com/' + uid + '/friends') NameError: name 'driver' is not defined """ </code></pre> <p>Can you show me how to fix it ? Thank you very much ! Below code is my code</p> <pre><code>import multiprocessing from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By def from_uid(uid): driver.get('https://www.facebook.com/' + uid + '/friends') return BeautifulSoup(driver.page_source, "html5lib") def friend_uid_list(uid): soup = from_uid(uid) friends = soup.find_all("div", class_="fsl fwb fcb") target = open('C:/friend_uid_list.txt', 'a') for href in friends: href = href.find('a') try: target.write(href + "\n") except: pass target.close() if __name__ == '__main__': driver = webdriver.Firefox() driver.get("https://www.facebook.com/") driver.find_element_by_css_selector("#email").send_keys("myemail@gmail.com") driver.find_element_by_css_selector("#pass").send_keys("mypass") driver.find_element_by_css_selector("#u_0_m").click() pool = multiprocessing.Pool(3) pool.map(friend_uid_list, [100004159542140,100004159542140,100004159542140]) </code></pre>
0
2016-08-06T05:34:09Z
38,801,204
<p>The reason is simple: <strong>You create some new processes, and it can't see the variables in another process(main process).</strong></p> <p>There are several solutions: </p> <ol> <li><p>Pass the variables you need as arguments. But this is not possible since <code>driver</code> is not picklable.</p></li> <li><p>Create a new driver for each process.</p></li> <li><p>Use multi-threading instead of multi-processing. However I'm not sure if selenium works this way, you'll have to test it yourself.</p></li> </ol>
0
2016-08-06T06:21:06Z
[ "python", "python-3.x", "multiprocessing" ]
How to concat multiple functions in python
38,800,914
<p>How to do this in python?</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c </code></pre> <p>How to get something like <code>k = f+g</code> hence that</p> <pre><code>k(a, b) is g(f(a,b)) </code></pre> <p>Note that this is an abstract question. I wonder whether there's a function that can return a concat of <code>f+g</code> or even concat([...]) generally working regardless of the args of <code>f</code>.</p> <p>In another word, I want a function whose args is <code>f</code> and <code>g</code> and returns <code>k</code>:</p> <pre><code>def concat(f,g): return something_equivalent_to_k_above </code></pre>
2
2016-08-06T05:35:23Z
38,800,945
<h3>Answer for original question</h3> <p>Define:</p> <pre><code>k = lambda x,y:g(*f(x,y)) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; k(2,3) 13 </code></pre> <h3>Answer for revised question</h3> <p>Define:</p> <pre><code>concat = lambda a,b:lambda *args: b(*a(*args)) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; k = concat(f,g) &gt;&gt;&gt; k(2,3) 13 </code></pre>
4
2016-08-06T05:41:23Z
[ "python", "functools" ]
How to concat multiple functions in python
38,800,914
<p>How to do this in python?</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c </code></pre> <p>How to get something like <code>k = f+g</code> hence that</p> <pre><code>k(a, b) is g(f(a,b)) </code></pre> <p>Note that this is an abstract question. I wonder whether there's a function that can return a concat of <code>f+g</code> or even concat([...]) generally working regardless of the args of <code>f</code>.</p> <p>In another word, I want a function whose args is <code>f</code> and <code>g</code> and returns <code>k</code>:</p> <pre><code>def concat(f,g): return something_equivalent_to_k_above </code></pre>
2
2016-08-06T05:35:23Z
38,801,006
<p>Why not define a third function as you did with <code>f</code> and <code>g</code>:</p> <pre><code>&gt;&gt;&gt; def f(a, b): return a, b+2, b+3 &gt;&gt;&gt; def g(a,b,c): return a+b+c &gt;&gt;&gt; def k(a,b): return g(*f(a,b)) &gt;&gt;&gt; k(2,3) 13 </code></pre>
1
2016-08-06T05:51:46Z
[ "python", "functools" ]
How to concat multiple functions in python
38,800,914
<p>How to do this in python?</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c </code></pre> <p>How to get something like <code>k = f+g</code> hence that</p> <pre><code>k(a, b) is g(f(a,b)) </code></pre> <p>Note that this is an abstract question. I wonder whether there's a function that can return a concat of <code>f+g</code> or even concat([...]) generally working regardless of the args of <code>f</code>.</p> <p>In another word, I want a function whose args is <code>f</code> and <code>g</code> and returns <code>k</code>:</p> <pre><code>def concat(f,g): return something_equivalent_to_k_above </code></pre>
2
2016-08-06T05:35:23Z
38,801,609
<p>There are at least 2 approaches to do this:</p> <p>Approach A (recommended):</p> <pre><code>def compound(inner_func, outer_func): def wrapper(*args, **kwargs): return outer_func(*inner_func(*args, **kwargs)) return wrapper </code></pre> <p>Note that <code>inner_func</code> mustn't return a dictionary, in which case we should write <code>return outer_func(**inner_func(*args, **argv))</code>.</p> <p>Usage:</p> <pre><code>def f(a, b): return a, b+2, b+3 def g(a, b, c): return a+b+c k = compound(f, g) print k(1, 2) # output: 10 </code></pre> <hr> <p>Approach B:</p> <p>First, define a "decorator factory" like this:</p> <pre><code>def decorator_factory(inner_func): def decorator(outer_func): def wrapper(*args, **kwargs): return outer_func(*inner_func(*args, **kwargs)) return wrapper return decorator </code></pre> <p>Then you can use it like this:</p> <pre><code>def f(a, b): return a, b+2, b+3 @decorator_factory(f) def g(a, b, c): return a+b+c print g(1, 2) # output: 10 </code></pre>
2
2016-08-06T07:15:48Z
[ "python", "functools" ]
Scrapy i/o block when downloading files
38,800,942
<p>I using Scrapy to scrapy a webside and download some files. Since the file_url I get will redirect to another url (302 redirect).So I use another method handle_redirect to get the redirected url. I custom the filespipeline like this.</p> <pre><code>class MyFilesPipeline(FilesPipeline): def handle_redirect(self, file_url): response = requests.head(file_url) if response.status_code == 302: file_url = response.headers["Location"] return file_url def get_media_requests(self, item, info): redirect_url = self.handle_redirect(item["file_urls"][0]) yield scrapy.Request(redirect_url) def item_completed(self, results, item, info): file_paths = [x['path'] for ok, x in results if ok] if not file_paths: raise DropItem("Item contains no images") item['file_urls'] = file_paths return item </code></pre> <p>With the code above, I can download the file, but the process were block when downloading, so the whole project become very slow.</p> <p>I tried another solution in spider, use Requests get redirected url first then pass to another function.and use the default filespipeline.</p> <pre><code>yield scrapy.Request( download_url[0], meta={ "name": name, }, dont_filter=True, callback=self.handle_redirect) def handle_redirect(self, response): logging.warning("respon %s" % response.meta) download_url = response.headers["Location"].decode("utf-8") return AppListItem( name=response.meta["name"], file_urls=[download_url], ) </code></pre> <p>Still block the process.</p> <p>From the dos here </p> <p><a href="http://doc.scrapy.org/en/latest/topics/media-pipeline.html#using-the-files-pipeline" rel="nofollow">Using the Files Pipeline</a></p> <blockquote> <p>When the item reaches the FilesPipeline, the URLs in the file_urls field are scheduled for download using the standard Scrapy scheduler and downloader (which means the scheduler and downloader middlewares are reused), but with a higher priority, processing them before other pages are scraped. The item remains “locked” at that particular pipeline stage until the files have finish downloading (or fail for some reason)</p> </blockquote> <p>Is this mean I can't scrapy next url until the file had been downloaded? (I don't set download_delay in my settings)</p> <h3>EDIT</h3> <p>I already added this at first:</p> <pre><code>handle_httpstatus_list = [302] </code></pre> <p>so I will not be redirect to the redirected url, My first solution use requests is because I think yield will work like this:</p> <ol> <li>I crawl a page, keep yield callback, then call return item</li> <li>The item pass to the pipeline and If it meet some i/o, it will yield to spider to crawl next page like normal Asynchronous i/o do.</li> </ol> <p>Or I have to wait for the files downloaded so I can crawl next page? Is it the downside of Scrapy? The second part I don't follow is how to calculate the speed of crawl the page.For instance, 3s for a complete page, with a default concurrency of 16.I guess @neverlastn use 16/2/3 to get 2.5 pages/s.Doesn't concurrency 16 means I can handle 16 request at the same time? So the speed should be 16 pages/s? Please correct if I wrong.</p> <h3>Edit2</h3> <p>Thanks for your answer, I understand how to calculate now,But I still don't understand the second part.On 302 I first meet this problem. <a href="https://stackoverflow.com/questions/37368030/error-302-downloading-file-in-scrapy/38783648#38783648">Error 302 Downloading File in Scrapy</a> I have a url like</p> <pre><code>http://example.com/first </code></pre> <p>which will use 302 and redirect to </p> <pre><code>http://example.com/second </code></pre> <p>but Scrapy don't auto redirect to the second one, and can not download the file which is wired. From the code here <a href="https://github.com/scrapy/scrapy/blob/ebef6d7c6dd8922210db8a4a44f48fe27ee0cd16/scrapy/downloadermiddlewares/redirect.py#L64" rel="nofollow">Scrapy-redirect</a> and dos here <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#module-scrapy.downloadermiddlewares.redirect" rel="nofollow">RedirectMiddleware</a> points out that scrapy should handle redirect by default. That is why I do some trick and trying to fix it.My third solution will try to use <a href="https://github.com/celery/celery" rel="nofollow">Celery</a> like this</p> <pre><code>class MyFilesPipeline(FilesPipeline): @app.task def handle_redirect(self, file_url): response = requests.head(file_url) if response.status_code == 302: file_url = response.headers["Location"] return file_url def get_media_requests(self, item, info): redirect_url = self.handle_redirect.delay(item["file_urls"][0]) yield scrapy.Request(redirect_url) def item_completed(self, results, item, info): file_paths = [x['path'] for ok, x in results if ok] if not file_paths: raise DropItem("Item contains no images") item['file_urls'] = file_paths return item </code></pre> <p>Since I have lot of spider already, I don't want to override them use the second solution. So I handle them in the pipeline,Is this solution will be better?</p>
2
2016-08-06T05:41:17Z
38,810,558
<p>You use the <code>requests</code> API which is synchronous/blocking. This means that you turn your concurrency (<code>CONCURRENT_REQUESTS_PER_DOMAIN</code>) from (by default) 8, to effectively one. It seems like it dominates your delay. Nice trick the one you did on your second attempt. This doesn't use <code>requests</code> thus it should be faster compared to using <code>requests</code> (isn't it?) Now, of course you add extra delay... If your first (HTML) request takes 1s and the second (image) request 2s, overall you have 3s for a complete page. With a default concurrency of 16, this would mean that you would crawl about 2.5 pages/s. When your redirect fails and you don't crawl the image, the process would take aprox. 1s i.e. 8 pages/s. So you might see a 3x slowdown. One solution might be to 3x the number of concurrent requests you allow to run in parallel by increasing <code>CONCURRENT_REQUESTS_PER_DOMAIN</code> and/or <code>CONCURRENT_REQUESTS</code>. If you are now running this from a place with limited bandwidth and/or increased latency, another solution might be to run it from a cloud server closer to the area where the image servers are hosted (e.g. EC2 US East).</p> <p><strong>EDIT</strong></p> <p>The performance is better understood by "little's law". 1st both <code>CONCURRENT_REQUESTS_PER_DOMAIN</code> and <code>CONCURRENT_REQUESTS</code> work typically in parallel. <code>CONCURRENT_REQUESTS_PER_DOMAIN</code> = 8 by default and I would guess that you typically download from a single domain thus your actual concurrency limit is 8. The level of concurrency (i.e. 8) isn't per second but it's a fixed number, like saying that "that oven can bake at most 8 croissants in it". How quickly your croissants bake is the latency (this is the web response time) and the metric you're interested in is their ratio i.e. 8 croissants can bake in parallel / 3 second per croissant = I will be baking 2.5 croissants/second.</p> <p><a href="http://i.stack.imgur.com/3s2ST.png" rel="nofollow"><img src="http://i.stack.imgur.com/3s2ST.png" alt="enter image description here"></a></p> <p>On 302, I'm not sure what exactly you're trying to do. I think you're just following them - it's just that you do it manually. I think that scrapy will do this for you when extending the allowed codes. <code>FilesPipeline</code> might not get the value from <code>handle_httpstatus_list</code> but the global setting <code>HTTPERROR_ALLOWED_CODES</code> should affect the <code>FilesPipeline</code> as well.</p> <p>Anyway, <code>requests</code> is a bad option because it blocks = definitely very bad performance. <code>yield</code>ing Scrapy <code>Request</code>s will "get them out of the way" (for now) but you will "meet them" again because they use the same resource, the scheduler and the downloader to do the actual downloads. This means that they will highly likely slow down your performance... and this is a good thing. I understand that your need here is to crawl fast, but scrapy wants you to be conscious of what you're doing and when you set a concurrency limit of e.g. 8 or 16, you trust scrapy to not "flood" your target sites with higher than that rate. Scrapy will take the pessimistic assumption that your media files served by the same server/domain are traffic to their web server (instead of some CDN) and will apply the same limits in order to protect the target site and you. Otherwise, imagine a page that happens to have 1000 images in it. If you get those 1000 downloads somehow "for free", you will be doing 8000 requests to the server in parallel, with concurrency set to 8 - not a good thing.</p> <p>If you want to get some downloads "for free" i.e. ones that don't adhere to the concurrency limits, you can use <a href="https://github.com/twisted/treq" rel="nofollow">treq</a>. This is the requests package for the Twisted framework. <a href="https://github.com/scalingexcellence/scrapybook/blob/master/ch10/speed/speed/spiders/speed.py#L191" rel="nofollow">Here</a>'s how to use it in a pipeline. I would feel more comfortable using it for hitting API's or web servers I own, rather than 3rd party servers.</p>
0
2016-08-07T03:16:23Z
[ "python", "scrapy" ]
Python OOP Monty Hall not giving the expected results
38,800,946
<p>Trying out some OOP in python, I tried to create a Monty Hall Problem simulation that is giving odd results. I implement three different strategies that a player can choose from, either to stay with the first door selected, switch to the second closed door, or randomly choose between them.</p> <pre><code>import random class Door(): behind = None is_open = False is_chosen = False def __init__(self,name=None): self.name = name def open(self): self.is_open = True def choose(self): self.is_chosen = True class Goat(): is_a = 'goat' class Car(): is_a = 'car' class Player(): door = None def choose(self,door): self.door = door self.door.choose() def open(self): self.door.open() if self.door.behind.is_a == 'car': return True return False def play(strategy): player = Player() items = [Goat(),Goat(),Car()] doors = [Door(name='a'),Door(name='b'),Door(name='c')] for door in doors: item = items.pop() door.behind = item random.shuffle(doors) player.choose(random.choice(doors)) if strategy == 'random': if random.choice([True,False]): for door in doors: if not door.is_open and not door.is_chosen: final = door break else: final = player.door elif strategy == 'switch': for door in doors: if not door.is_open and not door.is_chosen: final = door break elif strategy == 'stay': final = player.door player.choose(final) if player.open(): return True else: return False ## Play some games for strategy in ['random','switch','stay']: results = [] for game in range(0,10000): if play(strategy): results.append(True) else: results.append(False) ## Gather the results wins = 0 loses = 0 for game in results: if game: wins += 1 else: loses += 1 print 'results:\tstrategy={}\twins={}\tloses={}'.format(strategy,str(wins),str(loses)) </code></pre> <p>But every time I run it, I get something like:</p> <pre><code>results: strategy=random wins=3369 loses=6631 results: strategy=switch wins=3369 loses=6631 results: strategy=stay wins=3320 loses=6680 </code></pre> <p>Why is this giving nearly the same results for each strategy? Shouldn't the 'switch' strategy give a ratio of ~66% wins and 'stay' give ~33%?</p>
0
2016-08-06T05:41:30Z
38,801,574
<p>You're not playing the game correctly. After the contestant chooses a door, the host reveals a goat behind one of the other two doors, and then offers the contestant the opportunity to switch -- you're allowing a choice between three doors instead of two. Here's a revised <code>play()</code> function:</p> <pre><code>def play(strategy): player = Player() items = [Goat(), Goat(), Car()] doors = [Door(name='a'), Door(name='b'), Door(name='c')] random.shuffle(items) for door in doors: item = items.pop() door.behind = item player.choose(random.choice(doors)) # player has chosen a door, now show a goat behind one of the other two show = None for door in doors: if not (door.is_open or door.is_chosen) and door.behind.is_a == 'goat': show = door show.open() break # The player has now been shown a goat behind one of the two doors not chosen if strategy == 'random': if random.choice([True, False]): for door in doors: if not (door.is_open or door.is_chosen): final = door break else: final = player.door elif strategy == 'switch': for door in doors: if not (door.is_open or door.is_chosen): final = door break elif strategy == 'stay': final = player.door player.choose(final) return player.open() </code></pre> <p>That produces results like:</p> <pre><code>results: strategy=random wins=4977 loses=5023 results: strategy=switch wins=6592 loses=3408 results: strategy=stay wins=3368 loses=6632 </code></pre>
1
2016-08-06T07:11:48Z
[ "python" ]
Jupyter Notebook does not work fully in Pycharm
38,800,953
<p>I am following <a href="https://confluence.jetbrains.com/display/PYH/Using+IPython+Notebook+with+PyCharm" rel="nofollow">these</a> steps to run IPython in the Pycharm IDE. On pressing <code>run</code> button in any cell, I do get below pop-up window</p> <p><a href="http://i.stack.imgur.com/ewupL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ewupL.png" alt="enter image description here"></a></p> <p>According to the mentioned guide (given link), On pressing <code>OK</code>, I should get following message </p> <p><a href="http://i.stack.imgur.com/Ct8zd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ct8zd.png" alt="enter image description here"></a> </p> <p>But, I am not getting any type of message/response. So, I am not able to see the output of any cell contents. Does anyone know why I am not getting any response on selecting <code>OK</code>?</p> <p>System Information:</p> <pre><code>OS: MAC OS 10.10.3 Python: 2.7.10 using Anaconda 2.3.0 Ipython: 4.0.0 Pycharm: pycharm community addition 2016.2 </code></pre>
1
2016-08-06T05:42:54Z
38,801,082
<p>For the PyCharm Jupyter notebooks, to see results you need to open up a jupyter notebook. </p> <p>The reason why you don't just do all your code in Jupyter Notebooks is because Pycharm helps with LaTex integration and many more functions.</p>
0
2016-08-06T06:03:47Z
[ "python", "ipython", "pycharm", "jupyter", "jupyter-notebook" ]
Jupyter Notebook does not work fully in Pycharm
38,800,953
<p>I am following <a href="https://confluence.jetbrains.com/display/PYH/Using+IPython+Notebook+with+PyCharm" rel="nofollow">these</a> steps to run IPython in the Pycharm IDE. On pressing <code>run</code> button in any cell, I do get below pop-up window</p> <p><a href="http://i.stack.imgur.com/ewupL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ewupL.png" alt="enter image description here"></a></p> <p>According to the mentioned guide (given link), On pressing <code>OK</code>, I should get following message </p> <p><a href="http://i.stack.imgur.com/Ct8zd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ct8zd.png" alt="enter image description here"></a> </p> <p>But, I am not getting any type of message/response. So, I am not able to see the output of any cell contents. Does anyone know why I am not getting any response on selecting <code>OK</code>?</p> <p>System Information:</p> <pre><code>OS: MAC OS 10.10.3 Python: 2.7.10 using Anaconda 2.3.0 Ipython: 4.0.0 Pycharm: pycharm community addition 2016.2 </code></pre>
1
2016-08-06T05:42:54Z
39,165,872
<p>I solved following:</p> <p>First I followed the reply to the <a href="https://github.com/ContinuumIO/anaconda-issues/issues/921" rel="nofollow">issue jupyter-notebook No such file or directory: 'conda'</a>, in short you should do:</p> <pre><code>conda update nb_conda nb_conda_kernels nb_anacondacloud </code></pre> <p>Then, I ran my jupyter notebook in my browser. I took note where the Jupyter notebook was running, i.e.</p> <pre><code>The Jupyter Notebook is running at: http://localhost:8888/ </code></pre> <p>Then I started a new Jupyter Notebook in PyCharm2016.2.2, and when it asked about the Jupyter Notebook URL I changed the default <code>http://127.0.0.1:8888</code> to <code>http://localhost:8888/</code> </p> <p>and finally it worked.</p>
1
2016-08-26T12:03:00Z
[ "python", "ipython", "pycharm", "jupyter", "jupyter-notebook" ]
Nginx debugging logging levels
38,800,991
<p>I followed <a href="https://www.digitalocean.com/community/tutorials/how-to-configure-logging-and-log-rotation-in-nginx-on-an-ubuntu-vps" rel="nofollow">these</a> instructions and enabled the error log within nginx.</p> <p>I was trying to test the log, I created a syntax error by removing a <code>:</code> at the end of a for loop.</p> <p>When trying to load the website, it threw a 500 internal server error.</p> <p>After looking at the log, im pretty lost at what im seeing. I currently have the level set as <code>debug</code>.</p> <p>How would I configure the settings so that it would tell me that the issue is a syntax error?</p> <p>heres a sample of what the tail of the error log looks like:</p> <pre><code>5098 2016/08/06 01:53:05 [debug] 23526#23526: *44 write new buf t:1 f:0 0000559FAC0F0508, pos 0000559FAC0F0508, size: 161 file: 0, size: 0 5099 2016/08/06 01:53:05 [debug] 23526#23526: *44 http write filter: l:0 f:0 s:161 5100 2016/08/06 01:53:05 [debug] 23526#23526: *44 http output filter "/tag/getting-started/?" 5101 2016/08/06 01:53:05 [debug] 23526#23526: *44 http copy filter: "/tag/getting-started/?" 5102 2016/08/06 01:53:05 [debug] 23526#23526: *44 image filter 5103 2016/08/06 01:53:05 [debug] 23526#23526: *44 xslt filter body 5104 2016/08/06 01:53:05 [debug] 23526#23526: *44 http postpone filter "/tag/getting-started/?" 0000559FAC0F06E8 5105 2016/08/06 01:53:05 [debug] 23526#23526: *44 write old buf t:1 f:0 0000559FAC0F0508, pos 0000559FAC0F0508, size: 161 file: 0, size: 0 5106 2016/08/06 01:53:05 [debug] 23526#23526: *44 write new buf t:0 f:0 0000000000000000, pos 0000559FAB989AC0, size: 120 file: 0, size: 0 5107 2016/08/06 01:53:05 [debug] 23526#23526: *44 write new buf t:0 f:0 0000000000000000, pos 0000559FAB98ADA0, size: 62 file: 0, size: 0 5108 2016/08/06 01:53:05 [debug] 23526#23526: *44 http write filter: l:1 f:0 s:343 5109 2016/08/06 01:53:05 [debug] 23526#23526: *44 http write filter limit 0 5110 2016/08/06 01:53:05 [debug] 23526#23526: *44 writev: 343 of 343 5111 2016/08/06 01:53:05 [debug] 23526#23526: *44 http write filter 0000000000000000 5112 2016/08/06 01:53:05 [debug] 23526#23526: *44 http copy filter: 0 "/tag/getting-started/?" 5113 2016/08/06 01:53:05 [debug] 23526#23526: *44 http finalize request: 0, "/tag/getting-started/?" a:1, c:1 5114 2016/08/06 01:53:05 [debug] 23526#23526: *44 event timer add: 12: 5000:1470462790191 5115 2016/08/06 01:53:05 [debug] 23526#23526: *44 http lingering close handler 5116 2016/08/06 01:53:05 [debug] 23526#23526: *44 recv: fd:12 -1 of 4096 5117 2016/08/06 01:53:05 [debug] 23526#23526: *44 recv() not ready (11: Resource temporarily unavailable) 5118 2016/08/06 01:53:05 [debug] 23526#23526: *44 lingering read: -2 5119 2016/08/06 01:53:05 [debug] 23526#23526: *44 event timer: 12, old: 1470462790191, new: 1470462790191 5120 2016/08/06 01:53:05 [debug] 23526#23526: *44 http empty handler 5121 2016/08/06 01:53:05 [debug] 23526#23526: *44 http empty handler 5122 2016/08/06 01:53:05 [debug] 23526#23526: *44 http lingering close handler 5123 2016/08/06 01:53:05 [debug] 23526#23526: *44 recv: fd:12 -1 of 4096 5124 2016/08/06 01:53:05 [info] 23526#23526: *44 recv() failed (104: Connection reset by peer) while sending to client, client: 180.76.15.12, server: chriskoh.io, request: "GET /tag/getting-started/ HTTP/1.1", upstream: "http://127 .0.0.1:2368/tag/getting-started/", host: "sites.bugsplat.info" 5125 2016/08/06 01:53:05 [debug] 23526#23526: *44 lingering read: -1 5126 2016/08/06 01:53:05 [debug] 23526#23526: *44 http request count:1 blk:0 5127 2016/08/06 01:53:05 [debug] 23526#23526: *44 http close request 5128 2016/08/06 01:53:05 [debug] 23526#23526: *44 http log handler 5129 2016/08/06 01:53:05 [debug] 23526#23526: *44 free: 0000559FAC0F8BA0, unused: 0 5130 2016/08/06 01:53:05 [debug] 23526#23526: *44 free: 0000559FAC0EFB70, unused: 881 5131 2016/08/06 01:53:05 [debug] 23526#23526: *44 close http connection: 12 5132 2016/08/06 01:53:05 [debug] 23526#23526: *44 event timer del: 12: 1470462790191 5133 2016/08/06 01:53:05 [debug] 23526#23526: *44 reusable connection: 0 5134 2016/08/06 01:53:05 [debug] 23526#23526: *44 free: 0000559FAC0EE400 5135 2016/08/06 01:53:05 [debug] 23526#23526: *44 free: 0000559FAC0EE1F0, unused: 128 </code></pre>
1
2016-08-06T05:48:48Z
38,801,069
<p>1) Disable nginx debug mode, it will eat your hdd. Nginx debug mode log purpose is to debug nginx itself, not your application errors.</p> <p>2) Don't look for errors in the wrong places, nginx error log has nothing to do with your application(flask)/middleware (uwsgi in your case) logs</p> <p>3) <a href="https://www.digitalocean.com/community/questions/how-to-check-error-logs-for-flask-uwsgi-nginx-app" rel="nofollow">DO faq about uwsgi logs</a></p>
1
2016-08-06T06:01:54Z
[ "python", "nginx", "uwsgi", "error-log" ]
How to set focus in tkinter entry box
38,801,019
<p>have spent a while looking for an answer. I'm new to Python but not to coding in general. Finding the various versions quite challenging!</p> <p>Anyway I'm very Gui orientated and have managed to get tkinter working with Python 3.5.1</p> <p>Just playing with basics and have the following code but cannot set focus to the first entry box. Have tried mEntry1.focus() and mEntry1.focus_set() but always get object has no attribute error. Any help?</p> <pre><code>from tkinter import * def calc(*args): try: value1 = float(V1.get()) value2 = float(V2.get()) result.set(value1 * value2) except ValueError: pass mGui = Tk() mGui.geometry('450x450+200+200') mGui.title('Test Gui') V1 = StringVar() V2 = StringVar() result = StringVar() mEntry1 = Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W) mEntry2 = Entry(textvariable=V2).grid(row=1,column=0) mButton = Button(text='Calculate',command=calc).grid(row=3,column=0) mlabel = Label(textvariable=result).grid(row=4,column=2) </code></pre>
-1
2016-08-06T05:53:48Z
38,801,587
<p>Every Tkinter widget has the <code>focus_set</code> method.</p> <p>The problem with your code is that the <code>.grid</code> method returns <code>None</code>. Thus </p> <pre><code>mEntry1 = Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W) </code></pre> <p>sets <code>mEntry1</code> to <code>None</code>, not the widget. So you need to create the widget and put it in the grid in two steps:</p> <pre><code>mEntry1 = Entry(textvariable=V1,width=10) mEntry1.grid(row=0,column=0,sticky=W) </code></pre> <p>Of course, if you don't actually <em>need</em> a reference to the widget object then it's ok to do it in one step. So something like</p> <pre><code>Entry(textvariable=V1,width=10).grid(row=0,column=0,sticky=W) </code></pre> <p>would be fine.</p> <hr> <p>BTW, it's not a good idea to use <code>from tkinter import *</code>. It imports over 130 names into your namespace, which can lead to name collisions with your own names, or with those of other modules if you also import them with a "star" import statement. It also makes the code harder to read. Instead, you can do</p> <pre><code>import tkinter as tk </code></pre> <p>and then refer to Tkinter names using the <code>tk.</code> prefix, eg <code>tk.Entry</code> instead of <code>Entry</code>. </p>
1
2016-08-06T07:12:55Z
[ "python", "tkinter" ]
regex: find all asterisks without prepended backslashes
38,801,092
<p>I am building a regex that transforms <code>*asterisks*</code> into <code>&lt;b&gt;bold tags&lt;/b&gt;</code>, as a simpler version of Markdown. The regex looks like this:</p> <pre><code>markdown = '\*(?P&lt;name&gt;.+)\*' bold = '&lt;b&gt;\g&lt;name&gt;&lt;/b&gt;' text = 'abcdef *bold* ghijkl' print(re.sub(markdown, bold, text)) &gt;&gt;&gt; abcdef &lt;b&gt;bold&lt;/b&gt; ghijkl </code></pre> <p>Now I need to ignore escaped asterisks <code>\*</code>, and here I run into two problems:</p> <h2>Problem 1</h2> <p>When I try to specify escape symbol as <code>\\</code></p> <pre><code>markdown = '[^\\]\*(?P&lt;name&gt;.+)[^\\]\*' </code></pre> <p>I get a Python error:</p> <pre><code>sre_constants.error: unexpected end of regular expression </code></pre> <p>so there is a syntax error somewhere, can't seem to fix it.</p> <h2>Problem 2</h2> <p>Suppose I want to ignore prepended symbol <code>A</code> (not a backslash). Here my regex works:</p> <pre><code>markdown = '[^A]\*(?P&lt;name&gt;.+)[^A]\*' bold = '&lt;b&gt;\g&lt;name&gt;&lt;/b&gt;' text = 'abcdef A*bold* ghijkl' print(re.sub(markdown, bold, text)) &gt;&gt;&gt; abcdef A*bold* ghijkl </code></pre> <p>But if there are no prepending <code>A</code>'s in my line, some valuable symbols from the text are consumed by the regex:</p> <pre><code>text = 'abcdef *bold* ghijkl' print(re.sub(markdown, bold, text)) &gt;&gt;&gt; abcdef&lt;b&gt;bol&lt;/b&gt; ghijkl </code></pre> <p>Note the first space <code></code> and letter <code>d</code> have disappeared.</p> <p>How do I deal with these two problems?</p>
1
2016-08-06T06:05:09Z
38,802,952
<p><strong>Problem 1a: Syntax Error</strong></p> <p>It's not working, because you have to escape the backslashes as well.</p> <pre><code>markdown = '[^\\\\]\*(?P&lt;name&gt;.+)[^\\\\]\*' </code></pre> <p>Or use <code>r''</code> to define a raw string.</p> <pre><code>markdown = r'[^\\]\*(?P&lt;name&gt;.+)[^\\]\*' </code></pre> <p><strong>Problem 1b: Solution</strong></p> <p>My advice: Don't try to solve it with one regex.</p> <ol> <li>Custom escape the problematic character. </li> <li>Run the normal regex. </li> <li>Undo the custom escape.</li> </ol> <p>Code:</p> <pre><code>my_escapes = { '%backslash-escaped%': '\\\\', '%bold-escaped%': '\\*', } text = r'text \*not-bold text2 *bold* text3 \\*bold* text4 \\\*not-bold text5 \\\\*bold* text6' text = re.sub('\\\\\\\\', '%backslash-escaped%', text) # escape escaped escape characters text = re.sub('\\\\\*', '%bold-escaped%', text) # escape escaped bold characters text = re.sub('(?&lt;!\\\\)\*(?P&lt;bold&gt;[^\*\\\\]+)\*', '&lt;b&gt;\g&lt;bold&gt;&lt;/b&gt;', text) # add bold parts # undo all escapes for key, value in my_escapes.iteritems(): text = text.replace(key, value) print text &gt;&gt;&gt; text \*not-bold text2 &lt;b&gt;bold&lt;/b&gt; text3 \\&lt;b&gt;bold&lt;/b&gt; text4 \\\*not-bold text5 \\\\&lt;b&gt;bold&lt;/b&gt; text6 </code></pre> <p><strong>Problem 2: Disappearing of characters</strong></p> <p>They disappear, because you have matched but not re-inserted them. To do so, wrap them in groups (here named groups) and insert the groups inside the replacement-string.</p> <pre><code>markdown = '(?P&lt;first_char&gt;[^A])\*(?P&lt;name&gt;.+)(?P&lt;sec_char&gt;[^A])\*' bold = '\g&lt;first_char&gt;&lt;b&gt;\g&lt;name&gt;&lt;/b&gt;\g&lt;sec_char&gt;' </code></pre> <p>Or use <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookarounds</a>, they will match but not consume the character.</p> <pre><code>markdown = '(?&lt;!A)\*(?P&lt;name&gt;.+)(?!A)\*' bold = '&lt;b&gt;\g&lt;name&gt;&lt;/b&gt;' </code></pre>
1
2016-08-06T09:57:20Z
[ "python", "regex" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for putting the second number in every pair into an array, with its row index being determined by the first number in the pair?</p>
0
2016-08-06T06:09:07Z
38,801,179
<p>As @thefourtheye noted <code>dict</code> might be better container. In case you want 2D list you could first add the values a intermediate <code>dict</code> where key is row and value is list of numbers. Then you could use list comprehension to generate the final result:</p> <pre><code>&gt;&gt;&gt; l = [[3,350],[4,800],[0,150],[0,200],[4,750]] &gt;&gt;&gt; d = {} &gt;&gt;&gt; for row, num in l: ... d.setdefault(row, []).append(num) ... &gt;&gt;&gt; [d.get(i, []) for i in range(max(d.keys()) + 1)] [[150, 200], [], [], [350], [800, 750]] </code></pre>
0
2016-08-06T06:17:30Z
[ "python", "list", "multidimensional-array", "indexing" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for putting the second number in every pair into an array, with its row index being determined by the first number in the pair?</p>
0
2016-08-06T06:09:07Z
38,801,181
<p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">pandas</a> module for this task:</p> <pre><code>In [186]: a = np.array([[3,350],[4,800],[0,150],[0,200],[4,750]]) In [187]: res = pd.DataFrame(a).groupby(0)[1].apply(list).to_frame('val').rename_axis('idx') In [188]: res Out[188]: val idx 0 [150, 200] 3 [350] 4 [800, 750] </code></pre> <p>Now you have an indexed data set and you can use it in the following way:</p> <pre><code>In [190]: res.ix[0, 'val'] Out[190]: [150, 200] In [191]: res.ix[0, 'val'][1] Out[191]: 200 In [192]: res.ix[4, 'val'] Out[192]: [800, 750] </code></pre> <p>PS i think you don't have to keep empty lists in the resulting data set - as it's a waste of resources</p>
0
2016-08-06T06:17:44Z
[ "python", "list", "multidimensional-array", "indexing" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for putting the second number in every pair into an array, with its row index being determined by the first number in the pair?</p>
0
2016-08-06T06:09:07Z
38,801,187
<p>Try taking a look at list comprehensions, they provide a one-liner way of creating lists. If you don't know what they are this is a pretty decent guide to get you started <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">here</a>. Also, take a look at <code>tuple</code>'s, as they are more appropriate for paired values, as opposed to lists. Note that tuples are not mutable, so you cannot make changes once you have created it. </p> <p>Your list using tuples would look like this</p> <pre><code>foo = [(3,350),(4,800),(0,200),(4,750)] </code></pre> <p>As far as I'm aware, Python lists have no predefined size, rather they grow and shrink as changes are made. So, what you'll want to do, is find the largest index value in the list, or <code>foo = [x[0] for x in list_of_pairs]</code> would access the first index of every list inside of your main list, the one named <code>list_of_pairs</code>. Note that this strategy would work for the <code>tuple</code> based list as well. </p> <p>The below should do what you want </p> <pre><code>list_of_pairs = [[3,350],[4,800],[0,200],[4,750]] indexes = {x[0] for x in list_of_pairs} new_list = [] for i in indexes: new_list.append([x[1] for x in list_of_pairs if x[0] == i]) </code></pre>
1
2016-08-06T06:18:24Z
[ "python", "list", "multidimensional-array", "indexing" ]
converting an array of pairs into a 2D array based on first column
38,801,132
<p>is there a (preferably elegant) way in Python for taking an array of pairs such as</p> <pre><code>[[3,350],[4,800],[0,150],[0,200],[4,750]] </code></pre> <p>into something like</p> <pre><code>[ [150,200], [], [], [350], [800,750] ] </code></pre> <p>?</p> <p>In other words, what's a good method for putting the second number in every pair into an array, with its row index being determined by the first number in the pair?</p>
0
2016-08-06T06:09:07Z
38,802,285
<p>There are numerious ways to do this. Here's a fairly straight-forward one:</p> <pre><code>a = [[3, 350], [4, 800], [0, 150], [0, 200], [4, 750]] rows, values = zip(*a) b = [[] for _ in range(max(rows)+1)] # initialize 2D output for i, row in enumerate(rows): b[row].append(values[i]) print(b) # -&gt; [[150, 200], [], [], [350], [800, 750]] </code></pre>
0
2016-08-06T08:39:08Z
[ "python", "list", "multidimensional-array", "indexing" ]
how to convert the %3A and %2F to : and / in the url in python?
38,801,188
<p>How to convert the replace(%3A and %2F ...) in the url. <br><strong>URL</strong><br> <code>https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%3DFri%2520Aug%252005%25202016%252011%3A40%3A14%2520GMT%2B0530%28India%2520Standard%2520Time%29</code> <br><br> <strong>Required URL</strong> <br> <code>https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https://url/&amp;TIME=Sat Aug 06 2016 11:42:36 GMT+0530 (India Standard Time)</code> <br><br> I was wondering is there any simple way to do this?</p>
0
2016-08-06T06:18:32Z
38,801,219
<p>Take a look at <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote" rel="nofollow">urllib.parse.unquote</a>: "Replace %xx escapes by their single-character equivalent."</p>
2
2016-08-06T06:23:01Z
[ "python", "python-3.x", "url" ]
how to convert the %3A and %2F to : and / in the url in python?
38,801,188
<p>How to convert the replace(%3A and %2F ...) in the url. <br><strong>URL</strong><br> <code>https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%3DFri%2520Aug%252005%25202016%252011%3A40%3A14%2520GMT%2B0530%28India%2520Standard%2520Time%29</code> <br><br> <strong>Required URL</strong> <br> <code>https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https://url/&amp;TIME=Sat Aug 06 2016 11:42:36 GMT+0530 (India Standard Time)</code> <br><br> I was wondering is there any simple way to do this?</p>
0
2016-08-06T06:18:32Z
38,801,429
<p>In <code>python 2.7</code>, use <a href="https://docs.python.org/2/library/urllib.html#urllib.quote" rel="nofollow">urllib.unquote</a>:</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; urllib.unquote(urllib.unquote('https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%3DFri%2520Aug%252005%25202016%252011%3A40%3A14%2520GMT%2B0530%28India%2520Standard%2520Time%29')) 'https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https://url/&amp;TIME=Fri Aug 05 2016 11:40:14 GMT+0530(India Standard Time)' </code></pre> <p>In <code>python 3+</code>, use <a href="https://docs.python.org/3.2/library/urllib.parse.html#urllib.parse.unquote" rel="nofollow">urllib.parse.unquote</a></p> <pre><code>&gt;&gt;&gt; from urllib.parse import unquote &gt;&gt;&gt; unquote(unquote("https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https%3A%2F%2Furl%2F%26TIME%3DFri%2520Aug%252005%25202016%252011%3A40%3A14%2520GMT%2B0530%28India%2520Standard%2520Time%29")) 'https://url/login_data.php?username=user&amp;categoryid=0&amp;URL=https://url/&amp;TIME=Fri Aug 05 2016 11:40:14 GMT+0530(India Standard Time)' </code></pre>
2
2016-08-06T06:52:25Z
[ "python", "python-3.x", "url" ]
How to run a process with timeout and still get stdout at runtime
38,801,202
<p>The need:</p> <ol> <li>Timeout after X seconds, and kill the process (and all the processes it opened) if timeout reached before the process ends gracefully.</li> <li>Read ongoing output at runtime.</li> <li>Work with processes that produce output, ones that don't, and ones that produce output, and then stop producing it (e.g. get stuck).</li> <li>Run on Windows.</li> <li>Run on Python 3.5.2.</li> </ol> <p>Python 3 subprocess module has <a href="https://docs.python.org/3/library/subprocess.html#subprocess.TimeoutExpired.timeout">timeout</a> built in, and I've also tried and implemented timeout myself using timer and using threads, but it doesn't work with the output. <code>readline()</code> is blocking or not? <code>readlines()</code> is definitely waiting for the process to end before spitting out all the output, which is not what I need (I need ongoing).</p> <p>I am close to switching to node.js :-(</p>
6
2016-08-06T06:20:45Z
38,868,895
<p>I would use asyncio for this kind of task.</p> <p>Read IO from the process like in this accepted anwser: <a href="http://stackoverflow.com/questions/24435987/how-to-stream-stdout-stderr-from-a-child-process-using-asyncio-and-obtain-its-e">How to stream stdout/stderr from a child process using asyncio, and obtain its exit code after?</a></p> <p>(I don't want to fully copy it here)</p> <p>Wrap it in a timeout:</p> <pre><code>async def killer(trans, timeout): await asyncio.sleep(timeout) trans.kill() print ('killed!!') trans, *other_stuff = loop.run_until_complete( loop.subprocess_exec( SubprocessProtocol, 'py', '-3', '-c', 'import time; time.sleep(6); print("Yay!")' , ) ) asyncio.ensure_future(killer(trans, 5)) # 5 seconds timeout for the kill loop.run_forever() </code></pre> <p>Have fun ...</p>
4
2016-08-10T09:08:56Z
[ "python", "python-3.x", "timeout", "subprocess", "stdout" ]
How to run a process with timeout and still get stdout at runtime
38,801,202
<p>The need:</p> <ol> <li>Timeout after X seconds, and kill the process (and all the processes it opened) if timeout reached before the process ends gracefully.</li> <li>Read ongoing output at runtime.</li> <li>Work with processes that produce output, ones that don't, and ones that produce output, and then stop producing it (e.g. get stuck).</li> <li>Run on Windows.</li> <li>Run on Python 3.5.2.</li> </ol> <p>Python 3 subprocess module has <a href="https://docs.python.org/3/library/subprocess.html#subprocess.TimeoutExpired.timeout">timeout</a> built in, and I've also tried and implemented timeout myself using timer and using threads, but it doesn't work with the output. <code>readline()</code> is blocking or not? <code>readlines()</code> is definitely waiting for the process to end before spitting out all the output, which is not what I need (I need ongoing).</p> <p>I am close to switching to node.js :-(</p>
6
2016-08-06T06:20:45Z
38,880,667
<p>Use the 2 python script below.</p> <ul> <li><p>The <em>Master.py</em> will use <code>Popen</code> to start a new process and will start a watcher thread that will kill the process after <code>3.0</code> seconds.</p></li> <li><p>The slave must call the flush method if no newline in the data written to the <code>stdout</code>, (on windows the <code>'\n'</code> also cause a flush).</p></li> </ul> <blockquote> <p>Be careful the <code>time</code> module is not a high precision timer.</p> <p>The load time of the process can be longer than 3.0 seconds in extreme cases (reading an executable from a flash drive having USB 1.0)</p> </blockquote> <p><strong>Master.py</strong></p> <pre><code>import subprocess, threading, time def watcher(proc, delay): time.sleep(delay) proc.kill() proc = subprocess.Popen('python Slave.py', stdout = subprocess.PIPE) threading.Thread(target = watcher, args = (proc, 3.0)).start() data = bytearray() while proc: chunk = proc.stdout.read(1) if not chunk: break data.extend(chunk) print(data) </code></pre> <p><strong>Slave.py</strong></p> <pre><code>import time, sys while True: time.sleep(0.1) sys.stdout.write('aaaa') sys.stdout.flush() </code></pre>
0
2016-08-10T18:10:57Z
[ "python", "python-3.x", "timeout", "subprocess", "stdout" ]
Efficient group by and where clause in python
38,801,205
<p>I am having <strong>weekly( say 5 weeks)</strong> sales and baskets for <strong>product and store combination</strong>, i want to find the total spend and visits of product <strong>(irrespective of store)</strong> for a particular <strong>week(say 201520)</strong>" i.e. 20th week of year 2015. the moment i select a week , there can be some product that are not sold in that week. but i <strong>do not want to remove them from my group by</strong>. Essentially i want all the products sold in 5 weeks , but if a product is not sold in the week i selected above , i want it to be present in my final dataFrame with aggregated numbers to be 0. Sample data.(lets <strong>assume prod 122 is not sold in week 201520</strong>) </p> <pre><code>prod store week baskets sales 123 112 201518 20 100.45 123 112 201519 21 89.65 123 112 201520 22 1890.54 122 112 201518 10 909.99 </code></pre> <p>sample output (for 201520) </p> <pre><code>prod total_baskets total_sales spend_per_basket 123 22 1890.54 85.93363636 122 0 0 0 </code></pre> <p>i know this can be done using <strong>groupby</strong> using pandas. But i am doing multiple steps. i am looking for a more pythonic and efficient way. currently<br> i am first selecting the week for which i am doing groupby.<br> then creating a list of all product present in my inital weekly dataset.<br> then remerging back with the group by data. I find this non - efficient. please help. Also need to create <strong>spend per basket . if total_baskets > 0 then spend_per_basket is total_sales/ total_baskets. else 0</strong> TIA. dummy code: </p> <pre><code>trans_for_my_week=weekly_trans[weekly_trans['week']==201520] avg_sales=pd.DataFrame(trans_for_my_week.groupby(['prod']).agg({'baskets': {'total_baskets':'sum'}, 'sales' :{'total_sales':'sum'}})) avg_sales_period_0.columns=avg_sales_period_0.columns.droplevel(0) avg_sales_period_0=avg_sales_period_0.reset_index() </code></pre> <p>and so on</p>
1
2016-08-06T06:21:18Z
38,801,383
<p><strong>UPDATE2:</strong> adding new calculated multi-level column:</p> <pre><code>In [229]: x = res.sales / res.baskets In [230]: x Out[230]: week 201518 201519 201520 prod 122 90.9990 NaN NaN 123 5.0225 4.269048 85.933636 In [231]: x.columns = pd.MultiIndex.from_product(['spend_per_basket', res.columns.get_level_values(1).drop_duplicates()]) In [232]: x Out[232]: spend_per_basket 201518 201519 201520 prod 122 90.9990 NaN NaN 123 5.0225 4.269048 85.933636 In [234]: res = res.join(x) In [235]: res Out[235]: baskets sales spend_per_basket week 201518 201519 201520 201518 201519 201520 201518 201519 201520 prod 122 10 0 0 909.99 0.00 0.00 90.9990 NaN NaN 123 20 21 22 100.45 89.65 1890.54 5.0225 4.269048 85.933636 </code></pre> <p>PS <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">here is very well documented multiindexing (multi-level) pandas techniques with lots of examples</a></p> <p><strong>UPDATE:</strong> inspired by <a href="http://stackoverflow.com/a/38801480/5741205">@JoeR's solution</a> - here is modified <code>pivot_table()</code> version:</p> <pre><code>res = df.pivot_table(index='prod', columns='week', values=['baskets','sales'], aggfunc='sum', fill_value=0) In [189]: res Out[189]: baskets sales week 201518 201519 201520 201518 201519 201520 prod 122 10 0 0 909.99 0.00 0.00 123 20 21 22 100.45 89.65 1890.54 In [190]: res[[('baskets',201519)]] Out[190]: baskets week 201519 prod 122 0 123 21 In [192]: res.ix[122, [('sales',201519)]] Out[192]: week sales 201519 0.0 Name: 122, dtype: float64 </code></pre> <p>you can also flatten your column levels as follows:</p> <pre><code>In [194]: res2 = res.copy() In [196]: res2.columns = ['{0[0]}_{0[1]}'.format(col) for col in res2.columns] In [197]: res2 Out[197]: baskets_201518 baskets_201519 baskets_201520 sales_201518 sales_201519 sales_201520 prod 122 10 0 0 909.99 0.00 0.00 123 20 21 22 100.45 89.65 1890.54 </code></pre> <p>but i would keep it as multilevel column so you could use advanced indexing (like in the example above)</p> <p><strong>OLD answer:</strong></p> <p>I'd calculate it once for all your data:</p> <pre><code>from itertools import product In [165]: %paste g = df.groupby(['week', 'prod']).agg({'baskets':'sum', 'sales':'sum'}).reset_index() al = pd.DataFrame(list(product(df['prod'].unique(), df.week.unique())), columns=['prod','week']) res = pd.merge(al, g, on=['prod','week'], how='left').fillna(0) ## -- End pasted text -- In [166]: res Out[166]: prod week sales baskets 0 123 201518 100.45 20.0 1 123 201519 89.65 21.0 2 123 201520 1890.54 22.0 3 122 201518 909.99 10.0 4 122 201519 0.00 0.0 5 122 201520 0.00 0.0 </code></pre>
2
2016-08-06T06:45:09Z
[ "python", "python-3.x", "pandas" ]
Efficient group by and where clause in python
38,801,205
<p>I am having <strong>weekly( say 5 weeks)</strong> sales and baskets for <strong>product and store combination</strong>, i want to find the total spend and visits of product <strong>(irrespective of store)</strong> for a particular <strong>week(say 201520)</strong>" i.e. 20th week of year 2015. the moment i select a week , there can be some product that are not sold in that week. but i <strong>do not want to remove them from my group by</strong>. Essentially i want all the products sold in 5 weeks , but if a product is not sold in the week i selected above , i want it to be present in my final dataFrame with aggregated numbers to be 0. Sample data.(lets <strong>assume prod 122 is not sold in week 201520</strong>) </p> <pre><code>prod store week baskets sales 123 112 201518 20 100.45 123 112 201519 21 89.65 123 112 201520 22 1890.54 122 112 201518 10 909.99 </code></pre> <p>sample output (for 201520) </p> <pre><code>prod total_baskets total_sales spend_per_basket 123 22 1890.54 85.93363636 122 0 0 0 </code></pre> <p>i know this can be done using <strong>groupby</strong> using pandas. But i am doing multiple steps. i am looking for a more pythonic and efficient way. currently<br> i am first selecting the week for which i am doing groupby.<br> then creating a list of all product present in my inital weekly dataset.<br> then remerging back with the group by data. I find this non - efficient. please help. Also need to create <strong>spend per basket . if total_baskets > 0 then spend_per_basket is total_sales/ total_baskets. else 0</strong> TIA. dummy code: </p> <pre><code>trans_for_my_week=weekly_trans[weekly_trans['week']==201520] avg_sales=pd.DataFrame(trans_for_my_week.groupby(['prod']).agg({'baskets': {'total_baskets':'sum'}, 'sales' :{'total_sales':'sum'}})) avg_sales_period_0.columns=avg_sales_period_0.columns.droplevel(0) avg_sales_period_0=avg_sales_period_0.reset_index() </code></pre> <p>and so on</p>
1
2016-08-06T06:21:18Z
38,801,397
<p>I think the easiest and more "Pythonic" solution will involve at least two steps: groupby, then a merge. And you can do it as follows:</p> <pre><code># First create a container DataFrame to hold the data: columns = pd.MultiIndex.from_arrays([['a', 'b'], df[0].unique()]) output = pd.DataFrame(columns=columns) # Then the groupby magic agg_sales = weekly_trans.groupby(['week','prod']).agg({'baskets' : {'total_baskets':'sum'}, 'sales' : {'total_sales' :'sum'}}) agg_sales = agg_sales.unstack() # This will set your 'prod' as columns output = pd.concat([output, agg_sales], axis=0) # And you can do that in one line, if you need to: output = pd.concat([output, weekly_trans.groupby(['week','prod']).\ agg({'baskets' : {'total_baskets':'sum'}, 'sales' : {'total_sales' :'sum'}}).\ unstack()], axis=0) </code></pre>
0
2016-08-06T06:47:48Z
[ "python", "python-3.x", "pandas" ]
Efficient group by and where clause in python
38,801,205
<p>I am having <strong>weekly( say 5 weeks)</strong> sales and baskets for <strong>product and store combination</strong>, i want to find the total spend and visits of product <strong>(irrespective of store)</strong> for a particular <strong>week(say 201520)</strong>" i.e. 20th week of year 2015. the moment i select a week , there can be some product that are not sold in that week. but i <strong>do not want to remove them from my group by</strong>. Essentially i want all the products sold in 5 weeks , but if a product is not sold in the week i selected above , i want it to be present in my final dataFrame with aggregated numbers to be 0. Sample data.(lets <strong>assume prod 122 is not sold in week 201520</strong>) </p> <pre><code>prod store week baskets sales 123 112 201518 20 100.45 123 112 201519 21 89.65 123 112 201520 22 1890.54 122 112 201518 10 909.99 </code></pre> <p>sample output (for 201520) </p> <pre><code>prod total_baskets total_sales spend_per_basket 123 22 1890.54 85.93363636 122 0 0 0 </code></pre> <p>i know this can be done using <strong>groupby</strong> using pandas. But i am doing multiple steps. i am looking for a more pythonic and efficient way. currently<br> i am first selecting the week for which i am doing groupby.<br> then creating a list of all product present in my inital weekly dataset.<br> then remerging back with the group by data. I find this non - efficient. please help. Also need to create <strong>spend per basket . if total_baskets > 0 then spend_per_basket is total_sales/ total_baskets. else 0</strong> TIA. dummy code: </p> <pre><code>trans_for_my_week=weekly_trans[weekly_trans['week']==201520] avg_sales=pd.DataFrame(trans_for_my_week.groupby(['prod']).agg({'baskets': {'total_baskets':'sum'}, 'sales' :{'total_sales':'sum'}})) avg_sales_period_0.columns=avg_sales_period_0.columns.droplevel(0) avg_sales_period_0=avg_sales_period_0.reset_index() </code></pre> <p>and so on</p>
1
2016-08-06T06:21:18Z
38,801,480
<p>You can also get what you need using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table</a>, although it's a little different approach, <em>but you were looking for a one line code</em>:</p> <pre><code>print(pd.pivot_table(df, index = 'week', columns = 'prod', values = 'sales', aggfunc = 'sum').fillna(0)) </code></pre> <p>Output:</p> <pre><code>prod 122 123 week 201518 909.99 100.45 201519 0.00 89.65 201520 0.00 1890.54 </code></pre>
3
2016-08-06T06:56:52Z
[ "python", "python-3.x", "pandas" ]
Pytest: Update a global variable in test
38,801,234
<p>I am new to Python and am using pytest for testing</p> <p>I am executing the pytest from within the python script. I have a global variable in the script which I modify based on the result in the test. The updated global variable is again used after the tests are executed.</p> <pre><code>import pytest global test_suite_passed test_suite_passed = True def test_toggle(): global test_suite_passed a = True b = True c = True if a == b else False test_suite_passed = c assert c def test_switch(): global test_suite_passed one = True two = False three = True if one == two else False if test_suite_passed: test_suite_passed = three assert three if __name__ == '__main__': pytest.main() if not test_suite_passed: raise Exception("Test suite failed") print "Test suite passed" </code></pre> <p>I have two questions:</p> <p>1) The above code snippet prints "Test suite passed", whereas I am expecting an Exception to be raised as the second test case has failed.</p> <p>2) Basically, I want a handle to the result of the pytest, through which I can get to know the number of test cases passed and failed. This shows up in the test summary. But I am looking for a object which I can use further in the script after the tests are executed </p>
0
2016-08-06T06:24:45Z
38,802,415
<p>pytest is designed to be called from command line, not from inside your test script. Your global variable does not work, because pytest imports your script as module, which has it's own namespace.</p> <p>To customize the report generation, use the post-process-hook: <a href="http://doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures" rel="nofollow">http://doc.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures</a></p>
0
2016-08-06T08:56:20Z
[ "python", "python-2.7", "py.test", "pytest-django" ]
Pytest: Update a global variable in test
38,801,234
<p>I am new to Python and am using pytest for testing</p> <p>I am executing the pytest from within the python script. I have a global variable in the script which I modify based on the result in the test. The updated global variable is again used after the tests are executed.</p> <pre><code>import pytest global test_suite_passed test_suite_passed = True def test_toggle(): global test_suite_passed a = True b = True c = True if a == b else False test_suite_passed = c assert c def test_switch(): global test_suite_passed one = True two = False three = True if one == two else False if test_suite_passed: test_suite_passed = three assert three if __name__ == '__main__': pytest.main() if not test_suite_passed: raise Exception("Test suite failed") print "Test suite passed" </code></pre> <p>I have two questions:</p> <p>1) The above code snippet prints "Test suite passed", whereas I am expecting an Exception to be raised as the second test case has failed.</p> <p>2) Basically, I want a handle to the result of the pytest, through which I can get to know the number of test cases passed and failed. This shows up in the test summary. But I am looking for a object which I can use further in the script after the tests are executed </p>
0
2016-08-06T06:24:45Z
38,810,233
<p>This can be solved using the exit code return when calling <strong>pytest.main()</strong> The global variable is not necessary</p> <pre><code>import pytest def test_toggle(): a = True b = True c = True if a == b else False assert c def test_switch(): one = True two = False three = True if one == two else False assert three if __name__ == '__main__': exit_code = pytest.main() if exit_code == 1: raise Exception("Test suite failed") print "Test suite passed" </code></pre>
0
2016-08-07T01:59:13Z
[ "python", "python-2.7", "py.test", "pytest-django" ]
Is there a way to convert multiple date formats into datetime python
38,801,516
<p>Is there an easy way to convert multiple date formats into a datetime object in python? Eventually these will be inserted into a MySQL database with type DATE.</p> <p>Examples of what type of data I might be receiving:</p> <p>August 2, 2008</p> <p>04-02-2007</p> <p>May 2014</p> <p>Converted I would like these to be:</p> <p>2008-08-02</p> <p>2007-04-02</p> <p>2014-05-00</p> <p>Is there a simple way to do this or do I have to hard code each scenario?</p>
0
2016-08-06T07:02:05Z
38,801,552
<p>Use the third party <a href="http://labix.org/python-dateutil" rel="nofollow">dateutil</a> library:</p> <pre><code>&gt;&gt;&gt; from dateutil import parser &gt;&gt;&gt; parser.parse("August 2, 2008") datetime.datetime(2008, 8, 2, 0, 0) &gt;&gt;&gt; parser.parse("04-02-2007") datetime.datetime(2007, 4, 2, 0, 0) &gt;&gt;&gt; parser.parse("May 2014") datetime.datetime(2014, 5, 6, 0, 0) </code></pre> <p>Converting to required format:</p> <pre><code>&gt;&gt;&gt; parser.parse("August 2, 2008").strftime('%Y-%m-%d') '2008-08-02' &gt;&gt;&gt; parser.parse("04-02-2007").strftime('%Y-%m-%d') '2007-04-02' &gt;&gt;&gt; parser.parse("May 2014").strftime('%Y-%m-%d') '2014-05-06' </code></pre> <p>You can install it with pip:</p> <pre><code>pip install python-dateutil </code></pre> <p>Also look at:</p> <pre><code>&gt;&gt;&gt; parser.parse("May 2014") datetime.datetime(2014, 5, 6, 0, 0) &gt;&gt;&gt; # As you wanted day to be 0 and that is not valid ... &gt;&gt;&gt; datetime.datetime(2014, 5, 0, 0, 0) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: type object 'datetime.datetime' has no attribute 'datetime' &gt;&gt;&gt; # Workaround: ... &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datedefault = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0) &gt;&gt;&gt; parser.parse("May 2014",default=datedefault).strftime('%Y-%m-%d') '2014-05-01' </code></pre> <p>If day is not specified in the date string and also no default is specified, it will take the current day. Since today is <code>06 Aug 2016</code>, it replaced the day to <code>0</code> in the first section of the answer for <code>"May 2014"</code>.</p>
3
2016-08-06T07:08:11Z
[ "python", "mysql", "datetime" ]
Is there a way to convert multiple date formats into datetime python
38,801,516
<p>Is there an easy way to convert multiple date formats into a datetime object in python? Eventually these will be inserted into a MySQL database with type DATE.</p> <p>Examples of what type of data I might be receiving:</p> <p>August 2, 2008</p> <p>04-02-2007</p> <p>May 2014</p> <p>Converted I would like these to be:</p> <p>2008-08-02</p> <p>2007-04-02</p> <p>2014-05-00</p> <p>Is there a simple way to do this or do I have to hard code each scenario?</p>
0
2016-08-06T07:02:05Z
39,757,592
<p>You might also want to checkout <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow">dateparser</a>:</p> <pre><code>&gt;&gt;&gt; import dateparser &gt;&gt;&gt; dates = ['August 2, 2008', '04-02-2007', 'May 2014'] &gt;&gt;&gt; [dateparser.parse(d, settings={'PREFER_DAY_OF_MONTH': 'first'}).strftime('%Y-%m-%d') for d in dates] ['2008-08-02', '2007-04-02', '2014-05-01'] </code></pre> <p>Plus side is you can specify to fill date with day missing (e.g. May 2014) to use either first day of the month, last or current.</p>
0
2016-09-28T21:01:43Z
[ "python", "mysql", "datetime" ]
Functioning of append in dictionary?
38,801,672
<p>Please explain the use of <code>append</code> function in the following example:</p> <p>Example 1:</p> <pre><code>new = {} for (key, value) in data: if key in new: new[key].append( value ) else: new[key] = [value] </code></pre> <p>and in example 2:</p> <pre><code>new = {} for (key, value) in data: group = new.setdefault(key, []) group.append( value ) </code></pre>
1
2016-08-06T07:23:34Z
38,801,719
<p><code>new</code> is a dictionary, but the dictionary’s value are lists, which have the <a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="nofollow"><code>list.append()</code></a> method.</p> <p>In the loop, the dictionary is being filled with the values from <code>data</code>. Apparently, it is possible that there are multiple values for a single <code>key</code>. So in order to save that within a dictionary, the dictionary needs to be able to store multiple values for a key; so a list is being used which then holds all the values.</p> <p>The two examples show two different ways of making sure that the dictionary value is a list when the key is new.</p> <p>The first example explicitly checks if the key is already in the dictionary using <code>key in new</code>. If that’s the case, you can just append to the already existing list. Otherwise, you need to add a new list to the dictionary.</p> <p>The second example uses <a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow"><code>dict.setdefault</code></a> which sets a value <em>if</em> the key does not exist yet. So this is a special way of making sure that there’s always a list you can append the value to.</p>
1
2016-08-06T07:30:31Z
[ "python" ]
How to know when creating set or frozenset
38,801,695
<p>I am new to Python. I am reading Building Skills in Python (<em>Lott</em>) and trying out some examples. I see that the <code>set(iterable)</code> function creates both a mutable set and an immutable frozenset. How do I know if I am creating a set or a frozenset?</p>
1
2016-08-06T07:26:36Z
38,801,805
<p>That is simply incorrect. The <a href="https://docs.python.org/2/library/functions.html#func-set" rel="nofollow"><code>set()</code></a> built-in returns a set, not a frozenset. <a href="https://docs.python.org/2/library/functions.html#func-frozenset" rel="nofollow"><code>frozenset()</code></a> returns a frozenset. A set and a frozenset are both <a href="https://docs.python.org/2/library/stdtypes.html#types-set" rel="nofollow">set types</a>, however they are <em>distinct</em> set types. </p> <p><a href="https://docs.python.org/2/index.html" rel="nofollow">The Python docs</a> can always be useful for clarification on things like this, there's an entire <a href="https://docs.python.org/2/library/functions.html" rel="nofollow">list of built-in functions</a>.</p> <hr> <p><sup> Excerpt from the book Building Skills in Python (Lott) noted by OP in a comment, emphasis mine. </sup></p> <blockquote> <p>A set <strong>value</strong> is created by using the <code>set()</code> <strong>or</strong> <code>frozenset()</code> factory functions. These can be applied to any iterable container, which includes any sequence, the keys of a dict, or even a file.</p> </blockquote> <p>The author here is using "set value" to describe a value of set <em>type</em>, and is thus not indicating that <code>set()</code> and <code>frozenset()</code> do the same thing - they produce values of distinct set types, namely sets and frozensets. </p>
2
2016-08-06T07:41:13Z
[ "python", "python-2.7" ]
how to make a different conditions with one input (python)
38,801,851
<p>Can anyone help me with this coding?</p> <p>I want to insert a RFID card data to a MySQL database. When i first tap the tag on RFID Reader, the program will insert the data to Masuk table When i tap the tag again, the program will insert the data to Keluar table.</p> <p>Am i doing right with this code?</p> <pre><code>import MFRC522 import signal import time import MySQLdb import datetime db = MySQLdb.connect(host='localhost', user='root', passwd='12345678', db='pa')&lt;br&gt; cursor = db.cursor() continue_reading = True MIFAREReader = MFRC522.MFRC522() cardA = [131,89,173,1,118] def read (): read = 1 def end_read(signal, frame): global continue_reading continue_reading = False print "Ctrl+C captured, ending read." MIFAREReader.GPIO_CLEEN() signal.signal(signal.SIGINT, end_read) while continue_reading: (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) if status == MIFAREReader.MI_OK: print "Card detected" (status,backData) = MIFAREReader.MFRC522_Anticoll() if status == MIFAREReader.MI_OK: print "Card read UID: "+str(backData[0])+""+str(backData[1])+""+str(backData$ if backData == cardA: print "Selamat Datang Dheny" if (read == True): sql = """ INSERT INTO Masuk(Nama, No_ID, datetime) VALUES ('Dheny', $ try: cursor.execute(sql) db.commit() except: db.rollback() read = False if (read == False): sql = """ INSERT INTO Keluar(Nama, No_ID, datetime) VALUES ('Dhe$ try: cursor.execute(sql) db.commit() except: db.rollback() read = True </code></pre>
0
2016-08-06T07:48:29Z
38,803,580
<p>all you need is something like this.create a global variable(count) to achieve the behavior with <code>if and elif</code> condition like </p> <pre><code> if (count==True): # insert into musak and update count to false elif(count==False): # insert into other table and update count to True </code></pre> <p>i don't know if you are try to achieve the behavior with <code>read</code> variable if yes then it should be global and use <code>elif</code> instead of <code>if</code> to execute only one case and you need to change it's value of <code>read</code> like following.</p> <pre><code> if (read == True): sql = """ INSERT INTO Masuk(Nama, No_ID, datetime) VALUES ('Dheny', $ try: cursor.execute(sql) db.commit() except: db.rollback() global read # Needed to modify global copy of read globvar = False # next time read==False case will be executed elif (read == False): global read # Needed to modify global copy of read read = True # next time read==True case will be executed sql = """ INSERT INTO Keluar(Nama, No_ID, datetime) VALUES ('Dhe$ try: cursor.execute(sql) db.commit() except: db.rollback() </code></pre>
0
2016-08-06T11:08:15Z
[ "python", "mysql", "database", "raspberry-pi", "rfid" ]
how to make a different conditions with one input (python)
38,801,851
<p>Can anyone help me with this coding?</p> <p>I want to insert a RFID card data to a MySQL database. When i first tap the tag on RFID Reader, the program will insert the data to Masuk table When i tap the tag again, the program will insert the data to Keluar table.</p> <p>Am i doing right with this code?</p> <pre><code>import MFRC522 import signal import time import MySQLdb import datetime db = MySQLdb.connect(host='localhost', user='root', passwd='12345678', db='pa')&lt;br&gt; cursor = db.cursor() continue_reading = True MIFAREReader = MFRC522.MFRC522() cardA = [131,89,173,1,118] def read (): read = 1 def end_read(signal, frame): global continue_reading continue_reading = False print "Ctrl+C captured, ending read." MIFAREReader.GPIO_CLEEN() signal.signal(signal.SIGINT, end_read) while continue_reading: (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) if status == MIFAREReader.MI_OK: print "Card detected" (status,backData) = MIFAREReader.MFRC522_Anticoll() if status == MIFAREReader.MI_OK: print "Card read UID: "+str(backData[0])+""+str(backData[1])+""+str(backData$ if backData == cardA: print "Selamat Datang Dheny" if (read == True): sql = """ INSERT INTO Masuk(Nama, No_ID, datetime) VALUES ('Dheny', $ try: cursor.execute(sql) db.commit() except: db.rollback() read = False if (read == False): sql = """ INSERT INTO Keluar(Nama, No_ID, datetime) VALUES ('Dhe$ try: cursor.execute(sql) db.commit() except: db.rollback() read = True </code></pre>
0
2016-08-06T07:48:29Z
38,864,616
<p>see the code to access and modify the global variable</p> <pre><code>global count def modi(): global count # required to modify the global copy count=10 def printc(): if (count==10): # read it as a normal variable print("yes") modi() printc() </code></pre>
0
2016-08-10T05:03:44Z
[ "python", "mysql", "database", "raspberry-pi", "rfid" ]
kill python thread while it waits for read for a long time
38,802,014
<p>I need to terminate thread but can't check regularly any flags since it waits for reading/input.</p> <p>Simple example:</p> <pre><code>import threading, time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print(input("wainting for input: ")) th = Test() th.start() time.sleep(5) print("killing!") th.join(5) print(th.is_alive()) </code></pre> <p>The more real example is this (kill thread when it hangs - no output for longer time):</p> <pre><code>import threading, time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def call(args): return subprocess.Popen(" ".join(args), shell=True, stderr=subprocess.PIPE) def run(self): mainProcess = call([ any program that could hang]) out = None while mainProcess.returncode != 0 or out == '' and mainProcess.poll() != None: out = mainProcess.stderr.read(1) if out != '': sys.stdout.write(out) sys.stdout.flush() th = Test() th.start() time.sleep(5) print("killing!") th.join(5) print(th.is_alive()) </code></pre> <p>If there is a better approach, I would be happy too.</p>
0
2016-08-06T08:07:37Z
38,802,275
<p>Here's an example, how you can solve your hanging process problem with <code>select</code>:</p> <pre><code>import threading import select import subprocess import sys def watch_output(args, timeout): process = subprocess.Popen(args, stdout=subprocess.PIPE) while True: ready_to_read, _, _ = select.select([process.stdout], [], [], timeout) if not ready_to_read: print "hanging process" process.kill() break out = ready_to_read[0].read(1) if not out: print "normal exit" break sys.stdout.write(out) sys.stdout.flush() return process.wait() watch_output(['ls'], timeout=10) </code></pre> <p>or even your input with timeout is possible:</p> <pre><code>def read_input(prompt, timeout): sys.stdout.write(prompt) sys.stdout.flush() ready_to_read, _, _ = select.select([sys.stdin], [], [], timeout) if not ready_to_read: return None return ready_to_read[0].readline() print read_input("wainting for input (4s): ", 4) </code></pre>
1
2016-08-06T08:36:48Z
[ "python", "multithreading" ]
kill python thread while it waits for read for a long time
38,802,014
<p>I need to terminate thread but can't check regularly any flags since it waits for reading/input.</p> <p>Simple example:</p> <pre><code>import threading, time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): print(input("wainting for input: ")) th = Test() th.start() time.sleep(5) print("killing!") th.join(5) print(th.is_alive()) </code></pre> <p>The more real example is this (kill thread when it hangs - no output for longer time):</p> <pre><code>import threading, time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def call(args): return subprocess.Popen(" ".join(args), shell=True, stderr=subprocess.PIPE) def run(self): mainProcess = call([ any program that could hang]) out = None while mainProcess.returncode != 0 or out == '' and mainProcess.poll() != None: out = mainProcess.stderr.read(1) if out != '': sys.stdout.write(out) sys.stdout.flush() th = Test() th.start() time.sleep(5) print("killing!") th.join(5) print(th.is_alive()) </code></pre> <p>If there is a better approach, I would be happy too.</p>
0
2016-08-06T08:07:37Z
38,802,300
<p>You can just have the main thread kill the process. The reader thread will eventually hit EOF and then exit.</p> <p>Example:</p> <pre><code>#!/usr/bin/env python import threading import subprocess import time import sys def pipe_thread(handle): print "in pipe_thread" x = handle.readline() while x: print "got:", x[:-1] x = handle.readline() def main(): p = subprocess.Popen(["./sender"], stdout = subprocess.PIPE) t = threading.Thread(target = pipe_thread, args = [p.stdout]) t.start() print "sleeping for a while" time.sleep(5) print "killing process" p.kill() print "joining" t.join() print "joined" main() </code></pre>
0
2016-08-06T08:41:07Z
[ "python", "multithreading" ]
Spark UDF that takes in unknown number of columns
38,802,054
<p>I have a list of spark dataframes with different schemas. Example: </p> <pre><code>list_df = [df1, df2, df3, df4] # df1.columns = ['a', 'b'] # df2.columns = ['a', 'b', 'c'] # df3.columns = ['a', 'b', 'c', 'd'] # df4.columns = ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>Now, I want to write a single udf that is able to operate on this list of dataframes with different number of columns. </p> <p>There is a previous post on how to do it using scala: <a href="http://stackoverflow.com/questions/33151866/spark-udf-with-varargs">Spark UDF with varargs</a>, where the udf takes in an array of columns.</p> <p>But it seems that the approach does not work for python. Any suggestions?</p> <p>Thanks.</p>
1
2016-08-06T08:12:36Z
38,803,457
<p>Actually this approach works just fine in Python:</p> <pre><code>from pyspark.sql.functions import array, udf df = sc.parallelize([("a", "b", "c", "d")]).toDF() f = udf(lambda xs: "+".join(xs)) df.select(f("_1")).show() ## +------------+ ## |&lt;lambda&gt;(_1)| ## +------------+ ## | a| ## +------------+ df.select(f(array("_1", "_2"))).show() ## +-----------------------+ ## |&lt;lambda&gt;(array(_1, _2))| ## +-----------------------+ ## | a+b| ## +-----------------------+ df.select(f(array("_1", "_2", "_3"))).show() ## +---------------------------+ ## |&lt;lambda&gt;(array(_1, _2, _3))| ## +---------------------------+ ## | a+b+c| ## +---------------------------+ </code></pre> <p>Since Python UDF are not the same type of entity like their Scala counterpart are not constrained by the types and number of the input arguments you also use args:</p> <pre><code>g = udf(lambda *xs: "+".join(xs)) df.select(g("_1", "_2", "_3", "_4")).show() ## +------------------------+ ## |&lt;lambda&gt;(_1, _2, _3, _4)| ## +------------------------+ ## | a+b+c+d| ## +------------------------+ </code></pre> <p>to avoid wrapping input with <code>array</code>.</p> <p>You can also use <code>struct</code> as an alternative wrapper to get access to the column names:</p> <pre><code>h = udf(lambda row: "+".join(row.asDict().keys())) df.select(h(struct("_1", "_2", "_3"))).show() ## +----------------------------+ ## |&lt;lambda&gt;(struct(_1, _2, _3))| ## +----------------------------+ ## | _1+_3+_2| ## +----------------------------+ </code></pre>
2
2016-08-06T10:54:17Z
[ "python", "apache-spark", "dataframe", "pyspark", "udf" ]
For loop queryset from inline model
38,802,097
<p>have a model and and inline model.. I need to create a queryset which retrieves data from the inline model and returns a for loop in a template..Looks like my code is not working though..can anyone help?</p> <pre><code>class Account(models.Model): uuid = ShortUUIDField(unique=True) name = models.CharField(max_length=80) desc = models.TextField(blank=True) address_one = models.CharField(max_length=100) def __str__(self): return u"%s" % self.name class Rates(models.Model): airline = models.CharField(max_length=30, blank=True, verbose_name= 'AIRLINE') dest = models.CharField(max_length=3,blank=True,verbose_name= 'DEST') name= models.ForeignKey (Account, default = False, related_name="rates") def __str__(self): return self.airline My for loop should retrieve all rates in case account name is XXX def rates_acc(request, account): account = Account.objects.get(name = xxx) rates = [x for x in account.rates.all()] context = { 'rates': Account.objects.filter (name__name__icontains = 'xxx'), } return render(request,'accounts/account.html',context) </code></pre>
2
2016-08-06T08:17:06Z
38,804,557
<blockquote> <p>My for loop should retrieve all rates in case account name is XXX</p> </blockquote> <p>Then this:</p> <pre><code>'rates': Account.objects.filter(name__name__icontains='xxx) </code></pre> <p>Should be like this</p> <pre><code>'rates': Rates.objects.filter(name__name='XXX') </code></pre> <p>OR if you want to get all rates where account name contains XXX</p> <pre><code>'rates': Rates.objects.filter(name__name__icontains='XXX') </code></pre>
1
2016-08-06T13:02:19Z
[ "python", "django-models" ]
Adding BioNetGen to Anaconda environment
38,802,101
<p>I am trying to use <a href="http://docs.pysb.org/en/latest/" rel="nofollow">PySB</a> with Anaconda3 and Windows7. I have added the relevant depedencies (numpy, scipy, sympi, perl) to a working environment. However I am struggling with the BioNetGen program. I have downloaded it, and added the path to BNG, but I cannot add it to my environment. </p> <p>Here is what I have tried:</p> <pre><code>&gt;conda search bionetgen Using Anaconda Cloud api site http.... Fetching package metadata... </code></pre> <p>Then nothing happens.</p> <pre><code>&gt;pip install bionetgen Collecting bionetgen </code></pre> <p>Then error message:</p> <pre><code>Could not find a version that satisfies the requirement bionetgen (from versions: ) No matching distribution found for bionetgen </code></pre> <p>Finally, I tried:</p> <pre><code>&gt;easy_install bionetgen Processing bionetgen... error: could not find a setup script in C:\.... </code></pre> <p>However I can open the BioNetGen programme manually and get the gui so I assume it has installed correctly. I just don't know how to add it to anaconda. Is the problem that BioNetGen runs on perl?</p> <p>There is a Virtual Box available for visualisation the pysb models but I would prefer to install dependencies manually.</p> <p>Thanks for any help!</p>
0
2016-08-06T08:17:39Z
38,807,164
<p>Yes, BioNetGen itself is written in Perl and thus can't be installed via pip or other Python package managers. You need to download the <a href="http://www.bionetgen.org/index.php/BioNetGen_Distributions" rel="nofollow">BioNetGen command-line interface</a> for your platform and then follow the instructions in the <a href="http://pysb.readthedocs.io/en/latest/installation.html#option-2-installing-the-dependencies-yourself" rel="nofollow">PySB installation documentation</a> to install it where PySB can find it:</p> <blockquote> <p>Rename the unzipped BioNetGen-x.y.z folder to just <code>BioNetGen</code> and move it into /usr/local/share (Mac or Linux) or C:\Program Files (Windows). If you would like to put it somewhere else, set the <code>BNGPATH</code> environment variable to the full path to the BioNetGen-x.y.z folder.</p> </blockquote> <p>You mention the BioNetGen "GUI" which leads me to believe you've downloaded the RuleBender GUI interface rather than the command-line tools. The PySB docs don't explicitly state that you need the command-line tools -- we will definitely rectify this oversight.</p>
0
2016-08-06T17:52:04Z
[ "python", "anaconda", "pysb" ]
How to index a tensor using arrays?
38,802,258
<p>Suppose I have a 3D array (tensor)</p> <pre><code>print a.shape (100, 100, 100) </code></pre> <p>and want to index its first axis using one array:</p> <pre><code>print i.shape (20,) </code></pre> <p>and its last axis using another array</p> <pre><code>print j.shape (30,) </code></pre> <p>My intent is to get a (20, 100, 30) array, for example, to be used in assignments like</p> <pre><code>a[?!, :, ?!] = b </code></pre> <p>However, I can't figure out how.</p> <pre><code>print a[i.reshape(20, 1, 1), :, j.reshape(1, 1, 30)].shape (20, 1, 30, 100) print a[i.reshape(20, 1, 1), :, j].shape (20, 1, 30, 100) print a[i.reshape(20, 1), :, j].shape (20, 30, 100) print a[i.reshape(20, 1, 1), j.reshape(1, 1, 30)].shape (20, 1, 30, 100) </code></pre> <p>As I understand the "advanced indexing" rules, the first attempt should have worked, but I didn't even end up with a 3D array, and the full dimension (100) came at the end instead of the middle.</p>
0
2016-08-06T08:35:39Z
38,802,289
<p><strong>Approach #1 :</strong> You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html" rel="nofollow"><code>np.ix_</code></a> for getting such meshes of indices and simply indexing into the input array must give you the desired output. Thus, an implementation would be like so -</p> <pre><code>a[np.ix_(i,np.arange(a.shape[1]),j)] </code></pre> <p><strong>Approach #2 :</strong> Simpler way using broadcasted indexing -</p> <pre><code>a[i[:,None],:,j].swapaxes(1,2) </code></pre> <hr> <p>Verify with a sample case -</p> <pre><code>In [24]: a = np.random.randint(0,99,(5,3,5)) In [25]: i = np.random.randint(0,5,(2)) In [26]: j = np.random.randint(0,5,(2)) In [27]: a[i[0],:,j[0]] Out[27]: array([15, 7, 74]) In [28]: a[i[0],:,j[1]] Out[28]: array([32, 19, 85]) In [29]: a[i[1],:,j[0]] Out[29]: array([76, 65, 96]) In [30]: a[i[1],:,j[1]] Out[30]: array([54, 65, 66]) In [31]: a[np.ix_(i,np.arange(a.shape[1]),j)] Out[31]: array([[[15, 32], [ 7, 19], [74, 85]], [[76, 54], [65, 65], [96, 66]]]) In [50]: a[i[:,None],:,j].swapaxes(1,2) Out[50]: array([[[15, 32], [ 7, 19], [74, 85]], [[76, 54], [65, 65], [96, 66]]]) </code></pre> <hr> <p><strong>Assigning values with the indexing</strong></p> <p>For approach #1, it's just straight-forward -</p> <pre><code>a[np.ix_(i,np.arange(a.shape[1]),j)] = b </code></pre> <p>For approach #2, if <code>b</code> is a scalar, it should be straight-forward too -</p> <pre><code>a[i[:,None],:,j] = b </code></pre> <p>For approach #2 again, if you are assigning to a ndarray <code>b</code> of shape <code>(20,100,30)</code>, we need to swap axes of <code>b</code> before assigning, like so -</p> <pre><code>a[i[:,None],:,j] = np.swapaxes(b,1,2) </code></pre>
1
2016-08-06T08:40:02Z
[ "python", "python-2.7", "numpy", "slice" ]
ValueError unknown label type array sklearn- load_boston
38,802,537
<p>I am using the following code to check SGDClassifier</p> <pre><code>import numpy as np from sklearn.datasets import load_boston from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split data = load_boston() x_train, x_test, y_train, y_test = train_test_split(data.data, data.target) x_scalar = StandardScaler() y_scalar = StandardScaler() x_train = x_scalar.fit_transform(x_train) y_train = y_scalar.fit_transform(y_train) x_test = x_scalar.transform(x_test) y_test = y_scalar.transform(y_test) regressor = SGDClassifier(loss='squared_loss') scores = cross_val_score(regressor, x_train, y_train, cv=5) print 'cross validation r scores ', scores print 'average score ', np.mean(scores) regressor.fit_transform(x_train, y_train) print 'test set r score ', regressor.score(x_test,y_test) </code></pre> <p>However when I run it I get deprecation warnings to reshape and the following value error </p> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-55-4d64d112f5db&gt; in &lt;module&gt;() 18 19 regressor = SGDClassifier(loss='squared_loss') ---&gt; 20 scores = cross_val_score(regressor, x_train, y_train, cv=5) ValueError: Unknown label type: (array([ -1.89568750e+00, -1.75715217e+00, -1.68255622e+00, -1.66124309e+00, -1.62927339e+00, -1.54402088e+00, -1.49073806e+00, -1.41614211e+00, -1.40548554e+00, -1.34154616e+00, -1.32023303e+00, -1.30957647e+00, -1.27760677e+00, -1.26695021e+00, -1.25629365e+00, -1.20301082e+00, -1.17104113e+00, -1.16038457e+00,....]),) </code></pre> <p>What could be the probable error in the code ?</p>
0
2016-08-06T09:09:57Z
38,802,710
<p>In classification tasks, the dependent variable (or the <em>target</em>) is categorical. We try to predict if a claim is fraudulent or not, for example. In regression, on the other hand, the dependent variable is numerical. It can be measured. </p> <p>In the Boston Housing dataset, the dependent variable is <em>"Median value of owner-occupied homes in $1000's"</em> (You can see the description by executing <code>print(data.DESCR)</code>). It is a continuous variable and cannot be predicted with a classifier.</p> <p>If you want to test the classifier, you can use another dataset. For example, change <code>load_boston()</code> to <code>load_iris()</code>. Note that you also need to remove the transformation for the target variable - it is for numerical variables. With these modifications, it should work correctly.</p> <pre><code>import numpy as np from sklearn.datasets import load_iris from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split data = load_iris() x_train, x_test, y_train, y_test = train_test_split(data.data, data.target) x_scalar = StandardScaler() x_train = x_scalar.fit_transform(x_train) x_test = x_scalar.transform(x_test) classifier = SGDClassifier(loss='squared_loss') scores = cross_val_score(classifier, x_train, y_train, cv=5) scores Out: array([ 0.33333333, 0.2173913 , 0.31818182, 0. , 0.19047619]) </code></pre>
2
2016-08-06T09:30:25Z
[ "python", "scikit-learn" ]
Removing duplicates if paired adjacently
38,802,590
<p>Deleting any pair of <strong>adjacent</strong> letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.</p> <p>Sample input = aaabccddd <br/> Sample output = abd</p> <p>Confused how to iterate the list or the string in a way to match the duplicates and removing them, here is the way I am trying and I know it is wrong.</p> <pre><code>S = input() removals = [] for i in range(0, len(S)): if i + 1 &gt;= len(S): break elif S[i] == S[i + 1]: removals.append(i) # removals is to store all the indexes that are to be deleted. removals.append(i + 1) i += 1 print(i) Array = list(S) set(removals) #removes duplicates from removals for j in range(0, len(removals)): Array.pop(removals[j]) # Creates IndexOutOfRange error </code></pre> <p>This is a problem from Hackerrank: <a href="https://www.hackerrank.com/challenges/reduced-string" rel="nofollow">Super Reduced String</a></p>
0
2016-08-06T09:16:02Z
38,802,724
<p>Removing paired letters can be reduced to reducing runs of letters to an empty sequence if there are an even number of them, 1 if there are an odd number. <code>aaaaaa</code> becomes empty, <code>aaaaa</code> is reduced to <code>a</code>.</p> <p>To do this on any sequence, use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> and count the group size:</p> <pre><code># only include a value if their consecutive count is odd [v for v, group in groupby(sequence) if sum(1 for _ in group) % 2] </code></pre> <p>then repeat until the size of the sequence no longer changes:</p> <pre><code>prev = len(sequence) + 1 while len(sequence) &lt; prev: prev = len(sequence) sequence = [v for v, group in groupby(sequence) if sum(1 for _ in group) % 2] </code></pre> <p>However, since Hackerrank gives you <em>text</em> it'd be faster if you did this with a regular expression:</p> <pre><code>import re even = re.compile(r'(?:([a-z])\1)+') prev = len(text) + 1 while len(text) &lt; prev: prev = len(text) text = even.sub(r'', text) </code></pre> <p><code>[a-z]</code> in a regex matches a lower-case letter, (..)<code>groups that match, and</code>\1<code>references the first match and will only match if that letter was repeated.</code>(?:...)+<code>asks for repeats of the same two characters.</code>re.sub()` replaces all those patterns with empty text.</p> <p>The regex approach is good enough to pass that Hackerrank challenge.</p>
1
2016-08-06T09:31:09Z
[ "python", "arrays", "string", "list" ]
Removing duplicates if paired adjacently
38,802,590
<p>Deleting any pair of <strong>adjacent</strong> letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.</p> <p>Sample input = aaabccddd <br/> Sample output = abd</p> <p>Confused how to iterate the list or the string in a way to match the duplicates and removing them, here is the way I am trying and I know it is wrong.</p> <pre><code>S = input() removals = [] for i in range(0, len(S)): if i + 1 &gt;= len(S): break elif S[i] == S[i + 1]: removals.append(i) # removals is to store all the indexes that are to be deleted. removals.append(i + 1) i += 1 print(i) Array = list(S) set(removals) #removes duplicates from removals for j in range(0, len(removals)): Array.pop(removals[j]) # Creates IndexOutOfRange error </code></pre> <p>This is a problem from Hackerrank: <a href="https://www.hackerrank.com/challenges/reduced-string" rel="nofollow">Super Reduced String</a></p>
0
2016-08-06T09:16:02Z
38,802,785
<p>You can use stack in order to achieve <strong>O(n)</strong> time complexity. Iterate over the characters in a string and for each character check if the top of stack contains the same character. In case it does pop the character from stack and move to next item. Otherwise push the character to the stack. Whatever remains in the stack is the result:</p> <pre><code>s = 'aaabccddd' stack = [] for c in s: if stack and stack[-1] == c: stack.pop() else: stack.append(c) print ''.join(stack) if stack else 'Empty String' # abd </code></pre> <p><strong>Update</strong> Based on the discussion I ran couple of tests to measure the speed of regex and stack based solutions with input length of <code>100</code>. Tests were run on Python 2.7 on Windows 8:</p> <pre><code>All same Regex: 0.0563033799756 Stack: 0.267807865445 Nothing to remove Regex: 0.075074750044 Stack: 0.183467329017 Worst case Regex: 1.9983200193 Stack: 0.196362265609 Alphabet Regex: 0.0759905517997 Stack: 0.182778728207 </code></pre> <p>Code used for benchmarking:</p> <pre><code>import re import timeit def reduce_regexp(text): even = re.compile(r'(?:([a-z])\1)+') prev = len(text) + 1 while len(text) &lt; prev: prev = len(text) text = even.sub(r'', text) return text def reduce_stack(s): stack = [] for c in s: if stack and stack[-1] == c: stack.pop() else: stack.append(c) return ''.join(stack) CASES = [ ['All same', 'a' * 100], ['Nothing to remove', 'ab' * 50], ['Worst case', 'ab' * 25 + 'ba' * 25], ['Alphabet', ''.join([chr(ord('a') + i) for i in range(25)] * 4)] ] for name, case in CASES: print(name) res = timeit.timeit('reduce_regexp(case)', setup='from __main__ import reduce_regexp, case; import re', number=10000) print('Regex: {}'.format(res)) res = timeit.timeit('reduce_stack(case)', setup='from __main__ import reduce_stack, case', number=10000) print('Stack: {}'.format(res)) </code></pre>
1
2016-08-06T09:37:39Z
[ "python", "arrays", "string", "list" ]
Unit test failing after moving functions into a class
38,802,595
<p>I'm trying to write a unit test for a function within a class but I'm having a little trouble. Before moving the importer function into a class, this test worked. However, now I get <code>TypeError: grab_column_locations missing 1 required positional argument: 'sheet'</code>. The importer function itself is correctly getting parsing <code>sheet</code> and works correctly when the program is run, but not when tested.</p> <p>The line the TypeError refers to in the importer function is:</p> <pre><code>columns = self.grab_column_locations(sheet) </code></pre> <p>The test that's failing is:</p> <pre><code>from unittest import TestCase from gtt import GTT class TestGTT(TestCase): def test_importer(self): """ Test import of valid xlsx file :return: """ file_list = ['testData_1.xls'] # Run Test 1 importer_results = GTT.importer(GTT, file_list) assert importer_results[0] == True </code></pre> <p>So essentially, when run from a test, <code>importer</code>isn't passing <code>sheet</code>to <code>grab_column_locations</code>. This only started happening when I moved both of those functions into a class. I know I broke something somehow, but what?</p>
-1
2016-08-06T09:16:23Z
38,804,498
<p>The error message says this:</p> <pre><code>TypeError: grab_column_locations missing 1 required positional argument: 'sheet' </code></pre> <p>This sounds like the function signature is:</p> <pre><code>def grab_column_locations(self, sheet): </code></pre> <p>Are you not calling it from an <strong>instance</strong> of the class owning this function?</p> <p>That is, if the function belongs to the class <code>Foo</code>:</p> <pre><code>class Foo: def grab_column_locations(self, sheet): ... </code></pre> <p>The error message makes me think that you're calling the function as follows:</p> <pre><code>Foo.grab_column_locations(sheet) </code></pre> <p>When you really should call it:</p> <pre><code>foo = Foo() foo.grab_column_locations(sheet) </code></pre> <p>Alternatively, that function could be defined as a <strong>class</strong> method, if you don't want to bind it to an <strong>instance</strong>:</p> <pre><code>class Foo: @classmethod def grab_column_locations(self, sheet): ... </code></pre> <p>Then you can call it as follows:</p> <pre><code>Foo.grab_column_locations(sheet) </code></pre> <p>But anyway, this is just guesswork, since you didn't give much details.</p>
0
2016-08-06T12:54:04Z
[ "python", "unit-testing" ]
Using JSON with AJAX and Python database
38,802,638
<p>I am new to python and am trying to access the db though python and return some results in a JSON array using AJAX.<br> I test it by returning a JSON list and alerting it using js. it works when I don't use the db connection but as soon as I add it the js alert stops too. the db connection seems to work properly when I run the file <code>getSchedule.py</code>. the db connection is in a separate file <code>webairdb.py</code><br> Can someone please try to help me figure out whats wrong?</p> <h3>getSchedule.py</h3> <pre><code>#!D:/Programming/Software/python3.4.4/python import sys, json,cgi, cgitb, mysql.connector, webairdb cgitb.enable() fs = cgi.FieldStorage() sys.stdout.write("Content-Type: application/json") sys.stdout.write("\n") sys.stdout.write("\n") conn = webairdb.getConnection() conn.close() listr = [11111] sys.stdout.write(json.dumps(listr)) sys.stdout.write("\n") sys.stdout.close() </code></pre> <h3>webairdb.py</h3> <pre><code>#!D:/Programming/Software/python3.4.4/python import cgi, cgitb, imp, mysql.connector host ="localhost" db = "webair" user = "root" password = "" def getConnection(): conn = mysql.connector.connect(user=user,password=password,host=host,database=db) if conn.is_connected(): print("aaaqqqq") return conn </code></pre>
1
2016-08-06T09:22:50Z
38,803,837
<p>In <strong>webairdb.py</strong> you write to <code>sys.stdout</code> (that is what <code>print</code> does) - putting effectively breaking the json output. (You might want to have a look at the output by pressing F12 in your browser)</p> <p>So just remove it and either write to <code>sys.stderr</code> or use <a href="https://docs.python.org/3/howto/logging.html#logging-basic-tutorial" rel="nofollow">logging</a> instead.</p> <p>You should also consider using <a href="https://docs.python.org/3/library/wsgiref.html" rel="nofollow">wsgi</a> instead of cgi which makes things a bit easier (no need to care about printing at all) or a framework like <a href="http://bottlepy.org" rel="nofollow">bottle</a> or <a href="http://cherrypy.org/" rel="nofollow">cherrypy</a>.</p>
0
2016-08-06T11:36:08Z
[ "javascript", "python", "json", "ajax", "database" ]
how to get two inputs and accessing to objects and methods of a class?
38,802,726
<p>I wrote this code to access an object via user input. It works with locals (I know I can make dictionary too) </p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs redfire = Dragon(2, 4) dic1 = {"redfire": redfire} input_object = input() print(dic1[input_object].sum()) </code></pre> <p>but when I'm trying to do the same with methods of the class:</p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs def mul(self): return self.head * self.legs redfire = Dragon(2, 4) dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} input_object = input() input_method = input() print(dic1[input_object].dic1[input_method]) </code></pre> <p>I'm getting all kinds of errors asking me to modify my dictionary:</p> <pre><code>Traceback (most recent call last): File "C:\Users\millw0rm\test.py", line 10, in &lt;module&gt; dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} NameError: name 'self' is not defined </code></pre> <p>What can I do to define a valid key for my methods in my dictionary? </p>
-1
2016-08-06T09:31:15Z
38,802,871
<p>You are not using class method rightly :</p> <pre><code>redfire = Dragon(2, 4) dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} </code></pre> <p>In fact, in your class function definition: <code>def sum(self):</code>, self refer to an object of the class.</p> <p>You should then use it like this :</p> <pre><code># Create one dragon redfire = Dragon(2, 4) # Enter the dragon in the dict dic1 = {"redfire": redfire, "sum": redfire.sum(), "mul": redfire.mul()} </code></pre> <p>Therefore you are using <code>redfire.sum()</code> that is basically using <code>sum()</code> function on the object <code>redfire</code> that is a <code>Dragon</code> object.</p> <p>For the second part of your work: <code>print(dic1[input_object].dic1[input_method])</code>, you need to store a reference to a function:</p> <pre><code>sum_method = Dragon.sum sum_redfire = sum_method(redfire) </code></pre> <p>Finaly we get:</p> <pre><code>redfire = Dragon(2, 4) sum_method = Dragon.sum dict1 = {"redfire": redfire, "sum": sum_method} input_object = input() input_method = input() print(dict1[input_method](dict1[input_object])) </code></pre>
0
2016-08-06T09:47:43Z
[ "python", "class", "python-3.x", "methods", "input" ]
how to get two inputs and accessing to objects and methods of a class?
38,802,726
<p>I wrote this code to access an object via user input. It works with locals (I know I can make dictionary too) </p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs redfire = Dragon(2, 4) dic1 = {"redfire": redfire} input_object = input() print(dic1[input_object].sum()) </code></pre> <p>but when I'm trying to do the same with methods of the class:</p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs def mul(self): return self.head * self.legs redfire = Dragon(2, 4) dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} input_object = input() input_method = input() print(dic1[input_object].dic1[input_method]) </code></pre> <p>I'm getting all kinds of errors asking me to modify my dictionary:</p> <pre><code>Traceback (most recent call last): File "C:\Users\millw0rm\test.py", line 10, in &lt;module&gt; dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} NameError: name 'self' is not defined </code></pre> <p>What can I do to define a valid key for my methods in my dictionary? </p>
-1
2016-08-06T09:31:15Z
38,803,423
<p>There's no point storing the methods in the dictionary: they're already stored in the Dragon class itself. As jonrsharpe mentions in the comments, you can use the built-in <code>getattr</code> function to retrieve an attribute of a class instance; that applies to methods like your <code>sum</code> and <code>mul</code> as well as the simple <code>head</code> and <code>legs</code> attributes.</p> <p>Here's a re-organised version of your code that I think you'll find useful. I've added a <code>__repr__</code> method to the class so that we get useful info when we print a Dragon instance.</p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs def mul(self): return self.head * self.legs def __repr__(self): return 'Dragon({}, {})'.format(self.head, self.legs) dragons = {} dragons["redfire"] = Dragon(2, 4) dragons["greenfire"] = Dragon(1, 2) print(dragons) name = input("name: ") method_name = input("method: ") d = dragons[name] method = getattr(d, method_name) print(d, method()) </code></pre> <p><strong>test</strong></p> <pre><code>{'redfire': Dragon(2, 4), 'greenfire': Dragon(1, 2)} name: redfire method: sum Dragon(2, 4) 6 </code></pre> <p>Of course, you <em>could</em> create the <code>dragons</code> dictionary like this:</p> <pre><code>dragons = { "redfire": Dragon(2, 4), "greenfire": Dragon(1, 2), } </code></pre>
0
2016-08-06T10:49:18Z
[ "python", "class", "python-3.x", "methods", "input" ]
how to get two inputs and accessing to objects and methods of a class?
38,802,726
<p>I wrote this code to access an object via user input. It works with locals (I know I can make dictionary too) </p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs redfire = Dragon(2, 4) dic1 = {"redfire": redfire} input_object = input() print(dic1[input_object].sum()) </code></pre> <p>but when I'm trying to do the same with methods of the class:</p> <pre><code>class Dragon: def __init__(self, head, legs): self.head = head self.legs = legs def sum(self): return self.head + self.legs def mul(self): return self.head * self.legs redfire = Dragon(2, 4) dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} input_object = input() input_method = input() print(dic1[input_object].dic1[input_method]) </code></pre> <p>I'm getting all kinds of errors asking me to modify my dictionary:</p> <pre><code>Traceback (most recent call last): File "C:\Users\millw0rm\test.py", line 10, in &lt;module&gt; dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul} NameError: name 'self' is not defined </code></pre> <p>What can I do to define a valid key for my methods in my dictionary? </p>
-1
2016-08-06T09:31:15Z
38,804,242
<p>Thanks so much everbody especially jonrsharp and PM 2Ring for mentioning getattr() function . code below is what i was seeking for </p> <pre><code>class Dragon: def __init__(self,head,tail): self.head=head self.tail=tail def sum(self): return (self.head + self.tail) class Snake: def __init__(self,head,tail): self.head=head self.tail=tail def sum(self): return (self.head * self.tail) python=Snake(1,1) anakonda=Snake(3,5) redfire=Dragon(2,4) hellfly=Dragon(2,10) x=input() y=input() z=objectdic[x].__class__.__name__ print(getattr(locals()[z],y)(locals()[x])) </code></pre>
0
2016-08-06T12:20:18Z
[ "python", "class", "python-3.x", "methods", "input" ]
Importing module with "current-directory" imports
38,802,908
<p>I have the following code to load a module dynamically:</p> <pre><code>def load_module(absolute_path): import importlib.util module_name, _ = os.path.splitext(os.path.split(absolute_path)[-1]) try: py_mod = imp.load_source(module_name, absolute_path) except ImportError: module_root = os.path.dirname(absolute_path) print("Could not directly load module, including dir: {}".format(module_root)) spec = importlib.util.spec_from_file_location( module_name, absolute_path, submodule_search_locations=[module_root, "."]) py_mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(py_mod) return py_mod </code></pre> <p>It works really well, except for the case when it is trying to import a script in the same folder (and not part of a package with the same name). For example, script <code>a.py</code> is doing <code>import b</code>. It results in the error <code>ImportError: No module named 'b'</code> (which is common for Python 3).</p> <p>But I would really like to find a way to solve this? It would be solved by prepending:</p> <pre><code>import sys sys.path.append(".") </code></pre> <p>to script "a".</p> <p>Though I hoped it could have been solved by: </p> <pre><code>submodule_search_locations=[module_root, "."] </code></pre> <p>Oh yea, the rationale is that I also want to support importing modules that are not proper packages/modules, but just some scripts that would work in an interpreter.</p> <p><strong>Reproducible code</strong>:</p> <h2>~/example/a.py</h2> <pre><code>import b </code></pre> <h2>~/example/b.py</h2> <pre><code>print("hi") </code></pre> <h2>~/somewhere_else/main.py (located different from a/b)</h2> <pre><code>import sys, os, imp, importlib.util def load_module(absolute_path) ... load_module(sys.argv[1]) </code></pre> <p>Then run on command line:</p> <pre><code>cd ~/somewhere_else python3.5 main.py /home/me/example/a.py </code></pre> <p>which results in <code>ImportError: No module named 'b'</code></p> <p>The following code solves it, but of course we cannot put <code>sys.path</code> stuff manually in all scripts.</p> <h2>~/example/a.py (2)</h2> <pre><code>import sys sys.path.append(".") import b </code></pre> <p>I really hope others might have a solution that I didn't think of yet.</p> <h1>Appendix</h1> <pre><code>def load_module(absolute_path): import importlib.util module_name, _ = os.path.splitext(os.path.split(absolute_path)[-1]) try: py_mod = imp.load_source(module_name, absolute_path) except ImportError as e: if "No module named" not in e.msg: raise e missing_module = e.name module_root = os.path.dirname(absolute_path) if missing_module + ".py" not in os.listdir(module_root): msg = "Could not find '{}' in '{}'" raise ImportError(msg.format(missing_module, module_root)) print("Could not directly load module, including dir: {}".format(module_root)) sys.path.append(module_root) spec = importlib.util.spec_from_file_location(module_name, absolute_path) py_mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(py_mod) return py_mod </code></pre>
0
2016-08-06T09:52:09Z
38,804,371
<p>It doesn't really matter that this you are using dynamic importing here; the same problem applies to any code making assumptions about the current directory being on the path. It is the responsibility of those scripts to ensure that the current directory is on the path themselves.</p> <p>Rather than use <code>'.'</code> (current working directory), use the <code>__file__</code> global to add the directory to the path:</p> <pre><code>import os.path import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) </code></pre> <p>You <em>could</em> retry your dynamic import by adding <code>os.path.dirname(absolute_path)</code> to <code>sys.path</code> when you have an <code>ImportError</code> (perhaps <a href="https://stackoverflow.com/questions/16625906/distinguish-between-importerror-because-of-not-found-module-or-faulty-import-in">detecting it was a transient import that failed</a>), but that's a huge leap to make as you can't distinguish between a missing dependency and a module making an assumption about <code>sys.path</code>.</p>
1
2016-08-06T12:36:01Z
[ "python", "import", "python-3.5", "python-importlib" ]
Translate/Rotate 2D points to change perspective
38,802,990
<p>I am recording a video of a users eye, and then using computer vision to track their eyes in an attempt to estimate their gaze, however the angle I am able to record the user at is not straight on and the representation of the data needs to be displayed, as if the user is looking straight on.</p> <p>To explain myself further please consider the following images depicticing what I have so far, and what I am trying to achieve:</p> <p><a href="http://i.stack.imgur.com/fica8.png"><img src="http://i.stack.imgur.com/fica8.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/OdmtM.png"><img src="http://i.stack.imgur.com/OdmtM.png" alt="enter image description here"></a></p> <p>I thought perhaps the best way to achieve this would be to translate the perspective, but not being very well versed in this, I have no idea where to begin.</p> <p>I am open to any suggestions on the best way to achieve the desired result, but please bear in mind that my matrix math is fairly rusty, so if you use any well-known methods, please cater to my ignorance and explain everything as well as you can.</p> <p>The data is currently stored as a NumPy array of X/Y Points</p>
5
2016-08-06T10:00:23Z
38,831,587
<p>My matrix math is worse than "fairly rusty," but I've got a few ideas that could be helpful.</p> <p>Overall, there's a lot more information on transforming images than transforming discrete points. You may want to look into transforming the eye portion of your image rather than transforming the pupil points.</p> <p>Anyway, here are my ideas:</p> <h3>Approach 1: simple perspective transformation</h3> <p><a href="http://stackoverflow.com/questions/14177744/how-does-perspective-transformation-work-in-pil">This answer</a> describes how to perform perspective transformation in Python Imaging Library, using <code>numpy</code> to calculate coefficients for the transformation.</p> <p>It's probably easy to adapt this to operate on points rather than an image (google suggests <code>scipy</code> has some functions similar to PIL.Image.transform` which may be more applicable). Failing this, you could just render your points onto a binary image, as white pixels on a black background, then transforming that image and reading the points back out.</p> <p>However, for perspective transformation, you still need an approach for determining the coordinates of <code>pa</code>, the plane from which you're transforming. You could likely achieve reasonable results simply by fitting a rectangle around the eye. To do this, I would probably rotate your figure so it was parallel with the X axis, by constructing a line between the ends of the eye and then rotating by the line's angle from 0°. Then I'd record the bounding box, and rotate both back. Your plane will look something like this:</p> <p><img src="http://i.stack.imgur.com/3LYPY.png" alt="Example"></p> <p>At this point, you might be able to extract the angle of the dominant contours of the eye and pinch and squeeze your bounding rectangle accordingly. Simple perspective transformation will probably prove unreliable, though.</p> <h3>Approach 2: Better perspective transformation</h3> <p>Given a set of starting points and a set of ending points, there's almost certainly a way to calculate perspective transformation coefficients from those, even if the number is greater than 4. You could just skip bounding boxes and assume translating each point to its counterpart on the ideal shape, then calculate coefficients based on that. Don't ask me how, though, I have no idea :P</p> <h2>Approach 3: basic stretching</h2> <p>If your "destination shape" has the same number of points as the shape from which you're transforming, you could emulate the stretch functions of many image editing programs. Photoshop has tools that allow you to pull points on a shape to move them around, stretching the content inside. If you could reproduce this behavior, you could just move each point on the starting shape to a corresponding point on the destination shape, stretching the image. This is probably the most reliable approach, simply stretch your image to fit the destination shape, then pull the pupil from that new image.</p> <hr> <p>The problem with all these approaches is that normal perspective transformation will never be quite accurate, because the eye is curved, not flat. You can't really approximate the surface of an eye with a plane and expect complete accuracy. Even stretching (approach 3) will suffer from the angle of your photo; it will favor the visible side of the eye and make it appear as if the eye is looking far more to the left (their right) than it is. <strong>If</strong> the angle of the photo is constant and known, you may be able to correct this yourself. Otherwise, I don't see an easy solution to this obstacle.</p> <hr> <p>I know very little about higher-level math, but hopefully you find my ideas helpful.</p> <p>FWIW, eye tracking is well-researched and there are several thorough papers like <a href="http://thirtysixthspan.com/openEyes/starburst.pdf" rel="nofollow">this one</a></p>
4
2016-08-08T14:15:25Z
[ "python", "numpy", "2d", "matrix-multiplication", "perspectivecamera" ]
Reading spcific columns out of file
38,802,991
<p>I am having a problem reading big (300008 lines) output file of simulation code. I am using this function to read two columns of the file </p> <pre><code>def read2(filename,i1,i2): "Read 2 ARRAYS from the i1-th and i2-th columns of a text file" from numpy import * # import numpy package f = open(filename,'r') # open the file n = len(f.readlines()) # get number of rows L1= [] ; L2=[] # create empty lists f.seek(0) # go to beginning of file for k in range(n): s = f.readline() # read current row in string format e = s.split() # split the elements of the string between white spaces if "#" not in e[0]: L1.append( e[i1-1] ) L2.append( e[i2-1] ) f.close() # close input file A1 = convert(L1,i1) A2 = convert(L2,i2) return A1,A2 # return arrays A1 &amp; A2 to __main__ . </code></pre> <p>The problem is; it always giving me IndexError: list index out of range.</p> <p>PS. convert is another function converting the string lists into arrays. </p>
0
2016-08-06T10:00:35Z
38,804,041
<p>When you <code>len(f.readlines())</code>, the it comes to the end of the file, so <code>f.readline()</code> starts from the end of file every time. You get empty string all the time.</p>
0
2016-08-06T11:57:28Z
[ "python", "string", "list", "python-2.7", "numpy" ]
How to sum Threads in python
38,803,050
<p>I need help on how i can sum all the threads.to get sum of thread one to three all together..The parallel program should use all processors in host computer</p> <pre><code>import threading import time from datetime import datetime start_time = datetime.now() def sum_number(): summ = 100 for num in range (1, 100): summ = summ + num num -= 1 print ("SUM IS", summ) def sum_number1(): summr = 200 for num in range (101,200): summr = summr + num num -= 1 print ("SUM IS", summr) def sum_number2(): summy = 300 for num in range (201, 300): summy = summy + num num -= 1 print ("SUM IS", summy) #take time t2 #end_time =datetime.now() #print t2 -t1 #print('Time taken : {}'. format(end_time-start_time)) if __name__=="__main__": #sum_number() #sum_number1() #sum_number2() #sum_number3() t1=threading.Thread(target=sum_number) t1.start() time.sleep(5) t2=threading.Thread(target=sum_number1) t2.start() time.sleep(10) t3=threading.Thread(target=sum_number2) t3.start() time.sleep(15) #end_time =datetime.now() </code></pre> <p>I need help on how i can sum all the threads.to get sum of thread one to three all together..The parallel program should use all processors in host computer</p>
0
2016-08-06T10:06:15Z
38,803,360
<p>You can do</p> <pre><code>import time import multiprocessing.dummy as mp # uses threads instead of full processes def sum_range(start_stop): start,stop=start_stop return sum(range(start,stop)) if __name__=="__main__": start_time=time.perf_counter() with mp.Pool() as p: my_sums=p.map(sum_range,[(1,101),(101,201),(201,301)]) # sums from 1 to 300 (including 300) full_sum=sum(my_sums) end_time=time.perf_counter() print("The sum is", full_sum) print("Calculating it took",end_time-start_time, "seconds." ) </code></pre> <p>for using processes instead of threads use <code>import multiprocessing as mp</code></p> <p>In this case if you are after performance, doing the sum in a single thread/process is much faster because you are summing so few numbers. Creating Threads takes time and creating Processes takes much more time. (Normally using threads does not increase computational performance with the standard interpreter if you are not using special functions which release the "GIL")</p>
0
2016-08-06T10:40:53Z
[ "python", "multithreading", "python-3.x", "parallel-processing", "multiprocessing" ]
indentation error on If Statement
38,803,093
<pre><code>if mssge &lt;= answr: print("Too High, Try Again") elif mssge &gt;= answr: print("Too Low, Try Again") else: print("Nice Job! R to play again; Q to quit") if event.type == pygame.Q: sys.exit() else event.type == pygame.R: break gotoline(7) </code></pre> <p>I have been making games for a while but I just started on python. I'm making a number guessing game out of boredom but I keep getting an Indentation Error on line 17, or the last else of the if statement. </p>
-1
2016-08-06T10:10:49Z
38,803,112
<p>You cannot have conditions in the <code>else</code>-statement. <code>Else</code> is supposed to catch every case which is <strong>not</strong> caught by the preceding <code>if/elifs</code>.</p> <p>Your first code-block should be</p> <pre><code>if message_1 &lt;= rand_numb: print("Too High, Try Again") elif message_1 &gt;= rand_numb: print("Too Low, Try Again") else: # &lt;------ no conditions here! print("Nice Job! R to play again; Q to quit") if event.type == pygame.Q: sys.exit() else event.type == pygame.R: gotoline(5) break </code></pre>
0
2016-08-06T10:12:59Z
[ "python", "if-statement", "indentation" ]
indentation error on If Statement
38,803,093
<pre><code>if mssge &lt;= answr: print("Too High, Try Again") elif mssge &gt;= answr: print("Too Low, Try Again") else: print("Nice Job! R to play again; Q to quit") if event.type == pygame.Q: sys.exit() else event.type == pygame.R: break gotoline(7) </code></pre> <p>I have been making games for a while but I just started on python. I'm making a number guessing game out of boredom but I keep getting an Indentation Error on line 17, or the last else of the if statement. </p>
-1
2016-08-06T10:10:49Z
38,803,126
<p>An <code>else</code> clause doesn't take a condition. You could either write it as an <code>elif</code> clause, or as a straight-forward <code>else.</code> Note, BTW, that you should remove the <code>=</code> from the first two conditions to make the code correct:</p> <pre><code>if message_1 &lt; rand_numb: # &lt;= replaced with &lt; in this condition ^ print("Too High, Try Again") elif message_1 &gt; rand_numb: print("Too Low, Try Again") # &gt;= replaced with &gt; in this condition ^ else: # No condition on else ^ print("Nice Job! R to play again; Q to quit") </code></pre>
2
2016-08-06T10:15:01Z
[ "python", "if-statement", "indentation" ]
Python, have a process run in the background and get status from the main thread
38,803,153
<p>this is a noob question, I have never done much in Python. I need to have a main process run and do stuff, while a background process does other calculations and saves the result to a variable. When the main thread wants, it should be able to read the last value stored in the variable: every value stored before is forgotten. Say that the background process is counting: I want to know what number it is at at this very moment. Here's a dummy code:</p> <pre><code>from multiprocessing import Process, Pipe import os import time def f(queue): a=0 while True: a=a+1 child_conn.send(a) time.sleep(0.1) if __name__ == '__main__': parent_conn, child_conn = Pipe() p = Process(target=f, args=(child_conn,)) p.start() time.sleep(1) while True: print(parent_conn.recv()) time.sleep(1) </code></pre> <p>So the main thread prints the variable of the background thread every second, which is updated 10 times a second. I have tried with Pipe and Queue, but I do not get the last stored variable. This output is 1,2,3,4,... while I want to get 10,20,30,... (or similar, depending on timing). The problem here is that it, as the name suggests, works as a queue.</p> <p>What I would do in java is create something like an asynctask and have it update a public variable, but my understanding is that multi processes cannot share variables.</p> <p>What's the proper way of doing this with Python? </p>
1
2016-08-06T10:18:33Z
38,803,231
<p>Use <a href="https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">multiprocessing.Value</a>, which is implemented with shared memory between the processes:</p> <pre><code>from multiprocessing import Process, Value import time def f(n): while True: n.value += 1 time.sleep(0.1) if __name__ == '__main__': n = Value('i',0) p = Process(target=f, args=(n,)) p.start() while True: time.sleep(1) print(n.value) </code></pre> <p>Output:</p> <pre><code>7 17 26 35 44 53 </code></pre>
2
2016-08-06T10:26:38Z
[ "python", "multiprocessing" ]
Uploading multiple files with Flask App Builder
38,803,257
<p>Creating a simple front end with Flask where I can select multiple files and runs some calculations on them. </p> <p>Currently I am using the code below, but it is only good for 1 file, <code>#do something</code> is where the conversion happens;</p> <pre><code>class Sources(SimpleFormView): form = MyForm form_title = 'This is my first form view' message = 'My form submitted' def form_get(self, form): form.field1.data = 'This was prefilled' def form_post(self, form): x = #do something return self.render_template('test.html', table = x ,name='TEST') </code></pre> <p>The form basically lets me type in the path as shown below:</p> <pre><code>from wtforms import Form, StringField from wtforms.validators import DataRequired from flask.ext.appbuilder.fieldwidgets import BS3TextFieldWidget from flask.ext.appbuilder.forms import DynamicForm class MyForm(DynamicForm): Path = StringField(('Field1'), description=('Your field number one!'), validators = [DataRequired()], widget=BS3TextFieldWidget()) </code></pre> <p>I am trying to select multiple files from my local machine and then process them together. Much like how we attach files using Gmail;</p> <ol> <li>Option to select file path</li> <li>Open file browser</li> <li>Store file path</li> <li>Process 1 and 3 repeats till hit threshold or submitted.</li> </ol> <p>I am currently using Flask App Builder to get my front end right. </p>
0
2016-08-06T10:29:18Z
38,804,331
<p>You can use this HTML form which will allow the user to select multiple files:</p> <pre><code>&lt;form method="POST" enctype="multipart/form-data" action="/upload"&gt; &lt;input type="file" name="file[]" multiple=""&gt; &lt;input type="submit" value="Upload Files"&gt; &lt;/form&gt; </code></pre> <p>Then in your upload function you use getlist function from Flask.</p> <pre><code>@app.route("/upload", methods=["POST"]) def upload(): uploaded_files = flask.request.files.getlist("file[]") print uploaded_files return "" </code></pre> <p>I would recommend appending your do something function to accept a list of all of the files as an input. Then do something like </p> <pre><code>For file in uploaded_files: Process the files </code></pre>
0
2016-08-06T12:32:04Z
[ "python", "html", "flask", "flask-wtforms", "flask-appbuilder" ]
Sign extending from a variable bit width
38,803,320
<p>Here is a code in C++:</p> <pre><code>#include &lt;iostream&gt; #include&lt;limits.h&gt; using namespace std; void sign_extending(int x,unsigned b) { int r; // resulting sign-extended number int const m = CHAR_BIT * sizeof(x) - b; r = (x &lt;&lt; m) &gt;&gt; m; cout &lt;&lt; r; } void Run() { unsigned b = 5; // number of bits representing the number in x int x = 29; // sign extend this b-bit number to r sign_extending(x,b); } </code></pre> <blockquote> <p>Result : -3</p> </blockquote> <p>The resulting number will be a signed number with its number of bits stored in b. I am trying to replicate this code in python :</p> <pre><code>from ctypes import * import os def sign_extending(x, b): m = c_int(os.sysconf('SC_CHAR_BIT') * sizeof(c_int(x)) - b) r = c_int((x &lt;&lt; m.value) &gt;&gt; m.value) # Resulting sign-extended number return r.value b = c_int(5) # number of bits representing the number in x x = c_int(29) # sign extend this b-bit number to r r = sign_extending(x.value, b.value) print r </code></pre> <blockquote> <p>Result : 29</p> </blockquote> <p>I cannot get the sign extended number just like from the output in c++. I would like to know the error or problems in my current code(python) and also a possible solution to the issue using this technique. </p>
2
2016-08-06T10:35:53Z
38,803,993
<p>you can use</p> <pre><code>def sign_extending(x, b): if x&amp;(1&lt;&lt;(b-1)): # is the highest bit (sign) set? (x&gt;&gt;(b-1)) would be faster return x-(1&lt;&lt;b) # 2s complement return x </code></pre>
2
2016-08-06T11:52:04Z
[ "python", "c++", "ctypes", "sign-extension" ]
Decorator not working correctly
38,803,385
<p>I'm trying to get my decorator working but I keep getting returned with</p> <pre><code>TypeError: command() takes 1 positional argument but 2 were given </code></pre> <p>I'm not sure what is happening, is someone able to explain to me what I'm doing wrong?</p> <p><strong>Decorator Code</strong></p> <pre><code>def command(command): def method(self, *args, **kwargs): return command(self, *args, **kwargs) return method </code></pre> <p><strong>Function using Decorator</strong></p> <pre><code>@bot.command async def speak(msg : str): await bot.say(msg) </code></pre> <p><strong>Demonstration</strong></p> <p>I would like to have a bot that'll react to commands on a trigger.</p> <p>For example, I'll send a chat message:</p> <pre><code>?eval 1 * 2 </code></pre> <p>which the bot will reply with </p> <pre><code>2 </code></pre> <p>By using the <code>@bot.command</code>, I'll be able to create a flexible system which tells the application that the function is a command on-trigger.</p> <p>e.g</p> <pre><code>@bot.command async def eval(self, *args) await bot.send(eval(*args)) </code></pre>
0
2016-08-06T10:43:51Z
38,803,412
<p>You are decorating with <code>bot.command</code>.</p> <p>If <code>bot</code> is an object, then <code>bot.command</code> is a method and is called with a <code>self</code> parameter before the <code>command</code> argument, hence the “2 were given”.</p>
0
2016-08-06T10:47:37Z
[ "python", "python-3.x" ]
python multiprocessing.Process's join can not end
38,803,425
<p>I'm going to write a program which has multiple process(CPU-crowded) and multiple threading(IO-crowded).(the code below just a sample, not the program)</p> <p>But when the code meet the <code>join()</code> ,it make the program become a deadlock.</p> <p>My code is post below</p> <pre><code>import requests import time from multiprocessing import Process, Queue from multiprocessing.dummy import Pool start = time.time() queue = Queue() rQueue = Queue() url = 'http://www.bilibili.com/video/av' for i in xrange(10): queue.put(url+str(i)) def goURLsCrawl(queue, rQueue): threadPool = Pool(7) while not queue.empty(): threadPool.apply_async(urlsCrawl, args=(queue.get(), rQueue)) threadPool.close() threadPool.join() print 'end' def urlsCrawl(url, rQueue): response = requests.get(url) rQueue.put(response) p = Process(target=goURLsCrawl, args=(queue, rQueue)) p.start() p.join() # join() is here end = time.time() print 'totle time %0.4f' % (end-start,) </code></pre> <p>Thanks in advance.😊</p>
2
2016-08-06T10:49:24Z
38,928,677
<p>I finally find the reason. As you can see, I import the <code>Queue</code> from the <code>multiprocessing</code>, so the <code>Queue</code> should only used for <strong>Process</strong>, but I make the <strong>Thread</strong> access the <code>Queue</code> on my code, so it must something unknown occur behind the program.</p> <p>To correct it, just import <code>Queue</code> instead of <code>multiprocessing.Queue</code></p>
0
2016-08-13T02:41:09Z
[ "python", "multiprocessing" ]
Py2app: A main script could not be located in the Resources folder
38,803,437
<p>I am building a GUI tkinter python3 application and attempting to compile it with py2app. For some reason when I try to launch the .app bundle in the dist folder it gives me this error:<br> <i>A main script could not be located in the Resources folder</i><br> I was wondering why it is doing this, as it is rather frustrating, and I can not find anything about it anywhere. I copied my .py file into the resources folder (Networking.py). Previous to this error I also found an error in the Info.plist. In the key where it states the runtime executable, I found it was trying to get python2.7, which I have updated and am no longer using. I changed it to my current version, which the path for looks like this:<br> /Library/Frameworks/Python.framework/Versions/3.6/Python<br> It may be worth noting that it had a strange path previously, which did not look like a proper path to me. It was <br><br>@executable_path/../Frameworks/Python.framework/Versions/2.7/Python<br><br>I removed this completely... Was this wrong? I have no idea about anything about XML, which is what it seemed to be...</p> <p>Also when compiling this happened:<br><br> error: [Errno 1] Operation not permitted: '/Users/Ember/dist/Networking.app/Contents/MacOS/Networking'<br><br></p> <p>Any help would be highly appreciated! Thanks!</p> <p><strong>EDIT</strong></p> <p>I actually figured out: a bit of a stupid mistake, but since I'm using python 3.x I have to type in python3 before doing it.</p>
0
2016-08-06T10:51:22Z
39,367,323
<p>In your "setup.py" file that you used to create the application, did you remember to list all the modules used in your code. For example, if you used the OS and Glob modules, then you would add this to your setup.py next to "OPTIONS":</p> <pre><code>OPTIONS = {'argv_emulation': True, 'includes':['glob', 'os']} </code></pre> <p>Basically, anything that you import into your module, you should include in the setup.py. Let me know if that works.</p>
0
2016-09-07T10:24:16Z
[ "python", "user-interface", "tkinter", "py2app" ]
Py2app: A main script could not be located in the Resources folder
38,803,437
<p>I am building a GUI tkinter python3 application and attempting to compile it with py2app. For some reason when I try to launch the .app bundle in the dist folder it gives me this error:<br> <i>A main script could not be located in the Resources folder</i><br> I was wondering why it is doing this, as it is rather frustrating, and I can not find anything about it anywhere. I copied my .py file into the resources folder (Networking.py). Previous to this error I also found an error in the Info.plist. In the key where it states the runtime executable, I found it was trying to get python2.7, which I have updated and am no longer using. I changed it to my current version, which the path for looks like this:<br> /Library/Frameworks/Python.framework/Versions/3.6/Python<br> It may be worth noting that it had a strange path previously, which did not look like a proper path to me. It was <br><br>@executable_path/../Frameworks/Python.framework/Versions/2.7/Python<br><br>I removed this completely... Was this wrong? I have no idea about anything about XML, which is what it seemed to be...</p> <p>Also when compiling this happened:<br><br> error: [Errno 1] Operation not permitted: '/Users/Ember/dist/Networking.app/Contents/MacOS/Networking'<br><br></p> <p>Any help would be highly appreciated! Thanks!</p> <p><strong>EDIT</strong></p> <p>I actually figured out: a bit of a stupid mistake, but since I'm using python 3.x I have to type in python3 before doing it.</p>
0
2016-08-06T10:51:22Z
39,405,027
<p>I actually figured out: a bit of a stupid mistake, but since I'm using python 3.x I have to type in <code>python3</code> before doing it.</p>
0
2016-09-09T06:21:21Z
[ "python", "user-interface", "tkinter", "py2app" ]
how to interrogate ontology with sparql, rdflib in python
38,803,464
<p>I have developed my own ontology (I defined my classes, properties, etc.) and I want to interrogate my ontology with sparql. </p> <p>in protégé 2000 (open-source ontology editor) everything works fine, but when I want to implement my request sparql in python I encountered some problems.</p> <p>I did it in Java and it worked but it's not what I want, I wanted to it do with <code>pyjnius</code> (A Python module to access Java classes as Python classes) but nothing worked also.</p> <p>How I can use sparql to interrogate my ontology? Is there any way to use jena in Python?</p> <p>that's how i did it with java :</p> <pre><code>try{ Model model = ModelFactory.createDefaultModel(); String FName = "C:\\Users\\p\\Desktop\\protégé project jour\\jour.owl"; InputStream inStr = FileManager.get().open(FName); if (inStr == null) { throw new IllegalArgumentException("Fichier non trouvé");} // Lire le fichier RDF vers le modèle précédemment créé. model.read(inStr, ""); //**************************** String requete = //***=====This is the query that works good in the ontology with properties between classes "PREFIX OntoJO:&lt;http://www.owl-ontologies.com/Ontology1400008538.owl#&gt;" + "SELECT ?path " + "WHERE { " + " ?n OntoJO:signee_par '"+choixsignrech1.getText()+"' ." + " ?s OntoJO:mot_cle '"+choixclrech1.getText()+"' ." + " ?m OntoJO:secteur '"+choixsecrech1.getSelectedItem()+"' ." + " ?f OntoJO:ministere '"+choixminisrech1.getSelectedItem()+"' ." + " ?r OntoJO:synonymes '"+choixsyrech1.getText()+"' ." + "?n OntoJO:a_un_chemin ?y . " + "?s OntoJO:a_un_chemin ?y . " + "?m OntoJO:a_un_chemin ?y . " + "?f OntoJO:a_un_chemin ?y . " + "?r OntoJO:a_un_chemin ?y . " + "?y OntoJO:chemin ?path . }"; Query query = QueryFactory.create(requete); QueryExecution qexec = QueryExecutionFactory.create(query, model); try { ResultSet results = qexec.execSelect(); while (results.hasNext()){ QuerySolution soln = results.nextSolution(); RDFNode name = soln.get("path"); System.out.println(name); javax.swing.JOptionPane.showMessageDialog(this,soln.get("path")); } } finally { qexec.close(); } </code></pre> <p>the properties are: signee_par, mot_cle, secteur, ministere etc ..... ( in french ), the sqarql request is based on these properties </p> <p>i wanna do it with python, anyone know how i can ?!</p>
0
2016-08-06T10:54:56Z
38,817,186
<p>Look at this if you want to use Jena Fuseki. <a href="http://stackoverflow.com/questions/7634618/jena-tdb-in-python">Jena TDB in Python?</a></p> <p>I can suggest a way to use rdflib. My work with rdflib has been limited to simple queries and serialization. The simplest way would be to load your graph ( in any of the RDF formats nt,ttl etc.) Query the graph and format the results as required.</p> <pre><code>import rdflib graph = rdflib.Graph() graph = graph.parse("triples.nt",format = "nt") query = "PREFIX OntoJO:&lt;http://www.owl-ontologies.com /Ontology1400008538.owl#&gt;" +\ "SELECT ?path " +\ "WHERE { "\ \ + " ?n OntoJO:signee_par '"+choixsignrech1.getText()+"' ." \ + " ?s OntoJO:mot_cle '"+choixclrech1.getText()+"' ." \ + " ?m OntoJO:secteur '"+choixsecrech1.getSelectedItem()+"' ."\ + " ?f OntoJO:ministere '"+choixminisrech1.getSelectedItem()+"' ."\ + " ?r OntoJO:synonymes '"+choixsyrech1.getText()+"' ."\ + "?n OntoJO:a_un_chemin ?y . "\ + "?s OntoJO:a_un_chemin ?y . "\ + "?m OntoJO:a_un_chemin ?y . "\ + "?f OntoJO:a_un_chemin ?y . "\ + "?r OntoJO:a_un_chemin ?y . "\ + "?y OntoJO:chemin ?path . }" result = graph.query(query) #The result will be a QueryRow object because of the SELECT , look in the docs for further info. for i in result: print i[0] </code></pre> <p>I have neglected replacing your getText Calls, take care. The above code is in for python2 and should print all the results of the query on the triple.nt data</p> <p>Please comment and let me know your views on this answers. There aren't many sources about rdflib, so ping me if you have any questions related to the same and I would happy to explore it.</p>
0
2016-08-07T18:22:59Z
[ "python", "sparql", "jena", "rdflib", "pyjnius" ]
Expire index in mongoDB based on condition
38,803,658
<p>I have <code>boolean</code> field named <code>pending</code> in <code>Mongoengine</code> model in Python. I want the document to be removed after 1 hour only if <code>pending=True</code>. If I needed to remove the document after 1 hour unconditionally I would just set expire index. Is there some smart and easy way to add some conditional check to expire index?</p> <p>Thank you in advance!</p>
1
2016-08-06T11:15:19Z
38,803,774
<p>I am afraid it is not directly possible to add some custom logic to the periodic cleaning of expired documents but as described in the <a href="https://docs.mongodb.com/manual/core/index-ttl/#expiration-of-data" rel="nofollow">docs</a> you could use a expire index and only set the indexed field from your application if <code>pending = True</code> - as documents without the field of the expire index are not removed this should work although not exactly what you requested.</p>
1
2016-08-06T11:29:27Z
[ "python", "mongodb", "mongoengine", "ttl" ]
Cannot import hachoir_core in python
38,803,753
<p>I can't import <code>hachoir_core</code> (or <code>hachoir_parser</code>, or <code>hachoir_metadata</code>) in python anymore (I used to be able to just a day ago):</p> <pre><code>ImportError: No module named hachoir_core </code></pre> <p>I've tried uninstalling all three (core, parser and metadata) with <code>pip</code></p> <pre><code>sudo pip uninstall hachoir-core </code></pre> <p>then re-installing</p> <pre><code>sudo pip install hachoir-core </code></pre> <p>and restarting the computer.</p> <p>Nothing works. The only think I can think of that may have caused this is instilling anaconda (which I've since uninstalled by removing the anaconda directory, ~/anaconda), though I cannot confirm that is the reason.</p> <p>I'm running python 2.7 on Mac OS X El Capitan</p>
1
2016-08-06T11:27:05Z
38,803,850
<p>Press Command+Space and type Terminal and press enter/return key. Run in Terminal app:</p> <pre><code>ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" &lt; /dev/null 2&gt; /dev/null </code></pre> <p>and press enter/return key. Wait for the command to finish. Run:</p> <pre><code>brew install hachoir-metadata </code></pre> <p>Done! You can now use hachoir-metadata</p> <p>Download hachoir-core 1.0.1 from <a href="http://hachoir3.readthedocs.io/install.html" rel="nofollow">http://hachoir3.readthedocs.io/install.html</a></p> <p>Uncompress each tarball, eg. <code>tar -xvzf hachoir-core-1.3.3.tar.gz</code> Go to Hachoir directory, eg. cd hachoir-core-1.3.3</p> <p>(with administrator privileges) Run setup.py: <code>python setup.py install</code></p> <p>This will probably help you.</p>
1
2016-08-06T11:36:55Z
[ "python", "pip", "anaconda" ]
Google Challenge Dilemma, Insights into possible errors?
38,803,824
<p>I am currently passing 4 of the 5 hidden test cases for this challenge and would like some input</p> <p>Quick problem description:</p> <blockquote> <p>You are given two input strings, String chunk and String word</p> <p>The string "word" has been inserted into "chunk" some number of times</p> <p>The task is to find the shortest string possible when all instances of "word" have been removed from "chunk".</p> <p>Keep in mind during removal, more instances of the "word" might be created in "chunk". "word" can also be inserted anywhere, including between "word" instances</p> <p>If there are more the one shortest possible strings after removal, return the shortest word that is lexicographic-ally the earliest. </p> <p>This is easier understood with examples: </p> <p>Inputs:<br> (string) chunk = "lololololo"<br> (string) word = "lol"</p> <p>Output:<br> (string) "looo" (since "looo" is eariler than "oolo")</p> <p>Inputs:<br> (string) chunk = "goodgooogoogfogoood"<br> (string) word = "goo"</p> <p>Output:<br> (string) "dogfood"</p> </blockquote> <p>right now I am iterating forwards then backwards, removing all instances of word and then comparing the two results of the two iterations. </p> <p>Is there a case I am overlooking? Is it possible there is a case where you have to remove from the middle first or something along those lines? </p> <p>Any insight is appreciated. </p>
0
2016-08-06T11:34:49Z
38,963,429
<p>I am not sure. But i will avoid matching first and last character of chunk. Should replace all other.</p>
0
2016-08-15T21:35:22Z
[ "java", "python", "string", "challenge-response" ]
How to optimize searching multiple strings ("needles") in one string ("haystack"), in python
38,803,945
<p>I need to know if either/all needle are found in a haystack. I assume there's a way to optimize the time for searching. For example:</p> <pre><code>haystack = "xxxxxefgyyy" needles = [ 'ezz', 'efg', 'eee', 'b', ... ] </code></pre> <p>In this example an optimized method would probably sort the needles by first letter(s). After matching "ezz" in the haystack, there's no point in searching haystack all over again. Ideally for the next needle ("egh"), the haystack would be searched from the last position of 'e', and not from the beginning ('xxx..').</p> <p>What is the name for such an algorithm?</p> <p>What are the python implementations for that?</p> <p>notes:</p> <ul> <li>my current program searches thousands of known needles in an unknown text.</li> <li>In this case i just need to check for existence (true/false)</li> <li>in this case i search if any needle exists ("OR" search). Assume that most needles need to be searched anyway (@marko).</li> </ul>
0
2016-08-06T11:45:45Z
38,804,175
<p>Maybe there is a more efficient implementation for that but you can simply use <a href="https://docs.python.org/3/library/re.html" rel="nofollow">re</a>. For a really big <code>needles</code> this might not be ideal - don't know where "really big" starts.</p> <pre><code>import re haystack = "xxxxxefgyyy" needles = [ 'ezz', 'efg', 'eee', 'b'] needles_re=re.compile("|".join(map(re.escape,needles))) for m in needles_re.finditer(haystack): print(m.group(0)) </code></pre>
-1
2016-08-06T12:12:13Z
[ "python", "search", "optimization" ]
Why does this for loop only work if it iterates at the zeroth index?
38,803,987
<p>I have a list:</p> <pre><code>oldlist = ['do gs\n','ca ts\n','monk eys\n','fro gs\n','\n','lio ns\n','tige rs\n','she ep\n'] </code></pre> <p>I'm trying to extract only the <strong>first</strong> portion of the list <strong>['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n']</strong> before the newline <strong>'\n'</strong>.</p> <p>This is my code and it outputs the correct solution:</p> <pre><code>oldlist = ['do gs\n','ca ts\n','monk eys\n','fro gs\n','\n','lio ns\n','tige rs\n','she ep\n'] print("Before Loop: ", oldlist) newlist = [] for iter in oldlist: if '\n' in iter[0]: break else: newlist.append(iter) print("After Loop: ", newlist) </code></pre> <p>However the line which begins from </p> <pre><code>if '\n' in iter[0]: </code></pre> <p>is the one which I do not understand how it works. Why does this loop only work when <strong>iter[0]</strong>? Why is it that if I just iterate over iter it outputs only a blank list?</p> <p><strong>OUTPUT if "iter[0]" used:</strong></p> <pre><code>Before Loop: ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n', '\n', 'lio ns\n', 'tige rs\n', 'she ep\n'] After Loop: ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n'] </code></pre> <p><strong>OUTPUT if "iter" used :</strong></p> <pre><code>Before Loop: ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n', '\n', 'lio ns\n', 'tige rs\n', 'she ep\n'] After Loop: [] </code></pre> <p>Also if I do this:</p> <pre><code>for iter in oldlist: print(iter[0]) </code></pre> <p>It spits out only <strong>d</strong> from the first string <strong>do gs\n</strong></p> <p>So in summary, what is going on behind the scenes that is allowing iter[0] to iterate through the oldlist to give the correct solution in newlist?</p>
0
2016-08-06T11:51:40Z
38,804,059
<p>The <code>in</code> operator when used on strings checks if a given character exists at all in the string. So <code>\n in "do gs\n"</code> evaluates to true, because there is a newline character in this string. However, if you check for <code>\n in "do gs\n"[0]</code> it only checks if the first character is the newline.</p> <p>It would be more clear if you simply did <code>if iter == '\n'</code> since that's basically what you're doing.</p>
2
2016-08-06T11:59:30Z
[ "python", "loops", "python-3.x", "for-loop", "iteration" ]
Why does this for loop only work if it iterates at the zeroth index?
38,803,987
<p>I have a list:</p> <pre><code>oldlist = ['do gs\n','ca ts\n','monk eys\n','fro gs\n','\n','lio ns\n','tige rs\n','she ep\n'] </code></pre> <p>I'm trying to extract only the <strong>first</strong> portion of the list <strong>['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n']</strong> before the newline <strong>'\n'</strong>.</p> <p>This is my code and it outputs the correct solution:</p> <pre><code>oldlist = ['do gs\n','ca ts\n','monk eys\n','fro gs\n','\n','lio ns\n','tige rs\n','she ep\n'] print("Before Loop: ", oldlist) newlist = [] for iter in oldlist: if '\n' in iter[0]: break else: newlist.append(iter) print("After Loop: ", newlist) </code></pre> <p>However the line which begins from </p> <pre><code>if '\n' in iter[0]: </code></pre> <p>is the one which I do not understand how it works. Why does this loop only work when <strong>iter[0]</strong>? Why is it that if I just iterate over iter it outputs only a blank list?</p> <p><strong>OUTPUT if "iter[0]" used:</strong></p> <pre><code>Before Loop: ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n', '\n', 'lio ns\n', 'tige rs\n', 'she ep\n'] After Loop: ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n'] </code></pre> <p><strong>OUTPUT if "iter" used :</strong></p> <pre><code>Before Loop: ['do gs\n', 'ca ts\n', 'monk eys\n', 'fro gs\n', '\n', 'lio ns\n', 'tige rs\n', 'she ep\n'] After Loop: [] </code></pre> <p>Also if I do this:</p> <pre><code>for iter in oldlist: print(iter[0]) </code></pre> <p>It spits out only <strong>d</strong> from the first string <strong>do gs\n</strong></p> <p>So in summary, what is going on behind the scenes that is allowing iter[0] to iterate through the oldlist to give the correct solution in newlist?</p>
0
2016-08-06T11:51:40Z
38,804,075
<p>Your <code>iter[0]</code> means the first character in each string while <code>iter</code> means each full string. eg <code>'do gs\n'[0]</code> means <code>'d'</code> and of course in <code>'do gs\n'</code> there is a <code>'\n'</code>.</p> <p>You can also use the shorter <code>newlist=oldlist[:oldlist.index("\n")]</code> instead of your loop.</p>
0
2016-08-06T12:01:18Z
[ "python", "loops", "python-3.x", "for-loop", "iteration" ]
Kivy SQLalchemy and Android, No module named MySQLdb
38,803,988
<p>I'm building an app for android and i need to interact with Mysql database. I have some problem at configuring access from android but not with my linux installation. </p> <p>I have succesfully imported the recipe of SQLAlchemy on my android apk but when i run the app trough logcat i see the error:</p> <pre><code>NO module named MySQLdb </code></pre> <p>so i tried adding in buildozer also the recipe of MySQLdb and it says:</p> <pre><code>No matching distribution found for MySQLdb </code></pre> <p>This is the part of the code invoking mysql part:</p> <pre><code>import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import MetaData, Column, Table, ForeignKey from sqlalchemy import Integer, String from sqlalchemy.sql import select def check_sql_list(_id, string): cur = engine.connect() res = cur.execute("SELECT * FROM tbl_user") for x in res.fetchall(): if x[_id] == string: return True cur.close() def create_user(name,e_mail,psw): if check_sql_list(1,name): print 'Select another username.' elif check_sql_list(2,e_mail): print 'Your E-Mail have already an account.' else: connection = engine.raw_connection() try: cursor = connection.cursor() cursor.callproc("sp_createUser",[name, e_mail, psw]) results = list(cursor.fetchall()) for a in cursor.fetchall(): print a print results cursor.close connection.commit() finally: connection.close() print 'Account registered succesfully.' ip = 'localhost' databs = 'mydb' user = 'guest' psw = 'password' porta = '3306' engine = create_engine('mysql://' + user + ':' + psw + '@' + ip + ':' + porta + '/' + databs) create_user('user001','mail@001.com','password') </code></pre> <p>How can i connect to my database without the needing of MySQLdb recipe? Or where i can find that recipe?</p>
0
2016-08-06T11:51:43Z
38,813,571
<p>I answer to my own question hoping someone will find it usefull.</p> <p>I find out how to solve it, use as a dialer mysql+mysqlconnector like:</p> <pre><code>engine = create_engine('mysql+mysqlconnector://user00:psw@localhost:3306/database') </code></pre> <p>and adds the recipe requirements in the buildozer.spec:</p> <pre><code>requirements = kivy,sqlalchemy,mysql_connector </code></pre>
0
2016-08-07T11:17:49Z
[ "android", "python", "mysql", "buildozer" ]
Kivy SQLalchemy and Android, No module named MySQLdb
38,803,988
<p>I'm building an app for android and i need to interact with Mysql database. I have some problem at configuring access from android but not with my linux installation. </p> <p>I have succesfully imported the recipe of SQLAlchemy on my android apk but when i run the app trough logcat i see the error:</p> <pre><code>NO module named MySQLdb </code></pre> <p>so i tried adding in buildozer also the recipe of MySQLdb and it says:</p> <pre><code>No matching distribution found for MySQLdb </code></pre> <p>This is the part of the code invoking mysql part:</p> <pre><code>import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import MetaData, Column, Table, ForeignKey from sqlalchemy import Integer, String from sqlalchemy.sql import select def check_sql_list(_id, string): cur = engine.connect() res = cur.execute("SELECT * FROM tbl_user") for x in res.fetchall(): if x[_id] == string: return True cur.close() def create_user(name,e_mail,psw): if check_sql_list(1,name): print 'Select another username.' elif check_sql_list(2,e_mail): print 'Your E-Mail have already an account.' else: connection = engine.raw_connection() try: cursor = connection.cursor() cursor.callproc("sp_createUser",[name, e_mail, psw]) results = list(cursor.fetchall()) for a in cursor.fetchall(): print a print results cursor.close connection.commit() finally: connection.close() print 'Account registered succesfully.' ip = 'localhost' databs = 'mydb' user = 'guest' psw = 'password' porta = '3306' engine = create_engine('mysql://' + user + ':' + psw + '@' + ip + ':' + porta + '/' + databs) create_user('user001','mail@001.com','password') </code></pre> <p>How can i connect to my database without the needing of MySQLdb recipe? Or where i can find that recipe?</p>
0
2016-08-06T11:51:43Z
39,254,396
<blockquote> <p>kivy -m pip install mysql-connector </p> </blockquote> <p>than: </p> <blockquote> <p>import mysql.connector</p> </blockquote> <p>working for me :)</p>
0
2016-08-31T16:11:37Z
[ "android", "python", "mysql", "buildozer" ]
How to have several handlers using Logbook?
38,804,018
<p>I'm using <a href="https://logbook.readthedocs.io/" rel="nofollow">logbook</a> to log message in a Python app but</p> <pre><code>import logbook from logbook import Logger, StreamHandler, NullHandler log = Logger('LogbookExample') import sys StreamHandler(sys.stdout).push_application() NullHandler().push_application() def main(): log.info('Hello, World!') if __name__ == "__main__": main() </code></pre> <p>doesn't work as I was expecting... nothing appears. Like if <code>NullHandler</code> was replacing <code>StreamHandler</code></p> <p>So I wonder how to have several handlers connected to app ?</p>
3
2016-08-06T11:55:12Z
38,818,189
<p>The problem here is choosing <code>NullHandler</code>. It acts as a "black hole", swallowing all logs and not propagating them up the stack.</p> <p>Stacking non-<code>NullHandler</code>s is easy:</p> <pre><code>StreamHandler(sys.stdout).push_application() StreamHandler(sys.stderr, bubble=True).push_application() </code></pre> <p>The <code>bubble</code> keyword means the handler should continue propagation up the stack after handling the record.</p>
1
2016-08-07T20:21:56Z
[ "python", "logging", "logbook" ]
Issue in django proejct with two version of python installed on centos server
38,804,103
<p>Working on django1.9 project, the issue is that default python installed on my server is 2.6 and i have to use python 2.7 for django 1.9. I have installed python2.6 on server. And while creating django projected i hve created it using virtual environment with python2.7 but whenever i am trying to access project it gives me 500 internal server error. When i checked my apache http error log file if found that it is still using python2.6 for my project.</p> <pre><code>Error :- [Sat Aug 06 07:48:13 2016] [error] [client 112.196.41.202] fasttypes = {int, str, frozenset, type(None)}, [Sat Aug 06 07:48:13 2016] [error] [client 112.196.41.202] ^ [Sat Aug 06 07:48:13 2016] [error] [client 112.196.41.202] SyntaxError: invalid syntax </code></pre> <p>mod_wsgi configuration is :-</p> <pre><code>WSGIScriptAlias /onpointtickets /home/onpoin21/public_html/onpointtickets/onpointtickets/wsgi.py WSGIPythonPath /home/onpoin21/public_html/onpointtickets &lt;Directory /home/onpoin21/public_html/onpointtickets/onpointtickets&gt; &lt;Files wsgi.py&gt; Order deny,allow Allow from all &lt;/Files&gt; &lt;/Directory&gt; </code></pre>
0
2016-08-06T12:04:01Z
38,813,220
<p>Your mod_wsgi is compiled for Python 2.6. You cannot make it use a virtual environment for Python 2.7 and wouldn't be able to use it with application code which requires Python 2.7. You need to reinstall mod_wsgi with it recompiled for Python 2.7.</p>
0
2016-08-07T10:30:57Z
[ "python", "django" ]
mapping over 2 numpy.ndarray simultaneously
38,804,186
<p>Here's the problem. Let's say I have a matrix A =</p> <pre><code>array([[ 1., 0., 2.], [ 0., 0., 2.], [ 0., -1., 3.]]) </code></pre> <p>and a vector of indices p = <code>array([0, 2, 1])</code>. I want to turn a 3x3 matrix A to an array of length 3 (call it v) where v[j] = A[j, p[j]] for j = 0, 1, 2. I can do it the following way:</p> <pre><code>v = map(lambda (row, idx): row[idx], zip(A, p)) </code></pre> <p>So for the above matrix A and a vector of indices p I expect to get <code>array([1, 2, -1])</code> (ie 0th element of row 0, 2nd element of row 1, 1st element of row 2).</p> <p>But can I achieve the same result by using native numpy (ie without explicitly zipping and then mapping)? Thanks.</p>
0
2016-08-06T12:13:23Z
38,804,529
<p>I don't think that such a functionality exists. To achieve what you want, I can think of two easy ways. You could do:</p> <pre><code>np.diag(A[:, p]) </code></pre> <p>Here the array <code>p</code> is applied as a column index for every row such that on the diagonal you will have the elements that you are looking for.</p> <p>As an alternative you can avoid to produce a lot of unnecessary entries by using:</p> <pre><code>A[np.arange(A.shape[0]), p] </code></pre>
4
2016-08-06T12:58:03Z
[ "python", "arrays", "numpy", "matrix" ]
Getting multiple values in dictionary
38,804,366
<p>I want to get the values of a key in a dictionary. After working with googlemaps and I got my result, I want to just get the values I need and move on. But it seems not to be working for me.</p> <p>The result:</p> <pre><code>&gt;&gt;&gt;the_distance= gmaps.distance_matrix(origins, destinations) &gt;&gt;&gt; print the_distance {u'status': u'OK', u'rows': [{u'elements': [{u'duration': {u'text': u'27 mins', u'value': 1599}, u'distance': {u'text': u'11.9 km', u'value': 11874}, u'status': u'OK'}]}], u'origin_addresses': [u'Lamu, Kayyy'], u'destination_addresses': [u'20 Dave Ave, Mars, Amsterdam']} </code></pre> <p>Looking at the result, the key 'rows' has different values. I only need the duration: <code>27 mins</code> and distance: <code>11.9km</code>.</p> <p>I tried </p> <pre><code>&gt;&gt;&gt;the_distance.values()[1:3] </code></pre> <p>I got the same result as above.</p> <p>I also tried</p> <pre><code>&gt;&gt;the_distance['rows'][:2] </code></pre> <p>I got</p> <pre><code>{u'status': u'OK', u'rows': [{u'elements': [{u'duration': {u'text': u'27 mins', u'value': 1599}, u'distance': {u'text': u'11.9 km', u'value': 11874}, u'status': u'OK'}]}] </code></pre> <p>what do I need to do?</p>
0
2016-08-06T12:35:30Z
38,804,407
<p>simple access to the dictionary could be done as follows.</p> <pre><code>cool_variable = the_distance['rows'][0]['elements'][0] cool_variable['duration']['text'] cool_variable['distance']['text'] </code></pre>
3
2016-08-06T12:40:05Z
[ "python" ]
'from __future__ import unicode_literals' in Django Migrations
38,804,449
<p>I just want to know that why does every auto-generated Django migration file contains the following line. </p> <pre><code>from __future__ import unicode_literals </code></pre> <p>The applications is running fine even if I remove all these lines. So, what's it purpose?</p>
0
2016-08-06T12:46:48Z
38,804,896
<p><code>from __future__ import unicode_literals</code> makes <code>"abc"</code> <code>unicode</code> instead of <code>str</code> in Python 2.x, so <code>"abc"</code> then means the same as <code>u"abc"</code> while otherwise <code>"abc"</code> would mean the same as <code>b"abc"</code>.</p> <p>For more info see the <a href="https://docs.python.org/2/library/__future__.html" rel="nofollow"><code>__future__</code></a> docs or <a href="https://www.python.org/dev/peps/pep-3112/" rel="nofollow">PEP 3112</a> directly.</p>
1
2016-08-06T13:41:30Z
[ "python", "django", "import", "migration" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as follows:</p> <pre><code>users = { 'Participants': [ {'first_name': 'Jerry', 'last_name' : 'Johnson'}, {'first_name' : 'Blaine', 'last_name' : 'Diamond'}, {'first_name' : 'Ginny', 'last_name' : 'Gelspy'}, {'first_name' : 'LG', 'last_name' : 'Murphy'} ], 'Leaders': [ {'first_name' : 'TJ', 'last_name' : 'Knight'}, {'first_name' : 'Jasper', 'last_name' : 'Red'} ] } users_list = users.items() # converts users dict to a list for key, data in users_list: print key for value in data: print "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>My current output is as follows:</p> <pre><code>Participants - JERRY JOHNSON - 12 - BLAINE DIAMOND - 13 - GINNY GELSPY - 11 - LG MURPHY - 8 Leaders - TJ KNIGHT - 8 - JASPER RED - 9 </code></pre> <p>However, I'd like to add a count to each participant or leader, so the output would instead read:</p> <pre><code>Participants 1 - JERRY JOHNSON - 12 2 - BLAINE DIAMOND - 13 3 - GINNY GELSPY - 11 4 - LG MURPHY - 8 Leaders 1 - TJ KNIGHT - 8 2 - JASPER RED - 9 </code></pre> <p>in this format:</p> <pre><code>&lt;dictionary name&gt; &lt;count&gt; - &lt;FULL NAME IN CAPS&gt; - &lt;char count in full name no space included&gt; </code></pre> <p>I did read that dictionaries in python are unordered and cannot be referenced in regards to index, but is there a simple way to setup a counter or to count each output in a way that I'm not seeing?</p> <p>Thank you so much for any insight provided!</p>
1
2016-08-06T12:49:29Z
38,804,518
<p>Start the counter to 0 right after the first for loop, and increase by 1 each time after the second for loop:</p> <pre><code>for key, data in users_list: counter = 0 print key for value in data: counter += 1 print str(counter), "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre>
0
2016-08-06T12:56:26Z
[ "python", "dictionary" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as follows:</p> <pre><code>users = { 'Participants': [ {'first_name': 'Jerry', 'last_name' : 'Johnson'}, {'first_name' : 'Blaine', 'last_name' : 'Diamond'}, {'first_name' : 'Ginny', 'last_name' : 'Gelspy'}, {'first_name' : 'LG', 'last_name' : 'Murphy'} ], 'Leaders': [ {'first_name' : 'TJ', 'last_name' : 'Knight'}, {'first_name' : 'Jasper', 'last_name' : 'Red'} ] } users_list = users.items() # converts users dict to a list for key, data in users_list: print key for value in data: print "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>My current output is as follows:</p> <pre><code>Participants - JERRY JOHNSON - 12 - BLAINE DIAMOND - 13 - GINNY GELSPY - 11 - LG MURPHY - 8 Leaders - TJ KNIGHT - 8 - JASPER RED - 9 </code></pre> <p>However, I'd like to add a count to each participant or leader, so the output would instead read:</p> <pre><code>Participants 1 - JERRY JOHNSON - 12 2 - BLAINE DIAMOND - 13 3 - GINNY GELSPY - 11 4 - LG MURPHY - 8 Leaders 1 - TJ KNIGHT - 8 2 - JASPER RED - 9 </code></pre> <p>in this format:</p> <pre><code>&lt;dictionary name&gt; &lt;count&gt; - &lt;FULL NAME IN CAPS&gt; - &lt;char count in full name no space included&gt; </code></pre> <p>I did read that dictionaries in python are unordered and cannot be referenced in regards to index, but is there a simple way to setup a counter or to count each output in a way that I'm not seeing?</p> <p>Thank you so much for any insight provided!</p>
1
2016-08-06T12:49:29Z
38,804,523
<pre><code>for key, data in users_list: print key for count, value in enumerate(data): print (count + 1), "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>That should do it. Read more about <code>enumerate</code> <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow">here</a></p> <p>EDIT: As pointed out in the comments, you can also do <code>enumerate(data, start=1)</code> instead. You wouldn't need <code>count + 1</code> in that case:</p> <pre><code>for key, data in users_list: print key for count, value in enumerate(data, start=1): print count, "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre>
3
2016-08-06T12:57:19Z
[ "python", "dictionary" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as follows:</p> <pre><code>users = { 'Participants': [ {'first_name': 'Jerry', 'last_name' : 'Johnson'}, {'first_name' : 'Blaine', 'last_name' : 'Diamond'}, {'first_name' : 'Ginny', 'last_name' : 'Gelspy'}, {'first_name' : 'LG', 'last_name' : 'Murphy'} ], 'Leaders': [ {'first_name' : 'TJ', 'last_name' : 'Knight'}, {'first_name' : 'Jasper', 'last_name' : 'Red'} ] } users_list = users.items() # converts users dict to a list for key, data in users_list: print key for value in data: print "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>My current output is as follows:</p> <pre><code>Participants - JERRY JOHNSON - 12 - BLAINE DIAMOND - 13 - GINNY GELSPY - 11 - LG MURPHY - 8 Leaders - TJ KNIGHT - 8 - JASPER RED - 9 </code></pre> <p>However, I'd like to add a count to each participant or leader, so the output would instead read:</p> <pre><code>Participants 1 - JERRY JOHNSON - 12 2 - BLAINE DIAMOND - 13 3 - GINNY GELSPY - 11 4 - LG MURPHY - 8 Leaders 1 - TJ KNIGHT - 8 2 - JASPER RED - 9 </code></pre> <p>in this format:</p> <pre><code>&lt;dictionary name&gt; &lt;count&gt; - &lt;FULL NAME IN CAPS&gt; - &lt;char count in full name no space included&gt; </code></pre> <p>I did read that dictionaries in python are unordered and cannot be referenced in regards to index, but is there a simple way to setup a counter or to count each output in a way that I'm not seeing?</p> <p>Thank you so much for any insight provided!</p>
1
2016-08-06T12:49:29Z
38,804,545
<p>You may want to use the <em>enumerate</em> function on the list like that:</p> <pre><code>users_list = users.items() # converts users dict to a list for key, data in users_list: print key for i, value in enumerate(data, 1): print str(i), "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>The <em>enumerate</em> function returns the index in addition to the element itself.</p> <p>EDIT:</p> <p>As mentioned in Priyatham Kattakinda's answer, the second parameter of the function indicates the first element's index (the default is zero).</p>
0
2016-08-06T13:00:06Z
[ "python", "dictionary" ]
How can I count each dictionary value output in Python in the following code example?
38,804,469
<p>I'm learning to play with lists, tuples and dictionaries in Python (2.7), and to convert dictionaries to lists and to reference them, but am experiencing some difficulties in understanding how I might add a count number to specific values that I am retrieving from dictionaries.</p> <p>I start with this code as follows:</p> <pre><code>users = { 'Participants': [ {'first_name': 'Jerry', 'last_name' : 'Johnson'}, {'first_name' : 'Blaine', 'last_name' : 'Diamond'}, {'first_name' : 'Ginny', 'last_name' : 'Gelspy'}, {'first_name' : 'LG', 'last_name' : 'Murphy'} ], 'Leaders': [ {'first_name' : 'TJ', 'last_name' : 'Knight'}, {'first_name' : 'Jasper', 'last_name' : 'Red'} ] } users_list = users.items() # converts users dict to a list for key, data in users_list: print key for value in data: print "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"] + value["last_name"]) </code></pre> <p>My current output is as follows:</p> <pre><code>Participants - JERRY JOHNSON - 12 - BLAINE DIAMOND - 13 - GINNY GELSPY - 11 - LG MURPHY - 8 Leaders - TJ KNIGHT - 8 - JASPER RED - 9 </code></pre> <p>However, I'd like to add a count to each participant or leader, so the output would instead read:</p> <pre><code>Participants 1 - JERRY JOHNSON - 12 2 - BLAINE DIAMOND - 13 3 - GINNY GELSPY - 11 4 - LG MURPHY - 8 Leaders 1 - TJ KNIGHT - 8 2 - JASPER RED - 9 </code></pre> <p>in this format:</p> <pre><code>&lt;dictionary name&gt; &lt;count&gt; - &lt;FULL NAME IN CAPS&gt; - &lt;char count in full name no space included&gt; </code></pre> <p>I did read that dictionaries in python are unordered and cannot be referenced in regards to index, but is there a simple way to setup a counter or to count each output in a way that I'm not seeing?</p> <p>Thank you so much for any insight provided!</p>
1
2016-08-06T12:49:29Z
38,805,546
<p>as mention by other, <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> is the best way to go, so I will just add some extra tip to make the program more efficient:</p> <ol> <li><p>unless you really need the <code>user_list</code> later on, iterate over <code>users.items()</code> directly or better yet as you are in python 2, iterate over <code>users.iteritems()</code> the reason is that <a href="https://docs.python.org/2/library/stdtypes.html#dict.items" rel="nofollow"><code>.items</code></a> make a copy of the whole thing which is a waste of space and time, while <a href="https://docs.python.org/2/library/stdtypes.html#dict.iteritems" rel="nofollow"><code>.iteritems</code></a> don't do that. In python 3 <code>items</code> is equivalent to <code>iteritems</code>. In this little program that might not have a significant impact, but if the dictionary were much larger you would notice a difference </p></li> <li><p>and speaking of wasted space, here <code>len(value["first_name"] + value["last_name"])</code> you are making a new string, without any other change, to just calculate its length so you're wasting a little bit of space here, so just add the length of each</p></li> </ol> <p>with those tip the changes are a follow </p> <pre><code>for key, data in users.iteritems(): print key for i, value in enumerate(data, 1): print i, "-", value["first_name"].upper(), value["last_name"].upper(), "-", len(value["first_name"]) + len(value["last_name"]) </code></pre> <p>You can take a look at <a href="https://docs.python.org/2/library/string.html#formatstrings" rel="nofollow">string</a> <a href="https://docs.python.org/2/library/string.html#formatspec" rel="nofollow">formatting</a> to have a better control over how it will look like, for instance with string formatting this can be done as</p> <pre><code>print "{} - {} {} - {}".format(i, value["last_name"].upper(), value["last_name"].upper(), len(value["first_name"]) + len(value["last_name"]) ) </code></pre> <p>(for more interesting examples look at the documentation)</p>
0
2016-08-06T14:51:18Z
[ "python", "dictionary" ]
URL Regular Expression mismatch
38,804,535
<p>I am trying to learn Django and I am currently stuck in an issue.</p> <p>I created an app Contact and run the server, I get the error.</p> <p>The error page displayed by server:</p> <p><a href="http://i.stack.imgur.com/Z9H90.png" rel="nofollow"><img src="http://i.stack.imgur.com/Z9H90.png" alt="enter image description here"></a></p> <p>The urls.py file in the app Contact</p> <p>urls.py in conatct</p> <p><a href="http://i.stack.imgur.com/fVALb.png" rel="nofollow"><img src="http://i.stack.imgur.com/fVALb.png" alt="enter image description here"></a></p> <p>When the pattern in urls.py is urlpatterns =[url(r'^$', views.form, name ='form')] it works properly, but not with other pattern shown in the picture</p> <p>Your help would be greatly appreciated.</p>
-3
2016-08-06T12:58:35Z
38,804,661
<p>The <em>Page not found</em> error message tells you what went wrong: For the URL (<em>/contact</em>) you requested, Django was unable to find a suitable view. Because you have debugging enabled, you get some information, including a list of registered views.</p> <p>First things first: You probably have <code>url(r'^contact/', include('contact.urls'))</code> somewhere in your top level <code>urls.py</code>. This makes the URLs defined in the <code>contact/urls.py</code> available under the prefix <code>/contact</code>.</p> <p>With</p> <pre><code>urlpatterns = [ url(r'^form/', views.form, name='form'), ] </code></pre> <p>in <code>contact/urls.py</code> you are telling Django that you want urls starting with <code>contact/form/</code> to be handled by <code>views.form</code>.</p> <p>Consequently, when you access <a href="http://localhost:8000/contact/" rel="nofollow">http://localhost:8000/contact/</a> in your browser, there is no view associated with that URL, hence the 404. Your view is <em>reacting to</em> to <a href="http://localhost:8000/contact/form" rel="nofollow">http://localhost:8000/contact/form</a>, not <a href="http://localhost:8000/contact" rel="nofollow">http://localhost:8000/contact</a>.</p> <p>When you change the URL pattern to</p> <pre><code>urlpatterns = [ url(r'^$', views.form, name='form'), ] </code></pre> <p>you modify the URL <code>views.form</code> reacts to.</p>
0
2016-08-06T13:13:15Z
[ "python", "django" ]
Cannot update pip on ubuntu
38,804,596
<p>I am trying to update pip on ubuntu because it keeps telling me "You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command." but when I use that command it tells me "bash: /home/zak/.local/bin/pip: /usr/bin/python: bad interpreter: No such file or directory"</p>
0
2016-08-06T13:06:24Z
38,804,818
<p>If you are updating it globally (and not inside a virtualbox) try using sudo.</p> <pre><code>sudo pip install --upgrade pip </code></pre>
0
2016-08-06T13:32:05Z
[ "python", "ubuntu", "pip" ]
Unable to HTTP POST using python raw socket
38,804,615
<p>I am trying to do a http post on a url using a python raw socket.But I am unable to do so, while http get requests are working fine. The problem is when I try post.</p> <p>My code</p> <pre><code>import socket HOST = 'www.example.com' PORT = 80 DATA = "POST /example/email.php HTTP/1.1\r\n" # send headers "HOST: example.com\r\n" "Accept: */\r\n*" "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n" "Referer: http://example.com/example/\r\n" "action=subscribeme&amp;email=laaarr@gmail.com\r\n" #actual post payload data def tcp_client(): client = socket.socket( socket.AF_INET, socket.SOCK_STREAM) client.connect(( HOST, PORT )) client.send(DATA) response = client.recv(4096) print response if __name__ == '__main__': tcp_client() </code></pre> <p>There is no error/reply from the server side(bad request or anything else) but it seems to be not working. Everything else is correct, because I checked them on POSTMAN and by curl.</p>
-2
2016-08-06T13:08:04Z
38,804,835
<p>try it with</p> <pre><code>DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers "HOST: example.com\r\n" "Accept: *\r\n" "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n" "Referer: http://example.com/example/\r\n" "\r\n" # blank line seperating headers from body "action=subscribeme&amp;email=laaarr@gmail.com\r\n") #actual post payload data </code></pre> <p>and you should get an answer.</p> <p>Using</p> <pre><code>import socket HOST = 'www.example.com' PORT = 80 DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers "HOST: example.com\r\n" "Accept: *\r\n" "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n" "Referer: http://example.com/example/\r\n" "\r\n" # blank line seperating headers from body "action=subscribeme&amp;email=laaarr@gmail.com\r\n") #actual post payload data def tcp_client(): client = socket.socket( socket.AF_INET, socket.SOCK_STREAM) client.connect(( HOST, PORT )) client.send(DATA) response = client.recv(4096) print response if __name__ == '__main__': tcp_client() </code></pre> <p>I get </p> <pre><code>HTTP/1.1 411 Length Required Content-Type: text/html Content-Length: 357 Connection: close Date: Mon, 08 Aug 2016 11:23:16 GMT Server: ECSF (ewr/1443) &lt;?xml version="1.0" encoding="iso-8859-1"?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;title&gt;411 - Length Required&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;411 - Length Required&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>which obviously is an error but totally a response.</p> <p>With </p> <pre><code>DATA = ("POST /example/email.php HTTP/1.1\r\n" # send headers "HOST: example.com\r\n" "Accept: *\r\n" "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n" "Content-Length: 41\r\n" #fixes error 411 "Referer: http://example.com/example/\r\n" "\r\n" # blank line seperating headers from body "action=subscribeme&amp;email=laaarr@gmail.com") #actual post payload data </code></pre> <p>I get a normal <code>404 Not Found</code>.</p>
1
2016-08-06T13:35:42Z
[ "python" ]
how run kivy program?
38,804,663
<p>I wrote some program with python kivy lib but it's not working. </p> <pre><code>import kivy from kivy.app import App from kivy.uix.button import Button from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.graphics import Color class Controller(BoxLayout): def welcome(self): wid = BoxLayout(orientation='vertical') wid.add_widget(Label(text='hellow',size_hint=(1,.1))) wid.add_widget(Button(text='welcom',size_hint=(1,.1))) wid.add_widget(Button(text='khoroj',size_hint=(1,.1))) wid.add_widget(Button(text='rahnama',size_hint=(1,.1))) class UiApp(App): def build(self): root = Controller() return root if __name__ == '__main__': UiApp().run() </code></pre> <p>When I run the program, only a black window is shown, no widgets. What can be the problem?</p>
1
2016-08-06T13:13:19Z
38,805,809
<p>There are two problems here. </p> <p>I will show two examples in this answer. The first without nested <code>BoxLayout</code>, and second with nested <code>BoxLayout</code>.<br> In both examples, I will use <code>__init__</code> instead of <code>welcome()</code><br> You can also use <code>welcome()</code>. Read below on how to do that. </p> <p>Then to the two problems: </p> <p>First: </p> <p>You never run the <code>welcome()</code> method in your <code>Controller</code> class.<br> You could eiter fix that by, running it in the apps <code>build</code> method, before you return <code>root</code>. Like this: </p> <pre><code>root.welcome() return root </code></pre> <p>Or you could put it in a <code>__init__</code> method in the class. I will show an example of that, after I explain what the second problem here is. </p> <p>The second problem is that you create a new <code>BoxLayout</code> in to your class, which allready inherits a <code>BoxLayout</code>. But you never add this new <code>BoxLayout</code> to your widget, which in this case allready is a <code>BoxLayout</code>. </p> <p>So, how to fix this.<br> Since the class allready inherits <code>BoxLayout</code>, you dont need to make a new in this simple app. Only if you need to nest a <code>BoxLayout</code>, you would do that. </p> <p>Lets say you dont need to nest another <code>BoxLayout</code>.<br> An example on how you do that, and use a <code>__init__</code> method: </p> <pre><code>import kivy from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout class Controller(BoxLayout): def __init__(self,**kwargs): super(Controller,self).__init__(**kwargs) # this is what you need to overite the BoxLayout's __init__ method # self.orientation and self.add_widget because self is the BoxLayout you inherited self.orientation='vertical' self.add_widget(Label(text='hellow',size_hint=(1,.1))) self.add_widget(Button(text='welcom',size_hint=(1,.1))) self.add_widget(Button(text='khoroj',size_hint=(1,.1))) self.add_widget(Button(text='rahnama',size_hint=(1,.1))) class UiApp(App): def build(self): root = Controller() return root if __name__ == '__main__': UiApp().run() </code></pre> <p>Lets say you need to nest another <code>BoxLayout</code>.<br> You would do like this: </p> <pre><code>import kivy from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout class Controller(BoxLayout): def __init__(self,**kwargs): super(Controller,self).__init__(**kwargs) # this is what you need to overite the BoxLayout's __init__ method # I make this BoxLayout horizontal, and add a Button, just to show the idea of nesting self.orientation='horizontal' self.add_widget(Button(text='First Button')) self.nested_boxlayout = BoxLayout(orientation="vertical") # then we add stuff to the nested layout self.nested_boxlayout.add_widget(Label(text='hellow',size_hint=(1,.1))) self.nested_boxlayout.add_widget(Button(text='welcom',size_hint=(1,.1))) self.nested_boxlayout.add_widget(Button(text='khoroj',size_hint=(1,.1))) self.nested_boxlayout.add_widget(Button(text='rahnama',size_hint=(1,.1))) # but we still need to add the nested layout to the root layout. (nest it) self.add_widget(self.nested_boxlayout) class UiApp(App): def build(self): root = Controller() return root if __name__ == '__main__': UiApp().run() </code></pre>
1
2016-08-06T15:22:43Z
[ "python", "kivy" ]
The if statement looks right but got wrong answer
38,804,744
<pre><code>a = 5 b = 10 if a &lt; 5 and b &gt; 5: print('Yes') else: print('No') </code></pre> <p>When running the code above, I expect the answer is Yes. But the output is 'No'. Could anyone please tell me what wrong in my code is? Thank you in advance! </p>
-5
2016-08-06T13:23:47Z
38,804,765
<p>You are expecting <code>5</code> to be lower than <code>5</code> (<code>a = 5</code> and <code>a &lt; 5</code>). That's clearly not true, so the expression <code>a &lt; 5 and b &gt; 5</code> is False and the <code>else</code> branch is picked.</p>
2
2016-08-06T13:26:11Z
[ "python", "python-3.5" ]
The if statement looks right but got wrong answer
38,804,744
<pre><code>a = 5 b = 10 if a &lt; 5 and b &gt; 5: print('Yes') else: print('No') </code></pre> <p>When running the code above, I expect the answer is Yes. But the output is 'No'. Could anyone please tell me what wrong in my code is? Thank you in advance! </p>
-5
2016-08-06T13:23:47Z
38,804,806
<p>a is assigned to 5 this means that a is equal to five (a &lt; 5 is false) try doing</p> <pre><code> if a &lt;= 5 and b &gt;= 5: print('yes' else: print('no') </code></pre>
2
2016-08-06T13:30:24Z
[ "python", "python-3.5" ]
is there any command to "terminate all other sessions" in telegram-cli?
38,804,807
<p>i need a script to terminate all other sessions each time new login in my account detected(or each second) in python. <strong>is there any command to "terminate all other sessions" in telegram-cli?</strong></p>
1
2016-08-06T13:30:47Z
38,806,055
<p>You would need the session_id of your other sessions:</p> <pre><code>destroy_session#e7512126 session_id:long = DestroySessionRes;The expected </code></pre> <p>responses is:</p> <pre><code>destroy_session_ok#e22045fc session_id:long = DestroySessionRes; </code></pre> <p>or</p> <pre><code>destroy_session_none#62d350c9 session_id:long = DestroySessionRes; </code></pre>
2
2016-08-06T15:49:08Z
[ "python", "telegram" ]
[Numpy/Pandas]How can I efficiently create a panel data set from transaction records?
38,804,820
<p>I have data arranged in the following form:</p> <pre><code>ID,DATE,STATUS 1,6/20/2011,A 1,1/14/2013,B 1,8/1/2016,C 2,3/1/2005,A 2,4/30/2005,B 2,6/30/2010,C 2,8/20/2010,D </code></pre> <p>I want to convert these transactions into an unbalanced panel with an annual frequency:</p> <pre><code>ID,YEAR,STATUS 1,2011,A 1,2012,A 1,2013,B 1,2014,B 1,2015,B 1,2016,C 2,2005,B 2,2006,B 2,2007,B 2,2008,B 2,2009,B 2,2010,D </code></pre> <p>So basically I want an annual series for each ID that spans the first through last date observed for that ID. The status in each year will be the last status observed in the year if there is more than one record for that year, or the last observed status if there is no date in that year.</p> <p>This is a big dataset, so a good answer needs to use efficient methods provided by numpy/pandas.</p>
0
2016-08-06T13:32:09Z
38,805,181
<p>Here's one way:</p> <pre><code>import pandas as pd df = pd.read_csv('file', parse_dates=['DATE']) df = df.set_index('DATE').resample('A').ffill() df['YEAR'] = df.index.year df = df.sort_values(['ID', 'YEAR']).reset_index(drop=True) df Out: ID STATUS YEAR 0 1 A 2011 1 1 A 2012 2 1 B 2013 3 1 B 2014 4 1 B 2015 5 1 C 2016 6 2 B 2005 7 2 B 2006 8 2 B 2007 9 2 B 2008 10 2 B 2009 11 2 D 2010 </code></pre>
2
2016-08-06T14:11:53Z
[ "python", "pandas", "numpy" ]
Select texts between tags in Xpath in Python
38,804,848
<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>&lt;td width="250"&gt; 10.03.1984 16:30 &lt;br/&gt; Lütfi Kırdar, İstanbul &lt;br/&gt; &lt;br/&gt; 47-38, 49-58, 8-10 &lt;/td&gt;</code></pre> </div> </div> </p> <p>I want to get all text between "td" tags. My code is mactarih=tree.xpath("//tr//td[@width='250']//text()") . But it is wrong. </p> <p>The expected result is: text=['10.03.1984 16:30','Lütfi Kırdar, İstanbul','47-38, 49-58, 8-10']</p>
2
2016-08-06T13:37:04Z
38,805,274
<blockquote> <p><em>"My code is <code>mactarih=tree.xpath("//tr//td[@width='250']//text()")</code>. But it is wrong"</em>. </p> </blockquote> <p>If it was 'wrong' in the sense that it returned empty texts or newlines along with the correct texts, then you can use <code>normalize-space()</code> to filter out whitespace-only texts :</p> <pre><code>mactarih=tree.xpath("//tr//td[@width='250']//text()[normalize-space()]") </code></pre> <p>Quick test :</p> <pre><code>&gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; raw = '''&lt;td width="250"&gt; ... 10.03.1984 16:30 ... &lt;br/&gt; ... Lütfi Kırdar, İstanbul ... &lt;br/&gt; ... &lt;br/&gt; ... 47-38, 49-58, 8-10 ... &lt;/td&gt;''' &gt;&gt;&gt; root = etree.fromstring(raw) &gt;&gt;&gt; root.xpath("//td[@width='250']//text()[normalize-space()]") ['\n10.03.1984 16:30\n', u'\nL\xfctfi K\u0131rdar, \u0130stanbul\n', '\n47-38, 49-58, 8-10\n'] </code></pre>
2
2016-08-06T14:22:00Z
[ "python", "xpath" ]
Why does cookielib.LWPCookieJar accept an empty argument list?
38,804,897
<p>In the cookielib documentation, the definition of <a href="https://docs.python.org/2/library/cookielib.html#file-cookie-jar-classes" rel="nofollow">cookielib.LWPCookieJar</a> is:</p> <pre><code>class cookielib.LWPCookieJar(filename, delayload=None, policy=None) </code></pre> <p>The filename is a required argument.</p> <p>But in the following python code, <code>LWPCookieJar</code> has no argument, yet still works.</p> <pre><code>import cookielib cookie = cookielib.LWPCookieJar() </code></pre> <p>Who knows why?</p>
1
2016-08-06T13:41:34Z
38,809,931
<p>Because the documentation is lying, apparently.</p> <p><code>cookielib.py</code> imports the definition of <a href="https://hg.python.org/cpython/file/2.7/Lib/_LWPCookieJar.py#l49" rel="nofollow"><code>LWPCookieJar</code></a> from <code>_LWPCookieJar.py</code>, which defines it as:</p> <pre><code>class LWPCookieJar(FileCookieJar): ... </code></pre> <p><a href="https://hg.python.org/cpython/file/2.7/Lib/cookielib.py#l1749" rel="nofollow"><code>FileCookieJar</code></a> is defined in <code>cookielib.py</code>, as:</p> <pre><code>class FileCookieJar(CookieJar): """CookieJar that can be loaded from and saved to a file.""" def __init__(self, filename=None, delayload=False, policy=None): ... </code></pre> <p>So the <code>filename</code> argument is actually optional (and <code>delayload</code> defaults to <code>False</code>, not <code>None</code>).</p>
1
2016-08-07T00:48:28Z
[ "python", "cookies" ]
Exit function after if
38,804,905
<p>This maybe a stupid question, but I don't kow how to exit the function below after if statement. This code is written in python</p> <pre><code>def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print("sum(%s)=%s" % (partial, target)) print("True") return if s &gt; target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i + 1:] subset_sum(remaining, target, partial + [n]) def main(): print(subset_sum([10, 7, 6, 3], 13)) main() </code></pre> <p>The output is </p> <pre><code>sum([10, 3])=13 True sum([7, 6])=13 True None </code></pre> <p>What I need is when sum([10,3)]==13, the function will print </p> <pre><code>sum([10, 3])=13 True </code></pre> <p>and then end.</p>
0
2016-08-06T13:42:21Z
38,804,917
<p>You are printing the return value of the function. Your function returns <code>None</code> (the default return value), so that is what is printed.</p> <p>Drop the <code>print()</code> function call, just call the function and leave it at that:</p> <pre><code>def main(): subset_sum([10, 7, 6, 3], 13) </code></pre> <p>Next, your recursive function continues to search for additional solutions, because you don't flag when a solution has been found.</p> <p>You could return <code>True</code> when you have found a solution, then stop all further searches when a recursive call is true:</p> <pre><code>def subset_sum(numbers, target, partial=None): partial = partial or [] s = sum(partial) # check if the partial sum is equals to target if s == target: print("sum(%s)=%s" % (partial, target)) print("True") return True if s &gt; target: return False # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i + 1:] if subset_sum(remaining, target, partial + [n]): # solution found, stop searching return True return False </code></pre>
2
2016-08-06T13:43:52Z
[ "python", "if-statement", "exit" ]
Exit function after if
38,804,905
<p>This maybe a stupid question, but I don't kow how to exit the function below after if statement. This code is written in python</p> <pre><code>def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print("sum(%s)=%s" % (partial, target)) print("True") return if s &gt; target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i + 1:] subset_sum(remaining, target, partial + [n]) def main(): print(subset_sum([10, 7, 6, 3], 13)) main() </code></pre> <p>The output is </p> <pre><code>sum([10, 3])=13 True sum([7, 6])=13 True None </code></pre> <p>What I need is when sum([10,3)]==13, the function will print </p> <pre><code>sum([10, 3])=13 True </code></pre> <p>and then end.</p>
0
2016-08-06T13:42:21Z
38,804,929
<p>Your function is just returning, which means it returns <code>None</code>. This is a problem when you're calling the function recursively, because the parent doesn't know whether it should continue recursing or not.</p> <p>You should instead return a value that tells the parent call whether or not it should return or continue. </p>
0
2016-08-06T13:45:18Z
[ "python", "if-statement", "exit" ]
Replacing pairs of variables in a file
38,804,986
<p>I working on a problem and my goal is to replace variables in the file and the name of the files. The issue is that I have to change a couple of variables at the same time for all combinations (Generally 24 combinations).</p> <p>I know how to create of all combinations of strings, but I want to put lists inside and iterate over them.</p> <pre><code>a = [ 'distance', 'T1', 'T2', 'gamma' ] new_list = list(itertools.permutations(a, 2)) </code></pre> <p>I created the function to pass my values:</p> <pre><code>def replace_variables(distance ='0', T1 ='0', T2 = '0', gamma = '0'): template_new = template.replace('*distance*', distance).replace('*T1*', T1).replace('*T2*', T2).replace('*gamma*', gamma) input_file = input_name.replace('one','T1'+T1).replace('two','T2'+T2).replace('phi','PHI'+Phi).replace('distance','R'+distance) return template_new, input_file </code></pre> <p>when I call that function I can pass only names of variables.</p> <pre><code>for i in new_list: elem1 = i[0] elem2 = i[1] template_new, input_file =replace_variables(elem1, elem2) print input_file </code></pre> <p>Though I need to use lists:</p> <pre><code>distance = ['-3','+3'] T1 = ['-3', '+3'] T2 = ['-3', '+3'] gamma = ['-3', '+3'] </code></pre> <p>And for each pair of variables change values in a file and a name of file such as:</p> <p>original file: <code>name_file_R_T1_T2_gamma.txt</code></p> <p>will be replaced by:</p> <pre><code>name_file_3_3_0_0.txt, name_file_3_-3_0_0.txt, name_file_-3_3_0_0.txt, name_file_3_3_0_0.txt, name_file_3_0_3_0.txt, name_file_3_0_-3_0.txt, </code></pre> <p>and so forth.</p> <p>The original template looks like:</p> <pre><code>template = """ R = 3.0 *distance* cm THETA1 = 60. *T1* degree THETA2 = 2.0 *T2* degree GAMMA = 0 *gamma* degree """ </code></pre> <p>and I want to obtain:</p> <pre><code>template = """ R = 3.0 +3 cm THETA1 = 60. +3 degree THETA2 = 2.0 +0 degree GAMMA = 0 +0 degree """ </code></pre> <p>and so forth</p>
-2
2016-08-06T13:52:02Z
38,806,936
<p>I think I almost tackled the above problem:</p> <pre><code>#!/usr/bin/env python import itertools import copy def replace_variables(i, distance ='0', T1 ='0', T2 = '0', gamma = '0' ): k_ = copy.deepcopy(i) k_[0][0] = '-2' k_[1][0] = '2' template_new = template.replace('*distance*', distance).replace('*T1*', T1).replace('*T2*', T2).replace('*gamma*', gamma) input_file = input_name.replace('one','T1'+T1).replace('two','T2'+T2).replace('gamma','gamma'+gamma).replace('distance','R'+distance) f = open(template_new, 'w') f.write(template_new) f.close() input_name = 'name_file_distance_T1_T2_gamma.txt' template = """ R = 3.0 *distance* cm THETA1 = 60. *T1* degree THETA2 = 2.0 *T2* degree GAMMA = 0 *gamma* degree """ a = [['distance','+2','-2'], ['T1','+2','-2'], ['T2','+2','-2'], ['gamma','+2','-2']] new_list = list(itertools.permutations(a, 2)) for i in new_list: replace_variables(i, x, y) </code></pre> <p>Though I faced 2 problems:</p> <p>1) My code does not change values of variables (apart from default ones) in the replace_variables function and I'm getting: name_file_Rdistance_T1T1_T20_gamma0.txt, and so on I think because of default arguments passed to the function.</p> <p>2) My function does not create a separated files.</p>
0
2016-08-06T17:27:41Z
[ "python" ]
What does sys.exit really do with multiple threads?
38,804,988
<p>I was really confused by sys.exit() in python. In <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">python documentation</a>, it says "Exit from Python"; does that mean when <code>sys.exit()</code> is called in a python program, the process will exit? If so, the code below shows a different result:</p> <pre><code>import sys import time import threading def threadrun(): while(True): time.sleep(1) if __name__=="__main__": t=threading.Thread(target=threadrun) t.start() sys.exit() </code></pre> <p>Launching this program in linux, result was not the expected one as python documentation says but still run in the system, so what does <code>sys.exit()</code> really do?</p>
4
2016-08-06T13:52:16Z
38,805,142
<p>It is easy. </p> <p>In your case, the end of the program is when the last thread will be terminated. Maybe kind of join() method(as in Java) in python will wait for other threads. you can change <code>while(true)</code> to have finite method in sense of time.</p> <pre><code>def threadrun(): i=1000_000_000_000 while(i&gt;0): i=i-1 time.sleep(1) </code></pre> <p>and watch another behave your program. </p> <p>in advance sorry for my english(: </p> <p>and please, read this article(: there is a good explanation how to play with threads in your case <a href="http://stackoverflow.com/questions/19138219/use-of-threading-thread-join">Use of threading.Thread.join()</a></p> <p>and </p> <p>documentation <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">https://docs.python.org/2/library/threading.html</a> (but relax, it is only for additional knowledge.</p> <p>and read this article about daemon property(if you do not want to wait for others threads become terminated <a href="http://stackoverflow.com/questions/4330111/python-thread-daemon-property">Python thread daemon property</a></p>
1
2016-08-06T14:09:19Z
[ "python", "multithreading", "exit" ]
What does sys.exit really do with multiple threads?
38,804,988
<p>I was really confused by sys.exit() in python. In <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">python documentation</a>, it says "Exit from Python"; does that mean when <code>sys.exit()</code> is called in a python program, the process will exit? If so, the code below shows a different result:</p> <pre><code>import sys import time import threading def threadrun(): while(True): time.sleep(1) if __name__=="__main__": t=threading.Thread(target=threadrun) t.start() sys.exit() </code></pre> <p>Launching this program in linux, result was not the expected one as python documentation says but still run in the system, so what does <code>sys.exit()</code> really do?</p>
4
2016-08-06T13:52:16Z
38,805,169
<p>As per the documentation <a href="https://docs.python.org/2/library/sys.html#sys.exit" rel="nofollow"><code>sys.exit()</code></a> raises <code>SystemExit</code>:</p> <blockquote> <p>Exit the interpreter by raising SystemExit(status).</p> </blockquote> <p>If <code>SystemExit</code> reaches the <a href="https://github.com/python/cpython/blob/70689fd8eeba2a9fcbdf6007c61ca9aebe2ec522/Python/pythonrun.c#L1156" rel="nofollow">default exception handler</a>, it calls <code>handle_system_exit()</code>, which more or less pushes through to <a href="https://github.com/python/cpython/blob/70689fd8eeba2a9fcbdf6007c61ca9aebe2ec522/Python/pythonrun.c#L404" rel="nofollow"><code>Py_Finalize()</code></a>, which in turn calls <a href="https://github.com/python/cpython/blob/70689fd8eeba2a9fcbdf6007c61ca9aebe2ec522/Python/pythonrun.c#L412" rel="nofollow"><code>wait_for_thread_shutdown()</code></a> in Python 2, so <code>sys.exit()</code> is the same as the normal <em>falling off the bottom of the main module</em> in waiting for all non-daemon threads to terminate.</p>
4
2016-08-06T14:11:08Z
[ "python", "multithreading", "exit" ]
What does sys.exit really do with multiple threads?
38,804,988
<p>I was really confused by sys.exit() in python. In <a href="https://docs.python.org/2/library/sys.html" rel="nofollow">python documentation</a>, it says "Exit from Python"; does that mean when <code>sys.exit()</code> is called in a python program, the process will exit? If so, the code below shows a different result:</p> <pre><code>import sys import time import threading def threadrun(): while(True): time.sleep(1) if __name__=="__main__": t=threading.Thread(target=threadrun) t.start() sys.exit() </code></pre> <p>Launching this program in linux, result was not the expected one as python documentation says but still run in the system, so what does <code>sys.exit()</code> really do?</p>
4
2016-08-06T13:52:16Z
38,805,873
<p><sub>Paraphrasing what's in the documentation for <a href="https://docs.python.org/2/library/threading.html#thread-objects" rel="nofollow">Thread Objects</a></sub></p> <p>Normally a Python program exits only when there's nothing but daemon threads (ignoring itself) are left running. The “main thread” object which corresponds to the initial thread of control in the program <em>isn't</em> a daemon thread. Threads created using <code>threading.Thread</code> inherit their daemonic status from the creating thread, so if that's the main thread they will also be non-daemonic.</p> <p>This means that <em>by default</em> any threads created and started by your main program will prevent it from exiting if they are still running when the main thread is terminated (by say, <code>sys.exit()</code>. In other words, the program exits only when no alive <strong>non-daemon</strong> threads are left.</p> <p>You can override this default behavior by explicitly setting the <code>daemon</code> property of any created thread objects to <code>True</code> <em>before</em> starting, it as show below:</p> <pre><code> ... if __name__=="__main__": t = threading.Thread(target=threadrun) t.daemon = True # added t.start() sys.exit() </code></pre> <p>Which will allow the program to actually end when <code>sys.exit()</code> is called (although calling it explicitly like that isn't necessary since it's at the end of the script anyway).</p>
0
2016-08-06T15:29:44Z
[ "python", "multithreading", "exit" ]
access first message in Django template
38,804,989
<p>I am using the following code to access the first message in Django template,</p> <pre><code>{% if messages %} {% for message in messages %} {% if forloop.first %} {{ message }} {% endif %} {% endfor %} {% endif %} </code></pre> <p>How I can achieve the same without using the for loop in a single statement.</p>
0
2016-08-06T13:52:28Z
38,805,227
<p>Following should work:</p> <pre><code>{% if messages %} {{ messages.0 }} {% endif %} </code></pre>
2
2016-08-06T14:17:27Z
[ "python", "django" ]