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 |
|---|---|---|---|---|---|---|---|---|---|
App engine PHP modules not working | 38,716,279 | <p>I read the docs about GAE's modules. This <a href="https://github.com/GoogleCloudPlatform/appengine-modules-helloworld-python" rel="nofollow">sample application</a> shows how to use modules in a GAE app. I have modified the code little bit to use both <a href="http://stackoverflow.com/a/21588987/3297613">php and python languages</a> on that.</p>
<p>Here is the <a href="https://github.com/Avinash-Raj/appengine-modules-helloworld-python" rel="nofollow">Github link</a> where the corresponding code resides.</p>
<p>When I try to run this application on my local machine, by running this command</p>
<pre><code>dev_appserver.py dispatch.yaml app.yaml php.yaml static_backend.yaml --php_executable_path /usr/bin/php
</code></pre>
<p>all works fine except the code written in php. When I try to access that particular part by triggering this <code>localhost:8080/mobile/</code>, I get an empty page instead of <code>Hello World</code>. </p>
| 0 | 2016-08-02T09:11:33Z | 38,734,406 | <p>I have ran your code without a problem.</p>
<p><a href="http://i.stack.imgur.com/elHfS.png" rel="nofollow"><img src="http://i.stack.imgur.com/elHfS.png" alt="php module"></a>
<a href="http://i.stack.imgur.com/JJtyD.png" rel="nofollow"><img src="http://i.stack.imgur.com/JJtyD.png" alt="python module"></a></p>
<pre><code>dev_appserver.py dispatch.yaml app.yaml php.yaml static_backend.yaml
INFO 2016-08-03 04:19:01,413 devappserver2.py:769] Skipping SDK update check.
INFO 2016-08-03 04:19:01,517 api_server.py:205] Starting API server at: http://localhost:52017
INFO 2016-08-03 04:19:01,520 dispatcher.py:185] Starting dispatcher running at: http://localhost:8080
INFO 2016-08-03 04:19:01,526 dispatcher.py:197] Starting module "default" running at: http://localhost:8081
INFO 2016-08-03 04:19:01,718 dispatcher.py:197] Starting module "php-module" running at: http://localhost:8082
INFO 2016-08-03 04:19:01,734 dispatcher.py:197] Starting module "static-backend" running at: http://localhost:8083
INFO 2016-08-03 04:19:01,744 admin_server.py:116] Starting admin server at: http://localhost:8000
INFO 2016-08-03 04:19:02,209 module.py:1730] New instance for module "php-module" serving on:
http://localhost:8082
INFO 2016-08-03 04:19:02,759 module.py:1730] New instance for module "static-backend" serving on:
http://localhost:8083
INFO 2016-08-03 04:19:03,283 module.py:788] php-module: "GET /_ah/start HTTP/1.1" 200 24
INFO 2016-08-03 04:19:03,470 module.py:788] static-backend: "GET /_ah/start HTTP/1.1" 200 3108
INFO 2016-08-03 04:19:15,683 module.py:788] static-backend: "GET /mobile/ HTTP/1.1" 200 3752
INFO 2016-08-03 04:19:16,407 module.py:788] static-backend: "GET /favicon.ico HTTP/1.1" 200 3626
INFO 2016-08-03 04:19:18,914 module.py:788] static-backend: "GET /mobile HTTP/1.1" 200 3710
INFO 2016-08-03 04:19:19,345 module.py:788] static-backend: "GET /favicon.ico HTTP/1.1" 200 3650
INFO 2016-08-03 04:19:21,096 module.py:788] static-backend: "GET / HTTP/1.1" 200 3648
</code></pre>
<p>Try the following:</p>
<ul>
<li>Installing all necessary PHP extensions using <code>gcloud components install app-engine-php</code></li>
<li>Omitting the <code>--php-executable-flag</code></li>
<li>Making sure it is correct with the command <code>which php</code> on your terminal, and pointing the <code>--php-executable-flag</code> to your <code>php-cgi</code></li>
</ul>
| 1 | 2016-08-03T04:26:24Z | [
"php",
"python",
"google-app-engine"
] |
capture response data into an array using python | 38,716,359 | <p>Capture response data into an array using python:</p>
<p>When I read an url using urlib2 I get the below response in the console using print resp</p>
<pre><code>code : resp = urllib2.urlopen(memberProfileInfo).read()
Console display
OCODE: 11
UCODE: XXX
GID: XXXXXX
GDISP: XXXXX
\# rc=0, count=1, message=Success
</code></pre>
<p>How do I capture these values of ocode etc into arrays using python 2.7 ? </p>
| 0 | 2016-08-02T09:15:16Z | 38,720,092 | <pre><code>I did this and it worked:
Code as below:
profdata = []
resp = urllib2.urlopen(memberProfileInfo).read()
profdata = resp.split('\n')
return profdata
However now in the excel I get all the response appended:
OCODE: 11 UCODE: XXX GID: XXXXXX GDISP: XXXXX \# rc=0, count=1, message=Success
Can we use regex and only capture data after : ? any suggestions here for the rest of the capture.
</code></pre>
| 0 | 2016-08-02T12:12:02Z | [
"python",
"python-2.7"
] |
Python tkinter entry prompt | 38,716,453 | <p>I want to prompt a string of letters one for each time to ask user to click and the game will continue only when user press the correct key.</p>
<p>I am having trouble with the key pressing part. I want to get the text on the button and test if it matches with the prompted letter, if it matches the entry widget will prompt the next letter otherwise it just stays still.</p>
<p>I imported random to shuffle the letters so that every time it will generates different letters. I did not add the <code>random.shuffle(alist)</code>, because it does not work.</p>
<p>here is my code:</p>
<pre><code>from tkinter import *
from tkinter.ttk import *
import random
import tkinter
class KeyboardGame:
def __init__(self):
window = Tk()
window.title('haha')
self.value = StringVar()
self.value.set('click on any key to start...')
btm_frame = Frame(window, relief=RAISED)
entry = Entry(window, text=self.value)
entry.grid(row=0, column=0, padx=40, pady=5, sticky='EW')
for i in ['ixnsywfhze', 'uobpqgtav', 'lmjkcdr']:
frame1 = Frame(btm_frame)
for j in i:
button = Button(frame1, text=j, command=self.game)
button.pack(side=LEFT)
frame1.pack(padx=2, pady=2)
btm_frame.grid(row=1, column=0, padx=5, pady=5)
window.mainloop()
def game(self):
n = 0
alist = ['h', 'c', 'p', 'e', 'm', 'n', 'd']
self.value.set(alist[n])
while button['text'] != alist[n]:
self.value.set(alist[n])
n += 1
KeyboardGame()
</code></pre>
| 1 | 2016-08-02T09:19:15Z | 38,720,653 | <p>You can resolve your problem by <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow"><code>binding</code></a> the same event to each button you created.</p>
<p>Hence, in your callback you will need to identify the button which is clicked (which thing your actual code does not do) in order to compare its text using <a href="http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.cget-method" rel="nofollow"><code>cget()</code></a> method to the content of the entry widget.</p>
<p>Notice that in order to increment <code>n</code> inside <code>game()</code> you will need to render it as an <a href="http://www.python-course.eu/python3_class_and_instance_attributes.php" rel="nofollow">instance variable</a>. You must be careful not to increment it when it reaches the same value as the <code>alist</code>'s length.</p>
<h1>Full program</h1>
<p>Here are the ideas mentioned above implemented. Note that I focus on fixing your issues only. This means I am not going to comment the best practices you should follow:</p>
<pre><code>from tkinter import *
from tkinter.ttk import *
import tkinter
class KeyboardGame:
def __init__(self):
window = Tk()
window.title('haha')
self.value = StringVar()
self.value.set('h')
self.btm_frame = Frame(window, relief=RAISED)
self.entry = Entry(window, text=self.value)
self.entry.grid(row=0, column=0, padx=40, pady=5, sticky='EW')
self.n = 0
for i in ['ixnsywfhze', 'uobpqgtav', 'lmjkcdr']:
self.frame1 = Frame(self.btm_frame)
for j in i:
button = Button(self.frame1, text=j)
button.pack(side=LEFT)
button.bind("<Button-1>", self.game)
self.frame1.pack(padx=2, pady=2)
self.btm_frame.grid(row=1, column=0, padx=5, pady=5)
window.mainloop()
def game(self, event):
alist = ['h', 'c', 'p', 'e', 'm', 'n', 'd']
w = event.widget # Identify the button
if w.cget("text") == self.value.get() and self.n < 6:
self.n = self.n + 1
self.value.set(alist[self.n])
# Start program
if __name__ =="__main__":
KeyboardGame()
</code></pre>
<h1>Demo</h1>
<p>Here is a screenshot of the running above program:</p>
<p><a href="http://i.stack.imgur.com/lLTG0.png" rel="nofollow"><img src="http://i.stack.imgur.com/lLTG0.png" alt="enter image description here"></a></p>
| 2 | 2016-08-02T12:38:39Z | [
"python",
"python-3.x",
"tkinter"
] |
PYTHON prime numbers function | 38,716,517 | <p>I am new to programming and I face an issue while trying to write a program in finding out prime number. Here is my code:</p>
<pre><code>def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x-1):
if x % n == 0:
return False
else:
return True
</code></pre>
<p>I received an error stating "Your function fails on is_prime(3). It returns None when it should return True."</p>
<p>Can someone please explain the flaw in this code?</p>
<p>Thank you!</p>
| 0 | 2016-08-02T09:22:07Z | 38,716,556 | <p><code>range()</code> has an <a href="https://docs.python.org/3.4/library/stdtypes.html#range" rel="nofollow">exclusive upper bound</a>, so it's trying to get the range between 2 and 2 (3 - 1), which is no elements. Since you can't iterate over nothing, the for loop never runs, so <code>None</code> is returned (this is the default return type of a function if none is specified).</p>
<p>The solution to your immediate problem would be to use <code>range(2, x)</code> rather than <code>range(2, x - 1)</code>. You'll find that you'll have problems at x > 3 though because as @khelwood said, you're returning <code>True</code> or <code>False</code> immediately after checking the first value. Instead, only return <code>True</code> after checking <strong>all</strong> values in the range.</p>
| 3 | 2016-08-02T09:24:12Z | [
"python",
"if-statement",
"for-loop",
"primes",
"prime-factoring"
] |
PYTHON prime numbers function | 38,716,517 | <p>I am new to programming and I face an issue while trying to write a program in finding out prime number. Here is my code:</p>
<pre><code>def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x-1):
if x % n == 0:
return False
else:
return True
</code></pre>
<p>I received an error stating "Your function fails on is_prime(3). It returns None when it should return True."</p>
<p>Can someone please explain the flaw in this code?</p>
<p>Thank you!</p>
| 0 | 2016-08-02T09:22:07Z | 38,716,812 | <pre><code>def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range (2,x): # range function will iterate till x-1
if x % n == 0:
return False
# return true only at the end after making sure it is not divisible by any number in the middle
return True
</code></pre>
| 0 | 2016-08-02T09:35:50Z | [
"python",
"if-statement",
"for-loop",
"primes",
"prime-factoring"
] |
Python Session 10054 Connection Aborted Error | 38,716,539 | <p>I wrote a web scraper using requests module. I open up a session and send subsequent requests using this session. It has 2 phases.</p>
<p>1) Scrape page by page and collect id's in an array.
2) Get details about each id in the array using requests to an ajax server on the same host.</p>
<p>The scraper works fine on my Linux machine. However when I run the bot on Windows 10, phase 1 is completed just fine but after a couple of requests in phase 2 python throws this exception</p>
<p>File "c:\python27\lib\site-packages\requests\adapters.py", line 453, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(10054, 'Varolan bir ba\xf0lant\xfd uzaktaki bir ana bilgisayar taraf\xfdndan zorla kapat\xfdld'))</p>
<p>What is different between two OS's which causes this? How can I overcome this problem?</p>
<p>Having modified my request code like below using retrying module had no positive effects. Now script doesn't throw exceptions but simply hangs doing nothing.</p>
<pre><code>@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_attempt_number=7)
def doReq(self, url):
time.sleep(0.5)
response = self.session.get(url, headers=self.headers)
return response
</code></pre>
| 0 | 2016-08-02T09:23:12Z | 39,290,736 | <p>I still don't know why this problem occurs only in Windows. However, retrying decorator seems to have fixed the problem of socket error. The reason why the script hangs was due to the server not responding to a request. By default requests mode waits forever for a response. By adding a timeout value requests throws a timeout exception and retry decorator catches it and tries again. I know this is a work around rather than a solution but this is the best I've got right now.</p>
| 0 | 2016-09-02T10:58:18Z | [
"python",
"windows",
"session",
"web-scraping",
"python-requests"
] |
Unable to run TensorFlow on Spark | 38,716,584 | <p>I am trying to make TensorFlow work on my Spark cluster in order to make it run in parallel.
As a start, I tried to use this <a href="https://gist.github.com/tnachen/e004539cdd38e5941d0cb712d0ad3b91" rel="nofollow">demo</a> as-is.</p>
<p>The demo works great without Spark, but when using Spark, I get the following error:</p>
<pre><code>16/08/02 10:44:16 INFO DAGScheduler: Job 0 failed: collect at /home/hdfs/tfspark.py:294, took 1.151383 s
Traceback (most recent call last):
File "/home/hdfs/tfspark.py", line 294, in <module>
local_labelled_images = labelled_images.collect()
File "/usr/hdp/2.4.2.0-258/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 771, in collect
File "/usr/hdp/2.4.2.0-258/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
File "/usr/hdp/2.4.2.0-258/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError16/08/02 10:44:17 INFO BlockManagerInfo: Removed broadcast_2_piece0 on localhost:45020 in memory (size: 6.4 KB, free: 419.5 MB)
16/08/02 10:44:17 INFO ContextCleaner: Cleaned accumulator 2
: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/usr/hdp/2.4.2.0-258/spark/python/lib/pyspark.zip/pyspark/worker.py", line 98, in main
command = pickleSer._read_with_length(infile)
File "/usr/hdp/2.4.2.0-258/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 164, in _read_with_length
return self.loads(obj)
File "/usr/hdp/2.4.2.0-258/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 422, in loads
return pickle.loads(obj)
File "/usr/lib/python2.7/site-packages/six.py", line 118, in __getattr__
_module = self._resolve()
File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve
return _import_module(self.mod)
File "/usr/lib/python2.7/site-packages/six.py", line 118, in __getattr__
_module = self._resolve()
File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve
return _import_module(self.mod)
File "/usr/lib/python2.7/site-packages/six.py", line 118, in __getattr__
_module = self._resolve()
.
.
.
RuntimeError: maximum recursion depth exceeded
</code></pre>
<p>I get the same error when I use pyspark or when I use spark-submit directly.</p>
<p>I tried to increase the recursion limit to 50000 (even though it is probably not the root-cause), but it didn't help.</p>
<p>Since the error is with the <strong><em>six</em></strong> package, I thought that python 3 may fix it, but I didn't try it yet since it may require adjustments in our production environment (would be better if we can avoid it). </p>
<p>Should python 3 work better with pyspark? (I know it works well with TensorFlow) </p>
<p>Any idea of how to make it work with python 2?</p>
<p>I am running TensorFlow 0.9.0 Spark 1.6.1 in HortonWorks cluster on RHEL 7.2 with python 2.7.5.</p>
<p>Thanks</p>
<h3>Update:</h3>
<p>Tried it with python 3.5 - getting the same exception. So apparently upgrading to python 3 is not a possible workaround.</p>
| 2 | 2016-08-02T09:25:45Z | 38,723,690 | <p>I finally realised that the root-cause is the six module itself - it has some compatibility issues with spark, and whenever it is loaded there are problems.</p>
<p>Therefore, to solve the issue I searched for all the usages of the <strong><em>six</em></strong> package in the demo, and replaced them with an equivalent module from python 2 (for example, <em>six.moves.urllib.response</em> simply became <em>urllib2</em>). When all the occurrences of six are removed, the demo runs perfectly on Spark.</p>
| 4 | 2016-08-02T14:47:12Z | [
"python",
"apache-spark",
"tensorflow",
"pyspark"
] |
using pandas.read_csv to read certain columns | 38,716,643 | <p>I have a .csv file with three columns and many rows. I am trying to use pandas to read only the third column.</p>
<p>right now I have:</p>
<pre><code>import pandas as pd
pd.read_csv(r"C:\test.csv",usecols=(3))
</code></pre>
| 1 | 2016-08-02T09:28:32Z | 38,716,698 | <p>column indexing is zero based, pass <code>2</code> to read the third column:</p>
<pre><code>pd.read_csv(r"C:\test.csv",usecols=[2])
</code></pre>
| 2 | 2016-08-02T09:30:51Z | [
"python",
"csv",
"pandas"
] |
gloabl name cx not defined | 38,716,862 | <p>I wanna call an Oracle function returning an objectby using cx_Oracle`s cursor.callfunc(). But this is not working</p>
<p>Here you can see my code:</p>
<pre><code>import cx_Oracle
import json
import web
urls = (
"/", "index",
"/grid", "grid",
)
app = web.application(urls, globals(),web.profiler )
web.config.debug = True
connection = cx_Oracle.Connection("TEST_3D/limo1013@10.40.33.160:1521/sdetest")
typeObj = connection.gettype("MDSYS.SDO_GEOMETRY")
class index:
def GET(self):
return "hallo moritz "
class grid:
def GET(self):
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
cursor = connection.cursor()
cursor.arraysize = 10000 # default = 50
cursor.execute("""SELECT a.id AS building_nr, c.Geometry AS geometry, d.Classname FROM building a, THEMATIC_SURFACE b, SURFACE_GEOMETRY c, OBJECTCLASS d WHERE a.grid_id_400 = 4158 AND a.id = b.BUILDING_ID AND b.LOD2_MULTI_SURFACE_ID = c.ROOT_ID AND c.GEOMETRY IS NOT NULL AND b.OBJECTCLASS_ID = d.ID""")
obj = cursor.fetchone()
obj = obj[1]
print obj
cursor.callfunc("SDO2GEOJSON", cx.Oracle.OBJECT, [obj])
# Aufruf der App
if __name__ == "__main__":
app.run(web.profiler)
</code></pre>
<p>Error message:
<strong> at /grid
global name 'cx' is not defined</strong></p>
<p>But I am sure that cx_Oracle is correct installed. Furthermore I use import cx_Oracle at the beginning and this is working.</p>
<p>What is wrong?</p>
| 0 | 2016-08-02T09:38:22Z | 38,717,006 | <p>Simple typo. In the line</p>
<pre><code>cursor.callfunc("SDO2GEOJSON", cx.Oracle.OBJECT, [obj])
</code></pre>
<p>You should use <code>cx_Oracle.OBJECT</code></p>
| 1 | 2016-08-02T09:45:05Z | [
"python",
"web.py",
"cx-oracle"
] |
Python thread scope | 38,716,886 | <p>Both codes seem to have similar performance. How does the scope work in this case? Is any of them better than the other? Is there a better way to achieve the same behavior?</p>
<p>code 1:</p>
<pre><code>class ex:
b = 6
def foo(self, a):
def fooHandler(a):
while True:
print a
time.sleep(1)
threading.Thread(target=fooHandler, args=(a,)).start()
x = ex()
x.foo(10)
x.foo(100)
x.foo(1000)
</code></pre>
<p>code 2:</p>
<pre><code>class ex:
b = 6
def foo(self, a):
def fooHandler():
while True:
print a
time.sleep(1)
threading.Thread(target=fooHandler).start()
x = ex()
x.foo(10)
x.foo(100)
x.foo(1000)
</code></pre>
| 3 | 2016-08-02T09:39:40Z | 38,718,152 | <p>This has nothing to do with threading, it's just a matter of using a value from nested scope vs. passing it explicitly as an argument and using it from local scope.</p>
<p>It doesn't particularly matter which approach you use in this case; you're using the same value in either case. Looking it up in nested scope is more expensive, but only trivially so (it's essentially equivalent to a single <code>dict</code> lookup, where local scope lookups are closer to array access performance).</p>
<p>If you needed to change the binding of <code>a</code> during the function, you could not do so with implicit nested scope access (you'd have to use a different name), because you can't read and write from a nested scope variable in Python 2 (which lacks the <code>nonlocal</code> keyword). Using a different name (initially set to <code>a</code>) would be similar to accepting it as an argument in any event, so again, no major distinction.</p>
| 0 | 2016-08-02T10:37:48Z | [
"python",
"multithreading",
"scope"
] |
Python thread scope | 38,716,886 | <p>Both codes seem to have similar performance. How does the scope work in this case? Is any of them better than the other? Is there a better way to achieve the same behavior?</p>
<p>code 1:</p>
<pre><code>class ex:
b = 6
def foo(self, a):
def fooHandler(a):
while True:
print a
time.sleep(1)
threading.Thread(target=fooHandler, args=(a,)).start()
x = ex()
x.foo(10)
x.foo(100)
x.foo(1000)
</code></pre>
<p>code 2:</p>
<pre><code>class ex:
b = 6
def foo(self, a):
def fooHandler():
while True:
print a
time.sleep(1)
threading.Thread(target=fooHandler).start()
x = ex()
x.foo(10)
x.foo(100)
x.foo(1000)
</code></pre>
| 3 | 2016-08-02T09:39:40Z | 38,719,721 | <p>Well, there <strong>is</strong> a difference in the generated code (at least when using CPython 2.7.12):</p>
<pre><code>def runThread(a):
def threadFunc():
while True:
print a
time.sleep(1)
t = threading.Thread(target=threadFunc)
t.start()
</code></pre>
<p>Will issue a <code>LOAD_GLOBAL</code> opcode for <code>a</code> inside <code>threadFunc()</code> (output is from <code>inspect.dis.dis()</code>):</p>
<pre><code>8 9 LOAD_GLOBAL 1 (a)
</code></pre>
<p>while</p>
<pre><code>def runThread(a):
def threadFunc(a):
while True:
time.sleep(1)
t = threading.Thread(target=threadFunc, args=(a, ))
t.start()
</code></pre>
<p>will issue a <code>LOAD_FAST</code> opcode:</p>
<pre><code>8 9 LOAD_FAST 0 (a)
</code></pre>
<p>The <code>LOAD_FAST</code> happens, because the compiler knows that <code>a</code> is parameter and thus the lookup only needs to happen wrt. to the current namespace. <code>LOAD_FAST</code> (hence the name) is potentially faster than <code>LOAD_GLOBAL</code>, but if you need think about the differences in terms of performance, you probably shouldn't be using Python in the first place.</p>
<p>And yeah, everything screams "implementation detail" to me, too.</p>
<p>Scope-importing <code>a</code> from an outer scope gives you added flexibility, since you can still modify <code>a</code> even after the thread is already running. When passing <code>a</code> as parameter to the thread function, that possibility is more or less gone. In any case, I would consider the former an antipattern unless its <code>a</code> is the thread termination flag.</p>
| 1 | 2016-08-02T11:52:57Z | [
"python",
"multithreading",
"scope"
] |
Python Json Config 'Extended Interpolation' | 38,716,890 | <p>I am currently using the Python library configparser:</p>
<pre><code>from configparser import ConfigParser, ExtendedInterpolation
</code></pre>
<p>I find the ExtendedInterpolation very useful because it avoids the risk of having to reenter constants in multiple places.</p>
<p>I now have a requirement to use a Json document as the basis of the configuration as it provides more structure.</p>
<pre><code>import json
from collections import OrderedDict
def get_json_config(file):
"""Load Json into OrderedDict from file"""
with open(file) as json_data:
d = json.load(json_data, object_pairs_hook=OrderedDict)
return d
</code></pre>
<p>Does anyone have any suggestions as to the best way to implement configparser style ExtendedInterpolation? </p>
<p>For example if a node in the Json contains the value ${home_dir}/lumberjack this would copy root node home_dir and take value 'lumberjack'?</p>
| 2 | 2016-08-02T09:39:52Z | 38,843,138 | <p>Try to use <code>string.Template</code>. But I'm not sure whether it's your need. There is one package can do this may be. Bellow is what i should do. </p>
<p><code>config.json</code></p>
<pre><code>{
"home_dir": "/home/joey",
"class_path": "/user/local/bin",
"dir_one": "${home_dir}/dir_one",
"dir_two": "${home_dir}/dir_two",
"sep_path_list": [
"${class_path}/python",
"${class_path}/ruby",
"${class_path}/php"
]
}
</code></pre>
<p>python code:</p>
<pre><code>import json
from string import Template
with open("config.json", "r") as config_file:
config_content = config_file.read()
config_template = Template(config_content)
mid_json = json.loads(config_content)
config = config_template.safe_substitute(mid_json)
print config
</code></pre>
<p>This can substitute the defined key in json file.</p>
| 0 | 2016-08-09T06:00:53Z | [
"python",
"json",
"configparser"
] |
ImportError: DLL load failed: Le module spécifié est introuvable | 38,716,945 | <p>I use Python 3.5.2 32-bit on Windows 64-bit. I get this error when I execute the project which uses Scipy, Pandas and Numpy:</p>
<pre><code>Traceback (most recent call last):
import scipy.stats as stat
File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\site- packages\scipy\stats\__init__.py", line 344, in <module>
from .stats import *
File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\site- packages\scipy\stats\stats.py", line 173, in <module>
import scipy.special as special
File "C:\Users\Mohammed\AppData\Local\Programs\Python\Python35-32\lib\site-packages\scipy\special\__init__.py", line 636, in <module>
from ._ufuncs import *
File "scipy\special\_ufuncs.pyx", line 1, in init scipy.special._ufuncs (scipy\special\_ufuncs.c:36522)
ImportError: DLL load failed: Le module spécifié est introuvable.
</code></pre>
<p>I installed these packages:</p>
<ul>
<li>numpy-1.11.1+mkl-cp35-cp35m-win32.whl</li>
<li>scipy-0.18.0-cp35-cp35m-win32.whl</li>
</ul>
| 0 | 2016-08-02T09:42:14Z | 39,146,632 | <p>Open the most concerned .pyd file with <a href="http://www.dependencywalker.com/" rel="nofollow">dependency walker</a> (the file should be somewhere in <em>Python35-32\lib\site-packages\scipy\special\</em> ) to find which dll is missing and where it is expected to be.</p>
| 0 | 2016-08-25T13:26:14Z | [
"python",
"pandas",
"numpy",
"scipy"
] |
Python: how to access a class's attribute from a module | 38,717,058 | <p>I have a main file, which contains mainly the GUI(Tkinter code). A window which has <code>Label</code>, a <code>Text</code> area where text gets updated on users action and a <code>Button</code>.</p>
<pre><code># ~/main.py
import Tkinter
import buttonevent
from itertools import cycle
msglist = ['main_msg1\n', 'main_msg2\n', 'main_msg3\n', 'main_msg4\n']
class Root(object):
def __init__(self, master):
self.msglist = cycle(msglist)
self.master = master
self.frame1 = Tkinter.Frame(master)
self.frame1.pack()
Root.status = Tkinter.StringVar()
self.status_info = Tkinter.Label(self.frame1, textvariable=Root.status)
self.status_info.pack()
Root.status.set("Set by constructor")
self.frame2 = Tkinter.Frame(master)
self.frame2.pack()
Root.textinfo = Tkinter.Text(self.frame2, width=20, height=10)
Root.textinfo.insert(Tkinter.END, 'message 1')
Root.textinfo.config(font='Arial')
Root.textinfo.pack()
Root.textinfo.config(bg=master.cget('bg'), relief=Tkinter.SUNKEN)
Root.textinfo.configure(state='disabled')
self.frame3 = Tkinter.Frame(master)
self.frame3.pack()
self.button = Tkinter.Button(self.frame3, text='Ok', command=self.ok)
self.button.pack()
def ok(self):
text_info(self.msglist.next())
buttonevent.do_event()
buttonevent.do_stuff()
def text_info(msg):
Root.textinfo.configure(state='normal')
Root.textinfo.insert(Tkinter.END, msg)
Root.textinfo.see(Tkinter.END)
Root.textinfo.configure(state='disabled')
if __name__ == '__main__':
root = Tkinter.Tk()
main_window = Root(root)
root.mainloop()
</code></pre>
<p>The user actions are defined on a different file.</p>
<pre><code># ~/buttonevent.py
from itertools import cycle
import main
do_msg = ['do_msg1\n', 'do_msg2\n', 'do_msg3\n', 'do_msg4\n']
msg = cycle(do_msg)
def do_event():
# do something
main.text_info(msg.next())
def do_stuff():
# do something
print 'doing stuff'
</code></pre>
<p>Previously the code was on one single file, Now im trying to write it as a multiple file based on its functionality. Basically, when user does something a message will be displayed onto the <code>Text</code> area. Since the <code>Text</code> field displays message and has some commonality while every display/activity/update, i created a function for it as <code>text_info</code> in the main file. </p>
<p>Say if i want to send a different message on the <code>Text</code> field to update from a different file,.. for example from the <code>buttonevent.py</code> file how can i achieve it.</p>
<p>when i run it i get error as </p>
<pre><code>$ python main.py
do_msg1
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/miniconda2/lib/python2.7/lib-tk/Tkinter.py", line 1537, in __call__
return self.func(*args)
File "main.py", line 38, in ok
buttonevent.do_event()
File "/home/buttonevent.py", line 14, in do_event
main.text_info(xx)
File "/home/main.py", line 51, in text_info
Root.textinfo.configure(state='normal')
AttributeError: type object 'Root' has no attribute 'textinfo'
</code></pre>
<ol>
<li>How can i call a function in the main py-file from a different py-file.</li>
<li>what is the best way, Should i make use of a <code>class</code> or a <code>function</code> for the <code>text_info</code> in the <code>main.py</code> file</li>
<li>If this is not the right way to code, please correct me.</li>
</ol>
| 1 | 2016-08-02T09:47:27Z | 38,717,417 | <p>You can achieve what you want by giving a reference of the Root instance as a parameter to your functions:</p>
<p>Instead of assigning to the Root class:</p>
<pre><code>Root.status = Tkinter.StringVar()
</code></pre>
<p>Assign it to the Root instance:</p>
<pre><code>self.status = Tkinter.StringVar()
</code></pre>
<p>There is no reason for assigning it to Root class instead of to the instance self, because its ownership is part of the Root instance as well: it is the components of the Root instance (the Tkinter parts) that fire the event to update.
You could then give self as a parameter to your buttonevent:</p>
<pre><code>def ok(self):
text_info(self.msglist.next())
buttonevent.do_event(self)
buttonevent.do_stuff(self)
</code></pre>
<p>And you can then make text_info part of your class:</p>
<pre><code>class Root(object):
...
def text_info(self, msg):
self.textinfo.configure(state='normal')
self.textinfo.insert(Tkinter.END, msg)
self.textinfo.see(Tkinter.END)
</code></pre>
<p>And change the buttonevent to this:</p>
<pre><code>def do_event(root_instance):
# do something
root_instance.text_info(msg.next())
</code></pre>
| 1 | 2016-08-02T10:03:32Z | [
"python",
"tkinter",
"attributeerror"
] |
Python: how to access a class's attribute from a module | 38,717,058 | <p>I have a main file, which contains mainly the GUI(Tkinter code). A window which has <code>Label</code>, a <code>Text</code> area where text gets updated on users action and a <code>Button</code>.</p>
<pre><code># ~/main.py
import Tkinter
import buttonevent
from itertools import cycle
msglist = ['main_msg1\n', 'main_msg2\n', 'main_msg3\n', 'main_msg4\n']
class Root(object):
def __init__(self, master):
self.msglist = cycle(msglist)
self.master = master
self.frame1 = Tkinter.Frame(master)
self.frame1.pack()
Root.status = Tkinter.StringVar()
self.status_info = Tkinter.Label(self.frame1, textvariable=Root.status)
self.status_info.pack()
Root.status.set("Set by constructor")
self.frame2 = Tkinter.Frame(master)
self.frame2.pack()
Root.textinfo = Tkinter.Text(self.frame2, width=20, height=10)
Root.textinfo.insert(Tkinter.END, 'message 1')
Root.textinfo.config(font='Arial')
Root.textinfo.pack()
Root.textinfo.config(bg=master.cget('bg'), relief=Tkinter.SUNKEN)
Root.textinfo.configure(state='disabled')
self.frame3 = Tkinter.Frame(master)
self.frame3.pack()
self.button = Tkinter.Button(self.frame3, text='Ok', command=self.ok)
self.button.pack()
def ok(self):
text_info(self.msglist.next())
buttonevent.do_event()
buttonevent.do_stuff()
def text_info(msg):
Root.textinfo.configure(state='normal')
Root.textinfo.insert(Tkinter.END, msg)
Root.textinfo.see(Tkinter.END)
Root.textinfo.configure(state='disabled')
if __name__ == '__main__':
root = Tkinter.Tk()
main_window = Root(root)
root.mainloop()
</code></pre>
<p>The user actions are defined on a different file.</p>
<pre><code># ~/buttonevent.py
from itertools import cycle
import main
do_msg = ['do_msg1\n', 'do_msg2\n', 'do_msg3\n', 'do_msg4\n']
msg = cycle(do_msg)
def do_event():
# do something
main.text_info(msg.next())
def do_stuff():
# do something
print 'doing stuff'
</code></pre>
<p>Previously the code was on one single file, Now im trying to write it as a multiple file based on its functionality. Basically, when user does something a message will be displayed onto the <code>Text</code> area. Since the <code>Text</code> field displays message and has some commonality while every display/activity/update, i created a function for it as <code>text_info</code> in the main file. </p>
<p>Say if i want to send a different message on the <code>Text</code> field to update from a different file,.. for example from the <code>buttonevent.py</code> file how can i achieve it.</p>
<p>when i run it i get error as </p>
<pre><code>$ python main.py
do_msg1
Exception in Tkinter callback
Traceback (most recent call last):
File "/home/miniconda2/lib/python2.7/lib-tk/Tkinter.py", line 1537, in __call__
return self.func(*args)
File "main.py", line 38, in ok
buttonevent.do_event()
File "/home/buttonevent.py", line 14, in do_event
main.text_info(xx)
File "/home/main.py", line 51, in text_info
Root.textinfo.configure(state='normal')
AttributeError: type object 'Root' has no attribute 'textinfo'
</code></pre>
<ol>
<li>How can i call a function in the main py-file from a different py-file.</li>
<li>what is the best way, Should i make use of a <code>class</code> or a <code>function</code> for the <code>text_info</code> in the <code>main.py</code> file</li>
<li>If this is not the right way to code, please correct me.</li>
</ol>
| 1 | 2016-08-02T09:47:27Z | 38,718,635 | <p>All "Root." changed as "self."
main.py</p>
<pre><code># ~/main.py
import Tkinter
import buttonevent
from itertools import cycle
curwin=None
msglist = ['main_msg1\n', 'main_msg2\n', 'main_msg3\n', 'main_msg4\n']
class Root(object):
def __init__(self, master):
self.msglist = cycle(msglist)
self.master = master
self.frame1 = Tkinter.Frame(master)
self.frame1.pack()
self.status = Tkinter.StringVar()
self.status_info = Tkinter.Label(self.frame1, textvariable=self.status)
self.status_info.pack()
self.status.set("Set by constructor")
self.curmsg='message 1\n'
self.frame2 = Tkinter.Frame(master)
self.frame2.pack()
self.textinfo = Tkinter.Text(self.frame2, width=20, height=10)
self.textinfo.insert(Tkinter.END, 'message 1\n')
self.textinfo.config(font='Arial')
self.textinfo.pack()
self.textinfo.config(bg=master.cget('bg'), relief=Tkinter.SUNKEN)
self.textinfo.configure(state='disabled')
self.frame3 = Tkinter.Frame(master)
self.frame3.pack()
self.button = Tkinter.Button(self.frame3, text='Ok', command=self.ok) # "Ok" function defined for click event
self.button.pack()
def ok(self):
#self.text_info(buttonevent.curmsg)
self.textinfo.configure(state='normal')
self.textinfo.insert(Tkinter.END, buttonevent.curmsg) # get message from buttonevent.py and set for window. Fisrst clicking will get initalized curmsg value. if you want get value after click write buttonevent.do_event() above this codes.
self.textinfo.see(Tkinter.END)
self.textinfo.configure(state='disabled')
buttonevent.do_event() # calling buttonevent's do_event function so it means global message will be changed. next click you will see new value for message.
buttonevent.do_stuff()
if __name__ == '__main__':
root = Tkinter.Tk()
curwin=Root(root)
root.mainloop()
</code></pre>
<p>buttonevent.py</p>
<pre><code># ~/buttonevent.py
from itertools import cycle
import main
do_msg = ['do_msg1\n', 'do_msg2\n', 'do_msg3\n', 'do_msg4\n']
msg = cycle(do_msg)
curmsg=msg.next() # Add this variable to call main.py to first click event
def do_event():
# do something
global curmsg #to edit variable value you must call it as global
curmsg=msg.next() #Changing variable value for each click
#Removed text_info function from main.py it is not necessary.
def do_stuff():
# do something
print 'doing stuff'
</code></pre>
| 1 | 2016-08-02T11:02:14Z | [
"python",
"tkinter",
"attributeerror"
] |
Loop through file and execute an api request | 38,717,207 | <p>I'm trying to write a web service in Python (fairly new to it). I have acces to an API that wants an url in a specific format:</p>
<pre><code>http://api.company-x.com/api/publickey/string/0/json
</code></pre>
<p>It is not a problem to perform a GET-request one by one but I would like to do it in a batch. So I have a text-file with strings in it. For example:</p>
<pre><code>string1,
string2,
string3,
</code></pre>
<p>I would like to write a Python-script that iterates through that file, makes it in the specific format, performs the requests and writes the responses of the batch to a new text-file. I've read the docs of requests and it mentioned adding parameters to your url but it doesn't do it in the specific format I need for this API.</p>
<p>My basic code so far without the loop looks like this:</p>
<pre><code>import requests
r = requests.get('http://api.company-x.com/api/publickey/string/0/json')
print(r.url)
data = r.text
text_file = open("file.txt", "w")
text_file.write(data)
text_file.close()
</code></pre>
| 0 | 2016-08-02T09:53:54Z | 38,717,675 | <p>First open the file that has the strings,</p>
<pre><code>import requests
with open(filename) as file:
data = file.read()
split_data = data.split(',')
</code></pre>
<p>Then iterate through the list,</p>
<pre><code>for string in split_data:
r = requests.get(string)
(...your code...)
</code></pre>
<p>Is this what you wanted?</p>
| 0 | 2016-08-02T10:15:38Z | [
"python",
"api",
"loops",
"batch-file",
"for-loop"
] |
Loop through file and execute an api request | 38,717,207 | <p>I'm trying to write a web service in Python (fairly new to it). I have acces to an API that wants an url in a specific format:</p>
<pre><code>http://api.company-x.com/api/publickey/string/0/json
</code></pre>
<p>It is not a problem to perform a GET-request one by one but I would like to do it in a batch. So I have a text-file with strings in it. For example:</p>
<pre><code>string1,
string2,
string3,
</code></pre>
<p>I would like to write a Python-script that iterates through that file, makes it in the specific format, performs the requests and writes the responses of the batch to a new text-file. I've read the docs of requests and it mentioned adding parameters to your url but it doesn't do it in the specific format I need for this API.</p>
<p>My basic code so far without the loop looks like this:</p>
<pre><code>import requests
r = requests.get('http://api.company-x.com/api/publickey/string/0/json')
print(r.url)
data = r.text
text_file = open("file.txt", "w")
text_file.write(data)
text_file.close()
</code></pre>
| 0 | 2016-08-02T09:53:54Z | 38,763,885 | <p>I've played around some more and this is what I wanted:</p>
<pre><code>#requests to talk easily with API's
import requests
#to use strip to remove spaces in textfiles.
import sys
#two variables to squeeze a string between these two so it will become a full uri
part1 = 'http://api.companyx.com/api/productkey/'
part2 = '/precision/format'
#open the outputfile before the for loop
text_file = open("uri.txt", "w")
#open the file which contains the strings
with open('strings.txt', 'r') as f:
for i in f:
uri = part1 + i.strip(' \n\t') + part2
print uri
text_file.write(uri)
text_file.write("\n")
text_file.close()
#open a new file textfile for saving the responses from the api
text_file = open("responses.txt", "w")
#send every uri to the api and write the respsones to a textfile
with open('uri.txt', 'r') as f2:
for i in f2:
uri = i.strip(' \n\t')
batch = requests.get(i)
data = batch.text
print data
text_file.write(data)
text_file.write('\n')
text_file.close()
</code></pre>
| 0 | 2016-08-04T09:43:31Z | [
"python",
"api",
"loops",
"batch-file",
"for-loop"
] |
Get attributes from module imported with star | 38,717,337 | <p>A python script needs a per-user configuration to override (redefine) "default" assignments (e.g. <code>path = "local/path/"</code>) which could by done by importing a custom module's attributes with <code>from custom_settings import *</code>. I would like to output the ones that are being changed by the custom module.</p>
<p>From within <code>custom_settings</code> its attributes can be obtained with <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow"><code>dir()</code></a>, e.g. <code>", ".join( (a for a in dir() if not a.startswith("__") ) )</code>.
How can this be done from the importing script if the imported module attributes are bound to the existing namespace?</p>
| -1 | 2016-08-02T09:59:45Z | 38,717,890 | <p>This may not be the neatest solution, and it seems painfully redundant, but you could always simply:</p>
<pre><code>from custom_settings import *
import custom_settings
overridden = ", ".join(a for a in dir(custom_settings) if not a.startswith("__"))
</code></pre>
| 0 | 2016-08-02T10:26:22Z | [
"python",
"python-3.x",
"python-3.5"
] |
regex for markdown validator | 38,717,564 | <p>I've been developing a Telegram bot with CMS with Markdown support. The tags supported are</p>
<pre><code>*bold text*
_italic text_
`inline fixed-width code`
```text
pre-formatted fixed-width code block
```
</code></pre>
<p>the problem is when there is, say, an opening <code>*</code> tag and no closing <code>*</code> tag, the bot API breaks and refuses to send the message.</p>
<p>I'm not that much into regex, but is there a way to build a regex that validates all said tags when the message is constructed? or is there a ready-made markdown validator? </p>
<p>I tried python <code>markdown</code> lib, meaning to catch an exception from it, but it doesnt break when the tags are broken, it just leaves the incorrect tags untouched.</p>
| 1 | 2016-08-02T10:10:27Z | 38,717,900 | <p>To check if the line starts and ends with '*' try regex pattern</p>
<pre><code>> ^\*.*\*$
</code></pre>
| 0 | 2016-08-02T10:26:49Z | [
"python",
"regex",
"markdown"
] |
regex for markdown validator | 38,717,564 | <p>I've been developing a Telegram bot with CMS with Markdown support. The tags supported are</p>
<pre><code>*bold text*
_italic text_
`inline fixed-width code`
```text
pre-formatted fixed-width code block
```
</code></pre>
<p>the problem is when there is, say, an opening <code>*</code> tag and no closing <code>*</code> tag, the bot API breaks and refuses to send the message.</p>
<p>I'm not that much into regex, but is there a way to build a regex that validates all said tags when the message is constructed? or is there a ready-made markdown validator? </p>
<p>I tried python <code>markdown</code> lib, meaning to catch an exception from it, but it doesnt break when the tags are broken, it just leaves the incorrect tags untouched.</p>
| 1 | 2016-08-02T10:10:27Z | 38,718,913 | <p>This approach might suit your needs:</p>
<pre><code>import re
teststring="*hello*?Q@*()@(UE) World?@(EI)@EN *"
results=re.findall("^[*].*[*]$",teststring)
if not len(results)==1:
raise Exception
</code></pre>
<p>It assumes that a line starts with * and ends with *.
The _ and ' cases would follow a similar approach.
Because the ''' case includes newlines, use the DOTALL flag:</p>
<pre><code>re.findall("^[']{3}.*[']{3}$",teststring, re.DOTALL)
</code></pre>
| 0 | 2016-08-02T11:15:10Z | [
"python",
"regex",
"markdown"
] |
python rfc3161 verification failed but openssl verification is ok | 38,717,609 | <p>I am trying to get my content timestamped so I know when it was changed. First I used a shell script but I want to implement it in my python program. the shell script works fine for now but I can't get the python version to work for me.
This is the <strong>working</strong> shell version</p>
<pre><code>in_file='test_content'
out_file="${in_file}.tsr"
ts_server='http://time.certum.pl/'
openssl ts -query -data "$in_file" -sha1 -cert | curl -o "$out_file" -sSH 'Content-Type: application/timestamp-query' --data-binary @- "$ts_server"
openssl ts -verify -data "$in_file" -in "$out_file" -CAfile "/usr/lib/ssl/certs/Certum_Trusted_Network_CA.pem"
openssl ts -reply -in "$out_file" -text
</code></pre>
<p>I tried to mimic this with <a href="https://pypi.python.org/pypi/rfc3161" rel="nofollow">rfc3161 package</a> but the verification is not going as expected. This is the python code</p>
<pre><code>import rfc3161
cert = file('/usr/lib/ssl/certs/Certum_Trusted_Network_CA.pem').read()
rt = rfc3161.RemoteTimestamper('http://time.certum.pl/', certificate=cert)
data_to_sign = file('test_content').read()
print rt.timestamp(data=data_to_sign)
>>> (False, 'Bad signature')
</code></pre>
<p>I don't know what is wrong since both scripts should do the same thing. Can somebody give me a clue on what is wrong with the python version?</p>
| 0 | 2016-08-02T10:12:28Z | 38,784,069 | <p>The problem lies in the library <a href="https://pypi.python.org/pypi/rfc3161" rel="nofollow">rfc3161</a> that I used. It seems like the author does not include check for TSA authority certificate so I had to make a change to the library.</p>
<p>The changed code is in <code>api.py</code> in <code>check_timestamp</code> function. You have to change the code block for certificate loading with this one:</p>
<p><strong>EDIT:</strong>
The Certificate from the response should be validated against some certificate store. If you cannot validate it u should raise an Exception</p>
<pre><code>if certificate != "":
try:
certificate = X509.load_cert_der_string(encoder.encode(signed_data['certificates'][0][0]))
# YOU SHOULD VALIDATE THE CERTIFICATE AGAINST SOME CERTIFICATE STORE !!!!
if not validate_certificate(certificate): #NOTE: I am not ready with this function.
raise TypeError('The TSA returned certificate should be valid one')
except:
raise AttributeError("missing certificate")
else:
try:
certificate = X509.load_cert_string(certificate)
except:
certificate = X509.load_cert_der_string(certificate)
</code></pre>
<p><strong>EDIT2:</strong> for validation you can use the code described <a href="http://stackoverflow.com/a/4427081/1020127">here</a>:</p>
<p>Now the verification is working as expected.</p>
| 0 | 2016-08-05T07:57:15Z | [
"python",
"shell",
"ssl",
"trusted-timestamp"
] |
python rfc3161 verification failed but openssl verification is ok | 38,717,609 | <p>I am trying to get my content timestamped so I know when it was changed. First I used a shell script but I want to implement it in my python program. the shell script works fine for now but I can't get the python version to work for me.
This is the <strong>working</strong> shell version</p>
<pre><code>in_file='test_content'
out_file="${in_file}.tsr"
ts_server='http://time.certum.pl/'
openssl ts -query -data "$in_file" -sha1 -cert | curl -o "$out_file" -sSH 'Content-Type: application/timestamp-query' --data-binary @- "$ts_server"
openssl ts -verify -data "$in_file" -in "$out_file" -CAfile "/usr/lib/ssl/certs/Certum_Trusted_Network_CA.pem"
openssl ts -reply -in "$out_file" -text
</code></pre>
<p>I tried to mimic this with <a href="https://pypi.python.org/pypi/rfc3161" rel="nofollow">rfc3161 package</a> but the verification is not going as expected. This is the python code</p>
<pre><code>import rfc3161
cert = file('/usr/lib/ssl/certs/Certum_Trusted_Network_CA.pem').read()
rt = rfc3161.RemoteTimestamper('http://time.certum.pl/', certificate=cert)
data_to_sign = file('test_content').read()
print rt.timestamp(data=data_to_sign)
>>> (False, 'Bad signature')
</code></pre>
<p>I don't know what is wrong since both scripts should do the same thing. Can somebody give me a clue on what is wrong with the python version?</p>
| 0 | 2016-08-02T10:12:28Z | 38,809,586 | <p>python-rfc3161's author here. If bad signature is returned, it means that the certificate your declared for TSA is not the one that is really used for signing.</p>
<p>The patch provided by melanholly does not seem right to me, you should never use certificate bundled with a signature to check if you cannot verify its origin (using a PKI for example). It does not seem to be the case here.</p>
| 0 | 2016-08-06T23:26:49Z | [
"python",
"shell",
"ssl",
"trusted-timestamp"
] |
Python:Input images in a list with a for loop | 38,717,651 | <p>Is there a way to fill a list with Images through a for loop and if so how do I do that?If there is no way just show me a way to add variables through a for loop in a list and I'll take it from there</p>
| -1 | 2016-08-02T10:14:15Z | 38,717,715 | <p>Adding items to a list is straightforward</p>
<pre><code>>>> l = []
>>> for i in range(10):
... l.append(i)
...
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code></pre>
| 0 | 2016-08-02T10:18:01Z | [
"python",
"list",
"for-loop",
"image-processing"
] |
Make Matlab print the complex unit as "j" instead of "i" | 38,717,710 | <p>I want to print complex data to a text-file using Matlab. Afterwards I want to read the data using Python (via the open() function for example). However, Matlab prints the complex numbers like</p>
<blockquote>
<p>1+1i</p>
</blockquote>
<p>but Python would like it in the form</p>
<blockquote>
<p>1+1j</p>
</blockquote>
<p>How can I make Matlab print the complex unit as "j"? Or alternatively, how can I make Python accept "i" as the complex unit?</p>
| 0 | 2016-08-02T10:17:45Z | 38,718,685 | <p>As you're writing to a text-file, while not just do the conversion there?</p>
<p>Something like</p>
<pre><code>>> a=1+2i
a =
1.0000 + 2.0000i
>> sprintf('%f+%fj',real(a), imag(a))
ans =
1.000000+2.000000j
</code></pre>
<p>You can of course replace <code>sprintf</code> with <code>fprintf</code>.</p>
| 2 | 2016-08-02T11:04:17Z | [
"python",
"matlab",
"complex-numbers"
] |
Make Matlab print the complex unit as "j" instead of "i" | 38,717,710 | <p>I want to print complex data to a text-file using Matlab. Afterwards I want to read the data using Python (via the open() function for example). However, Matlab prints the complex numbers like</p>
<blockquote>
<p>1+1i</p>
</blockquote>
<p>but Python would like it in the form</p>
<blockquote>
<p>1+1j</p>
</blockquote>
<p>How can I make Matlab print the complex unit as "j"? Or alternatively, how can I make Python accept "i" as the complex unit?</p>
| 0 | 2016-08-02T10:17:45Z | 38,722,971 | <p>Could you use a regex replacement? Perhaps the one in MATLAB?</p>
<pre><code>newStr=regexprep(str,'([\d.]+\s*[+\-]\s*[\d.]+)i','$1j');
</code></pre>
| 0 | 2016-08-02T14:17:06Z | [
"python",
"matlab",
"complex-numbers"
] |
Raspberry Pi as iBeacon reciever | 38,718,022 | <p>I have to make a iBeacon reciever for my Raspberry Pi and I have tried to follow this guide: <a href="http://www.switchdoc.com/2014/08/ibeacon-raspberry-pi-scanner-python/" rel="nofollow">http://www.switchdoc.com/2014/08/ibeacon-raspberry-pi-scanner-python/</a></p>
<p>The problem is that when I try the command: sudo python testblescan.py</p>
<p>I get the following message: "python: can't open file 'testblescan.py': [Errno 2] No such file or directory"</p>
<p>I'm accessing the Raspberry Pi through PuTTY. If it helps solve my problem.</p>
| 0 | 2016-08-02T10:32:38Z | 38,718,648 | <p>If you followed the instructions exactly then <code>testblescan.py</code> should be in the <code>blescanner</code> sub-directory of your home directory. Try</p>
<pre><code>cd ~/blescanner
</code></pre>
<p>before you attempt to run the program. Then the Python interpreter should be able to find it.</p>
<p>If for some reason the program has ended up in another directory then you will need to <code>cd</code> to that instead.</p>
| 0 | 2016-08-02T11:02:52Z | [
"python",
"linux",
"bluetooth",
"ibeacon"
] |
Python matplot3d - plot two sets of data on the same 3D plot | 38,718,082 | <p>I`m trying to plot 2 sets of data on a single 3D plot.
What I expect to see is these two images on the same plot:
<a href="http://i.stack.imgur.com/YdSIP.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/YdSIP.jpg" alt="enter image description here"></a></p>
<p>The plot I am looking for is this: <a href="http://i.stack.imgur.com/c1i5Z.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/c1i5Z.jpg" alt="enter image description here"></a></p>
<p>I use Anaconda and Jupiter, matplotlib 1.5.1. </p>
<p>This is my code so far:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d as a3
import matplotlib.pyplot as plt
import cop
class var1:
def __init__(self,b1, b2):
self.pt1 = copy.deepcopy(b1)
self.pt2 = copy.deepcopy(b2)
self.cords = (
list(self.pt1 + [high]), # top-left
list(self.pt2 + [high]), # top-right
list(self.pt2 + [low]), # bottom-right
list(self.pt1 + [low]), # bottom-left
)
def drawFunction(self):
dataSet1 = a3.art3d.Poly3DCollection([self.cords])
dataSet1.set_color('firebrick')
dataSet1.set_edgecolor('k')
ax.add_collection3d(dataSet1) #If you comment out this line- var2 will be shown. I`m trying to show one on top of the other
var2(self.pt1, self.pt2, high, low).drawFunction()
class var2:
def __init__(self,b1, b2, high, low):
self.pt1 = copy.deepcopy(b1)
self.pt2 = copy.deepcopy(b2)
self.cords = (
list(self.pt1 + [(high/2) + (high/4)]), # top-left
list(self.pt2 + [(high/2) + (high/4)]), # top-right
list(self.pt2 + [(high/2) - (high/4)]), # bottom-right
list(self.pt1 + [(high/2) - (high/4)]), # bottom-left
)
def drawFunction(self):
dataSet2 = a3.art3d.Poly3DCollection([self.cords])
dataSet2.set_color('cornflowerblue')
dataSet2.set_edgecolor('k')
ax.add_collection3d(dataSet2)
high = 500
low = 0
fig = plt.figure()
ax = Axes3D(fig)
i = 0
while i<4:
if (i==0):
p1 = [0,200]
p2 = [0,0]
if (i==1):
p1 = [0,0]
p2 = [200,0]
if (i==2):
p1 = [200,0]
p2 = [200,200]
if (i==3):
p1 = [200,200]
p2 = [0,200]
var1(p1, p2).drawFunction()
i = i+1
ax.set_xlim(0,200)
ax.set_ylim(0, 200)
ax.set_zlim(0, 1000)
plt.show()
</code></pre>
| 0 | 2016-08-02T10:34:57Z | 38,748,271 | <p>Note, that in the example code both the figures are present, you can see it by changing the code in the following way <code>Poly3DCollection([self.cords],alpha=0.5)</code>. It's just that the <code>add_collection3d</code> draws one over the other, so you don't see both.</p>
<p>I didn't find a way to beat it, but you can look <a href="https://stackoverflow.com/questions/14824893/how-to-draw-intersecting-planes/14825951#14825951">here</a> for a possible workaround.</p>
<p>BTW, the code is missing <code>import copy</code> and <code>ax = a3.Axes3D(fig)</code> to work.</p>
| 0 | 2016-08-03T15:48:42Z | [
"python",
"matplotlib",
"plot"
] |
In DjangoRestFramework(DRF), name 'request' is not defined | 38,718,098 | <p>I'm making api that gets 'android or iphone' user's coordinates, and depend on that coordinates, makes 'post_list'(It means just post_list literally).</p>
<p>Using DRF i made my queryset(this queryset is for making 'post_list') like this</p>
<p><strong>views.py</strong></p>
<pre><code>from django.shortcuts import render
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.measure import D
from .models import Post
from django.http import HttpResponse
from blog.models import Post, Comment
from blog.serializers import PostSerializer, CommentSerializer
import django_filters
from rest_framework import filters, viewsets, generics
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated
class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self) :
#these are for getting user's coordinates.
lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
userpoint = GEOSGeometry('POINT(' + lat + ' ' + lon + ')', srid=4326)
#these is for making my post_list
result = []
i = 1
while i<50:
list_i = Post.objects.filter(point__distance_lte = (userpoint, D(km=i)))
result.extend(list_i)
if len(result) > 0:
result = result[:0]
break
i += 1
return self.result
</code></pre>
<p><strong>error traceback</strong></p>
<pre><code>Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/posts/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.sites',
'debug_toolbar',
'blog',
'rest_framework',
'rest_framework.authtoken',]
Installed Middleware:
['debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/viewsets.py" in view
87. return self.dispatch(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/rest_framework/mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "/home/keepair/djangogirls/blog/views.py" in get_queryset
28. lat = request.POST.get('user_lat', '13')
Exception Type: NameError at /posts/
Exception Value: name 'request' is not defined
</code></pre>
<p>I made these codes following <a href="http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/#tutorial-6-viewsets-routers" rel="nofollow">http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/#tutorial-6-viewsets-routers</a> , <a href="http://www.django-rest-framework.org/api-guide/viewsets/#api-reference" rel="nofollow">http://www.django-rest-framework.org/api-guide/viewsets/#api-reference</a></p>
<p>But i think i didn't understand fully docs at above</p>
<p>Please help me, what should i do to solve this?</p>
| 1 | 2016-08-02T10:35:30Z | 38,718,164 | <pre><code>lat = request.POST.get('user_lat', '13')
lon = request.POST.get('user_lon', '15')
</code></pre>
<p>should be:</p>
<pre><code>lat = self.request.POST.get('user_lat', '13')
lon = self.request.POST.get('user_lon', '15')
</code></pre>
| 2 | 2016-08-02T10:38:38Z | [
"python",
"django",
"django-rest-framework"
] |
Construct image from 4D list | 38,718,234 | <p>I have a list of size <code>(10,10,3,64)</code></p>
<p>This represents a list of 64 images of size <code>10x10x3</code></p>
<p>I want to create 1 image of size <code>80x80x3</code>, where each image is side by side. I am not sure exactly how to merge these axes to make sure that the image integrity holds.</p>
<p>Just an example, a signle image is </p>
<pre><code>myList[all][all][all][0]
</code></pre>
| 2 | 2016-08-02T10:42:01Z | 38,718,296 | <p>IIUC one way to solve it would be with reshaping and permuting dimensions.</p>
<p>1) Reshape to split the last dimension into two dimensions.</p>
<p>2) Transpose to bring the last two split dims come next to the first two dims).</p>
<p>3) Finally reshape again to merge the first two dims and next two dims into one dim each. </p>
<p>Thus, we would have an implementation like so -</p>
<pre><code>np.array(myList).reshape(10,10,3,8,8).transpose(0,3,1,4,2).reshape(80,80,3)
</code></pre>
| 3 | 2016-08-02T10:45:13Z | [
"python",
"list",
"python-2.7",
"numpy"
] |
Construct image from 4D list | 38,718,234 | <p>I have a list of size <code>(10,10,3,64)</code></p>
<p>This represents a list of 64 images of size <code>10x10x3</code></p>
<p>I want to create 1 image of size <code>80x80x3</code>, where each image is side by side. I am not sure exactly how to merge these axes to make sure that the image integrity holds.</p>
<p>Just an example, a signle image is </p>
<pre><code>myList[all][all][all][0]
</code></pre>
| 2 | 2016-08-02T10:42:01Z | 38,719,525 | <p>You could try this through <code>np.concatenate</code> and nested list comprehensions, e.g.:
</p>
<pre><code>arr = np.array(mylist)
arr2 = np.concatenate([ np.concatenate([arr[...,i + 8*j] for i in np.arange(8)],axis=0) for j in np.arange(8)],axis=1 )
print(arr2.shape)
</code></pre>
<p>gives</p>
<pre><code>(80, 80, 3)
</code></pre>
<p>The list comprehensions split the full array of images into individual images stored in lists of length 8, and the concatenate then forms an array from these lists where each image is stored sequentially. </p>
<p>Note. It should be relatively easy to change the way you want to tile your images too by just changing the numbers used. For example if you wanted a 12x4 tiling instead of 8x8</p>
<pre><code>arr2 = np.concatenate([ np.concatenate([arr[...,i + 12*j] for i in np.arange(12)],axis=0) for j in np.arange(4)],axis=1 )
</code></pre>
| 1 | 2016-08-02T11:44:03Z | [
"python",
"list",
"python-2.7",
"numpy"
] |
Comparing values of two dictionaries | 38,718,339 | <p>I have two dictionaries as follows:</p>
<pre><code>a = {1:2, 3:4, 5:6}
b = {1:5, 3:6, 7:1}
</code></pre>
<p>For every key in <code>a</code>, I want to check if the key exists in <code>b</code>, if so, I want to print the value of both keys, if it does not, I print <code>0</code> as the value of the key in <code>b</code>:</p>
<pre><code>for key in a.keys():
if key in b.keys():
print key, a[key], b[key]
else:
print key, a[key], '0'
</code></pre>
<p>The output would be:</p>
<pre><code>1 2 5
3 4 6
5 6 0
</code></pre>
<p>But, I also want to print the value of key in <code>b</code> if it does not exist in <code>a</code>, that is the opposite of the last statement, if key is in <code>b</code> but not in <code>a</code>, print the value of the key in <code>b</code> and <code>0</code> as the value of the key in <code>a</code>. The output would be:</p>
<pre><code>1 2 5
3 4 6
5 6 0
7 0 1
</code></pre>
<p>It should be simple but I can't figure out how I can do it. Thanks!</p>
| 1 | 2016-08-02T10:47:13Z | 38,718,418 | <p>Use dict <code>b</code>'s <code>get</code> method, supplying a default value for use when the key isn't found.</p>
<pre><code>for key in a:
print key, a[key], b.get(key, '0')
</code></pre>
| 0 | 2016-08-02T10:51:16Z | [
"python",
"dictionary"
] |
Comparing values of two dictionaries | 38,718,339 | <p>I have two dictionaries as follows:</p>
<pre><code>a = {1:2, 3:4, 5:6}
b = {1:5, 3:6, 7:1}
</code></pre>
<p>For every key in <code>a</code>, I want to check if the key exists in <code>b</code>, if so, I want to print the value of both keys, if it does not, I print <code>0</code> as the value of the key in <code>b</code>:</p>
<pre><code>for key in a.keys():
if key in b.keys():
print key, a[key], b[key]
else:
print key, a[key], '0'
</code></pre>
<p>The output would be:</p>
<pre><code>1 2 5
3 4 6
5 6 0
</code></pre>
<p>But, I also want to print the value of key in <code>b</code> if it does not exist in <code>a</code>, that is the opposite of the last statement, if key is in <code>b</code> but not in <code>a</code>, print the value of the key in <code>b</code> and <code>0</code> as the value of the key in <code>a</code>. The output would be:</p>
<pre><code>1 2 5
3 4 6
5 6 0
7 0 1
</code></pre>
<p>It should be simple but I can't figure out how I can do it. Thanks!</p>
| 1 | 2016-08-02T10:47:13Z | 38,718,420 | <p>If I understand correctly, you want to iterate through all keys from either dictionary, and print their values from the two dictionaries, using <code>'0'</code> if the key is missing from that dictionary. Something like this:</p>
<pre><code>for key in set(a)|set(b):
print key, a.get(key, '0'), b.get(key, '0')
</code></pre>
<p><code>set(a)|set(b)</code> is the union of the sets of keys from each dictionary (i.e. it is a collection of distinct keys from either dictionary).</p>
<p><code>dictionary.get(key, '0')</code> returns <code>'0'</code> if the key is missing from the dictionary.</p>
| 2 | 2016-08-02T10:51:31Z | [
"python",
"dictionary"
] |
Comparing values of two dictionaries | 38,718,339 | <p>I have two dictionaries as follows:</p>
<pre><code>a = {1:2, 3:4, 5:6}
b = {1:5, 3:6, 7:1}
</code></pre>
<p>For every key in <code>a</code>, I want to check if the key exists in <code>b</code>, if so, I want to print the value of both keys, if it does not, I print <code>0</code> as the value of the key in <code>b</code>:</p>
<pre><code>for key in a.keys():
if key in b.keys():
print key, a[key], b[key]
else:
print key, a[key], '0'
</code></pre>
<p>The output would be:</p>
<pre><code>1 2 5
3 4 6
5 6 0
</code></pre>
<p>But, I also want to print the value of key in <code>b</code> if it does not exist in <code>a</code>, that is the opposite of the last statement, if key is in <code>b</code> but not in <code>a</code>, print the value of the key in <code>b</code> and <code>0</code> as the value of the key in <code>a</code>. The output would be:</p>
<pre><code>1 2 5
3 4 6
5 6 0
7 0 1
</code></pre>
<p>It should be simple but I can't figure out how I can do it. Thanks!</p>
| 1 | 2016-08-02T10:47:13Z | 38,718,430 | <pre><code>for key in set(a.keys()) | set(b.keys()):
print key, a.get(key, 0), b.get(key,0)
</code></pre>
<p><code>|</code> means union in a set context. You can also convert the resulting set into a list and sort it before iterating.</p>
| 2 | 2016-08-02T10:51:52Z | [
"python",
"dictionary"
] |
For getting describe attributes checks in aws | 38,718,363 | <p>Here I am trying to get AWS limit check ids from <code>AWSLIMITCHECKER</code> module and from that I need to check <code>categorywise</code>.</p>
<p>This is my sample code:</p>
<pre><code>from awslimitchecker.checker import AwsLimitChecker
from awslimitchecker.trustedadvisor import TrustedAdvisor
#from awslimitchecker.services.base import _AwsService
res = TrustedAdvisor(all_services={},
region='my region',
account_id='myacct id',
account_role='my role'
)
</code></pre>
<p>Here I need to pass these params of all_services. What all do I need to pass in this dictionary? How can I get check ids using function <code>_get_limit_check_id</code>.</p>
<p>Here is the reference link for <code>awslimitchecker</code>: <a href="https://awslimitchecker.readthedocs.io/en/latest/_modules/awslimitchecker/trustedadvisor.html#TrustedAdvisor._get_limit_check_id" rel="nofollow">https://awslimitchecker.readthedocs.io/en/latest/_modules/awslimitchecker/trustedadvisor.html#TrustedAdvisor._get_limit_check_id</a> </p>
<p>I have checked boto api also,but whether is it possible to get check ids and checks of aws trusted advisor using awslimitcheckermodule itself?</p>
<p>Thanks in advance</p>
| -1 | 2016-08-02T10:48:19Z | 38,742,021 | <pre><code> Hi i have resolved this,but when i getting check ids it shows the following
</code></pre>
<p>error:</p>
<pre><code> mycode:
d = TrustedAdvisor(services,
region='myregion',
account_id='none',
account_role='none'
)
e = d._get_limit_check_id()
error:
File "/usr/lib/python2.6/site- packages/awslimitchecker/trustedadvisor.py", line 190, in _get_limit_check_id
checks = self.conn.describe_trusted_advisor_checks(
AttributeError: 'NoneType' object has no attribute 'describe_trusted_advisor_checks'
</code></pre>
| 0 | 2016-08-03T11:15:41Z | [
"python",
"amazon-web-services",
"aws-lib"
] |
py.test in Jenkins: No tests found in slack. Where I'm wrong? | 38,718,364 | <p>I keep receiving an error when run Build. py.tests in jenkins:</p>
<p>jenkins execute shell:</p>
<pre><code>#!/bin/sh
py.test tests || true
</code></pre>
<p>it starts. and after it finished I see next log:</p>
<pre><code> Started by user manny
Building in workspace /var/lib/jenkins/workspace/web-services tests
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://example.git # timeout=10
Fetching upstream changes from https://example.org/m.git
...
...
[web-services tests] $ /bin/sh /tmp/hudson1759686215204688979.sh
============================= test session starts ==============================
platform linux -- Python 3.5.1, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
rootdir: /var/lib/jenkins/workspace/web-services tests/tests, inifile:
plugins: asyncio-0.3.0
collected 99 items / 4 errors
tests/bll/test_action_manager.py ...... //here goes list of tests
...
===== 3 failed, 75 passed, 1 skipped, 20 xfailed, 4 error in 76.85 seconds =====
Finished: SUCCESS
</code></pre>
<p>jenkins notify Slack:</p>
<pre><code>web-services tests - #44 Back to normal after 19 min (</job/web-services%20tests/44/|Open>)
No Tests found.
</code></pre>
<p>No tests found. How to fix it?</p>
| 0 | 2016-08-02T10:48:20Z | 38,718,525 | <p>Run the same test manually (outside of Jenkins) and check the error there.
Could be a problem is test collection, or just a test failure itself.</p>
<p>Also: please post full logs so we can better check what is going on</p>
| 0 | 2016-08-02T10:56:45Z | [
"python",
"jenkins",
"slack"
] |
py.test in Jenkins: No tests found in slack. Where I'm wrong? | 38,718,364 | <p>I keep receiving an error when run Build. py.tests in jenkins:</p>
<p>jenkins execute shell:</p>
<pre><code>#!/bin/sh
py.test tests || true
</code></pre>
<p>it starts. and after it finished I see next log:</p>
<pre><code> Started by user manny
Building in workspace /var/lib/jenkins/workspace/web-services tests
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://example.git # timeout=10
Fetching upstream changes from https://example.org/m.git
...
...
[web-services tests] $ /bin/sh /tmp/hudson1759686215204688979.sh
============================= test session starts ==============================
platform linux -- Python 3.5.1, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
rootdir: /var/lib/jenkins/workspace/web-services tests/tests, inifile:
plugins: asyncio-0.3.0
collected 99 items / 4 errors
tests/bll/test_action_manager.py ...... //here goes list of tests
...
===== 3 failed, 75 passed, 1 skipped, 20 xfailed, 4 error in 76.85 seconds =====
Finished: SUCCESS
</code></pre>
<p>jenkins notify Slack:</p>
<pre><code>web-services tests - #44 Back to normal after 19 min (</job/web-services%20tests/44/|Open>)
No Tests found.
</code></pre>
<p>No tests found. How to fix it?</p>
| 0 | 2016-08-02T10:48:20Z | 38,718,568 | <p>Jenkins marks the build success/failed depending on the exit code. 0 is success, else failed.</p>
<p>Exitcode of Py.Test is 0 when there are no errors. When there are 1 or more errors, not 0 (maybe 1, no idea exactly).</p>
<p>Solution:</p>
<ul>
<li>Wrap your call into a seperate shellscript and ignore the exitcode</li>
<li>Change Jenkins job to <code>'your command || true'</code></li>
</ul>
| 1 | 2016-08-02T10:59:01Z | [
"python",
"jenkins",
"slack"
] |
py.test in Jenkins: No tests found in slack. Where I'm wrong? | 38,718,364 | <p>I keep receiving an error when run Build. py.tests in jenkins:</p>
<p>jenkins execute shell:</p>
<pre><code>#!/bin/sh
py.test tests || true
</code></pre>
<p>it starts. and after it finished I see next log:</p>
<pre><code> Started by user manny
Building in workspace /var/lib/jenkins/workspace/web-services tests
> git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://example.git # timeout=10
Fetching upstream changes from https://example.org/m.git
...
...
[web-services tests] $ /bin/sh /tmp/hudson1759686215204688979.sh
============================= test session starts ==============================
platform linux -- Python 3.5.1, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
rootdir: /var/lib/jenkins/workspace/web-services tests/tests, inifile:
plugins: asyncio-0.3.0
collected 99 items / 4 errors
tests/bll/test_action_manager.py ...... //here goes list of tests
...
===== 3 failed, 75 passed, 1 skipped, 20 xfailed, 4 error in 76.85 seconds =====
Finished: SUCCESS
</code></pre>
<p>jenkins notify Slack:</p>
<pre><code>web-services tests - #44 Back to normal after 19 min (</job/web-services%20tests/44/|Open>)
No Tests found.
</code></pre>
<p>No tests found. How to fix it?</p>
| 0 | 2016-08-02T10:48:20Z | 38,718,920 | <p>From the log, we can see that the python script has failed</p>
<p><strong><code>collected 99 items / 4 errors</code></strong></p>
<p>And from Jenkins point of view, if any error is encountered, it will give failure as Jenkins uses <code>/bin/sh -xe</code> by default.</p>
<p>So by adding the <code>#!/bin/sh</code> before calling the python script might help in resolving this issue :</p>
<pre><code> #!/bin/sh
py.test tests
</code></pre>
| 0 | 2016-08-02T11:15:31Z | [
"python",
"jenkins",
"slack"
] |
State of Response object 'dead' while using livy with python | 38,718,448 | <p>I am trying to use livy, it is my first time with a REST api as well. Following the <a href="https://github.com/cloudera/livy" rel="nofollow">tutorial</a>, when I type</p>
<p><code>r = requests.post(statements_url, data=json.dumps(data), headers=headers)</code> </p>
<p>and then</p>
<p><code>r.json()</code></p>
<p>I receive as ouput <code>u'java.lang.IllegalStateException: Session is in state dead'</code>. According to the tutorial, the session state should be iddle, but it seems to change to dead after is done with starting. I don't know what should I do to keep the state in <code>iddle</code> so I can make post request.</p>
<p>In the console where the server is running, I receive the following output <code>16/08/02 12:37:18 ERROR SessionServlet$: internal error java.lang.IllegalStateException: Session is in state dead</code></p>
| 0 | 2016-08-02T10:52:51Z | 38,720,983 | <p>After several attempts, I realized that I am running spark with scala 2.11, and Livy only supports Scala 2.10.</p>
| 0 | 2016-08-02T12:52:41Z | [
"python",
"rest",
"cloudera",
"hue"
] |
Django Rest Framework owner permissions | 38,718,454 | <p>I use Django Rest Framework and in my one of my viewsets class I have <strong>partial_update</strong> method (PATCH) for update my user profile. I want to create a permission for one user can update <strong><em>only his profile</em></strong>.</p>
<pre><code>class ProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows profiles to be viewed, added,
deleted or edited
"""
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch']
def get_queryset(self):
user = self.request.user
return self.queryset.filter(user=user)
def get_serializer_class(self):
if self.action == 'list':
return ListingMyProfileSerializer
if self.action == 'retrieve':
return ListingMyProfileSerializer
if self.action == 'update':
return ProfileSerializer
return ProfileSerializer
def get_permissions(self):
# Your logic should be all here
if self.request.method == 'GET':
self.permission_classes = (IsAuthenticated,)
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsOwnerOrReject)
return super(ProfileViewSet, self).get_permissions()
def partial_update(self, request, pk=None):
...
...
</code></pre>
<p>Now one user can update his profile and any other profile.
I tried to create a permission class: <strong>IsOwnerOrReject</strong> but I don't know exactly what I must to do.
Thanks for helping :D</p>
<p><strong>SOLVED:</strong></p>
<p><em>permissions.py</em> class:</p>
<pre><code>class IsUpdateProfile(permissions.BasePermission):
def has_permission(self, request, view):
# can write custom code
print view.kwargs
try:
user_profile = Profile.objects.get(
pk=view.kwargs['pk'])
except:
return False
if request.user.profile == user_profile:
return True
return False
</code></pre>
<p><em>views.py</em>:</p>
<pre><code> class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch', 'delete']
...
def get_permissions(self):
...
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsUpdateProfile)
return super(ProfileViewSet, self).get_permissions()
def partial_update(self, request, pk=None):
...
</code></pre>
| 1 | 2016-08-02T10:53:15Z | 38,718,896 | <p>You can add a custom permission that checks whether it's his own profile. Something like this.</p>
<pre><code># permissions.py
from rest_framework import permissions
class OwnProfilePermission(permissions.BasePermission):
"""
Object-level permission to only allow updating his own profile
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# obj here is a UserProfile instance
return obj.user == request.user
# views.py
class ProfileViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated, OwnProfilePermission,)
</code></pre>
<p>UPDATE: You can remove the <code>def get_permissions(self):</code> part.</p>
<p>You can check the <a href="http://www.django-rest-framework.org/api-guide/permissions/" rel="nofollow">documentation</a> for more info.</p>
| 0 | 2016-08-02T11:14:09Z | [
"python",
"django",
"api",
"permissions",
"django-rest-framework"
] |
Django Rest Framework owner permissions | 38,718,454 | <p>I use Django Rest Framework and in my one of my viewsets class I have <strong>partial_update</strong> method (PATCH) for update my user profile. I want to create a permission for one user can update <strong><em>only his profile</em></strong>.</p>
<pre><code>class ProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows profiles to be viewed, added,
deleted or edited
"""
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch']
def get_queryset(self):
user = self.request.user
return self.queryset.filter(user=user)
def get_serializer_class(self):
if self.action == 'list':
return ListingMyProfileSerializer
if self.action == 'retrieve':
return ListingMyProfileSerializer
if self.action == 'update':
return ProfileSerializer
return ProfileSerializer
def get_permissions(self):
# Your logic should be all here
if self.request.method == 'GET':
self.permission_classes = (IsAuthenticated,)
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsOwnerOrReject)
return super(ProfileViewSet, self).get_permissions()
def partial_update(self, request, pk=None):
...
...
</code></pre>
<p>Now one user can update his profile and any other profile.
I tried to create a permission class: <strong>IsOwnerOrReject</strong> but I don't know exactly what I must to do.
Thanks for helping :D</p>
<p><strong>SOLVED:</strong></p>
<p><em>permissions.py</em> class:</p>
<pre><code>class IsUpdateProfile(permissions.BasePermission):
def has_permission(self, request, view):
# can write custom code
print view.kwargs
try:
user_profile = Profile.objects.get(
pk=view.kwargs['pk'])
except:
return False
if request.user.profile == user_profile:
return True
return False
</code></pre>
<p><em>views.py</em>:</p>
<pre><code> class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch', 'delete']
...
def get_permissions(self):
...
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsUpdateProfile)
return super(ProfileViewSet, self).get_permissions()
def partial_update(self, request, pk=None):
...
</code></pre>
| 1 | 2016-08-02T10:53:15Z | 38,718,998 | <p>IsOwnerOrReject is permission class that match the user to current login user otherwise it rejects.</p>
<p>In your case you have to define custom permission class. Which check user is login for other profile what ever permission you want to apply. You can do it like this:</p>
<pre><code>class IsUpdateProfile(permissions.BasePermission):
def has_permission(self, request, view):
#### can write custom code
user = User.objects.get(pk=view.kwargs['id']) // get user from user table.
if request.user == user:
return True
## if have more condition then apply
if more_condition:
return True
return False
</code></pre>
| 1 | 2016-08-02T11:19:28Z | [
"python",
"django",
"api",
"permissions",
"django-rest-framework"
] |
What's convention for naming a class or method as "class" in Python? | 38,718,484 | <p>Let's say I have a class in Python like this:</p>
<pre><code>class Student:
def __init__(self, classs):
self.classs = classs
</code></pre>
<p>Now, what's convention for naming a parameter (and class property) <code>classs</code>? I saw <code>classs</code> as well as <code>klass</code> and I'm wondering: is there some convention for it? Didn't find it in PEP8.</p>
| 1 | 2016-08-02T10:55:03Z | 38,718,532 | <p>There isn't really a convention. I've seen - and probably used - <code>klass</code>, <code>_class</code>, and <code>cls</code>.</p>
| 1 | 2016-08-02T10:57:00Z | [
"python",
"naming-conventions",
"pep8"
] |
What's convention for naming a class or method as "class" in Python? | 38,718,484 | <p>Let's say I have a class in Python like this:</p>
<pre><code>class Student:
def __init__(self, classs):
self.classs = classs
</code></pre>
<p>Now, what's convention for naming a parameter (and class property) <code>classs</code>? I saw <code>classs</code> as well as <code>klass</code> and I'm wondering: is there some convention for it? Didn't find it in PEP8.</p>
| 1 | 2016-08-02T10:55:03Z | 38,718,583 | <p>PEP 8 advises to use a trailing underscore in that case: <code>class_</code>.</p>
<p>See <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow">https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles</a> for details:</p>
<blockquote>
<p>single_trailing_underscore_ : used by convention to avoid conflicts
with Python keyword, e.g.</p>
<p><code>Tkinter.Toplevel(master, class_='ClassName')</code></p>
</blockquote>
| 4 | 2016-08-02T10:59:56Z | [
"python",
"naming-conventions",
"pep8"
] |
Python twice opens a file if uses subprocess.Popen for run another script | 38,718,558 | <p>I have script test1.py (For example)</p>
<pre><code>import test2
def main():
f = open("File.txt")
test2.run()
while True:
pass
if __name__ == '__main__':
main()
</code></pre>
<p>And test2.py</p>
<pre><code>import subprocess, sys, os
def run():
# Self run
subprocess.Popen(['C:\\Windows\\System32\\cmd.exe', '/C', 'start',
sys.executable, os.path.abspath(__file__)])
def main():
while True:
pass
if __name__ == '__main__':
main()
</code></pre>
<p>The problem is that the startup of the second script re-open the file "File.txt". Why is the second script at startup opens the file?</p>
<pre><code>D:\test>Handle.exe File.txt
Handle v4.0
Copyright (C) 1997-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
python.exe pid: 9376 type: File 29C: D:\test\File.txt
python.exe pid: 9792 type: File 29C: D:\test\File.txt
</code></pre>
| 1 | 2016-08-02T10:58:37Z | 38,718,834 | <p>The child process inherits a file handle for compatibility with the Unix model (see <a href="https://www.python.org/dev/peps/pep-0446/#rationale" rel="nofollow">PEP 446</a> for more explanation). After the subprocess call, both the original and the new script should have access to the file; on Windows that means two separate file handles open.</p>
<p>A better idiom if you want to avoid this is to close the file before forking, either explicitly or using the <code>with</code> construct:</p>
<pre><code>with open('File.txt', 'r') as inputfile:
pass # or do something with inputfile
</code></pre>
| 1 | 2016-08-02T11:11:12Z | [
"python",
"subprocess",
"popen"
] |
Python twice opens a file if uses subprocess.Popen for run another script | 38,718,558 | <p>I have script test1.py (For example)</p>
<pre><code>import test2
def main():
f = open("File.txt")
test2.run()
while True:
pass
if __name__ == '__main__':
main()
</code></pre>
<p>And test2.py</p>
<pre><code>import subprocess, sys, os
def run():
# Self run
subprocess.Popen(['C:\\Windows\\System32\\cmd.exe', '/C', 'start',
sys.executable, os.path.abspath(__file__)])
def main():
while True:
pass
if __name__ == '__main__':
main()
</code></pre>
<p>The problem is that the startup of the second script re-open the file "File.txt". Why is the second script at startup opens the file?</p>
<pre><code>D:\test>Handle.exe File.txt
Handle v4.0
Copyright (C) 1997-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
python.exe pid: 9376 type: File 29C: D:\test\File.txt
python.exe pid: 9792 type: File 29C: D:\test\File.txt
</code></pre>
| 1 | 2016-08-02T10:58:37Z | 38,718,921 | <p>By the time you call <code>test2</code> your <code>test1</code> program has already opened the file. Therefore, when you create a subprocess that child process inherits any open files - including <code>File.txt</code>.</p>
<p>See the <a href="https://docs.python.org/2/library/subprocess.html#popen-constructor" rel="nofollow">notes on file inheritance</a> in the documentation for <code>subprocess</code>.</p>
| 1 | 2016-08-02T11:15:32Z | [
"python",
"subprocess",
"popen"
] |
Python text parsing and saving as html | 38,718,622 | <p>I've been playing around with Python trying to write a script to scan a directory for specific files, finding certain keywords and saving the lines where these keywords appear into a new file. I came up with this;</p>
<pre><code>import sys, os, glob
for filename in glob.glob("./*.LOG"):
with open(filename) as logFile:
name = os.path.splitext(logFile.name)[0]
newLOG = open(name + '_ERROR!'+'.LOG', "w")
allLines = logFile.readlines()
logFile.close()
printList = []
for line in allLines:
if ('ERROR' in line) or ('error' in line):
printList.append(line)
for item in printList:
# print item
newLOG.write(item)
</code></pre>
<p>This is all good but I thought I'd try instead saving this new file as html wrapping it all in the rights tags(html,head,body...) so that maybe I could change the font colour of the keywords. So far it looks like this;</p>
<pre><code>import sys, os, glob
for filename in glob.glob("./*.LOG"):
with open (filename) as logFile:
name = os.path.splitext(logFile.name)[0]
newLOG = open(name + '_ERROR!'+'.html', "w")
newLOG.write('<html>')
newLOG.write('<head>')
newLOG.write('<body><p>')
allLines = logFile.readlines()
logFile.close()
printList = []
for line in allLines:
if ('ERROR' in line) or ('error' in line):
printList.append(line)
for item in printList:
# print item
newLOG.write('</html>')
newLOG.write('</head>')
newLOG.write('</body><p>')
newLOG.write(item)
</code></pre>
<p>Now the problem is I'm new to this and I'm still trying to figure out how to work with indentations and loops.. Because my html tags are being appended from within the loop, every line has the <code><html></code>, <code><head></code> & <code><body><p></code> tag around them and it just looks wrong. I understand the problem and have tried rewriting things so that the tags are applied outside the loop but I've not had much success. </p>
<p>Could someone show me a better way of getting the file name of the current file, creating a new file+appending it as I think this is why I'm getting the file handling errors when trying to change how it all works.</p>
<p>Thanks</p>
| 0 | 2016-08-02T11:01:34Z | 38,719,058 | <p>It's a matter of indenting the lines to the right level. The HTML footer must be printed at the indentation level of the header lines, not indented within the loop. Try this:</p>
<pre><code>import sys, os, glob
import cgi
for filename in glob.glob("./*.LOG"):
name = os.path.splitext(filename)[0]
with open(filename, 'r') as logFile, open('%s_ERROR!.html' % name, 'w') as outfile:
outfile.write("<html>\n<head>\n</head>\n<body><p>")
allLines = logFile.readlines()
printList = []
for line in allLines:
if ('ERROR' in line) or ('error' in line):
printList.append(line)
for item in printList:
# Note: HTML-escape value of item
outfile.write(cgi.escape(item) + '<br>')
outfile.write("</p></body>\n</html>")
</code></pre>
<p>Note that you don't need to use printList - you could just emit the HTML code as you go through the log.</p>
<p>Consider breaking this into smaller functions for reusability and readability.</p>
| 1 | 2016-08-02T11:22:05Z | [
"python",
"html",
"loops"
] |
Python - How to loop through lines of multiple files | 38,718,714 | <p>I have 2 files: <code>"a.txt"</code> and <code>"b.txt"</code> where I want to match lines between them. The files contain the following:</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>To match the lines, I'm doing the following</p>
<pre><code> a = open("a.txt","r")
b = open("b.txt","r")
for al in a:
al = al.split()
val_a = al[0]
for bl in b:
bl = bl.split()
val_b = bl[0]
print val_a, val_b
</code></pre>
<p>Surprisingly, the print statement <code>ONLY</code> prints the following:</p>
<pre><code>1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
</code></pre>
<p>Which appears to be that the loop on a is only accessed once. What I tried for debugging is the following:</p>
<pre><code>for al in a:
al = al.split()
val_a = al[0]
print val_a
for bl in b:
bl = bl.split()
val_b = bl[0]
</code></pre>
<p>The print statement here prints all the values within <code>a</code></p>
<p>Can someone help me with a possible explanation?</p>
| 0 | 2016-08-02T11:05:51Z | 38,718,780 | <p>You can fetch <code>b</code> to a list of lines with <code>readlines()</code>, and then you can iterate over it again and again:</p>
<pre><code>a = open("a.txt","r")
b = open("b.txt","r").readlines()
for al in a:
al = al.split()
val_a = al[0]
for bl in b:
bl = bl.split()
val_b = bl[0]
print val_a, val_b
</code></pre>
| 3 | 2016-08-02T11:08:53Z | [
"python",
"file"
] |
Python - How to loop through lines of multiple files | 38,718,714 | <p>I have 2 files: <code>"a.txt"</code> and <code>"b.txt"</code> where I want to match lines between them. The files contain the following:</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>To match the lines, I'm doing the following</p>
<pre><code> a = open("a.txt","r")
b = open("b.txt","r")
for al in a:
al = al.split()
val_a = al[0]
for bl in b:
bl = bl.split()
val_b = bl[0]
print val_a, val_b
</code></pre>
<p>Surprisingly, the print statement <code>ONLY</code> prints the following:</p>
<pre><code>1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
</code></pre>
<p>Which appears to be that the loop on a is only accessed once. What I tried for debugging is the following:</p>
<pre><code>for al in a:
al = al.split()
val_a = al[0]
print val_a
for bl in b:
bl = bl.split()
val_b = bl[0]
</code></pre>
<p>The print statement here prints all the values within <code>a</code></p>
<p>Can someone help me with a possible explanation?</p>
| 0 | 2016-08-02T11:05:51Z | 38,718,793 | <p>Convert b as a list else first iteration through b will consume the file.</p>
<pre><code> blist= list(b)
</code></pre>
<p>Then the inner loop</p>
<pre><code>For bl in blist:
...
</code></pre>
| 0 | 2016-08-02T11:09:16Z | [
"python",
"file"
] |
Python - How to loop through lines of multiple files | 38,718,714 | <p>I have 2 files: <code>"a.txt"</code> and <code>"b.txt"</code> where I want to match lines between them. The files contain the following:</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>To match the lines, I'm doing the following</p>
<pre><code> a = open("a.txt","r")
b = open("b.txt","r")
for al in a:
al = al.split()
val_a = al[0]
for bl in b:
bl = bl.split()
val_b = bl[0]
print val_a, val_b
</code></pre>
<p>Surprisingly, the print statement <code>ONLY</code> prints the following:</p>
<pre><code>1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
</code></pre>
<p>Which appears to be that the loop on a is only accessed once. What I tried for debugging is the following:</p>
<pre><code>for al in a:
al = al.split()
val_a = al[0]
print val_a
for bl in b:
bl = bl.split()
val_b = bl[0]
</code></pre>
<p>The print statement here prints all the values within <code>a</code></p>
<p>Can someone help me with a possible explanation?</p>
| 0 | 2016-08-02T11:05:51Z | 38,718,816 | <p>You need to reset the file pointer to the start of the file for <code>b.txt</code> each time you attempt to loop through it, otherwise you've reached the end.</p>
<p>The easiest way to do this is with <code>file.seek(0)</code> as shown below:</p>
<pre><code>a = open("a.txt","r")
b = open("b.txt","r")
for al in a:
al = al.split()
val_a = al[0]
b.seek(0)
for bl in b:
bl = bl.split()
val_b = bl[0]
print val_a, val_b
</code></pre>
| 4 | 2016-08-02T11:10:33Z | [
"python",
"file"
] |
Python - How to loop through lines of multiple files | 38,718,714 | <p>I have 2 files: <code>"a.txt"</code> and <code>"b.txt"</code> where I want to match lines between them. The files contain the following:</p>
<pre><code>1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>To match the lines, I'm doing the following</p>
<pre><code> a = open("a.txt","r")
b = open("b.txt","r")
for al in a:
al = al.split()
val_a = al[0]
for bl in b:
bl = bl.split()
val_b = bl[0]
print val_a, val_b
</code></pre>
<p>Surprisingly, the print statement <code>ONLY</code> prints the following:</p>
<pre><code>1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
</code></pre>
<p>Which appears to be that the loop on a is only accessed once. What I tried for debugging is the following:</p>
<pre><code>for al in a:
al = al.split()
val_a = al[0]
print val_a
for bl in b:
bl = bl.split()
val_b = bl[0]
</code></pre>
<p>The print statement here prints all the values within <code>a</code></p>
<p>Can someone help me with a possible explanation?</p>
| 0 | 2016-08-02T11:05:51Z | 38,718,893 | <p>try this :</p>
<pre><code>a = open("a.txt","r")
b = open("b.txt","r")
for i,j in zip(a,b):
print (i.split())[0]
print (j.split())[0]
</code></pre>
| 0 | 2016-08-02T11:14:00Z | [
"python",
"file"
] |
pandas time-series data preprocessing | 38,718,774 | <p>I have dataframe look likes this :</p>
<pre><code>> dt
text timestamp
0 a 2016-06-13 18:00
1 b 2016-06-20 14:08
2 c 2016-07-01 07:41
3 d 2016-07-11 19:07
4 e 2016-08-01 16:00
</code></pre>
<p>And I want to summarise every month's data like:</p>
<pre><code>> dt_month
count timestamp
0 2 2016-06
1 2 2016-07
2 1 2016-08
</code></pre>
<p>the original dataset(<code>dt</code>) can be generated by:</p>
<pre><code>import pandas as pd
data = {'text': ['a', 'b', 'c', 'd', 'e'],
'timestamp': ['2016-06-13 18:00', '2016-06-20 14:08', '2016-07-01 07:41', '2016-07-11 19:07', '2016-08-01 16:00']}
dt = pd.DataFrame(data)
</code></pre>
<p>And are there any ways can plot a time-frequency plot by <code>dt_month</code> ?</p>
| 2 | 2016-08-02T11:08:33Z | 38,718,832 | <p>You can groupby by <code>timestamp</code> column converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_period.html" rel="nofollow"><code>to_period</code></a> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>:</p>
<pre><code>print (df.text.groupby(df.timestamp.dt.to_period('m'))
.size()
.rename('count')
.reset_index())
timestamp count
0 2016-06 2
1 2016-07 2
2 2016-08 1
</code></pre>
| 0 | 2016-08-02T11:11:08Z | [
"python",
"pandas",
"dataframe",
"time-series",
"visualization"
] |
Python Decorators - <Classname> object has no attribute '__name__' | 38,719,002 | <p>I have a tornado method like below and I tried to decorate method to cache stuff. I have the following setup</p>
<pre><code>def request_cacher(x):
def wrapper(funca):
@functools.wraps(funca)
@asynchronous
@coroutine
def wrapped_f(self, *args, **kwargs):
pass
return wrapped_f
return wrapper
class PhotoListHandler(BaseHandler):
@request_cacher
@auth_required
@asynchronous
@coroutine
def get(self):
pass
</code></pre>
<p>I am receiving the error, <code>AttributeError: 'PhotoListHandler' object has no attribute '__name__'</code>
Any ideas?</p>
| 0 | 2016-08-02T11:19:39Z | 38,720,698 | <p>i think this might work for you,</p>
<pre><code>import tornado.ioloop
import tornado.web
from tornado.gen import coroutine
from functools import wraps
cache = {}
class cached(object):
def __init__ (self, rule, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.rule = rule
cache[rule] = 'xxx'
def __call__(self, fn):
def newf(*args, **kwargs):
slf = args[0]
if cache.get(self.rule):
slf.write(cache.get(self.rule))
return
return fn(*args, **kwargs)
return newf
class MainHandler(tornado.web.RequestHandler):
@coroutine
@cached('/foo')
def get(self):
print "helloo"
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
</code></pre>
| 1 | 2016-08-02T12:40:55Z | [
"python",
"tornado",
"decorator",
"python-decorators",
"functools"
] |
Python Decorators - <Classname> object has no attribute '__name__' | 38,719,002 | <p>I have a tornado method like below and I tried to decorate method to cache stuff. I have the following setup</p>
<pre><code>def request_cacher(x):
def wrapper(funca):
@functools.wraps(funca)
@asynchronous
@coroutine
def wrapped_f(self, *args, **kwargs):
pass
return wrapped_f
return wrapper
class PhotoListHandler(BaseHandler):
@request_cacher
@auth_required
@asynchronous
@coroutine
def get(self):
pass
</code></pre>
<p>I am receiving the error, <code>AttributeError: 'PhotoListHandler' object has no attribute '__name__'</code>
Any ideas?</p>
| 0 | 2016-08-02T11:19:39Z | 38,720,779 | <p>Your code throws from <code>functools.wraps(funca)</code>, so <code>funca</code> must be a <code>PhotoListHandler</code> instance instead of a wrapped <code>get</code> method as you intend. I believe this means that the next decorator down the stack, <code>auth_required</code>, is written incorrectly: <code>auth_required</code> is returning <code>self</code> instead of returning a function.</p>
<p>While I'm here: stacking a cache on top of an authenticated function looks wrong to me. Won't the first authenticated user's photo list be cached and then shown to all subsequent users?</p>
| 0 | 2016-08-02T12:44:59Z | [
"python",
"tornado",
"decorator",
"python-decorators",
"functools"
] |
Python Decorators - <Classname> object has no attribute '__name__' | 38,719,002 | <p>I have a tornado method like below and I tried to decorate method to cache stuff. I have the following setup</p>
<pre><code>def request_cacher(x):
def wrapper(funca):
@functools.wraps(funca)
@asynchronous
@coroutine
def wrapped_f(self, *args, **kwargs):
pass
return wrapped_f
return wrapper
class PhotoListHandler(BaseHandler):
@request_cacher
@auth_required
@asynchronous
@coroutine
def get(self):
pass
</code></pre>
<p>I am receiving the error, <code>AttributeError: 'PhotoListHandler' object has no attribute '__name__'</code>
Any ideas?</p>
| 0 | 2016-08-02T11:19:39Z | 38,721,615 | <p>The issue is that you defined your <code>request_cacher</code> decorator as a decorator with arguments but you forgot to pass the argument!</p>
<p>Consider this code:</p>
<pre><code>import functools
def my_decorator_with_argument(useless_and_wrong):
def wrapper(func):
@functools.wraps(func)
def wrapped(self):
print('wrapped!')
return wrapped
return wrapper
class MyClass(object):
@my_decorator_with_argument
def method(self):
print('method')
@my_decorator_with_argument(None)
def method2(self):
print('method2')
</code></pre>
<p>When you try to use <code>method</code> in an instance you get:</p>
<pre><code>>>> inst = MyClass()
>>> inst.method # should be the wrapped function, not wrapper!
<bound method MyClass.wrapper of <bad_decorator.MyClass object at 0x7fed32dc6f50>>
>>> inst.method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bad_decorator.py", line 6, in wrapper
@functools.wraps(func)
File "/usr/lib/python2.7/functools.py", line 33, in update_wrapper
setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'MyClass' object has no attribute '__name__'
</code></pre>
<p>With the correct usage of the decorator:</p>
<pre><code>>>> inst.method2()
wrapped!
</code></pre>
<p>Alternative fix is remove one layer from the decorator:</p>
<pre><code>def my_simpler_decorator(func):
@functools.wraps(func)
def wrapped(self):
print('wrapped!')
return wrapped
class MyClass(object):
@my_simpler_decorator
def method3(self):
print('method3')
</code></pre>
<p>And you can see that it does not raise the error:</p>
<pre><code>>>> inst = MyClass()
>>> inst.method3()
wrapped!
</code></pre>
| 2 | 2016-08-02T13:20:05Z | [
"python",
"tornado",
"decorator",
"python-decorators",
"functools"
] |
select special elements in a list and compute conditional probabilities | 38,719,138 | <p>I need to compute the probability of a bigram given the existence of its corresponding unigrams in a list. The desired outcome is, for instance, in the following list, <code>'pretty girl', 'pretty', 'girl'</code> all exist. The probability is therefore, by using the values in list <code>P</code>, <code>(0.0017) % (0.003 * 0.002) = 5.999999999999987e-06</code> </p>
<pre><code>S = ['girl', 'pretty', 'pretty girl', 'our', 'our world', 'wide', 'word', 'yes', 'yike', 'yummy']
P = [0.003, 0.002, 0.0017, 0.003, 0.006, 0.004, 0.002, 0.012, 0.006, 0.003]
</code></pre>
<p>I have the following code. It doesn't seem to give me the results and therefore I cannot go ahead to compute the probabilities. What I am attempting to do with this code is to select bigrams in the list and find their corresponding unigrams. Then I plan to match their probabilities in <code>P</code>. </p>
<pre><code>In [60]: import re
In [61]: M = []
In [62]: for i in range(len(S)):
s_split = S[i].split()
s_split_len = len(S[i].split())
if s_split_len == 2:
m = []
a = re.match(s_split[0], S[i])
b = re.match(s_split[1], S[i])
m.append(a)
m.append(b)
M.append(m)
print M
[[<_sre.SRE_Match object at 0x10447b988>, None], [<_sre.SRE_Match object at 0x10447b8b8>, None], [<_sre.SRE_Match object at 0x10447b920>, None], [<_sre.SRE_Match object at 0x10447b9f0>, None], [<_sre.SRE_Match object at 0x10447bac0>, None], [<_sre.SRE_Match object at 0x10447bb90>, None], [<_sre.SRE_Match object at 0x10447bbf8>, None], [<_sre.SRE_Match object at 0x10447bc60>, None], [<_sre.SRE_Match object at 0x10447bcc8>, None], [<_sre.SRE_Match object at 0x10447bd30>, None], [<_sre.SRE_Match object at 0x10447bd98>, None], [<_sre.SRE_Match object at 0x10447be00>, None], [<_sre.SRE_Match object at 0x10447be68>, None], [<_sre.SRE_Match object at 0x10447bed0>, None], [<_sre.SRE_Match object at 0x10447bf38>, None], [<_sre.SRE_Match object at 0x1044a8030>, None], [<_sre.SRE_Match object at 0x1044a8098>, None], [<_sre.SRE_Match object at 0x1044a8100>, None], [<_sre.SRE_Match object at 0x1044a8168>, None], [<_sre.SRE_Match object at 0x1044a81d0>, None], [<_sre.SRE_Match object at 0x1044a8238>, None], [<_sre.SRE_Match object at 0x1044a82a0>, None], [<_sre.SRE_Match object at 0x1044a8308>, None], [<_sre.SRE_Match object at 0x1044a8370>, None], [<_sre.SRE_Match object at 0x1044a83d8>, None], [<_sre.SRE_Match object at 0x1044a8440>, None], [<_sre.SRE_Match object at 0x1044a84a8>, None], [<_sre.SRE_Match object at 0x1044a8510>, None], [<_sre.SRE_Match object at 0x1044a8578>, None], [<_sre.SRE_Match object at 0x1044a85e0>, None], [<_sre.SRE_Match object at 0x1044a8648>, None], [<_sre.SRE_Match object at 0x1044a86b0>, None], [<_sre.SRE_Match object at 0x1044a8718>, None]]
[[<_sre.SRE_Match object at 0x10447b988>, None], [<_sre.SRE_Match object at 0x10447b8b8>, None], [<_sre.SRE_Match object at 0x10447b920>, None], [<_sre.SRE_Match object at 0x10447b9f0>, None], [<_sre.SRE_Match object at 0x10447bac0>, None], [<_sre.SRE_Match object at 0x10447bb90>, None], [<_sre.SRE_Match object at 0x10447bbf8>, None], [<_sre.SRE_Match object at 0x10447bc60>, None], [<_sre.SRE_Match object at 0x10447bcc8>, None], [<_sre.SRE_Match object at 0x10447bd30>, None], [<_sre.SRE_Match object at 0x10447bd98>, None], [<_sre.SRE_Match object at 0x10447be00>, None], [<_sre.SRE_Match object at 0x10447be68>, None], [<_sre.SRE_Match object at 0x10447bed0>, None], [<_sre.SRE_Match object at 0x10447bf38>, None], [<_sre.SRE_Match object at 0x1044a8030>, None], [<_sre.SRE_Match object at 0x1044a8098>, None], [<_sre.SRE_Match object at 0x1044a8100>, None], [<_sre.SRE_Match object at 0x1044a8168>, None], [<_sre.SRE_Match object at 0x1044a81d0>, None], [<_sre.SRE_Match object at 0x1044a8238>, None], [<_sre.SRE_Match object at 0x1044a82a0>, None], [<_sre.SRE_Match object at 0x1044a8308>, None], [<_sre.SRE_Match object at 0x1044a8370>, None], [<_sre.SRE_Match object at 0x1044a83d8>, None], [<_sre.SRE_Match object at 0x1044a8440>, None], [<_sre.SRE_Match object at 0x1044a84a8>, None], [<_sre.SRE_Match object at 0x1044a8510>, None], [<_sre.SRE_Match object at 0x1044a8578>, None], [<_sre.SRE_Match object at 0x1044a85e0>, None], [<_sre.SRE_Match object at 0x1044a8648>, None], [<_sre.SRE_Match object at 0x1044a86b0>, None], [<_sre.SRE_Match object at 0x1044a8718>, None], [<_sre.SRE_Match object at 0x1044a8780>, None]]
</code></pre>
| 0 | 2016-08-02T11:25:24Z | 38,720,714 | <p>This works</p>
<pre><code>S = ['girl', 'pretty', 'pretty girl', 'our', 'our world', 'wide', 'world', 'yes', 'yike', 'yummy']
P = [0.003, 0.002, 0.0017, 0.003, 0.006, 0.004, 0.002, 0.012, 0.006, 0.003]
for i in range(len(S)):
s_split = S[i].split()
s_split_len = len(S[i].split())
if s_split_len == 2:
a = S.index(S[i])
b = S.index(S[i].split()[0])
c = S.index(S[i].split()[1])
if a != None:
if b != None:
co = [a, b, c]
probs = P[co[0]], P[co[1]], P[co[2]]
print S[i], probs[0] % (probs[1] * probs[2])
</code></pre>
| 0 | 2016-08-02T12:41:42Z | [
"python",
"string",
"loops",
"probability"
] |
Pyqt two buttons connect to method to set text in label | 38,719,142 | <p>I have two buttons and I would like to connect it to label to see text.</p>
<p>In __init__method i have:</p>
<pre><code>self.pushButton.clicked.connect(self.labeltext)
self.pushButton_2.clicked.connect(self.labeltext)
def labeltext(self):
if self.pushButton.clicked:
self.label.setText('A')
elif self.pushButton_2.clicked:
self.label.setText('B')
</code></pre>
<p>The problem is, if I click button number two, it label text with "A", which is defined under Pushbutton.</p>
| 1 | 2016-08-02T11:25:53Z | 38,719,618 | <p>If you use functools.partial, you can replace the connection lines as below. Also you can simplify labeltext function by adding a string parameter which is passed when the button is pushed.</p>
<pre><code>def labeltext(self, text):
self.label.setText(text)
self.pushButton.clicked.connect(partial(self.labeltext, 'A'))
self.pushButton_2.clicked.connect(partial(self.labeltext, 'B'))
</code></pre>
<p>If you don't like functools.partial, you can also use lambda as follows:</p>
<pre><code>self.pushButton_2.clicked.connect(lambda: self.labeltext('B'))
</code></pre>
| 1 | 2016-08-02T11:48:23Z | [
"python",
"pyqt5"
] |
Pyqt two buttons connect to method to set text in label | 38,719,142 | <p>I have two buttons and I would like to connect it to label to see text.</p>
<p>In __init__method i have:</p>
<pre><code>self.pushButton.clicked.connect(self.labeltext)
self.pushButton_2.clicked.connect(self.labeltext)
def labeltext(self):
if self.pushButton.clicked:
self.label.setText('A')
elif self.pushButton_2.clicked:
self.label.setText('B')
</code></pre>
<p>The problem is, if I click button number two, it label text with "A", which is defined under Pushbutton.</p>
| 1 | 2016-08-02T11:25:53Z | 38,719,844 | <p>You can accomplish this by using <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow"><code>partial</code></a>.</p>
<p>Using <code>partial</code>, you will pass the text you want displayed in your <code>.connect()</code>.</p>
<pre><code>qbtn1.clicked.connect(partial(self.labeltext, "A"))
qbtn2.clicked.connect(partial(self.labeltext, "B"))
</code></pre>
<p>You will also need to adjust the <code>labeltext</code> function signature to accept the text you wish to display. </p>
<pre><code>def labeltext(self, text)
</code></pre>
<p>instead of the standard</p>
<pre><code>def labeltext(self)
</code></pre>
<hr>
<p>A full demo looks like this (with code borrowed from <a href="http://zetcode.com/gui/pyqt4/firstprograms/" rel="nofollow">zetcode</a> for the quick samples):</p>
<pre><code>import sys
from PyQt4 import QtGui, QtCore
from functools import partial
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.lbl = QtGui.QLabel(self)
qbtn1 = QtGui.QPushButton('Set "A"', self)
qbtn2 = QtGui.QPushButton('Set "B"', self)
self.lbl.move(20, 100)
qbtn1.move(20,40)
qbtn2.move(20,60)
qbtn1.clicked.connect(partial(self.labeltext, "A"))
qbtn2.clicked.connect(partial(self.labeltext, "B"))
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Demo')
self.show()
def labeltext(self, text):
self.lbl.setText(text)
self.lbl.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
<hr>
<p>Notice that the function we are calling <code>labeltext</code> now takes two parameters - <code>self</code> and <code>text</code>. </p>
<p>When the application first launches, the label is empty:</p>
<p><a href="http://i.stack.imgur.com/Dmg95.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dmg95.png" alt="First open"></a></p>
<p>The label will change when each button is clicked:</p>
<p><a href="http://i.stack.imgur.com/SBfE9.png" rel="nofollow"><img src="http://i.stack.imgur.com/SBfE9.png" alt="Clicked A"></a><a href="http://i.stack.imgur.com/dUP2Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/dUP2Q.png" alt="Clicked B"></a></p>
| 1 | 2016-08-02T11:59:27Z | [
"python",
"pyqt5"
] |
Pyqt two buttons connect to method to set text in label | 38,719,142 | <p>I have two buttons and I would like to connect it to label to see text.</p>
<p>In __init__method i have:</p>
<pre><code>self.pushButton.clicked.connect(self.labeltext)
self.pushButton_2.clicked.connect(self.labeltext)
def labeltext(self):
if self.pushButton.clicked:
self.label.setText('A')
elif self.pushButton_2.clicked:
self.label.setText('B')
</code></pre>
<p>The problem is, if I click button number two, it label text with "A", which is defined under Pushbutton.</p>
| 1 | 2016-08-02T11:25:53Z | 38,725,276 | <p>You can use the <a href="http://doc.qt.io/qt-5/qobject.html#sender" rel="nofollow">sender()</a> method for this:</p>
<pre><code>def labeltext(self):
sender = self.sender()
if sender is self.pushButton:
self.label.setText('A')
elif sender is self.pushButton_2:
self.label.setText('B')
</code></pre>
| 1 | 2016-08-02T15:55:54Z | [
"python",
"pyqt5"
] |
Pandas: how to edit values in a column of a .csv file? | 38,719,184 | <p>I have a .csv file which looks as follows:<a href="http://i.stack.imgur.com/buFdW.png" rel="nofollow">link</a></p>
<p>I want to open this file using pandas and edit the column <strong>Coordinate</strong> by adding a constant value of 756 to each value in it. Finally, I want the changes to be reflected in the .csv file.</p>
<p>How do I do that?</p>
<p>Edit: What I had been doing is as follows (@EdChum):</p>
<pre><code>df = pd.read_csv('C:/TestBook1.csv')
df = df[['Coordinate','Speed']]
Coord = df['Coordinate']
Coord = Coord + 756
</code></pre>
<p>This is where I was going wrong. From here it would have been a messy affair to save changes into the .csv file.</p>
| 0 | 2016-08-02T11:27:51Z | 38,719,493 | <p>Define path where csv file is located </p>
<pre><code>Location = r'C:\\'
df = pd.read_csv(Location,header=None)
df["Coorinate"].values +756
</code></pre>
<p>Do not forget to import pandas package</p>
<pre><code>import pandas as pd
</code></pre>
| 0 | 2016-08-02T11:42:22Z | [
"python",
"pandas"
] |
Pandas: how to edit values in a column of a .csv file? | 38,719,184 | <p>I have a .csv file which looks as follows:<a href="http://i.stack.imgur.com/buFdW.png" rel="nofollow">link</a></p>
<p>I want to open this file using pandas and edit the column <strong>Coordinate</strong> by adding a constant value of 756 to each value in it. Finally, I want the changes to be reflected in the .csv file.</p>
<p>How do I do that?</p>
<p>Edit: What I had been doing is as follows (@EdChum):</p>
<pre><code>df = pd.read_csv('C:/TestBook1.csv')
df = df[['Coordinate','Speed']]
Coord = df['Coordinate']
Coord = Coord + 756
</code></pre>
<p>This is where I was going wrong. From here it would have been a messy affair to save changes into the .csv file.</p>
| 0 | 2016-08-02T11:27:51Z | 38,719,555 | <p>you can also type:</p>
<pre><code>df["Coordinate"] = df["Coordinate"] + 756
</code></pre>
| 0 | 2016-08-02T11:45:21Z | [
"python",
"pandas"
] |
Pandas: how to edit values in a column of a .csv file? | 38,719,184 | <p>I have a .csv file which looks as follows:<a href="http://i.stack.imgur.com/buFdW.png" rel="nofollow">link</a></p>
<p>I want to open this file using pandas and edit the column <strong>Coordinate</strong> by adding a constant value of 756 to each value in it. Finally, I want the changes to be reflected in the .csv file.</p>
<p>How do I do that?</p>
<p>Edit: What I had been doing is as follows (@EdChum):</p>
<pre><code>df = pd.read_csv('C:/TestBook1.csv')
df = df[['Coordinate','Speed']]
Coord = df['Coordinate']
Coord = Coord + 756
</code></pre>
<p>This is where I was going wrong. From here it would have been a messy affair to save changes into the .csv file.</p>
| 0 | 2016-08-02T11:27:51Z | 38,719,709 | <p>@EdChum: Thanks for your comment. It kind of fired me up. I was unnecessarily complicating things for myself. Following is what I did:</p>
<pre><code>df = pd.read_csv('C:/TestBook1.csv')
df = df[['Coordinate','Speed']]
df['Coordinate']+=756
df.to_csv('C:/TestBook1.csv')
</code></pre>
<p>Initially I was loading all the values of the column into a variable and trying to find a way to save it. After your comment I thought of experimenting and I am glad that it worked for me.</p>
| 0 | 2016-08-02T11:52:33Z | [
"python",
"pandas"
] |
AttributeError: 'Window' object has no attribute 'q' | 38,719,276 | <p>I'm trying to append a simple string to a list in and object. But I'm guessing the self keyword is interfereing with the pyqt window? </p>
<p>How can I work around this?</p>
<pre><code>class Window(qt.QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.CreateWidgets()
self.q = Qfetch.DataFetch()
def CreateWidgets(self):
toPortfolio = "str"
self.q.Portfolio.append(toPortfolio) #<---- This cause the error
</code></pre>
<p>q class</p>
<pre><code>class DataFetch():
def __init__(self):
self.Portfolio = []
</code></pre>
| 0 | 2016-08-02T11:32:22Z | 38,722,931 | <p>You are trying to fetch the member <strong>q</strong> before it is initialized. Call Qfetch.DataFetch() before self.CreateWidgets().</p>
<p>This code for the constructor should work:</p>
<pre><code>class Window(qt.QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.q = Qfetch.DataFetch()
self.CreateWidgets()
</code></pre>
| 4 | 2016-08-02T14:15:10Z | [
"python",
"pyqt"
] |
Not able to take screenshot of alert box in selenium using python | 38,719,337 | <p>I am new to selenium i want to take the screenshot of alert box whenever the alert is popped.
The code i have written is as below:</p>
<pre><code>import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoAlertPresentException
import time
class SearchXSS(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://testfire.net/")
ele = driver.find_element_by_name("txtSearch")
ele.send_keys("<script>alert(document.cookie)</script>")
ele.send_keys(Keys.RETURN)
try:
time.sleep(1)
alert = driver.switch_to_alert()
driver.get_screenshot_as_file('screenshot.png')
alert.accept()
except NoAlertPresentException as e:
print "no alert to accept "
fo.close()
def tearDown(self):
self.driver.quit()
if __name__=="__main__":
unittest.main()
</code></pre>
<p>I am facing the issue while taking the screenshot.The Error message is as below</p>
<blockquote>
<p>====================================================================== ERROR: test_search_in_python_org (<strong>main</strong>.SearchXSS)
---------------------------------------------------------------------- Traceback (most recent call last): File
"/home/user/programs/sele/testx.py", line 22, in
test_search_in_python_org
driver.get_screenshot_as_file('screenshot.png') File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py",
line 798, in get_screenshot_as_file
png = self.get_screenshot_as_png() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py",
line 817, in get_screenshot_as_png
return base64.b64decode(self.get_screenshot_as_base64().encode('ascii'))<br>
File
"/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py",
line 827, in get_screenshot_as_base64
return self.execute(Command.SCREENSHOT)['value'] File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py",
line 236, in execute
self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py",
line 191, in check_response
raise exception_class(message, screen, stacktrace, value['alert'].get('text')) UnexpectedAlertPresentException: Alert
Text: amSessionId=92632533494 Message: Unexpected modal dialog (text:
amSessionId=92632533494) Stacktrace:
at fxdriver.modals.closeUnhandledAlert/< (file:///tmp/tmpdnEJbt/extensions/fxdriver@googlecode.com/components/prompt-service.js:4745)
at (<a href="http://testfire.net/search.aspx?txtSearch=%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E:80" rel="nofollow">http://testfire.net/search.aspx?txtSearch=%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E:80</a>)</p>
<p>---------------------------------------------------------------------- Ran 1 test in 10.346s</p>
<p>FAILED (errors=1) [Finished in 10.4s with exit code 1]</p>
</blockquote>
<p>Help me out of this issue.</p>
| 1 | 2016-08-02T11:35:29Z | 38,719,648 | <p>You can not take <code>screenshot</code> with the <code>alert</code> box, you need to handle <code>alert</code> first means <code>accept</code> or <code>dismiss</code> then go to take screenshot because when selenium goes to take screenshot with alert present, it always throws the <code>UnexpectedAlertPresentException</code> as you are getting, <strong>It is not possible to take screenshot with the <code>alert</code> box using <code>selenium</code></strong>. So you need to do as below :-</p>
<pre><code>alert = driver.switch_to_alert()
alert.accept()
driver.get_screenshot_as_file('screenshot.png')
</code></pre>
<p>If you want to take screenshot with <code>alert</code>, you should try some different approach with some other library, In java there is <code>Robot</code> class present which be able to take <code>screenshot</code> in such type of scenario but I'm not sure what is the equivalent in python for this.</p>
| 0 | 2016-08-02T11:49:33Z | [
"python",
"selenium"
] |
ImportError: No module named 'pkg_resources.extern.six.moves'; 'pkg_resources.extern.six' is not a package | 38,719,356 | <p>I can not import pkg_resources. Whenever I tried it shows</p>
<pre><code>Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_resources
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/site-packages/pkg_resources/__init__.py", line 47, in <module>
from pkg_resources.extern.six.moves import urllib, map, filter
ImportError: No module named 'pkg_resources.extern.six.moves'; 'pkg_resources.extern.six' is not a package
</code></pre>
<p>Is <code>from pkg_resources</code> referring to <code>/usr/lib/python3.5/site-packages/pkg_resources/extern</code> (in which there is no six package). Can you point out what I am doing wrong?</p>
<p>I am using Arch Linux, Python 3.5.2</p>
| 1 | 2016-08-02T11:36:21Z | 38,779,433 | <p>Well, there is no <code>six</code> package there. <code>six</code> is just a name defined in</p>
<pre><code>/usr/lib/python3.5/site-packages/pkg_resources/extern/__init__.py
</code></pre>
<p>To be exact, it looks as follows:</p>
<pre><code>names = 'packaging', 'pyparsing', 'six'
VendorImporter(__name__, names).install()
</code></pre>
<p>But <code>VendorImporter</code> is a rather uncommon piece of <code>python</code>, it is part of <code>setuptools</code> therefore it can be expected, I guess. In simple words it performs the import from:</p>
<pre><code>/usr/lib/python3.5/site-packages/six.py
</code></pre>
<p>Which does contain <code>moves</code> alright:</p>
<pre><code>_MovedItems._moved_attributes = _moved_attributes
moves = _MovedItems(__name__ + ".moves")
_importer._add_module(moves, "moves")
</code></pre>
<hr>
<p>Now let's see how <code>pacman</code> deals with that:</p>
<pre><code># pacman -Qo /usr/lib/python3.5/site-packages/pkg_resources/extern/__init__.py
/usr/lib/python3.5/site-packages/pkg_resources/extern/__init__.py is owned by python-setuptools 1:25.1.3-1
</code></pre>
<p>Right, <code>extern/__init__.py</code> is owned by <code>setuptools</code>, that is what we expected. Now</p>
<pre><code># pacman -Qo /usr/lib/python3.5/site-packages/six.py
/usr/lib/python3.5/site-packages/six.py is owned by python-six 1.10.0-2
</code></pre>
<p>We see that <code>six</code> is part of <code>python-six</code>.</p>
<p>So, we discovered that <code>python-setuptools</code> is dependent on <code>python-six</code>. The <a href="https://www.archlinux.org/packages/extra/any/python-setuptools/" rel="nofollow"><code>python-setuptools</code> dependency chain</a> is therefore incorrect since it does not list <code>python-six</code>, that is something that happens sometimes with package managers (not only <code>pacman</code> but all package managers suffer from problems with dependency chains from time to time).</p>
<p>For the problem at hand, you need to install <code>python-six</code> manually, and <code>python-setuptools</code> will then work as expected:</p>
<pre><code>pacman -S python-six
</code></pre>
| 1 | 2016-08-05T00:34:15Z | [
"python",
"python-3.x",
"setuptools",
"archlinux"
] |
Scrapy yields only the last element | 38,719,489 | <p>I am scraping some courses/lessons with the help of <code>scrapy</code>, however it seems to yield only ever the <strong>last</strong> element of a list.<br>
Here's the code in question:</p>
<pre><code>def parse_course_list(self, response):
""" Scrape list of lessons for each course """
lessons = response.css('ul.lessons-list a')
for lesson in lessons:
title = lesson.xpath("text()").extract_first().strip()
link = lesson.xpath("@href").extract_first().strip()
url = response.urljoin(link)
item = response.meta['item']
item['Lesson'] = title
item['URL'] = link
yield scrapy.Request(url, \
callback=self.parse_lesson,
meta={'item': item} \
)
</code></pre>
<p>So basically I am scraping the lessons and yield a request for the details page. However, the lesson is always the same in the <code>parse_lesson</code> function.<br>
Am I missing something here completely?</p>
| 1 | 2016-08-02T11:42:14Z | 38,720,951 | <p>Ah... The classic pointer problem!</p>
<p>I'm not sure on why this happens besides that the requests you're yielding carry items with the same address on the stack.</p>
<p>Here is how you can solve it:</p>
<pre><code>def parse_course_list(self, response):
lessons = response.css('ul.lessons-list a')
itemToCopy = response.meta['item']
for lesson in lessons:
item=itemToCopy.copy()
...
</code></pre>
<p>The rest is just as it is minus the <code>item = response.meta['item']</code> obviously.</p>
<p>Tell me how it went.</p>
| 2 | 2016-08-02T12:51:21Z | [
"python",
"scrapy",
"scrapy-spider"
] |
wxFormBuilder and frame subclasses | 38,719,521 | <p>I have been trying to work with wxFrameBuilder to create subclasses of frames so I can call a subclass that inherits a lot of the main frame but overwrites part of the frame by replacing a panel.
Here is the wxFormBuilder generated test code.</p>
<pre><code> class MainMenu ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
bSizer59 = wx.BoxSizer( wx.VERTICAL )
self.m_panel53 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer60 = wx.BoxSizer( wx.HORIZONTAL )
self.m_staticText18 = wx.StaticText( self.m_panel53, wx.ID_ANY, u"Menu Title", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_staticText18.Wrap( -1 )
self.m_staticText18.SetFont( wx.Font( 20, 70, 90, 90, False, wx.EmptyString ) )
self.m_staticText18.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
bSizer60.Add( self.m_staticText18, 0, wx.ALL, 5 )
self.m_panel53.SetSizer( bSizer60 )
self.m_panel53.Layout()
bSizer60.Fit( self.m_panel53 )
bSizer59.Add( self.m_panel53, 1, wx.EXPAND |wx.ALL, 5 )
self.m_panel55 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer61 = wx.BoxSizer( wx.HORIZONTAL )
self.m_button22 = wx.Button( self.m_panel55, wx.ID_ANY, u"1", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer61.Add( self.m_button22, 0, wx.ALL, 5 )
bSizer61.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_button23 = wx.Button( self.m_panel55, wx.ID_ANY, u"2", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer61.Add( self.m_button23, 0, wx.ALL, 5 )
bSizer61.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_button24 = wx.Button( self.m_panel55, wx.ID_ANY, u"3", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer61.Add( self.m_button24, 0, wx.ALL, 5 )
self.m_panel55.SetSizer( bSizer61 )
self.m_panel55.Layout()
bSizer61.Fit( self.m_panel55 )
bSizer59.Add( self.m_panel55, 1, wx.EXPAND |wx.ALL, 5 )
self.SetSizer( bSizer59 )
self.Layout()
self.Centre( wx.BOTH )
def __del__( self ):
pass
class SubMenu ( MainMenu ):
def __init__( self, parent ):
MainMenu.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
bSizer59 = wx.BoxSizer( wx.VERTICAL )
self.m_panel55 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
self.m_panel55.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_ACTIVECAPTION ) )
bSizer61 = wx.BoxSizer( wx.HORIZONTAL )
self.m_button22 = wx.Button( self.m_panel55, wx.ID_ANY, u"one", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer61.Add( self.m_button22, 0, wx.ALL, 5 )
bSizer61.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_button23 = wx.Button( self.m_panel55, wx.ID_ANY, u"two", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer61.Add( self.m_button23, 0, wx.ALL, 5 )
bSizer61.AddSpacer( ( 0, 0), 1, wx.EXPAND, 5 )
self.m_button24 = wx.Button( self.m_panel55, wx.ID_ANY, u"three", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer61.Add( self.m_button24, 0, wx.ALL, 5 )
self.m_panel55.SetSizer( bSizer61 )
self.m_panel55.Layout()
bSizer61.Fit( self.m_panel55 )
bSizer59.Add( self.m_panel55, 1, wx.EXPAND |wx.ALL, 5 )
self.SetSizer( bSizer59 )
self.Layout()
self.Centre( wx.BOTH )
def __del__( self ):
pass
</code></pre>
<p>Here is the code I use to display the frames.</p>
<pre><code>import wx
from gui import *
class TopMenu(MainMenu):
def __init__(self, parent):
MainMenu.__init__(self, parent)
class SecondMenu(SubMenu):
def __init__(self, parent):
SubMenu.__init__(self, parent)
if __name__ == '__main__':
app = wx.App(0)
frame = SecondMenu(None)
frame.Centre()
frame.Show()
app.MainLoop()
</code></pre>
<p>Displaying the TopMenu(MainMenu) works fine but calling the SecondMenu(Submenu) class as above gives the following error.</p>
<pre><code>MainMenu.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
</code></pre>
<p>TypeError: <strong>init</strong>() got an unexpected keyword argument 'id'</p>
<p>This is a simplified recreated error.
Can anyone help?</p>
| 1 | 2016-08-02T11:43:54Z | 38,726,921 | <p><code>MainMenu.__init__</code> is defined like this:</p>
<pre><code>def __init__( self, parent ):
</code></pre>
<p>But you are calling it like this: </p>
<pre><code>MainMenu.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString,
pos = wx.DefaultPosition, size = wx.Size( 500,300 ),
style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
</code></pre>
<p>See the problem?</p>
| 1 | 2016-08-02T17:26:47Z | [
"python",
"python-2.7",
"wxpython",
"wx",
"wxformbuilder"
] |
Use x if z equals true else use z | 38,719,534 | <p>I need forLoop1 to use <code>y</code> if <code>z</code> equals 1 else use <code>x</code> and same for forLoop2 but reversed</p>
<p>my code:</p>
<pre><code>for z in range(3):
count=[0]*plys
for y in range(len(game)): #forLoop1
for x in range(len(game[y])): #forLoop2
for i in range(plys):
if game[y][x] == i+1:
count[i] += 1
for i in range(plys):
if count[i] >= 3:
print("Player " + str(i+1) + " is the winner")
count=[0]*plys
</code></pre>
<p>I tried something like this:</p>
<pre><code>for y if z == 0 else x in range(len(game)):
</code></pre>
<p>and:</p>
<pre><code>for (y if z == 0 else x) in range(len(game)):
</code></pre>
<p>But that didn't work</p>
<p>Any help would be greatly appreciated
and sorry if I'm bad at explaining it</p>
| 0 | 2016-08-02T11:44:33Z | 38,719,799 | <p>The <code>... if ... else ...</code> conditional expression produces an <em>expression</em>, you can't use it to man-handle the <code>for</code> loop index variable names like that.</p>
<p>But you <em>can</em> do this:</p>
<pre><code>for z in range(3):
count=[0]*plys
for k1 in range(len(game)): #forLoop1
for k2 in range(len(game)): #forLoop2
y, x = (k1, k2) if z == 1 else (k2, k1)
for i in range(plys):
if game[y][x] == i+1:
count[i] += 1
for i in range(plys):
if count[i] >= 3:
print("Player " + str(i+1) + " is the winner")
count=[0]*plys
</code></pre>
<p>However, it might be clearer if you just use a full <code>if... else</code> block:</p>
<pre><code>if z == 1:
y, x = k1, k2
else:
y, x = k2, k1
</code></pre>
| 1 | 2016-08-02T11:57:07Z | [
"python",
"python-3.x"
] |
How to set current user to be an attribute of the ModelForm? | 38,719,567 | <p>I have a form which creates a <code>Reservation</code> object. This object has a <code>customer = models.ForeignKey(User)</code> - which is a required attribute. </p>
<p>What to do to be able to create object using <code>ReservationCreationForm().save()</code>?</p>
<p>I've tried to overwrite save method:</p>
<pre><code>def save(self,user,*args,**kwargs):
self.customer = user
super(ReservationCreationForm).save()
</code></pre>
<p>so I could create a form with <code>request.user</code> attribute but it not works - Exception Value: </p>
<pre><code>'super' object has no attribute 'save'
</code></pre>
<p>What would you do?</p>
<p><strong>EDIT</strong></p>
<p>According to todor's answer, I've changed the save to </p>
<pre><code>def save(self,user,*args,**kwargs):
self.customer = user
super(ReservationCreationForm, self).save(*args, **kwargs)
</code></pre>
<p>Which solved problem with save() itself but it still does not add <code>user</code> to the <code>Reservation</code> so it raises Exception Value: </p>
<pre><code>va_app_reservation.customer_id may not be NULL
</code></pre>
| 0 | 2016-08-02T11:45:44Z | 38,719,722 | <p>Your are not calling the <code>.save</code> method correctly. <code>super</code> accepts a second argument which is the object instance.</p>
<pre><code>super(ReservationCreationForm, self).save(*args, **kwargs)
</code></pre>
<p>UPDATE</p>
<p>You are not setting <code>customer</code> to a <code>reservation instance</code>, but to a <code>form instance</code>, that's why your <code>reservation</code> object does not have a <code>customer</code>. </p>
<p>try with this one, (and don't forget the <code>return</code>):</p>
<pre><code>def save(self, user, *args,**kwargs):
self.instance.customer = user
return super(ReservationCreationForm, self).save(*args, **kwargs)
</code></pre>
| 1 | 2016-08-02T11:52:58Z | [
"python",
"django",
"django-forms"
] |
Get an error when installing virtualenv for flask | 38,719,628 | <p>I am learning to use flask for python web framework, however, when I try to <code>sudo easy_install virtualenv</code>, I get an error:</p>
<pre><code>[Errno 97] Address family not supported by protocol
</code></pre>
<p>how to solve this? My linux is CentOS release 4.3 (Final) and python version is 2.7.3</p>
| 0 | 2016-08-02T11:48:44Z | 38,720,003 | <p>You can install it from source package...</p>
<pre><code>$ curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-X.X.tar.gz
$ tar xvfz virtualenv-X.X.tar.gz
$ cd virtualenv-X.X
$ [sudo] python setup.py install
</code></pre>
| 1 | 2016-08-02T12:07:10Z | [
"python"
] |
Can't get BeautifulSoup to recognize columns correctly (Python, xml (Excel web) html file) | 38,719,764 | <p>I'm working with a number of files of this format (eliminated styling html):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<meta name="Generator" content="SAS Software Version 9.3, see www.sas.com">
<meta http-equiv="Content-type" content="charset=windows-1252">
</head>
<body>
<table class="table">
<colgroup>
<col>
<col>
<col>
<col>
</colgroup>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<td class="header" rowspan="2" colspan="4" scope="colgroup">&nbsp;</td>
<td class="header" colspan="2" scope="colgroup">SubDistrict</td>
</tr>
<tr>
<td class="header" scope="col">Title1
<br>
<br>
</td>
<td class="header" scope="col">Title2
<br>
<br>
</td>
</tr>
</thead>
<tbody>
<tr>
<td class="rowheader" rowspan="12" scope="rowgroup">M1</td>
<td class="rowheader" scope="row">1.1</td>
<td class="rowheader" scope="row">var1</td>
<td class="rowheader" scope="row">TOTAL</td>
<td class="data">7</td>
<td class="data">7</td>
</tr>
<tr>
etc...</code></pre>
</div>
</div>
</p>
<p>In the browser, they appear like this:</p>
<p><a href="http://i.stack.imgur.com/tIX8O.png" rel="nofollow"><img src="http://i.stack.imgur.com/tIX8O.png" alt="enter image description here"></a></p>
<p>And I've written the following in Beautiful Soup, which I'm brand new to:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>def read_xls(file):
f = open(file)
soup = BeautifulSoup(f.read(), 'html.parser')
table = soup.find_all('table')
#table[0].thead.find_all('tr')[1].td.get_text()
data = []
for tr in table[0].find_all('tr'):
temp = []
for td in tr.find_all('td'):
temp.append(td.get_text())
data.append(temp)
return pd.DataFrame(data)</code></pre>
</div>
</div>
</p>
<p>But my code is resulting in significant column alignment problems:</p>
<p><a href="http://i.stack.imgur.com/XACTy.png" rel="nofollow"><img src="http://i.stack.imgur.com/XACTy.png" alt="enter image description here"></a></p>
<p>Any advice on how to improve my BeautifulSoup code to parse this more correctly? Thanks.</p>
| 0 | 2016-08-02T11:55:09Z | 38,721,383 | <p>If I understood well this is what you wanted to extract:</p>
<p><a href="http://i.stack.imgur.com/qv7La.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/qv7La.jpg" alt="enter image description here"></a></p>
<p>You should be able to get it with the following code:</p>
<pre><code>def read_xls(file):
f = open(file)
soup = BeautifulSoup(f.read())
tbody = soup.find('tbody')
data = []
trs = tbody.findAll('tr')
for tr in trs:
tds = tr.findAll('td')
for td in tds:
data.append(td.text)
return pd.DataFrame(data).T
</code></pre>
| -1 | 2016-08-02T13:10:34Z | [
"python",
"parsing",
"xml-parsing",
"beautifulsoup",
"html-parsing"
] |
Not able to install scapy module in python | 38,720,118 | <p>I am using python version 2.7 and Pycharm IDE , I installed scapy module via pycharm UI (file --- default setting -- added scapy)</p>
<pre><code>from scapy.all import DNS
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/apple/Library/Python/2.7/lib/python/site-packages/scapy/all.py", line 16, in <module>
from arch import *
File "/Users/apple/Library/Python/2.7/lib/python/site-packages/scapy/arch/__init__.py", line 76, in <module>
from bsd import *
File "/Users/apple/Library/Python/2.7/lib/python/site-packages/scapy/arch/bsd.py", line 12, in <module>
from unix import *
File "/Users/apple/Library/Python/2.7/lib/python/site-packages/scapy/arch/unix.py", line 20, in <module>
from pcapdnet import *
File "/Users/apple/Library/Python/2.7/lib/python/site-packages/scapy/arch/pcapdnet.py", line 173, in <module>
import dnet
ImportError: No module named dnet
</code></pre>
<p>when I run above statement it shows above error , I installed scapy module successfully ...</p>
| -1 | 2016-08-02T12:13:06Z | 38,722,379 | <p>You have to install <code>libdnet</code></p>
<pre><code>$ wget http://libdnet.googlecode.com/files/libdnet-1.12.tgz
$ tar xfz libdnet-1.12.tgz
$ ./configure
$ make
$ sudo make install
$ cd python
$ python2.5 setup.py install
</code></pre>
<p>For 64 bit....</p>
<pre><code>$ CFLAGS='-arch i386 -arch x86_64' ./configure
$ archargs='-arch i386 -arch x86_64' make
</code></pre>
| 0 | 2016-08-02T13:51:05Z | [
"python",
"django",
"python-2.7",
"python-3.x",
"module"
] |
one if statement with unknown number of conditions python | 38,720,150 | <p>I have a list of list that contains all the conditions that the if statement has to satisfy, but the problem is that the number of conditions stored into the list of list is unknown. For e.g., the list of list is like this:</p>
<pre><code>my_list: [["A", "0"], ["B", "1"], ["C", "2"]]
</code></pre>
<p>so the if should be:</p>
<pre><code>if A==0 and B==1 and C==2:
#do-something
else:
pass
</code></pre>
<p>since I don't know the number of elements in the list of lists, <strong>I cannot do</strong>: </p>
<pre><code>if my_list[0][0]==my_list[0][1] and my_list[1][0]==my_list[1][1] and my_list[2][0]==my_list[2][1]:
#do-something
else:
pass
</code></pre>
<p>how do I solve this problem?</p>
<p>A similar problem has been raised <a href="http://stackoverflow.com/questions/28477072/good-architecture-for-one-if-statement-with-many-conditions">here</a> but there is no a clear explanation/implementation of this problem.</p>
<p>Thanks. </p>
| 2 | 2016-08-02T12:14:27Z | 38,720,186 | <p>You can use a <a href="https://www.python.org/dev/peps/pep-0289/"><em>generator expression</em></a> within <a href="https://docs.python.org/3.5/library/functions.html#all"><code>all()</code></a>:</p>
<pre><code>if all(i == j for i, j in my_list): # use int(j) if 'j' is string and 'i' is integer.
# do something
</code></pre>
| 5 | 2016-08-02T12:16:20Z | [
"python",
"if-statement"
] |
one if statement with unknown number of conditions python | 38,720,150 | <p>I have a list of list that contains all the conditions that the if statement has to satisfy, but the problem is that the number of conditions stored into the list of list is unknown. For e.g., the list of list is like this:</p>
<pre><code>my_list: [["A", "0"], ["B", "1"], ["C", "2"]]
</code></pre>
<p>so the if should be:</p>
<pre><code>if A==0 and B==1 and C==2:
#do-something
else:
pass
</code></pre>
<p>since I don't know the number of elements in the list of lists, <strong>I cannot do</strong>: </p>
<pre><code>if my_list[0][0]==my_list[0][1] and my_list[1][0]==my_list[1][1] and my_list[2][0]==my_list[2][1]:
#do-something
else:
pass
</code></pre>
<p>how do I solve this problem?</p>
<p>A similar problem has been raised <a href="http://stackoverflow.com/questions/28477072/good-architecture-for-one-if-statement-with-many-conditions">here</a> but there is no a clear explanation/implementation of this problem.</p>
<p>Thanks. </p>
| 2 | 2016-08-02T12:14:27Z | 38,720,291 | <p>I think @Kasramwd provides the most pythonic solution, but an alternative makes use of Python's <a href="http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html" rel="nofollow"><code>else</code> clause on a <code>for</code> loop</a>.</p>
<pre><code>for item in my_list:
if item[0] != item[1]:
break
else:
# do-something
</code></pre>
| 1 | 2016-08-02T12:21:26Z | [
"python",
"if-statement"
] |
Pandas - Datetime Manipulations Not Using Apply or Map | 38,720,173 | <p>You can convert pandas' datetime objects pretty easily using apply() on a column, but the issue I'm running into is that it is really slow. </p>
<p>I'm trying to develop another solution, but I keep running into a performance wall.</p>
<p>My current solution is:</p>
<pre><code>def modify_date2(x):
"""
applies datetime mask 1 of MM YYYY to the data
Example: 01 2016
"""
try:
if pd.isnull(x) == False:
return x.strftime('%m %Y')
else:
return pd.NaT
except:
return pd.NaT
df['columnname'] = df['columnname'].apply(modify_date2)
</code></pre>
<p>For roughly 700K records it is take 3 minutes and this is just a sub-set of my production dataset which is 23+ million records. You see my concern.</p>
<p>I was trying this out:</p>
<pre><code>df.ix[pd.notnull(df['sourcedt']), "sourcedt"] = \
datetime.fromtimestamp(mktime(df['sourcedt'].dt.timetuple()))
</code></pre>
<p>But I can't do the low level conversion on the 'Series' according to the error message I am getting. The query works fine, I can use pd.notnull() without an issue, but the setting of the value is my problem.</p>
<p>Any ideas on how I can speed things up?
My source data is being loaded using the pd.DataFrame.from_records().</p>
<p>I am using Pandas 0.16.1, Python 2.7.10</p>
<p>Thank you</p>
| 0 | 2016-08-02T12:15:43Z | 38,720,324 | <p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>dt.strftime</code></a>, dtype of <code>columnname</code> is <code>datetime</code>:</p>
<pre><code>print (df)
text columnname
0 a 2016-06-13 18:00:00
1 b NaT
2 c 2016-07-11 19:07:00
3 d 2016-07-11 19:07:00
4 e 2016-08-01 16:00:00
print (df['columnname'].dt.strftime('%m %Y'))
0 06 2016
1 NaT
2 07 2016
3 07 2016
4 08 2016
Name: columnname, dtype: object
</code></pre>
<p>If need first convert to datetime and some dates are corrupted use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>
<pre><code>df['columnname'] = pd.to_datetime(df['columnname'], errors='coerce').dt.strftime('%m %Y')
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'columnname': {0: '2016-06-13 18:00', 1: np.nan, 2: 'dd', 3: '2016-07-11 19:07', 4: '2016-08-01 16:00'}, 'text': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}})
print (df)
columnname text
0 2016-06-13 18:00 a
1 NaN b
2 dd c
3 2016-07-11 19:07 d
4 2016-08-01 16:00 e
df['columnname'] = pd.to_datetime(df['columnname'], errors='coerce').dt.strftime('%m %Y')
print (df)
columnname text
0 06 2016 a
1 NaT b
2 NaT c
3 07 2016 d
4 08 2016 e
</code></pre>
| 1 | 2016-08-02T12:22:44Z | [
"python",
"datetime",
"pandas"
] |
Python: String clustering with scikit-learn's dbscan, using Levenshtein distance as metric: | 38,720,283 | <p>I have been trying to cluster multiple datasets of URLs (around 1 million each), to find the original and the typos of each URL. I decided to use the levenshtein distance as a similarity metric, along with dbscan as the clustering algorithm as k-means algorithms won't work because I do not know the number of clusters.</p>
<p>I am facing some problems using Scikit-learn's implementation of dbscan.</p>
<p>This snippet below works on small datasets in the format I an using, but since it is precomputing the entire distance matrix, that takes O(n^2) space and time and is way too much for my large datasets. I have run this for many hours but it just ends up taking all the memory of my PC. </p>
<pre><code>lev_similarity = -1*np.array([[distance.levenshtein(w1[0],w2[0]) for w1 in words] for w2 in words])
dbscan = sklearn.cluster.DBSCAN(eps = 7, min_samples = 1)
dbscan.fit(lev_similarity)
</code></pre>
<p>So I figured I needed some way to compute the similarity on the fly and hence tried this method.</p>
<pre><code>dbscan = sklearn.cluster.DBSCAN(eps = 7, min_samples = 1, metric = distance.levenshtein)
dbscan.fit(words)
</code></pre>
<p>But this method ends up giving me an error:</p>
<pre><code>ValueError: could not convert string to float: URL
</code></pre>
<p>Which I realize means that its trying to convert the inputs to the similarity function to floats. But I don't want it to do that.
As far as I understand, it just needs a function that can take two arguments and return a float value that it can then compare to eps, which the levenshtein distance should do.</p>
<p>I am stuck at this point, as I do not know the implementation details of sklearn's dbscan to find why it is trying to convert it to float, and neither do I have any better idea on how to avoid the O(n^2) matrix computation. </p>
<p>Please let me know if there is any better or faster way to cluster these many strings that I may have overlooked.</p>
| 2 | 2016-08-02T12:20:55Z | 38,729,114 | <p>Try ELKI instead of sklearn.</p>
<p>It is the only tool I know that allows index accelerated DBSCAN with <em>any</em> metric.</p>
<p>It includes Levenshtein distance. You need to add an index to your database with <code>-db.index</code>. I always use the cover tree index (you need to choose the same distance for the index and for the algorithm, of course!)</p>
<p>You could use "pyfunc" distances and ball trees in sklearn, but performance was really bad because of the interpreter. Also, DBSCAN in sklearn is much more memory intensive.</p>
| 1 | 2016-08-02T19:38:51Z | [
"python",
"machine-learning",
"scikit-learn",
"cluster-analysis",
"levenshtein-distance"
] |
"ValueError: need more than 0 values to unpack" | 38,720,472 | <p>I have looked at the questions on here and none of them seem to help my cause. Essentially what I am doing is calling <code>getAllOpenChoices</code> to try and return a the value of the Radio button so when one is selected it saves.</p>
<p><strong>forms.py</strong></p>
<pre><code>def getAllOpenChoices():
listOpenChoice = [('All', 'All'), ('No One', 'No One'), ('Test','Test')]
all_choices = Requisition.objects.distinct()
for choices in all_choices:
temp = (Requisition.objects.filter(open_to=choices))
listOpenChoice.append(temp)
return tuple(listOpenChoice)
</code></pre>
<p>This error that I am getting is: </p>
<pre><code>ValueError: need more than 0 values to unpack
</code></pre>
<p><code>getAllOpenChoices</code> is being called:</p>
<pre><code>self.fields['open_to'] = forms.ChoiceField( choices = getAllOpenChoices, widget = forms.RadioSelect())
</code></pre>
| 1 | 2016-08-02T12:29:39Z | 38,720,696 | <p>The choices should be a list of 2-tuples, like your initial value <code>listOpenChoice</code></p>
<pre><code>listOpenChoice = [('All', 'All'), ('No One', 'No One'), ('Test','Test')]`
</code></pre>
<p>If you extend that list, you should only add 2-tuples. For example:</p>
<pre><code>listOpenChoice.append(('new', 'New'))
</code></pre>
<p>However, you are appending querysets, e.g. <code>Requisition.objects.filter(open_to=choices)</code>. This doesn't make sense. One of your querysets is empty, which is why you get the zero in the error message "need more than 0 values to unpack".</p>
<p>It's not clear to me what you're trying to append to the list, so I can't tell you how to fix your code. As long as you only append 2-tuples, you should be ok.</p>
| 1 | 2016-08-02T12:40:54Z | [
"python",
"django"
] |
Opening and reading several files in different directories | 38,720,527 | <p>I have a huge list of directories. With <code>/home</code> as my current directory, the highest level is the year. There are seven years: 2010, 2011, 2012, 2013, 2014, 2015 and 2016.</p>
<p>Then there are subdirectories for each month, so for instance <code>/home/2010/01</code>. There are, of course, twelve months, each one labeled as 01, 02, 03, ..., 11, 12.</p>
<p>For each month there is each day: 01, 02, ..., with as many days as the month has.</p>
<p>For each day there is a subdirectory always called <code>0700</code>. So, following the previous example we would be in <code>/home/2010/01/01/0700</code>.</p>
<p>And there is a file in such directory with data (tabular form). The name of the file reveals its date, for instance: <code>/home/2010/01/01/0700/pnw_20100101_TG.geo</code>.</p>
<p>I want to read the data in that files and load it to a pandas dataframe to filter outliers. I think I know how to do that, so let's put that apart, but the problem is that I can't read the files. <strong>This is what I have tried</strong>:</p>
<pre><code>import os
for root, dirs, files in os.walk("/home"):
for name in files:
f = open(name, 'r')
f.close
</code></pre>
<p>But I get the error message associated the opening of the file: <code>IOError: [Errno 2] No such file or directory: 'pnw_20100101_TG.geo'.</code> It seems that it does not recognize the file. But if I do, for instance, <code>print(os.path.join(root, name))</code> it correctly lists all the files.</p>
<p>What do you suggest to be able to open and read the files?</p>
<p>Thank you.</p>
| 0 | 2016-08-02T12:32:26Z | 38,720,681 | <p>You are opening the simple file name, but in nested folders it will not be found. Join it with the root:</p>
<pre><code>import os
for root, dirs, files in os.walk("/home"):
for name in files:
f = open(os.path.join(root, name), 'r')
f.close
</code></pre>
| 1 | 2016-08-02T12:40:09Z | [
"python",
"directory",
"os.walk"
] |
Django directing users after login | 38,720,569 | <p>I've got problems login people with my django app, and I don't think I quite understand how login currently works. Here's my user class, that extends Django's user with some extra fields. The extra fields indicate the type of the user, which I'll just call A, B and C.</p>
<pre><code>class MyUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
isA = models.BooleanField(default=False)
isB = models.BooleanField(default=False)
isC = models.BooleanField(default=False)
</code></pre>
<p>I've got a login view that should redirect the users as per their type:</p>
<pre><code>def myLogin(request):
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
myuser = MyUser.objects.get(user=user)
if user is not None:
if user.is_active:
login(request, user)
if myuser.isA:
return redirect('/aView/')
elif myuser.isB:
return redirect('/bView/')
elif myuser.isC:
return redirect('/cView/')
else:
return HttpResponse('disabled account')
else:
return HttpResponse('Invalid login')
</code></pre>
<p>and my template is the default login template from the django docs:</p>
<pre><code>{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
</code></pre>
<p>Currently I get an error sayin:</p>
<pre><code>DoesNotExist at /login/
MyUser matching query does not exist.
</code></pre>
<p>I'm wondering also, that shouldn't I link my "login.html" file to myLogin view? Any help is much appriciated!</p>
| 0 | 2016-08-02T12:34:14Z | 38,721,290 | <p>The <code>get</code> <code>QuerySet</code> method raises an <code>DoesNotExist</code> exception if there is no matching entry. The line <code>myuser = MyUser.objects.get(user=user)</code> needs changing.</p>
<h3>try/except</h3>
<pre><code>try:
myuser = MyUser.objects.get(user=user)
except MyUser.DoesNotExist:
myuser = None
</code></pre>
<h3>check with exists (extra query)</h3>
<pre><code> myuser_qs = MyUser.objects.filter(user=user)
myuser = myuser_qs.get() if myuser_qs.exists() else None
</code></pre>
<p>this will still warn if there are <code>MyUser.MultipleObjectsReturned</code></p>
<h3>using first/last QuerySet methods</h3>
<pre><code>myuser = MyUser.objects.filter(user=user).first()
</code></pre>
<p>this will return <code>None</code> if not matching entry is there, but the downside is that if you have multiple entries in the database, there won't be an error raised</p>
<hr>
<p>Reading <a href="https://github.com/django/django/blob/stable/1.10.x/django/db/models/query.py#L550" rel="nofollow">relevant Django source code</a> might be helpful</p>
| 0 | 2016-08-02T13:06:27Z | [
"python",
"django"
] |
Python's OS module to write to file giving "TypeError" | 38,720,688 | <p>Here is my script:</p>
<pre><code>import random
import os
i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")
</code></pre>
<p>The end goal is simply a text file with 5000 randomly generated numbers in it that I would like to use in subsequent projects. When I run this little script I get the following error : </p>
<pre><code>Traceback (most recent call last):
File "C:/Users/LewTo002/Desktop/New folder (2)/numGen.py", line 5, in <module>
file = os.open("numbers.txt", "w")
TypeError: an integer is required (got type str)
</code></pre>
<p>I've reviewed the following sites to solve the problem myself :
<a href="http://learnpythonthehardway.org/book/ex16.html" rel="nofollow">http://learnpythonthehardway.org/book/ex16.html</a></p>
<p><a href="https://docs.python.org/3/library/os.html" rel="nofollow">https://docs.python.org/3/library/os.html</a></p>
<p><a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/3/tutorial/inputoutput.html</a></p>
<p>And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file = os.open('numbers.txt', 'w')" according to my IDE ( using JetBrain's PyCharm ). I feel like I am overlooking something trivial especially with how simple this script is... Any assistance would be thoroughly appreciated! :)</p>
| 0 | 2016-08-02T12:40:29Z | 38,720,741 | <p>If you want to use <a href="https://docs.python.org/2/library/os.html#os.open" rel="nofollow">os.open</a> you have to use <a href="https://docs.python.org/2/library/os.html#open-constants" rel="nofollow">os flags</a> to identify mode in which you are going to open file:</p>
<pre><code>file = os.open("numbers.txt", os.O_WRONLY)
</code></pre>
<p>The way you are trying to open file is correct for <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">built in open method</a></p>
<p><strong>Good Luck !</strong></p>
| 2 | 2016-08-02T12:43:12Z | [
"python",
"typeerror"
] |
Python's OS module to write to file giving "TypeError" | 38,720,688 | <p>Here is my script:</p>
<pre><code>import random
import os
i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")
</code></pre>
<p>The end goal is simply a text file with 5000 randomly generated numbers in it that I would like to use in subsequent projects. When I run this little script I get the following error : </p>
<pre><code>Traceback (most recent call last):
File "C:/Users/LewTo002/Desktop/New folder (2)/numGen.py", line 5, in <module>
file = os.open("numbers.txt", "w")
TypeError: an integer is required (got type str)
</code></pre>
<p>I've reviewed the following sites to solve the problem myself :
<a href="http://learnpythonthehardway.org/book/ex16.html" rel="nofollow">http://learnpythonthehardway.org/book/ex16.html</a></p>
<p><a href="https://docs.python.org/3/library/os.html" rel="nofollow">https://docs.python.org/3/library/os.html</a></p>
<p><a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/3/tutorial/inputoutput.html</a></p>
<p>And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file = os.open('numbers.txt', 'w')" according to my IDE ( using JetBrain's PyCharm ). I feel like I am overlooking something trivial especially with how simple this script is... Any assistance would be thoroughly appreciated! :)</p>
| 0 | 2016-08-02T12:40:29Z | 38,720,749 | <p>From the <a href="https://docs.python.org/3/library/os.html" rel="nofollow">documentation</a> you linked:</p>
<blockquote>
<p>If you just want to read or write a file see <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow">open()</a>.</p>
</blockquote>
<p>As I said in the comment, change this:</p>
<pre><code>os.open(...)
</code></pre>
<p>To this:</p>
<pre><code>open(...)
</code></pre>
| 0 | 2016-08-02T12:43:37Z | [
"python",
"typeerror"
] |
Python's OS module to write to file giving "TypeError" | 38,720,688 | <p>Here is my script:</p>
<pre><code>import random
import os
i = 0
file = os.open("numbers.txt", "w")
while i < 5000:
ranNumb = str(random.randint(1,500))
file.write(ranNumb,",")
</code></pre>
<p>The end goal is simply a text file with 5000 randomly generated numbers in it that I would like to use in subsequent projects. When I run this little script I get the following error : </p>
<pre><code>Traceback (most recent call last):
File "C:/Users/LewTo002/Desktop/New folder (2)/numGen.py", line 5, in <module>
file = os.open("numbers.txt", "w")
TypeError: an integer is required (got type str)
</code></pre>
<p>I've reviewed the following sites to solve the problem myself :
<a href="http://learnpythonthehardway.org/book/ex16.html" rel="nofollow">http://learnpythonthehardway.org/book/ex16.html</a></p>
<p><a href="https://docs.python.org/3/library/os.html" rel="nofollow">https://docs.python.org/3/library/os.html</a></p>
<p><a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/3/tutorial/inputoutput.html</a></p>
<p>And according to those, I am doing the correctly. The error is thrown specifically due to the "w" in "file = os.open('numbers.txt', 'w')" according to my IDE ( using JetBrain's PyCharm ). I feel like I am overlooking something trivial especially with how simple this script is... Any assistance would be thoroughly appreciated! :)</p>
| 0 | 2016-08-02T12:40:29Z | 38,720,766 | <p>Citing after Python docs available <a href="https://docs.python.org/2/library/os.html#os.open" rel="nofollow">here</a></p>
<blockquote>
<p>This function is intended for low-level I/O. For normal usage, use the built-in function open(), which returns a âfile objectâ with read() and write() methods (and many more). To wrap a file descriptor in a âfile objectâ, use fdopen().</p>
</blockquote>
<p>You should use the built-in <code>open</code> function as others has said already.</p>
| 0 | 2016-08-02T12:44:28Z | [
"python",
"typeerror"
] |
Setting boolean values in pandas dataframe (by date) based on column header membership in other dataframe (by date) | 38,720,745 | <p>I have two pandas dataframes (X and Y) and am trying to populate a third (Z) with boolean values based on interrelationships between the axes of X and the columns/constituents of Y. I could only manage to do this via nested loops and the code works on my toy example but is too slow for my actual data set.</p>
<pre><code># define X, Y and Z
idx=pd.date_range('2016-1-31',periods=3,freq='M')
codes = list('ABCD')
X = np.random.randn(3,4)
X = pd.DataFrame(X,columns=codes,index=idx)
Y = [['A','A','B'],['C','B','C'],['','C','D']]
Y = pd.DataFrame(Y,columns=idx)
Z = pd.DataFrame(columns=X.columns, index=X.index)
</code></pre>
<p>As you can see the index of X matches the columns of Y in this example. In my real example the columns of Y are a subset of the index of X.</p>
<p>Z's axes match X's. I want to populate elements of Z with True if the column header of Z is in the column of Y with header equal to the index of Z. My working code is as follows:</p>
<pre><code>for r in Y:
for c in Z:
Z.loc[r,c] = c in Y[r].values
</code></pre>
<p>The code is pretty clean and short but it takes a LONG time to run on the larger data sets. I'm hoping there is vectorised way to achieve the same much faster.</p>
<p>Any help would be greatly appreciated</p>
<p>Thanks!</p>
| 1 | 2016-08-02T12:43:27Z | 38,721,441 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> method, where values of DataFrame are converted to columns and columns to values of DataFrames. Last test <code>NaN</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.notnull.html" rel="nofollow"><code>notnull</code></a>:</p>
<pre><code>print (Y.replace({'':np.nan})
.stack()
.reset_index(0)
.set_index(0, append=True)
.squeeze()
.unstack()
.rename_axis(None, axis=1)
.notnull())
A B C D
2016-01-31 True False True False
2016-02-29 True True True False
2016-03-31 False True True True
</code></pre>
<p>Another solution with <code>pivot</code>:</p>
<pre><code>print (Y.replace({'':np.nan})
.stack()
.reset_index(name='a')
.pivot(index='level_1', columns='a', values='level_0')
.rename_axis(None, axis=1)
.rename_axis(None)
.notnull())
A B C D
2016-01-31 True False True False
2016-02-29 True True True False
2016-03-31 False True True True
</code></pre>
<p>EDIT by comment:</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> if indexes are unique and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a> by <code>False</code>:</p>
<pre><code>import pandas as pd
import numpy as np
# define X, Y and Z
idx=pd.date_range('2016-1-31',periods=5,freq='M')
codes = list('ABCD')
X = np.random.randn(5,4)
X = pd.DataFrame(X,columns=codes,index=idx)
Y = [['A','A','B'],['C','B','C'],['','C','D']]
Y = pd.DataFrame(Y,columns=idx[:3])
Z = pd.DataFrame(columns=X.columns, index=X.index)
print (X)
A B C D
2016-01-31 0.810348 -0.737780 -0.523869 -0.585772
2016-02-29 -1.126655 -0.494999 -1.388351 0.460340
2016-03-31 -1.578155 0.950643 -1.699921 1.149540
2016-04-30 -2.320711 1.263740 -1.401714 0.090788
2016-05-31 1.218036 0.565395 0.172278 0.288698
print (Y)
2016-01-31 2016-02-29 2016-03-31
0 A A B
1 C B C
2 C D
print (Z)
A B C D
2016-01-31 NaN NaN NaN NaN
2016-02-29 NaN NaN NaN NaN
2016-03-31 NaN NaN NaN NaN
2016-04-30 NaN NaN NaN NaN
2016-05-31 NaN NaN NaN NaN
</code></pre>
<pre><code>Y1 = Y.replace({'':np.nan})
.stack()
.reset_index(name='a')
.pivot(index='level_1', columns='a', values='level_0')
.rename_axis(None, axis=1)
.rename_axis(None)
.notnull()
print (Y1)
A B C D
2016-01-31 True False True False
2016-02-29 True True True False
2016-03-31 False True True True
print (Y1.reindex(X.index).fillna(False))
A B C D
2016-01-31 True False True False
2016-02-29 True True True False
2016-03-31 False True True True
2016-04-30 False False False False
2016-05-31 False False False False
</code></pre>
| 1 | 2016-08-02T13:13:29Z | [
"python",
"pandas",
"boolean",
"intersection"
] |
change a range of colors to white in python | 38,720,810 | <p>I use following code to change specific colors (grays) to white in photos. But the code is too slow. any suggestion or alternative is welcomed.</p>
<pre><code>import os
import numpy as np
from PIL import Image
for j in range(1,160):
im = Image.open(str(j)+'.jpg')
data = np.array(im)
for i in (range(205,254)):
r1, g1, b1 = i, i, i # Original
r2, g2, b2 = 255, 255, 255 # Replacement
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]
im = Image.fromarray(data)
im.save(os.getcwd()+'\\conv\\'+str(j)+'.jpg')
</code></pre>
| 0 | 2016-08-02T12:45:55Z | 38,721,027 | <p>This way of image processing is slow because it is single threaded, and straightforward. Try splitting it into multiple equal parts, and running them at the same time for a major speedup (try to split the job with function and check the results: more of smaller chunks vs lesser number of larger ones).
For greater improvement: GPU supported image manipulating, but it's quite hard in Python.</p>
| 0 | 2016-08-02T12:54:45Z | [
"python",
"image-processing"
] |
change a range of colors to white in python | 38,720,810 | <p>I use following code to change specific colors (grays) to white in photos. But the code is too slow. any suggestion or alternative is welcomed.</p>
<pre><code>import os
import numpy as np
from PIL import Image
for j in range(1,160):
im = Image.open(str(j)+'.jpg')
data = np.array(im)
for i in (range(205,254)):
r1, g1, b1 = i, i, i # Original
r2, g2, b2 = 255, 255, 255 # Replacement
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]
im = Image.fromarray(data)
im.save(os.getcwd()+'\\conv\\'+str(j)+'.jpg')
</code></pre>
| 0 | 2016-08-02T12:45:55Z | 38,721,161 | <p>You are searching for all the values in the image were all thae values of all channels are the same. Therefore first create a mask for all the pixels that are equal for all three channels and than from them only leave the ones that are in your range.
Try the following code:</p>
<pre><code>import os
import numpy as np
from PIL import Image
for j in range(1,160):
im = Image.open(str(j)+'.jpg')
data = np.array(im)
for i in (range(205,254)):
r1, g1, b1 = i, i, i # Original
r2, g2, b2 = 255, 255, 255 # Replacement
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
maskEqualValues = (red==green) & (red==blue) & (green==blue)
maskEqualValuesVal = np.multiply(maskEqualValues,red);
mask = (maskEqualValuesVal > 205) & (maskEqualValuesVal <= 254)
im = Image.fromarray(data)
im.save(os.getcwd()+'\\conv\\'+str(j)+'.jpg')
</code></pre>
| 0 | 2016-08-02T13:00:14Z | [
"python",
"image-processing"
] |
change a range of colors to white in python | 38,720,810 | <p>I use following code to change specific colors (grays) to white in photos. But the code is too slow. any suggestion or alternative is welcomed.</p>
<pre><code>import os
import numpy as np
from PIL import Image
for j in range(1,160):
im = Image.open(str(j)+'.jpg')
data = np.array(im)
for i in (range(205,254)):
r1, g1, b1 = i, i, i # Original
r2, g2, b2 = 255, 255, 255 # Replacement
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]
im = Image.fromarray(data)
im.save(os.getcwd()+'\\conv\\'+str(j)+'.jpg')
</code></pre>
| 0 | 2016-08-02T12:45:55Z | 38,743,233 | <p>I think you are missing an indent at the end, you're saving each output image 50 times. I changed your code to be:</p>
<pre><code>import os
import numpy as np
from PIL import Image
for j in range(1, 10):
filename = str(j) + '.jpg'
print 'processing', filename, '...'
im = Image.open(filename)
data = np.array(im)
for i in range(205, 254):
r1, g1, b1 = i, i, i # Original
r2, g2, b2 = 255, 255, 255 # Replacement
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]
im = Image.fromarray(data)
im.save('x_' + filename)
</code></pre>
<p>160 took too long for testing, so I just tried with 10 images. On my laptop with a 2k x 2k jpg image I see:</p>
<pre><code>$ time ../grey.py
processing 1.jpg ...
...
processing 9.jpg ...
real 0m7.884s
user 0m7.912s
sys 0m0.300s
</code></pre>
<p>I rewrote your program using <a href="http://www.vips.ecs.soton.ac.uk/index.php?title=VIPS" rel="nofollow">vips</a>. It has a <a href="http://www.vips.ecs.soton.ac.uk/supported/current/doc/html/libvips/using-from-python.html" rel="nofollow">high-level Python binding</a>, and it's <a href="http://www.vips.ecs.soton.ac.uk/index.php?title=Speed_and_Memory_Use" rel="nofollow">much faster than PIL, numpy or opencv</a> at this kind of thing. The vips version looks like:</p>
<pre><code>import gi
gi.require_version('Vips', '8.0')
from gi.repository import Vips
for j in range(1, 10):
filename = str(j) + '.jpg'
print 'processing', filename, '...'
im = Vips.Image.new_from_file(filename)
# find all pixels where RGB are equal
mask = (im[0] == im[1]) & (im[1] == im[2])
# we also need g > 204
mask &= im[1] > 204
# and send all those pixels to 255
im = mask.ifthenelse(255, im)
im.write_to_file('x_' + filename)
</code></pre>
<p>On my laptop I see:</p>
<pre><code>$ time ../grey-vips.py
processing 1.jpg ...
...
processing 9.jpg ...
real 0m0.880s
user 0m2.052s
sys 0m0.072s
</code></pre>
<p>So about 10x faster. </p>
<p>Of course that's a bit unfair, as Amitay says, your code is looping rather than masking a range, but I don't know numpy well enough to fix that. </p>
| 0 | 2016-08-03T12:07:50Z | [
"python",
"image-processing"
] |
Python pandas plot scatter datetime error | 38,720,851 | <p>I want a scatter plot where x-axis is a <code>datetime</code>, y-axis is an <code>int</code>. And I have only a few of datapoints that are discrete and not continuous, so I don't want to connect datapoints.</p>
<p>My DataFrame is:</p>
<pre><code>df = pd.DataFrame({'datetime':[dt.datetime(2016,1,1,0,0,0), dt.datetime(2016,1,4,0,0,0),
dt.datetime(2016,1,9,0,0,0)], 'value':[10, 7, 8]})
</code></pre>
<p>If I use "normal" plot than I got a "line" figure:</p>
<pre><code>df.plot(x='datetime', y='value')
</code></pre>
<p>But how can I plot only the dots? This gives error:</p>
<pre><code>df.plot.scatter(x='datetime', y='value')
KeyError: 'datetime'
</code></pre>
<p>Of course I can use some cheat to get the result I want, for example:</p>
<pre><code>df.plot(x='datetime', y='value', marker='o', linewidth=0)
</code></pre>
<p>But I don't understand why the <code>scatter</code> version does not work...</p>
<p>Thank you for help!</p>
| 0 | 2016-08-02T12:47:36Z | 38,723,651 | <p><em>Scatter plot can be drawn by using the DataFrame.plot.scatter() method. Scatter plot requires <strong>numeric</strong> columns for x and y axis. These
can be specified by x and y keywords each.</em></p>
<p>Alternative Approach:</p>
<pre><code>In [71]: df['day'] = df['datetime'].dt.day
In [72]: df.plot.scatter(x='day', y='value')
Out[72]: <matplotlib.axes._subplots.AxesSubplot at 0x25440a1bc88>
</code></pre>
<p><img src="http://i.stack.imgur.com/g5Xfv.png" alt="Image">
</p>
| 1 | 2016-08-02T14:45:21Z | [
"python",
"pandas",
"plot",
"scatter-plot"
] |
How to unpack deep nested iterable structure | 38,720,918 | <p>Say for example I have a structure that contains many sub-elements some of which are structures:</p>
<pre><code>v = [1, 2, 3, [4, (5, 6)]]
</code></pre>
<p>How can I unpack these into a series of names that contain only the contents of the structures and not a structure?</p>
<p>Trying <code>a, b, c, d, e, f = v</code> raises a <code>ValueError</code> while using the starred expression would assign a structure to the names. How can I unpack them in order to get:</p>
<pre><code>print(a, b, c, d, e, f)
</code></pre>
<p>to print:</p>
<pre><code>1 2 3 4 5 6
</code></pre>
| 4 | 2016-08-02T12:50:13Z | 38,720,943 | <p>Assignments are defined recursively, you need to <em><a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">use parentheses <code>()</code> and/or square brackets <code>[]</code> to enclose target names</a></em> and match the nested structure of your iterable. In your case:</p>
<pre><code>a, b, c, (d, (e, f)) = v
print(a, b, c, d, e, f)
1 2 3 4 5 6
</code></pre>
<p>Similarly, with no change in semantics, you could use <code>[]</code> to denote the structure:</p>
<pre><code>a, b, c, [d, [e, f]] = v
print(a, b, c, d, e, f)
1 2 3 4 5 6
</code></pre>
<p>or, of course, mix them up.</p>
<p>Python will then unpack <code>v</code> and assign the first 3 values normally, then unpack the contents of <code>(d, (e, f))</code> and assign <code>d</code> and then again unpack <code>(e, f)</code> and do the same.</p>
<p>You can see this happening if you import the <code>dis</code> module and disassembling the statement with <code>dis.dis</code>:</p>
<pre><code>dis.dis('a, b, c, (d, (e, f)) = v')
1 0 LOAD_NAME 0 (v)
3 UNPACK_SEQUENCE 4 # <- first unpack
6 STORE_NAME 1 (a)
9 STORE_NAME 2 (b)
12 STORE_NAME 3 (c)
15 UNPACK_SEQUENCE 2 # <- second unpack
18 STORE_NAME 4 (d)
21 UNPACK_SEQUENCE 2 # <- third unpack
24 STORE_NAME 5 (e)
27 STORE_NAME 6 (f)
30 LOAD_CONST 0 (None)
33 RETURN_VALUE
</code></pre>
<p>In general, to unpack arbitrarily nested structures, match the structure in the left side of the assignment (target-list):</p>
<pre><code>v = [1, [2, [3, [4, 5]]]]
[a, [b, [c, [d, e]]]] = v
print(a, b, c, d, e)
1 2 3 4 5
</code></pre>
<p>the outer <code>[]</code> are, of course, unnecessary, just adding them to show that simply matching the structure suffices. </p>
<p>A more general (soft) introduction on iterable unpacking can be found on <a class='doc-link' href="http://stackoverflow.com/documentation/python/809/python-3-vs-python-2/2845/unpacking-iterables#t=20160802141126769914">the doc page for it</a>, even though the case of nested structures have not yet been discussed there.</p>
| 10 | 2016-08-02T12:51:02Z | [
"python",
"python-3.x",
"iterable",
"iterable-unpacking"
] |
How to unpack deep nested iterable structure | 38,720,918 | <p>Say for example I have a structure that contains many sub-elements some of which are structures:</p>
<pre><code>v = [1, 2, 3, [4, (5, 6)]]
</code></pre>
<p>How can I unpack these into a series of names that contain only the contents of the structures and not a structure?</p>
<p>Trying <code>a, b, c, d, e, f = v</code> raises a <code>ValueError</code> while using the starred expression would assign a structure to the names. How can I unpack them in order to get:</p>
<pre><code>print(a, b, c, d, e, f)
</code></pre>
<p>to print:</p>
<pre><code>1 2 3 4 5 6
</code></pre>
| 4 | 2016-08-02T12:50:13Z | 38,722,308 | <p>Another option you might consider is to flatten the structure and then assign it.</p>
<pre><code>def flatten(container):
for i in container:
if isinstance(i, (list,tuple)):
for j in flatten(i):
yield j
else:
yield i
</code></pre>
<p>Then </p>
<pre><code>a, b, c, d, e, f = flatten(v)
</code></pre>
| 3 | 2016-08-02T13:47:55Z | [
"python",
"python-3.x",
"iterable",
"iterable-unpacking"
] |
Python: Is it better to pass in a mutable object as a parameter or have the method create one locally and return it? | 38,721,013 | <p>I have a relatively straightforward question but couldn't really find the answer online. I know in C++, if you are trying to create a large object (say a huge vector of strings) you would avoid doing:</p>
<pre><code>int main() {
vector<string> v = foo()
}
vector<string> foo() {
vector<string> result;
// populate result
return result;
}
</code></pre>
<p>instead opting for the version below because a method call like above will have to copy the local vector to the vector declared in main whereas the lower example adds directly to the vector in main (more or less):</p>
<pre><code>int main() {
vector<string> v;
foo(v)
}
void foo(vector<string>& result) {
// populate result
return result;
}
</code></pre>
<p>My question is the same related to python. Is it better to pass in a mutable object as a parameter or have the method create one locally and return it? I'm not incredibly familiar with the mechanics of Python.</p>
| 0 | 2016-08-02T12:54:09Z | 38,721,225 | <p>Python's data model is very different from C++'s.</p>
<p>In Python, new objects are created on the heap and bound to variables that exist in namespaces (function calls, classes, instances and varaious other parts of the language implement namespaces).</p>
<p>In C++, without proper care you can create an object in a function or method call that is allocated on the stack. Then if your function returns a reference to this object you will see problems, because the memory will likely be re-used, and the reference will become invalid at best and dangerous at worst!</p>
<p>In Python it isn't possible to create a "dangling reference" of this type, because objects are kept alive as long as there are any references to them. Therefore it's perfectly permissible to create new objects inside a function and return them without worries. This will normally be preferable to forcing the caller to create a mutable object for the function to modify.</p>
| 1 | 2016-08-02T13:03:14Z | [
"python",
"performance"
] |
Fetch certain parts of sympy solution | 38,721,014 | <p>I have a huge symbolic sympy expression on the form</p>
<pre><code>expression = factor * (f1*a + f2*b + f3*c + f4*d + f5*e)
</code></pre>
<p>where all of the factors a through e all consists of several terms. I.e: </p>
<pre><code>a = exp(2x) + exp(3x) + sin(Ix).
</code></pre>
<p>I want to create en array on the form</p>
<pre><code>array = factor * [a,b,c,d,e]
</code></pre>
<p>But dont see a cleaver way to do this. I´ve tried to use the factor function, but it only gives me the expression on the form of "expression" above. </p>
<p>Until now i have used </p>
<pre><code>print(expression)
</code></pre>
<p>and then done some brute force copy paste of the factors a through e. Since I am going to get expressions with way more terms than in this example, I want to do this without the copy paste routine. Any ideas?</p>
| 1 | 2016-08-02T12:54:11Z | 38,721,394 | <p>Here's a simple example you can extrapolate for more terms</p>
<pre><code>import sympy as sp
x = sp.var('x')
f1, f2 = sp.symbols('f1:3')
factor = sp.symbols('factor')
a = x**2 + sp.sin(x) + sp.exp(sp.I * x)
b = sp.log(x)/(x+1)**2
# example expression:
expression = (factor * (f1 * a + f2 * b)).expand()
print(expression)
# collect coefficients of f1 and f2
coeffs = sp.collect(expression.expand(),[f1,f2], evaluate=False)
print(coeffs)
# show the coefficients w/o the factor factor
[(coeffs[f]/factor).simplify() for f in (f1,f2)]
</code></pre>
<blockquote>
<pre><code>f1*factor*x**2 + f1*factor*exp(I*x) + f1*factor*sin(x) + f2*factor*log(x)/(x**2 + 2*x + 1)
{f2: factor*log(x)/(x**2 + 2*x + 1), f1: factor*x**2 + factor*exp(I*x) + factor*sin(x)}
[x**2 + exp(I*x) + sin(x), log(x)/(x**2 + 2*x + 1)]
</code></pre>
</blockquote>
| 1 | 2016-08-02T13:10:59Z | [
"python",
"arrays",
"math",
"sympy",
"factors"
] |
AWS S3 Data Protection Using Client-Side Encryption | 38,721,026 | <p>I need to use AWS S3 feature - <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingClientSideEncryption.html" rel="nofollow">Protecting Data Using Client-Side Encryption</a></p>
<p>According to AWS documentation the following AWS SDKs support client-side encryption:</p>
<pre><code>AWS SDK for Java
AWS SDK for .NET
AWS SDK for Ruby
</code></pre>
<p>I have to use this functionality from Python. Is any way to do it ?</p>
| 1 | 2016-08-02T12:54:37Z | 38,721,409 | <p>Client-side encryption means that you are encrypting the file prior to uploading it to S3. You can accomplish that using any programming language along with any encryption tool. For that matter, you could just use a tool like gpg and the AWS CLI to encrypt and upload files to S3. You manage the encryption keys on your side. The referenced SDKs just include a wrapper that simplify some of the client-side encryption operations.</p>
| 2 | 2016-08-02T13:11:45Z | [
"python",
"amazon-web-services",
"amazon-s3"
] |
Why does this Python code give Runtime Error(NZEC)? | 38,721,038 | <p>I already read the other questions and answers but couldn't implement any of the solutions to my code. I'm still clueless about the reason why this code gives a runtime error.</p>
<p>I'm trying to submit the code on CodeChef, yet it gives the Runtime Error(NZEC), although the code runs flawlessly on my console for some inputs. Here's my code:</p>
<pre><code>def GetSquares(base):
if not base or base < 4:
return 0
else:
x = (base - 4) - (base % 2) + 1
return x + GetSquares(base - 4)
num_test = int(input())
for test in range(num_test):
base = int(input())
print (int(GetSquares(base)))
</code></pre>
<p>Codechef's explanation for NZEC:</p>
<blockquote>
<p>NZEC stands for Non Zero Exit Code. For C users, this will be
generated if your main method does not have a return 0; statement.
Other languages like Java/C++ could generate this error if they throw
an exception.</p>
</blockquote>
<p>The problem I'm trying to solve:</p>
<p><a href="https://www.codechef.com/problems/TRISQ" rel="nofollow">https://www.codechef.com/problems/TRISQ</a></p>
| 0 | 2016-08-02T12:55:00Z | 38,721,250 | <p>The problem description says that the input is constrained to be < 10^4. That's 10,000! Your code will need to make 10,000/4 = 2500 recursive calls to GetSquares, that's a lot! In fact, it's so much that it's going to give you, fittingly, this error:</p>
<pre><code>RuntimeError: maximum recursion depth exceeded
</code></pre>
<p>You're going to have to think of a better way to solve the problem that doesn't involve so much recursion! Because you're doing this coding challenge, I'm not going to give a solution in this answer as that would sort of defeat the purpose, but if you'd like some prodding towards an answer, feel free to ask.</p>
| 3 | 2016-08-02T13:04:39Z | [
"python",
"python-3.x"
] |
Why does this Python code give Runtime Error(NZEC)? | 38,721,038 | <p>I already read the other questions and answers but couldn't implement any of the solutions to my code. I'm still clueless about the reason why this code gives a runtime error.</p>
<p>I'm trying to submit the code on CodeChef, yet it gives the Runtime Error(NZEC), although the code runs flawlessly on my console for some inputs. Here's my code:</p>
<pre><code>def GetSquares(base):
if not base or base < 4:
return 0
else:
x = (base - 4) - (base % 2) + 1
return x + GetSquares(base - 4)
num_test = int(input())
for test in range(num_test):
base = int(input())
print (int(GetSquares(base)))
</code></pre>
<p>Codechef's explanation for NZEC:</p>
<blockquote>
<p>NZEC stands for Non Zero Exit Code. For C users, this will be
generated if your main method does not have a return 0; statement.
Other languages like Java/C++ could generate this error if they throw
an exception.</p>
</blockquote>
<p>The problem I'm trying to solve:</p>
<p><a href="https://www.codechef.com/problems/TRISQ" rel="nofollow">https://www.codechef.com/problems/TRISQ</a></p>
| 0 | 2016-08-02T12:55:00Z | 38,721,773 | <p>The question puts a constraint on the value of '<strong>B</strong>' which is 10000 at max, which means there are a lot of recursive calls and giving a runtime error. Try solving using iteration.</p>
| 0 | 2016-08-02T13:26:09Z | [
"python",
"python-3.x"
] |
Python pandas plot more columns but shows only one legend | 38,721,080 | <p>I want to plot two columns on the same x-axis & y-axis. But <code>pandas-plot</code> only displays the second column's legend (so no dots for the first column). Of course both labels (name of columns) are displayed in the legend box.</p>
<p>My DataFrame is:</p>
<pre><code>df = pd.DataFrame({'datetime':[dt.datetime(2016,1,1,0,0,0), dt.datetime(2016,1,4,0,0,0),
dt.datetime(2016,1,9,0,0,0)], 'value':[10,7,8], 'value2':[12,4,9]})
</code></pre>
<p>And my plot is:</p>
<pre><code>ax = df.plot(x='datetime', y='value', marker='o', linewidth=0)
df.plot(ax=ax, x='datetime', y='value2', marker='o', linewidth=0)
</code></pre>
<p>If I plot the lines as well than the "legend" of the first column is displayed, but it is only a blue line without dots:</p>
<pre><code>ax = df.plot(x='datetime', y='value', marker='o')
df.plot(ax=ax, x='datetime', y='value2', marker='o')
</code></pre>
<p>Is it possible to show only the dots in the legend box (and on the plot) for both columns?</p>
<p>Thank you!</p>
| 0 | 2016-08-02T12:56:36Z | 38,771,349 | <p>You should try recalling the legend after you call the second plot:</p>
<pre><code>ax.legend()
</code></pre>
<p>this is what I get:</p>
<p><a href="http://i.stack.imgur.com/HmFdo.png" rel="nofollow"><img src="http://i.stack.imgur.com/HmFdo.png" alt="enter image description here"></a></p>
| 1 | 2016-08-04T15:19:53Z | [
"python",
"pandas",
"plot",
"legend"
] |
first and last bars on matplotlib histogram appear moved | 38,721,086 | <p>I'm trying to create a histogram using these values:</p>
<pre><code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2, 1, 1, 4, 1, 1, 2, 1, 1, 2]
</code></pre>
<p>The code I'm using is this</p>
<pre><code>plt.hist(values, histtype='bar', color='green', alpha=0.5)
plt.title(library_name, fontsize=12)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.savefig("../results/histograms/" + library_name)
</code></pre>
<p>And I get this histogram <a href="http://i.stack.imgur.com/Dj9Fd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dj9Fd.png" alt="histogram with first and last bars poorly located"></a></p>
<p>Does anyone know why are the first and last bars looks aside from their xtick? I tried using plt.margins function with no results. </p>
<p>Thank you very much</p>
| 1 | 2016-08-02T12:56:53Z | 38,721,373 | <p>To get centre-aligned bins instead of left-aligned, use <code>plt.hist(data, bins=np.arange(50)-0.5)</code></p>
<p>Example code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
values = [1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2,5,3,2,5, 1, 1, 4, 1, 1, 2, 1, 1,7,8,9,9,3,8,6, 2]
offset = 0.5
plt.hist(values, bins=np.arange(1,np.max(values)+2)-offset, histtype='bar', color='green', alpha=0.5)
plt.title('library_name', fontsize=12)
plt.xlabel('xlabel')
plt.ylabel('ylabel')
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.show()
</code></pre>
| 1 | 2016-08-02T13:10:15Z | [
"python",
"matplotlib",
"histogram"
] |
first and last bars on matplotlib histogram appear moved | 38,721,086 | <p>I'm trying to create a histogram using these values:</p>
<pre><code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2, 1, 1, 4, 1, 1, 2, 1, 1, 2]
</code></pre>
<p>The code I'm using is this</p>
<pre><code>plt.hist(values, histtype='bar', color='green', alpha=0.5)
plt.title(library_name, fontsize=12)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.savefig("../results/histograms/" + library_name)
</code></pre>
<p>And I get this histogram <a href="http://i.stack.imgur.com/Dj9Fd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dj9Fd.png" alt="histogram with first and last bars poorly located"></a></p>
<p>Does anyone know why are the first and last bars looks aside from their xtick? I tried using plt.margins function with no results. </p>
<p>Thank you very much</p>
| 1 | 2016-08-02T12:56:53Z | 38,739,635 | <p>As an aside, you can use [<strong>DISCLAIMER: I wrote it</strong>] the "physt" library which has a couple of binning options including one suitable for integers - see <a href="https://github.com/janpipek/physt" rel="nofollow">https://github.com/janpipek/physt</a>, and particularly for your case <a href="http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning.ipynb#Integer-binning" rel="nofollow">http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning.ipynb#Integer-binning</a>. </p>
<p>The code be the following:</p>
<pre><code>import physt
h = physt.histogram(values, "integer")
ax = h.plot(color="green", alpha=0.5, ticks="center")
</code></pre>
<p>...and then add your axis/plt formatting...</p>
| 0 | 2016-08-03T09:28:18Z | [
"python",
"matplotlib",
"histogram"
] |
Split timestamp column into two seperate date and time columns with python | 38,721,087 | <p>I have a dataset called "df_no_missing". </p>
<pre><code>df_no_missing.head()
</code></pre>
<blockquote>
<pre><code>TIMESTAMP object
P_ACT_KW float64
PERIODE_TARIF object
P_SOUSCR float64
SITE object
TARIF object
depassement float64
dtype: object
</code></pre>
</blockquote>
<p>I try to extract date and time into two different columns from the timestamp column, so I did :</p>
<pre><code>dt = datetime.strptime('TIMESTAMP', '%d/%m/%y %H:%M')
df_no_missing['date'] = df_no_missing['TIMESTAMP'].dt.date
df_no_missing['time'] = df_no_missing['TIMESTAMP'].dt.time
</code></pre>
<p>But I got an error : </p>
<pre><code>> ValueError Traceback (most recent call
> last) <ipython-input-185-6599284ba17f> in <module>()
> 1 print(df_no_missing.dtypes)
> 2 df_no_missing.head()
> ----> 3 dt = datetime.strptime('TIMESTAMP', '%d/%m/%y %H:%M')
> 4 df_no_missing['date'] = df_no_missing['TIMESTAMP'].dt.date
> 5 df_no_missing['time'] = df_no_missing['TIMESTAMP'].dt.time
>
> C:\Users\Demonstrator\Anaconda3\lib\_strptime.py in
> _strptime_datetime(cls, data_string, format)
> 508 """Return a class cls instance based on the input string and the
> 509 format string."""
> --> 510 tt, fraction = _strptime(data_string, format)
> 511 tzname, gmtoff = tt[-2:]
> 512 args = tt[:6] + (fraction,)
>
> C:\Users\Demonstrator\Anaconda3\lib\_strptime.py in
> _strptime(data_string, format)
> 341 if not found:
> 342 raise ValueError("time data %r does not match format %r" %
> --> 343 (data_string, format))
> 344 if len(data_string) != found.end():
> 345 raise ValueError("unconverted data remains: %s" %
>
> ValueError: time data 'TIMESTAMP' does not match format '%d/%m/%y
> %H:%M'
</code></pre>
<p>Here is the csv file : </p>
<pre><code>TIMESTAMP;P_ACT_KW;PERIODE_TARIF;P_SOUSCR;SITE;TARIF
31/07/2015 23:00;12;HC;;ST GEREON;TURPE_HTA5
31/07/2015 23:10;466;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:20;18;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:30;17;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:40;13;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:50;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:00;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:10;14;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:20;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:30;20;HC;425;ST GEREON;TURPE_HTA5
</code></pre>
<p>Any idea to help me please?</p>
<p>Thank you in advance</p>
<p>Best regrads </p>
| -3 | 2016-08-02T12:56:53Z | 38,721,175 | <p>IIUC you want:</p>
<pre><code>df_no_missing['TIMESTAMP'] = pd.to_datetime(df_no_missin['TIMESTAMP'], '%d/%m/%y %H:%M')
</code></pre>
<p>then you can do <code>.dt.time</code> and <code>dt.date</code> after the conversion</p>
<p>Also you need to post what the datetime strings look like</p>
<p><strong>EDIT</strong></p>
<p>You can tell <code>read_csv</code> to just parse your datestrings on loading:</p>
<pre><code>In [42]:
import pandas as pd
import io
t="""TIMESTAMP;P_ACT_KW;PERIODE_TARIF;P_SOUSCR;SITE;TARIF
31/07/2015 23:00;12;HC;;ST GEREON;TURPE_HTA5
31/07/2015 23:10;466;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:20;18;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:30;17;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:40;13;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:50;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:00;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:10;14;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:20;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:30;20;HC;425;ST GEREON;TURPE_HTA5"""
df = pd.read_csv(io.StringIO(t), sep=';', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 6 columns):
TIMESTAMP 10 non-null datetime64[ns]
P_ACT_KW 10 non-null int64
PERIODE_TARIF 10 non-null object
P_SOUSCR 9 non-null float64
SITE 10 non-null object
TARIF 10 non-null object
dtypes: datetime64[ns](1), float64(1), int64(1), object(3)
memory usage: 560.0+ bytes
</code></pre>
<p>So in your case:</p>
<pre><code>df = pd.read_csv(your_file, sep=';', parse_dates=[0])
</code></pre>
<p>should just work</p>
| 0 | 2016-08-02T13:00:50Z | [
"python",
"pandas",
"time",
"timestamp"
] |
Split timestamp column into two seperate date and time columns with python | 38,721,087 | <p>I have a dataset called "df_no_missing". </p>
<pre><code>df_no_missing.head()
</code></pre>
<blockquote>
<pre><code>TIMESTAMP object
P_ACT_KW float64
PERIODE_TARIF object
P_SOUSCR float64
SITE object
TARIF object
depassement float64
dtype: object
</code></pre>
</blockquote>
<p>I try to extract date and time into two different columns from the timestamp column, so I did :</p>
<pre><code>dt = datetime.strptime('TIMESTAMP', '%d/%m/%y %H:%M')
df_no_missing['date'] = df_no_missing['TIMESTAMP'].dt.date
df_no_missing['time'] = df_no_missing['TIMESTAMP'].dt.time
</code></pre>
<p>But I got an error : </p>
<pre><code>> ValueError Traceback (most recent call
> last) <ipython-input-185-6599284ba17f> in <module>()
> 1 print(df_no_missing.dtypes)
> 2 df_no_missing.head()
> ----> 3 dt = datetime.strptime('TIMESTAMP', '%d/%m/%y %H:%M')
> 4 df_no_missing['date'] = df_no_missing['TIMESTAMP'].dt.date
> 5 df_no_missing['time'] = df_no_missing['TIMESTAMP'].dt.time
>
> C:\Users\Demonstrator\Anaconda3\lib\_strptime.py in
> _strptime_datetime(cls, data_string, format)
> 508 """Return a class cls instance based on the input string and the
> 509 format string."""
> --> 510 tt, fraction = _strptime(data_string, format)
> 511 tzname, gmtoff = tt[-2:]
> 512 args = tt[:6] + (fraction,)
>
> C:\Users\Demonstrator\Anaconda3\lib\_strptime.py in
> _strptime(data_string, format)
> 341 if not found:
> 342 raise ValueError("time data %r does not match format %r" %
> --> 343 (data_string, format))
> 344 if len(data_string) != found.end():
> 345 raise ValueError("unconverted data remains: %s" %
>
> ValueError: time data 'TIMESTAMP' does not match format '%d/%m/%y
> %H:%M'
</code></pre>
<p>Here is the csv file : </p>
<pre><code>TIMESTAMP;P_ACT_KW;PERIODE_TARIF;P_SOUSCR;SITE;TARIF
31/07/2015 23:00;12;HC;;ST GEREON;TURPE_HTA5
31/07/2015 23:10;466;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:20;18;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:30;17;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:40;13;HC;425;ST GEREON;TURPE_HTA5
31/07/2015 23:50;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:00;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:10;14;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:20;13;HC;425;ST GEREON;TURPE_HTA5
01/08/2015 00:30;20;HC;425;ST GEREON;TURPE_HTA5
</code></pre>
<p>Any idea to help me please?</p>
<p>Thank you in advance</p>
<p>Best regrads </p>
| -3 | 2016-08-02T12:56:53Z | 38,722,360 | <p>If you define</p>
<pre><code>dt = datetime.strptime(TIMESTAMP, '%d/%m/%y %H:%M')
</code></pre>
<p>Then the value of <code>TIMESTAMP</code> has to be like</p>
<pre><code>TIMESTAMP = '03/08/16 16:49'
</code></pre>
<p>If the format is defined as</p>
<pre><code>dt = datetime.strptime(TIMESTAMP, '%d/%m/%Y %H:%M')
</code></pre>
<p>then</p>
<pre><code>TIMESTAMP = '03/08/2016 16:49'
</code></pre>
<p>should be an acceptable argument for <code>strptime</code>.</p>
| 0 | 2016-08-02T13:50:13Z | [
"python",
"pandas",
"time",
"timestamp"
] |
sqlalchemy select by filter | 38,721,092 | <p>app.py:</p>
<pre><code>from flask import Flask, render_template
from itertools import groupby
from flask import request
import MySQLdb
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db import PUser
engine = create_engine('mysql://myusername:mypassword@localhost/mydbname')
engine.connect()
Session = sessionmaker(bind=engine)
session = Session()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myusername:mypassword@localhost/mydbname'
db = SQLAlchemy(app)
@app.route('/people/')
def people():
result = pUser.query.filter_by(shahr = 'tehran')
result = PUser.query.all()
return result
</code></pre>
<p>In the script above, how should I edit these lines to work?</p>
<pre><code>result = PUser.query.filter_by(shahr = 'tehran')
result = PUser.query.all()
</code></pre>
<p>I want to select all data from "PUser" table and also know how to filter my select query.</p>
<p><code>Puser</code> is the name of a table in my database, and this is a part of db.py in the same directory:</p>
<pre><code>class PUser(Base):
__tablename__ = 'p_user'
</code></pre>
| 0 | 2016-08-02T12:57:14Z | 38,722,434 | <p>You are making two queries and that's probably why you aren't getting the desired result.</p>
<p><code>pUser.query</code> creates a <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query" rel="nofollow"><code>Query</code></a> object. On that you're able to call stuff like <code>select_from</code>, <code>join</code>, <code>filter</code>, <code>filter_by</code> and other methods like that, which also return a <code>Query</code> object.</p>
<p>To get the resulting rows to a python <code>list</code>, you have to call <code>all</code>, <code>one</code> etc. on that.</p>
<p>So, in your case</p>
<p><code>result = pUser.query.filter_by(shahr='tehran').all()</code></p>
| 0 | 2016-08-02T13:53:24Z | [
"python",
"sqlalchemy"
] |
Execute function with variable from imported file | 38,721,132 | <p>I'm trying to execute function with value from other file as variable.</p>
<p>one file (let's assume text.py) containing:</p>
<pre><code>VAR="abc"
</code></pre>
<p>In main file:</p>
<pre><code>variable1 -> that variable contain value "VAR"
import text
</code></pre>
<p>Execute function:</p>
<pre><code>example_function(connect=text.variable1)
</code></pre>
<p>Why I cannot do it this way? </p>
<p>EDIT:</p>
<p>real code:</p>
<pre><code>variable = "VAR_23_23"
import text
from functionfile import number_function
from functionfile import find_number
number_to_substr=find_number(variable,"_",1)
source_var=variable[:number_to_substr]
number_function(connect=text.source_var)
</code></pre>
<p>Edit 2.</p>
<p>text.py contain:</p>
<pre><code>VAR="abc"
</code></pre>
<p>main.my contain:</p>
<pre><code> import text
variable = "VAR_23_23"
from functionfile import number_function
from functionfile import find_number
number_to_substr=find_number(variable,"_",1) -> the result is "4"
source_var=variable[:number_to_substr] -> the result is "VAR"
number_function(connect=text.source_var) -> now trying to execute function with that variable name but as result I expect value from TEXT.py file.
</code></pre>
<p>For now instead of 'abc' value I got 'VAR' value.` </p>
| 0 | 2016-08-02T12:58:49Z | 38,721,329 | <p>You cannot do <code>text.variable1</code> because <code>variable1</code> resides in your main file.</p>
<p>You can either use the value from the imported file:</p>
<pre><code>import text
example_function(connect=text.VAR)
</code></pre>
<p>Or use the value in <code>variable1</code>:</p>
<pre><code>example_function(connect=variable1)
</code></pre>
<p>If what you're trying to do is as I've posted in my comment then this is what you should change in order to make it work:</p>
<p>First, edit the <code>text.py</code> file so that instead of containing an instantiation of a variable named <code>VAR</code>, it contains an instantiation of a dictionary containing a <code>"VAR"</code> key:</p>
<pre><code>d = {'VAR': "abc"}
</code></pre>
<p>Now, in order to access the value of <code>'VAR'</code> in the main file, do <code>text.d[source_var]</code>. That is,</p>
<pre><code>number_function(connect=text.d[source_var])
</code></pre>
<p>This is assuming that the <code>source_var</code> variable contains the string <code>"VAR"</code>.</p>
| 1 | 2016-08-02T13:08:20Z | [
"python",
"import"
] |
Does Spark Dataframe have an equivalent option of Panda's merge indicator? | 38,721,194 | <p>The python Pandas library contains the following function :</p>
<pre><code>DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False,
right_index=False, sort=False, suffixes=('_x', '_y'), copy=True,
indicator=False)
</code></pre>
<p>The indicator field combined with Panda's value_counts() function can be used to quickly determine how well a join performed.</p>
<p>Example:</p>
<pre><code>In [48]: df1 = pd.DataFrame({'col1': [0, 1], 'col_left':['a', 'b']})
In [49]: df2 = pd.DataFrame({'col1': [1, 2, 2],'col_right':[2, 2, 2]})
In [50]: pd.merge(df1, df2, on='col1', how='outer', indicator=True)
Out[50]:
col1 col_left col_right _merge
0 0 a NaN left_only
1 1 b 2.0 both
2 2 NaN 2.0 right_only
3 2 NaN 2.0 right_only
</code></pre>
<p>What is the best way to check the performance of a join within a Spark Dataframe? </p>
<p>A custom function was provided in 1 of the answers: It does not yet give the correct results but it would be great if it would:</p>
<pre><code>ASchema = StructType([StructField('id', IntegerType(),nullable=False),
StructField('name', StringType(),nullable=False)])
BSchema = StructType([StructField('id', IntegerType(),nullable=False),
StructField('role', StringType(),nullable=False)])
AData = sc.parallelize ([ Row(1,'michel'), Row(2,'diederik'), Row(3,'rok'), Row(4,'piet')])
BData = sc.parallelize ([ Row(1,'engineer'), Row(2,'lead'), Row(3,'scientist'), Row(5,'manager')])
ADF = hc.createDataFrame(AData,ASchema)
BDF = hc.createDataFrame(BData,BSchema)
DFJOIN = ADF.join(BDF, ADF['id'] == BDF['id'], "outer")
DFJOIN.show()
Input:
+----+--------+----+---------+
| id| name| id| role|
+----+--------+----+---------+
| 1| michel| 1| engineer|
| 2|diederik| 2| lead|
| 3| rok| 3|scientist|
| 4| piet|null| null|
|null| null| 5| manager|
+----+--------+----+---------+
from pyspark.sql.functions import *
DFJOINMERGE = DFJOIN.withColumn("_merge", when(ADF["id"].isNull(), "right_only").when(BDF["id"].isNull(), "left_only").otherwise("both"))\
.withColumn("id", coalesce(ADF["id"], BDF["id"]))\
.drop(ADF["id"])\
.drop(BDF["id"])
DFJOINMERGE.show()
Output
+---+--------+---+---------+------+
| id| name| id| role|_merge|
+---+--------+---+---------+------+
| 1| michel| 1| engineer| both|
| 2|diederik| 2| lead| both|
| 3| rok| 3|scientist| both|
| 4| piet| 4| null| both|
| 5| null| 5| manager| both|
+---+--------+---+---------+------+
==> I would expect id 4 to be left, and id 5 to be right.
Changing join to "left":
Input:
+---+--------+----+---------+
| id| name| id| role|
+---+--------+----+---------+
| 1| michel| 1| engineer|
| 2|diederik| 2| lead|
| 3| rok| 3|scientist|
| 4| piet|null| null|
+---+--------+----+---------+
Output
+---+--------+---+---------+------+
| id| name| id| role|_merge|
+---+--------+---+---------+------+
| 1| michel| 1| engineer| both|
| 2|diederik| 2| lead| both|
| 3| rok| 3|scientist| both|
| 4| piet| 4| null| both|
+---+--------+---+---------+------+
</code></pre>
| 1 | 2016-08-02T13:01:45Z | 38,731,256 | <p>Try this:</p>
<pre><code>>>> from pyspark.sql.functions import *
>>> sdf1 = sqlContext.createDataFrame(df1)
>>> sdf2 = sqlContext.createDataFrame(df2)
>>> sdf = sdf1.join(sdf2, sdf1["col1"] == sdf2["col1"], "outer")
>>> sdf.withColumn("_merge", when(sdf1["col1"].isNull(), "right_only").when(sdf2["col1"].isNull(), "left_only").otherwise("both"))\
... .withColumn("col1", coalesce(sdf1["col1"], sdf2["col1"]))\
... .drop(sdf1["col1"])\
... .drop(sdf2["col1"])
</code></pre>
| 2 | 2016-08-02T22:07:48Z | [
"python",
"pandas",
"pyspark",
"spark-dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.