title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to understand this doc
37,501,828
<p>This is from <a href="https://docs.python.org/2/reference/datamodel.html#slots" rel="nofollow">the Python docs</a>. I don't understand this, can someone give some examples?</p> <blockquote> <p>If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inacces...
-5
2016-05-28T17:19:26Z
37,502,080
<blockquote> <p>When I run the program below it prints 1, so the variable is not inaccessible.</p> </blockquote> <p>You actually have <em>two</em> <code>a</code> instance variables here. The one defined by <code>Base</code> is not accessible through attribute access; for an object of type <code>Subclass</code>, all ...
2
2016-05-28T17:45:46Z
[ "python", "slot" ]
Grouping of all possible combinations of points taken m at a time into r groups
37,501,900
<p>I want to group all possible combinations of points taken <strong>m</strong> at a time into <strong>r</strong> groups.</p> <blockquote> <p>Points = [A,B,C,D........] Total <strong>n</strong> points</p> </blockquote> <p>Combinations of these points taken <strong>m</strong> at a time will be a list <strong>l</stro...
4
2016-05-28T17:27:57Z
37,502,656
<p>This is a tough problem! I've implemented a naive brute force solution. This is probably too slow but it's a starting point.</p> <pre><code>from itertools import combinations, permutations points = 'ABCDEF' r = 3 m = len(points) // r all_combinations = list(combinations(points, m)) group_length = len(all_combinati...
1
2016-05-28T18:44:56Z
[ "python", "algorithm", "logic" ]
Im getting an error in the shell whenever enter is pressed when I'm changing the board size
37,501,923
<p>Have a look at ChangeBoardSize() It'll be part of the while loop that I have to change but I'm not sure what to change or what to change it to. I would appreciate any help for this to be done in anyway. Ignore this but now because I am just trying to get the character count up so that I can post this.</p> <pre><cod...
-1
2016-05-28T17:30:49Z
37,502,035
<p>There is a problem because you don't handle entering characters other than numbers so it fails on line 39</p> <pre><code>return int(Coordinates) # if Coordinates is not str convertable to int it fails </code></pre> <p>So you need to do something like</p> <pre><code>def GetHumanPlayerMove(PlayerName): print(Pl...
1
2016-05-28T17:41:37Z
[ "python" ]
gdb python module can't find any function of it's own
37,501,966
<p>I compiled&amp;installed gdb(7.1.1) from the source code by doing <code>CC=gcc-6 ./configure --with-python=python3 &amp;&amp; make</code> then <code>sudo make install</code>. Then I invoked gdb from bash as usual. But when I tried to load my python script within gdb by doing <code>source asdf.py</code>, it threw an ...
0
2016-05-28T17:35:41Z
37,504,927
<p>I found that the files needed for gdb is located at gdb/data-directory. So moving all files from to the place where python scripts should be did the trick.</p> <pre><code>sudo cp -R gdb/data-directory/* /usr/share/gdb/ </code></pre>
0
2016-05-29T00:13:57Z
[ "python", "linux", "python-3.x", "gdb", "gdb-python" ]
Download file with Kivy app without locking event loop
37,502,084
<p>Here's a Kivy application that has a button and a progress bar. When the button is pressed, a ZIP file is downloaded from the web and unzipped. The progress bar advances to mark the download's progress.</p> <p>The problem is, the downloading locks the Kivy event loop, freezing the application during the download....
2
2016-05-28T17:46:05Z
37,504,614
<p>First, as @Nykakin suggests, to make the download asynchronous, use <code>kivy.network.urlrequest.UrlRequest</code>:</p> <pre><code>def download_content(self): self.ids["download_button"].disabled = True req = UrlRequest(ZIP_URL, on_progress=self.update_progress, chunk_size=1024, on_suc...
3
2016-05-28T23:17:17Z
[ "python", "kivy" ]
"no module named..." when running this python code
37,502,095
<p>I have no idea what causes this error, this is as simplest as I could get, yet SO gives me hint that my question does not meet their quality standards so I must post this longer intro.</p> <pre><code>#=== # my_script.py import myModule #=== # myModule\__init__.py import sys from my_def import * class MyModule: ...
-4
2016-05-28T17:47:03Z
37,502,137
<p>you can try this:</p> <pre><code>sys.path.append("path_of_script") </code></pre>
1
2016-05-28T17:50:54Z
[ "python", "python-module" ]
"no module named..." when running this python code
37,502,095
<p>I have no idea what causes this error, this is as simplest as I could get, yet SO gives me hint that my question does not meet their quality standards so I must post this longer intro.</p> <pre><code>#=== # my_script.py import myModule #=== # myModule\__init__.py import sys from my_def import * class MyModule: ...
-4
2016-05-28T17:47:03Z
37,502,780
<p>In <code>__init__.py</code>, add a <code>.</code> before <code>my_def</code>. The <code>.</code> means that it should be looking for the file in the same folder as the script itself, rather than relative to <code>my_script.py</code>.</p> <pre><code>from .my_def import * </code></pre>
1
2016-05-28T18:59:04Z
[ "python", "python-module" ]
While Loops Only Iterates Correctly Once
37,502,208
<p>I am working on a python script to brute force deobfuscate malicious Java Script I have been finding in security events. Long story short at one point in the process they are obfuscating the script that redirects to the payload with an XOR. So here is how I am going about this. Python:</p> <pre><code>#!/usr/bin/pyt...
1
2016-05-28T17:57:54Z
37,502,230
<p>you return inside of the while loop, which means it is only going to run once</p> <p>if you move the return outside of the while loop, your code should function</p> <pre><code>def deobBrute(): count = 0 while (count &lt; 101): count = count + 1 return(str(userInput)+str(perl)+str(count)+str(tai...
0
2016-05-28T18:01:12Z
[ "python" ]
While Loops Only Iterates Correctly Once
37,502,208
<p>I am working on a python script to brute force deobfuscate malicious Java Script I have been finding in security events. Long story short at one point in the process they are obfuscating the script that redirects to the payload with an XOR. So here is how I am going about this. Python:</p> <pre><code>#!/usr/bin/pyt...
1
2016-05-28T17:57:54Z
37,502,239
<p>If this is your method (your tabbing is messed up), then the function will return <code>(str(userInput)+str(perl)+str(count)+str(tail))</code> straight away, and the rest of the function will not execute, consider using yield if you want to continue within the method and return more values. As yield returns a genera...
1
2016-05-28T18:02:03Z
[ "python" ]
Error with pycripto and AWS-Lambda
37,502,267
<p>I'm trying to use pycrypto and lambda service, but every time that i run my script lambda service return:</p> <blockquote> <p>Unable to import module 'service': /var/task/Crypto/Cipher/_AES.so: invalid ELF header</p> </blockquote> <p>I don't know why is happen if someone have the same problem, please help me.<...
2
2016-05-28T18:04:19Z
39,710,515
<p>I ran into this same issue, had to build my deployable zip on a Linux VM.</p> <p>As alex-luminul <a href="https://github.com/fugue/credstash/issues/58#issuecomment-224282388" rel="nofollow">comments</a> in this <a href="https://github.com/fugue/credstash/issues/5" rel="nofollow">issue</a>, it may be due to the OSX-...
0
2016-09-26T19:08:05Z
[ "python", "aws-lambda", "pycrypto" ]
Error with pycripto and AWS-Lambda
37,502,267
<p>I'm trying to use pycrypto and lambda service, but every time that i run my script lambda service return:</p> <blockquote> <p>Unable to import module 'service': /var/task/Crypto/Cipher/_AES.so: invalid ELF header</p> </blockquote> <p>I don't know why is happen if someone have the same problem, please help me.<...
2
2016-05-28T18:04:19Z
40,054,994
<p>There are some people who have pre-compiled some python packages for use in AWS Lambda. For example the pip package <a href="https://pypi.python.org/pypi/lambda_packages" rel="nofollow">lambda_packages</a> and a GitHub repository called <a href="https://github.com/Doerge/awslambda-pycrypto" rel="nofollow">awslambda-...
0
2016-10-15T04:36:15Z
[ "python", "aws-lambda", "pycrypto" ]
Use different view in Django if the url contains specific character
37,502,270
<p>I have this view:</p> <pre><code>def url_redirect(request,id): url = get_object_or_404(Url,short_id=id) return HttpResponseRedirect(url.httpurl) </code></pre> <p>and these urls:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(ur'^(?P&lt;id&gt;.*)$', views.url_r...
0
2016-05-28T18:04:37Z
37,502,567
<p>If you want to deal with it in the same view, leave the <code>urls</code> as they are and change the view:</p> <pre><code>def url_redirect(request,id): if id.startswith('!'): id = id[1:] # do whatever you want with id else: url = get_object_or_404(Url,short_id=id) return Http...
1
2016-05-28T18:36:22Z
[ "python", "django", "django-views", "django-urls" ]
Python Pandas: Get index from column value
37,502,298
<p>Very simple question: I have a Pandas dataframe. One of the columns looks like this. </p> <pre><code>Date 2016-04-15 2016-04-14 2016-04-13 2016-04-12 2016-04-11 2016-04-08 </code></pre> <p>How do I get the index of a particular value assuming that values are unique. </p> <p>For example, "2016-04-13" would return...
0
2016-05-28T18:07:43Z
37,502,368
<p>With boolean indexing, you can slice the dataframe to get only the rows where the date equals "2016-04-13" and get the index of the slice:</p> <pre><code>df[df.Date == "2016-04-13"].index Out[37]: Int64Index([2], dtype='int64') </code></pre> <p>With the uniqueness assumption, there will be only one element in that...
1
2016-05-28T18:15:00Z
[ "python", "pandas" ]
Python Pandas: Get index from column value
37,502,298
<p>Very simple question: I have a Pandas dataframe. One of the columns looks like this. </p> <pre><code>Date 2016-04-15 2016-04-14 2016-04-13 2016-04-12 2016-04-11 2016-04-08 </code></pre> <p>How do I get the index of a particular value assuming that values are unique. </p> <p>For example, "2016-04-13" would return...
0
2016-05-28T18:07:43Z
37,502,375
<p>Use <code>df.index.get_loc('2016-04-14')</code> to get the integer location for requested label. This will return <code>1</code> as intital starts from <code>0</code>. So you can add one to get the index value as <code>2</code> </p>
2
2016-05-28T18:15:39Z
[ "python", "pandas" ]
Python Pandas: Get index from column value
37,502,298
<p>Very simple question: I have a Pandas dataframe. One of the columns looks like this. </p> <pre><code>Date 2016-04-15 2016-04-14 2016-04-13 2016-04-12 2016-04-11 2016-04-08 </code></pre> <p>How do I get the index of a particular value assuming that values are unique. </p> <p>For example, "2016-04-13" would return...
0
2016-05-28T18:07:43Z
37,503,440
<p><code>df['Date'].values.tolist().index("2016-04-13")</code> will return 2</p>
0
2016-05-28T20:22:50Z
[ "python", "pandas" ]
trouble trying to show an image from my static folder in a django template
37,502,351
<p>im trying to show an image in my template if the profile haven't any picture. I have this code in my template</p> <pre><code>{% if not profileForm.avatar %} &lt;img src="{% static 'img/empty-profile-picture.png' %}" alt="" /&gt; {% endif %} </code></pre> <p>and i obtain that error</p> <pre><code>Template error...
0
2016-05-28T18:13:11Z
37,502,390
<p>You've got a typo - the keyword is <code>static</code>, not <code>satic</code>.</p>
0
2016-05-28T18:16:56Z
[ "python", "django", "django-templates" ]
trouble trying to show an image from my static folder in a django template
37,502,351
<p>im trying to show an image in my template if the profile haven't any picture. I have this code in my template</p> <pre><code>{% if not profileForm.avatar %} &lt;img src="{% static 'img/empty-profile-picture.png' %}" alt="" /&gt; {% endif %} </code></pre> <p>and i obtain that error</p> <pre><code>Template error...
0
2016-05-28T18:13:11Z
37,502,501
<p>I solved the problem by putting the missing <code>{% load staticfiles %}</code> in the beginning of the child template too.</p>
0
2016-05-28T18:29:42Z
[ "python", "django", "django-templates" ]
within a dictionary, how do I remove a value from a key with multiple values? Python
37,502,367
<pre><code>from collections import OrderedDict def main(): dictionary = OrderedDict() dictionary["one"] = ["hello", "blowing"] dictionary["two"] = ["frying", "goodbye"] for key in dictionary: print key, dictionary[key] user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N") if...
0
2016-05-28T18:14:50Z
37,502,408
<p>You can do this in an immutable fashion (i.e., without mutating the original dict) by using a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; d = {'one': ['hello', 'blowing'], 'two': ['frying', 'goodbye']} &g...
0
2016-05-28T18:20:04Z
[ "python", "dictionary", "key" ]
within a dictionary, how do I remove a value from a key with multiple values? Python
37,502,367
<pre><code>from collections import OrderedDict def main(): dictionary = OrderedDict() dictionary["one"] = ["hello", "blowing"] dictionary["two"] = ["frying", "goodbye"] for key in dictionary: print key, dictionary[key] user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N") if...
0
2016-05-28T18:14:50Z
37,502,416
<p>You were trying to delete with string index not int position reference. Here is the modified code:</p> <pre><code>from collections import OrderedDict def main(): dictionary = OrderedDict() dictionary["one"] = ["hello", "blowing"] dictionary["two"] = ["frying", "goodbye"] for key in dictionary: ...
-1
2016-05-28T18:20:47Z
[ "python", "dictionary", "key" ]
within a dictionary, how do I remove a value from a key with multiple values? Python
37,502,367
<pre><code>from collections import OrderedDict def main(): dictionary = OrderedDict() dictionary["one"] = ["hello", "blowing"] dictionary["two"] = ["frying", "goodbye"] for key in dictionary: print key, dictionary[key] user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N") if...
0
2016-05-28T18:14:50Z
37,502,430
<p>Try this:</p> <pre><code>&gt;&gt;&gt; collections.OrderedDict({key:filter(lambda x:not x.endswith('ing'), value) for key,value in dictionary.items()}) OrderedDict([('two', ['goodbye']), ('one', ['hello'])]) </code></pre>
0
2016-05-28T18:22:08Z
[ "python", "dictionary", "key" ]
within a dictionary, how do I remove a value from a key with multiple values? Python
37,502,367
<pre><code>from collections import OrderedDict def main(): dictionary = OrderedDict() dictionary["one"] = ["hello", "blowing"] dictionary["two"] = ["frying", "goodbye"] for key in dictionary: print key, dictionary[key] user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N") if...
0
2016-05-28T18:14:50Z
37,502,470
<p>dict comprehension.</p> <pre><code>return {x : [i for i in dictionary[x] if not i.lower().endswith('ing')] for x in dictionary} </code></pre> <p>Edited to replace values ending with 'ing' with 'removed'</p> <pre><code>return {x : [i if not i.lower().endswith('ing') else 'removed' for i in dictionary[x]] for x in ...
1
2016-05-28T18:26:35Z
[ "python", "dictionary", "key" ]
within a dictionary, how do I remove a value from a key with multiple values? Python
37,502,367
<pre><code>from collections import OrderedDict def main(): dictionary = OrderedDict() dictionary["one"] = ["hello", "blowing"] dictionary["two"] = ["frying", "goodbye"] for key in dictionary: print key, dictionary[key] user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N") if...
0
2016-05-28T18:14:50Z
37,502,647
<pre><code>{key: [ele for ele in val if not ele.lower().endswith('ing')] for key, val in d.items()} </code></pre> <p><strong>Explanation:</strong></p> <p>Start from the right,</p> <ul> <li><p><code>d</code> is the dictionary, it stores <code>&lt;key, [val]&gt;</code></p></li> <li><p>for each <code>key, val</code> in...
0
2016-05-28T18:44:11Z
[ "python", "dictionary", "key" ]
Are grequests responses in the same order as the requests?
37,502,384
<p>I am using the grequests to asynchronously download data from a website using the same url but different parameters.</p> <p>For example,</p> <pre><code>unsent_requests = [] for param in params: # assume params is a list containing different parameters or query strings unsent_requests.append(grequests.get(url =...
1
2016-05-28T18:16:35Z
37,502,896
<p>Responses are in the same order as the requests, as shown in the <a href="https://github.com/kennethreitz/grequests#usage" rel="nofollow">usage example</a>:</p> <pre><code>&gt;&gt;&gt; reqs = [ ... grequests.get('http://httpbin.org/delay/1', timeout=0.001), ... grequests.get('http://fakedomain/'), ... greq...
1
2016-05-28T19:10:47Z
[ "python", "python-requests", "grequests" ]
Why is dict definition faster in Python 2.7 than in Python 3.x?
37,502,392
<p>I have encountered a (not very unusual) situation in which I had to either use a <code>map()</code> or a list comprehension expression. And then I wondered which one is faster.</p> <p><a href="http://stackoverflow.com/a/1247490/3120525">This</a> StackOverflow answer provided me the solution, but then I started to t...
24
2016-05-28T18:17:18Z
37,502,529
<p><strong>Because nobody cares</strong></p> <p>The differences you are citing are on the order of tens or hundreds of nanoseconds. A slight difference in how the C compiler optimizes register use could easily cause such changes (as could any number of other C-level optimization differences). That, in turn, could be...
31
2016-05-28T18:33:09Z
[ "python", "python-2.7", "python-3.x", "dictionary", "python-internals" ]
Why is dict definition faster in Python 2.7 than in Python 3.x?
37,502,392
<p>I have encountered a (not very unusual) situation in which I had to either use a <code>map()</code> or a list comprehension expression. And then I wondered which one is faster.</p> <p><a href="http://stackoverflow.com/a/1247490/3120525">This</a> StackOverflow answer provided me the solution, but then I started to t...
24
2016-05-28T18:17:18Z
37,502,747
<p>As @Kevin already stated:</p> <blockquote> <p>CPython is not designed to be fast in an absolute sense. It is designed to be scalable</p> </blockquote> <p>Try this instead:</p> <pre><code>$ python -mtimeit "dict([(2,3)]*10000000)" 10 loops, best of 3: 512 msec per loop $ $ python3 -mtimeit "dict([(2,3)]*100000...
20
2016-05-28T18:55:41Z
[ "python", "python-2.7", "python-3.x", "dictionary", "python-internals" ]
Why is dict definition faster in Python 2.7 than in Python 3.x?
37,502,392
<p>I have encountered a (not very unusual) situation in which I had to either use a <code>map()</code> or a list comprehension expression. And then I wondered which one is faster.</p> <p><a href="http://stackoverflow.com/a/1247490/3120525">This</a> StackOverflow answer provided me the solution, but then I started to t...
24
2016-05-28T18:17:18Z
37,503,256
<p>Let's <a href="https://docs.python.org/3/library/dis.html#dis.dis">disassemble</a> <code>{}</code>:</p> <pre><code>&gt;&gt;&gt; from dis import dis &gt;&gt;&gt; dis(lambda: {}) 1 0 BUILD_MAP 0 3 RETURN_VALUE </code></pre> <p><a href="https://hg.python.org/cpython/file/2.7/P...
17
2016-05-28T19:56:10Z
[ "python", "python-2.7", "python-3.x", "dictionary", "python-internals" ]
Convert pandas df multi index to columns
37,502,463
<p>first post here, any assistance is much appreciated.</p> <p>After reading a csv file response from an api request using python urllib2, i am left with a multi index df. It contains 19 index' then only 2 'columns'.</p> <p>How do i convert these 19 index' to additional columns please?</p> <p>I tried resting the ind...
0
2016-05-28T18:25:21Z
37,503,963
<p>I think you can add parameter <code>inplace</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>df.reset_index(inplace=True) </code></pre> <p>Or assign it back:</p> <pre><code>df = df.reset_index() ...
0
2016-05-28T21:39:24Z
[ "python", "pandas", "multi-index" ]
How can I get correct scoreboard in 'Pong' by using pygame?
37,502,545
<p>How can I get correct scoreboard in 'Pong' by using pygame? I tried many times but the scoreboard only shows me 0 and 1. </p> <p>Here is my code:</p> <pre><code>import pygame, sys, time from pygame.locals import * def main(): # Initialize pygame pygame.init() # Set window size and title, and frame delay ...
0
2016-05-28T18:34:18Z
37,503,873
<p>You are overwriting the parameters, and not the actual game score</p> <pre><code>def drawScore(...,right_score,left_score): # given here ... if center[0] &lt; ball_radius: right_score = right_score + 1 # updated, but only locally ... if center[0] &gt; size[0] - ball_radius: ...
1
2016-05-28T21:25:19Z
[ "python", "python-3.x", "pygame", "pong" ]
Multithreading or Asynchronous for Python GTK/Socket Server/Data Writing
37,502,578
<p>I'm new to Python, socket, multithreading and asynchronous programming. I'm wondering what is the best approach to implement a server that receives and sends data between a client such as a Unity3D game and plot out these data in a GUI using Python GTK while writing these data to a text file in real time. To make th...
0
2016-05-28T18:37:52Z
37,503,738
<p>Use TCP. UDP are mostly used for things like video/audio streaming. That's not the case here.</p> <p>As for <code>async</code> vs <code>thread</code> in Unity, I would suggest you go for with Thread. It is easier and you are guaranteed that your network code will not be slowing Unity down in any way.</p> <blockquo...
0
2016-05-28T21:06:34Z
[ "python", "multithreading", "sockets", "asynchronous", "unity3d" ]
Numpy from string (Difference of uint8 and uint16) [Combining two uint8 values to one uint16 value]
37,502,610
<p>I have an audio file in Java, when I read <code>AudioInputStream</code> and convert it to byte array, I get values between <code>-128</code> and <code>127</code>. I need to convert those values to a range between <code>-32768</code> and <code>32767</code>. So I think I need to combine every two values in my Java arr...
0
2016-05-28T18:40:53Z
37,502,731
<p>Use <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html" rel="nofollow"><code>ByteBuffer</code></a>:</p> <pre><code>byte[] b = { 37, -39, -112, -32, 123, -40, -114, 121 }; short[] s = new short[b.length / 2]; ByteBuffer buf = ByteBuffer.wrap(b); // buf.order(ByteOrder.LITTLE_ENDIAN); for (in...
0
2016-05-28T18:53:13Z
[ "java", "python", "numpy", "binary", "hex" ]
Login Error when using library googleplay-api
37,502,655
<p>I am using the <a href="https://github.com/NeroBurner/googleplay-api" rel="nofollow">googleplay-api</a> module to download sample Android apps for my research project. In the past, I could use this library using my GMail account name, password, and Android ID/Google Service Framework (GSF). But just few days a ago, ...
0
2016-05-28T18:44:55Z
37,552,925
<p>Try to login to play.google site and open any application. Do you, by any chance, have "You don't have any devices" error message? Instead of "This app is compatible with your device".</p>
0
2016-05-31T18:18:09Z
[ "android", "python", "download", "google-play" ]
Python async TCP server: cannot get sockets from it
37,502,685
<p>I'm trying to simulate a network using asychronious TCP servers and sockets. I used an <a href="https://docs.python.org/dev/library/asyncio-protocol.html#asyncio-tcp-echo-client-protocol" rel="nofollow">example from documentation</a> as a starting point for my task. Here's the code of my server class:</p> <pre><cod...
0
2016-05-28T18:48:20Z
37,502,997
<p>The call to <code>create_server</code> returns a coroutine. The server instance which has the sockets attribute is returned when you call <code>run_until_complete</code>. Change the definition of <code>startListening</code> to save the return value of <code>run_until_complete</code> as <code>self.server</code> and m...
1
2016-05-28T19:22:46Z
[ "python", "sockets", "python-3.x", "tcp" ]
Ansible install from source - hacking/env-setup fails
37,502,772
<p>I'm trying to install ansible from source. I have done:</p> <pre><code>sudo apt-get install python2.7-dev sudo pip install paramiko PyYAML Jinja2 httplib2 git clone git://github.com/ansible/ansible.git --recursive </code></pre> <p>Then, when I try </p> <pre><code>~/src/ansible$ source ./hacking/env-setup </code><...
0
2016-05-28T18:58:43Z
37,516,429
<p>Do you happen to have dos line endings in your env-setup? Check your core.autocrlf setting, that should not be true. If it is, do:</p> <pre><code>git config --global core.autocrlf false </code></pre>
1
2016-05-30T01:09:10Z
[ "python", "ansible" ]
How to embed animation into ParaView scene from script?
37,502,787
<p>So I try to add animation to my scene in paraview using Python. I started with <a href="http://www.paraview.org/Wiki/ParaView/Python/Animation" rel="nofollow">wiki script</a>. Animation plays only when <code>scene.Play()</code> is called. While it is playing ParaView (5.0.1 in my case) get stuck with window paying ...
0
2016-05-28T18:59:49Z
37,527,198
<p>That wiki example appears to be a little dated.</p> <p>Try this in a script instead:</p> <pre><code># get active source. sphere1 = GetActiveSource() # get animation track sphere1StartThetaTrack = GetAnimationTrack('StartTheta', index=0, proxy=sphere1) # create keyframes for this animation track # create a key f...
2
2016-05-30T13:41:32Z
[ "python", "animation", "vtk", "scene", "paraview" ]
Trouble Installing virtualenv on Python 3.5.1 OSX
37,502,794
<p>I've tried to install virtualenv using <code>sudo pip install virtualenv</code> but it's not installing properly. This is what happens when I use <code>sudo pip install virtualenv</code> again and then try to get the version of it. <a href="https://gyazo.com/0cbff8acaf8f4fdc505e53913739e28a" rel="nofollow">https://g...
0
2016-05-28T19:00:24Z
37,502,836
<p>You need to add the folder containing virtualenv to your shell's path:</p> <pre><code>export PATH=$PATH:/path/to/folder/containing/virtualenv/ </code></pre> <p>You could also create a symlink to the virtualenv file in <code>/usr/bin</code> or <code>/usr/local/bin</code>. These two folders are usually in the shell ...
0
2016-05-28T19:04:44Z
[ "python", "osx", "virtualenv" ]
Python CSV: One code but unfortunately two diffrent results
37,502,804
<p>I have problems with the following Code. I'm trying to read datas from a CSV file to create a nested dictonary. When I run it the first time it does exactly what I intent but when I run it twice it changes the order of the output. Does anyone have an idea why this is hapening? I'm using Python 3.4.</p> <pre><code>i...
0
2016-05-28T19:01:05Z
37,503,087
<p>From <a href="https://docs.python.org/2/library/stdtypes.html#dict.items" rel="nofollow">the docs</a> we have this helpful note:</p> <blockquote> <p><strong>CPython implementation detail:</strong> Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depen...
0
2016-05-28T19:34:19Z
[ "python", "csv", "dictionary" ]
Pandas: Append rows to DataFrame already running through pandas.DataFrame.apply
37,502,825
<p><em>Brief</em>: I am using <code>Selenium WebDriver</code> and <code>Pandas</code> for <em>Python 2.7</em> to make a web scraper that goes to a sequence of URLs and scrapes URLs on that page. If it finds URLs there, I want them to be added to the running sequence. How can I do this using <code>pandas.DataFrame.appl...
1
2016-05-28T19:03:07Z
37,505,036
<p>I don't think there is a way to use <code>apply</code> the way you envision. And even if there were a way, </p> <ul> <li><p>it would most likely require keeping track of how many items have already been iterated over so you would know where to insert new items into <code>df['URL']</code></p></li> <li><p>inserting i...
2
2016-05-29T00:34:40Z
[ "python", "selenium", "pandas" ]
Error while parsing json from IBM watson using python
37,502,848
<p>I am trying to parse out a JSON download using python and here is the download that I have:</p> <pre><code>{ "document_tone":{ "tone_categories":[ { "tones":[ { "score":0.044115, "tone_id":"anger", "tone_n...
1
2016-05-28T19:06:29Z
37,503,170
<p>As <a href="http://stackoverflow.com/users/3001761/jonrsharpe">jonrsharpe</a> said in a <a href="http://stackoverflow.com/questions/37502848/error-while-parsing-json-from-ibm-watson-using-python#comment62500719_37502848">comment</a>:</p> <blockquote> <p><code>data['document_tone']</code> is a dictionary, but <cod...
0
2016-05-28T19:44:31Z
[ "python", "json", "python-3.x" ]
Error while parsing json from IBM watson using python
37,502,848
<p>I am trying to parse out a JSON download using python and here is the download that I have:</p> <pre><code>{ "document_tone":{ "tone_categories":[ { "tones":[ { "score":0.044115, "tone_id":"anger", "tone_n...
1
2016-05-28T19:06:29Z
37,503,176
<p>You are incorrectly walking the structure. The root node has a single <code>document_tone</code> key, the value of which only has the <code>tone_categories</code> key. Each of the categories has a list of tones and it's name. Here is how you would print it out (adjust as needed):</p> <pre><code>for cat in data['doc...
0
2016-05-28T19:45:00Z
[ "python", "json", "python-3.x" ]
Indenting in a txt file from python script in terminal
37,502,953
<p>Im trying to write a python script that will make a txt file if there isn't a current one and add "Indent Me Somewhere Onto The Next Line" this text to it. I am wondering how the text could be indented in the middle of the string onto the next line with the least amount of python. Thanks everyone.</p> <pre><code> ...
-1
2016-05-28T19:18:04Z
37,503,030
<p>You need to put a tab character and linefeed at the end, like:</p> <pre><code>memory.write("\tIndent Me Somewhere Onto The Next Line\n") </code></pre>
1
2016-05-28T19:26:49Z
[ "python" ]
Indenting in a txt file from python script in terminal
37,502,953
<p>Im trying to write a python script that will make a txt file if there isn't a current one and add "Indent Me Somewhere Onto The Next Line" this text to it. I am wondering how the text could be indented in the middle of the string onto the next line with the least amount of python. Thanks everyone.</p> <pre><code> ...
-1
2016-05-28T19:18:04Z
37,503,330
<p>You need to put <code>memory.write("\tIndent me onto the next line \n")</code>. </p> <p>OR </p> <p><code>memory.write("\n\tIndent me onto the next line ")</code>, if you want the first line to be blank.</p>
0
2016-05-28T20:08:22Z
[ "python" ]
Scope of warnings.simplefilter('error', Image.DecompressionBombWarning)
37,503,005
<p>I have the following skeleton tornado program:</p> <pre><code>class IS(BaseHandler): @tornado.gen.coroutine def get(self): #render stuff def post(self): try: # load Image except RuntimeWarning: # handle exception class Application(tornado.web.Application): def __init__(s...
1
2016-05-28T19:23:47Z
37,503,280
<p><code>warnings.simplefilter</code> affects the whole process (when it is not called from inside a <code>with warnings.catch_warnings()</code> block), so to control warnings globally you just have to call it once at startup, as you've done.</p>
2
2016-05-28T20:00:01Z
[ "python", "tornado", "pillow" ]
Python 3.5 convert values during re-write to new csv
37,503,152
<p>I have a CSV file that I am writing to another file, but in the process want to change values based on greater then or less than. For example, in column for in the new file (row 2 from the old one) I want to transform the data from a number into a word, depending on the value in the column. My actual data has more ...
0
2016-05-28T19:42:05Z
37,503,333
<p>You need to have a function or something to process the data (3rd column). Here's a way to do so:</p> <pre><code> import csv # expected codes and their replacements CODES = { '50': 'order now', '999': 'no order necessary', '500': 'order next month', 'amount available': 'order timeline' } # you ...
0
2016-05-28T20:08:52Z
[ "python", "csv", "if-statement", "nested", "row" ]
Python 3.5 convert values during re-write to new csv
37,503,152
<p>I have a CSV file that I am writing to another file, but in the process want to change values based on greater then or less than. For example, in column for in the new file (row 2 from the old one) I want to transform the data from a number into a word, depending on the value in the column. My actual data has more ...
0
2016-05-28T19:42:05Z
37,503,580
<p>I am assuming that the amount available column affects the result in the final csv file. I suggest you take a look at the pandas package, it allows easy manipulation of a csv file. You can read the first file into pandas and create a new column whose values depend on the value in the amount available column. Somethi...
0
2016-05-28T20:42:36Z
[ "python", "csv", "if-statement", "nested", "row" ]
how to convert str to float in pandas dataframe
37,503,244
<p>I am using below line to read a csv file where column B ends as str format and I do not manage to convert it to float directly:</p> <pre><code> df = pd.read_csv('data.csv', sep=";", encoding = "ISO-8859-1") </code></pre> <p>this produces a dataframe where all columns are in str format:</p> <pre><code> ...
0
2016-05-28T19:54:54Z
37,503,263
<p>For me it works nice, I only omit <code>dtype={'B': np.float32}</code>:</p> <pre><code>import pandas as pd import io temp=u"""A;B 0;Emma;-20,50 1;Filo;-15,75 2;Theo;17,23""" #after testing replace io.StringIO(temp) to filename df = pd.read_csv(io.StringIO(temp), sep=";", encoding = "ISO-8859-1", decimal= ',') prin...
0
2016-05-28T19:57:31Z
[ "python", "csv", "pandas", "typeconverter" ]
Keras error with merge layer
37,503,270
<p>I am trying to build a model to colorize images. I am using the LAB color space. The input to the model is the L channel and the model is to be trained to predict the A and B channels. I want to run the L channel through a few convolutions and then split it off into two other models which independently calculate ...
1
2016-05-28T19:58:41Z
37,506,565
<p>The <code>Sequential</code> model doesn't allow you to create forks in the network. Use the functional API (new in Keras 1.0) instead. You can follow <a href="http://keras.io/getting-started/functional-api-guide/#multi-input-and-multi-output-models" rel="nofollow">this tutorial</a>.</p>
2
2016-05-29T05:35:28Z
[ "python", "neural-network", "theano", "keras" ]
Displaying time in Python using "Strptime()"
37,503,315
<p>I'm trying to make a basic program that shows how many days are left until your next birthday, however when I run it in terminal, it says that the input value should be returning a string not an integer? when using the input function in python, doesnt it automatically return as a string value? </p> <pre><code> i...
2
2016-05-28T20:06:26Z
37,503,393
<p>In Python 2 use <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow">raw_input()</a> instead.</p>
2
2016-05-28T20:17:20Z
[ "python", "time" ]
Displaying time in Python using "Strptime()"
37,503,315
<p>I'm trying to make a basic program that shows how many days are left until your next birthday, however when I run it in terminal, it says that the input value should be returning a string not an integer? when using the input function in python, doesnt it automatically return as a string value? </p> <pre><code> i...
2
2016-05-28T20:06:26Z
37,503,406
<ol> <li>Use <code>%y</code> (small letter) to catch two digit years</li> <li>You should advice the user about the expected format - you expect "MM/DD/YY", but you tell the user to type "MM.DD.YY"</li> </ol> <p>To calculate the difference use something like this (for python3, for python2 use raw_input as Jahangir ment...
2
2016-05-28T20:18:27Z
[ "python", "time" ]
Getting an empty jpg file, when try to Download an image
37,503,345
<p>I have been trying to download an image from website (no username and password required) but every time I am getting an empty file. I have used conventional urllib .retrieve and requests methodologies but getting the same result. One thing more is that if I try to open the same image manually by copy pasting the URL...
0
2016-05-28T20:10:40Z
37,531,734
<p>When you try to implement some HTTP code in Python do not forget to validate that you can use <code>curl</code> or <code>wget</code> to perform these HTTP requests. This will save you a lot of time trying to debug a problem that is not in your code.</p> <p>The also have very good verbose modes which will give you s...
0
2016-05-30T18:25:42Z
[ "python", "urllib" ]
Writing binary in c++ and read in python
37,503,346
<p>I would like to store a series of numbers to a binary file using c++, to open later using python. Currently I have the following script in c++ named *writer.cpp:</p> <pre><code>#include &lt;fstream&gt; int main() { std::ofstream outFile; outFile.open("binaryFile.bin", std::ios::binary); int number = 0; for...
1
2016-05-28T20:10:44Z
37,503,377
<p><a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.fromfile.html" rel="nofollow"><code>fromfile</code></a> assumes floating point numbers by default. If you want to change this behaviour, you need to pass in the type in the <code>dtype</code> named parameter.</p> <p>As you're writing ints, th...
2
2016-05-28T20:15:00Z
[ "python", "c++", "numpy", "binary" ]
Writing binary in c++ and read in python
37,503,346
<p>I would like to store a series of numbers to a binary file using c++, to open later using python. Currently I have the following script in c++ named *writer.cpp:</p> <pre><code>#include &lt;fstream&gt; int main() { std::ofstream outFile; outFile.open("binaryFile.bin", std::ios::binary); int number = 0; for...
1
2016-05-28T20:10:44Z
37,503,386
<p>You have to specify the type of the values you're going to be reading, <code>numpy</code> has no way to guess that as there is no metadata stored in the file itself. So in your case you have to do something like:</p> <pre class="lang-py prettyprint-override"><code>x = np.fromfile(path, dtype=int) </code></pre> <p>...
2
2016-05-28T20:16:24Z
[ "python", "c++", "numpy", "binary" ]
Using Numpy from keyword.py
37,503,366
<p>I want to use NumPy in a Python script that uses <code>pandas</code> to process an Excel file. However, one of my constraints is that my file must be named <code>keyword.py</code>, which causes an import error. The import error is traced back to a line <code>from keyword import iskeyword as _iskeyword</code> in <cod...
0
2016-05-28T20:13:36Z
37,503,683
<p>Not pretty, but a <code>keyword.py</code> of</p> <pre><code>if True: import imp, sys keyword_loc = imp.find_module("keyword", sys.path[1:])[1] imp.load_source("keyword", keyword_loc) import collections print(collections.Counter) </code></pre> <p>fails with an AttributeError if we replace <code>Tru...
1
2016-05-28T20:59:11Z
[ "python", "numpy", "pandas" ]
Using Numpy from keyword.py
37,503,366
<p>I want to use NumPy in a Python script that uses <code>pandas</code> to process an Excel file. However, one of my constraints is that my file must be named <code>keyword.py</code>, which causes an import error. The import error is traced back to a line <code>from keyword import iskeyword as _iskeyword</code> in <cod...
0
2016-05-28T20:13:36Z
37,503,761
<p>For working with a single script, you can remove the current directory from the import search path. That might be sufficient for working on your TopCoder problem, but I wouldn't recommend it as a long-term solution. (Long-term: don't use file names that mirror the standard library.)</p> <p>If the following script...
1
2016-05-28T21:09:41Z
[ "python", "numpy", "pandas" ]
How to call method of an instance in python
37,503,375
<p>I am having an issue calling a method in a very simple python class. I have something that looks like this:</p> <pre><code>from shape import Shape class Figure: def __init__(self): self.shapes = [] # the shape objects that make up self self.shape0 = shape([1, 3, 2], [30, 20]) self.sh...
-2
2016-05-28T20:14:36Z
37,503,396
<p>Create an instance of <code>Figure</code> first.</p> <pre><code>f = Figure() f.get_points() </code></pre>
1
2016-05-28T20:17:27Z
[ "python" ]
How to call method of an instance in python
37,503,375
<p>I am having an issue calling a method in a very simple python class. I have something that looks like this:</p> <pre><code>from shape import Shape class Figure: def __init__(self): self.shapes = [] # the shape objects that make up self self.shape0 = shape([1, 3, 2], [30, 20]) self.sh...
-2
2016-05-28T20:14:36Z
37,503,410
<p>You need an instance of <code>Figure</code> to call the method upon:</p> <pre><code>f = Figure() print f.get_points() </code></pre>
0
2016-05-28T20:18:41Z
[ "python" ]
I can't access QuerySet in Manager's init method in Django
37,503,378
<p>I'd like to get a QuerySet of a Model in Manager's <code>__init__</code> method to setup Pagination for the QuerySet results. The reason why I want to setup Pagination in <code>__init__</code> method is because I have lots of simple methods in the Manager like <code>getPage</code> and <code>getNumberOfPages</code> e...
0
2016-05-28T20:15:09Z
37,503,439
<p>You're calling the parent's <code>get_query()</code> method. You're not overriding it so there's no point, just call it on <code>self</code>. Better yet, make this operation lazy. Properties are an option:</p> <pre><code>class ArticleManager(models.Manager): @property def article_paginator(self): re...
1
2016-05-28T20:22:48Z
[ "python", "django", "django-models", "django-queryset" ]
Python function not returning anything
37,503,399
<pre><code>def equip(x): global bag_sword global bag_chest global bag_gloves global bag_helmet while x == "iron sword" and "iron sword" in bag: if bag_sword: print "You can't have 2 weapons equipped!" x = "" print "\nYou equip the iron sword.\n" bag.re...
1
2016-05-28T20:18:00Z
37,503,493
<p>Here is how you can make the function work as described:</p> <pre><code>bag_sword = [] def equip(x): global bag_sword if x == "iron sword": if "iron sword" in bag_sword: print "You can't have 2 weapons equipped!" else: bag_sword.append("iron sword") print bag_sword ...
2
2016-05-28T20:29:51Z
[ "python", "python-2.7" ]
Python function not returning anything
37,503,399
<pre><code>def equip(x): global bag_sword global bag_chest global bag_gloves global bag_helmet while x == "iron sword" and "iron sword" in bag: if bag_sword: print "You can't have 2 weapons equipped!" x = "" print "\nYou equip the iron sword.\n" bag.re...
1
2016-05-28T20:18:00Z
37,503,895
<p>You can make nwk's solution more general (also try to get rid of global variables):</p> <pre><code>def equip(item, bag): if item in bag: print "You can't have 2 {}s equipped!".format(item) else: bag.append(item) def main(): bag_sword = [] print bag_sword equip("iron sword", bag_...
0
2016-05-28T21:29:32Z
[ "python", "python-2.7" ]
creating a .pxd file for a python module
37,503,462
<p>One way of using cython, the Python to C compiler, is to instead of rewriting your python code in Cython, just writing a .pxd file with the same name of your module where you declare the type of your variables, as explained in <a href="http://docs.cython.org/src/tutorial/pure.html" rel="nofollow">here</a></p> <p>Do...
0
2016-05-28T20:25:53Z
37,503,709
<p>What specifically are you trying to automate? Cython can take a python module and compile it down into C, but this only achieves modest speed increases. Most of the speed increase comes from providing type declarations. And that's really not something you can automate. You have to provide them one way or another to ...
2
2016-05-28T21:02:24Z
[ "python", "cython" ]
creating a .pxd file for a python module
37,503,462
<p>One way of using cython, the Python to C compiler, is to instead of rewriting your python code in Cython, just writing a .pxd file with the same name of your module where you declare the type of your variables, as explained in <a href="http://docs.cython.org/src/tutorial/pure.html" rel="nofollow">here</a></p> <p>Do...
0
2016-05-28T20:25:53Z
37,504,450
<p>Well, I haven't found a way to fully automate this but semi-automating -- which really needs minor effort to fully automate -- is available.</p> <p>In the official <code>Cython</code> repository on github there's a script <a href="https://github.com/cython/cython/blob/master/Tools/jedityper.py" rel="nofollow"><code...
1
2016-05-28T22:48:41Z
[ "python", "cython" ]
jupyter: how to stop execution on errors?
37,503,464
<p>The common way to defensively abort execution in python is to simply do something like:</p> <pre><code>if something_went_wrong: print("Error message: goodbye cruel world") exit(1) </code></pre> <p>However, this is not good practice when using <strong>jupyter notebook</strong>, as this seems to abort the ke...
-1
2016-05-28T20:26:06Z
37,513,589
<p>No, <code>exit()</code> is <strong>not</strong> the way to abort Python execution usually. <code>exit()</code> is meant to stop the interpreter immediately with a status code. </p> <p>Usually you will write a script like that:</p> <pre><code> if __name__ == '__main__': sys.exit(main()) </code></pre> <p>Try n...
3
2016-05-29T18:44:13Z
[ "python", "jupyter" ]
Force python to auto-scale the colorbar in image every iteration
37,503,471
<p>I have a loop that utilizes the <code>'set_data'</code> command so that I can rapidly image data in Python, while in a loop. This was inspired by this answer <a href="http://stackoverflow.com/questions/10272478/why-does-my-pylab-animation-slow-down-with-each-update">here</a>. </p> <p>However one issue is that it se...
1
2016-05-28T20:26:59Z
37,511,779
<p>You could manually change <code>vmin</code> and <code>vmax</code> using <code>im.set_clim()</code>, then the colorbar (assuming that's what you are refering to as "color axis") is rescaled automatically:</p> <pre><code>import matplotlib.pylab as pl import numpy as np pl.close('all') someImage = np.random.random((...
1
2016-05-29T15:39:02Z
[ "python", "matplotlib", "colors", "figure" ]
How can I cache API data in a class attribute?
37,503,506
<p>I would like to have a class, similar to the one below, where I can use a property to access data from an API. I would like to be able to cache the data for a certain period of time, though, so that I may access the attribute rapidly without being ratelimited. What would be the cleanest way to implement this functio...
2
2016-05-28T20:31:48Z
37,505,155
<p>Here's one way to make it look neat (it may seem overcomplicated but it's not really):</p> <pre class="lang-py prettyprint-override"><code>from uuid import uuid4 from datetime import datetime class cached_descriptor(object): def __init__(self, func, timeout): self.__doc__ = getattr(func, '__doc__') ...
1
2016-05-29T00:57:58Z
[ "python", "python-3.x", "caching", "python-requests", "rate-limiting" ]
SQLAlchemy - Try Except for different Integrity Errors
37,503,508
<p>SQLAlchemy raises a <code>IntegrityError</code> for both Unique constraint and Foreign Key contraint violations. How can I wrap this in a <code>try/except</code> block and discriminate between the various causes of the exception? I want to know which column the violation occurred and whether or not it was a Unique o...
1
2016-05-28T20:31:54Z
37,517,064
<p>you're absolutely right, you need to parse out the errors and it's database-specific. Here is an example you can use with MySQL:</p> <pre><code>from sqlalchemy import UniqueConstraint from sqlalchemy.exc import IntegrityError class MyUser(Base): __tablename__ = 'MyUser' id = Column(Integer, primary_key=True)...
0
2016-05-30T03:04:48Z
[ "python", "sqlalchemy" ]
How to get the Nth occurrence of a day of the week for a given month?
37,503,616
<p>The week of month does not define this value. The shift between the starting week and starting month causes the problem in most cases.</p> <p>Is there any python lib or algorithm to calculate this value?</p>
-1
2016-05-28T20:48:32Z
37,503,651
<p>You can calculate this by looping over the days of the month and counting whether you've come across that <em>n</em>th weekday:</p> <pre><code>import datetime def get_n_weekday(year, month, day_of_week, n): count = 0 for i in xrange(1, 32): try: d = datetime.date(year, month, i) ...
1
2016-05-28T20:55:19Z
[ "python", "python-2.7", "date" ]
How to get the Nth occurrence of a day of the week for a given month?
37,503,616
<p>The week of month does not define this value. The shift between the starting week and starting month causes the problem in most cases.</p> <p>Is there any python lib or algorithm to calculate this value?</p>
-1
2016-05-28T20:48:32Z
37,504,067
<p>Two more simpler solutions than Simeon's answer:</p> <pre><code>def f1(day_of_month): ret = None if ( day_of_month % 7 == 0 ): ret = day_of_month/7 else: ret = (day_of_month//7) + 1 return ret def f2(day_of_month): actual_day = day_of_month counter = 0 while ...
0
2016-05-28T21:55:21Z
[ "python", "python-2.7", "date" ]
Python displaying ints as long?
37,503,640
<p>So here are two functions for finding the prime factors of a number. Credits: Triptych <a href="http://stackoverflow.com/a/412942/6211963">http://stackoverflow.com/a/412942/6211963</a></p> <pre><code>def prime_factors1(n): """Returns all the prime factors of a positive integer""" factors = [] d = 2 ...
2
2016-05-28T20:53:27Z
37,504,096
<p>The difference is the following. In <code>prime_factors1(n)</code>, the last factor is appended here:</p> <pre><code>while n &gt; 1: while n % d == 0: factors.append(d) </code></pre> <p>where <code>d</code> starts out at <code>2</code> (definitely an <code>int</code> no matter which runtime), grows via...
5
2016-05-28T22:01:27Z
[ "python", "python-2.7", "long-integer" ]
Custom user model not working on django admin
37,503,697
<p>I created an app authentication, code for models is,</p> <pre><code>from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.db import models class AccountManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): i...
0
2016-05-28T21:00:21Z
39,715,454
<p>You added the <strong>is_staff</strong> later on which seems to be false by default, so when you migrated the field was created in database with the value false in the is_staff field.</p> <p>Please make the changes as below and try</p> <p>class AccountManager(BaseUserManager): def create_user(self, email, pass...
0
2016-09-27T03:20:19Z
[ "python", "django" ]
How do I apply CodecOptions to a mongoengine collection to get tzinfo?
37,503,932
<p>Using a mongoengine <code>Document</code>, when I load a <code>DateTimeField</code> from mongo, it lacks <code>tzinfo</code>. Our application by policy wants all datetimes to have <code>tzinfo</code>.</p> <p>When I save to mongo, I know that pymongo does the correct and predictable thing wrt timezones; if it is nai...
1
2016-05-28T21:34:52Z
38,618,475
<p>My understanding is that mongoengine doesn't support <em>per-model</em> <code>codec_options</code>. If it did, they should be part of the <code>opts</code> dictionary <a href="https://github.com/MongoEngine/mongoengine/blob/f35034b989d83cae883c37524d86711a4014046f/mongoengine/document.py#L201" rel="nofollow">here</a...
1
2016-07-27T16:24:50Z
[ "python", "mongodb", "pymongo", "mongoengine", "bson" ]
Error: AttributeError: 'NoneType' object has no attribute 'text'
37,503,991
<p>i have to simillar codes, one has multithreading and the other one doesnt. the one that has multithreading is getting this error <strong>AttributeError: 'NoneType' object has no attribute 'text'</strong> while the other isnt, here is my code:</p> <p>multithreading:</p> <pre><code>import threading import requests f...
0
2016-05-28T21:43:47Z
37,509,779
<p>The multihreading code works perfectly fine on my system (Win10, Python 3.4-64bit) when <code>symbolslist</code> is set to <code>['AAPL']</code>. But the script crashes with the reported error when <code>symbolslist</code> is set to <code>['AAPL', 'IBM']</code>.</p> <p>When inspecting the returned HTML code, you ca...
0
2016-05-29T12:13:45Z
[ "python", "multithreading", "python-3.x", "web-scraping" ]
Is it possible to check for db updates before performing db.rollback() within a worker transaction?
37,503,993
<p>I'm using a queue to queue transactions for a MySQL database in python. I'm using autocommit=False so that I can rollback a transaction if not all of the data queries are executed properly. </p> <p>I'm wondering whether it's possible to check whether a worker has performed an action on the database before performin...
0
2016-05-28T21:44:32Z
37,504,175
<p>If you issue a </p> <pre><code>START TRANSACTION; </code></pre> <p>(which brings the connection into the same as <code>autocommit = false</code>), sending the command</p> <pre><code>ROLLBACK WORK; </code></pre> <p>(see also <a href="https://dev.mysql.com/doc/refman/5.5/en/commit.html" rel="nofollow">https://dev....
0
2016-05-28T22:11:35Z
[ "python", "mysql", "transactions" ]
Is it possible to check for db updates before performing db.rollback() within a worker transaction?
37,503,993
<p>I'm using a queue to queue transactions for a MySQL database in python. I'm using autocommit=False so that I can rollback a transaction if not all of the data queries are executed properly. </p> <p>I'm wondering whether it's possible to check whether a worker has performed an action on the database before performin...
0
2016-05-28T21:44:32Z
37,504,177
<p>If I've understood the question correctly, it is <em>not</em> an error to rollback a transaction where nothing else has happened, although it <em>is</em> an error to attempt to rollback when no transaction exists. To tell which is the case you can test the <a href="http://dev.mysql.com/doc/connector-python/en/connec...
2
2016-05-28T22:11:43Z
[ "python", "mysql", "transactions" ]
Determining if a grid is solvable
37,504,017
<p>I'm making a simple "Rumba Robot" simulation. I've included the whole code below, though I'm only asking about the is_furniture_valid function. There are green tiles that are furniture that the vacuum must clean around. The vacuum checks its next location every step. If that location is invalid, it picks a random ne...
1
2016-05-28T21:48:10Z
37,504,553
<p>Here's a non-recursive version of <code>find_accessable_tiles</code>. </p> <p>Rather than recursing, it pushes the tiles to be tested onto the end of a queue, implemented as a list named <code>tile_queue</code>. I've replaced your <code>l</code> with a set named <code>accessable</code> because testing set membershi...
2
2016-05-28T23:08:49Z
[ "python", "recursion" ]
argparse: optional argument as flag and variable
37,504,090
<p>I'm writing a program that takes two argument (paths) and as an option <code>-l</code>, witch enables save the log in a log file.</p> <p>I'm using <code>argparse</code> and create the following argument:</p> <pre><code>parser.add_argument('-l', '--logfile', nargs='?', cons...
0
2016-05-28T22:00:16Z
37,504,257
<p>The neat way to do this would be to introduce option flags for the both the paths arguments too. Then there would be no ambiguity and you'd be able to say:</p> <pre><code>prog.py -l -leftpath path_1 -rightpath path_2 </code></pre>
0
2016-05-28T22:22:46Z
[ "python", "argparse" ]
argparse: optional argument as flag and variable
37,504,090
<p>I'm writing a program that takes two argument (paths) and as an option <code>-l</code>, witch enables save the log in a log file.</p> <p>I'm using <code>argparse</code> and create the following argument:</p> <pre><code>parser.add_argument('-l', '--logfile', nargs='?', cons...
0
2016-05-28T22:00:16Z
37,504,379
<p>you can also store all options in a single argument and check by hand, as in</p> <pre><code>parser.add_argument('-p', dest='path', nargs='?', default=('path1/','path2/')) args = parser.parse_args() if len(args.path) == 3: args.logfile = args.path[0] args.path = args.path[1:] elif len(args....
0
2016-05-28T22:38:12Z
[ "python", "argparse" ]
argparse: optional argument as flag and variable
37,504,090
<p>I'm writing a program that takes two argument (paths) and as an option <code>-l</code>, witch enables save the log in a log file.</p> <p>I'm using <code>argparse</code> and create the following argument:</p> <pre><code>parser.add_argument('-l', '--logfile', nargs='?', cons...
0
2016-05-28T22:00:16Z
37,505,140
<p>Your assessment is right, </p> <pre><code>prog.py -l path_1 path_2 </code></pre> <p>will assign <code>path_1</code> to <code>l</code> and <code>path_2</code> to the first positional, and raise an error about missing 2nd positional.</p> <p><a href="http://bugs.python.org/issue9338" rel="nofollow">http://bugs.pytho...
0
2016-05-29T00:54:45Z
[ "python", "argparse" ]
Pygame holding multiple keys
37,504,182
<p>I'm making a game with Pygame, but I have a problem with commands: when I press, for example, Left-Key player goes left; holding Left-key i press Right-Key: then player goes right. When I release Right_Key i want that player goes again left until i don't effectively release the Left-Key.</p> <p>Here is my code for ...
0
2016-05-28T22:12:16Z
37,504,295
<blockquote> <pre><code>elif event.type == pygame.KEYUP: if event.key in (275, 276): KeyVar.dx = 0 </code></pre> <p>this bit of code makes it so that if either key is released it stops moving. you may want to use an "and" statement to prevent it from stopping you even if you are holding a key down</p> ...
2
2016-05-28T22:28:20Z
[ "python", "multithreading", "keyboard", "pygame" ]
Tweepy mentions_timeline returns an empty list
37,504,245
<p>I just started to make a Twitter Api. Normally I don't have a Twitter account, for this api I created one. I Tweeted 4 times, including some mentions. But when I use <code>mentions_timeline</code> like this;</p> <pre><code>my_mentions = api.mentions_timeline() #print(my_mentions) #output: [] </code></pre> <p>After...
0
2016-05-28T22:21:42Z
37,504,535
<p>Try using the new <a href="http://docs.tweepy.org/en/v3.5.0/cursor_tutorial.html" rel="nofollow">Cursor Object</a> as follows:</p> <pre><code>api = tweepy.API(auth) for mentions in tweepy.Cursor(api.mentions_timeline).items(): # process mentions here print mentions.text </code></pre> <p>as per Twitters do...
0
2016-05-28T23:05:31Z
[ "python", "python-3.4", "tweepy", "tweets", "mention" ]
AttributeError: 'str' has no attribute 'shape'
37,504,274
<p>EDIT: I am very sorry to anyone who has been trying to figure this out... for SOME REASON in one of my other functions, I had a for loop</p> <pre><code>for turt in winningRowTurtles: winningRowTurtles[turt] = '' </code></pre> <p>I really don't know why... sorry for all the confusion!</p> <p>I'm making a conne...
1
2016-05-28T22:25:17Z
37,519,005
<p>Consider:</p> <blockquote> <p>for turt in range(4):</p> </blockquote> <p>and:</p> <blockquote> <p>I defined winningRowTurtles[1,2,3,4] before I ran the other code.</p> </blockquote> <p>But <code>range(4)</code> is [0, 1, 2, 3]. What we would have expected you to say is:</p> <blockquote> <p>I defined winn...
0
2016-05-30T06:30:32Z
[ "python", "turtle-graphics", "attributeerror" ]
Train NGramModel in Python
37,504,391
<p>I am using Python 3.5, installed and managed with Anaconda. I want to train an NGramModel (from nltk) using some text. My installation does not find the module nltk.model</p> <p>There are some possible answers to this question (pick the correct one, and explain how to do it):</p> <ol> <li>A different version of nl...
3
2016-05-28T22:41:00Z
37,507,447
<p>First of all, as was indicated in the comments to your question, if training/running speed is an issue for you, KenLM is probably a better choice. At this point <code>nltk.model</code> is primarily for educational/prototyping purposes, it's not made to be fast.</p> <p>If you still decide to stick with NLTK, read on...
5
2016-05-29T07:45:13Z
[ "python", "python-3.x", "nltk", "n-gram" ]
Pygame lagging because of sprites?
37,504,394
<p>I made the game like this with sprites to make a platform game. </p> <p>It was fine before but now it's lagging, so when the gravity is applied it moves by one and looks unnatural. </p> <p>It was fine at first, when the platforms were rectangles. </p> <p>I changed the platforms and also inserted a list of enemie...
1
2016-05-28T22:41:46Z
37,504,479
<p>Try to insert at the end of the while "clock.tick", with the argument FPS(variable):</p> <pre><code>clock.tick(60) #60 are the frames per second pygame.display.update() </code></pre> <p>this function allows you to set the game frame_rate</p>
0
2016-05-28T22:54:06Z
[ "python", "pygame", "sprite", "lag", "platform" ]
Pygame lagging because of sprites?
37,504,394
<p>I made the game like this with sprites to make a platform game. </p> <p>It was fine before but now it's lagging, so when the gravity is applied it moves by one and looks unnatural. </p> <p>It was fine at first, when the platforms were rectangles. </p> <p>I changed the platforms and also inserted a list of enemie...
1
2016-05-28T22:41:46Z
37,504,509
<p>I notice that you're loading your LevOne background on every iteration, as well as initialising the various sprites. This is a one time operation, and so doing it on every iteration isn't necessary, and is probably causing the stuttering you're experiencing. You should load the background in an <code>__init__</code>...
2
2016-05-28T22:59:08Z
[ "python", "pygame", "sprite", "lag", "platform" ]
Pandas Mapping Multiple Column Function on a DataFrame
37,504,429
<p>So I have a pandas dataframe containing column fields 'Latitude' and 'Longitude' and I would like to map a function that would take those two fields as well as a precision that would be applied to an entire dataframe, and add the column 'GEOHASH' to the frame with the output of the function being mapped. </p> <p>Ri...
1
2016-05-28T22:46:07Z
37,510,095
<p>IIUC you can do it this way:</p> <pre><code>data['HASH'] = data.apply(lambda x: geohash.encode(x.Latitude, x.Longitude, precision), axis=1) </code></pre>
0
2016-05-29T12:48:13Z
[ "python", "pandas", "geospatial" ]
Pandas Mapping Multiple Column Function on a DataFrame
37,504,429
<p>So I have a pandas dataframe containing column fields 'Latitude' and 'Longitude' and I would like to map a function that would take those two fields as well as a precision that would be applied to an entire dataframe, and add the column 'GEOHASH' to the frame with the output of the function being mapped. </p> <p>Ri...
1
2016-05-28T22:46:07Z
37,510,370
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a>:</p> <p>(I modified the function because I don't have geohash)</p> <pre><code>def my_encode(argstring): argstring = str.split(argstring,'_') lat,long,precision = flo...
0
2016-05-29T13:17:41Z
[ "python", "pandas", "geospatial" ]
Tensorflow crashes when using sess.run()
37,504,470
<p>I'm using tensorflow 0.8.0 with Python v2.7. My IDE is PyCharm and my os is Linux Ubuntu 14.04</p> <p>I'm noticing that the following code causes my computer to freeze and/or crash:</p> <pre><code># you will need these files! # https://www.kaggle.com/c/digit-recognizer/download/train.csv # https://www.kaggle.com/...
0
2016-05-28T22:52:56Z
37,504,776
<p>Setting the session as default, and initializing your variable before running the session may solve your problem.</p> <pre><code>import tensorflow as tf sess = tf.Session() g = tf.ones([25088]) sess.as_default(): tf.initialize_all_variables().run() results = sess.run(g) print results </code></pre>
0
2016-05-28T23:42:36Z
[ "python", "crash", "tensorflow" ]
Tensorflow crashes when using sess.run()
37,504,470
<p>I'm using tensorflow 0.8.0 with Python v2.7. My IDE is PyCharm and my os is Linux Ubuntu 14.04</p> <p>I'm noticing that the following code causes my computer to freeze and/or crash:</p> <pre><code># you will need these files! # https://www.kaggle.com/c/digit-recognizer/download/train.csv # https://www.kaggle.com/...
0
2016-05-28T22:52:56Z
37,555,630
<p>I suspect the problem arises because <code>mull[0, 2]</code>&mdash;despite its small apparent size&mdash;depends on a very large computation, including multiple convolutions, max-poolings, and a large matrix multiplication; and therefore either your computer becomes fully loaded for a long period of time, or it runs...
1
2016-05-31T21:07:25Z
[ "python", "crash", "tensorflow" ]
pandas: find partial string and use it in new columns
37,504,564
<p>I would like to create a new columns in case a certain string is a substring of another columns. Suppose I have a DataFrame with one column df['A']:</p> <pre><code> A 0 bbh AA chd 1 d10 DKL BB 2 kj AAdbl 5 3 kBB d7d dl </code></pre> <p>and a list:</p> <pre><code>check = ['AA', ...
3
2016-05-28T23:09:45Z
37,504,987
<h3>Setup</h3> <pre><code>import pandas as pd text = """A bbh AA chd d10 DKL BB kj AAdbl 5 kBB d7d dl""" df = pd.read_csv(StringIO(text)) check = ['AA', 'BB'] print df A 0 bbh AA chd 1 d10 DKL BB 2 kj AAdbl 5 3 kBB d7d dl </code></pre> <h3>Solution</h3> <pre><code>df_expanded = df.A.str.split(ex...
1
2016-05-29T00:24:49Z
[ "python", "loops", "pandas", "vectorization" ]
pandas: find partial string and use it in new columns
37,504,564
<p>I would like to create a new columns in case a certain string is a substring of another columns. Suppose I have a DataFrame with one column df['A']:</p> <pre><code> A 0 bbh AA chd 1 d10 DKL BB 2 kj AAdbl 5 3 kBB d7d dl </code></pre> <p>and a list:</p> <pre><code>check = ['AA', ...
3
2016-05-28T23:09:45Z
37,507,053
<p>Try using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html" rel="nofollow">iterrows</a> to iterate through the rows and check if the rows contains any elements inside the check list and then put it into a new column. </p> <pre><code>for idx, row in df.iterrows(): for...
0
2016-05-29T06:47:09Z
[ "python", "loops", "pandas", "vectorization" ]
Route testing with Tornado
37,504,566
<p>I'm new to Tornado, and working on a project that involves some rather complex routing. In most of the other frameworks I've used I've been able to isolate routing for testing, without spinning up a server or doing anything terribly complex. I'd prefer to use pytest as my testing framework, but I'm not sure it matte...
0
2016-05-28T23:09:55Z
37,504,714
<p>No, it is not currently possible to test this in Tornado via any public interface (as of Tornado version 4.3). </p> <p>It's straightforward to avoid spinning up a server, although it requires a nontrivial amount of code: the interface between HTTPServer and Application is well-defined and documented. The trickier p...
2
2016-05-28T23:31:33Z
[ "python", "python-3.x", "tornado", "py.test" ]
Timestamps into sessions pandas
37,504,605
<p>I am very new to panadas and have a DataFrame in pandas that looks like this:</p> <pre><code> customer_id, timestamp 74594, 1, 2016-05-25 15:39:41 74556, 1, 2016-05-25 15:40:33 74403, 1, 2016-05-25 15:43:26 73783, 1, 2016-05-25 15:52:40 73241, 1, 2016...
1
2016-05-28T23:15:23Z
37,505,077
<h3>Setup</h3> <pre><code>import pandas as pd from string import ascii_uppercase text = """index,customer_id,timestamp 74594,1,2016-05-25 15:39:41 74556,1,2016-05-25 15:40:33 74403,1,2016-05-25 15:43:26 73783,1,2016-05-25 15:52:40 73241,1,2016-05-25 16:01:01 71960,1,2016-05-25 16:19:35 71590,1,2016-05-25 16:26:05 117...
3
2016-05-29T00:43:00Z
[ "python", "pandas" ]
How to install a Python wheel under an alternative package name? (in my specific case, PyCryptodome under the "Cryptodome" package name)
37,504,622
<p>The installation information page of <a href="http://pycryptodome.readthedocs.io/en/latest/src/introduction.html" rel="nofollow">PyCryptodome</a> says the following under the <a href="http://pycryptodome.readthedocs.io/en/latest/src/installation.html#windows-pre-compiled" rel="nofollow">"Windows (pre-compiled)" sect...
2
2016-05-28T23:17:52Z
37,531,493
<p>As far as I know this is not possible. The only way to achieve this by recompiling the wheel yourself after you modified its name in the <code>setup.py</code>.</p>
1
2016-05-30T18:07:47Z
[ "python", "pip", "python-wheel" ]
pandas dataframe return first word in string for column
37,504,672
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({'id' : ['abarth 1.4 a','abarth 1 a','land rover 1.3 r','land rover 2', 'land rover 5 g','mazda 4.55 bl'], 'series': ['a','a','r','','g', 'bl'] }) </code></pre> <p>I would like to remove the 'series' string from the...
1
2016-05-28T23:25:41Z
37,504,853
<p>If I got your question correctly you can just use <code>replace</code> function:</p> <pre><code>df.make = df.make.replace("", test.id) </code></pre>
0
2016-05-28T23:59:36Z
[ "python", "pandas" ]
pandas dataframe return first word in string for column
37,504,672
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({'id' : ['abarth 1.4 a','abarth 1 a','land rover 1.3 r','land rover 2', 'land rover 5 g','mazda 4.55 bl'], 'series': ['a','a','r','','g', 'bl'] }) </code></pre> <p>I would like to remove the 'series' string from the...
1
2016-05-28T23:25:41Z
37,504,895
<p>Consider a regex solution with <code>loc</code> where it extracts everything before first space:</p> <pre><code>df.loc[df['make']=='', 'make'] = df['id'].str.extract('(.*) ', expand=False) </code></pre> <p>Alternatively, use numpy's <code>where</code> which allows the if/then/else conditional logic:</p> <pre><cod...
1
2016-05-29T00:07:37Z
[ "python", "pandas" ]
pandas dataframe return first word in string for column
37,504,672
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({'id' : ['abarth 1.4 a','abarth 1 a','land rover 1.3 r','land rover 2', 'land rover 5 g','mazda 4.55 bl'], 'series': ['a','a','r','','g', 'bl'] }) </code></pre> <p>I would like to remove the 'series' string from the...
1
2016-05-28T23:25:41Z
37,505,031
<p>Use <code>str.split</code> and <code>str.get</code> and assign using <code>loc</code> only where <code>df.make == ''</code></p> <pre><code>df.loc[df.make == '', 'make'] = df.id.str.split().str.get(0) print df id make 0 abarth 1.4 abarth 1 abarth 1 abarth 2 land rover 1.3 rover 3...
4
2016-05-29T00:33:46Z
[ "python", "pandas" ]
How to merge some
37,504,687
<p>I read a lot of lower and upper limits from text files and want to merge these limits. The data type is either float number or date string as <code>yyyy-mm-dd</code> (two independent cases).</p> <p>Here, a short list of int boundaries, is just a simplified example for demonstration.</p> <pre><code> # boundaries r...
0
2016-05-28T23:27:44Z
37,504,750
<pre><code>b = [[-1, 2], [-2, 1], [0, 4], [3, 5], [-3, 1], [-10, -7], [6, 8]] b.sort() result = [] current = b[0] for interval in b[1:]: if current[1] &gt;= interval[0]: current[1] = interval[1] else: result.append(current) current = interval result.append(current) print(result) # [[-10...
1
2016-05-28T23:38:20Z
[ "python" ]
How to merge some
37,504,687
<p>I read a lot of lower and upper limits from text files and want to merge these limits. The data type is either float number or date string as <code>yyyy-mm-dd</code> (two independent cases).</p> <p>Here, a short list of int boundaries, is just a simplified example for demonstration.</p> <pre><code> # boundaries r...
0
2016-05-28T23:27:44Z
37,504,981
<p>If you like using <code>reduce</code>, you can still do it this way:</p> <pre class="lang-py prettyprint-override"><code>from functools import reduce def join(acc, v): if not acc: return [v] last = acc.pop() if v[0] &gt; last[1]: return acc + [last, v] return acc + [(last[0], max(la...
1
2016-05-29T00:22:49Z
[ "python" ]
Databricks + H2O PySparkling: addURL Py4JException
37,504,691
<p>I am a newbie to H2O and spark framework and I am having troubles with on boarding <code>H2O+Spark (sparkling-water)</code> PySparkling in Databricks. I have a 12 worker cluster running in Databricks in 1.5.2 environment.</p> <p>Steps I took were as following: <br> 1. Attach (Installed) necessary libraries (six, re...
0
2016-05-28T23:28:09Z
37,526,428
<p>This is a <a href="http://0xdata.atlassian.net/browse/SW-137" rel="nofollow">bug in PySparkling</a>. <a href="https://github.com/h2oai/sparkling-water/commit/7f5fef09cfc6b746f743198e438ec4eb2ab09403" rel="nofollow">A fix</a> has been already committed but is still waiting for the next release, might be introduced in...
0
2016-05-30T13:04:26Z
[ "python", "pyspark", "jupyter-notebook", "h2o", "sparkling-water" ]
What happens if I say x = x? (On a low, compiler level)
37,504,769
<p>In Python (more specifically Python 3.x), what happens if I say <code>x = x</code>, where <code>x</code> is either a reference to a mutable (like <code>list</code>) or a reference to an immutable (like <code>int</code>) on the low-level? Does the compiler simply ignore such nonsense?</p> <p>More specifically, what ...
1
2016-05-28T23:41:34Z
37,504,798
<pre><code>from dis import dis def foo(): x = 1 x = x dis(foo) </code></pre> <p>Result:</p> <pre><code> 4 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (x) 5 6 LOAD_FAST 0 (x) 9 STORE_FAST 0 (x) 12 ...
5
2016-05-28T23:47:42Z
[ "python", "reference", "compilation" ]
What happens if I say x = x? (On a low, compiler level)
37,504,769
<p>In Python (more specifically Python 3.x), what happens if I say <code>x = x</code>, where <code>x</code> is either a reference to a mutable (like <code>list</code>) or a reference to an immutable (like <code>int</code>) on the low-level? Does the compiler simply ignore such nonsense?</p> <p>More specifically, what ...
1
2016-05-28T23:41:34Z
37,504,862
<blockquote> <p>I just want to know for interest's sake whether the compiler optimizes that step away, or whether it does some operations in any case, even though the statement does not result in anything.</p> </blockquote> <p>Unless the Python Language Reference says something about it<sup>1</sup>, then any optimiz...
1
2016-05-29T00:01:02Z
[ "python", "reference", "compilation" ]
What happens if I say x = x? (On a low, compiler level)
37,504,769
<p>In Python (more specifically Python 3.x), what happens if I say <code>x = x</code>, where <code>x</code> is either a reference to a mutable (like <code>list</code>) or a reference to an immutable (like <code>int</code>) on the low-level? Does the compiler simply ignore such nonsense?</p> <p>More specifically, what ...
1
2016-05-28T23:41:34Z
37,577,165
<p>This may seem very strange, but it is not actually possible to implement the optimization you suggested, as python is far too dynamic.</p> <p>Consider the following code:</p> <pre><code>[Definition of your A class] @property def sneaky(self): return self._a @sneaky.setter def sneaky(self, value): self._a =...
1
2016-06-01T19:23:35Z
[ "python", "reference", "compilation" ]