title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
scrape Url and text from website using lxml python
39,214,339
<p>I don't know much about lxml and xpaths and I want to learn how to scrape data from website. When I run this code I don't get any results and don't know why. Please help me to fix it.</p> <p>code here</p> <pre><code>from lxml import html import requests pageLen=str(100) page = requests.get('http://www.yellowpages.com/search?search_terms=lawyer&amp;geo_location_terms=usa&amp;page=2') print(page) tree = html.fromstring(page.content) #phoneNumber = tree.xpath('//span[@class="c411Phone"]/text()') Link=tree.xpath('//div[@class="info"]/a/@href') Bname=tree.xpath('//a[@class="business-name"]/text()') print(Bussiness_names) print(Bname) </code></pre> <p>HTML CODE</p> <p><img src="http://i.stack.imgur.com/Ar0oG.png" alt="enter image description here"></p>
-1
2016-08-29T20:07:17Z
39,216,900
<p>Thank you @Abd Azrad. Your solution helped me a lot.</p> <p>Can you please further guide me? I am confused how to deal with inconsistent data? Sometimes, there are postal address missing and sometimes location missing. I just want to ignore that data which does not fulfill my requirements.<br> <code> page = requests.get('http://www.yellowpages.com/search?search_terms=%s&amp;geo_location_terms=%s&amp;page=%s'%("lawyer","toronot","2")) tree = html.fromstring(page.text) bus_names=tree.xpath('//a[@class="business-name"]/text()') print bus_names ##bus_url=tree.xpath('//a[@class="business-name"]/href()') ##print bus_url street_ad=tree.xpath('//span[@class="street-address"]/text()') print(street_ad) loc=tree.xpath('//span[@class="locality"]/text()') print(loc) postal=tree.xpath('//span[@itemprop="postalCode"]/text()') print(postal) contact=tree.xpath('//div[@class="phones phone primary"]/text()') print(contact)</code></p> <p>In this way I am getting list and I failed to keep track data because lists lenght is not same. Is there any way to get data of every person in list and all data in form of 2d list [[person_one_name,person_one_address],[person_two_name,person_two_contact]]?</p>
0
2016-08-29T23:56:09Z
[ "python", "web-scraping", "lxml" ]
PostgreSQL: Unable to drop a specific table named "user"
39,214,369
<p>I'm unable to delete a specific table in my PostgreSQL database. That table is called "user". When I try to run the snippet of code below,</p> <pre><code> import psycopg2 conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'") cur = conn.cursor() cur.execute("DROP TABLE user;") conn.commit() conn.close() </code></pre> <p>It spits out the following error</p> <pre><code> Traceback (most recent call last): File "dev_psycog.py", line 20, in &lt;module&gt; cur.execute("DROP TABLE user;") psycopg2.ProgrammingError: syntax error at or near "user" LINE 1: DROP TABLE user; </code></pre> <p>I can delete any other table in my database just fine, but I can't seem to delete my table called "user". Is it because "user" is a <a href="https://www.postgresql.org/docs/7.3/static/sql-keywords-appendix.html" rel="nofollow">reserved keyword</a>?</p>
2
2016-08-29T20:09:01Z
39,214,396
<p>Quote "user" as below</p> <pre><code>import psycopg2 conn = psycopg2.connect("dbname='mydatabase' user='postgres' host='localhost' password='mypassword'") cur = conn.cursor() cur.execute('DROP TABLE "user";') conn.commit() conn.close() </code></pre> <p>See <a href="https://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html" rel="nofollow">here</a>.</p> <blockquote> <p>There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes (").</p> </blockquote>
0
2016-08-29T20:11:28Z
[ "python", "sql", "postgresql", "psycopg2" ]
Running Flask dev server in Python 3.6 raises ImportError for SocketServer and ForkingMixIn
39,214,395
<p>I am trying to run a basic Flask app using Python 3.6. However, I get an <code>ImportError: cannot import name 'ForkingMixIn'</code>. I don't get this error when running with Python 2.7 or 3.5. How can I run Flask with Python 3.6?</p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" </code></pre> <pre><code>Traceback (most recent call last): File "C:\Python36\lib\site-packages\werkzeug\serving.py", line 65, in &lt;module&gt; from SocketServer import ThreadingMixIn, ForkingMixIn ImportError: No module named 'SocketServer' During handling of the above exception, another exception occurred: Traceback (most recent call last): File ".\fsk.py", line 9, in &lt;module&gt; app.run() File "C:\Python36\lib\site-packages\flask\app.py", line 828, in run from werkzeug.serving import run_simple File "C:\Python36\lib\site-packages\werkzeug\serving.py", line 68, in &lt;module&gt; from socketserver import ThreadingMixIn, ForkingMixIn ImportError: cannot import name 'ForkingMixIn' </code></pre>
2
2016-08-29T20:11:22Z
39,214,538
<p>This is a known issue that was <a href="https://github.com/pallets/werkzeug/pull/999" rel="nofollow">reported to Werkzeug</a> in anticipation of Python 3.6. Until that or another patch is merged and released, Werkzeug's dev server will not run on Python 3.6.</p> <blockquote> <p>Check if OS can fork before importing <code>ForkingMixIn</code> since Python 3.6 will no longer define that when it is not available on the operating system (<a href="https://github.com/python/cpython/commit/aadff9bea61a2fc9f4cf0f213f0ee50fc54d6574" rel="nofollow">python/cpython@aadff9b</a>) and <code>ImportError: cannot import name 'ForkingMixIn'</code> will occur.</p> </blockquote> <p>In the mean time, you can run your app with an external WSGI server such as Gunicorn.</p> <pre><code>pip install gunicorn gunicorn my_app:app </code></pre> <p>You can wrap your app in the <a href="http://werkzeug.pocoo.org/docs/0.11/debug/#werkzeug.debug.DebuggedApplication" rel="nofollow">debug middleware</a> if you need the in-page debugger (as long as you only run Gunicorn with one worker).</p>
0
2016-08-29T20:19:21Z
[ "python", "flask", "werkzeug", "python-3.6" ]
Fetching first record from NDB datastore in GAE
39,214,414
<p>I'm currently writing an application on the Google App Engine for Python. I want to fetch the first record in my datastore, but for some reason this won't work. This is how I'd do it in MySQL:</p> <pre><code>SELECT * FROM MyClass LIMIT 1; </code></pre> <p>However since I'm new to NDB, I can't quite seem to wrap my head around how this works. I tried reading <a href="https://cloud.google.com/appengine/docs/python/ndb/queryclass" rel="nofollow">the documentation</a> for examples but they don't quite work.</p> <p>This is the code I currently have:</p> <pre><code>from google.appengine.ext.ndb import Model as NdbModel from google.appengine.ext.ndb import StringProperty class Model(NdbModel): @classmethod def get_first(cls): """ Get the first record in the model datastore :return: Model """ try: return cls.query().fetch(1)[0] except IndexError: raise ModelException("No records found in [%s] datastore" % cls.__name__) class MyClass(Model): foo = StringProperty() bar = StringProperty() a = MyClass.get_first() # TypeError: 'NoneType' object does not support item assignment </code></pre> <hr> <p>This is my full stack trace:</p> <pre><code>TypeError: 'NoneType' object does not support item assignment at _store_value (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py:1127) at _deserialize (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py:1496) at _from_pb (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py:3209) at pb_to_entity (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py:691) at pb_to_query_result (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py:201) at _process_results (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_query.py:2980) at __query_result_hook (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_query.py:2947) at get_result (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py:613) at _on_rpc_completion (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py:513) at _run_to_list (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/query.py:995) at _help_tasklet_along (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py:427) at get_result (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py:383) at fetch (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/query.py:1218) at positional_wrapper (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/utils.py:160) at get_first (/base/data/home/apps/s~project-id/v1.395271489319521947/project/core/models/utils.py:55) at me (/base/data/home/apps/s~project-id/v1.395271489319521947/project/core/routes/api/v1/profile.py:22) at dispatch_request (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1625) at full_dispatch_request (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1639) at handle_user_exception (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1544) at full_dispatch_request (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1641) at wsgi_app (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1988) at handle_exception (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1567) at wsgi_app (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:1991) at __call__ (/base/data/home/apps/s~project-id/v1.395271489319521947/lib/flask/app.py:2000) at Handle (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:267) </code></pre>
0
2016-08-29T20:12:39Z
39,332,538
<p>It seems like you are trying to retrieve the data immediately after it is written to the Datastore which will not work unless you set the same <code>parent key</code> on each entity as stated in App Engine's <a href="https://cloud.google.com/appengine/docs/python/getting-started/storing-data-datastore" rel="nofollow">Storing Data in Cloud Datastore</a> document.</p> <p>To create a <code>parent key</code>, you could write:</p> <pre><code>from google.appengine.ext.ndb import Key parent_key = Key('my_data', 'version_1') </code></pre> <p>and when you create your entity you should pass the <code>parent key</code> to the <code>constructor</code>:</p> <pre><code>my_entity = MyKindClass(parent=parent_key, foo=foo_input, bar=bar_input) </code></pre> <p>Then, you query your database by passing the <code>parent_key</code> to <code>query</code> method of your <code>kind</code> class:</p> <pre><code>first_result = MyKindClass.query( ancestor=parent_key).order(-MyKindClass.created).get() </code></pre> <p>I think you are interested in getting the latest data, so I ordered the results using <code>order</code> method with <code>-</code> operator which orders data descendingly. In addition, I used <code>get</code> method instead of <code>fetch(1)</code> which returns the first query result or <code>None</code> if there is no data.</p> <p>The full code will be:</p> <pre><code>import webapp2 from google.appengine.ext.ndb import ( Model, StringProperty, DateTimeProperty, Key) class MyKindClass(Model): foo = StringProperty() bar = StringProperty() created = DateTimeProperty(auto_now_add=True) parent_key = Key('my_data', 'version_1') class MainHandler(webapp2.RequestHandler): def get(self): foo_input = self.request.get('foo') bar_input = self.request.get('bar') if foo_input and bar_input: my_entity = MyKindClass(parent=parent_key, foo=foo_input, bar=bar_input) my_entity.put() first_result = MyKindClass.query( ancestor=parent_key).order(-MyKindClass.created).get() if first_result is not None: self.response.write('foo: %s, and bar: %s' % (first_result.foo, first_result.bar)) else: self.response.write('No data yet!') app = webapp2.WSGIApplication([ ('/', MainHandler) ], debug=True) </code></pre> <p>For more information, see App Engine's <a href="https://cloud.google.com/appengine/docs/python/ndb/" rel="nofollow">The Python NDB Client Library Overview</a> document.</p>
0
2016-09-05T14:16:22Z
[ "python", "google-app-engine" ]
Where to get name of signature algorithm from SSLSocket?
39,214,464
<p>I could not find a suitable way to get the name of the signature algorithm used for a certificate that is received by an SSLSocket. I'm aware you can pull the bytes of the peer's cert with <code>SSLSocket.getpeercert(True)</code> but I don't know what to do with it past that. PyOpenSSL doesn't seem to have an easy interface to load an X509 from it's byte content. </p> <p>I would like to know this information as certificates with SHA1 are not allowed to have expiration times after January 1st, 2017 and this is not checked by Python's <code>SSLSocket.do_handshake()</code> implementation.</p>
0
2016-08-29T20:15:19Z
39,231,835
<p>After the very helpful comment pointing me in the right direction, you can use the <code>cryptography</code> module to load the DER X509 format that the <code>SSLSocket.getpeercert()</code> function outputs. From this <code>Certificate</code> instance you can also access many other fields about the certificate such as expiration time. Here is the way that I am doing it right now:</p> <pre><code>import cryptography.x509 import cryptography.hazmat.backends.openssl import ssl sock = ssl.SSLSocket() # Wrap a socket, connect, handshake, etc etc... cert = cryptography.x509.load_der_x509_certificate( sock.getpeercert(True), cryptography.hazmat.backends.openssl.backend ) print(cert.signature_hash_algorithm.name) # This prints "sha1". </code></pre>
0
2016-08-30T15:39:30Z
[ "python", "ssl", "digital-signature", "x509", "verification" ]
How to rank plot in seaborn boxplot?
39,214,484
<p>Take the following seaborn boxplot for example, from <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html</a></p> <pre><code>import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes ax = sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, color="c") # Add in points to show each observation sns.stripplot(x="distance", y="method", data=planets, jitter=True, size=3, color=".3", linewidth=0) # Make the quantitative axis logarithmic ax.set_xscale("log") sns.despine(trim=True) </code></pre> <p><a href="http://i.stack.imgur.com/O298h.png" rel="nofollow"><img src="http://i.stack.imgur.com/O298h.png" alt="enter image description here"></a></p> <p>Is it possible to "rank" the entries, from greatest to lowest (or vice versa)? In this plot, "astrometry" should be the last entry, if ranking from greatest to lowest.</p>
0
2016-08-29T20:16:18Z
39,215,275
<p>You can use the <code>order</code> argument in the <code>sns.boxplot</code> and <code>sns.stripplot</code> functions to order your "boxes". Here is an example of how to do this (since it is not completely clear what you mean by "greatest to lowest", i.e. which variable you want to sort the entries based on, I am assume you want to sort them based on the sum of their "distance" values, you should be able to edit the solution to fit your needs if you want to sort them based on a different value):</p> <pre><code>import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") # Determine the order of boxes order = planets.groupby(by=["method"])["distance"].sum().iloc[::-1].index # Plot the orbital period with horizontal boxes ax = sns.boxplot(x="distance", y="method", data=planets, order=order, whis=np.inf, color="c") # Add in points to show each observation sns.stripplot(x="distance", y="method", data=planets, order=order, jitter=True, size=3, color=".3", linewidth=0) # Make the quantitative axis logarithmic ax.set_xscale("log") sns.despine(trim=True) </code></pre> <p>This modifed code (notice the use of the <code>order</code> argument in the <code>sns.boxplot</code> and <code>sns.stripplot</code> functions) will produce the following figure:</p> <p><a href="http://i.stack.imgur.com/LEQgl.png" rel="nofollow"><img src="http://i.stack.imgur.com/LEQgl.png" alt="Ordered Boxplot"></a></p>
0
2016-08-29T21:10:46Z
[ "python", "pandas", "matplotlib", "seaborn" ]
How to rank plot in seaborn boxplot?
39,214,484
<p>Take the following seaborn boxplot for example, from <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_boxplot.html</a></p> <pre><code>import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes ax = sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, color="c") # Add in points to show each observation sns.stripplot(x="distance", y="method", data=planets, jitter=True, size=3, color=".3", linewidth=0) # Make the quantitative axis logarithmic ax.set_xscale("log") sns.despine(trim=True) </code></pre> <p><a href="http://i.stack.imgur.com/O298h.png" rel="nofollow"><img src="http://i.stack.imgur.com/O298h.png" alt="enter image description here"></a></p> <p>Is it possible to "rank" the entries, from greatest to lowest (or vice versa)? In this plot, "astrometry" should be the last entry, if ranking from greatest to lowest.</p>
0
2016-08-29T20:16:18Z
39,215,913
<p>Try this: </p> <pre><code>import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") ranks = planets.groupby("method")["distance"].mean().fillna(0).sort_values()[::-1].index # Plot the orbital period with horizontal boxes ax = sns.boxplot(x="distance", y="method", data=planets, whis=np.inf, color="c", order = ranks) # Add in points to show each observation sns.stripplot(x="distance", y="method", data=planets, jitter=True, size=3, color=".3", linewidth=0, order = ranks) # Make the quantitative axis logarithmic ax.set_xscale("log") sns.despine(trim=True) </code></pre> <p><a href="http://i.stack.imgur.com/FYJlf.png" rel="nofollow"><img src="http://i.stack.imgur.com/FYJlf.png" alt="image"></a></p>
1
2016-08-29T22:06:38Z
[ "python", "pandas", "matplotlib", "seaborn" ]
Understanding asyncio: Asynchronous vs synchronous callbacks
39,214,526
<p>There's one very particular thing about <code>asyncio</code> that I can't seem to understand. And that is the difference between asynchronous and synchronous callbacks. Let me introduce some examples.</p> <p>Asyncio TCP example:</p> <pre><code>class EchoServer(asyncio.Protocol): def connection_made(self, transport): print('connection made') def data_received(self, data): print('data received: ', data.decode()) def eof_received(self): pass def connection_lost(self, exc): print('connection lost:', exc) </code></pre> <p>Aiohttp example:</p> <pre><code>async def simple(request): return Response(text="Simple answer") async def init(loop): app = Application(loop=loop) app.router.add_get('/simple', simple) return app loop = asyncio.get_event_loop() app = loop.run_until_complete(init(loop)) run_app(app, loop=loop) </code></pre> <p>Those two examples are very similar in functionality but they seem to be both doing it in different way. In the first example, if you want to be notified on some action, you specify a synchronous function (<code>EchoServer.connection_made</code>). However, in the second example, if you want to be notified on some action, you have to define an asynchronous callback function (<code>simple</code>).</p> <p>I would like to ask what is the difference between these two types of callback. I understand the difference between regular functions and asynchronous functions, but I cannot wrap my head around the callback difference. For example, if I would want to write an asynchrnonous API like <code>aiohttp</code> is, and I would have a function that would do something and call a callback after that, how would I decide if I should demand an asynchronous function to be passed as an argument or just a regular synchronous one?</p>
3
2016-08-29T20:18:40Z
39,232,069
<p>In <code>aiohttp</code> example you could do asynchronous calls from <code>simple</code> web-handler: access to database, make http requests etc.</p> <p>In <code>Protocol.data_received()</code> you should call only regular synchronous methods.</p> <p><strong>UPD</strong></p> <p><code>Protocol</code> callbacks are supposed to be synchronous by design. They are very low-level bridge between sync and async. You may call async code from them but it requires really tricky coding. User level <code>asyncio</code> API for sockets etc. are streams: <a href="https://docs.python.org/3/library/asyncio-stream.html" rel="nofollow">https://docs.python.org/3/library/asyncio-stream.html</a></p> <p>When you introduce your own callback system must likely you need asynchronous callback unless you are %100 sure why the callback will never want to call async code.</p> <p>Regular functions (<code>def</code>) and coroutines (<code>async def</code>) have a different signatures. It's hard to change a required signature, especially if your code has published as a library and you cannot control all users of your callback.</p> <p>P.S.</p> <p>The same is true for any public API methods.</p> <p>The hardest lesson I've learned during development of my libraries is: <code>.close()</code> method <strong>should</strong> be a coroutine even initially it calls sync functions only, e.g. <code>socket.close()</code>.</p> <p>But later you perhaps will want to add a graceful shutdown which requires a waiting for current activity finishing and so on.</p> <p>If your users had call your api as <code>obj.close()</code> now they should use <code>await obj.close()</code> but it's <strong>backward incompatible</strong> change!</p>
1
2016-08-30T15:51:48Z
[ "python", "asynchronous", "callback", "python-asyncio" ]
(PY)Object has no attribute error
39,214,577
<pre><code># The imports include turtle graphics and tkinter modules. # The colorchooser and filedialog modules let the user # pick a color and a filename. import turtle import tkinter import tkinter.colorchooser import tkinter.filedialog import xml.dom.minidom # The following classes define the different commands that # are supported by the drawing application. class GoToCommand: def __init__(self,x,y,width=1,color="black"): self.x = x self.y = y self.width = width self.color = color # The draw method for each command draws the command # using the given turtle def draw(self,turtle): turtle.width(self.width) turtle.pencolor(self.color) turtle.goto(self.x,self.y) # The __str__ method is a special method that is called # when a command is converted to a string. The string # version of the command is how it appears in the graphics # file format. def __str__(self): return '&lt;Command x="' + str(self.x) + '" y="' + str(self.y) + \ '" width="' + str(self.width) \ + '" color="' + self.color + '"&gt;GoTo&lt;/Command&gt;' class CircleCommand: def __init__(self,radius, width=1,color="black"): self.radius = radius self.width = width self.color = color def draw(self,turtle): turtle.width(self.width) turtle.pencolor(self.color) turtle.circle(self.radius) def __str__(self): return '&lt;Command radius="' + str(self.radius) + '" width="' + \ str(self.width) + '" color="' + self.color + '"&gt;Circle&lt;/Command&gt;' class TextCommand: def __init__(self, move=False, align="left", font=("Arial", 8, "normal")): self.move = move self.align = align self.font = font def draw(self,turtle): #turtle.write("test",self.move,self.align,self.font) turtle.move(self.move) turtle.align(self.align) turtle.font(self.font) def __str__(self): return '&lt;Command TODO ENTER COMMAND&gt;' class BeginFillCommand: def __init__(self,color): self.color = color def draw(self,turtle): turtle.fillcolor(self.color) turtle.begin_fill() def __str__(self): return '&lt;Command color="' + self.color + '"&gt;BeginFill&lt;/Command&gt;' class EndFillCommand: def __init__(self): pass def draw(self,turtle): turtle.end_fill() def __str__(self): return "&lt;Command&gt;EndFill&lt;/Command&gt;" class PenUpCommand: def __init__(self): pass def draw(self,turtle): turtle.penup() def __str__(self): return "&lt;Command&gt;PenUp&lt;/Command&gt;" class PenDownCommand: def __init__(self): pass def draw(self,turtle): turtle.pendown() def __str__(self): return "&lt;Command&gt;PenDown&lt;/Command&gt;" # This is the PyList container object. It is meant to hold a class PyList: def __init__(self): self.gcList = [] # The append method is used to add commands to the sequence. def append(self,item): self.gcList = self.gcList + [item] # This method is used by the undo function. It slices the sequence # to remove the last item def removeLast(self): self.gcList = self.gcList[:-1] # This special method is called when iterating over the sequence. # Each time yield is called another element of the sequence is returned # to the iterator (i.e. the for loop that called this.) def __iter__(self): for c in self.gcList: yield c # This is called when the len function is called on the sequence. def __len__(self): return len(self.gcList) # This class defines the drawing application. The following line says that # the DrawingApplication class inherits from the Frame class. This means # that a DrawingApplication is like a Frame object except for the code # written here which redefines/extends the behavior of a Frame. class DrawingApplication(tkinter.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.buildWindow() self.graphicsCommands = PyList() # This method is called to create all the widgets, place them in the GUI, # and define the event handlers for the application. def buildWindow(self): # The master is the root window. The title is set as below. self.master.title("Draw") # Here is how to create a menu bar. The tearoff=0 means that menus # can't be separated from the window which is a feature of tkinter. bar = tkinter.Menu(self.master) fileMenu = tkinter.Menu(bar,tearoff=0) # This code is called by the "New" menu item below when it is selected. # The same applies for loadFile, addToFile, and saveFile below. The # "Exit" menu item below calls quit on the "master" or root window. def newWindow(): # This sets up the turtle to be ready for a new picture to be # drawn. It also sets the sequence back to empty. It is necessary # for the graphicsCommands sequence to be in the object (i.e. # self.graphicsCommands) because otherwise the statement: # graphicsCommands = PyList() # would make this variable a local variable in the newWindow # method. If it were local, it would not be set anymore once the # newWindow method returned. theTurtle.clear() theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() screen.update() screen.listen() self.graphicsCommands = PyList() fileMenu.add_command(label="New",command=newWindow) # The parse function adds the contents of an XML file to the sequence. def parse(filename): xmldoc = xml.dom.minidom.parse(filename) graphicsCommandsElement = xmldoc.getElementsByTagName("GraphicsCommands")[0] graphicsCommands = graphicsCommandsElement.getElementsByTagName("Command") for commandElement in graphicsCommands: print(type(commandElement)) command = commandElement.firstChild.data.strip() attr = commandElement.attributes if command == "GoTo": x = float(attr["x"].value) y = float(attr["y"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = GoToCommand(x,y,width,color) elif command == "Circle": radius = float(attr["radius"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = CircleCommand(radius,width,color) elif command == "BeginFill": color = attr["color"].value.strip() cmd = BeginFillCommand(color) elif command == "EndFill": cmd = EndFillCommand() elif command == "PenUp": cmd = PenUpCommand() elif command == "PenDown": cmd = PenDownCommand() else: raise RuntimeError("Unknown Command: " + command) self.graphicsCommands.append(cmd) def loadFile(): filename = tkinter.filedialog.askopenfilename(title="Select a Graphics File") newWindow() # This re-initializes the sequence for the new picture. self.graphicsCommands = PyList() # calling parse will read the graphics commands from the file. parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) # This line is necessary to update the window after the picture is drawn. screen.update() fileMenu.add_command(label="Load...",command=loadFile) def addToFile(): filename = tkinter.filedialog.askopenfilename(title="Select a Graphics File") theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() theTurtle.pencolor("#000000") theTurtle.fillcolor("#000000") cmd = PenUpCommand() self.graphicsCommands.append(cmd) cmd = GoToCommand(0,0,1,"#000000") self.graphicsCommands.append(cmd) cmd = PenDownCommand() self.graphicsCommands.append(cmd) screen.update() parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() fileMenu.add_command(label="Load Into...",command=addToFile) # The write function writes an XML file to the given filename def write(filename): file = open(filename, "w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') file.write('&lt;GraphicsCommands&gt;\n') for cmd in self.graphicsCommands: file.write(' '+str(cmd)+"\n") file.write('&lt;/GraphicsCommands&gt;\n') file.close() def saveFile(): filename = tkinter.filedialog.asksaveasfilename(title="Save Picture As...") write(filename) fileMenu.add_command(label="Save As...",command=saveFile) fileMenu.add_command(label="Exit",command=self.master.quit) bar.add_cascade(label="File",menu=fileMenu) # This tells the root window to display the newly created menu bar. self.master.config(menu=bar) # Here several widgets are created. The canvas is the drawing area on # the left side of the window. canvas = tkinter.Canvas(self,width=600,height=600) canvas.pack(side=tkinter.LEFT) # By creating a RawTurtle, we can have the turtle draw on this canvas. # Otherwise, a RawTurtle and a Turtle are exactly the same. theTurtle = turtle.RawTurtle(canvas) # This makes the shape of the turtle a circle. theTurtle.shape("circle") screen = theTurtle.getscreen() # This causes the application to not update the screen unless # screen.update() is called. This is necessary for the ondrag event # handler below. Without it, the program bombs after dragging the # turtle around for a while. screen.tracer(0) # This is the area on the right side of the window where all the # buttons, labels, and entry boxes are located. The pad creates some empty # space around the side. The side puts the sideBar on the right side of the # this frame. The fill tells it to fill in all space available on the right # side. sideBar = tkinter.Frame(self,padx=5,pady=5) sideBar.pack(side=tkinter.RIGHT, fill=tkinter.BOTH) # This is a label widget. Packing it puts it at the top of the sidebar. pointLabel = tkinter.Label(sideBar,text="Width") pointLabel.pack() # This entry widget allows the user to pick a width for their lines. # With the widthSize variable below you can write widthSize.get() to get # the contents of the entry widget and widthSize.set(val) to set the value # of the entry widget to val. Initially the widthSize is set to 1. str(1) is # needed because the entry widget must be given a string. widthSize = tkinter.StringVar() widthEntry = tkinter.Entry(sideBar,textvariable=widthSize) widthEntry.pack() widthSize.set(str(1)) radiusLabel = tkinter.Label(sideBar,text="Radius") radiusLabel.pack() radiusSize = tkinter.StringVar() radiusEntry = tkinter.Entry(sideBar,textvariable=radiusSize) radiusSize.set(str(10)) radiusEntry.pack() # A button widget calls an event handler when it is pressed. The circleHandler # function below is the event handler when the Draw Circle button is pressed. def circleHandler(): # When drawing, a command is created and then the command is drawn by calling # the draw method. Adding the command to the graphicsCommands sequence means the # application will remember the picture. cmd = CircleCommand(float(radiusSize.get()), float(widthSize.get()), penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) # These two lines are needed to update the screen and to put the focus back # in the drawing canvas. This is necessary because when pressing "u" to undo, # the screen must have focus to receive the key press. screen.update() screen.listen() def textHandler(): # When drawing, a command is created and then the command is drawn by calling # the draw method. Adding the command to the graphicsCommands sequence means the # application will remember the picture. cmd = TextCommand(False, penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) # These two lines are needed to update the screen and to put the focus back # in the drawing canvas. This is necessary because when pressing "u" to undo, # the screen must have focus to receive the key press. screen.update() screen.listen() # This creates the button widget in the sideBar. The fill=tkinter.BOTH causes the button # to expand to fill the entire width of the sideBar. circleButton = tkinter.Button(sideBar, text = "Draw Circle", command=circleHandler) circleButton.pack(fill=tkinter.BOTH) textButton = tkinter.Button(sideBar, text = "Draw Text", command=textHandler) textButton.pack(fill=tkinter.BOTH) # The color mode 255 below allows colors to be specified in RGB form (i.e. Red/ # Green/Blue). The mode allows the Red value to be set by a two digit hexadecimal # number ranging from 00-FF. The same applies for Blue and Green values. The # color choosers below return a string representing the selected color and a slice # is taken to extract the #RRGGBB hexadecimal string that the color choosers return. screen.colormode(255) penLabel = tkinter.Label(sideBar,text="Pen Color") penLabel.pack() penColor = tkinter.StringVar() penEntry = tkinter.Entry(sideBar,textvariable=penColor) penEntry.pack() # This is the color black. penColor.set("#000000") def getPenColor(): color = tkinter.colorchooser.askcolor() if color != None: penColor.set(str(color)[-9:-2]) penColorButton = tkinter.Button(sideBar, text = "Pick Pen Color", command=getPenColor) penColorButton.pack(fill=tkinter.BOTH) fillLabel = tkinter.Label(sideBar,text="Fill Color") fillLabel.pack() fillColor = tkinter.StringVar() fillEntry = tkinter.Entry(sideBar,textvariable=fillColor) fillEntry.pack() fillColor.set("#000000") def getFillColor(): color = tkinter.colorchooser.askcolor() if color != None: fillColor.set(str(color)[-9:-2]) fillColorButton = \ tkinter.Button(sideBar, text = "Pick Fill Color", command=getFillColor) fillColorButton.pack(fill=tkinter.BOTH) def beginFillHandler(): cmd = BeginFillCommand(fillColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) beginFillButton = tkinter.Button(sideBar, text = "Begin Fill", command=beginFillHandler) beginFillButton.pack(fill=tkinter.BOTH) def endFillHandler(): cmd = EndFillCommand() cmd.draw(theTurtle) self.graphicsCommands.append(cmd) endFillButton = tkinter.Button(sideBar, text = "End Fill", command=endFillHandler) endFillButton.pack(fill=tkinter.BOTH) penLabel = tkinter.Label(sideBar,text="Pen Is Down") penLabel.pack() def penUpHandler(): cmd = PenUpCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Up") self.graphicsCommands.append(cmd) penUpButton = tkinter.Button(sideBar, text = "Pen Up", command=penUpHandler) penUpButton.pack(fill=tkinter.BOTH) def penDownHandler(): cmd = PenDownCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Down") self.graphicsCommands.append(cmd) penDownButton = tkinter.Button(sideBar, text = "Pen Down", command=penDownHandler) penDownButton.pack(fill=tkinter.BOTH) # Here is another event handler. This one handles mouse clicks on the screen. def clickHandler(x,y): # When a mouse click occurs, get the widthSize entry value and set the width of the # pen to the widthSize value. The float(widthSize.get()) is needed because # the width is an integer, but the entry widget stores it as a string. cmd = GoToCommand(x,y,float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() # Here is how we tie the clickHandler to mouse clicks. screen.onclick(clickHandler) def dragHandler(x,y): cmd = GoToCommand(x,y,float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() theTurtle.ondrag(dragHandler) # the undoHandler undoes the last command by removing it from the # sequence and then redrawing the entire picture. def undoHandler(): if len(self.graphicsCommands) &gt; 0: self.graphicsCommands.removeLast() theTurtle.clear() theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() screen.listen() screen.onkeypress(undoHandler, "u") screen.listen() # The main function in our GUI program is very simple. It creates the # root window. Then it creates the DrawingApplication frame which creates # all the widgets and has the logic for the event handlers. Calling mainloop # on the frames makes it start listening for events. The mainloop function will # return when the application is exited. def main(): root = tkinter.Tk() drawingApp = DrawingApplication(root) drawingApp.mainloop() print("Program Execution Completed.") if __name__ == "__main__": main() </code></pre> <p>Running the following code works flawlessly, once it is ran I would press the button labeled "Draw Text" and the following error is displayed:</p> <pre><code>C:\Python34\python.exe C:/Users/ThinkTank/PycharmProjects/untitled2/1/__init__.py Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) File "C:/Users/ThinkTank/PycharmProjects/untitled2/1/__init__.py", line 354, in textHandler cmd.draw(theTurtle) File "C:/Users/ThinkTank/PycharmProjects/untitled2/1/__init__.py", line 57, in draw turtle.move(self.move) AttributeError: 'RawTurtle' object has no attribute 'move' </code></pre> <p>There is a task which requires me to draw some text on a tkinter screen using turtle. I have added in code which tells the turtle to draw this if the button in the menu is pressed, but this error than shows up. I am rather new to python and don't understand how to go about fixing such a problem.</p>
-3
2016-08-29T20:22:09Z
39,214,695
<p>The problem is that the <code>RawTurtle</code> object, from the turtle module, has no attribute <code>move</code>. You can use the commands <code>forward</code>, <code>backward</code>, <code>left</code>, and <code>right</code> to move your turtle. Before using the above commands, I suggest looking at the <a href="https://docs.python.org/2/library/turtle.html" rel="nofollow">documentation for the turtle module</a>, as you seem to be confused about how to properly use it.</p> <p>Here is a quick explanation for the basic turtle move methods:</p> <ul> <li><code>turtle.forward(int\float)</code>: This method moves a turtle object forward(in pixels). Use a integer or a float to specify how far to move the turtle.</li> <li><code>turtle.backward(int\float)</code>: This method moves a turtle object backwards(in pixels). Use a integer or a float to specify how far to move the turtle.</li> <li><code>turtle.left(int\float)</code>: This method turns a turtle object left(in degrees). Use a integer or a float to specify how far to turn the turtle.</li> <li><code>turtle.right(int\float)</code>: This method turns a turtle object right(in degrees). Use a integer or a float to specify how far to turn the turtle.</li> </ul>
1
2016-08-29T20:30:10Z
[ "python", "pycharm" ]
(PY)Object has no attribute error
39,214,577
<pre><code># The imports include turtle graphics and tkinter modules. # The colorchooser and filedialog modules let the user # pick a color and a filename. import turtle import tkinter import tkinter.colorchooser import tkinter.filedialog import xml.dom.minidom # The following classes define the different commands that # are supported by the drawing application. class GoToCommand: def __init__(self,x,y,width=1,color="black"): self.x = x self.y = y self.width = width self.color = color # The draw method for each command draws the command # using the given turtle def draw(self,turtle): turtle.width(self.width) turtle.pencolor(self.color) turtle.goto(self.x,self.y) # The __str__ method is a special method that is called # when a command is converted to a string. The string # version of the command is how it appears in the graphics # file format. def __str__(self): return '&lt;Command x="' + str(self.x) + '" y="' + str(self.y) + \ '" width="' + str(self.width) \ + '" color="' + self.color + '"&gt;GoTo&lt;/Command&gt;' class CircleCommand: def __init__(self,radius, width=1,color="black"): self.radius = radius self.width = width self.color = color def draw(self,turtle): turtle.width(self.width) turtle.pencolor(self.color) turtle.circle(self.radius) def __str__(self): return '&lt;Command radius="' + str(self.radius) + '" width="' + \ str(self.width) + '" color="' + self.color + '"&gt;Circle&lt;/Command&gt;' class TextCommand: def __init__(self, move=False, align="left", font=("Arial", 8, "normal")): self.move = move self.align = align self.font = font def draw(self,turtle): #turtle.write("test",self.move,self.align,self.font) turtle.move(self.move) turtle.align(self.align) turtle.font(self.font) def __str__(self): return '&lt;Command TODO ENTER COMMAND&gt;' class BeginFillCommand: def __init__(self,color): self.color = color def draw(self,turtle): turtle.fillcolor(self.color) turtle.begin_fill() def __str__(self): return '&lt;Command color="' + self.color + '"&gt;BeginFill&lt;/Command&gt;' class EndFillCommand: def __init__(self): pass def draw(self,turtle): turtle.end_fill() def __str__(self): return "&lt;Command&gt;EndFill&lt;/Command&gt;" class PenUpCommand: def __init__(self): pass def draw(self,turtle): turtle.penup() def __str__(self): return "&lt;Command&gt;PenUp&lt;/Command&gt;" class PenDownCommand: def __init__(self): pass def draw(self,turtle): turtle.pendown() def __str__(self): return "&lt;Command&gt;PenDown&lt;/Command&gt;" # This is the PyList container object. It is meant to hold a class PyList: def __init__(self): self.gcList = [] # The append method is used to add commands to the sequence. def append(self,item): self.gcList = self.gcList + [item] # This method is used by the undo function. It slices the sequence # to remove the last item def removeLast(self): self.gcList = self.gcList[:-1] # This special method is called when iterating over the sequence. # Each time yield is called another element of the sequence is returned # to the iterator (i.e. the for loop that called this.) def __iter__(self): for c in self.gcList: yield c # This is called when the len function is called on the sequence. def __len__(self): return len(self.gcList) # This class defines the drawing application. The following line says that # the DrawingApplication class inherits from the Frame class. This means # that a DrawingApplication is like a Frame object except for the code # written here which redefines/extends the behavior of a Frame. class DrawingApplication(tkinter.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.buildWindow() self.graphicsCommands = PyList() # This method is called to create all the widgets, place them in the GUI, # and define the event handlers for the application. def buildWindow(self): # The master is the root window. The title is set as below. self.master.title("Draw") # Here is how to create a menu bar. The tearoff=0 means that menus # can't be separated from the window which is a feature of tkinter. bar = tkinter.Menu(self.master) fileMenu = tkinter.Menu(bar,tearoff=0) # This code is called by the "New" menu item below when it is selected. # The same applies for loadFile, addToFile, and saveFile below. The # "Exit" menu item below calls quit on the "master" or root window. def newWindow(): # This sets up the turtle to be ready for a new picture to be # drawn. It also sets the sequence back to empty. It is necessary # for the graphicsCommands sequence to be in the object (i.e. # self.graphicsCommands) because otherwise the statement: # graphicsCommands = PyList() # would make this variable a local variable in the newWindow # method. If it were local, it would not be set anymore once the # newWindow method returned. theTurtle.clear() theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() screen.update() screen.listen() self.graphicsCommands = PyList() fileMenu.add_command(label="New",command=newWindow) # The parse function adds the contents of an XML file to the sequence. def parse(filename): xmldoc = xml.dom.minidom.parse(filename) graphicsCommandsElement = xmldoc.getElementsByTagName("GraphicsCommands")[0] graphicsCommands = graphicsCommandsElement.getElementsByTagName("Command") for commandElement in graphicsCommands: print(type(commandElement)) command = commandElement.firstChild.data.strip() attr = commandElement.attributes if command == "GoTo": x = float(attr["x"].value) y = float(attr["y"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = GoToCommand(x,y,width,color) elif command == "Circle": radius = float(attr["radius"].value) width = float(attr["width"].value) color = attr["color"].value.strip() cmd = CircleCommand(radius,width,color) elif command == "BeginFill": color = attr["color"].value.strip() cmd = BeginFillCommand(color) elif command == "EndFill": cmd = EndFillCommand() elif command == "PenUp": cmd = PenUpCommand() elif command == "PenDown": cmd = PenDownCommand() else: raise RuntimeError("Unknown Command: " + command) self.graphicsCommands.append(cmd) def loadFile(): filename = tkinter.filedialog.askopenfilename(title="Select a Graphics File") newWindow() # This re-initializes the sequence for the new picture. self.graphicsCommands = PyList() # calling parse will read the graphics commands from the file. parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) # This line is necessary to update the window after the picture is drawn. screen.update() fileMenu.add_command(label="Load...",command=loadFile) def addToFile(): filename = tkinter.filedialog.askopenfilename(title="Select a Graphics File") theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() theTurtle.pencolor("#000000") theTurtle.fillcolor("#000000") cmd = PenUpCommand() self.graphicsCommands.append(cmd) cmd = GoToCommand(0,0,1,"#000000") self.graphicsCommands.append(cmd) cmd = PenDownCommand() self.graphicsCommands.append(cmd) screen.update() parse(filename) for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() fileMenu.add_command(label="Load Into...",command=addToFile) # The write function writes an XML file to the given filename def write(filename): file = open(filename, "w") file.write('&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt;\n') file.write('&lt;GraphicsCommands&gt;\n') for cmd in self.graphicsCommands: file.write(' '+str(cmd)+"\n") file.write('&lt;/GraphicsCommands&gt;\n') file.close() def saveFile(): filename = tkinter.filedialog.asksaveasfilename(title="Save Picture As...") write(filename) fileMenu.add_command(label="Save As...",command=saveFile) fileMenu.add_command(label="Exit",command=self.master.quit) bar.add_cascade(label="File",menu=fileMenu) # This tells the root window to display the newly created menu bar. self.master.config(menu=bar) # Here several widgets are created. The canvas is the drawing area on # the left side of the window. canvas = tkinter.Canvas(self,width=600,height=600) canvas.pack(side=tkinter.LEFT) # By creating a RawTurtle, we can have the turtle draw on this canvas. # Otherwise, a RawTurtle and a Turtle are exactly the same. theTurtle = turtle.RawTurtle(canvas) # This makes the shape of the turtle a circle. theTurtle.shape("circle") screen = theTurtle.getscreen() # This causes the application to not update the screen unless # screen.update() is called. This is necessary for the ondrag event # handler below. Without it, the program bombs after dragging the # turtle around for a while. screen.tracer(0) # This is the area on the right side of the window where all the # buttons, labels, and entry boxes are located. The pad creates some empty # space around the side. The side puts the sideBar on the right side of the # this frame. The fill tells it to fill in all space available on the right # side. sideBar = tkinter.Frame(self,padx=5,pady=5) sideBar.pack(side=tkinter.RIGHT, fill=tkinter.BOTH) # This is a label widget. Packing it puts it at the top of the sidebar. pointLabel = tkinter.Label(sideBar,text="Width") pointLabel.pack() # This entry widget allows the user to pick a width for their lines. # With the widthSize variable below you can write widthSize.get() to get # the contents of the entry widget and widthSize.set(val) to set the value # of the entry widget to val. Initially the widthSize is set to 1. str(1) is # needed because the entry widget must be given a string. widthSize = tkinter.StringVar() widthEntry = tkinter.Entry(sideBar,textvariable=widthSize) widthEntry.pack() widthSize.set(str(1)) radiusLabel = tkinter.Label(sideBar,text="Radius") radiusLabel.pack() radiusSize = tkinter.StringVar() radiusEntry = tkinter.Entry(sideBar,textvariable=radiusSize) radiusSize.set(str(10)) radiusEntry.pack() # A button widget calls an event handler when it is pressed. The circleHandler # function below is the event handler when the Draw Circle button is pressed. def circleHandler(): # When drawing, a command is created and then the command is drawn by calling # the draw method. Adding the command to the graphicsCommands sequence means the # application will remember the picture. cmd = CircleCommand(float(radiusSize.get()), float(widthSize.get()), penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) # These two lines are needed to update the screen and to put the focus back # in the drawing canvas. This is necessary because when pressing "u" to undo, # the screen must have focus to receive the key press. screen.update() screen.listen() def textHandler(): # When drawing, a command is created and then the command is drawn by calling # the draw method. Adding the command to the graphicsCommands sequence means the # application will remember the picture. cmd = TextCommand(False, penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) # These two lines are needed to update the screen and to put the focus back # in the drawing canvas. This is necessary because when pressing "u" to undo, # the screen must have focus to receive the key press. screen.update() screen.listen() # This creates the button widget in the sideBar. The fill=tkinter.BOTH causes the button # to expand to fill the entire width of the sideBar. circleButton = tkinter.Button(sideBar, text = "Draw Circle", command=circleHandler) circleButton.pack(fill=tkinter.BOTH) textButton = tkinter.Button(sideBar, text = "Draw Text", command=textHandler) textButton.pack(fill=tkinter.BOTH) # The color mode 255 below allows colors to be specified in RGB form (i.e. Red/ # Green/Blue). The mode allows the Red value to be set by a two digit hexadecimal # number ranging from 00-FF. The same applies for Blue and Green values. The # color choosers below return a string representing the selected color and a slice # is taken to extract the #RRGGBB hexadecimal string that the color choosers return. screen.colormode(255) penLabel = tkinter.Label(sideBar,text="Pen Color") penLabel.pack() penColor = tkinter.StringVar() penEntry = tkinter.Entry(sideBar,textvariable=penColor) penEntry.pack() # This is the color black. penColor.set("#000000") def getPenColor(): color = tkinter.colorchooser.askcolor() if color != None: penColor.set(str(color)[-9:-2]) penColorButton = tkinter.Button(sideBar, text = "Pick Pen Color", command=getPenColor) penColorButton.pack(fill=tkinter.BOTH) fillLabel = tkinter.Label(sideBar,text="Fill Color") fillLabel.pack() fillColor = tkinter.StringVar() fillEntry = tkinter.Entry(sideBar,textvariable=fillColor) fillEntry.pack() fillColor.set("#000000") def getFillColor(): color = tkinter.colorchooser.askcolor() if color != None: fillColor.set(str(color)[-9:-2]) fillColorButton = \ tkinter.Button(sideBar, text = "Pick Fill Color", command=getFillColor) fillColorButton.pack(fill=tkinter.BOTH) def beginFillHandler(): cmd = BeginFillCommand(fillColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) beginFillButton = tkinter.Button(sideBar, text = "Begin Fill", command=beginFillHandler) beginFillButton.pack(fill=tkinter.BOTH) def endFillHandler(): cmd = EndFillCommand() cmd.draw(theTurtle) self.graphicsCommands.append(cmd) endFillButton = tkinter.Button(sideBar, text = "End Fill", command=endFillHandler) endFillButton.pack(fill=tkinter.BOTH) penLabel = tkinter.Label(sideBar,text="Pen Is Down") penLabel.pack() def penUpHandler(): cmd = PenUpCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Up") self.graphicsCommands.append(cmd) penUpButton = tkinter.Button(sideBar, text = "Pen Up", command=penUpHandler) penUpButton.pack(fill=tkinter.BOTH) def penDownHandler(): cmd = PenDownCommand() cmd.draw(theTurtle) penLabel.configure(text="Pen Is Down") self.graphicsCommands.append(cmd) penDownButton = tkinter.Button(sideBar, text = "Pen Down", command=penDownHandler) penDownButton.pack(fill=tkinter.BOTH) # Here is another event handler. This one handles mouse clicks on the screen. def clickHandler(x,y): # When a mouse click occurs, get the widthSize entry value and set the width of the # pen to the widthSize value. The float(widthSize.get()) is needed because # the width is an integer, but the entry widget stores it as a string. cmd = GoToCommand(x,y,float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() # Here is how we tie the clickHandler to mouse clicks. screen.onclick(clickHandler) def dragHandler(x,y): cmd = GoToCommand(x,y,float(widthSize.get()),penColor.get()) cmd.draw(theTurtle) self.graphicsCommands.append(cmd) screen.update() screen.listen() theTurtle.ondrag(dragHandler) # the undoHandler undoes the last command by removing it from the # sequence and then redrawing the entire picture. def undoHandler(): if len(self.graphicsCommands) &gt; 0: self.graphicsCommands.removeLast() theTurtle.clear() theTurtle.penup() theTurtle.goto(0,0) theTurtle.pendown() for cmd in self.graphicsCommands: cmd.draw(theTurtle) screen.update() screen.listen() screen.onkeypress(undoHandler, "u") screen.listen() # The main function in our GUI program is very simple. It creates the # root window. Then it creates the DrawingApplication frame which creates # all the widgets and has the logic for the event handlers. Calling mainloop # on the frames makes it start listening for events. The mainloop function will # return when the application is exited. def main(): root = tkinter.Tk() drawingApp = DrawingApplication(root) drawingApp.mainloop() print("Program Execution Completed.") if __name__ == "__main__": main() </code></pre> <p>Running the following code works flawlessly, once it is ran I would press the button labeled "Draw Text" and the following error is displayed:</p> <pre><code>C:\Python34\python.exe C:/Users/ThinkTank/PycharmProjects/untitled2/1/__init__.py Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) File "C:/Users/ThinkTank/PycharmProjects/untitled2/1/__init__.py", line 354, in textHandler cmd.draw(theTurtle) File "C:/Users/ThinkTank/PycharmProjects/untitled2/1/__init__.py", line 57, in draw turtle.move(self.move) AttributeError: 'RawTurtle' object has no attribute 'move' </code></pre> <p>There is a task which requires me to draw some text on a tkinter screen using turtle. I have added in code which tells the turtle to draw this if the button in the menu is pressed, but this error than shows up. I am rather new to python and don't understand how to go about fixing such a problem.</p>
-3
2016-08-29T20:22:09Z
39,214,699
<p>This is fairly straightforward. You initialize <code>theTurtle</code> in the caller to be a <code>turtle.RawTurtle</code>. <code>RawTurtle</code> doesn't have an attribute or method named <code>move</code>, <a href="https://docs.python.org/3/library/turtle.html#turtle-motion" rel="nofollow">it has special purpose methods for moving forward or backwards, and other methods to turn relatively (<code>right</code> and <code>left</code>) or to an absolute orientation (<code>setheading</code>)</a>.</p> <p>If your goal is to, say, move the turtle forward by <code>move</code> "distance" or something from its current heading, you'd call <code>forward</code>/<code>fd</code>.</p>
1
2016-08-29T20:30:26Z
[ "python", "pycharm" ]
Ternary using pass keyword python
39,214,741
<p>I have a working conditional statement:</p> <pre><code>if True: pass else: continue </code></pre> <p>that I would like to turn it into a ternary expression:</p> <pre><code>pass if True else continue </code></pre> <p>However, Python does not allow this. Can anyone help? </p> <p>Thanks!</p>
1
2016-08-29T20:34:01Z
39,214,775
<p>Ternary expression are used to compute values; neither <code>pass</code> nor <code>continue</code> are values.</p>
1
2016-08-29T20:36:10Z
[ "python", "conditional", "ternary" ]
Ternary using pass keyword python
39,214,741
<p>I have a working conditional statement:</p> <pre><code>if True: pass else: continue </code></pre> <p>that I would like to turn it into a ternary expression:</p> <pre><code>pass if True else continue </code></pre> <p>However, Python does not allow this. Can anyone help? </p> <p>Thanks!</p>
1
2016-08-29T20:34:01Z
39,214,784
<p><code>pass</code> and <code>continue</code> are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.</p> <p>Nevertheless, you can still shorten the condition you brought like this:</p> <pre><code>if False: continue </code></pre>
1
2016-08-29T20:36:42Z
[ "python", "conditional", "ternary" ]
Ternary using pass keyword python
39,214,741
<p>I have a working conditional statement:</p> <pre><code>if True: pass else: continue </code></pre> <p>that I would like to turn it into a ternary expression:</p> <pre><code>pass if True else continue </code></pre> <p>However, Python does not allow this. Can anyone help? </p> <p>Thanks!</p>
1
2016-08-29T20:34:01Z
39,214,823
<p><strong>Point 1</strong>: Are your sure your condition is right? Because <code>if True</code> will always be <code>True</code> and code will never go to <code>else</code> block. </p> <p><strong>Point 2</strong>: <code>pass</code> and <code>continue</code> are not expressions or values, but a action instead You can not use these is one line. Instead if you use, <code>3 if x else 4</code> &lt;-- it will work</p>
1
2016-08-29T20:39:37Z
[ "python", "conditional", "ternary" ]
get time difference in seconds for time referring to another timezone
39,214,761
<p>I intend to find the time difference between two time variables in seconds. The issue here is that I am referring to time in a different zone. I have managed to find a solution, but it is a mix of pandas.datetime function and python datetime library. I guess, the objective can be achieved with just pandas/numpy alone and with fewer lines of code. below is my code, appreciate any guidance on how can i achieve the final_output more efficiently.</p> <pre><code>import pandas as pd from datetime import timedelta local_time = pd.to_datetime('now').tz_localize('UTC').tz_convert('Asia/Dubai') t1 = timedelta(hours=local_time.now('Asia/Dubai').hour, minutes=local_time.now('Asia/Dubai').minute) t2 = timedelta(hours=9, minutes=14) final_output = (t2 - t1).seconds </code></pre>
0
2016-08-29T20:35:08Z
39,214,799
<p>You may want to convert both times to UTC, then find the difference. Programmers usually like to work with UTC until the time reaches the front end.</p>
0
2016-08-29T20:37:59Z
[ "python", "datetime", "pandas", "numpy", "timedelta" ]
PythonQt doesn't print anything
39,214,773
<p>I'm following the examples at <a href="http://pythonqt.sourceforge.net/Examples.html" rel="nofollow">http://pythonqt.sourceforge.net/Examples.html</a>, but PythonQt doesn't print anything on the console. I execute a script that just prints <code>hello</code>, but nothing gets printed.</p> <pre><code>PythonQt::init(); PythonQtObjectPtr context = PythonQt::self()-&gt;getMainModule(); context.evalScript("print 'hello'\n"); </code></pre> <p>On the other hand, if I execute it using plain python embedding it works and <code>hello</code> is printed:</p> <pre><code>Py_Initialize(); PyRun_SimpleString("print 'hello'\n"); </code></pre> <p>What's interesting is that if I add <code>PythonQt::init();</code> before <code>Py_Initialize();</code>, nothing gets printed again. So I assume <code>PythonQt::init();</code> does something to python's console output. Does it redirect it somehow? How do I make it print?</p> <p>I'm on Qt 4.8.6, PythonQt 2.1, and Python 2.7.6.</p>
0
2016-08-29T20:35:57Z
39,214,854
<p>After reading <a href="https://sourceforge.net/p/pythonqt/discussion/631393/thread/33ad915c" rel="nofollow">https://sourceforge.net/p/pythonqt/discussion/631393/thread/33ad915c</a>, it seems that <code>PythonQt::init();</code> does redirect python output to the PythonQt::pythonStdOut signal.</p> <p>This is because <code>PythonQt::init()</code> declaration sets <code>RedirectStdOut</code> by default:</p> <pre><code>static void init(int flags = IgnoreSiteModule | RedirectStdOut, const QByteArray&amp; pythonQtModuleName = QByteArray()); </code></pre> <p>So this works now:</p> <pre><code>PythonQt::init(PythonQt::IgnoreSiteModule); PythonQtObjectPtr context = PythonQt::self()-&gt;getMainModule(); context.evalScript("print 'hello'\n"); </code></pre> <p>Or alternatively, I could connect the signal:</p> <pre><code>QObject::connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&amp;)), this, SLOT(Print(const QString&amp;))); </code></pre>
1
2016-08-29T20:42:00Z
[ "python", "c++", "qt", "python-embedding", "pythonqt" ]
How to install python "gi" module in virtual environment?
39,214,803
<p>I have looked at <a href="http://stackoverflow.com/questions/12830662/python-package-installed-globally-but-not-in-a-virtualenv-pygtk">this</a>, and tried the following code:</p> <pre><code>ln -s /usr/lib/python2.7/dist-packages/pygtk.pth tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist-packages/gobject tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist-packages/gtk-2.0 tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist-packages/pygtk.pth tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist-packages/glib tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist-packages/gi tools/python_2_7_9/lib/python2.7/site-packages/ ln -s /usr/lib/python2.7/dist-packages/pygtkcompat tools/python_2_7_9/lib/python2.7/site-packages/ </code></pre> <p>,but <code>import glib</code> or <code>import gi</code> still generates errors:</p> <pre><code>yba@ubuntu:~/Documents/XXX/tools$ source python_2_7_9/bin/activate (python_2_7_9) yba@ubuntu:~/Documents/XXX/tools$ python Python 2.7.9 (default, Aug 29 2016, 16:04:36) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import glib Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/yba/Documents/XXX/tools/python_2_7_9/lib/python2.7/dist-packages/glib/__init__.py", line 22, in &lt;module&gt; from glib._glib import * ImportError: /home/yba/Documents/XXX/tools/python_2_7_9/lib/python2.7/dist-packages/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8 &gt;&gt;&gt; import gi Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/yba/Documents/XXX/tools/python_2_7_9/lib/python2.7/dist-packages/gi/__init__.py", line 36, in &lt;module&gt; from ._gi import _gobject ImportError: /home/yba/Documents/lucida/tools/python_2_7_9/lib/python2.7/dist-packages/gi/_gi.so: undefined symbol: PyUnicodeUCS4_FromUnicode &gt;&gt;&gt; </code></pre> <p>Similar to that post, the system-wide python works fine:</p> <pre><code>yba@ubuntu:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import gi &gt;&gt;&gt; import glib &gt;&gt;&gt; </code></pre> <p>How to solve this issue? Also, what I really need is <code>import gi.repository</code> rather than <code>import gi</code>. Thanks a lot!</p>
0
2016-08-29T20:38:12Z
39,215,042
<p>You need to install the necessary modules on your virtual environment. </p> <p>After activating it, you have to <code>pip install &lt;library name&gt;</code>. In your case, it should be <code>pip install gi</code></p>
0
2016-08-29T20:54:53Z
[ "python", "virtualenv", "python-gstreamer" ]
zip unknown number of lists with Python for more than one list
39,214,810
<p>I need to do something very similar to what was asked here <a href="http://stackoverflow.com/questions/5938786/how-would-you-zip-an-unknown-number-of-lists-in-python">How would you zip an unknown number of lists in Python?</a>, but in a more general case.</p> <p>I have the following set up:</p> <pre><code>a = [['a', '0', 'b', 'f', '78']] b = [['3', 'w', 'hh', '12', '8']] c = [['g', '7', '1', 'a0', '9'], ['45', '4', 'fe', 'h', 'k']] </code></pre> <p>I need to zip these lists together to obtain:</p> <pre><code>abc = [['a', '3', 'g', '45'], ['0', 'w', '7', '4'], ['b', 'hh', '1', 'fe'], ['f', '12', 'a0', 'h'], ['78', '8', '9', 'k']] </code></pre> <p>which I can generate with:</p> <pre><code>zip(a[0], b[0], c[0], c[1]) </code></pre> <p>But the lists <code>a,b,c</code> contain a number of sublists that will vary for successive runs, so this "manual" way of expanding them won't work.</p> <p>The closest I can get is:</p> <pre><code>zip(a[0], b[0], *c) </code></pre> <p>Since unpacking a list with <code>*</code> in any other position than the last is not allowed, the "ideal" expression:</p> <pre><code>zip(*a, *b, *c) </code></pre> <p>does not work.</p> <p>How could I zip together a number of lists with an unknown number of sublists?</p>
0
2016-08-29T20:38:41Z
39,214,849
<p><code>itertools.chain</code> to the rescue:</p> <pre><code>import itertools z = list(zip(*itertools.chain(a, b, c))) </code></pre>
5
2016-08-29T20:41:33Z
[ "python", "list", "zip" ]
replacing quotes, commas, apostrophes w/ regex - python/pandas
39,214,938
<p>I have a column with addresses, and sometimes it has these characters I want to remove => <code>'</code> - <code>"</code> - <code>,</code>(apostrophe, double quotes, commas)</p> <p>I would like to replace these characters with space in one shot. I'm using pandas and this is the code I have so far to replace one of them.</p> <pre><code>test['Address 1'].map(lambda x: x.replace(',', '')) </code></pre> <p>Is there a way to modify these code so I can replace these characters in one shot? Sorry for being a noob, but I would like to learn more about pandas and regex.</p> <p>Your help will be appreciated!</p>
1
2016-08-29T20:48:14Z
39,215,021
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a>:</p> <pre><code>test['Address 1'] = test['Address 1'].str.replace(r"[\"\',]", '') </code></pre> <p>Sample:</p> <pre><code>import pandas as pd test = pd.DataFrame({'Address 1': ["'aaa",'sa,ss"']}) print (test) Address 1 0 'aaa 1 sa,ss" test['Address 1'] = test['Address 1'].str.replace(r"[\"\',]", '') print (test) Address 1 0 aaa 1 sass </code></pre>
1
2016-08-29T20:53:18Z
[ "python", "string", "pandas", "replace", "dataframe" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1, A2, A3) cool1 = random.sample([A1, A2, A3],1) cool2 = random.sample([A1, A2, A3],1) cool3 = random.sample([A1, A2, A3],1) print ("%s job is %s." %(P1, cool1)) print ("%s job is %s." %(P2, cool2)) print ("%s job is %s." %(P3, cool3)) </code></pre> <p>The problem is that it is randomizing but it keeps repeating numbers like here</p> <p>**</p> <blockquote> <p>1.0 job is [4.0]. 2.0 job is [5.0]. 3.0 job is [4.0].</p> </blockquote> <p>**</p> <p>What can I do to make it not repeat. I'm using python 2.7.12</p> <p>Also how can I use alphanumerical instead of float only.</p>
-1
2016-08-29T20:48:21Z
39,215,060
<p>Best way to achieve this will be to use <a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow"><code>random.shuffle</code></a> (if you want to randomize the original sample list) or <a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow"><code>random.select</code></a> (if you want to keep the original sample copy):</p> <p><em>Example with <code>random.shuffle</code>:</em></p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; my_samples = ['A1', 'A2', 'A3'] &gt;&gt;&gt; shuffle(my_samples) &gt;&gt;&gt; cool1, cool2, cool3 = my_samples # Random Result: cool1 = 'A3', cool2='A1', cool3='A2' </code></pre> <p><em>Example with <code>random.select</code>:</em></p> <pre><code>&gt;&gt;&gt; cool1, cool2, cool3 = random.sample(['A1', 'A2', 'A3'], 3) </code></pre> <hr> <p>If you want minimal changes in your solution. You may remove an entry from your samples based on random selection and get next choice from remaining samples like:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; cool1 = random.sample(my_samples,1) &gt;&gt;&gt; my_samples.remove(*cool1) &gt;&gt;&gt; my_samples ['A1', 'A3'] &gt;&gt;&gt; cool2 = random.sample(my_samples,1) &gt;&gt;&gt; my_samples.remove(*cool2) &gt;&gt;&gt; cool3 = random.sample(my_samples,1) &gt;&gt;&gt; my_samples.remove(*cool3) &gt;&gt;&gt; my_samples [] &gt;&gt;&gt; cool1, cool2, cool3 (['A2'], ['A3'], ['A1']) </code></pre>
1
2016-08-29T20:55:38Z
[ "python", "python-2.7" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1, A2, A3) cool1 = random.sample([A1, A2, A3],1) cool2 = random.sample([A1, A2, A3],1) cool3 = random.sample([A1, A2, A3],1) print ("%s job is %s." %(P1, cool1)) print ("%s job is %s." %(P2, cool2)) print ("%s job is %s." %(P3, cool3)) </code></pre> <p>The problem is that it is randomizing but it keeps repeating numbers like here</p> <p>**</p> <blockquote> <p>1.0 job is [4.0]. 2.0 job is [5.0]. 3.0 job is [4.0].</p> </blockquote> <p>**</p> <p>What can I do to make it not repeat. I'm using python 2.7.12</p> <p>Also how can I use alphanumerical instead of float only.</p>
-1
2016-08-29T20:48:21Z
39,215,092
<p>You could do this:</p> <pre><code>cool1, cool2, cool3 = random.sample([A1, A2, A3], 3) </code></pre> <blockquote> <p>Also how can I use alphanumerical instead of float only.</p> </blockquote> <p>Have you tried not converting your inputs to float...?</p>
-2
2016-08-29T20:58:03Z
[ "python", "python-2.7" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1, A2, A3) cool1 = random.sample([A1, A2, A3],1) cool2 = random.sample([A1, A2, A3],1) cool3 = random.sample([A1, A2, A3],1) print ("%s job is %s." %(P1, cool1)) print ("%s job is %s." %(P2, cool2)) print ("%s job is %s." %(P3, cool3)) </code></pre> <p>The problem is that it is randomizing but it keeps repeating numbers like here</p> <p>**</p> <blockquote> <p>1.0 job is [4.0]. 2.0 job is [5.0]. 3.0 job is [4.0].</p> </blockquote> <p>**</p> <p>What can I do to make it not repeat. I'm using python 2.7.12</p> <p>Also how can I use alphanumerical instead of float only.</p>
-1
2016-08-29T20:48:21Z
39,215,099
<p>Since you are selecting from a list, then you should delete the entry from the list after each check.</p> <ol> <li><p>Create your original list, which will be used as needed.</p></li> <li><p>Create a second list from the first to use as you select.</p></li> <li><p>As you choose each element from the list, remove it</p></li> <li><p>Put the chosen element into a list of chosen element.</p></li> </ol> <p><a href="http://www.tutorialspoint.com/python/list_remove.htm" rel="nofollow">Python remove method</a></p> <blockquote> <p><strong>Parameters</strong><br> obj -- This is the object to be removed from the list.</p> <p><strong>Return Value</strong><br> This method does not return any value but removes the given object from the list.</p> <p><strong>Example</strong><br> The following example shows the usage of remove() method.</p> <pre><code>#!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc', 'xyz']; aList.remove('xyz'); print "List : ", aList aList.remove('abc'); print "List : ", aList </code></pre> <p>When we run above program, it produces following result −</p> <pre><code>List : [123, 'zara', 'abc', 'xyz'] List : [123, 'zara', 'xyz'] </code></pre> </blockquote>
0
2016-08-29T20:58:43Z
[ "python", "python-2.7" ]
How to select a number without replacement in python
39,214,944
<p>So I'm trying to make a mix and match between numbers here is my code</p> <pre><code>import random P1 = float(input("Person's name?")) P2 = float(input("Person's name?")) P3 = float(input("Person's name?")) A1 = float(input("Activity?")) A2 = float(input("Activity?")) A3 = float(input("Activity?")) s = (A1, A2, A3) cool1 = random.sample([A1, A2, A3],1) cool2 = random.sample([A1, A2, A3],1) cool3 = random.sample([A1, A2, A3],1) print ("%s job is %s." %(P1, cool1)) print ("%s job is %s." %(P2, cool2)) print ("%s job is %s." %(P3, cool3)) </code></pre> <p>The problem is that it is randomizing but it keeps repeating numbers like here</p> <p>**</p> <blockquote> <p>1.0 job is [4.0]. 2.0 job is [5.0]. 3.0 job is [4.0].</p> </blockquote> <p>**</p> <p>What can I do to make it not repeat. I'm using python 2.7.12</p> <p>Also how can I use alphanumerical instead of float only.</p>
-1
2016-08-29T20:48:21Z
39,215,482
<p>write a class to pick a unique element from list<br> 1. permutations finds all unique elements <br> 2. rest can define new data and length of result<br></p> <pre><code>from itertools import permutations class PickOne( object ): def __init__(self,lst,l): self.lst = lst self.visit = set() self.l = l self.lenght = self.number(l) def pick(self): if len(self.visit) == self.lenght : print 'run out numbers' return res = tuple(random.sample(self.lst,self.l)) while res in self.visit: res = tuple(random.sample(self.lst,self.l)) self.visit.add( res ) return res def reset(self,l,lst = None): if not lst: lst = self.lst self.__init__(lst,l) def number(self,l): return len( list(permutations(self.lst,l)) ) </code></pre> <p>Example:</p> <pre><code> a = PickOne([1,2,3,4],1) &gt;&gt;&gt; a.pick() (2,) &gt;&gt;&gt; a.pick() (1,) &gt;&gt;&gt; a.pick() (4,) &gt;&gt;&gt; a.pick() (3,) &gt;&gt;&gt; a.pick() run out numbers &gt;&gt;&gt; a.reset(2) &gt;&gt;&gt; a.pick() (3, 1) &gt;&gt;&gt; a.pick() (3, 4) &gt;&gt;&gt; a.pick() (2, 1) </code></pre>
1
2016-08-29T21:26:50Z
[ "python", "python-2.7" ]
Why does list(next(iter(())) for _ in range(1)) == []?
39,214,961
<p>Why does <code>list(next(iter(())) for _ in range(1))</code> return an empty list rather than raising <code>StopIteration</code>?</p> <pre><code>&gt;&gt;&gt; next(iter(())) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; [next(iter(())) for _ in range(1)] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; list(next(iter(())) for _ in range(1)) # ?! [] </code></pre> <p>The same thing happens with a custom function that explicitly raises <code>StopIteration</code>:</p> <pre><code>&gt;&gt;&gt; def x(): ... raise StopIteration ... &gt;&gt;&gt; x() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in x StopIteration &gt;&gt;&gt; [x() for _ in range(1)] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in x StopIteration &gt;&gt;&gt; list(x() for _ in range(1)) # ?! [] </code></pre>
17
2016-08-29T20:49:16Z
39,214,998
<p>The <code>StopIteration</code> exception is used to tell the underlying mechanism of the <code>list</code> function when to actually stop iterating on the iterable that has been passed to it. In your case, you're telling Python that the thing that has been passed into <code>list()</code> is a generator. So when it gets that, it outputs an empty list because nothing has been accumulated.</p>
6
2016-08-29T20:51:55Z
[ "python" ]
Why does list(next(iter(())) for _ in range(1)) == []?
39,214,961
<p>Why does <code>list(next(iter(())) for _ in range(1))</code> return an empty list rather than raising <code>StopIteration</code>?</p> <pre><code>&gt;&gt;&gt; next(iter(())) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; [next(iter(())) for _ in range(1)] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; list(next(iter(())) for _ in range(1)) # ?! [] </code></pre> <p>The same thing happens with a custom function that explicitly raises <code>StopIteration</code>:</p> <pre><code>&gt;&gt;&gt; def x(): ... raise StopIteration ... &gt;&gt;&gt; x() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in x StopIteration &gt;&gt;&gt; [x() for _ in range(1)] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in x StopIteration &gt;&gt;&gt; list(x() for _ in range(1)) # ?! [] </code></pre>
17
2016-08-29T20:49:16Z
39,215,240
<p>assuming all goes well, the generator comprehension <code>x() for _ in range(1)</code> should raise <code>StopIteration</code> when it is finished iterating over <code>range(1)</code> to indicate that there are no more items to pack into the list.</p> <p>However because <code>x()</code> raises <code>StopIteration</code> it ends up exiting early meaning this behaviour is a bug in python that is being addressed with <a href="http://legacy.python.org/dev/peps/pep-0479/">PEP 479</a></p> <p>In python 3.6 or using <code>from __future__ import generator_stop</code> in python 3.5 when a StopIteration propagates out farther it is converted into a <code>RuntimeError</code> so that <code>list</code> doesn't register it as the end of the comprehension. When this is in effect the error looks like this:</p> <pre><code>Traceback (most recent call last): File "/Users/Tadhg/Documents/codes/test.py", line 6, in &lt;genexpr&gt; stuff = list(x() for _ in range(1)) File "/Users/Tadhg/Documents/codes/test.py", line 4, in x raise StopIteration StopIteration The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/Tadhg/Documents/codes/test.py", line 6, in &lt;module&gt; stuff = list(x() for _ in range(1)) RuntimeError: generator raised StopIteration </code></pre>
9
2016-08-29T21:07:37Z
[ "python" ]
Unbalanced worker/machine assignment
39,215,098
<p>I have a problem of assigning 7 possible workers to 3 machines. There is a cost when a worker is assigned to a machine as well as when a worker is idle. It is required that all 3 machines are used. The cost matrices are</p> <pre><code> M1 M2 M3 W1 [72, 74, 74] [64, W2 [48, 50, 50] 44, C = W3 [52, 52, 52] I = 52, W4 [40, 20, 18] 10, W5 [46, 48, 48] 42, W6 [40, 26, 26] 18, W7 [40, 20, 18] 12] </code></pre> <p>With matrix C being the cost of each worker being assigned to each machine. Matrix I represents the cost of each worker to be idle.</p> <p>I'm currently using <code>scipy.optimize.linear_sum_assignment</code> to determine the minimum cost with a cost matrix </p> <pre><code> M1 M2 M3 W1 [72, 74, 74,64,M,M,M,M,M,M] W2 [48, 50, 50,M,44,M,M,M,M,M] C = W3 [52, 52, 52,M,M,52,M,M,M,M] With M being very big. W4 [40, 20, 18,M,M,M,10,M,M,M] W5 [46, 48, 48,M,M,M,M,42,M,M] W6 [40, 26, 26,M,M,M,M,M,18,M] W7 [40, 20, 18,M,M,M,M,M,M,12] </code></pre> <p>With the current cost matrix it sometimes happens that not all machines are assigned. To counter this I simply multiplied all the idle cost with 10 to ensure that the machines are selected first.</p> <p>My python code however does not give me the optimal answer. Is there maybe a different function I could use that would solves this type of problems?</p> <p>The code:</p> <pre><code>from scipy.optimize import linear_sum_assignment C = [[72, 74, 74, 640, M, M, M, M, M, M], [48, 50, 50, M, 440, M, M, M, M, M], [52, 52, 52, M, M, 520, M, M, M, M], [40, 20, 18, M, M, M, 100, M, M, M], [46, 48, 48, M, M, M, M, 420, M, M], [40, 26, 26, M, M, M, M, M, 180, M], [40, 20, 18, M, M, M, M, M , M, 120]] row_ind, col_ind = linear_sum_assignment(C) print(row_ind) print(col_ind ) </code></pre> <p>I need a way to solve the assignment while forcing all three the machines to be assigned a worker. My way of defining the cost matrix seems to do it but doesn't give the wanted answer (obtained using a Tabu search). I'm not sure how to force <code>scipy.optimize.linear_sum_assignment</code> to always assign the three machines. Is this even possible to do in <code>scipy.optimize.linear_sum_assignment</code> or should I rather be for a different python package to use? </p>
-3
2016-08-29T20:58:22Z
39,224,750
<p>Found what was wrong with it. I had to many dummy machines allowing workers to be assigned to them rather than to the machines. By changing the dimensions of the matrix to be square (7x7) and changing the cost matrix </p> <pre><code> M1 M2 M3 W1 [72, 74, 74,64,64,64,64] W2 [48, 50, 50,44,44,44,44] C = W3 [52, 52, 52,52,52,52,52] W4 [40, 20, 18,10,10,10,10] W5 [46, 48, 48,42,42,42,42] W6 [40, 26, 26,18,18,18,18] W7 [40, 20, 18,12,12,12,12] </code></pre> <p><code>scipy.optimize.linear_sum_assignment</code> now gives me the correct assignment.</p>
0
2016-08-30T10:16:37Z
[ "python", "matrix", "variable-assignment" ]
Trying to run multiple python scripts in Java
39,215,111
<p>I have a python script called generate_graphs.py that generates graphs with python libraries. The graphs are trends we show to customers with our internal data. </p> <p>I'm trying to run the script from Java, but I don't see any evidence of it running. There is no evidence of logs showing it ran, but I'm not sure if this is the script itself not running, or if its the implementation of the exec method.</p> <p>The script inserts data into a database as part of its process, and nothing is inserted. However, when running the script command from command line separately, the script runs perfectly fine.</p> <p>Here's the execute command implementation used from mkyong.com:</p> <pre><code>private String executeCommand(String command) { StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine())!= null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } </code></pre> <p>Here's the method that is called about 40 times in total, roughly once per 3 seconds:</p> <pre><code>/** * Runs a command to execute the generate_graph python script * * @param server_id */ public void generateGraph(List&lt;String&gt; list_name, String server_id, String email_addr, String report_str) { String generate_graph_cmd = "python2.7 generate_graphs.py --l '%s' --server_name '%s' --email_addr '%s' --report_string '%s' --debug"; //We want to remove the lm_ part from the server name String server_name = server_id.split("_")[1].replace("\'", ""); String list_name_str = ""; for (String name : list_name){ list_name_str += name + ","; } //We want to remove the trailing comma left by the above loop if (list_name_str.length() &gt; 1){ list_name_str = list_name_str.substring(0, list_name_str.length() - 1); } generate_graph_cmd = String.format(generate_graph_cmd, list_name_str, server_name, email_addr, report_str); try { System.out.println("[Py Output] " + executeCommand(generate_graph_cmd)); } catch (Exception e) { e.printStackTrace(); } log.debug("Generating graph with the following parameters:\nserver_id: " + server_id + "\nlist_id: " + list_name.toString()); } </code></pre> <p>I only see the <code>log.debug</code> portion of the output in the logs. Am I calling it too quickly/incorrectly? Any help would be appreciated, thanks!</p>
0
2016-08-29T20:59:30Z
39,230,271
<p>I ended up using <a href="https://commons.apache.org/proper/commons-exec/download_exec.cgi" rel="nofollow">Apache Common's Exec</a> to solve my issue. </p>
0
2016-08-30T14:28:53Z
[ "java", "python", "logging", "command-line", "command" ]
Adding print statements to cython code affects output
39,215,155
<p>I have an application that's written in a combination of Python and Cython. I recently added a new feature and tests to this application. The tests pass on my local machine (a macbook), but when I push to appveyor (a Windows CI service) the tests fail. This in itself is not so strange. When I add print statements to my Cython code in an attempt to see what is happening when it runs on appveyor, the tests no longer fail. This is frustrating because it leaves me no way to figure out what's happening when the tests fail on appveyor. It also is just perplexing because it violates my understanding of how Python and Cython work in general. </p> <p>My code is complex and there's no reasonable way for me to share an example of this phenomenon. However, I'm looking for reasons this could happen. How and in what situations might a print statement in Cython code have an effect on other computations?</p>
0
2016-08-29T21:02:13Z
39,215,388
<p>The typical case in my experience is where you've managed to grab a value from unallocated or unaligned storage -- in short, a memory usage error that finesses the compiler's ability to detect such abuse. Normally, you get a garbage value; the print statement forces an evaluation or memory alignment that "fixes" the problem.</p> <p>This is hard to do accidentally in most modern languages, unless you specifically "hard-cast" a value, changing a type without altering the bit value.</p>
2
2016-08-29T21:18:58Z
[ "python", "windows", "cython", "appveyor" ]
Adding print statements to cython code affects output
39,215,155
<p>I have an application that's written in a combination of Python and Cython. I recently added a new feature and tests to this application. The tests pass on my local machine (a macbook), but when I push to appveyor (a Windows CI service) the tests fail. This in itself is not so strange. When I add print statements to my Cython code in an attempt to see what is happening when it runs on appveyor, the tests no longer fail. This is frustrating because it leaves me no way to figure out what's happening when the tests fail on appveyor. It also is just perplexing because it violates my understanding of how Python and Cython work in general. </p> <p>My code is complex and there's no reasonable way for me to share an example of this phenomenon. However, I'm looking for reasons this could happen. How and in what situations might a print statement in Cython code have an effect on other computations?</p>
0
2016-08-29T21:02:13Z
39,215,418
<p>To save some time, you can try to debug deeper using blocking RDP (<a href="https://www.appveyor.com/docs/how-to/rdp-to-build-worker/" rel="nofollow">https://www.appveyor.com/docs/how-to/rdp-to-build-worker/</a>) which you can insert in different stages of Appveyor build. Just please note that Environment variables in RDP session are not the same as for build agent process so you might need to adjust RDP environment to get a repo.</p> <p>--ilya. </p>
1
2016-08-29T21:21:29Z
[ "python", "windows", "cython", "appveyor" ]
What is the correct method to spark-submit python applications on aws emr?
39,215,244
<p>I'm connected to the master node of a Spark cluster, running inside of emr, and am trying to submit a python based application:</p> <pre><code>spark-submit --verbose --deploy-mode cluster --master yarn-cluster --num-executors 3 --executor-cores 6 --executor-memory 1g test.py </code></pre> <p>The process produces a set of logs dump, including the following confirmation of deployment to the cluster:</p> <pre><code>6/08/29 20:47:51 INFO Client: Uploading resource file:/home/hadoop/test.py -&gt; hdfs://ip-xxx-xxx-xxx-xxx.ec2.internal:8020/user/hadoop/.sparkStaging/application_1472396426409_0007/test.py 16/08/29 20:47:51 INFO Client: Uploading resource file:/usr/lib/spark/python/lib/pyspark.zip -&gt; hdfs://ip-xxx-xxx-xxx-xxx.ec2.internal:8020/user/hadoop/.sparkStaging/application_1472396426409_0007/pyspark.zip 16/08/29 20:47:51 INFO Client: Uploading resource file:/usr/lib/spark/python/lib/py4j-0.10.1-src.zip -&gt; hdfs://ip-xxx-xxx-xxx-xxx.ec2.internal:8020/user/hadoop/.sparkStaging/application_1472396426409_0007/py4j-0.10.1-src.zip </code></pre> <p>Yet, the application fails to run, reporting a missing py4j library? :</p> <pre><code>6/08/29 20:48:47 INFO Client: Application report for application_1472396426409_0007 (state: ACCEPTED) 16/08/29 20:48:48 INFO Client: Application report for application_1472396426409_0007 (state: FAILED) 16/08/29 20:48:48 INFO Client: client token: N/A diagnostics: Application application_1472396426409_0007 failed 2 times due to AM Container for appattempt_1472396426409_0007_000002 exited with exitCode: -1000 For more detailed output, check application tracking page:http://ip-xxx-xxx-xxx-xxx.ec2.internal:8088/cluster/app/application_1472396426409_0007Then, click on links to logs of each attempt. Diagnostics: File does not exist: hdfs://ip-xxx-xxx-xxx-xxx.ec2.internal:8020/user/hadoop/.sparkStaging/application_1472396426409_0007/py4j-0.10.1-src.zip java.io.FileNotFoundException: File does not exist: hdfs://ip-xxx-xxx-xxx-xxx.ec2.internal:8020/user/hadoop/.sparkStaging/application_1472396426409_0007/py4j-0.10.1-src.zip at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1309) at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1301) </code></pre> <p>Am I misusing the command or something?</p>
2
2016-08-29T21:07:52Z
39,239,106
<p>This appears to be a bug with the aws system. Yarn monitors the system and notices that the deployed code is no longer there - which is really a sign that spark is done processing.</p> <p>To verify that this is the problem, double check by reading the logs for your application - ie, run something like this against your master node:</p> <pre><code>yarn logs -applicationId application_1472396426409_0007 </code></pre> <p>and double check that you see a success message in the logs:</p> <pre><code>INFO ApplicationMaster: Unregistering ApplicationMaster with SUCCEEDED </code></pre>
0
2016-08-31T00:45:22Z
[ "python", "amazon-web-services", "apache-spark", "emr" ]
Python Float to String TypeError
39,215,272
<p>I am writing a temperature converter for fun and everything seems to be working except I am getting a 'TypeError: Can't convert 'float' object to str implicitly' message. From what I can tell I am converting it to a string after the fact, can anyone tell me what I am doing wrong? </p> <p>I looked this this question previously <a href="http://stackoverflow.com/questions/22397261/cant-convert-float-object-to-str-implicitly">&quot;Can&#39;t convert &#39;float&#39; object to str implicitly&quot;</a> </p> <pre><code>def tempconverter(startType,Temp): #conversion types: c -&gt; f c-&gt; K , f -&gt; c, f -&gt; k, k -&gt; c, k -&gt; f # maybe have them select only their beginning type then show # all temp types by that temperature if startType[0].lower() == 'c': return ('Your temperature ' + Temp +'\n' + 'Farenheight: ' + ((int(Temp)*9)/5)+32 + '\n' + 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ## ) elif startType[0].lower() == 'f': #commented out until first is fixed #return ((int(Temp)-32)*5)/9 return Temp elif startType[0].lower() == 'k': return Temp print('Welcome to our temperature converter program.') print('''Please enter your temperature type: C = Celsius F = Farenheight K = Kelvin''') sType = input('&gt; ') print('Please enter the temperature you wish to convert.') sTemp = input('&gt; ') print(tempconverter(sType,sTemp)) </code></pre>
0
2016-08-29T21:10:28Z
39,215,298
<p>In this calculation:</p> <pre><code>((int(Temp)*9)/5)+32 </code></pre> <p>You are not converting your result to <code>str</code>.</p> <p>Also, you have spelled "Fahrenheit" incorrectly.</p>
1
2016-08-29T21:12:06Z
[ "python", "python-3.x" ]
Python Float to String TypeError
39,215,272
<p>I am writing a temperature converter for fun and everything seems to be working except I am getting a 'TypeError: Can't convert 'float' object to str implicitly' message. From what I can tell I am converting it to a string after the fact, can anyone tell me what I am doing wrong? </p> <p>I looked this this question previously <a href="http://stackoverflow.com/questions/22397261/cant-convert-float-object-to-str-implicitly">&quot;Can&#39;t convert &#39;float&#39; object to str implicitly&quot;</a> </p> <pre><code>def tempconverter(startType,Temp): #conversion types: c -&gt; f c-&gt; K , f -&gt; c, f -&gt; k, k -&gt; c, k -&gt; f # maybe have them select only their beginning type then show # all temp types by that temperature if startType[0].lower() == 'c': return ('Your temperature ' + Temp +'\n' + 'Farenheight: ' + ((int(Temp)*9)/5)+32 + '\n' + 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ## ) elif startType[0].lower() == 'f': #commented out until first is fixed #return ((int(Temp)-32)*5)/9 return Temp elif startType[0].lower() == 'k': return Temp print('Welcome to our temperature converter program.') print('''Please enter your temperature type: C = Celsius F = Farenheight K = Kelvin''') sType = input('&gt; ') print('Please enter the temperature you wish to convert.') sTemp = input('&gt; ') print(tempconverter(sType,sTemp)) </code></pre>
0
2016-08-29T21:10:28Z
39,215,532
<p>In the line of code:</p> <pre><code>+ 'Kelvin: ' + str((Temp+ 273.15)) ## I get the error here ## </code></pre> <p>The error is caused by this part of it:</p> <pre><code>Temp+ 273.15 </code></pre> <p><code>Temp</code> is a string. You can't add a string and a number together.</p>
2
2016-08-29T21:30:32Z
[ "python", "python-3.x" ]
Alembic migration for GeoAlchemy2 raises NameError: name 'geoalchemy2' is not defined
39,215,278
<p>I've decided to write a small webapp using Flask, postgresql and leaflet. I wanted to store coordinates (latitude and longitude) using <a href="http://postgis.net/" rel="nofollow">PostGIS</a> extender for postgresql. My flask application uses Flask-SQLAlchemy, blueprint and especially Flask-Migrate for the database migration process.</p> <p>Here is an excerpt of my database model:</p> <pre><code>from . import db from geoalchemy2 import Geometry class Station(db.Model): __tablename__ = 'stations' id = db.Column(db.Integer, primary_key=True, unique=True) name = db.Column(db.String(255)) position = db.Column(Geometry('Point', srid=4326)) </code></pre> <p>Here an excerpt of my app/<strong>init</strong>.py</p> <pre><code>import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from config import config db = SQLAlchemy() migrate = Migrate() def create_app(config_name=None, main=True): if config_name is None: config_name = os.environ.get('FLASK_CONFIG', 'development') app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) migrate.init_app(app, db) from .home import home as home_blueprint app.register_blueprint(home_blueprint) from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint, url_prefix='/admin') return app </code></pre> <p>Before trying to use the specific extender, I didn't have any issue to adapt my model. Since then, the migration is doing alright but the upgrade doesn't work (python manage.py db upgrade).</p> <p>Here the log I obtain from the webserver:</p> <pre><code>sa.Column('position', geoalchemy2.types.Geometry(geometry_type='POINT', srid=4326), nullable=True), `enter code here`NameError: name 'geoalchemy2' is not defined </code></pre> <p>I'm a bit lost and I didn't find much help on this specific subject. Any idea on what might cause this issue?</p>
0
2016-08-29T21:10:57Z
39,215,327
<p>Alembic does not try to determine and render all imports for custom types in the migration scripts. Edit the generated script to include <code>from geoalchemy2.types import Geometry</code> and change the column def to just use <code>Geometry</code>.</p> <p>You should always review the auto-generated scripts before running them. There's even comments in the script saying so.</p>
0
2016-08-29T21:14:03Z
[ "python", "postgresql", "flask", "alembic", "geoalchemy2" ]
How to call deepcopy with super in python?
39,215,452
<p>I have 2 classes, let's call them Class1 and Class2(Class1), and Class2 derives from Class1. </p> <p>In Class1, copy.deepcopy works very well and I <strong>don't</strong> want to implement a method <strong>deepcopy</strong> on Class1. </p> <p>Now, I have an instance i2=Class2(someParameters). I want to make a deepcopy of i2 as in instance of Class1. </p> <p>I cannot call copy.deepcopy(i2) because this would deepcopy i2 as in instance of class2 (with signature problems in my case). </p> <p>I cannot call super().<strong>deepcopy</strong>(i2) because <strong>deepcopy</strong> is not found in class1, and one falls back to the computation of copy.deepcopy(i2) as an instance of class2, and we go to an infinite loop. </p> <p>How to proceed then to call the builtin copy.deepcopy(i2), regarding i2 as an instance of Class1 ? </p> <p>Thank you for your ideas, Laurent.</p> <p>EDIT: As asked in the comments, an example of code to show the signature problem if I simply call copy.deepcopy</p> <pre><code>import copy from copy import deepcopy class Class1(object): pass class Class2(Class1): def __new__(cls,start): eClass1=Class1.__new__(cls) Class1.__init__(eClass1) eClass1.start=start return eClass1 instanceClass2=Class2(1) copy.deepcopy(instanceClass2) </code></pre> <p>The answer from the interpreter:</p> <pre><code>Traceback (most recent call last): File "essaiDebug7.py", line 18, in &lt;module&gt; copy.deepcopy(instanceClass2) File "/usr/lib/python2.7/copy.py", line 190, in deepcopy y = _reconstruct(x, rv, 1, memo) File "/usr/lib/python2.7/copy.py", line 329, in _reconstruct y = callable(*args) File "/usr/lib/python2.7/copy_reg.py", line 93, in __newobj__ return cls.__new__(cls, *args) TypeError: __new__() takes exactly 2 arguments (1 given) </code></pre>
1
2016-08-29T21:23:55Z
39,215,519
<p>How about instead of inheriting <code>Class1</code>, create a object of <code>Class2 in Class1</code>? Like:</p> <pre><code>class Class2(object): def __init__(self): self.class_1 = Class1() # Then deepcopy copy.deepcopy(class_2.class_1) </code></pre> <p><strong>Note</strong>: It would be great if you can share the real scenario. Because, based on the problem you mentioned, I do not think that your classes are inheritable. If they are, <em>I do not understand why you just want to copy parent class?</em></p>
0
2016-08-29T21:29:12Z
[ "python", "copy", "super" ]
Order of the link in the page with Scrapy
39,215,467
<p>I have a simple <code>LinkExtractor</code> rule for a given domain. Something like this: <code>Rule(LinkExtractor(allow=('domain\.com/.+/\d+', )), callback='parse_page'),</code></p> <p>What I would like and I can't figure out, it's to know on which position was the link in the page.</p> <p>For example, if a given domain has 5 links on the page that match my rule I need to know from the top to the bottom their order in the HTML.</p> <p>I found many questions about the order of the extraction, but nothing, or I misunderstood something, about the order of the link itself in the HTML</p>
0
2016-08-29T21:25:05Z
39,215,622
<p>Scrapy uses lxml to for html parsing. <code>LinkExtractor</code> uses <code>root.iter()</code> to iterate through. <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/linkextractors/lxmlhtml.py#L37" rel="nofollow">This line to be more exact.</a></p> <p><a href="http://lxml.de/tutorial.html#tree-iteration" rel="nofollow">Lxml's docs say:</a></p> <blockquote> <p>Elements provide a tree iterator for this purpose. It yields elements in document order, i.e. in the order their tags would appear if you serialised the tree to XML:</p> </blockquote> <p>so for html source:</p> <pre><code>&lt;root&gt; &lt;child&gt;Child 1&lt;/child&gt; &lt;child&gt;Child 2&lt;/child&gt; &lt;another&gt;Child 3&lt;/another&gt; &lt;/root&gt; </code></pre> <p>it would yield:</p> <pre><code>&gt;&gt;&gt; for element in root.iter(tag=etree.Element): ... print("%s - %s" % (element.tag, element.text)) root - None child - Child 1 child - Child 2 another - Child 3 </code></pre> <p>You can replicate the process using the examples provided in the lxml docs link posted above.</p>
1
2016-08-29T21:39:44Z
[ "python", "scrapy" ]
Conditionally Merging list of lists with rows of a text file
39,215,510
<p>Consider these two data structures:</p> <pre><code>var_a = [['apple','fruit','1'],['banana', 'fruit', '2'],['orange', 'fruit', '3']] </code></pre> <p>text file contents:</p> <pre><code>'1', '20,000', 'USA' '2', '45,000', 'Russia' '3', '56,000', 'China' </code></pre> <p>I want to use a list comprehension that will give me an output as follows:</p> <pre><code>'Apple', '1', '20,000', 'USA' 'Banana', '2', '45,000', 'Russia' 'Orange', '3', '56,000', 'China' </code></pre> <p>The code I have tried so far is:</p> <pre><code>import json file = open(name, 'r') #read in rows of data from text file file_rows = file.read() file_rows = file_rows.split('\n') for x_file in file_rows: x_file2 = x_file.split(',') my_text_file = open(text_file_path, 'r') var_a = my_text_file.read() #read in list of lists from text file the_list = json.loads(var_a.replace("'", '"')) if any(x_file2[0] == x[2] for x in the_list) == True: print xfile2[0], x </code></pre> <p>I'm still a bit out there from what I am after. Can someone tell me how I should amend the list comprehension to achieve the desired output?</p> <p>Thanks</p>
0
2016-08-29T21:28:32Z
39,215,817
<p>Below is the sample code for list comprehension with the use of <code>itertools</code>:</p> <pre><code>import itertools with open('/tmp/my_text_file.txt') as f: new_list = [list(itertools.chain(item[1][:1], item[0].strip().replace("'", "").split(", "))) for item in zip(f.readlines(), var_a)] # new_list = [['apple', '1', '20,000', 'USA'], ['banana', '2', '45,000', 'Russia'], ['orange', '3', '56,000', 'China']] </code></pre>
1
2016-08-29T21:57:51Z
[ "python", "json", "list-comprehension" ]
Psycopg2 connection unusable after SELECTs interrupted by OS signal
39,215,527
<h1>Problem</h1> <p>I am working on a long-running python process that performs a lot of database access (mostly reads, occasional writes). Sometimes it may be necessary to terminate the process before it finishes (e.g. by using the <code>kill</code> command) and when this happens I would like to log a value to the database indicating that the particular run was canceled. (I am also logging the occurrence to a log file; I would like to have the information in both places.)</p> <p>I have found that if I interrupt the process while the database connection is active, the connection becomes unusable; specifically, it hangs the process if I try to use it in any way.</p> <h1>Minimum working example</h1> <p>The actual application is rather large and complex, but this snippet reproduces the problem reliably.</p> <p>The table <code>test</code> in the database has two columns, <code>id</code> (serial) and <code>message</code> (text). I prepopulated it with one row so the <code>UPDATE</code> statement below would have something to change.</p> <pre><code>import psycopg2 import sys import signal pg_host = 'localhost' pg_user = 'redacted' pg_password = 'redacted' pg_database = 'test_db' def write_message(msg): print "Writing: " + msg cur.execute("UPDATE test SET message = %s WHERE id = 1", (msg,)) conn.commit() def signal_handler(signal, frame): write_message('Interrupt!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) if __name__ == '__main__': conn = psycopg2.connect(host=pg_host, user=pg_user, password=pg_password, database=pg_database) cur = conn.cursor() write_message("Starting") for i in xrange(10000): # I press ^C somewhere in here cur.execute("SELECT * FROM test") cur.fetchall() write_message("Finishing") </code></pre> <p>When I run this script without interruption, it completes as expected. That is, the row in the database is updated to say "Starting" then "Finishing".</p> <p>If I press <code>ctrl-C</code> during the loop indicated by the comment, python hangs indefinitely. It no longer responds to keyboard input, and the process has to be killed from elsewhere. Looking in my postgresql log, the <code>UPDATE</code> statement with "Interrupted!" is never received by the database server.</p> <p>If I add a debugging breakpoint at the beginning of signal_handler() I can see that doing almost anything with the database connection at that point causes the same hang. Trying to <code>execute</code> a <code>SELECT</code>, issuing a <code>conn.rollback()</code>, <code>conn.commit()</code>, <code>conn.close()</code> or <code>conn.reset()</code> all cause the hang. Executing <code>conn.cancel()</code> does not cause a hang, but it doesn't improve the situation; subsequent use of the connection still causes a hang. If I remove the database access from <code>write_message()</code> then the script is able to exit gracefully when interrupted, so the hang is definitely database connection related.</p> <p>Also worth noting: if I change the script so that I am interrupting something other than database activity, it works as desired, logging "Interrupted!" to the database. E.g., if I replace the <code>for i in xrange(10000)</code> loop with a simple <code>sleep(10)</code> and interrupt that, it works fine. So the problem seems to be specifically related to interrupting psycopg2 with a signal while it is performing database access, <em>then</em> trying to use the connection.</p> <h1>Questions</h1> <p>Is there any way to salvage the existing psycopg2 connection and use it to update the database after this kind of interruption?</p> <p>If not, is there at least a way to terminate it cleanly so if some subsequent code tried to use it, it wouldn't cause a hang?</p> <p>Finally, is this somehow expected behavior, or is it a bug that should be reported? It makes sense to me that the connection could be in a bad state after this kind of interruption, but ideally it would throw an exception indicating the problem rather than hanging.</p> <h1>Workaround</h1> <p>In the meantime, I have discovered that if I create an entirely new connection with <code>psycopg2.connect()</code> after the interrupt and am careful not to access the old one, I can still update the database from the interrupted process. This is probably what I'll do for now, but it feels untidy. </p> <h1>Environment</h1> <ul> <li>OS X 10.11.6</li> <li>python 2.7.11</li> <li>psycopg2 2.6.1</li> <li>postgresql 9.5.1.0</li> </ul>
0
2016-08-29T21:30:13Z
39,668,740
<p>I filed an <a href="https://github.com/psycopg/psycopg2/issues/471" rel="nofollow">issue</a> for this on the psycopg2 github and received a helpful response from the developer. In summary:</p> <ul> <li>The behavior of an existing connection within a signal handler is OS dependent and there's probably no way to use the old connection reliably; creating a new one is the recommended solution.</li> <li>Using <code>psycopg2.extensions.set_wait_callback(psycopg2.extras.wait_select)</code> improves the situation a bit (at least in my environment) by causing <code>execute()</code> statements called from within the signal handler to throw an exception rather than hang. However, doing other things with the conneciton (e.g. <code>reset()</code>) still caused a hang for me, so ultimately it's still best to just create a new connection within the signal handler rather than trying to salvage the existing one.</li> </ul>
0
2016-09-23T20:05:26Z
[ "python", "postgresql", "python-2.7", "signals", "psycopg2" ]
Fill in web form using Python
39,215,539
<p>I've been trying to fill in a web form using Selenium in Python. It's a simple enough task, and the code I'm using is this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("https://...") elem = driver.find_element_by_id("receipt_number") elem.clear() elem.send_keys("13lettercode") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close() </code></pre> <p>After inspecting the web form element I got this:</p> <pre><code>&lt;input id="receipt_number" name="appReceiptNum" type="text" class="form-control textbox" maxlength="13"&gt; </code></pre> <p>The website gives me an error saying that my code is invalid, and I'm wondering if there's anything obvious that I'm doing wrong. Thanks for your help!</p>
2
2016-08-29T21:31:13Z
39,215,568
<p>click the submit button instead of sending a return key</p>
1
2016-08-29T21:33:26Z
[ "python", "selenium-webdriver" ]
What is map_partitions doing?
39,215,617
<p>The dask API says, that map_partition can be used to "apply a Python function on each DataFrame partition." From this description and according to the usual behaviour of "map", I would expect the return value of map_partitions to be (something like) a list whose length equals the number of partitions. Each element of the list should be one of the return values of the function calls.</p> <p>However, with respect to the following code, I am not sure, what the return value depends on:</p> <pre><code>#generate example dataframe pdf = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) ddf = dd.from_pandas(pdf, npartitions=3) #define helper function for map. VAL is the return value VAL = pd.Series({'A': 1}) #VAL = pd.DataFrame({'A': [1]}) #other return values used in this example #VAL = None #VAL = 1 def helper(x): print('function called\n') return VAL #check result out = ddf.map_partitions(helper).compute() print(len(out)) </code></pre> <ul> <li><code>VAL = pd.Series({'A': 1})</code> causes 4 function calls (probably one to infer the dtype and 3 for the partitions) and an output with len == 3 and the type pd.Series.</li> <li><code>pd.DataFrame({'A': [1]})</code> results in the same numbers, however the resulting type is pd.DataFrame.</li> <li><code>VAL = None</code> causes an TypeError ... why? Couldn't a possible use of map_partitions be to <strong>do</strong> something rather than to <strong>return</strong> something?</li> <li><code>VAL = 1</code> results in only 2 function calls. The result of map_partitions is the integer 1.</li> </ul> <p>Therefore, I want to ask some questions:</p> <ol> <li>how is the return value of map_partitions determined? </li> <li>What influences the number of function calls besides the number of partitions / What criteria has a function to fulfil to be called once with each partition? </li> <li>What should be the return value of a function, that only "does" something, i.e. a procedure? </li> <li>How should a function be designed, that returns arbitrary objects?</li> </ol>
3
2016-08-29T21:38:44Z
39,227,474
<p>The <a href="http://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.DataFrame.map_partitions" rel="nofollow">Dask DataFrame.map_partitions</a> function returns a new Dask Dataframe or Series, based on the output type of the mapped function. See the <a href="http://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.DataFrame.map_partitions" rel="nofollow">API documentation</a> for a thorough explanation. </p> <ol> <li><p>How is the return value of map_partitions determined?</p> <p>See the API docs referred to above. </p></li> <li><p>What influences the number of function calls besides the number of partitions / What criteria has a function to fulfil to be called once with each partition?</p> <p>You're correct that we're calling it once immediately to guess the dtypes/columns of the output. You can avoid this by specifying a <code>meta=</code> keyword directly. Other than that the function is called once per partition.</p></li> <li><p>What should be the return value of a function, that only "does" something, i.e. a procedure?</p> <p>You could always return an empty dataframe. You might also want to consider transforming your dataframe into a sequence of <a href="http://dask.readthedocs.io/en/latest/delayed.html" rel="nofollow">dask.delayed</a> objects, which are typically more often used for ad-hoc computations.</p></li> <li><p>How should a function be designed, that returns arbitrary objects?</p> <p>If your function doesn't return series/dataframes then I recommend converting your dataframe to a sequence of <a href="http://dask.readthedocs.io/en/latest/delayed.html" rel="nofollow">dask.delayed</a> objects with the <a href="http://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.DataFrame.to_delayed" rel="nofollow">DataFrame.to_delayed</a> method.</p></li> </ol>
1
2016-08-30T12:26:27Z
[ "python", "pandas", "dask" ]
Flask-SQLAlchemy - Backref isn't working, value is None
39,215,663
<p>I think I have the same issue as <a href="http://stackoverflow.com/questions/28323644/flask-sqlalchemy-backref-not-working">here on SO.</a> Using python 3.5, flask-sqlalchemy, and sqlite. I am trying to establish a one (User) to many (Post) relationship.</p> <pre><code>class User(db_blog.Model): id = db_blog.Column(db_blog.Integer, primary_key=True) nickname = db_blog.Column(db_blog.String(64), index=True, unique=True) email = db_blog.Column(db_blog.String(120), unique=True) posts = db_blog.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '&lt;User: {0}&gt;'.format(self.nickname) class Post(db_blog.Model): id = db_blog.Column(db_blog.Integer, primary_key=True) body = db_blog.Column(db_blog.String(2500)) title = db_blog.Column(db_blog.String(140)) user_id = db_blog.Column(db_blog.Integer, db_blog.ForeignKey('user.id')) def __init__(self, body, title, **kwargs): self.body = body self.title = title def __repr__(self): return '&lt;Title: {0}\nPost: {1}\nAuthor: {2}&gt;'.format(self.title, self.body, self.author) </code></pre> <p>Author is None.</p> <pre><code>&gt;&gt;&gt; u = User(nickname="John Doe", email="jdoe@email.com") &gt;&gt;&gt; u &lt;User: John Doe&gt; &gt;&gt;&gt; db_blog.session.add(u) &gt;&gt;&gt; db_blog.session.commit() &gt;&gt;&gt; u = User.query.get(1) &gt;&gt;&gt; u &lt;User: John Doe&gt; &gt;&gt;&gt; p = Post(body="Body of post", title="Title of Post", author=u) &gt;&gt;&gt; p &lt;Title: Title of Post Post: Body of post Author: None&gt; #Here I expect- "Author: John Doe&gt;" </code></pre> <p>I get the same result after session add/commit of the post and so can't find the post author.</p>
0
2016-08-29T21:43:27Z
39,216,243
<p>If you add the newly created <code>post</code> to the <code>posts</code> attribute of the user, it will work:</p> <pre><code>&gt;&gt;&gt; u = User(nickname="John Doe", email="jdoe@email.com") &gt;&gt;&gt; u &lt;User: John Doe&gt; &gt;&gt;&gt; db_blog.session.add(u) &gt;&gt;&gt; p = Post(body="Body of post", title="Title of Post") &gt;&gt;&gt; p &lt;Title: Title of Post Post: Body of post Author: None&gt; &gt;&gt;&gt; db_blog.session.add(p) &gt;&gt;&gt; db_blog.session.commit() &gt;&gt;&gt; u.posts.append(p) &gt;&gt;&gt; p &lt;Title: Title of Post Post: Body of post Author: &lt;User: John Doe&gt;&gt; &gt;&gt;&gt; p.author &lt;User: John Doe&gt; </code></pre> <p>The reason your code doesn't work as-is, is because you've defined an <code>__init__</code> constructor for your <code>Post</code> class, and this doesn't consider the <code>author</code> field at all, so Python doesn't know what to do with that <code>author</code> parameter.</p>
0
2016-08-29T22:39:05Z
[ "python", "sqlite", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Flask-SQLAlchemy - Backref isn't working, value is None
39,215,663
<p>I think I have the same issue as <a href="http://stackoverflow.com/questions/28323644/flask-sqlalchemy-backref-not-working">here on SO.</a> Using python 3.5, flask-sqlalchemy, and sqlite. I am trying to establish a one (User) to many (Post) relationship.</p> <pre><code>class User(db_blog.Model): id = db_blog.Column(db_blog.Integer, primary_key=True) nickname = db_blog.Column(db_blog.String(64), index=True, unique=True) email = db_blog.Column(db_blog.String(120), unique=True) posts = db_blog.relationship('Post', backref='author', lazy='dynamic') def __repr__(self): return '&lt;User: {0}&gt;'.format(self.nickname) class Post(db_blog.Model): id = db_blog.Column(db_blog.Integer, primary_key=True) body = db_blog.Column(db_blog.String(2500)) title = db_blog.Column(db_blog.String(140)) user_id = db_blog.Column(db_blog.Integer, db_blog.ForeignKey('user.id')) def __init__(self, body, title, **kwargs): self.body = body self.title = title def __repr__(self): return '&lt;Title: {0}\nPost: {1}\nAuthor: {2}&gt;'.format(self.title, self.body, self.author) </code></pre> <p>Author is None.</p> <pre><code>&gt;&gt;&gt; u = User(nickname="John Doe", email="jdoe@email.com") &gt;&gt;&gt; u &lt;User: John Doe&gt; &gt;&gt;&gt; db_blog.session.add(u) &gt;&gt;&gt; db_blog.session.commit() &gt;&gt;&gt; u = User.query.get(1) &gt;&gt;&gt; u &lt;User: John Doe&gt; &gt;&gt;&gt; p = Post(body="Body of post", title="Title of Post", author=u) &gt;&gt;&gt; p &lt;Title: Title of Post Post: Body of post Author: None&gt; #Here I expect- "Author: John Doe&gt;" </code></pre> <p>I get the same result after session add/commit of the post and so can't find the post author.</p>
0
2016-08-29T21:43:27Z
39,217,136
<p>You added your own <code>__init__</code> to <code>Post</code>. While it accepts keyword arguments, it does nothing with them. You can either update it to use them</p> <pre><code>def __init__(self, body, title, **kwargs): self.body = body self.title = title for k, v in kwargs: setattr(self, k, v) </code></pre> <p>Or, ideally, you can just remove the method and let SQLAlchemy handle it for you. </p>
0
2016-08-30T00:29:47Z
[ "python", "sqlite", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Can I "touch" a SQLAlchemy record to trigger "onupdate"?
39,215,673
<p>Here's a SQLAlchemy class:</p> <pre><code>class MyGroup(Base): __tablename__ = 'my_group' group_id = Column(Integer, Sequence('my_seq'), primary_key=True) group_name = Column(String(200), nullable=False, index=True) date_created = Column(DateTime, default=func.now()) date_updated = Column(DateTime, default=func.now(), onupdate=func.now()) </code></pre> <p>Anytime I add a group_name or (for example) update the group_name, the <code>date_updated</code> field will get updated. That's great.</p> <p>But sometimes there are cases where I want to mark a group as "updated" even if the group record itself did not change (for example, if data in a different but related table is updated). </p> <p>I could do it manually:</p> <pre><code>group = session.query(SgmGroup).filter(SgmGroup.group_name=='Some Group').one() group.date_updated = datetime.datetime.utcnow() session.commit() </code></pre> <p>but I'd really rather let the model do it in its own way, rather than recreate a Python process to manually update the date. (For example, to avoid mistakes like where maybe the model uses <code>now()</code> while the manual function mistakenly uses <code>utcnow()</code>)</p> <p>Is there a way with SQLAlchemy to "touch" a record (kind of like UNIX <code>touch</code>) that wouldn't alter any of the record's other values but would trigger the <code>onupdate=</code> function?</p>
0
2016-08-29T21:44:28Z
39,279,472
<p>I haven't looked at the source but from the <a href="http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.onupdate" rel="nofollow">docs</a> it seems that this is only triggered by issuing a SQL <code>UPDATE</code> command:</p> <blockquote> <p>onupdate – A scalar, Python callable, or ClauseElement representing a default value to be applied to the column within UPDATE statements, which wil be invoked upon update if this column is not present in the SET clause of the update. This is a shortcut to using ColumnDefault as a positional argument with for_update=True.</p> </blockquote> <p>If your concern is ensuring that your "touch" uses the same function as the <code>onupdate</code> function you could define a method on your model to perform the touch and have the <code>onupdate</code> parameter point this method.</p> <p>I think something like this would work:</p> <pre><code>class MyGroup(Base): __tablename__ = 'my_group' group_id = Column(Integer, Sequence('my_seq'), primary_key=True) group_name = Column(String(200), nullable=False, index=True) date_created = Column(DateTime, default=func.now()) date_updated = Column( DateTime, default=self.get_todays_date(), onupdate=self.get_todays_date()) def get_todays_date(self): return datetime.datetime.utcnow() def update_date_updated(self): self.date_updated = self.get_todays_date() </code></pre> <p>You could then update your record like this:</p> <pre><code>group.update_date_updated() session.commit() </code></pre>
0
2016-09-01T19:28:07Z
[ "python", "sqlalchemy", "sql-update" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>result = [[6, 8]] </code></pre> <p>For the above input.</p> <p>I think my answer will involve the grouping itertools recipe described <a href="https://docs.python.org/2.6/library/itertools.html#examples" rel="nofollow">here</a>. I tried to do a simple implementation of it for my purposes, but I am unsure how to transform the results into my desired result:</p> <pre><code>from operator import itemgetter from itertools import groupby data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} for k, pos in groupby(enumerate(data.iteritems()), lambda (i, (a, s)):i - s): print map(itemgetter(1), pos) </code></pre> <p>Has the output:</p> <pre><code>[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)] [(7, 6)] [(8, 6), (9, 7), (10, 8)] </code></pre> <p>Which properly groups my input data, but does not really give me the interval I want. The challenge I see in parsing this output to the interval I want is that it is giving me an interval for the 'skip region'.</p>
1
2016-08-29T21:46:02Z
39,215,873
<p>Assuming that the "non-increasing" values remain constant in those regions and do not decrease either, you can just group entries that have the same value and then pick those groups that have more than one entry. Finally, extract the beginning and the end index.</p> <pre><code>&gt;&gt;&gt; data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} &gt;&gt;&gt; items = sorted(data.items()) &gt;&gt;&gt; groups = itertools.groupby(items, key=operator.itemgetter(1)) &gt;&gt;&gt; ranges = [grp for grp in (list(grp) for key, grp in groups) if len(grp) &gt; 1] &gt;&gt;&gt; ranges [[(6, 6), (7, 6), (8, 6)]] &gt;&gt;&gt; [(r[0][0], r[-1][0]) for r in ranges] [(6, 8)] </code></pre>
2
2016-08-29T22:02:28Z
[ "python" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>result = [[6, 8]] </code></pre> <p>For the above input.</p> <p>I think my answer will involve the grouping itertools recipe described <a href="https://docs.python.org/2.6/library/itertools.html#examples" rel="nofollow">here</a>. I tried to do a simple implementation of it for my purposes, but I am unsure how to transform the results into my desired result:</p> <pre><code>from operator import itemgetter from itertools import groupby data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} for k, pos in groupby(enumerate(data.iteritems()), lambda (i, (a, s)):i - s): print map(itemgetter(1), pos) </code></pre> <p>Has the output:</p> <pre><code>[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)] [(7, 6)] [(8, 6), (9, 7), (10, 8)] </code></pre> <p>Which properly groups my input data, but does not really give me the interval I want. The challenge I see in parsing this output to the interval I want is that it is giving me an interval for the 'skip region'.</p>
1
2016-08-29T21:46:02Z
39,215,874
<p>If it is the case that (a) your keys are consecutive integers and (b) you want to find those keys whose values are not greater than the value corresponding to preceding integer <em>or</em> not less than the value corresponding to the successive integer, then:</p> <pre><code>&gt;&gt;&gt; [k for k in sorted(data.keys()) if (k-1 in data and not data[k-1] &lt; data[k]) or (k+1 in data and not data[k] &lt; data[k+1])] [6, 7, 8] </code></pre>
1
2016-08-29T22:02:36Z
[ "python" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>result = [[6, 8]] </code></pre> <p>For the above input.</p> <p>I think my answer will involve the grouping itertools recipe described <a href="https://docs.python.org/2.6/library/itertools.html#examples" rel="nofollow">here</a>. I tried to do a simple implementation of it for my purposes, but I am unsure how to transform the results into my desired result:</p> <pre><code>from operator import itemgetter from itertools import groupby data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} for k, pos in groupby(enumerate(data.iteritems()), lambda (i, (a, s)):i - s): print map(itemgetter(1), pos) </code></pre> <p>Has the output:</p> <pre><code>[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)] [(7, 6)] [(8, 6), (9, 7), (10, 8)] </code></pre> <p>Which properly groups my input data, but does not really give me the interval I want. The challenge I see in parsing this output to the interval I want is that it is giving me an interval for the 'skip region'.</p>
1
2016-08-29T21:46:02Z
39,215,937
<p>Here's an alternative way using <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>.</p> <pre><code>from collections import defaultdict ranges = defaultdict(list) data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} for index, num in data.iteritems(): ranges[num].append(index) print [(r[0], r[-1]) for r in ranges.itervalues() if len(r) &gt; 1] </code></pre> <p>One advantage of this approach is that it doesn't require sorting the dictionary.</p>
0
2016-08-29T22:08:40Z
[ "python" ]
pythonic way to find separate integer intervals in dictionary integer mapping
39,215,692
<p>I have a dictionary mapping one integer range onto another, as an example:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} </code></pre> <p>I want to find all regions where the numeric intervals in the values fail to increment, so my output should be:</p> <pre><code>result = [[6, 8]] </code></pre> <p>For the above input.</p> <p>I think my answer will involve the grouping itertools recipe described <a href="https://docs.python.org/2.6/library/itertools.html#examples" rel="nofollow">here</a>. I tried to do a simple implementation of it for my purposes, but I am unsure how to transform the results into my desired result:</p> <pre><code>from operator import itemgetter from itertools import groupby data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} for k, pos in groupby(enumerate(data.iteritems()), lambda (i, (a, s)):i - s): print map(itemgetter(1), pos) </code></pre> <p>Has the output:</p> <pre><code>[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)] [(7, 6)] [(8, 6), (9, 7), (10, 8)] </code></pre> <p>Which properly groups my input data, but does not really give me the interval I want. The challenge I see in parsing this output to the interval I want is that it is giving me an interval for the 'skip region'.</p>
1
2016-08-29T21:46:02Z
39,215,953
<p>What about something like that:</p> <pre><code>data = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 6, 9: 7, 10: 8} sd = sorted(data.items()) result = [] for i in range(1, len(sd)): if sd[i][1] == sd[i-1][1]: result.append(i) </code></pre> <p>I think <code>sorted(data.items())</code> is both clearer and more pythonic that your loop</p> <p>This gives the result:</p> <pre><code>print result [7, 8] </code></pre> <p>That might be a good start ?</p>
0
2016-08-29T22:10:31Z
[ "python" ]
Feature Importance for Random Forest Regressor in Python
39,215,700
<p>I'm trying to find out which features have the most importance for my predictive model.</p> <p>Currently I'm using sklearn's inbuilt attribute as such</p> <pre><code>Model = Model.fit(Train_Features, Labels_Train) print(Model.feature_importances_) </code></pre> <p>It's just that its more of a black box type method, I'm not understanding what method it uses to weight the importance towards the features. Is there a better approach for doing this?</p>
0
2016-08-29T21:46:39Z
39,215,847
<p>Feature importance is not a black-box when it comes to decision trees. From the documentation for a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html#sklearn.tree.DecisionTreeRegressor.feature_importances_" rel="nofollow">DecisionTreeRegressor</a>:</p> <blockquote> <p>The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.</p> </blockquote> <p>For a forest, it just averages across the different trees in your forest. Check out the <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/ensemble/forest.py#L322" rel="nofollow">source code</a>:</p> <pre><code>def feature_importances_(self): """Return the feature importances (the higher, the more important the feature). Returns ------- feature_importances_ : array, shape = [n_features] """ if self.estimators_ is None or len(self.estimators_) == 0: raise NotFittedError("Estimator not fitted, " "call `fit` before `feature_importances_`.") all_importances = Parallel(n_jobs=self.n_jobs, backend="threading")( delayed(getattr)(tree, 'feature_importances_') for tree in self.estimators_) return sum(all_importances) / len(self.estimators_) </code></pre>
1
2016-08-29T22:00:36Z
[ "python", "regression", "random-forest", "feature-selection" ]
Efficiency when printing progress updates, print x vs if x%y==0: print x
39,215,750
<p>I am running an algorithm which reads an excel document by rows, and pushes the rows to a SQL Server, using Python. I would like to print some sort of progression through the loop. I can think of two very simple options and I would like to know which is more lightweight and why. Option A:</p> <pre><code>for x in xrange(1, sheet.nrows): print x cur.execute() # pushes to sql </code></pre> <p>Option B:</p> <pre><code>for x in xrange(1, sheet.nrows): if x % some_check_progress_value == 0: print x cur.execute() # pushes to sql </code></pre> <p>I have a feeling that the second one would be more efficient but only for larger scale programs. Is there any way to calculate/determine this? </p>
1
2016-08-29T21:52:02Z
39,219,220
<p>I'm a newbie, so I can't comment. An "answer" might be overkill, but it's all I can do for now. </p> <p>My favorite thing for this is <a href="https://pypi.python.org/pypi/tqdm" rel="nofollow">tqdm</a>. It's minimally invasive, both code-wise and output-wise, and it gets the job done. </p>
3
2016-08-30T05:16:04Z
[ "python", "algorithm", "performance", "python-2.7" ]
Efficiency when printing progress updates, print x vs if x%y==0: print x
39,215,750
<p>I am running an algorithm which reads an excel document by rows, and pushes the rows to a SQL Server, using Python. I would like to print some sort of progression through the loop. I can think of two very simple options and I would like to know which is more lightweight and why. Option A:</p> <pre><code>for x in xrange(1, sheet.nrows): print x cur.execute() # pushes to sql </code></pre> <p>Option B:</p> <pre><code>for x in xrange(1, sheet.nrows): if x % some_check_progress_value == 0: print x cur.execute() # pushes to sql </code></pre> <p>I have a feeling that the second one would be more efficient but only for larger scale programs. Is there any way to calculate/determine this? </p>
1
2016-08-29T21:52:02Z
39,225,991
<p>Using the modulus check (counter % N == 0) is almost free compared print and a great solution if you run a high frequency iteration (log a lot). Specially if you does not need to print for each iteration but want some feedback along the way.</p>
1
2016-08-30T11:14:33Z
[ "python", "algorithm", "performance", "python-2.7" ]
Efficiency when printing progress updates, print x vs if x%y==0: print x
39,215,750
<p>I am running an algorithm which reads an excel document by rows, and pushes the rows to a SQL Server, using Python. I would like to print some sort of progression through the loop. I can think of two very simple options and I would like to know which is more lightweight and why. Option A:</p> <pre><code>for x in xrange(1, sheet.nrows): print x cur.execute() # pushes to sql </code></pre> <p>Option B:</p> <pre><code>for x in xrange(1, sheet.nrows): if x % some_check_progress_value == 0: print x cur.execute() # pushes to sql </code></pre> <p>I have a feeling that the second one would be more efficient but only for larger scale programs. Is there any way to calculate/determine this? </p>
1
2016-08-29T21:52:02Z
39,299,328
<p>I am one of the developers of <a href="https://github.com/tqdm/tqdm" rel="nofollow">tqdm, a Python progress bar</a> that tries to be as efficient as possible while providing as many automated features as possible.</p> <p>The biggest performance sink we had was indeed I/O: printing to the console/file/whatever.</p> <p>But if your loop is tight (more than 100 iterations/second), then it's useless to print <em>every</em> update, you'd just as well print just 1/10 of the updates and the user would see no difference, while your bar would be 10 times less overhead (faster).</p> <p>To fix that, at first we added a <code>mininterval</code> parameter which updated the display only every <code>x</code> seconds (which is by default 0.1 seconds, the human eye cannot really see anything faster than that). Something like that:</p> <pre><code>import time def my_bar(iterator, mininterval=0.1) counter = 0 last_print_t = 0 for item in iterator: if (time.time() - last_print_t) &gt;= mininterval: last_print_t = time.time() print_your_bar_update(counter) counter += 1 </code></pre> <p>This will mostly fix your issue as your bar will always have a constant display overhead which will be more and more negligible as you have bigger iterators.</p> <p>If you want to go further in the optimization, <code>time.time()</code> is also an I/O operation and thus has a cost greater than simple Python statements. To avoid that, you want to minimize the calls you do to <code>time.time()</code> by introducing another variable: <code>miniters</code>, which is the minimum number of iterations you want to skip before even checking the time:</p> <pre><code>import time def my_bar(iterator, mininterval=0.1, miniters=10) counter = 0 last_print_t = 0 last_print_counter = 0 for item in iterator: if (counter - last_print_counter) &gt;= miniters: if (time.time() - last_print_t) &gt;= mininterval: last_print_t = time.time() last_print_counter = counter print_your_bar_update(counter) counter += 1 </code></pre> <p>You can see that <code>miniters</code> is similar to your Option B modulus solution, but it's better fitted as an added layer over time because time is more easily configured.</p> <p>With these two parameters, you can manually finetune your progress bar to make it the most efficient possible for your loop.</p> <p>However, <code>miniters</code> (or modulus) is tricky to get to work generally for everyone without manual finetuning, you need to make good assumptions and clever tricks to automate this finetuning. This is one of the major ongoing work we are doing on <code>tqdm</code>. Basically, what we do is that we try to calculate <code>miniters</code> to equal <code>mininterval</code>, so that time checking isn't even needed anymore. This automagic setting kicks in after <code>mininterval</code> gets triggered, something like that:</p> <pre><code>from __future__ import division import time def my_bar(iterator, mininterval=0.1, miniters=10, dynamic_miniters=True) counter = 0 last_print_t = 0 last_print_counter = 0 for item in iterator: if (counter - last_print_counter) &gt;= miniters: cur_time = time.time() if (cur_time - last_print_t) &gt;= mininterval: if dynamic_miniters: # Simple rule of three delta_it = counter - last_print_counter delta_t = cur_time - last_print_t miniters = delta_it * mininterval / delta_t last_print_t = cur_time last_print_counter = counter print_your_bar_update(counter) counter += 1 </code></pre> <p>There are various ways to compute <code>miniters</code> automatically, but usually you want to update it to match <code>mininterval</code>.</p> <p>If you are interested in digging more, you can check the <code>dynamic_miniters</code> internal parameters, <code>maxinterval</code> and an <a href="https://github.com/tqdm/tqdm/pull/251" rel="nofollow">experimental monitoring thread</a> of the <a href="https://github.com/tqdm/tqdm" rel="nofollow">tqdm project</a>.</p>
1
2016-09-02T19:14:17Z
[ "python", "algorithm", "performance", "python-2.7" ]
Fastest way to calculate "cosine" metrics with scipy
39,215,925
<p>I am given a matrix of ones and zeros. I need to find 20 rows which have the highest cosine metrics towards 1 <code>specific</code> row in matrix: </p> <p>If I have 10 rows, and 5th is called <code>specific</code>, I want to choose the highest value between these:<br> <code>cosine(1row,5row),cosine(2row,5row),...,cosine(8row,5row),cosine(9row,5row)</code></p> <p>First, i tried to count metrics. This didn't work:</p> <pre><code>A = ratings[:,100] A = A.reshape(1,A.shape[0]) B = ratings.transpose() similarity = -cosine(A,B)+1 A.shape = (1L, 71869L) B.shape = (10000L, 71869L) </code></pre> <p>Error is: <code>Input vector should be 1-D.</code> I'd like to know, how to implement this aesthetically with no errors, but the most important - which solution will be the fastest? </p> <p>In my opinion, the fastest way is not realized with help of <code>scipy</code>; We just have to take all ones in <code>specific</code> row and look at these indices in all other rows. Those rows, which have the highest coincidence will have the highest matrix. </p> <p>Are there any faster ways?</p>
2
2016-08-29T22:07:35Z
39,645,684
<p>The fastest way is to use matrix operations: <code>something like np.multipy(A,B)</code> </p>
0
2016-09-22T17:48:08Z
[ "python", "scipy", "cosine" ]
Python - allowed values of a variable
39,216,012
<p>How can I explicitly define what values can given variable have? Let's say I want value of variable <strong>size</strong> to be either <strong>'small'</strong>, <strong>'medium'</strong>, or <strong>'big'</strong> and nothing else.</p> <p>EDIT: I want to avoid a situation when variable is set to something from beyond the list (for example to 'tiny' in this case). Like enum in Java. This variable would be a class field.</p>
-3
2016-08-29T22:15:36Z
39,216,069
<p>Simplest way would be to always use dedicated method which would firstly validate input and if it's correct then set variable. Below you may find some example:</p> <pre class="lang-py prettyprint-override"><code>class Test: def __init__(self): self.__variable = None def set_variable(self, value): if value not in ('small', 'medium', 'big'): raise ValueError() self.__variable = value </code></pre>
3
2016-08-29T22:21:32Z
[ "python", "enums" ]
Python - allowed values of a variable
39,216,012
<p>How can I explicitly define what values can given variable have? Let's say I want value of variable <strong>size</strong> to be either <strong>'small'</strong>, <strong>'medium'</strong>, or <strong>'big'</strong> and nothing else.</p> <p>EDIT: I want to avoid a situation when variable is set to something from beyond the list (for example to 'tiny' in this case). Like enum in Java. This variable would be a class field.</p>
-3
2016-08-29T22:15:36Z
39,216,090
<p>You are describing an <code>enumeration</code>, which is supported in Python by the <code>enum</code> library:</p> <pre><code>from enum import Enum class Size(Enum): small = 'small' medium = 'medium' big = 'big' size = Size('big') print(size) try: size = Size('tiny') except ValueError as e: print("invalid Size (", e.args[0].split()[0], "). Size must be one of 'small', 'medium' or 'big'", sep='') </code></pre> <p><strong>Output:</strong></p> <pre><code>Size.big invalid Size ('tiny'). Size must be one of 'small', 'medium' or 'big' </code></pre>
2
2016-08-29T22:23:59Z
[ "python", "enums" ]
Python example of how to get formatting information from a cell in Google Sheets API v4?
39,216,029
<p>I've been trying to write my own Google Sheets wrapper, and it's been a frustrating experience so far. The thing I'm stuck on at the moment is how to get a symmetrical in / out format of sheet data.</p> <p>Basically, I want to call values().get(), alter the resulting hash, and send that same hash back up to update().</p> <p>I'm happy to write my own solution to process or coerce the output of values().get() to the structure that batchUpdate() needs, but <strong>I need the formatting information of each of the cells to do that</strong>.</p> <p>batchUpdate() expects formatting information like this:</p> <pre><code>bod = { 'updateCells': { 'start': { 'sheetId': 0, 'rowIndex': 7, 'columnIndex': 0 }, 'rows': [ { 'values': [ { "userEnteredValue": { 'stringValue': 'LOL' }, "userEnteredFormat": { 'backgroundColor': { 'red': .2, 'blue': .75, 'green': .75 } } }, { "userEnteredValue": { 'stringValue': 'LOL2' }, "userEnteredFormat": { 'backgroundColor': { 'red': .2, 'blue': 1, 'green': .75 } } }, { "userEnteredValue": { 'stringValue': 'LOL3' }, "userEnteredFormat": { 'backgroundColor': { 'red': .2, 'blue': 1, 'green': 1 } } } ] } ], 'fields': 'userEnteredValue,userEnteredFormat.backgroundColor' } } </code></pre> <p>How I'm retrieving values currently looks something like this:</p> <pre><code>import requests import json from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build #Set up credentials object auth_key_url = "&lt;JSON CREDENTIALS FILE&gt;" file_contents = requests.get(auth_key_url).content key_dict = json.loads(file_contents) creds = ServiceAccountCredentials.from_json_keyfile_dict(key_dict, ['https://spreadsheets.google.com/feeds']) #Now build the API object discoveryUrl = "https://sheets.googleapis.com/$discovery/rest?version=v4" gsheet = build('sheets', 'v4', discoveryServiceUrl=discoveryUrl, credentials=creds) result = gsheet.spreadsheets().values().get(spreadsheetId="&lt;A SHEET ID&gt;", range="Sheet1!A1:ZZ").execute() </code></pre> <p>This produces "results", which is a dictionary with 2 keys, "range" and "values", and "values" is a list of lists of the values of the spreadsheet. These lists do not contain formatting data - just the values in the cells.</p> <p>Can someone show me, in Python, how I can get cell value, background color, alignment, and other cell formatting information from spreadsheets().values() or from the spreadsheet?</p>
0
2016-08-29T22:17:16Z
39,500,316
<p>The <code>spreadsheets.values.get</code> endpoint only returns the values. If you want a more complete picture of the spreadsheet (formatting, etc) then you need to use the <code>spreadsheets.get</code> endpoint:</p> <p><a href="https://developers.google.com/sheets/reference/rest/v4/spreadsheets/get" rel="nofollow">https://developers.google.com/sheets/reference/rest/v4/spreadsheets/get</a></p> <p>Make sure to pass either <code>includeGridData=true</code> or pass a value for the <code>fields</code> that includes <code>sheets.data</code> so that the cell data is returned. Pass a value in the <code>range</code> parameter to limit the results to only a specific range.</p>
0
2016-09-14T22:00:57Z
[ "python", "google-api-client", "google-sheets-api" ]
get column names from numpy genfromtxt in python
39,216,092
<p>using numpy genfromtxt in python, i want to be able to get column headers as key for a given data. I tried the following, but not able to get the column names for the corresponding data.</p> <pre><code>column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0)) columnData = np.genfromtxt(pathToFile,dtype=str,delimiter=',') data = dict(zip(column,columnData.tolist())) </code></pre> <p>Below is the data file</p> <pre><code>header0,header1,header2 mydate,3.4,2.0 nextdate,4,6 afterthat,7,8 </code></pre> <p>Currently, it shows data as </p> <pre><code>{ "mydate": [ "mydate", "3.4", "2.0" ], "nextdate": [ "nextdate", "4", "6" ], "afterthat": [ "afterthat", "7", "8" ] } </code></pre> <p>I want to get to this format</p> <pre><code>{ "mydate": { "header1":"3.4", "header2":"2.0" }, "nextdate": { "header1":"4", "header2":"6" }, "afterthat": { "header1":"7", "header2": "8" } } </code></pre> <p>any suggestions?</p>
1
2016-08-29T22:24:02Z
39,216,177
<p>Using pandas module:</p> <pre><code>In [94]: fn = r'D:\temp\.data\z.csv' </code></pre> <p>read CSV into data frame:</p> <pre><code>In [95]: df = pd.read_csv(fn) In [96]: df Out[96]: header0 header1 header2 0 mydate 3.4 2.0 1 nextdate 4.0 6.0 2 afterthat 7.0 8.0 </code></pre> <p>getting desired dict:</p> <pre><code>In [97]: df.set_index('header0').to_dict('index') Out[97]: {'afterthat': {'header1': 7.0, 'header2': 8.0}, 'mydate': {'header1': 3.3999999999999999, 'header2': 2.0}, 'nextdate': {'header1': 4.0, 'header2': 6.0}} </code></pre> <p>or as a JSON string:</p> <pre><code>In [107]: df.set_index('header0').to_json(orient='index') Out[107]: '{"mydate":{"header1":3.4,"header2":2.0},"nextdate":{"header1":4.0,"header2":6.0},"afterthat":{"header1":7.0,"header2":8.0}}' </code></pre>
2
2016-08-29T22:32:53Z
[ "python", "numpy", "genfromtxt" ]
get column names from numpy genfromtxt in python
39,216,092
<p>using numpy genfromtxt in python, i want to be able to get column headers as key for a given data. I tried the following, but not able to get the column names for the corresponding data.</p> <pre><code>column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0)) columnData = np.genfromtxt(pathToFile,dtype=str,delimiter=',') data = dict(zip(column,columnData.tolist())) </code></pre> <p>Below is the data file</p> <pre><code>header0,header1,header2 mydate,3.4,2.0 nextdate,4,6 afterthat,7,8 </code></pre> <p>Currently, it shows data as </p> <pre><code>{ "mydate": [ "mydate", "3.4", "2.0" ], "nextdate": [ "nextdate", "4", "6" ], "afterthat": [ "afterthat", "7", "8" ] } </code></pre> <p>I want to get to this format</p> <pre><code>{ "mydate": { "header1":"3.4", "header2":"2.0" }, "nextdate": { "header1":"4", "header2":"6" }, "afterthat": { "header1":"7", "header2": "8" } } </code></pre> <p>any suggestions?</p>
1
2016-08-29T22:24:02Z
39,216,405
<p>With your sample file and <code>genfromtxt</code> calls I get 2 arrays:</p> <pre><code>In [89]: column Out[89]: array(['header0', 'mydate', 'nextdate', 'afterthat'], dtype='&lt;U9') In [90]: columnData Out[90]: array([['header0', 'header1', 'header2'], ['mydate', '3.4', '2.0'], ['nextdate', '4', '6'], ['afterthat', '7', '8']], dtype='&lt;U9') </code></pre> <p>Pull out the first row of <code>columnData</code></p> <pre><code>In [91]: headers=columnData[0,:] In [92]: headers Out[92]: array(['header0', 'header1', 'header2'], dtype='&lt;U9') </code></pre> <p>Now construct a dictionary of dictionaries (I don't need the separate <code>column</code> array):</p> <pre><code>In [94]: {row[0]: {h:v for h,v in zip(headers, row)} for row in columnData[1:]} Out[94]: {'afterthat': {'header0': 'afterthat', 'header1': '7', 'header2': '8'}, 'mydate': {'header0': 'mydate', 'header1': '3.4', 'header2': '2.0'}, 'nextdate': {'header0': 'nextdate', 'header1': '4', 'header2': '6'}} </code></pre> <p>refine it a bit:</p> <pre><code>In [95]: {row[0]: {h:v for h,v in zip(headers[1:], row[1:])} for row in columnData[1:]} Out[95]: {'afterthat': {'header1': '7', 'header2': '8'}, 'mydate': {'header1': '3.4', 'header2': '2.0'}, 'nextdate': {'header1': '4', 'header2': '6'}} </code></pre> <p>I like dictionary comprehensions!</p> <p>Your dictionary of lists version:</p> <pre><code>In [100]: {row[0]:row[1:] for row in columnData[1:].tolist()} Out[100]: {'afterthat': ['7', '8'], 'mydate': ['3.4', '2.0'], 'nextdate': ['4', '6']} </code></pre>
1
2016-08-29T22:58:13Z
[ "python", "numpy", "genfromtxt" ]
python tkinter open new window with button click and close first window
39,216,151
<p>I have a login window. I want to close that login window when access is granted to a user, and open a new window. I've searched a lot to find a solution to this simple problem, but didn't understand how to do that. I tried <code>self.destroy()</code> but it close the entire program.</p> <p>here is the code</p> <pre><code>#!/usr/bin/python from tkinter import * from tkinter import ttk class Login(Tk): def __init__(self): super().__init__() self.uname_var = StringVar() self.pword_var = StringVar() self.init_widgets() def init_widgets(self): # frame mainframe = ttk.Frame(self, padding='5 5') mainframe.grid(row=0, column=0, sticky=(N, E, S, W)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) # label ttk.Label(mainframe, text='Username').grid(row=0, column=0, sticky=W) ttk.Label(mainframe, text='Password').grid(row=1, column=0, sticky=W) # entry uname_entry = ttk.Entry(mainframe, width=20, textvariable=self.uname_var) uname_entry.grid(row=0, column=1, sticky=(E, W)) pword_entry = ttk.Entry(mainframe, width=20, textvariable=self.pword_var) pword_entry.grid(row=1, column=1, sticky=(E, W)) # button ttk.Button(mainframe, text='Sign in', command=self.check_login).grid(row=2, column=1, sticky=E) for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) uname_entry.focus() self.bind('&lt;Return&gt;', self.check_login) def check_login(self, *args): uname = self.uname_var.get() pword = self.pword_var.get() if uname == 'admin' and pword == 'admin': print("Access Granted") new = MainForm() new.title("Main Window") #self.destory() # HERE I WANT TO CLOSE THIS WINDOW else: print("Access Denied") class MainForm(Toplevel): def __init__(self): super().__init__() self.init_widgets() def init_widgets(self): mainframe = ttk.Frame(self, padding='5 5') mainframe.grid(column=0, row=0, sticky=(N, E, S, W)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) ttk.Button(mainframe, text='Click me').grid(column=0, row=0, sticky=(N, W)) def main(): root = Login() root.title("Login") root.mainloop() if __name__ == '__main__': main() </code></pre>
0
2016-08-29T22:30:03Z
39,216,646
<p>In my opinion, the best solution is to make each of your sections of the GUI (login page, main page) a subclass of <code>Frame</code> rather than <code>Toplevel</code> or <code>Tk</code>. With that, you can simply destroy the frame representing the login frame, and replace it with the frame representing the main part of your application. This way you don't have to destroy any windows.</p> <p>Anoter way to get the same effect is to make your main window a subclass of <code>Tk</code>, and have your login window be a <code>Toplevel</code>. At startup you can hide the root window and show the login window, and then when the user logs in you can hide or destroy the login window and show the root window.</p>
0
2016-08-29T23:26:31Z
[ "python", "python-3.x", "user-interface", "tkinter" ]
How to use the root package in an import?
39,216,182
<p>Taking the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">Ansible</a> project as an example, there is, inside the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">lib/ansible root directory</a>, many other packages, like this</p> <pre><code>ansible/cli /errors /...many omitted for brevity /utils /vars __init__.py </code></pre> <p>As an example, from <code>ansible/utils/vars.py</code>, the imports start at the root ansible/lib directory, such as</p> <pre><code> from ansible.errors import AnsibleError </code></pre> <p>and</p> <pre><code>from ansible.errors import AnsibleError </code></pre> <p>rather than</p> <pre><code>from errors import AnsibleError etc. </code></pre> <p>I have a demo project with a directory structure like this</p> <pre><code>beatles/george/harrison.py /george/__init__.py /john/lennon.py /john/__init__.py /ringo/starr.py /ringo/__init__.py /paul/mccartney.py /paul/__init__.py __init__.py (this __init__.py file is in the beatles dir) helpers.py </code></pre> <p>So, using the Ansible example, I tried (in file <code>john/lennon.py</code>) to do</p> <p>from beatles.george.harrison import Guitar</p> <p>but I get an error `No module named beatles.george.harrison</p> <p>However, the code works fine if I omit the <code>beatles</code> package (the equivalent of ansible in the ansible project)</p> <p>from george.harrison import Guitar</p> <p>How come, with my directory structure, I am not able to code the import as</p> <pre><code>from beatles.george.harrison import Guitar </code></pre> <p>from the beatles/john/lennon.py file? If possible, please explain with reference to the ansible project so it's clear why it works in one situation but not the other.</p> <pre><code>&gt;&gt;&gt; from beatles.john.lennon import Guitar Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named beatles.john.lennon &gt;&gt;&gt; from john.lennon import Guitar &gt;&gt;&gt; Guitar &lt;class 'john.lennon.Guitar'&gt; </code></pre>
1
2016-08-29T22:33:19Z
39,216,255
<p>The difference here is that when you install ansible, it puts files into a subdirectory which is accessible from your <code>sys.path</code>. For example, it might go here:</p> <pre><code>/home/leahcim/.local/lib/python2.7/site-packages' </code></pre> <p>That's just a guess at the location. <code>import ansible</code> and check on <code>ansible.__file__</code> for the actual location it ended up in (the exact location is dependent on several things). </p> <p>Now, if you write a <code>setup.py</code> file, you could also get your app visible locally with:</p> <pre><code>python setup.py develop </code></pre> <p>If you don't want to write a working <code>setup.py</code> for your app just yet, then you will need to find some other way to make it visible in <code>sys.path</code>. </p> <p>Specifically, the <strong>parent directory of your "beatles" directory</strong> should be contained in <code>sys.path</code>. One easy way to do that is to export it in the environment variable <code>PYTHONPATH</code>. </p>
1
2016-08-29T22:40:50Z
[ "python" ]
How to use the root package in an import?
39,216,182
<p>Taking the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">Ansible</a> project as an example, there is, inside the <a href="https://github.com/ansible/ansible/tree/devel/lib/ansible" rel="nofollow">lib/ansible root directory</a>, many other packages, like this</p> <pre><code>ansible/cli /errors /...many omitted for brevity /utils /vars __init__.py </code></pre> <p>As an example, from <code>ansible/utils/vars.py</code>, the imports start at the root ansible/lib directory, such as</p> <pre><code> from ansible.errors import AnsibleError </code></pre> <p>and</p> <pre><code>from ansible.errors import AnsibleError </code></pre> <p>rather than</p> <pre><code>from errors import AnsibleError etc. </code></pre> <p>I have a demo project with a directory structure like this</p> <pre><code>beatles/george/harrison.py /george/__init__.py /john/lennon.py /john/__init__.py /ringo/starr.py /ringo/__init__.py /paul/mccartney.py /paul/__init__.py __init__.py (this __init__.py file is in the beatles dir) helpers.py </code></pre> <p>So, using the Ansible example, I tried (in file <code>john/lennon.py</code>) to do</p> <p>from beatles.george.harrison import Guitar</p> <p>but I get an error `No module named beatles.george.harrison</p> <p>However, the code works fine if I omit the <code>beatles</code> package (the equivalent of ansible in the ansible project)</p> <p>from george.harrison import Guitar</p> <p>How come, with my directory structure, I am not able to code the import as</p> <pre><code>from beatles.george.harrison import Guitar </code></pre> <p>from the beatles/john/lennon.py file? If possible, please explain with reference to the ansible project so it's clear why it works in one situation but not the other.</p> <pre><code>&gt;&gt;&gt; from beatles.john.lennon import Guitar Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named beatles.john.lennon &gt;&gt;&gt; from john.lennon import Guitar &gt;&gt;&gt; Guitar &lt;class 'john.lennon.Guitar'&gt; </code></pre>
1
2016-08-29T22:33:19Z
39,216,374
<p>Works for me. Structure:</p> <pre><code>. └── beatles ├── george │   ├── harrison.py │   ├── __init__.py ├── __init__.py ├── john │   ├── __init__.py │   ├── lennon.py ├── paul │   ├── __init__.py │   └── mccartney.py └── ringo ├── __init__.py └── starr.py </code></pre> <p>and:</p> <pre><code>$ cat beatles/john/lennon.py from beatles.george.harrison import Guitar def Guitar(x): return "John's guitar" </code></pre> <p>and:</p> <pre><code>$ cat beatles/george/harrison.py def Guitar(x): return "George's guitar" </code></pre> <p>and I can do, <strong>with my working directory being the one with the <code>beatles</code> folder</strong>:</p> <pre><code>&gt;&gt;&gt; from beatles.john.lennon import Guitar &gt;&gt;&gt; Guitar(1) "John's guitar" </code></pre> <p>Which seems to be exactly your setup as described but does not give an error message when <code>lennon.py</code> imports <code>Guitar</code> from <code>harrison.py</code>.</p> <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13) </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; sys.path ['', '/usr/lib/py...[etc] </code></pre> <p>so that my working directory is the first item in the path. Have you tried to install your package? Or is it in your working directory?</p>
1
2016-08-29T22:55:09Z
[ "python" ]
MATCH function in python?
39,216,229
<p>Is there a way to do an Excel match() function in Python, such that:</p> <p>In a graph like this </p> <p><img src="http://i.stack.imgur.com/O3oiF.png" alt="K-Means Elbow Method results">...</p> <p>...wherein I cut-off at y = 90, I would like to print which corresponding x value is the closest.</p> <p>Based on my investigation the value/answer should be 4, but how can I possibly print or store this in a variable? </p> <pre><code>In: print(bss/tss*100) Out: [ 1.21976032e-14 7.42743185e+01 8.51440985e+01 9.21584826e+01 9.59771981e+01 9.74117561e+01 9.82980987e+01 9.90505760e+01 9.92982678e+01 9.94756800e+01 9.96396123e+01 9.97126077e+01 9.97593424e+01 9.98030600e+01 9.98344280e+01 9.98692896e+01 9.98840717e+01 9.99020097e+01 9.99142963e+01] </code></pre>
0
2016-08-29T22:37:41Z
39,216,432
<p>You can also beat it to death with this simple-minded function. It finds the first value at least as large as the target value, checks the previous value, and returns the position (1-based, not 0-based) of the closer value.</p> <pre><code>def match (table, target): for over in range(len(table)): if table[over] &gt;= target: break # over is the index of the first vale at least as large as the target # return the position (index+1) of the nearer value return over+1 if 2*target &gt; table[over-1] + table[over] \ else over ss_table = [ 1.21976032e-14, 7.42743185e+01, 8.51440985e+01, 9.21584826e+01, 9.59771981e+01, 9.74117561e+01, 9.82980987e+01, 9.90505760e+01, 9.92982678e+01, 9.94756800e+01, 9.96396123e+01, 9.97126077e+01, 9.97593424e+01, 9.98030600e+01, 9.98344280e+01, 9.98692896e+01, 9.98840717e+01, 9.99020097e+01, 9.99142963e+01 ] print match(ss_table, 87) print match(ss_table, 90) </code></pre> <p>For your example, this returns 3 and 4, as desired.</p>
0
2016-08-29T23:00:11Z
[ "python", "match", "cluster-analysis", "k-means" ]
MATCH function in python?
39,216,229
<p>Is there a way to do an Excel match() function in Python, such that:</p> <p>In a graph like this </p> <p><img src="http://i.stack.imgur.com/O3oiF.png" alt="K-Means Elbow Method results">...</p> <p>...wherein I cut-off at y = 90, I would like to print which corresponding x value is the closest.</p> <p>Based on my investigation the value/answer should be 4, but how can I possibly print or store this in a variable? </p> <pre><code>In: print(bss/tss*100) Out: [ 1.21976032e-14 7.42743185e+01 8.51440985e+01 9.21584826e+01 9.59771981e+01 9.74117561e+01 9.82980987e+01 9.90505760e+01 9.92982678e+01 9.94756800e+01 9.96396123e+01 9.97126077e+01 9.97593424e+01 9.98030600e+01 9.98344280e+01 9.98692896e+01 9.98840717e+01 9.99020097e+01 9.99142963e+01] </code></pre>
0
2016-08-29T22:37:41Z
39,244,621
<p>You are looking for an <em>argmin</em> function.</p> <pre><code>from numpy import * print argmin(abs(data - threshold)) </code></pre> <p>will find the <em>index</em> of the smallest deviation from the threshold. It's much more precise to specify the math relationship (<code>argmin(abs(...))</code>) than to hide this in a vague "match" function. This way, it is clear how to use e.g. two thresholds (an upper and a lower threshold), or a non-constant threshold function. We can find the closest point of <em>two</em> functions the same way.</p>
0
2016-08-31T08:36:02Z
[ "python", "match", "cluster-analysis", "k-means" ]
Python Threading - Simple but tricky
39,216,238
<p>Could someone please point out, why my code is not printing "hello". I feel that my thread 2 - t2 is not starting. This is just a code snippet, I am trying to work on to implement in my main program. Basically, my idea is the following: </p> <ol> <li>Have a single function - which has two set of codes ---- one code in "if condition statement" and the other in "while loop"</li> <li>Thread 1 - uses function 1 - "while loop" continuously - until I abruptly stop the program</li> <li>Thread 2 or thread 3 or thread 4 etc, wants to use the same function - but the code under "if condition statement"</li> <li>My approach in the following code is to have a thread 1 - run continuously, while thread2 - does its work without interrupting thread1. </li> </ol> <p>The code:</p> <pre><code>import threading import Queue def Continuous(stop_event, queue_read, queue_write,lock): #lock.acquire() try: if stop_event == True: print stop_event.is_set() print "hello" c = 7 d = 8 msg2 = (c+d)*2 queue_write.put(msg2) while not stop_event.wait(1): print "hello2" #print ("working on %s" % arg) a = 3; b = 4 msg1 = a*b queue_read.put(msg1) time.sleep(1) finally: print "Inside finally" #lock.release() print"Outside try and finally" def main(): pill2kill = threading.Event() lock = threading.Lock() pill2kill.clear() queue1 = Queue.Queue() queue2 = Queue.Queue() #self.queue2 = Queue.Queue() t1 = threading.Thread(target = Continuous, args = (pill2kill,queue1,queue2,lock)) t1.deamon = True t1.start() print "asdfasfd" time.sleep(2) pill2kill_1 = threading.Event() pill2kill_1.set() print "hjgkhj" t2 = threading.Thread(target=Continuous, args=(pill2kill_1, queue1, queue2,lock)) t2.start() t2.join() pill2kill.clear() print "End of program" main() </code></pre> <p>PS: I am extremely sorry, for posting my code this way. I tried for over 15 minutes and I am unsuccesful to get it formatted</p>
1
2016-08-29T22:38:38Z
39,216,360
<p>(Converted from comment because subsequent comment by OP made it clear what they were expecting) The problems come from misuse of <code>Event</code>:</p> <ol> <li><code>if stop_event == True:</code> will always evaluate to <code>False</code> and the <code>if</code> block never executes its contents (<code>stop_event</code> is an <code>Event</code>, it's not equal to anything of type <code>bool</code>, did you mean <code>if stop_event.is_set():</code>?). This prevents <code>hello</code> from being printed.</li> <li>You set the event for the second thread before you create the thread, let alone start it, so <code>while not stop_event.wait(1):</code> will exit the loop immediately without executing the body (preventing <code>hello2</code> from being printed); the only expected output would be from the <code>finally</code> block and below the <code>finally</code>.</li> </ol> <p>Side-note: <code>t1.deamon = True</code> does nothing; the attribute is spelled <code>daemon</code>. Since you never <code>set</code> the <code>Event</code> for thread 1, this seems like it would mean the program would never exit.</p>
0
2016-08-29T22:53:27Z
[ "python", "multithreading" ]
troubles with pandas anaconda package
39,216,240
<p>I got a new mac and just installed anaconda. When I use <code>ipython</code> and <code>spyder</code>, I can <code>import pandas</code> without any problem. However, when I use <code>sublime</code>, I get the error</p> <pre><code>ImportError: No module named pandas </code></pre> <p><code>which python</code> gives <code>//anaconda/bin/python</code>. Also, <code>pandas</code> is listed in <code>conda list</code>. I am using <code>Anaconda2 4.1.1</code> and <code>python 2.7.12</code>. Can someone help?</p>
1
2016-08-29T22:38:44Z
39,426,440
<p>Just add these two line in your .bash_profile, (if you are on bash) export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 and source it, or restart the terminal. Or if you are using "oh my zsh" shell, then add the lines in .zshrc.</p>
0
2016-09-10T13:16:16Z
[ "python", "pandas", "sublimetext2", "spyder" ]
I'm getting an error list index out of range
39,216,282
<p>I'm reading 'Invent Your own Games with Python' and I'm trying to create a game that's in the book. Even though my code matches the code in the book I'm still getting an error:</p> <pre><code>File "/Users/Rocky/reverso.py", line 251, in &lt;module&gt; resetBoard(mainBoard) File "/Users/Rocky/reverso.py", line 27, in resetBoard board[x][y] = ' ' IndexError: list index out of range </code></pre> <p>Code:</p> <pre><code>def resetBoard(board): for x in range(8): for y in range(8): board[x][y] = ' ' #This is line 27 board[3][3] = 'X' board[3][4] = 'O' board[4][3] = 'O' board[4][4] = 'X' def getNewBoard(): board = [] for i in range(8): board.append([' '] * 8) return board while True: # line 248 mainBoard = getNewBoard() resetBoard(mainBoard) # This is line 251 playerTile, computerTile = enterPlayerTile() showHints = False turn = whoGoesFirst() print('The ' + turn + ' will go first.') </code></pre>
0
2016-08-29T22:44:49Z
39,216,850
<p>You can initialize your list using this instead:</p> <pre><code>board = [[' ' for _ in range(8)] for _ in range(8)] </code></pre> <p>It should initialize an 8x8 2d list (which will work without errors).</p> <p>This code works:</p> <pre><code>def resetBoard(board): for x in range(8): for y in range(8): board[y][x] = ' ' board[3][3] = 'X' board[3][4] = 'O' board[4][3] = 'O' board[4][4] = 'X' def getNewBoard(): return [[' ' for _ in range(8)] for _ in range(8)] while True: # line 248 mainBoard = getNewBoard() resetBoard(mainBoard) # This is line 251 playerTile, computerTile = enterPlayerTile() showHints = False turn = whoGoesFirst() print('The ' + turn + ' will go first.') </code></pre>
-1
2016-08-29T23:49:35Z
[ "python" ]
I'm getting an error list index out of range
39,216,282
<p>I'm reading 'Invent Your own Games with Python' and I'm trying to create a game that's in the book. Even though my code matches the code in the book I'm still getting an error:</p> <pre><code>File "/Users/Rocky/reverso.py", line 251, in &lt;module&gt; resetBoard(mainBoard) File "/Users/Rocky/reverso.py", line 27, in resetBoard board[x][y] = ' ' IndexError: list index out of range </code></pre> <p>Code:</p> <pre><code>def resetBoard(board): for x in range(8): for y in range(8): board[x][y] = ' ' #This is line 27 board[3][3] = 'X' board[3][4] = 'O' board[4][3] = 'O' board[4][4] = 'X' def getNewBoard(): board = [] for i in range(8): board.append([' '] * 8) return board while True: # line 248 mainBoard = getNewBoard() resetBoard(mainBoard) # This is line 251 playerTile, computerTile = enterPlayerTile() showHints = False turn = whoGoesFirst() print('The ' + turn + ' will go first.') </code></pre>
0
2016-08-29T22:44:49Z
39,216,996
<p>Return statement indentation in function <code>getNewBoard()</code> was incorrect.</p>
0
2016-08-30T00:09:17Z
[ "python" ]
Django - Filtering query by difference of two DateTimeFields
39,216,301
<p>I have a model with two DateTimeFields:</p> <pre><code>starttime = models.DateTimeField(db_column='starttime', blank=False, null=False) endtime = models.DateTimeField(db_column='endtime', blank=False, null=False) </code></pre> <p>In my view I would like to filter this by the difference between them. For example if the difference between start and end is more than 45 seconds.</p> <p>I tried this as a guess:</p> <pre><code> .filter((models.F('endtime') - models.F('starttime')).seconds &gt; 45)\ </code></pre> <p>But that didn't work. Is there a way to do this with the Django ORM?</p>
0
2016-08-29T22:47:01Z
39,217,786
<p>You can use the F expression as shown below. </p> <pre><code>from django.db.models import F from django.utils import timezone .filter(endtime__gt = models.F('starttime') + timezone.timedelta(0, 45)) </code></pre> <p>It will return only the rows which endtime is greater than starttime + 45 seconds. </p>
2
2016-08-30T02:13:13Z
[ "python", "django" ]
Add letters to string conditionally
39,216,335
<p><strong>Input</strong>: <code>1 10 avenue</code></p> <p><strong>Desired Output</strong>: <code>1 10th avenue</code></p> <p>As you can see above I have given an example of an input, as well as the desired output that I would like. Essentially I need to look for instances where there is a number followed by a certain pattern (avenue, street, etc). I have a list which contains all of the patterns and it's called <code>patterns</code>.</p> <p>If that number does not have "th" after it, I would like to add "th". Simply adding "th" is fine, because other portions of my code will correct it to either "st", "nd", "rd" if necessary.</p> <p><strong>Examples:</strong></p> <p><code>1 10th avenue</code> OK</p> <p><code>1 10 avenue</code> NOT OK, TH SHOULD BE ADDED!</p> <p>I have implemented a working solution, which is this:</p> <pre><code>def Add_Th(address): try: address = address.split(' ') except AttributeError: pass for pattern in patterns: try: location = address.index(pattern) - 1 number_location = address[location] except (ValueError, IndexError): continue if 'th' not in number_location: new = number_location + 'th' address[location] = new address = ' '.join(address) return address </code></pre> <p>I would like to convert this implementation to <strong>regex</strong>, as this solution seems a bit messy to me, and occasionally causes some issues. I am not the best with regex, so if anyone could steer me in the right direction that would be greatly appreciated!</p> <p>Here is my current attempt at the regex implementation:</p> <pre><code>def add_th(address): find_num = re.compile(r'(?P&lt;number&gt;[\d]{1,2}(' + "|".join(patterns + ')(?P&lt;following&gt;.*)') check_th = find_num.search(address) if check_th is not None: if re.match(r'(th)', check_th.group('following')): return address else: # this is where I would add th. I know I should use re.sub, i'm just not too sure # how I would do it else: return address </code></pre> <p>I do not have a lot of experience with regex, so please let me know if any of the work I've done is incorrect, as well as what would be the best way to add "th" to the appropriate spot.</p> <p>Thanks.</p>
0
2016-08-29T22:49:56Z
39,216,498
<p>Just one way, finding the positions <strong>behind a digit</strong> and <strong>ahead of one of those pattern words</strong> and placing <code>'th'</code> into them:</p> <pre><code>&gt;&gt;&gt; address = '1 10 avenue 3 33 street' &gt;&gt;&gt; patterns = ['avenue', 'street'] &gt;&gt;&gt; &gt;&gt;&gt; import re &gt;&gt;&gt; pattern = re.compile(r'(?&lt;=\d)(?= ({}))'.format('|'.join(patterns))) &gt;&gt;&gt; pattern.sub('th', address) '1 10th avenue 3 33th street' </code></pre>
0
2016-08-29T23:07:01Z
[ "python", "regex" ]
Printing HTML data with Python 3
39,216,368
<p>I am new to Python. I am doing a course in Python 2.7, but at the same time, I want to be able to do everything in Python 3.</p> <p>Code in Python 2.7:</p> <pre><code>import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('www.py4inf.com', 80)) mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n') while True: data = mysock.recv(512) if ( len(data) &lt; 1 ) : break print data mysock.close() </code></pre> <p>Yields properly formatted data, like so:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; </code></pre> <p>Code in Python 3:</p> <pre><code>import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('www.py4inf.com', 80)) mysock.send(('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n').encode()) while True: data = mysock.recv(512) if ( len(data) &lt; 1 ) : break print(data); mysock.close() </code></pre> <p>And it yields:</p> <pre><code>b'HTTP/1.1 200 OK\r\nContent-Type: text/html; charset="utf-8"\r\nContent-Length: 2788\r\nConnection: Close\r\n\r\n&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;\n </code></pre> <p>As you can see, it adds a "b" character, and ignores \r \n. The formatting is way off. Where did the 'b' come from? How can I make python format it properly? I have tried converting it to a string, prior to printing but it didn't help.</p>
0
2016-08-29T22:54:32Z
39,216,462
<p>It has a <code>b''</code> because what is returned by <code>mysock.recv</code> is of type <code>bytes</code>. You should decode your byte string to a unicode one with <code>decode</code>:</p> <pre><code>print(data.decode('utf-8')) </code></pre> <p>Remember, Python 2 and 3 differ regarding strings as specified in <a href="https://www.python.org/dev/peps/pep-3137/" rel="nofollow"><code>PEP 3137</code></a>. Python 3 offers a clear separation between text and binary data, Python 2 doesn't.</p> <p>The issue here is that when <code>print</code> receives your bytes object, it'll call <code>str</code> on it which will simply build a string out of it as it knows best; i.e escape backslashes and retain the rest:</p> <pre><code>&gt;&gt;&gt; str(b"hello\nworld") "b'hello\\nworld'" </code></pre> <p>Then <code>print</code> will just take that and print it out.</p>
2
2016-08-29T23:03:22Z
[ "python", "python-2.7", "python-3.x" ]
Cannot split a unicode string without converting to ascii - python 2.7
39,216,381
<p>I want to split the string <code>I have £300</code> but it seems that the split function first converts it to a ascii and after. But I can't convert it back to unicode the same as it was before. </p> <p>Is there any other way to split such a unicode string without breaking it as in the snippet bellow.</p> <pre><code># -*- coding: utf-8 -*- mystring = 'I have £300.' alist = mystring.split() alist = [item.decode("utf-8") for item in alist] print "alist",alist print "mystring.split()",mystring.split() #I want to get [I,have,£300] #I get: ['I', 'have', '\xc2\xa3300.'] </code></pre>
1
2016-08-29T22:56:07Z
39,216,478
<p>You are looking at a limitation of the way python 2 <em>displays</em> data.</p> <p>Using python 2:</p> <pre><code>&gt;&gt;&gt; mystring = 'I have £300.' &gt;&gt;&gt; mystring.split() ['I', 'have', '\xc2\xa3300.'] </code></pre> <p>But, observe that it will print as you want:</p> <pre><code>&gt;&gt;&gt; print(mystring.split()[2]) £300. </code></pre> <p>Using python 3, by contrast, it displays as you would like:</p> <pre><code>&gt;&gt;&gt; mystring = 'I have £300.' &gt;&gt;&gt; mystring.split() ['I', 'have', '£300.'] </code></pre> <p>A major reason to use python 3 is its superior handling of unicode.</p>
3
2016-08-29T23:04:54Z
[ "python", "python-2.7", "unicode", "split", "non-ascii-characters" ]
Cannot split a unicode string without converting to ascii - python 2.7
39,216,381
<p>I want to split the string <code>I have £300</code> but it seems that the split function first converts it to a ascii and after. But I can't convert it back to unicode the same as it was before. </p> <p>Is there any other way to split such a unicode string without breaking it as in the snippet bellow.</p> <pre><code># -*- coding: utf-8 -*- mystring = 'I have £300.' alist = mystring.split() alist = [item.decode("utf-8") for item in alist] print "alist",alist print "mystring.split()",mystring.split() #I want to get [I,have,£300] #I get: ['I', 'have', '\xc2\xa3300.'] </code></pre>
1
2016-08-29T22:56:07Z
39,216,633
<p>The problem is not with <code>split()</code>. The real problem is that the handling of unicode in python 2 is confusing.</p> <p>The first line in your code produces a string, i.e. a sequence of bytes, which contains the utf-8 encoding of the symbol <code>£</code>. You can confirm this by displaying the <code>repr</code> of your original string:</p> <pre><code>&gt;&gt;&gt; mystring 'I have \xc2\xa3300.' </code></pre> <p>The rest of the statements just do what you would expect them to with such input. If you want to work with unicode, create a unicode string to start with:</p> <pre><code>&gt;&gt;&gt; mystring = u'I have £300.' </code></pre> <p>A far better solution, however, is to switch to Python 3. Wrapping your head around the semantics of unicode in python 2 is not worth the effort when there's such a superior alternative.</p>
1
2016-08-29T23:24:57Z
[ "python", "python-2.7", "unicode", "split", "non-ascii-characters" ]
Spark: Extract zipped keys without computing values
39,216,409
<p>Spark has a <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.zip" rel="nofollow"><code>zip()</code></a> function to combine two RDDs. It also has functions to split them apart again: <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.keys" rel="nofollow"><code>keys()</code></a> and <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.values" rel="nofollow"><code>values()</code></a>. But to my surprise, if you ask for just the <code>keys()</code>, both RDDs are fully computed, even if the values weren't necessary for the computation.</p> <p>In this example, I create an RDD of <code>(key, value)</code> pairs, but then I only ask for the keys. Why are the values computed anyway? Does Spark make no attempt to simplify it's internal DAG in such cases?</p> <pre class="lang-py prettyprint-override"><code>In [1]: def process_value(val): ...: print "Processing {}".format(val) ...: return 2*val ...: In [2]: k = sc.parallelize(['a','b','c']) In [3]: v = sc.parallelize([1,2,3]).map(process_value) In [4]: zipped = k.zip(v) In [5]: zipped.keys().collect() Processing 1 Processing 2 Processing 3 Out[5]: ['a', 'b', 'c'] </code></pre>
0
2016-08-29T22:58:30Z
39,216,798
<p>If you look at the <a href="https://github.com/apache/spark/blob/v2.0.0/core/src/main/scala/org/apache/spark/rdd/PairRDDFunctions.scala#L1249" rel="nofollow">source</a> (at least at 2.0) keys() is simply implemented as </p> <p><code>rdd.map(_._1)</code></p> <p>I.e. returning the first attribute of the tuple, so the tuple must be fully instantiated.</p> <p>This might have worked if zip returned <code>RDD[Seq[K, V]]</code> or some other lazy data structure, but a tuple is not a lazy data structure.</p> <p>In short: no.</p>
2
2016-08-29T23:43:16Z
[ "python", "apache-spark", "pyspark" ]
How to extract only the key-value from this list-dict json response?
39,216,533
<p>I would like how can I extract only the keys and values from this json response:</p> <pre><code>[{u'SkuSellersInformation': [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}], u'BestInstallmentNumber': 10, u'RealWeightKg': 100.0, u'NotifyMe': True, u'HasServiceAtCartPage': False, u'RewardValue': 0.0, u'ListPrice': 409, u'Name': u'Light Blue Eau de Toilette Dolce &amp; Gabbana - Perfume Feminino - 50ml', u'HasExtendedWarranty': False, u'BestInstallmentValue': 40.9, u'Ean': u'0737052074313', u'Price': 409, u'RealWidth': 10.0, u'IdProduct': 909, u'AvailabilityMessage': u'True', u'HasServiceAtServicePage': False, u'RealLength': 10.0, u'RealHeight': 10.0, u'HasServiceAtProductPage': False, u'SalesChannel': u'1', u'DefaultSellerId': u'1', u'Reference': u'002796', u'HasExtendedWarrantyPage': False, u'Id': 5293, u'Images': [[{u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-320-320/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-55-55/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-65-65/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-500-500/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-120-120/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-130-130/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}], [{u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-320-320/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-55-55/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-65-65/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-500-500/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-120-120/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-130-130/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}]], u'Availability': True}] </code></pre> <p>I tried this way, but still remain some dicts inside sub-lists</p> <pre><code>import urllib2 import json response = urllib2.urlopen('http://www.site.com.br/produto/sku/5293') data = json.load(response) for a in data: for key, value in a.items(): print key, value </code></pre> <p>This is the result, but as you guys can see, still remain some key-value inside the sub-list</p> <pre class="lang-none prettyprint-override"><code>SkuSellersInformation : [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}] BestInstallmentNumber : 10 RealWeightKg : 100.0 NotifyMe : True HasServiceAtCartPage : False RewardValue : 0.0 ListPrice : 409 Name : Light Blue Eau de Toilette Dolce &amp; Gabbana - Perfume Feminino - 50ml HasExtendedWarranty : False BestInstallmentValue : 40.9 Ean : 0737052074313 Price : 409 RealWidth : 10.0 IdProduct : 909 AvailabilityMessage : True HasServiceAtServicePage : False RealLength : 10.0 RealHeight : 10.0 HasServiceAtProductPage : False SalesChannel : 1 DefaultSellerId : 1 Reference : 002796 HasExtendedWarrantyPage : False Id : 5293 Images : [[{u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-320-320/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-55-55/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-65-65/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-500-500/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-120-120/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-130-130/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}], [{u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-320-320/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-55-55/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-65-65/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-500-500/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-120-120/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-130-130/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}]] Availability : True </code></pre>
0
2016-08-29T23:11:34Z
39,216,809
<p>Well,</p> <p>Your question is not clear, but maybe, this is what you want:</p> <pre><code>for a in data: for key, value in a.items(): if key in ['BestInstallmentNumber', 'RealWeightKg', 'NotifyMe', 'HasServiceAtCartPage', 'RewardValue']: print key, value </code></pre>
-1
2016-08-29T23:44:46Z
[ "python", "json", "list", "dictionary" ]
How to extract only the key-value from this list-dict json response?
39,216,533
<p>I would like how can I extract only the keys and values from this json response:</p> <pre><code>[{u'SkuSellersInformation': [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}], u'BestInstallmentNumber': 10, u'RealWeightKg': 100.0, u'NotifyMe': True, u'HasServiceAtCartPage': False, u'RewardValue': 0.0, u'ListPrice': 409, u'Name': u'Light Blue Eau de Toilette Dolce &amp; Gabbana - Perfume Feminino - 50ml', u'HasExtendedWarranty': False, u'BestInstallmentValue': 40.9, u'Ean': u'0737052074313', u'Price': 409, u'RealWidth': 10.0, u'IdProduct': 909, u'AvailabilityMessage': u'True', u'HasServiceAtServicePage': False, u'RealLength': 10.0, u'RealHeight': 10.0, u'HasServiceAtProductPage': False, u'SalesChannel': u'1', u'DefaultSellerId': u'1', u'Reference': u'002796', u'HasExtendedWarrantyPage': False, u'Id': 5293, u'Images': [[{u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-320-320/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-55-55/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-65-65/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-500-500/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-120-120/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-130-130/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}], [{u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-320-320/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-55-55/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-65-65/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-500-500/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-120-120/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-130-130/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}]], u'Availability': True}] </code></pre> <p>I tried this way, but still remain some dicts inside sub-lists</p> <pre><code>import urllib2 import json response = urllib2.urlopen('http://www.site.com.br/produto/sku/5293') data = json.load(response) for a in data: for key, value in a.items(): print key, value </code></pre> <p>This is the result, but as you guys can see, still remain some key-value inside the sub-list</p> <pre class="lang-none prettyprint-override"><code>SkuSellersInformation : [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}] BestInstallmentNumber : 10 RealWeightKg : 100.0 NotifyMe : True HasServiceAtCartPage : False RewardValue : 0.0 ListPrice : 409 Name : Light Blue Eau de Toilette Dolce &amp; Gabbana - Perfume Feminino - 50ml HasExtendedWarranty : False BestInstallmentValue : 40.9 Ean : 0737052074313 Price : 409 RealWidth : 10.0 IdProduct : 909 AvailabilityMessage : True HasServiceAtServicePage : False RealLength : 10.0 RealHeight : 10.0 HasServiceAtProductPage : False SalesChannel : 1 DefaultSellerId : 1 Reference : 002796 HasExtendedWarrantyPage : False Id : 5293 Images : [[{u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-320-320/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-55-55/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-65-65/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-500-500/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-120-120/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-130-130/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}], [{u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-320-320/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-55-55/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-65-65/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-500-500/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-120-120/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-130-130/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}]] Availability : True </code></pre>
0
2016-08-29T23:11:34Z
39,217,920
<p>Since JSON allow the definition of recursive data structures, the following recursive function will find all the key, value pairs in all the dictionaries encountered in one. Note it may yield the same key multiple times when it occurs in more than one (nested or parallel) dictionary.</p> <pre><code>def get_all(myjson): """ Recursively find the keys and associated values in all the dictionaries in the json object or list. """ if isinstance(myjson, dict): for jsonkey, jsonvalue in myjson.items(): if not isinstance(jsonvalue, (dict, list)): yield jsonkey, jsonvalue else: for k, v in get_all(jsonvalue): yield k, v elif isinstance(myjson, list): for element in myjson: if isinstance(element, (dict, list)): for k, v in get_all(element): yield k, v data = [{u'SkuSellersInformation': [{u'Name': u'site', u'Price': 409, u'IsDefaultSeller': True, u'AvailableQuantity': 2, u'LogoUrl': None, u'SellerId': u'1', u'ListPrice': 409}], u'BestInstallmentNumber': 10, u'RealWeightKg': 100.0, u'NotifyMe': True, u'HasServiceAtCartPage': False, u'RewardValue': 0.0, u'ListPrice': 409, u'Name': u'Light Blue Eau de Toilette Dolce &amp; Gabbana - Perfume Feminino - 50ml', u'HasExtendedWarranty': False, u'BestInstallmentValue': 40.9, u'Ean': u'0737052074313', u'Price': 409, u'RealWidth': 10.0, u'IdProduct': 909, u'AvailabilityMessage': u'True', u'HasServiceAtServicePage': False, u'RealLength': 10.0, u'RealHeight': 10.0, u'HasServiceAtProductPage': False, u'SalesChannel': u'1', u'DefaultSellerId': u'1', u'Reference': u'002796', u'HasExtendedWarrantyPage': False, u'Id': 5293, u'Images': [[{u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-320-320/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-55-55/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-65-65/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-500-500/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-120-120/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/183280-130-130/light-blue-edt-dg-2.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'183280', u'IsMain': False}], [{u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-320-320/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 2, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-55-55/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 3, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-65-65/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 1, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-500-500/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 10, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-120-120/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 29, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}, {u'Path': u'http://site.vteximg.com.br/arquivos/ids/187857-130-130/light-blue-eau-de-toilette-dolce-gabbana-perfume-feminino.jpg', u'ArchiveTypeId': 30, u'Name': None, u'IdArchive': u'187857', u'IsMain': True}]], u'Availability': True}] for key, value in get_all(data): print('{!r}: {!r}'.format(key, value)) </code></pre>
1
2016-08-30T02:31:06Z
[ "python", "json", "list", "dictionary" ]
Queue runs successfully! Exits instead of continue, after Break
39,216,593
<p>I am using this script to resolve thousands of domains. It runs successfully, and ends when the queue is empty. I am trying to it to break out of the loop and continue the script by printing.</p> <p>How do I get this code to break out of the loop, ans print, when the queue is empty?</p> <pre><code>q = queue.Queue() for name in names: q.put(name) def async_dns(): s = adns.init() while True: try: dname = q.get(False) q.task_done() except queue.Empty: return response = s.synchronous(dname,adns.rr.NS)[0] if response == 0: dot_net.append("Y") print(dname + ", is Y") elif response == 300 or response == 30 or response == 60: dot_net.append("N") print(dname + ", is N") threads = [] for i in range(20): t = threading.Thread(target=async_dns) threads.append(t) t.start() print("Done !!") </code></pre>
0
2016-08-29T23:19:18Z
39,216,706
<p>You could simply move the code that does the dns lookup and prints the result into the body of the <code>try/except</code> block:</p> <pre><code>def async_dns(): s = adns.init() while True: try: dname = q.get(False) response = s.synchronous(dname,adns.rr.NS)[0] if response == 0: dot_net.append("Y") print(dname + ", is Y") elif response == 300 or response == 30 or response == 60: dot_net.append("N") print(dname + ", is N") q.task_done() except queue.Empty: return </code></pre> <p>Now when the queue is empty a <code>queue.Empty</code> will be raised and the exception handler will simply exit the thread function, otherwise it will print out the dns values.</p>
0
2016-08-29T23:32:47Z
[ "python", "queue" ]
How to overwrite a tensorflow variable after it has been initialized?
39,216,625
<p>Assuming codes like this:</p> <pre><code> sess.run(tf.initialize_all_variables()) assign_op_0 = embedding_list[0].assign(tf.random_normal([35019, 32], stddev = 0.0)) assign_op_1 = embedding_list[1].assign(tf.random_normal([35019, 32], stddev = 0.0)) sess.run(assign_op_0) sess.run(assign_op_1) </code></pre> <p>embedding_list[0] and embedding_list[1] are two variables which have been initialized in the first line of codes. Now I want to overwrite with some new values, so I have the following four lines of code, however, I don't know if this is correct. And I can not even print the values of the embedding_list[0] and embedding_list[1]. When I do like this:</p> <pre><code>print(embedding_list[0].eval(session=sess.run)) </code></pre> <p>it has this error:</p> <pre><code>Traceback (most recent call last): File "/home/zhao/DeepQA-master/main.py", line 29, in &lt;module&gt; chatbot.main() File "/home/zhao/DeepQA-master/chatbot/chatbot.py", line 213, in main print(embedding_list[0].eval(session=self.sess.run)) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/variables.py", line 437, in eval return self._variable.eval(session=session) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 555, in eval return _eval_using_default_session(self, feed_dict, self.graph, session) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 3494, in _eval_using_default_session if session.graph is not graph: AttributeError: 'function' object has no attribute 'graph' </code></pre>
0
2016-08-29T23:24:07Z
39,229,707
<p>Try as follows:</p> <pre><code>sess.run(tf.initialize_all_variables()) W_0 = tf.Variable(tf.random_normal([35019, 32], stddev = 0.0)) assign_op_0 = W_0.assign(embedding_list[0]) sess.run(assign_op_0) </code></pre>
1
2016-08-30T14:05:01Z
[ "python", "tensorflow" ]
Python KMax Pooling (MXNet)
39,216,640
<p>I'm trying to recreate the char-level CNN in <a href="https://arxiv.org/pdf/1606.01781v1.pdf" rel="nofollow">this paper</a> and am a bit stuck at the final step where I need to create a k-max pooling layer, because I am using MXNet and it does not have this.</p> <blockquote> <p>An important difference is also the introduction of multiple temporal k-max pooling layers. This allows to detect the k most important features in a sentence, independent of their specific position, preserving their relative order.</p> </blockquote> <p>However, MXNet does have the ability to <a href="http://mxnet.readthedocs.io/en/latest/how_to/new_op.html" rel="nofollow">add a new-op</a> which I have been trying to do like so (although getting a bit confused with the shape of the data, given filters and batch-size). </p> <p>The shape of the data coming in:</p> <pre><code>128 (min-batch) x 512 (number of filters) x 1 (height) x 125 (width) </code></pre> <p>The shape of the data coming out (k-max pooling, k = 7):</p> <pre><code>128 (min-batch) x 512 (number of filters) x 1 (height) x 7 (width) </code></pre> <p>My idea so far ... :</p> <pre><code>class KMaxPooling(mx.operator.CustomOp): def forward(self, is_train, req, in_data, out_data, aux): # Desired (k=3): # in_data = np.array([1, 2, 4, 10, 5, 3]) # out_data = [4, 10, 5] x = in_data[0].asnumpy() idx = x.argsort()[-k:] idx.sort(axis=0) y = x[idx] </code></pre> <p>However, I'm not sure about several things:</p> <ol> <li>How to test whether this works (once I have some complete code)</li> <li>What the dimensions should be? I'm sorting on the last dimension (axis=0)</li> <li>What to do for the backward() function i.e. the gradient propogation</li> <li>Whether this will work with GPU - I'm guessing I will have to rewrite it in C/cuda?</li> </ol> <p>I found this example by someone else for keras (but don't have the rep to link):</p> <pre><code>import numpy as np import theano.tensor as T from keras.layers.core import MaskedLayer class KMaxPooling(MaskedLayer): def __init__(self, pooling_size): super(MaskedLayer, self).__init__() self.pooling_size = pooling_size self.input = T.tensor3() def get_output_mask(self, train=False): return None def get_output(self, train=False): data = self.get_input(train) mask = self.get_input_mask(train) if mask is None: mask = T.sum(T.ones_like(data), axis=-1) mask = mask.dimshuffle(0, 1, "x") masked_data = T.switch(T.eq(mask, 0), -np.inf, data) result = masked_data[T.arange(masked_data.shape[0]).dimshuffle(0, "x", "x"), T.sort(T.argsort(masked_data, axis=1)[:, -self.pooling_size:, :], axis=1), T.arange(masked_data.shape[2]).dimshuffle("x", "x", 0)] </code></pre>
1
2016-08-29T23:25:43Z
39,317,223
<p><a href="https://github.com/CNevd/DeepLearning-Mxnet/blob/master/DCNN/dcnn_train.py#L15" rel="nofollow">Here</a> you have the code in python with mxnet. </p> <p>It would be great to have it as well in R.</p>
0
2016-09-04T13:06:16Z
[ "python", "neural-network", "deep-learning", "conv-neural-network", "mxnet" ]
How to generate random number between 0 and 1 in genetic algorithm toolbox, Deap
39,216,660
<p>I am using <a href="https://pypi.python.org/pypi/deap" rel="nofollow">genetic algorithm toolbox</a> in Python. The code: </p> <p><code>toolbox.register("attr_bool", random.randint, 0, 1)</code> usually defines random numbers of <code>0</code> and <code>1</code> to be generated. The question is that I am looking for random numbers <strong>between</strong> <code>0</code> and <code>1</code>. I used <code>toolbox.register("attr_bool", random.uniform(0, 1))</code>, but it takes me the below error: <code>TypeError: the first argument must be callable</code></p>
0
2016-08-29T23:27:51Z
39,216,858
<p>The error is telling you that it must be able to call the first argument, meaning that it has to be able to act as a function. <code>random.randint</code> is a function, but <code>random.uniform(0, 1)</code> is not. It's a floating-point number. To fix this, you can simply make an anonymous wrapper function with the <code>lambda</code> keyword:</p> <pre><code>toolbox.register("attr_bool", lambda: random.uniform(0, 1)) </code></pre>
2
2016-08-29T23:50:28Z
[ "python", "random", "genetic-algorithm" ]
When using BING SEARCH API, how do you omit duplicate results?
39,216,665
<p>I built a python 2.7 BING SEARCH API pull, that returns 50 counts per page, and paginates by changing the offset value by a value of 50 each time. My results are written to a JSON file. </p> <p>I am specifying a User-Agent and X-Search-ClientIP in the header of my api call. I am also specifying a responseFilter of webpages, as well as the mkt value of 'en-us'. </p> <p>I am concerned, because I'm getting several duplicate search results. When I page 10 times (thus, retrieving 50 X 10 = 500 results), roughly 17% of these are duplicate records. Is there a way that I can force bing to only return non-duplicate values? What extra steps do you recommend I take, to get as close to getting back unique values only?</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib, urllib, base64, json, re, os, sys, codecs, locale, time pull_count = 50 ## Var used to control # of hits per pull offset = 0 ## Var used to push pagination counter to http get num_paginations = 10 ## Var used to control max # of paginations local_counter = 1 ## Helps Write commas to json file for all but last run timer_counter = 1 ## Variable used to make system wait after 5 pulls dump_file = 'BingDump.json' ## Name of local file where results are written to api_domain = 'api.cognitive.microsoft.com' query = 'Bill Gates' user_agent = 'Mozilla/5.0 (MAC OSX, Educational Usage Only)' x_search = '199.99.99.99' #Request Headers, open connection, open file write to output file headers = { 'Ocp-Apim-Subscription-Key': 'MYSUBSCRIPTIONKEY', 'User-Agent' : user_agent, 'X-Search-ClientIP': x_search, } conn = httplib.HTTPSConnection(api_domain) fhand = open(dump_file,'w') #Function to build URL for API PULL def scraper() : pull_count_str = str(pull_count) offset_str = str(offset) params = urllib.urlencode({ 'q': query, 'count': pull_count_str, 'offset': offset_str, 'mkt': 'en-us', 'safesearch': 'Moderate', 'responseFilter': 'webpages', #controls whether pull scrapes from web/image/news etc }) return(params) #Function set to wait 4 seconds after 5 pulls def holdup(entry) : if entry != 5 : entry += 1 else: entry = 1 time.sleep(4) return(entry) #Function that establishes http get, and writes data to json file def getwrite(entry1, entry2) : conn.request("GET", "/bing/v5.0/search?%s" % entry1, "{body}", entry2) response = conn.getresponse() data = response.read() json_data = json.loads(data) fhand.write(json.dumps(json_data, indent=4)) #Main Code - Pulls data iteratively and writes it to json file fhand.write('{') for i in range(num_paginations) : dict_load = '"' + str(local_counter) + '"' + ' : ' fhand.write(dict_load) try: link_params = scraper() print('Retrieving: ' + api_domain + '/bing/v5.0/search?' + link_params) getwrite(link_params, headers) except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) fhand.write('"Error. Could not pull data"') offset += pull_count if local_counter != num_paginations : fhand.write(', ') local_counter += 1 timer_counter = holdup(timer_counter) fhand.write('}') fhand.close() conn.close() </code></pre>
-1
2016-08-29T23:28:38Z
39,455,834
<p>Thank you for your inquiry. We noticed you have the following # of paginations:</p> <p>One thing I noticed is that the pagination is set to 10. num_paginations = 10 ## Var used to control max # of paginations.</p> <p>Thanks, Patrick</p>
0
2016-09-12T17:41:29Z
[ "python", "duplicates", "bing-api", "microsoft-cognitive" ]
String variable as literal bytes
39,216,694
<p>I'm reading in a config file. Say I end up with a configuration variable:</p> <pre><code>header = '\x42\x5a\x68' </code></pre> <p>I want to match this against binary files using startswith.</p> <p>Unsurprisingly, I get a <code>"TypeError startswith first arg must be bytes or a tuple of bytes, not str"</code>, if I try to use this directly. How do I use this string? I don't want it encoded.</p> <p>I have to read the string from a file. If there's some other way to go about this, I'm all ears. Thanks for reading!</p>
0
2016-08-29T23:32:09Z
39,216,928
<blockquote> <p>How do I use this string? I don't want it encoded.</p> </blockquote> <p>You must. Make a decision, either <code>decode</code> the string you get from the binary file or <code>encode</code> the <code>header</code> name. You can't mix those two types together.</p> <p>See <em><a href="https://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit" rel="nofollow">Text Vs. Data Instead Of Unicode Vs. 8-bit</a></em> in the python docs, all mixing between these types (as it occurs in <code>startswith</code> too) will result in a <code>TypeError</code>.</p>
0
2016-08-29T23:59:49Z
[ "python", "string", "python-3.x" ]
How do I access google cloud storage from local python app?
39,216,702
<p>I am able to access gcs when my app is deployed to gae, but I would like to access gcs from my local machine during development. How would I go about doing this? </p> <p>Here is the traceback i get when i try to open a file on gcs: </p> <pre><code>Traceback (most recent call last): File "/Users/alvinsolidum/Downloads/google_appengine/google/appengine/runtime/wsgi.py", line 267, in Handle result = handler(dict(self._environ), self._StartResponse) File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 1519, in __call__ response = self._internal_error(e) File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 1511, in __call__ rv = self.handle_exception(request, response, e) File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 1505, in __call__ rv = self.router.dispatch(request, response) File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher return route.handler_adapter(request, response) File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 1077, in __call__ return handler.dispatch() File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 547, in dispatch return self.handle_exception(e, self.app.debug) File "/Users/alvinsolidum/Downloads/google_appengine/lib/webapp2-2.3/webapp2.py", line 545, in dispatch return method(*args, **kwargs) File "/Users/alvinsolidum/Documents/fallsafety-dataflow/preprocess/main.py", line 74, in get self.to_csv() File "/Users/alvinsolidum/Documents/fallsafety-dataflow/preprocess/main.py", line 41, in to_csv compressed_flo = gcs.open(read_filepath, 'r') File "/Users/alvinsolidum/Documents/fallsafety-dataflow/preprocess/lib/cloudstorage/cloudstorage_api.py", line 103, in open offset=offset) File "/Users/alvinsolidum/Documents/fallsafety-dataflow/preprocess/lib/cloudstorage/storage_api.py", line 249, in __init__ errors.check_status(status, [200], path, resp_headers=headers, body=content) File "/Users/alvinsolidum/Documents/fallsafety-dataflow/preprocess/lib/cloudstorage/errors.py", line 132, in check_status raise NotFoundError(msg) NotFoundError: Expect status [200] from Google Storage. But got status 404. Path: '/fallsafety-test-general/apple-watch/continuous/active/54d0044919e92b0c00c29555-29391CEA593C4D798A1EA08BD23DA47E-0002-continuous.csv.gz'. Request headers: None. Response headers: {'date': 'Mon, 29 Aug 2016 23:15:49 GMT', 'server': 'Development/2.0', 'connection': 'close'}. Body: ''. Extra info: None. </code></pre>
1
2016-08-29T23:32:32Z
39,221,406
<p>Ah, it looks like you're using the appengine-gcs-client for Python. When running on the local development server, the client defaults to using a local, fake version of GCS (see the response header that says "Server: Development/2.0"?). I'm guessing that you're looking for a real GCS object that you haven't uploaded to the local fake.</p> <p>You can get around this either by uploading the object in question as part of your server initialization, using a different library (gcloud-python is really nice), or disabling the local fake, which you could do by setting the SERVER_SOFTWARE environment variable:</p> <pre><code># Logic for whether to use local fake is here: https://github.com/GoogleCloudPlatform/appengine-gcs-client/blob/f9dbbd43ec431f739aa33a44cf24d32a19579f33/python/src/cloudstorage/common.py#L387 os.environ['SERVER_SOFTWARE'] = 'Development (remote_api)/1.0' </code></pre>
1
2016-08-30T07:31:48Z
[ "python", "google-app-engine", "google-cloud-storage", "google-cloud-platform" ]
Compute Cost of Kmeans
39,216,760
<p>I am using this <a href="https://github.com/yahoo/lopq/blob/master/python/lopq/model.py" rel="nofollow">model</a>, which is not written by me. In order to predict the centroids I had to do this:</p> <pre><code>model = cPickle.load(open("/tmp/model_centroids_128d_pkl.lopq")) codes = d.map(lambda x: (x[0], model.predict_coarse(x[1]))) </code></pre> <p>where `d.first()' yields this:</p> <pre><code>(u'3768915289', array([ -86.00641097, -100.41325623, &lt;128 coords in total&gt;])) </code></pre> <p>and <code>codes.first()</code>:</p> <pre><code>(u'3768915289', (5657, 7810)) </code></pre> <p>How can I <a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel.computeCost" rel="nofollow">computeCost()</a> of this KMeans model?</p> <hr> <p>After reading <a href="https://github.com/yahoo/lopq/blob/master/spark/train_model.py" rel="nofollow">train_model.py</a>, I am trying like this:</p> <pre><code>In [23]: from pyspark.mllib.clustering import KMeans, KMeansModel In [24]: Cs = model.Cs # centroids In [25]: model = KMeansModel(Cs[0]) # I am very positive this line is good In [26]: costs = d.map(lambda x: model.computeCost(x[1])) In [27]: costs.first() </code></pre> <p>but I get this error:</p> <pre><code>AttributeError: 'numpy.ndarray' object has no attribute 'map' </code></pre> <p>which means that Spark tries to use <code>map()</code> under the hood for <code>x[1]</code>...</p> <hr> <p>which means that it expects an RDD!!! But of which form?</p> <p>I am trying now with:</p> <pre><code>d = d.map(lambda x: x[1]) d.first() array([ 7.17036494e+01, 1.07987890e+01, ...]) costs = model.computeCost(d) </code></pre> <p>and I don't get the error:</p> <pre><code>16/08/30 00:39:21 WARN TaskSetManager: Lost task 821.0 in stage 40.0 : java.lang.IllegalArgumentException: requirement failed at scala.Predef$.require(Predef.scala:221) at org.apache.spark.mllib.util.MLUtils$.fastSquaredDistance(MLUtils.scala:330) at org.apache.spark.mllib.clustering.KMeans$.fastSquaredDistance(KMeans.scala:595) at org.apache.spark.mllib.clustering.KMeans$$anonfun$findClosest$1.apply(KMeans.scala:569) at org.apache.spark.mllib.clustering.KMeans$$anonfun$findClosest$1.apply(KMeans.scala:563) at scala.collection.mutable.ArraySeq.foreach(ArraySeq.scala:73) at org.apache.spark.mllib.clustering.KMeans$.findClosest(KMeans.scala:563) at org.apache.spark.mllib.clustering.KMeans$.pointCost(KMeans.scala:586) at org.apache.spark.mllib.clustering.KMeansModel$$anonfun$computeCost$1.apply(KMeansModel.scala:88) at org.apache.spark.mllib.clustering.KMeansModel$$anonfun$computeCost$1.apply(KMeansModel.scala:88) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) at scala.collection.TraversableOnce$class.foldLeft(TraversableOnce.scala:144) at scala.collection.AbstractIterator.foldLeft(Iterator.scala:1157) at scala.collection.TraversableOnce$class.fold(TraversableOnce.scala:199) at scala.collection.AbstractIterator.fold(Iterator.scala:1157) at org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$19.apply(RDD.scala:1086) at org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$19.apply(RDD.scala:1086) at org.apache.spark.SparkContext$$anonfun$36.apply(SparkContext.scala:1951) at org.apache.spark.SparkContext$$anonfun$36.apply(SparkContext.scala:1951) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66) at org.apache.spark.scheduler.Task.run(Task.scala:89) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-44-6223595c8b5f&gt; in &lt;module&gt;() ----&gt; 1 costs = model.computeCost(d) /home/gs/spark/current/python/pyspark/mllib/clustering.py in computeCost(self, rdd) 140 """ 141 cost = callMLlibFunc("computeCostKmeansModel", rdd.map(_convert_to_vector), --&gt; 142 [_convert_to_vector(c) for c in self.centers]) 143 return cost 144 /home/gs/spark/current/python/pyspark/mllib/common.py in callMLlibFunc(name, *args) 128 sc = SparkContext.getOrCreate() 129 api = getattr(sc._jvm.PythonMLLibAPI(), name) --&gt; 130 return callJavaFunc(sc, api, *args) 131 132 /home/gs/spark/current/python/pyspark/mllib/common.py in callJavaFunc(sc, func, *args) 121 """ Call Java Function """ 122 args = [_py2java(sc, a) for a in args] --&gt; 123 return _java2py(sc, func(*args)) 124 125 /home/gs/spark/current/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args) 811 answer = self.gateway_client.send_command(command) 812 return_value = get_return_value( --&gt; 813 answer, self.gateway_client, self.target_id, self.name) 814 815 for temp_arg in temp_args: /home/gs/spark/current/python/pyspark/sql/utils.py in deco(*a, **kw) 43 def deco(*a, **kw): 44 try: ---&gt; 45 return f(*a, **kw) 46 except py4j.protocol.Py4JJavaError as e: 47 s = e.java_exception.toString() /home/gs/spark/current/python/lib/py4j-0.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 306 raise Py4JJavaError( 307 "An error occurred while calling {0}{1}{2}.\n". --&gt; 308 format(target_id, ".", name), value) 309 else: 310 raise Py4JError( Py4JJavaError: An error occurred while calling o25177.computeCostKmeansModel. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 821 in stage 40.0 failed 4 times, most recent failure: Lost task 821.3 in stage 40.0: java.lang.IllegalArgumentException: requirement failed at scala.Predef$.require(Predef.scala:221) at org.apache.spark.mllib.util.MLUtils$.fastSquaredDistance(MLUtils.scala:330) at org.apache.spark.mllib.clustering.KMeans$.fastSquaredDistance(KMeans.scala:595) at org.apache.spark.mllib.clustering.KMeans$$anonfun$findClosest$1.apply(KMeans.scala:569) at org.apache.spark.mllib.clustering.KMeans$$anonfun$findClosest$1.apply(KMeans.scala:563) at scala.collection.mutable.ArraySeq.foreach(ArraySeq.scala:73) at org.apache.spark.mllib.clustering.KMeans$.findClosest(KMeans.scala:563) at org.apache.spark.mllib.clustering.KMeans$.pointCost(KMeans.scala:586) at org.apache.spark.mllib.clustering.KMeansModel$$anonfun$computeCost$1.apply(KMeansModel.scala:88) at org.apache.spark.mllib.clustering.KMeansModel$$anonfun$computeCost$1.apply(KMeansModel.scala:88) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) at scala.collection.TraversableOnce$class.foldLeft(TraversableOnce.scala:144) at scala.collection.AbstractIterator.foldLeft(Iterator.scala:1157) at scala.collection.TraversableOnce$class.fold(TraversableOnce.scala:199) at scala.collection.AbstractIterator.fold(Iterator.scala:1157) at org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$19.apply(RDD.scala:1086) at org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$19.apply(RDD.scala:1086) at org.apache.spark.SparkContext$$anonfun$36.apply(SparkContext.scala:1951) at org.apache.spark.SparkContext$$anonfun$36.apply(SparkContext.scala:1951) at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66) at org.apache.spark.scheduler.Task.run(Task.scala:89) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:227) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) </code></pre> <hr> <p>Edit:</p> <pre><code>split_vecs = d.map(lambda x: np.split(x[1], 2)) </code></pre> <p>seems to be a good step, since the centroids are of 64 dimensions.</p> <pre><code>model.computeCost((d.map(lambda x: x[1])).first()) </code></pre> <p>gives this error: <code>AttributeError: 'numpy.ndarray' object has no attribute 'map'</code>.</p>
1
2016-08-29T23:38:35Z
39,217,175
<p>Apparently from the <a href="https://spark.apache.org/docs/latest/mllib-clustering.html" rel="nofollow">documentation</a> I've read, you have to:</p> <ol> <li><p>Create a model maybe by <a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel.load" rel="nofollow">reading</a> a previously <a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel.save" rel="nofollow">saved </a> model, or by fitting a new model.</p></li> <li><p>After obtaining that <a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel" rel="nofollow">model</a> you can use its method <a href="http://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=kmeans#pyspark.mllib.clustering.KMeansModel.clusterCenters" rel="nofollow">computeCost</a>, which needs a well formatted <code>RDD</code> to output something useful. </p></li> </ol> <p>Thus, if I assume that your variable <code>model</code> is a <code>KMeansModel</code> and the data stored in the variable <code>d</code> has the expected representation, then you should be able to run the following code:</p> <pre><code>model.computeCost(d) </code></pre> <hr> <p>Edit:</p> <p>You should create an RDD that will contain vectors of the same dimensions as the centroids, and provide that as an input parameter to <code>computeCost()</code>, like this for example:</p> <pre><code>split_vecs = d.map(lambda x: (x[0], np.split(x[1], 2))) costs_per_split = [KMeansModel(model.Cs[i]).computeCost(split_vecs.map(lambda x: x[1][i])) for i in range(2)] </code></pre>
1
2016-08-30T00:34:27Z
[ "python", "apache-spark", "machine-learning", "distributed-computing", "k-means" ]
Stacking up multiple shapely polygons to form a heatmap
39,216,767
<p>I have a bunch of Shapely polygons that overlap. Each shape represents one particular observation of the object in the wild. I want to build up some sort of a cumulative observation (heatmap?) by combining the polygons together. Not just the union: I want to combine them in such a way that I can threshold it together and form a better estimate of where the object actually is. What is the best to "rasterize" the shapely polygon?</p>
1
2016-08-29T23:39:04Z
39,351,731
<p>one could perhaps proceed by adding one polygon at a time, keep a list of disjoint shapes and remember for each of them how many polygons contributed:</p> <pre><code>import copy from itertools import groupby from random import randint, seed from shapely.geometry import Polygon, box from shapely.ops import cascaded_union polygons = [ Polygon([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]), Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), Polygon([(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)]) ] def check_shape(s): return (s.geom_type in ['Polygon', 'MultiPolygon'] and not s.is_empty) shapes = [] for p in polygons: polygon = copy.deepcopy(p) new_shapes = [] for shape_cnt, shape in shapes: new_shapes.extend([ (shape_cnt, shape.difference(polygon)), (shape_cnt+1, shape.intersection(polygon)) ]) polygon = polygon.difference(shape) new_shapes.append((1, polygon)) shapes = list(filter(lambda s: check_shape(s[1]), new_shapes)) for p in polygons: print(p) for cnt, g in groupby(sorted(shapes, key = lambda s: s[0]), key = lambda s: s[0]): print(cnt, cascaded_union(list(map(lambda s: s[1], g)))) </code></pre> <p>This then produces:</p> <pre><code>POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0)) POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0)) POLYGON ((1 1, 2 1, 2 2, 1 2, 1 1)) 1 MULTIPOLYGON (((2 1, 2 0, 1 0, 1 1, 2 1)), ((0 1, 0 2, 1 2, 1 1, 0 1))) 2 MULTIPOLYGON (((1 0, 0 0, 0 1, 1 1, 1 0)), ((1 2, 2 2, 2 1, 1 1, 1 2))) </code></pre>
1
2016-09-06T14:38:04Z
[ "python", "matplotlib", "shapely" ]
Problems with multi-layer perceptron in Tensorflow
39,216,771
<p>I created a perceptron (i.e. neural network with fully connected layer(s)) in Tensorflow with one hidden layer (with RELU activation function) and ran it on MNIST data successfully, getting a 90%+ accuracy rate. But when I add a second hidden layer, I get a very low accuracy rate (10%) even after many mini-batches of stochastic gradient descent. Any ideas for why this would happen? I can add my Python code to this post if it would be helpful.</p> <p>Here is my graph code (uses Udacity course's starter code, but with additional layers added). Note that some aspects are commented out for simplicity - but even with this simpler version, the symptom remains the same (low accuracy rate of approx 10% even after many iterations):</p> <pre><code>import tensorflow as tf batch_size = 128 hidden_size = 256 train_subset = 10000 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) #tf_train_dataset = tf.constant(train_dataset[:train_subset, :]) #tf_train_labels = tf.constant(train_labels[:train_subset]) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weightsToHidden1 = tf.Variable( tf.truncated_normal([image_size * image_size, hidden_size])) biasesToHidden1 = tf.Variable(tf.zeros([hidden_size])) weightsToHidden2 = tf.Variable( tf.truncated_normal([hidden_size, hidden_size])) biasesToHidden2 = tf.Variable(tf.zeros([hidden_size])) weightsToOutput = tf.Variable( tf.truncated_normal([hidden_size, num_labels])) biasesToOutput = tf.Variable(tf.zeros([num_labels])) # Training computation. logitsToHidden1 = tf.nn.relu(tf.matmul(tf_train_dataset, weightsToHidden1) + biasesToHidden1) validLogitsToHidden1 = tf.nn.relu(tf.matmul(tf_valid_dataset, weightsToHidden1) + biasesToHidden1) testLogitsToHidden1 = tf.nn.relu(tf.matmul(tf_test_dataset, weightsToHidden1) + biasesToHidden1) logitsToHidden2 = tf.nn.relu(tf.matmul(logitsToHidden1, weightsToHidden2) + biasesToHidden2) validLogitsToHidden2 = tf.nn.relu(tf.matmul(validLogitsToHidden1, weightsToHidden2) + biasesToHidden2) testLogitsToHidden2 = tf.nn.relu(tf.matmul(testLogitsToHidden1, weightsToHidden2) + biasesToHidden2) logitsToOutput = tf.matmul(logitsToHidden2, weightsToOutput) + biasesToOutput validLogitsToOutput = tf.matmul(validLogitsToHidden2, weightsToOutput) + biasesToOutput testLogitsToOutput = tf.matmul(testLogitsToHidden2, weightsToOutput) + biasesToOutput loss = (tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logitsToOutput, tf_train_labels))) #+ # tf.nn.l2_loss(weightsToHidden1) * 0.002 + #tf.nn.l2_loss(weightsToHidden2) * 0.002 + #tf.nn.l2_loss(weightsToOutput) * 0.002) # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logitsToOutput) valid_prediction = tf.nn.softmax(validLogitsToOutput) test_prediction = tf.nn.softmax(testLogitsToOutput) </code></pre>
0
2016-08-29T23:40:09Z
39,684,928
<p>Change your learning rate to 0.01 or even smaller value. It helps but in my case accuracy is still worse than with two layers perceptron</p>
0
2016-09-25T08:40:14Z
[ "python", "python-2.7", "neural-network", "tensorflow", "perceptron" ]
Regex matches only one string. Need it to match two
39,216,777
<p>I have the following regex</p> <pre><code>^(.+?)(\s+engine$|\s+ROW_FORMAT) </code></pre> <p>with ignore case enabled.</p> <p>The problem with this is, it matches either "engine" or "row_format" and doesn't match both (as shown in the <a href="https://regex101.com/r/qC3tB7/3" rel="nofollow">last example</a>). What am I missing here?</p> <pre><code>In [17]: st = 'this is my engine and row_format' In [18]: match = re.match('^(.+?)(\s+engine$|\s+ROW_FORMAT)', st, re.I) In [19]: match Out[19]: &lt;_sre.SRE_Match at 0x26c5030&gt; In [20]: match.group(1) Out[20]: 'this is my' In [21]: st = 'this is my row_format and engine' In [22]: match = re.match('^(.+?)(\s+engine$|\s+ROW_FORMAT)', st, re.I) In [23]: match.group(1) Out[23]: 'this is my' In [24]: match.group(2) Out[24]: ' row_format' In [25]: match.group(3) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-25-da7df187e689&gt; in &lt;module&gt;() ----&gt; 1 match.group(3) IndexError: no such group </code></pre>
0
2016-08-29T23:40:41Z
39,216,917
<p>add the special character <code>+</code>; this <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">causes the resulting RE to match 1 or more repetitions of the preceding RE</a></p> <pre><code>^(.+?)(\s+engine$|\s+ROW_FORMAT)+ </code></pre>
3
2016-08-29T23:58:13Z
[ "python", "regex" ]
Exercism Python Bob
39,216,804
<p>I'm learning Python through Exercism.IO, I'm currently on the <code>Bob</code> problem where the object of the problem is as follows:</p> <blockquote> <p>Bob is a lackadaisical teenager. In conversation, his responses are very limited. Bob answers 'Sure.' if you ask him a question. He answers 'Whoa, chill out!' if you yell at him. He says 'Fine. Be that way!' if you address him without actually saying anything. He answers 'Whatever.' to anything else.</p> </blockquote> <p>So far I've passed a few tests and I'm stuck at a point where it's suppose to return <code>whatever</code> but all the characters are integers, so of course it's not working.</p> <p>Here's where I'm failing:</p> <pre><code>def test_only_numbers(self): self.assertEqual( 'Whatever.', bob.hey('1, 2, 3') ) </code></pre> <p>All the characters are integers and my test to see if they're yelling looks like this:</p> <pre><code>def is_yelling(self): return self.sentence == self.sentence.upper() </code></pre> <p>Obviously the characters are the same when upper or lower case because they're numbers so the program thinks they're yelling. My question is how can I refactor this program to make it so that when the assertion is all numbers, it won't count it as yelling?</p> <pre><code>def hey(what): sentence = SentenceThinker(what) if sentence.is_silence(): return "Fine. Be that way!" elif sentence.is_yelling(): return "Whoa, chill out!" elif sentence.is_question(): return "Sure." else: return "Whatever." class SentenceThinker(object): def __init__(self, sentence): self.sentence = sentence def is_yelling(self): return self.sentence == self.sentence.upper() def is_question(self): return self.sentence.endswith("?") def is_silence(self): return not self.sentence </code></pre>
2
2016-08-29T23:44:19Z
39,217,223
<p>consider using the built-in String method <a href="https://docs.python.org/3/library/stdtypes.html#str.isupper" rel="nofollow"><code>str.isupper()</code></a></p>
3
2016-08-30T00:41:25Z
[ "python" ]
Receive and Parse Emails on AWS SES
39,216,839
<p>I want to setup a Lambda function to parse incoming emails to SES. I followed the documentation and setup the receipt rules. </p> <p>I tested out my script by storing a MIME email in a txt file, parsing the email, and storing required info in a JSON document to be stored in a database. Now, I'm unsure of how to access the received email from SES and pull the information into my Python script. Any help would be greatly appreciated. </p> <pre><code>from email.parser import Parser parser = Parser() f = open('roundtripMime.txt', "r") rawText = f.read() incoming = Parser().parsestr(rawText) subject = incoming subjectList = subject.split("|") #Get number NumberList = subjectList[0].split() Number = NumberList[2].strip("()") #Get Name fullNameList = subjectList[3].split("/") firstName = fullNameList[1].strip() lastName = fullNameList[0].strip() </code></pre>
0
2016-08-29T23:48:28Z
39,217,238
<p>See <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email.html" rel="nofollow">Amazon Simple Email Service document</a></p> <p>Actually, there is a better way; using <a href="http://boto3.readthedocs.io/en/latest/guide/sqs.html#processing-messages" rel="nofollow">boto3</a>, you can send email and process messages easily.</p> <pre><code># Get the service resource sqs = boto3.resource('sqs') # Get the queue queue = sqs.get_queue_by_name(QueueName='test') # Process messages by printing out body and optional author name for message in queue.receive_messages(MessageAttributeNames=['Author']): # Get the custom author message attribute if it was set author_text = '' if message.message_attributes is not None: author_name = message.message_attributes.get('Author').get('StringValue') if author_name: author_text = ' ({0})'.format(author_name) # Print out the body and author (if set) print('Hello, {0}!{1}'.format(message.body, author_text)) # Let the queue know that the message is processed message.delete() </code></pre>
0
2016-08-30T00:44:11Z
[ "python", "aws-lambda", "amazon-ses" ]
Receive and Parse Emails on AWS SES
39,216,839
<p>I want to setup a Lambda function to parse incoming emails to SES. I followed the documentation and setup the receipt rules. </p> <p>I tested out my script by storing a MIME email in a txt file, parsing the email, and storing required info in a JSON document to be stored in a database. Now, I'm unsure of how to access the received email from SES and pull the information into my Python script. Any help would be greatly appreciated. </p> <pre><code>from email.parser import Parser parser = Parser() f = open('roundtripMime.txt', "r") rawText = f.read() incoming = Parser().parsestr(rawText) subject = incoming subjectList = subject.split("|") #Get number NumberList = subjectList[0].split() Number = NumberList[2].strip("()") #Get Name fullNameList = subjectList[3].split("/") firstName = fullNameList[1].strip() lastName = fullNameList[0].strip() </code></pre>
0
2016-08-29T23:48:28Z
39,332,587
<p>You can set up an Action in your SES Rules Set to automatically PUT your email files into S3. Then you set up an event in S3 (for a specific bucket) to trigger your lambda function. With that, you will be able to retrieve the email with something like this:</p> <pre><code>def lambda_handler(event, context): for record in event['Records']: key = record['s3']['object']['key'] bucket = record['s3']['bucket']['name'] # here you can download the file from s3 with bucket and key </code></pre>
0
2016-09-05T14:18:49Z
[ "python", "aws-lambda", "amazon-ses" ]
How to plot PCA `loadings` and `loading.label` like R's `autoplot` w/ `matplotlib` and `sklearn`?
39,216,897
<p>I saw this tutorial in <code>R</code> w/ <code>autoplot</code>. They plotted the loadings and loading labels:</p> <pre><code>autoplot(prcomp(df), data = iris, colour = 'Species', loadings = TRUE, loadings.colour = 'blue', loadings.label = TRUE, loadings.label.size = 3) </code></pre> <p><a href="http://i.stack.imgur.com/QRuAn.png" rel="nofollow"><img src="http://i.stack.imgur.com/QRuAn.png" alt="enter image description here"></a> <a href="https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_pca.html" rel="nofollow">https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_pca.html</a></p> <p>I prefer <code>Python 3</code> w/ <code>matplotlib, scikit-learn, and pandas</code> for my data analysis. However, I don't know how to add these on? </p> <p><strong>How can you plot these vectors w/ <code>matplotlib</code>?</strong> </p> <p>I've been reading <a href="http://stackoverflow.com/questions/22984335/recovering-features-names-of-explained-variance-ration-in-pca-with-sklearn">Recovering features names of explained_variance_ration in PCA with sklearn</a> but haven't figured it out yet</p> <p>Here's how I plot it in <code>Python</code></p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn import decomposition import seaborn as sns; sns.set_style("whitegrid", {'axes.grid' : False}) %matplotlib inline np.random.seed(0) # Iris dataset DF_data = pd.DataFrame(load_iris().data, index = ["iris_%d" % i for i in range(load_iris().data.shape[0])], columns = load_iris().feature_names) Se_targets = pd.Series(load_iris().target, index = ["iris_%d" % i for i in range(load_iris().data.shape[0])], name = "Species") # Scaling mean = 0, var = 1 DF_standard = pd.DataFrame(StandardScaler().fit_transform(DF_data), index = DF_data.index, columns = DF_data.columns) # Sklearn for Principal Componenet Analysis # Dims m = DF_standard.shape[1] K = 2 # PCA (How I tend to set it up) Mod_PCA = decomposition.PCA(n_components=m) DF_PCA = pd.DataFrame(Mod_PCA.fit_transform(DF_standard), columns=["PC%d" % k for k in range(1,m + 1)]).iloc[:,:K] # Color classes color_list = [{0:"r",1:"g",2:"b"}[x] for x in Se_targets] fig, ax = plt.subplots() ax.scatter(x=DF_PCA["PC1"], y=DF_PCA["PC2"], color=color_list) </code></pre> <p><a href="http://i.stack.imgur.com/9dO1P.png" rel="nofollow"><img src="http://i.stack.imgur.com/9dO1P.png" alt="enter image description here"></a></p>
2
2016-08-29T23:55:31Z
39,234,799
<p>I found the answer here by @teddyroland: <a href="https://github.com/teddyroland/python-biplot/blob/master/biplot.py" rel="nofollow">https://github.com/teddyroland/python-biplot/blob/master/biplot.py</a></p>
1
2016-08-30T18:36:20Z
[ "python", "matplotlib", "plot", "ggplot2", "pca" ]
/Library/Python/2.7/site-packages directory empty
39,216,936
<p>When I cd into the /Library/Python/2.7/site-packages directory, there is only a README file. Where are all the third-party modules I installed such as sklearn?</p>
0
2016-08-30T00:01:01Z
39,216,969
<p>Probably you installed the packages for a different version of python, or you installed them locally (in your home dir, not system-wide).</p> <p>Inside a Python shell, type this:</p> <pre><code>import sklearn print (sklearn.__file__) </code></pre> <p>That will tell you where the package is located.</p>
1
2016-08-30T00:05:56Z
[ "python" ]
string to base64 bytes, exactly with the same literal chars
39,216,947
<p>today I got stucked with the following issue. I can explain it better with the inverse purpose: Say we have the following base64-variable,</p> <pre><code>b64_var = b'aGVsbG8gd29ybGQ=' </code></pre> <p>Imagine that what we want it's not to decode it into string object of python, namely,</p> <pre><code>base64.b64decode(b64_var).decode('utf-8') &gt;&gt;&gt; 'hello world' </code></pre> <p>but the literal equivalent characters in string instead,</p> <pre><code>repr( b64_var )[1:] &gt;&gt;&gt; 'aGVsbG8gd29ybGQ=' </code></pre> <p>Ok, now it's my question. I want to build a function that performs just the opposite,</p> <pre><code>'aGVsbG8gd29ybGQ=' -&gt; b'aGVsbG8gd29ybGQ=' (base64-obj) ??? </code></pre> <p>I got stucked, I don't know how to do it.. Any suggestion? Thank you in advance.</p>
0
2016-08-30T00:02:13Z
39,217,360
<p>Is this doing what you want?</p> <pre><code>b64_var = b'aGVsbG8gd29ybGQ=' print(repr(b64_var)) # b'aGVsbG8gd29ybGQ=' print(repr(b64_var)[1:]) # 'aGVsbG8gd29ybGQ=' print('b' + repr(b64_var)[1:]) # b'aGVsbG8gd29ybGQ=' </code></pre>
0
2016-08-30T01:06:48Z
[ "python", "string", "python-3.x", "base64", "literals" ]
string to base64 bytes, exactly with the same literal chars
39,216,947
<p>today I got stucked with the following issue. I can explain it better with the inverse purpose: Say we have the following base64-variable,</p> <pre><code>b64_var = b'aGVsbG8gd29ybGQ=' </code></pre> <p>Imagine that what we want it's not to decode it into string object of python, namely,</p> <pre><code>base64.b64decode(b64_var).decode('utf-8') &gt;&gt;&gt; 'hello world' </code></pre> <p>but the literal equivalent characters in string instead,</p> <pre><code>repr( b64_var )[1:] &gt;&gt;&gt; 'aGVsbG8gd29ybGQ=' </code></pre> <p>Ok, now it's my question. I want to build a function that performs just the opposite,</p> <pre><code>'aGVsbG8gd29ybGQ=' -&gt; b'aGVsbG8gd29ybGQ=' (base64-obj) ??? </code></pre> <p>I got stucked, I don't know how to do it.. Any suggestion? Thank you in advance.</p>
0
2016-08-30T00:02:13Z
39,225,738
<p>Ok, I found the problem, it was easier as I expected.</p> <p>First I am going to try to clarify what actually I wanted to do,</p> <pre><code>str_var = 'aGVsbG8gd29ybGQ=' # str_var: string b64_var = fun_str_2_b64samechars(str_var) # b64_var: bytes (b64) </code></pre> <p>Console,</p> <pre><code>b64_var &gt;&gt;&gt;b'aGVsbG8gd29ybGQ=' </code></pre> <p>My goal was to guess how to build that <code>fun_str_2_b64samechars</code> function. And here it is exactly <code>bytes(str_var,'utf-8')</code>,</p> <pre><code>bytes('aGVsbG8gd29ybGQ=','utf-8') &gt;&gt;&gt;b'aGVsbG8gd29ybGQ=' </code></pre> <p>Probably it was because I thought it was some kind of base64 class as long as I employed the base64 module (due to this I edited the title). Thanks for the help and I hope it could be useful for someone :)</p>
0
2016-08-30T11:01:55Z
[ "python", "string", "python-3.x", "base64", "literals" ]
Module has not attrbiute many2one - Odoo v9 community
39,217,019
<p>I'm adding a field to a model froma custom module in Odoov9 Community edition.</p> <p>Like this:</p> <pre><code>import logging from openerp import api, fields, models, _ from openerp.exceptions import UserError, ValidationError from openerp.tools.safe_eval import safe_eval as eval class refund(models.Model): """Inherits account.invoice.refund and adds journal_id field""" _name = "account.invoice.refund" _inherit = "account.invoice.refund" _columns = { 'journal_id': fields.many2one('account.journal', 'Refund Journal', help='You can select here the journal to use for the credit note that will be created. If you leave that field empty, it will use the same journal as the current invoice.'), } </code></pre> <p>But when server loads, it throws me this error:</p> <pre><code>2016-08-30 00:04:41,807 12893 CRITICAL odoov9_ openerp.modules.module: Couldn't load module debit_credit_note 2016-08-30 00:04:41,807 12893 CRITICAL odoov9_ openerp.modules.module: 'module' object has no attribute 'many2one' 2016-08-30 00:04:41,808 12893 ERROR odoov9_ openerp.modules.registry: Failed to load registry Traceback (most recent call last): File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/registry.py", line 386, in new openerp.modules.load_modules(registry._db, force_demo, status, update_module) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/loading.py", line 334, in load_modules force, status, report, loaded_modules, update_module) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/loading.py", line 237, in load_marked_modules loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/loading.py", line 123, in load_module_graph load_openerp_module(package.name) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/module.py", line 324, in load_openerp_module __import__('openerp.addons.' + module_name) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/modules/module.py", line 61, in load_module mod = imp.load_module('openerp.addons.' + module_part, f, path, descr) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/debit_credit_note/__init__.py", line 31, in &lt;module&gt; import models File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/debit_credit_note/models/__init__.py", line 1, in &lt;module&gt; import debit_credit File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/debit_credit_note/models/debit_credit.py", line 27, in &lt;module&gt; class refund(models.Model): File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/debit_credit_note/models/debit_credit.py", line 36, in refund 'journal_id': fields.many2one('account.journal', 'Refund Journal', help='You can select here the journal to use for the credit note that will be created. If you leave that field empty, it will use the same journal as the current invoice.'), AttributeError: 'module' object has no attribute 'many2one' </code></pre> <p>Anybody can shed light on this?</p> <p>I'm very confused at this, never had this error before.</p>
1
2016-08-30T00:13:01Z
39,219,459
<p>If you are inheriting from an already defined module, you don't need to define the <code>_name</code> variable, just defining the <code>_inherit</code> variable will work too.</p> <p>You were getting the error "Module has not attrbiute many2one", as you were importing the <code>fields</code> for the new api but defining it the old api way. The maximum recursion error should also get solved if you write the code in the new api.</p> <p>If you are writing this module for Odoo 9, it would be a good idea to write it in the new api. Below is your code written with the new api:</p> <pre><code>import logging from openerp import api, fields, models, _ from openerp.exceptions import UserError, ValidationError from openerp.tools.safe_eval import safe_eval as eval class refund(models.Model): _inherit = "account.invoice.refund" journal_id = fields.Many2one('account.journal', string='Refund Journal', help='You can select here the journal to use for the credit note that will be created. If you leave that field empty, it will use the same journal as the current invoice.') </code></pre> <p>The above piece of code should work without any problems. </p>
2
2016-08-30T05:37:26Z
[ "python", "openerp", "odoo-9" ]
How can I tell in my django view, which of the 2 forms' fields were filled?
39,217,044
<p>I want to display both <code>form1</code> and <code>form2</code> on a web page. If <code>form2</code> is filled (<code>if success == True</code>), I want my view to not execute <code>if form1.is_valid:</code></p> <p>(which gives errors). How can I access the value of <code>success</code> in views.py?</p> <p>forms.py</p> <pre><code>class Form1(forms.Form): .... .... def clean(self): .... .... class Form2(forms.Form): .... .... def clean(self): .... success = False </code></pre> <p>views.py</p> <pre><code>def my_view(request, element_pk): .... .... if request.method == POST: form2 = Form2(request.POST) form1 = Form1(request.POST) if form2.is_valid(): .... if form1.is_valid(): .... else: form2 = Form2() form1 = Form1() </code></pre>
0
2016-08-30T00:16:56Z
39,217,094
<p>For your <code>&lt;input /&gt;</code> or <code>&lt;button&gt;&lt;/button&gt;</code> tag, use a <code>name</code> parameter for each form (i.e.):</p> <pre><code>&lt;button type="submit" name="form_1"&gt;Go!&lt;/button&gt; </code></pre> <p>Then, in your view, do something like:</p> <pre><code>if form2.is_valid() and 'form_2' in request.POST: . . . if form1.is_valid() and 'form_1' in request.POST: . . . </code></pre>
0
2016-08-30T00:23:54Z
[ "python", "django", "django-forms", "django-views" ]
How can I tell in my django view, which of the 2 forms' fields were filled?
39,217,044
<p>I want to display both <code>form1</code> and <code>form2</code> on a web page. If <code>form2</code> is filled (<code>if success == True</code>), I want my view to not execute <code>if form1.is_valid:</code></p> <p>(which gives errors). How can I access the value of <code>success</code> in views.py?</p> <p>forms.py</p> <pre><code>class Form1(forms.Form): .... .... def clean(self): .... .... class Form2(forms.Form): .... .... def clean(self): .... success = False </code></pre> <p>views.py</p> <pre><code>def my_view(request, element_pk): .... .... if request.method == POST: form2 = Form2(request.POST) form1 = Form1(request.POST) if form2.is_valid(): .... if form1.is_valid(): .... else: form2 = Form2() form1 = Form1() </code></pre>
0
2016-08-30T00:16:56Z
39,222,503
<p>Setting <code>success = False</code> as you've done in the clean method only sets it locally. Store the value on the class (<code>self.success = False</code>) or in the cleaned_data (<code>self.cleaned_data['success'] = False</code>, assuming your form has no field called success).</p> <p>Then, you can access the value with:</p> <pre><code>if form2.is_valid(): success = form2.success </code></pre> <p>or</p> <pre><code>if form2.is_valid(): success = form2.cleaned_data.get('success') </code></pre> <p>For more information about the <code>clean</code> function, see the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other" rel="nofollow">docs</a>.</p>
0
2016-08-30T08:32:52Z
[ "python", "django", "django-forms", "django-views" ]
Finding the length of the longest repeating 1s in a string
39,217,188
<p>I was wondering how one can find the length of the longest repeating 1s in a string of 1s and 0s in python, taking into account the empty string. like<code>'1011110111111'</code> would return <code>6</code> and <code>''</code> would return <code>0</code>.</p> <p>A past post suggested using regex,</p> <p><code>max([len(i) for i in re.compile('(1+1)').findall(count)])</code></p> <p>but it doesn't count the case for one single 1 and the empty string.</p>
-1
2016-08-30T00:37:09Z
39,217,253
<p>Just split the string using '0' as separator and find the longest item in the list:</p> <pre><code>s = '1011110111111' result = len(max(s.split('0'))) </code></pre>
6
2016-08-30T00:47:47Z
[ "python" ]
How to colorize Django test results in OSX terminal?
39,217,201
<p>I'd like to colorize the Django test outputs with the nice visual queues of "green=pass, red=failure" font colors in the terminal, similar to what I get with rails/rake (e.g. ....F..FF.... where F is red for failure and the dots are green for passing unit tests). Anyone know how to do this easily? Is there a bash_profile or python import or setting? </p>
0
2016-08-30T00:38:22Z
39,222,952
<p>Django has it <a href="https://docs.djangoproject.com/en/dev/ref/django-admin/#syntax-coloring" rel="nofollow">built-in</a>.</p> <p>The colors used for syntax highlighting can be customized. Django ships with three color palettes:</p> <ul> <li>dark, suited to terminals that show white text on a black background. This is the default palette.</li> <li>light, suited to terminals that show black text on a white background.</li> <li>nocolor, which disables syntax highlighting.</li> </ul> <p>You select a palette by setting a DJANGO_COLORS environment variable to specify the palette you want to use. For example, to specify the light palette under a Unix or OS/X BASH shell, you would run the following at a command prompt:</p> <pre><code>export DJANGO_COLORS="light" </code></pre> <p>There's also <a href="https://github.com/tiliv/django-colors-formatter" rel="nofollow">django-colors-formatter</a> package if you wish more customization:</p> <pre><code>LOGGING = { 'formatters': { 'colored': { '()': 'djangocolors_formatter.DjangoColorsFormatter', 'format': '%(levelname)s %(module)s %(message)s', }, }, 'handlers': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'colored', }, 'loggers': 'myproject': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } </code></pre>
0
2016-08-30T08:56:47Z
[ "python", "django", "osx", "terminal" ]
Python telnetlib.expect() dot character '.' not working as expected
39,217,235
<p>I am trying to automate generic telnet connections. I am relying heavily on REGEX to handle different login prompts. Currently, I am using the regex <code>[Ll]ogin</code>, but the prompt causing me problems is the standard Ubuntu prompt:</p> <pre><code>b-davis login: Password: Last login: Mon Aug 29 20:28:24 EDT 2016 from localhost on pts/5 </code></pre> <p>Because the word login is mentioned twice. Now the regex <code>[Ll]ogin.{0,3}$</code> I thought should solve this, but it stopped matching all together. I tried something simpler, <code>[Ll]ogin.</code> which should produce the same results as <code>[Ll]ogin</code> but it doesn't!</p> <p>I am using bytestrings because python throws a <code>TypeError</code> if I don't. I feel the problem lies somewhere not regex related, so here is the entire piece of code:</p> <pre><code>import telnetlib import re pw = "p@ssw0rd" user = "bdavis" regex = [ b"[Ll]ogin.", # b"[Ll]ogin" works here b"[Pp]assword", b'&gt;', b'#'] tn = telnetlib.Telnet("1.2.3.4") while type(tn.get_socket()) is not int: result = tn.expect(regex, 5) # Retrieve send information s = result[2].decode() if re.search("[Ll]ogin$",s) is not None: print("Do login stuff") print(result) tn.write((user + "\n").encode()) # Send Username elif re.search("[Pp]assword",s) is not None: print("Do password stuff") tn.write((pw + "\n").encode()) # Send Password elif re.search('&gt;',s) is not None: print("Do Cisco User Stuff") tn.write(b"exit\n") # exit telnet tn.close() elif re.search('#',s) is not None: print("Do Cisco Admin Stuff") else: print("I Don't understand this, help me:") print(s) tn.close() </code></pre>
0
2016-08-30T00:44:00Z
39,217,353
<p>I think the following line:</p> <pre><code>if re.search("[Ll]ogin$",s) is not None: </code></pre> <p>should be replaced with:</p> <pre><code>if re.search("[Ll]ogin", s) is not None: # NOTE: No `$` </code></pre> <p>OR using simple string operations:</p> <pre><code>if 'login' in s.lower(): </code></pre> <p>because the matched part will not ends with <code>ogin</code> because of <code>:</code>.</p>
0
2016-08-30T01:05:44Z
[ "python", "regex", "telnet", "telnetlib" ]
No conversion for undefined on selection field - Odoo v9 community
39,217,313
<p>I have a selection field on a module for Odoov9 Community</p> <p>But, everytime, I click on it, to select a record it throws me this error:</p> <pre><code>Error: No conversion for undefined http://localhost:8070/web/static/src/js/framework/pyeval.js:732 Traceback: wrap@http://localhost:8070/web/static/src/js/framework/pyeval.js:732:29 wrapping_list&lt;.__getitem__@http://localhost:8070/web/static/src/js/framework/pyeval.js:787:16 py.PY_getItem@http://localhost:8070/web/static/lib/py.js/lib/py.js:610:19 py.evaluate@http://localhost:8070/web/static/lib/py.js/lib/py.js:1403:24 py.evaluate@http://localhost:8070/web/static/lib/py.js/lib/py.js:1404:21 py.evaluate@http://localhost:8070/web/static/lib/py.js/lib/py.js:1397:35 py.evaluate@http://localhost:8070/web/static/lib/py.js/lib/py.js:1409:34 py.eval@http://localhost:8070/web/static/lib/py.js/lib/py.js:1453:16 eval_domains/&lt;@http://localhost:8070/web/static/src/js/framework/pyeval.js:862:32 _.forEach@http://localhost:8070/web/static/lib/underscore/underscore.js:145:9 _.mixin/&lt;/_.prototype[name]@http://localhost:8070/web/static/lib/underscore/underscore.js:1484:29 eval_domains@http://localhost:8070/web/static/src/js/framework/pyeval.js:853:5 eval_domains/&lt;@http://localhost:8070/web/static/src/js/framework/pyeval.js:867:32 _.forEach@http://localhost:8070/web/static/lib/underscore/underscore.js:145:9 _.mixin/&lt;/_.prototype[name]@http://localhost:8070/web/static/lib/underscore/underscore.js:1484:29 eval_domains@http://localhost:8070/web/static/src/js/framework/pyeval.js:853:5 eval_domains/&lt;@http://localhost:8070/web/static/src/js/framework/pyeval.js:867:32 _.forEach@http://localhost:8070/web/static/lib/underscore/underscore.js:145:9 _.mixin/&lt;/_.prototype[name]@http://localhost:8070/web/static/lib/underscore/underscore.js:1484:29 eval_domains@http://localhost:8070/web/static/src/js/framework/pyeval.js:853:5 pyeval@http://localhost:8070/web/static/src/js/framework/pyeval.js:946:16 eval_arg@http://localhost:8070/web/static/src/js/framework/pyeval.js:957:16 ensure_evaluated@http://localhost:8070/web/static/src/js/framework/pyeval.js:980:21 .call@http://localhost:8070/web/static/src/js/framework/data_model.js:56:9 DataSet&lt;.name_search@http://localhost:8070/web/static/src/js/framework/data.js:537:16 CompletionFieldMixin.get_search_result@http://localhost:8070/web/static/src/js/views/form_common.js:192:33 FieldMany2One&lt;.render_editable/&lt;.source@http://localhost:8070/web/static/src/js/views/form_relational_widgets.js:271:17 ._search@http://localhost:8070/web/static/lib/jquery.ui/jquery-ui.js:7404:3 $.widget/&lt;/proxiedPrototype[prop]&lt;/&lt;@http://localhost:8070/web/static/lib/jquery.ui/jquery-ui.js:415:19 .search@http://localhost:8070/web/static/lib/jquery.ui/jquery-ui.js:7396:10 $.widget/&lt;/proxiedPrototype[prop]&lt;/&lt;@http://localhost:8070/web/static/lib/jquery.ui/jquery-ui.js:415:19 $.widget.bridge/$.fn[name]/&lt;@http://localhost:8070/web/static/lib/jquery.ui/jquery-ui.js:513:19 .each@http://localhost:8070/web/static/lib/jquery/jquery.js:383:49 jQuery.prototype.each@http://localhost:8070/web/static/lib/jquery/jquery.js:136:24 $.widget.bridge/$.fn[name]@http://localhost:8070/web/static/lib/jquery.ui/jquery-ui.js:499:4 FieldMany2One&lt;.render_editable/&lt;@http://localhost:8070/web/static/src/js/views/form_relational_widgets.js:189:21 jQuery.event.dispatch@http://localhost:8070/web/static/lib/jquery/jquery.js:4640:50 jQuery.event.add/elemData.handle@http://localhost:8070/web/static/lib/jquery/jquery.js:4309:41 </code></pre> <p>I'm not fond on new javascript libraries for Odoo, so, I don't know where to start looking for this, has this happened to anyone before?</p> <p>Thanks in advance!</p> <p><strong>EDIT</strong></p> <p>This is the invoice model code(where I'm calling it from):</p> <pre><code>class account_move_line(models.Model): _inherit = "account.move.line" document_class_id = new_fields.Many2one( 'sii.document_class', 'Document Type', related='move_id.document_class_id', store=True, readonly=True, ) document_number = new_fields.Char( string='Document Number', related='move_id.document_number', store=True, readonly=True, ) class account_journal_sii_document_class(models.Model): _name = "account.journal.sii_document_class" _description = "Journal SII Documents" def name_get(self, cr, uid, ids, context=None): result = [] for record in self.browse(cr, uid, ids, context=context): result.append((record.id, record.sii_document_class_id.name)) return result _order = 'journal_id desc, sequence, id' sii_document_class_id = new_fields.Many2one('sii.document_class', 'Document Type', required=True) sequence_id = new_fields.Many2one( 'ir.sequence', 'Entry Sequence', required=False, help="""This field contains the information related to the numbering \ of the documents entries of this document type.""") journal_id = new_fields.Many2one( 'account.journal', 'Journal', required=True) sequence = new_fields.Integer('Sequence',) </code></pre> <p>The invoice view definitions:</p> <pre><code>&lt;xpath expr="//group[last()]" position="inside"&gt; &lt;filter string="Document Type" icon="terp-folder-orange" domain="[]" context="{'group_by':'sii_document_class_id'}"/&gt; &lt;/xpath&gt; </code></pre> <p>The document_type model itself:</p> <pre><code>class sii_document_class(models.Model): _name = 'sii.document_class' _description = 'SII Document Class' name = fields.Char( 'Name', size=120) doc_code_prefix = fields.Char( 'Document Code Prefix', help="Prefix for Documents Codes on Invoices \ and Account Moves. For eg. 'FAC' will build 'FAC 00001' Document Number") code_template = fields.Char( 'Code Template for Journal') sii_code = fields.Integer( 'SII Code', required=True) document_letter_id = fields.Many2one( 'sii.document_letter', 'Document Letter') report_name = fields.Char( 'Name on Reports', help='Name that will be printed in reports, for example "CREDIT NOTE"') document_type = fields.Selection( [ ('invoice', 'Invoices'), ('invoice_in', 'Purchase Invoices'), ('debit_note', 'Debit Notes'), ('credit_note', 'Credit Notes'), ('other_document', 'Other Documents') ], string='Document Type', help='It defines some behaviours on automatic journal selection and\ in menus where it is shown.') active = fields.Boolean( 'Active', default=True) dte = fields.Boolean( 'DTE', required=True) </code></pre> <p><strong>SECOND EDIT</strong></p> <p>This is the actual field in the form view which is giving me the error, everytime I click to select one document:</p> <pre><code> &lt;h6 style="color:red;text-align:center;text-transform:uppercase;font-weight:900"&gt; &lt;span t-field="o.journal_document_class_id.sii_document_class_id.name"/&gt; &lt;/h6&gt; </code></pre>
0
2016-08-30T00:56:55Z
39,336,832
<ol> <li><p>You can't use QWeb for normal view definitions (formular, tree, search, etc.).</p></li> <li><p>You can't use dot-notation on normal view field definitions.</p></li> </ol> <p>So first off create a related <code>Char</code> field on the model your view is for. Then just define a simple field in the view.</p> <p>Example (close to your code above):</p> <pre class="lang-py prettyprint-override"><code>class my_model(models.Model): _name = 'my.model' journal_document_class_id = fields.Many2one( comodel_name="journal.document.class", string="Journal Doc Class") # related field sii_document_name = fields.Char( string="Sii Document Name", related="journal_document_class_id.sii_document_class_id.name") </code></pre> <pre class="lang-xml prettyprint-override"><code>&lt;h6 style="color:red;text-align:center;text-transform:uppercase;font-weight:900"&gt; &lt;field name="sii_document_name"/&gt; &lt;/h6&gt; </code></pre>
1
2016-09-05T19:47:46Z
[ "javascript", "python", "openerp", "odoo-9" ]
how to split 'number' to separate columns in pandas DataFrame
39,217,347
<p>I have a dataframe;</p> <pre><code>df=pd.DataFrame({'col1':[100000,100001,100002,100003,100004]}) col1 0 100000 1 100001 2 100002 3 100003 4 100004 </code></pre> <p>I wish I could get the result below;</p> <pre><code> col1 col2 col3 0 10 00 00 1 10 00 01 2 10 00 02 3 10 00 03 4 10 00 04 </code></pre> <p>each rows show the splitted number. I guess the number should be converted to string, but I have no idea next step.... I wanna ask how to split number to separate columns.</p>
1
2016-08-30T01:04:52Z
39,217,425
<pre><code># make string version of original column, call it 'col' df['col'] = df['col1'].astype(str) # make the new columns using string indexing df['col1'] = df['col'].str[0:2] df['col2'] = df['col'].str[2:4] df['col3'] = df['col'].str[4:6] # get rid of the extra variable (if you want) df.drop('col', axis=1, inplace=True) </code></pre>
1
2016-08-30T01:15:52Z
[ "python", "pandas", "numpy", "dataframe", "split" ]
how to split 'number' to separate columns in pandas DataFrame
39,217,347
<p>I have a dataframe;</p> <pre><code>df=pd.DataFrame({'col1':[100000,100001,100002,100003,100004]}) col1 0 100000 1 100001 2 100002 3 100003 4 100004 </code></pre> <p>I wish I could get the result below;</p> <pre><code> col1 col2 col3 0 10 00 00 1 10 00 01 2 10 00 02 3 10 00 03 4 10 00 04 </code></pre> <p>each rows show the splitted number. I guess the number should be converted to string, but I have no idea next step.... I wanna ask how to split number to separate columns.</p>
1
2016-08-30T01:04:52Z
39,217,444
<p>One option is to use <code>extractall()</code> method with regex <code>(\d{2})(\d{2})(\d{2})</code> which captures every other two digits as columns. <code>?P&lt;col1&gt;</code> is the name of the captured group which will be converted to the column names:</p> <pre><code>df.col1.astype(str).str.extractall("(?P&lt;col1&gt;\d{2})(?P&lt;col2&gt;\d{2})(?P&lt;col3&gt;\d{2})").reset_index(drop=True) # col1 col2 col3 # 0 10 00 00 # 1 10 00 01 # 2 10 00 02 # 3 10 00 03 # 4 10 00 04 </code></pre>
2
2016-08-30T01:18:59Z
[ "python", "pandas", "numpy", "dataframe", "split" ]
Secret key is there though it is saying no secret key in django
39,217,362
<p>When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 14, in &lt;module&gt; from django.db.migrations.executor import MigrationExecutor File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 6, in &lt;module&gt; from .loader import MigrationLoader File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 10, in &lt;module&gt; from django.db.migrations.recorder import MigrationRecorder File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 9, in &lt;module&gt; class MigrationRecorder(object): File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 23, in MigrationRecorder class Migration(models.Model): File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 24, in Migration app = models.CharField(max_length=255) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1081, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 113, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. </code></pre> <p>This is my development settings</p> <pre><code>""" Django settings for kgecweb project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'my_secret key here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'administration', 'stdimage', 'dept', 'trplc', # Training and Placement app 'faculty', 'student', 'hostels', 'nkn', 'clibrary', 'page', 'contact' ) MIDDLEWARE_CLASSES = ( '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', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'kgecweb.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '../templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'kgecweb.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.mysql'), 'USER': 'root', 'PASSWORD': '713331', 'HOST': '192.168.33.19', 'PORT': '3306', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATICFILES_DIRS = (os.path.join(BASE_DIR, "../static"),) #STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, '../media') MEDIA_URL = '/media/' </code></pre> <p>I also have made the sql command for initializing database and secret key is also not empty here. Though it keep on saying. i don't know how to tackle this. This is my project directory <a href="http://i.stack.imgur.com/iJvj0.png" rel="nofollow"><img src="http://i.stack.imgur.com/iJvj0.png" alt="enter image description here"></a></p> <p>I even tried making a settings.py file then also this error is coming.</p>
0
2016-08-30T01:07:04Z
39,217,496
<p>Then try:</p> <pre><code>python manage.py runserver --settings=kgecweb.settings.development </code></pre> <p>I guess your didn't use the build-in setting.py or you rename it or make a directory to handle different settings.py.</p> <h3>EDIT</h3> <ul> <li><p>Make sure your project in your python path, use this to find out.</p> <pre><code>import sys print(sys.path) </code></pre></li> <li><p>or you can just create a settings.py in kgecweb(the app) then run</p> <pre><code>python manage.py runserver </code></pre></li> <li><p>if it works, you just try:</p> <pre><code>python manage.py runserver --settings=kgecweb.settings.development </code></pre></li> </ul>
1
2016-08-30T01:25:21Z
[ "python", "django" ]